repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
chuahou/wrtele
|
src/wrtele.c
|
// SPDX-License-Identifier: MIT
// Copyright (c) 2021 <NAME>
#define _GNU_SOURCE
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "botapi.h"
#include "config.h"
#include "mac.h"
int main(int argc, char **argv)
{
// Get list of devices to watch.
size_t macs_len;
struct device *macs = config_mac_addrs(&macs_len);
if (!macs || macs_len < 1) {
errno = EINVAL;
perror("Invalid MAC addresses to watch");
return -1;
}
puts("Watching devices:");
for (size_t i = 0; i < macs_len; i++) {
struct device mac = macs[i];
printf("%s %s\n", mac.mac, mac.name);
}
// Infinite loop to watch.
unsigned int sleep_duration = config_sleep_duration();
while (true) {
size_t changed_len;
struct device *changed = check_status(macs, macs_len, &changed_len);
for (size_t i = 0; i < changed_len; i++) {
if (changed[i].connected) {
char *msg;
if (asprintf(&msg, "Device %s connected.", changed[i].name) < 0) {
perror("Failed to create message");
return -1;
}
tele_send_message(msg); puts(msg); free(msg);
} else {
char *msg;
if (asprintf(&msg, "Device %s disconnected.", changed[i].name) < 0) {
perror("Failed to create message");
return -1;
}
tele_send_message(msg); puts(msg); free(msg);
}
}
free(changed);
sleep(sleep_duration);
}
}
|
chuahou/wrtele
|
src/botapi.h
|
// SPDX-License-Identifier: MIT
// Copyright (c) 2021 <NAME>
//
// Bot API helper functions.
#ifndef __BOTAPI_H_INCLUDE__
#define __BOTAPI_H_INCLUDE__
#include <stdbool.h>
// Uses Telegram Bot API to send a message to the target user.
// Returns true on success.
bool tele_send_message(char *msg);
#endif
|
chuahou/wrtele
|
src/mac.c
|
<reponame>chuahou/wrtele<filename>src/mac.c
// SPDX-License-Identifier: MIT
// Copyright (c) 2021 <NAME>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "config.h"
#include "mac.h"
struct device *check_status(struct device *devs, size_t devs_len, size_t *changed_len)
{
*changed_len = 0;
char *macs = list_macs();
if (!macs) return NULL;
// Make everything lowercase.
for (char *p = macs; *p != '\0'; p++) *p = tolower(*p);
// Array of changed devices.
struct device *changed = malloc(sizeof(struct device) * devs_len);
if (!changed) { free(macs); return NULL; }
// Iterate through devices.
for (size_t i = 0; i < devs_len; i++) {
if (strstr(macs, devs[i].mac) != NULL) {
if (!devs[i].connected) {
devs[i].connected = true;
changed[(*changed_len)++] = devs[i];
}
} else if (devs[i].connected) {
devs[i].connected = false;
changed[(*changed_len)++] = devs[i];
}
}
free(macs);
return changed;
}
char *list_macs()
{
// Create mutable copy of commands config string since we use destructive
// calls to strtok.
char *commands;
char *commands_env = config_list_command();
if (!commands_env) return NULL;
size_t len = strlen(commands_env);
if ((commands = malloc(len + 1))) {
memcpy(commands, commands_env, len + 1);
// Iterate over commands.
char *command = strtok(commands, ";");
char *output = NULL; size_t output_len = 0;
while (command != NULL) {
FILE *p = popen(command, "r");
if (!p) { free(commands); return NULL; }
// Copy output into output variable.
const size_t BUF_SIZE = 128;
char buf[BUF_SIZE];
while (fgets(buf, BUF_SIZE, p)) {
size_t read_len = strlen(buf);
char *new_output = realloc(output, output_len + read_len + 1);
if (!new_output) {
free(output); free(commands); pclose(p); return NULL;
}
output = new_output;
memcpy(&output[output_len], buf, read_len + 1); // +1 for '\0'
output_len += read_len;
}
pclose(p);
// Next command.
command = strtok(NULL, ";");
}
free(commands);
return output;
} else {
return NULL;
}
}
|
chuahou/wrtele
|
src/mac.h
|
<filename>src/mac.h
// SPDX-License-Identifier: MIT
// Copyright (c) 2021 <NAME>
//
// Functions to get information about MAC addresses.
#ifndef __WRTELE_MAC_H_INCLUDED__
#define __WRTELE_MAC_H_INCLUDED__
#include <stdbool.h>
#include <stddef.h>
#define MAX_DEVICE_NAME_LEN 46 // 64 - 18
// Status of a MAC address and its last known status.
struct device {
char mac[18];
char name[MAX_DEVICE_NAME_LEN];
bool connected;
};
// Updates the connection status of devices devs, and returns a list of changed
// devices. The list must be free()-ed.
struct device *check_status(struct device *devs, size_t num_devs, size_t *changed_len);
// Returns a string of the output of config_list_command()'s commands, which
// must be free()-ed.
char *list_macs();
#endif
|
bijoumd78/ecal
|
ecal/core/src/mon/ecal_monitoring_def.h
|
<filename>ecal/core/src/mon/ecal_monitoring_def.h
/* ========================= eCAL LICENSE =================================
*
* Copyright (C) 2016 - 2019 Continental Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ========================= eCAL LICENSE =================================
*/
/**
* @brief Global monitoring class
**/
#pragma once
#include <string>
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4146 4800)
#endif
#include "ecal/pb/ecal.pb.h"
#include "ecal/pb/monitoring.pb.h"
#ifdef _MSC_VER
#pragma warning(pop)
#endif
namespace eCAL
{
////////////////////////////////////////
// global database class
////////////////////////////////////////
class CMonitoringImpl;
class CMonitoring
{
public:
CMonitoring();
~CMonitoring();
void Create();
void Destroy();
void SetExclFilter(const std::string& filter_);
void SetInclFilter(const std::string& filter_);
void SetFilterState(bool state_);
void Monitor(eCAL::pb::Monitoring& monitoring_);
void Monitor(eCAL::pb::Logging& logging_);
int PubMonitoring(bool state_, std::string& name_);
int PubLogging(bool state_, std::string& name_);
size_t ApplySample(const eCAL::pb::Sample& ecal_sample_);
protected:
CMonitoringImpl* m_monitoring_impl;
private:
CMonitoring(const CMonitoring&); // prevent copy-construction
CMonitoring& operator=(const CMonitoring&); // prevent assignment
};
}
|
bijoumd78/ecal
|
ecal/core/src/readwrite/ecal_writer_shm.h
|
<filename>ecal/core/src/readwrite/ecal_writer_shm.h
/* ========================= eCAL LICENSE =================================
*
* Copyright (C) 2016 - 2019 Continental Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ========================= eCAL LICENSE =================================
*/
/**
* @brief memory file data writer
**/
#pragma once
#include "ecal_def.h"
#include "readwrite/ecal_writer_base.h"
#include "io/ecal_memfile.h"
#include <ecal/ecal_eventhandle.h>
#include <mutex>
#include <string>
#include <unordered_map>
#include <atomic>
namespace eCAL
{
class CDataWriterSHM : public CDataWriterBase
{
public:
CDataWriterSHM();
~CDataWriterSHM();
void GetInfo(SWriterInfo info_) override;
bool Create(const std::string& host_name_, const std::string& topic_name_, const std::string & topic_id_) override;
bool Destroy() override;
bool SetQOS(const QOS::SWriterQOS& qos_) override;
bool PrepareSend(size_t len_) override;
size_t Send(const SWriterData& data_) override;
bool AddLocConnection(const std::string& process_id_, const std::string& conn_par_) override;
bool RemLocConnection(const std::string& process_id_) override;
std::string GetConectionPar();
protected:
void SignalMemFileWritten();
void BuildMemFileName();
bool CreateMemFile(size_t size_);
bool DestroyMemFile();
std::string m_memfile_name;
CMemoryFile m_memfile;
struct SEventHandlePair
{
EventHandleT event_snd;
EventHandleT event_ack;
};
typedef std::unordered_map<std::string, SEventHandlePair> EventHandleMapT;
std::mutex m_event_handle_map_sync;
EventHandleMapT m_event_handle_map;
int m_timeout_ack;
};
}
|
bijoumd78/ecal
|
lib/CustomQt/include/CustomQt/QGroupByProxyModel.h
|
/* ========================= eCAL LICENSE =================================
*
* Copyright (C) 2016 - 2019 Continental Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ========================= eCAL LICENSE =================================
*/
#pragma once
#include <QObject>
#include <QAbstractProxyModel>
#include <QMap>
#include <QVariant>
#include <QModelIndex>
class QGroupByProxyModel : public QAbstractProxyModel
{
Q_OBJECT
public:
QGroupByProxyModel(QObject* parent = NULL);
~QGroupByProxyModel();
void setGroupRole(int role);
int groupRole() const;
void setSourceModel(QAbstractItemModel *model);
void setGroupBy(int column);
QString whichGroup(int row) const;
QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const;
QModelIndex parent(const QModelIndex &index) const;
QModelIndex mapToSource(const QModelIndex &proxyIndex) const;
QModelIndex mapFromSource(const QModelIndex &sourceIndex) const;
QVariant data(const QModelIndex &proxyIndex, int role = Qt::DisplayRole) const;
QVariant headerData (int section, Qt::Orientation orientation, int role = Qt::DisplayRole ) const;
int columnCount(const QModelIndex &parent = QModelIndex()) const;
int rowCount(const QModelIndex &parent = QModelIndex()) const;
QString groupFromValue(QString header_string, QString value_string) const;
void setGroups();
void clearGroups();
private:
int group_role_;
//TODO: make more generic
int group_by_column_ = 1;
QList<QString> groups_;
QList<QModelIndex> group_indices_;
QMap<QString, QVector<int>*> group_row_to_source_row_;
QVector<int> source_row_to_group_row_;
};
|
bijoumd78/ecal
|
app/mon/topic/src/ecal_topic_defs.h
|
;/* ========================= eCAL LICENSE =================================
; *
; * Copyright (C) 2016 - 2019 Continental Corporation
; *
; * Licensed under the Apache License, Version 2.0 (the "License");
; * you may not use this file except in compliance with the License.
; * You may obtain a copy of the License at
; *
; * http://www.apache.org/licenses/LICENSE-2.0
; *
; * Unless required by applicable law or agreed to in writing, software
; * distributed under the License is distributed on an "AS IS" BASIS,
; * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; * See the License for the specific language governing permissions and
; * limitations under the License.
; *
; * ========================= eCAL LICENSE =================================
;*/
;/**
; * eCALTopic version definition
;**/
#pragma once
;/* version parsed out into numeric values */
#define ECAL_TOPIC_VERSION_MAJOR 1
#define ECAL_TOPIC_VERSION_MINOR 0
#define ECAL_TOPIC_VERSION_PATCH 1
;/* version as string */
#define ECAL_TOPIC_VERSION "v.1.0.1.20150910"
#define ECAL_TOPIC_DATE "10.09.2015"
;/* name as string */
#define ECAL_TOPIC_NAME "eCALTopic"
|
bijoumd78/ecal
|
app/rec/rec_core/src/recorder.h
|
/* ========================= eCAL LICENSE =================================
*
* Copyright (C) 2016 - 2019 Continental Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ========================= eCAL LICENSE =================================
*/
#pragma once
#include "frame.h"
#include <chrono>
#include <deque>
#include <mutex>
#include <list>
#include <map>
#include <set>
#include <thread>
#include <EcalUtils/EcalUtils.h>
#include "rec_core/recorder_state.h"
#include "rec_core/topic_info.h"
#include "rec_core/record_mode.h"
#include "rec_core/job_config.h"
namespace eCAL
{
namespace rec
{
class Hdf5WriterThread;
class GarbageCollectorTriggerThread;
class MonitoringThread;
class Recorder
{
public:
Recorder();
~Recorder();
//////////////////////////////////////
//// Recorder control ////
//////////////////////////////////////
void SetPreBufferingEnabled(bool enabled);
void SetMaxPreBufferLength(std::chrono::steady_clock::duration max_pre_buffer_length);
std::chrono::steady_clock::duration GetMaxPreBufferLength() const;
bool IsPreBufferingEnabled() const;
std::pair<size_t, std::chrono::steady_clock::duration> GetCurrentPreBufferLength() const;
bool SavePreBufferedData(const JobConfig& job_config);
bool StartRecording(const JobConfig& job_config);
bool StopRecording();
WriterState GetMainRecorderState() const;
RecorderState GetRecorderState() const;
//////////////////////////////////////
//// Topic filters ////
//////////////////////////////////////
bool SetHostFilter(const std::set<std::string>& hosts);
bool SetRecordMode(RecordMode mode, std::set<std::string> listed_topics = {});
bool SetListedTopics(const std::set<std::string>& listed_topics);
std::set<std::string> GetHostsFilter() const;
RecordMode GetRecordMode() const;
RecordMode GetRecordMode(std::set<std::string>& listed_topics) const;
std::set<std::string> GetListedTopics() const;
//////////////////////////////////////
//// eCAL ////
//////////////////////////////////////
void ConnectToEcal();
void DisconnectFromEcal();
bool IsConnectedToEcal() const;
std::set<std::string> GetSubscribedTopics() const;
std::map<std::string, bool> GetHostsRunningEcalRpcService() const;
void EcalMessageReceived(const char* topic_name, const eCAL::SReceiveCallbackData* callback_data);
//////////////////////////////////////
//// API for external threads ////
//////////////////////////////////////
void GarbageCollect();
void SetTopicInfo(const std::map<std::string, TopicInfo>& topic_info_map);
private:
mutable std::mutex recorder_mutex_;
std::unique_ptr<Hdf5WriterThread> main_recorder_thread_;
std::list<std::unique_ptr<Hdf5WriterThread>> buffer_writer_threads_;
std::deque<std::shared_ptr<Frame>> frame_buffer_;
bool pre_buffering_enabled_;
std::chrono::steady_clock::duration max_pre_buffer_length_;
// Threads
std::unique_ptr<GarbageCollectorTriggerThread> garbage_collector_trigger_thread_; /** frame_buffer_, buffer_writer_threads_, max_pre_buffer_length_ */
std::unique_ptr<MonitoringThread> monitoring_thread_; /** connected_to_ecal_, FilterAvailableTopics_NoLock(hosts_filter_, topic_whitelist_, topic_blacklist_), CreateNewSubscribers_NoLock(subscriber_map_), main_writer_thread_, buffer_writer_threads_ */
// eCAL subscribers
mutable std::mutex ecal_mutex_;
bool connected_to_ecal_;
std::map<std::string, std::unique_ptr<eCAL::CSubscriber>> subscriber_map_; /**< buffering_enabled_, frame_buffer_, main_writer_thread_*/
RecordMode record_mode_; /**< All / Blacklist / Whitelist */
std::set<std::string> listed_topics_; /**< When in Blacklist or Whitelist mode, this list holds the according topic list */
std::set<std::string> hosts_filter_; /**< Only subscribe to topics published by there hosts*/
//////////////////////////////////////////////////////////////////////////////
//// Private functions ////
//////////////////////////////////////////////////////////////////////////////
void UpdateAndCleanSubscribers();
std::set<std::string> FilterAvailableTopics_NoLock(const std::map<std::string, TopicInfo>& topic_info_map) const;
void CreateNewSubscribers_NoLock(const std::set<std::string>& topic_set);
void RemoveOldSubscribers_NoLock(const std::set<std::string>& topic_set);
bool StopRecording_NoLock();
std::pair<size_t, std::chrono::steady_clock::duration> GetCurrentPreBufferLength_NoLock() const;
bool IsAnythingSavingToPath_NoLock(const std::string& path) const;
};
}
}
|
bijoumd78/ecal
|
contrib/ecalproto/include/ecal/protobuf/ecal_proto_dyn.h
|
/* ========================= eCAL LICENSE =================================
*
* Copyright (C) 2016 - 2019 Continental Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ========================= eCAL LICENSE =================================
*/
/**
* @brief dynamic protobuf message decoder
**/
#pragma once
#include <string>
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4100 4146 4800)
#endif
#if defined(__linux__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#endif
#include <google/protobuf/message.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/dynamic_message.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/io/tokenizer.h>
#include <google/protobuf/compiler/parser.h>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#if defined(__linux__)
#pragma GCC diagnostic pop
#endif
#include <ecal/protobuf/ecal_proto_hlp.h>
namespace eCAL
{
namespace protobuf
{
/**
* @brief eCAL dynamic protobuf decoder.
*
* The CProtoDynDecoder class is used to decode a protobuf message using protobuf reflection interface.
*
**/
/**
* @code
* // create dynamic decoder
* std::string error_s;
* eCAL::CProtoDynDecoder decoder;
* google::protobuf::Message* msg_obj = decoder.GetProtoMessageFromFile("foo.proto", "FooMessage", error_s);
*
* // receive a message
* std::string msg_s = ReceiveMessageFromAnyWhere("foo");
*
* // decode message
* msg_obj->ParseFromString(msg_s);
*
* // print message
* std::cout << msg_obj->DebugString() << std::endl;
* @endcode
**/
class CProtoDynDecoder
{
public:
/**
* @brief Create message from proto file.
*
* @param proto_filename_ Proto file name.
* @param msg_type_ Type name.
* @param [out] error_s_ Error string.
**/
google::protobuf::Message* GetProtoMessageFromFile(const std::string& proto_filename_, const std::string& msg_type_, std::string& error_s_);
/**
* @brief Create message from proto string.
*
* @param proto_string_ Proto string.
* @param msg_type_ Type name.
* @param [out] error_s_ Error string.
**/
google::protobuf::Message* GetProtoMessageFromString(const std::string& proto_string_, const std::string& msg_type_, std::string& error_s_);
/**
* @brief Create message from proto descriptor.
*
* @param proto_desc_ Proto descriptor.
* @param msg_type_ Type name.
* @param [out] error_s_ Error string.
**/
google::protobuf::Message* GetProtoMessageFromDescriptor(const google::protobuf::FileDescriptorProto& proto_desc_, const std::string& msg_type_, std::string& error_s_);
/**
* @brief Create message from proto descriptor set.
*
* @param proto_desc_set_ Proto descriptor set.
* @param msg_type_ Type name.
* @param [out] error_s_ Error string.
**/
google::protobuf::Message* GetProtoMessageFromDescriptorSet(const google::protobuf::FileDescriptorSet& proto_desc_set_, const std::string& msg_type_, std::string& error_s_);
/**
* @brief Returns the DescriptorPool member variable
**/
google::protobuf::DescriptorPool* GetDescriptorPool();
/**
* @brief Create proto descriptor from proto file.
*
* @param proto_filename_ Proto file name.
* @param [out] file_desc_proto_ Type name.
* @param [out] error_s_ Error string.
**/
static bool GetFileDescriptorFromFile(const std::string& proto_filename_, google::protobuf::FileDescriptorProto* file_desc_proto_, std::string& error_s_);
/**
* @brief Create proto descriptor from proto string.
*
* @param proto_string_ Proto string.
* @param [out] file_desc_proto_ Type name.
* @param [out] error_s_ Error string.
**/
static bool GetFileDescriptorFromString(const std::string& proto_string_, google::protobuf::FileDescriptorProto* file_desc_proto_, std::string& error_s_);
protected:
google::protobuf::DescriptorPool m_descriptor_pool;
google::protobuf::DynamicMessageFactory m_message_factory;
};
}
}
|
bijoumd78/ecal
|
lib/CustomQt/include/CustomQt/QAdvancedTreeView.h
|
/* ========================= eCAL LICENSE =================================
*
* Copyright (C) 2016 - 2019 Continental Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ========================= eCAL LICENSE =================================
*/
#pragma once
#include <QTreeView>
#include <QPoint>
#include <QKeyEvent>
#include <QDataStream>
/**
* @brief The QAdvancedTreeView class is a QTreeView with more features
*
* The added featurs compared to an ordinary QTreeView are:
* - A header context menu that lets the user select / deselect visible
* columns
* - The possbilty to save the state (i.e. the visibile columns and the size
* of all columns) to a QByteArray and restore the state again
* - Auto-expanding up to a certain depth, if new elements are added to the
* model
* - Deselection of elements with the ESC key
* - Signals for often used keys and key sequences
*
* Note that some functions of the QTreeView are not virtual, although they have
* to be overridden:
* - setModel
* - setHeader
* Therefore, the object should always be of type @code{QAdvancedTreeView}, not
* of type @code{QTreeView} for this class to operate correctly.
*/
class QAdvancedTreeView : public QTreeView
{
Q_OBJECT
public:
explicit QAdvancedTreeView(QWidget *parent = Q_NULLPTR);
~QAdvancedTreeView();
void setHeader(QHeaderView *new_header); // Not virtual, but needs to be overridden
/**
* @brief Returns a list of all forced columns
*
* A Forced column cannot be hidden by the user. This is necessary, as he
* would not be able to enable any column once he disabled all columns
* (disabling all columns hides the header).
*
* By default, column 0 is the only forced column.
*
* @return The list of all forced columns
*/
QVector<int> forcedColumns() const;
/**
* @brief Sets the list of forced columns
*
* A Forced column cannot be hidden by the user. This is necessary, as the
* would not be able to enable any column once he disabled all columns
* (disabling all columns hides the header).
*
* By default, column 0 is the only forced column.
*
* @param forced_columns The list of forced columns
*/
void setForcedColumns(const QVector<int>& forced_columns);
/**
* @brief Check whether the given column is forced, i.e. cannot be disabled by the user
* @param column The column to check
* @return True, if the column is forced
*/
bool isForced(int column);
void setModel(QAbstractItemModel *model); // Not virtual, but needs to be overridden
/**
* @brief Sets the maximum depth that the tree view will expand a node to, if children are added
*
* A depth < 0 means that the tree view should not auto-expand any nodes.
* The default is -1.
* The invisible root node does not count as depth, i.e. a depth of 0 applies
* to the visible elements of a flat list.
*
* When a Node is added to the Model, its parent will be expanded, if it did
* not have any children before. If it did have children, the expansion state
* will not be changed in order to give the user the ability to manually
* collapse nodes.
*
* @param auto_expand_depth The maximum depth of a node that should be auto-expanded.
*/
void setAutoExpandDepth(int auto_expand_depth);
/**
* @brief Returns the current auto expand depth.
*
* A depth < 0 means that the tree view should not auto-expand any nodes.
* The default is -1.
* The invisible root node does not count as depth, i.e. a depth of 0 applies
* to the visible elements of a flat list.
*
* When a Node is added to the Model, its parent will be expanded, if it did
* not have any children before. If it did have children, the expansion state
* will not be changed in order to give the user the ability to manually
* collapse nodes.
*
* @return the current auto-expand depth
*/
int autoExpandDepth() const;
/**
* @brief Save the tree state (visible columns, column size and order) to a byte array.
*
* The byte array will also contain information about the column count and the
* version number that is given as parameter. Those information will be used
* as sanity check when restoring the state.
*
* Calling this function will temporarily set all hidden columns visible and
* hide them again, afterwards. Usually, this process is fast enough to not be
* visible. Nevertheless, if called in a loop (e.g. by connecting it to the
* @code{QHeaderView::sectionResized} signal, this may cause undesired effects
* and should be avoided.
*
* @param version A number that will be included in the QByteArray and used to perform a sanity check when restoring the state
*
* @return The Tree State as QByteArray
*/
QByteArray saveState(int32_t version = 0);
/**
* @brief restores the tree state (visible columns, column size and order) from a given QByteArray.
*
* Before restoring, a sanity check is performed:
* - The column count must match this treeView
* - The version number from the state must match the given version number
*
* @param state The state to restore
* @param version The version number to use for the sanity check
*
* @return True, if the state could be restored
*/
bool restoreState(const QByteArray& state, int32_t version = 0);
protected:
void keyPressEvent(QKeyEvent* key_event);
signals:
void keySequenceDeletePressed();
void keySequenceCopyPressed();
void keyEnterPressed();
private slots:
void headerContextMenu(const QPoint& pos);
void expandInsertedRows(const QModelIndex& parent, int first, int last);
private:
QVector<int> forced_columns_; /** The list of columns that cannot be hidden by the user */
int auto_expand_depth_; /** The maximum depth up to which a node will automatically be expanded, if a child is added */
/**
* @brief internal recursive helper function for expanding nodes
*/
void expandNodeToDepth(const QModelIndex& node, int remaining_depth);
/**
* @brief Counts the depth of the node
* @param node The node to count the depth for
* @return The depth of the node
*/
int depth(const QModelIndex& node) const;
struct ColumnState
{
bool visible = false;
uint32_t size = 0;
uint32_t position = 0;
friend QDataStream& operator<< (QDataStream &stream, const QAdvancedTreeView::ColumnState& state)
{
return stream << state.visible << state.size << state.position;
}
friend QDataStream& operator>> (QDataStream &stream, QAdvancedTreeView::ColumnState& state)
{
stream >> state.visible;
stream >> state.size;
stream >> state.position;
return stream;
}
};
};
|
bijoumd78/ecal
|
contrib/ecalproto/include/ecal/protobuf/ecal_proto_hlp.h
|
<reponame>bijoumd78/ecal
/* ========================= eCAL LICENSE =================================
*
* Copyright (C) 2016 - 2019 Continental Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ========================= eCAL LICENSE =================================
*/
/**
* @brief protobuf message description handling
**/
#pragma once
#include <algorithm>
#include <string>
#include <vector>
// protobuf includes
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4100 4146 4800)
#endif
#include <google/protobuf/descriptor.pb.h>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
namespace eCAL
{
namespace protobuf
{
inline std::string CreateCompleteMessageName(const std::string& name_, const std::string& prefix_)
{
std::string message_name;
if (!prefix_.empty())
{
message_name += prefix_;
message_name += '.';
}
message_name += name_;
return message_name;
}
inline std::string ExtractTopicName(const std::string& element_)
{
return element_.substr(0, element_.find('.'));
}
inline bool HasFile(const google::protobuf::FileDescriptorSet& fset_, const std::string& fname_)
{
for (auto findex = 0; findex < fset_.file_size(); ++findex)
{
if (fset_.file(findex).name() == fname_)
{
return(true);
}
}
return(false);
}
inline bool GetFileDescriptor(const google::protobuf::Descriptor* desc_, google::protobuf::FileDescriptorSet& fset_)
{
if (desc_ == nullptr) return(false);
const google::protobuf::FileDescriptor* fdesc = desc_->file();
for (auto dep = 0; dep < fdesc->dependency_count(); ++dep)
{
// iterate containing messages
const google::protobuf::FileDescriptor* sfdesc = fdesc->dependency(dep);
for (auto mtype = 0; mtype < sfdesc->message_type_count(); ++mtype)
{
const google::protobuf::Descriptor* desc = sfdesc->message_type(mtype);
GetFileDescriptor(desc, fset_);
}
// containing enums ?
if (sfdesc->enum_type_count() > 0)
{
const google::protobuf::EnumDescriptor* edesc = sfdesc->enum_type(0);
const google::protobuf::FileDescriptor* efdesc = edesc->file();
if (!HasFile(fset_, efdesc->name()))
{
google::protobuf::FileDescriptorProto* epdesc = fset_.add_file();
efdesc->CopyTo(epdesc);
}
}
// containing services ?
if (sfdesc->service_count() > 0)
{
const google::protobuf::ServiceDescriptor* svdesc = sfdesc->service(0);
const google::protobuf::FileDescriptor* svfdesc = svdesc->file();
if (!HasFile(fset_, svfdesc->name()))
{
google::protobuf::FileDescriptorProto* svpdesc = fset_.add_file();
svfdesc->CopyTo(svpdesc);
}
}
}
if (HasFile(fset_, fdesc->name())) return(true);
google::protobuf::FileDescriptorProto* pdesc = fset_.add_file();
fdesc->CopyTo(pdesc);
for (auto field = 0; field < desc_->field_count(); ++field)
{
const google::protobuf::FieldDescriptor* fddesc = desc_->field(field);
const google::protobuf::Descriptor* desc = fddesc->message_type();
GetFileDescriptor(desc, fset_);
}
return(true);
}
inline std::string GetProtoMessageDescription(const google::protobuf::Message& msg_)
{
const google::protobuf::Descriptor* desc = msg_.GetDescriptor();
google::protobuf::FileDescriptorSet pset;
if (GetFileDescriptor(desc, pset))
{
std::string desc_s = pset.SerializeAsString();
return(desc_s);
}
return("");
}
inline std::string GetProtoMessageTypeName(const google::protobuf::Message& msg_)
{
return(std::string("proto:") + msg_.GetTypeName());
}
inline std::vector<std::string> GetProtoMessageFieldNames(const std::vector<const google::protobuf::FieldDescriptor*>& fields_)
{
std::vector<std::string> names_vec;
std::transform(fields_.begin(), fields_.end(), std::back_inserter(names_vec),
[](const google::protobuf::FieldDescriptor* field)
{
return field->name();
}
);
return names_vec;
}
}
}
|
bijoumd78/ecal
|
My_Working_Opencv_Protobuf/image.pb.h
|
<gh_stars>0
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: image.proto
#ifndef PROTOBUF_image_2eproto__INCLUDED
#define PROTOBUF_image_2eproto__INCLUDED
#include <string>
#include <google/protobuf/stubs/common.h>
#if GOOGLE_PROTOBUF_VERSION < 3000000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 3000000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
namespace opencv {
// Internal implementation detail -- do not call these.
void protobuf_AddDesc_image_2eproto();
void protobuf_AssignDesc_image_2eproto();
void protobuf_ShutdownFile_image_2eproto();
class OcvMat;
// ===================================================================
class OcvMat : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:opencv.OcvMat) */ {
public:
OcvMat();
virtual ~OcvMat();
OcvMat(const OcvMat& from);
inline OcvMat& operator=(const OcvMat& from) {
CopyFrom(from);
return *this;
}
static const ::google::protobuf::Descriptor* descriptor();
static const OcvMat& default_instance();
void Swap(OcvMat* other);
// implements Message ----------------------------------------------
inline OcvMat* New() const { return New(NULL); }
OcvMat* New(::google::protobuf::Arena* arena) const;
void CopyFrom(const ::google::protobuf::Message& from);
void MergeFrom(const ::google::protobuf::Message& from);
void CopyFrom(const OcvMat& from);
void MergeFrom(const OcvMat& from);
void Clear();
bool IsInitialized() const;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* output) const;
::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const {
return InternalSerializeWithCachedSizesToArray(false, output);
}
int GetCachedSize() const { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(OcvMat* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
}
inline void* MaybeArenaPtr() const {
return _internal_metadata_.raw_arena_ptr();
}
public:
::google::protobuf::Metadata GetMetadata() const;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// optional int32 id = 1;
void clear_id();
static const int kIdFieldNumber = 1;
::google::protobuf::int32 id() const;
void set_id(::google::protobuf::int32 value);
// optional int32 rows = 2;
void clear_rows();
static const int kRowsFieldNumber = 2;
::google::protobuf::int32 rows() const;
void set_rows(::google::protobuf::int32 value);
// optional int32 cols = 3;
void clear_cols();
static const int kColsFieldNumber = 3;
::google::protobuf::int32 cols() const;
void set_cols(::google::protobuf::int32 value);
// optional int32 elt_type = 4;
void clear_elt_type();
static const int kEltTypeFieldNumber = 4;
::google::protobuf::int32 elt_type() const;
void set_elt_type(::google::protobuf::int32 value);
// optional int32 elt_size = 5;
void clear_elt_size();
static const int kEltSizeFieldNumber = 5;
::google::protobuf::int32 elt_size() const;
void set_elt_size(::google::protobuf::int32 value);
// optional bytes mat_data = 6;
void clear_mat_data();
static const int kMatDataFieldNumber = 6;
const ::std::string& mat_data() const;
void set_mat_data(const ::std::string& value);
void set_mat_data(const char* value);
void set_mat_data(const void* value, size_t size);
::std::string* mutable_mat_data();
::std::string* release_mat_data();
void set_allocated_mat_data(::std::string* mat_data);
// @@protoc_insertion_point(class_scope:opencv.OcvMat)
private:
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
bool _is_default_instance_;
::google::protobuf::int32 id_;
::google::protobuf::int32 rows_;
::google::protobuf::int32 cols_;
::google::protobuf::int32 elt_type_;
::google::protobuf::internal::ArenaStringPtr mat_data_;
::google::protobuf::int32 elt_size_;
mutable int _cached_size_;
friend void protobuf_AddDesc_image_2eproto();
friend void protobuf_AssignDesc_image_2eproto();
friend void protobuf_ShutdownFile_image_2eproto();
void InitAsDefaultInstance();
static OcvMat* default_instance_;
};
// ===================================================================
// ===================================================================
#if !PROTOBUF_INLINE_NOT_IN_HEADERS
// OcvMat
// optional int32 id = 1;
inline void OcvMat::clear_id() {
id_ = 0;
}
inline ::google::protobuf::int32 OcvMat::id() const {
// @@protoc_insertion_point(field_get:opencv.OcvMat.id)
return id_;
}
inline void OcvMat::set_id(::google::protobuf::int32 value) {
id_ = value;
// @@protoc_insertion_point(field_set:opencv.OcvMat.id)
}
// optional int32 rows = 2;
inline void OcvMat::clear_rows() {
rows_ = 0;
}
inline ::google::protobuf::int32 OcvMat::rows() const {
// @@protoc_insertion_point(field_get:opencv.OcvMat.rows)
return rows_;
}
inline void OcvMat::set_rows(::google::protobuf::int32 value) {
rows_ = value;
// @@protoc_insertion_point(field_set:opencv.OcvMat.rows)
}
// optional int32 cols = 3;
inline void OcvMat::clear_cols() {
cols_ = 0;
}
inline ::google::protobuf::int32 OcvMat::cols() const {
// @@protoc_insertion_point(field_get:opencv.OcvMat.cols)
return cols_;
}
inline void OcvMat::set_cols(::google::protobuf::int32 value) {
cols_ = value;
// @@protoc_insertion_point(field_set:opencv.OcvMat.cols)
}
// optional int32 elt_type = 4;
inline void OcvMat::clear_elt_type() {
elt_type_ = 0;
}
inline ::google::protobuf::int32 OcvMat::elt_type() const {
// @@protoc_insertion_point(field_get:opencv.OcvMat.elt_type)
return elt_type_;
}
inline void OcvMat::set_elt_type(::google::protobuf::int32 value) {
elt_type_ = value;
// @@protoc_insertion_point(field_set:opencv.OcvMat.elt_type)
}
// optional int32 elt_size = 5;
inline void OcvMat::clear_elt_size() {
elt_size_ = 0;
}
inline ::google::protobuf::int32 OcvMat::elt_size() const {
// @@protoc_insertion_point(field_get:opencv.OcvMat.elt_size)
return elt_size_;
}
inline void OcvMat::set_elt_size(::google::protobuf::int32 value) {
elt_size_ = value;
// @@protoc_insertion_point(field_set:opencv.OcvMat.elt_size)
}
// optional bytes mat_data = 6;
inline void OcvMat::clear_mat_data() {
mat_data_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline const ::std::string& OcvMat::mat_data() const {
// @@protoc_insertion_point(field_get:opencv.OcvMat.mat_data)
return mat_data_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void OcvMat::set_mat_data(const ::std::string& value) {
mat_data_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:opencv.OcvMat.mat_data)
}
inline void OcvMat::set_mat_data(const char* value) {
mat_data_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:opencv.OcvMat.mat_data)
}
inline void OcvMat::set_mat_data(const void* value, size_t size) {
mat_data_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:opencv.OcvMat.mat_data)
}
inline ::std::string* OcvMat::mutable_mat_data() {
// @@protoc_insertion_point(field_mutable:opencv.OcvMat.mat_data)
return mat_data_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline ::std::string* OcvMat::release_mat_data() {
// @@protoc_insertion_point(field_release:opencv.OcvMat.mat_data)
return mat_data_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void OcvMat::set_allocated_mat_data(::std::string* mat_data) {
if (mat_data != NULL) {
} else {
}
mat_data_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), mat_data);
// @@protoc_insertion_point(field_set_allocated:opencv.OcvMat.mat_data)
}
#endif // !PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
} // namespace opencv
// @@protoc_insertion_point(global_scope)
#endif // PROTOBUF_image_2eproto__INCLUDED
|
bijoumd78/ecal
|
app/mon/mon_gui/src/widgets/models/log_model.h
|
<filename>app/mon/mon_gui/src/widgets/models/log_model.h<gh_stars>0
/* ========================= eCAL LICENSE =================================
*
* Copyright (C) 2016 - 2019 Continental Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ========================= eCAL LICENSE =================================
*/
#pragma once
#include <QAbstractItemModel>
#include <QVector>
#include <QColor>
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4146 4800)
#endif
#include "ecal/pb/monitoring.pb.h"
#ifdef _MSC_VER
#pragma warning(pop)
#endif
class LogModel : public QAbstractItemModel
{
Q_OBJECT
public:
struct LogEntry
{ //-V802
long long time;
QString host_name;
int pid;
QString process_name;
QString process_path;
int log_level;
QString message;
};
enum Columns : int
{
TIME,
LOG_LEVEL,
HOST_NAME,
PID,
PROCESS_NAME,
PROCESS_PATH,
MESSAGE,
COLUMN_COUNT
};
LogModel(QObject* parent = Q_NULLPTR);
~LogModel();
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
int columnCount(const QModelIndex &parent) const override;
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override;
QModelIndex parent(const QModelIndex &index) const override;
Qt::ItemFlags flags(const QModelIndex &index) const override;
void insertLogs(const eCAL::pb::Logging& logs);
void setParseTimeEnabled(bool enabled);
bool isParseTimeEnabled() const;
void clear();
bool dumpToCsv(const QString& path);
private:
QList<LogEntry> logs_;
const QMap<Columns, QString> header_data
{
{ Columns::TIME, "Time" },
{ Columns::HOST_NAME, "Host" },
{ Columns::PID, "PID" },
{ Columns::PROCESS_NAME, "Process" },
{ Columns::PROCESS_PATH, "Process Path" },
{ Columns::LOG_LEVEL, "Level" },
{ Columns::MESSAGE, "Message" },
};
int max_entries_;
bool parse_time_enabled_;
static QString logLevelToString(int log_level);
static QColor logLevelColor(int log_level);
QString timeToString(long long milliseconds) const;
};
|
bijoumd78/ecal
|
ecal/core/include/ecal/msg/protobuf/server.h
|
/* ========================= eCAL LICENSE =================================
*
* Copyright (C) 2016 - 2019 Continental Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ========================= eCAL LICENSE =================================
*/
/**
* @file server.h
* @brief eCAL Server interface based on protobuf service description
**/
#pragma once
#include <ecal/ecal_server.h>
#include <ecal/protobuf/ecal_proto_hlp.h>
// protobuf includes
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4100 4146 4800)
#endif
#include <google/protobuf/descriptor.pb.h>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
// stl includes
#include <map>
#include <memory>
#include <string>
namespace eCAL
{
namespace protobuf
{
/**
* @brief Google Protobuf Server wrapper class.
**/
template <typename T>
class CServiceServer
{
public:
/**
* @brief Constructor.
**/
CServiceServer() : m_service(nullptr)
{
}
/**
* @brief Constructor.
*
* @param service_ Google protobuf service instance.
**/
CServiceServer(std::shared_ptr<T> service_) : m_service(nullptr)
{
Create(service_);
}
/**
* @brief Destructor.
**/
~CServiceServer()
{
Destroy();
}
/**
* @brief CServiceServers are non-copyable
**/
CServiceServer(const CServiceServer&) = delete;
/**
* @brief CServiceServers are non-copyable
**/
CServiceServer& operator=(const CServiceServer&) = delete;
/**
* @brief Create service.
*
* @param service_ Google protobuf service instance.
*
* @return True if successful.
**/
bool Create(std::shared_ptr<T> service_)
{
if (service_ == nullptr) return false;
m_service = service_;
const google::protobuf::ServiceDescriptor* service_descriptor = service_->GetDescriptor();
m_server.Create(service_descriptor->full_name());
for (int i = 0; i < service_descriptor->method_count(); ++i)
{
const google::protobuf::MethodDescriptor* method_descriptor = service_descriptor->method(i);
std::string method_name = method_descriptor->name();
m_methods[method_name] = method_descriptor;
m_server.AddMethodCallback(method_name,
method_descriptor->input_type()->name(),
method_descriptor->output_type()->name(),
std::bind(&CServiceServer::RequestCallback, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, std::placeholders::_5)
);
}
return true;
}
/**
* @brief Destroy service.
*
* @return True if successful.
**/
bool Destroy()
{
m_service = nullptr;
return m_server.Destroy();
}
protected:
int RequestCallback(const std::string& method_, const std::string& /*req_type_*/, const std::string& /*resp_type_*/, const std::string& request_, std::string& response_)
{
if (m_service == nullptr) return -1;
auto iter = m_methods.find(method_);
if (iter == m_methods.end()) return -1;
// method descriptor
const google::protobuf::MethodDescriptor* method_descriptor = iter->second;
// create request
google::protobuf::Message* request(m_service->GetRequestPrototype(method_descriptor).New());
if (!request->ParseFromString(request_)) return -1;
// create response
google::protobuf::Message* response(m_service->GetResponsePrototype(method_descriptor).New());
// call method
m_service->CallMethod(method_descriptor, nullptr, request, response, nullptr);
response_ = response->SerializeAsString();
return 0;
};
eCAL::CServiceServer m_server;
std::shared_ptr<T> m_service;
std::map<std::string, const google::protobuf::MethodDescriptor*> m_methods;
};
}
}
|
bijoumd78/ecal
|
ecal/core/src/readwrite/ecal_reader.h
|
/* ========================= eCAL LICENSE =================================
*
* Copyright (C) 2016 - 2019 Continental Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ========================= eCAL LICENSE =================================
*/
/**
* @brief common eCAL data reader
**/
#pragma once
#include <ecal/ecal.h>
#include <ecal/ecal_callback.h>
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4146 4800)
#endif
#include "ecal/pb/ecal.pb.h"
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "ecal_expmap.h"
#include <mutex>
#include <atomic>
#include <set>
#include <string>
#include <unordered_map>
namespace eCAL
{
class CDataReader
{
public:
CDataReader();
~CDataReader();
static void InitializeLayers();
bool Create(const std::string& topic_name_, const std::string& topic_type_, const std::string& topic_desc_);
bool Destroy();
bool SetQOS(QOS::SReaderQOS qos_);
size_t Receive(std::string& buf_, long long* time_ = nullptr, int rcv_timeout_ = 0);
bool AddReceiveCallback(ReceiveCallbackT callback_);
bool RemReceiveCallback();
bool AddEventCallback(eCAL_Subscriber_Event type_, SubEventCallbackT callback_);
bool RemEventCallback(eCAL_Subscriber_Event type_);
bool SetTimeout(int timeout_);
void SetID(const std::set<long long>& id_set_);
void ApplyLocPublication(const std::string& process_id_);
void ApplyExtPublication(const std::string& host_name_);
void ApplyLocLayerParameter(const std::string& process_id_, eCAL::pb::eTLayerType type_, const std::string& parameter_);
void ApplyExtLayerParameter(const std::string& host_name_, eCAL::pb::eTLayerType type_, const std::string& parameter_);
std::string Dump(const std::string& indent_ = "");
bool IsCreated() const {return(m_created);}
const std::string GetTopicName() const {return(m_topic_name);}
const std::string GetTopicID() const {return(m_topic_id);}
const std::string GetTypeName() const {return(m_topic_type);}
const std::string GetDescription() const;
void RefreshRegistration();
void CheckReceiveTimeout();
size_t AddSample(const std::string& tid_, const char* payload_, size_t size_, long long id_, long long clock_, long long time_, size_t hash_, eCAL::pb::eTLayerType layer_);
protected:
void StartDataLayers();
void StopDataLayers();
bool DoRegister(const bool force_);
void SetConnected(bool state_);
void CheckCounter(const std::string& tid_, long long counter_);
std::string m_host_name;
int m_host_id;
int m_pid;
std::string m_pname;
std::string m_topic_name;
std::string m_topic_id;
std::string m_topic_type;
std::string m_topic_desc;
std::string m_mcast_address;
std::atomic<size_t> m_topic_size;
QOS::SReaderQOS m_qos;
std::atomic<bool> m_connected;
typedef Util::CExpMap<std::string, bool> ConnectedMapT;
std::mutex m_pub_map_sync;
ConnectedMapT m_loc_pub_map;
ConnectedMapT m_ext_pub_map;
EventHandleT m_receive_event;
std::mutex m_read_buf_sync;
std::string m_read_buf;
long long m_read_time;
std::mutex m_receive_callback_sync;
ReceiveCallbackT m_receive_callback;
std::atomic<int> m_receive_timeout;
std::atomic<int> m_receive_time;
typedef Util::CExpMap<size_t, size_t> SampleHashMapT;
SampleHashMapT m_sample_hash;
std::mutex m_event_callback_sync;
typedef std::map<eCAL_Subscriber_Event, SubEventCallbackT> EventCallbackMapT;
EventCallbackMapT m_event_callback_map;
std::atomic<long long> m_clock;
long long m_clock_old;
std::chrono::steady_clock::time_point m_rec_time;
long m_freq;
std::set<long long> m_id_set;
typedef std::unordered_map<std::string, long long> WriterCounterMapT;
WriterCounterMapT m_writer_counter_map;
long long m_message_drops;
std::atomic<bool> m_loc_published;
std::atomic<bool> m_ext_published;
bool m_use_ttype;
bool m_use_tdesc;
bool m_use_udp_mc_confirmed;
bool m_use_shm_confirmed;
bool m_use_inproc_confirmed;
std::atomic<bool> m_created;
};
}
|
bijoumd78/ecal
|
app/mon/mon_gui/src/widgets/models/service_tree_model.h
|
<filename>app/mon/mon_gui/src/widgets/models/service_tree_model.h
/* ========================= eCAL LICENSE =================================
*
* Copyright (C) 2016 - 2019 Continental Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ========================= eCAL LICENSE =================================
*/
#pragma once
#include "group_tree_model.h"
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4146 4800)
#endif
#include "ecal/pb/monitoring.pb.h"
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "service_tree_item.h"
#include <QMap>
#include <QVector>
#include <QPair>
class ServiceTreeModel : public GroupTreeModel
{
Q_OBJECT
public:
enum class Columns : int
{
GROUP,
UNIT_NAME,
SERVICE_NAME,
PROCESS_NAME,
HOST_NAME,
PID,
TCP_PORT,
METHOD_NAME,
METHOD_REQUEST_TYPE,
METHOD_RESPONSE_TYPE,
HEARTBEAT,
CALL_COUNT,
COLUMN_COUNT
};
ServiceTreeModel(QObject *parent = nullptr);
~ServiceTreeModel();
int columnCount(const QModelIndex &parent = QModelIndex()) const;
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
QVector<QPair<int, QString>> getTreeItemColumnNameMapping() const;
void monitorUpdated(const eCAL::pb::Monitoring& monitoring_pb);
protected:
int mapColumnToItem(int model_column, int tree_item_type) const override;
int groupColumn() const;
private:
std::map<Columns, QString> columnLabels =
{
{ Columns::GROUP, "Group" },
{ Columns::HEARTBEAT, "Heartbeat" },
{ Columns::HOST_NAME, "Host" },
{ Columns::PID, "PID" },
{ Columns::PROCESS_NAME, "Process Path" },
{ Columns::UNIT_NAME, "Process" },
{ Columns::SERVICE_NAME, "Service" },
{ Columns::TCP_PORT, "TCP Port" },
{ Columns::METHOD_NAME, "Method" },
{ Columns::METHOD_REQUEST_TYPE, "Req. Type" },
{ Columns::METHOD_RESPONSE_TYPE, "Resp. Type" },
{ Columns::CALL_COUNT, "Call count" },
};
std::map<Columns, int> tree_item_column_mapping =
{
{ Columns::GROUP, -1 },
{ Columns::HEARTBEAT, (int)ServiceTreeItem::Columns::RCLOCK },
{ Columns::HOST_NAME, (int)ServiceTreeItem::Columns::HNAME },
{ Columns::PID, (int)ServiceTreeItem::Columns::PID },
{ Columns::PROCESS_NAME, (int)ServiceTreeItem::Columns::PNAME },
{ Columns::UNIT_NAME, (int)ServiceTreeItem::Columns::UNAME },
{ Columns::SERVICE_NAME, (int)ServiceTreeItem::Columns::SNAME },
{ Columns::TCP_PORT, (int)ServiceTreeItem::Columns::TCP_PORT },
{ Columns::METHOD_NAME, (int)ServiceTreeItem::Columns::MNAME },
{ Columns::METHOD_REQUEST_TYPE, (int)ServiceTreeItem::Columns::REQ_TYPE },
{ Columns::METHOD_RESPONSE_TYPE, (int)ServiceTreeItem::Columns::RESP_TYPE },
{ Columns::CALL_COUNT, (int)ServiceTreeItem::Columns::CALL_COUNT },
};
std::map<std::string, ServiceTreeItem*> tree_item_map_;
};
|
bijoumd78/ecal
|
app/mon/mon_gui/src/widgets/models/topic_tree_model.h
|
/* ========================= eCAL LICENSE =================================
*
* Copyright (C) 2016 - 2019 Continental Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ========================= eCAL LICENSE =================================
*/
#pragma once
#include "group_tree_model.h"
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4146 4800)
#endif
#include "ecal/pb/monitoring.pb.h"
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "topic_tree_item.h"
#include "group_tree_item.h"
#include <QMap>
#include <QVector>
#include <QPair>
class TopicTreeModel : public GroupTreeModel
{
Q_OBJECT
public:
enum class Columns : int
{
GROUP,
TOPIC_ID,
TOPIC_NAME,
DIRECTION,
UNIT_NAME,
HOST_NAME,
PID,
PROCESS_NAME,
MESSAGE_TYPE,
HEARTBEAT,
//TOPIC_DESCRIPTION,
QOS,
TRANSPORT_LAYER,
TOPIC_SIZE,
CONNECTIONS_LOCAL,
CONNECTIONS_EXTERNAL,
MESSAGE_DROPS,
DATA_CLOCK,
DATA_FREQUENCY,
COLUMN_COUNT
};
TopicTreeModel(QObject *parent = nullptr);
~TopicTreeModel();
int columnCount(const QModelIndex &parent = QModelIndex()) const;
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
QVector<QPair<int, QString>> getTreeItemColumnNameMapping() const;
void monitorUpdated(const eCAL::pb::Monitoring& monitoring_pb);
protected:
int mapColumnToItem(int model_column, int tree_item_type) const override;
int groupColumn() const;
private:
std::map<Columns, QString> columnLabels =
{
{ Columns::GROUP, "Group" },
{ Columns::HEARTBEAT, "Heartbeat" },
{ Columns::HOST_NAME, "Host" },
{ Columns::PID, "PID" },
{ Columns::PROCESS_NAME, "Process Path" },
{ Columns::UNIT_NAME, "Process" },
{ Columns::TOPIC_ID, "Topic ID" },
{ Columns::TOPIC_NAME, "Topic" },
{ Columns::DIRECTION, "Direction" },
{ Columns::MESSAGE_TYPE, "Message Type" },
//{ Columns::TOPIC_DESCRIPTION, "Description" },
{ Columns::QOS, "QoS" },
{ Columns::TRANSPORT_LAYER, "Layer" },
{ Columns::TOPIC_SIZE, "Size [Byte]" },
{ Columns::CONNECTIONS_LOCAL, "Loc. Connections" },
{ Columns::CONNECTIONS_EXTERNAL, "Ext. Connections" },
{ Columns::MESSAGE_DROPS, "Drops" },
{ Columns::DATA_CLOCK, "Data Clock" },
{ Columns::DATA_FREQUENCY, "Frequency [Hz]" },
};
std::map<Columns, int> topic_tree_item_column_mapping =
{
{ Columns::GROUP, -1 },
{ Columns::HEARTBEAT, (int)TopicTreeItem::Columns::RCLOCK },
{ Columns::HOST_NAME, (int)TopicTreeItem::Columns::HNAME },
{ Columns::PID, (int)TopicTreeItem::Columns::PID },
{ Columns::PROCESS_NAME, (int)TopicTreeItem::Columns::PNAME },
{ Columns::UNIT_NAME, (int)TopicTreeItem::Columns::UNAME },
{ Columns::TOPIC_ID, (int)TopicTreeItem::Columns::TID },
{ Columns::TOPIC_NAME, (int)TopicTreeItem::Columns::TNAME },
{ Columns::DIRECTION, (int)TopicTreeItem::Columns::DIRECTION },
{ Columns::MESSAGE_TYPE, (int)TopicTreeItem::Columns::TTYPE },
//{ Columns::TOPIC_DESCRIPTION, (int)TopicTreeItem::Columns::TDESC },
{ Columns::QOS, (int)TopicTreeItem::Columns::TQOS },
{ Columns::TRANSPORT_LAYER, (int)TopicTreeItem::Columns::TLAYER },
{ Columns::TOPIC_SIZE, (int)TopicTreeItem::Columns::TSIZE },
{ Columns::CONNECTIONS_LOCAL, (int)TopicTreeItem::Columns::CONNECTIONS_LOC },
{ Columns::CONNECTIONS_EXTERNAL, (int)TopicTreeItem::Columns::CONNECTIONS_EXT },
{ Columns::MESSAGE_DROPS, (int)TopicTreeItem::Columns::MESSAGE_DROPS },
{ Columns::DATA_CLOCK, (int)TopicTreeItem::Columns::DCLOCK },
{ Columns::DATA_FREQUENCY, (int)TopicTreeItem::Columns::DFREQ },
};
std::map<std::string, TopicTreeItem*> topic_tree_item_map_;
};
|
bijoumd78/ecal
|
ecal/core/src/ecal_timegate.h
|
/* ========================= eCAL LICENSE =================================
*
* Copyright (C) 2016 - 2019 Continental Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ========================= eCAL LICENSE =================================
*/
/**
* @brief eCAL time gateway class
**/
#pragma once
#include <ecal/ecal.h>
#include "ecal_global_accessors.h"
#include <atomic>
#ifdef ECAL_OS_WINDOWS
#include "ecal_win_main.h"
typedef int (__cdecl *etime_initialize) (void);
typedef int (__cdecl *etime_finalize) (void);
typedef long long (__cdecl *etime_get_nanoseconds) (void);
typedef int (__cdecl *etime_set_nanoseconds) (long long time_);
typedef int (__cdecl *etime_is_synchronized) (void);
typedef int (__cdecl *etime_is_master) (void);
typedef int (__cdecl *etime_sleep_for_nanoseconds)(long long duration_nsecs_);
typedef void (__cdecl *etime_get_status) (int*, char*, const int);
#endif // ECAL_OS_WINDOWS
#ifdef ECAL_OS_LINUX
typedef int (*etime_initialize) (void);
typedef int (*etime_finalize) (void);
typedef long long (*etime_get_nanoseconds) (void);
typedef int (*etime_set_nanoseconds) (long long time_);
typedef int (*etime_is_synchronized) (void);
typedef int (*etime_is_master) (void);
typedef int (*etime_sleep_for_nanoseconds)(long long duration_nsecs_);
typedef void (*etime_get_status) (int*, char*, const int);
#endif //ECAL_OS_LINUX
namespace eCAL
{
class CTimeGate
{
public:
enum eTimeSyncMode { none, realtime, replay };
CTimeGate();
~CTimeGate();
void Create(enum eTimeSyncMode sync_mode_);
void Destroy();
std::string GetName();
long long GetMicroSeconds();
long long GetNanoSeconds();
bool SetNanoSeconds(long long time_);
bool IsSynchronized();
bool IsMaster();
void SleepForNanoseconds(long long duration_nsecs_);
void GetStatus(int& error_, std::string* const status_message_);
bool IsValid();
eTimeSyncMode GetSyncMode() { return(m_sync_mode); };
protected:
static std::atomic<bool> m_created;
std::string m_time_sync_modname;
std::atomic<bool> m_is_initialized_rt;
std::atomic<bool> m_is_initialized_replay;
std::atomic<bool> m_successfully_loaded_rt;
std::atomic<bool> m_successfully_loaded_replay;
eTimeSyncMode m_sync_mode;
struct STimeDllInterface
{
STimeDllInterface() :
module_handle(nullptr),
module_name(),
etime_initialize_ptr(nullptr),
etime_finalize_ptr(nullptr),
etime_get_nanoseconds_ptr(nullptr),
etime_set_nanoseconds_ptr(nullptr),
etime_is_synchronized_ptr(nullptr),
etime_is_master_ptr(nullptr),
etime_sleep_for_nanoseconds_ptr(nullptr),
etime_get_status_ptr(nullptr)
{
}
#ifdef _WIN32
HINSTANCE module_handle;
#endif //_WIN32
#ifdef __linux__
void* module_handle;
#endif //__linux__
std::string module_name;
etime_initialize etime_initialize_ptr;
etime_finalize etime_finalize_ptr;
etime_get_nanoseconds etime_get_nanoseconds_ptr;
etime_set_nanoseconds etime_set_nanoseconds_ptr;
etime_is_synchronized etime_is_synchronized_ptr;
etime_is_master etime_is_master_ptr;
etime_sleep_for_nanoseconds etime_sleep_for_nanoseconds_ptr;
etime_get_status etime_get_status_ptr;
};
bool LoadModule(const std::string& interface_name_, STimeDllInterface& interface_);
STimeDllInterface m_time_sync_rt;
STimeDllInterface m_time_sync_replay;
};
};
|
danielcdev/libserver
|
src/factory/headers/SocketFactory.h
|
/*
* SocketFactory.h
*
* Created on: Aug 11, 2015
* Author: <NAME>
*/
#ifndef FACTORY_SOCKETFACTORY_H_
#define FACTORY_SOCKETFACTORY_H_
#include <sys/socket.h>
#include <netinet/in.h>
#include "../../interface/headers/ServerSocket.h"
#include "../../interface/headers/ClientSocket.h"
#include "../../model/headers/Client.h"
class SocketFactory: public ServerSocket, ClientSocket {
unsigned short int port;
int actualSocket, timeoutSeconds = 0, timeoutMilliseconds = 0,
addressLength = 0, yes = 1, no = 0;
struct timeval timeout;
struct sockaddr_in address;
void setupTimeout();
void setupAddress();
bool createSocket();
bool setupSocketOptions();
bool bindSocket();
bool listenOnSocket();
public:
void generateServerSocket();
Client listenForNewConnection();
void setPort(unsigned short int port);
void setTimeoutMilliseconds(int milliseconds);
void setTimeoutSeconds(int seconds);
};
#endif /* FACTORY_SOCKETFACTORY_H_ */
|
danielcdev/libserver
|
src/interface/headers/ClientSocket.h
|
<gh_stars>0
/*
* ClientSocket.h
*
* Created on: Aug 15, 2015
* Author: <NAME>
*/
#ifndef INTERFACE_CLIENTSOCKET_H_
#define INTERFACE_CLIENTSOCKET_H_
class ClientSocket {
public:
virtual ~ClientSocket();
};
#endif /* INTERFACE_CLIENTSOCKET_H_ */
|
danielcdev/libserver
|
src/model/headers/Client.h
|
/*
* Client.h
*
* Created on: Aug 12, 2015
* Author: <NAME>
*/
#ifndef MODEL_CLIENT_H_
#define MODEL_CLIENT_H_
#include <string>
#include <sys/socket.h>
#include <unistd.h>
using namespace std;
class Client {
protected:
int socket = 0;
public:
string readUntil(string delimiter);
void send(string data);
void close();
Client();
Client(int socket);
int getSocket();
bool compare(Client c);
bool operator ==(Client c) {
return compare(c);
}
};
#endif /* MODEL_CLIENT_H_ */
|
danielcdev/libserver
|
src/utility/headers/StringUtility.h
|
<reponame>danielcdev/libserver
/*
* StringUtility.h
*
* Created on: Aug 14, 2015
* Author: <NAME>
*/
#ifndef UTILITY_STRINGUTILITY_H_
#define UTILITY_STRINGUTILITY_H_
#include <string>
#include <list>
using namespace std;
class StringUtility {
public:
static unsigned int findOccurrences(string data, string token);
static list<string> explode(string data, string token);
static string trim(string data);
};
#endif /* UTILITY_STRINGUTILITY_H_ */
|
danielcdev/libserver
|
src/interface/headers/ThreadTask.h
|
/*
* ThreadTask.h
*
* Created on: Aug 12, 2015
* Author: <NAME>
*/
#ifndef INTERFACE_THREADTASK_H_
#define INTERFACE_THREADTASK_H_
#include "../../model/headers/Client.h"
class ThreadTask {
public:
virtual void performTask(Client client);
virtual ~ThreadTask();
};
#endif /* INTERFACE_THREADTASK_H_ */
|
danielcdev/libserver
|
include/ThreadManager.h
|
<filename>include/ThreadManager.h
/*
* ThreadManager.h
*
* Created on: Aug 15, 2015
* Author: <NAME>
*/
#ifndef INTERFACE_THREADMANAGER_H_
#define INTERFACE_THREADMANAGER_H_
#include <libserver/ThreadTask.h>
#include <libserver/Client.h>
class ThreadManager {
public:
virtual ~ThreadManager();
virtual void generateThreadManager();
virtual void setTask(ThreadTask *task);
virtual void newTask(Client client);
};
#endif /* INTERFACE_THREADMANAGER_H_ */
|
danielcdev/libserver
|
include/ServerSocket.h
|
/*
* ServerSocket.h
*
* Created on: Aug 16, 2015
* Author: <NAME>
*/
#ifndef INTERFACE_SERVERSOCKET_H_
#define INTERFACE_SERVERSOCKET_H_
#include <libserver/Client.h>
class ServerSocket {
public:
virtual ~ServerSocket();
virtual void setPort(unsigned short int port);
virtual void setTimeoutSeconds(int seconds);
virtual void setTimeoutMilliseconds(int milliseconds);
virtual void generateServerSocket();
virtual Client listenForNewConnection();
};
#endif /* INTERFACE_SERVERSOCKET_H_ */
|
danielcdev/libserver
|
src/interface/headers/ThreadManager.h
|
/*
* ThreadManager.h
*
* Created on: Aug 15, 2015
* Author: <NAME>
*/
#ifndef INTERFACE_THREADMANAGER_H_
#define INTERFACE_THREADMANAGER_H_
#include "../../interface/headers/ThreadTask.h"
#include "../../model/headers/Client.h"
class ThreadManager {
public:
virtual ~ThreadManager();
virtual void generateThreadManager();
virtual void setTask(ThreadTask *task);
virtual void newTask(Client client);
};
#endif /* INTERFACE_THREADMANAGER_H_ */
|
danielcdev/libserver
|
src/factory/headers/ThreadManagerFactory.h
|
/*
* ThreadManagerFactory.h
*
* Created on: Aug 15, 2015
* Author: <NAME>
*/
#ifndef FACTORY_THREADMANAGERFACTORY_H_
#define FACTORY_THREADMANAGERFACTORY_H_
#include <condition_variable>
#include <exception>
#include <mutex>
#include <thread>
#include <map>
#include <unistd.h>
#include "../../interface/headers/ThreadTask.h"
#include "../../interface/headers/ThreadManager.h"
#include "../../model/headers/Client.h"
using namespace std;
class ThreadManagerFactory: public ThreadManager {
unsigned short int maxThreads;
unsigned short int currentTask = 0;
mutex threadManagerMutex;
map<unsigned short int, condition_variable> taskNotify;
map<unsigned short int, Client> connectionArray;
ThreadTask *task;
static void entryPoint(void *me, unsigned short int threadId);
static void watcherEntryPoint(void *me);
void threadRun(unsigned short int threadId);
void watcherThread();
public:
ThreadManagerFactory(unsigned short int maxThreads);
~ThreadManagerFactory();
void generateThreadManager();
void newTask(Client client);
void setTask(ThreadTask *task);
};
#endif /* FACTORY_THREADMANAGERFACTORY_H_ */
|
bluescan/tacit-texview
|
Src/InputBindings.h
|
<filename>Src/InputBindings.h
// InputBindings.h
//
// Allows you to set key bindings for all TacentView operations.
//
// Copyright (c) 2022 <NAME>.
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby
// granted, provided that the above copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
// AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
#pragma once
#include <Foundation/tString.h>
#include <System/tScript.h>
#include <GLFW/glfw3.h>
#include "Profile.h"
namespace Viewer {
namespace Bindings
{
// Add new operations to the bottom of this enum. If you add in the middle or reorder,
// it will invalidate the key bindings in previous version's config save files.
enum class Operation
{
None,
NextImage, First = NextImage,
PrevImage,
SkipToLastImage,
SkipToFirstImage,
NextImageFrame,
PrevImageFrame,
PixelRight,
PixelLeft,
PixelDown,
PixelUp,
ZoomIn,
ZoomOut,
ZoomFit,
ZoomDownscaleOnly,
ZoomOneToOne,
ResetPan,
FlipVertically,
FlipHorizontally,
Rotate90Anticlockwise,
Rotate90Clockwise,
RotateImage,
Crop,
ResizeImage,
ResizeCanvas,
PixelEdit,
PropertyEdit,
ChannelFilter,
RedChannel,
GreenChannel,
BlueChannel,
AlphaChannel,
ChannelAsIntensity,
Details,
Tile,
Undo,
Redo,
Refresh,
Rename,
Delete,
DeletePermanent,
SaveAs,
SaveAll,
SaveMultiFrameImage,
SaveContactSheet,
MenuBar,
NavBar,
Thumbnails,
FileBrowser,
SlideshowTimer,
CheatSheet,
DebugLog,
Profile,
Preferences,
KeyBindings,
Fullscreen,
Escape, // Exit-Fullscreen | Exit-Basic-Profile.
EscapeSupportingQuit, // Exit-Fullscreen | Exit-Basic-Profile | Quit.
Quit,
OpenFile,
OpenDir,
// Add new operations here. Adding above will invalidate save file keybindings.
NumOperations
};
enum Modifier
{
Modifier_None,
Modifier_Ctrl = 1 << 0,
Modifier_Alt = 1 << 1,
Modifier_Shift = 1 << 2,
Modifier_NumCombinations = 1 << 3
};
const char* GetModifiersText(uint32 modifiers);
// Gets the combined (modifiers plus key) text. ex. "Ctrl-Alt-Shift Space" or "Ctrl A" or "A".
// Returns empty string if the key is not supported.
tString GetModKeyText(int glfwkey, uint32 modifiers);
// Specifies, for a single key, what operations it performs. The same key can map to multiple operations if modifier
// keys are used.
struct KeyOps
{
KeyOps() { Clear(); }
KeyOps(const KeyOps& src) { Set(src); }
void Set(const KeyOps& src) { if (&src == this) return; for (int m = 0; m < Modifier_NumCombinations; m++) Operations[m] = src.Operations[m]; }
void Clear() { for (int m = 0; m < Modifier_NumCombinations; m++) Operations[m] = Operation::None; }
bool IsAnythingAssigned() const { for (int m = 0; m < Modifier_NumCombinations; m++) if (Operations[m] != Operation::None) return true; return false; }
int GetAssignedCount() const { int count = 0; for (int m = 0; m < Modifier_NumCombinations; m++) if (Operations[m] != Operation::None) count++; return count; }
// Finds the mods for the first (there may be more than one) operation matching the search operation.
// Returns false if no such operation was found.
bool FindOperationMods(uint32& mods, Operation searchOp) const { for (uint32 m = 0; m < Modifier_NumCombinations; m++) { if (Operations[m] == searchOp) { mods = m; return true; } } return false; }
KeyOps& operator=(const KeyOps& src) { Set(src); return *this; }
Operation Operations[Modifier_NumCombinations];
};
class InputMap
{
public:
InputMap() { Clear(); }
InputMap(const InputMap& src) { Set(src); }
void Set(const InputMap& src) { if (&src == this) return; for (int k = 0; k <= GLFW_KEY_LAST; k++) KeyTable[k] = src.KeyTable[k]; }
void Clear() /* Unassigns all keys. */ { for (int k = 0; k <= GLFW_KEY_LAST; k++) KeyTable[k].Clear(); }
// Sets all keys to their default operations. Some keys have different operations depending on the profile so we
// need to pass that in. If onlyIfUnassigned is true, the reset will only apply to keys that are not already
// bound to something. A 'key' here refers to the actual key plus any modifiers (ctrl, alt, shift).
void Reset(Viewer::Profile, bool onlyIfUnassigned = false);
// Returns the operation assigned to a particular key and set of modifiers. This can also be used before an
// assign call to see what a current key is bound to so an already-assigned message can be dislayed if needed.
Operation GetOperation(int glfwKey, uint32 modifiers) { return KeyTable[glfwKey].Operations[modifiers]; }
KeyOps& GetKeyOps(int glfwKey) { return KeyTable[glfwKey]; }
// Assigns the operation to the key and modifiers specified. Returns true is there was a previous assignment
// that needed to be replaced. Pass in onlyIfUnassigned if you only want assignment to happen if the key is
// currently unassigned.
bool AssignKey(int glfwkey, uint32 modifiers, Operation, bool onlyIfUnassigned = false);
void ClearKey(int glfwkey, uint32 modifiers) { KeyTable[glfwkey].Operations[modifiers] = Operation::None; }
int GetTotalAssigned() const { int count = 0; for (int k = 0; k <= GLFW_KEY_LAST; k++) count += KeyTable[k].GetAssignedCount(); return count; }
// Searches for the first occurrence of the supplied operation and returns the key and modifiers that are bound
// to it. Note that since there may be more than one key bound to the same operation, this function returns the
// first one found. Returns true if something found.
bool FindModKey(int& key, uint32& mods, Operation);
// Convenience. Basically calls FindModKey on the supplied operation and then calls GetModKeyText on the result.
// The returned string will be empty if nothing is bound to the operation.
tString FindModKeyText(Operation op) { int key = 0; uint32 mods = 0; if (FindModKey(key, mods, op)) return GetModKeyText(key, mods); else return tString(); }
void Read(tExpression);
void Write(tScriptWriter&);
InputMap& operator=(const InputMap& src) { Set(src); return *this; }
private:
KeyOps KeyTable[GLFW_KEY_LAST+1];
};
// Some descriptions may change based on the current config, for example, what the esc key does
const char* GetOperationDesc(Operation);
// Converts from GLFW modifiers to viewer modifiers.
uint32 TranslateModifiers(int glfwModifiers);
void ShowBindingsWindow(bool* popen, bool justOpened);
void ShowCheatSheetWindow(bool* popen);
}
}
|
bluescan/tacit-texview
|
Src/Dialogs.h
|
// Dialogs.h
//
// Various dialogs and helpers including a log window, info overlay, cheatsheet, help window, and about window.
//
// Copyright (c) 2019, 2020, 2021, 2022 <NAME>.
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby
// granted, provided that the above copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
// AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
#pragma once
namespace Viewer
{
void ShowImageDetailsOverlay(bool* popen, float x, float y, float w, float h, int cursorX, int cursorY, float zoom);
void ShowPixelEditorOverlay(bool* popen);
void ShowChannelFilterOverlay(bool* popen);
void ShowAboutPopup(bool* popen);
void ColourCopyAs();
void DoDeleteFileModal();
void DoDeleteFileNoRecycleModal();
void DoRenameModal(bool justOpened);
void DoSnapMessageNoFileBrowseModal(bool justOpened);
void DoSnapMessageNoFrameTransModal(bool justOpened);
// Parts of this class are a modification of the one that ships with Dear ImGui. The DearImGui
// licence (MIT) may be found in the txt file Licence_DearImGui_MIT.txt in the Data folder.
class NavLogBar
{
public:
NavLogBar() : LogScrollToBottom(true) { ClearLog(); }
void Draw();
void SetShowLog(bool enabled) { ShowLog = enabled; }
bool GetShowLog() const { return ShowLog; }
void AddLog(const char* fmt, ...) IM_FMTARGS(2);
private:
void ClearLog();
void DrawLog();
bool ShowLog = false;
ImGuiTextBuffer LogBuf;
ImGuiTextFilter LogFilter;
// Index to lines offset. We maintain this with AddLog() calls, allowing us to have a random access on lines.
ImVector<int> LogLineOffsets;
bool LogScrollToBottom;
};
}
|
bluescan/tacit-texview
|
Src/Image.h
|
// Image.h
//
// An image class that can load a file from disk into main memory and to VRAM.
//
// Copyright (c) 2019-2022 <NAME>.
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby
// granted, provided that the above copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
// AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
#pragma once
#include <thread>
#include <atomic>
#include <glad/glad.h>
#include <Foundation/tList.h>
#include <Foundation/tString.h>
#include <System/tFile.h>
#include <Image/tPicture.h>
#include <Image/tTexture.h>
#include <Image/tCubemap.h>
#include <Image/tImageHDR.h>
#include "Config.h"
#include "Undo.h"
namespace Viewer
{
class Image : public tLink<Image>
{
public:
Image();
// These constructors do not actually load the image, but Load() may be called at any point afterwards.
Image(const tString& filename);
Image(const tSystem::tFileInfo& fileInfo);
virtual ~Image();
// These params are in principle different to the ones in tPicture since a Image does not necessarily
// only use tPicture to do the loading. For example, we might include dds load params here.
void ResetLoadParams();
tImage::tPicture::LoadParams LoadParams;
void Play();
void Stop();
void UpdatePlaying(float dt);
bool FrameDurationPreviewEnabled = false;
float FrameDurationPreview = 1.0f/30.0f;
float FrameCurrCountdown = 0.0f;
bool FramePlaying = false;
bool FramePlayRev = false;
bool FramePlayLooping = true;
int FrameNum = 0;
bool Load(const tString& filename);
bool Load(); // Load into main memory.
bool IsLoaded() const { return (Pictures.Count() > 0); }
int GetNumFrames() const { return Pictures.Count(); }
bool IsOpaque() const;
bool Unload(bool force = false);
float GetLoadedTime() const { return LoadedTime; }
// Bind to a texture ID and load into VRAM. If already in VRAM, it makes the texture current. Since some ImGui
// functions require a texture ID as parameter, this function return the ID.
// If the alt image is enabled, the bound texture and ID will be the alt image's.
// Returns 0 (invalid id) if there was a problem.
uint64 Bind();
void Unbind();
int GetWidth() const;
int GetHeight() const;
int GetArea() const;
tColouri GetPixel(int x, int y) const;
// Some images can store multiple complete images inside a single file (multiple frames).
// The primary one is the first one.
tImage::tPicture* GetPrimaryPic() const { return Pictures.First(); }
tImage::tPicture* GetCurrentPic() const { tImage::tPicture* pic = Pictures.First(); for (int i = 0; i < FrameNum; i++) pic = pic ? pic->Next() : nullptr; return pic; }
tList<tImage::tPicture>& GetPictures() { return Pictures; }
// Functions that edit and cause dirty flag to be set.
void Rotate90(bool antiClockWise);
void Rotate(float angle, const tColouri& fill, tImage::tResampleFilter upFilter, tImage::tResampleFilter downFilter);
void Flip(bool horizontal);
void Crop(int newWidth, int newHeight, int originX, int originY, const tColouri& fillColour = tColour::black);
void Crop(int newWidth, int newHeight, tImage::tPicture::Anchor, const tColouri& fillColour = tColour::black);
void Crop(const tColouri& borderColour, uint32 channels = tMath::ColourChannel_RGBA);
void Resample(int newWidth, int newHeight, tImage::tResampleFilter filter, tImage::tResampleEdgeMode edgeMode);
void SetPixelColour(int x, int y, const tColouri&, bool pushUndo, bool supressDirty = false);
void SetAllPixels(const tColouri& colour, uint32 channels = tMath::ColourChannel_RGBA);
void AlphaBlendColour(const tColouri& blendColour, bool resetAlpha);
void SetFrameDuration(float duration, bool allFrames = false);
// Undo and redo functions.
void Undo() { UndoStack.Undo(Pictures, Dirty); }
void Redo() { UndoStack.Redo(Pictures, Dirty); }
bool IsUndoAvailable() const { return UndoStack.UndoAvailable(); }
bool IsRedoAvailable() const { return UndoStack.RedoAvailable(); }
tString GetUndoDesc() const { tString desc; tsPrintf(desc, "[%s]", UndoStack.GetUndoDesc().Chars()); return desc; }
tString GetRedoDesc() const { tString desc; tsPrintf(desc, "[%s]", UndoStack.GetRedoDesc().Chars()); return desc; }
// Since from outside this class you can save to any filename, we need the ability to clear the dirty flag.
void ClearDirty() { Dirty = false; }
bool IsDirty() const { return Dirty; }
struct ImgInfo
{
bool IsValid() const { return (SrcPixelFormat != tImage::tPixelFormat::Invalid); }
tImage::tPixelFormat SrcPixelFormat = tImage::tPixelFormat::Invalid;
bool Opaque = false;
int FileSizeBytes = 0;
int MemSizeBytes = 0;
};
bool IsAltMipmapsPictureAvail() const { return DDSTexture2D.IsValid() && AltPicture.IsValid(); }
bool IsAltCubemapPictureAvail() const { return DDSCubemap.IsValid() && AltPicture.IsValid(); }
void EnableAltPicture(bool enabled) { AltPictureEnabled = enabled; }
bool IsAltPictureEnabled() const { return AltPictureEnabled; }
// Thumbnail generation is done on a seperate thread. Calling RequestThumbnail starts the thread. You should call it
// over and over as it will only ever start one thread, and it may not start it if too mnay threads are already
// working. BindThumbnail will at some point return a non-zero texture ID, but not necessarily right away. Just keep
// calling it. Unloaded images remain unloaded after thumbnail generation.
void RequestThumbnail();
// Call this if you need to invaidate the thumbnail. For example, if the file was saved/edited this should be called
// to force regeneration.
void RequestInvalidateThumbnail();
// You are allowed to unrequest. It will succeed if a worker was never assigned.
void UnrequestThumbnail();
bool IsThumbnailWorkerActive() const { return ThumbnailThreadRunning; }
uint64 BindThumbnail();
inline static int GetThumbnailNumThreadsRunning() { return ThumbnailNumThreadsRunning; }
ImgInfo Info; // Info is only valid AFTER loading.
tString Filename; // Valid before load.
tSystem::tFileType Filetype; // Valid before load. Based on extension.
std::time_t FileModTime; // Valid before load.
uint64 FileSizeB; // Valid before load.
int CachePrimaryWidth = 0; // Valid once thumbnail loaded. Used for sorting without having to do full load.
int CachePrimaryHeight = 0;
int CachePrimaryArea = 0;
const static uint32 ThumbChunkInfoID;
const static int ThumbWidth; // = 256;
const static int ThumbHeight; // = 144;
const static int ThumbMinDispWidth; // = 64;
static tString ThumbCacheDir;
bool TypeSupportsProperties() const;
private:
void PushUndo(const tString& desc) { UndoStack.Push(Pictures, desc, Dirty); }
// Dds files are special and already in HW ready format. The tTexture can store dds files, while tPicture stores
// other types (tga, gif, jpg, bmp, tif, png, etc). If the image is a dds file, the tTexture is valid and in order
// to read pixel data, the image is fetched from the framebuffer to ALSO make a valid PictureImage.
//
// Note: A tTexture contains all mipmap levels while a tPicture does not. That's why we have a list of tPictures.
tImage::tTexture DDSTexture2D;
tImage::tCubemap DDSCubemap;
tList<tImage::tPicture> Pictures;
// The 'alternative' picture is valid when there is another valid way of displaying the image.
// Specifically for cubemaps and dds files with mipmaps this offers an alternative view.
bool AltPictureEnabled = false;
tImage::tPicture AltPicture;
bool ThumbnailRequested = false; // True if ever requested.
bool ThumbnailInvalidateRequested = false;
bool ThumbnailThreadRunning = false; // Only true while worker thread going.
static int ThumbnailNumThreadsRunning; // How many worker threads active.
std::thread ThumbnailThread;
std::atomic_flag ThumbnailThreadFlag = ATOMIC_FLAG_INIT;
tImage::tPicture ThumbnailPicture;
// These 2 functions run on a helper thread.
static void GenerateThumbnailBridge(Image*);
void GenerateThumbnail();
// Zero is invalid and means texture has never been bound and loaded into VRAM.
uint TexIDAlt = 0;
uint TexIDThumbnail = 0;
// Returns the approx main mem size of this image. Considers the Pictures list and the AltPicture.
int GetMemSizeBytes() const;
bool ConvertTexture2DToPicture();
bool ConvertCubemapToPicture();
void GetGLFormatInfo(GLint& srcFormat, GLenum& srcType, GLint& dstFormat, bool& compressed, tImage::tPixelFormat);
void BindLayers(const tList<tImage::tLayer>&, uint texID);
void CreateAltPictureFromDDS_2DMipmaps();
void CreateAltPictureFromDDS_Cubemap();
float LoadedTime = -1.0f;
bool Dirty = false;
// Undo / Redo
Undo::Stack UndoStack;
};
// Implementation below.
inline bool Image::TypeSupportsProperties() const
{
return
(
(Filetype == tSystem::tFileType::HDR) ||
(Filetype == tSystem::tFileType::EXR)
);
}
}
|
bluescan/tacit-texview
|
Src/Profile.h
|
// Profile.h
//
// The viewer profile enum.
//
// Copyright (c) 2022 <NAME>.
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby
// granted, provided that the above copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
// AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
#pragma once
namespace Viewer
{
enum class Profile
{
Main,
Basic,
NumProfiles
};
const char* GetProfileName(Profile);
const char* GetProfileNameLong(Profile);
extern const char* ProfileNames[int(Profile::NumProfiles)];
extern const char* ProfileNamesLong[int(Profile::NumProfiles)];
}
// Implementation only below.
inline const char* Viewer::GetProfileName(Profile profile)
{
return ProfileNames[int(profile)];
}
inline const char* Viewer::GetProfileNameLong(Profile profile)
{
return ProfileNamesLong[int(profile)];
}
|
bluescan/tacit-texview
|
Src/Version.cmake.h
|
<reponame>bluescan/tacit-texview
#pragma once
#define set(verStr) namespace ViewerVersion { extern int Major, Minor, Revision; struct Parser { Parser(const char*); }; static Parser parser(#verStr); }
set("VIEWER_VERSION" "1.0.27")
#undef set
|
bluescan/tacit-texview
|
Src/FileDialog.h
|
<gh_stars>10-100
// FileDialog.h
//
// Dialog that allows selection of a file or directory. May be used for opening a file/directory or saving to a file.
//
// Copyright (c) 2021, 2022 <NAME>.
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby
// granted, provided that the above copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
// AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
#pragma once
#include <Foundation/tString.h>
#include <System/tFile.h>
// This seems like a reasonable namespace for all generic ImGui widgets and dialogs that may eventually find a home
// outside this viewer app.
namespace tInterface
{
struct ContentItem;
class TreeNode;
// You can use multiple instances or repurpose the same one.
class FileDialog
{
public:
enum class DialogMode
{
OpenFile,
OpenFiles,
OpenDir,
SaveFile
};
// In OpenDir dialog mode the file-types are ignored. If file-types is empty (default) then all types are used.
FileDialog(DialogMode, const tSystem::tFileTypes& = tSystem::tFileTypes());
// Call when you want the modal dialog to open.
void OpenPopup();
enum class DialogResult
{
Open, // Modal is currently open.
Closed, // Modal is currently not open.
OK, // Call GetResult to see what the user selected.
Cancel
};
DialogResult DoPopup(); // Call every frame and observe result.
tString GetResult();
private:
tString GetSelectedDir();
void DoSelectable(ContentItem*);
void PopulateBookmarks();
void PopulateLocal();
#ifdef PLATFORM_WINDOWS
void PopulateNetwork();
#endif
// Needed in cases where we need a reload of content. For example, when changing filetype filters.
void InvalidateAllNodeContent();
void InvalidateAllNodeContentRecursive(TreeNode*);
void TreeNodeRecursive(TreeNode*);
void TreeNodeFlat(TreeNode*);
#ifdef PLATFORM_WINDOWS
void RequestNetworkSharesThread();
void ProcessShareResults();
tSystem::tNetworkShareResult NetworkShareResults;
bool ProcessingNetworkPath = false;
#endif
DialogMode Mode;
tSystem::tFileTypes FileTypes;
tString Result;
TreeNode* BookmarkTreeNode;
TreeNode* LocalTreeNode;
#ifdef PLATFORM_WINDOWS
TreeNode* NetworkTreeNode;
#endif
TreeNode* SelectedNode = nullptr;
};
}
|
bluescan/tacit-texview
|
Src/Config.h
|
// Config.h
//
// Viewer settings stored as human-readable symbolic expressions.
//
// Copyright (c) 2019, 2020, 2021, 2022 <NAME>.
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby
// granted, provided that the above copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
// AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
#pragma once
#include <Foundation/tString.h>
#include <Math/tColour.h>
#include <System/tScript.h>
#include "InputBindings.h"
namespace Viewer { namespace Config {
enum Category
{
Category_None,
Category_Unspecified = 1 << 0, // Everything that's not in a category below.
Category_Display = 1 << 1, // Includes background and aspect settings.
Category_Slideshow = 1 << 2,
Category_System = 1 << 3,
Category_Interface = 1 << 4,
Category_Bindings = 1 << 5, // Key bindings.
Category_All = 0xFFFFFFFF,
Category_AllNoBindings = Category_All & ~Category_Bindings
};
// The settings struct represents a single set of all configurable parameters.
// There can be multiple instances for different profiles. Currently we only have
// two profiles: normal and basic.
struct Settings
{
Settings() : Profile(), InputBindings() { Reset(Profile::Main, Category_All); }
tString Profile;
int WindowX;
int WindowY;
int WindowW;
int WindowH;
bool ShowMenuBar;
bool ShowNavBar;
bool ShowImageDetails;
bool ShowPixelEditor;
bool ShowChannelFilter;
bool ShowFrameScrubber;
bool ContentViewShow;
float ThumbnailWidth;
enum class SortKeyEnum
{
FileName,
FileModTime,
FileSize,
FileType,
ImageArea,
ImageWidth,
ImageHeight
};
int SortKey; // Matches SortKeyEnum values.
bool SortAscending; // Sort direction.
int OverlayCorner;
bool Tile;
enum class BGStyle
{
None,
Checkerboard,
SolidColour,
NumStyles
};
int BackgroundStyle;
tColouri BackgroundColour; // Only used if BGStyle is SolidColour.
bool BackgroundExtend; // Extend background past image bounds.
bool TransparentWorkArea;
bool FixedAspectWorkArea;
int ResampleFilter; // Matches tImage::tResampleFilter.
int ResampleEdgeMode; // Matches tImage::tResampleEdgeMode.
int ResampleFilterRotateUp; // Matches tImage::tResampleFilter.
int ResampleFilterRotateDown; // Matches tImage::tResampleFilter.
enum class RotMode
{
Fill,
Crop,
CropResize,
NumModes
};
int RotateMode;
enum class ZoomMode
{
User,
Fit,
DownscaleOnly,
OneToOne,
NumModes
};
int DefaultZoomMode; // Zoom mode to use when opening a new image. User means don't change modes.
bool ConfirmDeletes;
bool ConfirmFileOverwrites;
bool SlideshowLooping;
bool SlideshowProgressArc;
double SlideshowPeriod;
tString SaveSubFolder;
int SaveFileType;
int SaveFileTypeMultiFrame;
bool SaveFileTargaRLE;
int SaveFileJpegQuality; // E [1, 100]
bool SaveFileWebpLossy;
float SaveFileWebpQualComp; // E [0.0, 100.0]
bool SaveFileTiffZLibDeflate;
int SaveFileWebpDurOverride; // E [-1, inf]. In ms.
int SaveFileGifDurOverride; // E [-1, inf]. In 1/100 seconds.
int SaveFileApngDurOverride; // E [-1, 65535]. In ms.
int SaveFileTiffDurOverride; // E [-1, inf]. In ms.
int SaveFileWebpDurMultiFrame; // E [0, inf]. In ms.
int SaveFileGifDurMultiFrame; // E [0, inf]. In 1/100 seconds.
int SaveFileApngDurMultiFrame; // E [0, 65536]. In ms.
int SaveFileTiffDurMultiFrame; // E [0, inf]. In ms.
enum class SizeMode
{
Percent,
SetWidthAndHeight,
SetWidthRetainAspect,
SetHeightRetainAspect
};
int SaveAllSizeMode;
int CropAnchor; // E [-1, 9] with 4 being the default (middle), 0 being top-left, and -1 being 'cursor position'.
tColouri FillColour;
int ResizeAspectNum;
int ResizeAspectDen;
int ResizeAspectMode; // 0 = Crop Mode. 1 = Letterbox Mode.
int MaxImageMemMB; // Max image mem before unloading images.
int MaxCacheFiles; // Max number of cache files before removing oldest.
int MaxUndoSteps;
bool StrictLoading; // No attempt to display ill-formed images.
bool DetectAPNGInsidePNG; // Look for APNG data (animated) hidden inside a regular PNG file.
int MipmapFilter; // Matches tImage::tResampleFilter. Use None for no mipmaps.
bool MipmapChaining; // True for faster mipmap generation. False for a lot slower and slightly better results.
bool AutoPropertyWindow; // Auto display property editor window for supported file types.
bool AutoPlayAnimatedImages; // Automatically play animated gifs, apngs, and WebPs.
float MonitorGamma; // Used when displaying HDR formats to do gamma correction.
Viewer::Bindings::InputMap InputBindings; // Each Settings struct (profile) gets its own copy of the InputMap (key bindings).
void Load(tExpression);
bool Save(tScriptWriter&);
// Yes, this struct only represents a single profile, but the defaults are different
// depending on which profile is chosen, so we need to pass it in.
void Reset(Viewer::Profile, uint32 categories);
};
struct GlobalSettings
{
GlobalSettings() { Clear(); }
int ConfigVersion;
int CurrentProfile;
void Save(tScriptWriter&);
void Load(tExpression);
void Reset();
void Clear() { ConfigVersion = -1; CurrentProfile = int(Profile::Main); }
};
// Loads the global settings and all profile settings from a single file.
void Load(const tString& filename);
// Saves the global settings and all profile settings in a single file.
void Save(const tString& filename);
// These apply to the current profile.
void SetProfile(Profile);
Profile GetProfile();
const char* GetProfileName();
// Current profile reset. If category is 'All' it resets all categories plus stuff not in a category.
void ResetProfile(uint32 categories);
// Resets all profiles, but only the categories specified.
void ResetAllProfiles(uint32 categories);
// All profiles reset. Resets everything. Calls ResetAllProfiles with All as the category.
void ResetAll();
extern Settings* Current;
extern Settings MainSettings;
extern Settings BasicSettings;
} }
|
iFindTA/NHKeyboardPro
|
NHKeyboardPro/KeyBoard/NHKeyboard.h
|
//
// NHKeyboard.h
// NHKeyboardPro
//
// Created by <NAME> on 16/3/15.
// Copyright © 2016年 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
typedef enum{
NHKBTypeNumberPad = 1 << 0,
NHKBTypeDecimalPad = 1 << 1,
NHKBTypeASCIICapable = 1 << 2
}NHKBType;
/*!
* @brief Dependency:Masonry framework
*/
@interface NHKeyboard : UIView
/*!
* @brief create safe keyboard
*
* @param type kb's type
*
* @return the kb's instance
*/
+ (nonnull instancetype)keyboardWithType:(NHKBType)type;
/*!
* @brief kb's icon logo to show user
*/
@property (nullable, nonatomic, copy) NSString *icon;
/*!
* @brief kb's title to show user
*/
@property (nonatomic, nullable, copy) NSString *enterprise;
/*!
* @brief such as UITextField,UITextView,UISearchBar
*/
@property (nonatomic, nullable, strong) UIView *inputSource;
@end
|
Goallying/MQTT
|
AppDelegate.h
|
//
// AppDelegate.h
// MQTT
//
// Created by Lifee on 2019/12/23.
// Copyright © 2019 Lifee. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@end
|
Goallying/MQTT
|
ViewController.h
|
//
// ViewController.h
// MQTT
//
// Created by Lifee on 2019/12/23.
// Copyright © 2019 Lifee. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
|
HassanElDesouky/OperationQueueLeak
|
OperationQueueLeak/OperationQueueLeak/InternalService.h
|
//
// InternalService.h
// OperationQueueLeak
//
// Created by <NAME> on 21/10/2021.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@class CoreDataLayer;
@interface InternalService : NSObject
- (instancetype)initWithCoreDataLayer:(CoreDataLayer *)coreDataLayer;
@end
NS_ASSUME_NONNULL_END
|
HassanElDesouky/OperationQueueLeak
|
OperationQueueLeak/OperationQueueLeak/OperationQueueLeak-Bridging-Header.h
|
//
// Use this file to import your target's public headers that you would like to expose to Swift.
//
#import "InternalService.h"
#import "CoreDataLayer.h"
|
HassanElDesouky/OperationQueueLeak
|
OperationQueueLeak/OperationQueueLeak/CoreDataLayer.h
|
//
// CoreDataLayer.h
// OperationQueueLeak
//
// Created by <NAME> on 21/10/2021.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface CoreDataLayer : NSObject
@property (atomic, strong) NSOperationQueue *afterInitializationCoreDataQueue;
@end
NS_ASSUME_NONNULL_END
|
AbdullahAbaza/cs50-progress
|
pset2/readability/readability2.c
|
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
int index(string text);
int main(void)
{
string text = get_string("Text: ");
int grade = index(text);
//printing Grade
if (grade < 1)
{
printf("Before Grade 1\n");
}
else if (grade >= 16)
{
printf("Grade 16+\n");
}
else
{
printf("Grade %i\n", grade);
}
}
int index(string text)
{
//store letters, words and sentences as a float
int l, w, s;
l = s = 0, w = 1;
// calculate letters, words and sentences
for (int i = 0, n = strlen(text); i < n; i++)
{
// calculate letters
if (isalpha(text[i]))
{
l++;
}
// calculate words
else if (isblank(text[i]))
// if (( text[i] == 0 && text[i] == ' ') || ( (text[i] != n -1 && text[i] == ' ' && text[i + 1] != ' '))
{
w++;
}
// calculate sentences
else if (text[i] == '.' || text[i] == '!' || text[i] == '?')
{
s++;
}
}
// calculate L = Letters ÷ Words × 100
float L = ((float)l / (float)w) * 100;
// calculate S = Sentences ÷ Words × 100
float S = ((float)s / (float)w) * 100;
//calculate index = 0.0588 * L - 0.296 * S - 15.8
float I = (0.0588 * L) - (0.296 * S) - 15.8;
float INDEX = roundf(I);
return INDEX;
}
|
AbdullahAbaza/cs50-progress
|
counter.c
|
#include <cs50.h>
#include <stdio.h>
#include <unistd.h>
int main(void)
{
int s;
int m;
do
{
s = get_int("starting number: ");
m = get_int("the maximum number to count to: ");
}
while (s >= m || s < 0);
for (int i = s ; m >= i; i++)
{
printf("%i\n", i);
sleep(1);
}
}
|
AbdullahAbaza/cs50-progress
|
condetions.c
|
#include <stdio.h>
#include <cs50.h>
#include <unistd.h>
int main(void)
{
int x = get_int("x == ");
int y = get_int("y == ");
if (x < y)
{
printf("x is less than y\n");
}
else if (x > y)
{
printf("x is greater than y\n");
}
else
{
printf("x is equal to y\n");
}
int i = 0;
while (i < 10)
{
printf("i is less than 10\n");
sleep(1);
i++;
}
for (int l = 0; l < 10; l++)
{
printf("this is a for loop\n");
sleep(1);
}
}
|
AbdullahAbaza/cs50-progress
|
pset2/substitution/substitution1.c
|
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int verify_key(string argv[]);
int main(int argc, string argv[])
{
//terminating the program if the key is not valid
string key = argv[1];
if (argc != 2 || verify_key(argv) == 1)
{
printf("Usage: ./substitution key\n");
return 1;
}
else if (strlen(key) != 26)
{
printf("Key must contain 26 characters.\nand there mustn't be any duplicate characters.\n");
return 1;
}
string P = get_string("plaintext: ");
printf("\nciphertext: ");
for (int i = 0; i < strlen(P);)
{
if (isupper(P[i]) || isspace(P[i]) || ispunct(P[i]) || isdigit(P[i]))
{
for (int j = 65, A = 0; j < 91; j++, A++)
{
if (P[i] == j)
{
P[i] = toupper(key[A]);
printf("%c", P[i]);
i++;
}
else if (isspace(P[i]) || ispunct(P[i]) || isdigit(P[i]))
{
printf("%c", P[i]);
i++;
}
}
}
else if (islower(P[i]) || isspace(P[i]) || ispunct(P[i]) || isdigit(P[i]))
{
for (int x = 97, a = 0; x < 123; x++, a++)
{
if (P[i] == x)
{
P[i] = tolower(key[a]);
printf("%c", P[i]);
i++;
}
else if (isspace(P[i]) || ispunct(P[i]) || isdigit(P[i]))
{
printf("%c", P[i]);
i++;
}
}
}
}
printf("\n");
}
//checking the validity of the key
int verify_key(string argv[])
{
int ver = 0;
string key = argv[1];
for (int i = 0, n = strlen(key); i < n; i++)
{
//handling invalid characters in key
if (! isalpha(key[i]))
{
return ver = 1;
}
//handling duplicate characters in key
for (int j = i + 1; j < n; j++)
{
if (key[i] == key[j])
{
return ver = 1;
}
}
}
return ver;
}
|
AbdullahAbaza/cs50-progress
|
pset2/substitution/substitution.c
|
<reponame>AbdullahAbaza/cs50-progress<filename>pset2/substitution/substitution.c
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
bool verify_key(string key);
int main(int argc, string argv[])
{
//terminating the program if the key is not valid
string key = argv[1];
if (argc != 2)
{
printf("Usage: ./substitution key\n");
return 1;
}
else if (! verify_key(key))
{
printf("Key must contain 26 characters.\nand there mustn't be any duplicate characters.\n");
return 1;
}
// prompting the user for the plaintext
string P = get_string("plaintext: ");
printf("\nciphertext: ");
for (int i = 0; i < strlen(P);)
{
if (isupper(P[i]) || isspace(P[i]) || ispunct(P[i]) || isdigit(P[i]))
{
for (int j = 65, A = 0; j < 91; j++, A++)
{
if (P[i] == j)
{
P[i] = toupper(key[A]);
printf("%c", P[i]);
i++;
}
else if (isspace(P[i]) || ispunct(P[i]) || isdigit(P[i]))
{
printf("%c", P[i]);
i++;
}
}
}
else if (islower(P[i]) || isspace(P[i]) || ispunct(P[i]) || isdigit(P[i]))
{
for (int x = 97, a = 0; x < 123; x++, a++)
{
if (P[i] == x)
{
P[i] = tolower(key[a]);
printf("%c", P[i]);
i++;
}
else if (isspace(P[i]) || ispunct(P[i]) || isdigit(P[i]))
{
printf("%c", P[i]);
i++;
}
}
}
}
printf("\n");
}
//checking the validity of the key
bool verify_key(string key)
{
int len = strlen(key);
if (len != 26)
{
return false;
}
for (int i = 0; i < len; i++)
{
//handling invalid characters in key
if (! isalpha(key[i]))
{
return false;
}
//handling duplicate characters in key
for (int j = i + 1; j < len; j++)
{
if (key[i] == key[j])
{
return false;
}
}
}
return true;
}
|
AbdullahAbaza/cs50-progress
|
pset1/cash/cash2.c
|
//Greedy Algorithms
#include <stdio.h>
#include <cs50.h>
#include <math.h>
float change(void);
int main(void)
{
float n = change();
int cents = round(n * 100);
int coins = 0;
int denominations[] = {25, 10, 5, 1};
int size = sizeof(denominations)/sizeof(int);
for (int i = 0; i < size; i++)
{
coins += cents / denominations[i];
cents %= denominations[i];
}
printf("%i\n", coins);
}
float change(void)
{
float n;
do
{
n = get_float("Change owed: ");
}
while (n < 0);
return n;
}
/*while (number > 0)
{
int digit = number%10;
number /= 10;
printf("%i\n", digit);
}
/*
|
AbdullahAbaza/cs50-progress
|
pset1/cash/cash.c
|
//Greedy Algorithms
#include <stdio.h>
#include <cs50.h>
#include <math.h>
float change(void);
int main(void)
{
float n = change();
//round cents to the nearest penny
int cents = round(n * 100);
int coins = 0;
int quarters = 0;
int dimes = 0;
int nickels = 0;
int pennies = 0;
//starting loops to subtract cents and add 1 to coins for every subtarction
for (int i = 0; cents >= 25; i++)
{
cents = cents - 25;
coins++;
quarters++;
}
for (int j = 0; cents >= 10; j++)
{
cents = cents - 10;
coins++;
dimes++;
}
for (int x = 0; cents >= 5; x++)
{
cents = cents - 5;
coins++;
nickels++;
}
for (int y = 0; cents >= 1; y++)
{
cents = cents - 1;
coins++;
pennies++;
}
//print num of coins
printf("number of coins you should give to the customer: %i\n", coins);
//print how many quarters, dimes, nickels, pennies
printf("%i quarters.\n%i dimes.\n%i nickels.\n%i pennies.\n", quarters, dimes, nickels, pennies);
}
//prompt the user for change
float change(void)
{
float n;
do
{
n = get_float("Change owed: ");
}
while (n < 0.001);
return n;
}
/*we can use while loops for simplicity*/
|
AbdullahAbaza/cs50-progress
|
pset2/readability/readability.c
|
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
int count_letters(string text);
int count_words(string text);
int count_sentences(string text);
int index(string text);
int main(void)
{
string text = get_string("Text: ");
int grade = index(text);
//printing Grade
if (grade < 1)
{
printf("Before Grade 1\n");
}
else if (grade >= 16)
{
printf("Grade 16+\n");
}
else
{
printf("Grade %i\n", grade);
}
}
// calculate letters
int count_letters(string text)
{
int L = 0;
for (int i = 0, n = strlen(text); i < n; i++)
{
if (islower(text[i]) || isupper(text[i]))
{
L++;
}
}
return L;
}
// calculate words
int count_words(string text)
{
int W = 1;
for (int i = 0, n = strlen(text); i < n; i++)
{
if (isblank(text[i]))
{
W++;
}
}
return W;
}
// calculate sentences
int count_sentences(string text)
{
int S = 0;
for (int i = 0, n = strlen(text); i < n; i++)
{
if (text[i] == '.' || text[i] == '!' || text[i] == '?')
{
S++;
}
}
return S;
}
int index(string text)
{
//store letters, words and sentences as a float
float l = count_letters(text);
float w = count_words(text);
float s = count_sentences(text);
// calculate L = Letters ÷ Words × 100
float L = (l / w) * 100;
// calculate S = Sentences ÷ Words × 100
float S = (s / w) * 100;
//calculate index = 0.0588 * L - 0.296 * S - 15.8
float I = (0.0588 * L) - (0.296 * S) - 15.8;
float INDEX = roundf(I);
return INDEX;
}
|
AbdullahAbaza/cs50-progress
|
pset1/mario/mario.c
|
#include <cs50.h>
#include <stdio.h>
void print(char c, int n);
int main(void)
{
int n;
do
{
// prompt user for input
n = get_int("Hieght: ");
}
while (n < 1 || n > 8);
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (i + j < n - 1)
printf(" ");
else
printf("#");
}
printf(" ");
print('#', i + 1);
printf("\n");
}
}
void print(char c, int n)
{
for (int x = 0; x < n; x++)
{
printf("%c", c);
}
}
|
AbdullahAbaza/cs50-progress
|
pset2/caesar/caesar2.c
|
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
bool verify_digit(string key);
int main(int argc, string argv[])
{
//Check that program was run with one command-line argument
while (argc != 2 || ! verify_digit(argv[1]))
{
printf("Usage: ./caesar key\n");
return 1;
}
//Convert argv[1] from a string to an int
int K = atoi(argv[1]);
//Prompt user for plaintext
string P = get_string("plaintext: ");
printf("\nciphertext: ");
//ci = (pi + k) % 26
//pi is the ith character in p
// k is a secret key a non-negative integer
//each letter, ci, in the ciphertext, c
for (int i = 0, n = strlen(P); i < n; i++)
{
if (isupper(P[i]))
{
P[i] = (((P[i] - 'A') + K) % 26 + 'A');
printf("%c", P[i]);
}
else if (islower(P[i]))
{
P[i] = (((P[i] - 'a') + K) % 26 + 'a');
printf("%c", P[i]);
}
else
{
printf("%c", P[i]);
}
}
printf("\n\nNote: If you want to decipher your text just substitute your key from 26 and use the result as the decipher key.\n");
}
//Iterate over the provided argument to make sure all characters are digits
bool verify_digit(string key)
{
for (int i = 0, n = strlen(key); i < n; i++)
{
if (! isdigit(key[i]))
{
return false;
}
}
return true;
}
|
AbdullahAbaza/cs50-progress
|
pset1/credit/credit.c
|
#include <stdio.h>
#include <cs50.h>
bool check_validity(long number);
int find_length(long number);
bool checksum(long number);
void print_brand(long number);
int main(void)
{
long number;
do
{
number = get_long("Number: ");
}
while (number < 0);
if (check_validity(number) == true)
{
print_brand(number);
}
else
{
printf("INVALID\n");
}
}
bool check_validity(long number)
{
int len = find_length(number);
return (len == 13 || len == 15 || len == 16) && checksum(number);
}
int find_length(long number)
{
int len;
for (len = 0; number != 0; len++)
{
number /= 10;
}
return len;
}
bool checksum(long number)
{
int sum = 0;
for (int i = 0; number != 0; i++, number /= 10)
{
if (i % 2 == 0)
{
sum += number % 10;
}
else
{
int digit = (number % 10) * 2;
sum += digit / 10 + digit % 10;
}
}
return (sum % 10) == 0;
}
//brand function takes the credit card number and checks for the brand
void print_brand(long number)
{
if ((number >= 34e13 && number < 35e13) || (number >= 37e13 && number < 38e13))
{
printf("AMEX\n");
}
else if (number >= 51e14 && number < 56e14)
{
printf("MASTERCARD\n");
}
else if ((number >= 4e15 && number < 5e15) || (number >= 4e12 && number < 5e12))
{
printf("VISA\n");
}
else
{
printf("INVALID\n");
}
}
|
AbdullahAbaza/cs50-progress
|
credit.c
|
#include <stdio.h>
#include <cs50.h>
// recall functions
bool check_validity(long number);
int find_length(long number);
bool checksum(long number);
void print_brand(long number);
int main(void)
{
// prompting the user for input
long number;
do
{
number = get_long("Number: ");
}
while (number < 0);
// printing the brand if the check validity function returns true, if not printing invalid
if (check_validity(number) == true)
{
print_brand(number);
}
else
{
printf("INVALID\n");
}
}
/* checking the validity of the card by comparing the credit number's length to the standard length
and making sure that the checksum function returns true at the same time */
bool check_validity(long number)
{
int len = find_length(number);
return (len == 13 || len == 15 || len == 16) && checksum(number);
}
// finding the length of the input card number
int find_length(long number)
{
// deviding the card number by 10 and adding 1 to the variable len for each time untill the number becomes 0
int len;
for (len = 0; number != 0; len++)
{
number /= 10;
}
return len;
}
// calculating the checksum
bool checksum(long number)
{
/* initiating the variable len as an int and assigning it to 0 the starting a for loop that
initiates a variable i that starts from 0 and add 1 to it every time the card number is
devided by 10 */
int sum = 0;
for (int i = 0; number != 0; i++, number /= 10)
{
if (i % 2 == 0)
{
sum += number % 10;
}
/* making sure that every other number from the seconed to the last digit when multiplied
by 2 the and the result is a 2 digit number to split them and add them then add the result to the sum variable */
else
{
int digit = (number % 10) * 2;
sum += digit / 10 + digit % 10;
}
}
return (sum % 10) == 0;
}
//brand function takes the credit card number and checks for the brand
void print_brand(long number)
{
// the (e+number) refers to how many zeros after the number befor e
if ((number >= 34e13 && number < 35e13) || (number >= 37e13 && number < 38e13))
{
printf("AMEX\n");
}
else if (number >= 51e14 && number < 56e14)
{
printf("MASTERCARD\n");
}
else if ((number >= 4e15 && number < 5e15) || (number >= 4e12 && number < 5e12))
{
printf("VISA\n");
}
else
{
printf("INVALID\n");
}
}
|
moj3ve/DarkKeysReborn
|
DarkKeys.h
|
<gh_stars>1-10
bool enabled;
bool darkkeys;
bool nocaps;
bool nolight;
bool nlm;
@interface UIKeyboard : UIView
@end
@interface UIKeyboardDockView : UIView
@end
@interface UIKeyboardLayoutStar : UIView
@end
@interface UIKBKeyView : UIView
@end
@interface UIUserInterfaceStyleArbiter : NSObject
+ (id) sharedInstance;
- (long long) currentStyle;
@end
|
RahulM98/Language-Dictionary
|
Dictionary.c
|
<reponame>RahulM98/Language-Dictionary
//The Dictionary Program
//Password required for some purposes
//The Password is "<PASSWORD>..."
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#include<conio.h>
#define w_size 25
#define m_size 250
char word_list[100];
int cursor_pos = 0;
struct Tree
{
char arr[w_size];
char meaning[m_size];
struct Tree *left;
struct Tree *right;
};
struct Tree *get_node(char word[],char meaning[])
{
struct Tree *new_node = (struct Tree *)malloc(sizeof(struct Tree));
strcpy(new_node->arr,word);
strcpy(new_node->meaning,meaning);
new_node->left = new_node->right = NULL;
return new_node;
}
struct Tree *insert(struct Tree *root,char word[],char meaning[]) // Inserting into Binary Search Tree
{
if(root == NULL)
{
root = get_node(word,meaning);
}
else
{
if(strcmp(root->arr,word) < 0) //if(compare < 0) // if Lexicographically " WORD " comes later
{
root->right = insert(root->right,word,meaning);
}
else
{
root->left = insert(root->left,word,meaning);
}
}
return root;
}
struct Tree *smallest_ascii(struct Tree *root) // Finding the word of smallest ASCII value, required to delete from Binary Search Tree
{
while(root->left != NULL)
root = root->left;
return root;
}
struct Tree *Delete(struct Tree *root,char word[]) // Deleting the word from Binary Search Tree
{
struct Tree *store;
if(strcmp(root->arr,word) < 0)
root->right = Delete(root->right,word);
else if(strcmp(root->arr,word) > 0)
root->left = Delete(root->left,word);
else
{
if(root->left == NULL && root->right == NULL)
{
free(root);
root = NULL;
}
else if(root->left == NULL)
{
free(root);
root = root->right;
}
else if(root->right == NULL)
{
free(root);
root = root->left;
}
else
{
store = smallest_ascii(root->right);
strcpy(root->arr,store->arr);
strcpy(root->meaning,store->meaning);
free(store);
store = NULL;
}
}
return root;
}
int search(struct Tree *root,char word[]) // Searching of a word in Dictionary is done through searching in Binary Search Tree
{
if(root == NULL)
return 0;
else if(strcmp(root->arr,word) == 0)
return 1;
else if(strcmp(root->arr,word) < 0)
return search(root->right,word);
else
return search(root->left,word);
}
void FILE_input(char array[],char m_array[]) // taking input from FILE
{ // Taking only 1st word from each line
char s;
int i = 0;
FILE *fp;
fp = fopen("Dictionary_2.0.txt","r");
fseek(fp,cursor_pos,0);
s = fgetc(fp);
while((s != '~') && (s != EOF) && (i != w_size))
{
array[i] = s;
i++;
s = fgetc(fp);
}
if(i != w_size)
array[i] = '\0';
i = 0;
s = fgetc(fp);
while((s != '\n') && (s != EOF) && (i != m_size))
{
m_array[i] = s;
i++;
s = fgetc(fp);
}
if(i != m_size)
m_array[i] = '\0';
cursor_pos = ftell(fp) - 1;
fclose(fp);
}
struct Tree *load_BST(struct Tree *root) // Loading all the words from file in Binary Search Tree
{
FILE *fp;
char temp[w_size];
char m_temp[m_size];
int c;
fp = fopen("Dictionary_2.0.txt","r");
c = fgetc(fp);
cursor_pos = ftell(fp);
while(c != EOF)
{
if(c == '\n')
{
FILE_input(temp,m_temp); //////////////// ??????????? ////////////////////////
root = insert(root,temp,m_temp);
}
fseek(fp,cursor_pos,0);
c = fgetc(fp);
cursor_pos = ftell(fp);
}
fclose(fp);
return root;
}
void display(struct Tree *root)
{
if(root != NULL)
{
display(root->left);
printf("%s = %s\n",root->arr,root->meaning);
display(root->right);
}
}
void file_insert(char word[],char word_user[],char meaning[]) // Inserting the meaning with corresponding word in File
{
FILE *fp;
fp = fopen("Dictionary_2.0.txt","a"); // Only adding string, so 'a'
fprintf(fp,"\n");
fprintf(fp,word);
fputc('~',fp);
fputs(meaning,fp);
fclose(fp);
}
void find_meaning(struct Tree *root,char word[]) // Finding from BST
{
if(root == NULL)
return;
else if(strcmp(root->arr,word) == 0)
printf("\nThe meaning is : %s",root->meaning);
else if(strcmp(root->arr,word) < 0)
find_meaning(root->right,word);
else
find_meaning(root->left,word);
}
int line_number(char word[]) // Reading the line number of the given WORD from file
{
int c,line=0;
char words[w_size],m[m_size];
FILE *fp;
fp = fopen("Dictionary_2.0.txt","r");
while((c=fgetc(fp)) != EOF)
{
if(c == '\n')
{
line++;
FILE_input(words,m);
if((strcmp(word,words)) == 0)
break;
}
}
fclose(fp);
return line;
}
void del_from_file(char word[]) // Deleting from file
{
FILE *fp1,*fp2;
int c,line,count=0;
line = line_number(word);
fp1 = fopen("Dictionary_2.0.txt","r");
fp2 = fopen("Temporary.txt","w");
while((c=fgetc(fp1)) != EOF)
{
if(c == '\n')
{
count++;
}
if(count != line)
{
fputc(c,fp2);
}
}
fclose(fp1);
fclose(fp2);
remove("Dictionary_2.0.txt");
rename("Temporary.txt","Dictionary_2.0.txt");
}
void arrange_words_in_FILE(struct Tree *root)
{
if(root != NULL)
{
arrange_words_in_FILE(root->left);
FILE *fp;
fp = fopen("arrange.txt","a");
fprintf(fp,"\n%s",root->arr);
fclose(fp);
arrange_words_in_FILE(root->right);
}
}
void send_words_from_FILE(int n,char word[]) // Sends the similar words from the FILE where words are arranged
{ // LEXICOGRAPHICALLY, for word suggestion
int i,len,c,count = 0,max_word_count = 0;
int x;
char s;
char new_word[w_size];
FILE *fp;
fp = fopen("arrange.txt","r");
strupr(word);
word_list[0] = '\0';
s = fgetc(fp);
if(n == 0)
{
return;
}
while(s != EOF)
{
if(s == '\n')
{
i = 0;
while((s=fgetc(fp)) != '\n')
{
new_word[i] = s;
i++;
}
new_word[i] = '\0';
c = 0;
for(i=0;i<n;i++)
{
if(word[i] == new_word[i])
c++;
}
if(c == n)
{
max_word_count = max_word_count + 1;
len = strlen(new_word);
for(i=0;i<len;i++)
{
word_list[count] = new_word[i];
count++;
}
word_list[count] = ',';
count++;
}
}
new_word[n] = '\0';
if((max_word_count == 4) || (strcmp(word,new_word) < 0)) // Sends maximum 5 similar words
{
break;
}
}
word_list[count-1] = '\0';
fclose(fp);
}
void user_input(struct Tree *root,char array[],int size,char array_user[])
{
int ch,i;
FILE *fp;
fp = fopen("arrange.txt","w");
fclose(fp);
arrange_words_in_FILE(root);
for(i=0;i<size;i++)
{
ch = getch();
printf("\r ");
if(ch == 8) // For Backspace key
{
array[i-1] = '\0';
array_user[i-1] = '\0';
send_words_from_FILE(i-1,array);
printf("\rEnter word :%s %s",array_user,word_list);
i = i-2;
}
else if(ch == 13) // For Enter key
{
array[i] = '\0';
array_user[i] = '\0';
printf("\rEnter word :%s",array_user);
break;
}
else if(ch == 32) // For Space Bar key
{
if(i==0 || isspace(array[i-1]))
i = i-1;
else
{
array[i] = ch;
array_user[i] = ch;
array[i+1] = '\0';
array_user[i+1] = '\0';
}
printf("\rEnter word :%s %s",array_user,word_list);
}
else if((ch >= 91 && ch <= 96) || (ch >= 123 && ch <= 126))
{
array[i] = ch;
array_user[i] = ch;
array[i+1] = '\0';
array_user[i+1] = '\0';
if(ch == 95)
{
send_words_from_FILE(i+1,array);
}
printf("\rEnter word :%s %s",array_user,word_list);
}
else // For a valid character
{
array[i] = ch;
array_user[i] = ch;
array[i+1] = '\0';
array_user[i+1] = '\0';
send_words_from_FILE(i+1,array);
printf("\rEnter word :%s %s",array_user,word_list);
}
if(i < 0)
{
i = -1;
printf("\r ");
printf("\rEnter word :");
}
}
remove("arrange.txt");
}
int password()
{
int i,j,ch;
char password[12];
printf("Enter the password (maximum 10 characters) : ");
for(i=0;i<10;i++)
{
ch = getch();
if(ch == 8)
{
i = i-2;
printf("\r ");
printf("\rEnter the password (maximum 10 characters) : ");
for(j=0;j<=i;j++)
printf("*");
}
else if(ch == 13)
break;
else
{
password[i] = ch;
printf("*");
}
if(i < 0)
{
printf("\r ");
printf("\rEnter the password (maximum 10 characters) : ");
i = -1;
}
}
password[i] = '\0';
if((strcmp(password,"<PASSWORD>...")) == 0)
return 1;
else
return 0;
}
main()
{
struct Tree *root=NULL;
int ch;
int s;
char word[w_size],word_user[w_size];
word_list[0] = '\0';
root = load_BST(root); // First of all loading all the words from file in Binary Search Tree
printf("\n\t\t\t\tThe DICTIONARY\n\t\t\t\t\t--- By <NAME>\n\n");
printf("\t----------------------------------------------------------------\n");
printf("\t* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * \n");
printf("\t----------------------------------------------------------------\n\n");
printf("Welcome to the program \" The Dictionary \"");
printf("\nPlease let me know, what do you want to do with me by pressing the numbers from the MENU...\n");
while(ch != '5')
{
printf("\n\n\t-------- Program MENU --------\n\n");
printf("Press 1 To search a word's meaning\n\t2 To add a word\n\t3 To delete a word\n\t4 To edit a word's meaning\n\t5 To Exit\n\n\n");
printf("Enter your choice : ");
fflush(stdin);
ch = getchar();
switch(ch)
{
case '1':
printf("Enter word :");
user_input(root,word,24,word_user);
if(search(root,word) == 0)
{
printf("\nEntered word is not listed in Dictionary.\n\t--Do you want to add this word ?");
s = 0;
do
{
printf("\n\t--Press Y for YES or N for NO : ");
while((getchar()) != '\n');
s = getchar();
if(s == 'Y' || s == 'y')
{
if(password() == 1)
{
printf("\n\tAccess granted...\n\n");
char meaning[m_size];
printf("\nEnter the meaning of %s : ",word_user);
while((getchar()) != '\n');
gets(meaning);
root = insert(root,word,meaning);
file_insert(word,word_user,meaning);
printf("\n \" %s \" is added to the Dictionary.",word_user);
}
else
printf("\n\tIncorrect password.\n\tAccess denied...");
break;
}
else if(s == 'N' || s == 'n')
printf("\n \" %s \" is not added in dictionary.\n\n",word_user);
}while(s != 'N' && s != 'n');
}
else
{
find_meaning(root,word);
}
break;
case '2':
if(password() == 1)
{
printf("\n\tAccess granted...\n\n");
printf("Enter word :");
user_input(root,word,24,word_user);
if(search(root,word) == 0)
{
char meaning[m_size];
printf("\nEnter the meaning of %s : ",word_user);
while((getchar()) != '\n');
gets(meaning);
root = insert(root,word,meaning);
file_insert(word,word_user,meaning);
printf("\n \" %s \" is added to the Dictionary.",word_user);
}
else
printf("\n\"%s\" alrady exists in Dictionary.\n",word_user);
}
else
printf("\n\tIncorrect password.\n\tAccess denied...");
break;
case '3':
if(password() == 1)
{
printf("\n\tAccess granted...\n\n");
printf("Enter word :");
user_input(root,word,24,word_user);
if(search(root,word) == 0)
printf("Entered word is not listed in Dictionary.\n\n");
else
{
printf("\n\nThe word will be deleted permanently from the Dictionary.\n\n\tDo you want to delete this word ?");
s = -1;
while(s != 'N' && s != 'n')
{
printf("\n\t--Press Y for YES or N for NO : ");
fflush(stdin);
s = getchar();
if(s == 'Y' || s == 'y')
{
root = Delete(root,word);
del_from_file(word);
printf("\" %s \" is deleted from the Dictionary.\n",word_user);
break;
}
else if(s == 'N' || s == 'n')
printf("\" %s \" is not deleted from the Dictionary.\n",word_user);
}
}
}
else
printf("\n\tIncorrect password.\n\tAccess denied...");
break;
case '4':
if(password() == 1)
{
printf("\n\tAccess granted...\n\n");
printf("Enter word :");
user_input(root,word,24,word_user);
if(search(root,word) == 0)
printf("Entered word is not listed in Dictionary.\n\n");
else
{
root = Delete(root,word);
del_from_file(word);
char meaning[m_size];
printf("\nEnter the meaning of %s : ",word_user);
while((getchar()) != '\n');
gets(meaning);
root = insert(root,word,meaning);
file_insert(word,word_user,meaning);
//file_insert(word,word_user);
printf("The meaning of \" %s \" is edited.\n",word_user);
}
}
else
printf("\n\tIncorrect password.\n\tAccess denied...");
break;
case '5':
printf("\nThanks for visiting...\n\tPlease visit again...");
break;
default :
printf("Please press any of the numbers from the MENU\n\n\n");
}
printf("\n\n\n");
}
}
|
VendorSniper/reg
|
Wrapper/Wrapper.h
|
<reponame>VendorSniper/reg
#pragma once
#include "CHECK.h"
#include <itkObject.h>
#include <itkSmartPointer.h>
#include <memory>
#include <type_traits>
#include <typeinfo>
#include <vector>
#include <vtkObject.h>
#include <vtkSmartPointer.h>
namespace reg {
/// \struct AbstractWrapper
/// \brief abstract class for all Wrapper classes
/// \details encapsulates data
/// \param T contained type
/// \param Container container type
/// \note RTTI
template <typename T, typename Container>
struct AbstractWrapper : CHECK<T>,
std::true_type ///< check if Wrapper inherits any
/// specialized WrapperBase structs
{
using self_type = T; ///< for introspection
protected:
AbstractWrapper() { std::cout << typeid(this).name() << std::endl; } ///< RTTI
virtual T *Get() const noexcept = 0;
virtual void Set(T *) noexcept = 0;
virtual void Allocate() noexcept = 0;
Container container_;
};
/// \struct WrapperBase
/// \brief general template of WrapperBase
/// \note not specialized
/// \warning not meant to be selected as Base
template <typename, typename>
struct WrapperBase : std::false_type ///< check if Wrapper inherits any
/// specialized WrapperBase structs
{};
/// \struct WrapperBase
/// \brief specialized template of WrapperBase
/// \details specialized for types in STL
/// \param T contained type
template <typename T>
struct WrapperBase<T, std::unique_ptr<T>>
: AbstractWrapper<T, std::unique_ptr<T>> {
T *Get() const noexcept override;
void Set(T *) noexcept override;
protected:
void Allocate() noexcept override;
};
/// \struct WrapperBase
/// \brief specialized template of WrapperBase
/// \details specialized for types in itk
/// \param T contained type
template <typename T>
struct WrapperBase<T, itk::SmartPointer<T>>
: AbstractWrapper<T, itk::SmartPointer<T>> {
T *Get() const noexcept override;
void Set(T *) noexcept override;
protected:
void Allocate() noexcept override;
};
/// \struct WrapperBase
/// \brief specialized template of WrapperBase
/// \details specialized for types in vtk
/// \param T contained type
template <typename T>
struct WrapperBase<T, vtkSmartPointer<T>>
: AbstractWrapper<T, vtkSmartPointer<T>> {
T *Get() const noexcept override;
void Set(T *) noexcept override;
protected:
void Allocate() noexcept override;
};
/// \struct is_stl
/// \brief general template of is_stl
/// \details check if type is STL
template <typename> struct is_stl : std::false_type {};
/// \struct is_stl
/// \brief specialized template of is_stl
/// \details detects any containers based on std::vector
/// \param T contained type
/// \param Alloc STL specific allocator
template <typename T, typename Alloc>
struct is_stl<std::vector<T, Alloc>> : std::true_type {};
/// \struct is_stl
/// \brief specialized template of is_stl
/// \details detects std::string
template <> struct is_stl<std::string> : std::true_type {};
/// \struct Wrapper
/// \brief interface Wrapper
/// \details chooses which WrapperBase to inherit depending on \p T
/// \warning not optimized for extensibility
/// \note possible future implementation using SFINAE and void_t
/// \param T contained type
template <typename T>
struct Wrapper
: std::conditional<is_stl<T>::value, WrapperBase<T, std::unique_ptr<T>>,
typename std::conditional<
std::is_base_of<itk::Object, T>::value,
WrapperBase<T, itk::SmartPointer<T>>,
typename std::conditional<
std::is_base_of<vtkObject, T>::value,
WrapperBase<T, vtkSmartPointer<T>>,
WrapperBase<void, void>>::type>::type>::type {};
template <typename T>
inline T *WrapperBase<T, std::unique_ptr<T>>::Get() const noexcept {
CHECK<T>::NULLPTR_ERROR(
AbstractWrapper<T, std::unique_ptr<T>>::container_.get(),
"stl type container_ is nullptr");
return AbstractWrapper<T, std::unique_ptr<T>>::container_.get();
}
template <typename T>
inline T *WrapperBase<T, itk::SmartPointer<T>>::Get() const noexcept {
CHECK<T>::NULLPTR_ERROR(
AbstractWrapper<T, itk::SmartPointer<T>>::container_.GetPointer(),
"itk type container_ is nullptr");
return AbstractWrapper<T, itk::SmartPointer<T>>::container_.GetPointer();
}
template <typename T>
inline T *WrapperBase<T, vtkSmartPointer<T>>::Get() const noexcept {
CHECK<T>::NULLPTR_ERROR(
AbstractWrapper<T, vtkSmartPointer<T>>::container_.GetPointer(),
"vtk type container_ is nullptr");
return AbstractWrapper<T, vtkSmartPointer<T>>::container_.GetPointer();
}
template <typename T>
inline void WrapperBase<T, std::unique_ptr<T>>::Set(T *m) noexcept {
CHECK<T>::NULLPTR_NOTE(
AbstractWrapper<T, std::unique_ptr<T>>::container_.get(),
"stl type container_ before set operation is nullptr");
AbstractWrapper<T, std::unique_ptr<T>>::container_.reset(m);
CHECK<T>::NULLPTR_WARNING(
AbstractWrapper<T, std::unique_ptr<T>>::container_.get(),
"stl type container_ set to nullptr");
}
template <typename T>
inline void WrapperBase<T, itk::SmartPointer<T>>::Set(T *m) noexcept {
CHECK<T>::NULLPTR_NOTE(
AbstractWrapper<T, itk::SmartPointer<T>>::container_.GetPointer(),
"itk type container_ before set operation is nullptr");
AbstractWrapper<T, itk::SmartPointer<T>>::container_ = m;
CHECK<T>::NULLPTR_WARNING(
AbstractWrapper<T, itk::SmartPointer<T>>::container_.GetPointer(),
"itk type container_ set to nullptr");
}
template <typename T>
inline void WrapperBase<T, vtkSmartPointer<T>>::Set(T *m) noexcept {
CHECK<T>::NULLPTR_NOTE(
AbstractWrapper<T, vtkSmartPointer<T>>::container_.GetPointer(),
"vtk type container_ before set operation is nullptr");
AbstractWrapper<T, vtkSmartPointer<T>>::container_ = m;
CHECK<T>::NULLPTR_WARNING(
AbstractWrapper<T, vtkSmartPointer<T>>::container_.GetPointer(),
"vtk type container_ set to nullptr");
}
template <typename T>
inline void WrapperBase<T, std::unique_ptr<T>>::Allocate() noexcept {
Set(new T);
}
template <typename T>
inline void WrapperBase<T, itk::SmartPointer<T>>::Allocate() noexcept {
Set(T::New());
}
template <typename T>
inline void WrapperBase<T, vtkSmartPointer<T>>::Allocate() noexcept {
Set(T::New());
}
}
|
VendorSniper/reg
|
CHECK/CHECK.h
|
#pragma once
#include <exception>
#include <iostream>
#include <string>
namespace reg {
/// \struct CHECK
/// \brief error checking class
/// \details avoid exceptions because they cause undefined behavior; rather, use
/// detailed reporting
/// \note every class should directly or indirectly be derived from this class
/// \param T the base type to monitor
template <typename T>
struct CHECK {
protected:
void NULLPTR_ERROR(T *t, std::string &&msg = "NULLPTR_ERROR") const noexcept {
if (t == nullptr)
std::cerr << "Error: " << std::forward<std::string>(msg) << std::endl;
}
void NULLPTR_NOTE(T *t, std::string &&msg = "NULLPTR_NOTE") const noexcept {
if (t == nullptr)
std::cout << "Note: " << std::forward<std::string>(msg) << std::endl;
}
void NULLPTR_WARNING(T *t, std::string &&msg = "NULLPTR_WARNING") const
noexcept {
if (t == nullptr)
std::cerr << "Warning: " << std::forward<std::string>(msg) << std::endl;
}
};
} // namespace reg
|
VendorSniper/reg
|
Reader/Reader.h
|
<reponame>VendorSniper/reg<filename>Reader/Reader.h
#pragma once
#include "Wrapper.h"
#include <itkImage.h>
#include <itkImageFileReader.h>
namespace reg {
/// \struct Reader
/// \brief read an image into itk::Image<double, 3>
/// \note \var Wrapper<std::string> requires a fully qualified file path and extension
struct Reader : Wrapper<itk::Image<double, 3>>,
Wrapper<itk::ImageFileReader<itk::Image<double, 3>>>,
Wrapper<std::string> {
Reader() = default;
Reader(std::string &&);
void Execute(std::string &&);
void Initialize(std::string &&);
};
}
|
VendorSniper/reg
|
Observer/Observer.h
|
<gh_stars>0
#pragma once
#include "ITKtoVTK.h"
#include "Visualizer.h"
#include "Wrapper.h"
#include <itkCenteredTransformInitializer.h>
#include <itkCommand.h>
#include <itkGradientDescentOptimizerv4.h>
#include <itkImage.h>
#include <itkImageRegistrationMethodv4.h>
#include <itkLinearInterpolateImageFunction.h>
#include <itkMattesMutualInformationImageToImageMetricv4.h>
#include <itkResampleImageFilter.h>
#include <itkVersorRigid3DTransform.h>
/// \see https://itk.org/Doxygen45/html/Registration_2ImageRegistration8_8cxx-example.html
/// \note uses itk::GradientDescentOptimizerv4Template<double> instead
/// \warning no considerations for extensibility
class CommandIterationUpdate : public itk::Command {
public:
typedef CommandIterationUpdate Self;
typedef itk::Command Superclass;
typedef itk::SmartPointer<Self> Pointer;
itkNewMacro(Self);
protected:
CommandIterationUpdate(){};
public:
typedef itk::GradientDescentOptimizerv4Template<double> OptimizerType;
typedef const OptimizerType *OptimizerPointer;
void Execute(itk::Object *caller,
const itk::EventObject &event) ITK_OVERRIDE {
Execute((const itk::Object *)caller, event);
}
void Execute(const itk::Object *object,
const itk::EventObject &event) ITK_OVERRIDE {
OptimizerPointer optimizer = static_cast<OptimizerPointer>(object);
if (!itk::IterationEvent().CheckEvent(&event)) {
return;
}
std::cout << optimizer->GetCurrentIteration() << " ";
std::cout << optimizer->GetValue() << " ";
std::cout << optimizer->GetCurrentPosition() << std::endl;
}
};
|
VendorSniper/reg
|
ITKtoVTK/ITKtoVTK.h
|
#pragma once
#include "Wrapper.h"
#include <itkImage.h>
#include <itkImageToVTKImageFilter.h>
#include <vtkImageData.h>
namespace reg {
/// \struct ITKtoVTK
/// \brief converts itk::Image<double, 3> to vtk::ImageData
/// \warning requires itk to be built with ITKVTKglue
struct ITKtoVTK : Wrapper<itk::Image<double, 3>>,
Wrapper<vtkImageData>,
Wrapper<itk::ImageToVTKImageFilter<itk::Image<double, 3>>> {
ITKtoVTK() = default;
ITKtoVTK(itk::Image<double, 3> *);
void Execute(itk::Image<double, 3> *);
void Initialize(itk::Image<double, 3> *);
};
}
|
VendorSniper/reg
|
Registrator/Registrator.h
|
<filename>Registrator/Registrator.h
#pragma once
#include "Observer.h"
#include "Wrapper.h"
#include <itkCenteredTransformInitializer.h>
#include <itkGradientDescentOptimizerv4.h>
#include <itkImage.h>
#include <itkImageRegistrationMethodv4.h>
#include <itkLinearInterpolateImageFunction.h>
#include <itkMattesMutualInformationImageToImageMetricv4.h>
#include <itkResampleImageFilter.h>
#include <itkVersorRigid3DTransform.h>
namespace reg {
using PIXEL = double;
constexpr auto DIMENSIONS = 3u;
struct Combined : Wrapper<itk::Image<PIXEL, DIMENSIONS>> {};
struct Fixed : Wrapper<itk::Image<PIXEL, DIMENSIONS>> {};
struct Moving : Wrapper<itk::Image<PIXEL, DIMENSIONS>> {};
struct Transform
: Wrapper<itk::VersorRigid3DTransform<PIXEL>> ///< \warning require
/// manipulation when changing
/// DIMENSIONS
{};
struct Interpolator
: Wrapper<itk::LinearInterpolateImageFunction<Moving::self_type>> {};
struct Method
: Wrapper<itk::ImageRegistrationMethodv4<
Fixed::self_type, Moving::self_type, Transform::self_type>> {};
struct Metric : Wrapper<itk::MattesMutualInformationImageToImageMetricv4<
Fixed::self_type, Moving::self_type>> {};
struct Optimizer : Wrapper<itk::GradientDescentOptimizerv4Template<PIXEL>> {};
struct Resampler
: Wrapper<itk::ResampleImageFilter<Moving::self_type,
Fixed::self_type>> ///< \note optional
/// template
/// parameters not
/// explicitly
/// declared
{};
struct TransformInitializer
: Wrapper<itk::CenteredTransformInitializer<
Transform::self_type, Fixed::self_type, Moving::self_type>> {};
struct Monitor : Wrapper<CommandIterationUpdate> {};
struct Registrator : Combined,
Fixed,
Interpolator,
Method,
Metric,
Moving,
Optimizer,
Resampler,
Transform,
TransformInitializer,
Monitor {
Registrator() = default;
Registrator(Fixed::self_type *, Moving::self_type *);
void Initialize(Fixed::self_type *, Moving::self_type *);
void Execute(Fixed::self_type *, Moving::self_type *);
};
}
|
VendorSniper/reg
|
Writer/Writer.h
|
<reponame>VendorSniper/reg
#pragma once
#include "Wrapper.h"
#include <itkImage.h>
#include <itkImageFileWriter.h>
namespace reg {
/// \struct Writer
/// \brief writes itk::Image<double, 3> to given filename
/// \note \var Wrapper<std::string> requires a fully qualified file path and extension
struct Writer : Wrapper<itk::Image<double, 3>>,
Wrapper<itk::ImageFileWriter<itk::Image<double, 3>>>,
Wrapper<std::string> {
Writer() = default;
Writer(std::string &&, itk::Image<double, 3> *);
void Execute(std::string &&, itk::Image<double, 3> *);
void Initialize(std::string &&, itk::Image<double, 3> *);
};
}
|
VendorSniper/reg
|
Visualizer/Visualizer.h
|
#pragma once
#include "ITKtoVTK.h"
#include <limits>
#include <vtkImageShiftScale.h>
#include <vtkImageThreshold.h>
#include <vtkPiecewiseFunction.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <vtkSmartVolumeMapper.h>
#include <vtkVolume.h>
#include <vtkVolumeProperty.h>
namespace reg {
/// \struct CompositeOpacity
/// \brief alias for Wrapper<vtkPiecewiseFunction> for disambiguation
struct CompositeOpacity : Wrapper<vtkPiecewiseFunction> {};
/// \struct Visualizer
/// \brief visualize vtkImageData in 3D space
struct Visualizer : Wrapper<vtkImageData>,
Wrapper<vtkRenderer>,
Wrapper<vtkRenderWindow>,
Wrapper<vtkRenderWindowInteractor>,
Wrapper<vtkSmartVolumeMapper>, ///< maps vtkImageData to
/// visualization framework
Wrapper<vtkVolume>,
Wrapper<vtkVolumeProperty>,
CompositeOpacity,
Wrapper<vtkImageShiftScale>, ///< adjusts brightness
Wrapper<vtkImageThreshold> {
Visualizer() = default;
Visualizer(vtkImageData *);
void Execute(vtkImageData *);
void Initialize(vtkImageData *);
};
}
|
maxgerhardt/framework-arduinostm32
|
system/Middlewares/ST/STM32_USB_Host_Library/Class/HID/Inc/usbh_hid_usage.h
|
/**
******************************************************************************
* @file usbh_hid_usage.c
* @author MCD Application Team
* @brief This file contain the USAGE page codes
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2015 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* http://www.st.com/SLA0044
*
******************************************************************************
*/
/* Define to prevent recursive ----------------------------------------------*/
#ifndef __USDH_HID_USAGE_H
#define __USDH_HID_USAGE_H
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup USBH_LIB
* @{
*/
/** @addtogroup USBH_CLASS
* @{
*/
/** @addtogroup USBH_HID_CLASS
* @{
*/
/** @defgroup USBH_HID_USAGE
* @brief This file is the Header file for usbh_hid_usage.c
* @{
*/
/** @defgroup USBH_HID_USAGE_Exported_Types
* @{
*/
/****************************************************/
/* HID 1.11 usage pages */
/****************************************************/
#define HID_USAGE_PAGE_UNDEFINED uint16_t (0x00) /* Undefined */
/**** Top level pages */
#define HID_USAGE_PAGE_GEN_DES uint16_t (0x01) /* Generic Desktop Controls*/
#define HID_USAGE_PAGE_SIM_CTR uint16_t (0x02) /* Simulation Controls */
#define HID_USAGE_PAGE_VR_CTR uint16_t (0x03) /* VR Controls */
#define HID_USAGE_PAGE_SPORT_CTR uint16_t (0x04) /* Sport Controls */
#define HID_USAGE_PAGE_GAME_CTR uint16_t (0x05) /* Game Controls */
#define HID_USAGE_PAGE_GEN_DEV uint16_t (0x06) /* Generic Device Controls */
#define HID_USAGE_PAGE_KEYB uint16_t (0x07) /* Keyboard/Keypad */
#define HID_USAGE_PAGE_LED uint16_t (0x08) /* LEDs */
#define HID_USAGE_PAGE_BUTTON uint16_t (0x09) /* Button */
#define HID_USAGE_PAGE_ORDINAL uint16_t (0x0A) /* Ordinal */
#define HID_USAGE_PAGE_PHONE uint16_t (0x0B) /* Telephony */
#define HID_USAGE_PAGE_CONSUMER uint16_t (0x0C) /* Consumer */
#define HID_USAGE_PAGE_DIGITIZER uint16_t (0x0D) /* Digitizer*/
/* 0E Reserved */
#define HID_USAGE_PAGE_PID uint16_t (0x0F) /* PID Page (force feedback and related devices) */
#define HID_USAGE_PAGE_UNICODE uint16_t (0x10) /* Unicode */
/* 11-13 Reserved */
#define HID_USAGE_PAGE_ALNUM_DISP uint16_t (0x14) /* Alphanumeric Display */
/* 15-1f Reserved */
/**** END of top level pages */
/* 25-3f Reserved */
#define HID_USAGE_PAGE_MEDICAL uint16_t (0x40) /* Medical Instruments */
/* 41-7F Reserved */
/*80-83 Monitor pages USB Device Class Definition for Monitor Devices
84-87 Power pages USB Device Class Definition for Power Devices */
/* 88-8B Reserved */
#define HID_USAGE_PAGE_BARCODE uint16_t (0x8C) /* Bar Code Scanner page */
#define HID_USAGE_PAGE_SCALE uint16_t (0x8D) /* Scale page */
#define HID_USAGE_PAGE_MSR uint16_t (0x8E) /* Magnetic Stripe Reading (MSR) Devices */
#define HID_USAGE_PAGE_POS uint16_t (0x8F) /* Reserved Point of Sale pages */
#define HID_USAGE_PAGE_CAMERA_CTR uint16_t (0x90) /* Camera Control Page */
#define HID_USAGE_PAGE_ARCADE uint16_t (0x91) /* Arcade Page */
/****************************************************/
/* Usage definitions for the "Generic Desktop" page */
/****************************************************/
#define HID_USAGE_UNDEFINED uint16_t (0x00) /* Undefined */
#define HID_USAGE_POINTER uint16_t (0x01) /* Pointer (Physical Collection) */
#define HID_USAGE_MOUSE uint16_t (0x02) /* Mouse (Application Collection) */
/* 03 Reserved */
#define HID_USAGE_JOYSTICK uint16_t (0x04) /* Joystick (Application Collection) */
#define HID_USAGE_GAMEPAD uint16_t (0x05) /* Game Pad (Application Collection) */
#define HID_USAGE_KBD uint16_t (0x06) /* Keyboard (Application Collection) */
#define HID_USAGE_KEYPAD uint16_t (0x07) /* Keypad (Application Collection) */
#define HID_USAGE_MAX_CTR uint16_t (0x08) /* Multi-axis Controller (Application Collection) */
/* 09-2F Reserved */
#define HID_USAGE_X uint16_t (0x30) /* X (Dynamic Value) */
#define HID_USAGE_Y uint16_t (0x31) /* Y (Dynamic Value) */
#define HID_USAGE_Z uint16_t (0x32) /* Z (Dynamic Value) */
#define HID_USAGE_RX uint16_t (0x33) /* Rx (Dynamic Value) */
#define HID_USAGE_RY uint16_t (0x34) /* Ry (Dynamic Value) */
#define HID_USAGE_RZ uint16_t (0x35) /* Rz (Dynamic Value) */
#define HID_USAGE_SLIDER uint16_t (0x36) /* Slider (Dynamic Value) */
#define HID_USAGE_DIAL uint16_t (0x37) /* Dial (Dynamic Value) */
#define HID_USAGE_WHEEL uint16_t (0x38) /* Wheel (Dynamic Value) */
#define HID_USAGE_HATSW uint16_t (0x39) /* Hat switch (Dynamic Value) */
#define HID_USAGE_COUNTEDBUF uint16_t (0x3A) /* Counted Buffer (Logical Collection) */
#define HID_USAGE_BYTECOUNT uint16_t (0x3B) /* Byte Count (Dynamic Value) */
#define HID_USAGE_MOTIONWAKE uint16_t (0x3C) /* Motion Wakeup (One Shot Control) */
#define HID_USAGE_START uint16_t (0x3D) /* Start (On/Off Control) */
#define HID_USAGE_SELECT uint16_t (0x3E) /* Select (On/Off Control) */
/* 3F Reserved */
#define HID_USAGE_VX uint16_t (0x40) /* Vx (Dynamic Value) */
#define HID_USAGE_VY uint16_t (0x41) /* Vy (Dynamic Value) */
#define HID_USAGE_VZ uint16_t (0x42) /* Vz (Dynamic Value) */
#define HID_USAGE_VBRX uint16_t (0x43) /* Vbrx (Dynamic Value) */
#define HID_USAGE_VBRY uint16_t (0x44) /* Vbry (Dynamic Value) */
#define HID_USAGE_VBRZ uint16_t (0x45) /* Vbrz (Dynamic Value) */
#define HID_USAGE_VNO uint16_t (0x46) /* Vno (Dynamic Value) */
#define HID_USAGE_FEATNOTIF uint16_t (0x47) /* Feature Notification (Dynamic Value),(Dynamic Flag) */
/* 48-7F Reserved */
#define HID_USAGE_SYSCTL uint16_t (0x80) /* System Control (Application Collection) */
#define HID_USAGE_PWDOWN uint16_t (0x81) /* System Power Down (One Shot Control) */
#define HID_USAGE_SLEEP uint16_t (0x82) /* System Sleep (One Shot Control) */
#define HID_USAGE_WAKEUP uint16_t (0x83) /* System Wake Up (One Shot Control) */
#define HID_USAGE_CONTEXTM uint16_t (0x84) /* System Context Menu (One Shot Control) */
#define HID_USAGE_MAINM uint16_t (0x85) /* System Main Menu (One Shot Control) */
#define HID_USAGE_APPM uint16_t (0x86) /* System App Menu (One Shot Control) */
#define HID_USAGE_MENUHELP uint16_t (0x87) /* System Menu Help (One Shot Control) */
#define HID_USAGE_MENUEXIT uint16_t (0x88) /* System Menu Exit (One Shot Control) */
#define HID_USAGE_MENUSELECT uint16_t (0x89) /* System Menu Select (One Shot Control) */
#define HID_USAGE_SYSM_RIGHT uint16_t (0x8A) /* System Menu Right (Re-Trigger Control) */
#define HID_USAGE_SYSM_LEFT uint16_t (0x8B) /* System Menu Left (Re-Trigger Control) */
#define HID_USAGE_SYSM_UP uint16_t (0x8C) /* System Menu Up (Re-Trigger Control) */
#define HID_USAGE_SYSM_DOWN uint16_t (0x8D) /* System Menu Down (Re-Trigger Control) */
#define HID_USAGE_COLDRESET uint16_t (0x8E) /* System Cold Restart (One Shot Control) */
#define HID_USAGE_WARMRESET uint16_t (0x8F) /* System Warm Restart (One Shot Control) */
#define HID_USAGE_DUP uint16_t (0x90) /* D-pad Up (On/Off Control) */
#define HID_USAGE_DDOWN uint16_t (0x91) /* D-pad Down (On/Off Control) */
#define HID_USAGE_DRIGHT uint16_t (0x92) /* D-pad Right (On/Off Control) */
#define HID_USAGE_DLEFT uint16_t (0x93) /* D-pad Left (On/Off Control) */
/* 94-9F Reserved */
#define HID_USAGE_SYS_DOCK uint16_t (0xA0) /* System Dock (One Shot Control) */
#define HID_USAGE_SYS_UNDOCK uint16_t (0xA1) /* System Undock (One Shot Control) */
#define HID_USAGE_SYS_SETUP uint16_t (0xA2) /* System Setup (One Shot Control) */
#define HID_USAGE_SYS_BREAK uint16_t (0xA3) /* System Break (One Shot Control) */
#define HID_USAGE_SYS_DBGBRK uint16_t (0xA4) /* System Debugger Break (One Shot Control) */
#define HID_USAGE_APP_BRK uint16_t (0xA5) /* Application Break (One Shot Control) */
#define HID_USAGE_APP_DBGBRK uint16_t (0xA6) /* Application Debugger Break (One Shot Control) */
#define HID_USAGE_SYS_SPKMUTE uint16_t (0xA7) /* System Speaker Mute (One Shot Control) */
#define HID_USAGE_SYS_HIBERN uint16_t (0xA8) /* System Hibernate (One Shot Control) */
/* A9-AF Reserved */
#define HID_USAGE_SYS_SIDPINV uint16_t (0xB0) /* System Display Invert (One Shot Control) */
#define HID_USAGE_SYS_DISPINT uint16_t (0xB1) /* System Display Internal (One Shot Control) */
#define HID_USAGE_SYS_DISPEXT uint16_t (0xB2) /* System Display External (One Shot Control) */
#define HID_USAGE_SYS_DISPBOTH uint16_t (0xB3) /* System Display Both (One Shot Control) */
#define HID_USAGE_SYS_DISPDUAL uint16_t (0xB4) /* System Display Dual (One Shot Control) */
#define HID_USAGE_SYS_DISPTGLIE uint16_t (0xB5) /* System Display Toggle Int/Ext (One Shot Control) */
#define HID_USAGE_SYS_DISP_SWAP uint16_t (0xB6) /* System Display Swap Primary/Secondary (One Shot Control) */
#define HID_USAGE_SYS_DIPS_LCDA uint16_t (0xB7) /* System Display LCD Autoscale (One Shot Control) */
/* B8-FFFF Reserved */
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USDH_HID_USAGE_H */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
maxgerhardt/framework-arduinostm32
|
system/Middlewares/ST/STM32_USB_Host_Library/Core/Src/usbh_core.c
|
/**
******************************************************************************
* @file usbh_core.c
* @author MCD Application Team
* @brief This file implements the functions for the core state machine process
* the enumeration and the control transfer process
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2015 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* http://www.st.com/SLA0044
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "usbh_core.h"
/** @addtogroup USBH_LIB
* @{
*/
/** @addtogroup USBH_LIB_CORE
* @{
*/
/** @defgroup USBH_CORE
* @brief This file handles the basic enumeration when a device is connected
* to the host.
* @{
*/
/** @defgroup USBH_CORE_Private_Defines
* @{
*/
#define USBH_ADDRESS_DEFAULT 0x00U
#define USBH_ADDRESS_ASSIGNED 0x01U
#define USBH_MPS_DEFAULT 0x40U
/**
* @}
*/
/** @defgroup USBH_CORE_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBH_CORE_Private_Variables
* @{
*/
#if (USBH_USE_OS == 1U)
#if (osCMSIS >= 0x20000U)
osThreadAttr_t USBH_Thread_Atrr;
#endif
#endif
/**
* @}
*/
/** @defgroup USBH_CORE_Private_Functions
* @{
*/
static USBH_StatusTypeDef USBH_HandleEnum (USBH_HandleTypeDef *phost);
static void USBH_HandleSof (USBH_HandleTypeDef *phost);
static USBH_StatusTypeDef DeInitStateMachine(USBH_HandleTypeDef *phost);
#if (USBH_USE_OS == 1U)
#if (osCMSIS < 0x20000U)
static void USBH_Process_OS(void const *argument);
#else
static void USBH_Process_OS(void *argument);
#endif
#endif
/**
* @brief HCD_Init
* Initialize the HOST Core.
* @param phost: Host Handle
* @param pUsrFunc: User Callback
* @retval USBH Status
*/
USBH_StatusTypeDef USBH_Init(USBH_HandleTypeDef *phost, void (*pUsrFunc)(USBH_HandleTypeDef *phost, uint8_t id), uint8_t id)
{
/* Check whether the USB Host handle is valid */
if(phost == NULL)
{
USBH_ErrLog("Invalid Host handle");
return USBH_FAIL;
}
/* Set DRiver ID */
phost->id = id;
/* Unlink class*/
phost->pActiveClass = NULL;
phost->ClassNumber = 0U;
/* Restore default states and prepare EP0 */
DeInitStateMachine(phost);
/* Assign User process */
if(pUsrFunc != NULL)
{
phost->pUser = pUsrFunc;
}
#if (USBH_USE_OS == 1U)
#if (osCMSIS < 0x20000U)
/* Create USB Host Queue */
osMessageQDef(USBH_Queue, MSGQUEUE_OBJECTS, uint16_t);
phost->os_event = osMessageCreate (osMessageQ(USBH_Queue), NULL);
/* Create USB Host Task */
#if defined (USBH_PROCESS_STACK_SIZE)
osThreadDef(USBH_Thread, USBH_Process_OS, USBH_PROCESS_PRIO, 0U, USBH_PROCESS_STACK_SIZE);
#else
osThreadDef(USBH_Thread, USBH_Process_OS, USBH_PROCESS_PRIO, 0U, 8U * configMINIMAL_STACK_SIZE);
#endif /* defined (USBH_PROCESS_STACK_SIZE) */
phost->thread = osThreadCreate (osThread(USBH_Thread), phost);
#else
/* Create USB Host Queue */
phost->os_event = osMessageQueueNew (MSGQUEUE_OBJECTS, sizeof(uint32_t), NULL);
/* Create USB Host Task */
USBH_Thread_Atrr.name = "USBH_Queue";
#if defined (USBH_PROCESS_STACK_SIZE)
USBH_Thread_Atrr.stack_size = USBH_PROCESS_STACK_SIZE;
#else
USBH_Thread_Atrr.stack_size = (8U * configMINIMAL_STACK_SIZE);
#endif /* defined (USBH_PROCESS_STACK_SIZE) */
USBH_Thread_Atrr.priority = USBH_PROCESS_PRIO;
phost->thread = osThreadNew(USBH_Process_OS, phost, &USBH_Thread_Atrr);
#endif /* (osCMSIS < 0x20000U) */
#endif /* (USBH_USE_OS == 1U) */
/* Initialize low level driver */
USBH_LL_Init(phost);
return USBH_OK;
}
/**
* @brief HCD_Init
* De-Initialize the Host portion of the driver.
* @param phost: Host Handle
* @retval USBH Status
*/
USBH_StatusTypeDef USBH_DeInit(USBH_HandleTypeDef *phost)
{
DeInitStateMachine(phost);
if(phost->pData != NULL)
{
USBH_free (phost->pActiveClass->pData);
phost->pActiveClass->pData = NULL;
USBH_LL_Stop(phost);
}
return USBH_OK;
}
/**
* @brief DeInitStateMachine
* De-Initialize the Host state machine.
* @param phost: Host Handle
* @retval USBH Status
*/
static USBH_StatusTypeDef DeInitStateMachine(USBH_HandleTypeDef *phost)
{
uint32_t i = 0U;
/* Clear Pipes flags*/
for ( ; i < USBH_MAX_PIPES_NBR; i++)
{
phost->Pipes[i] = 0U;
}
for(i = 0U; i< USBH_MAX_DATA_BUFFER; i++)
{
phost->device.Data[i] = 0U;
}
phost->gState = HOST_IDLE;
phost->EnumState = ENUM_IDLE;
phost->RequestState = CMD_SEND;
phost->Timer = 0U;
phost->Control.state = CTRL_SETUP;
phost->Control.pipe_size = USBH_MPS_DEFAULT;
phost->Control.errorcount = 0U;
phost->device.address = USBH_ADDRESS_DEFAULT;
phost->device.speed = USBH_SPEED_FULL;
return USBH_OK;
}
/**
* @brief USBH_RegisterClass
* Link class driver to Host Core.
* @param phost : Host Handle
* @param pclass: Class handle
* @retval USBH Status
*/
USBH_StatusTypeDef USBH_RegisterClass(USBH_HandleTypeDef *phost, USBH_ClassTypeDef *pclass)
{
USBH_StatusTypeDef status = USBH_OK;
if(pclass != 0)
{
if(phost->ClassNumber < USBH_MAX_NUM_SUPPORTED_CLASS)
{
/* link the class to the USB Host handle */
phost->pClass[phost->ClassNumber++] = pclass;
status = USBH_OK;
}
else
{
USBH_ErrLog("Max Class Number reached");
status = USBH_FAIL;
}
}
else
{
USBH_ErrLog("Invalid Class handle");
status = USBH_FAIL;
}
return status;
}
/**
* @brief USBH_SelectInterface
* Select current interface.
* @param phost: Host Handle
* @param interface: Interface number
* @retval USBH Status
*/
USBH_StatusTypeDef USBH_SelectInterface(USBH_HandleTypeDef *phost, uint8_t interface)
{
USBH_StatusTypeDef status = USBH_OK;
if(interface < phost->device.CfgDesc.bNumInterfaces)
{
phost->device.current_interface = interface;
USBH_UsrLog ("Switching to Interface (#%d)", interface);
USBH_UsrLog ("Class : %xh", phost->device.CfgDesc.Itf_Desc[interface].bInterfaceClass );
USBH_UsrLog ("SubClass : %xh", phost->device.CfgDesc.Itf_Desc[interface].bInterfaceSubClass );
USBH_UsrLog ("Protocol : %xh", phost->device.CfgDesc.Itf_Desc[interface].bInterfaceProtocol );
}
else
{
USBH_ErrLog ("Cannot Select This Interface.");
status = USBH_FAIL;
}
return status;
}
/**
* @brief USBH_GetActiveClass
* Return Device Class.
* @param phost: Host Handle
* @param interface: Interface index
* @retval Class Code
*/
uint8_t USBH_GetActiveClass(USBH_HandleTypeDef *phost)
{
return (phost->device.CfgDesc.Itf_Desc[0].bInterfaceClass);
}
/**
* @brief USBH_FindInterface
* Find the interface index for a specific class.
* @param phost: Host Handle
* @param Class: Class code
* @param SubClass: SubClass code
* @param Protocol: Protocol code
* @retval interface index in the configuration structure
* @note : (1)interface index 0xFF means interface index not found
*/
uint8_t USBH_FindInterface(USBH_HandleTypeDef *phost, uint8_t Class, uint8_t SubClass, uint8_t Protocol)
{
USBH_InterfaceDescTypeDef *pif ;
USBH_CfgDescTypeDef *pcfg ;
uint8_t if_ix = 0U;
pif = (USBH_InterfaceDescTypeDef *)0;
pcfg = &phost->device.CfgDesc;
while (if_ix < USBH_MAX_NUM_INTERFACES)
{
pif = &pcfg->Itf_Desc[if_ix];
if(((pif->bInterfaceClass == Class) || (Class == 0xFFU))&&
((pif->bInterfaceSubClass == SubClass) || (SubClass == 0xFFU))&&
((pif->bInterfaceProtocol == Protocol) || (Protocol == 0xFFU)))
{
return if_ix;
}
if_ix++;
}
return 0xFFU;
}
/**
* @brief USBH_FindInterfaceIndex
* Find the interface index for a specific class interface and alternate setting number.
* @param phost: Host Handle
* @param interface_number: interface number
* @param alt_settings : alternate setting number
* @retval interface index in the configuration structure
* @note : (1)interface index 0xFF means interface index not found
*/
uint8_t USBH_FindInterfaceIndex(USBH_HandleTypeDef *phost, uint8_t interface_number, uint8_t alt_settings)
{
USBH_InterfaceDescTypeDef *pif ;
USBH_CfgDescTypeDef *pcfg ;
uint8_t if_ix = 0U;
pif = (USBH_InterfaceDescTypeDef *)0;
pcfg = &phost->device.CfgDesc;
while (if_ix < USBH_MAX_NUM_INTERFACES)
{
pif = &pcfg->Itf_Desc[if_ix];
if((pif->bInterfaceNumber == interface_number) && (pif->bAlternateSetting == alt_settings))
{
return if_ix;
}
if_ix++;
}
return 0xFFU;
}
/**
* @brief USBH_Start
* Start the USB Host Core.
* @param phost: Host Handle
* @retval USBH Status
*/
USBH_StatusTypeDef USBH_Start (USBH_HandleTypeDef *phost)
{
/* Start the low level driver */
USBH_LL_Start(phost);
/* Activate VBUS on the port */
USBH_LL_DriverVBUS (phost, TRUE);
return USBH_OK;
}
/**
* @brief USBH_Stop
* Stop the USB Host Core.
* @param phost: Host Handle
* @retval USBH Status
*/
USBH_StatusTypeDef USBH_Stop (USBH_HandleTypeDef *phost)
{
/* Stop and cleanup the low level driver */
USBH_LL_Stop(phost);
/* DeActivate VBUS on the port */
USBH_LL_DriverVBUS (phost, FALSE);
/* FRee Control Pipes */
USBH_FreePipe (phost, phost->Control.pipe_in);
USBH_FreePipe (phost, phost->Control.pipe_out);
return USBH_OK;
}
/**
* @brief HCD_ReEnumerate
* Perform a new Enumeration phase.
* @param phost: Host Handle
* @retval USBH Status
*/
USBH_StatusTypeDef USBH_ReEnumerate(USBH_HandleTypeDef *phost)
{
/*Stop Host */
USBH_Stop(phost);
/*Device has disconnected, so wait for 200 ms */
USBH_Delay(200U);
/* Set State machines in default state */
DeInitStateMachine(phost);
/* Start again the host */
USBH_Start(phost);
#if (USBH_USE_OS == 1U)
phost->os_msg = (uint32_t)USBH_PORT_EVENT;
#if (osCMSIS < 0x20000U)
(void)osMessagePut(phost->os_event, phost->os_msg, 0U);
#else
(void)osMessageQueuePut(phost->os_event, &phost->os_msg, 0U, NULL);
#endif
#endif
return USBH_OK;
}
/**
* @brief USBH_Process
* Background process of the USB Core.
* @param phost: Host Handle
* @retval USBH Status
*/
USBH_StatusTypeDef USBH_Process(USBH_HandleTypeDef *phost)
{
__IO USBH_StatusTypeDef status = USBH_FAIL;
uint8_t idx = 0U;
/* check for Host port events */
if (((USBH_IsPortEnabled(phost) == 0U)) && (phost->gState != HOST_IDLE))
{
if(phost->gState != HOST_DEV_DISCONNECTED)
{
phost->gState = HOST_DEV_DISCONNECTED;
}
}
switch (phost->gState)
{
case HOST_IDLE :
if (phost->device.is_connected)
{
/* Wait for 200 ms after connection */
phost->gState = HOST_DEV_WAIT_FOR_ATTACHMENT;
USBH_Delay(200U);
USBH_LL_ResetPort(phost);
#if (USBH_USE_OS == 1U)
phost->os_msg = (uint32_t)USBH_PORT_EVENT;
#if (osCMSIS < 0x20000U)
(void)osMessagePut(phost->os_event, phost->os_msg, 0U);
#else
(void)osMessageQueuePut(phost->os_event, &phost->os_msg, 0U, NULL);
#endif
#endif
}
break;
case HOST_DEV_WAIT_FOR_ATTACHMENT: /* Wait for Port Eabled */
if (phost->device.PortEnabled == 1U)
{
phost->gState = HOST_DEV_ATTACHED;
}
break;
case HOST_DEV_ATTACHED :
USBH_UsrLog("USB Device Attached");
/* Wait for 100 ms after Reset */
USBH_Delay(100U);
phost->device.speed = USBH_LL_GetSpeed(phost);
phost->gState = HOST_ENUMERATION;
phost->Control.pipe_out = USBH_AllocPipe (phost, 0x00U);
phost->Control.pipe_in = USBH_AllocPipe (phost, 0x80U);
/* Open Control pipes */
USBH_OpenPipe (phost,
phost->Control.pipe_in,
0x80U,
phost->device.address,
phost->device.speed,
USBH_EP_CONTROL,
(uint16_t)phost->Control.pipe_size);
/* Open Control pipes */
USBH_OpenPipe (phost,
phost->Control.pipe_out,
0x00U,
phost->device.address,
phost->device.speed,
USBH_EP_CONTROL,
(uint16_t)phost->Control.pipe_size);
#if (USBH_USE_OS == 1U)
phost->os_msg = (uint32_t)USBH_PORT_EVENT;
#if (osCMSIS < 0x20000U)
(void)osMessagePut(phost->os_event, phost->os_msg, 0U);
#else
(void)osMessageQueuePut(phost->os_event, &phost->os_msg, 0U, NULL);
#endif
#endif
break;
case HOST_ENUMERATION:
/* Check for enumeration status */
if ( USBH_HandleEnum(phost) == USBH_OK)
{
/* The function shall return USBH_OK when full enumeration is complete */
USBH_UsrLog ("Enumeration done.");
phost->device.current_interface = 0U;
if(phost->device.DevDesc.bNumConfigurations == 1U)
{
USBH_UsrLog ("This device has only 1 configuration.");
phost->gState = HOST_SET_CONFIGURATION;
}
else
{
phost->gState = HOST_INPUT;
}
}
break;
case HOST_INPUT:
{
/* user callback for end of device basic enumeration */
if(phost->pUser != NULL)
{
phost->pUser(phost, HOST_USER_SELECT_CONFIGURATION);
phost->gState = HOST_SET_CONFIGURATION;
#if (USBH_USE_OS == 1U)
phost->os_msg = (uint32_t)USBH_STATE_CHANGED_EVENT;
#if (osCMSIS < 0x20000U)
(void)osMessagePut(phost->os_event, phost->os_msg, 0U);
#else
(void)osMessageQueuePut(phost->os_event, &phost->os_msg, 0U, NULL);
#endif
#endif
}
}
break;
case HOST_SET_CONFIGURATION:
/* set configuration */
if (USBH_SetCfg(phost, (uint16_t)phost->device.CfgDesc.bConfigurationValue) == USBH_OK)
{
phost->gState = HOST_SET_WAKEUP_FEATURE;
USBH_UsrLog ("Default configuration set.");
}
#if (USBH_USE_OS == 1U)
phost->os_msg = (uint32_t)USBH_PORT_EVENT;
#if (osCMSIS < 0x20000U)
(void)osMessagePut(phost->os_event, phost->os_msg, 0U);
#else
(void)osMessageQueuePut(phost->os_event, &phost->os_msg, 0U, NULL);
#endif
#endif
break;
case HOST_SET_WAKEUP_FEATURE:
if ((phost->device.CfgDesc.bmAttributes) & (1U << 5))
{
if (USBH_SetFeature(phost, FEATURE_SELECTOR_REMOTEWAKEUP) == USBH_OK)
{
USBH_UsrLog ("Device remote wakeup enabled");
phost->gState = HOST_CHECK_CLASS;
}
}
else
{
phost->gState = HOST_CHECK_CLASS;
}
#if (USBH_USE_OS == 1U)
phost->os_msg = (uint32_t)USBH_PORT_EVENT;
#if (osCMSIS < 0x20000U)
(void)osMessagePut(phost->os_event, phost->os_msg, 0U);
#else
(void)osMessageQueuePut(phost->os_event, &phost->os_msg, 0U, NULL);
#endif
#endif
break;
case HOST_CHECK_CLASS:
if(phost->ClassNumber == 0U)
{
USBH_UsrLog ("No Class has been registered.");
}
else
{
phost->pActiveClass = NULL;
for (idx = 0U; idx < USBH_MAX_NUM_SUPPORTED_CLASS; idx++)
{
if(phost->pClass[idx]->ClassCode == phost->device.CfgDesc.Itf_Desc[0].bInterfaceClass)
{
phost->pActiveClass = phost->pClass[idx];
}
}
if(phost->pActiveClass != NULL)
{
if(phost->pActiveClass->Init(phost)== USBH_OK)
{
phost->gState = HOST_CLASS_REQUEST;
USBH_UsrLog ("%s class started.", phost->pActiveClass->Name);
/* Inform user that a class has been activated */
phost->pUser(phost, HOST_USER_CLASS_SELECTED);
}
else
{
phost->gState = HOST_ABORT_STATE;
USBH_UsrLog ("Device not supporting %s class.", phost->pActiveClass->Name);
}
}
else
{
phost->gState = HOST_ABORT_STATE;
USBH_UsrLog ("No registered class for this device.");
}
}
#if (USBH_USE_OS == 1U)
phost->os_msg = (uint32_t)USBH_STATE_CHANGED_EVENT;
#if (osCMSIS < 0x20000U)
(void)osMessagePut(phost->os_event, phost->os_msg, 0U);
#else
(void)osMessageQueuePut(phost->os_event, &phost->os_msg, 0U, NULL);
#endif
#endif
break;
case HOST_CLASS_REQUEST:
/* process class standard control requests state machine */
if(phost->pActiveClass != NULL)
{
status = phost->pActiveClass->Requests(phost);
if(status == USBH_OK)
{
phost->gState = HOST_CLASS;
}
}
else
{
phost->gState = HOST_ABORT_STATE;
USBH_ErrLog ("Invalid Class Driver.");
#if (USBH_USE_OS == 1U)
phost->os_msg = (uint32_t)USBH_STATE_CHANGED_EVENT;
#if (osCMSIS < 0x20000U)
(void)osMessagePut(phost->os_event, phost->os_msg, 0U);
#else
(void)osMessageQueuePut(phost->os_event, &phost->os_msg, 0U, NULL);
#endif
#endif
}
break;
case HOST_CLASS:
/* process class state machine */
if(phost->pActiveClass != NULL)
{
phost->pActiveClass->BgndProcess(phost);
}
break;
case HOST_DEV_DISCONNECTED :
DeInitStateMachine(phost);
/* Re-Initilaize Host for new Enumeration */
if(phost->pActiveClass != NULL)
{
phost->pActiveClass->DeInit(phost);
phost->pActiveClass = NULL;
}
break;
case HOST_ABORT_STATE:
default :
break;
}
return USBH_OK;
}
/**
* @brief USBH_HandleEnum
* This function includes the complete enumeration process
* @param phost: Host Handle
* @retval USBH_Status
*/
static USBH_StatusTypeDef USBH_HandleEnum (USBH_HandleTypeDef *phost)
{
USBH_StatusTypeDef Status = USBH_BUSY;
switch (phost->EnumState)
{
case ENUM_IDLE:
/* Get Device Desc for only 1st 8 bytes : To get EP0 MaxPacketSize */
if ( USBH_Get_DevDesc(phost, 8U) == USBH_OK)
{
phost->Control.pipe_size = phost->device.DevDesc.bMaxPacketSize;
phost->EnumState = ENUM_GET_FULL_DEV_DESC;
/* modify control channels configuration for MaxPacket size */
USBH_OpenPipe (phost,
phost->Control.pipe_in,
0x80U,
phost->device.address,
phost->device.speed,
USBH_EP_CONTROL,
(uint16_t)phost->Control.pipe_size);
/* Open Control pipes */
USBH_OpenPipe (phost,
phost->Control.pipe_out,
0x00U,
phost->device.address,
phost->device.speed,
USBH_EP_CONTROL,
(uint16_t)phost->Control.pipe_size);
}
break;
case ENUM_GET_FULL_DEV_DESC:
/* Get FULL Device Desc */
if ( USBH_Get_DevDesc(phost, USB_DEVICE_DESC_SIZE)== USBH_OK)
{
USBH_UsrLog("PID: %xh", phost->device.DevDesc.idProduct );
USBH_UsrLog("VID: %xh", phost->device.DevDesc.idVendor );
phost->EnumState = ENUM_SET_ADDR;
}
break;
case ENUM_SET_ADDR:
/* set address */
if ( USBH_SetAddress(phost, USBH_DEVICE_ADDRESS) == USBH_OK)
{
USBH_Delay(2U);
phost->device.address = USBH_DEVICE_ADDRESS;
/* user callback for device address assigned */
USBH_UsrLog("Address (#%d) assigned.", phost->device.address);
phost->EnumState = ENUM_GET_CFG_DESC;
/* modify control channels to update device address */
USBH_OpenPipe (phost,
phost->Control.pipe_in,
0x80U,
phost->device.address,
phost->device.speed,
USBH_EP_CONTROL,
(uint16_t)phost->Control.pipe_size);
/* Open Control pipes */
USBH_OpenPipe (phost,
phost->Control.pipe_out,
0x00U,
phost->device.address,
phost->device.speed,
USBH_EP_CONTROL,
(uint16_t)phost->Control.pipe_size);
}
break;
case ENUM_GET_CFG_DESC:
/* get standard configuration descriptor */
if ( USBH_Get_CfgDesc(phost,
USB_CONFIGURATION_DESC_SIZE) == USBH_OK)
{
phost->EnumState = ENUM_GET_FULL_CFG_DESC;
}
break;
case ENUM_GET_FULL_CFG_DESC:
/* get FULL config descriptor (config, interface, endpoints) */
if (USBH_Get_CfgDesc(phost,
phost->device.CfgDesc.wTotalLength) == USBH_OK)
{
phost->EnumState = ENUM_GET_MFC_STRING_DESC;
}
break;
case ENUM_GET_MFC_STRING_DESC:
if (phost->device.DevDesc.iManufacturer != 0U)
{ /* Check that Manufacturer String is available */
if ( USBH_Get_StringDesc(phost,
phost->device.DevDesc.iManufacturer,
phost->device.Data,
0xFFU) == USBH_OK)
{
/* User callback for Manufacturing string */
USBH_UsrLog("Manufacturer : %s", (char *)(void*)phost->device.Data);
phost->EnumState = ENUM_GET_PRODUCT_STRING_DESC;
#if (USBH_USE_OS == 1U)
phost->os_msg = (uint32_t)USBH_STATE_CHANGED_EVENT;
#if (osCMSIS < 0x20000U)
(void)osMessagePut(phost->os_event, phost->os_msg, 0U);
#else
(void)osMessageQueuePut(phost->os_event, &phost->os_msg, 0U, NULL);
#endif
#endif
}
}
else
{
USBH_UsrLog("Manufacturer : N/A");
phost->EnumState = ENUM_GET_PRODUCT_STRING_DESC;
#if (USBH_USE_OS == 1U)
phost->os_msg = (uint32_t)USBH_STATE_CHANGED_EVENT;
#if (osCMSIS < 0x20000U)
(void)osMessagePut(phost->os_event, phost->os_msg, 0U);
#else
(void)osMessageQueuePut(phost->os_event, &phost->os_msg, 0U, NULL);
#endif
#endif
}
break;
case ENUM_GET_PRODUCT_STRING_DESC:
if (phost->device.DevDesc.iProduct != 0U)
{ /* Check that Product string is available */
if ( USBH_Get_StringDesc(phost,
phost->device.DevDesc.iProduct,
phost->device.Data,
0xFFU) == USBH_OK)
{
/* User callback for Product string */
USBH_UsrLog("Product : %s", (char *)(void *)phost->device.Data);
phost->EnumState = ENUM_GET_SERIALNUM_STRING_DESC;
}
}
else
{
USBH_UsrLog("Product : N/A");
phost->EnumState = ENUM_GET_SERIALNUM_STRING_DESC;
#if (USBH_USE_OS == 1U)
phost->os_msg = (uint32_t)USBH_STATE_CHANGED_EVENT;
#if (osCMSIS < 0x20000U)
(void)osMessagePut(phost->os_event, phost->os_msg, 0U);
#else
(void)osMessageQueuePut(phost->os_event, &phost->os_msg, 0U, NULL);
#endif
#endif
}
break;
case ENUM_GET_SERIALNUM_STRING_DESC:
if (phost->device.DevDesc.iSerialNumber != 0U)
{ /* Check that Serial number string is available */
if ( USBH_Get_StringDesc(phost,
phost->device.DevDesc.iSerialNumber,
phost->device.Data,
0xFFU) == USBH_OK)
{
/* User callback for Serial number string */
USBH_UsrLog("Serial Number : %s", (char *)(void*)phost->device.Data);
Status = USBH_OK;
}
}
else
{
USBH_UsrLog("Serial Number : N/A");
Status = USBH_OK;
#if (USBH_USE_OS == 1U)
phost->os_msg = (uint32_t)USBH_STATE_CHANGED_EVENT;
#if (osCMSIS < 0x20000U)
(void)osMessagePut(phost->os_event, phost->os_msg, 0U);
#else
(void)osMessageQueuePut(phost->os_event, &phost->os_msg, 0U, NULL);
#endif
#endif
}
break;
default:
break;
}
return Status;
}
/**
* @brief USBH_LL_SetTimer
* Set the initial Host Timer tick
* @param phost: Host Handle
* @retval None
*/
void USBH_LL_SetTimer (USBH_HandleTypeDef *phost, uint32_t time)
{
phost->Timer = time;
}
/**
* @brief USBH_LL_IncTimer
* Increment Host Timer tick
* @param phost: Host Handle
* @retval None
*/
void USBH_LL_IncTimer (USBH_HandleTypeDef *phost)
{
phost->Timer ++;
USBH_HandleSof(phost);
}
/**
* @brief USBH_HandleSof
* Call SOF process
* @param phost: Host Handle
* @retval None
*/
static void USBH_HandleSof (USBH_HandleTypeDef *phost)
{
if((phost->gState == HOST_CLASS)&&(phost->pActiveClass != NULL))
{
phost->pActiveClass->SOFProcess(phost);
}
}
/**
* @brief USBH_PortEnabled
* Port Enabled
* @param phost: Host Handle
* @retval None
*/
void USBH_LL_PortEnabled (USBH_HandleTypeDef *phost)
{
phost->device.PortEnabled = 1U;
return;
}
/**
* @brief USBH_LL_PortDisabled
* Port Disabled
* @param phost: Host Handle
* @retval None
*/
void USBH_LL_PortDisabled (USBH_HandleTypeDef *phost)
{
phost->device.PortEnabled = 0U;
return;
}
/**
* @brief HCD_IsPortEnabled
* Is Port Enabled
* @param phost: Host Handle
* @retval None
*/
uint8_t USBH_IsPortEnabled(USBH_HandleTypeDef *phost)
{
return(phost->device.PortEnabled);
}
/**
* @brief USBH_LL_Connect
* Handle USB Host connexion event
* @param phost: Host Handle
* @retval USBH_Status
*/
USBH_StatusTypeDef USBH_LL_Connect (USBH_HandleTypeDef *phost)
{
if(phost->gState == HOST_IDLE )
{
phost->device.is_connected = 1U;
if(phost->pUser != NULL)
{
phost->pUser(phost, HOST_USER_CONNECTION);
}
}
else
{
if (phost->device.PortEnabled == 1U)
{
phost->gState = HOST_DEV_ATTACHED;
}
}
#if (USBH_USE_OS == 1U)
phost->os_msg = (uint32_t)USBH_PORT_EVENT;
#if (osCMSIS < 0x20000U)
(void)osMessagePut(phost->os_event, phost->os_msg, 0U);
#else
(void)osMessageQueuePut(phost->os_event, &phost->os_msg, 0U, NULL);
#endif
#endif
return USBH_OK;
}
/**
* @brief USBH_LL_Disconnect
* Handle USB Host disconnection event
* @param phost: Host Handle
* @retval USBH_Status
*/
USBH_StatusTypeDef USBH_LL_Disconnect (USBH_HandleTypeDef *phost)
{
/*Stop Host */
USBH_LL_Stop(phost);
/* FRee Control Pipes */
USBH_FreePipe (phost, phost->Control.pipe_in);
USBH_FreePipe (phost, phost->Control.pipe_out);
phost->device.is_connected = 0U;
if(phost->pUser != NULL)
{
phost->pUser(phost, HOST_USER_DISCONNECTION);
}
USBH_UsrLog("USB Device disconnected");
/* Start the low level driver */
USBH_LL_Start(phost);
phost->gState = HOST_DEV_DISCONNECTED;
#if (USBH_USE_OS == 1U)
phost->os_msg = (uint32_t)USBH_PORT_EVENT;
#if (osCMSIS < 0x20000U)
(void)osMessagePut(phost->os_event, phost->os_msg, 0U);
#else
(void)osMessageQueuePut(phost->os_event, &phost->os_msg, 0U, NULL);
#endif
#endif
return USBH_OK;
}
#if (USBH_USE_OS == 1U)
/**
* @brief USB Host Thread task
* @param pvParameters not used
* @retval None
*/
#if (osCMSIS < 0x20000U)
static void USBH_Process_OS(void const *argument)
{
osEvent event;
for(;;)
{
event = osMessageGet(((USBH_HandleTypeDef *)argument)->os_event, osWaitForever);
if(event.status == osEventMessage)
{
USBH_Process((USBH_HandleTypeDef *)argument);
}
}
}
#else
static void USBH_Process_OS(void *argument)
{
osStatus_t status;
for(;;)
{
status = osMessageQueueGet(((USBH_HandleTypeDef *)argument)->os_event,
&((USBH_HandleTypeDef *)argument)->os_msg, NULL, osWaitForever);
if (status == osOK)
{
USBH_Process((USBH_HandleTypeDef *)argument);
}
}
}
#endif /* (osCMSIS < 0x20000U) */
/**
* @brief USBH_LL_NotifyURBChange
* Notify URB state Change
* @param phost: Host handle
* @retval USBH Status
*/
USBH_StatusTypeDef USBH_LL_NotifyURBChange (USBH_HandleTypeDef *phost)
{
phost->os_msg = (uint32_t)USBH_PORT_EVENT;
#if (osCMSIS < 0x20000U)
(void)osMessagePut(phost->os_event, phost->os_msg, 0U);
#else
(void)osMessageQueuePut(phost->os_event, &phost->os_msg, 0U, NULL);
#endif
return USBH_OK;
}
#endif
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
maxgerhardt/framework-arduinostm32
|
cores/arduino/stm32/usb/cdc/cdc_queue.h
|
/**
******************************************************************************
* @file cdc_queue.h
* @author makarenya
* @version V1.0.0
* @date 23-December-2018
* @brief Header for cdc_queue.c module
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2016 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __CDC_QUEUE_H
#define __CDC_QUEUE_H
/* Includes ------------------------------------------------------------------*/
#include "usbd_def.h"
#ifdef __cplusplus
extern "C" {
#endif
#if USE_USB_HS
#define CDC_QUEUE_MAX_PACKET_SIZE USB_HS_MAX_PACKET_SIZE
#else
#define CDC_QUEUE_MAX_PACKET_SIZE USB_FS_MAX_PACKET_SIZE
#endif
#define CDC_TRANSMIT_QUEUE_BUFFER_SIZE ((uint16_t)(CDC_QUEUE_MAX_PACKET_SIZE * 2))
#define CDC_RECEIVE_QUEUE_BUFFER_SIZE ((uint16_t)(CDC_QUEUE_MAX_PACKET_SIZE * 3))
typedef struct {
uint8_t buffer[CDC_TRANSMIT_QUEUE_BUFFER_SIZE];
volatile uint16_t write;
volatile uint16_t read;
volatile uint16_t reserved;
} CDC_TransmitQueue_TypeDef;
typedef struct {
uint8_t buffer[CDC_RECEIVE_QUEUE_BUFFER_SIZE];
volatile uint16_t write;
volatile uint16_t read;
volatile uint16_t length;
} CDC_ReceiveQueue_TypeDef;
void CDC_TransmitQueue_Init(CDC_TransmitQueue_TypeDef* queue);
int CDC_TransmitQueue_WriteSize(CDC_TransmitQueue_TypeDef* queue);
int CDC_TransmitQueue_ReadSize(CDC_TransmitQueue_TypeDef* queue);
void CDC_TransmitQueue_Enqueue(CDC_TransmitQueue_TypeDef* queue, const uint8_t* buffer, uint32_t size);
uint8_t* CDC_TransmitQueue_ReadBlock(CDC_TransmitQueue_TypeDef* queue, uint16_t* size);
void CDC_TransmitQueue_CommitRead(CDC_TransmitQueue_TypeDef *queue);
void CDC_ReceiveQueue_Init(CDC_ReceiveQueue_TypeDef* queue);
int CDC_ReceiveQueue_ReadSize(CDC_ReceiveQueue_TypeDef* queue);
int CDC_ReceiveQueue_Dequeue(CDC_ReceiveQueue_TypeDef* queue);
int CDC_ReceiveQueue_Peek(CDC_ReceiveQueue_TypeDef* queue);
uint16_t CDC_ReceiveQueue_Read(CDC_ReceiveQueue_TypeDef* queue, uint8_t* buffer, uint16_t size);
bool CDC_ReceiveQueue_ReadUntil(CDC_ReceiveQueue_TypeDef* queue, uint8_t terminator, uint8_t* buffer,
uint16_t size, uint16_t* fetched);
uint8_t* CDC_ReceiveQueue_ReserveBlock(CDC_ReceiveQueue_TypeDef* queue);
void CDC_ReceiveQueue_CommitBlock(CDC_ReceiveQueue_TypeDef* queue, uint16_t size);
#ifdef __cplusplus
}
#endif
#endif // __CDC_QUEUE_H
|
maxgerhardt/framework-arduinostm32
|
cores/arduino/stm32/PinAF_STM32F1.h
|
<reponame>maxgerhardt/framework-arduinostm32<filename>cores/arduino/stm32/PinAF_STM32F1.h
/*
*******************************************************************************
* Copyright (c) 2017, STMicroelectronics
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************
*/
#ifndef _PINAF_STM32F1_H
#define _PINAF_STM32F1_H
#ifdef STM32F1xx
#ifdef __cplusplus
extern "C" {
#endif
enum {
AFIO_NONE,
AFIO_SPI1_ENABLE,
AFIO_SPI1_DISABLE,
AFIO_I2C1_ENABLE,
AFIO_I2C1_DISABLE,
AFIO_USART1_ENABLE,
AFIO_USART1_DISABLE,
AFIO_USART2_ENABLE,
AFIO_USART2_DISABLE,
AFIO_USART3_ENABLE,
AFIO_USART3_PARTIAL,
AFIO_USART3_DISABLE,
AFIO_TIM1_ENABLE,
AFIO_TIM1_PARTIAL,
AFIO_TIM1_DISABLE,
AFIO_TIM2_ENABLE,
AFIO_TIM2_PARTIAL_2,
AFIO_TIM2_PARTIAL_1,
AFIO_TIM2_DISABLE,
AFIO_TIM3_ENABLE,
AFIO_TIM3_PARTIAL,
AFIO_TIM3_DISABLE,
AFIO_TIM4_ENABLE,
AFIO_TIM4_DISABLE,
//#if defined(AFIO_MAPR_CAN_REMAP1)
AFIO_CAN1_1,
AFIO_CAN1_2,
AFIO_CAN1_3,
//#endif
AFIO_PD01_ENABLE,
AFIO_PD01_DISABLE,
#if defined(AFIO_MAPR_TIM5CH4_IREMAP)
AFIO_TIM5CH4_ENABLE,
AFIO_TIM5CH4_DISABLE,
#endif
#if defined(AFIO_MAPR_ETH_REMAP)
AFIO_ETH_ENABLE,
AFIO_ETH_DISABLE,
#endif
#if defined(AFIO_MAPR_CAN2_REMAP)
AFIO_CAN2_ENABLE,
AFIO_CAN2_DISABLE,
#endif
#if defined(AFIO_MAPR_MII_RMII_SEL)
AFIO_ETH_RMII,
AFIO_ETH_MII,
#endif
AFIO_ADC1_ETRGINJ_ENABLE,
AFIO_ADC1_ETRGINJ_DISABLE,
AFIO_ADC1_ETRGREG_ENABLE,
AFIO_ADC1_ETRGREG_DISABLE,
#if defined(AFIO_MAPR_ADC2_ETRGINJ_REMAP)
AFIO_ADC2_ETRGINJ_ENABLE,
AFIO_ADC2_ETRGINJ_DISABLE,
#endif
#if defined(AFIO_MAPR_ADC2_ETRGREG_REMAP)
AFIO_ADC2_ETRGREG_ENABLE,
AFIO_ADC2_ETRGREG_DISABLE,
#endif
AFIO_SWJ_ENABLE,
AFIO_SWJ_NONJTRST,
AFIO_SWJ_NOJTAG,
AFIO_SWJ_DISABLE,
#if defined(AFIO_MAPR_SPI3_REMAP)
AFIO_SPI3_ENABLE,
AFIO_SPI3_DISABLE,
#endif
#if defined(AFIO_MAPR_TIM2ITR1_IREMAP)
AFIO_TIM2ITR1_TO_USB,
AFIO_TIM2ITR1_TO_ETH,
#endif
#if defined(AFIO_MAPR_PTP_PPS_REMAP)
AFIO_ETH_PTP_PPS_ENABLE,
AFIO_ETH_PTP_PPS_DISABLE,
#endif
#if defined(AFIO_MAPR2_TIM9_REMAP)
AFIO_TIM9_ENABLE,
AFIO_TIM9_DISABLE,
#endif
#if defined(AFIO_MAPR2_TIM10_REMAP)
AFIO_TIM10_ENABLE,
AFIO_TIM10_DISABLE,
#endif
#if defined(AFIO_MAPR2_TIM11_REMAP)
AFIO_TIM11_ENABLE,
AFIO_TIM11_DISABLE,
#endif
#if defined(AFIO_MAPR2_TIM13_REMAP)
AFIO_TIM13_ENABLE,
AFIO_TIM13_DISABLE,
#endif
#if defined(AFIO_MAPR2_TIM14_REMAP)
AFIO_TIM14_ENABLE,
AFIO_TIM14_DISABLE,
#endif
#if defined(AFIO_MAPR2_FSMC_NADV_REMAP)
AFIO_FSMCNADV_DISCONNECTED,
AFIO_FSMCNADV_CONNECTED,
#endif
#if defined(AFIO_MAPR2_TIM15_REMAP)
AFIO_TIM15_ENABLE,
AFIO_TIM15_DISABLE,
#endif
#if defined(AFIO_MAPR2_TIM16_REMAP)
AFIO_TIM16_ENABLE,
AFIO_TIM16_DISABLE,
#endif
#if defined(AFIO_MAPR2_TIM17_REMAP)
AFIO_TIM17_ENABLE,
AFIO_TIM17_DISABLE,
#endif
#if defined(AFIO_MAPR2_CEC_REMAP)
AFIO_CEC_ENABLE,
AFIO_CEC_DISABLE,
#endif
#if defined(AFIO_MAPR2_TIM1_DMA_REMAP)
AFIO_TIM1DMA_ENABLE,
AFIO_TIM1DMA_DISABLE,
#endif
#if defined(AFIO_MAPR2_TIM67_DAC_DMA_REMAP)
AFIO_TIM67DACDMA_ENABLE,
AFIO_TIM67DACDMA_DISABLE,
#endif
#if defined(AFIO_MAPR2_TIM12_REMAP)
AFIO_TIM12_ENABLE,
AFIO_TIM12_DISABLE,
#endif
#if defined(AFIO_MAPR2_MISC_REMAP)
AFIO_MISC_ENABLE,
AFIO_MISC_DISABLE,
#endif
};
static inline void pinF1_DisconnectDebug(PinName pin)
{
/** Enable this flag gives the possibility to use debug pins without any risk
* to lose traces
*/
#ifndef STM32F1_LOCK_DEBUG
// Enable AFIO clock
__HAL_RCC_AFIO_CLK_ENABLE();
// Disconnect JTAG-DP + SW-DP signals.
// Warning: Need to reconnect under reset
if ((pin == PA_13) || (pin == PA_14)) {
__HAL_AFIO_REMAP_SWJ_DISABLE(); // JTAG-DP Disabled and SW-DP Disabled
}
if ((pin == PA_15) || (pin == PB_3) || (pin == PB_4)) {
__HAL_AFIO_REMAP_SWJ_NOJTAG(); // JTAG-DP Disabled and SW-DP enabled
}
#else
UNUSED(pin);
#endif /* STM32F1_FORCE_DEBUG */
}
static inline void pin_SetF1AFPin(uint32_t afnum)
{
// Enable AFIO clock
__HAL_RCC_AFIO_CLK_ENABLE();
switch (afnum) {
case AFIO_SPI1_ENABLE:
__HAL_AFIO_REMAP_SPI1_ENABLE();
break;
case AFIO_SPI1_DISABLE:
__HAL_AFIO_REMAP_SPI1_DISABLE();
break;
case AFIO_I2C1_ENABLE:
__HAL_AFIO_REMAP_I2C1_ENABLE();
break;
case AFIO_I2C1_DISABLE:
__HAL_AFIO_REMAP_I2C1_DISABLE();
break;
case AFIO_USART1_ENABLE:
__HAL_AFIO_REMAP_USART1_ENABLE();
break;
case AFIO_USART1_DISABLE:
__HAL_AFIO_REMAP_USART1_DISABLE();
break;
case AFIO_USART2_ENABLE:
__HAL_AFIO_REMAP_USART2_ENABLE();
break;
case AFIO_USART2_DISABLE:
__HAL_AFIO_REMAP_USART2_DISABLE();
break;
#if defined(AFIO_MAPR_USART3_REMAP)
case AFIO_USART3_ENABLE:
__HAL_AFIO_REMAP_USART3_ENABLE();
break;
case AFIO_USART3_PARTIAL:
__HAL_AFIO_REMAP_USART3_PARTIAL();
break;
case AFIO_USART3_DISABLE:
__HAL_AFIO_REMAP_USART3_DISABLE();
break;
#endif
case AFIO_TIM1_ENABLE:
__HAL_AFIO_REMAP_TIM1_ENABLE();
break;
case AFIO_TIM1_PARTIAL:
__HAL_AFIO_REMAP_TIM1_PARTIAL();
break;
case AFIO_TIM1_DISABLE:
__HAL_AFIO_REMAP_TIM1_DISABLE();
break;
case AFIO_TIM2_ENABLE:
__HAL_AFIO_REMAP_TIM2_ENABLE();
break;
case AFIO_TIM2_PARTIAL_2:
__HAL_AFIO_REMAP_TIM2_PARTIAL_2();
break;
case AFIO_TIM2_PARTIAL_1:
__HAL_AFIO_REMAP_TIM2_PARTIAL_1();
break;
case AFIO_TIM2_DISABLE:
__HAL_AFIO_REMAP_TIM2_DISABLE();
break;
case AFIO_TIM3_ENABLE:
__HAL_AFIO_REMAP_TIM3_ENABLE();
break;
case AFIO_TIM3_PARTIAL:
__HAL_AFIO_REMAP_TIM3_PARTIAL();
break;
case AFIO_TIM3_DISABLE:
__HAL_AFIO_REMAP_TIM3_DISABLE();
break;
#if defined(AFIO_MAPR_TIM4_REMAP)
case AFIO_TIM4_ENABLE:
__HAL_AFIO_REMAP_TIM4_ENABLE();
break;
case AFIO_TIM4_DISABLE:
__HAL_AFIO_REMAP_TIM4_DISABLE();
break;
#endif
#if defined(AFIO_MAPR_CAN_REMAP1)
case AFIO_CAN1_1:
__HAL_AFIO_REMAP_CAN1_1();
break;
case AFIO_CAN1_2:
__HAL_AFIO_REMAP_CAN1_2();
break;
case AFIO_CAN1_3:
__HAL_AFIO_REMAP_CAN1_3();
break;
#endif
case AFIO_PD01_ENABLE:
__HAL_AFIO_REMAP_PD01_ENABLE();
break;
case AFIO_PD01_DISABLE:
__HAL_AFIO_REMAP_PD01_DISABLE();
break;
#if defined(AFIO_MAPR_TIM5CH4_IREMAP)
case AFIO_TIM5CH4_ENABLE:
__HAL_AFIO_REMAP_TIM5CH4_ENABLE();
break;
case AFIO_TIM5CH4_DISABLE:
__HAL_AFIO_REMAP_TIM5CH4_DISABLE();
break;
#endif
#if defined(AFIO_MAPR_ETH_REMAP)
case AFIO_ETH_ENABLE:
__HAL_AFIO_REMAP_ETH_ENABLE();
break;
case AFIO_ETH_DISABLE:
__HAL_AFIO_REMAP_ETH_DISABLE();
break;
#endif
#if defined(AFIO_MAPR_CAN2_REMAP)
case AFIO_CAN2_ENABLE:
__HAL_AFIO_REMAP_CAN2_ENABLE();
break;
case AFIO_CAN2_DISABLE:
__HAL_AFIO_REMAP_CAN2_DISABLE();
break;
#endif
#if defined(AFIO_MAPR_MII_RMII_SEL)
case AFIO_ETH_RMII:
__HAL_AFIO_ETH_RMII();
break;
case AFIO_ETH_MII:
__HAL_AFIO_ETH_MII();
break;
#endif
#if defined(AFIO_MAPR_ADC1_ETRGINJ_REMAP)
case AFIO_ADC1_ETRGINJ_ENABLE:
__HAL_AFIO_REMAP_ADC1_ETRGINJ_ENABLE();
break;
case AFIO_ADC1_ETRGINJ_DISABLE:
__HAL_AFIO_REMAP_ADC1_ETRGINJ_DISABLE();
break;
#endif
#if defined(AFIO_MAPR_ADC1_ETRGREG_REMAP)
case AFIO_ADC1_ETRGREG_ENABLE:
__HAL_AFIO_REMAP_ADC1_ETRGREG_ENABLE();
break;
case AFIO_ADC1_ETRGREG_DISABLE:
__HAL_AFIO_REMAP_ADC1_ETRGREG_DISABLE();
break;
#endif
#if defined(AFIO_MAPR_ADC2_ETRGINJ_REMAP)
case AFIO_ADC2_ETRGINJ_ENABLE:
__HAL_AFIO_REMAP_ADC2_ETRGINJ_ENABLE();
break;
case AFIO_ADC2_ETRGINJ_DISABLE:
__HAL_AFIO_REMAP_ADC2_ETRGINJ_DISABLE();
break;
#endif
#if defined(AFIO_MAPR_ADC2_ETRGREG_REMAP)
case AFIO_ADC2_ETRGREG_ENABLE:
__HAL_AFIO_REMAP_ADC2_ETRGREG_ENABLE();
break;
case AFIO_ADC2_ETRGREG_DISABLE:
__HAL_AFIO_REMAP_ADC2_ETRGREG_DISABLE();
break;
#endif
case AFIO_SWJ_ENABLE:
__HAL_AFIO_REMAP_SWJ_ENABLE();
break;
case AFIO_SWJ_NONJTRST:
__HAL_AFIO_REMAP_SWJ_NONJTRST();
break;
case AFIO_SWJ_NOJTAG:
__HAL_AFIO_REMAP_SWJ_NOJTAG();
break;
case AFIO_SWJ_DISABLE:
__HAL_AFIO_REMAP_SWJ_DISABLE();
break;
#if defined(AFIO_MAPR_SPI3_REMAP)
case AFIO_SPI3_ENABLE:
__HAL_AFIO_REMAP_SPI3_ENABLE();
break;
case AFIO_SPI3_DISABLE:
__HAL_AFIO_REMAP_SPI3_DISABLE();
break;
#endif
#if defined(AFIO_MAPR_TIM2ITR1_IREMAP)
case AFIO_TIM2ITR1_TO_USB:
__HAL_AFIO_TIM2ITR1_TO_USB();
break;
case AFIO_TIM2ITR1_TO_ETH:
__HAL_AFIO_TIM2ITR1_TO_ETH();
break;
#endif
#if defined(AFIO_MAPR_PTP_PPS_REMAP)
case AFIO_ETH_PTP_PPS_ENABLE:
__HAL_AFIO_ETH_PTP_PPS_ENABLE();
break;
case AFIO_ETH_PTP_PPS_DISABLE:
__HAL_AFIO_ETH_PTP_PPS_DISABLE();
break;
#endif
#if defined(AFIO_MAPR2_TIM9_REMAP)
case AFIO_TIM9_ENABLE:
__HAL_AFIO_REMAP_TIM9_ENABLE();
break;
case AFIO_TIM9_DISABLE:
__HAL_AFIO_REMAP_TIM9_DISABLE();
break;
#endif
#if defined(AFIO_MAPR2_TIM10_REMAP)
case AFIO_TIM10_ENABLE:
__HAL_AFIO_REMAP_TIM10_ENABLE();
break;
case AFIO_TIM10_DISABLE:
__HAL_AFIO_REMAP_TIM10_DISABLE();
break;
#endif
#if defined(AFIO_MAPR2_TIM11_REMAP)
case AFIO_TIM11_ENABLE:
__HAL_AFIO_REMAP_TIM11_ENABLE();
break;
case AFIO_TIM11_DISABLE:
__HAL_AFIO_REMAP_TIM11_DISABLE();
break;
#endif
#if defined(AFIO_MAPR2_TIM13_REMAP)
case AFIO_TIM13_ENABLE:
__HAL_AFIO_REMAP_TIM13_ENABLE();
break;
case AFIO_TIM13_DISABLE:
__HAL_AFIO_REMAP_TIM13_DISABLE();
break;
#endif
#if defined(AFIO_MAPR2_TIM14_REMAP)
case AFIO_TIM14_ENABLE:
__HAL_AFIO_REMAP_TIM14_ENABLE();
break;
case AFIO_TIM14_DISABLE:
__HAL_AFIO_REMAP_TIM14_DISABLE();
break;
#endif
#if defined(AFIO_MAPR2_FSMC_NADV_REMAP)
case AFIO_FSMCNADV_DISCONNECTED:
__HAL_AFIO_FSMCNADV_DISCONNECTED();
break;
case AFIO_FSMCNADV_CONNECTED:
__HAL_AFIO_FSMCNADV_CONNECTED();
break;
#endif
#if defined(AFIO_MAPR2_TIM15_REMAP)
case AFIO_TIM15_ENABLE:
__HAL_AFIO_REMAP_TIM15_ENABLE();
break;
case AFIO_TIM15_DISABLE:
__HAL_AFIO_REMAP_TIM15_DISABLE();
break;
#endif
#if defined(AFIO_MAPR2_TIM16_REMAP)
case AFIO_TIM16_ENABLE:
__HAL_AFIO_REMAP_TIM16_ENABLE();
break;
case AFIO_TIM16_DISABLE:
__HAL_AFIO_REMAP_TIM16_DISABLE();
break;
#endif
#if defined(AFIO_MAPR2_TIM17_REMAP)
case AFIO_TIM17_ENABLE:
__HAL_AFIO_REMAP_TIM17_ENABLE();
break;
case AFIO_TIM17_DISABLE:
__HAL_AFIO_REMAP_TIM17_DISABLE();
break;
#endif
#if defined(AFIO_MAPR2_CEC_REMAP)
case AFIO_CEC_ENABLE:
__HAL_AFIO_REMAP_CEC_ENABLE();
break;
case AFIO_CEC_DISABLE:
__HAL_AFIO_REMAP_CEC_DISABLE();
break;
#endif
#if defined(AFIO_MAPR2_TIM1_DMA_REMAP)
case AFIO_TIM1DMA_ENABLE:
__HAL_AFIO_REMAP_TIM1DMA_ENABLE();
break;
case AFIO_TIM1DMA_DISABLE:
__HAL_AFIO_REMAP_TIM1DMA_DISABLE();
break;
#endif
#if defined(AFIO_MAPR2_TIM67_DAC_DMA_REMAP)
case AFIO_TIM67DACDMA_ENABLE:
__HAL_AFIO_REMAP_TIM67DACDMA_ENABLE();
break;
case AFIO_TIM67DACDMA_DISABLE:
__HAL_AFIO_REMAP_TIM67DACDMA_DISABLE();
break;
#endif
#if defined(AFIO_MAPR2_TIM12_REMAP)
case AFIO_TIM12_ENABLE:
__HAL_AFIO_REMAP_TIM12_ENABLE();
break;
case AFIO_TIM12_DISABLE:
__HAL_AFIO_REMAP_TIM12_DISABLE();
break;
#endif
#if defined(AFIO_MAPR2_MISC_REMAP)
case AFIO_MISC_ENABLE:
__HAL_AFIO_REMAP_MISC_ENABLE();
break;
case AFIO_MISC_DISABLE:
__HAL_AFIO_REMAP_MISC_DISABLE();
break;
#endif
default:
case AFIO_NONE:
break;
}
}
#ifdef __cplusplus
}
#endif
#endif /* STM32F1xx */
#endif /* _PINAF_STM32F1_H */
|
maxgerhardt/framework-arduinostm32
|
variants/FK407M1/variant.h
|
/*
*******************************************************************************
* Copyright (c) 2017, STMicroelectronics
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************
*/
#ifndef _VARIANT_ARDUINO_STM32_
#define _VARIANT_ARDUINO_STM32_
/*----------------------------------------------------------------------------
* Headers
*----------------------------------------------------------------------------*/
#include "PeripheralPins.h"
#ifdef __cplusplus
extern "C"{
#endif // __cplusplus
/*----------------------------------------------------------------------------
* Pins
*----------------------------------------------------------------------------*/
extern const PinName digitalPin[];
// Left Side
#define PD10 0
#define PD11 1
#define PB15 2
#define PD9 3
#define PB12 4
#define PD8 5
#define PB14 6
#define PB11 7
#define PE8 8
#define PB13 9
#define PB10 10
#define PE7 11
#define PE14 12
#define PE15 13
#define PE12 14
#define PE13 15
#define PE11 16
#define PE10 17
#define PE9 18
#define PB1 19
#define PB2 20
#define PC5 21
#define PB0 22
#define PA7 23
#define PC4 24
#define PA6 25
#define PA5 26
#define PA3 27
#define PA4 28
#define PC3 29
#define PA0 30
#define PA2 31
#define PA1 32
#define PD13 33
#define PD14 34
#define PC0 35
#define PC1 36
#define PC2 37
// Right Side
#define PA12 38
#define PA11 39
#define PA10 40
#define PD12 41
#define PC9 42
#define PA9 43
#define PA8 44
#define PC10 45
#define PC11 46
#define PC12 47
#define PD0 48
#define PD1 49
#define PD2 50
#define PD3 51
#define PD4 52
#define PD5 53
#define PB5 54
#define PB4 55
#define PB7 56
#define PB6 57
#define PB9 58
#define PB8 59
#define PE1 60
#define PE0 61
#define PE2 62
#define PE6 63
#define PE3 64
#define PE5 65
#define PB3 66
#define PE4 67
#define PD6 68
#define PD7 69
#define PC7 70
#define PC8 71
#define PD15 72
#define PC6 73
#define PC13 74
#define PA15 75
// This must be a literal
#define NUM_DIGITAL_PINS 92
// This must be a literal with a value less than or equal to MAX_ANALOG_INPUTS
#define NUM_ANALOG_INPUTS 16
#define NUM_ANALOG_FIRST 76
// On-board LED pin number
#define LED_D1 PC13
#define LED_BUILTIN LED_D1
// On-board user button
#define BTN_KEY PA15
#define USER_BTN BTN_KEY
// Below SPI and I2C definitions already done in the core
// Could be redefined here if differs from the default one
// SPI Definitions
#define PIN_SPI_MOSI PB5
#define PIN_SPI_MISO PB4
#define PIN_SPI_SCK PB3
// I2C Definitions
#define PIN_WIRE_SDA PB9
#define PIN_WIRE_SCL PB8
// Timer Definitions
//Do not use timer used by PWM pins when possible. See PinMap_PWM in PeripheralPins.c
#define TIMER_TONE TIM6
// Do not use basic timer: OC is required
#define TIMER_SERVO TIM2 //TODO: advanced-control timers don't work
// UART Definitions
// Define here Serial instance number to map on Serial generic name
#define SERIAL_UART_INSTANCE 1 //ex: 2 for Serial2 (USART2)
// DEBUG_UART could be redefined to print on another instance than 'Serial'
//#define DEBUG_UART ((USART_TypeDef *) U(S)ARTX) // ex: USART3
// DEBUG_UART baudrate, default: 9600 if not defined
//#define DEBUG_UART_BAUDRATE x
// DEBUG_UART Tx pin name, default: the first one found in PinMap_UART_TX for DEBUG_UART
//#define DEBUG_PINNAME_TX PX_n // PinName used for TX
// Default pin used for 'Serial' instance (ex: ST-Link)
// Mandatory for Firmata
#define PIN_SERIAL_RX PA10
#define PIN_SERIAL_TX PA9
#ifdef __cplusplus
} // extern "C"
#endif
/*----------------------------------------------------------------------------
* Arduino objects - C++ only
*----------------------------------------------------------------------------*/
#ifdef __cplusplus
// These serial port names are intended to allow libraries and architecture-neutral
// sketches to automatically default to the correct port name for a particular type
// of use. For example, a GPS module would normally connect to SERIAL_PORT_HARDWARE_OPEN,
// the first hardware serial port whose RX/TX pins are not dedicated to another use.
//
// SERIAL_PORT_MONITOR Port which normally prints to the Arduino Serial Monitor
//
// SERIAL_PORT_USBVIRTUAL Port which is USB virtual serial
//
// SERIAL_PORT_LINUXBRIDGE Port which connects to a Linux system via Bridge library
//
// SERIAL_PORT_HARDWARE Hardware serial port, physical RX & TX pins.
//
// SERIAL_PORT_HARDWARE_OPEN Hardware serial ports which are open for use. Their RX & TX
// pins are NOT connected to anything by default.
#define SERIAL_PORT_MONITOR Serial
#define SERIAL_PORT_HARDWARE Serial1
#endif
#endif /* _VARIANT_ARDUINO_STM32_ */
|
maxgerhardt/framework-arduinostm32
|
system/Middlewares/ST/STM32_USB_Device_Library/Class/AUDIO/Inc/usbd_audio.h
|
<gh_stars>1-10
/**
******************************************************************************
* @file usbd_audio.h
* @author MCD Application Team
* @brief header file for the usbd_audio.c file.
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2015 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* http://www.st.com/SLA0044
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __USB_AUDIO_H
#define __USB_AUDIO_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_ioreq.h"
/** @addtogroup STM32_USB_DEVICE_LIBRARY
* @{
*/
/** @defgroup USBD_AUDIO
* @brief This file is the Header file for usbd_audio.c
* @{
*/
/** @defgroup USBD_AUDIO_Exported_Defines
* @{
*/
#ifndef USBD_AUDIO_FREQ
/* AUDIO Class Config */
#define USBD_AUDIO_FREQ 48000U
#endif /* USBD_AUDIO_FREQ */
#ifndef USBD_MAX_NUM_INTERFACES
#define USBD_MAX_NUM_INTERFACES 1U
#endif /* USBD_AUDIO_FREQ */
#define AUDIO_OUT_EP 0x01U
#define USB_AUDIO_CONFIG_DESC_SIZ 0x6DU
#define AUDIO_INTERFACE_DESC_SIZE 0x09U
#define USB_AUDIO_DESC_SIZ 0x09U
#define AUDIO_STANDARD_ENDPOINT_DESC_SIZE 0x09U
#define AUDIO_STREAMING_ENDPOINT_DESC_SIZE 0x07U
#define AUDIO_DESCRIPTOR_TYPE 0x21U
#define USB_DEVICE_CLASS_AUDIO 0x01U
#define AUDIO_SUBCLASS_AUDIOCONTROL 0x01U
#define AUDIO_SUBCLASS_AUDIOSTREAMING 0x02U
#define AUDIO_PROTOCOL_UNDEFINED 0x00U
#define AUDIO_STREAMING_GENERAL 0x01U
#define AUDIO_STREAMING_FORMAT_TYPE 0x02U
/* Audio Descriptor Types */
#define AUDIO_INTERFACE_DESCRIPTOR_TYPE 0x24U
#define AUDIO_ENDPOINT_DESCRIPTOR_TYPE 0x25U
/* Audio Control Interface Descriptor Subtypes */
#define AUDIO_CONTROL_HEADER 0x01U
#define AUDIO_CONTROL_INPUT_TERMINAL 0x02U
#define AUDIO_CONTROL_OUTPUT_TERMINAL 0x03U
#define AUDIO_CONTROL_FEATURE_UNIT 0x06U
#define AUDIO_INPUT_TERMINAL_DESC_SIZE 0x0CU
#define AUDIO_OUTPUT_TERMINAL_DESC_SIZE 0x09U
#define AUDIO_STREAMING_INTERFACE_DESC_SIZE 0x07U
#define AUDIO_CONTROL_MUTE 0x0001U
#define AUDIO_FORMAT_TYPE_I 0x01U
#define AUDIO_FORMAT_TYPE_III 0x03U
#define AUDIO_ENDPOINT_GENERAL 0x01U
#define AUDIO_REQ_GET_CUR 0x81U
#define AUDIO_REQ_SET_CUR 0x01U
#define AUDIO_OUT_STREAMING_CTRL 0x02U
#define AUDIO_OUT_PACKET (uint16_t)(((USBD_AUDIO_FREQ * 2U * 2U) / 1000U))
#define AUDIO_DEFAULT_VOLUME 70U
/* Number of sub-packets in the audio transfer buffer. You can modify this value but always make sure
that it is an even number and higher than 3 */
#define AUDIO_OUT_PACKET_NUM 80U
/* Total size of the audio transfer buffer */
#define AUDIO_TOTAL_BUF_SIZE ((uint16_t)(AUDIO_OUT_PACKET * AUDIO_OUT_PACKET_NUM))
/* Audio Commands enumeration */
typedef enum
{
AUDIO_CMD_START = 1,
AUDIO_CMD_PLAY,
AUDIO_CMD_STOP,
}AUDIO_CMD_TypeDef;
typedef enum
{
AUDIO_OFFSET_NONE = 0,
AUDIO_OFFSET_HALF,
AUDIO_OFFSET_FULL,
AUDIO_OFFSET_UNKNOWN,
}
AUDIO_OffsetTypeDef;
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_TypesDefinitions
* @{
*/
typedef struct
{
uint8_t cmd;
uint8_t data[USB_MAX_EP0_SIZE];
uint8_t len;
uint8_t unit;
}
USBD_AUDIO_ControlTypeDef;
typedef struct
{
uint32_t alt_setting;
uint8_t buffer[AUDIO_TOTAL_BUF_SIZE];
AUDIO_OffsetTypeDef offset;
uint8_t rd_enable;
uint16_t rd_ptr;
uint16_t wr_ptr;
USBD_AUDIO_ControlTypeDef control;
}
USBD_AUDIO_HandleTypeDef;
typedef struct
{
int8_t (*Init) (uint32_t AudioFreq, uint32_t Volume, uint32_t options);
int8_t (*DeInit) (uint32_t options);
int8_t (*AudioCmd) (uint8_t* pbuf, uint32_t size, uint8_t cmd);
int8_t (*VolumeCtl) (uint8_t vol);
int8_t (*MuteCtl) (uint8_t cmd);
int8_t (*PeriodicTC) (uint8_t cmd);
int8_t (*GetState) (void);
}USBD_AUDIO_ItfTypeDef;
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBD_CORE_Exported_Variables
* @{
*/
extern USBD_ClassTypeDef USBD_AUDIO;
#define USBD_AUDIO_CLASS &USBD_AUDIO
/**
* @}
*/
/** @defgroup USB_CORE_Exported_Functions
* @{
*/
uint8_t USBD_AUDIO_RegisterInterface (USBD_HandleTypeDef *pdev,
USBD_AUDIO_ItfTypeDef *fops);
void USBD_AUDIO_Sync (USBD_HandleTypeDef *pdev, AUDIO_OffsetTypeDef offset);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __USB_AUDIO_H */
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
maxgerhardt/framework-arduinostm32
|
cores/arduino/stm32/usb/cdc/usbd_cdc_if.h
|
/**
******************************************************************************
* @file usbd_cdc_if.h
* @author MCD Application Team
* @brief Header for usbd_cdc_if.c file.
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2015 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* http://www.st.com/SLA0044
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __USBD_CDC_IF_H
#define __USBD_CDC_IF_H
#ifdef USBCON
#ifdef USBD_USE_CDC
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "usbd_cdc.h"
#include "cdc_queue.h"
/* Periodically, the state of the buffer "UserTxBuffer" is checked.
The period depends on CDC_POLLING_INTERVAL */
#define CDC_POLLING_INTERVAL 2 /* in ms. The max is 65 and the min is 1 */
/* Exported types ------------------------------------------------------------*/
/* Exported constants --------------------------------------------------------*/
extern USBD_CDC_ItfTypeDef USBD_CDC_fops;
extern CDC_TransmitQueue_TypeDef TransmitQueue;
extern CDC_ReceiveQueue_TypeDef ReceiveQueue;
/* Exported macro ------------------------------------------------------------*/
/* Exported functions ------------------------------------------------------- */
void CDC_continue_transmit(void);
void CDC_resume_receive(void);
void CDC_init(void);
void CDC_deInit(void);
#ifdef __cplusplus
}
#endif
#endif /* USBD_USE_CDC */
#endif /* USBCON */
#endif /* __USBD_CDC_IF_H */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
maxgerhardt/framework-arduinostm32
|
system/Middlewares/ST/STM32_USB_Host_Library/Class/MSC/Src/usbh_msc_scsi.c
|
/**
******************************************************************************
* @file usbh_msc_scsi.c
* @author MCD Application Team
* @brief This file implements the SCSI commands
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2015 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* http://www.st.com/SLA0044
*
******************************************************************************
*/
/* BSPDependencies
- "stm32xxxxx_{eval}{discovery}{nucleo_144}.c"
- "stm32xxxxx_{eval}{discovery}_io.c"
- "stm32xxxxx_{eval}{discovery}{adafruit}_lcd.c"
- "stm32xxxxx_{eval}{discovery}_sdram.c"
EndBSPDependencies */
/* Includes ------------------------------------------------------------------*/
#include "usbh_msc.h"
#include "usbh_msc_scsi.h"
#include "usbh_msc_bot.h"
/** @addtogroup USBH_LIB
* @{
*/
/** @addtogroup USBH_CLASS
* @{
*/
/** @addtogroup USBH_MSC_CLASS
* @{
*/
/** @defgroup USBH_MSC_SCSI
* @brief This file includes the mass storage related functions
* @{
*/
/** @defgroup USBH_MSC_SCSI_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup USBH_MSC_SCSI_Private_Defines
* @{
*/
/**
* @}
*/
/** @defgroup USBH_MSC_SCSI_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup USBH_MSC_SCSI_Private_FunctionPrototypes
* @{
*/
/**
* @}
*/
/** @defgroup USBH_MSC_SCSI_Exported_Variables
* @{
*/
/**
* @}
*/
/** @defgroup USBH_MSC_SCSI_Private_Functions
* @{
*/
/**
* @brief USBH_MSC_SCSI_TestUnitReady
* Issue TestUnitReady command.
* @param phost: Host handle
* @param lun: Logical Unit Number
* @retval USBH Status
*/
USBH_StatusTypeDef USBH_MSC_SCSI_TestUnitReady (USBH_HandleTypeDef *phost,
uint8_t lun)
{
USBH_StatusTypeDef error = USBH_FAIL ;
MSC_HandleTypeDef *MSC_Handle = (MSC_HandleTypeDef *) phost->pActiveClass->pData;
switch(MSC_Handle->hbot.cmd_state)
{
case BOT_CMD_SEND:
/*Prepare the CBW and relevent field*/
MSC_Handle->hbot.cbw.field.DataTransferLength = DATA_LEN_MODE_TEST_UNIT_READY;
MSC_Handle->hbot.cbw.field.Flags = USB_EP_DIR_OUT;
MSC_Handle->hbot.cbw.field.CBLength = CBW_LENGTH;
USBH_memset(MSC_Handle->hbot.cbw.field.CB, 0, CBW_CB_LENGTH);
MSC_Handle->hbot.cbw.field.CB[0] = OPCODE_TEST_UNIT_READY;
MSC_Handle->hbot.state = BOT_SEND_CBW;
MSC_Handle->hbot.cmd_state = BOT_CMD_WAIT;
error = USBH_BUSY;
break;
case BOT_CMD_WAIT:
error = USBH_MSC_BOT_Process(phost, lun);
break;
default:
break;
}
return error;
}
/**
* @brief USBH_MSC_SCSI_ReadCapacity
* Issue Read Capacity command.
* @param phost: Host handle
* @param lun: Logical Unit Number
* @param capacity: pointer to the capacity structure
* @retval USBH Status
*/
USBH_StatusTypeDef USBH_MSC_SCSI_ReadCapacity (USBH_HandleTypeDef *phost,
uint8_t lun,
SCSI_CapacityTypeDef *capacity)
{
USBH_StatusTypeDef error = USBH_BUSY ;
MSC_HandleTypeDef *MSC_Handle = (MSC_HandleTypeDef *) phost->pActiveClass->pData;
switch(MSC_Handle->hbot.cmd_state)
{
case BOT_CMD_SEND:
/*Prepare the CBW and relevent field*/
MSC_Handle->hbot.cbw.field.DataTransferLength = DATA_LEN_READ_CAPACITY10;
MSC_Handle->hbot.cbw.field.Flags = USB_EP_DIR_IN;
MSC_Handle->hbot.cbw.field.CBLength = CBW_LENGTH;
USBH_memset(MSC_Handle->hbot.cbw.field.CB, 0, CBW_CB_LENGTH);
MSC_Handle->hbot.cbw.field.CB[0] = OPCODE_READ_CAPACITY10;
MSC_Handle->hbot.state = BOT_SEND_CBW;
MSC_Handle->hbot.cmd_state = BOT_CMD_WAIT;
MSC_Handle->hbot.pbuf = (uint8_t *)(void *)MSC_Handle->hbot.data;
error = USBH_BUSY;
break;
case BOT_CMD_WAIT:
error = USBH_MSC_BOT_Process(phost, lun);
if(error == USBH_OK)
{
/*assign the capacity*/
capacity->block_nbr = MSC_Handle->hbot.pbuf[3] | ((uint32_t)MSC_Handle->hbot.pbuf[2] << 8U) |\
((uint32_t)MSC_Handle->hbot.pbuf[1] << 16U) | ((uint32_t)MSC_Handle->hbot.pbuf[0] << 24U);
/*assign the page length*/
capacity->block_size = (uint16_t)(MSC_Handle->hbot.pbuf[7] | ((uint32_t)MSC_Handle->hbot.pbuf[6] << 8U));
}
break;
default:
break;
}
return error;
}
/**
* @brief USBH_MSC_SCSI_Inquiry
* Issue Inquiry command.
* @param phost: Host handle
* @param lun: Logical Unit Number
* @param capacity: pointer to the inquiry structure
* @retval USBH Status
*/
USBH_StatusTypeDef USBH_MSC_SCSI_Inquiry (USBH_HandleTypeDef *phost, uint8_t lun,
SCSI_StdInquiryDataTypeDef *inquiry)
{
USBH_StatusTypeDef error = USBH_FAIL;
MSC_HandleTypeDef *MSC_Handle = (MSC_HandleTypeDef *) phost->pActiveClass->pData;
switch(MSC_Handle->hbot.cmd_state)
{
case BOT_CMD_SEND:
/*Prepare the CBW and relevent field*/
MSC_Handle->hbot.cbw.field.DataTransferLength = DATA_LEN_INQUIRY;
MSC_Handle->hbot.cbw.field.Flags = USB_EP_DIR_IN;
MSC_Handle->hbot.cbw.field.CBLength = CBW_LENGTH;
USBH_memset(MSC_Handle->hbot.cbw.field.CB, 0, CBW_LENGTH);
MSC_Handle->hbot.cbw.field.CB[0] = OPCODE_INQUIRY;
MSC_Handle->hbot.cbw.field.CB[1] = (lun << 5);
MSC_Handle->hbot.cbw.field.CB[2] = 0U;
MSC_Handle->hbot.cbw.field.CB[3] = 0U;
MSC_Handle->hbot.cbw.field.CB[4] = 0x24U;
MSC_Handle->hbot.cbw.field.CB[5] = 0U;
MSC_Handle->hbot.state = BOT_SEND_CBW;
MSC_Handle->hbot.cmd_state = BOT_CMD_WAIT;
MSC_Handle->hbot.pbuf = (uint8_t *)(void *)MSC_Handle->hbot.data;
error = USBH_BUSY;
break;
case BOT_CMD_WAIT:
error = USBH_MSC_BOT_Process(phost, lun);
if(error == USBH_OK)
{
USBH_memset(inquiry, 0, sizeof(SCSI_StdInquiryDataTypeDef));
/*assign Inquiry Data */
inquiry->DeviceType = MSC_Handle->hbot.pbuf[0] & 0x1FU;
inquiry->PeripheralQualifier = MSC_Handle->hbot.pbuf[0] >> 5U;
if (((uint32_t)MSC_Handle->hbot.pbuf[1] & 0x80U) == 0x80U)
{
inquiry->RemovableMedia = 1U;
}
else
{
inquiry->RemovableMedia = 0U;
}
USBH_memcpy (inquiry->vendor_id, &MSC_Handle->hbot.pbuf[8], 8U);
USBH_memcpy (inquiry->product_id, &MSC_Handle->hbot.pbuf[16], 16U);
USBH_memcpy (inquiry->revision_id, &MSC_Handle->hbot.pbuf[32], 4U);
}
break;
default:
break;
}
return error;
}
/**
* @brief USBH_MSC_SCSI_RequestSense
* Issue RequestSense command.
* @param phost: Host handle
* @param lun: Logical Unit Number
* @param capacity: pointer to the sense data structure
* @retval USBH Status
*/
USBH_StatusTypeDef USBH_MSC_SCSI_RequestSense (USBH_HandleTypeDef *phost,
uint8_t lun,
SCSI_SenseTypeDef *sense_data)
{
USBH_StatusTypeDef error = USBH_FAIL ;
MSC_HandleTypeDef *MSC_Handle = (MSC_HandleTypeDef *) phost->pActiveClass->pData;
switch(MSC_Handle->hbot.cmd_state)
{
case BOT_CMD_SEND:
/*Prepare the CBW and relevent field*/
MSC_Handle->hbot.cbw.field.DataTransferLength = DATA_LEN_REQUEST_SENSE;
MSC_Handle->hbot.cbw.field.Flags = USB_EP_DIR_IN;
MSC_Handle->hbot.cbw.field.CBLength = CBW_LENGTH;
USBH_memset(MSC_Handle->hbot.cbw.field.CB, 0, CBW_CB_LENGTH);
MSC_Handle->hbot.cbw.field.CB[0] = OPCODE_REQUEST_SENSE;
MSC_Handle->hbot.cbw.field.CB[1] = (lun << 5);
MSC_Handle->hbot.cbw.field.CB[2] = 0U;
MSC_Handle->hbot.cbw.field.CB[3] = 0U;
MSC_Handle->hbot.cbw.field.CB[4] = DATA_LEN_REQUEST_SENSE;
MSC_Handle->hbot.cbw.field.CB[5] = 0U;
MSC_Handle->hbot.state = BOT_SEND_CBW;
MSC_Handle->hbot.cmd_state = BOT_CMD_WAIT;
MSC_Handle->hbot.pbuf = (uint8_t *)(void *)MSC_Handle->hbot.data;
error = USBH_BUSY;
break;
case BOT_CMD_WAIT:
error = USBH_MSC_BOT_Process(phost, lun);
if(error == USBH_OK)
{
sense_data->key = MSC_Handle->hbot.pbuf[2] & 0x0FU;
sense_data->asc = MSC_Handle->hbot.pbuf[12];
sense_data->ascq = MSC_Handle->hbot.pbuf[13];
}
break;
default:
break;
}
return error;
}
/**
* @brief USBH_MSC_SCSI_Write
* Issue write10 command.
* @param phost: Host handle
* @param lun: Logical Unit Number
* @param address: sector address
* @param pbuf: pointer to data
* @param length: number of sector to write
* @retval USBH Status
*/
USBH_StatusTypeDef USBH_MSC_SCSI_Write(USBH_HandleTypeDef *phost,
uint8_t lun,
uint32_t address,
uint8_t *pbuf,
uint32_t length)
{
USBH_StatusTypeDef error = USBH_FAIL ;
MSC_HandleTypeDef *MSC_Handle = (MSC_HandleTypeDef *) phost->pActiveClass->pData;
switch(MSC_Handle->hbot.cmd_state)
{
case BOT_CMD_SEND:
/*Prepare the CBW and relevent field*/
MSC_Handle->hbot.cbw.field.DataTransferLength = length * MSC_Handle->unit[0].capacity.block_size;
MSC_Handle->hbot.cbw.field.Flags = USB_EP_DIR_OUT;
MSC_Handle->hbot.cbw.field.CBLength = CBW_LENGTH;
USBH_memset(MSC_Handle->hbot.cbw.field.CB, 0, CBW_CB_LENGTH);
MSC_Handle->hbot.cbw.field.CB[0] = OPCODE_WRITE10;
/*logical block address*/
MSC_Handle->hbot.cbw.field.CB[2] = (((uint8_t*)(void *)&address)[3]);
MSC_Handle->hbot.cbw.field.CB[3] = (((uint8_t*)(void *)&address)[2]);
MSC_Handle->hbot.cbw.field.CB[4] = (((uint8_t*)(void *)&address)[1]);
MSC_Handle->hbot.cbw.field.CB[5] = (((uint8_t*)(void *)&address)[0]);
/*Transfer length */
MSC_Handle->hbot.cbw.field.CB[7] = (((uint8_t *)(void *)&length)[1]) ;
MSC_Handle->hbot.cbw.field.CB[8] = (((uint8_t *)(void *)&length)[0]) ;
MSC_Handle->hbot.state = BOT_SEND_CBW;
MSC_Handle->hbot.cmd_state = BOT_CMD_WAIT;
MSC_Handle->hbot.pbuf = pbuf;
error = USBH_BUSY;
break;
case BOT_CMD_WAIT:
error = USBH_MSC_BOT_Process(phost, lun);
break;
default:
break;
}
return error;
}
/**
* @brief USBH_MSC_SCSI_Read
* Issue Read10 command.
* @param phost: Host handle
* @param lun: Logical Unit Number
* @param address: sector address
* @param pbuf: pointer to data
* @param length: number of sector to read
* @retval USBH Status
*/
USBH_StatusTypeDef USBH_MSC_SCSI_Read(USBH_HandleTypeDef *phost,
uint8_t lun,
uint32_t address,
uint8_t *pbuf,
uint32_t length)
{
USBH_StatusTypeDef error = USBH_FAIL ;
MSC_HandleTypeDef *MSC_Handle = (MSC_HandleTypeDef *) phost->pActiveClass->pData;
switch(MSC_Handle->hbot.cmd_state)
{
case BOT_CMD_SEND:
/*Prepare the CBW and relevent field*/
MSC_Handle->hbot.cbw.field.DataTransferLength = length * MSC_Handle->unit[0].capacity.block_size;
MSC_Handle->hbot.cbw.field.Flags = USB_EP_DIR_IN;
MSC_Handle->hbot.cbw.field.CBLength = CBW_LENGTH;
USBH_memset(MSC_Handle->hbot.cbw.field.CB, 0, CBW_CB_LENGTH);
MSC_Handle->hbot.cbw.field.CB[0] = OPCODE_READ10;
/*logical block address*/
MSC_Handle->hbot.cbw.field.CB[2] = (((uint8_t*)(void *)&address)[3]);
MSC_Handle->hbot.cbw.field.CB[3] = (((uint8_t*)(void *)&address)[2]);
MSC_Handle->hbot.cbw.field.CB[4] = (((uint8_t*)(void *)&address)[1]);
MSC_Handle->hbot.cbw.field.CB[5] = (((uint8_t*)(void *)&address)[0]);
/*Transfer length */
MSC_Handle->hbot.cbw.field.CB[7] = (((uint8_t *)(void *)&length)[1]) ;
MSC_Handle->hbot.cbw.field.CB[8] = (((uint8_t *)(void *)&length)[0]) ;
MSC_Handle->hbot.state = BOT_SEND_CBW;
MSC_Handle->hbot.cmd_state = BOT_CMD_WAIT;
MSC_Handle->hbot.pbuf = pbuf;
error = USBH_BUSY;
break;
case BOT_CMD_WAIT:
error = USBH_MSC_BOT_Process(phost, lun);
break;
default:
break;
}
return error;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
maxgerhardt/framework-arduinostm32
|
system/Middlewares/ST/STM32_USB_Device_Library/Class/CustomHID/Src/usbd_customhid_if_template.c
|
/**
******************************************************************************
* @file usbd_customhid_if_template.c
* @author MCD Application Team
* @brief USB Device Custom HID interface file.
* This template should be copied to the user folder, renamed and customized
* following user needs.
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2015 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* http://www.st.com/SLA0044
*
******************************************************************************
*/
/* BSPDependencies
- "stm32xxxxx_{eval}{discovery}{nucleo_144}.c"
- "stm32xxxxx_{eval}{discovery}_io.c"
EndBSPDependencies */
/* Includes ------------------------------------------------------------------*/
#include "usbd_customhid_if_template.h"
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
static int8_t TEMPLATE_CUSTOM_HID_Init (void);
static int8_t TEMPLATE_CUSTOM_HID_DeInit (void);
static int8_t TEMPLATE_CUSTOM_HID_OutEvent (uint8_t event_idx, uint8_t state);
/* Private variables ---------------------------------------------------------*/
USBD_CUSTOM_HID_ItfTypeDef USBD_CustomHID_template_fops =
{
TEMPLATE_CUSTOM_HID_ReportDesc,
TEMPLATE_CUSTOM_HID_Init,
TEMPLATE_CUSTOM_HID_DeInit,
TEMPLATE_CUSTOM_HID_OutEvent,
};
/* Private functions ---------------------------------------------------------*/
/**
* @brief TEMPLATE_CUSTOM_HID_Init
* Initializes the CUSTOM HID media low layer
* @param None
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t TEMPLATE_CUSTOM_HID_Init(void)
{
return (0);
}
/**
* @brief TEMPLATE_CUSTOM_HID_DeInit
* DeInitializes the CUSTOM HID media low layer
* @param None
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t TEMPLATE_CUSTOM_HID_DeInit(void)
{
/*
Add your deinitialization code here
*/
return (0);
}
/**
* @brief TEMPLATE_CUSTOM_HID_Control
* Manage the CUSTOM HID class events
* @param event_idx: event index
* @param state: event state
* @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL
*/
static int8_t TEMPLATE_CUSTOM_HID_OutEvent (uint8_t event_idx, uint8_t state)
{
return (0);
}
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
pavelsevecek/OpenSPH
|
core/system/Profiler.h
|
<gh_stars>10-100
#pragma once
/// \file Profiler.h
/// \brief Tool to measure time spent in functions and profile the code
/// \author <NAME> (sevecek at s<EMAIL>)
/// \date 2016-2021
#include "io/Logger.h"
#include "objects/wrappers/Optional.h"
#include "system/Platform.h"
#include "system/Timer.h"
#include <atomic>
#include <map>
#include <thread>
NAMESPACE_SPH_BEGIN
/// \brief Timer that reports the measured duration when being destroyed.
///
/// If measured scope is executed by multiple thread at once, the total time is equal to the sum of all
/// per-thread times.
struct ScopedTimer {
private:
StoppableTimer impl;
std::string name;
using OnScopeEnds = std::function<void(const std::string&, const uint64_t)>;
OnScopeEnds callback;
public:
/// Creates a scoped time.
/// \param name User-defined name of the timer.
/// \param callback Function called when the timer goes out of scoped. The timer passes its name and
/// elapsed time as parameters of the function.
ScopedTimer(const std::string& name, const OnScopeEnds& callback)
: name(name)
, callback(callback) {}
~ScopedTimer() {
callback(name, impl.elapsed(TimerUnit::MICROSECOND));
}
void stop() {
impl.stop();
}
void resume() {
impl.resume();
}
void next(const std::string& newName) {
callback(name, impl.elapsed(TimerUnit::MICROSECOND));
impl.restart();
name = newName;
}
};
#ifdef SPH_PROFILE
#define MEASURE_SCOPE(name) \
ScopedTimer __timer("", [](const std::string&, const uint64_t time) { \
StdOutLogger logger; \
logger.write(name, " took ", time / 1000, " ms"); \
});
#define MEASURE(name, what) \
{ \
MEASURE_SCOPE(name); \
what; \
}
#else
#define MEASURE_SCOPE(name)
#define MEASURE(name, what) what
#endif
#ifdef SPH_PROFILE
struct ScopeStatistics {
/// User defined name of the scope
std::string name;
/// Time spent in the scope (in ms)
uint64_t totalTime;
/// Relative time spent in the scope with a respect to all measured scopes. Relative times of all measured
/// scoped sum up to 1.
Float relativeTime;
Float cpuUsage;
};
/// Profiler object implemented as singleton.
class Profiler : public Noncopyable {
private:
static AutoPtr<Profiler> instance;
struct ScopeRecord {
/// Total time spent inside the scope
std::atomic<uint64_t> duration{ 0 };
/// Average cpu usage inside the scope
Float cpuUsage = 0._f;
/// Number of samples used to compute the cpu Usage
Size weight = 0;
};
// map of profiled scopes, its key being a string = name of the scope
std::map<std::string, ScopeRecord> records;
struct {
std::string currentScope;
std::thread thread;
} cpuUsage;
std::atomic_bool quitting{ false };
public:
Profiler() {
cpuUsage.thread = std::thread([this] {
while (!quitting) {
const Optional<Float> usage = getCpuUsage();
if (usage && !cpuUsage.currentScope.empty()) {
ScopeRecord& scope = records[cpuUsage.currentScope];
scope.cpuUsage = (scope.cpuUsage * scope.weight + usage.value()) / (scope.weight + 1);
scope.weight++;
}
std::this_thread::sleep_for(std::chrono::milliseconds(20));
}
});
}
~Profiler() {
quitting = true;
cpuUsage.thread.join();
}
static Profiler& getInstance() {
if (!instance) {
instance = makeAuto<Profiler>();
}
return *instance;
}
/// \brief Creates a new scoped timer of given name.
///
/// The timer will automatically adds elapsed time to the profile when being destroyed.
ScopedTimer makeScopedTimer(const std::string& name) {
cpuUsage.currentScope = name;
return ScopedTimer(name, [this](const std::string& n, const uint64_t elapsed) { //
records[n].duration += elapsed;
});
}
/// Returns the array of scope statistics, sorted by elapsed time.
Array<ScopeStatistics> getStatistics() const;
/// Prints statistics into the logger.
void printStatistics(ILogger& logger) const;
/// Clears all records, mainly for testing purposes
void clear() {
records.clear();
}
};
#define PROFILE_SCOPE(name) \
Profiler& __instance = Profiler::getInstance(); \
ScopedTimer __scopedTimer = __instance.makeScopedTimer(name);
#define PROFILE(name, what) \
{ \
PROFILE_SCOPE(name); \
what; \
}
#else
#define PROFILE_SCOPE(name)
#define PROFILE(name, what) what
#endif
NAMESPACE_SPH_END
|
pavelsevecek/OpenSPH
|
gui/objects/Point.h
|
#pragma once
/// \file Point.h
/// \brief Simple 2D vector with integer coordinates. Provides conversion from and to wxPoint.
/// \author <NAME> (sevecek at s<EMAIL>)
/// \date 2016-2021
#include "math/MathUtils.h"
#include "objects/Object.h"
#include "objects/utility/IteratorAdapters.h"
#include <wx/gdicmn.h>
NAMESPACE_SPH_BEGIN
template <typename T, typename TDerived>
struct BasicPoint {
T x, y;
BasicPoint() = default;
BasicPoint(const T x, const T y)
: x(x)
, y(y) {}
T& operator[](const Size index) {
SPH_ASSERT(index < 2);
return reinterpret_cast<T*>(this)[index];
}
const T& operator[](const Size index) const {
SPH_ASSERT(index < 2);
return reinterpret_cast<const T*>(this)[index];
}
TDerived& operator+=(const TDerived& other) {
x += other.x;
y += other.y;
return static_cast<TDerived&>(*this);
}
TDerived& operator-=(const TDerived& other) {
x -= other.x;
y -= other.y;
return static_cast<TDerived&>(*this);
}
TDerived& operator*=(const float factor) {
x = T(x * factor);
y = T(y * factor);
return static_cast<TDerived&>(*this);
}
TDerived& operator/=(const float factor) {
x = T(x / factor);
y = T(y / factor);
return static_cast<TDerived&>(*this);
}
TDerived operator+(const TDerived& other) const {
TDerived result(static_cast<const TDerived&>(*this));
result += other;
return result;
}
TDerived operator-(const TDerived& other) const {
TDerived result(static_cast<const TDerived&>(*this));
result -= other;
return result;
}
TDerived operator*(const float factor) const {
TDerived result(static_cast<const TDerived&>(*this));
result *= factor;
return result;
}
TDerived operator/(const float factor) const {
TDerived result(static_cast<const TDerived&>(*this));
result /= factor;
return result;
}
bool operator==(const TDerived& other) const {
return x == other.x && y == other.y;
}
bool operator!=(const TDerived& other) const {
return !(*this == other);
}
friend std::ostream& operator<<(std::ostream& stream, const BasicPoint& p) {
stream << p.x << " " << p.y;
return stream;
}
friend std::istream& operator>>(std::istream& stream, BasicPoint& p) {
stream >> p.x >> p.y;
return stream;
}
};
struct Pixel : public BasicPoint<int, Pixel> {
Pixel() = default;
Pixel(const int x, const int y)
: BasicPoint<int, Pixel>(x, y) {}
explicit Pixel(const wxPoint point)
: BasicPoint<int, Pixel>(point.x, point.y) {}
explicit operator wxPoint() const {
return wxPoint(this->x, this->y);
}
};
struct Coords : public BasicPoint<float, Coords> {
Coords() = default;
Coords(const float x, const float y)
: BasicPoint<float, Coords>(x, y) {}
explicit Coords(const Pixel p)
: BasicPoint<float, Coords>(p.x, p.y) {}
using BasicPoint<float, Coords>::operator*;
using BasicPoint<float, Coords>::operator/;
Coords operator*(const Coords& other) const {
Coords res = *this;
res.x *= other.x;
res.y *= other.y;
return res;
}
Coords operator/(const Coords& other) const {
Coords res = *this;
SPH_ASSERT(other.x != 0.f && other.y != 0.f);
res.x /= other.x;
res.y /= other.y;
return res;
}
explicit operator Pixel() const {
return Pixel(int(x), int(y));
}
explicit operator wxPoint() const {
return wxPoint(int(x), int(y));
}
};
template <typename T, typename TDerived>
INLINE float getLength(const BasicPoint<T, TDerived>& p) {
return sqrt(float(sqr(p.x) + sqr(p.y)));
}
class Rectangle {
private:
Pixel minBound;
Pixel maxBound;
public:
Rectangle() = default;
Rectangle(const Pixel& lower, const Pixel& upper)
: minBound(lower)
, maxBound(upper) {}
static Rectangle window(const Pixel center, const Size radius) {
return Rectangle(center - Pixel(radius, radius), center + Pixel(radius, radius));
}
Pixel lower() const {
return minBound;
}
Pixel upper() const {
return maxBound;
}
Pixel size() const {
return maxBound - minBound;
}
bool empty() const {
return maxBound.x < minBound.x || maxBound.y < minBound.y;
}
bool contains(const Pixel& p) const {
return p.x >= minBound.x && p.y >= minBound.y && p.x <= maxBound.x && p.y <= maxBound.y;
}
Rectangle intersect(const Rectangle& other) const {
Rectangle is;
is.minBound.x = max(minBound.x, other.minBound.x);
is.minBound.y = max(minBound.y, other.minBound.y);
is.maxBound.x = min(maxBound.x, other.maxBound.x);
is.maxBound.y = min(maxBound.y, other.maxBound.y);
SPH_ASSERT(!is.empty());
return is;
}
IndexSequence colRange() const {
return IndexSequence(minBound.x, maxBound.x);
}
IndexSequence rowRange() const {
return IndexSequence(minBound.y, maxBound.y);
}
};
NAMESPACE_SPH_END
|
pavelsevecek/OpenSPH
|
gui/Factory.h
|
#pragma once
#include "gui/Settings.h"
#include "objects/containers/FlatMap.h"
#include "objects/wrappers/AutoPtr.h"
#include "objects/wrappers/ExtendedEnum.h"
NAMESPACE_SPH_BEGIN
class ICamera;
class IColorizer;
class IRenderer;
class Palette;
struct Pixel;
class Interval;
class ITracker;
class IBrdf;
class IColorMap;
class IScheduler;
class Project;
enum class ColorizerId;
using ExtColorizerId = ExtendedEnum<ColorizerId>;
namespace Factory {
/// Creates a camera
/// \param size Resolution of produced image
AutoPtr<ICamera> getCamera(const GuiSettings& settings, const Pixel size);
AutoPtr<ITracker> getTracker(const GuiSettings& settings);
AutoPtr<IRenderer> getRenderer(const GuiSettings& settings);
AutoPtr<IRenderer> getRenderer(SharedPtr<IScheduler> scheduler, const GuiSettings& settings);
AutoPtr<IBrdf> getBrdf(const GuiSettings& settings);
AutoPtr<IColorMap> getColorMap(const GuiSettings& settings);
AutoPtr<IColorizer> getColorizer(const Project& project, const ExtColorizerId id);
Palette getPalette(const ExtColorizerId id);
} // namespace Factory
NAMESPACE_SPH_END
|
pavelsevecek/OpenSPH
|
core/thread/Tbb.h
|
#pragma once
/// \file Tbb.h
/// \brief Implements IScheduler interface using TBB.
/// \author <NAME> (sevecek at s<EMAIL>)
/// \date 2016-2021
#include "objects/wrappers/PropagateConst.h"
#include "thread/Scheduler.h"
NAMESPACE_SPH_BEGIN
struct TbbData;
/// \brief Scheduler encapsulating Intel Thread Building Blocks (TBB).
///
/// TBB libraries need to be linked in order to use this scheduler.
class Tbb : public IScheduler {
private:
PropagateConst<AutoPtr<TbbData>> data;
static SharedPtr<Tbb> globalInstance;
public:
Tbb(const Size numThreads = 0, const Size granularity = 1000);
~Tbb();
void setGranularity(const Size newGranularity);
void setThreadCnt(const Size numThreads);
virtual SharedPtr<ITask> submit(const Function<void()>& task) override;
virtual Optional<Size> getThreadIdx() const override;
virtual Size getThreadCnt() const override;
virtual Size getRecommendedGranularity() const override;
virtual void parallelFor(const Size from,
const Size to,
const Size granularity,
const Function<void(Size n1, Size n2)>& functor) override;
static SharedPtr<Tbb> getGlobalInstance();
};
NAMESPACE_SPH_END
|
pavelsevecek/OpenSPH
|
core/objects/geometry/Multipole.h
|
#pragma once
#include "objects/containers/StaticArray.h"
#include "objects/geometry/Vector.h"
NAMESPACE_SPH_BEGIN
/// c++14 sort of template parameters
template <Size... Is>
constexpr auto sortIndices() {
constexpr Size N = sizeof...(Is);
ConstexprArray<Size, N> array{ Is... };
for (Size i = 0; i < N - 1; i++) {
for (Size j = 0; j < N - i - 1; j++) {
if (array[j] > array[j + 1]) {
Size k = array[j];
array[j] = array[j + 1];
array[j + 1] = k;
}
}
}
return array;
}
namespace Detail {
constexpr Size multipoleComponentCnt(Size order) {
return (order + 1) * (order + 2) / 2;
}
template <Size Last>
constexpr Size sum() {
return Last;
}
template <Size First, Size Second, Size... Idxs>
constexpr Size sum() {
return First + sum<Second, Idxs...>();
}
template <Size... Idxs>
struct MultipoleMappingImpl;
template <Size Second, Size... Idxs>
struct MultipoleMappingImpl<X, Second, Idxs...> {
static constexpr Size value = MultipoleMappingImpl<Second, Idxs...>::value;
};
template <Size I>
struct MultipoleMappingImpl<I> {
static constexpr Size value = I;
};
template <Size Second, Size... Idxs>
struct MultipoleMappingImpl<Y, Second, Idxs...> {
static constexpr Size value =
multipoleComponentCnt(sizeof...(Idxs) + 1) - 1 - sizeof...(Idxs) + sum<Second, Idxs...>();
};
template <Size Second, Size... Idxs>
struct MultipoleMappingImpl<Z, Second, Idxs...> {
static constexpr Size value = multipoleComponentCnt(sizeof...(Idxs) + 2) - 1;
};
template <std::size_t... Idxs, std::size_t... Is>
constexpr Size expandMultipoleArray(std::index_sequence<Is...>) {
constexpr ConstexprArray<Size, sizeof...(Idxs)> ar = sortIndices<Idxs...>();
return MultipoleMappingImpl<ar[Is]...>::value;
}
template <Size... Idxs>
struct MultipoleMapping {
using Sequence = std::make_index_sequence<sizeof...(Idxs)>;
static constexpr Size value = expandMultipoleArray<Idxs...>(Sequence{});
};
template <Size I>
struct MultipoleMapping<I> {
static constexpr Size value = I;
};
template <>
struct MultipoleMapping<> {
static constexpr Size value = 0;
};
} // namespace Detail
template <Size Order>
class Multipole {
private:
static constexpr Size COMPONENT_CNT = Detail::multipoleComponentCnt(Order);
Float data[COMPONENT_CNT];
public:
static constexpr Size ORDER = Order;
Multipole() = default;
Multipole(const Float f) {
for (Float& v : data) {
v = f;
}
}
template <Size... Idxs>
INLINE Float value() const {
static_assert(sizeof...(Idxs) == Order, "Number of indices must match the order");
const Size idx = Detail::MultipoleMapping<Idxs...>::value;
SPH_ASSERT(idx < COMPONENT_CNT, idx);
return *(&data[0] + idx);
}
template <Size... Idxs>
INLINE Float& value() {
static_assert(sizeof...(Idxs) == Order, "Number of indices must match the order");
const Size idx = Detail::MultipoleMapping<Idxs...>::value;
SPH_ASSERT(idx < COMPONENT_CNT, idx);
return *(&data[0] + idx);
}
INLINE Float operator[](const Size idx) const {
SPH_ASSERT(idx < COMPONENT_CNT, idx);
return data[idx];
}
Multipole& operator+=(const Multipole& other) {
for (Size i = 0; i < COMPONENT_CNT; ++i) {
data[i] += other[i];
}
return *this;
}
Multipole operator*(const Float f) const {
Multipole m;
for (Size i = 0; i < COMPONENT_CNT; ++i) {
m.data[i] = data[i] * f;
}
return m;
}
bool operator==(const Multipole& other) const {
for (Size i = 0; i < COMPONENT_CNT; ++i) {
if (data[i] != other[i]) {
return false;
}
}
return true;
}
friend std::ostream& operator<<(std::ostream& stream, const Multipole& m) {
for (Size i = 0; i < COMPONENT_CNT; ++i) {
stream << m.data[i] << " ";
}
return stream;
}
};
template <Size N>
INLINE auto almostEqual(const Multipole<N>& f1, const Multipole<N>& f2, const Float& eps = EPS) {
for (Size i = 0; i < Detail::multipoleComponentCnt(N); ++i) {
if (!almostEqual(f1[i], f2[i], eps)) {
return false;
}
}
return true;
}
/// Creates multipole by evaluating given object for each independent component
template <Size N>
struct MakeMultipole;
template <>
struct MakeMultipole<0> {
template <typename TValue>
static Multipole<0> make(const TValue& v) {
Multipole<0> m;
m.value() = v.value();
return m;
}
};
template <>
struct MakeMultipole<1> {
template <typename TValue>
static Multipole<1> make(const TValue& v) {
Multipole<1> m;
m.value<X>() = v.template value<X>();
m.value<Y>() = v.template value<Y>();
m.value<Z>() = v.template value<Z>();
return m;
}
};
template <>
struct MakeMultipole<2> {
template <typename TValue>
static Multipole<2> make(const TValue& v) {
Multipole<2> m;
m.value<X, X>() = v.template value<X, X>();
m.value<X, Y>() = v.template value<X, Y>();
m.value<X, Z>() = v.template value<X, Z>();
m.value<Y, Y>() = v.template value<Y, Y>();
m.value<Y, Z>() = v.template value<Y, Z>();
m.value<Z, Z>() = v.template value<Z, Z>();
return m;
}
};
template <>
struct MakeMultipole<3> {
template <typename TValue>
static Multipole<3> make(const TValue& v) {
Multipole<3> m;
m.value<X, X, X>() = v.template value<X, X, X>();
m.value<X, X, Y>() = v.template value<X, X, Y>();
m.value<X, X, Z>() = v.template value<X, X, Z>();
m.value<X, Y, Y>() = v.template value<X, Y, Y>();
m.value<X, Y, Z>() = v.template value<X, Y, Z>();
m.value<X, Z, Z>() = v.template value<X, Z, Z>();
m.value<Y, Y, Y>() = v.template value<Y, Y, Y>();
m.value<Y, Y, Z>() = v.template value<Y, Y, Z>();
m.value<Y, Z, Z>() = v.template value<Y, Z, Z>();
m.value<Z, Z, Z>() = v.template value<Z, Z, Z>();
return m;
}
};
template <>
struct MakeMultipole<4> {
template <typename TValue>
static Multipole<4> make(const TValue& v) {
Multipole<4> m;
m.value<X, X, X, X>() = v.template value<X, X, X, X>();
m.value<X, X, X, Y>() = v.template value<X, X, X, Y>();
m.value<X, X, X, Z>() = v.template value<X, X, X, Z>();
m.value<X, X, Y, Y>() = v.template value<X, X, Y, Y>();
m.value<X, X, Y, Z>() = v.template value<X, X, Y, Z>();
m.value<X, X, Z, Z>() = v.template value<X, X, Z, Z>();
m.value<X, Y, Y, Y>() = v.template value<X, Y, Y, Y>();
m.value<X, Y, Y, Z>() = v.template value<X, Y, Y, Z>();
m.value<X, Y, Z, Z>() = v.template value<X, Y, Z, Z>();
m.value<X, Z, Z, Z>() = v.template value<X, Z, Z, Z>();
m.value<Y, Y, Y, Y>() = v.template value<Y, Y, Y, Y>();
m.value<Y, Y, Y, Z>() = v.template value<Y, Y, Y, Z>();
m.value<Y, Y, Z, Z>() = v.template value<Y, Y, Z, Z>();
m.value<Y, Z, Z, Z>() = v.template value<Y, Z, Z, Z>();
m.value<Z, Z, Z, Z>() = v.template value<Z, Z, Z, Z>();
return m;
}
};
template <Size N, typename TValue>
Multipole<N> makeMultipole(const TValue& v) {
return MakeMultipole<N>::make(v);
}
namespace Detail {
constexpr Size tracelessMultipoleComponentCnt(Size order) {
return 2 * order + 1;
}
template <Size... Idxs>
struct TracelessMultipoleMappingImpl;
template <Size Second, Size... Idxs>
struct TracelessMultipoleMappingImpl<X, Second, Idxs...> {
static constexpr Size value = TracelessMultipoleMappingImpl<Second, Idxs...>::value;
};
template <Size Second, Size... Idxs>
struct TracelessMultipoleMappingImpl<Y, Second, Idxs...> {
static constexpr Size value =
tracelessMultipoleComponentCnt(sizeof...(Idxs) + 1) - 1 - sizeof...(Idxs) + sum<Second, Idxs...>();
};
template <Size I>
struct TracelessMultipoleMappingImpl<I> {
static constexpr Size value = I;
};
template <std::size_t... Idxs, std::size_t... Is>
constexpr Size expandTracelessMultipoleArray(std::index_sequence<Is...>) {
constexpr ConstexprArray<Size, sizeof...(Idxs)> ar = sortIndices<Idxs...>();
return TracelessMultipoleMappingImpl<ar[Is]...>::value;
}
template <Size... Idxs>
struct TracelessMultipoleMapping {
using Sequence = std::make_index_sequence<sizeof...(Idxs)>;
static constexpr Size value = expandTracelessMultipoleArray<Idxs...>(Sequence{});
};
template <Size I>
struct TracelessMultipoleMapping<I> {
static constexpr Size value = I;
};
} // namespace Detail
template <Size... Idxs>
struct TracelessMultipoleComponent;
template <Size Order>
class TracelessMultipole {
private:
static constexpr Size COMPONENT_CNT = Detail::tracelessMultipoleComponentCnt(Order);
Float data[COMPONENT_CNT];
public:
static constexpr Size ORDER = Order;
constexpr TracelessMultipole() = default;
constexpr TracelessMultipole(const Float f) {
for (Float& v : data) {
v = f;
}
}
template <Size... Idxs>
INLINE constexpr Float value() const {
return TracelessMultipoleComponent<Idxs...>{}.get(*this);
}
template <Size... Idxs>
INLINE Float& value() {
static_assert(sizeof...(Idxs) == Order, "Number of indices must match the order");
const Size idx = Detail::TracelessMultipoleMapping<Idxs...>::value;
SPH_ASSERT(idx < COMPONENT_CNT, idx);
return *(&data[0] + idx);
}
template <Size... Idxs>
INLINE constexpr Float valueImpl() const {
static_assert(sizeof...(Idxs) == Order, "Number of indices must match the order");
const Size idx = Detail::TracelessMultipoleMapping<Idxs...>::value;
SPH_ASSERT(idx < COMPONENT_CNT, idx, Idxs...);
return *(&data[0] + idx);
}
INLINE constexpr Float operator[](const Size idx) const {
SPH_ASSERT(idx < COMPONENT_CNT, idx);
return data[idx];
}
INLINE Float& operator[](const Size idx) {
SPH_ASSERT(idx < COMPONENT_CNT, idx);
return data[idx];
}
INLINE constexpr Size size() const {
return COMPONENT_CNT;
}
TracelessMultipole& operator+=(const TracelessMultipole& other) {
for (Size i = 0; i < COMPONENT_CNT; ++i) {
data[i] += other.data[i];
}
return *this;
}
bool operator==(const TracelessMultipole& other) const {
for (Size i = 0; i < COMPONENT_CNT; ++i) {
if (data[i] != other.data[i]) {
return false;
}
}
return true;
}
friend std::ostream& operator<<(std::ostream& stream, const TracelessMultipole& m) {
for (Size i = 0; i < COMPONENT_CNT; ++i) {
stream << m.data[i] << " ";
}
return stream;
}
};
template <>
class TracelessMultipole<1> {
private:
Vector data;
public:
INLINE TracelessMultipole() = default;
INLINE TracelessMultipole(const Float v)
: data(v) {}
static constexpr Size ORDER = 1;
template <Size Idx>
INLINE Float& value() {
return data[Idx];
}
template <Size Idx>
INLINE Float value() const {
return data[Idx];
}
INLINE Float operator[](const Size idx) const {
SPH_ASSERT(idx < 3, idx);
return data[idx];
}
INLINE Float& operator[](const Size idx) {
SPH_ASSERT(idx < 3, idx);
return data[idx];
}
INLINE constexpr Size size() const {
return 3;
}
Vector vector() const {
return data;
}
TracelessMultipole& operator+=(const TracelessMultipole& other) {
data += other.data;
return *this;
}
bool operator==(const TracelessMultipole& other) const {
return data == other.data;
}
friend std::ostream& operator<<(std::ostream& stream, const TracelessMultipole& m) {
stream << m.data;
return stream;
}
};
template <>
class TracelessMultipole<0> {
private:
Float data;
public:
TracelessMultipole() = default;
constexpr INLINE TracelessMultipole(const Float v)
: data(v) {}
static constexpr Size ORDER = 0;
INLINE constexpr Float& value() {
return data;
}
INLINE constexpr Float value() const {
return data;
}
INLINE Float operator[](const Size idx) const {
SPH_ASSERT(idx == 0);
return data;
}
INLINE constexpr Size size() const {
return 1;
}
INLINE constexpr operator Float() const {
return data;
}
TracelessMultipole& operator+=(const TracelessMultipole& other) {
data += other.data;
return *this;
}
constexpr bool operator==(const TracelessMultipole& other) const {
return data == other.data;
}
};
template <Size N>
INLINE auto almostEqual(const TracelessMultipole<N>& f1,
const TracelessMultipole<N>& f2,
const Float& eps = EPS) {
for (Size i = 0; i < Detail::tracelessMultipoleComponentCnt(N); ++i) {
if (!almostEqual(f1[i], f2[i], eps)) {
return false;
}
}
return true;
}
/// Creates multipole by evaluating given object for each independent component
template <Size N>
struct MakeTracelessMultipole;
template <>
struct MakeTracelessMultipole<0> {
template <typename TValue>
static TracelessMultipole<0> make(const TValue& v) {
TracelessMultipole<0> m;
m.value() = v.value();
return m;
}
};
template <>
struct MakeTracelessMultipole<1> {
template <typename TValue>
static TracelessMultipole<1> make(const TValue& v) {
TracelessMultipole<1> m;
m.value<X>() = v.template value<X>();
m.value<Y>() = v.template value<Y>();
m.value<Z>() = v.template value<Z>();
return m;
}
};
template <>
struct MakeTracelessMultipole<2> {
template <typename TValue>
static TracelessMultipole<2> make(const TValue& v) {
TracelessMultipole<2> m;
m.value<X, X>() = v.template value<X, X>();
m.value<X, Y>() = v.template value<X, Y>();
m.value<X, Z>() = v.template value<X, Z>();
m.value<Y, Y>() = v.template value<Y, Y>();
m.value<Y, Z>() = v.template value<Y, Z>();
return m;
}
};
template <>
struct MakeTracelessMultipole<3> {
template <typename TValue>
static TracelessMultipole<3> make(const TValue& v) {
TracelessMultipole<3> m;
m.value<X, X, X>() = v.template value<X, X, X>();
m.value<X, X, Y>() = v.template value<X, X, Y>();
m.value<X, X, Z>() = v.template value<X, X, Z>();
m.value<X, Y, Y>() = v.template value<X, Y, Y>();
m.value<X, Y, Z>() = v.template value<X, Y, Z>();
m.value<Y, Y, Y>() = v.template value<Y, Y, Y>();
m.value<Y, Y, Z>() = v.template value<Y, Y, Z>();
return m;
}
};
template <>
struct MakeTracelessMultipole<4> {
template <typename TValue>
static TracelessMultipole<4> make(const TValue& v) {
TracelessMultipole<4> m;
m.value<X, X, X, X>() = v.template value<X, X, X, X>();
m.value<X, X, X, Y>() = v.template value<X, X, X, Y>();
m.value<X, X, X, Z>() = v.template value<X, X, X, Z>();
m.value<X, X, Y, Y>() = v.template value<X, X, Y, Y>();
m.value<X, X, Y, Z>() = v.template value<X, X, Y, Z>();
m.value<X, Y, Y, Y>() = v.template value<X, Y, Y, Y>();
m.value<X, Y, Y, Z>() = v.template value<X, Y, Y, Z>();
m.value<Y, Y, Y, Y>() = v.template value<Y, Y, Y, Y>();
m.value<Y, Y, Y, Z>() = v.template value<Y, Y, Y, Z>();
return m;
}
};
template <Size N, typename TValue>
TracelessMultipole<N> makeTracelessMultipole(const TValue& v) {
return MakeTracelessMultipole<N>::make(v);
}
template <Size... Idxs>
struct TracelessMultipoleComponentImpl {
INLINE static Float get(const TracelessMultipole<sizeof...(Idxs)>& m) {
return m.template valueImpl<Idxs...>();
}
};
template <std::size_t... Idxs, std::size_t... Is>
constexpr Float expandTracelessMultipoleComponent(const TracelessMultipole<sizeof...(Idxs)>& m,
std::index_sequence<Is...>) {
constexpr ConstexprArray<Size, sizeof...(Idxs)> ar = sortIndices<Idxs...>();
return TracelessMultipoleComponentImpl<ar[Is]...>::get(m);
}
// computes component from traceless multipole
template <Size... Idxs>
struct TracelessMultipoleComponent {
using Sequence = std::make_index_sequence<sizeof...(Idxs)>;
INLINE static constexpr Float get(const TracelessMultipole<sizeof...(Idxs)>& m) {
return expandTracelessMultipoleComponent<Idxs...>(m, Sequence{});
}
};
template <>
struct TracelessMultipoleComponentImpl<Z, Z> {
INLINE static constexpr Float get(const TracelessMultipole<2>& m) {
return -m.valueImpl<X, X>() - m.valueImpl<Y, Y>();
}
};
template <Size I>
struct TracelessMultipoleComponentImpl<I, Z, Z> {
INLINE static constexpr Float get(const TracelessMultipole<3>& m) {
return -m.valueImpl<X, X, I>() - m.valueImpl<Y, Y, I>();
}
};
template <Size I, Size J>
struct TracelessMultipoleComponentImpl<I, J, Z, Z> {
INLINE static constexpr Float get(const TracelessMultipole<4>& m) {
return -m.valueImpl<X, X, I, J>() - m.valueImpl<Y, Y, I, J>();
}
};
inline constexpr Size factorial(const Size n) {
return n <= 1 ? 1 : n * factorial(n - 1);
}
static_assert(factorial(1) == 1, "static test failed");
static_assert(factorial(2) == 2, "static test failed");
static_assert(factorial(3) == 6, "static test failed");
static_assert(factorial(4) == 24, "static test failed");
inline constexpr Size doubleFactorial(const Size n) {
return n <= 1 ? 1 : n * doubleFactorial(n - 2);
}
static_assert(doubleFactorial(1) == 1, "static test failed");
static_assert(doubleFactorial(2) == 2, "static test failed");
static_assert(doubleFactorial(3) == 3, "static test failed");
static_assert(doubleFactorial(4) == 8, "static test failed");
static_assert(doubleFactorial(5) == 15, "static test failed");
namespace MomentOperators {
template <Size Order>
struct Delta {
static constexpr Size ORDER = Order;
template <Size I, Size J, Size K, Size L, Size... Rest>
INLINE static constexpr int value() {
static_assert(sizeof...(Rest) + 4 == Order, "Invalid number of indices");
return ((I == J) ? 1 : 0) * Delta<Order - 2>::template value<K, L, Rest...>();
}
template <Size I, Size J>
INLINE static constexpr int value() {
static_assert(Order == 2, "Invalid number of indices");
return ((I == J) ? 1 : 0);
}
};
template <Size N1, Size N2, typename Value1, typename Value2>
struct Permutations;
template <Size N, typename Value1, typename Value2>
struct Permutations<N, 0, Value1, Value2> {
const Value1& v1;
const Value2& v2;
static constexpr Size ORDER = N;
template <Size... Is>
INLINE constexpr Float value() const {
static_assert(sizeof...(Is) == N, "Invalid number of indices");
return v1.template value<Is...>() * v2.value();
}
};
template <Size N, typename Value1, typename Value2>
struct Permutations<0, N, Value1, Value2> {
const Value1& v1;
const Value2& v2;
static constexpr Size ORDER = N;
template <Size... Is>
INLINE constexpr Float value() const {
static_assert(sizeof...(Is) == N, "Invalid number of indices");
return v1.value() * v2.template value<Is...>();
}
};
template <typename Value1, typename Value2>
struct Permutations<2, 2, Value1, Value2> {
const Value1& v1;
const Value2& v2;
static constexpr Size ORDER = 4;
template <Size I, Size J, Size K, Size L>
INLINE constexpr Float value() const {
return v1.template value<I, J>() * v2.template value<K, L>() +
v1.template value<I, K>() * v2.template value<J, L>() +
v1.template value<I, L>() * v2.template value<J, K>() +
v1.template value<J, K>() * v2.template value<I, L>() +
v1.template value<J, L>() * v2.template value<I, K>() +
v1.template value<K, L>() * v2.template value<I, J>();
}
};
template <typename Value1, typename Value2>
struct Permutations<3, 1, Value1, Value2> {
const Value1& v1;
const Value2& v2;
static constexpr Size ORDER = 4;
template <Size I, Size J, Size K, Size L>
INLINE constexpr Float value() const {
return v1.template value<I, J, K>() * v2.template value<L>() +
v1.template value<I, J, L>() * v2.template value<K>() +
v1.template value<I, K, L>() * v2.template value<J>() +
v1.template value<J, K, L>() * v2.template value<I>();
}
};
template <typename Value1, typename Value2>
struct Permutations<2, 1, Value1, Value2> {
const Value1& v1;
const Value2& v2;
static constexpr Size ORDER = 3;
template <Size I, Size J, Size K>
INLINE constexpr Float value() const {
return v1.template value<I, J>() * v2.template value<K>() +
v1.template value<J, K>() * v2.template value<I>() +
v1.template value<K, I>() * v2.template value<J>();
}
};
template <typename Value1, typename Value2>
struct Permutations<1, 2, Value1, Value2> {
const Value1& v1;
const Value2& v2;
static constexpr Size ORDER = 3;
template <Size I, Size J, Size K>
INLINE constexpr Float value() const {
return v1.template value<I>() * v2.template value<J, K>() +
v1.template value<J>() * v2.template value<K, I>() +
v1.template value<K>() * v2.template value<I, J>();
}
};
template <typename Value1, typename Value2>
Permutations<Value1::ORDER, Value2::ORDER, Value1, Value2> makePermutations(const Value1& v1,
const Value2& v2) {
return Permutations<Value1::ORDER, Value2::ORDER, Value1, Value2>{ v1, v2 };
}
template <typename TValue>
struct Contraction {
const TValue& v;
template <Size... Is>
INLINE constexpr Float value() const {
return v.template value<0, 0, Is...>() + v.template value<1, 1, Is...>() +
v.template value<2, 2, Is...>();
}
};
template <typename TValue>
Contraction<TValue> makeContraction(const TValue& v) {
return Contraction<TValue>{ v };
}
template <Size N, Size O1, typename TValue1, typename TValue2>
struct InnerProduct;
template <typename TValue1, typename TValue2>
struct InnerProduct<1, 2, TValue1, TValue2> {
const TValue1& v1;
const TValue2& v2;
template <Size I, Size... Is>
INLINE constexpr Float value() const {
static_assert(TValue1::ORDER == 2, "Invalid number of indices");
static_assert(TValue2::ORDER == sizeof...(Is) + 1, "Invalid number of indices");
return v1.template value<0, I>() * v2.template value<0, Is...>() +
v1.template value<1, I>() * v2.template value<1, Is...>() +
v1.template value<2, I>() * v2.template value<2, Is...>();
}
};
template <typename TValue1, typename TValue2>
struct InnerProduct<1, 1, TValue1, TValue2> {
const TValue1& v1;
const TValue2& v2;
template <Size... Is>
INLINE constexpr Float value() const {
static_assert(TValue1::ORDER == 1, "Invalid number of indices");
static_assert(TValue2::ORDER == sizeof...(Is) + 1, "Invalid number of indices");
return v1.template value<0>() * v2.template value<0, Is...>() +
v1.template value<1>() * v2.template value<1, Is...>() +
v1.template value<2>() * v2.template value<2, Is...>();
}
};
template <typename TValue1, typename TValue2>
struct InnerProduct<2, 2, TValue1, TValue2> {
const TValue1& v1;
const TValue2& v2;
template <Size... Is>
INLINE constexpr Float value() const {
static_assert(TValue1::ORDER == 2, "Invalid number of indices");
static_assert(TValue2::ORDER == sizeof...(Is) + 2, "Invalid number of indices");
return v1.template value<0, 0>() * v2.template value<0, 0, Is...>() +
v1.template value<0, 1>() * v2.template value<0, 1, Is...>() +
v1.template value<0, 2>() * v2.template value<0, 2, Is...>() +
v1.template value<1, 0>() * v2.template value<1, 0, Is...>() +
v1.template value<1, 1>() * v2.template value<1, 1, Is...>() +
v1.template value<1, 2>() * v2.template value<1, 2, Is...>() +
v1.template value<2, 0>() * v2.template value<2, 0, Is...>() +
v1.template value<2, 1>() * v2.template value<2, 1, Is...>() +
v1.template value<2, 2>() * v2.template value<2, 2, Is...>();
}
};
template <typename TValue1, typename TValue2>
struct InnerProduct<3, 3, TValue1, TValue2> {
const TValue1& v1;
const TValue2& v2;
template <Size... Is>
INLINE constexpr Float value() const {
static_assert(TValue1::ORDER == 3, "Invalid number of indices");
static_assert(TValue2::ORDER == sizeof...(Is) + 3, "Invalid number of indices");
return v1.template value<0, 0, 0>() * v2.template value<0, 0, 0, Is...>() +
v1.template value<0, 0, 1>() * v2.template value<0, 0, 1, Is...>() +
v1.template value<0, 0, 2>() * v2.template value<0, 0, 2, Is...>() +
v1.template value<0, 1, 0>() * v2.template value<0, 1, 0, Is...>() +
v1.template value<0, 1, 1>() * v2.template value<0, 1, 1, Is...>() +
v1.template value<0, 1, 2>() * v2.template value<0, 1, 2, Is...>() +
v1.template value<0, 2, 0>() * v2.template value<0, 2, 0, Is...>() +
v1.template value<0, 2, 1>() * v2.template value<0, 2, 1, Is...>() +
v1.template value<0, 2, 2>() * v2.template value<0, 2, 2, Is...>() +
v1.template value<1, 0, 0>() * v2.template value<1, 0, 0, Is...>() +
v1.template value<1, 0, 1>() * v2.template value<1, 0, 1, Is...>() +
v1.template value<1, 0, 2>() * v2.template value<1, 0, 2, Is...>() +
v1.template value<1, 1, 0>() * v2.template value<1, 1, 0, Is...>() +
v1.template value<1, 1, 1>() * v2.template value<1, 1, 1, Is...>() +
v1.template value<1, 1, 2>() * v2.template value<1, 1, 2, Is...>() +
v1.template value<1, 2, 0>() * v2.template value<1, 2, 0, Is...>() +
v1.template value<1, 2, 1>() * v2.template value<1, 2, 1, Is...>() +
v1.template value<1, 2, 2>() * v2.template value<1, 2, 2, Is...>() +
v1.template value<2, 0, 0>() * v2.template value<2, 0, 0, Is...>() +
v1.template value<2, 0, 1>() * v2.template value<2, 0, 1, Is...>() +
v1.template value<2, 0, 2>() * v2.template value<2, 0, 2, Is...>() +
v1.template value<2, 1, 0>() * v2.template value<2, 1, 0, Is...>() +
v1.template value<2, 1, 1>() * v2.template value<2, 1, 1, Is...>() +
v1.template value<2, 1, 2>() * v2.template value<2, 1, 2, Is...>() +
v1.template value<2, 2, 0>() * v2.template value<2, 2, 0, Is...>() +
v1.template value<2, 2, 1>() * v2.template value<2, 2, 1, Is...>() +
v1.template value<2, 2, 2>() * v2.template value<2, 2, 2, Is...>();
}
};
template <Size N, typename TValue1, typename TValue2>
InnerProduct<N, TValue1::ORDER, TValue1, TValue2> makeInner(const TValue1& v1, const TValue2& v2) {
return InnerProduct<N, TValue1::ORDER, TValue1, TValue2>{ v1, v2 };
}
template <typename TValue>
struct MultiplyByScalar {
const TValue& v;
const Float f;
template <Size... Is>
INLINE constexpr Float value() const {
return f * v.template value<Is...>();
}
};
template <Size O1, typename TValue1, typename TValue2>
struct MultiplyTwo;
template <typename TValue1, typename TValue2>
struct MultiplyTwo<1, TValue1, TValue2> {
const TValue1& v1;
const TValue2& v2;
template <Size I, Size... Is>
INLINE constexpr Float value() const {
static_assert(TValue1::ORDER == 1 && TValue2::ORDER == sizeof...(Is), "Invalid number of indices");
return v1.template value<I>() * v2.template value<Is...>();
}
};
template <typename TValue1, typename TValue2>
struct MultiplyTwo<2, TValue1, TValue2> {
const TValue1& v1;
const TValue2& v2;
template <Size I, Size J, Size... Is>
INLINE constexpr Float value() const {
static_assert(TValue1::ORDER == 2 && TValue2::ORDER == sizeof...(Is), "Invalid number of indices");
return v1.template value<I, J>() * v2.template value<Is...>();
}
};
template <typename TValue1, typename TValue2>
struct MultiplyTwo<4, TValue1, TValue2> {
const TValue1& v1;
const TValue2& v2;
template <Size I, Size J, Size K, Size L, Size... Is>
INLINE constexpr Float value() const {
static_assert(TValue1::ORDER == 4 && TValue2::ORDER == sizeof...(Is), "Invalid number of indices");
return v1.template value<I, J, K, L>() * v2.template value<Is...>();
}
};
template <typename TValue>
MultiplyByScalar<TValue> operator*(const TValue& v, const Float f) {
return MultiplyByScalar<TValue>{ v, f };
}
template <typename TValue1, typename TValue2>
MultiplyTwo<TValue1::ORDER, TValue1, TValue2> makeMultiply(const TValue1& v1, const TValue2& v2) {
return MultiplyTwo<TValue1::ORDER, TValue1, TValue2>{ v1, v2 };
}
template <typename TValue1, typename TValue2>
struct Sum {
const TValue1& v1;
const TValue2& v2;
template <Size... Is>
INLINE constexpr Float value() const {
return v1.template value<Is...>() + v2.template value<Is...>();
}
};
template <typename TValue1, typename TValue2>
Sum<TValue1, TValue2> operator+(const TValue1& v1, const TValue2& v2) {
return Sum<TValue1, TValue2>{ v1, v2 };
}
template <typename TValue1, typename TValue2>
struct Difference {
const TValue1& v1;
const TValue2& v2;
template <Size... Is>
INLINE constexpr Float value() const {
return v1.template value<Is...>() - v2.template value<Is...>();
}
};
template <typename TValue1, typename TValue2>
Difference<TValue1, TValue2> operator-(const TValue1& v1, const TValue2& v2) {
return Difference<TValue1, TValue2>{ v1, v2 };
}
template <Size Order>
struct OuterProduct {
static constexpr Size ORDER = Order;
const Vector& v;
template <Size I, Size J, Size... Is>
INLINE constexpr Float value() const {
static_assert(sizeof...(Is) + 2 == Order, "Invalid number of indices");
return v[I] * OuterProduct<Order - 1>{ v }.template value<J, Is...>();
}
template <Size I>
INLINE constexpr Float value() const {
static_assert(Order == 1, "Invalid number of indices");
return v[I];
}
};
} // namespace MomentOperators
template <Size N>
struct MultipoleExpansion {
TracelessMultipole<N> Qn;
MultipoleExpansion<N - 1> lower;
template <Size M>
INLINE std::enable_if_t<M != N, TracelessMultipole<M>&> order() {
return lower.template order<M>();
}
template <Size M>
INLINE std::enable_if_t<M != N, const TracelessMultipole<M>&> order() const {
return lower.template order<M>();
}
template <Size M>
INLINE std::enable_if_t<M == N, TracelessMultipole<M>&> order() {
return Qn;
}
template <Size M>
INLINE std::enable_if_t<M == N, const TracelessMultipole<M>&> order() const {
return Qn;
}
MultipoleExpansion multiply(const Float factor) const {
MultipoleExpansion m = *this;
m.lower = lower.multiply(factor);
for (Size i = 0; i < Qn.size(); ++i) {
m.Qn[i] *= factor;
}
return m;
}
};
template <>
struct MultipoleExpansion<0> {
TracelessMultipole<0> Qn;
template <Size M>
INLINE TracelessMultipole<0>& order() {
static_assert(M == 0, "Invalid index");
return Qn;
}
template <Size M>
INLINE const TracelessMultipole<0>& order() const {
static_assert(M == 0, "Invalid index");
return Qn;
}
MultipoleExpansion multiply(const Float factor) const {
MultipoleExpansion m = *this;
m.Qn.value() *= factor;
return m;
}
};
/*template <Size M, Size N>
INLINE const TracelessMultipole<M>& getOrder(const MultipoleExpansion<N>& ms) {
return getOrder<M>(ms.lower);
}
template <Size M, Size N>
INLINE TracelessMultipole<M>& getOrder(MultipoleExpansion<N>& ms) {
return getOrder<M>(ms.lower);
}
template <Size M>
INLINE const TracelessMultipole<M>& getOrder(const MultipoleExpansion<M>& ms) {
return ms.Qn;
}
template <Size M>
INLINE TracelessMultipole<M>& getOrder(MultipoleExpansion<M>& ms) {
return ms.Qn;
}*/
/*
template <>
class Multipole<3> {
private:
Vector data[3];
Float components[COMPONENT_CNT];
public:
Multipole() = default;
Multipole(const Multipole& other) = default;
Multipole(const Float value) {
for (Size i = 0; i < COMPONENT_CNT; ++i) {
components[i] = value;
}
}
template <typename... TArgs>
INLINE Float& value()(const Size idx, const TArgs... rest) {
static_assert(sizeof...(T1Args) == Order - 1, "Number of indices must be equal to multipole
order");
SPH_ASSERT(min(rest...) >= idx);
switch (idx) {
case Z:
// other components must be all Zs
return components[COMPONENT_CNT - 1];
}
}
/// Multiplication by scalar
INLINE Multipole operator*(const Float f) const {
return Multipole(data[0] * f, data[1] * f, data[2] * f);
}
/// Inner product with a vector
INLINE Multipole<Order - 1> operator*(const Vector& v) {
return v[0] * data[0] + v[1] * data[1] + v[2] * data[2];
}
template <typename... TArgs>
INLINE Float apply(const Vector& v1, const TArgs&... rest) {
static_assert(sizeof...(TArgs) == Order - 1, "Number of vectors must be equal to multipole
order");
return (*this * v1).apply(rest...);
}
INLINE Multipole operator+(const Multipole& other) {
return Multipole(data[0] + other.data[0], data[1] + other.data[1], data[2] + other.data[2]);
}
INLINE Multipole& operator+=(const Multipole& other) {
data[0] += other.data[0];
data[1] += other.data[1];
data[2] += other.data[2];
return *this;
}
bool operator==(const Multipole& other) const {
return data[0] == other.data[0] && data[1] == other.data[1] && data[2] == other.data[2];
}
friend std::ostream& operator<<(std::ostream& stream, const Multipole& t) {
stream << t.data[0] << std::endl;
stream << t.data[1] << std::endl;
stream << t.data[2] << std::endl << std::endl;
return stream;
}
};
*/
/*
template <>
class Multipole<0> {
private:
Float data;
public:
Multipole() = default;
Multipole(const Multipole& other) = default;
Multipole(const Float& v)
: data(v) {}
INLINE Float& value() {
return data;
}
INLINE const Float& value() const {
return data;
}
INLINE Multipole operator*(const Float f) const ,1{
return data * f;
}
INLINE Multipole operator+(const Multipole& other) {
return data + other.data;
}
INLINE Multipole& operator+=(const Multipole& other) {
data += other.data;
return *this;
}
INLINE bool operator==(const Multipole& other) const {
return data == other.data;
}
friend std::ostream& operator<<(std::ostream& stream, const Multipole& t) {
stream << t.data;
return stream;
}
};
/// Specialization for dipole = vector
template <>
class Multipole<1> {
private:
Vector data;
public:
Multipole() = default;
Multipole(const Multipole& other) = default;
Multipole(const Vector& v)
: data(v) {}
Multipole(const Float m1, const Float m2, const Float m3)
: data{ m1, m2, m3 } {}
Multipole(const Float value)
: data{ value, value, value } {}
INLINE Multipole<0>& operator[](const Size idx) {
SPH_ASSERT(unsigned(idx) < 3);
return (Multipole<0>&)data[idx];
}
INLINE Vector& value() {
return data;
}
INLINE const Vector& value() const {
return data;
}
INLINE Multipole<0> operator[](const Size idx) const {
SPH_ASSERT(unsigned(idx) < 3);
return data[idx];
}
INLINE Float& operator()(const Size idx) {
return data[idx];
}
INLINE Multipole operator*(const Float f) const {
return data * f;
}
INLINE Float operator*(const Vector& v) {
return dot(data, v);
}
INLINE Float apply(const Vector& v) {
return dot(data, v);
}
INLINE Multipole operator+(const Multipole& other) {
return data + other.data;
}
INLINE Multipole& operator+=(const Multipole& other) {
data += other.data;
return *this;
}
INLINE bool operator==(const Multipole& other) const {
return data == other.data;
}
friend std::ostream& operator<<(std::ostream& stream, const Multipole& t) {
stream << t.data;
return stream;
}
};*/
namespace Experimental {
template <Size N>
class MultipoleBase {
protected:
static constexpr Size COMPONENT_CNT = (N + 1) * (N + 2) / 2;
Float data[COMPONENT_CNT];
public:
// inner
};
} // namespace Experimental
NAMESPACE_SPH_END
|
pavelsevecek/OpenSPH
|
core/sph/initial/Stellar.h
|
#pragma once
/// \file Stellar.h
/// \brief Initial conditions of a polytropic star
/// \author <NAME> (sevecek at <EMAIL>)
/// \date 2016-2021
#include "objects/wrappers/Lut.h"
#include "quantities/Storage.h"
NAMESPACE_SPH_BEGIN
class IEos;
namespace Stellar {
/// \brief Solves the Lane-Emden equation given the polytrope index.
Lut<Float> solveLaneEmden(const Float n, const Float dz = 1.e-3_f, const Float z_max = 1.e3_f);
struct Star {
Lut<Float> rho;
Lut<Float> u;
Lut<Float> p;
};
/// \brief Computes radial profiles of state quantities for a polytropic star.
Star polytropicStar(const IEos& eos, const Float radius, const Float mass, const Float n);
/// \brief Creates a spherical polytropic star.
///
/// \param scheduler Scheduler used for parallelization
/// \param material Material containing the equation of state to use.
/// \param distribution Distribution used to generate particles
/// \param particleCnt Number of particles
/// \param radius Radius of the star
/// \param mass Total mass of the star
Storage generateIc(const SharedPtr<IScheduler>& scheduler,
const SharedPtr<IMaterial>& material,
const IDistribution& distribution,
const Size particleCnt,
const Float radius,
const Float mass);
} // namespace Stellar
NAMESPACE_SPH_END
|
pavelsevecek/OpenSPH
|
core/run/jobs/GeometryJobs.h
|
<filename>core/run/jobs/GeometryJobs.h<gh_stars>10-100
#pragma once
#include "run/Job.h"
NAMESPACE_SPH_BEGIN
class SphereJob : public IGeometryJob {
private:
Float radius = 1.e5_f;
public:
explicit SphereJob(const std::string& name);
virtual std::string className() const override;
virtual UnorderedMap<std::string, ExtJobType> getSlots() const override;
virtual VirtualSettings getSettings() override;
virtual void evaluate(const RunSettings& global, IRunCallbacks& callbacks) override;
};
class BlockJob : public IGeometryJob {
private:
Vector center = Vector(0._f);
Vector dimensions = Vector(1.e5_f);
public:
explicit BlockJob(const std::string& name)
: IGeometryJob(name) {}
virtual std::string className() const override {
return "block";
}
virtual UnorderedMap<std::string, ExtJobType> getSlots() const override {
return {};
}
virtual VirtualSettings getSettings() override;
virtual void evaluate(const RunSettings& global, IRunCallbacks& UNUSED(callbacks)) override;
};
class EllipsoidJob : public IGeometryJob {
private:
Vector semiaxes = Vector(2.e5_f, 1.e5_f, 1.e5_f);
public:
explicit EllipsoidJob(const std::string& name)
: IGeometryJob(name) {}
virtual std::string className() const override {
return "ellipsoid";
}
virtual UnorderedMap<std::string, ExtJobType> getSlots() const override {
return {};
}
virtual VirtualSettings getSettings() override;
virtual void evaluate(const RunSettings& global, IRunCallbacks& UNUSED(callbacks)) override;
};
class CylinderJob : public IGeometryJob {
private:
Float radius = 1.e5_f;
Float height = 2.e5_f;
public:
explicit CylinderJob(const std::string& name);
virtual std::string className() const override;
virtual UnorderedMap<std::string, ExtJobType> getSlots() const override;
virtual VirtualSettings getSettings() override;
virtual void evaluate(const RunSettings& global, IRunCallbacks& UNUSED(callbacks)) override;
};
class ToroidJob : public IGeometryJob {
private:
Float a = 1.e5_f;
Float b = 2.5e4_f;
public:
explicit ToroidJob(const std::string& name)
: IGeometryJob(name) {}
virtual std::string className() const override {
return "toroid";
}
virtual UnorderedMap<std::string, ExtJobType> getSlots() const override {
return {};
}
virtual VirtualSettings getSettings() override;
virtual void evaluate(const RunSettings& global, IRunCallbacks& UNUSED(callbacks)) override;
};
class MaclaurinSpheroidJob : public IGeometryJob {
private:
Float semimajorAxis = 1.e5_f;
Float spinRate = 0._f;
Float density = 2700._f;
public:
explicit MaclaurinSpheroidJob(const std::string& name)
: IGeometryJob(name) {}
virtual std::string className() const override {
return "Maclaurin spheroid";
}
virtual UnorderedMap<std::string, ExtJobType> getSlots() const override {
return {};
}
virtual VirtualSettings getSettings() override;
virtual void evaluate(const RunSettings& global, IRunCallbacks& UNUSED(callbacks)) override;
};
class HalfSpaceJob : public IGeometryJob {
public:
explicit HalfSpaceJob(const std::string& name)
: IGeometryJob(name) {}
virtual std::string className() const override {
return "half space";
}
virtual UnorderedMap<std::string, ExtJobType> getSlots() const override {
return {};
}
virtual VirtualSettings getSettings() override;
virtual void evaluate(const RunSettings& global, IRunCallbacks& UNUSED(callbacks)) override;
};
class GaussianSphereJob : public IGeometryJob {
private:
Float radius = 1.e5_f;
Float beta = 0.2_f;
int seed = 1337;
public:
explicit GaussianSphereJob(const std::string& name)
: IGeometryJob(name) {}
virtual std::string className() const override {
return "Gaussian sphere";
}
virtual UnorderedMap<std::string, ExtJobType> getSlots() const override {
return {};
}
virtual VirtualSettings getSettings() override;
virtual void evaluate(const RunSettings& global, IRunCallbacks& UNUSED(callbacks)) override;
};
class MeshGeometryJob : public IGeometryJob {
private:
Path path = Path("file.ply");
Float scale = 1._f;
bool precompute = false;
public:
explicit MeshGeometryJob(const std::string& name);
virtual std::string className() const override;
virtual UnorderedMap<std::string, ExtJobType> getSlots() const override;
virtual VirtualSettings getSettings() override;
virtual void evaluate(const RunSettings& global, IRunCallbacks& callbacks) override;
};
class ParticleGeometryJob : public IGeometryJob {
private:
Float resolution = 1.e3_f;
Float surfaceLevel = 0.15_f;
Float smoothingMult = 1._f;
public:
explicit ParticleGeometryJob(const std::string& name)
: IGeometryJob(name) {}
virtual std::string className() const override {
return "particle geometry";
}
virtual UnorderedMap<std::string, ExtJobType> getSlots() const override {
return { { "particles", JobType::PARTICLES } };
}
virtual VirtualSettings getSettings() override;
virtual void evaluate(const RunSettings& global, IRunCallbacks& callbacks) override;
};
class SpheresGeometryJob : public IGeometryJob {
public:
explicit SpheresGeometryJob(const std::string& name)
: IGeometryJob(name) {}
virtual std::string className() const override {
return "spheres geometry";
}
virtual UnorderedMap<std::string, ExtJobType> getSlots() const override {
return { { "spheres", JobType::PARTICLES } };
}
virtual VirtualSettings getSettings() override;
virtual void evaluate(const RunSettings& global, IRunCallbacks& callbacks) override;
};
class InvertGeometryJob : public IGeometryJob {
public:
explicit InvertGeometryJob(const std::string& name)
: IGeometryJob(name) {}
virtual std::string className() const override {
return "invert geometry";
}
virtual UnorderedMap<std::string, ExtJobType> getSlots() const override {
return { { "geometry", JobType::GEOMETRY } };
}
virtual VirtualSettings getSettings() override;
virtual void evaluate(const RunSettings& global, IRunCallbacks& callbacks) override;
};
class TransformGeometryJob : public IGeometryJob {
private:
Vector scaling = Vector(1._f);
Vector offset = Vector(0._f);
public:
explicit TransformGeometryJob(const std::string& name)
: IGeometryJob(name) {}
virtual std::string className() const override {
return "transform geometry";
}
virtual UnorderedMap<std::string, ExtJobType> getSlots() const override {
return { { "geometry", JobType::GEOMETRY } };
}
virtual VirtualSettings getSettings() override;
virtual void evaluate(const RunSettings& global, IRunCallbacks& callbacks) override;
};
enum class BooleanEnum {
UNION,
DIFFERENCE,
INTERSECTION,
};
static RegisterEnum<BooleanEnum> sBoolean({
{ BooleanEnum::UNION, "union", "union" },
{ BooleanEnum::INTERSECTION, "intersection", "intersection" },
{ BooleanEnum::DIFFERENCE, "difference", "difference" },
});
class BooleanGeometryJob : public IGeometryJob {
EnumWrapper mode;
Vector offset = Vector(0._f);
public:
BooleanGeometryJob(const std::string& name)
: IGeometryJob(name) {
mode = EnumWrapper(BooleanEnum::DIFFERENCE);
}
virtual std::string className() const override {
return "boolean";
}
virtual UnorderedMap<std::string, ExtJobType> getSlots() const override {
return { { "operand A", JobType::GEOMETRY }, { "operand B", JobType::GEOMETRY } };
}
virtual VirtualSettings getSettings() override;
virtual void evaluate(const RunSettings& global, IRunCallbacks& callbacks) override;
};
NAMESPACE_SPH_END
|
pavelsevecek/OpenSPH
|
core/objects/containers/UnorderedMap.h
|
<gh_stars>10-100
#pragma once
/// \file UnorderedMap.h
/// \brief Key-value associative container
/// \author <NAME> (sevecek at s<EMAIL>)
/// \date 2016-2021
#include "objects/containers/Array.h"
#include "objects/wrappers/Optional.h"
NAMESPACE_SPH_BEGIN
template <typename TKey, typename TValue>
class UnorderedMap : public Noncopyable {
public:
/// Element of the container.
struct Element {
TKey key;
TValue value;
};
private:
Array<Element> data;
public:
UnorderedMap() = default;
/// \brief Constructs the map fromm initializer list of elements.
UnorderedMap(std::initializer_list<Element> list)
: data(list) {}
/// \brief Returns a reference to the element, given its key.
///
/// The element must exists in the map, checked by assert.
INLINE TValue& operator[](const TKey& key) {
Element* element = this->find(key);
SPH_ASSERT(element);
return element->value;
}
/// \brief Returns a reference to the element, given its key.
///
/// The element must exists in the map, checked by assert.
INLINE const TValue& operator[](const TKey& key) const {
const Element* element = this->find(key);
SPH_ASSERT(element);
return element->value;
}
/// \brief Adds a new element into the map or sets new value of element with the same key.
INLINE TValue& insert(const TKey& key, const TValue& value) {
Element* element = this->find(key);
if (!element) {
return this->add(key, value);
} else {
element->value = value;
return element->value;
}
}
/// \copydoc insert(const TKey& key, const TValue& value)
INLINE TValue& insert(const TKey& key, TValue&& value) {
Element* element = this->find(key);
if (!element) {
return this->add(key, std::move(value));
} else {
element->value = std::move(value);
return element->value;
}
}
/// \brief Inserts a new element into the given position in the map or sets new value of element with the
/// same key.
INLINE TValue& insert(const TKey& key, const Size position, const TValue& value) {
Element* element = this->find(key);
if (!element) {
return this->add(key, position, value);
} else {
element->value = value;
return element->value;
}
}
/// \copydoc insert(const TKey& key, const Size position, const TValue& value) {
INLINE TValue& insert(const TKey& key, const Size position, TValue&& value) {
Element* element = this->find(key);
if (!element) {
return this->add(key, position, std::move(value));
} else {
element->value = std::move(value);
return element->value;
}
}
/// \brief Removes element with given key from the map.
///
/// The element must exists in the map, checked by assert.
INLINE void remove(const TKey& key) {
Element* element = this->find(key);
SPH_ASSERT(element);
const Size index = element - &data[0];
data.remove(index);
}
/// \brief Removes element with given key if present, otherwise it does nothing.
///
/// \return True if the element was removed, false otherwise.
INLINE bool tryRemove(const TKey& key) {
Element* element = this->find(key);
if (!element) {
return false;
} else {
const Size index = element - &data[0];
data.remove(index);
return true;
}
}
/// \brief Removes all elements from the map.
INLINE void clear() {
data.clear();
}
/// \brief Returns a reference to the value matching the given key, or NOTHING if no such value exists.
///
/// Safe alternative to operator[].
INLINE Optional<TValue&> tryGet(const TKey& key) {
Element* element = this->find(key);
if (!element) {
return NOTHING;
} else {
return element->value;
}
}
/// \brief Returns a reference to the value matching the given key, or NOTHING if no such value exists.
INLINE Optional<const TValue&> tryGet(const TKey& key) const {
const Element* element = this->find(key);
if (!element) {
return NOTHING;
} else {
return element->value;
}
}
/// \brief Returns true if the map contains element of given key.
///
/// Equivalent to bool(tryGet(key)).
INLINE bool contains(const TKey& key) const {
return this->find(key) != nullptr;
}
/// Returns the number of elements in the map.
INLINE Size size() const {
return data.size();
}
/// Returns true if the map contains no elements, false otherwise.
INLINE Size empty() const {
return data.empty();
}
/// \brief Returns the iterator pointing to the first element.
INLINE Iterator<Element> begin() {
return data.begin();
}
/// \brief Returns the iterator pointing to the first element.
INLINE Iterator<const Element> begin() const {
return data.begin();
}
/// \brief Returns the iterator pointing to the one-past-last element.
INLINE Iterator<Element> end() {
return data.end();
}
/// \brief Returns the iterator pointing to the one-past-last element.
INLINE Iterator<const Element> end() const {
return data.end();
}
INLINE operator ArrayView<Element>() {
return data;
}
INLINE operator ArrayView<const Element>() const {
return data;
}
UnorderedMap clone() const {
UnorderedMap cloned;
cloned.data = data.clone();
return cloned;
}
private:
/// Returns a pointer to the element with given key or nullptr if no such element exists.
INLINE Element* find(const TKey& key) {
for (Element& element : data) {
if (element.key == key) {
return &element;
}
}
return nullptr;
}
INLINE const Element* find(const TKey& key) const {
return const_cast<UnorderedMap*>(this)->find(key);
}
/// Adds new element into the map, assuming no element with the same key exists.
template <typename T>
INLINE TValue& add(const TKey& key, T&& value) {
data.push(Element{ key, std::forward<T>(value) });
return data.back().value;
}
/// Inserts new element into given position
template <typename T>
INLINE TValue& add(const TKey& key, const Size position, T&& value) {
data.insert(position, Element{ key, std::forward<T>(value) });
return data.back().value;
}
};
NAMESPACE_SPH_END
|
pavelsevecek/OpenSPH
|
core/objects/finders/KdTree.h
|
#pragma once
/// \file KdTree.h
/// \brief K-d tree for efficient search of neighboring particles.
/// \author <NAME> (sevecek at sirrah.troja.m<EMAIL>))
/// \date 2016-2021
#include "io/Logger.h"
#include "objects/finders/NeighborFinder.h"
#include "objects/geometry/Box.h"
#include "objects/utility/IteratorAdapters.h"
#include "objects/wrappers/Finally.h"
#include "objects/wrappers/Function.h"
#include "objects/wrappers/Outcome.h"
#include "thread/ThreadLocal.h"
#include <set>
#include <shared_mutex>
NAMESPACE_SPH_BEGIN
/// \brief Base class for nodes of K-d tree.
///
/// Can be derived to include additional user data for each node.
struct KdNode : public Noncopyable {
/// Here X, Y, Z must be 0, 1, 2
enum class Type : Size { X, Y, Z, LEAF };
Type type;
/// Bounding box of particles in the node
Box box;
KdNode(const Type& type)
: type(type) {}
INLINE bool isLeaf() const {
return type == Type::LEAF;
}
};
/// \brief Inner node of K-d tree
template <typename TBase>
struct InnerNode : public TBase {
/// Position where the selected dimension is split
float splitPosition;
/// Index of left child node
Size left;
/// Index of right child node
Size right;
InnerNode()
: TBase(KdNode::Type(-1)) {}
InnerNode(const KdNode::Type& type)
: TBase(type) {}
};
/// \brief Leaf (bucket) node of K-d tree
template <typename TBase>
struct LeafNode : public TBase {
/// First index of particlse belonging to the leaf
Size from;
/// One-past-last index of particles belonging to the leaf
Size to;
/// Unused, used so that LeafNode and InnerNode have the same size
Size padding;
LeafNode(const KdNode::Type& type)
: TBase(type) {}
/// Returns the number of points in the leaf. Can be zero.
INLINE Size size() const {
return to - from;
}
};
static_assert(sizeof(Size) == sizeof(float), "Sizes must match to keep this layout");
/// \brief Index iterator with given mapping (index permutation).
///
/// Returns value mapping[index] when dereferenced,
class LeafIndexIterator : public IndexIterator {
private:
ArrayView<const Size> mapping;
public:
INLINE LeafIndexIterator(const Size idx, ArrayView<const Size> mapping)
: IndexIterator(idx)
, mapping(mapping) {}
INLINE Size operator*() const {
return mapping[idx];
}
};
/// \brief Helper index sequence to iterate over particle indices of a leaf node.
class LeafIndexSequence : public IndexSequence {
private:
ArrayView<const Size> mapping;
public:
INLINE LeafIndexSequence(const Size from, const Size to, ArrayView<const Size> mapping)
: IndexSequence(from, to)
, mapping(mapping) {
SPH_ASSERT(to <= mapping.size());
}
INLINE LeafIndexIterator begin() const {
return LeafIndexIterator(from, mapping);
}
INLINE LeafIndexIterator end() const {
return LeafIndexIterator(to, mapping);
}
};
struct EuclideanMetric {
INLINE Float operator()(const Vector& v) const {
return getSqrLength(v);
}
};
enum class KdChild;
/// \brief K-d tree, used for hierarchical clustering of particles and accelerated Kn queries.
///
/// Allows storing arbitrary data at each node of the tree.
///
/// https://www.cs.umd.edu/~mount/Papers/cgc99-smpack.pdf
/// \tparam TNode Nodes of the tree, should always derive from KdNode and should be POD structs.
/// \tparam TMetric Functor returning the squared distance of two vectors.
template <typename TNode, typename TMetric = EuclideanMetric>
class KdTree : public FinderTemplate<KdTree<TNode, TMetric>> {
private:
struct {
/// Maximal number of particles in the leaf node
Size leafSize;
/// Maximal depth for which the build is parallelized
Size maxParallelDepth;
} config;
Box entireBox;
Array<Size> idxs;
/// Holds all nodes, either \ref InnerNode or \ref LeafNode (depending on the value of \ref type).
Array<InnerNode<TNode>> nodes;
std::atomic_int nodeCounter;
std::shared_timed_mutex nodesMutex;
static constexpr Size ROOT_PARENT_NODE = -1;
public:
explicit KdTree(const Size leafSize = 25, const Size maxParallelDepth = 50) {
SPH_ASSERT(leafSize >= 1);
config.leafSize = leafSize;
config.maxParallelDepth = maxParallelDepth;
}
template <bool FindAll>
Size find(const Vector& pos, const Size index, const Float radius, Array<NeighborRecord>& neighs) const;
/// \brief Returns the node with given index
INLINE TNode& getNode(const Size nodeIdx) {
return nodes[nodeIdx];
}
/// \brief Returns the node with given index
INLINE const TNode& getNode(const Size nodeIdx) const {
return nodes[nodeIdx];
}
/// \brief Returns the number of nodes in the tree
INLINE Size getNodeCnt() const {
return nodes.size();
}
/// \brief Returns the sequence of particles indices belonging to given leaf.
INLINE LeafIndexSequence getLeafIndices(const LeafNode<TNode>& leaf) const {
return LeafIndexSequence(leaf.from, leaf.to, idxs);
}
/// \brief Performs some checks of KdTree consistency, returns SUCCESS if everything is OK
Outcome sanityCheck() const;
protected:
virtual void buildImpl(IScheduler& scheduler, ArrayView<const Vector> points) override;
private:
void init();
void buildTree(IScheduler& scheduler,
const Size parent,
const KdChild child,
const Size from,
const Size to,
const Box& box,
const Size slidingCnt,
const Size depth);
void addLeaf(const Size parent, const KdChild child, const Size from, const Size to);
Size addInner(const Size parent, const KdChild child, const Float splitPosition, const Size splitIdx);
bool isSingular(const Size from, const Size to, const Size splitIdx) const;
bool checkBoxes(const Size from, const Size to, const Size mid, const Box& box1, const Box& box2) const;
};
enum class IterateDirection {
TOP_DOWN, ///< From root to leaves
BOTTOM_UP, ///< From leaves to root
};
/// \brief Calls a functor for every node of a K-d tree tree in specified direction.
///
/// The functor is called with the node as a parameter. For top-down direction, functor may return false
/// to skip all children nodes from processing, otherwise the iteration proceedes through the tree into
/// leaf nodes.
/// \param tree KdTree to iterate.
/// \param scheduler Scheduler used for sequential or parallelized task execution
/// \param functor Functor executed for every node
/// \param nodeIdx Index of the first processed node; use 0 for root node
/// \param depthLimit Maximal depth processed in parallel.
template <IterateDirection Dir, typename TNode, typename TMetric, typename TFunctor>
void iterateTree(KdTree<TNode, TMetric>& tree,
IScheduler& scheduler,
const TFunctor& functor,
const Size nodeIdx = 0,
const Size depthLimit = Size(-1));
/// \copydoc iterateTree
template <IterateDirection Dir, typename TNode, typename TMetric, typename TFunctor>
void iterateTree(const KdTree<TNode, TMetric>& tree,
IScheduler& scheduler,
const TFunctor& functor,
const Size nodeIdx = 0,
const Size depthLimit = Size(-1));
NAMESPACE_SPH_END
#include "objects/finders/KdTree.inl.h"
|
pavelsevecek/OpenSPH
|
gui/renderers/ParticleRenderer.h
|
#pragma once
/// \file ParticleRenderer.h
/// \brief Renderer drawing individual particles as dots
/// \author <NAME> (sevecek at s<EMAIL>)
/// \date 2016-2021
#include "gui/Settings.h"
#include "gui/objects/Bitmap.h"
#include "gui/objects/Palette.h"
#include "gui/renderers/IRenderer.h"
#include "system/Timer.h"
#include <atomic>
NAMESPACE_SPH_BEGIN
class IRenderContext;
/// \todo exposed for PaletteDialog, should be possibly generalized, used by other renderers, etc.
void drawPalette(IRenderContext& context,
const Pixel origin,
const Pixel size,
const Rgba& lineColor,
const Palette& palette);
class ParticleRenderer : public IRenderer {
private:
/// Grid size
float grid;
/// Cached values of visible particles, used for faster drawing.
struct {
/// Positions of particles
Array<Vector> positions;
/// Indices (in parent storage) of particles
Array<Size> idxs;
/// Colors of particles assigned by the colorizer
Array<Rgba> colors;
/// Vectors representing the colorized quantity. May be empty.
Array<Vector> vectors;
/// Camera direction for which the cached values have been sorted.
Vector cameraDir;
} cached;
mutable std::atomic_bool shouldContinue;
mutable Timer lastRenderTimer;
public:
explicit ParticleRenderer(const GuiSettings& settings);
virtual void initialize(const Storage& storage,
const IColorizer& colorizer,
const ICamera& camera) override;
virtual bool isInitialized() const override;
virtual void setColorizer(const IColorizer& colorizer) override;
virtual void render(const RenderParams& params, Statistics& stats, IRenderOutput& output) const override;
virtual void cancelRender() override;
};
NAMESPACE_SPH_END
|
pavelsevecek/OpenSPH
|
core/physics/Integrals.h
|
<reponame>pavelsevecek/OpenSPH<filename>core/physics/Integrals.h
#pragma once
/// \file Integrals.h
/// \brief Integrals of motion and other integral quantities
/// \author <NAME> (sevecek at s<EMAIL>)
/// \date 2016-2021
#include "common/ForwardDecl.h"
#include "math/Means.h"
#include "objects/containers/Array.h"
#include "objects/utility/Dynamic.h"
#include "objects/wrappers/Function.h"
#include "quantities/QuantityIds.h"
#include "system/Settings.h"
NAMESPACE_SPH_BEGIN
/// \brief Interface for classes computing integral quantities from storage
///
/// This interface is used to get reduced information from all particles (and possibly all quantities) in the
/// storage. The result is a single value, type of which is given by the template parameter. This is useful to
/// get integrals of motion, as the name suggests, as well as other useful values, like
/// average/minimal/maximal value of given quantity, etc.
///
/// \todo automatically exclude ghost particles?
template <typename Type>
class IIntegral : public Polymorphic {
public:
/// \brief Computes the integral quantity using particles in the storage.
///
/// Storage must contain quantites relevant to the integral implementation. Generally positions, masses
/// and density must be present.
virtual Type evaluate(const Storage& storage) const = 0;
/// \brief Returns the name of the integral.
///
/// Needed to label the integral in logs, GUI etc.
virtual std::string getName() const = 0;
};
/// \brief Computes the total mass of all SPH particles.
///
/// Storage must contains particle masses, of course; checked by assert.
///
/// \note Total mass is always conserved automatically as particles do not change their mass. This is
/// therefore only useful as a sanity check, or potentially when using solver with variable number of
/// particles.
class TotalMass : public IIntegral<Float> {
public:
virtual Float evaluate(const Storage& storage) const override;
virtual std::string getName() const override {
return "Total mass";
}
};
/// \brief Computes total momentum of all SPH particles with a respect to the reference frame.
///
/// Storage must contain at least particle masses and particle positions with velocities, checked by
/// assert.
class TotalMomentum : public IIntegral<Vector> {
private:
Vector omega;
public:
explicit TotalMomentum(const Float omega = 0._f);
virtual Vector evaluate(const Storage& storage) const override;
virtual std::string getName() const override {
return "Total momentum";
}
};
/// \brief Computes total angular momentum of all SPH particles with a respect to the reference frame.
///
/// Storage must contain at least particle masses and particle positions with velocities, checked by
/// assert. If the particles also have nonzero angular velocities, the 'local' angular momenta are added to
/// the total angular momentum.
class TotalAngularMomentum : public IIntegral<Vector> {
private:
Vector frameFrequency;
public:
explicit TotalAngularMomentum(const Float frameFrequency = 0._f);
virtual Vector evaluate(const Storage& storage) const override;
virtual std::string getName() const override {
return "Total angular momentum";
}
};
/// \brief Returns the total kinetic energy of all particles.
///
/// Storage must contain at least particle masses and particle positions with velocities, checked by assert.
/// If the particles also have nonzero angular velocities, the rotational energy is added to the total kinetic
/// energy.
class TotalKineticEnergy : public IIntegral<Float> {
private:
Vector omega;
public:
explicit TotalKineticEnergy(const Float omega = 0._f);
virtual Float evaluate(const Storage& storage) const override;
virtual std::string getName() const override {
return "Kinetic energy";
}
};
/// \brief Returns the total internal energy of all particles.
///
/// Storage must contain at least particle masses and specific internal energy. If used solver works with
/// other independent quantity (energy density, total energy, specific entropy), specific energy must be
/// derived and saved to storage before the function is called.
class TotalInternalEnergy : public IIntegral<Float> {
public:
virtual Float evaluate(const Storage& storage) const override;
virtual std::string getName() const override {
return "Internal energy";
}
};
/// \brief Returns the total energy of all particles.
///
/// This is simply of sum of total kinetic energy and total internal energy.
/// \todo this has to be generalized if some external potential is used.
class TotalEnergy : public IIntegral<Float> {
private:
Vector omega;
public:
explicit TotalEnergy(const Float omega = 0._f);
virtual Float evaluate(const Storage& storage) const override;
virtual std::string getName() const override {
return "Total energy";
}
};
/// \brief Computes the center of mass of particles.
///
/// By default, the center of mass is computed from all particles, optionally only particles belonging to body
/// of given ID are considered. The center is evaluated with a respect to reference frame.
class CenterOfMass : public IIntegral<Vector> {
private:
Optional<Size> bodyId;
public:
explicit CenterOfMass(const Optional<Size> bodyId = NOTHING);
virtual Vector evaluate(const Storage& storage) const override;
virtual std::string getName() const override {
return "Center of mass";
}
};
/// \brief Interface for auxilirary user-defined scalar quantities.
///
/// The quantity values needs to be computed from other quantities already stored in Storage. The class is
/// therefore suitable for quantities such as velocity magnitude, second invariant of stress tensor, etc.
class IUserQuantity : public Polymorphic {
public:
virtual void initialize(const Storage& storage) = 0;
virtual Float evaluate(const Size i) const = 0;
virtual std::string name() const = 0;
};
/// \brief Returns means of given scalar quantity.
///
/// By default means are computed from all particles, optionally only from particles of given body. Storage
/// must contain quantity of given ID, checked by assert.
class QuantityMeans : public IIntegral<MinMaxMean> {
private:
Variant<QuantityId, AutoPtr<IUserQuantity>> quantity;
Optional<Size> bodyId;
public:
/// \brief Computes mean of quantity values.
/// \param id Quantity ID of average quantity
/// \param bodyId Optional body index; by default all particles are averaged.
explicit QuantityMeans(const QuantityId id, const Optional<Size> bodyId = NOTHING);
/// \brief Computes mean of user-defined function.
explicit QuantityMeans(AutoPtr<IUserQuantity>&& func, const Optional<Size> bodyId = NOTHING);
virtual MinMaxMean evaluate(const Storage& storage) const override;
virtual std::string getName() const override {
if (auto id = quantity.tryGet<QuantityId>()) {
return getMetadata(id.value()).quantityName;
} else {
return quantity.get<AutoPtr<IUserQuantity>>()->name();
}
}
};
/// \brief Returns the quantity value of given particle.
///
/// Mainly used for debugging. Currently available only for scalar quantities.
class QuantityValue : public IIntegral<Float> {
private:
QuantityId id;
Size idx;
public:
QuantityValue(const QuantityId id, const Size particleIdx);
virtual Float evaluate(const Storage& storage) const override;
virtual std::string getName() const override {
return getMetadata(id).quantityName + " " + std::to_string(idx);
}
};
/// \brief Helper integral wrapping another integral and converting the returned value to scalar.
///
/// Works as type erasere, allowing to integrals without template parameters, store integrals of different
/// types in one container, etc.
class IntegralWrapper : public IIntegral<Float> {
private:
/// As integrals are templated, we have to put one more indirection to store them
Function<Dynamic(const Storage& storage)> closure;
/// Cached name of the object. This is not optimal, because the name can theorically change, but well ...
std::string name;
public:
IntegralWrapper() = default;
template <typename TIntegral>
IntegralWrapper(AutoPtr<TIntegral>&& integral) {
name = integral->getName();
closure = [i = std::move(integral)](
const Storage& storage) -> Dynamic { return i->evaluate(storage); };
}
virtual Float evaluate(const Storage& storage) const override {
return closure(storage).getScalar();
}
virtual std::string getName() const override {
return name;
}
};
NAMESPACE_SPH_END
|
pavelsevecek/OpenSPH
|
gui/windows/PlotView.h
|
<reponame>pavelsevecek/OpenSPH<filename>gui/windows/PlotView.h
#pragma once
/// \file PlotView.h
/// \brief Drawing of plots
/// \author <NAME> (sevecek at s<EMAIL>)
/// \date 2016-2021
#include "gui/objects/GraphicsContext.h"
#include "gui/objects/Plots.h"
#include "gui/objects/Point.h"
#include "gui/windows/Widgets.h"
#include "physics/Integrals.h"
#include "thread/CheckFunction.h"
#include <wx/frame.h>
#include <wx/panel.h>
class wxBoxSizer;
NAMESPACE_SPH_BEGIN
class PlotPage;
struct TicsParams {
Size minCnt = 6;
Size digits = 3;
};
class PlotView : public wxPanel {
private:
wxSize padding;
SharedPtr<Array<PlotData>> list;
struct {
LockingPtr<IPlot> plot;
Rgba color;
} cached;
Optional<TicsParams> ticsParams;
public:
/// Include zero in x-range
bool addZeroX = false;
/// Include zero in y-range
bool addZeroY = false;
PlotView(wxWindow* parent,
const wxSize size,
const wxSize padding,
const SharedPtr<Array<PlotData>>& list,
const Size defaultSelectedIdx,
Optional<TicsParams> ticsParams);
void resize(const Pixel size);
/// \brief Returns the transformation matrix for managed plot.
AffineMatrix2 getPlotTransformMatrix(const Interval& rangeX, const Interval& rangeY) const;
void drawAxes(wxDC& dc, const Interval rangeX, const Interval rangeY);
private:
void updatePlot(const Size index);
/// Wx handlers
void onRightUp(wxMouseEvent& evt);
void onDoubleClick(wxMouseEvent& evt);
void onMenu(wxCommandEvent& evt);
void onPaint(wxPaintEvent& evt);
/// Helper drawing functions
void drawPlot(wxPaintDC& dc, IPlot& lockedPlot, const Interval rangeX, const Interval rangeY);
void drawCaption(wxDC& dc, IPlot& lockedPlot);
};
class PlotPage : public ClosablePage {
private:
LockingPtr<IPlot> plot;
wxSize padding;
PlotView* plotView;
public:
PlotPage(wxWindow* parent, const wxSize size, const wxSize padding, const LockingPtr<IPlot>& plot);
private:
wxBoxSizer* createToolbar(const Size toolbarHeight);
void saveImage(const Path& path);
void saveData(const Path& path);
virtual bool isRunning() const override {
return false;
}
virtual void stop() override {}
virtual void quit() override {}
};
NAMESPACE_SPH_END
|
pavelsevecek/OpenSPH
|
core/objects/wrappers/AutoPtr.h
|
<filename>core/objects/wrappers/AutoPtr.h
#pragma once
/// \file AutoPtr.h
/// \brief Simplified implementation of std::unique_ptr, using only default deleter.
/// \author <NAME> (sevecek at sirrah.tro<EMAIL>)
/// \date 2016-2021
#include "objects/wrappers/AlignedStorage.h"
#include "objects/wrappers/RawPtr.h"
NAMESPACE_SPH_BEGIN
/// \brief Wrapper of pointer that deletes the resource from destructor.
template <typename T>
class AutoPtr {
template <typename>
friend class AutoPtr;
private:
T* ptr;
public:
INLINE AutoPtr()
: ptr(nullptr) {}
INLINE AutoPtr(std::nullptr_t)
: ptr(nullptr) {}
INLINE explicit AutoPtr(T* ptr)
: ptr(ptr) {}
INLINE AutoPtr(const AutoPtr& other) = delete;
template <typename T2>
INLINE AutoPtr(AutoPtr<T2>&& other)
: ptr(other.ptr) {
other.ptr = nullptr;
}
~AutoPtr() {
this->reset();
}
INLINE AutoPtr& operator=(const AutoPtr& other) = delete;
template <typename T2>
INLINE AutoPtr& operator=(AutoPtr<T2>&& other) {
reset();
ptr = other.ptr;
other.ptr = nullptr;
return *this;
}
INLINE AutoPtr& operator=(std::nullptr_t) {
this->reset();
return *this;
}
INLINE T& operator*() const {
SPH_ASSERT(ptr);
return *ptr;
}
INLINE T* operator->() const {
SPH_ASSERT(ptr);
return ptr;
}
INLINE RawPtr<T> get() const {
return ptr;
}
INLINE explicit operator bool() const {
return ptr != nullptr;
}
INLINE bool operator!() const {
return !ptr;
}
template <typename... TArgs>
INLINE decltype(auto) operator()(TArgs&&... args) const {
SPH_ASSERT(ptr);
return (*ptr)(std::forward<TArgs>(args)...);
}
INLINE void reset() {
alignedDelete(ptr);
ptr = nullptr;
}
INLINE T* release() {
T* resource = ptr;
ptr = nullptr;
return resource;
}
INLINE void swap(AutoPtr& other) {
std::swap(ptr, other.ptr);
}
};
template <typename T>
bool operator==(const AutoPtr<T>& ptr, std::nullptr_t) {
return !ptr;
}
template <typename T>
bool operator==(std::nullptr_t, const AutoPtr<T>& ptr) {
return !ptr;
}
template <typename T>
bool operator!=(const AutoPtr<T>& ptr, std::nullptr_t) {
return bool(ptr);
}
template <typename T>
bool operator!=(std::nullptr_t, const AutoPtr<T>& ptr) {
return bool(ptr);
}
template <typename T, typename... TArgs>
INLINE AutoPtr<T> makeAuto(TArgs&&... args) {
return AutoPtr<T>(alignedNew<T>(std::forward<TArgs>(args)...));
}
/// \brief Performs a dynamic_cast on an AutoPtr, moving the ownership of the resource to the created object.
///
/// If the dynamic type of given pointer is not T1 (or derived from T1), the function return nullptr and the
/// resource remains owned by the input \ref AutoPtr (no move is performed).
template <typename T1, typename T2>
INLINE AutoPtr<T1> dynamicCast(AutoPtr<T2>&& source) {
if (RawPtr<T1> ptr = dynamicCast<T1>(source.get())) {
source.release();
return AutoPtr<T1>(ptr.get());
} else {
return nullptr;
}
}
NAMESPACE_SPH_END
namespace std {
template <typename T>
void swap(Sph::AutoPtr<T>& p1, Sph::AutoPtr<T>& p2) {
p1.swap(p2);
}
} // namespace std
|
pavelsevecek/OpenSPH
|
core/sph/equations/HelperTerms.h
|
#pragma once
/// \file HelperTerms.h
/// \brief Additional equation terms computing SPH statistics rather than physical quantities
/// \author <NAME> (sevecek at s<EMAIL>)
/// \date 2016-2021
#include "io/FileSystem.h"
#include "run/ScriptUtils.h"
#include "sph/equations/DerivativeHelpers.h"
#include "sph/equations/EquationTerm.h"
NAMESPACE_SPH_BEGIN
/// \brief Helper term counting the number of neighbors of each particle.
class NeighborCountTerm : public IEquationTerm {
private:
class Derivative : public DerivativeTemplate<Derivative> {
private:
ArrayView<Size> neighCnts;
public:
explicit Derivative(const RunSettings& settings)
: DerivativeTemplate<Derivative>(settings) {}
INLINE void additionalCreate(Accumulated& results) {
results.insert<Size>(QuantityId::NEIGHBOR_CNT, OrderEnum::ZERO, BufferSource::UNIQUE);
}
INLINE void additionalInitialize(const Storage& UNUSED(input), Accumulated& results) {
neighCnts = results.getBuffer<Size>(QuantityId::NEIGHBOR_CNT, OrderEnum::ZERO);
}
INLINE bool additionalEquals(const Derivative& UNUSED(other)) const {
return true;
}
template <bool Symmetrize>
INLINE void eval(const Size i, const Size j, const Vector& UNUSED(grad)) {
// there is no need to use this in asymmetric solver, since we already know all the neighbors
SPH_ASSERT(Symmetrize);
neighCnts[i]++;
if (Symmetrize) {
neighCnts[j]++;
}
}
};
public:
virtual void setDerivatives(DerivativeHolder& derivatives, const RunSettings& settings) override {
derivatives.require(makeAuto<Derivative>(settings));
}
virtual void initialize(IScheduler& UNUSED(scheduler),
Storage& UNUSED(storage),
const Float UNUSED(t)) override {}
virtual void finalize(IScheduler& UNUSED(scheduler),
Storage& UNUSED(storage),
const Float UNUSED(t)) override {}
virtual void create(Storage& UNUSED(storage), IMaterial& UNUSED(material)) const override {}
};
/// \brief Term computing normals of free surface.
///
/// For particles inside the bodies, this will result to vectors close to zero (depending on the number of
/// neighbors), and the term can be therefore used to detect boundary particles
class SurfaceNormal : public IEquationTerm {
private:
class Derivative : public DerivativeTemplate<Derivative> {
private:
ArrayView<const Vector> r;
ArrayView<Vector> n;
public:
explicit Derivative(const RunSettings& settings)
: DerivativeTemplate<Derivative>(settings) {}
INLINE void additionalCreate(Accumulated& results) {
results.insert<Vector>(QuantityId::SURFACE_NORMAL, OrderEnum::ZERO, BufferSource::UNIQUE);
}
INLINE void additionalInitialize(const Storage& input, Accumulated& results) {
r = input.getValue<Vector>(QuantityId::POSITION);
n = results.getBuffer<Vector>(QuantityId::SURFACE_NORMAL, OrderEnum::ZERO);
}
INLINE bool additionalEquals(const Derivative& UNUSED(other)) const {
return true;
}
template <bool Symmetrize>
INLINE void eval(const Size i, const Size j, const Vector& UNUSED(grad)) {
const Vector dr = (r[j] - r[i]) / (r[i][H] + r[j][H]);
const Float length = getLength(dr);
if (length != 0) {
const Vector normalized = dr / length;
n[i] += normalized;
if (Symmetrize) {
n[j] -= normalized;
}
}
}
};
public:
virtual void setDerivatives(DerivativeHolder& derivatives, const RunSettings& settings) override {
derivatives.require(makeAuto<Derivative>(settings));
}
virtual void initialize(IScheduler& UNUSED(scheduler),
Storage& UNUSED(storage),
const Float UNUSED(t)) override {}
virtual void finalize(IScheduler& UNUSED(scheduler),
Storage& UNUSED(storage),
const Float UNUSED(t)) override {}
virtual void create(Storage& storage, IMaterial& UNUSED(material)) const override {
storage.insert<Vector>(QuantityId::SURFACE_NORMAL, OrderEnum::ZERO, Vector(0._f));
}
};
class ChaiScriptTerm : public IEquationTerm {
private:
std::string script;
Float period;
bool oneShot;
bool done;
Float nextTime;
#ifdef SPH_USE_CHAISCRIPT
Chai::Particles particles;
#endif
public:
explicit ChaiScriptTerm(const Path& scriptFile, const Float period, const bool oneShot)
: period(period)
, oneShot(oneShot) {
nextTime = period;
done = false;
#ifdef SPH_USE_CHAISCRIPT
script = FileSystem::readFile(scriptFile);
#else
(void)scriptFile;
throw InvalidSetup("Code not built with ChaiScript support. Re-build with flag 'use_chaiscript'.");
#endif
}
virtual void setDerivatives(DerivativeHolder& UNUSED(derivatives),
const RunSettings& UNUSED(settings)) override {}
virtual void initialize(IScheduler& UNUSED(scheduler),
Storage& UNUSED(storage),
const Float UNUSED(t)) override {}
virtual void finalize(IScheduler& UNUSED(scheduler), Storage& storage, const Float t) override {
#ifdef SPH_USE_CHAISCRIPT
if (t < nextTime || done) {
return;
}
nextTime += period;
particles.bindToStorage(storage);
chaiscript::ChaiScript chai;
Chai::registerBindings(chai);
chai.add(chaiscript::var(std::ref(particles)), "particles");
chai.add(chaiscript::const_var(t), "time");
chai.eval(script);
particles.store();
if (oneShot) {
done = true;
}
#else
(void)storage;
(void)t;
(void)period;
(void)oneShot;
#endif
}
virtual void create(Storage& UNUSED(storage), IMaterial& UNUSED(material)) const override {}
};
NAMESPACE_SPH_END
|
pavelsevecek/OpenSPH
|
bench/Session.h
|
<filename>bench/Session.h
#pragma once
/// \file Session.h
/// \brief Benchmark
/// \author <NAME> (sevecek at s<EMAIL>)
/// \date 2016-2021
#include "bench/Common.h"
#include "bench/Stats.h"
#include "io/Logger.h"
#include "io/Path.h"
#include "objects/containers/Array.h"
#include "objects/utility/StringUtils.h"
#include "objects/wrappers/Expected.h"
#include "objects/wrappers/Outcome.h"
#include "objects/wrappers/SharedPtr.h"
#include "system/Timer.h"
#include <fstream>
#include <map>
NAMESPACE_BENCHMARK_BEGIN
/// Benchmark mode
enum class Mode {
SIMPLE, ///< Just run benchmarks and report statistics
MAKE_BASELINE, ///< Store iteration numbers to baseline file
RUN_AGAINST_BASELINE, ///< Compare iteration numbers with recorded baseline
};
struct Target {
Mode mode;
uint64_t duration;
Size iterateCnt;
};
struct Result {
uint64_t duration;
Size iterateCnt;
Float mean;
Float variance;
Float min;
Float max;
};
/// Accessible from benchmarks
class Context {
private:
Target target;
bool state = true;
Size iterateCnt = 0;
Timer timer;
Timer iterationTimer;
Stats stats;
/// Name of the running benchmark
std::string name;
public:
Context(const Target target, const std::string& name)
: target(target)
, timer(target.duration)
, name(name) {}
/// Whether to keep running or exit
INLINE bool running() {
state = this->shouldContinue();
if (iterateCnt <= 2) {
// restart to discard benchmark setup time and first few iterations (startup)
timer.restart();
} else {
stats.add(1.e-3_f * iterationTimer.elapsed(TimerUnit::MICROSECOND));
}
iterationTimer.restart();
iterateCnt++;
return state;
}
INLINE uint64_t elapsed() const {
return timer.elapsed(TimerUnit::MILLISECOND);
}
INLINE Size iterationCnt() const {
return iterateCnt;
}
INLINE Stats getStats() const {
return stats;
}
/// Writes given message into the logger
template <typename... TArgs>
INLINE void log(TArgs&&... args) {
StdOutLogger logger;
logger.write(std::forward<TArgs>(args)...);
}
private:
INLINE bool shouldContinue() const {
switch (target.mode) {
case Mode::SIMPLE:
case Mode::MAKE_BASELINE:
// either not enough time passed, or not enough iterations
return iterateCnt < target.iterateCnt || !timer.isExpired();
case Mode::RUN_AGAINST_BASELINE:
return iterateCnt < target.iterateCnt;
default:
NOT_IMPLEMENTED;
}
}
};
/// Single benchmark unit
class Unit {
private:
std::string name;
using Function = void (*)(Context&);
Function function;
public:
Unit(const std::string& name, const Function func)
: name(name)
, function(func) {
SPH_ASSERT(function != nullptr);
}
const std::string& getName() const {
return name;
}
Expected<Result> run(const Target target) {
Context context(target, name);
function(context);
uint64_t elapsed = context.elapsed();
Stats stats = context.getStats();
return Result{
elapsed, context.iterationCnt() - 1, stats.mean(), stats.variance(), stats.min(), stats.max()
};
}
};
class Group {
private:
std::string name;
Array<SharedPtr<Unit>> benchmarks;
public:
Group() = default;
Group(const std::string& name)
: name(name) {}
const std::string& getName() const {
return name;
}
void addBenchmark(const SharedPtr<Unit>& benchmark) {
benchmarks.push(benchmark);
}
auto begin() const {
return benchmarks.begin();
}
auto end() const {
return benchmarks.end();
}
Size size() const {
return benchmarks.size();
}
};
template <class T>
INLINE T&& doNotOptimize(T&& value) {
#if defined(__clang__)
asm volatile("" : : "g"(value) : "memory");
#else
asm volatile("" : : "i,r,m"(value) : "memory");
#endif
return std::forward<T>(value);
}
// Force the compiler to flush pending writes to global memory. Acts as an effective read/write barrier
INLINE void clobberMemory() {
asm volatile("" : : : "memory");
}
class Baseline {
private:
std::map<std::string, Result> benchs;
public:
Baseline() = default;
bool parse(const Path& path) {
benchs.clear();
std::ifstream ifs(path.native());
std::string line;
while (std::getline(ifs, line)) {
std::size_t n = line.find_last_of('/');
if (n == std::string::npos) {
return false;
}
const std::string name = trim(line.substr(0, n));
Array<std::string> values = split(line.substr(n + 1), ',');
if (values.size() != 6) {
return false;
}
Result result;
result.duration = std::stoi(values[0]);
result.iterateCnt = std::stoi(values[1]);
result.mean = std::stof(values[2]);
result.variance = std::stof(values[3]);
result.min = std::stof(values[4]);
result.max = std::stof(values[5]);
benchs[name] = result;
}
return true;
}
bool isRecorded(const std::string& name) {
return benchs.find(name) != benchs.end();
}
INLINE Result operator[](const std::string& name) {
return benchs[name];
}
};
class Session {
private:
/// Global instance of the session
static AutoPtr<Session> instance;
/// List of all benchmarks in the session
Array<SharedPtr<Unit>> benchmarks;
/// Benchmark groups
Array<Group> groups;
/// Logger used to output benchmark results
AutoPtr<ILogger> logger;
/// Status of the session, contains an error if the session is in invalid state.
Outcome status = SUCCESS;
enum class Flag {
RUN_AGAINST_BASELINE = 1 << 0, ///< Compare results with baseline
MAKE_BASELINE = 1 << 1, ///< Record and cache baseline
SILENT = 1 << 2, ///< Only print failed benchmarks
};
struct {
/// Run only selected group of benchmarks
std::string group;
Flags<Flag> flags;
struct {
Path path;
Size commit = 0;
} baseline;
Array<std::string> benchmarksToRun;
Target target{ Mode::SIMPLE, 500 /*ms*/, 10 };
Float confidence = 6._f; // sigma
/// Maximum allowed duration of single benchmark unit; benchmarks running longer that that will
/// generate a warning.
uint64_t maxAllowedDuration = 5000 /*ms*/;
} params;
public:
Session();
static Session& getInstance();
/// Adds a new benchmark into the session.
void registerBenchmark(const SharedPtr<Unit>& benchmark, const std::string& groupName);
/// Runs all benchmarks.
void run(int argc, char* argv[]);
~Session();
private:
Group& getGroupByName(const std::string& groupName);
Outcome parseArgs(int arcs, char* argv[]);
void printHelp();
void writeBaseline(const std::string& name, const Result& measured);
Path getBaselinePath();
void compareResults(const Result& measured, const Result& baseline);
template <typename... TArgs>
void log(TArgs&&... args);
template <typename... TArgs>
void logError(TArgs&&... args);
};
/// \todo param, warning for too fast/too slow units
/// \todo add comparing benchmarks, running two functions and comparing, instead of comparing against
/// baseline
class Register {
public:
Register(const SharedPtr<Unit>& benchmark, const std::string& groupName);
};
#define BENCHMARK_UNIQUE_NAME_IMPL(prefix, line) prefix##line
#define BENCHMARK_UNIQUE_NAME(prefix, line) BENCHMARK_UNIQUE_NAME_IMPL(prefix, line)
#define BENCHMARK_FUNCTION_NAME BENCHMARK_UNIQUE_NAME(BENCHMARK, __LINE__)
#define BENCHMARK_REGISTER_NAME BENCHMARK_UNIQUE_NAME(REGISTER, __LINE__)
#define BENCHMARK(name, group, ...) \
static void BENCHMARK_FUNCTION_NAME(__VA_ARGS__); \
namespace { \
::Sph::Benchmark::Register BENCHMARK_REGISTER_NAME( \
makeShared<::Sph::Benchmark::Unit>(name, &BENCHMARK_FUNCTION_NAME), \
group); \
} \
static void BENCHMARK_FUNCTION_NAME(__VA_ARGS__)
NAMESPACE_BENCHMARK_END
|
pavelsevecek/OpenSPH
|
core/objects/geometry/Indices.h
|
<reponame>pavelsevecek/OpenSPH<filename>core/objects/geometry/Indices.h
#pragma once
/// \file Indices.h
/// \brief Vectorized computations with integral numbers
/// \author <NAME> (sevecek at s<EMAIL>)
/// \date 2016-2021
#include "objects/Object.h"
#include "objects/geometry/Vector.h"
NAMESPACE_SPH_BEGIN
#define SPH_NO_ROUNDING_MODE
/// Helper object for storing three (possibly four) int or bool values.
class Indices {
private:
union {
__m128i i;
int a[4];
} data;
public:
INLINE Indices() = default;
INLINE Indices(__m128i i) {
data.i = i;
}
/// Constructs indices from single value by copying it to all components.
INLINE explicit Indices(const int value) {
data.i = _mm_set1_epi32(value);
}
/// Constructs indices from values. Fourth component is optional.
INLINE Indices(const int i, const int j, const int k, const int l = 0) {
data.i = _mm_set_epi32(l, k, j, i);
}
/// Constructs indices by casting components of vectors to ints
#ifndef SPH_NO_ROUNDING_MODE
INLINE explicit Indices(const BasicVector<float>& v) {
data = _mm_cvtps_epi32(v.sse());
}
#else
INLINE explicit Indices(const BasicVector<float>& v)
: Indices(int(v[X]), int(v[Y]), int(v[Z]), int(v[H])) {}
#endif
INLINE explicit Indices(const BasicVector<double>& v) {
/// \todo optimize
*this = Indices(int(v[0]), int(v[1]), int(v[2]), int(v[3]));
}
INLINE Indices(const Indices& other)
: data(other.data) {}
/// Must be called once before Indices are used
INLINE static void init() {
#ifndef SPH_NO_ROUNDING_MODE
_MM_SET_ROUNDING_MODE(_MM_ROUND_DOWN);
#endif
}
INLINE Indices& operator=(const Indices& other) {
data = other.data;
return *this;
}
#ifndef SPH_NO_ROUNDING_MODE
INLINE operator BasicVector<float>() const {
return BasicVector<float>(_mm_cvtepi32_ps(data));
}
#else
INLINE operator BasicVector<float>() const {
return BasicVector<float>((*this)[0], (*this)[1], (*this)[2], (*this)[3]);
}
#endif
INLINE operator BasicVector<double>() const {
/// \todo optimize
return BasicVector<double>((*this)[0], (*this)[1], (*this)[2], (*this)[3]);
}
INLINE int& operator[](const int idx) {
SPH_ASSERT(unsigned(idx) < 4);
return data.a[idx];
}
INLINE int operator[](const int idx) const {
SPH_ASSERT(unsigned(idx) < 4);
return data.a[idx];
}
INLINE Indices operator==(const Indices& other) const {
return _mm_cmpeq_epi32(data.i, other.data.i);
}
INLINE Indices operator!=(const Indices& other) {
return _mm_xor_si128(_mm_cmpeq_epi32(data.i, other.data.i), _mm_set1_epi32(-1));
}
INLINE Indices operator>(const Indices& other) const {
return _mm_cmpgt_epi32(data.i, other.data.i);
}
INLINE Indices operator<(const Indices& other) const {
return _mm_cmplt_epi32(data.i, other.data.i);
}
INLINE Indices operator+(const Indices& other) const {
return _mm_add_epi32(data.i, other.data.i);
}
INLINE Indices operator-(const Indices& other) const {
return _mm_sub_epi32(data.i, other.data.i);
}
INLINE Indices max(const Indices& other) const {
return _mm_max_epi32(data.i, other.data.i);
}
INLINE Indices min(const Indices& other) const {
return _mm_min_epi32(data.i, other.data.i);
}
friend std::ostream& operator<<(std::ostream& stream, const Indices& idxs) {
for (int i = 0; i < 3; ++i) {
stream << std::setw(20) << idxs[i];
}
return stream;
}
};
INLINE Indices max(const Indices i1, const Indices i2) {
return i1.max(i2);
}
INLINE Indices min(const Indices i1, const Indices i2) {
return i1.min(i2);
}
INLINE bool all(const Indices& i) {
return i[0] && i[1] && i[2];
}
INLINE bool any(const Indices& i) {
return i[0] || i[1] || i[2];
}
template <>
INLINE auto floor(const Vector& v) {
return Indices(int(std::floor(v[X])), int(std::floor(v[Y])), int(std::floor(v[Z])));
}
struct IndicesEqual {
INLINE bool operator()(const Indices& i1, const Indices& i2) const {
return all(i1 == i2);
}
};
NAMESPACE_SPH_END
template <>
class std::hash<Sph::Indices> {
public:
INLINE size_t operator()(const Sph::Indices& idxs) const {
return (idxs[0] * 73856093ull) ^ (idxs[1] * 19349663ull) ^ (idxs[2] * 83492791ull);
}
};
|
pavelsevecek/OpenSPH
|
gui/windows/SessionDialog.h
|
<filename>gui/windows/SessionDialog.h
#pragma once
#include "run/Node.h"
#include <wx/dialog.h>
NAMESPACE_SPH_BEGIN
class SessionDialog : public wxDialog {
private:
SharedPtr<JobNode> preset;
public:
SessionDialog(wxWindow* parent, UniqueNameManager& nameMgr);
SharedPtr<JobNode> selectedPreset() const {
return preset;
}
~SessionDialog();
};
NAMESPACE_SPH_END
|
pavelsevecek/OpenSPH
|
core/run/jobs/MaterialJobs.h
|
#pragma once
#include "run/Job.h"
NAMESPACE_SPH_BEGIN
class MaterialProvider {
protected:
BodySettings body;
public:
explicit MaterialProvider(const BodySettings& overrides = EMPTY_SETTINGS);
protected:
void addMaterialEntries(VirtualSettings::Category& category, Function<bool()> enabler);
};
class MaterialJob : public IMaterialJob, public MaterialProvider {
public:
MaterialJob(const std::string& name, const BodySettings& overrides = EMPTY_SETTINGS);
virtual std::string className() const override {
return "material";
}
virtual UnorderedMap<std::string, ExtJobType> getSlots() const override {
return {};
}
virtual VirtualSettings getSettings() override;
virtual void evaluate(const RunSettings& global, IRunCallbacks& UNUSED(callbacks)) override;
};
class DisableDerivativeCriterionJob : public IMaterialJob {
public:
DisableDerivativeCriterionJob(const std::string& name)
: IMaterialJob(name) {}
virtual std::string className() const override {
return "optimize timestepping";
}
virtual UnorderedMap<std::string, ExtJobType> getSlots() const override {
return { { "material", JobType::MATERIAL } };
}
virtual VirtualSettings getSettings() override;
virtual void evaluate(const RunSettings& global, IRunCallbacks& UNUSED(callbacks)) override;
};
NAMESPACE_SPH_END
|
pavelsevecek/OpenSPH
|
core/objects/utility/Iterator.h
|
<reponame>pavelsevecek/OpenSPH<gh_stars>10-100
#pragma once
/// \file Iterator.h
/// \brief Ordinary iterator for custom containers.
/// \author <NAME> (sevecek at s<EMAIL>)
/// \date 2016-2021
#include "common/Assert.h"
#include "common/Traits.h"
#include <iterator>
NAMESPACE_SPH_BEGIN
/// \brief Simple (forward) iterator over continuous array of objects of type T.
///
/// Can be used with STL algorithms.
template <typename T>
class Iterator {
protected:
using TValue = typename UnwrapReferenceType<T>::Type;
T* data;
#ifdef SPH_DEBUG
const T *begin = nullptr, *end = nullptr;
#endif
#ifndef SPH_DEBUG
Iterator(T* data)
: data(data) {}
#endif
public:
using TCounter = ptrdiff_t;
using iterator_category = std::random_access_iterator_tag;
using value_type = T;
using difference_type = ptrdiff_t;
using pointer = T*;
using reference = T&;
Iterator() = default;
Iterator(T* data, const T* begin, const T* end)
: data(data)
#ifdef SPH_DEBUG
, begin(begin)
, end(end)
#endif
{
SPH_ASSERT(end >= begin, begin, end);
}
Iterator(std::nullptr_t)
: data(nullptr)
#ifdef SPH_DEBUG
, begin(nullptr)
, end(nullptr)
#endif
{
}
INLINE const TValue& operator*() const {
SPH_ASSERT(data != nullptr);
SPH_ASSERT_UNEVAL(data >= begin && data < end);
return *data;
}
INLINE TValue& operator*() {
SPH_ASSERT(data != nullptr);
SPH_ASSERT_UNEVAL(data >= begin && data < end);
return *data;
}
INLINE T* operator->() {
SPH_ASSERT(data != nullptr);
SPH_ASSERT_UNEVAL(data >= begin && data < end);
return data;
}
INLINE const T* operator->() const {
SPH_ASSERT(data != nullptr);
SPH_ASSERT_UNEVAL(data >= begin && data < end);
return data;
}
INLINE explicit operator bool() const {
return data != nullptr;
}
#ifdef SPH_DEBUG
INLINE Iterator operator+(const TCounter n) const {
SPH_ASSERT(data != nullptr);
return Iterator(data + n, begin, end);
}
INLINE Iterator operator-(const TCounter n) const {
SPH_ASSERT(data != nullptr);
return Iterator(data - n, begin, end);
}
#else
INLINE Iterator operator+(const TCounter n) const {
return Iterator(data + n);
}
INLINE Iterator operator-(const TCounter n) const {
return Iterator(data - n);
}
#endif
INLINE void operator+=(const TCounter n) {
SPH_ASSERT(data != nullptr);
data += n;
}
INLINE void operator-=(const TCounter n) {
SPH_ASSERT(data != nullptr);
data -= n;
}
INLINE Iterator& operator++() {
SPH_ASSERT(data != nullptr);
++data;
return *this;
}
INLINE Iterator operator++(int) {
SPH_ASSERT(data != nullptr);
Iterator tmp(*this);
operator++();
return tmp;
}
INLINE Iterator& operator--() {
SPH_ASSERT(data != nullptr);
--data;
return *this;
}
INLINE Iterator operator--(int) {
SPH_ASSERT(data != nullptr);
Iterator tmp(*this);
operator--();
return tmp;
}
INLINE difference_type operator-(const Iterator& iter) const {
// only valid if both iterators are non-nullptr or both are nullptr
SPH_ASSERT((data != nullptr) == (iter.data != nullptr));
return data - iter.data;
}
INLINE bool operator<(const Iterator& iter) const {
SPH_ASSERT(data != nullptr && iter.data != nullptr);
return data < iter.data;
}
INLINE bool operator>(const Iterator& iter) const {
SPH_ASSERT(data != nullptr && iter.data != nullptr);
return data > iter.data;
}
INLINE bool operator<=(const Iterator& iter) const {
SPH_ASSERT(data != nullptr && iter.data != nullptr);
return data <= iter.data;
}
INLINE bool operator>=(const Iterator& iter) const {
SPH_ASSERT(data != nullptr && iter.data != nullptr);
return data >= iter.data;
}
INLINE bool operator==(const Iterator& iter) const {
return data == iter.data;
}
INLINE bool operator!=(const Iterator& iter) const {
return data != iter.data;
}
INLINE operator Iterator<const T>() const {
#ifdef SPH_DEBUG
return Iterator<const T>(data, begin, end);
#else
return Iterator<const T>(data, nullptr, nullptr);
#endif
}
};
NAMESPACE_SPH_END
|
pavelsevecek/OpenSPH
|
gui/Utils.h
|
#pragma once
/// \file Utils.h
/// \brief Random utility functions for drawing stuff to DC
/// \author <NAME> (sevecek at s<EMAIL>)
/// \date 2016-2021
#include "common/Globals.h"
#include "gui/renderers/IRenderer.h"
#include "objects/Object.h"
#include "objects/wrappers/Flags.h"
#include "run/VirtualSettings.h"
#include <wx/window.h>
class wxDC;
class wxPaintDC;
NAMESPACE_SPH_BEGIN
class Path;
using FileFormat = IVirtualEntry::FileFormat;
Optional<Path> doSaveFileDialog(const std::string& title, Array<FileFormat>&& formats);
Optional<Path> doOpenFileDialog(const std::string& title, Array<FileFormat>&& formats);
/// Draws a text into the DC using current font and color, replacing all _x with corresponding subscript
/// character.
void drawTextWithSubscripts(wxDC& dc, const std::wstring& text, const wxPoint point);
void drawTextWithSubscripts(wxDC& dc, const std::string& text, const wxPoint point);
/// Converts the value to a printable string.
std::wstring toPrintableString(const Float value,
const Size precision = 5,
const Float decimalThreshold = 1000._f);
void printLabels(wxDC& dc, ArrayView<const IRenderOutput::Label> labels);
class BusyCursor {
private:
wxWindow* window;
public:
explicit BusyCursor(wxWindow* window)
: window(window) {
window->SetCursor(*wxHOURGLASS_CURSOR);
wxYield();
}
~BusyCursor() {
window->SetCursor(*wxSTANDARD_CURSOR);
}
};
class TransparencyPattern {
private:
Bitmap<Rgba> stipple;
public:
explicit TransparencyPattern(const Size side = 8,
const Rgba& dark = Rgba::gray(0.25f),
const Rgba& light = Rgba::gray(0.3f));
void draw(wxDC& dc, const wxRect& rect) const;
};
NAMESPACE_SPH_END
|
pavelsevecek/OpenSPH
|
gui/Project.h
|
#pragma once
#include "gui/Settings.h"
#include "gui/objects/Palette.h"
#include "objects/containers/CallbackSet.h"
#include "run/Config.h"
#include "thread/CheckFunction.h"
NAMESPACE_SPH_BEGIN
/// \todo deduplicate
inline std::string getIdentifier(const std::string& name) {
std::string escaped = replaceAll(name, " ", "-");
return lowercase(escaped);
}
class Project {
private:
GuiSettings gui;
FlatMap<std::string, Palette> palettes;
Project();
public:
CallbackSet<void(const std::string& name, const Palette& palette)> onPaletteChanged;
static Project& getInstance() {
static Project project;
return project;
}
Project clone() const {
Project cloned;
cloned.gui = gui;
cloned.palettes = palettes.clone();
return cloned;
}
void setPalette(const std::string& name, const Palette& palette) {
palettes.insert(name, palette);
onPaletteChanged(name, palette);
}
bool getPalette(const std::string& name, Palette& palette) const {
if (palettes.contains(name)) {
palette = palettes[name];
return true;
} else {
return false;
}
}
/// \todo synchronize
GuiSettings& getGuiSettings() {
return gui;
}
const GuiSettings& getGuiSettings() const {
return gui;
}
void save(Config& config);
void load(Config& config);
private:
void savePalettes(Config& config);
void saveGui(Config& config);
void loadPalettes(Config& config);
void loadGui(Config& config);
};
NAMESPACE_SPH_END
|
pavelsevecek/OpenSPH
|
core/math/Means.h
|
#pragma once
/// \file Means.h
/// \brief Computing minimum, maximum and mean value of floats.
/// \author <NAME> (sevecek at s<EMAIL>)
/// \date 2016-2021
#include "objects/geometry/Generic.h"
#include "objects/wrappers/Interval.h"
NAMESPACE_SPH_BEGIN
/// \brief Generalized mean with fixed (compile-time) power.
template <int Power>
class GeneralizedMean {
private:
double sum = 0.; // using double to limit round-off errors in summing
Size weight = 0;
public:
GeneralizedMean() = default;
INLINE void accumulate(const Float value) {
sum += pow<Power>(value);
weight++;
}
/// Removes all values from the set.
INLINE void reset() {
sum = 0.;
weight = 0;
}
INLINE Float compute() const {
return Float(pow(sum / weight, 1. / Power));
}
INLINE Size count() const {
return weight;
}
friend std::ostream& operator<<(std::ostream& stream, const GeneralizedMean& stats) {
stream << stats.compute();
return stream;
}
};
/// Geometric mean has to be specialized.
template <>
class GeneralizedMean<0> {
private:
double sum = 1.;
Size weight = 0;
public:
GeneralizedMean() = default;
INLINE void accumulate(const Float value) {
sum *= value;
weight++;
}
INLINE void reset() {
sum = 1.;
weight = 0;
}
INLINE Float compute() const {
return Float(pow(sum, 1. / weight));
}
INLINE Size count() const {
return weight;
}
friend std::ostream& operator<<(std::ostream& stream, const GeneralizedMean& stats) {
stream << stats.compute();
return stream;
}
};
/// Aliases
using ArithmeticMean = GeneralizedMean<1>;
using HarmonicMean = GeneralizedMean<-1>;
using GeometricMean = GeneralizedMean<0>;
/// \brief Generalized mean with positive (runtime) power.
///
/// Cannot be used to compute geometric mean. If constructed with non-positive power, it issues an assert.
class PositiveMean {
protected:
double sum = 0.;
Size weight = 0;
Float power;
public:
PositiveMean(const Float power)
: power(power) {
SPH_ASSERT(power > 0._f);
}
INLINE void accumulate(const Float value) {
sum += powFastest(value, power);
weight++;
}
INLINE void accumulate(const PositiveMean& other) {
SPH_ASSERT(power == other.power); // it only makes sense to sum up same means
sum += other.sum;
weight += other.weight;
}
INLINE void reset() {
sum = 0.;
weight = 0;
}
INLINE Float compute() const {
return Float(powFastest(Float(sum / weight), 1._f / power));
}
INLINE Size count() const {
return weight;
}
friend std::ostream& operator<<(std::ostream& stream, const PositiveMean& stats) {
stream << stats.compute();
return stream;
}
};
/// \brief Generalized mean with negative (runtime) power.
///
/// Cannot be used to compute geometric mean. If constructed with non-negative power, it issues an assert.
class NegativeMean : public PositiveMean {
public:
NegativeMean(const Float power)
: PositiveMean(-power) {}
INLINE void accumulate(const Float value) {
SPH_ASSERT(value > 0._f, value);
const Float p = pow(value, power);
if (p == INFTY) {
weight++; // just increase weight
} else if (p > 0._f) {
sum += 1._f / p;
weight++;
}
}
INLINE void accumulate(const NegativeMean& other) {
SPH_ASSERT(power == other.power);
sum += other.sum;
weight += other.weight;
}
INLINE Float compute() const {
Float avg = Float(sum / weight);
SPH_ASSERT(isReal(avg), avg, sum, weight);
Float avgPow = pow(avg, 1._f / power);
if (avgPow == 0._f) {
return INFINITY;
} else {
return 1._f / avgPow;
}
}
};
/// Helper class for statistics, accumulating minimal, maximal and mean value of a set of numbers.
class MinMaxMean {
private:
Interval minMax;
ArithmeticMean avg;
public:
MinMaxMean() = default;
INLINE void accumulate(const Float value) {
avg.accumulate(value);
minMax.extend(value);
}
/// Removes all values from the set.
INLINE void reset() {
avg.reset();
minMax = Interval();
}
INLINE Float mean() const {
return avg.compute();
}
INLINE Float min() const {
return minMax.lower();
}
INLINE Float max() const {
return minMax.upper();
}
INLINE Interval range() const {
return minMax;
}
INLINE Size count() const {
return avg.count();
}
friend std::ostream& operator<<(std::ostream& stream, const MinMaxMean& stats) {
stream << "average = " << stats.mean() << " (min = " << stats.min() << ", max = " << stats.max()
<< ")";
return stream;
}
};
NAMESPACE_SPH_END
|
pavelsevecek/OpenSPH
|
gui/windows/PaletteDialog.h
|
<gh_stars>10-100
#pragma once
#include "gui/objects/Palette.h"
#include "objects/containers/UnorderedMap.h"
#include "objects/wrappers/Function.h"
#include <wx/frame.h>
#include <wx/panel.h>
NAMESPACE_SPH_BEGIN
class ComboBox;
class FloatTextCtrl;
class PaletteCanvas;
class PalettePanel : public wxPanel {
private:
ComboBox* paletteBox;
PaletteCanvas* canvas;
FloatTextCtrl* lowerCtrl;
FloatTextCtrl* upperCtrl;
UnorderedMap<std::string, Palette> paletteMap;
Palette initial;
Palette selected;
public:
PalettePanel(wxWindow* parent, wxSize size, const Palette palette);
void setPalette(const Palette& palette);
Function<void(Palette)> onPaletteChanged;
private:
void setDefaultPaletteList();
void loadPalettes(const Path& path);
void update();
};
NAMESPACE_SPH_END
|
pavelsevecek/OpenSPH
|
core/objects/containers/AdvancedAllocators.h
|
#pragma once
#include "objects/containers/BasicAllocators.h"
NAMESPACE_SPH_BEGIN
/// \brief Allocator that obtains memory blocks from given memory resource.
///
/// Allocator does not own the resource, therefore the resource must exist as long as any object that uses the
/// allocator. Allocator cannot deallocate memory.
template <typename TResource>
class MemoryResourceAllocator {
private:
TResource* resource = nullptr;
public:
INLINE void bind(TResource& other) {
resource = &other;
}
INLINE MemoryBlock allocate(const std::size_t size, const Size align) noexcept {
if (resource) {
return resource->allocate(size, align);
} else {
return MemoryBlock::EMPTY();
}
}
INLINE void deallocate(MemoryBlock& UNUSED(block)) noexcept {}
INLINE bool owns(const MemoryBlock& block) const noexcept {
if (resource) {
return resource->owns(block);
} else {
return false;
}
}
};
/// \brief Simple memory resource with pre-allocated contiguous memory buffer.
template <typename TAllocator>
class MonotonicMemoryResource : private TAllocator {
MemoryBlock resource;
std::size_t position = 0;
public:
MonotonicMemoryResource(const std::size_t size, const std::size_t align) {
resource = TAllocator::allocate(size, align);
}
~MonotonicMemoryResource() {
TAllocator::deallocate(resource);
}
INLINE MemoryBlock allocate(const std::size_t size, const std::size_t align) noexcept {
if (position + size <= resource.size) {
MemoryBlock block;
block.ptr = roundToAlignment((uint8_t*)resource.ptr + position, align);
SPH_ASSERT(isAligned(block.ptr, align));
block.size = size;
SPH_ASSERT(isAligned(block.size, align));
position = ((uint8_t*)block.ptr + block.size) - (uint8_t*)resource.ptr;
return block;
} else {
return MemoryBlock::EMPTY();
}
}
INLINE bool owns(const MemoryBlock& block) const noexcept {
return block.ptr >= resource.ptr && block.ptr < (uint8_t*)resource.ptr + resource.size;
}
};
template <typename TAllocator>
class FreeListAllocator : private TAllocator {
private:
struct Node {
MemoryBlock block;
Node* next = nullptr;
};
Node* list = nullptr;
public:
~FreeListAllocator() {
while (list) {
TAllocator::deallocate(list->block);
Node* next = list->next;
allocatorDelete(this->underlying(), list);
list = next;
}
}
INLINE MemoryBlock allocate(const std::size_t size, const Size align) noexcept {
if (list != nullptr) {
SPH_ASSERT(list->block.ptr);
SPH_ASSERT(list->block.size == size); // could be generalized if needed
MemoryBlock block = list->block;
list = list->next;
return block;
} else {
return TAllocator::allocate(size, align);
}
}
INLINE void deallocate(MemoryBlock& block) noexcept {
SPH_ASSERT(block.ptr);
Node* node = allocatorNew<Node>(this->underlying());
SPH_ASSERT(node);
node->block = block;
node->next = list;
list = node;
}
// only for debug purposes
Size getListSize() const {
Size size = 0;
Node* ptr = list;
while (ptr) {
size++;
ptr = ptr->next;
}
return size;
}
const TAllocator& underlying() const {
return *this;
}
TAllocator& underlying() {
return *this;
}
};
NAMESPACE_SPH_END
|
pavelsevecek/OpenSPH
|
core/timestepping/TimeStepping.h
|
<reponame>pavelsevecek/OpenSPH<filename>core/timestepping/TimeStepping.h
#pragma once
/// \file TimeStepping.h
/// \brief Algorithms for temporal evolution of the physical model.
/// \author <NAME> (sevecek at s<EMAIL>)
/// \date 2016-2021
#include "common/ForwardDecl.h"
#include "objects/containers/Array.h"
#include "objects/geometry/Vector.h"
#include "objects/wrappers/SharedPtr.h"
NAMESPACE_SPH_BEGIN
class IScheduler;
/// \brief Base object providing integration in time for all quantities.
///
/// The integration is done by iterating with discrete time step, using \ref step method. All derived
/// objects must implement \ref stepParticles function, which shall iterate over all independant quantities
/// and advance their values using temporal derivatives computed by \ref ISolver object passed in argument of
/// the method. The \ref step function then calls the user-defined \ref stepParticles while also doing more
/// legwork, such as saving statistics and computing new value of time step. Function \ref stepParticles can
/// also save statistics specific to the implementation, using provided \ref Statistics object, but it shall
/// not compute the time step value. To control time step, see \ref TimeStepCriterion and derived classes.
///
/// The time-stepping object must take care of clearing derivatives, as there can be values from previous
/// timestep, or some garbage memory when the method is called for the first time. It is also necessary to
/// clamp all quantities by their minimal/maximal allowed values. These values can be different for
/// different materials; the range of quantity for given \ref IMaterial object can be obtained by
/// \ref IMaterial::range() const function.
///
/// Temporal derivatives are computed by calling \ref ISolver::integrate function. The solver
/// assumes the storage already has zeroed highest-order derivatives of all quantities. The implementation of
/// \ref ITimeStepping inteface must also assume that \ref ISolver::integrate changes the number of particles
/// in the storage. If the timestepping uses derivatives from different times, stored in separate Storage
/// objects, the variable number of particles can be handled automatically by the Storage object, using the
/// concept of dependenet storages - if you create an auxiliary storage, for example to store the prediction
/// derivatives in predictor-corrector algorithm, simply add this storage as a dependent storage to the main
/// one, and it will be updated every time the number of particles in the main storage changes.
///
/// Timestepping is bound to a single Storage object, passed in constructor, and this object cannot be changed
/// during the lifetime of the timestepping object. Timestepping implementation can create any number of
/// auxiliary storages and link then to the main one, this hierarchy established in the constructor will not
/// change during the run.
class ITimeStepping : public Polymorphic {
protected:
/// Main storage holding all the particles in the run
SharedPtr<Storage> storage;
/// Current time step
Float timeStep;
/// Maximal allowed time step
Float maxTimeStep;
/// Criterion used to compute the time step
AutoPtr<ITimeStepCriterion> criterion;
public:
/// \brief Constructs the timestepping, using timestep criteria from parameters in settings.
///
/// \param storage Storage used during the run
/// \param settings Settings containing initial and maximal timestep and aslo timestep criteria
ITimeStepping(const SharedPtr<Storage>& storage, const RunSettings& settings);
/// \brief Constructs the timestepping, explicitly specifying the timestep criterion used in the run.
///
/// \note Use MultiCriterion if more than one criterion is used.
ITimeStepping(const SharedPtr<Storage>& storage,
const RunSettings& settings,
AutoPtr<ITimeStepCriterion>&& criterion);
~ITimeStepping() override;
INLINE Float getTimeStep() const {
return timeStep;
}
void step(IScheduler& scheduler, ISolver& solver, Statistics& stats);
protected:
virtual void stepParticles(IScheduler& scheduler, ISolver& solver, Statistics& stats) = 0;
};
/// \brief Simple Euler first-order timestepping.
class EulerExplicit : public ITimeStepping {
public:
explicit EulerExplicit(const SharedPtr<Storage>& storage, const RunSettings& settings)
: ITimeStepping(storage, settings) {}
virtual void stepParticles(IScheduler& scheduler, ISolver& solver, Statistics& stats) override;
};
/// \brief Predictor-corrector second-order timestepping
class PredictorCorrector : public ITimeStepping {
private:
/// Separate storage holding prediction derivatives. Holds only highest-order derivatives, other buffers
/// are empty. Must be kept synchronized with the main storage.
SharedPtr<Storage> predictions;
public:
PredictorCorrector(const SharedPtr<Storage>& storage, const RunSettings& settings);
~PredictorCorrector() override;
protected:
virtual void stepParticles(IScheduler& scheduler, ISolver& solver, Statistics& stats) override;
void makePredictions(IScheduler& scheduler);
void makeCorrections(IScheduler& scheduler);
};
/// \brief Leapfrog timestepping
///
/// Uses the drift-kick-drift version of the algorithm for second-order quantities. First-order quantities are
/// integrated using ordinary Euler timestepping.
class LeapFrog : public ITimeStepping {
public:
LeapFrog(const SharedPtr<Storage>& storage, const RunSettings& settings)
: ITimeStepping(storage, settings) {}
protected:
virtual void stepParticles(IScheduler& scheduler, ISolver& solver, Statistics& stats) override;
};
class RungeKutta : public ITimeStepping {
private:
SharedPtr<Storage> k1, k2, k3, k4;
public:
RungeKutta(const SharedPtr<Storage>& storage, const RunSettings& settings);
~RungeKutta() override;
protected:
virtual void stepParticles(IScheduler& scheduler, ISolver& solver, Statistics& stats) override;
void integrateAndAdvance(ISolver& solver, Statistics& stats, Storage& k, const Float m, const Float n);
};
class ModifiedMidpointMethod : public ITimeStepping {
private:
SharedPtr<Storage> mid;
Size n;
public:
ModifiedMidpointMethod(const SharedPtr<Storage>& storage, const RunSettings& settings);
protected:
virtual void stepParticles(IScheduler& scheduler, ISolver& solver, Statistics& stats) override;
};
class BulirschStoer : public ITimeStepping {
private:
Float eps;
public:
BulirschStoer(const SharedPtr<Storage>& storage, const RunSettings& settings);
protected:
virtual void stepParticles(IScheduler& scheduler, ISolver& solver, Statistics& stats) override;
};
NAMESPACE_SPH_END
|
pavelsevecek/OpenSPH
|
core/timestepping/TimeStepCriterion.h
|
#pragma once
/// \file TimeStepCriterion.h
/// \brief Criteria for computing the time step
/// \author <NAME> (sevecek at s<EMAIL>)
/// \date 2016-2021
#include "common/ForwardDecl.h"
#include "objects/containers/Array.h"
#include "objects/wrappers/AutoPtr.h"
#include "quantities/QuantityIds.h"
NAMESPACE_SPH_BEGIN
class IScheduler;
enum class CriterionId {
INITIAL_VALUE, ///< Timestep is not computed, using given initial value
MAXIMAL_VALUE, ///< Timestep given by selected maximal value
DERIVATIVE, ///< Timestep based on value-to-derivative ratio
CFL_CONDITION, ///< Timestep computed using CFL condition
ACCELERATION, ///< Timestep constrained by acceleration condition
DIVERGENCE, ///< Timestep computed by velocity divergence
MAX_CHANGE, ///< Timestep is limited by the maximum allowed change from previous timestep
};
std::ostream& operator<<(std::ostream& stream, const CriterionId id);
struct TimeStep {
/// Value of the time step in code units (currently SI).
Float value;
/// Criterion applied to compute the time step;
CriterionId id;
};
/// \brief Base class for timestep setters.
class ITimeStepCriterion : public Polymorphic {
public:
/// \brief Computes the value of the time step.
///
/// \param scheduler Scheduler than can be used for parallelization.
/// \param storage Storage containing all physical quantities from which the time step is determined.
/// \param maxStep Maximal allowed time step.
/// \param stats Used to save statistics of the criterion.
/// \returns Computed time step and ID of criterion that determined the value.
virtual TimeStep compute(IScheduler& scheduler, Storage& storage, Float maxStep, Statistics& stats) = 0;
};
/// \brief Criterion setting time step based on value-to-derivative ratio for time-dependent quantities.
///
/// The value-to-derivative ratio is evaluated for each particle and each first-order quantity in the storage.
/// This criterion ensures a constant relative error of the timestepping algorithms. Quantities that allows
/// for (zero or negative) values, such as all vector and tensor quantities, have to be treated differently,
/// as zero values with any non-zero derivatives would formally lead to zero time step.
/// Therefore, all time-depended quantities have a scale value assigned. For quantity value \f[x\f] with scale
/// value \f[x_0\f] and derivative \f[dx\f], the time step is computed as
/// \f[ dt = \frac{|x| + x_0}{|dx|} \f].
///
/// The scale value can be chosen arbitrarily, it represents a transitional value between relative and
/// absolute error of the quantity. The optimal scale value is about 0.01 to 0.1 of the typical value of the
/// quantity in the run; for density 2700 kg/m^3, the default scale value is 50 kg/m^3.
/// Larger scale value makes the criterion less restrictive (allowing larger time steps), and vice versa.
/// Setting the scale value to a very large number (10^20, for example) excludes the quantity from the
/// criterion.
///
/// The scale value can be set differently for each material. The value can be set by calling \ref
/// IMaterial::setRange and later obtained by IMaterial::minimal.
///
/// By default, the most restrictive time step is chosen, i.e. the lowest time step for all particles and all
/// quantities. This can be relaxed by setting a power (parameter RunSettingsId::TIMESTEPPING_MEAN_POWER) of a
/// mean, computed from time steps of individual particles. This makes the resulting time step more 'smooth',
/// as it is less influenced by outliers. The lower the value of the power, the more restrictive time step.
///
/// \note The computed mean can be quite imprecise as it uses approximative pow function. This shouldn't be an
/// issue as there is no need for exact value of time step.
///
/// \todo currently only used on first-order quantities.
class DerivativeCriterion : public ITimeStepCriterion {
private:
/// Multiplicative factor for the time step
Float factor;
/// Power of the mean used to get final time step from time steps of individual particles. Value of -INFTY
/// means the minimum of all time steps is used. Currently only implemented for negative powers.
Float power;
public:
explicit DerivativeCriterion(const RunSettings& settings);
virtual TimeStep compute(IScheduler& scheduler,
Storage& storage,
Float maxStep,
Statistics& stats) override;
private:
template <template <typename> class Tls>
TimeStep computeImpl(IScheduler& scheduler, Storage& storage, Float maxStep, Statistics& stats);
};
/// \brief Criterion setting time step based on computed acceleration of particles.
///
/// This criterion is somewhat similar to \ref DerivativeCriterion; the time step is computed from the ratio
/// of smoothing length and particle acceleration (or square root of the ratio, to be exact).
class AccelerationCriterion : public ITimeStepCriterion {
private:
Float factor;
public:
explicit AccelerationCriterion(const RunSettings& settings);
virtual TimeStep compute(IScheduler& scheduler,
Storage& storage,
Float maxStep,
Statistics& stats) override;
};
/// \brief Criterion computing time step from velocity divergence.
///
/// This criterion constrains the time step based on relative velocities of interacting particles.
class DivergenceCriterion : public ITimeStepCriterion {
private:
Float factor;
public:
explicit DivergenceCriterion(const RunSettings& settings);
virtual TimeStep compute(IScheduler& scheduler,
Storage& storage,
Float maxStep,
Statistics& stats) override;
};
/// \brief Time step based on CFL criterion.
///
/// This criterion should be always used as it is necessary for stability of the integration in time. It can
/// be made more restrictive or less restrictive by setting Courant number. Setting values larger than 1 is
/// not recommended.
class CourantCriterion : public ITimeStepCriterion {
private:
Float courant;
public:
explicit CourantCriterion(const RunSettings& settings);
/// Storage must contain at least positions of particles and sound speed, checked by assert.
virtual TimeStep compute(IScheduler& scheduler,
Storage& storage,
Float maxStep,
Statistics& stats) override;
};
/// \brief Helper criterion, wrapping multiple criteria under \ref ITimeStepCriterion interface.
///
/// Time step critaria can be added automatically based on parameter \ref
/// RunSettingsId::TIMESTEPPING_CRITERION in settings, or they can be specified explicitly. Each criterion
/// computes a time step and the minimal time step of these is returned.
class MultiCriterion : public ITimeStepCriterion {
private:
Array<AutoPtr<ITimeStepCriterion>> criteria;
/// Parameters for smoothing the timestep
/// \todo separate into a separate criterion, doesn't belong here
Float maxChange;
Float lastStep;
public:
explicit MultiCriterion(const RunSettings& settings);
MultiCriterion(Array<AutoPtr<ITimeStepCriterion>>&& criteria, const Float maxChange, const Float initial);
virtual TimeStep compute(IScheduler& scheduler,
Storage& storage,
const Float maxStep,
Statistics& stats) override;
};
NAMESPACE_SPH_END
|
pavelsevecek/OpenSPH
|
core/objects/Exceptions.h
|
<reponame>pavelsevecek/OpenSPH
#pragma once
#include "common/Globals.h"
#include <exception>
#include <string>
NAMESPACE_SPH_BEGIN
/// \brief Generic exception
class Exception : public std::exception {
private:
std::string message;
public:
explicit Exception(const std::string& message)
: message(message) {}
virtual const char* what() const noexcept {
return message.c_str();
}
};
/// \brief Thrown when components of the run are mutually incompatible, parameters have invalid values, etc.
class InvalidSetup : public Exception {
public:
explicit InvalidSetup(const std::string& message)
: Exception(message) {}
};
/// \brief Throws when a data-dependend error is encountered (all particles got removed, etc.)
class DataException : public Exception {
public:
explicit DataException(const std::string& message)
: Exception(message) {}
};
/// \brief Exception thrown when file cannot be read, it has invalid format, etc.
class IoError : public Exception {
public:
explicit IoError(const std::string& message)
: Exception(message) {}
};
NAMESPACE_SPH_END
|
pavelsevecek/OpenSPH
|
core/math/MathUtils.h
|
#pragma once
/// \file MathUtils.h
/// \brief Additional math routines (with more includes).
/// \author <NAME> (sevecek at <EMAIL>)
/// \date 2016-2021
#include "common/Assert.h"
#include "math/MathBasic.h"
#include <cmath>
#include <cstring>
#include <limits>
#include <utility>
NAMESPACE_SPH_BEGIN
/// Small value (compared with 1) for given precision.
template <typename T>
struct Eps;
template <>
struct Eps<float> {
constexpr static float value = 1.e-6f;
};
template <>
struct Eps<double> {
constexpr static double value = 1.e-12f;
};
constexpr Float EPS = Eps<Float>::value;
/// Large value (compared with 1). It's safe to do basic arithmetic operations (multiply by 2, for example)
/// without worying about float overflow.
constexpr Float LARGE = 1.e20f;
/// Largest value representable by float/double. Any increase (multiplication by 2, for example) will cause
/// float overflow! Use carefully, maily for comparisons.
constexpr Float INFTY = std::numeric_limits<Float>::max();
/// Returns an approximate value of inverse square root.
/// \tparam Iters Number of iterations of the algorithm. Higher value = more accurate result.
template <typename T>
INLINE T sqrtInv(const T& f) {
int i;
// cast to float
float x2 = float(f) * 0.5f;
float y = float(f);
memcpy(&i, &y, sizeof(float));
i = 0x5f3759df - (i >> 1);
memcpy(&y, &i, sizeof(float));
return y * (1.5f - (x2 * y * y));
}
/// Returns an approximative value of square root.
template <typename T>
INLINE T sqrtApprox(const T f) {
if (f == T(0)) {
return T(0);
}
return T(1.f) / sqrtInv(f);
}
/// Return a squared value.
template <typename T>
INLINE constexpr T sqr(const T& f) noexcept {
return f * f;
}
/// Returns true if given n is a power of 2. N must at least 1.
INLINE constexpr bool isPower2(const Size n) noexcept {
return n >= 1 && (n & (n - 1)) == 0;
}
/// Return a squared root of a value.
template <typename T>
INLINE T sqrt(const T f) {
SPH_ASSERT(f >= T(0), f);
return std::sqrt(f);
}
/// Returns a cubed root of a value.
INLINE Float cbrt(const Float f) {
return std::cbrt(f);
}
/// Returns a positive modulo value
INLINE int positiveMod(const int i, const int n) {
return (i % n + n) % n;
}
template <int N>
INLINE Float root(const Float f);
template <>
INLINE Float root<1>(const Float f) {
return f;
}
template <>
INLINE Float root<2>(const Float f) {
return sqrt(f);
}
template <>
INLINE Float root<3>(const Float f) {
return cbrt(f);
}
template <>
INLINE Float root<4>(const Float f) {
/// \todo is this faster than pow(f, 0.25)?
return sqrt(sqrt(f));
}
/// Power for floats
template <int N>
INLINE constexpr Float pow(const Float v);
template <>
INLINE constexpr Float pow<0>(const Float) {
return 1._f;
}
template <>
INLINE constexpr Float pow<1>(const Float v) {
return v;
}
template <>
INLINE constexpr Float pow<2>(const Float v) {
return v * v;
}
template <>
INLINE constexpr Float pow<3>(const Float v) {
return v * v * v;
}
template <>
INLINE constexpr Float pow<4>(const Float v) {
return pow<2>(pow<2>(v));
}
template <>
INLINE constexpr Float pow<5>(const Float v) {
return pow<2>(pow<2>(v)) * v;
}
template <>
INLINE constexpr Float pow<6>(const Float v) {
return pow<3>(pow<2>(v));
}
template <>
INLINE constexpr Float pow<7>(const Float v) {
return pow<6>(v) * v;
}
template <>
INLINE constexpr Float pow<8>(const Float v) {
return pow<4>(pow<2>(v));
}
template <>
INLINE constexpr Float pow<-1>(const Float v) {
return 1._f / v;
}
template <>
INLINE constexpr Float pow<-2>(const Float v) {
return 1._f / (v * v);
}
template <>
INLINE constexpr Float pow<-3>(const Float v) {
return 1._f / (v * v * v);
}
template <>
INLINE constexpr Float pow<-4>(const Float v) {
return 1._f / (pow<2>(pow<2>(v)));
}
template <>
INLINE constexpr Float pow<-5>(const Float v) {
return 1._f / (v * pow<2>(pow<2>(v)));
}
template <>
INLINE constexpr Float pow<-8>(const Float v) {
return 1._f / (pow<2>(pow<4>(v)));
}
template <>
INLINE constexpr Float pow<-16>(const Float v) {
return 1._f / (pow<2>(pow<8>(v)));
}
/// Power for ints
template <int N>
INLINE constexpr Size pow(const Size v);
template <>
INLINE constexpr Size pow<0>(const Size) {
return 1;
}
template <>
INLINE constexpr Size pow<1>(const Size v) {
return v;
}
template <>
INLINE constexpr Size pow<2>(const Size v) {
return v * v;
}
template <>
INLINE constexpr Size pow<3>(const Size v) {
return v * v * v;
}
template <>
INLINE constexpr Size pow<4>(const Size v) {
return pow<2>(pow<2>(v));
}
template <>
INLINE constexpr Size pow<5>(const Size v) {
return pow<2>(pow<2>(v)) * v;
}
template <>
INLINE constexpr Size pow<6>(const Size v) {
return pow<3>(pow<2>(v));
}
/// Mathematical functions
template <typename T>
INLINE T pow(const T value, const T power) {
return std::pow(value, power);
}
/// Approximative version of pow function.
///
/// Expected error is about 5 %. Works only for positive values and positive powers.
INLINE Float powFastest(const Float value, const Float power) {
SPH_ASSERT(value > 0._f && power > 0._f, value, power);
// https://martin.ankerl.com/2012/01/25/optimized-approximative-pow-in-c-and-cpp/
// this type-punning through union is undefined behavior according to C++ standard, but most compilers
// behave expectably ...
union {
double d;
int x[2];
} u = { value };
u.x[1] = (int)(double(power) * (u.x[1] - 1072632447) + 1072632447);
u.x[0] = 0;
return Float(u.d);
}
/// Approximative version of pow function, slightly more precise than powFastest.
///
/// Expected error is about 2 %. Works only for positive values and positive powers.
INLINE Float powFast(Float value, const Float power) {
SPH_ASSERT(value > 0._f && power > 0._f, value, power);
// https://martin.ankerl.com/2012/01/25/optimized-approximative-pow-in-c-and-cpp/
int e = (int)power;
union {
double d;
int x[2];
} u = { value };
u.x[1] = (int)((double(power) - e) * (u.x[1] - 1072632447) + 1072632447);
u.x[0] = 0;
double r = 1.0;
while (e) {
if (e & 1) {
r *= value;
}
value *= value;
e >>= 1;
}
return Float(r * u.d);
}
template <typename T>
INLINE T exp(const T f) {
return T(::exp(f));
}
template <typename T>
struct AbsoluteValueType {
using Type = T;
};
template <typename T>
using AbsoluteValue = typename AbsoluteValueType<T>::Type;
/// Computes absolute value.
/// \note Return type may not be T, e.g. abs(TracelessTensor) != TracelessTensor
template <typename T>
INLINE AbsoluteValue<T> abs(const T& f) {
return AbsoluteValue<T>(::fabs(f));
}
template <>
INLINE int abs(const int& f) {
return int(::abs(f));
}
template <>
INLINE Size abs(const Size& f) {
return Size(f);
}
INLINE Float cos(const Float f) {
return std::cos(f);
}
INLINE Float sin(const Float f) {
return std::sin(f);
}
INLINE Float tan(const Float f) {
return std::tan(f);
}
INLINE Float acos(const Float f) {
return std::acos(f);
}
INLINE Float asin(const Float f) {
return std::asin(f);
}
INLINE Float atan(const Float f) {
return std::atan(f);
}
INLINE Float atan2(const Float y, const Float x) {
return std::atan2(y, x);
}
INLINE Float cosh(const Float f) {
return std::cosh(f);
}
INLINE Float sinh(const Float f) {
return std::sinh(f);
}
INLINE Float exp10(const Float f) {
return std::pow(10._f, f);
}
INLINE Float log10(const Float f) {
return std::log10(f);
}
template <typename T>
INLINE int sgn(const T val) {
return (T(0) < val) - (val < T(0));
}
template <typename T, typename TAmount>
INLINE T lerp(const T v1, const T v2, const TAmount amount) {
return v1 * (TAmount(1) - amount) + v2 * amount;
}
template <typename T>
INLINE auto floor(const T& f) {
return std::floor(f);
}
template <typename T>
INLINE auto ceil(const T& f) {
return std::ceil(f);
}
template <typename T>
INLINE auto round(const T& f) {
return std::round(f);
}
/// Mathematical constants
constexpr Float PI = 3.14159265358979323846264338327950288419716939937510582097_f;
constexpr Float PI_INV = 1._f / PI;
constexpr Float E = 2.718281828459045235360287471352662497757247093699959574967_f;
constexpr Float SQRT_3 = 1.732050807568877293527446341505872366942805253810380628055_f;
constexpr Float DEG_TO_RAD = PI / 180._f;
constexpr Float RAD_TO_DEG = 180._f / PI;
/// Computes a volume of a sphere given its radius.
INLINE constexpr Float sphereVolume(const Float radius) {
return 1.3333333333333333333333_f * PI * pow<3>(radius);
}
/// Computes a surface area of a sphere given its radius.
INLINE constexpr Float sphereSurfaceArea(const Float radius) {
return 4._f * PI * pow<2>(radius);
}
/// Checks if two values are equal to some given accuracy.
/// \note We use <= rather than < on purpose as EPS for integral types is zero.
INLINE bool almostEqual(const Float& f1, const Float& f2, const Float& eps = EPS) {
return abs(f1 - f2) <= eps * (1._f + max(abs(f1), abs(f2)));
}
NAMESPACE_SPH_END
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.