hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
10461147eae97696cf6f4acabe7897df9a0fe2e0 | 34,696 | cpp | C++ | src/rdmnet/broker/broker_core.cpp | RichardTea/RDMnet | fb48866be0396beb7875ba515ad966f19aa46350 | [
"Apache-2.0"
] | null | null | null | src/rdmnet/broker/broker_core.cpp | RichardTea/RDMnet | fb48866be0396beb7875ba515ad966f19aa46350 | [
"Apache-2.0"
] | null | null | null | src/rdmnet/broker/broker_core.cpp | RichardTea/RDMnet | fb48866be0396beb7875ba515ad966f19aa46350 | [
"Apache-2.0"
] | null | null | null | /******************************************************************************
* Copyright 2019 ETC Inc.
*
* 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.
******************************************************************************
* This file is a part of RDMnet. For more information, go to:
* https://github.com/ETCLabs/RDMnet
*****************************************************************************/
// The core broker implementation. Contains the private implementation of Broker functionality.
#include "broker_core.h"
#include <cstring>
#include <cstddef>
#include "etcpal/cpp/error.h"
#include "etcpal/netint.h"
#include "etcpal/pack.h"
#include "rdmnet/version.h"
#include "rdmnet/core/connection.h"
#include "broker_client.h"
#include "broker_responder.h"
#include "broker_util.h"
/*************************** Function definitions ****************************/
BrokerCore::BrokerCore() : BrokerComponentNotify()
{
}
BrokerCore::~BrokerCore()
{
if (started_)
Shutdown();
}
bool BrokerCore::Startup(const rdmnet::BrokerSettings& settings, rdmnet::BrokerNotify* notify, rdmnet::BrokerLog* log,
BrokerComponents components)
{
if (!started_)
{
// Check the settings for validity
if (!settings.valid())
return false;
// Save members
settings_ = settings;
notify_ = notify;
log_ = log;
components_ = std::move(components);
components_.SetNotify(this);
// Generate IDs if necessary
my_uid_ = settings.uid;
if (settings.uid_type == rdmnet::BrokerSettings::kDynamicUid)
{
my_uid_.id = 1;
components_.uids.SetNextDeviceId(2);
}
if (!components_.conn_interface->Startup(settings.cid, log_->GetLogParams()))
{
return false;
}
if (!components_.socket_mgr->Startup())
{
rdmnet_core_deinit();
return false;
}
if (!StartBrokerServices())
{
components_.socket_mgr->Shutdown();
rdmnet_core_deinit();
return false;
}
started_ = true;
components_.disc->RegisterBroker(settings_);
log_->Info("%s RDMnet Broker Version %s", settings_.dns.manufacturer.c_str(), RDMNET_VERSION_STRING);
log_->Info("Broker starting at scope \"%s\", listening on port %d.", settings_.scope.c_str(),
settings_.listen_port);
if (!settings_.listen_addrs.empty())
{
log_->Info("Listening on manually-specified network interfaces:");
for (auto addr : settings.listen_addrs)
{
log_->Info("%s", addr.ToString().c_str());
}
}
}
return started_;
}
// Call before destruction to gracefully close
void BrokerCore::Shutdown()
{
if (started_)
{
components_.disc->UnregisterBroker();
StopBrokerServices();
components_.socket_mgr->Shutdown();
components_.conn_interface->Shutdown();
started_ = false;
}
}
void BrokerCore::Tick()
{
DestroyMarkedClientSockets();
}
bool BrokerCore::IsDeviceManuBroadcastUID(const RdmUid& uid, uint16_t& manu)
{
if (RDMNET_UID_IS_DEVICE_MANU_BROADCAST(&uid))
{
manu = RDMNET_DEVICE_BROADCAST_MANU_ID(&uid);
return true;
}
return false;
}
bool BrokerCore::IsValidControllerDestinationUID(const RdmUid& uid) const
{
if (RDMNET_UID_IS_CONTROLLER_BROADCAST(&uid) || (uid == my_uid_))
return true;
// TODO this should only check devices
int tmp;
return components_.uids.UidToHandle(uid, tmp);
}
bool BrokerCore::IsValidDeviceDestinationUID(const RdmUid& uid) const
{
if (RDMNET_UID_IS_CONTROLLER_BROADCAST(&uid))
return true;
// TODO this should only check controllers
int tmp;
return components_.uids.UidToHandle(uid, tmp);
}
// The passed-in vector is cleared and filled with the cookies of connections that match the
// criteria.
void BrokerCore::GetConnSnapshot(std::vector<rdmnet_conn_t>& conns, bool include_devices, bool include_controllers,
bool include_unknown, uint16_t manufacturer_filter)
{
conns.clear();
etcpal::ReadGuard client_read(client_lock_);
if (!clients_.empty())
{
// We'll just do a bulk reserve. The actual vector may take up less.
conns.reserve(clients_.size());
for (const auto& client : clients_)
{
// TODO EPT
if (client.second)
{
RPTClient* rpt = static_cast<RPTClient*>(client.second.get());
if (((include_devices && (rpt->client_type == kRPTClientTypeDevice)) ||
(include_controllers && (rpt->client_type == kRPTClientTypeController)) ||
(include_unknown && (rpt->client_type == kRPTClientTypeUnknown))) &&
((manufacturer_filter == 0xffff) || (manufacturer_filter == rpt->uid.manu)))
{
conns.push_back(client.first);
}
}
}
}
}
bool BrokerCore::HandleNewConnection(etcpal_socket_t new_sock, const etcpal::SockAddr& addr)
{
if (log_->CanLog(ETCPAL_LOG_INFO))
{
log_->Info("Creating a new connection for ip addr %s", addr.ip().ToString().c_str());
}
rdmnet_conn_t connhandle = RDMNET_CONN_INVALID;
bool result = false;
{ // Client write lock scope
etcpal::WriteGuard client_write(client_lock_);
if (settings_.max_connections == 0 ||
(clients_.size() <= settings_.max_connections + settings_.max_reject_connections))
{
auto create_res = components_.conn_interface->CreateNewConnectionForSocket(new_sock, addr, connhandle);
if (create_res)
{
auto client = std::make_shared<BrokerClient>(connhandle);
// Before inserting the connection, make sure we can attach the socket.
if (client)
{
client->addr = addr;
clients_.insert(std::make_pair(connhandle, std::move(client)));
components_.socket_mgr->AddSocket(connhandle, new_sock);
result = true;
}
else
{
components_.conn_interface->DestroyConnection(connhandle);
}
}
}
}
if (result)
{
log_->Debug("New connection created with handle %d", connhandle);
}
else
{
log_->Error("New connection failed");
}
return result;
}
void BrokerCore::HandleSocketDataReceived(rdmnet_conn_t conn_handle, const uint8_t* data, size_t data_size)
{
components_.conn_interface->SocketDataReceived(conn_handle, data, data_size);
}
void BrokerCore::HandleSocketClosed(rdmnet_conn_t conn_handle, bool graceful)
{
components_.conn_interface->SocketError(conn_handle, graceful ? kEtcPalErrConnClosed : kEtcPalErrConnReset);
}
// Process each controller queue, sending out the next message from each queue if devices are
// available. Also sends connect reply, error and status messages generated asynchronously to
// devices. Return false if no controllers messages were sent.
bool BrokerCore::ServiceClients()
{
bool result = false;
std::vector<int> client_conns;
etcpal::ReadGuard clients_read(client_lock_);
for (auto client : clients_)
{
ClientWriteGuard client_write(*client.second);
result |= client.second->Send();
}
return result;
}
// Message processing functions
void BrokerCore::HandleRdmnetConnMsgReceived(rdmnet_conn_t handle, const RdmnetMessage& msg)
{
switch (msg.vector)
{
case ACN_VECTOR_ROOT_BROKER:
{
const BrokerMessage* bmsg = GET_BROKER_MSG(&msg);
switch (bmsg->vector)
{
case VECTOR_BROKER_CONNECT:
ProcessConnectRequest(handle, GET_CLIENT_CONNECT_MSG(bmsg));
break;
case VECTOR_BROKER_FETCH_CLIENT_LIST:
SendClientList(handle);
log_->Debug("Received Fetch Client List from Client %d; sending Client List.", handle);
break;
default:
log_->Warning("Received Broker PDU with unknown or unhandled vector %d", bmsg->vector);
break;
}
break;
}
case ACN_VECTOR_ROOT_RPT:
ProcessRPTMessage(handle, &msg);
break;
default:
log_->Warning("Received Root Layer PDU with unknown or unhandled vector %d", msg.vector);
break;
}
}
void BrokerCore::HandleRdmnetConnDisconnected(rdmnet_conn_t handle, const RdmnetDisconnectedInfo& /*disconn_info*/)
{
MarkConnForDestruction(handle);
}
void BrokerCore::SendClientList(int conn)
{
BrokerMessage bmsg;
bmsg.vector = VECTOR_BROKER_CONNECTED_CLIENT_LIST;
etcpal::ReadGuard clients_read(client_lock_);
auto to_client = clients_.find(conn);
if (to_client != clients_.end())
{
std::vector<ClientEntryData> entries;
entries.reserve(clients_.size());
for (auto client : clients_)
{
if (client.second->client_protocol == to_client->second->client_protocol)
{
ClientEntryData cli_data;
cli_data.client_cid = client.second->cid.get();
cli_data.client_protocol = client.second->client_protocol;
if (client.second->client_protocol == E133_CLIENT_PROTOCOL_RPT)
{
ClientEntryDataRpt* rpt_cli_data = GET_RPT_CLIENT_ENTRY_DATA(&cli_data);
RPTClient* rptcli = static_cast<RPTClient*>(client.second.get());
rpt_cli_data->client_uid = rptcli->uid;
rpt_cli_data->client_type = rptcli->client_type;
rpt_cli_data->binding_cid = rptcli->binding_cid.get();
}
cli_data.next = nullptr;
entries.push_back(cli_data);
// Keep the list linked for the pack function.
if (entries.size() > 1)
entries[entries.size() - 2].next = &entries[entries.size() - 1];
}
}
if (!entries.empty())
{
GET_CLIENT_LIST(&bmsg)->client_entry_list = entries.data();
to_client->second->Push(settings_.cid, bmsg);
}
}
}
void BrokerCore::SendClientsAdded(client_protocol_t client_prot, int conn_to_ignore,
std::vector<ClientEntryData>& entries)
{
BrokerMessage bmsg;
bmsg.vector = VECTOR_BROKER_CLIENT_ADD;
GET_CLIENT_LIST(&bmsg)->client_entry_list = entries.data();
for (const auto controller : controllers_)
{
if (controller.second->client_protocol == client_prot && controller.first != conn_to_ignore)
controller.second->Push(settings_.cid, bmsg);
}
}
void BrokerCore::SendClientsRemoved(client_protocol_t client_prot, std::vector<ClientEntryData>& entries)
{
BrokerMessage bmsg;
bmsg.vector = VECTOR_BROKER_CLIENT_REMOVE;
GET_CLIENT_LIST(&bmsg)->client_entry_list = entries.data();
for (const auto controller : controllers_)
{
if (controller.second->client_protocol == client_prot)
controller.second->Push(settings_.cid, bmsg);
}
}
void BrokerCore::SendStatus(RPTController* controller, const RptHeader& header, rpt_status_code_t status_code,
const std::string& status_str)
{
RptHeader new_header;
new_header.dest_endpoint_id = header.source_endpoint_id;
new_header.dest_uid = header.source_uid;
new_header.seqnum = header.seqnum;
new_header.source_endpoint_id = header.dest_endpoint_id;
new_header.source_uid = header.dest_uid;
RptStatusMsg status;
status.status_code = status_code;
if (!status_str.empty())
status.status_string = status_str.c_str();
else
status.status_string = nullptr;
if (controller->Push(settings_.cid, new_header, status))
{
log_->Warning("Sending RPT Status code %d to Controller %s", status_code, controller->cid.ToString().c_str());
}
else
{
// TODO disconnect
}
}
void BrokerCore::ProcessConnectRequest(int conn, const ClientConnectMsg* cmsg)
{
bool deny_connection = true;
rdmnet_connect_status_t connect_status = kRdmnetConnectScopeMismatch;
if ((cmsg->e133_version <= E133_VERSION) && (cmsg->scope == settings_.scope))
{
switch (cmsg->client_entry.client_protocol)
{
case E133_CLIENT_PROTOCOL_RPT:
deny_connection = !ProcessRPTConnectRequest(conn, cmsg->client_entry, connect_status);
break;
default:
connect_status = kRdmnetConnectInvalidClientEntry;
break;
}
}
if (deny_connection)
{
etcpal::ReadGuard client_read(client_lock_);
auto it = clients_.find(conn);
if (it != clients_.end() && it->second)
{
ConnectReplyMsg creply = {connect_status, E133_VERSION, my_uid_, {}};
send_connect_reply(conn, &settings_.cid.get(), &creply);
}
// Clean up this socket. TODO
// MarkSocketForDestruction(cookie, false, 0);
}
}
bool BrokerCore::ProcessRPTConnectRequest(rdmnet_conn_t handle, const ClientEntryData& data,
rdmnet_connect_status_t& connect_status)
{
bool continue_adding = true;
// We need to make a copy of the data because we might be changing the UID value
ClientEntryData updated_data = data;
ClientEntryDataRpt* rptdata = GET_RPT_CLIENT_ENTRY_DATA(&updated_data);
if (!components_.conn_interface->SetBlocking(handle, false))
{
log_->Error("Error translating socket into non-blocking socket for Client %d", handle);
return false;
}
etcpal::WriteGuard clients_write(client_lock_);
RPTClient* new_client = nullptr;
if ((settings_.max_connections > 0) && (clients_.size() >= settings_.max_connections))
{
connect_status = kRdmnetConnectCapacityExceeded;
continue_adding = false;
}
// Resolve the Client's UID
if (RDMNET_UID_IS_DYNAMIC_UID_REQUEST(&rptdata->client_uid))
{
BrokerUidManager::AddResult add_result =
components_.uids.AddDynamicUid(handle, updated_data.client_cid, rptdata->client_uid);
switch (add_result)
{
case BrokerUidManager::AddResult::kOk:
break;
case BrokerUidManager::AddResult::kDuplicateId:
connect_status = kRdmnetConnectDuplicateUid;
continue_adding = false;
break;
case BrokerUidManager::AddResult::kCapacityExceeded:
default:
connect_status = kRdmnetConnectCapacityExceeded;
continue_adding = false;
break;
}
}
else if (RDMNET_UID_IS_STATIC(&rptdata->client_uid))
{
BrokerUidManager::AddResult add_result = components_.uids.AddStaticUid(handle, rptdata->client_uid);
switch (add_result)
{
case BrokerUidManager::AddResult::kOk:
break;
case BrokerUidManager::AddResult::kDuplicateId:
connect_status = kRdmnetConnectDuplicateUid;
continue_adding = false;
break;
case BrokerUidManager::AddResult::kCapacityExceeded:
default:
connect_status = kRdmnetConnectCapacityExceeded;
continue_adding = false;
break;
}
}
else
{
// Client sent an invalid UID of some kind, like a bad dynamic UID request or a broadcast value
connect_status = kRdmnetConnectInvalidUid;
continue_adding = false;
}
if (continue_adding)
{
// If it's a controller, add it to the controller queues -- unless
// we've hit our maximum number of controllers
if (rptdata->client_type == kRPTClientTypeController)
{
if ((settings_.max_controllers > 0) && (controllers_.size() >= settings_.max_controllers))
{
connect_status = kRdmnetConnectCapacityExceeded;
continue_adding = false;
components_.uids.RemoveUid(rptdata->client_uid);
}
else
{
auto controller =
std::make_shared<RPTController>(settings_.max_controller_messages, updated_data, *clients_[handle]);
if (controller)
{
new_client = controller.get();
controllers_.insert(std::make_pair(handle, controller));
clients_[handle] = std::move(controller);
}
}
}
// If it's a device, add it to the device states -- unless we've hit
// our maximum number of devices
else if (rptdata->client_type == kRPTClientTypeDevice)
{
if ((settings_.max_devices > 0) && (devices_.size() >= settings_.max_devices))
{
connect_status = kRdmnetConnectCapacityExceeded;
continue_adding = false;
components_.uids.RemoveUid(rptdata->client_uid);
}
else
{
auto device = std::make_shared<RPTDevice>(settings_.max_device_messages, updated_data, *clients_[handle]);
if (device)
{
new_client = device.get();
devices_.insert(std::make_pair(handle, device));
clients_[handle] = std::move(device);
}
}
}
}
// The client is already part of our connections, but we need to update
// it or check if capacity is exceeded
if (continue_adding && new_client)
{
new_client->client_type = rptdata->client_type;
new_client->uid = rptdata->client_uid;
new_client->binding_cid = rptdata->binding_cid;
// Send the connect reply
BrokerMessage msg;
msg.vector = VECTOR_BROKER_CONNECT_REPLY;
ConnectReplyMsg* creply = GET_CONNECT_REPLY_MSG(&msg);
creply->connect_status = kRdmnetConnectOk;
creply->e133_version = E133_VERSION;
creply->broker_uid = my_uid_;
creply->client_uid = rptdata->client_uid;
new_client->Push(settings_.cid, msg);
if (log_->CanLog(ETCPAL_LOG_INFO))
{
log_->Info("Successfully processed RPT Connect request from %s (connection %d), UID %04x:%08x",
new_client->client_type == kRPTClientTypeController ? "Controller" : "Device", handle,
new_client->uid.manu, new_client->uid.id);
}
// Update everyone
std::vector<ClientEntryData> entries;
entries.push_back(updated_data);
entries[0].next = nullptr;
SendClientsAdded(kClientProtocolRPT, handle, entries);
}
return continue_adding;
}
void BrokerCore::ProcessRPTMessage(int conn, const RdmnetMessage* msg)
{
etcpal::ReadGuard clients_read(client_lock_);
const RptMessage* rptmsg = GET_RPT_MSG(msg);
bool route_msg = false;
auto client = clients_.find(conn);
if ((client != clients_.end()) && client->second)
{
ClientWriteGuard client_write(*client->second);
if (client->second->client_protocol == E133_CLIENT_PROTOCOL_RPT)
{
RPTClient* rptcli = static_cast<RPTClient*>(client->second.get());
switch (rptmsg->vector)
{
case VECTOR_RPT_REQUEST:
if (rptcli->client_type == kRPTClientTypeController)
{
RPTController* controller = static_cast<RPTController*>(rptcli);
if (!IsValidControllerDestinationUID(rptmsg->header.dest_uid))
{
SendStatus(controller, rptmsg->header, kRptStatusUnknownRptUid);
log_->Debug("Received Request PDU addressed to invalid or not found UID %04x:%08x from Controller %d",
rptmsg->header.dest_uid.manu, rptmsg->header.dest_uid.id, conn);
}
else if (GET_RDM_BUF_LIST(rptmsg)->list->next)
{
// There should only ever be one RDM command in an RPT request.
SendStatus(controller, rptmsg->header, kRptStatusInvalidMessage);
log_->Debug(
"Received Request PDU from Controller %d which incorrectly contains multiple RDM Command PDUs", conn);
}
else
{
route_msg = true;
}
}
else
{
log_->Debug("Received Request PDU from Client %d, which is not an RPT Controller", conn);
}
break;
case VECTOR_RPT_STATUS:
if (rptcli->client_type == kRPTClientTypeDevice)
{
if (IsValidDeviceDestinationUID(rptmsg->header.dest_uid))
{
if (GET_RPT_STATUS_MSG(rptmsg)->status_code != kRptStatusBroadcastComplete)
route_msg = true;
else
log_->Debug("Device %d sent broadcast complete message.", conn);
}
else
{
log_->Debug("Received Status PDU addressed to invalid or not found UID %04x:%08x from Device %d",
rptmsg->header.dest_uid.manu, rptmsg->header.dest_uid.id, conn);
}
}
else
{
log_->Debug("Received Status PDU from Client %d, which is not an RPT Device", conn);
}
break;
case VECTOR_RPT_NOTIFICATION:
if (rptcli->client_type != kRPTClientTypeUnknown)
{
if (IsValidDeviceDestinationUID(rptmsg->header.dest_uid))
{
route_msg = true;
}
else
{
log_->Debug("Received Notification PDU addressed to invalid or not found UID %04x:%08x from Device %d",
rptmsg->header.dest_uid.manu, rptmsg->header.dest_uid.id, conn);
}
}
else
{
log_->Debug("Received Notification PDU from Client %d of unknown client type", rptmsg->header.dest_uid.manu,
rptmsg->header.dest_uid.id, conn);
}
break;
default:
log_->Warning("Received RPT PDU with unknown vector %d from Client %d", rptmsg->vector, conn);
break;
}
}
}
if (route_msg)
{
uint16_t device_manu;
int dest_conn;
if (RDMNET_UID_IS_CONTROLLER_BROADCAST(&rptmsg->header.dest_uid))
{
log_->Debug("Broadcasting RPT message from Device %04x:%08x to all Controllers", rptmsg->header.source_uid.manu,
rptmsg->header.source_uid.id);
for (auto controller : controllers_)
{
ClientWriteGuard client_write(*controller.second);
if (!controller.second->Push(conn, msg->sender_cid, *rptmsg))
{
// TODO disconnect
log_->Error("Error pushing to send queue for RPT Controller %d. DEBUG:NOT disconnecting...",
controller.first);
}
}
}
else if (RDMNET_UID_IS_DEVICE_BROADCAST(&rptmsg->header.dest_uid))
{
log_->Debug("Broadcasting RPT message from Controller %04x:%08x to all Devices", rptmsg->header.source_uid.manu,
rptmsg->header.source_uid.id);
for (auto device : devices_)
{
ClientWriteGuard client_write(*device.second);
if (!device.second->Push(conn, msg->sender_cid, *rptmsg))
{
// TODO disconnect
log_->Error("Error pushing to send queue for RPT Device %d. DEBUG:NOT disconnecting...", device.first);
}
}
}
else if (IsDeviceManuBroadcastUID(rptmsg->header.dest_uid, device_manu))
{
log_->Debug("Broadcasting RPT message from Controller %04x:%08x to all Devices from manufacturer %04x",
rptmsg->header.source_uid.manu, rptmsg->header.source_uid.id, device_manu);
for (auto device : devices_)
{
if (device.second->uid.manu == device_manu)
{
ClientWriteGuard client_write(*device.second);
if (!device.second->Push(conn, msg->sender_cid, *rptmsg))
{
// TODO disconnect
log_->Error("Error pushing to send queue for RPT Device %d. DEBUG:NOT disconnecting...", device.first);
}
}
}
}
else
{
bool found_dest_client = false;
if (components_.uids.UidToHandle(rptmsg->header.dest_uid, dest_conn))
{
auto dest_client = clients_.find(dest_conn);
if (dest_client != clients_.end())
{
ClientWriteGuard client_write(*dest_client->second);
if (static_cast<RPTClient*>(dest_client->second.get())->Push(conn, msg->sender_cid, *rptmsg))
{
found_dest_client = true;
log_->Debug("Routing RPT PDU from Client %04x:%08x to Client %04x:%08x", rptmsg->header.source_uid.manu,
rptmsg->header.source_uid.id, rptmsg->header.dest_uid.manu, rptmsg->header.dest_uid.id);
}
else
{
// TODO disconnect
log_->Error("Error pushing to send queue for RPT Client %d. DEBUG:NOT disconnecting...",
dest_client->first);
}
}
}
if (!found_dest_client)
{
log_->Error("Could not route message from RPT Client %d (%04x:%08x): Destination UID %04x:%08x not found.",
conn, rptmsg->header.source_uid.manu, rptmsg->header.source_uid.id, rptmsg->header.dest_uid.manu,
rptmsg->header.dest_uid.id);
}
}
}
}
std::set<etcpal::IpAddr> BrokerCore::CombineMacsAndInterfaces(const std::set<etcpal::IpAddr>& interfaces,
const std::set<etcpal::MacAddr>& macs)
{
auto to_return = interfaces;
size_t num_netints = etcpal_netint_get_num_interfaces();
for (const auto& mac : macs)
{
const EtcPalNetintInfo* netint_list = etcpal_netint_get_interfaces();
for (const EtcPalNetintInfo* netint = netint_list; netint < netint_list + num_netints; ++netint)
{
if (netint->mac == mac)
{
to_return.insert(netint->addr);
// There could be multiple addresses that have this mac, we don't break here so we listen
// on all of them.
}
}
}
return to_return;
}
etcpal_socket_t BrokerCore::StartListening(const etcpal::IpAddr& ip, uint16_t& port)
{
etcpal::SockAddr addr(ip, port);
etcpal_socket_t listen_sock;
etcpal::Error res = etcpal_socket(addr.ip().IsV4() ? ETCPAL_AF_INET : ETCPAL_AF_INET6, ETCPAL_STREAM, &listen_sock);
if (!res)
{
if (log_)
{
log_->Error("Broker: Failed to create listen socket with error: %s.", res.ToCString());
}
return ETCPAL_SOCKET_INVALID;
}
if (ip.IsV6())
{
int sockopt_val = (ip.IsWildcard() ? 0 : 1);
res = etcpal_setsockopt(listen_sock, ETCPAL_IPPROTO_IPV6, ETCPAL_IPV6_V6ONLY, &sockopt_val, sizeof(int));
if (!res)
{
etcpal_close(listen_sock);
if (log_)
{
log_->Error("Broker: Failed to set V6ONLY socket option on listen socket: %s.", res.ToCString());
}
return ETCPAL_SOCKET_INVALID;
}
}
res = etcpal_bind(listen_sock, &addr.get());
if (!res)
{
etcpal_close(listen_sock);
if (log_ && log_->CanLog(ETCPAL_LOG_ERR))
{
log_->Error("Broker: Bind to %s failed on listen socket with error: %s.", addr.ToString().c_str(),
res.ToCString());
}
return ETCPAL_SOCKET_INVALID;
}
if (port == 0)
{
// Get the ephemeral port number we were assigned and which we will use for all other
// applicable network interfaces.
res = etcpal_getsockname(listen_sock, &addr.get());
if (res)
{
port = addr.port();
}
else
{
etcpal_close(listen_sock);
if (log_)
{
log_->Error("Broker: Failed to get ephemeral port assigned to listen socket: %s", res.ToCString());
}
return ETCPAL_SOCKET_INVALID;
}
}
res = etcpal_listen(listen_sock, 0);
if (!res)
{
etcpal_close(listen_sock);
if (log_)
{
log_->Error("Broker: Listen failed on listen socket with error: %s.", res.ToCString());
}
return ETCPAL_SOCKET_INVALID;
}
return listen_sock;
}
bool BrokerCore::StartBrokerServices()
{
if (!components_.threads->AddClientServiceThread())
return false;
bool success = true;
auto final_listen_addrs = CombineMacsAndInterfaces(settings_.listen_addrs, settings_.listen_macs);
if (final_listen_addrs.empty())
{
// Listen on in6addr_any
const auto any_addr = etcpal::IpAddr::WildcardV6();
etcpal_socket_t listen_sock = StartListening(any_addr, settings_.listen_port);
if (listen_sock != ETCPAL_SOCKET_INVALID)
{
if (!components_.threads->AddListenThread(listen_sock))
{
etcpal_close(listen_sock);
success = false;
}
}
else
{
log_->Critical("Could not bind a wildcard listening socket.");
success = false;
}
}
else
{
// Listen on a specific set of interfaces supplied by the library user
auto addr_iter = final_listen_addrs.begin();
while (addr_iter != final_listen_addrs.end())
{
etcpal_socket_t listen_sock = StartListening(*addr_iter, settings_.listen_port);
if (listen_sock != ETCPAL_SOCKET_INVALID && components_.threads->AddListenThread(listen_sock))
{
if (components_.threads->AddListenThread(listen_sock))
{
++addr_iter;
}
else
{
etcpal_close(listen_sock);
addr_iter = final_listen_addrs.erase(addr_iter);
}
}
else
{
addr_iter = final_listen_addrs.erase(addr_iter);
}
}
// Errors on some interfaces are tolerated as long as we have at least one to listen on.
if (final_listen_addrs.empty())
{
log_->Critical("Could not listen on any provided IP addresses.");
success = false;
}
}
return success;
}
void BrokerCore::StopBrokerServices()
{
components_.threads->StopThreads();
// No new connections coming in, manually shut down the existing ones.
std::vector<rdmnet_conn_t> conns;
GetConnSnapshot(conns, true, true, true);
for (auto& conn : conns)
MarkConnForDestruction(conn, SendDisconnect(kRdmnetDisconnectShutdown));
DestroyMarkedClientSockets();
}
// This function grabs a read lock on client_lock_.
// Optionally sends a RDMnet-level disconnect message.
void BrokerCore::MarkConnForDestruction(rdmnet_conn_t conn, SendDisconnect send_disconnect)
{
bool found = false;
{ // Client read lock and destroy lock scope
etcpal::ReadGuard clients_read(client_lock_);
auto client = clients_.find(conn);
if ((client != clients_.end()) && client->second)
{
ClientWriteGuard client_write(*client->second);
found = true;
clients_to_destroy_.insert(client->first);
}
}
if (found)
{
components_.conn_interface->DestroyConnection(conn, send_disconnect);
log_->Debug("Connection %d marked for destruction", conn);
}
}
// These functions will take a write lock on client_lock_ and client_destroy_lock_.
void BrokerCore::DestroyMarkedClientSockets()
{
etcpal::WriteGuard clients_write(client_lock_);
std::vector<ClientEntryData> entries;
if (!clients_to_destroy_.empty())
{
for (auto to_destroy : clients_to_destroy_)
{
auto client = clients_.find(to_destroy);
if (client != clients_.end())
{
ClientEntryData entry;
entry.client_protocol = client->second->client_protocol;
entry.client_cid = client->second->cid.get();
if (client->second->client_protocol == E133_CLIENT_PROTOCOL_RPT)
{
RPTClient* rptcli = static_cast<RPTClient*>(client->second.get());
components_.uids.RemoveUid(rptcli->uid);
if (rptcli->client_type == kRPTClientTypeController)
controllers_.erase(to_destroy);
else if (rptcli->client_type == kRPTClientTypeDevice)
devices_.erase(to_destroy);
ClientEntryDataRpt* rptdata = GET_RPT_CLIENT_ENTRY_DATA(&entry);
rptdata->client_uid = rptcli->uid;
rptdata->client_type = rptcli->client_type;
rptdata->binding_cid = rptcli->binding_cid.get();
}
entries.push_back(entry);
entries[entries.size() - 1].next = nullptr;
if (entries.size() > 1)
entries[entries.size() - 2].next = &entries[entries.size() - 1];
clients_.erase(client);
log_->Info("Removing connection %d marked for destruction.", to_destroy);
if (log_->CanLog(ETCPAL_LOG_DEBUG))
{
log_->Debug("Clients: %zu Controllers: %zu Devices: %zu", clients_.size(), controllers_.size(),
devices_.size());
}
}
}
clients_to_destroy_.clear();
}
if (!entries.empty())
SendClientsRemoved(entries[0].client_protocol, entries);
}
void BrokerCore::HandleBrokerRegistered(const std::string& scope, const std::string& requested_service_name,
const std::string& assigned_service_name)
{
service_registered_ = true;
if (requested_service_name == assigned_service_name)
{
log_->Info("Broker \"%s\" successfully registered at scope \"%s\"", requested_service_name.c_str(), scope.c_str());
}
else
{
log_->Info("Broker \"%s\" (now named \"%s\") successfully registered at scope \"%s\"",
requested_service_name.c_str(), assigned_service_name.c_str(), scope.c_str());
}
}
void BrokerCore::HandleBrokerRegisterError(const std::string& scope, const std::string& requested_service_name,
int platform_specific_error)
{
log_->Critical("Broker \"%s\" register error %d at scope \"%s\"", requested_service_name.c_str(),
platform_specific_error, scope.c_str());
}
void BrokerCore::HandleOtherBrokerFound(const RdmnetBrokerDiscInfo& broker_info)
{
// If the broker is already registered with DNS-SD, the presence of another broker is an error
// condition. Otherwise, the system is still usable (this broker will not register)
int log_pri = (service_registered_ ? ETCPAL_LOG_ERR : ETCPAL_LOG_NOTICE);
if (log_->CanLog(log_pri))
{
std::string addrs;
for (size_t i = 0; i < broker_info.num_listen_addrs; ++i)
{
char addr_string[ETCPAL_INET6_ADDRSTRLEN];
if (kEtcPalErrOk == etcpal_inet_ntop(&broker_info.listen_addrs[i], addr_string, ETCPAL_INET6_ADDRSTRLEN))
{
addrs.append(addr_string);
if (i < broker_info.num_listen_addrs - 1)
addrs.append(", ");
}
}
log_->Log(log_pri, "Broker \"%s\", ip[%s] found at same scope(\"%s\") as this broker.", broker_info.service_name,
addrs.c_str(), broker_info.scope);
}
if (!service_registered_)
{
log_->Log(log_pri, "This broker will remain unregistered with DNS-SD until all conflicting brokers are removed.");
// StopBrokerServices();
}
}
void BrokerCore::HandleOtherBrokerLost(const std::string& scope, const std::string& service_name)
{
log_->Notice("Conflicting broker %s on scope \"%s\" no longer discovered.", service_name.c_str(), scope.c_str());
}
void BrokerCore::HandleScopeMonitorError(const std::string& scope, int platform_error)
{
log_->Error("Error code %d encountered while monitoring broker's scope \"%s\" for other brokers.", platform_error,
scope.c_str());
}
| 32.215413 | 120 | 0.647654 | [
"vector"
] |
104b7738788360980a631b708855915b8812818d | 2,872 | cpp | C++ | dirpg_tsp/retsp/batched_heaps.cpp | GuyLor/attention-learn-to-route | d07d5c1465f7ee5d18651e23cfae9aa1f52a9c6c | [
"MIT"
] | null | null | null | dirpg_tsp/retsp/batched_heaps.cpp | GuyLor/attention-learn-to-route | d07d5c1465f7ee5d18651e23cfae9aa1f52a9c6c | [
"MIT"
] | null | null | null | dirpg_tsp/retsp/batched_heaps.cpp | GuyLor/attention-learn-to-route | d07d5c1465f7ee5d18651e23cfae9aa1f52a9c6c | [
"MIT"
] | null | null | null |
#include "batched_heaps.h"
#include<vector>
using namespace std;
void Heap::push(HeapNode new_node) {
elements_.push_back(new_node);
push_heap(elements_.begin(), elements_.end());
}
HeapNode Heap::pop(){
HeapNode result = elements_.front();
pop_heap(elements_.begin(), elements_.end());
elements_.pop_back();
return result;
}
bool Heap::is_empty() {
return elements_.empty();
};
void Heap::clearHeap(){
elements_.clear();
}
void Heap::printHeap(){
py::print("#########", elements_.size() ,"##########");
for (int i=0; i<elements_.size(); i++){
py::print("------------------------");
elements_[i].dump();
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
BatchedHeaps::BatchedHeaps(int batch_size, bool prune_flag){
batch_size_ = batch_size;
prune_flag_ = prune_flag;
for (int i=0; i<batch_size_; i++){
heaps_.push_back(Heap());
}
}
HeapNode BatchedHeaps::pop(int heap_id, int sample_idx, ToptTdirect &trajectories, EmptyHeapsFilter &heaps_filter){
bool to_pop = true; //!heaps_[sample_idx].is_empty();
bool stop_first_improvement = false;
HeapNode node;
while (to_pop){
node = heaps_[heap_id].pop();
bool empty_heap = heaps_[heap_id].is_empty();
//if (!node.t_opt){
// trajectories.t_direct.objectives[sample_idx]
//}
bool to_prune = (prune_flag_ && node.to_prune(trajectories.t_direct.objectives[heap_id])) ||
(node.outer_node.steps_left > heaps_filter.budget_left);
if (to_prune){
trajectories.prune_count[heap_id] += 1;
/*
if(heap_id == 0){
py::print("-------trajectory--------");
trajectories.t_direct.dump(heap_id);
py::print("--------pruned node-------");
node.dump();
}
*/
}
if(node.done){
trajectories.setTrajectory(heap_id, node.outer_node);
if (trajectories.improvement_flag[heap_id])
stop_first_improvement = true;
}
if (empty_heap || stop_first_improvement) {heaps_filter.filter(heap_id, sample_idx);}
//non_empty_heaps[sample_idx] = non_empty_heap;
to_pop = (node.done || to_prune) && !empty_heap && !stop_first_improvement;
}
return node;
}
void BatchedHeaps::push(int heap_id, OuterNode outer_node){
HeapNode node(outer_node);
//node.dump();
heaps_[heap_id].push(node);
}
void BatchedHeaps::clearHeaps(){
for (int i=0; i<batch_size_; i++){
heaps_[i].clearHeap();
}
}
void BatchedHeaps::printHeap(int heap_id){
heaps_[heap_id].printHeap();
} | 27.883495 | 115 | 0.548747 | [
"vector"
] |
104c924e0999df0e1a814f1e7ae9e9a668e44b9d | 14,057 | cpp | C++ | CustomTileSet.cpp | bilalCh213/Console-Platformer | 87250d5c864d828b1111c94c96620e48a37f093b | [
"MIT"
] | null | null | null | CustomTileSet.cpp | bilalCh213/Console-Platformer | 87250d5c864d828b1111c94c96620e48a37f093b | [
"MIT"
] | null | null | null | CustomTileSet.cpp | bilalCh213/Console-Platformer | 87250d5c864d828b1111c94c96620e48a37f093b | [
"MIT"
] | null | null | null |
/*
FUNCTIONS FOR FRAMERUNNER:
customTileSet();
notSolidTileSet();
tileProperties();
FUNCTIONS FOR INTERNAL USE:
DrawTileLine(int, int, int, int, string, string);
*/
using namespace std;
string h = "h";
string v = "v";
string r = "r";
string l = "l";
int maxL = 2;
int maxR = 50;
//Draw TileSet Line
void DrawTileLine(int w1, int w2, int h1, int h2, string tile, string is_h_or_v)
{
if(is_h_or_v == h)
{
for (int lineFactor = w1; lineFactor < w2; lineFactor++)
{
h2 = h1;
px[lineFactor][h1] = tile;
}
}
else if(is_h_or_v == v)
{
for (int lineFactor = h1; lineFactor < h2; lineFactor++)
{
w2 = w1;
px[w1][lineFactor] = tile;
}
}
}
void EntranceToRoom(int height, string R_or_L)
{
if(R_or_L == r)
{
px[wallEntr_r][height - 1] = entrRoom;
px[wallEntr_r][height] = entrRoom;
px[wallEntr_r][height + 1] = entrRoom;
}
else if(R_or_L == l)
{
px[wallEntr_l][height - 1] = entrRoom;
px[wallEntr_l][height] = entrRoom;
px[wallEntr_l][height + 1] = entrRoom;
}
}
//Custom TileSet Arrangements for each level
void customTileSet() //Only for Solid blocks
{
/*
To spot a tile:
px[ width ][ height ] = name of tile;
To draw a line:
DrawTileLine( width1, width2, height1, height2, name of tile, if want horizontal line type 'h' else for vertical type 'v')
First point in DrawTileLine is not rendered
width2 must be greater than width1
height2 must be greater than height1
width2 = width1 for vertical line
height2 = height1 for horizon line
Max height = 22, Max Width = 53
*/
if( lv == 0)
{
if( room[0] == 0)
{
DrawTileLine(25,29,4,4,roof,h);
DrawTileLine(10,13,10,10,_floor,h);
DrawTileLine(40,43,10,10,_floor,h);
}
}
else if( lv == 1 )
{
if( room[1] == 0)
{
DrawTileLine(22,32,15,15,roof,h);
DrawTileLine(22,32,11,11,roof,h);
DrawTileLine(12,41,9,9,roof,h);
DrawTileLine(7,13,12,12,_floor,h);
DrawTileLine(9,13,15,15,_floor,h);
DrawTileLine(40,46,12,12,_floor,h);
DrawTileLine(40,44,15,15,_floor,h);
DrawTileLine(22,22,11,15,wall,v);
DrawTileLine(31,31,11,15,wall,v);
}
}
else if( lv == 2 )
{
if( room[2] == 0)
{
DrawTileLine(19,30,10,10,_floor,h);
DrawTileLine(35,46,10,10,_floor,h);
DrawTileLine(29,44,7,7,roof,h);
DrawTileLine(2,32,16,16,roof,h);
DrawTileLine(31,51,16,16,_floor,h);
DrawTileLine(2,32,13,13,_floor,h);
DrawTileLine(31,51,13,13,roof,h);
}
}
else if( lv == 3 )
{
if( room[3] == 0)
{
DrawTileLine(2,8,15,15,_floor,h);
DrawTileLine(2,8,12,12,_floor,h);
DrawTileLine(2,8,9,9,_floor,h);
DrawTileLine(2,8,6,6,_floor,h);
DrawTileLine(45,51,15,15,_floor,h);
DrawTileLine(45,51,12,12,_floor,h);
DrawTileLine(45,51,9,9,_floor,h);
DrawTileLine(45,51,6,6,_floor,h);
DrawTileLine(21,33,10,10,roof,h);
DrawTileLine(13,22,11,11,_floor,h);
DrawTileLine(32,41,11,11,_floor,h);
}
}
else if( lv == 4 )
{
if( room[4] == 0)
{
DrawTileLine(2,10,15,15,_floor,h);
DrawTileLine(2,9,12,12,_floor,h);
DrawTileLine(2,51,9,9,_floor,h);
DrawTileLine(39,51,6,6,_floor,h);
DrawTileLine(2,51,3,3,_floor,h);
DrawTileLine(10,43,9,9,roof,h);
px[16][2] = plPassWall;
px[22][2] = plPassWall;
}
}
else if( lv == 5 )
{
if( room[5] == 0)
{
px[4][14] = _floor;
px[5][14] = _floor;
px[6][14] = _floor;
px[9][13] = _floor;
px[12][14] = _floor;
px[15][15] = _floor;
px[16][15] = _floor;
px[18][13] = _floor;
px[21][14] = _floor;
px[24][12] = _floor;
px[27][13] = _floor;
px[30][12] = _floor;
px[33][11] = _floor;
px[36][13] = _floor;
px[39][11] = _floor;
px[41][10] = _floor;
px[42][9] = _floor;
px[43][9] = _floor;
px[47][7] = _floor;
px[48][7] = _floor;
px[49][7] = _floor;
px[50][7] = _floor;
px[50][11] = _floor;
px[50][15] = _floor;
DrawTileLine(2,51,19,19,spikes,h);
px[50][19] = _floor;
}
}
/*
From level 5 onwards, there is used Connected Room System to make levels more bigger!
It must be set in proper order else it will not work i.e the room number increases from left to right. The entrances must be made according to the room number order:
[ 0 ][ 1 ][ 2 ][ 3 ][ 4 ][ 5 ] << Proper order of room numbers
[ 0 ][ 3 ][ 1 ][ 2 ][ 5 ][ 4 ] << Wrong way!
[ 5 ][ 4 ][ 3 ][ 2 ][ 1 ][ 0 ] << Wrong way!
Entrance should not be at left side of 0-room and at right side of 5-room.
Tile used for entrance to other rooms:
entrRoom
Function for wall to enter other rooms:
EntranceToRoom( height {mid of point}, at right or left side);
IMP. NOTE:
Right Side means Increase in Room Number.
Left Side means Decrease in Room Number.
*/
else if( lv == 6)
{
if( room[6] == 0)
{
EntranceToRoom(17,r);
EntranceToRoom(8,r);
DrawTileLine(maxL,(maxR + 1),10,10,_floor,h);
DrawTileLine(6,12,10,10,roof,h);
DrawTileLine(15,21,7,7,_floor,h);
DrawTileLine(24,30,7,7,_floor,h);
DrawTileLine(33,39,7,7,_floor,h);
DrawTileLine(42,48,7,7,_floor,h);
DrawTileLine(maxL,(maxL + 10),13,13,_floor,h);
DrawTileLine(13,(maxR - 4),10,10,spikes,h);
DrawTileLine(35,45,18,18,_floor,h);
}
else if( room[6] == 1)
{
EntranceToRoom(17,l);
EntranceToRoom(8,l);
DrawTileLine(maxL,37,10,10,roof,h);
DrawTileLine(maxL,(maxL + 10),13,13,_floor,h);
DrawTileLine(40,(maxR + 1),15,15,_floor,h);
DrawTileLine(40,(maxR + 1),12,12,_floor,h);
DrawTileLine(40,(maxR + 1),9,9,_floor,h);
DrawTileLine(40,(maxR + 1),6,6,_floor,h);
DrawTileLine(maxL,(maxR + 1),3,3,_floor,h);
DrawTileLine(maxL,(maxL + 4),3,3,roof,h);
DrawTileLine(10,10,1,3,plPassWall,v);
}
}
else if( lv == 7)
{
if( room[7] == 0)
{
EntranceToRoom(17,r);
EntranceToRoom(8,r);
DrawTileLine(maxL,(maxR + 1),10,10,_floor,h);
DrawTileLine(maxL,(maxL + 16),13,13,_floor,h);
DrawTileLine(maxL,(maxL + 8),16,16,_floor,h);
DrawTileLine((maxL + 36),(maxL + 36),4,10,wall,v);
DrawTileLine((maxL + 36),(maxL + 36),1,4,plPassWall,v);
DrawTileLine((maxL + 20),(maxL + 36),7,7,_floor,h);
DrawTileLine((maxL + 28),(maxL + 36),4,4,_floor,h);
}
else if( room[7] == 1)
{
EntranceToRoom(17,r);
EntranceToRoom(17,l);
EntranceToRoom(8,r);
EntranceToRoom(8,l);
DrawTileLine(maxL,(maxR + 1),10,10,_floor,h);
DrawTileLine(26,26,1,10,wall,v);
DrawTileLine(16,37,7,7,_floor,h);
DrawTileLine(16,37,4,4,_floor,h);
DrawTileLine(24,29,10,10,roof,h);
DrawTileLine(40,45,18,18,_floor,h);
DrawTileLine(10,15,18,18,_floor,h);
}
else if( room[7] == 2)
{
EntranceToRoom(17,l);
EntranceToRoom(8,l);
DrawTileLine(maxL,(maxR + 1),10,10,_floor,h);
DrawTileLine((maxR - 16),(maxR + 1),13,13,_floor,h);
DrawTileLine((maxR - 8),(maxR + 1),16,16,_floor,h);
DrawTileLine((maxR - 36),(maxR - 36),4,10,wall,v);
DrawTileLine((maxR - 36),(maxR - 36),1,4,plPassWall,v);
DrawTileLine((maxR - 35),(maxR - 20),7,7,_floor,h);
DrawTileLine((maxR - 35),(maxR - 27),4,4,_floor,h);
}
}
else if( lv == 8)
{
if( room[8] == 0)
{
EntranceToRoom(7,r);
EntranceToRoom(12,r);
EntranceToRoom(17,r);
//DrawTileLine(maxL,(maxR + 1),10,10,roof,h);
DrawTileLine((maxL + 26),(maxR + 1),14,14,_floor,h);
DrawTileLine(28,32,16,16,_floor,h);
DrawTileLine((maxR - 12),(maxR + 1),9,9,roof,h);
DrawTileLine((maxR - 20),(maxR - 13),8,8,roof,h);
DrawTileLine((maxR - 28),(maxR - 21),7,7,roof,h);
DrawTileLine((maxR - 36),(maxR - 29),6,6,roof,h);
DrawTileLine((maxL),(maxR - 39),6,6,_floor,h);
}
else if( room[8] == 1)
{
EntranceToRoom(7,l);
EntranceToRoom(3,r);
EntranceToRoom(17,r);
EntranceToRoom(17,l);
EntranceToRoom(12,l);
EntranceToRoom(12,r);
//DrawTileLine(maxL,(maxR + 1),10,10,roof,h);
DrawTileLine((maxL),6,4,4,_floor,h);
DrawTileLine(maxL,(maxR + 1),14,14,_floor,h);
DrawTileLine((maxR - 6), (maxR + 1), 5,5,_floor,h);
DrawTileLine((maxR - 14), (maxR - 8), 7,7,_floor,h);
DrawTileLine((maxR - 20), (maxR - 15),6,6,_floor,h);
DrawTileLine((maxR - 28), (maxR - 22),7,7,_floor,h);
DrawTileLine((maxR - 36), (maxR - 30),7,7,_floor,h);
DrawTileLine((maxL), (maxR - 40),9,9,roof,h);
DrawTileLine(24,29,14,14,roof,h);
}
else if( room[8] == 2)
{
EntranceToRoom(12,l);
EntranceToRoom(17,l);
EntranceToRoom(3,l);
//DrawTileLine(maxL,(maxR - 11),10,10,roof,h);
DrawTileLine(maxL,(maxR - 12),14,14,_floor,h);
DrawTileLine((maxR - 11), (maxR + 1),10,10,_floor,h);
DrawTileLine((maxR - 11), (maxR + 1),13,13,_floor,h);
DrawTileLine((maxR - 11), (maxR + 1),16,16,_floor,h);
DrawTileLine((maxR - 11), (maxR + 1),7,7,_floor,h);
DrawTileLine((maxR - 11), (maxR + 1),4,4,_floor,h);
DrawTileLine((maxR - 12), (maxR - 11),4,17,wall,v);
DrawTileLine((maxR - 18), (maxR - 12),4,4,_floor,h);
DrawTileLine((maxR - 25), (maxR - 19),5,5,_floor,h);
DrawTileLine((maxR - 32), (maxR - 26),4,4,_floor,h);
DrawTileLine((maxR - 39), (maxR - 33),5,5,_floor,h);
DrawTileLine((maxR - 46), (maxR - 40),4,4,_floor,h);
px[maxL][5] = _floor;
px[(maxL + 1)][5] = _floor;
}
}
else if( lv == 9)
{
if( room[9] == 0)
{
EntranceToRoom(2,r);
DrawTileLine(21,(maxR + 1),16,16,_floor,h);
DrawTileLine(21,33,13,13,_floor,h);
DrawTileLine((maxL),33,10,10,_floor,h);
DrawTileLine(21,33,7,7,_floor,h);
DrawTileLine(21,(maxR + 1),4,4,_floor,h);
}
else if( room[9] == 1)
{
EntranceToRoom(8,r);
EntranceToRoom(2,l);
DrawTileLine((maxL),33,16,16,_floor,h);
DrawTileLine(21,33,13,13,_floor,h);
DrawTileLine(21,(maxR + 1),10,10,_floor,h);
DrawTileLine(21,33,7,7,_floor,h);
DrawTileLine((maxL),33,4,4,_floor,h);
}
else if( room[9] == 2)
{
EntranceToRoom(8,l);
DrawTileLine(21,(maxR + 1),16,16,_floor,h);
DrawTileLine(21,33,13,13,_floor,h);
DrawTileLine((maxL),33,10,10,_floor,h);
DrawTileLine(21,33,7,7,_floor,h);
DrawTileLine(21,(maxR + 1),4,4,_floor,h);
}
}
else if( lv == maxLv)
{
run = false;
}
isTileDone = true;
}
//notSolid TileSet arrangements for each level
void notSolidTileSet() //Only for NotSolid blocks
{
if(lvSet == true)
{
//Resetting all grave position values
for(int n = 0; n < totalGravesUsed; n++)
{
gravePosW[n] = zeroPosW;
gravePosH[n] = zeroPosH;
}
//Resetting grave enemy generation delay
for(int i = 0; i < totalGravesUsed; i++)
{
enemyRegenDelay[i] = maxEnemyRegenDelay;
}
}
//Power Indicator
if(plH != zeroPosH)
{
px[plW][plH - 1] = powInd;
}
//All doors rendered by this
if(room[lv] == doorRoom[lv])
{
px[doorlv_w[lv]][doorlv_h[lv]] = door;
}
//All shops(shopPlaces) rendered by this
if(room[lv] == shopRoom[lv])
{
px[shoplv_w[lv]][shoplv_h[lv]] = shop;
}
//Specific lv and room notSolid TileSets
//For Grave, mention position:gravePosW[](gPW),gravePosH[](gPH, and then, mention display: px[gPW][gPH] = grave;
//Other notSolid TileSets
if(lv == 9)
{
if(room[9] == 0)
{
gravePosW[0] = (maxR - 3);
gravePosH[0] = 15;
px[gravePosW[0]][gravePosH[0]] = grave;
gravePosW[1] = (maxL + 3);
gravePosH[1] = 9;
px[gravePosW[1]][gravePosH[1]] = grave;
gravePosW[2] = (maxR - 3);
gravePosH[2] = 3;
px[gravePosW[2]][gravePosH[2]] = grave;
}
else if(room[9] == 1)
{
gravePosW[0] = (maxL + 3);
gravePosH[0] = 15;
px[gravePosW[0]][gravePosH[0]] = grave;
gravePosW[1] = (maxR - 3);
gravePosH[1] = 9;
px[gravePosW[1]][gravePosH[1]] = grave;
gravePosW[2] = (maxL + 3);
gravePosH[2] = 3;
px[gravePosW[2]][gravePosH[2]] = grave;
}
else if(room[9] == 2)
{
gravePosW[0] = (maxR - 3);
gravePosH[0] = 15;
px[gravePosW[0]][gravePosH[0]] = grave;
gravePosW[1] = (maxL + 3);
gravePosH[1] = 9;
px[gravePosW[1]][gravePosH[1]] = grave;
gravePosW[2] = (maxR - 3);
gravePosH[2] = 3;
px[gravePosW[2]][gravePosH[2]] = grave;
}
}
}
//Particular TileSet properties
void tileProperties()
{
// FOR SOLID TILES
//For Permeable Wall
if(px[plW][plH] == plPassWall)
{
px[plW][plH] = pl;
}
// FOR NOT SOLID TILES
// For Grave
for(int i = 0; i < totalGravesUsed; i++)
{
if(
(gravePosW[i] != zeroPosW)
&& (gravePosH[i] != zeroPosH)
&& (enemyRegenDelay[i] <= 0)
)
{
for(int n = totalDefaultEnemies[room[lv]]; n < eNumb; n++)
{
if(eRun[n] == false)
{
eH[n] = gravePosH[i];
eW[n] = gravePosW[i];
eRun[n] = true;
eLoot[n] = true;
eFromGrave[n] = true;
goto oneEonly;
}
}
oneEonly:
enemyRegenDelay[i] = maxEnemyRegenDelay;
}
else if(enemyRegenDelay[i] > 0)
{
enemyRegenDelay[i]--;
}
}
for(int eG = totalDefaultEnemies[room[lv]]; eG < eNumb; eG++)
{
if(eFromGrave[eG] == true)
{
px[eW[eG]][eH[eG]] = enem[grave_eType];
eSetNumb(eG);
eFromGrave[eG] = false;
eFromGraveDisplay[eG] = true;
}
else if(eFromGraveDisplay[eG] == true && eHp[eG] > 0)
{
px[eW[eG]][eH[eG]] = enem[grave_eType];
}
}
// For Power Indicator
//SlowPow
if(isSlowPow == true)
{
if(slowPowDelay > 0)
{
if(slowPowDelay > emerSlowPow)
{
powInd = slowPowGInd;
}
else if(slowPowDelay <= emerSlowPow && slowPowDelay > 0)
{
if(powInd == slowPowGInd)
{
powInd = _empty;
}
else if(powInd == _empty)
{
powInd = slowPowGInd;
}
}
}
else if(slowPowDelay <= 0)
{
powInd = _empty;
}
}
//Regenerate
else if(isRegenerate == true)
{
if(regenDelay > 0)
{
if(regenDelay > emerRegenerate)
{
powInd = regenerateGInd;
}
else if(regenDelay <= emerRegenerate && regenDelay > 0)
{
if(powInd == regenerateGInd)
{
powInd = _empty;
}
else if(powInd == _empty)
{
powInd = regenerateGInd;
}
}
}
else if(regenDelay <= 0)
{
powInd = _empty;
}
}
//Add Power here
else
{
powInd = _empty;
}
notSolid[3] = powInd;
} | 23.78511 | 166 | 0.59337 | [
"solid"
] |
1051bac0944962fa3c3c3a2dc641000cd8298f2c | 5,914 | cc | C++ | src/kudu/client/authz_token_cache.cc | shirodkara/kudu | 1e39599b458c57c4016fc28680f2579d6472ce0b | [
"Apache-2.0"
] | 1 | 2019-09-27T10:01:52.000Z | 2019-09-27T10:01:52.000Z | src/kudu/client/authz_token_cache.cc | TingyLiang/kudu | 8c14875659b7edd0f4353e945351eada8d5fb9e3 | [
"Apache-2.0"
] | 1 | 2021-02-23T19:20:32.000Z | 2021-02-24T08:41:41.000Z | src/kudu/client/authz_token_cache.cc | TingyLiang/kudu | 8c14875659b7edd0f4353e945351eada8d5fb9e3 | [
"Apache-2.0"
] | null | null | null | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "kudu/client/authz_token_cache.h"
#include <cstdint>
#include <mutex>
#include <string>
#include <unordered_map>
#include <vector>
#include <boost/bind.hpp> // IWYU pragma: keep
#include <glog/logging.h>
#include "kudu/client/client-internal.h"
#include "kudu/client/client.h"
#include "kudu/client/master_proxy_rpc.h"
#include "kudu/common/wire_protocol.h"
#include "kudu/gutil/bind.h"
#include "kudu/gutil/bind_helpers.h"
#include "kudu/gutil/callback.h"
#include "kudu/gutil/map-util.h"
#include "kudu/gutil/port.h"
#include "kudu/gutil/strings/substitute.h"
#include "kudu/master/master.pb.h"
#include "kudu/master/master.proxy.h"
#include "kudu/rpc/response_callback.h"
#include "kudu/rpc/rpc.h"
#include "kudu/security/token.pb.h"
#include "kudu/util/monotime.h"
#include "kudu/util/status.h"
#include "kudu/util/status_callback.h"
using std::string;
using std::vector;
using strings::Substitute;
namespace kudu {
using master::MasterFeatures;
using master::MasterServiceProxy;
using rpc::BackoffType;
using security::SignedTokenPB;
namespace client {
namespace internal {
RetrieveAuthzTokenRpc::RetrieveAuthzTokenRpc(const KuduTable* table,
MonoTime deadline)
: AsyncLeaderMasterRpc(deadline, table->client(), BackoffType::LINEAR, req_, &resp_,
&MasterServiceProxy::GetTableSchemaAsync, "RetrieveAuthzToken",
Bind(&AuthzTokenCache::RetrievedNewAuthzTokenCb,
Unretained(&table->client()->data_->authz_token_cache_),
table->id()),
{ MasterFeatures::GENERATE_AUTHZ_TOKEN }),
table_(table) {
req_.mutable_table()->set_table_id(table_->id());
}
string RetrieveAuthzTokenRpc::ToString() const {
return Substitute("$0 { table: '$1' ($2), attempt: $3 }", AsyncLeaderMasterRpc::ToString(),
req_.table().table_name(), req_.table().table_id(), num_attempts());
}
void RetrieveAuthzTokenRpc::SendRpcCb(const Status& status) {
Status new_status = status;
// Check for generic master RPC errors.
if (RetryOrReconnectIfNecessary(&new_status)) {
return;
}
// Unwrap and return any other application errors that may be returned by the
// master service.
if (new_status.ok() && resp_.has_error()) {
new_status = StatusFromPB(resp_.error().status());
}
if (new_status.ok()) {
// Note: legacy masters will be caught by the required GENERATE_AUTHZ_TOKEN
// feature, and so we can only get here without an authz token if the
// master didn't return one, which is a programming error.
DCHECK(resp_.has_authz_token());
if (PREDICT_TRUE(resp_.has_authz_token())) {
client_->data_->authz_token_cache_.Put(table_->id(), resp_.authz_token());
}
}
user_cb_.Run(new_status);
}
void AuthzTokenCache::Put(const string& table_id, SignedTokenPB authz_token) {
VLOG(1) << Substitute("Putting new token for table $0 into the token cache", table_id);
std::lock_guard<simple_spinlock> l(token_lock_);
EmplaceOrUpdate(&authz_tokens_, table_id, std::move(authz_token));
}
bool AuthzTokenCache::Fetch(const string& table_id, SignedTokenPB* authz_token) {
DCHECK(authz_token);
std::lock_guard<simple_spinlock> l(token_lock_);
const auto* token = FindOrNull(authz_tokens_, table_id);
if (token) {
*authz_token = *token;
return true;
}
return false;
}
void AuthzTokenCache::RetrieveNewAuthzToken(const KuduTable* table,
StatusCallback callback,
MonoTime deadline) {
DCHECK(table);
DCHECK(deadline.Initialized());
const string& table_id = table->id();
std::unique_lock<simple_spinlock> l(rpc_lock_);
// If there already exists an RPC for this table; attach the callback.
auto* rpc_and_cbs = FindOrNull(authz_rpcs_, table_id);
if (rpc_and_cbs) {
DCHECK(!rpc_and_cbs->second.empty());
VLOG(2) << Substitute("Binding to in-flight RPC to retrieve authz token for $0", table_id);
rpc_and_cbs->second.emplace_back(std::move(callback));
} else {
// Otherwise, send out a new RPC.
VLOG(2) << Substitute("Sending new RPC to retrieve authz token for $0", table_id);
scoped_refptr<RetrieveAuthzTokenRpc> rpc(new RetrieveAuthzTokenRpc(table, deadline));
EmplaceOrDie(&authz_rpcs_, table_id,
RpcAndCallbacks(rpc, { std::move(callback) }));
l.unlock();
rpc->SendRpc();
}
}
void AuthzTokenCache::RetrievedNewAuthzTokenCb(const string& table_id,
const Status& status) {
VLOG(1) << Substitute("Retrieved new authz token for table $0", table_id);
vector<StatusCallback> cbs;
{
// Erase the RPC from our in-flight map.
std::lock_guard<simple_spinlock> l(rpc_lock_);
auto rpc_and_cbs = EraseKeyReturnValuePtr(&authz_rpcs_, table_id);
cbs = std::move(rpc_and_cbs.second);
}
DCHECK(!cbs.empty());
for (const auto& cb : cbs) {
cb.Run(status);
}
}
} // namespace internal
} // namespace client
} // namespace kudu
| 36.506173 | 95 | 0.690396 | [
"vector"
] |
10558556fd00e0479ed8eb8a9c4b83eda6274a9b | 22,929 | cc | C++ | src/samples/rsxgl_sample_base2/main.cc | williamblair/RSXGL | ffe01772456aac795961a0ab3532580f9cea84bb | [
"BSD-2-Clause"
] | 5 | 2021-06-05T19:30:07.000Z | 2021-07-05T20:22:34.000Z | src/samples/rsxgl_sample_base2/main.cc | williamblair/RSXGL | ffe01772456aac795961a0ab3532580f9cea84bb | [
"BSD-2-Clause"
] | null | null | null | src/samples/rsxgl_sample_base2/main.cc | williamblair/RSXGL | ffe01772456aac795961a0ab3532580f9cea84bb | [
"BSD-2-Clause"
] | 1 | 2021-08-14T23:47:49.000Z | 2021-08-14T23:47:49.000Z | /*
* rsxgltest - host code
*
* I promise this won't become a rewrite of GLUT. In fact, I plan to switch to SDL soon.
*/
#include <EGL/egl.h>
#define GL3_PROTOTYPES
//#define _GNU_SOURCE
#include <GL3/gl3.h>
#include <GL3/rsxgl.h>
#include <GL3/rsxgl3ext.h>
#include <stddef.h>
#include <net/net.h>
#include <sysutil/sysutil.h>
#include <io/pad.h>
#include "sine_wave.h"
#include <stdio.h>
#include <unistd.h>
#include <malloc.h>
#include <string.h>
#include <errno.h>
#include <math.h>
#include "math3d.h"
#include <time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <Eigen/Geometry>
#include <stdarg.h>
#include "rsxgl_config.h"
#include <rsx/commands.h>
#include "texcube_vert.h"
#include "texcube_frag.h"
const float geometry[] = {
0,0,0,1, 0,
1,0,0,1, 1,
1,1,0,0, 1,
0,1,0,0, 0,
1,0,1,1, 0,
1,1,1,0, 0,
0,1,1,0, 1,
0,0,1,1, 1,
0,1,1,1, 0,
0,1,0,1, 1,
1,0,1,0, 1,
1,0,0,0, 0
};
struct sine_wave_t rgb_waves[3] = {
{ 0.5f,
0.5f,
1.0f
},
{ 0.5f,
0.5f,
1.5f
},
{ 0.5f,
0.5f,
2.5f
}
};
struct sine_wave_t xyz_waves[3] = {
{ 0.5f,
0.5f,
1.0f / 4.0f
},
{ 0.5f,
0.5f,
1.5f / 4.0f
},
{ 0.5f,
0.5f,
2.5f / 4.0f
}
};
GLuint* client_indices = 0;
const GLuint indices[] = {
0,1,2, 0,2,3, 1,4,5, 1,5,2, 4,7,6, 4,6,5,
7,0,3, 7,3,6, 9,2,5, 9,5,8, 0,10,11, 0,7,10
};
// Test program might want to use these:
int rsxgltest_width = 0, rsxgltest_height = 0;
float rsxgltest_elapsed_time = 0, rsxgltest_last_time = 0, rsxgltest_delta_time = 0;
// Configure these (especially the IP) to your own setup.
// Use netcat to receive the results on your PC:
// TCP: nc -l -p 4000
// UDP: nc -u -l -p 4000
// For some versions of netcat the -p option may need to be removed.
//
//#define TESTIP "192.168.1.7"
//#define TESTIP "192.168.1.115"
//#define TESTPORT 9000
int sock = 0;
/** The view rotation [x, y, z] */
static GLfloat view_rot[3] = { 20.0, 30.0, 0.0 };
/** The gears */
//static struct gear* gear1; // , * gear2, * gear3;
/** The current gear rotation angle */
static GLfloat angle = 0.0;
/** The location of the shader uniforms */
static GLuint ModelViewProjectionMatrix_location,
NormalMatrix_location,
LightSourcePosition_location,
MaterialColor_location;
/** The projection matrix */
static GLfloat ProjectionMatrix[16];
/** The direction of the directional light for the scene */
static const GLfloat LightSourcePosition[4] = { 5.0, 5.0, 10.0, 1.0 };
//static struct gear*
//create_gear(GLfloat inner_radius, GLfloat outer_radius, GLfloat width,
// GLint teeth, GLfloat tooth_depth);
static void report_glerror(const char * label)
{
GLenum e = glGetError();
if(e != GL_NO_ERROR) {
if(label != 0) {
printf("%s: %x\n",label,e);
}
else {
printf("%x\n",e);
}
}
}
static void
report_shader_info(GLuint shader)
{
GLint type = 0, delete_status = 0, compile_status = 0;
if(glIsShader(shader)) {
glGetShaderiv(shader,GL_SHADER_TYPE,&type);
glGetShaderiv(shader,GL_DELETE_STATUS,&delete_status);
glGetShaderiv(shader,GL_COMPILE_STATUS,&compile_status);
printf("shader: %u type: %x compile_status: %i delete_status: %i\n",shader,type,compile_status,delete_status);
GLint nInfo = 0;
glGetShaderiv(shader,GL_INFO_LOG_LENGTH,&nInfo);
if(nInfo > 0) {
printf("\tinfo length: %u\n",nInfo);
char szInfo[nInfo + 1];
glGetShaderInfoLog(shader,nInfo + 1,0,szInfo);
printf("\tinfo: %s\n",szInfo);
}
}
else {
printf("%u is not a shader\n",shader);
}
}
static void
report_program_info(GLuint program)
{
if(glIsProgram(program)) {
GLint delete_status = 0, link_status = 0, validate_status = 0;
glGetProgramiv(program,GL_DELETE_STATUS,&delete_status);
glGetProgramiv(program,GL_LINK_STATUS,&link_status);
glGetProgramiv(program,GL_VALIDATE_STATUS,&validate_status);
printf("program: %u link_status: %i validate_status: %i delete_status: %i\n",program,link_status,validate_status,delete_status);
GLint num_attached = 0;
glGetProgramiv(program,GL_ATTACHED_SHADERS,&num_attached);
printf("\tattached shaders: %u\n",num_attached);
if(num_attached > 0) {
GLuint attached[2] = { 0,0 };
glGetAttachedShaders(program,2,0,attached);
printf("\t");
for(size_t i = 0;i < 2;++i) {
if(attached[i] > 0) {
printf("%u ",attached[i]);
}
}
printf("\n");
}
GLint nInfo = 0;
glGetProgramiv(program,GL_INFO_LOG_LENGTH,&nInfo);
if(nInfo > 0) {
printf("\tinfo length: %u\n",nInfo);
char szInfo[nInfo + 1];
glGetProgramInfoLog(program,nInfo + 1,0,szInfo);
printf("\tinfo: %s\n",szInfo);
}
}
else {
printf("%u is not a program\n",program);
}
}
static void
summarize_program(const char * label,GLuint program)
{
printf("summary of program %s:\n",label);
// Report on attributes:
{
GLint num_attribs = 0, attrib_name_length = 0;
glGetProgramiv(program,GL_ACTIVE_ATTRIBUTES,&num_attribs);
glGetProgramiv(program,GL_ACTIVE_ATTRIBUTE_MAX_LENGTH,&attrib_name_length);
printf("%u attribs, name max length: %u\n",num_attribs,attrib_name_length);
char szName[attrib_name_length + 1];
for(size_t i = 0;i < num_attribs;++i) {
GLint size = 0;
GLenum type = 0;
GLint location = 0;
glGetActiveAttrib(program,i,attrib_name_length + 1,0,&size,&type,szName);
location = glGetAttribLocation(program,szName);
printf("\t%u: %s %u %u %u\n",i,szName,(unsigned int)location,(unsigned int)size,(unsigned int)type);
}
}
// Report on uniforms:
{
GLint num_uniforms = 0, uniform_name_length = 0;
glGetProgramiv(program,GL_ACTIVE_UNIFORMS,&num_uniforms);
glGetProgramiv(program,GL_ACTIVE_UNIFORM_MAX_LENGTH,&uniform_name_length);
printf("%u uniforms, name max length: %u\n",num_uniforms,uniform_name_length);
char szName[uniform_name_length + 1];
for(size_t i = 0;i < num_uniforms;++i) {
GLint size = 0;
GLenum type = 0;
GLint location = 0;
glGetActiveUniform(program,i,uniform_name_length + 1,0,&size,&type,szName);
location = glGetUniformLocation(program,szName);
printf("\t%u: %s %u %u %x\n",i,szName,(unsigned int)location,(unsigned int)size,(unsigned int)type);
}
}
}
// quit:
int running = 1, drawing = 1;
static void
eventHandle(u64 status, u64 param, void * userdata) {
(void)param;
(void)userdata;
if(status == SYSUTIL_EXIT_GAME){
//printf("Quit app requested\n");
//exit(0);
running = 0;
}
else if(status == SYSUTIL_MENU_OPEN) {
drawing = 0;
}
else if(status == SYSUTIL_MENU_CLOSE) {
drawing = 1;
}
else {
//printf("Unhandled event: %08llX\n", (unsigned long long int)status);
}
}
static void
appCleanup()
{
sysUtilUnregisterCallback(SYSUTIL_EVENT_SLOT0);
//tcp_exit();
//netDeinitialize();
printf("Exiting for real.\n");
}
/* Convenience macros for operations on timevals.
NOTE: `timercmp' does not work for >= or <=. */
//#define timerisset(tvp) ((tvp)->tv_sec || (tvp)->tv_usec)
//#define timerclear(tvp) ((tvp)->tv_sec = (tvp)->tv_usec = 0)
//#define timercmp(a, b, CMP) \
// (((a)->tv_sec == (b)->tv_sec) ? \
// ((a)->tv_usec CMP (b)->tv_usec) : \
// ((a)->tv_sec CMP (b)->tv_sec))
//#define timeradd(a, b, result) \
// do { \
// (result)->tv_sec = (a)->tv_sec + (b)->tv_sec; \
// (result)->tv_usec = (a)->tv_usec + (b)->tv_usec; \
// if ((result)->tv_usec >= 1000000) \
// { \
// ++(result)->tv_sec; \
// (result)->tv_usec -= 1000000; \
// } \
// } while (0)
//#define timersub(a, b, result) \
// do { \
// (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
// (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \
// if ((result)->tv_usec < 0) { \
// --(result)->tv_sec; \
// (result)->tv_usec += 1000000; \
// } \
// } while (0)
static const char vertex_shader[] =
"attribute vec3 position;\n"
"attribute vec3 normal;\n"
"\n"
"uniform mat4 ModelViewProjectionMatrix;\n"
"uniform mat4 NormalMatrix;\n"
"uniform vec4 LightSourcePosition;\n"
"uniform vec4 MaterialColor;\n"
"\n"
"varying vec4 Color;\n"
"\n"
"void main(void)\n"
"{\n"
" // Transform the normal to eye coordinates\n"
" vec3 N = normalize(vec3(NormalMatrix * vec4(normal, 1.0)));\n"
"\n"
" // The LightSourcePosition is actually its direction for directional light\n"
" vec3 L = normalize(LightSourcePosition.xyz);\n"
"\n"
" // Multiply the diffuse value by the vertex color (which is fixed in this case)\n"
" // to get the actual color that we will use to draw this vertex with\n"
" float diffuse = max(dot(N, L), 0.0);\n"
" Color = diffuse * MaterialColor;\n"
"\n"
" // Transform the position to clip coordinates\n"
" gl_Position = ModelViewProjectionMatrix * vec4(position, 1.0);\n"
"}";
static const char fragment_shader[] =
"//precision mediump float;\n"
"varying vec4 Color;\n"
"\n"
"void main(void)\n"
"{\n"
" gl_FragColor = Color;\n"
"}";
GLuint vao = 0;
GLuint buffers[2] = { 0,0 };
GLuint shaders[2] = { 0,0 };
GLuint program = 0;
GLint ProjMatrix_location = -1, TransMatrix_location = -1, vertex_location = -1, tc_location = -1, image_location = -1, gradient_location = -1;
#define DTOR(X) ((X)*0.01745329f)
#define RTOD(d) ((d)*57.295788f)
Eigen::Projective3f ProjMatrix(perspective(DTOR(54.3), 1920.0 / 1080.0, 0.1, 1000.0));
Eigen::Affine3f ViewMatrixInv =
Eigen::Affine3f(Eigen::Affine3f::Identity() *
(
Eigen::Translation3f(1.779, 2.221, 4.034) *
(
Eigen::AngleAxisf(DTOR(0), Eigen::Vector3f::UnitZ()) *
Eigen::AngleAxisf(DTOR(23.8), Eigen::Vector3f::UnitY()) *
Eigen::AngleAxisf(DTOR(-26.738), Eigen::Vector3f::UnitX())
)
)
).inverse();
static void
cube_init(void)
{
printf("%s\n", __PRETTY_FUNCTION__);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
// Set up us the program:
shaders[0] = glCreateShader(GL_VERTEX_SHADER);
shaders[1] = glCreateShader(GL_FRAGMENT_SHADER);
program = glCreateProgram();
glAttachShader(program, shaders[0]);
glAttachShader(program, shaders[1]);
// Supply shader SOURCES!
const GLchar* shader_srcs[] = { (const GLchar*)texcube_vert, (const GLchar*)texcube_frag };
GLint shader_srcs_lengths[] = { texcube_vert_len, texcube_frag_len };
GLint compiled = 0;
glShaderSource(shaders[0], 1, shader_srcs, shader_srcs_lengths);
glCompileShader(shaders[0]);
glGetShaderiv(shaders[0], GL_COMPILE_STATUS, &compiled);
printf("shader compile status: %i\n", compiled);
glShaderSource(shaders[1], 1, shader_srcs + 1, shader_srcs_lengths + 1);
glCompileShader(shaders[1]);
glGetShaderiv(shaders[1], GL_COMPILE_STATUS, &compiled);
printf("shader compile status: %i\n", compiled);
// Link the program for real:
glLinkProgram(program);
glValidateProgram(program);
summarize_program("draw", program);
vertex_location = glGetAttribLocation(program, "vertex");
tc_location = glGetAttribLocation(program, "uv");
ProjMatrix_location = glGetUniformLocation(program, "ProjMatrix");
TransMatrix_location = glGetUniformLocation(program, "TransMatrix");
image_location = glGetUniformLocation(program, "image");
gradient_location = glGetUniformLocation(program, "gradient");
printf("vertex_location: %i\n", vertex_location);
printf("tc_location: %i\n", tc_location);
printf("ProjMatrix_location: %i TransMatrix_location: %i\n",
ProjMatrix_location, TransMatrix_location);
printf("image_location: %i gradient_location: %i\n", image_location, gradient_location);
glUseProgram(program);
glUniformMatrix4fv(ProjMatrix_location, 1, GL_FALSE, ProjMatrix.data());
glUniform1i(image_location, 0);
glUniform1i(gradient_location, 2);
// Set up us the vertex data:
glGenBuffers(2, buffers);
glBindBuffer(GL_ARRAY_BUFFER, buffers[0]);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 12 /*6 * 4*/ * 5, geometry, GL_STATIC_DRAW);
glEnableVertexAttribArray(vertex_location);
glEnableVertexAttribArray(tc_location);
glVertexAttribPointer(vertex_location, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 5, 0);
glVertexAttribPointer(tc_location, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 5, (const GLvoid*)(sizeof(float) * 3));
client_indices = (GLuint*)malloc(sizeof(GLuint) * 6 * 2 * 3);
memcpy(client_indices, indices, sizeof(GLuint) * 6 * 2 * 3);
}
/**
* Handles a new window size or exposure.
*
* @param width the window width
* @param height the window height
*/
//static void
//cube_reshape(int width, int height)
//{
// /* Update the projection matrix */
// perspective(ProjectionMatrix, 60.0, width / (float)height, 1.0, 1024.0);
//
// /* Set the viewport */
// glViewport(0, 0, (GLint)width, (GLint)height);
//}
/**
* Struct describing the vertices in triangle strip
*/
struct vertex_strip {
/** The first vertex in the strip */
GLint first;
/** The number of consecutive vertices in the strip after the first */
GLint count;
};
/**
* Multiplies two 4x4 matrices.
*
* The result is stored in matrix m.
*
* @param m the first matrix to multiply
* @param n the second matrix to multiply
*/
static void
multiply(GLfloat* m, const GLfloat* n)
{
GLfloat tmp[16];
const GLfloat* row, * column;
div_t d;
int i, j;
for (i = 0; i < 16; i++) {
tmp[i] = 0;
d = div(i, 4);
row = n + d.quot * 4;
column = m + d.rem;
for (j = 0; j < 4; j++)
tmp[i] += row[j] * column[j * 4];
}
memcpy(m, &tmp, sizeof tmp);
}
/**
* Rotates a 4x4 matrix.
*
* @param[in,out] m the matrix to rotate
* @param angle the angle to rotate
* @param x the x component of the direction to rotate to
* @param y the y component of the direction to rotate to
* @param z the z component of the direction to rotate to
*/
//static void
//rotate(GLfloat* m, GLfloat angle, GLfloat x, GLfloat y, GLfloat z)
//{
// double s, c;
//
// sincos(angle, &s, &c);
// GLfloat r[16] = {
// x * x * (1 - c) + c, y * x * (1 - c) + z * s, x * z * (1 - c) - y * s, 0,
// x * y * (1 - c) - z * s, y * y * (1 - c) + c, y * z * (1 - c) + x * s, 0,
// x * z * (1 - c) + y * s, y * z * (1 - c) - x * s, z * z * (1 - c) + c, 0,
// 0, 0, 0, 1
// };
//
// multiply(m, r);
//}
/**
* Translates a 4x4 matrix.
*
* @param[in,out] m the matrix to translate
* @param x the x component of the direction to translate to
* @param y the y component of the direction to translate to
* @param z the z component of the direction to translate to
*/
static void
translate(GLfloat* m, GLfloat x, GLfloat y, GLfloat z)
{
GLfloat t[16] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1 };
multiply(m, t);
}
/**
* Creates an identity 4x4 matrix.
*
* @param m the matrix make an identity matrix
*/
static void
identity(GLfloat* m)
{
GLfloat t[16] = {
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0,
};
memcpy(m, t, sizeof(t));
}
/**
* Transposes a 4x4 matrix.
*
* @param m the matrix to transpose
*/
static void
transpose(GLfloat* m)
{
GLfloat t[16] = {
m[0], m[4], m[8], m[12],
m[1], m[5], m[9], m[13],
m[2], m[6], m[10], m[14],
m[3], m[7], m[11], m[15] };
memcpy(m, t, sizeof(t));
}
/**
* Inverts a 4x4 matrix.
*
* This function can currently handle only pure translation-rotation matrices.
* Read http://www.gamedev.net/community/forums/topic.asp?topic_id=425118
* for an explanation.
*/
static void
invert(GLfloat* m)
{
GLfloat t[16];
identity(t);
// Extract and invert the translation part 't'. The inverse of a
// translation matrix can be calculated by negating the translation
// coordinates.
t[12] = -m[12]; t[13] = -m[13]; t[14] = -m[14];
// Invert the rotation part 'r'. The inverse of a rotation matrix is
// equal to its transpose.
m[12] = m[13] = m[14] = 0;
transpose(m);
// inv(m) = inv(r) * inv(t)
multiply(m, t);
}
/**
* Calculate a perspective projection transformation.
*
* @param m the matrix to save the transformation in
* @param fovy the field of view in the y direction
* @param aspect the view aspect ratio
* @param zNear the near clipping plane
* @param zFar the far clipping plane
*/
/**
* Draws a gear.
*
* @param gear the gear to draw
* @param transform the current transformation matrix
* @param x the x position to draw the gear at
* @param y the y position to draw the gear at
* @param angle the rotation angle of the gear
* @param color the color of the gear
*/
static void
draw_cube()
{
float rgb[3] = {
1,0,0
};
glClearColor(rgb[0], rgb[1], rgb[2], 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
float xyz[3] = {
compute_sine_wave(xyz_waves,rsxgltest_elapsed_time),
compute_sine_wave(xyz_waves + 1,rsxgltest_elapsed_time),
compute_sine_wave(xyz_waves + 2,rsxgltest_elapsed_time)
};
Eigen::Affine3f rotmat =
Eigen::Affine3f::Identity() *
Eigen::AngleAxisf(DTOR(xyz[2]) * 360.0f, Eigen::Vector3f::UnitZ()) *
Eigen::AngleAxisf(DTOR(xyz[1]) * 360.0f, Eigen::Vector3f::UnitY()) *
Eigen::AngleAxisf(DTOR(xyz[0]) * 360.0f, Eigen::Vector3f::UnitX());
{
//glActiveTexture(GL_TEXTURE0);
//glBindTexture(GL_TEXTURE_2D, textures[0]);
//glUniform1i(image_location,0);
Eigen::Affine3f modelview = ViewMatrixInv * (Eigen::Affine3f::Identity() * Eigen::Translation3f(-5, 0, 0) * rotmat * Eigen::UniformScaling< float >(3.0));
//Eigen::Affine3f modelview = ViewMatrixInv;
//Eigen::Affine3f modelview(Eigen::Affine3f::Identity());
glUniformMatrix4fv(TransMatrix_location, 1, GL_FALSE, modelview.data());
glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, client_indices);
}
{
//glActiveTexture(GL_TEXTURE0);
//glBindTexture(GL_TEXTURE_2D, textures[1]);
//glUniform1i(image_location,1);
Eigen::Affine3f modelview = ViewMatrixInv * (Eigen::Affine3f::Identity() * Eigen::Translation3f(5, 0, 0) * rotmat * Eigen::UniformScaling< float >(3.0));
//Eigen::Affine3f modelview = ViewMatrixInv;
//Eigen::Affine3f modelview(Eigen::Affine3f::Identity());
glUniformMatrix4fv(TransMatrix_location, 1, GL_FALSE, modelview.data());
glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, client_indices);
}
}
/**
* Draws the gears.
*/
// rsxgltest stuff goes here - replaces glut, eglut, etc.
char* rsxgltest_name = "rsxglgears";
int
main(int argc, const char ** argv)
{
//netInitialize();
//tcp_init();
printf("%s\n",rsxgltest_name);
//glInitDebug(1024*256,tcp_puts);
EGLDisplay dpy = eglGetDisplay(EGL_DEFAULT_DISPLAY);
if(dpy != EGL_NO_DISPLAY) {
// convert to a timeval structure:
/*const float ft = 1.0f / 60.0f;
float ft_integral, ft_fractional;
ft_fractional = modff(ft,&ft_integral);
struct timeval frame_time = { 0,0 };
frame_time.tv_sec = (int)ft_integral;
frame_time.tv_usec = (int)(ft_fractional * 1.0e6);*/
EGLint version0 = 0,version1 = 0;
EGLBoolean result;
result = eglInitialize(dpy,&version0,&version1);
if(result) {
printf("eglInitialize version: %i %i:%i\n",version0,version1,(int)result);
EGLint attribs[] = {
EGL_RED_SIZE,8,
EGL_BLUE_SIZE,8,
EGL_GREEN_SIZE,8,
EGL_ALPHA_SIZE,8,
EGL_DEPTH_SIZE,16,
EGL_NONE
};
EGLConfig config;
EGLint nconfig = 0;
result = eglChooseConfig(dpy,attribs,&config,1,&nconfig);
printf("eglChooseConfig:%i %u configs\n",(int)result,nconfig);
if(nconfig > 0) {
EGLSurface surface = eglCreateWindowSurface(dpy,config,0,0);
if(surface != EGL_NO_SURFACE) {
eglQuerySurface(dpy,surface,EGL_WIDTH,&rsxgltest_width);
eglQuerySurface(dpy,surface,EGL_HEIGHT,&rsxgltest_height);
printf("eglCreateWindowSurface: %ix%i\n",rsxgltest_width,rsxgltest_height);
EGLContext ctx = eglCreateContext(dpy,config,0,0);
printf("eglCreateContext: %lu\n",(unsigned long)ctx);
if(ctx != EGL_NO_CONTEXT) {
atexit(appCleanup);
sysUtilRegisterCallback(SYSUTIL_EVENT_SLOT0, eventHandle, NULL);
/*struct timeval start_time, current_time;
struct timeval timeout_time = {
.tv_sec = 6,
.tv_usec = 0
};*/
// Initialize:
result = eglMakeCurrent(dpy,surface,surface,ctx);
if(result == EGL_TRUE) {
printf("eglMakeCurrent\n");
cube_init();
//gears_reshape(rsxgltest_width, rsxgltest_height);
//gettimeofday(&start_time,0);
rsxgltest_last_time = 0.0f;
while(running) {
/*gettimeofday(¤t_time,0);
struct timeval elapsed_time;
timersub(¤t_time,&start_time,&elapsed_time);
rsxgltest_elapsed_time = ((float)(elapsed_time.tv_sec)) + ((float)(elapsed_time.tv_usec) / 1.0e6f);
rsxgltest_delta_time = rsxgltest_elapsed_time - rsxgltest_last_time;
rsxgltest_last_time = rsxgltest_elapsed_time;*/
//result = eglMakeCurrent(dpy,surface,surface,ctx);
if(drawing) {
//gears_idle();
draw_cube();
}
result = eglSwapBuffers(dpy,surface);
EGLint e = eglGetError();
if(!result) {
printf("Swap sync timed-out: %x\n",e);
break;
}
else {
/*struct timeval t, elapsed_time;
gettimeofday(&t,0);
timersub(&t,¤t_time,&elapsed_time);
if(timercmp(&elapsed_time,&frame_time,<)) {
struct timeval sleep_time;
timersub(&frame_time,&elapsed_time,&sleep_time);
usleep((sleep_time.tv_sec * 1e6) + sleep_time.tv_usec);
}*/
sysUtilCheckCallback();
}
}
//EXIT HERE
}
else {
printf("eglMakeCurrent failed: %x\n",eglGetError());
}
result = eglDestroyContext(dpy,ctx);
printf("eglDestroyContext:%i\n",(int)result);
}
else {
printf("eglCreateContext failed: %x\n",eglGetError());
}
}
else {
printf("eglCreateWindowSurface failed: %x\n",eglGetError());
}
}
result = eglTerminate(dpy);
printf("eglTerminate:%i\n",(int)result);
exit(0);
}
else {
printf("eglInitialize failed: %x\n",eglGetError());
}
}
else {
printf("eglGetDisplay failed: %x\n",eglGetError());
}
appCleanup();
return 0;
}
#include "sine_wave.c" | 27.102837 | 162 | 0.628244 | [
"geometry",
"transform"
] |
10565e142210b79ae468b75eadab26203c48be46 | 2,480 | cpp | C++ | third_party/skia_m63/third_party/externals/angle2/src/tests/gles_conformance_tests/gles_conformance_tests.cpp | kniefliu/WindowsSamples | c841268ef4a0f1c6f89b8e95bf68058ea2548394 | [
"MIT"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | third_party/angle/src/tests/gles_conformance_tests/gles_conformance_tests.cpp | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | third_party/angle/src/tests/gles_conformance_tests/gles_conformance_tests.cpp | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | #include "gles_conformance_tests.h"
#include "GTFMain.h"
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <sstream>
#include <stdarg.h>
static std::vector<char> FormatArg(const char* fmt, ...)
{
va_list vararg;
va_start(vararg, fmt);
int len = vsnprintf(nullptr, 0, fmt, vararg);
va_end(vararg);
std::vector<char> buf(len + 1);
va_start(vararg, fmt);
vsnprintf(buf.data(), buf.size(), fmt, vararg);
va_end(vararg);
return buf;
}
static std::string GetExecutableDirectory()
{
std::vector<char> executableFileBuf(MAX_PATH);
DWORD executablePathLen =
GetModuleFileNameA(nullptr, executableFileBuf.data(), executableFileBuf.size());
if (executablePathLen == 0)
{
return false;
}
std::string executableLocation = executableFileBuf.data();
size_t lastPathSepLoc = executableLocation.find_last_of("\\/");
if (lastPathSepLoc != std::string::npos)
{
executableLocation = executableLocation.substr(0, lastPathSepLoc);
}
else
{
executableLocation = "";
}
return executableLocation;
}
void RunConformanceTest(const std::string &testPath, EGLNativeDisplayType nativeDisplay)
{
std::vector<char*> args;
// Empty first argument for the program name
args.push_back("");
std::vector<char> widthArg = FormatArg("-width=%u", 64);
args.push_back(widthArg.data());
std::vector<char> heightArg = FormatArg("-height=%u", 64);
args.push_back(heightArg.data());
std::vector<char> displayArg = FormatArg("-d=%llu", nativeDisplay);
args.push_back(displayArg.data());
std::vector<char> runArg = FormatArg("-run=%s/conformance_tests/%s", GetExecutableDirectory().c_str(), testPath.c_str());
args.push_back(runArg.data());
// Redirect cout
std::streambuf* oldCoutStreamBuf = std::cout.rdbuf();
std::ostringstream strCout;
std::cout.rdbuf(strCout.rdbuf());
if (GTFMain(args.size(), args.data()) != 0)
{
FAIL() << "GTFMain failed.";
}
// Restore old cout
std::cout.rdbuf(oldCoutStreamBuf);
std::string log = strCout.str();
// Look for failures
size_t offset = 0;
std::string offsetSearchString = "failure = ";
while ((offset = log.find("failure = ", offset)) != std::string::npos)
{
offset += offsetSearchString.length();
size_t failureCount = atoll(log.c_str() + offset);
EXPECT_EQ(0, failureCount) << log;
}
}
| 26.382979 | 125 | 0.647581 | [
"vector"
] |
1058fc83e1a4f63b10d8191255c366189c5ca937 | 5,788 | hpp | C++ | src/AlignmentGraph.hpp | tijyojwad/shasta | dffb41279bbc606d06f5323add40c0b1ebd5ae65 | [
"BSD-3-Clause"
] | 2 | 2019-11-14T09:06:16.000Z | 2020-07-31T11:03:41.000Z | src/AlignmentGraph.hpp | tijyojwad/shasta | dffb41279bbc606d06f5323add40c0b1ebd5ae65 | [
"BSD-3-Clause"
] | null | null | null | src/AlignmentGraph.hpp | tijyojwad/shasta | dffb41279bbc606d06f5323add40c0b1ebd5ae65 | [
"BSD-3-Clause"
] | 2 | 2019-11-13T23:42:45.000Z | 2019-11-26T20:24:01.000Z | #ifndef SHASTA_ALIGNMENT_GRAPH_HPP
#define SHASTA_ALIGNMENT_GRAPH_HPP
/*******************************************************************************
Class AlignmentGraph is used to compute an alignment of the markers
of two oriented reads.
In the alignment graph, each vertex corresponds to a pair of markers
in the two oriented reads that have the same k-mer.
Edges in the alignment graph are created between vertices
that are sufficiently close on both oriented reads.
Each edge is assigned a weight based on the distances
between the two pairs of markers on each of the
oriented reads, measured using ordinals (not position).
To find a good alignment, we find a shortest path in the graph.
*******************************************************************************/
// Shasta
#include "CompactUndirectedGraph.hpp"
#include "Marker.hpp"
#include "shortestPath.hpp"
// Standard library.
#include "utility.hpp"
#include "vector.hpp"
namespace shasta {
class AlignmentGraphVertex;
class AlignmentGraphEdge;
class AlignmentGraph;
using AlignmentGraphBaseClass = CompactUndirectedGraph<
AlignmentGraphVertex,
AlignmentGraphEdge>;
class Alignment;
class AlignmentInfo;
// Top level function to compute the marker alignment.
void align(
// Markers of the two oriented reads to be aligned, sorted by KmerId.
const array<vector<MarkerWithOrdinal>, 2>& markers,
// The maximum ordinal skip to be tolerated between successive markers
// in the alignment.
size_t maxSkip,
// The maximum ordinal drift to be tolerated between successive markers
// in the alignment. This is the drift of the two oriented reads
// relative to each other.
size_t maxDrift,
// Marker frequency threshold.
// When computing an alignment between two oriented reads,
// marker kmers that appear more than this number of times
// in either of the two oriented reads are discarded
// (in both oriented reads).
// Change to size_t when conversion completed.
uint32_t maxMarkerFrequency,
// Flag to control various types of debug output.
bool debug,
// The AlignmentGraph can be reused.
// For performance, it should be reused when doing many alignments.
AlignmentGraph&,
// The computed alignment.
// This should also be reused when performance is important.
Alignment&,
// Also create alignment summary information.
AlignmentInfo&
);
}
// Each vertex corresponds a pair of markers in the
// two oriented reads that have the same kmer.
class shasta::AlignmentGraphVertex {
public:
// The KmerId of this marker.
KmerId kmerId;
// The index of this k-mer in each of the sorted markers vectors.
array<size_t, 2> indexes;
// The ordinals of this k-mer in each of the oriented reads.
// This equals the index when the markers are sorted by position.
array<size_t, 2> ordinals;
// The position of this marker in each of the two sequences.
array<int, 2> positions = array<int, 2>{
std::numeric_limits<int>::min(), std::numeric_limits<int>::min()};
// Data members used to find the shortest path.
AlignmentGraphBaseClass::vertex_descriptor predecessor;
uint64_t distance;
uint8_t color;
// Order by ordinal in the first sequence.
bool operator<(const AlignmentGraphVertex& that) const
{
return ordinals[0] < that.ordinals[0];
}
};
class shasta::AlignmentGraphEdge {
public:
uint64_t weight;
AlignmentGraphEdge(uint64_t weight) :
weight(weight)
{}
};
class shasta::AlignmentGraph : public AlignmentGraphBaseClass {
public:
void create(
const array<vector<MarkerWithOrdinal>, 2>&,
uint32_t maxMarkerFrequency,
size_t maxSkip,
size_t maxDrift,
bool debug,
Alignment&,
AlignmentInfo&);
private:
// There is a vertex for each pair of markers with the same k-mer.
// In addition, there is a start vertex and a finish vertex.
vertex_descriptor vStart;
vertex_descriptor vFinish;
static void writeMarkers(
const vector<MarkerWithOrdinal>&,
const string& fileName
);
void createVertices(
const array<vector<MarkerWithOrdinal>, 2>&,
uint32_t maxMarkerFrequency);
void writeVertices(const string& fileName) const;
void createEdges(
uint32_t markerCount0,
uint32_t MarkerCount1,
size_t maxSkip,
size_t maxDrift);
void writeEdges(const string& fileName) const;
// Write in graphviz format, without the start and finish vertices.
void writeGraphviz(const string& fileName) const;
// Write an image representing the markers and the computed alignment
// in 2-D ordinal space.
public:
static void writeImage(
const vector<MarkerWithOrdinal>&,
const vector<MarkerWithOrdinal>&,
const Alignment&,
const string& fileName);
private:
// Data members used to find the shortest path.
vector<vertex_descriptor> shortestPath;
FindShortestPathQueue<AlignmentGraph> queue;
void writeShortestPath(const string& fileName) const;
// Flags that are set for markers whose k-mers
// have frequency maxMarkerFrequency or less in
// both oriented reads being aligned.
// Indexed by [0 or 1][ordinal]
// (this is the standard marker ordinal that counts all markers).
array<vector<bool>, 2> isLowFrequencyMarker;
// The corrected ordinals, keeping into account only low frequency markers.
// Index by [01][ordinal].
array<vector<uint32_t>, 2> correctedOrdinals;
};
#endif
| 29.989637 | 80 | 0.671907 | [
"vector"
] |
105971000063b7e8afb395dd8b071c7a463458ae | 18,749 | cc | C++ | content/browser/renderer_host/media/in_process_video_capture_device_launcher.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/browser/renderer_host/media/in_process_video_capture_device_launcher.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/browser/renderer_host/media/in_process_video_capture_device_launcher.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-01-05T23:43:46.000Z | 2021-01-07T23:36:34.000Z | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_host/media/in_process_video_capture_device_launcher.h"
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/command_line.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/stringprintf.h"
#include "build/build_config.h"
#include "content/browser/renderer_host/media/in_process_launched_video_capture_device.h"
#include "content/browser/renderer_host/media/video_capture_controller.h"
#include "content/common/buildflags.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/desktop_media_id.h"
#include "media/base/bind_to_current_loop.h"
#include "media/base/media_switches.h"
#include "media/capture/video/fake_video_capture_device.h"
#include "media/capture/video/fake_video_capture_device_factory.h"
#include "media/capture/video/video_capture_buffer_pool_impl.h"
#include "media/capture/video/video_capture_buffer_tracker_factory_impl.h"
#include "media/capture/video/video_capture_device_client.h"
#include "media/capture/video/video_frame_receiver.h"
#include "media/capture/video/video_frame_receiver_on_task_runner.h"
#include "third_party/blink/public/common/mediastream/media_stream_request.h"
#if BUILDFLAG(ENABLE_SCREEN_CAPTURE)
#include "content/browser/media/capture/desktop_capture_device_uma_types.h"
#if defined(OS_ANDROID)
#include "content/browser/media/capture/screen_capture_device_android.h"
#else
#include "content/browser/media/capture/web_contents_video_capture_device.h"
#if defined(USE_AURA)
#include "content/browser/media/capture/aura_window_video_capture_device.h"
#endif
#include "content/browser/media/capture/desktop_capture_device.h"
#endif // defined(OS_ANDROID)
#endif // BUILDFLAG(ENABLE_SCREEN_CAPTURE)
#if defined(OS_CHROMEOS)
#include "content/browser/gpu/chromeos/video_capture_dependencies.h"
#include "media/capture/video/chromeos/scoped_video_capture_jpeg_decoder.h"
#include "media/capture/video/chromeos/video_capture_jpeg_decoder_impl.h"
#endif // defined(OS_CHROMEOS)
namespace {
#if defined(OS_CHROMEOS)
std::unique_ptr<media::VideoCaptureJpegDecoder> CreateGpuJpegDecoder(
media::VideoCaptureJpegDecoder::DecodeDoneCB decode_done_cb,
base::RepeatingCallback<void(const std::string&)> send_log_message_cb) {
auto io_task_runner = content::GetIOThreadTaskRunner({});
return std::make_unique<media::ScopedVideoCaptureJpegDecoder>(
std::make_unique<media::VideoCaptureJpegDecoderImpl>(
base::BindRepeating(
&content::VideoCaptureDependencies::CreateJpegDecodeAccelerator),
io_task_runner, std::move(decode_done_cb),
std::move(send_log_message_cb)),
io_task_runner);
}
#endif // defined(OS_CHROMEOS)
// The maximum number of video frame buffers in-flight at any one time. This
// value should be based on the logical capacity of the capture pipeline, and
// not on hardware performance.
const int kMaxNumberOfBuffers = 3;
} // anonymous namespace
namespace content {
InProcessVideoCaptureDeviceLauncher::InProcessVideoCaptureDeviceLauncher(
scoped_refptr<base::SingleThreadTaskRunner> device_task_runner,
media::VideoCaptureSystem* video_capture_system)
: device_task_runner_(std::move(device_task_runner)),
video_capture_system_(video_capture_system),
state_(State::READY_TO_LAUNCH) {}
InProcessVideoCaptureDeviceLauncher::~InProcessVideoCaptureDeviceLauncher() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DCHECK(state_ == State::READY_TO_LAUNCH);
}
void InProcessVideoCaptureDeviceLauncher::LaunchDeviceAsync(
const std::string& device_id,
blink::mojom::MediaStreamType stream_type,
const media::VideoCaptureParams& params,
base::WeakPtr<media::VideoFrameReceiver> receiver_on_io_thread,
base::OnceClosure /* connection_lost_cb */,
Callbacks* callbacks,
base::OnceClosure done_cb) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DCHECK(state_ == State::READY_TO_LAUNCH);
if (receiver_on_io_thread) {
std::ostringstream string_stream;
string_stream
<< "InProcessVideoCaptureDeviceLauncher::LaunchDeviceAsync: Posting "
"start request to device thread for device_id = "
<< device_id;
receiver_on_io_thread->OnLog(string_stream.str());
}
// Wrap the receiver, to trampoline all its method calls from the device
// to the IO thread.
auto receiver = std::make_unique<media::VideoFrameReceiverOnTaskRunner>(
receiver_on_io_thread, GetIOThreadTaskRunner({}));
base::OnceClosure start_capture_closure;
// Use of Unretained |this| is safe, because |done_cb| guarantees that |this|
// stays alive.
ReceiveDeviceCallback after_start_capture_callback = media::BindToCurrentLoop(
base::BindOnce(&InProcessVideoCaptureDeviceLauncher::OnDeviceStarted,
base::Unretained(this), callbacks, std::move(done_cb)));
switch (stream_type) {
case blink::mojom::MediaStreamType::DEVICE_VIDEO_CAPTURE: {
if (!video_capture_system_) {
// Clients who create an instance of |this| without providing a
// VideoCaptureSystem instance are expected to know that
// MEDIA_DEVICE_VIDEO_CAPTURE is not supported in this case.
NOTREACHED();
return;
}
start_capture_closure = base::BindOnce(
&InProcessVideoCaptureDeviceLauncher::
DoStartDeviceCaptureOnDeviceThread,
base::Unretained(this), device_id, params,
CreateDeviceClient(media::VideoCaptureBufferType::kSharedMemory,
kMaxNumberOfBuffers, std::move(receiver),
std::move(receiver_on_io_thread)),
std::move(after_start_capture_callback));
break;
}
#if BUILDFLAG(ENABLE_SCREEN_CAPTURE)
#if !defined(OS_ANDROID)
case blink::mojom::MediaStreamType::GUM_TAB_VIDEO_CAPTURE:
start_capture_closure = base::BindOnce(
&InProcessVideoCaptureDeviceLauncher::DoStartTabCaptureOnDeviceThread,
base::Unretained(this), device_id, params, std::move(receiver),
std::move(after_start_capture_callback));
break;
#endif // !defined(OS_ANDROID)
case blink::mojom::MediaStreamType::GUM_DESKTOP_VIDEO_CAPTURE:
FALLTHROUGH;
case blink::mojom::MediaStreamType::DISPLAY_VIDEO_CAPTURE: {
const DesktopMediaID desktop_id = DesktopMediaID::Parse(device_id);
if (desktop_id.is_null()) {
DLOG(ERROR) << "Desktop media ID is null";
start_capture_closure =
base::BindOnce(std::move(after_start_capture_callback), nullptr);
break;
}
if (desktop_id.id == DesktopMediaID::kFakeId) {
start_capture_closure = base::BindOnce(
&InProcessVideoCaptureDeviceLauncher::
DoStartFakeDisplayCaptureOnDeviceThread,
base::Unretained(this), desktop_id, params,
CreateDeviceClient(media::VideoCaptureBufferType::kSharedMemory,
kMaxNumberOfBuffers, std::move(receiver),
std::move(receiver_on_io_thread)),
std::move(after_start_capture_callback));
break;
}
#if !defined(OS_ANDROID)
if (desktop_id.type == DesktopMediaID::TYPE_WEB_CONTENTS) {
after_start_capture_callback = base::BindOnce(
[](bool with_audio, ReceiveDeviceCallback callback,
std::unique_ptr<media::VideoCaptureDevice> device) {
// Special case: Only call IncrementDesktopCaptureCounter()
// for WebContents capture if it was started from a desktop
// capture API.
if (device) {
IncrementDesktopCaptureCounter(TAB_VIDEO_CAPTURER_CREATED);
IncrementDesktopCaptureCounter(
with_audio ? TAB_VIDEO_CAPTURER_CREATED_WITH_AUDIO
: TAB_VIDEO_CAPTURER_CREATED_WITHOUT_AUDIO);
}
std::move(callback).Run(std::move(device));
},
desktop_id.audio_share, std::move(after_start_capture_callback));
start_capture_closure = base::BindOnce(
&InProcessVideoCaptureDeviceLauncher::
DoStartTabCaptureOnDeviceThread,
base::Unretained(this), device_id, params, std::move(receiver),
std::move(after_start_capture_callback));
break;
}
#endif // !defined(OS_ANDROID)
#if defined(USE_AURA)
if (desktop_id.window_id != DesktopMediaID::kNullId) {
start_capture_closure = base::BindOnce(
&InProcessVideoCaptureDeviceLauncher::
DoStartAuraWindowCaptureOnDeviceThread,
base::Unretained(this), desktop_id, params, std::move(receiver),
std::move(after_start_capture_callback));
break;
}
#endif // defined(USE_AURA)
// All cases other than tab capture or Aura desktop/window capture.
start_capture_closure = base::BindOnce(
&InProcessVideoCaptureDeviceLauncher::
DoStartDesktopCaptureOnDeviceThread,
base::Unretained(this), desktop_id, params,
CreateDeviceClient(media::VideoCaptureBufferType::kSharedMemory,
kMaxNumberOfBuffers, std::move(receiver),
std::move(receiver_on_io_thread)),
std::move(after_start_capture_callback));
break;
}
#endif // BUILDFLAG(ENABLE_SCREEN_CAPTURE)
default: {
NOTIMPLEMENTED();
std::move(after_start_capture_callback).Run(nullptr);
return;
}
}
device_task_runner_->PostTask(FROM_HERE, std::move(start_capture_closure));
state_ = State::DEVICE_START_IN_PROGRESS;
}
void InProcessVideoCaptureDeviceLauncher::AbortLaunch() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
if (state_ == State::DEVICE_START_IN_PROGRESS)
state_ = State::DEVICE_START_ABORTING;
}
std::unique_ptr<media::VideoCaptureDeviceClient>
InProcessVideoCaptureDeviceLauncher::CreateDeviceClient(
media::VideoCaptureBufferType requested_buffer_type,
int buffer_pool_max_buffer_count,
std::unique_ptr<media::VideoFrameReceiver> receiver,
base::WeakPtr<media::VideoFrameReceiver> receiver_on_io_thread) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
scoped_refptr<media::VideoCaptureBufferPool> buffer_pool =
new media::VideoCaptureBufferPoolImpl(
std::make_unique<media::VideoCaptureBufferTrackerFactoryImpl>(),
requested_buffer_type, buffer_pool_max_buffer_count);
#if defined(OS_CHROMEOS)
return std::make_unique<media::VideoCaptureDeviceClient>(
requested_buffer_type, std::move(receiver), std::move(buffer_pool),
base::BindRepeating(
&CreateGpuJpegDecoder,
base::BindRepeating(&media::VideoFrameReceiver::OnFrameReadyInBuffer,
receiver_on_io_thread),
base::BindRepeating(&media::VideoFrameReceiver::OnLog,
receiver_on_io_thread)));
#else
return std::make_unique<media::VideoCaptureDeviceClient>(
requested_buffer_type, std::move(receiver), std::move(buffer_pool));
#endif // defined(OS_CHROMEOS)
}
void InProcessVideoCaptureDeviceLauncher::OnDeviceStarted(
Callbacks* callbacks,
base::OnceClosure done_cb,
std::unique_ptr<media::VideoCaptureDevice> device) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
State state_copy = state_;
state_ = State::READY_TO_LAUNCH;
if (!device) {
switch (state_copy) {
case State::DEVICE_START_IN_PROGRESS:
callbacks->OnDeviceLaunchFailed(
media::VideoCaptureError::
kInProcessDeviceLauncherFailedToCreateDeviceInstance);
std::move(done_cb).Run();
return;
case State::DEVICE_START_ABORTING:
callbacks->OnDeviceLaunchAborted();
std::move(done_cb).Run();
return;
case State::READY_TO_LAUNCH:
NOTREACHED();
return;
}
}
auto launched_device = std::make_unique<InProcessLaunchedVideoCaptureDevice>(
std::move(device), device_task_runner_);
switch (state_copy) {
case State::DEVICE_START_IN_PROGRESS:
callbacks->OnDeviceLaunched(std::move(launched_device));
std::move(done_cb).Run();
return;
case State::DEVICE_START_ABORTING:
launched_device.reset();
callbacks->OnDeviceLaunchAborted();
std::move(done_cb).Run();
return;
case State::READY_TO_LAUNCH:
NOTREACHED();
return;
}
}
void InProcessVideoCaptureDeviceLauncher::DoStartDeviceCaptureOnDeviceThread(
const std::string& device_id,
const media::VideoCaptureParams& params,
std::unique_ptr<media::VideoCaptureDeviceClient> device_client,
ReceiveDeviceCallback result_callback) {
SCOPED_UMA_HISTOGRAM_TIMER("Media.VideoCaptureManager.StartDeviceTime");
DCHECK(device_task_runner_->BelongsToCurrentThread());
DCHECK(video_capture_system_);
std::unique_ptr<media::VideoCaptureDevice> video_capture_device =
video_capture_system_->CreateDevice(device_id);
if (video_capture_device)
video_capture_device->AllocateAndStart(params, std::move(device_client));
std::move(result_callback).Run(std::move(video_capture_device));
}
#if BUILDFLAG(ENABLE_SCREEN_CAPTURE)
#if !defined(OS_ANDROID)
void InProcessVideoCaptureDeviceLauncher::DoStartTabCaptureOnDeviceThread(
const std::string& device_id,
const media::VideoCaptureParams& params,
std::unique_ptr<media::VideoFrameReceiver> receiver,
ReceiveDeviceCallback result_callback) {
SCOPED_UMA_HISTOGRAM_TIMER("Media.VideoCaptureManager.StartDeviceTime");
DCHECK(device_task_runner_->BelongsToCurrentThread());
std::unique_ptr<WebContentsVideoCaptureDevice> video_capture_device =
WebContentsVideoCaptureDevice::Create(device_id);
if (video_capture_device) {
video_capture_device->AllocateAndStartWithReceiver(params,
std::move(receiver));
}
std::move(result_callback).Run(std::move(video_capture_device));
}
#endif // !defined(OS_ANDROID)
#if defined(USE_AURA)
void InProcessVideoCaptureDeviceLauncher::
DoStartAuraWindowCaptureOnDeviceThread(
const DesktopMediaID& device_id,
const media::VideoCaptureParams& params,
std::unique_ptr<media::VideoFrameReceiver> receiver,
ReceiveDeviceCallback result_callback) {
SCOPED_UMA_HISTOGRAM_TIMER("Media.VideoCaptureManager.StartDeviceTime");
DCHECK(device_task_runner_->BelongsToCurrentThread());
auto video_capture_device =
std::make_unique<AuraWindowVideoCaptureDevice>(device_id);
if (video_capture_device) {
video_capture_device->AllocateAndStartWithReceiver(params,
std::move(receiver));
switch (device_id.type) {
case DesktopMediaID::TYPE_SCREEN:
IncrementDesktopCaptureCounter(SCREEN_CAPTURER_CREATED);
IncrementDesktopCaptureCounter(
device_id.audio_share ? SCREEN_CAPTURER_CREATED_WITH_AUDIO
: SCREEN_CAPTURER_CREATED_WITHOUT_AUDIO);
break;
case DesktopMediaID::TYPE_WINDOW:
IncrementDesktopCaptureCounter(WINDOW_CAPTURER_CREATED);
break;
case DesktopMediaID::TYPE_NONE:
case DesktopMediaID::TYPE_WEB_CONTENTS:
NOTREACHED();
break;
}
}
std::move(result_callback).Run(std::move(video_capture_device));
}
#endif // defined(USE_AURA)
void InProcessVideoCaptureDeviceLauncher::DoStartDesktopCaptureOnDeviceThread(
const DesktopMediaID& desktop_id,
const media::VideoCaptureParams& params,
std::unique_ptr<media::VideoCaptureDeviceClient> device_client,
ReceiveDeviceCallback result_callback) {
SCOPED_UMA_HISTOGRAM_TIMER("Media.VideoCaptureManager.StartDeviceTime");
DCHECK(device_task_runner_->BelongsToCurrentThread());
DCHECK(!desktop_id.is_null());
std::unique_ptr<media::VideoCaptureDevice> video_capture_device;
#if defined(OS_ANDROID)
video_capture_device = std::make_unique<ScreenCaptureDeviceAndroid>();
#else
if (!video_capture_device)
video_capture_device = DesktopCaptureDevice::Create(desktop_id);
#endif // defined (OS_ANDROID)
if (video_capture_device)
video_capture_device->AllocateAndStart(params, std::move(device_client));
std::move(result_callback).Run(std::move(video_capture_device));
}
#endif // BUILDFLAG(ENABLE_SCREEN_CAPTURE)
void InProcessVideoCaptureDeviceLauncher::
DoStartFakeDisplayCaptureOnDeviceThread(
const DesktopMediaID& desktop_id,
const media::VideoCaptureParams& params,
std::unique_ptr<media::VideoCaptureDeviceClient> device_client,
ReceiveDeviceCallback result_callback) {
DCHECK(device_task_runner_->BelongsToCurrentThread());
DCHECK_EQ(DesktopMediaID::kFakeId, desktop_id.id);
fake_device_factory_ =
std::make_unique<media::FakeVideoCaptureDeviceFactory>();
const base::CommandLine* command_line =
base::CommandLine::ForCurrentProcess();
if (command_line &&
command_line->HasSwitch(switches::kUseFakeDeviceForMediaStream)) {
std::vector<media::FakeVideoCaptureDeviceSettings> config;
media::FakeVideoCaptureDeviceFactory::
ParseFakeDevicesConfigFromOptionsString(
command_line->GetSwitchValueASCII(
switches::kUseFakeDeviceForMediaStream),
&config);
fake_device_factory_->SetToCustomDevicesConfig(config);
}
// base::Unretained() is safe because |this| owns |fake_device_factory_|.
fake_device_factory_->GetDevicesInfo(base::BindOnce(
&InProcessVideoCaptureDeviceLauncher::OnFakeDevicesEnumerated,
base::Unretained(this), params, std::move(device_client),
std::move(result_callback)));
}
void InProcessVideoCaptureDeviceLauncher::OnFakeDevicesEnumerated(
const media::VideoCaptureParams& params,
std::unique_ptr<media::VideoCaptureDeviceClient> device_client,
ReceiveDeviceCallback result_callback,
std::vector<media::VideoCaptureDeviceInfo> devices_info) {
DCHECK(device_task_runner_->BelongsToCurrentThread());
if (devices_info.empty()) {
LOG(ERROR) << "Cannot start with no fake device config";
std::move(result_callback).Run(nullptr);
return;
}
auto video_capture_device =
fake_device_factory_->CreateDevice(devices_info.front().descriptor);
video_capture_device->AllocateAndStart(params, std::move(device_client));
std::move(result_callback).Run(std::move(video_capture_device));
}
} // namespace content
| 40.758696 | 89 | 0.728892 | [
"vector"
] |
105a7d907dff84fde40a1df0d11fd0b5e35e6fee | 1,373 | cpp | C++ | cses/bit_strings.cpp | harshvsingh8/gym | 3538698894cda18027881cbcabdc31fa46208043 | [
"MIT"
] | null | null | null | cses/bit_strings.cpp | harshvsingh8/gym | 3538698894cda18027881cbcabdc31fa46208043 | [
"MIT"
] | null | null | null | cses/bit_strings.cpp | harshvsingh8/gym | 3538698894cda18027881cbcabdc31fa46208043 | [
"MIT"
] | null | null | null | /*
Your task is to calculate the number of bit strings of length n.
For example, if n=3, the correct answer is 8, because the possible bit
strings are 000, 001, 010, 011, 100, 101, 110, and 111.
Input
The only input line has an integer n.
Output
Print the result modulo 10^9 + 7.
Constraints
1≤n≤10^6
Example
Input:
3
Output:
8
*/
#include <algorithm>
#include <bitset>
#include <iostream>
#include <list>
#include <set>
#include <vector>
using namespace std;
/*
- The problem to handle larger value of n, as those number of bits
cannot be fit in any integer type.
- Given we only need to return the modulo value; one option is to
carry forward only the modulo of the bit-value in each step.
- The desired value is 2^N, but that cannot fit into any integer
type (for the allowed range of N).
- Observation: we can only carry forward the remainder in the next
step as the next value, that is its multiple of two divided by the
same modulo wound not depend on the rest of the higher value
digits (so the can be safely ignored).
*/
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
long input;
cin >> input;
long long bitValue = 1;
long long modValue = 1000000007;
for (long i = 0; i < input; i++) {
bitValue = 2 * bitValue;
bitValue %= modValue;
}
cout << bitValue << endl;
return 0;
}
| 19.898551 | 70 | 0.680991 | [
"vector"
] |
105b43d7b3f9732d7acb066ee20999431020bb05 | 12,379 | cc | C++ | google/cloud/asset/asset_client.cc | GoogleCloudPlatform/google-cloud-cpp | c4fc35de9e15f95b1dbf585f1c96de5dba609e2b | [
"Apache-2.0"
] | 80 | 2017-11-24T00:19:45.000Z | 2019-01-25T10:24:33.000Z | google/cloud/asset/asset_client.cc | GoogleCloudPlatform/google-cloud-cpp | c4fc35de9e15f95b1dbf585f1c96de5dba609e2b | [
"Apache-2.0"
] | 1,579 | 2017-11-24T01:01:21.000Z | 2019-01-28T23:41:21.000Z | google/cloud/asset/asset_client.cc | GoogleCloudPlatform/google-cloud-cpp | c4fc35de9e15f95b1dbf585f1c96de5dba609e2b | [
"Apache-2.0"
] | 51 | 2017-11-24T00:56:11.000Z | 2019-01-18T20:35:02.000Z | // Copyright 2022 Google LLC
//
// 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
//
// https://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.
// Generated by the Codegen C++ plugin.
// If you make any local changes, they will be lost.
// source: google/cloud/asset/v1/asset_service.proto
#include "google/cloud/asset/asset_client.h"
#include "google/cloud/asset/internal/asset_option_defaults.h"
#include <memory>
namespace google {
namespace cloud {
namespace asset {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
AssetServiceClient::AssetServiceClient(
std::shared_ptr<AssetServiceConnection> connection, Options opts)
: connection_(std::move(connection)),
options_(internal::MergeOptions(
std::move(opts),
asset_internal::AssetServiceDefaultOptions(connection_->options()))) {
}
AssetServiceClient::~AssetServiceClient() = default;
future<StatusOr<google::cloud::asset::v1::ExportAssetsResponse>>
AssetServiceClient::ExportAssets(
google::cloud::asset::v1::ExportAssetsRequest const& request,
Options opts) {
internal::OptionsSpan span(internal::MergeOptions(std::move(opts), options_));
return connection_->ExportAssets(request);
}
StreamRange<google::cloud::asset::v1::Asset> AssetServiceClient::ListAssets(
std::string const& parent, Options opts) {
internal::OptionsSpan span(internal::MergeOptions(std::move(opts), options_));
google::cloud::asset::v1::ListAssetsRequest request;
request.set_parent(parent);
return connection_->ListAssets(request);
}
StreamRange<google::cloud::asset::v1::Asset> AssetServiceClient::ListAssets(
google::cloud::asset::v1::ListAssetsRequest request, Options opts) {
internal::OptionsSpan span(internal::MergeOptions(std::move(opts), options_));
return connection_->ListAssets(std::move(request));
}
StatusOr<google::cloud::asset::v1::BatchGetAssetsHistoryResponse>
AssetServiceClient::BatchGetAssetsHistory(
google::cloud::asset::v1::BatchGetAssetsHistoryRequest const& request,
Options opts) {
internal::OptionsSpan span(internal::MergeOptions(std::move(opts), options_));
return connection_->BatchGetAssetsHistory(request);
}
StatusOr<google::cloud::asset::v1::Feed> AssetServiceClient::CreateFeed(
std::string const& parent, Options opts) {
internal::OptionsSpan span(internal::MergeOptions(std::move(opts), options_));
google::cloud::asset::v1::CreateFeedRequest request;
request.set_parent(parent);
return connection_->CreateFeed(request);
}
StatusOr<google::cloud::asset::v1::Feed> AssetServiceClient::CreateFeed(
google::cloud::asset::v1::CreateFeedRequest const& request, Options opts) {
internal::OptionsSpan span(internal::MergeOptions(std::move(opts), options_));
return connection_->CreateFeed(request);
}
StatusOr<google::cloud::asset::v1::Feed> AssetServiceClient::GetFeed(
std::string const& name, Options opts) {
internal::OptionsSpan span(internal::MergeOptions(std::move(opts), options_));
google::cloud::asset::v1::GetFeedRequest request;
request.set_name(name);
return connection_->GetFeed(request);
}
StatusOr<google::cloud::asset::v1::Feed> AssetServiceClient::GetFeed(
google::cloud::asset::v1::GetFeedRequest const& request, Options opts) {
internal::OptionsSpan span(internal::MergeOptions(std::move(opts), options_));
return connection_->GetFeed(request);
}
StatusOr<google::cloud::asset::v1::ListFeedsResponse>
AssetServiceClient::ListFeeds(std::string const& parent, Options opts) {
internal::OptionsSpan span(internal::MergeOptions(std::move(opts), options_));
google::cloud::asset::v1::ListFeedsRequest request;
request.set_parent(parent);
return connection_->ListFeeds(request);
}
StatusOr<google::cloud::asset::v1::ListFeedsResponse>
AssetServiceClient::ListFeeds(
google::cloud::asset::v1::ListFeedsRequest const& request, Options opts) {
internal::OptionsSpan span(internal::MergeOptions(std::move(opts), options_));
return connection_->ListFeeds(request);
}
StatusOr<google::cloud::asset::v1::Feed> AssetServiceClient::UpdateFeed(
google::cloud::asset::v1::Feed const& feed, Options opts) {
internal::OptionsSpan span(internal::MergeOptions(std::move(opts), options_));
google::cloud::asset::v1::UpdateFeedRequest request;
*request.mutable_feed() = feed;
return connection_->UpdateFeed(request);
}
StatusOr<google::cloud::asset::v1::Feed> AssetServiceClient::UpdateFeed(
google::cloud::asset::v1::UpdateFeedRequest const& request, Options opts) {
internal::OptionsSpan span(internal::MergeOptions(std::move(opts), options_));
return connection_->UpdateFeed(request);
}
Status AssetServiceClient::DeleteFeed(std::string const& name, Options opts) {
internal::OptionsSpan span(internal::MergeOptions(std::move(opts), options_));
google::cloud::asset::v1::DeleteFeedRequest request;
request.set_name(name);
return connection_->DeleteFeed(request);
}
Status AssetServiceClient::DeleteFeed(
google::cloud::asset::v1::DeleteFeedRequest const& request, Options opts) {
internal::OptionsSpan span(internal::MergeOptions(std::move(opts), options_));
return connection_->DeleteFeed(request);
}
StreamRange<google::cloud::asset::v1::ResourceSearchResult>
AssetServiceClient::SearchAllResources(
std::string const& scope, std::string const& query,
std::vector<std::string> const& asset_types, Options opts) {
internal::OptionsSpan span(internal::MergeOptions(std::move(opts), options_));
google::cloud::asset::v1::SearchAllResourcesRequest request;
request.set_scope(scope);
request.set_query(query);
*request.mutable_asset_types() = {asset_types.begin(), asset_types.end()};
return connection_->SearchAllResources(request);
}
StreamRange<google::cloud::asset::v1::ResourceSearchResult>
AssetServiceClient::SearchAllResources(
google::cloud::asset::v1::SearchAllResourcesRequest request, Options opts) {
internal::OptionsSpan span(internal::MergeOptions(std::move(opts), options_));
return connection_->SearchAllResources(std::move(request));
}
StreamRange<google::cloud::asset::v1::IamPolicySearchResult>
AssetServiceClient::SearchAllIamPolicies(std::string const& scope,
std::string const& query,
Options opts) {
internal::OptionsSpan span(internal::MergeOptions(std::move(opts), options_));
google::cloud::asset::v1::SearchAllIamPoliciesRequest request;
request.set_scope(scope);
request.set_query(query);
return connection_->SearchAllIamPolicies(request);
}
StreamRange<google::cloud::asset::v1::IamPolicySearchResult>
AssetServiceClient::SearchAllIamPolicies(
google::cloud::asset::v1::SearchAllIamPoliciesRequest request,
Options opts) {
internal::OptionsSpan span(internal::MergeOptions(std::move(opts), options_));
return connection_->SearchAllIamPolicies(std::move(request));
}
StatusOr<google::cloud::asset::v1::AnalyzeIamPolicyResponse>
AssetServiceClient::AnalyzeIamPolicy(
google::cloud::asset::v1::AnalyzeIamPolicyRequest const& request,
Options opts) {
internal::OptionsSpan span(internal::MergeOptions(std::move(opts), options_));
return connection_->AnalyzeIamPolicy(request);
}
future<StatusOr<google::cloud::asset::v1::AnalyzeIamPolicyLongrunningResponse>>
AssetServiceClient::AnalyzeIamPolicyLongrunning(
google::cloud::asset::v1::AnalyzeIamPolicyLongrunningRequest const& request,
Options opts) {
internal::OptionsSpan span(internal::MergeOptions(std::move(opts), options_));
return connection_->AnalyzeIamPolicyLongrunning(request);
}
StatusOr<google::cloud::asset::v1::AnalyzeMoveResponse>
AssetServiceClient::AnalyzeMove(
google::cloud::asset::v1::AnalyzeMoveRequest const& request, Options opts) {
internal::OptionsSpan span(internal::MergeOptions(std::move(opts), options_));
return connection_->AnalyzeMove(request);
}
StatusOr<google::cloud::asset::v1::SavedQuery>
AssetServiceClient::CreateSavedQuery(
std::string const& parent,
google::cloud::asset::v1::SavedQuery const& saved_query,
std::string const& saved_query_id, Options opts) {
internal::OptionsSpan span(internal::MergeOptions(std::move(opts), options_));
google::cloud::asset::v1::CreateSavedQueryRequest request;
request.set_parent(parent);
*request.mutable_saved_query() = saved_query;
request.set_saved_query_id(saved_query_id);
return connection_->CreateSavedQuery(request);
}
StatusOr<google::cloud::asset::v1::SavedQuery>
AssetServiceClient::CreateSavedQuery(
google::cloud::asset::v1::CreateSavedQueryRequest const& request,
Options opts) {
internal::OptionsSpan span(internal::MergeOptions(std::move(opts), options_));
return connection_->CreateSavedQuery(request);
}
StatusOr<google::cloud::asset::v1::SavedQuery>
AssetServiceClient::GetSavedQuery(std::string const& name, Options opts) {
internal::OptionsSpan span(internal::MergeOptions(std::move(opts), options_));
google::cloud::asset::v1::GetSavedQueryRequest request;
request.set_name(name);
return connection_->GetSavedQuery(request);
}
StatusOr<google::cloud::asset::v1::SavedQuery>
AssetServiceClient::GetSavedQuery(
google::cloud::asset::v1::GetSavedQueryRequest const& request,
Options opts) {
internal::OptionsSpan span(internal::MergeOptions(std::move(opts), options_));
return connection_->GetSavedQuery(request);
}
StreamRange<google::cloud::asset::v1::SavedQuery>
AssetServiceClient::ListSavedQueries(std::string const& parent, Options opts) {
internal::OptionsSpan span(internal::MergeOptions(std::move(opts), options_));
google::cloud::asset::v1::ListSavedQueriesRequest request;
request.set_parent(parent);
return connection_->ListSavedQueries(request);
}
StreamRange<google::cloud::asset::v1::SavedQuery>
AssetServiceClient::ListSavedQueries(
google::cloud::asset::v1::ListSavedQueriesRequest request, Options opts) {
internal::OptionsSpan span(internal::MergeOptions(std::move(opts), options_));
return connection_->ListSavedQueries(std::move(request));
}
StatusOr<google::cloud::asset::v1::SavedQuery>
AssetServiceClient::UpdateSavedQuery(
google::cloud::asset::v1::SavedQuery const& saved_query,
google::protobuf::FieldMask const& update_mask, Options opts) {
internal::OptionsSpan span(internal::MergeOptions(std::move(opts), options_));
google::cloud::asset::v1::UpdateSavedQueryRequest request;
*request.mutable_saved_query() = saved_query;
*request.mutable_update_mask() = update_mask;
return connection_->UpdateSavedQuery(request);
}
StatusOr<google::cloud::asset::v1::SavedQuery>
AssetServiceClient::UpdateSavedQuery(
google::cloud::asset::v1::UpdateSavedQueryRequest const& request,
Options opts) {
internal::OptionsSpan span(internal::MergeOptions(std::move(opts), options_));
return connection_->UpdateSavedQuery(request);
}
Status AssetServiceClient::DeleteSavedQuery(std::string const& name,
Options opts) {
internal::OptionsSpan span(internal::MergeOptions(std::move(opts), options_));
google::cloud::asset::v1::DeleteSavedQueryRequest request;
request.set_name(name);
return connection_->DeleteSavedQuery(request);
}
Status AssetServiceClient::DeleteSavedQuery(
google::cloud::asset::v1::DeleteSavedQueryRequest const& request,
Options opts) {
internal::OptionsSpan span(internal::MergeOptions(std::move(opts), options_));
return connection_->DeleteSavedQuery(request);
}
StatusOr<google::cloud::asset::v1::BatchGetEffectiveIamPoliciesResponse>
AssetServiceClient::BatchGetEffectiveIamPolicies(
google::cloud::asset::v1::BatchGetEffectiveIamPoliciesRequest const&
request,
Options opts) {
internal::OptionsSpan span(internal::MergeOptions(std::move(opts), options_));
return connection_->BatchGetEffectiveIamPolicies(request);
}
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace asset
} // namespace cloud
} // namespace google
| 41.680135 | 80 | 0.759512 | [
"vector"
] |
105b48c50ae84a7b51042c493c1647ce9d141045 | 235 | cpp | C++ | LeetCode/#1470.cpp | ksdkamesh99/Code-Monker | 0105d50185796539d4c2328892c9c117cb62ba55 | [
"MIT"
] | 3 | 2020-06-29T15:37:26.000Z | 2020-12-02T09:14:13.000Z | LeetCode/#1470.cpp | ksdkamesh99/Code-Monker | 0105d50185796539d4c2328892c9c117cb62ba55 | [
"MIT"
] | null | null | null | LeetCode/#1470.cpp | ksdkamesh99/Code-Monker | 0105d50185796539d4c2328892c9c117cb62ba55 | [
"MIT"
] | 1 | 2021-02-23T23:31:54.000Z | 2021-02-23T23:31:54.000Z | class Solution {
public:
vector<int> shuffle(vector<int>& nums, int n) {
vector<int>v;
for(int i=0;i<n;i++){
v.push_back(nums[i]);
v.push_back(nums[i+n]);
}
return v;
}
}; | 21.363636 | 51 | 0.47234 | [
"vector"
] |
105c7748c4d531716b62949b07d0a1bc0810b327 | 1,198 | hpp | C++ | src/GameState/AI/Enemy/EnemyState.hpp | Heaven31415/SpaceShooter | 385e43aa2deb8720c1b0a23834ad31de97fd25eb | [
"Zlib"
] | null | null | null | src/GameState/AI/Enemy/EnemyState.hpp | Heaven31415/SpaceShooter | 385e43aa2deb8720c1b0a23834ad31de97fd25eb | [
"Zlib"
] | null | null | null | src/GameState/AI/Enemy/EnemyState.hpp | Heaven31415/SpaceShooter | 385e43aa2deb8720c1b0a23834ad31de97fd25eb | [
"Zlib"
] | null | null | null | #pragma once
class Enemy;
class Object;
class PhysicalObject;
class World;
#include <map>
#include <memory>
#include <SFML/System/Time.hpp>
#include <SFML/System/Vector2.hpp>
#include "../../GUID.hpp"
struct Message
{
enum class Type
{
Int,
Float,
Vector2f,
Object,
PhysicalObject,
GUID
} type;
union
{
int Int;
float Float;
sf::Vector2f Vector2f;
Object* Object;
PhysicalObject* PhysicalObject;
GUID Guid;
};
};
class EnemyState
{
public:
typedef std::unique_ptr<EnemyState> Ptr;
virtual ~EnemyState() {}
virtual void update(Enemy* enemy, sf::Time dt, Message* message) = 0;
};
class EnemyStateManager
{
public:
EnemyStateManager();
typedef std::unique_ptr<EnemyStateManager> Ptr;
virtual void changeState(unsigned state);
virtual void update(Enemy* enemy, sf::Time dt);
protected:
unsigned m_actual;
std::map<unsigned, EnemyState::Ptr> m_states;
Message m_message;
}; | 20.655172 | 86 | 0.548414 | [
"object"
] |
105e4a29bc40ad5b7ac1793d83f59800a62f7a94 | 1,330 | cpp | C++ | examples/bacon.cpp | lums658/cppcon21 | 1e33a23f5e8d61a3f5164234e116c4878a02fec6 | [
"Apache-2.0"
] | 5 | 2022-02-08T00:25:07.000Z | 2022-03-15T21:39:30.000Z | examples/bacon.cpp | lums658/cppcon21 | 1e33a23f5e8d61a3f5164234e116c4878a02fec6 | [
"Apache-2.0"
] | null | null | null | examples/bacon.cpp | lums658/cppcon21 | 1e33a23f5e8d61a3f5164234e116c4878a02fec6 | [
"Apache-2.0"
] | 1 | 2022-01-28T11:55:25.000Z | 2022-01-28T11:55:25.000Z | //
// Copyright 2021 Andrew Lumsdaine
//
// 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.
//
// Simple example of finding bacon numbers from a given adjacency list graph
//
#include "bfs_edge_range.hpp"
#include "imdb-graph.hpp"
#include <iostream>
#include <string>
#include <vector>
std::vector<std::vector<int>> costars{
{1, 5, 6},
{7, 10, 0, 5, 12},
{4, 3, 11},
{2, 11},
{8, 9, 2, 12},
{0, 1},
{7, 0},
{6, 1, 10},
{4, 9},
{4, 8},
{7, 1},
{2, 3},
{1, 4}};
int main() {
std::vector<int> bacon_number(size(actors));
for (auto&& [u, v] : bfs_edge_range(costars, 1)) {
bacon_number[v] = bacon_number[u] + 1;
}
for (int i = 0; i < size(actors); ++i) {
std::cout << actors[i] << " has Bacon number " << bacon_number[i] << std::endl;
}
return 0;
}
| 24.181818 | 83 | 0.625564 | [
"vector"
] |
1060b69cd32d78f62e851ad42d423d19897a7f8b | 2,748 | cpp | C++ | clients/cpp-pistache-server/generated/model/ClockDifference.cpp | cliffano/jenkins-api-clients-generator | 522d02b3a130a29471df5ec1d3d22c822b3d0813 | [
"MIT"
] | null | null | null | clients/cpp-pistache-server/generated/model/ClockDifference.cpp | cliffano/jenkins-api-clients-generator | 522d02b3a130a29471df5ec1d3d22c822b3d0813 | [
"MIT"
] | null | null | null | clients/cpp-pistache-server/generated/model/ClockDifference.cpp | cliffano/jenkins-api-clients-generator | 522d02b3a130a29471df5ec1d3d22c822b3d0813 | [
"MIT"
] | null | null | null | /**
* Swaggy Jenkins
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.1.2-pre.0
* Contact: blah@cliffano.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "ClockDifference.h"
#include "Helpers.h"
#include <sstream>
namespace org::openapitools::server::model
{
ClockDifference::ClockDifference()
{
m__class = "";
m__classIsSet = false;
m_Diff = 0;
m_DiffIsSet = false;
}
void ClockDifference::validate() const
{
std::stringstream msg;
if (!validate(msg))
{
throw org::openapitools::server::helpers::ValidationException(msg.str());
}
}
bool ClockDifference::validate(std::stringstream& msg) const
{
return validate(msg, "");
}
bool ClockDifference::validate(std::stringstream& msg, const std::string& pathPrefix) const
{
bool success = true;
const std::string _pathPrefix = pathPrefix.empty() ? "ClockDifference" : pathPrefix;
return success;
}
bool ClockDifference::operator==(const ClockDifference& rhs) const
{
return
((!r_classIsSet() && !rhs.r_classIsSet()) || (r_classIsSet() && rhs.r_classIsSet() && getClass() == rhs.getClass())) &&
((!diffIsSet() && !rhs.diffIsSet()) || (diffIsSet() && rhs.diffIsSet() && getDiff() == rhs.getDiff()))
;
}
bool ClockDifference::operator!=(const ClockDifference& rhs) const
{
return !(*this == rhs);
}
void to_json(nlohmann::json& j, const ClockDifference& o)
{
j = nlohmann::json();
if(o.r_classIsSet())
j["_class"] = o.m__class;
if(o.diffIsSet())
j["diff"] = o.m_Diff;
}
void from_json(const nlohmann::json& j, ClockDifference& o)
{
if(j.find("_class") != j.end())
{
j.at("_class").get_to(o.m__class);
o.m__classIsSet = true;
}
if(j.find("diff") != j.end())
{
j.at("diff").get_to(o.m_Diff);
o.m_DiffIsSet = true;
}
}
std::string ClockDifference::getClass() const
{
return m__class;
}
void ClockDifference::setClass(std::string const& value)
{
m__class = value;
m__classIsSet = true;
}
bool ClockDifference::r_classIsSet() const
{
return m__classIsSet;
}
void ClockDifference::unset_class()
{
m__classIsSet = false;
}
int32_t ClockDifference::getDiff() const
{
return m_Diff;
}
void ClockDifference::setDiff(int32_t const value)
{
m_Diff = value;
m_DiffIsSet = true;
}
bool ClockDifference::diffIsSet() const
{
return m_DiffIsSet;
}
void ClockDifference::unsetDiff()
{
m_DiffIsSet = false;
}
} // namespace org::openapitools::server::model
| 20.205882 | 123 | 0.646288 | [
"model"
] |
1060f1a06639ac4e49c0164c6080aeccc5fe6c64 | 1,153 | cxx | C++ | Algorithms/Implementation/electronics-shop.cxx | will-crawford/HackerRank | 74965480ee6a51603eb320e5982b0943fdaf1302 | [
"MIT"
] | null | null | null | Algorithms/Implementation/electronics-shop.cxx | will-crawford/HackerRank | 74965480ee6a51603eb320e5982b0943fdaf1302 | [
"MIT"
] | null | null | null | Algorithms/Implementation/electronics-shop.cxx | will-crawford/HackerRank | 74965480ee6a51603eb320e5982b0943fdaf1302 | [
"MIT"
] | null | null | null | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
ostream & operator<< ( ostream &os, vector<int> &v ) {
auto i = begin(v), last = end(v);
if ( i != last ) {
cerr << *i;
while ( ++i != last )
cerr << ' ' << *i;
}
return os;
}
inline void sort ( vector<int> &v ) { sort ( begin(v), end(v), greater<>() ); }
int hunt ( vector<int> &N, vector<int> &M, int s ) {
int spend = -1;
for ( auto &n : N ) {
if ( n + M[0] < spend )
break;
for ( auto &m : M ) {
if ( n + m < spend )
break;
else if ( n + m <= s ) {
spend = n + m;
if ( n + m == s )
return spend;
}
}
}
return spend;
}
int main() {
int s, n, m; cin >> s >> n >> m; cerr << s << ' ' << n << ' ' << m << endl;
vector<int> N (n); for ( auto &i : N ) cin >> i; sort( N ); cerr << N << endl;
vector<int> M (m); for ( auto &i : M ) cin >> i; sort( M ); cerr << M << endl;
cout << hunt( N, M, s ) << endl;
return 0;
}
| 25.622222 | 82 | 0.413703 | [
"vector"
] |
1061e57098622d5a53ded06ebd4f96bb0c2eaa4c | 298 | cpp | C++ | src/Model/Node/Operation/abstractoperationnode.cpp | tasmanianfox/sat-cnf-converter | a8ea106d8745f9f7ac14f7e8c39f6f6aa4819211 | [
"MIT"
] | 4 | 2017-04-01T05:09:51.000Z | 2018-06-15T04:43:15.000Z | src/Model/Node/Operation/abstractoperationnode.cpp | tasmanianfox/sat-cnf-converter | a8ea106d8745f9f7ac14f7e8c39f6f6aa4819211 | [
"MIT"
] | null | null | null | src/Model/Node/Operation/abstractoperationnode.cpp | tasmanianfox/sat-cnf-converter | a8ea106d8745f9f7ac14f7e8c39f6f6aa4819211 | [
"MIT"
] | 3 | 2015-09-20T09:17:12.000Z | 2021-01-31T09:09:34.000Z | #include "abstractoperationnode.h"
using namespace Model::Node::Operation;
AbstractOperationNode::~AbstractOperationNode()
{
}
AbstractOperationNode::AbstractOperationNode():AbstractNode()
{
}
int AbstractOperationNode::getType()
{
return this->TYPE_OPERATION_ABSTRACT;
}
| 16.555556 | 62 | 0.741611 | [
"model"
] |
106416a673d8fb5de037fec7241a0727005d8ea3 | 10,960 | cpp | C++ | Baseline/PCA-CD/ChangeDetection/CD.cpp | vincentpun/ConformanceConstraintsReproducibility | fc5df4ec9a3702a1837ffe6f3c05216523e8a1c5 | [
"MIT"
] | null | null | null | Baseline/PCA-CD/ChangeDetection/CD.cpp | vincentpun/ConformanceConstraintsReproducibility | fc5df4ec9a3702a1837ffe6f3c05216523e8a1c5 | [
"MIT"
] | 1 | 2021-12-09T09:30:49.000Z | 2021-12-09T09:30:49.000Z | Baseline/PCA-CD/ChangeDetection/CD.cpp | vincentpun/ConformanceConstraintsReproducibility | fc5df4ec9a3702a1837ffe6f3c05216523e8a1c5 | [
"MIT"
] | 1 | 2021-12-09T05:22:18.000Z | 2021-12-09T05:22:18.000Z | /*
* File: CD.cpp
* Author: Hakim
*
* Created on Aug 4, 2014, 10:05 PM
* Last modified on Feb. 12, 2015
*/
/*==============================================================*/
#include "stdlib.h"
#include "CD.h"
#include "pca.h"
using namespace std;
//*===============================================================
int main(int argc, char* argv[])
{
fstream infs, CHfs, den;
double rem_pnt;
double R_sum[MAX_DIM], R_sqsum[MAX_DIM];
int R_tot_num_pnts = 0, T_tot_num_pnts = 0;
double sigma[MAX_DIM];
double B_Width;
long data_length, i;
int DivMetric;
double DP;
double BNR[MAX_DIM];
double p_mean_current, m_current, M_current, PH_current, lambda;
long start_point = 0;
p_mean_current = 0;
m_current = 0;
M_current = 0;
PH_current = 0;
// ============================================================
// Initialize sum, sqsum variables
for (i = 0; i < MAX_DIM; i++)
{
R_sum[i] = 0.0;
R_sqsum[i] = 0.0;
}
/************************************/
clock_t BeginSim, EndSim;
double elapTicks;
double elapMilli;
/************************************/
std::list<double>::iterator it;
if(argc != 9)
{
cout << "\n\n\n Usage (" << argv[0] << "): <Data File> <Window Size> <Threshold Factor> "
"<Output Change File> <Data Dimension> <Delta>"
"<Divergence Metric [1/2]>" << endl;
cout << "\n\n <Press Enter to exit>" << endl;
getchar();
return 2;
}
//Handle first argument -- open the data file
infs.open(argv[1], ios::in);
if (!infs.good())
{
cout << "Error opening data file.." << endl;
return 3;
}
//============Read the Window Size================
Win_Size = atoi(argv[2]);
f = atof(argv[3]);
//========================================================
//Handle third argument -- open a file to store the density
CHfs.open(argv[4], ios::out);
if (!CHfs.good())
{
cout << "Error opening output MAE file.." << endl;
return 3;
}
//============Read the Dimension of the data================
DIM = atoi(argv[5]);
delta = atof(argv[6]);
DivMetric = atoi(argv[7]);
if (DivMetric != 1 && DivMetric != 2)
{
cout << "Unknown divergence metric ... \n";
return 3;
}
stats::pca *mypca;
mypca = new stats::pca(DIM);
if (mypca == NULL)
{
cout << "Error when allocating space for pca ... exiting ... \n";
return 3;
}
// =========== Start Timer ==============
BeginSim = clock(); //Get Starting Time
data_length = 0;
ScCount = 0;
for (i = 0; i < DIM; i++)
R_mean[i] = 0.0;
// ============== Create the first reference model ==============
while (infs.good() && R_tot_num_pnts < Win_Size)
{
vector<double> record(DIM);
int idx = 0;
for (auto value=record.begin(); value!=record.end(); ++value)
{
infs >> *value;
if(!infs.good())
break;
R_mean[idx++] += *value;
}
mypca->add_record(record);
data_length ++; R_tot_num_pnts ++;
}
for (int idx = 0; idx < DIM; idx++)
{
R_mean[idx] /= (double) R_tot_num_pnts;
}
mypca->solve();
eigs = 0;
New_DIM = DIM;
for (i = 0; i < DIM; i++)
{
eigs += mypca->get_eigenvalue(i);
if (eigs > cum_eig)
{
New_DIM = i + 1;
break;
}
}
for (i = 0; i < New_DIM; i++)
{
// =============== Extract eigen vectors =====================
vector<double> eigVec = mypca->get_eigenvector(i);
for (int m = 0; m < DIM; m ++)
eigVectors[m][i] = eigVec[m];
// =============== Extract principal components =====================
vector<double> princomp = mypca->get_principal(i);
for (int k = 0; k < princomp.size(); k++)
{
DP = princomp[k];
MD[i].Data_List.push_back(DP);
if (k == 0)
min_val[i] = max_val[i] = DP;
else
{
min_val[i] = MIN(min_val[i], DP);
max_val[i] = MAX(max_val[i], DP);
}
R_sum[i] += DP;
R_sqsum[i] += DP * DP;
}
}
for (i = 0; i < New_DIM; i++)
{
BNR[i] = Bandwidth_NR(R_sum[i], R_sqsum[i], MIN(data_length, Win_Size), sigma[i]);
num_resamp_pnts = bin_width_factor * (max_val[i] - min_val[i]) / BNR[i];
B_Width = (max_val[i] - min_val[i]) / (double) num_resamp_pnts;
create_Hist(Hist[i].H, MD[i].Data_List, min_val[i], max_val[i], num_resamp_pnts, 0);
}
T_tot_num_pnts = 0;
for (i = 0; i < DIM; i++)
{
while (!MD[i].Data_List.empty())
{
MD[i].Data_List.pop_front();
}
}
/*delete mypca;
mypca = new stats::pca(DIM);
if (mypca == NULL)
{
cout << "Error when allocating space for pca ... exiting ... \n";
return 3;
}
*/
infs.close();
infs.open(argv[1], ios::in);
data_length = 0;
while (infs.good())
{
if (T_tot_num_pnts < Win_Size)
{
while (infs.good() && (T_tot_num_pnts < Win_Size))
{
vector<double> record(DIM);
int idx = 0;
for (auto value=record.begin(); value!=record.end(); ++value)
{
infs >> *value;
if(!infs.good())
break;
*value = *value - R_mean[idx++];
}
vector<double> p_record(DIM);
for (int m = 0; m < DIM; m++)
p_record[m] = 0.0;
for (int m = 0; m < DIM; m++)
for (int k = 0; k < DIM; k++)
p_record[m] += record[k] * eigVectors[k][m];
for (int k = 0; k < DIM; k++)
{
DP = p_record[k];
MD[k].Data_List.push_back(DP);
}
data_length ++; T_tot_num_pnts ++;
}
// mypca->solve();
if (MD[0].Data_List.size() < Win_Size)
{
break;
}
for (i = 0; i < New_DIM; i++)
{
create_Hist(Hist[i].H, MD[i].Data_List, min_val[i], max_val[i],
num_resamp_pnts, 1);
Score[i] = Compare_Dist(Hist[i].H, B_Width, R_tot_num_pnts, DivMetric);
}
}
// ===================Compare the distributions=============
for (int k = 0; k < New_DIM; k++)
{
if (DivMetric == 1)
F_Score = 1.0 - Score[k] / R_tot_num_pnts;
else
F_Score = Score[k];
if (k == 0)
{ MaxScore = F_Score; }
else
{
MaxScore = MAX(MaxScore, F_Score);
}
}
// ======== Compute Tdynamic, the dynamic (PHT) threshold =============
/* Commented out by Anna
p_mean_current = (p_mean_current * (ScCount - start_point) +
MaxScore) / (double)(ScCount - start_point + 1.0);
m_current = m_current + p_mean_current - MaxScore + delta;
if (fabs(m_current) > M_current)
M_current = fabs(m_current);
PH_current = - m_current;
ScCount++;
lambda = f * p_mean_current;
*/
// These lines are added by Anna so that change amount is reported perodically
if(data_length % Win_Size == 0)
{
CHfs << MaxScore << endl;
start_point = ScCount;
p_mean_current = 0;
m_current = 0;
M_current = 0;
PH_current = 0;
// **************************************************************
// ====== Re-initialize the reference distribution parameters============
for (int k = 0; k < DIM; k++)
{
while (!MD[k].Data_List.empty())
{
if (atoi(argv[8]) == 0)
MD[k].Data_List.pop_back();
else
MD[k].Data_List.pop_front();
}
//R_sum[k] = 0.0;
//R_sqsum[k] = 0.0;
//R_mean[k] = 0.0;
}
/*R_tot_num_pnts = 0;
delete mypca;
mypca = new stats::pca(DIM);
if (mypca == NULL)
{
cout << "Error when allocating space for pca ... exiting ... \n";
return 3;
}
while (infs.good() && R_tot_num_pnts < Win_Size)
{
vector<double> record(DIM);
int idx = 0;
for (auto value=record.begin(); value!=record.end(); ++value)
{
infs >> *value;
if(!infs.good())
break;
R_mean[idx++] += *value;
}
mypca->add_record(record);
data_length ++; R_tot_num_pnts ++;
}
for (int idx = 0; idx < DIM; idx++)
R_mean[idx] /= (double) R_tot_num_pnts;
//mypca->solve();
*/
eigs = 0;
for (i = 0; i < DIM; i++)
{
eigs += mypca->get_eigenvalue(i);
if (eigs > cum_eig)
{
New_DIM = i + 1;
break;
}
}
for (i = 0; i < New_DIM; i++)
{
// =============== Extract eigen vectors =====================
vector<double> eigVec = mypca->get_eigenvector(i);
for (int m = 0; m < DIM; m ++)
eigVectors[m][i] = eigVec[m];
// =============== Extract principal components =====================
vector<double> princomp = mypca->get_principal(i);
for (int k = 0; k < princomp.size(); k++)
{
DP = princomp[k];
MD[i].Data_List.push_back(DP);
if (k == 0)
min_val[i] = max_val[i] = DP;
else
{
min_val[i] = MIN(min_val[i], DP);
max_val[i] = MAX(max_val[i], DP);
}
//R_sum[i] += DP;
//R_sqsum[i] += DP * DP;
}
}
if (MD[0].Data_List.size() < Win_Size)
{
break;
}
// ======================== Re-generate the Ref model ========================
for (i = 0; i < New_DIM; i++)
{
BNR[i] = Bandwidth_NR(R_sum[i], R_sqsum[i], MIN(data_length, Win_Size), sigma[i]);
num_resamp_pnts = bin_width_factor * (max_val[i] - min_val[i]) / BNR[i];
B_Width = (max_val[i] - min_val[i]) / (double) num_resamp_pnts;
create_Hist(Hist[i].H, MD[i].Data_List, min_val[i], max_val[i], num_resamp_pnts, 0);
}
/*delete mypca;
mypca = new stats::pca(DIM);
if (mypca == NULL)
{
cout << "Error when allocating space for pca ... exiting ... \n";
return 3;
}*/
T_tot_num_pnts = 0;
for (i = 0; i < DIM; i++)
{
while (!MD[i].Data_List.empty())
{
MD[i].Data_List.pop_front();
}
}
continue;
}
vector<double> n_record(DIM);
int idx = 0;
for (auto value=n_record.begin(); value!=n_record.end(); ++value)
{
infs >> *value;
if(!infs.good())
break;
*value = *value - R_mean[idx++];
}
// ========= Project the data point on the components ==========
vector<double> p_record(DIM);
for (int m = 0; m < DIM; m++)
p_record[m] = 0.0;
for (int m = 0; m < DIM; m++)
for (int k = 0; k < DIM; k++)
p_record[m] += n_record[k] * eigVectors[k][m];
for (int k = 0; k < New_DIM; k++)
{
DP = p_record[k];
rem_pnt = MD[k].Data_List.front();
MD[k].Data_List.pop_front();
// ====== Update the density of the test distribution
update_Hist(Hist[k].H, DP, rem_pnt, min_val[k], max_val[k], k, R_tot_num_pnts, DivMetric);
MD[k].Data_List.push_back(DP);
}
data_length++;
}
/******************************************/
EndSim = clock();
elapTicks = EndSim - BeginSim;
elapMilli = (double) elapTicks / 1000;
/******************************************/
CHfs.close();
infs.close();
Results(argv[4], data_length-1, Win_Size, elapMilli / 1000);
return 0;
}
| 25.311778 | 94 | 0.493887 | [
"vector",
"model"
] |
10647dd934d488990bdf9f6e449fc6500fbfb85a | 7,620 | cpp | C++ | cpp/src/jit/cache.cpp | chenrui17/cudf | a0045bd15981d8a2ef165c3a5e4306474eda958e | [
"Apache-2.0"
] | null | null | null | cpp/src/jit/cache.cpp | chenrui17/cudf | a0045bd15981d8a2ef165c3a5e4306474eda958e | [
"Apache-2.0"
] | null | null | null | cpp/src/jit/cache.cpp | chenrui17/cudf | a0045bd15981d8a2ef165c3a5e4306474eda958e | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2019-2020, NVIDIA 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.
*/
#include <jit/cache.h>
#include <cudf/utilities/error.hpp>
#include <errno.h>
#include <fcntl.h>
#include <pwd.h>
#include <stdio.h>
#include <unistd.h>
#include <boost/filesystem.hpp>
#include <cuda.h>
namespace cudf {
namespace jit {
// Get the directory in home to use for storing the cache
boost::filesystem::path get_user_home_cache_dir()
{
auto home_dir = std::getenv("HOME");
if (home_dir != nullptr) {
return boost::filesystem::path(home_dir) / ".cudf";
} else {
return boost::filesystem::path();
}
}
// Default `LIBCUDF_KERNEL_CACHE_PATH` to `$HOME/.cudf/$CUDF_VERSION`.
// This definition can be overridden at compile time by specifying a
// `-DLIBCUDF_KERNEL_CACHE_PATH=/kernel/cache/path` CMake argument.
// Use `boost::filesystem` for cross-platform path resolution and dir
// creation. This path is used in the `getCacheDir()` function below.
#if !defined(LIBCUDF_KERNEL_CACHE_PATH)
#define LIBCUDF_KERNEL_CACHE_PATH get_user_home_cache_dir()
#endif
/**
* @brief Get the string path to the JITIFY kernel cache directory.
*
* This path can be overridden at runtime by defining an environment variable
* named `LIBCUDF_KERNEL_CACHE_PATH`. The value of this variable must be a path
* under which the process' user has read/write privileges.
*
* This function returns a path to the cache directory, creating it if it
* doesn't exist.
*
* The default cache directory is `$HOME/.cudf/$CUDF_VERSION`. If no overrides
* are used and if $HOME is not defined, returns an empty path and file
* caching is not used.
*/
boost::filesystem::path getCacheDir()
{
// The environment variable always overrides the
// default/compile-time value of `LIBCUDF_KERNEL_CACHE_PATH`
auto kernel_cache_path_env = std::getenv("LIBCUDF_KERNEL_CACHE_PATH");
auto kernel_cache_path = boost::filesystem::path(
kernel_cache_path_env != nullptr ? kernel_cache_path_env : LIBCUDF_KERNEL_CACHE_PATH);
// Cache path could be empty when env HOME is unset or LIBCUDF_KERNEL_CACHE_PATH is defined to be
// empty, to disallow use of file cache at runtime.
if (not kernel_cache_path.empty()) {
kernel_cache_path /= std::string{CUDF_STRINGIFY(CUDF_VERSION)};
try {
// `mkdir -p` the kernel cache path if it doesn't exist
boost::filesystem::create_directories(kernel_cache_path);
} catch (const std::exception& e) {
// if directory creation fails for any reason, return empty path
return boost::filesystem::path();
}
}
return kernel_cache_path;
}
cudfJitCache::cudfJitCache() {}
cudfJitCache::~cudfJitCache() {}
std::mutex cudfJitCache::_kernel_cache_mutex;
std::mutex cudfJitCache::_program_cache_mutex;
named_prog<jitify::experimental::Program> cudfJitCache::getProgram(
std::string const& prog_name,
std::string const& cuda_source,
std::vector<std::string> const& given_headers,
std::vector<std::string> const& given_options,
jitify::experimental::file_callback_type file_callback)
{
// Lock for thread safety
std::lock_guard<std::mutex> lock(_program_cache_mutex);
return getCached(prog_name, program_map, [&]() {
CUDF_EXPECTS(not cuda_source.empty(), "Program not found in cache, Needs source string.");
return jitify::experimental::Program(cuda_source, given_headers, given_options, file_callback);
});
}
named_prog<jitify::experimental::KernelInstantiation> cudfJitCache::getKernelInstantiation(
std::string const& kern_name,
named_prog<jitify::experimental::Program> const& named_program,
std::vector<std::string> const& arguments)
{
// Lock for thread safety
std::lock_guard<std::mutex> lock(_kernel_cache_mutex);
std::string prog_name = std::get<0>(named_program);
jitify::experimental::Program& program = *std::get<1>(named_program);
// Make instance name e.g. "prog_binop.kernel_v_v_int_int_long int_Add"
std::string kern_inst_name = prog_name + '.' + kern_name;
for (auto&& arg : arguments) kern_inst_name += '_' + arg;
CUcontext c;
cuCtxGetCurrent(&c);
auto& kernel_inst_map = kernel_inst_context_map[c];
return getCached(kern_inst_name, kernel_inst_map, [&]() {
return program.kernel(kern_name).instantiate(arguments);
});
}
// Another overload for getKernelInstantiation which might be useful to get
// kernel instantiations in one step
// ------------------------------------------------------------------------
/*
jitify::experimental::KernelInstantiation cudfJitCache::getKernelInstantiation(
std::string const& kern_name,
std::string const& prog_name,
std::string const& cuda_source = "",
std::vector<std::string> const& given_headers = {},
std::vector<std::string> const& given_options = {},
file_callback_type file_callback = nullptr)
{
auto program = getProgram(prog_name,
cuda_source,
given_headers,
given_options,
file_callback);
return getKernelInstantiation(kern_name, program);
}
*/
cudfJitCache::cacheFile::cacheFile(std::string file_name) : _file_name{file_name} {}
cudfJitCache::cacheFile::~cacheFile() {}
std::string cudfJitCache::cacheFile::read()
{
// Open file (duh)
int fd = open(_file_name.c_str(), O_RDWR);
if (fd == -1) {
successful_read = false;
return std::string();
}
// Create args for file locking
flock fl{};
fl.l_type = F_RDLCK; // Shared lock for reading
fl.l_whence = SEEK_SET;
// Lock the file descriptor. Only reading is allowed now
if (fcntl(fd, F_SETLKW, &fl) == -1) {
successful_read = false;
return std::string();
}
// Get file descriptor from file pointer
FILE* fp = fdopen(fd, "rb");
// Get file length
fseek(fp, 0L, SEEK_END);
size_t file_size = ftell(fp);
rewind(fp);
// Allocate memory of file length size
std::string content;
content.resize(file_size);
char* buffer = &content[0];
// Copy file into buffer
if (fread(buffer, file_size, 1, fp) != 1) {
successful_read = false;
fclose(fp);
free(buffer);
return std::string();
}
fclose(fp);
successful_read = true;
return content;
}
void cudfJitCache::cacheFile::write(std::string content)
{
// Open file and create if it doesn't exist, with access 0600
int fd = open(_file_name.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
if (fd == -1) {
successful_write = false;
return;
}
// Create args for file locking
flock fl{};
fl.l_type = F_WRLCK; // Exclusive lock for writing
fl.l_whence = SEEK_SET;
// Lock the file descriptor. we the only ones now
if (fcntl(fd, F_SETLKW, &fl) == -1) {
successful_write = false;
return;
}
// Get file descriptor from file pointer
FILE* fp = fdopen(fd, "wb");
// Copy string into file
if (fwrite(content.c_str(), content.length(), 1, fp) != 1) {
successful_write = false;
fclose(fp);
return;
}
fclose(fp);
successful_write = true;
return;
}
} // namespace jit
} // namespace cudf
| 31.229508 | 99 | 0.692651 | [
"vector"
] |
10656ed3013d86e1d67d2f6679377f625530df9f | 45,037 | cpp | C++ | misc.cpp | ahmadhassan997/udp2raw-tunnel | 4729224cc4aa24ff333b7817ebca769308e01119 | [
"MIT"
] | 5,010 | 2017-08-05T23:31:36.000Z | 2021-09-22T01:57:43.000Z | misc.cpp | gladiopeace/udp2raw | b98a467eed197e856518e7ce31a4fe5d5d62901d | [
"MIT"
] | 396 | 2017-08-07T05:17:41.000Z | 2021-09-14T17:46:32.000Z | misc.cpp | gladiopeace/udp2raw | b98a467eed197e856518e7ce31a4fe5d5d62901d | [
"MIT"
] | 1,062 | 2017-08-05T23:31:06.000Z | 2021-09-20T12:36:33.000Z | /*
* misc.cpp
*
* Created on: Sep 23, 2017
* Author: root
*/
#include "git_version.h"
#include "common.h"
#include "encrypt.h"
#include "misc.h"
#include "network.h"
#include "connection.h"
#include "fd_manager.h"
int hb_mode=1;
int hb_len=1200;
char hb_buf[buf_len];
int mtu_warn=1375;//if a packet larger than mtu warn is receviced,there will be a warning
int max_rst_to_show=15;
int max_rst_allowed=-1;
int enable_dns_resolve=0;
int ttl_value=64;
fd_manager_t fd_manager;
//char remote_address[max_address_len]="";
//char local_ip[100]="0.0.0.0", remote_ip[100]="255.255.255.255",source_ip[100]="0.0.0.0";//local_ip is for -l option,remote_ip for -r option,source for --source-ip
//u32_t local_ip_uint32,remote_ip_uint32,source_ip_uint32;//convert from last line.
//int local_port = -1, remote_port=-1,source_port=0;//similiar to local_ip remote_ip,buf for port.source_port=0 indicates --source-port is not enabled
address_t local_addr,remote_addr,source_addr;
my_ip_t bind_addr;
int source_port=-1;
int bind_addr_used=0;
int force_source_ip=0; //if --source-ip is enabled
int force_source_port=0;
my_id_t const_id=0;//an id used for connection recovery,its generated randomly,it never change since its generated
int udp_fd=-1; //for client only. client use this fd to listen and handle udp connection
int bind_fd=-1; //bind only,never send or recv. its just a dummy fd for bind,so that other program wont occupy the same port
#ifdef UDP2RAW_LINUX
int epollfd=-1; //fd for epoll
int timer_fd=-1; //the general timer fd for client and server.for server this is not the only timer find,every connection has a timer fd.
#endif
int fail_time_counter=0;//determine if the max_fail_time is reached
int epoll_trigger_counter=0;//for debug only
int debug_flag=0;//for debug only
int simple_rule=0; //deprecated.
int keep_rule=0; //whether to monitor the iptables rule periodly,re-add if losted
int auto_add_iptables_rule=0;//if -a is set
int generate_iptables_rule=0;//if -g is set
int generate_iptables_rule_add=0;// if --gen-add is set
int retry_on_error=0;
int debug_resend=0; // debug only
char key_string[1000]= "secret key";// -k option
char fifo_file[1000]="";
int clear_iptables=0;
int wait_xtables_lock=0;
#ifdef UDP2RAW_LINUX
string iptables_command0="iptables/ip6tables ";
string iptables_command="";
string iptables_pattern="";
int iptables_rule_added=0;
int iptables_rule_keeped=0;
int iptables_rule_keep_index=0;
#endif
program_mode_t program_mode=unset_mode;//0 unset; 1client 2server
raw_mode_t raw_mode=mode_faketcp;
u32_t raw_ip_version=(u32_t)-1;
unordered_map<int, const char*> raw_mode_tostring = {{mode_faketcp, "faketcp"}, {mode_udp, "udp"}, {mode_icmp, "icmp"}};
int about_to_exit=0;
int socket_buf_size=1024*1024;
//int force_socket_buf=0;
//char lower_level_arg[1000];
#ifdef UDP2RAW_LINUX
int process_lower_level_arg()//handle --lower-level option
{
lower_level=1;
if(strcmp(optarg,"auto")==0)
{
return 0;
}
lower_level_manual=1;
if (strchr(optarg, '#') == 0) {
mylog(log_fatal,
"lower-level parameter invaild,check help page for format\n");
myexit(-1);
}
lower_level = 1;
u32_t hw[6];
memset(hw, 0, sizeof(hw));
sscanf(optarg, "%[^#]#%x:%x:%x:%x:%x:%x", if_name, &hw[0], &hw[1], &hw[2],
&hw[3], &hw[4], &hw[5]);
mylog(log_warn,
"make sure this is correct: if_name=<%s> dest_mac_adress=<%02x:%02x:%02x:%02x:%02x:%02x> \n",
if_name, hw[0], hw[1], hw[2], hw[3], hw[4], hw[5]);
for (int i = 0; i < 6; i++) {
dest_hw_addr[i] = uint8_t(hw[i]);
}
return 0;
}
#endif
void print_help()
{
char git_version_buf[100]={0};
strncpy(git_version_buf,gitversion,10);
printf("udp2raw-tunnel\n");
printf("git version:%s ",git_version_buf);
printf("build date:%s %s\n",__DATE__,__TIME__);
printf("repository: https://github.com/wangyu-/udp2raw-tunnel\n");
printf("\n");
#ifdef UDP2RAW_MP
#ifdef NO_LIBNET
printf("libnet is disabled at compile time\n");
printf("\n");
#endif
#endif
printf("usage:\n");
printf(" run as client : ./this_program -c -l local_listen_ip:local_port -r server_address:server_port [options]\n");
printf(" run as server : ./this_program -s -l server_listen_ip:server_port -r remote_address:remote_port [options]\n");
printf("\n");
printf("common options,these options must be same on both side:\n");
printf(" --raw-mode <string> available values:faketcp(default),udp,icmp and easy-faketcp\n");
printf(" -k,--key <string> password to gen symetric key,default:\"secret key\"\n");
printf(" --cipher-mode <string> available values:aes128cfb,aes128cbc(default),xor,none\n");
printf(" --auth-mode <string> available values:hmac_sha1,md5(default),crc32,simple,none\n");
printf(" -a,--auto-rule auto add (and delete) iptables rule\n");
printf(" -g,--gen-rule generate iptables rule then exit,so that you can copy and\n");
printf(" add it manually.overrides -a\n");
printf(" --disable-anti-replay disable anti-replay,not suggested\n");
printf(" --fix-gro try to fix huge packet caused by GRO. this option is at an early stage.\n");
printf(" make sure client and server are at same version.\n");
//printf("\n");
printf("client options:\n");
printf(" --source-ip <ip> force source-ip for raw socket\n");
printf(" --source-port <port> force source-port for raw socket,tcp/udp only\n");
printf(" this option disables port changing while re-connecting\n");
// printf(" \n");
printf("other options:\n");
printf(" --conf-file <string> read options from a configuration file instead of command line.\n");
printf(" check example.conf in repo for format\n");
printf(" --fifo <string> use a fifo(named pipe) for sending commands to the running program,\n");
printf(" check readme.md in repository for supported commands.\n");
printf(" --log-level <number> 0:never 1:fatal 2:error 3:warn \n");
printf(" 4:info (default) 5:debug 6:trace\n");
// printf("\n");
printf(" --log-position enable file name,function name,line number in log\n");
printf(" --disable-color disable log color\n");
printf(" --disable-bpf disable the kernel space filter,most time its not necessary\n");
printf(" unless you suspect there is a bug\n");
// printf("\n");
#ifdef UDP2RAW_LINUX
printf(" --dev <string> bind raw socket to a device, not necessary but improves performance\n");
#endif
printf(" --sock-buf <number> buf size for socket,>=10 and <=10240,unit:kbyte,default:1024\n");
printf(" --force-sock-buf bypass system limitation while setting sock-buf\n");
printf(" --seq-mode <number> seq increase mode for faketcp:\n");
printf(" 0:static header,do not increase seq and ack_seq\n");
printf(" 1:increase seq for every packet,simply ack last seq\n");
printf(" 2:increase seq randomly, about every 3 packets,simply ack last seq\n");
printf(" 3:simulate an almost real seq/ack procedure(default)\n");
printf(" 4:similiar to 3,but do not consider TCP Option Window_Scale,\n");
printf(" maybe useful when firewall doesnt support TCP Option \n");
// printf("\n");
printf(" --lower-level <string> send packets at OSI level 2, format:'if_name#dest_mac_adress'\n");
printf(" ie:'eth0#00:23:45:67:89:b9'.or try '--lower-level auto' to obtain\n");
printf(" the parameter automatically,specify it manually if 'auto' failed\n");
printf(" --wait-lock wait for xtables lock while invoking iptables, need iptables v1.4.20+\n");
printf(" --gen-add generate iptables rule and add it permanently,then exit.overrides -g\n");
printf(" --keep-rule monitor iptables and auto re-add if necessary.implys -a\n");
printf(" --hb-len <number> length of heart-beat packet, >=0 and <=1500\n");
printf(" --mtu-warn <number> mtu warning threshold, unit:byte, default:1375\n");
printf(" --clear clear any iptables rules added by this program.overrides everything\n");
printf(" --retry-on-error retry on error, allow to start udp2raw before network is initialized\n");
printf(" -h,--help print this help message\n");
//printf("common options,these options must be same on both side\n");
}
int load_config(char *file_name, int &argc, vector<string> &argv) //load conf file and append to argv
{
// Load configurations from config_file instead of the command line.
// See config.example for example configurations
std::ifstream conf_file(file_name);
std::string line;
if(conf_file.fail())
{
mylog(log_fatal,"conf_file %s open failed,reason :%s\n",file_name,get_sock_error());
myexit(-1);
}
while(std::getline(conf_file,line))
{
auto res=parse_conf_line(line);
argc+=res.size();
for(int i=0;i<(int)res.size();i++)
{
argv.push_back(res[i]);
}
}
conf_file.close();
return 0;
}
int process_log_level(int argc,char *argv[])//process --log-level and --disable-cloer --log-postion options
{
int i,j,k;
for (i = 0; i < argc; i++)
{
if(strcmp(argv[i],"--log-level")==0)
{
if(i<argc -1)
{
sscanf(argv[i+1],"%d",&log_level);
if(0<=log_level&&log_level<log_end)
{
}
else
{
log_bare(log_fatal,"invalid log_level\n");
myexit(-1);
}
}
}
if(strcmp(argv[i],"--enable-color")==0)
{
enable_log_color=1;
}
if(strcmp(argv[i],"--disable-color")==0)
{
enable_log_color=0;
}
if(strcmp(argv[i],"--log-position")==0)
{
enable_log_position=1;
}
}
return 0;
}
void process_arg(int argc, char *argv[]) //process all options
{
int i,j,k,opt;
int option_index = 0;
char options[]="l:r:schk:ag";
static struct option long_options[] =
{
/* These options set a flag. */
{"source-ip", required_argument, 0, 1},
{"source-port", required_argument, 0, 1},
{"log-level", required_argument, 0, 1},
{"key", required_argument, 0, 'k'},
{"auth-mode", required_argument, 0, 1},
{"cipher-mode", required_argument, 0, 1},
{"raw-mode", required_argument, 0, 1},
{"disable-color", no_argument, 0, 1},
{"enable-color", no_argument, 0, 1},
{"log-position", no_argument, 0, 1},
{"disable-bpf", no_argument, 0, 1},
{"disable-anti-replay", no_argument, 0, 1},
{"auto-rule", no_argument, 0, 'a'},
{"gen-rule", no_argument, 0, 'g'},
{"gen-add", no_argument, 0, 1},
{"debug", no_argument, 0, 1},
{"retry-on-error", no_argument, 0, 1},
{"clear", no_argument, 0, 1},
{"simple-rule", no_argument, 0, 1},
{"keep-rule", no_argument, 0, 1},
{"lower-level", required_argument, 0, 1},
{"sock-buf", required_argument, 0, 1},
{"seq-mode", required_argument, 0, 1},
{"conf-file", required_argument, 0, 1},
{"force-sock-buf", no_argument, 0, 1},
{"wait-lock", no_argument, 0, 1},
{"random-drop", required_argument, 0, 1},
{"fifo", required_argument, 0, 1},
{"hb-mode", required_argument, 0, 1},
{"hb-len", required_argument, 0, 1},
{"mtu-warn", required_argument, 0, 1},
{"max-rst-to-show", required_argument, 0, 1},
{"max-rst-allowed", required_argument, 0, 1},
{"set-ttl", required_argument, 0, 1},
{"dev", required_argument, 0, 1},
{"dns-resolve", no_argument, 0, 1},
{"easy-tcp", no_argument, 0, 1},
#ifdef UDP2RAW_MP
{"pcap-send", no_argument, 0, 1},
{"no-pcap-mutex", no_argument, 0, 1},
#endif
{"fix-gro", no_argument, 0, 1},
{NULL, 0, 0, 0}
};
process_log_level(argc,argv);
set<string> all_options;
map<string,string> shortcut_map;
all_options.insert("--help");
all_options.insert("-h");
string dummy="";
for(i=0;i<(int)strlen(options);i++)
{
char val=options[i];
if( ( val>='0'&&val<='9') ||( val>='a'&&val<='z')||(val>='A'&&val<='Z'))
{
all_options.insert(dummy+'-'+val);
}
}
for(i=0;i<int( sizeof(long_options)/sizeof(long_options[0]) );i++)
{
if(long_options[i].name==NULL) break;
int val=long_options[i].val;
if( ( val>='0'&&val<='9') ||( val>='a'&&val<='z')||(val>='A'&&val<='Z'))
{
shortcut_map[dummy+"--"+long_options[i].name]= dummy+"-"+ char(val);
}
all_options.insert(dummy+"--"+long_options[i].name);
}
for (i = 0; i < argc; i++)
{
int len=strlen(argv[i]);
if(len==0)
{
mylog(log_fatal,"found an empty string in options\n");
myexit(-1);
}
if(len==1&&argv[i][0]=='-' )
{
mylog(log_fatal,"invaild option '-' in argv\n");
myexit(-1);
}
if(len==2&&argv[i][0]=='-'&&argv[i][1]=='-' )
{
mylog(log_fatal,"invaild option '--' in argv\n");
myexit(-1);
}
}
mylog(log_info,"argc=%d ", argc);
for (i = 0; i < argc; i++) {
log_bare(log_info, "%s ", argv[i]);
}
log_bare(log_info, "\n");
//string dummy="";
for(i=+1;i<argc;i++)
{
if(argv[i][0]!='-') continue;
string a=argv[i];
if(a[0]=='-'&&a[1]!='-')
a=dummy+a[0]+a[1];
if(all_options.find(a.c_str())==all_options.end())
{
mylog(log_fatal,"invaild option %s\n",a.c_str());
myexit(-1);
}
for(j=i+1;j<argc;j++)
{
if(argv[j][0]!='-') continue;
string b=argv[j];
if(b[0]=='-'&&b[1]!='-')
b=dummy+b[0]+b[1];
if(shortcut_map.find(a)!=shortcut_map.end())
a=shortcut_map[a];
if(shortcut_map.find(b)!=shortcut_map.end())
b=shortcut_map[b];
if(a==b)
{
mylog(log_fatal,"%s duplicates with %s\n",argv[i],argv[j]);
myexit(-1);
}
}
}
int no_l = 1, no_r = 1;
while ((opt = getopt_long(argc, argv,options,long_options,&option_index)) != -1) {
//string opt_key;
//opt_key+=opt;
switch (opt) {
case 'l':
no_l = 0;
local_addr.from_str(optarg);
if(local_addr.get_port()==22)
{
mylog(log_fatal,"port 22 not allowed\n");
myexit(-1);
}
/*
if (strchr(optarg, ':') != 0) {
sscanf(optarg, "%[^:]:%d", local_ip, &local_port);
if(local_port==22)
{
mylog(log_fatal,"port 22 not allowed\n");
myexit(-1);
}
} else {
mylog(log_fatal,"invalid parameter for -l ,%s,should be ip:port\n",optarg);
myexit(-1);
}*/
break;
case 'r':
no_r = 0;
remote_addr.from_str(optarg);
if(remote_addr.get_port()==22)
{
mylog(log_fatal,"port 22 not allowed\n");
myexit(-1);
}
/*
if (strchr(optarg, ':') != 0) {
sscanf(optarg, "%[^:]:%d", remote_address, &remote_port);
if(remote_port==22)
{
mylog(log_fatal,"port 22 not allowed\n");
myexit(-1);
}
} else {
mylog(log_fatal,"invalid parameter for -r ,%s,should be ip:port\n",optarg);
myexit(-1);
}*/
break;
case 's':
if(program_mode==0)
{
program_mode=server_mode;
}
else
{
mylog(log_fatal,"-s /-c has already been set,conflict\n");
myexit(-1);
}
break;
case 'c':
if(program_mode==0)
{
program_mode=client_mode;
}
else
{
mylog(log_fatal,"-s /-c has already been set,conflict\n");
myexit(-1);
}
break;
case 'h':
break;
case 'a':
if(is_udp2raw_mp)
{
mylog(log_fatal,"-a not supported in this version, check -g or --raw-mode easyfaketcp\n");
myexit(-1);
}
auto_add_iptables_rule=1;
break;
case 'g':
generate_iptables_rule=1;
break;
case 'k':
mylog(log_debug,"parsing key option\n");
sscanf(optarg,"%s",key_string);
break;
case 1:
mylog(log_debug,"option_index: %d\n",option_index);
if(strcmp(long_options[option_index].name,"clear")==0)
{
if(is_udp2raw_mp)
{
mylog(log_fatal,"--clear not supported in this version\n");
myexit(-1);
}
clear_iptables=1;
}
else if(strcmp(long_options[option_index].name,"source-ip")==0)
{
mylog(log_debug,"parsing long option :source-ip\n");
//sscanf(optarg, "%s", source_ip);
source_addr.from_str_ip_only(optarg);
mylog(log_debug,"source: %s\n",source_addr.get_ip());
force_source_ip=1;
}
else if(strcmp(long_options[option_index].name,"source-port")==0)
{
mylog(log_debug,"parsing long option :source-port\n");
sscanf(optarg, "%d", &source_port);
mylog(log_info,"source: %d\n",source_port);
force_source_port=1;
}
else if(strcmp(long_options[option_index].name,"raw-mode")==0)
{
/*
for(i=0;i<mode_end;i++)
{
if(strcmp(optarg,raw_mode_tostring[i])==0)
{
//printf("%d i\n",i);
//printf("%s",raw_mode_tostring[i]);
raw_mode=(raw_mode_t)i;
break;
}
}
if(i==mode_end)
{
mylog(log_fatal,"no such raw_mode %s\n",optarg);
myexit(-1);
}
*/
if(strcmp(optarg,"easyfaketcp")==0||strcmp(optarg,"easy_faketcp")==0||strcmp(optarg,"easy-faketcp")==0)
{
raw_mode=mode_faketcp;
use_tcp_dummy_socket=1;
}
else
{
for(i=0;i<mode_end;i++)
{
if(strcmp(optarg,raw_mode_tostring[i])==0)
{
//printf("%d i\n",i);
//printf("%s",raw_mode_tostring[i]);
raw_mode=(raw_mode_t)i;
break;
}
}
if(i==mode_end)
{
mylog(log_fatal,"no such raw_mode %s\n",optarg);
myexit(-1);
}
}
}
else if(strcmp(long_options[option_index].name,"auth-mode")==0)
{
for(i=0;i<auth_end;i++)
{
if(strcmp(optarg,auth_mode_tostring[i])==0)
{
auth_mode=(auth_mode_t)i;
if(auth_mode==auth_none)
{
disable_anti_replay=1;
}
break;
}
}
if(i==auth_end)
{
mylog(log_fatal,"no such auth_mode %s\n",optarg);
myexit(-1);
}
}
else if(strcmp(long_options[option_index].name,"cipher-mode")==0)
{
string s=optarg;
if(s=="aes128cfb_0")
{
s="aes128cfb";
aes128cfb_old=1;
mylog(log_warn,"aes128cfb_0 is used\n");
}
for(i=0;i<cipher_end;i++)
{
if(strcmp(s.c_str(),cipher_mode_tostring[i])==0)
{
cipher_mode=(cipher_mode_t)i;
break;
}
}
if(i==cipher_end)
{
mylog(log_fatal,"no such cipher_mode %s\n",optarg);
myexit(-1);
}
}
else if(strcmp(long_options[option_index].name,"log-level")==0)
{
}
else if(strcmp(long_options[option_index].name,"lower-level")==0)
{
if(is_udp2raw_mp)
{
mylog(log_fatal,"--lower-level not supported in this version\n");
myexit(-1);
}
#ifdef UDP2RAW_LINUX
process_lower_level_arg();
#endif
//process_lower_level_arg();
//lower_level=1;
//strcpy(lower_level_arg,optarg);
}
else if(strcmp(long_options[option_index].name,"simple-rule")==0)
{
if(is_udp2raw_mp)
{
mylog(log_fatal,"--simple-rule not supported in this version\n");
myexit(-1);
}
simple_rule=1;
}
else if(strcmp(long_options[option_index].name,"keep-rule")==0)
{
if(is_udp2raw_mp)
{
mylog(log_fatal,"--keep-rule not supported in this version\n");
myexit(-1);
}
keep_rule=1;
}
else if(strcmp(long_options[option_index].name,"gen-add")==0)
{
if(is_udp2raw_mp)
{
mylog(log_fatal,"--gen-add not supported in this version\n");
myexit(-1);
}
generate_iptables_rule_add=1;
}
else if(strcmp(long_options[option_index].name,"disable-color")==0)
{
//enable_log_color=0;
}
else if(strcmp(long_options[option_index].name,"enable-color")==0)
{
//enable_log_color=0;
}
else if(strcmp(long_options[option_index].name,"debug")==0)
{
debug_flag=1;
//enable_log_color=0;
}
else if(strcmp(long_options[option_index].name,"dev")==0)
{
sscanf(optarg,"%s",dev);
//enable_log_color=0;
mylog(log_info,"dev=[%s]\n",dev);
}
else if(strcmp(long_options[option_index].name,"debug-resend")==0)
{
//debug_resend=1;
//enable_log_color=0;
}
else if(strcmp(long_options[option_index].name,"log-position")==0)
{
//enable_log_position=1;
}
else if(strcmp(long_options[option_index].name,"force-sock-buf")==0)
{
if(is_udp2raw_mp)
{
mylog(log_fatal,"--force-sock-buf not supported in this version\n");
myexit(-1);
}
force_socket_buf=1;
}
else if(strcmp(long_options[option_index].name,"retry-on-error")==0)
{
retry_on_error=1;
}
else if(strcmp(long_options[option_index].name,"wait-lock")==0)
{
wait_xtables_lock=1;
}
else if(strcmp(long_options[option_index].name,"disable-bpf")==0)
{
disable_bpf_filter=1;
}
else if(strcmp(long_options[option_index].name,"disable-anti-replay")==0)
{
disable_anti_replay=1;
}
else if(strcmp(long_options[option_index].name,"sock-buf")==0)
{
int tmp=-1;
sscanf(optarg,"%d",&tmp);
if(10<=tmp&&tmp<=10*1024)
{
socket_buf_size=tmp*1024;
}
else
{
mylog(log_fatal,"sock-buf value must be between 1 and 10240 (kbyte) \n");
myexit(-1);
}
}
else if(strcmp(long_options[option_index].name,"seq-mode")==0)
{
sscanf(optarg,"%d",&seq_mode);
if(0<=seq_mode&&seq_mode<=max_seq_mode)
{
}
else
{
mylog(log_fatal,"seq_mode value must be 0,1,or 2 \n");
myexit(-1);
}
}
else if(strcmp(long_options[option_index].name,"random-drop")==0)
{
sscanf(optarg,"%d",&random_drop);
if(random_drop<0||random_drop>10000)
{
mylog(log_fatal,"random_drop must be between 0 10000 \n");
myexit(-1);
}
mylog(log_info,"random_drop =%d \n",random_drop);
}
else if(strcmp(long_options[option_index].name,"fifo")==0)
{
if(is_udp2raw_mp)
{
mylog(log_fatal,"--fifo not supported in this version\n");
myexit(-1);
}
sscanf(optarg,"%s",fifo_file);
mylog(log_info,"fifo_file =%s \n",fifo_file);
}
else if(strcmp(long_options[option_index].name,"conf-file")==0)
{
mylog(log_info,"configuration loaded from %s\n",optarg);
}
else if(strcmp(long_options[option_index].name,"hb-mode")==0)
{
sscanf(optarg,"%d",&hb_mode);
assert(hb_mode==0||hb_mode==1);
mylog(log_info,"hb_mode =%d \n",hb_mode);
}
else if(strcmp(long_options[option_index].name,"hb-len")==0)
{
sscanf(optarg,"%d",&hb_len);
assert(hb_len>=0&&hb_len<=1500);
mylog(log_info,"hb_len =%d \n",hb_len);
}
else if(strcmp(long_options[option_index].name,"mtu-warn")==0)
{
sscanf(optarg,"%d",&mtu_warn);
assert(mtu_warn>0);
mylog(log_info,"mtu_warn=%d \n",mtu_warn);
}
else if(strcmp(long_options[option_index].name,"max-rst-to-show")==0)
{
sscanf(optarg,"%d",&max_rst_to_show);
assert(max_rst_to_show>=-1);
mylog(log_info,"max_rst_to_show=%d \n",max_rst_to_show);
}
else if(strcmp(long_options[option_index].name,"max-rst-allowed")==0)
{
sscanf(optarg,"%d",&max_rst_allowed);
assert(max_rst_allowed>=-1);
mylog(log_info,"max_rst_allowed=%d \n",max_rst_allowed);
}
else if(strcmp(long_options[option_index].name,"set-ttl")==0)
{
sscanf(optarg,"%d",&ttl_value);
assert(ttl_value>=0&&ttl_value<=255);
mylog(log_info,"ttl_value=%d\n",ttl_value);
}
else if(strcmp(long_options[option_index].name,"dns-resolve")==0) // currently not used
{
enable_dns_resolve=1;
mylog(log_info,"dns-resolve enabled\n");
}
#ifdef UDP2RAW_MP
else if(strcmp(long_options[option_index].name,"pcap-send")==0)
{
send_with_pcap=1;
mylog(log_info,"--pcap-send enabled, now pcap will be used for sending packet instead of libnet\n");
}
else if(strcmp(long_options[option_index].name,"no-pcap-mutex")==0)
{
use_pcap_mutex=0;
mylog(log_warn,"--no-pcap-mutex enabled, we will assume the underlying pcap calls are threadsafe\n");
}
#endif
else if(strcmp(long_options[option_index].name,"easy-tcp")==0)
{
use_tcp_dummy_socket=1;
mylog(log_info,"--easy-tcp enabled, now a dummy tcp socket will be created for handshake and block rst\n");
}
else if(strcmp(long_options[option_index].name,"fix-gro")==0)
{
mylog(log_info,"--fix-gro enabled\n");
g_fix_gro=1;
}
else
{
mylog(log_warn,"ignored unknown long option ,option_index:%d code:<%x>\n",option_index, optopt);
}
break;
default:
mylog(log_fatal,"unknown option ,code:<%c>,<%x>\n",optopt, optopt);
myexit(-1);
}
}
if (no_l)
mylog(log_fatal,"error: -l not found\n");
if (no_r)
mylog(log_fatal,"error: -r not found\n");
if(program_mode==0)
mylog(log_fatal,"error: -c /-s hasnt been set\n");
if (no_l || no_r||program_mode==0)
{
print_help();
myexit(-1);
}
if(program_mode==client_mode)
{
raw_ip_version=remote_addr.get_type();
}
else
{
raw_ip_version=local_addr.get_type();
}
if(auto_add_iptables_rule&& use_tcp_dummy_socket)
{
mylog(log_error,"-a,--auto-rule is not supposed to be used with easyfaketcp mode, you are likely making a mistake, but we can try to continue\n");
}
if(keep_rule&& use_tcp_dummy_socket)
{
mylog(log_error,"--keep-rule is not supposed to be used with easyfaketcp mode, you are likely making a mistake, but we can try to continue\n");
}
mylog(log_info,"important variables: ");
log_bare(log_info,"log_level=%d:%s ",log_level,log_text[log_level]);
log_bare(log_info,"raw_mode=%s ",raw_mode_tostring[raw_mode]);
log_bare(log_info,"cipher_mode=%s ",cipher_mode_tostring[cipher_mode]);
log_bare(log_info,"auth_mode=%s ",auth_mode_tostring[auth_mode]);
log_bare(log_info,"key=%s ",key_string);
log_bare(log_info,"local_addr=%s ",local_addr.get_str());
log_bare(log_info,"remote_addr=%s ",remote_addr.get_str());
if(force_source_ip)
log_bare(log_info,"source_addr=%s ",source_addr.get_ip());
if(force_source_port)
log_bare(log_info,"source_port=%d ",source_port);
log_bare(log_info,"socket_buf_size=%d ",socket_buf_size);
log_bare(log_info,"\n");
}
void pre_process_arg(int argc, char *argv[])//mainly for load conf file
{
int i,j,k;
for (i = 0; i < argc; i++)
{
if(strcmp(argv[i],"--unit-test")==0)
{
unit_test();
myexit(0);
}
}
for (i = 0; i < argc; i++)
{
if(strcmp(argv[i],"-h")==0||strcmp(argv[i],"--help")==0)
{
print_help();
myexit(0);
}
}
if (argc == 1)
{
print_help();
myexit(-1);
}
process_log_level(argc,argv);
int new_argc=0;
vector<string> new_argv;
int count=0;
int pos=-1;
for (i = 0; i < argc; i++)
{
if(strcmp(argv[i],"--conf-file")==0)
{
count++;
pos=i;
if(i==argc)
{
mylog(log_fatal,"--conf-file need a parameter\n");
myexit(-1);
}
if(argv[i+1][0]=='-')
{
mylog(log_fatal,"--conf-file need a parameter\n");
myexit(-1);
}
i++;
}
else
{
//printf("<%s>",argv[i]);
new_argc++;
new_argv.push_back(argv[i]);
}
}
if(count>1)
{
mylog(log_fatal,"duplicated --conf-file option\n");
myexit(-1);
}
if(count>0)
{
load_config(argv[pos+1],new_argc,new_argv);
}
char* new_argv_char[new_argv.size()];
new_argc=0;
for(i=0;i<(int)new_argv.size();i++)
{
if(strcmp(new_argv[i].c_str(),"--conf-file")==0)
{
mylog(log_fatal,"cant have --conf-file in a config file\n");
myexit(-1);
}
new_argv_char[new_argc++]=(char *)new_argv[i].c_str();
}
process_arg(new_argc,new_argv_char);
}
#ifdef UDP2RAW_LINUX
void *run_keep(void *none) //called in a new thread for --keep-rule option
{
while(1)
{
sleep(iptables_rule_keep_interval);
keep_iptables_rule();
if(about_to_exit) //just incase it runs forever if there is some bug,not necessary
{
sleep(10);
keep_thread_running=0; //not thread safe ,but wont cause problem
break;
}
}
return NULL;
}
void iptables_rule() // handles -a -g --gen-add --keep-rule --clear --wait-lock
{
assert(raw_ip_version==AF_INET||raw_ip_version==AF_INET6);
if(raw_ip_version==AF_INET)
{
iptables_command0="iptables ";
}
else
iptables_command0="ip6tables ";
if(!wait_xtables_lock)
{
iptables_command=iptables_command0;
}
else
{
iptables_command=iptables_command0+"-w ";
}
if(clear_iptables)
{
char *output;
//int ret =system("iptables-save |grep udp2raw_dWRwMnJhdw|sed -n 's/^-A/iptables -D/p'|sh");
int ret =run_command(iptables_command+"-S|sed -n '/udp2rawDwrW/p'|sed -n 's/^-A/"+iptables_command+"-D/p'|sh",output);
int ret2 =run_command(iptables_command+"-S|sed -n '/udp2rawDwrW/p'|sed -n 's/^-N/"+iptables_command+"-X/p'|sh",output);
//system("iptables-save |grep udp2raw_dWRwMnJhdw|sed 's/^-A/iptables -D/'|sh");
//system("iptables-save|grep -v udp2raw_dWRwMnJhdw|iptables-restore");
mylog(log_info,"tried to clear all iptables rule created previously,return value %d %d\n",ret,ret2);
myexit(-1);
}
if(auto_add_iptables_rule&&generate_iptables_rule)
{
mylog(log_warn," -g overrides -a\n");
auto_add_iptables_rule=0;
//myexit(-1);
}
if(generate_iptables_rule_add&&generate_iptables_rule)
{
mylog(log_warn," --gen-add overrides -g\n");
generate_iptables_rule=0;
//myexit(-1);
}
if(keep_rule&&auto_add_iptables_rule==0)
{
auto_add_iptables_rule=1;
mylog(log_warn," --keep_rule implys -a\n");
generate_iptables_rule=0;
//myexit(-1);
}
char tmp_pattern[200];
string pattern="";
if(program_mode==client_mode)
{
tmp_pattern[0]=0;
if(raw_mode==mode_faketcp)
{
sprintf(tmp_pattern,"-s %s -p tcp -m tcp --sport %d",remote_addr.get_ip(),remote_addr.get_port());
}
if(raw_mode==mode_udp)
{
sprintf(tmp_pattern,"-s %s -p udp -m udp --sport %d",remote_addr.get_ip(),remote_addr.get_port());
}
if(raw_mode==mode_icmp)
{
if(raw_ip_version==AF_INET)
sprintf(tmp_pattern,"-s %s -p icmp --icmp-type 0",remote_addr.get_ip());
else
sprintf(tmp_pattern,"-s %s -p icmpv6 --icmpv6-type 129",remote_addr.get_ip());
}
pattern+=tmp_pattern;
}
if(program_mode==server_mode)
{
tmp_pattern[0]=0;
if(raw_ip_version==AF_INET)
{
if(local_addr.inner.ipv4.sin_addr.s_addr!=0)
{
sprintf(tmp_pattern,"-d %s ",local_addr.get_ip());
}
}
else
{
char zero_arr[16]={0};
if(memcmp(&local_addr.inner.ipv6.sin6_addr,zero_arr,16)!=0)
{
sprintf(tmp_pattern,"-d %s ",local_addr.get_ip());
}
}
pattern+=tmp_pattern;
tmp_pattern[0]=0;
if(raw_mode==mode_faketcp)
{
sprintf(tmp_pattern,"-p tcp -m tcp --dport %d",local_addr.get_port());
}
if(raw_mode==mode_udp)
{
sprintf(tmp_pattern,"-p udp -m udp --dport %d",local_addr.get_port());
}
if(raw_mode==mode_icmp)
{
if(raw_ip_version==AF_INET)
sprintf(tmp_pattern,"-p icmp --icmp-type 8");
else
sprintf(tmp_pattern,"-p icmpv6 --icmpv6-type 128");
}
pattern+=tmp_pattern;
}
/*
if(!simple_rule)
{
pattern += " -m comment --comment udp2rawDwrW_";
char const_id_str[100];
sprintf(const_id_str, "%x_", const_id);
pattern += const_id_str;
time_t timer;
char buffer[26];
struct tm* tm_info;
time(&timer);
tm_info = localtime(&timer);
strftime(buffer, 26, "%Y-%m-%d-%H:%M:%S", tm_info);
pattern += buffer;
}*/
if(generate_iptables_rule)
{
string rule=iptables_command+"-I INPUT ";
rule+=pattern;
rule+=" -j DROP";
printf("generated iptables rule:\n");
printf("%s\n",rule.c_str());
myexit(0);
}
if(generate_iptables_rule_add)
{
iptables_gen_add(pattern.c_str(),const_id);
myexit(0);
}
if(auto_add_iptables_rule)
{
iptables_rule_init(pattern.c_str(),const_id,keep_rule);
if(keep_rule)
{
if(pthread_create(&keep_thread, NULL, run_keep, 0)) {
mylog(log_fatal, "Error creating thread\n");
myexit(-1);
}
keep_thread_running=1;
}
}
else
{
mylog(log_warn," -a has not been set, make sure you have added the needed iptables rules manually\n");
}
}
#endif
int unit_test()
{
printf("running unit test\n");
vector<string> conf_lines= {"---aaa","--aaa bbb","-a bbb"," \t \t \t-a\t \t \t bbbbb\t \t \t "};
for(int i=0;i<int(conf_lines.size());i++)
{
printf("orign:%s\n",conf_lines[i].c_str());
auto res=parse_conf_line(conf_lines[i]);
printf("pasrse_result: size %d",int(res.size()));
for(int j=0;j<int(res.size());j++)
{
printf("<%s>",res[j].c_str());
}
printf("\n");
}
char s1[]={1,2,3,4,5};
char s2[]={1};
short c1=csum((unsigned short*)s1,5);
short c2=csum((unsigned short*)s2,1);
//c2=0;
printf("%x %x\n",(int)c1,(int)c2);
const char buf[]={1,2,3,4,5,6,7,8,9,10,11,2,13,14,15,16};
char key[100]={0};
char buf2[100]={0};
char buf3[100]={0};
char buf4[100]={0};
int len=16;
for(int i=0;i<len;i++)
{
printf("<%d>",buf[i]);
}
printf("\n");
cipher_encrypt(buf,buf2,len,key);
for(int i=0;i<len;i++)
{
printf("<%d>",buf2[i]);
}
printf("\n");
int temp_len=len;
cipher_decrypt(buf2,buf3,len,key);
for(int i=0;i<len;i++)
{
printf("<%d>",buf3[i]);
}
printf("\n");
cipher_encrypt(buf2,buf4,temp_len,key);
for(int i=0;i<temp_len;i++)
{
printf("<%d>",buf4[i]);
}
return 0;
}
#ifdef UDP2RAW_LINUX
int set_timer(int epollfd,int &timer_fd)//put a timer_fd into epoll,general function,used both in client and server
{
int ret;
epoll_event ev;
itimerspec its;
memset(&its,0,sizeof(its));
if((timer_fd=timerfd_create(CLOCK_MONOTONIC,TFD_NONBLOCK)) < 0)
{
mylog(log_fatal,"timer_fd create error\n");
myexit(1);
}
its.it_interval.tv_sec=(timer_interval/1000);
its.it_interval.tv_nsec=(timer_interval%1000)*1000ll*1000ll;
its.it_value.tv_nsec=1; //imidiately
timerfd_settime(timer_fd,0,&its,0);
ev.events = EPOLLIN;
ev.data.u64 = timer_fd;
ret=epoll_ctl(epollfd, EPOLL_CTL_ADD, timer_fd, &ev);
if (ret < 0) {
mylog(log_fatal,"epoll_ctl return %d\n", ret);
myexit(-1);
}
return 0;
}
int set_timer_server(int epollfd,int &timer_fd,fd64_t &fd64)//only for server
{
int ret;
epoll_event ev;
itimerspec its;
memset(&its,0,sizeof(its));
if((timer_fd=timerfd_create(CLOCK_MONOTONIC,TFD_NONBLOCK)) < 0)
{
mylog(log_fatal,"timer_fd create error\n");
myexit(1);
}
its.it_interval.tv_sec=(timer_interval/1000);
its.it_interval.tv_nsec=(timer_interval%1000)*1000ll*1000ll;
its.it_value.tv_nsec=1; //imidiately
timerfd_settime(timer_fd,0,&its,0);
fd64=fd_manager.create(timer_fd);
ev.events = EPOLLIN;
ev.data.u64 = fd64;////difference
ret=epoll_ctl(epollfd, EPOLL_CTL_ADD, timer_fd, &ev);
if (ret < 0) {
mylog(log_fatal,"epoll_ctl return %d\n", ret);
myexit(-1);
}
return 0;
}
int handle_lower_level(raw_info_t &raw_info)//fill lower_level info,when --lower-level is enabled,only for server
{
packet_info_t &send_info=raw_info.send_info;
packet_info_t &recv_info=raw_info.recv_info;
if(lower_level_manual)
{
memset(&send_info.addr_ll,0,sizeof(send_info.addr_ll));
send_info.addr_ll.sll_family=AF_PACKET;
send_info.addr_ll.sll_ifindex=ifindex;
send_info.addr_ll.sll_halen=ETHER_ADDR_LEN;
send_info.addr_ll.sll_protocol=htons(ETH_P_IP);
memcpy(&send_info.addr_ll.sll_addr,dest_hw_addr,ETHER_ADDR_LEN);
mylog(log_debug,"[manual]lower level info %x %x\n ",send_info.addr_ll.sll_halen,send_info.addr_ll.sll_protocol);
}
else
{
memset(&send_info.addr_ll,0,sizeof(send_info.addr_ll));
send_info.addr_ll.sll_family=recv_info.addr_ll.sll_family;
send_info.addr_ll.sll_ifindex=recv_info.addr_ll.sll_ifindex;
send_info.addr_ll.sll_protocol=recv_info.addr_ll.sll_protocol;
send_info.addr_ll.sll_halen=recv_info.addr_ll.sll_halen;
memcpy(send_info.addr_ll.sll_addr,recv_info.addr_ll.sll_addr,sizeof(send_info.addr_ll.sll_addr));
//other bytes should be kept zero.
mylog(log_debug,"[auto]lower level info %x %x\n ",send_info.addr_ll.sll_halen,send_info.addr_ll.sll_protocol);
}
return 0;
}
string chain[2];
string rule_keep[2];
string rule_keep_add[2];
string rule_keep_del[2];
u64_t keep_rule_last_time=0;
pthread_t keep_thread;
int keep_thread_running=0;
int iptables_gen_add(const char * s,u32_t const_id)
{
string dummy="";
iptables_pattern=s;
chain[0] =dummy+ "udp2rawDwrW_C";
rule_keep[0]=dummy+ iptables_pattern+" -j " +chain[0];
rule_keep_add[0]=iptables_command+"-I INPUT "+rule_keep[0];
char *output;
run_command(iptables_command+"-N "+chain[0],output,show_none);
run_command(iptables_command+"-F "+chain[0],output);
run_command(iptables_command+"-I "+chain[0] + " -j DROP",output);
rule_keep_del[0]=iptables_command+"-D INPUT "+rule_keep[0];
run_command(rule_keep_del[0],output,show_none);
run_command(rule_keep_del[0],output,show_none);
if(run_command(rule_keep_add[0],output)!=0)
{
mylog(log_fatal,"auto added iptables failed by: %s\n",rule_keep_add[0].c_str());
myexit(-1);
}
return 0;
}
int iptables_rule_init(const char * s,u32_t const_id,int keep)
{
iptables_pattern=s;
iptables_rule_added=1;
iptables_rule_keeped=keep;
string dummy="";
char const_id_str[100];
sprintf(const_id_str, "%x", const_id);
chain[0] =dummy+ "udp2rawDwrW_"+const_id_str+"_C0";
chain[1] =dummy+ "udp2rawDwrW_"+const_id_str+"_C1";
rule_keep[0]=dummy+ iptables_pattern+" -j " +chain[0];
rule_keep[1]=dummy+ iptables_pattern+" -j " +chain[1];
rule_keep_add[0]=iptables_command+"-I INPUT "+rule_keep[0];
rule_keep_add[1]=iptables_command+"-I INPUT "+rule_keep[1];
rule_keep_del[0]=iptables_command+"-D INPUT "+rule_keep[0];
rule_keep_del[1]=iptables_command+"-D INPUT "+rule_keep[1];
keep_rule_last_time=get_current_time();
char *output;
for(int i=0;i<=iptables_rule_keeped;i++)
{
run_command(iptables_command+"-N "+chain[i],output);
run_command(iptables_command+"-F "+chain[i],output);
run_command(iptables_command+"-I "+chain[i] + " -j DROP",output);
if(run_command(rule_keep_add[i],output)!=0)
{
mylog(log_fatal,"auto added iptables failed by: %s\n",rule_keep_add[i].c_str());
myexit(-1);
}
}
mylog(log_warn,"auto added iptables rules\n");
return 0;
}
int keep_iptables_rule() //magic to work on a machine without grep/iptables --check/-m commment
{
/*
if(iptables_rule_keeped==0) return 0;
uint64_t tmp_current_time=get_current_time();
if(tmp_current_time-keep_rule_last_time<=iptables_rule_keep_interval)
{
return 0;
}
else
{
keep_rule_last_time=tmp_current_time;
}*/
mylog(log_debug,"keep_iptables_rule begin %llu\n",get_current_time());
iptables_rule_keep_index+=1;
iptables_rule_keep_index%=2;
string dummy="";
char *output;
int i=iptables_rule_keep_index;
run_command(iptables_command + "-N " + chain[i], output,show_none);
if (run_command(iptables_command + "-F " + chain[i], output,show_none) != 0)
mylog(log_warn, "iptables -F failed %d\n",i);
if (run_command(iptables_command + "-I " + chain[i] + " -j DROP",output,show_none) != 0)
mylog(log_warn, "iptables -I failed %d\n",i);
if (run_command(rule_keep_del[i], output,show_none) != 0)
mylog(log_warn, "rule_keep_del failed %d\n",i);
run_command(rule_keep_del[i], output,show_none); //do it twice,incase it fails for unknown random reason
if(run_command(rule_keep_add[i], output,show_log)!=0)
mylog(log_warn, "rule_keep_del failed %d\n",i);
mylog(log_debug,"keep_iptables_rule end %llu\n",get_current_time());
return 0;
}
int clear_iptables_rule()
{
char *output;
string dummy="";
if(!iptables_rule_added) return 0;
for(int i=0;i<=iptables_rule_keeped;i++ )
{
run_command(rule_keep_del[i],output);
run_command(iptables_command+"-F "+chain[i],output);
run_command(iptables_command+"-X "+chain[i],output);
}
return 0;
}
#endif
#ifdef UDP2RAW_MP
void iptables_rule() // handles -a -g --gen-add --keep-rule --clear --wait-lock
{
if(generate_iptables_rule)
{
if(raw_mode==mode_faketcp && use_tcp_dummy_socket==1)
{
mylog(log_fatal, "failed,-g doesnt work with easy-faketcp mode\n");
myexit(-1);
}
if(raw_mode==mode_udp)
{
mylog(log_warn, "It not necessary to use iptables/firewall rule in udp mode\n");
}
log_bare(log_warn,"for linux, use:\n");
if(raw_ip_version==AF_INET)
{
if(raw_mode==mode_faketcp)
printf("iptables -I INPUT -s %s -p tcp -m tcp --sport %d -j DROP\n",remote_addr.get_ip(),remote_addr.get_port());
if(raw_mode==mode_udp)
printf("iptables -I INPUT -s %s -p udp -m udp --sport %d -j DROP\n",remote_addr.get_ip(),remote_addr.get_port());
if(raw_mode==mode_icmp)
printf("iptables -I INPUT -s %s -p icmp --icmp-type 0 -j DROP\n",remote_addr.get_ip());
printf("\n");
}
else
{
assert(raw_ip_version==AF_INET6);
if(raw_mode==mode_faketcp)
printf("ip6tables -I INPUT -s %s -p tcp -m tcp --sport %d -j DROP\n",remote_addr.get_ip(),remote_addr.get_port());
if(raw_mode==mode_udp)
printf("ip6tables -I INPUT -s %s -p udp -m udp --sport %d -j DROP\n",remote_addr.get_ip(),remote_addr.get_port());
if(raw_mode==mode_icmp)
printf("ip6tables -I INPUT -s %s -p -p icmpv6 --icmpv6-type 129 -j DROP\n",remote_addr.get_ip());
printf("\n");
}
log_bare(log_warn,"for mac/bsd use:\n");
if(raw_ip_version==AF_INET)
{
if(raw_mode==mode_faketcp)
printf("echo 'block drop inet proto tcp from %s port %d to any' > ./1.conf\n",remote_addr.get_ip(),remote_addr.get_port());
if(raw_mode==mode_udp)
printf("echo 'block drop inet proto udp from %s port %d to any' > ./1.conf\n",remote_addr.get_ip(),remote_addr.get_port());
if(raw_mode==mode_icmp)
printf("echo 'block drop inet proto icmp from %s to any' > ./1.conf\n",remote_addr.get_ip());
}
else
{
assert(raw_ip_version==AF_INET6);
if(raw_mode==mode_faketcp)
printf("echo 'block drop inet6 proto tcp from %s port %d to any' > ./1.conf\n",remote_addr.get_ip(),remote_addr.get_port());
if(raw_mode==mode_udp)
printf("echo 'block drop inet6 proto udp from %s port %d to any' > ./1.conf\n",remote_addr.get_ip(),remote_addr.get_port());
if(raw_mode==mode_icmp)
printf("echo 'block drop inet6 proto icmp6 from %s to any' > ./1.conf\n",remote_addr.get_ip());
}
printf("pfctl -f ./1.conf\n");
printf("pfctl -e\n");
printf("\n");
log_bare(log_warn,"for windows vista and above use:\n");
if(raw_ip_version==AF_INET)
{
if(raw_mode==mode_faketcp)
{
printf("netsh advfirewall firewall add rule name=udp2raw protocol=TCP dir=in remoteip=%s remoteport=%d action=block\n",remote_addr.get_ip(),remote_addr.get_port());
printf("netsh advfirewall firewall add rule name=udp2raw protocol=TCP dir=out remoteip=%s remoteport=%d action=block\n",remote_addr.get_ip(),remote_addr.get_port());
}
if(raw_mode==mode_udp)
{
printf("netsh advfirewall firewall add rule name=udp2raw protocol=UDP dir=in remoteip=%s remoteport=%d action=block\n",remote_addr.get_ip(),remote_addr.get_port());
printf("netsh advfirewall firewall add rule name=udp2raw protocol=UDP dir=out remoteip=%s remoteport=%d action=block\n",remote_addr.get_ip(),remote_addr.get_port());
}
if(raw_mode==mode_icmp)
{
printf("netsh advfirewall firewall add rule name=udp2raw protocol=ICMPV4 dir=in remoteip=%s action=block\n",remote_addr.get_ip());
printf("netsh advfirewall firewall add rule name=udp2raw protocol=ICMPV4 dir=out remoteip=%s action=block\n",remote_addr.get_ip());
}
}
else
{
assert(raw_ip_version==AF_INET6);
if(raw_mode==mode_faketcp)
{
printf("netsh advfirewall firewall add rule name=udp2raw protocol=TCP dir=in remoteip=%s remoteport=%d action=block\n",remote_addr.get_ip(),remote_addr.get_port());
printf("netsh advfirewall firewall add rule name=udp2raw protocol=TCP dir=out remoteip=%s remoteport=%d action=block\n",remote_addr.get_ip(),remote_addr.get_port());
}
if(raw_mode==mode_udp)
{
printf("netsh advfirewall firewall add rule name=udp2raw protocol=UDP dir=in remoteip=%s remoteport=%d action=block\n",remote_addr.get_ip(),remote_addr.get_port());
printf("netsh advfirewall firewall add rule name=udp2raw protocol=UDP dir=out remoteip=%s remoteport=%d action=block\n",remote_addr.get_ip(),remote_addr.get_port());
}
if(raw_mode==mode_icmp)
{
printf("netsh advfirewall firewall add rule name=udp2raw protocol=ICMPV6 dir=in remoteip=%s action=block\n",remote_addr.get_ip());
printf("netsh advfirewall firewall add rule name=udp2raw protocol=ICMPV6 dir=out remoteip=%s action=block\n",remote_addr.get_ip());
}
}
myexit(0);
}
}
#endif
void signal_handler(int sig)
{
about_to_exit=1;
// myexit(0);
}
| 28.558656 | 169 | 0.641806 | [
"vector"
] |
1067614eaf93bfc0a001cc4695b153960eda575a | 487 | hpp | C++ | pxrun/pxrun/matrix.hpp | lyrahgames/random-number-generators | c78931c1a5c0a85a1ad36d7d8979567b0853be52 | [
"MIT"
] | 4 | 2020-03-28T15:12:07.000Z | 2021-04-20T00:07:23.000Z | pxrun/pxrun/matrix.hpp | lyrahgames/random-number-generators | c78931c1a5c0a85a1ad36d7d8979567b0853be52 | [
"MIT"
] | null | null | null | pxrun/pxrun/matrix.hpp | lyrahgames/random-number-generators | c78931c1a5c0a85a1ad36d7d8979567b0853be52 | [
"MIT"
] | null | null | null | #pragma once
#include <iostream>
#include <string>
#include <vector>
namespace pxrun {
class matrix {
public:
explicit matrix(const std::vector<std::string>& args);
matrix() : matrix{{}} {}
template <typename RNG>
void run(RNG&& rng) const {
for (int i = 0; i < rows; ++i) {
std::cout << rng();
for (int j = 1; j < cols; ++j) std::cout << "\t" << rng();
std::cout << "\n";
}
}
private:
int rows = 10;
int cols = 1;
};
} // namespace pxrun | 17.392857 | 64 | 0.548255 | [
"vector"
] |
1068b31ce7b4360cf06546c62dcb6994ab01134d | 4,328 | cpp | C++ | toonz/sources/toonzfarm/tfarm/tfarmserver_c.cpp | rozhuk-im/opentoonz | ad5b632512746b97fd526aa79660fbaedf934fad | [
"BSD-3-Clause"
] | 3,710 | 2016-03-26T00:40:48.000Z | 2022-03-31T21:35:12.000Z | toonz/sources/toonzfarm/tfarm/tfarmserver_c.cpp | rozhuk-im/opentoonz | ad5b632512746b97fd526aa79660fbaedf934fad | [
"BSD-3-Clause"
] | 4,246 | 2016-03-26T01:21:45.000Z | 2022-03-31T23:10:47.000Z | toonz/sources/toonzfarm/tfarm/tfarmserver_c.cpp | rozhuk-im/opentoonz | ad5b632512746b97fd526aa79660fbaedf934fad | [
"BSD-3-Clause"
] | 633 | 2016-03-26T00:42:25.000Z | 2022-03-17T02:55:13.000Z |
#include "tfarmserver.h"
//#include "ttcpip.h"
#include "tfarmproxy.h"
#include "tconvert.h"
namespace {
//------------------------------------------------------------------------------
class FarmServerProxy final : public TFarmServer, public TFarmProxy {
public:
FarmServerProxy(const QString &hostName, const QString &addr, int port)
: TFarmProxy(hostName, addr, port) {}
// TFarmServer interface implementation
int addTask(const QString &taskid, const QString &cmdline) override;
int terminateTask(const QString &taskid) override;
int getTasks(std::vector<QString> &tasks) override;
void queryHwInfo(HwInfo &hwInfo) override;
void attachController(const QString &name, const QString &addr,
int port) override;
void detachController(const QString &name, const QString &addr,
int port) override;
};
//------------------------------------------------------------------------------
int FarmServerProxy::addTask(const QString &taskid, const QString &cmdline) {
QString data("addTask");
data += ",";
data += taskid;
data += ",";
data += cmdline;
QString reply = sendToStub(data);
if (reply.isEmpty()) return -1;
int rc = reply.toInt();
return rc;
}
//------------------------------------------------------------------------------
int FarmServerProxy::terminateTask(const QString &taskid) {
QString data("terminateTask");
data += ",";
data += taskid;
QString reply = sendToStub(data);
return 0;
}
//------------------------------------------------------------------------------
int FarmServerProxy::getTasks(std::vector<QString> &tasks) {
QString data("getTasks");
QString reply = sendToStub(data);
// la stringa restituita contiene le informazioni desiderate separate da ","
std::vector<QString> argv;
int count = extractArgs(reply, argv);
assert(count > 0);
int taskCount = argv[0].toInt();
tasks.clear();
std::vector<QString>::iterator it = argv.begin();
std::advance(it, 1);
for (; it != argv.end(); ++it) tasks.push_back(*it);
return taskCount;
}
//------------------------------------------------------------------------------
void FarmServerProxy::queryHwInfo(HwInfo &hwInfo) {
QString data("queryHwInfo");
QString reply = sendToStub(data);
// la stringa restituita contiene le informazioni desiderate separate da ","
std::vector<QString> argv;
extractArgs(reply, argv);
assert(argv.size() > 4);
int cpuCount, totPhysMem, totVirtMem, availPhysMem, availVirtMem;
cpuCount = argv[0].toInt();
totPhysMem = argv[1].toInt();
availPhysMem = argv[2].toInt();
totVirtMem = argv[3].toInt();
availVirtMem = argv[4].toInt();
hwInfo.m_cpuCount = cpuCount;
hwInfo.m_totPhysMem = totPhysMem;
hwInfo.m_totVirtMem = totVirtMem;
hwInfo.m_availPhysMem = availPhysMem;
hwInfo.m_availVirtMem = availVirtMem;
if (argv.size() > 5) hwInfo.m_type = (TFarmPlatform)argv[5].toInt();
}
//------------------------------------------------------------------------------
void FarmServerProxy::attachController(const QString &name, const QString &addr,
int port) {
QString data("attachController");
data += ",";
data += name;
data += ",";
data += addr;
data += ",";
data += QString::number(port);
sendToStub(data);
}
//------------------------------------------------------------------------------
void FarmServerProxy::detachController(const QString &name, const QString &addr,
int port) {
QString data("detachController");
data += ",";
data += name;
data += ",";
data += addr;
data += ",";
data += QString::number(port);
QString reply = sendToStub(data);
}
} // anonymous namespace
//==============================================================================
TFarmServerFactory::TFarmServerFactory() {}
//------------------------------------------------------------------------------
TFarmServerFactory::~TFarmServerFactory() {}
//------------------------------------------------------------------------------
int TFarmServerFactory::create(const QString &hostName, const QString &addr,
int port, TFarmServer **tfserver) {
*tfserver = new FarmServerProxy(hostName, addr, port);
return 0;
}
| 28.287582 | 80 | 0.536506 | [
"vector"
] |
106adb94f8d4b9a4da75b5e3f31b7baef0ca6298 | 44,258 | cpp | C++ | Projects/krkr2_on_VC/kirikiri2/src/core/tjs2/tjsLex.cpp | CATION-M/X-moe | 2bac3bb45ff21e50921aac8422f2e00839f546e5 | [
"MIT"
] | 2 | 2020-02-25T15:18:53.000Z | 2020-08-24T13:30:34.000Z | Projects/krkr2_on_VC/kirikiri2/src/core/tjs2/tjsLex.cpp | CATION-M/X-moe | 2bac3bb45ff21e50921aac8422f2e00839f546e5 | [
"MIT"
] | null | null | null | Projects/krkr2_on_VC/kirikiri2/src/core/tjs2/tjsLex.cpp | CATION-M/X-moe | 2bac3bb45ff21e50921aac8422f2e00839f546e5 | [
"MIT"
] | 1 | 2019-11-25T05:29:30.000Z | 2019-11-25T05:29:30.000Z | //---------------------------------------------------------------------------
/*
TJS2 Script Engine
Copyright (C) 2000-2007 W.Dee <dee@kikyou.info> and contributors
See details of license at "license.txt"
*/
//---------------------------------------------------------------------------
// TJS2 lexical analyzer
//---------------------------------------------------------------------------
#include "tjsCommHead.h"
#include <math.h>
#include "tjsInterCodeGen.h"
#include "tjs.tab.h"
#include "tjsLex.h"
#include "tjsVariant.h"
#include "tjsError.h"
#include "tjsCompileControl.h"
#include "tjsScriptBlock.h"
#include "tjsObject.h"
#include "tjsMath.h"
namespace TJS
{
tjs_nchar tjsEnableDicFuncQuickHack_mark[] = " - 0 <- Put '1' to enable dicfunc quick-hack - ";
bool tjsEnableDicFuncQuickHack = tjsEnableDicFuncQuickHack_mark[3] != '0';
//----- dicfunc quick-hack
//---------------------------------------------------------------------------
const tjs_char TJS_SKIP_CODE = (tjs_char)~((tjs_char)0);
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// TJS_iswspace or etc. ( these functions do not collate )
//---------------------------------------------------------------------------
static bool inline TJS_iswspace(tjs_char ch)
{
if(ch&0xff00) return false; else return isspace(ch);
}
//---------------------------------------------------------------------------
static bool inline TJS_iswdigit(tjs_char ch)
{
if(ch&0xff00) return false; else return isdigit(ch);
}
//---------------------------------------------------------------------------
static bool inline TJS_iswalpha(tjs_char ch)
{
if(ch&0xff00) return true; else return isalpha(ch);
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// TJSNext
//---------------------------------------------------------------------------
static void _TJSNext(const tjs_char **ptr)
{
do
{
(*ptr)++;
} while(*(*ptr) && *(*ptr)==TJS_SKIP_CODE);
}
bool inline TJSNext(const tjs_char **ptr)
{
(*ptr)++;
if(*(*ptr) == TJS_SKIP_CODE) _TJSNext(ptr);
return *(*ptr)!=0;
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// TJSSkipSpace
//---------------------------------------------------------------------------
bool TJSSkipSpace(const tjs_char **ptr)
{
while(*(*ptr) && (*(*ptr)==TJS_SKIP_CODE || TJS_iswspace(*(*ptr))))
(*ptr)++;
return *(*ptr)!=0;
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// TJSHexNum
tjs_int TJSHexNum(tjs_char ch) throw()
{
if(ch>=TJS_W('a') && ch<=TJS_W('f')) return ch-TJS_W('a')+10;
if(ch>=TJS_W('A') && ch<=TJS_W('F')) return ch-TJS_W('A')+10;
if(ch>=TJS_W('0') && ch<=TJS_W('9')) return ch-TJS_W('0');
return -1;
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// TJSOctNum
//---------------------------------------------------------------------------
tjs_int TJSOctNum(tjs_char ch) throw()
{
if(ch>=TJS_W('0') && ch<=TJS_W('7')) return ch-TJS_W('0');
return -1;
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// TJSDecNum
//---------------------------------------------------------------------------
tjs_int TJSDecNum(tjs_char ch) throw()
{
if(ch>=TJS_W('0') && ch<=TJS_W('9')) return ch-TJS_W('0');
return -1;
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// TJSBinNum
//---------------------------------------------------------------------------
tjs_int TJSBinNum(tjs_char ch) throw()
{
if(ch==TJS_W('0')) return 0;
if(ch==TJS_W('1')) return 1;
return -1;
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// TJSUnescapeBackSlash
//---------------------------------------------------------------------------
tjs_int TJSUnescapeBackSlash(tjs_char ch) throw()
{
// convert "\?"
// ch must indicate "?"
switch(ch)
{
case TJS_W('a'): return 0x07;
case TJS_W('b'): return 0x08;
case TJS_W('f'): return 0x0c;
case TJS_W('n'): return 0x0a;
case TJS_W('r'): return 0x0d;
case TJS_W('t'): return 0x09;
case TJS_W('v'): return 0x0b;
default : return ch;
}
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// TJSSkipComment
//---------------------------------------------------------------------------
static tTJSSkipCommentResult TJSSkipComment(const tjs_char **ptr)
{
if((*ptr)[0] != TJS_W('/')) return scrNotComment;
if((*ptr)[1] == TJS_W('/'))
{
// line comment; skip to newline
while(*(*ptr)!=TJS_W('\n')) if(!TJSNext(&(*ptr))) break;
if(*(*ptr) ==0) return scrEnded;
(*ptr)++;
TJSSkipSpace(&(*ptr));
if(*(*ptr) ==0) return scrEnded;
return scrContinue;
}
else if((*ptr)[1] == TJS_W('*'))
{
// block comment; skip to the next '*' '/'
// and we must allow nesting of the comment.
(*ptr) += 2;
if(*(*ptr) == 0) TJS_eTJSError(TJSUnclosedComment);
tjs_int level = 0;
for(;;)
{
if((*ptr)[0] == TJS_W('/') && (*ptr)[1] == TJS_W('*'))
{
// note: we cannot avoid comment processing when the
// nested comment is in string literals.
level ++;
}
if((*ptr)[0] == TJS_W('*') && (*ptr)[1] == TJS_W('/'))
{
if(level == 0)
{
(*ptr) += 2;
break;
}
level --;
}
if(!TJSNext(&(*ptr))) TJS_eTJSError(TJSUnclosedComment);
}
if(*(*ptr) ==0) return scrEnded;
TJSSkipSpace(&(*ptr));
if(*(*ptr) ==0) return scrEnded;
return scrContinue;
}
return scrNotComment;
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// TJSStringMatch
//---------------------------------------------------------------------------
bool TJSStringMatch(const tjs_char **sc, const tjs_char *wrd, bool isword)
{
// compare string with a script starting from sc and wrd.
// word matching is processed if isword is true.
const tjs_char *save = (*sc);
while(*wrd && *(*sc))
{
if(*(*sc) != *wrd) break;
TJSNext(sc);
wrd++;
}
if(*wrd) { (*sc)=save; return false; }
if(isword)
{
if(TJS_iswalpha(*(*sc)) || *(*sc) == TJS_W('_'))
{ (*sc)=save; return false; }
}
return true;
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// TJSParseString
//---------------------------------------------------------------------------
enum tTJSInternalParseStringResult
{ psrNone, psrDelimiter, psrAmpersand, psrDollar };
static tTJSInternalParseStringResult
TJSInternalParseString(tTJSVariant &val, const tjs_char **ptr,
tjs_char delim, bool embexpmode)
{
// delim1 must be '\'' or '"'
// delim2 must be '&' or '\0'
ttstr str;
tTJSInternalParseStringResult status = psrNone;
for(;*(*ptr);)
{
if(*(*ptr)==TJS_W('\\'))
{
// escape
if(!TJSNext(ptr)) break;
if(*(*ptr)==TJS_W('x') || *(*ptr)==TJS_W('X'))
{
// hex
// starts with a "\x", be parsed while characters are
// recognized as hex-characters, but limited of size of tjs_char.
// on Windows, \xXXXXX will be parsed to UNICODE 16bit characters.
if(!TJSNext(ptr)) break;
tjs_int num;
tjs_int code = 0;
tjs_int count = 0;
while((num = TJSHexNum(*(*ptr)))!=-1 && count<(sizeof(tjs_char)*2))
{
code*=16;
code+=num;
count ++;
if(!TJSNext(ptr)) break;
}
if(*(*ptr) == 0) break;
str+=(tjs_char)code;
}
else if(*(*ptr) == TJS_W('0'))
{
// octal
if(!TJSNext(ptr)) break;
tjs_int num;
tjs_int code=0;
while((num=TJSOctNum(*(*ptr)))!=-1)
{
code*=8;
code+=num;
if(!TJSNext(ptr)) break;
}
if(*(*ptr) == 0) break;
str += (tjs_char)code;
}
else
{
str += (tjs_char)TJSUnescapeBackSlash(*(*ptr));
TJSNext(ptr);
}
}
else if(*(*ptr) == delim)
{
// string delimiters
if(!TJSNext(ptr))
{
status = psrDelimiter;
break;
}
const tjs_char *p=(*ptr);
TJSSkipSpace(&p);
if(*p == delim)
{
// sequence of 'A' 'B' will be combined as 'AB'
(*ptr) = p;
TJSNext(ptr);
}
else
{
status = psrDelimiter;
break;
}
}
else if(embexpmode && *(*ptr) == TJS_W('&'))
{
// '&'
if(!TJSNext(ptr)) break;
status = psrAmpersand;
break;
}
else if(embexpmode && *(*ptr) == TJS_W('$'))
{
// '$'
// '{' must be placed immediately after '$'
const tjs_char *p = (*ptr);
if(!TJSNext(ptr)) break;
if(*(*ptr) == TJS_W('{'))
{
if(!TJSNext(ptr)) break;
status = psrDollar;
break;
}
else
{
(*ptr) = p;
str += *(*ptr);
TJSNext(ptr);
}
}
else
{
str+=*(*ptr);
TJSNext(ptr);
}
}
if(status == psrNone)
{
// error
TJS_eTJSError(TJSStringParseError);
}
str.FixLen();
val = str;
return status;
}
//---------------------------------------------------------------------------
bool TJSParseString(tTJSVariant &val, const tjs_char **ptr)
{
// parse a string starts with '\'' or '"'
tjs_char delimiter=*(*ptr);
TJSNext(ptr);
return TJSInternalParseString(val, ptr, delimiter, false) == psrDelimiter;
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// TJSParseNumber
//---------------------------------------------------------------------------
static tTJSString TJSExtractNumber(tjs_int (*validdigits)(tjs_char ch),
const tjs_char *expmark, const tjs_char **ptr, bool &isreal)
{
tTJSString tmp;
bool point_found = false;
bool exp_found = false;
while(true)
{
if(validdigits(**ptr) != -1)
{
tmp += **ptr;
if(!TJSNext(ptr)) break;
}
else if(**ptr == TJS_W('.') && !point_found && !exp_found)
{
point_found = true;
tmp += **ptr;
if(!TJSNext(ptr)) break;
}
else if((**ptr == expmark[0] || **ptr == expmark[1]) && !exp_found)
{
exp_found = true;
tmp += **ptr;
if(!TJSNext(ptr)) break;
if(!TJSSkipSpace(ptr)) break;
if(**ptr == TJS_W('+'))
{
tmp += **ptr;
if(!TJSNext(ptr)) break;
if(!TJSSkipSpace(ptr)) break;
}
else if(**ptr == TJS_W('-'))
{
tmp += **ptr;
if(!TJSNext(ptr)) break;
if(!TJSSkipSpace(ptr)) break;
}
}
else
{
break;
}
}
isreal = point_found || exp_found;
return tmp;
}
static bool TJSParseNonDecimalReal(tTJSVariant &val, const tjs_char **ptr,
tjs_int (*validdigits)(tjs_char ch), tjs_int basebits)
{
// parse non-decimal(hexiadecimal, octal or binary) floating-point number.
// this routine heavily depends on IEEE double floating-point number expression.
tjs_uint64 main = TJS_UI64_VAL(0); // significand
tjs_int exp = 0; // 2^n exponental
tjs_int numsignif = 0; // significand bit count (including leading left-most '1') in "main"
bool pointpassed = false;
// scan input
while(true)
{
if(**ptr == TJS_W('.'))
{
pointpassed = true;
}
else if(**ptr == TJS_W('p') || **ptr == TJS_W('P'))
{
if(!TJSNext(ptr)) break;
if(!TJSSkipSpace(ptr)) break;
bool biassign = false;
if(**ptr == TJS_W('+'))
{
biassign = false;
if(!TJSNext(ptr)) break;
if(!TJSSkipSpace(ptr)) break;
}
if(**ptr == TJS_W('-'))
{
biassign = true;
if(!TJSNext(ptr)) break;
if(!TJSSkipSpace(ptr)) break;
}
tjs_int bias = 0;
while(true)
{
bias *= 10;
bias += TJSDecNum(**ptr);
if(!TJSNext(ptr)) break;
}
if(biassign) bias = -bias;
exp += bias;
break;
}
else
{
tjs_int n = validdigits(**ptr);
if(numsignif == 0)
{
// find msb flaged bit
tjs_int b = basebits - 1;
while(b >= 0)
{
if((1<<b) & n) break;
b--;
}
b++;
if(b)
{
// n is not zero
// place it to the main's msb
numsignif = b;
main |= ((tjs_uint64)n << (64 - numsignif));
if(pointpassed)
exp -= (basebits - b + 1);
else
exp = b - 1;
}
else
{
// n is zero
if(pointpassed) exp -= basebits;
}
}
else
{
// append to main
if(numsignif + basebits < 64)
{
numsignif += basebits;
main |= ((tjs_uint64)n << (64 - numsignif));
}
if(!pointpassed) exp += basebits;
}
}
if(!TJSNext(ptr)) break;
}
main >>= (64 - 1 - TJS_IEEE_D_SIGNIFICAND_BITS);
if(main == 0)
{
// zero
val = (tTVReal)0.0;
return true;
}
main &= ((TJS_UI64_VAL(1) << TJS_IEEE_D_SIGNIFICAND_BITS) - TJS_UI64_VAL(1));
if(exp < TJS_IEEE_D_EXP_MIN)
{
// denormal
// treat as zero
val = (tTVReal)0.0;
return true;
}
if(exp > TJS_IEEE_D_EXP_MAX)
{
// too large
// treat as infinity
tjs_real d;
*(tjs_uint64*)&d = TJS_IEEE_D_P_INF;
val = d;
return true;
}
// compose IEEE double
tjs_real d;
*(tjs_uint64*)&d =
TJS_IEEE_D_MAKE_SIGN(0) |
TJS_IEEE_D_MAKE_EXP(exp) |
TJS_IEEE_D_MAKE_SIGNIFICAND(main);
val = d;
return true;
}
static bool TJSParseNonDecimalInteger(tTJSVariant &val, const tjs_char **ptr,
tjs_int (*validdigits)(tjs_char ch), tjs_int basebits)
{
tjs_int64 v = 0;
while(true)
{
v <<= basebits;
v += validdigits(**ptr);
if(!TJSNext(ptr)) break;
}
val = (tTVInteger)v;
return true;
}
static bool TJSParseNonDecimalNumber(tTJSVariant &val, const tjs_char **ptr,
tjs_int (*validdigits)(tjs_char ch), tjs_int base)
{
bool isreal = false;
tTJSString tmp(TJSExtractNumber(validdigits, TJS_W("Pp"), ptr, isreal));
if(tmp.IsEmpty()) return false;
const tjs_char *p = tmp.c_str();
const tjs_char **pp = &p;
if(isreal)
return TJSParseNonDecimalReal(val, pp, validdigits, base);
else
return TJSParseNonDecimalInteger(val, pp, validdigits, base);
}
static bool TJSParseDecimalReal(tTJSVariant &val, const tjs_char **pp)
{
val = (tTVReal)TJS_strtod(*pp, NULL);
return true;
}
static bool TJSParseDecimalInteger(tTJSVariant &val, const tjs_char **pp)
{
int n;
tjs_int64 num = 0;
while((n = TJSDecNum(**pp)) != -1)
{
num *= 10;
num += n;
if(!TJSNext(pp)) break;
}
val = (tTVInteger)num;
return true;
}
static bool TJSParseNumber2(tTJSVariant &val, const tjs_char **ptr)
{
// stage 2
if(TJSStringMatch(ptr, TJS_W("true"), true))
{
val = (tjs_int)true;
return true;
}
if(TJSStringMatch(ptr, TJS_W("false"), true))
{
val = (tjs_int)false;
return true;
}
if(TJSStringMatch(ptr, TJS_W("NaN"), true))
{
// Not a Number
tjs_real d;
*(tjs_uint64*)&d = TJS_IEEE_D_P_NaN;
val = d;
return true;
}
if(TJSStringMatch(ptr, TJS_W("Infinity"), true))
{
// positive inifinity
tjs_real d;
*(tjs_uint64*)&d = TJS_IEEE_D_P_INF;
val = d;
return true;
}
const tjs_char *ptr_save = *ptr;
if(**ptr == TJS_W('0'))
{
if(!TJSNext(ptr))
{
val = (tjs_int) 0;
return true;
}
tjs_char mark = **ptr;
if(mark == TJS_W('X') || mark == TJS_W('x'))
{
// hexadecimal
if(!TJSNext(ptr)) return false;
return TJSParseNonDecimalNumber(val, ptr, TJSHexNum, 4);
}
if(mark == TJS_W('B') || mark == TJS_W('b'))
{
// binary
if(!TJSNext(ptr)) return false;
return TJSParseNonDecimalNumber(val, ptr, TJSBinNum, 1);
}
if(mark == TJS_W('.'))
{
// decimal point
*ptr = ptr_save;
goto decimal;
}
if(mark == TJS_W('E') || mark == TJS_W('e'))
{
// exp
*ptr = ptr_save;
goto decimal;
}
if(mark == TJS_W('P') || mark == TJS_W('p'))
{
// 2^n exp
return false;
}
// octal
*ptr = ptr_save;
return TJSParseNonDecimalNumber(val, ptr, TJSOctNum, 3);
}
// integer decimal or real decimal
decimal:
bool isreal = false;
tTJSString tmp(TJSExtractNumber(TJSDecNum, TJS_W("Ee"), ptr, isreal));
if(tmp.IsEmpty()) return false;
const tjs_char *p = tmp.c_str();
const tjs_char **pp = &p;
if(isreal)
return TJSParseDecimalReal(val, pp);
else
return TJSParseDecimalInteger(val, pp);
}
bool TJSParseNumber(tTJSVariant &val, const tjs_char **ptr)
{
// parse a number pointed by (*ptr)
TJSSetFPUE();
bool sign = false; // true if negative
if(**ptr == TJS_W('+'))
{
sign = false;
if(!TJSNext(ptr)) return false;
if(!TJSSkipSpace(ptr)) return false;
}
else if(**ptr == TJS_W('-'))
{
sign = true;
if(!TJSNext(ptr)) return false;
if(!TJSSkipSpace(ptr)) return false;
}
if(TJSParseNumber2(val, ptr))
{
if(sign) val = -val;
return true;
}
return false;
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// TJSParseOctet
//---------------------------------------------------------------------------
static bool TJSParseOctet(tTJSVariant &val, const tjs_char **ptr)
{
// parse a octet literal;
// syntax is:
// <% xx xx xx xx xx xx ... %>
// where xx is hexadecimal 8bit(octet) binary representation.
TJSNext(ptr);
TJSNext(ptr); // skip <%
tjs_uint8 *buf = NULL;
tjs_uint buflen = 0;
bool leading = true;
tjs_uint8 cur = 0;
for(;*(*ptr);)
{
switch(TJSSkipComment(ptr))
{
case scrEnded:
TJS_eTJSError(TJSStringParseError);
case scrContinue:
case scrNotComment:
;
}
const tjs_char *next = *ptr;
TJSNext(&next);
if(*(*ptr) == TJS_W('%') && *next == TJS_W('>'))
{
*ptr = next;
TJSNext(ptr);
// literal ended
if(!leading)
{
buf = (tjs_uint8*)TJS_realloc(buf, buflen+1);
if(!buf)
throw eTJSError(ttstr(TJSInsufficientMem));
buf[buflen] = cur;
buflen++;
}
val = tTJSVariant(buf, buflen); // create octet variant
if(buf) TJS_free(buf);
return true;
}
tjs_char ch = *(*ptr);
tjs_int n = TJSHexNum(ch);
if(n != -1)
{
if(leading)
{
cur = (tjs_uint8)(n);
leading = false;
}
else
{
cur <<= 4;
cur += n;
// store cur
buf = (tjs_uint8*)TJS_realloc(buf, buflen+1);
if(!buf)
throw eTJSError(ttstr(TJSInsufficientMem));
buf[buflen] = cur;
buflen++;
leading = true;
}
}
if(!leading && ch == TJS_W(','))
{
buf = (tjs_uint8*)TJS_realloc(buf, buflen+1);
if(!buf)
TJS_eTJSError(TJSInsufficientMem);
buf[buflen] = cur;
buflen++;
leading = true;
}
*ptr = next;
}
// error
TJS_eTJSError(TJSStringParseError);
return false;
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// TJSParseRegExp
//---------------------------------------------------------------------------
static bool TJSParseRegExp(tTJSVariant &pat, const tjs_char **ptr)
{
// parse a regular expression pointed by 'ptr'.
// this is essencially the same as string parsing, except for
// not to decode escaped characters by '\\'.
// the regexp must be terminated by the delimiter '/', not succeeded by '\\'.
// this returns an internal representation: '//flag/pattern' that can be parsed by
// RegExp._compile
// if(!TJSNext((*ptr))) TJS_eTJSError(TJSStringParseError);
bool ok = false;
bool lastbackslash = false;
ttstr str;
for(;*(*ptr);)
{
if(*(*ptr)==TJS_W('\\'))
{
str+=*(*ptr);
if(lastbackslash)
lastbackslash = false;
else
lastbackslash = true;
}
else if(*(*ptr)==TJS_W('/') && !lastbackslash)
{
// string delimiters
// lastbackslash = false;
if(!TJSNext(ptr))
{
ok = true;
break;
}
// flags can be here
ttstr flag;
while(*(*ptr) >= TJS_W('a') && *(*ptr) <= TJS_W('z'))
{
flag += *(*ptr);
if(!TJSNext(ptr)) break;
}
str = TJS_W("/")TJS_W("/")+ flag + TJS_W("/") + str;
ok = true;
break;
}
else
{
lastbackslash = false;
str+=*(*ptr);
}
TJSNext(ptr);
}
if(!ok)
{
// error
TJS_eTJSError(TJSStringParseError);
}
pat = str;
return true;
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// hash table for reserved words
//---------------------------------------------------------------------------
static tTJSCustomObject * TJSReservedWordHash = NULL;
static bool TJSReservedWordHashInit = false;
static tjs_int TJSReservedWordHashRefCount;
//---------------------------------------------------------------------------
void TJSReservedWordsHashAddRef()
{
if(TJSReservedWordHashRefCount == 0)
{
TJSReservedWordHashInit = false;
TJSReservedWordHash = new tTJSCustomObject();
}
TJSReservedWordHashRefCount ++;
}
//---------------------------------------------------------------------------
void TJSReservedWordsHashRelease()
{
TJSReservedWordHashRefCount --;
if(TJSReservedWordHashRefCount == 0)
{
TJSReservedWordHash->Release();
TJSReservedWordHash = NULL;
}
}
//---------------------------------------------------------------------------
static void TJSRegisterReservedWordsHash(const tjs_char *word, tjs_int num)
{
tTJSVariant val(num);
TJSReservedWordHash->PropSet(TJS_MEMBERENSURE, word, NULL, &val,
TJSReservedWordHash);
}
//---------------------------------------------------------------------------
#define TJS_REG_RES_WORD(word, value) TJSRegisterReservedWordsHash(TJS_W(word), value);
static void TJSInitReservedWordsHashTable()
{
if(TJSReservedWordHashInit) return;
TJSReservedWordHashInit = true;
TJS_REG_RES_WORD("break", T_BREAK);
TJS_REG_RES_WORD("continue", T_CONTINUE);
TJS_REG_RES_WORD("const", T_CONST);
TJS_REG_RES_WORD("catch", T_CATCH);
TJS_REG_RES_WORD("class", T_CLASS);
TJS_REG_RES_WORD("case", T_CASE);
TJS_REG_RES_WORD("debugger", T_DEBUGGER);
TJS_REG_RES_WORD("default", T_DEFAULT);
TJS_REG_RES_WORD("delete", T_DELETE);
TJS_REG_RES_WORD("do", T_DO);
TJS_REG_RES_WORD("extends", T_EXTENDS);
TJS_REG_RES_WORD("export", T_EXPORT);
TJS_REG_RES_WORD("enum", T_ENUM);
TJS_REG_RES_WORD("else", T_ELSE);
TJS_REG_RES_WORD("function", T_FUNCTION);
TJS_REG_RES_WORD("finally", T_FINALLY);
TJS_REG_RES_WORD("false", T_FALSE);
TJS_REG_RES_WORD("for", T_FOR);
TJS_REG_RES_WORD("global", T_GLOBAL);
TJS_REG_RES_WORD("getter", T_GETTER);
TJS_REG_RES_WORD("goto", T_GOTO);
TJS_REG_RES_WORD("incontextof", T_INCONTEXTOF);
TJS_REG_RES_WORD("invalidate", T_INVALIDATE);
TJS_REG_RES_WORD("instanceof", T_INSTANCEOF);
TJS_REG_RES_WORD("isvalid", T_ISVALID);
TJS_REG_RES_WORD("import", T_IMPORT);
TJS_REG_RES_WORD("int", T_INT);
TJS_REG_RES_WORD("in", T_IN);
TJS_REG_RES_WORD("if", T_IF);
TJS_REG_RES_WORD("null", T_NULL);
TJS_REG_RES_WORD("new", T_NEW);
TJS_REG_RES_WORD("octet", T_OCTET);
TJS_REG_RES_WORD("protected", T_PROTECTED);
TJS_REG_RES_WORD("property", T_PROPERTY);
TJS_REG_RES_WORD("private", T_PRIVATE);
TJS_REG_RES_WORD("public", T_PUBLIC);
TJS_REG_RES_WORD("return", T_RETURN);
TJS_REG_RES_WORD("real", T_REAL);
TJS_REG_RES_WORD("synchronized", T_SYNCHRONIZED);
TJS_REG_RES_WORD("switch", T_SWITCH);
TJS_REG_RES_WORD("static", T_STATIC);
TJS_REG_RES_WORD("setter", T_SETTER);
TJS_REG_RES_WORD("string", T_STRING);
TJS_REG_RES_WORD("super", T_SUPER);
TJS_REG_RES_WORD("typeof", T_TYPEOF);
TJS_REG_RES_WORD("throw", T_THROW);
TJS_REG_RES_WORD("this", T_THIS);
TJS_REG_RES_WORD("true", T_TRUE);
TJS_REG_RES_WORD("try", T_TRY);
TJS_REG_RES_WORD("void", T_VOID);
TJS_REG_RES_WORD("var", T_VAR);
TJS_REG_RES_WORD("while", T_WHILE);
#ifndef TJS_NaN_and_Infinity_ARE_NOT_RESERVED_WORD
TJS_REG_RES_WORD("NaN", T_NAN);
TJS_REG_RES_WORD("Infinity", T_INFINITY);
#endif
#ifndef TJS_WITH_IS_NOT_RESERVED_WORD
TJS_REG_RES_WORD("with", T_WITH);
#endif
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// tTJSLexicalAnalyzer
//---------------------------------------------------------------------------
tTJSLexicalAnalyzer::tTJSLexicalAnalyzer(tTJSScriptBlock *block,
const tjs_char *script, bool exprmode, bool resneeded)
{
// resneeded is valid only if exprmode is true
TJS_F_TRACE("tTJSLexicalAnalyzer::tTJSLexicalAnalyzer");
TJSInitReservedWordsHashTable();
Block = block;
ExprMode = exprmode;
ResultNeeded = resneeded;
PrevToken = -1;
tjs_int len = TJS_strlen(script);
Script = new tjs_char[len+2];
TJS_strcpy(Script, script);
if(ExprMode)
{
// append ';' on expression analyze mode
Script[len] = TJS_W(';');
Script[len+1] = 0;
}
else
{
if(Script[0] == TJS_W('#') && Script[1] == TJS_W('!'))
{
// shell script like file
Script[0] = TJS_W('/');
Script[1] = TJS_W('/'); // convert #! to //
}
}
if(tjsEnableDicFuncQuickHack) //----- dicfunc quick-hack
{
DicFunc = false;
if(ExprMode && (Script[0] == TJS_W('[') || (Script[0] == TJS_W('%') && Script[1] == TJS_W('['))))
{
DicFunc = true;
}
}
Current = Script;
IfLevel = 0;
PrevPos = 0;
NestLevel = 0;
First = true;
RegularExpression = false;
BareWord = false;
PutValue(tTJSVariant());
}
//---------------------------------------------------------------------------
tTJSLexicalAnalyzer::~tTJSLexicalAnalyzer()
{
Free();
}
//---------------------------------------------------------------------------
tTJSSkipCommentResult tTJSLexicalAnalyzer::SkipUntil_endif()
{
// skip until @endif
tjs_int exl = IfLevel;
IfLevel ++;
while(true)
{
if(*Current == TJS_W('/'))
{
switch(TJSSkipComment(&Current))
{
case scrEnded:
TJS_eTJSCompileError(TJSPPError, Block, Current-Script);
break;
case scrContinue:
break;
case scrNotComment:
if(!TJSNext(&Current))
TJS_eTJSCompileError(TJSPPError, Block, Current-Script);
break;
}
}
else if(*Current == TJS_W('@'))
{
Current ++;
bool skipp = false;
if(!TJS_strncmp(Current, TJS_W("if"), 2))
{
IfLevel ++;
Current += 2;
skipp = true;
}
else if(!TJS_strncmp(Current, TJS_W("set"), 3))
{
Current += 3;
skipp = true;
}
else if(!TJS_strncmp(Current, TJS_W("endif"), 5))
{
// endif
Current += 5;
IfLevel--;
if(IfLevel == exl)
{
// skip ended
TJSSkipSpace(&Current);
if(!*Current) return scrEnded;
return scrContinue;
}
}
else
{
// skipp = false
}
if(skipp)
{
// skip parenthesises
if(!TJSSkipSpace(&Current))
TJS_eTJSCompileError(TJSPPError, Block, Current-Script);
if(*Current!=TJS_W('('))
TJS_eTJSCompileError(TJSPPError, Block, Current-Script);
TJSNext(&Current);
tjs_int plevel = 0;
while(*Current && (plevel || *Current!=TJS_W(')')))
{
if(*Current == TJS_W('(')) plevel++;
else if(*Current == TJS_W(')')) plevel--;
TJSNext(&Current);
}
if(!*Current)
TJS_eTJSCompileError(TJSPPError, Block, Current-Script);
TJSNext(&Current);
if(!*Current)
TJS_eTJSCompileError(TJSPPError, Block, Current-Script);
}
}
else
{
if(!TJSNext(&Current))
TJS_eTJSCompileError(TJSPPError, Block, Current-Script);
}
}
}
//---------------------------------------------------------------------------
tTJSSkipCommentResult tTJSLexicalAnalyzer::ProcessPPStatement()
{
// process pre-prosessor statements.
// here "Current" points '@'.
const tjs_char *org = Current;
Current ++;
if(!TJS_strncmp(Current, TJS_W("set"), 3))
{
// set statement
Block->NotifyUsingPreProcessor();
Current+=3;
if(!TJSSkipSpace(&Current))
TJS_eTJSCompileError(TJSPPError, Block, Current-Script);
if(*Current!=TJS_W('('))
TJS_eTJSCompileError(TJSPPError, Block, Current-Script);
TJSNext(&Current);
const tjs_char *st = Current;
tjs_int plevel = 0;
while(*Current && (plevel || *Current!=TJS_W(')')))
{
if(*Current == TJS_W('(')) plevel++;
else if(*Current == TJS_W(')')) plevel--;
TJSNext(&Current);
}
const tjs_char *ed = Current;
TJSNext(&Current);
try
{
ParsePPExpression(st, ed-st); // evaluate exp
}
catch(...)
{
TJS_eTJSCompileError(TJSPPError, Block, Current-Script);
}
TJSSkipSpace(&Current);
if(!*Current) return scrEnded;
return scrContinue;
}
if(!TJS_strncmp(Current, TJS_W("if"), 2))
{
// if statement
Block->NotifyUsingPreProcessor();
Current += 2;
if(!TJSSkipSpace(&Current))
TJS_eTJSCompileError(TJSPPError, Block, Current-Script);
if(*Current!=TJS_W('('))
TJS_eTJSCompileError(TJSPPError, Block, Current-Script);
TJSNext(&Current);
const tjs_char *st = Current;
tjs_int plevel = 0;
while(*Current && (plevel || *Current!=TJS_W(')')))
{
if(*Current == TJS_W('(')) plevel++;
else if(*Current == TJS_W(')')) plevel--;
TJSNext(&Current);
}
const tjs_char *ed = Current;
TJSNext(&Current);
tjs_int32 ret;
try
{
ret = ParsePPExpression(st, ed-st); // evaluate exp
}
catch(...)
{
TJS_eTJSCompileError(TJSPPError, Block, Current-Script);
}
if(!ret) return SkipUntil_endif(); // skip to endif
IfLevel ++;
TJSSkipSpace(&Current);
if(!*Current) return scrEnded;
return scrContinue;
}
if(!TJS_strncmp(Current, TJS_W("endif"), 5))
{
Current += 5;
IfLevel --;
if(IfLevel < 0)
TJS_eTJSCompileError(TJSPPError, Block, Current-Script);
TJSSkipSpace(&Current);
if(!*Current) return scrEnded;
return scrContinue;
}
Current = org;
return scrNotComment;
}
//---------------------------------------------------------------------------
#define TJS_MATCH_W(word, code) \
if(TJSStringMatch(&Current, TJS_W(word), true)) return (code)
#define TJS_MATCH_S(word, code) \
if(TJSStringMatch(&Current, TJS_W(word), false)) return (code)
#define TJS_MATCH_W_V(word, code, val) \
if(TJSStringMatch(&Current, TJS_W(word), true)) { n=PutValue(val); return (code); }
#define TJS_MATCH_S_V(word, code, val) \
if(TJSStringMatch(&Current, TJS_W(word), false)) { n=PutValue(val); return (code); }
#define TJS_1CHAR(code) \
TJSNext(&Current); return (code)
tjs_int tTJSLexicalAnalyzer::GetToken(tjs_int &n)
{
// returns token, pointed by 'Current'
if(*Current == 0) return 0;
if(RegularExpression)
{
// the next token was marked as a regular expression by the parser
RegularExpression = false;
Current = Script + PrevPos; // draws position of the first '/' back
TJSNext(&Current);
tTJSVariant pat;
TJSParseRegExp(pat, &Current);
n = PutValue(pat);
return T_REGEXP;
}
re_match:
PrevPos = Current - Script; // remember current position as "PrevPos"
switch(*Current)
{
case TJS_W('>'):
TJS_MATCH_S(">>>=", T_RBITSHIFTEQUAL);
TJS_MATCH_S(">>>", T_RBITSHIFT);
TJS_MATCH_S(">>=", T_RARITHSHIFTEQUAL);
TJS_MATCH_S(">>", T_RARITHSHIFT);
TJS_MATCH_S(">=", T_GTOREQUAL);
TJS_1CHAR(T_GT);
case TJS_W('<'):
TJS_MATCH_S("<<=", T_LARITHSHIFTEQUAL);
TJS_MATCH_S("<->", T_SWAP);
TJS_MATCH_S("<=", T_LTOREQUAL);
TJS_MATCH_S("<<", T_LARITHSHIFT);
{
const tjs_char *next = Current;
TJSNext(&next);
if(*next == TJS_W('%'))
{
// '<%' octet literal
tTJSVariant v;
TJSParseOctet(v, &Current);
n = PutValue(v);
return T_CONSTVAL;
}
}
TJS_1CHAR(T_LT);
case TJS_W('='):
TJS_MATCH_S("===", T_DISCEQUAL);
TJS_MATCH_S("==", T_EQUALEQUAL);
TJS_MATCH_S("=>", T_COMMA);
// just a replacement for comma, like perl
TJS_1CHAR(T_EQUAL);
case TJS_W('!'):
TJS_MATCH_S("!==", T_DISCNOTEQUAL);
TJS_MATCH_S("!=", T_NOTEQUAL);
TJS_1CHAR(T_EXCRAMATION);
case TJS_W('&'):
TJS_MATCH_S("&&=", T_LOGICALANDEQUAL);
TJS_MATCH_S("&&", T_LOGICALAND);
TJS_MATCH_S("&=", T_AMPERSANDEQUAL);
TJS_1CHAR(T_AMPERSAND);
case TJS_W('|'):
TJS_MATCH_S("||=", T_LOGICALOREQUAL);
TJS_MATCH_S("||", T_LOGICALOR);
TJS_MATCH_S("|=", T_VERTLINEEQUAL);
TJS_1CHAR(T_VERTLINE);
case TJS_W('.'):
if(Current[1] >= TJS_W('0') && Current[1] <= TJS_W('9'))
{
// number
tTJSVariant v;
TJSParseNumber(v, &Current);
n=PutValue(v);
return T_CONSTVAL;
}
TJS_MATCH_S("...", T_OMIT);
TJS_1CHAR(T_DOT);
case TJS_W('+'):
TJS_MATCH_S("++", T_INCREMENT);
TJS_MATCH_S("+=", T_PLUSEQUAL);
TJS_1CHAR(T_PLUS);
case TJS_W('-'):
TJS_MATCH_S("-=", T_MINUSEQUAL);
TJS_MATCH_S("--", T_DECREMENT);
TJS_1CHAR(T_MINUS);
case TJS_W('*'):
TJS_MATCH_S("*=", T_ASTERISKEQUAL);
TJS_1CHAR(T_ASTERISK);
case TJS_W('/'):
// check comments
switch(TJSSkipComment(&Current))
{
case scrContinue:
goto re_match;
case scrEnded:
return 0;
case scrNotComment:
;
}
TJS_MATCH_S("/=", T_SLASHEQUAL);
TJS_1CHAR(T_SLASH);
case TJS_W('\\'):
TJS_MATCH_S("\\=", T_BACKSLASHEQUAL);
TJS_1CHAR(T_BACKSLASH);
case TJS_W('%'):
TJS_MATCH_S("%=", T_PERCENTEQUAL);
TJS_1CHAR(T_PERCENT);
case TJS_W('^'):
TJS_MATCH_S("^=", T_CHEVRONEQUAL);
TJS_1CHAR(T_CHEVRON);
case TJS_W('['):
NestLevel++;
TJS_1CHAR(T_LBRACKET);
case TJS_W(']'):
NestLevel--;
TJS_1CHAR(T_RBRACKET);
case TJS_W('('):
NestLevel++;
TJS_1CHAR(T_LPARENTHESIS);
case TJS_W(')'):
NestLevel--;
TJS_1CHAR(T_RPARENTHESIS);
case TJS_W('~'):
TJS_1CHAR(T_TILDE);
case TJS_W('?'):
TJS_1CHAR(T_QUESTION);
case TJS_W(':'):
TJS_1CHAR(T_COLON);
case TJS_W(','):
TJS_1CHAR(T_COMMA);
case TJS_W(';'):
TJS_1CHAR(T_SEMICOLON);
case TJS_W('{'):
NestLevel++;
TJS_1CHAR(T_LBRACE);
case TJS_W('}'):
NestLevel--;
TJS_1CHAR(T_RBRACE);
case TJS_W('#'):
TJS_1CHAR(T_SHARP);
case TJS_W('$'):
TJS_1CHAR(T_DOLLAR);
case TJS_W('\''):
case TJS_W('\"'):
// literal string
{
tTJSVariant v;
TJSParseString(v, &Current);
n=PutValue(v);
return T_CONSTVAL;
}
case TJS_W('@'):
// embeddable expression in string (such as @"this can be embeddable like &variable;")
{
const tjs_char *org = Current;
if(!TJSNext(&Current)) return 0;
if(!TJSSkipSpace(&Current)) return 0;
if(*Current == TJS_W('\'') || *Current == TJS_W('\"'))
{
tEmbeddableExpressionData data;
data.State = evsStart;
data.WaitingNestLevel = NestLevel;
data.Delimiter = *Current;
data.NeedPlus = false;
if(!TJSNext(&Current)) return 0;
EmbeddableExpressionDataStack.push_back(data);
return -1;
}
else
{
Current = org;
}
// possible pre-prosessor statements
switch(ProcessPPStatement())
{
case scrContinue:
goto re_match;
case scrEnded:
return 0;
case scrNotComment:
Current = org;
break;
}
break;
}
case TJS_W('0'):
case TJS_W('1'):
case TJS_W('2'):
case TJS_W('3'):
case TJS_W('4'):
case TJS_W('5'):
case TJS_W('6'):
case TJS_W('7'):
case TJS_W('8'):
case TJS_W('9'):
// number
{
tTJSVariant v;
bool r = TJSParseNumber(v, &Current);
if(!r) TJS_eTJSCompileError(TJSNumberError, Block, Current-Script);
n=PutValue(v);
return T_CONSTVAL;
}
}
if(!TJS_iswalpha(*Current) && *Current!=TJS_W('_'))
{
ttstr str(TJSInvalidChar);
str.Replace(TJS_W("%1"), ttstr(*Current).EscapeC());
TJS_eTJSError(str);
}
const tjs_char *ptr = Current;
tjs_int nch = 0;
while(TJS_iswdigit(*ptr) || TJS_iswalpha(*ptr) || *ptr==TJS_W('_') ||
*ptr>0x0100 || *ptr == TJS_SKIP_CODE)
ptr++, nch++;
if(nch == 0)
{
ttstr str(TJSInvalidChar);
str.Replace(TJS_W("%1"), ttstr(*Current).EscapeC());
TJS_eTJSError(str);
}
ttstr str(Current, nch);
Current += nch;
tjs_char *s, *d;
s = d = str.Independ();
while(*s)
{
// eliminate TJS_SKIP_CODE
if(*s == TJS_SKIP_CODE)
{
s++;
continue;
}
*d = *s;
d++, s++;
}
*d = 0;
str.FixLen();
tjs_int retnum;
if(BareWord)
retnum = -1;
else
retnum = TJSReservedWordHash->GetValueInteger(str.c_str(), str.GetHint());
BareWord = false;
if(retnum == -1)
{
// not a reserved word
n = PutValue(str);
return T_SYMBOL;
}
switch(retnum)
{
case T_FALSE:
n = PutValue(tTJSVariant(false));
return T_CONSTVAL;
case T_NULL:
n = PutValue(tTJSVariant((iTJSDispatch2*)NULL));
return T_CONSTVAL;
case T_TRUE:
n = PutValue(tTJSVariant(true));
return T_CONSTVAL;
case T_NAN:
{
TJSSetFPUE();
tjs_real d;
*(tjs_uint64*)&d = TJS_IEEE_D_P_NaN;
n = PutValue(tTJSVariant(d));
return T_CONSTVAL;
}
case T_INFINITY:
{
TJSSetFPUE();
tjs_real d;
*(tjs_uint64*)&d = TJS_IEEE_D_P_INF;
n = PutValue(tTJSVariant(d));
return T_CONSTVAL;
}
}
return retnum;
}
//---------------------------------------------------------------------------
tjs_int32 tTJSLexicalAnalyzer::ParsePPExpression(const tjs_char *start, tjs_int n)
{
// parses a conditional compile experssion starting with "start",
// character count "n".
tjs_char *buf = new tjs_char[n+1];
tjs_char *p;
const tjs_char *lim = start + n;
p=buf;
while(start < lim)
{
*p = *start;
TJSNext(&start);
p++;
}
*p = 0;
tTJSPPExprParser *parser = new tTJSPPExprParser(Block->GetTJS(), buf);
tjs_int32 result;
try
{
result = parser->Parse();
}
catch(...)
{
delete parser;
throw;
}
delete parser;
return result;
}
//---------------------------------------------------------------------------
void tTJSLexicalAnalyzer::PreProcess(void)
{
TJS_F_TRACE("tTJSLexicalAnalyzer::PreProcess");
// pre-process
// proceeds newline code unification, conditional compile control.
/* unify new line codes */
TJS_D((TJS_W("unifying new line codes ...\n")))
tjs_char *p;
p=Script;
while(*p)
{
if(*p==TJS_W('\r') && *(p+1)==TJS_W('\n'))
*p=TJS_SKIP_CODE;
else if(*p==TJS_W('\r'))
*p=TJS_W('\n');
p++;
}
}
//---------------------------------------------------------------------------
tjs_int tTJSLexicalAnalyzer::PutValue(const tTJSVariant &val)
{
tTJSVariant *v = new tTJSVariant(val);
Values.push_back(v);
return Values.size() -1;
}
//---------------------------------------------------------------------------
void tTJSLexicalAnalyzer::Free(void)
{
if(Script) delete [] Script;
std::vector<tTJSVariant*>::iterator i;
for(i = Values.begin(); i != Values.end(); i++)
{
delete *i;
}
Values.clear();
}
/*
//---------------------------------------------------------------------------
void tTJSLexicalAnalyzer::NextBraceIsBlockBrace()
{
BlockBrace = true;
}
*/
//---------------------------------------------------------------------------
tjs_int tTJSLexicalAnalyzer::GetCurrentPosition()
{
return Current - Script;
}
//---------------------------------------------------------------------------
tjs_int tTJSLexicalAnalyzer::GetNext(tjs_int &value)
{
TJS_F_TRACE("tTJSLexicalAnalyzer::GetNext");
if(First)
{
TJS_D((TJS_W("pre-processing ...\n")))
First = false;
try
{
PreProcess();
}
catch(eTJSCompileError &e)
{
_yyerror(e.GetMessage().c_str(), Block, e.GetPosition());
return 0;
}
Current = Script;
PrevPos = 0;
if(ExprMode && ResultNeeded)
{
value = 0;
return T_RETURN;
// return T_RETURN first if 'expression' mode
// (and ResultNeeded is specified)
}
}
tjs_int n;
value = 0;
do
{
if(RetValDeque.size())
{
tTokenPair pair = RetValDeque.front();
RetValDeque.pop_front();
value = pair.value;
PrevToken = pair.token;
return pair.token;
}
try
{
if(!EmbeddableExpressionDataStack.size())
{
// normal mode
TJSSkipSpace(&Current);
n = GetToken(value);
if(tjsEnableDicFuncQuickHack) //----- dicfunc quick-hack
{
if(DicFunc)
{
if(n == T_PERCENT)
{
// push "function { return %"
RetValDeque.push_back(tTokenPair(T_FUNCTION, 0));
RetValDeque.push_back(tTokenPair(T_LBRACE, 0));
RetValDeque.push_back(tTokenPair(T_RETURN, 0));
RetValDeque.push_back(tTokenPair(T_PERCENT, 0));
n = -1;
}
else if(n == T_LBRACKET && PrevToken != T_PERCENT)
{
// push "function { return ["
RetValDeque.push_back(tTokenPair(T_FUNCTION, 0));
RetValDeque.push_back(tTokenPair(T_LBRACE, 0));
RetValDeque.push_back(tTokenPair(T_RETURN, 0));
RetValDeque.push_back(tTokenPair(T_LBRACKET, 0));
n = -1;
}
else if(n == T_RBRACKET)
{
// push "] ; }( )"
RetValDeque.push_back(tTokenPair(T_RBRACKET, 0));
RetValDeque.push_back(tTokenPair(T_SEMICOLON, 0));
RetValDeque.push_back(tTokenPair(T_RBRACE, 0));
RetValDeque.push_back(tTokenPair(T_LPARENTHESIS, 0));
RetValDeque.push_back(tTokenPair(T_RPARENTHESIS, 0));
n = -1;
}
}
}
}
else
{
// embeddable expression mode
tEmbeddableExpressionData &data = EmbeddableExpressionDataStack.back();
switch(data.State)
{
case evsStart:
RetValDeque.push_back(tTokenPair(T_LPARENTHESIS, 0));
n = -1;
data.State = evsNextIsStringLiteral;
break;
case evsNextIsStringLiteral:
{
tTJSVariant v;
tTJSInternalParseStringResult res =
TJSInternalParseString(v, &Current,
data.Delimiter, TJS_W('&'));
if(res == psrDelimiter)
{
// embeddable expression mode ended
ttstr str(v);
if(!str.IsEmpty())
{
if(data.NeedPlus)
RetValDeque.push_back(tTokenPair(T_PLUS, 0));
}
if(!str.IsEmpty() || !data.NeedPlus)
RetValDeque.push_back(tTokenPair(T_CONSTVAL, PutValue(v)));
RetValDeque.push_back(tTokenPair(T_RPARENTHESIS, 0));
EmbeddableExpressionDataStack.pop_back();
n = -1;
break;
}
else
{
// *Current is next to ampersand mark or '${'
ttstr str(v);
if(!str.IsEmpty())
{
if(data.NeedPlus)
RetValDeque.push_back(tTokenPair(T_PLUS, 0));
RetValDeque.push_back(tTokenPair(T_CONSTVAL, PutValue(v)));
data.NeedPlus = true;
}
if(data.NeedPlus)
RetValDeque.push_back(tTokenPair(T_PLUS, 0));
RetValDeque.push_back(tTokenPair(T_STRING, 0));
RetValDeque.push_back(tTokenPair(T_LPARENTHESIS, 0));
data.State = evsNextIsExpression;
if(res == psrAmpersand)
data.WaitingToken = T_SEMICOLON;
else if(res == psrDollar)
data.WaitingToken = T_RBRACE, NestLevel++;
n = -1;
break;
}
}
case evsNextIsExpression:
{
TJSSkipSpace(&Current);
n = GetToken(value);
if(n == data.WaitingToken && NestLevel == data.WaitingNestLevel)
{
// end of embeddable expression mode
RetValDeque.push_back(tTokenPair(T_RPARENTHESIS, 0));
data.NeedPlus = true;
data.State = evsNextIsStringLiteral;
n = -1;
}
break;
}
}
}
if(n == 0)
{
if(IfLevel != 0)
TJS_eTJSCompileError(TJSPPError, Block, Current-Script);
}
}
catch(eTJSCompileError &e)
{
_yyerror(e.GetMessage().c_str(), Block);
return 0;
}
catch(eTJSScriptError &e)
{
_yyerror(e.GetMessage().c_str(), Block);
return 0;
}
catch(eTJS &e)
{
_yyerror(e.GetMessage().c_str(), Block);
return 0;
}
#ifdef TJS_SUPPORT_VCL
catch(EAccessViolation &e)
{
ttstr msg(e.Message.c_str());
_yyerror(msg.c_str(), Block);
return 0;
}
catch(Exception &e)
{
ttstr msg(e.Message.c_str());
_yyerror(msg.c_str(), Block);
return 0;
}
#endif
} while(n < 0);
/*
if(BlockBrace)
{
if(n == T_LBRACE) n = T_BLOCK_LBRACE;
BlockBrace = false;
}
*/
PrevToken = n;
return n;
}
//---------------------------------------------------------------------------
void tTJSLexicalAnalyzer::SetStartOfRegExp(void)
{
// notifies that a regular expression ( regexp ) 's
// first '/' ( that indicates the start of the regexp ) had been detected.
// this will be called by the parser.
RegularExpression = true;
}
//---------------------------------------------------------------------------
void tTJSLexicalAnalyzer::SetNextIsBareWord(void)
{
// notifies that the next word must be treated as a bare word
// (not a reserved word)
// this will be called after . (dot) operator by the parser.
BareWord = true;
}
//---------------------------------------------------------------------------
} // namespace TJS
| 22.511699 | 99 | 0.550341 | [
"vector"
] |
106c1cc8060ae6a8cb44345bb4383e3253b317f0 | 37,437 | cpp | C++ | deps/libgdal/gdal/ogr/ogrsf_frmts/libkml/ogrlibkmlfeature.cpp | AmristarSolutions/node-gdal-next | 8c0a7d9b26c240bf04abbf1b1de312b0691b3d88 | [
"Apache-2.0"
] | 57 | 2020-02-08T17:52:17.000Z | 2021-10-14T03:45:09.000Z | deps/libgdal/gdal/ogr/ogrsf_frmts/libkml/ogrlibkmlfeature.cpp | AmristarSolutions/node-gdal-next | 8c0a7d9b26c240bf04abbf1b1de312b0691b3d88 | [
"Apache-2.0"
] | 47 | 2020-02-12T16:41:40.000Z | 2021-09-28T22:27:56.000Z | deps/libgdal/gdal/ogr/ogrsf_frmts/libkml/ogrlibkmlfeature.cpp | AmristarSolutions/node-gdal-next | 8c0a7d9b26c240bf04abbf1b1de312b0691b3d88 | [
"Apache-2.0"
] | 8 | 2020-03-17T11:18:07.000Z | 2021-10-14T03:45:15.000Z | /******************************************************************************
*
* Project: KML Translator
* Purpose: Implements OGRLIBKMLDriver
* Author: Brian Case, rush at winkey dot org
*
******************************************************************************
* Copyright (c) 2010, Brian Case
* Copyright (c) 2014, Even Rouault <even dot rouault at spatialys.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*****************************************************************************/
#include "libkml_headers.h"
#include "ogrlibkmlfeature.h"
#include "gdal.h"
#include "ogr_geometry.h"
#include "ogr_libkml.h"
#include "ogrlibkmlfield.h"
#include "ogrlibkmlfeaturestyle.h"
#include "ogrlibkmlgeometry.h"
#include "ogrsf_frmts.h"
CPL_CVSID("$Id: ogrlibkmlfeature.cpp 8ca42e1b9c2e54b75d35e49885df9789a2643aa4 2020-05-17 21:43:40 +0200 Even Rouault $")
using kmldom::AliasPtr;
using kmldom::CameraPtr;
using kmldom::ElementPtr;
using kmldom::FeaturePtr;
using kmldom::GeometryPtr;
using kmldom::GroundOverlayPtr;
using kmldom::IconPtr;
using kmldom::ImagePyramidPtr;
using kmldom::KmlFactory;
using kmldom::LinkPtr;
using kmldom::LocationPtr;
using kmldom::ModelPtr;
using kmldom::NetworkLinkPtr;
using kmldom::OrientationPtr;
using kmldom::PhotoOverlayPtr;
using kmldom::PlacemarkPtr;
using kmldom::ResourceMapPtr;
using kmldom::ScalePtr;
using kmldom::ViewVolumePtr;
static CameraPtr feat2kmlcamera( const struct fieldconfig& oFC,
int iHeading,
int iTilt,
int iRoll,
OGRFeature * poOgrFeat,
KmlFactory * poKmlFactory )
{
const int iCameraLongitudeField =
poOgrFeat->GetFieldIndex(oFC.camera_longitude_field);
const int iCameraLatitudeField =
poOgrFeat->GetFieldIndex(oFC.camera_latitude_field);
const int iCameraAltitudeField =
poOgrFeat->GetFieldIndex(oFC.camera_altitude_field);
const int iCameraAltitudeModeField =
poOgrFeat->GetFieldIndex(oFC.camera_altitudemode_field);
const bool bNeedCamera =
iCameraLongitudeField >= 0 &&
poOgrFeat->IsFieldSetAndNotNull(iCameraLongitudeField) &&
iCameraLatitudeField >= 0 &&
poOgrFeat->IsFieldSetAndNotNull(iCameraLatitudeField) &&
((iHeading >= 0 && poOgrFeat->IsFieldSetAndNotNull(iHeading)) ||
(iTilt >= 0 && poOgrFeat->IsFieldSetAndNotNull(iTilt)) ||
(iRoll >= 0 && poOgrFeat->IsFieldSetAndNotNull(iRoll)));
if( !bNeedCamera )
return nullptr;
CameraPtr const camera = poKmlFactory->CreateCamera();
camera->set_latitude(poOgrFeat->GetFieldAsDouble(iCameraLatitudeField));
camera->set_longitude(poOgrFeat->GetFieldAsDouble(iCameraLongitudeField));
int isGX = FALSE;
if( iCameraAltitudeModeField >= 0 &&
poOgrFeat->IsFieldSetAndNotNull(iCameraAltitudeModeField) )
{
const int nAltitudeMode = kmlAltitudeModeFromString(
poOgrFeat->GetFieldAsString(iCameraAltitudeModeField), isGX);
camera->set_altitudemode(nAltitudeMode);
}
else if( CPLTestBool(
CPLGetConfigOption("LIBKML_STRICT_COMPLIANCE", "TRUE")) )
{
CPLError(CE_Warning, CPLE_AppDefined,
"Camera should define altitudeMode != 'clampToGround'");
}
if( iCameraAltitudeField >= 0 &&
poOgrFeat->IsFieldSetAndNotNull(iCameraAltitudeField))
{
camera->set_altitude(poOgrFeat->GetFieldAsDouble(iCameraAltitudeField));
}
else if( CPLTestBool(
CPLGetConfigOption("LIBKML_STRICT_COMPLIANCE", "TRUE")) )
{
CPLError(CE_Warning, CPLE_AppDefined,
"Camera should have an altitude/Z");
camera->set_altitude(0.0);
}
if( iHeading >= 0 && poOgrFeat->IsFieldSetAndNotNull(iHeading) )
camera->set_heading(poOgrFeat->GetFieldAsDouble(iHeading));
if( iTilt >= 0 && poOgrFeat->IsFieldSetAndNotNull(iTilt) )
camera->set_tilt(poOgrFeat->GetFieldAsDouble(iTilt));
if( iRoll >= 0 && poOgrFeat->IsFieldSetAndNotNull(iRoll) )
camera->set_roll(poOgrFeat->GetFieldAsDouble(iRoll));
return camera;
}
/************************************************************************/
/* OGRLIBKMLReplaceXYLevelInURL() */
/************************************************************************/
static CPLString OGRLIBKMLReplaceLevelXYInURL( const char* pszURL,
int level, int x, int y )
{
CPLString osRet(pszURL);
size_t nPos = osRet.find("$[level]");
osRet =
osRet.substr(0, nPos) + CPLSPrintf("%d", level) +
osRet.substr(nPos + strlen("$[level]"));
nPos = osRet.find("$[x]");
osRet =
osRet.substr(0, nPos) + CPLSPrintf("%d", x) +
osRet.substr(nPos + strlen("$[x]"));
nPos = osRet.find("$[y]");
osRet =
osRet.substr(0, nPos) + CPLSPrintf("%d", y) +
osRet.substr(nPos + strlen("$[y]"));
return osRet;
}
/************************************************************************/
/* IsPowerOf2 */
/************************************************************************/
static bool IsPowerOf2( int nVal )
{
if( nVal < 1 ) return false;
const unsigned int nTmp = static_cast<unsigned int>(nVal);
return (nTmp & (nTmp - 1)) == 0;
}
/************************************************************************/
/* OGRLIBKMLGetMaxDimensions() */
/************************************************************************/
static void OGRLIBKMLGetMaxDimensions( const char* pszURL,
int nTileSize,
int* panMaxWidth,
int* panMaxHeight )
{
VSIStatBufL sStat;
int nMaxLevel = 0;
*panMaxWidth = 0;
*panMaxHeight = 0;
while( true )
{
CPLString osURL = OGRLIBKMLReplaceLevelXYInURL(pszURL, nMaxLevel, 0, 0);
if( strstr(osURL, ".kmz/") )
osURL = "/vsizip/" + osURL;
if( VSIStatL(osURL, &sStat) == 0 )
nMaxLevel++;
else
{
if( nMaxLevel == 0 )
return;
break;
}
}
nMaxLevel--;
{
int i = 0; // Used after for.
for( ; ; i++ )
{
CPLString osURL =
OGRLIBKMLReplaceLevelXYInURL(pszURL, nMaxLevel, i + 1, 0);
if( strstr(osURL, ".kmz/") )
osURL = "/vsizip/" + osURL;
if( VSIStatL(osURL, &sStat) != 0 )
break;
}
*panMaxWidth = (i + 1) * nTileSize;
}
int i = 0; // Used after for.
for( ; ; i++ )
{
CPLString osURL =
OGRLIBKMLReplaceLevelXYInURL(pszURL, nMaxLevel, 0, i + 1);
if( strstr(osURL, ".kmz/") )
osURL = "/vsizip/" + osURL;
if( VSIStatL(osURL, &sStat) != 0 )
break;
}
*panMaxHeight = (i + 1) * nTileSize;
}
/************************************************************************/
/* feat2kml() */
/************************************************************************/
FeaturePtr feat2kml(
OGRLIBKMLDataSource * poOgrDS,
OGRLayer * poOgrLayer,
OGRFeature * poOgrFeat,
KmlFactory * poKmlFactory,
int bUseSimpleField )
{
FeaturePtr poKmlFeature = nullptr;
struct fieldconfig oFC;
get_fieldconfig( &oFC );
/***** geometry *****/
OGRGeometry *poOgrGeom = poOgrFeat->GetGeometryRef();
const int iHeading = poOgrFeat->GetFieldIndex(oFC.headingfield);
const int iTilt = poOgrFeat->GetFieldIndex(oFC.tiltfield);
const int iRoll = poOgrFeat->GetFieldIndex(oFC.rollfield);
const int iModel = poOgrFeat->GetFieldIndex(oFC.modelfield);
const int iNetworkLink = poOgrFeat->GetFieldIndex(oFC.networklinkfield);
const int iPhotoOverlay = poOgrFeat->GetFieldIndex(oFC.photooverlayfield);
CameraPtr camera = nullptr;
// PhotoOverlay.
if( iPhotoOverlay >= 0 && poOgrFeat->IsFieldSetAndNotNull(iPhotoOverlay) &&
poOgrGeom != nullptr && !poOgrGeom->IsEmpty() &&
wkbFlatten(poOgrGeom->getGeometryType()) == wkbPoint &&
(camera = feat2kmlcamera(oFC, iHeading, iTilt, iRoll,
poOgrFeat, poKmlFactory)) )
{
const int iLeftFovField = poOgrFeat->GetFieldIndex(oFC.leftfovfield);
const int iRightFovField = poOgrFeat->GetFieldIndex(oFC.rightfovfield);
const int iBottomFovField =
poOgrFeat->GetFieldIndex(oFC.bottomfovfield);
const int iTopFovField = poOgrFeat->GetFieldIndex(oFC.topfovfield);
const int iNearField = poOgrFeat->GetFieldIndex(oFC.nearfield);
const char* pszURL = poOgrFeat->GetFieldAsString(iPhotoOverlay);
const int iImagePyramidTileSize =
poOgrFeat->GetFieldIndex(oFC.imagepyramid_tilesize_field);
const int iImagePyramidMaxWidth =
poOgrFeat->GetFieldIndex(oFC.imagepyramid_maxwidth_field);
const int iImagePyramidMaxHeight =
poOgrFeat->GetFieldIndex(oFC.imagepyramid_maxheight_field);
const int iImagePyramidGridOrigin =
poOgrFeat->GetFieldIndex(oFC.imagepyramid_gridorigin_field);
int nTileSize = 0;
int nMaxWidth = 0;
int nMaxHeight = 0;
bool bIsTiledPhotoOverlay = false;
bool bGridOriginIsUpperLeft = true;
// OGC KML Abstract Test Case (ATC) 52 and 62
if( strstr(pszURL, "$[x]") &&
strstr(pszURL, "$[y]") &&
strstr(pszURL, "$[level]") )
{
bIsTiledPhotoOverlay = true;
bool bErrorEmitted = false;
if( iImagePyramidTileSize < 0 ||
!poOgrFeat->IsFieldSetAndNotNull(iImagePyramidTileSize) )
{
CPLDebug("LIBKML",
"Missing ImagePyramid tileSize. Computing it");
CPLString osURL = OGRLIBKMLReplaceLevelXYInURL(pszURL, 0, 0, 0);
if( strstr(osURL, ".kmz/") )
osURL = "/vsizip/" + osURL;
GDALDatasetH hDS = GDALOpen( osURL, GA_ReadOnly );
if( hDS != nullptr )
{
nTileSize = GDALGetRasterXSize(hDS);
if( nTileSize != GDALGetRasterYSize(hDS) )
{
CPLError(
CE_Failure, CPLE_AppDefined,
"Non square tile : %dx%d",
GDALGetRasterXSize(hDS), GDALGetRasterYSize(hDS));
nTileSize = 0;
bErrorEmitted = true;
}
GDALClose(hDS);
}
else
{
CPLError(
CE_Failure, CPLE_AppDefined,
"Cannot open %s", osURL.c_str());
bErrorEmitted = true;
}
}
else
{
nTileSize = poOgrFeat->GetFieldAsInteger(iImagePyramidTileSize);
}
if( !bErrorEmitted && (nTileSize <= 1 || !IsPowerOf2(nTileSize)) )
{
CPLError(
CE_Failure, CPLE_AppDefined,
"Tile size is not a power of two: %d", nTileSize);
nTileSize = 0;
}
if( nTileSize > 0 )
{
if( iImagePyramidMaxWidth < 0 ||
!poOgrFeat->IsFieldSetAndNotNull(iImagePyramidMaxWidth) ||
iImagePyramidMaxHeight < 0 ||
!poOgrFeat->IsFieldSetAndNotNull(iImagePyramidMaxHeight) )
{
CPLDebug(
"LIBKML",
"Missing ImagePyramid maxWidth and/or maxHeight. "
"Computing it");
OGRLIBKMLGetMaxDimensions(pszURL, nTileSize,
&nMaxWidth, &nMaxHeight);
}
else
{
nMaxWidth =
poOgrFeat->GetFieldAsInteger(iImagePyramidMaxWidth);
nMaxHeight =
poOgrFeat->GetFieldAsInteger(iImagePyramidMaxHeight);
}
if( nTileSize <= 0 || nMaxWidth <= 0 || nMaxHeight <= 0)
{
CPLError(
CE_Failure, CPLE_AppDefined,
"Cannot generate PhotoOverlay object since there are "
"missing information to generate ImagePyramid element");
}
}
if( iImagePyramidGridOrigin >= 0 &&
poOgrFeat->IsFieldSetAndNotNull(iImagePyramidGridOrigin) )
{
const char* pszGridOrigin =
poOgrFeat->GetFieldAsString(iImagePyramidGridOrigin);
if( EQUAL(pszGridOrigin, "UpperLeft") )
{
bGridOriginIsUpperLeft = true;
}
else if( EQUAL(pszGridOrigin, "BottomLeft") )
{
bGridOriginIsUpperLeft = false;
}
else
{
CPLError(
CE_Failure, CPLE_AppDefined,
"Unhandled value for imagepyramid_gridorigin : %s. "
"Assuming UpperLeft",
pszGridOrigin);
}
}
}
else
{
if( (iImagePyramidTileSize >= 0 &&
poOgrFeat->IsFieldSetAndNotNull(iImagePyramidTileSize)) ||
(iImagePyramidMaxWidth >= 0 &&
poOgrFeat->IsFieldSetAndNotNull(iImagePyramidMaxWidth)) ||
(iImagePyramidMaxHeight >= 0 &&
poOgrFeat->IsFieldSetAndNotNull(iImagePyramidMaxHeight)) ||
(iImagePyramidGridOrigin >= 0 &&
poOgrFeat->IsFieldSetAndNotNull(iImagePyramidGridOrigin)) )
{
CPLError(
CE_Warning, CPLE_AppDefined,
"Ignoring any ImagePyramid information since the URL does "
"not include $[x] and/or $[y] and/or $[level]");
}
}
// OGC KML Abstract Test Case (ATC) 19 & 35.
double dfNear = 0.0;
if( (!bIsTiledPhotoOverlay ||
(nTileSize > 0 && nMaxWidth > 0 && nMaxHeight > 0)) &&
iLeftFovField >= 0 && poOgrFeat->IsFieldSetAndNotNull(iLeftFovField) &&
iRightFovField >= 0 && poOgrFeat->IsFieldSetAndNotNull(iRightFovField) &&
iBottomFovField >= 0 && poOgrFeat->IsFieldSetAndNotNull(iBottomFovField) &&
iTopFovField >= 0 && poOgrFeat->IsFieldSetAndNotNull(iTopFovField) &&
iNearField >= 0 &&
(dfNear = poOgrFeat->GetFieldAsDouble(iNearField)) > 0 )
{
const PhotoOverlayPtr poKmlPhotoOverlay =
poKmlFactory->CreatePhotoOverlay();
poKmlFeature = poKmlPhotoOverlay;
const IconPtr poKmlIcon = poKmlFactory->CreateIcon();
poKmlPhotoOverlay->set_icon(poKmlIcon);
poKmlIcon->set_href( pszURL );
const ViewVolumePtr poKmlViewVolume =
poKmlFactory->CreateViewVolume();
poKmlPhotoOverlay->set_viewvolume(poKmlViewVolume);
const double dfLeftFov = poOgrFeat->GetFieldAsDouble(iLeftFovField);
const double dfRightFov =
poOgrFeat->GetFieldAsDouble(iRightFovField);
const double dfBottomFov =
poOgrFeat->GetFieldAsDouble(iBottomFovField);
const double dfTopFov = poOgrFeat->GetFieldAsDouble(iTopFovField);
poKmlViewVolume->set_leftfov(dfLeftFov);
poKmlViewVolume->set_rightfov(dfRightFov);
poKmlViewVolume->set_bottomfov(dfBottomFov);
poKmlViewVolume->set_topfov(dfTopFov);
poKmlViewVolume->set_near(dfNear);
if( bIsTiledPhotoOverlay )
{
const ImagePyramidPtr poKmlImagePyramid =
poKmlFactory->CreateImagePyramid();
poKmlPhotoOverlay->set_imagepyramid(poKmlImagePyramid);
poKmlImagePyramid->set_tilesize(nTileSize);
poKmlImagePyramid->set_maxwidth(nMaxWidth);
poKmlImagePyramid->set_maxheight(nMaxHeight);
poKmlImagePyramid->set_gridorigin(
bGridOriginIsUpperLeft ?
kmldom::GRIDORIGIN_UPPERLEFT :
kmldom::GRIDORIGIN_LOWERLEFT );
}
const int iPhotoOverlayShapeField =
poOgrFeat->GetFieldIndex(oFC.photooverlay_shape_field);
if( iPhotoOverlayShapeField >= 0 &&
poOgrFeat->IsFieldSetAndNotNull(iPhotoOverlayShapeField) )
{
const char* pszShape =
poOgrFeat->GetFieldAsString(iPhotoOverlayShapeField);
if( EQUAL(pszShape, "rectangle") )
poKmlPhotoOverlay->set_shape(kmldom::SHAPE_RECTANGLE);
else if( EQUAL(pszShape, "cylinder") )
poKmlPhotoOverlay->set_shape(kmldom::SHAPE_CYLINDER);
else if( EQUAL(pszShape, "sphere") )
poKmlPhotoOverlay->set_shape(kmldom::SHAPE_SPHERE);
}
ElementPtr poKmlElement = geom2kml( poOgrGeom, -1, poKmlFactory );
poKmlPhotoOverlay->set_point( AsPoint( poKmlElement ) );
}
}
// NetworkLink.
if( !poKmlFeature && iNetworkLink >= 0 &&
poOgrFeat->IsFieldSetAndNotNull(iNetworkLink) )
{
const NetworkLinkPtr poKmlNetworkLink =
poKmlFactory->CreateNetworkLink();
poKmlFeature = poKmlNetworkLink;
const int iRefreshVisibility =
poOgrFeat->GetFieldIndex(oFC.networklink_refreshvisibility_field);
if( iRefreshVisibility >= 0 &&
poOgrFeat->IsFieldSetAndNotNull(iRefreshVisibility) )
{
poKmlNetworkLink->set_refreshvisibility(CPL_TO_BOOL(
poOgrFeat->GetFieldAsInteger(iRefreshVisibility)));
}
const int iFlyToView =
poOgrFeat->GetFieldIndex(oFC.networklink_flytoview_field);
if( iFlyToView >= 0 && poOgrFeat->IsFieldSetAndNotNull(iFlyToView) )
poKmlNetworkLink->set_flytoview(CPL_TO_BOOL(
poOgrFeat->GetFieldAsInteger(iFlyToView)));
const LinkPtr poKmlLink = poKmlFactory->CreateLink();
poKmlLink->set_href( poOgrFeat->GetFieldAsString( iNetworkLink ) );
poKmlNetworkLink->set_link(poKmlLink);
const int iRefreshMode =
poOgrFeat->GetFieldIndex(oFC.networklink_refreshMode_field);
const int iRefreshInterval =
poOgrFeat->GetFieldIndex(oFC.networklink_refreshInterval_field);
const int iViewRefreshMode =
poOgrFeat->GetFieldIndex(oFC.networklink_viewRefreshMode_field);
const int iViewRefreshTime =
poOgrFeat->GetFieldIndex(oFC.networklink_viewRefreshTime_field);
const int iViewBoundScale =
poOgrFeat->GetFieldIndex(oFC.networklink_viewBoundScale_field);
const int iViewFormat =
poOgrFeat->GetFieldIndex(oFC.networklink_viewFormat_field);
const int iHttpQuery =
poOgrFeat->GetFieldIndex(oFC.networklink_httpQuery_field);
double dfRefreshInterval = 0.0;
if( iRefreshInterval >= 0 && poOgrFeat->IsFieldSetAndNotNull(iRefreshInterval) )
{
dfRefreshInterval = poOgrFeat->GetFieldAsDouble(iRefreshInterval);
if( dfRefreshInterval < 0 )
dfRefreshInterval = 0.0;
}
double dfViewRefreshTime = 0.0;
if( iViewRefreshTime >= 0 && poOgrFeat->IsFieldSetAndNotNull(iViewRefreshTime) )
{
dfViewRefreshTime = poOgrFeat->GetFieldAsDouble(iViewRefreshTime);
if( dfViewRefreshTime < 0 )
dfViewRefreshTime = 0.0;
}
if( dfRefreshInterval > 0 ) // ATC 51
poKmlLink->set_refreshmode(kmldom::REFRESHMODE_ONINTERVAL);
else if( iRefreshMode >= 0 && poOgrFeat->IsFieldSetAndNotNull(iRefreshMode) )
{
const char * const pszRefreshMode =
poOgrFeat->GetFieldAsString(iRefreshMode);
if( EQUAL(pszRefreshMode, "onChange") )
poKmlLink->set_refreshmode(kmldom::REFRESHMODE_ONCHANGE);
else if( EQUAL(pszRefreshMode, "onInterval") )
poKmlLink->set_refreshmode(kmldom::REFRESHMODE_ONINTERVAL);
else if( EQUAL(pszRefreshMode, "onExpire") )
poKmlLink->set_refreshmode(kmldom::REFRESHMODE_ONEXPIRE);
}
if( dfRefreshInterval > 0 ) // ATC 9
poKmlLink->set_refreshinterval(dfRefreshInterval);
if( dfViewRefreshTime > 0 ) // ATC 51
poKmlLink->set_viewrefreshmode(kmldom::VIEWREFRESHMODE_ONSTOP);
else if( iViewRefreshMode >= 0 &&
poOgrFeat->IsFieldSetAndNotNull(iViewRefreshMode) )
{
const char * const pszViewRefreshMode =
poOgrFeat->GetFieldAsString(iViewRefreshMode);
if( EQUAL(pszViewRefreshMode, "never") )
poKmlLink->set_viewrefreshmode(kmldom::VIEWREFRESHMODE_NEVER);
else if( EQUAL(pszViewRefreshMode, "onRequest") )
poKmlLink->set_viewrefreshmode(
kmldom::VIEWREFRESHMODE_ONREQUEST);
else if( EQUAL(pszViewRefreshMode, "onStop") )
poKmlLink->set_viewrefreshmode(kmldom::VIEWREFRESHMODE_ONSTOP);
else if( EQUAL(pszViewRefreshMode, "onRegion") )
poKmlLink->set_viewrefreshmode(
kmldom::VIEWREFRESHMODE_ONREGION);
}
if( dfViewRefreshTime > 0 ) // ATC 9
poKmlLink->set_viewrefreshtime(dfViewRefreshTime);
if( iViewBoundScale >= 0 && poOgrFeat->IsFieldSetAndNotNull(iViewBoundScale) )
{
const double dfViewBoundScale =
poOgrFeat->GetFieldAsDouble(iViewBoundScale);
if( dfViewBoundScale > 0 ) // ATC 9
poKmlLink->set_viewboundscale(dfViewBoundScale);
}
if( iViewFormat >= 0 && poOgrFeat->IsFieldSetAndNotNull(iViewFormat) )
{
const char * const pszViewFormat =
poOgrFeat->GetFieldAsString(iViewFormat);
if( pszViewFormat[0] != '\0' ) // ATC 46
poKmlLink->set_viewformat(pszViewFormat);
}
if( iHttpQuery >= 0 && poOgrFeat->IsFieldSetAndNotNull(iHttpQuery) )
{
const char* const pszHttpQuery =
poOgrFeat->GetFieldAsString(iHttpQuery);
if( strstr(pszHttpQuery, "[clientVersion]") != nullptr ||
strstr(pszHttpQuery, "[kmlVersion]") != nullptr ||
strstr(pszHttpQuery, "[clientName]") != nullptr ||
strstr(pszHttpQuery, "[language]") != nullptr ) // ATC 47
{
poKmlLink->set_httpquery(pszHttpQuery);
}
}
}
// Model.
else if( !poKmlFeature &&
iModel >= 0 &&
poOgrFeat->IsFieldSetAndNotNull(iModel) &&
poOgrGeom != nullptr && !poOgrGeom->IsEmpty() &&
wkbFlatten(poOgrGeom->getGeometryType()) == wkbPoint )
{
const PlacemarkPtr poKmlPlacemark = poKmlFactory->CreatePlacemark();
poKmlFeature = poKmlPlacemark;
const OGRPoint* const poOgrPoint = poOgrGeom->toPoint();
ModelPtr model = poKmlFactory->CreateModel();
LocationPtr location = poKmlFactory->CreateLocation();
model->set_location(location);
location->set_latitude(poOgrPoint->getY());
location->set_longitude(poOgrPoint->getX());
if( poOgrPoint->getCoordinateDimension() == 3 )
location->set_altitude(poOgrPoint->getZ());
int isGX = FALSE;
const int iAltitudeMode =
poOgrFeat->GetFieldIndex(oFC.altitudeModefield);
if( poOgrFeat->IsFieldSetAndNotNull(iAltitudeMode) )
{
const int nAltitudeMode = kmlAltitudeModeFromString(
poOgrFeat->GetFieldAsString(iAltitudeMode), isGX);
model->set_altitudemode(nAltitudeMode);
// ATC 55
if( nAltitudeMode != kmldom::ALTITUDEMODE_CLAMPTOGROUND &&
poOgrPoint->getCoordinateDimension() != 3 )
{
if( CPLTestBool(
CPLGetConfigOption("LIBKML_STRICT_COMPLIANCE", "TRUE")) )
CPLError(CE_Warning, CPLE_AppDefined,
"Altitude should be defined");
}
}
if( (iHeading >= 0 && poOgrFeat->IsFieldSetAndNotNull(iHeading)) ||
(iTilt >= 0 && poOgrFeat->IsFieldSetAndNotNull(iTilt)) ||
(iRoll >= 0 && poOgrFeat->IsFieldSetAndNotNull(iRoll)) )
{
OrientationPtr const orientation =
poKmlFactory->CreateOrientation();
model->set_orientation(orientation);
if( iHeading >= 0 && poOgrFeat->IsFieldSetAndNotNull(iHeading) )
orientation->set_heading(poOgrFeat->GetFieldAsDouble(iHeading));
else
orientation->set_heading(0);
if( iTilt >= 0 && poOgrFeat->IsFieldSetAndNotNull(iTilt) )
orientation->set_tilt(poOgrFeat->GetFieldAsDouble(iTilt));
else
orientation->set_tilt(0);
if( iRoll >= 0 && poOgrFeat->IsFieldSetAndNotNull(iRoll) )
orientation->set_roll(poOgrFeat->GetFieldAsDouble(iRoll));
else
orientation->set_roll(0);
}
const int iScaleX = poOgrFeat->GetFieldIndex(oFC.scalexfield);
const int iScaleY = poOgrFeat->GetFieldIndex(oFC.scaleyfield);
const int iScaleZ = poOgrFeat->GetFieldIndex(oFC.scalezfield);
const ScalePtr scale = poKmlFactory->CreateScale();
model->set_scale(scale);
if( iScaleX >= 0 && poOgrFeat->IsFieldSetAndNotNull(iScaleX) )
scale->set_x(poOgrFeat->GetFieldAsDouble(iScaleX));
else
scale->set_x(1.0);
if( iScaleY >= 0 && poOgrFeat->IsFieldSetAndNotNull(iScaleY) )
scale->set_y(poOgrFeat->GetFieldAsDouble(iScaleY));
else
scale->set_y(1.0);
if( iScaleZ >= 0 && poOgrFeat->IsFieldSetAndNotNull(iScaleZ) )
scale->set_z(poOgrFeat->GetFieldAsDouble(iScaleZ));
else
scale->set_z(1.0);
const LinkPtr link = poKmlFactory->CreateLink();
model->set_link(link);
const char* const pszURL = poOgrFeat->GetFieldAsString(oFC.modelfield);
link->set_href( pszURL );
// Collada 3D file?
if( EQUAL(CPLGetExtension(pszURL), "dae") &&
CPLTestBool(CPLGetConfigOption("LIBKML_ADD_RESOURCE_MAP", "TRUE")) )
{
VSILFILE* fp = nullptr;
bool bIsURL = false;
if( STARTS_WITH_CI(pszURL, "http://") ||
STARTS_WITH_CI(pszURL, "https://") )
{
bIsURL = true;
fp = VSIFOpenL(CPLSPrintf("/vsicurl/%s", pszURL), "rb");
}
else if( strstr(pszURL, ".kmz/") != nullptr )
{
fp = VSIFOpenL(CPLSPrintf("/vsizip/%s", pszURL), "rb");
}
else
{
fp = VSIFOpenL(pszURL, "rb");
}
if( fp != nullptr )
{
ResourceMapPtr resourceMap = nullptr;
const char* pszLine = nullptr;
while( (pszLine = CPLReadLineL(fp)) != nullptr )
{
const char* pszInitFrom = strstr(pszLine, "<init_from>");
if( pszInitFrom )
{
pszInitFrom += strlen("<init_from>");
const char* const pszInitFromEnd =
strstr(pszInitFrom, "</init_from>");
if( pszInitFromEnd )
{
CPLString osImage(pszInitFrom);
osImage.resize(pszInitFromEnd - pszInitFrom);
const char* const pszExtension =
CPLGetExtension(osImage);
if( EQUAL(pszExtension, "jpg") ||
EQUAL(pszExtension, "jpeg") ||
EQUAL(pszExtension, "png") ||
EQUAL(pszExtension, "gif") )
{
if( !resourceMap )
resourceMap =
poKmlFactory->CreateResourceMap();
const AliasPtr alias =
poKmlFactory->CreateAlias();
if( bIsURL && CPLIsFilenameRelative(osImage) )
{
if( STARTS_WITH(pszURL, "http") )
alias->set_targethref(
CPLSPrintf(
"%s/%s", CPLGetPath(pszURL),
osImage.c_str()));
else
alias->set_targethref(CPLFormFilename(
CPLGetPath(pszURL), osImage, nullptr));
}
else
alias->set_targethref(osImage);
alias->set_sourcehref(osImage);
resourceMap->add_alias(alias);
}
}
}
}
if( resourceMap )
model->set_resourcemap(resourceMap);
VSIFCloseL(fp);
}
}
poKmlPlacemark->set_geometry( AsGeometry( model ) );
}
// Camera.
else if( !poKmlFeature && poOgrGeom != nullptr &&
!poOgrGeom->IsEmpty() &&
wkbFlatten(poOgrGeom->getGeometryType()) == wkbPoint &&
poOgrFeat->GetFieldIndex(oFC.camera_longitude_field) < 0 &&
((iHeading >= 0 && poOgrFeat->IsFieldSetAndNotNull(iHeading)) ||
(iTilt >= 0 && poOgrFeat->IsFieldSetAndNotNull(iTilt)) ||
(iRoll >= 0 && poOgrFeat->IsFieldSetAndNotNull(iRoll))) )
{
const PlacemarkPtr poKmlPlacemark = poKmlFactory->CreatePlacemark();
poKmlFeature = poKmlPlacemark;
const OGRPoint* const poOgrPoint = poOgrGeom->toPoint();
camera = poKmlFactory->CreateCamera();
camera->set_latitude(poOgrPoint->getY());
camera->set_longitude(poOgrPoint->getX());
int isGX = FALSE;
const int iAltitudeMode =
poOgrFeat->GetFieldIndex(oFC.altitudeModefield);
if( poOgrFeat->IsFieldSetAndNotNull(iAltitudeMode) )
{
const int nAltitudeMode = kmlAltitudeModeFromString(
poOgrFeat->GetFieldAsString(iAltitudeMode), isGX);
camera->set_altitudemode(nAltitudeMode);
}
else if( CPLTestBool(
CPLGetConfigOption("LIBKML_STRICT_COMPLIANCE", "TRUE")) )
{
CPLError(CE_Warning, CPLE_AppDefined,
"Camera should define altitudeMode != 'clampToGround'");
}
if( poOgrPoint->getCoordinateDimension() == 3 )
{
camera->set_altitude(poOgrPoint->getZ());
}
else if( CPLTestBool(
CPLGetConfigOption("LIBKML_STRICT_COMPLIANCE", "TRUE")) )
{
CPLError(CE_Warning, CPLE_AppDefined,
"Camera should have an altitude/Z");
camera->set_altitude(0.0);
}
if( iHeading >= 0 && poOgrFeat->IsFieldSetAndNotNull(iHeading) )
camera->set_heading(poOgrFeat->GetFieldAsDouble(iHeading));
if( iTilt >= 0 && poOgrFeat->IsFieldSetAndNotNull(iTilt) )
camera->set_tilt(poOgrFeat->GetFieldAsDouble(iTilt));
if( iRoll >= 0 && poOgrFeat->IsFieldSetAndNotNull(iRoll) )
camera->set_roll(poOgrFeat->GetFieldAsDouble(iRoll));
poKmlPlacemark->set_abstractview(camera);
}
else if( !poKmlFeature )
{
const PlacemarkPtr poKmlPlacemark = poKmlFactory->CreatePlacemark();
poKmlFeature = poKmlPlacemark;
ElementPtr poKmlElement = geom2kml( poOgrGeom, -1, poKmlFactory );
poKmlPlacemark->set_geometry( AsGeometry( poKmlElement ) );
}
if( !camera )
camera = feat2kmlcamera(oFC, iHeading, iTilt, iRoll,
poOgrFeat, poKmlFactory);
if( camera )
poKmlFeature->set_abstractview(camera);
/***** style *****/
featurestyle2kml( poOgrDS, poOgrLayer, poOgrFeat, poKmlFactory,
poKmlFeature );
/***** fields *****/
OGRLIBKMLLayer * const poKmlLayer =
dynamic_cast<OGRLIBKMLLayer *>(poOgrLayer);
if( poKmlLayer == nullptr )
{
CPLError(CE_Failure, CPLE_AppDefined, "dynamic_cast failed.");
return nullptr;
}
field2kml( poOgrFeat, poKmlLayer, poKmlFactory,
poKmlFeature, bUseSimpleField );
return poKmlFeature;
}
OGRFeature *kml2feat(
PlacemarkPtr poKmlPlacemark,
OGRLIBKMLDataSource * poOgrDS,
OGRLayer * poOgrLayer,
OGRFeatureDefn * poOgrFeatDefn,
OGRSpatialReference *poOgrSRS )
{
OGRFeature *poOgrFeat = new OGRFeature( poOgrFeatDefn );
/***** style *****/
kml2featurestyle( poKmlPlacemark, poOgrDS, poOgrLayer, poOgrFeat );
/***** geometry *****/
if( poKmlPlacemark->has_geometry() )
{
OGRGeometry * const poOgrGeom =
kml2geom( poKmlPlacemark->get_geometry(), poOgrSRS );
poOgrFeat->SetGeometryDirectly( poOgrGeom );
}
else if( poKmlPlacemark->has_abstractview() &&
poKmlPlacemark->get_abstractview()->IsA( kmldom::Type_Camera) )
{
const CameraPtr& camera = AsCamera(poKmlPlacemark->get_abstractview());
if( camera->has_longitude() && camera->has_latitude() )
{
if( camera->has_altitude() )
poOgrFeat->SetGeometryDirectly(
new OGRPoint( camera->get_longitude(),
camera->get_latitude(),
camera->get_altitude() ) );
else
poOgrFeat->SetGeometryDirectly(
new OGRPoint( camera->get_longitude(),
camera->get_latitude() ) );
poOgrFeat->GetGeometryRef()->assignSpatialReference( poOgrSRS );
}
}
/***** fields *****/
kml2field( poOgrFeat, AsFeature( poKmlPlacemark ) );
return poOgrFeat;
}
OGRFeature *kmlgroundoverlay2feat(
GroundOverlayPtr poKmlOverlay,
OGRLIBKMLDataSource * /* poOgrDS */,
OGRLayer * /* poOgrLayer */,
OGRFeatureDefn * poOgrFeatDefn,
OGRSpatialReference *poOgrSRS)
{
OGRFeature *poOgrFeat = new OGRFeature( poOgrFeatDefn );
/***** geometry *****/
if( poKmlOverlay->has_latlonbox() )
{
OGRGeometry * const poOgrGeom =
kml2geom_latlonbox( poKmlOverlay->get_latlonbox(), poOgrSRS );
poOgrFeat->SetGeometryDirectly( poOgrGeom );
}
else if( poKmlOverlay->has_gx_latlonquad() )
{
OGRGeometry * const poOgrGeom =
kml2geom_latlonquad( poKmlOverlay->get_gx_latlonquad(), poOgrSRS );
poOgrFeat->SetGeometryDirectly( poOgrGeom );
}
/***** fields *****/
kml2field( poOgrFeat, AsFeature( poKmlOverlay ) );
return poOgrFeat;
}
| 40.472432 | 120 | 0.554532 | [
"geometry",
"object",
"model",
"3d"
] |
106de21eb105b36886444a605c0e241bd18b9e6e | 7,893 | cpp | C++ | src/environment.cpp | chadbramwell/librealsense | f7cdf6e8961e1709f6d864bdb33095c00a671ca7 | [
"Apache-2.0"
] | 6 | 2020-02-26T08:15:27.000Z | 2022-01-28T14:17:46.000Z | src/environment.cpp | chadbramwell/librealsense | f7cdf6e8961e1709f6d864bdb33095c00a671ca7 | [
"Apache-2.0"
] | 8 | 2020-01-08T04:01:48.000Z | 2022-02-15T16:17:06.000Z | src/environment.cpp | chadbramwell/librealsense | f7cdf6e8961e1709f6d864bdb33095c00a671ca7 | [
"Apache-2.0"
] | 4 | 2020-07-03T08:33:31.000Z | 2021-12-14T07:51:21.000Z | // License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2015 Intel Corporation. All Rights Reserved.
#include "environment.h"
namespace librealsense
{
extrinsics_graph::extrinsics_graph()
: _locks_count(0)
{
_id = std::make_shared<lazy<rs2_extrinsics>>([]()
{
return identity_matrix();
});
}
extrinsics_graph::extrinsics_lock extrinsics_graph::lock()
{
extrinsics_lock l(*this);
return l;
}
void extrinsics_graph::register_same_extrinsics(const stream_interface& from, const stream_interface& to)
{
register_extrinsics(from, to, _id);
}
void extrinsics_graph::register_extrinsics(const stream_interface& from, const stream_interface& to, std::weak_ptr<lazy<rs2_extrinsics>> extr)
{
std::lock_guard<std::mutex> lock(_mutex);
// First, trim any dead stream, to make sure we are not keep gaining memory
cleanup_extrinsics();
// Second, register new extrinsics
auto from_idx = find_stream_profile(from);
// If this is a new index, add it to the map preemptively,
// This way find on to will be able to return another new index
if (_extrinsics.find(from_idx) == _extrinsics.end())
_extrinsics.insert({from_idx, {}});
auto to_idx = find_stream_profile(to);
_extrinsics[from_idx][to_idx] = extr;
_extrinsics[to_idx][from_idx] = std::shared_ptr<lazy<rs2_extrinsics>>(nullptr);
}
void extrinsics_graph::register_extrinsics(const stream_interface & from, const stream_interface & to, rs2_extrinsics extr)
{
auto lazy_extr = std::make_shared<lazy<rs2_extrinsics>>([=]() {return extr; });
_external_extrinsics.push_back(lazy_extr);
register_extrinsics(from, to, lazy_extr);
}
void extrinsics_graph::override_extrinsics( const stream_interface& from, const stream_interface& to, rs2_extrinsics const & extr )
{
std::lock_guard<std::mutex> lock( _mutex );
// First, trim any dead stream, to make sure we are not keep gaining memory
cleanup_extrinsics();
// The extrinsics must already exist!
auto from_idx = find_stream_profile( from, false ); // do not add if not there
auto from_it = _extrinsics.find( from_idx );
if( from_it == _extrinsics.end() )
throw std::runtime_error( "override_extrinsics called for invalid <from> stream" );
auto& from_map = from_it->second;
auto to_idx = find_stream_profile( to, false ); // do not add if not there
auto to_it = from_map.find( to_idx );
if( to_it == from_map.end() )
throw std::runtime_error( "override_extrinsics called for invalid <to> stream" );
auto& weak_ptr = to_it->second;
auto sp = weak_ptr.lock();
if( !sp )
throw std::runtime_error( "override_extrinsics called for out-of-date stream" );
auto & lazy_extr = *sp;
lazy_extr = [=]() { return extr; };
}
void extrinsics_graph::cleanup_extrinsics()
{
if (_locks_count.load()) return;
auto counter = 0;
std::vector<int> invalid_ids;
for (auto&& kvp : _streams)
{
if (!kvp.second.lock())
{
auto invalid_id = kvp.first;
// Delete all extrinsics going out of this stream
_extrinsics.erase(invalid_id);
++counter;
invalid_ids.push_back(invalid_id);
}
}
for (auto removed_id : invalid_ids)
{
_streams.erase(removed_id);
for (auto&& elem : _extrinsics)
{
// Delete any extrinsics going into the stream
elem.second.erase(removed_id);
++counter;
}
}
if (!invalid_ids.empty())
LOG_INFO("Found " << invalid_ids.size() << " unreachable streams, " << std::dec << counter << " extrinsics deleted");
}
int extrinsics_graph::find_stream_profile(const stream_interface& p, bool add_if_not_there)
{
auto sp = p.shared_from_this();
auto max = 0;
for (auto&& kvp : _streams)
{
if (kvp.second.lock().get() == sp.get())
return kvp.first;
max = std::max( max, kvp.first );
}
if( !add_if_not_there )
return -1;
_streams[max + 1] = sp;
return max + 1;
}
bool extrinsics_graph::try_fetch_extrinsics(const stream_interface& from, const stream_interface& to, rs2_extrinsics* extr)
{
std::lock_guard<std::mutex> lock(_mutex);
cleanup_extrinsics();
auto from_idx = find_stream_profile(from);
auto to_idx = find_stream_profile(to);
if (from_idx == to_idx)
{
*extr = identity_matrix();
return true;
}
std::set<int> visited;
return try_fetch_extrinsics(from_idx, to_idx, visited, extr);
}
bool extrinsics_graph::try_fetch_extrinsics(int from, int to, std::set<int>& visited, rs2_extrinsics* extr)
{
if (visited.count(from)) return false;
auto it = _extrinsics.find(from);
if (it != _extrinsics.end())
{
auto back_edge = fetch_edge(to, from);
auto fwd_edge = fetch_edge(from, to);
// Make sure both parts of the edge are still available
if (fwd_edge.get() || back_edge.get())
{
if (fwd_edge.get())
*extr = fwd_edge->operator*(); // Evaluate the expression
else
*extr = inverse(back_edge->operator*());
return true;
}
else
{
visited.insert(from);
for (auto&& kvp : it->second)
{
auto new_from = kvp.first;
auto way = kvp.second;
// Lock down the edge in both directions to ensure we can evaluate the extrinsics
back_edge = fetch_edge(new_from, from);
fwd_edge = fetch_edge(from, new_from);
if ((back_edge.get() || fwd_edge.get()) &&
try_fetch_extrinsics(new_from, to, visited, extr))
{
const auto local = [&]() {
if (fwd_edge.get())
return fwd_edge->operator*(); // Evaluate the expression
else
return inverse(back_edge->operator*());
}();
auto pose = to_pose(*extr) * to_pose(local);
*extr = from_pose(pose);
return true;
}
}
}
} // If there are no extrinsics from from, there are none to it, so it is completely isolated
return false;
}
std::shared_ptr<lazy<rs2_extrinsics>> extrinsics_graph::fetch_edge(int from, int to)
{
auto it = _extrinsics.find(from);
if (it != _extrinsics.end())
{
auto it2 = it->second.find(to);
if (it2 != it->second.end())
{
return it2->second.lock();
}
}
return nullptr;
}
environment& environment::get_instance()
{
static environment env;
return env;
}
extrinsics_graph& environment::get_extrinsics_graph()
{
return _extrinsics;
}
void environment::set_time_service(std::shared_ptr<platform::time_service> ts)
{
_ts = ts;
}
std::shared_ptr<platform::time_service> environment::get_time_service()
{
return _ts;
}
}
| 33.163866 | 146 | 0.554795 | [
"vector"
] |
1071bba238380fb82cf143d13d0cb09feda0b3f2 | 1,561 | cpp | C++ | Codeforces/1203B - Equal Rectangles.cpp | naimulcsx/online-judge-solutions | 0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f | [
"MIT"
] | null | null | null | Codeforces/1203B - Equal Rectangles.cpp | naimulcsx/online-judge-solutions | 0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f | [
"MIT"
] | null | null | null | Codeforces/1203B - Equal Rectangles.cpp | naimulcsx/online-judge-solutions | 0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int cnt[10010];
bool used[10010];
int main() {
ios::sync_with_stdio(false);
int q;
cin >> q;
while(q--) {
int n;
cin >> n;
memset(cnt, 0, sizeof(cnt));
int mn = 1e4 + 10, mx = 0;
for (int i = 0; i < 4 * n; ++i) {
int p;
cin >> p;
cnt[p]++;
mn = min(mn, p);
mx = max(mx,p);
}
int prod = mx * mn;
vector<pair<int, int>> divp;
for (int i = 1; i * i <= prod; ++i) {
if (prod % i == 0) divp.push_back({i, prod / i});
}
bool flag = true;
for (auto el: divp) {
if (el.first > 1e4 || el.second > 1e4) continue;
if (el.first != el.second) {
if (cnt[el.first] == cnt[el.second] && cnt[el.first] % 2 == 0 && cnt[el.second] % 2 == 0) {
used[el.first] = 1;
used[el.second] = 1;
continue;
}
flag = false;
break;
} else {
if ( cnt[el.first] % 2 == 0 && (cnt[el.first] / 2) % 2 == 0 ) {
used[el.first] = 1;
continue;
}
flag = false;
break;
}
}
for (int i = 1; i <= 1e4; ++i)
if (cnt[i] > 0 && !used[i]) flag = false;
if (flag) cout << "YES" << endl;
else cout << "NO" << endl;
}
return 0;
}
| 24.390625 | 107 | 0.358104 | [
"vector"
] |
1073a957d83325347a014bb2da11aacb591f04cf | 5,293 | cpp | C++ | src/rpcdarksend.cpp | nexalt-project/nexalt-core | e0c2f3f8ee0eb3ab298dfbbdb1e9d5426c65670f | [
"MIT"
] | 7 | 2021-01-30T11:20:46.000Z | 2021-12-04T02:21:19.000Z | src/rpcdarksend.cpp | nexalt-project/nexalt-core | e0c2f3f8ee0eb3ab298dfbbdb1e9d5426c65670f | [
"MIT"
] | null | null | null | src/rpcdarksend.cpp | nexalt-project/nexalt-core | e0c2f3f8ee0eb3ab298dfbbdb1e9d5426c65670f | [
"MIT"
] | 7 | 2021-01-17T11:48:40.000Z | 2021-05-10T12:15:00.000Z | // Copyright (c) 2012-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2018 The Luxcore developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
//#include "main.h"
#include "primitives/transaction.h"
#include "db.h"
#include "init.h"
#include "masternode.h"
#include "activemasternode.h"
#include "masternodeconfig.h"
#include "rpc/server.h"
#include <boost/lexical_cast.hpp>
//#include "amount.h"
#include "rpc/util.h"
#include "util/moneystr.h"
#include "validation.h"
#include <consensus/validation.h>
#include <boost/tokenizer.hpp>
#include <fstream>
#include "key_io.h"
#include "net.h"
#include "wallet/rpcwallet.h"
#include <wallet/coincontrol.h>
void SendMoney(const CTxDestination& address, CAmount nValue, CWalletTx& wtxNew, AvailableCoinsType coin_type) {
// Check amount
std::string wallet_name = "";
std::shared_ptr <CWallet> wallet = GetWallet(wallet_name);
CWallet *const pwallet = wallet.get();
if (nValue <= 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid amount");
if (nValue > pwallet->GetBalance())
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds");
string strError;
if (pwallet->IsLocked()) {
strError = "Error: Wallet locked, unable to create transaction!";
LogPrintf("SendMoney() : %s", strError);
throw JSONRPCError(RPC_WALLET_ERROR, strError);
}
// Parse Nexalt address
CScript scriptPubKey = GetScriptForDestination(address);
// Create and send the transaction
CReserveKey reservekey(pwallet);
CCoinControl coinControl;
CAmount nFeeRequired;
std::vector<CRecipient> vecSend;
CRecipient recipient = {scriptPubKey, nValue, false};
vecSend.push_back(recipient);
int nChangePos;
auto locked_chain = pwallet->chain().lock();
LOCK(pwallet->cs_wallet);
if (!pwallet->CreateTransaction(*locked_chain,vecSend, wtxNew.tx, reservekey, nFeeRequired, nChangePos, strError, coinControl/*NULL, coin_type*/)) {
if (nValue + nFeeRequired > pwallet->GetBalance())
strError = strprintf("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!", FormatMoney(nFeeRequired));
LogPrintf("SendMoney() : %s\n", strError);
throw JSONRPCError(RPC_WALLET_ERROR, strError);
}
CValidationState state;
if (!pwallet->CommitTransaction(wtxNew.tx,{},{}, reservekey,g_connman.get(),state)){
throw JSONRPCError(RPC_WALLET_ERROR,
"Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.");
}
}
UniValue darksend(const UniValue& params, bool fHelp) {
std::string wallet_name = "";
std::shared_ptr <CWallet> wallet = GetWallet(wallet_name);
CWallet *const pwallet = wallet.get();
if (fHelp || params.size() == 0)
throw runtime_error(
"darksend <Luxaddress> <amount>\n"
"Luxaddress, reset, or auto (AutoDenominate)"
"<amount> is a real and is rounded to the nearest 0.00000001"
+ HelpRequiringPassphrase(pwallet));
if (pwallet->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
if (params[0].get_str() == "auto") {
if (fMasterNode)
return "DarkSend is not supported from masternodes";
darkSendPool.DoAutomaticDenominating();
return "DoAutomaticDenominating";
}
if (params[0].get_str() == "reset") {
darkSendPool.SetNull(true);
darkSendPool.UnlockCoins();
return "successfully reset darksend";
}
if (params.size() != 2)
throw runtime_error(
"darksend <Luxaddress> <amount>\n"
"Luxaddress, denominate, or auto (AutoDenominate)"
"<amount> is a real and is rounded to the nearest 0.00000001"
+ HelpRequiringPassphrase(pwallet));
CTxDestination dest = DecodeDestination(params[0].get_str());
if (!IsValidDestination(dest))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Nexalt address");
// Amount
int64_t nAmount = AmountFromValue(params[1]);
// Wallet comments
CTransactionRef txRef;
const CTransaction& tx = *txRef;
CWalletTx wtx(pwallet,txRef) ;
SendMoney(dest, nAmount, wtx, ONLY_DENOMINATED);
return wtx.GetHash().GetHex();
}
UniValue getpoolinfo(const UniValue& params, bool fHelp) {
if (fHelp || params.size() != 0)
throw runtime_error(
"getpoolinfo\n"
"Returns an object containing anonymous pool-related information.");
UniValue obj(UniValue::VOBJ);
obj.pushKV("current_masternode", GetCurrentMasterNode());
obj.pushKV("state", darkSendPool.GetState());
obj.pushKV("entries", darkSendPool.GetEntriesCount());
obj.pushKV("entries_accepted", darkSendPool.GetCountEntriesAccepted());
return obj;
} | 37.274648 | 245 | 0.679766 | [
"object",
"vector"
] |
107537b9be4659fe7722d9591385a0444dda2344 | 19,484 | cxx | C++ | Interaction/Widgets/Testing/Cxx/TestSeedWidget.cxx | michaelchanwahyan/vtk-7.0.0 | 770166bbe1f28a99d776b47624c6f6955b9aaaec | [
"BSD-3-Clause"
] | 1 | 2019-04-22T09:09:17.000Z | 2019-04-22T09:09:17.000Z | Interaction/Widgets/Testing/Cxx/TestSeedWidget.cxx | michaelchanwahyan/vtk-7.0.0 | 770166bbe1f28a99d776b47624c6f6955b9aaaec | [
"BSD-3-Clause"
] | null | null | null | Interaction/Widgets/Testing/Cxx/TestSeedWidget.cxx | michaelchanwahyan/vtk-7.0.0 | 770166bbe1f28a99d776b47624c6f6955b9aaaec | [
"BSD-3-Clause"
] | 1 | 2019-08-30T08:41:21.000Z | 2019-08-30T08:41:21.000Z | /*=========================================================================
Program: Visualization Toolkit
Module: TestSeedWidget.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
//
// This example tests the vtkSeedWidget
// First include the required header files for the VTK classes we are using.
#include "vtkActor.h"
#include "vtkAxisActor2D.h"
#include "vtkCommand.h"
#include "vtkCoordinate.h"
#include "vtkDebugLeaks.h"
#include "vtkHandleWidget.h"
#include "vtkInteractorStyleTrackballCamera.h"
#include "vtkMath.h"
#include "vtkPointHandleRepresentation2D.h"
#include "vtkPolyDataMapper.h"
#include "vtkProperty2D.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkSeedRepresentation.h"
#include "vtkSeedWidget.h"
#include "vtkSmartPointer.h"
#include "vtkSphereSource.h"
#include "vtkTesting.h"
const char TestSeedWidgetEventLog[] =
"# StreamVersion 1 i\n"
"CharEvent 185 179 0 0 105 1 i\n"
"KeyReleaseEvent 185 179 0 0 105 1 i\n"
"MouseMoveEvent 138 180 0 0 0 0 0 i\n"
"MouseMoveEvent 137 180 0 0 0 0 0 i\n"
"MouseMoveEvent 136 180 0 0 0 0 0 i\n"
"MouseMoveEvent 135 180 0 0 0 0 0 i\n"
"MouseMoveEvent 134 180 0 0 0 0 0 i\n"
"MouseMoveEvent 133 180 0 0 0 0 0 i\n"
"MouseMoveEvent 132 180 0 0 0 0 0 i\n"
"MouseMoveEvent 131 180 0 0 0 0 0 i\n"
"MouseMoveEvent 130 180 0 0 0 0 0 i\n"
"MouseMoveEvent 129 181 0 0 0 0 0 i\n"
"MouseMoveEvent 128 181 0 0 0 0 0 i\n"
"MouseMoveEvent 127 181 0 0 0 0 0 i\n"
"LeftButtonPressEvent 127 181 0 0 0 0 0 i\n"
"RenderEvent 127 181 0 0 0 0 0 i\n"
"MouseMoveEvent 124 181 0 0 0 0 0 i\n"
"RenderEvent 124 181 0 0 0 0 0 i\n"
"LeftButtonReleaseEvent 126 181 0 0 0 0 0 i\n"
"MouseMoveEvent 124 181 0 0 0 0 0 i\n"
"RenderEvent 124 181 0 0 0 0 0 i\n"
"MouseMoveEvent 96 144 0 0 0 0 0 i\n"
"RenderEvent 96 144 0 0 0 0 0 i\n"
"MouseMoveEvent 96 143 0 0 0 0 0 i\n"
"RenderEvent 96 143 0 0 0 0 0 i\n"
"MouseMoveEvent 96 142 0 0 0 0 0 i\n"
"RenderEvent 96 142 0 0 0 0 0 i\n"
"MouseMoveEvent 96 141 0 0 0 0 0 i\n"
"RenderEvent 96 141 0 0 0 0 0 i\n"
"MouseMoveEvent 96 140 0 0 0 0 0 i\n"
"RenderEvent 96 140 0 0 0 0 0 i\n"
"MouseMoveEvent 96 139 0 0 0 0 0 i\n"
"RenderEvent 96 139 0 0 0 0 0 i\n"
"MouseMoveEvent 96 138 0 0 0 0 0 i\n"
"RenderEvent 96 138 0 0 0 0 0 i\n"
"LeftButtonPressEvent 96 138 0 0 0 0 0 i\n"
"RenderEvent 96 138 0 0 0 0 0 i\n"
"LeftButtonReleaseEvent 96 138 0 0 0 0 0 i\n"
"MouseMoveEvent 96 137 0 0 0 0 0 i\n"
"RenderEvent 96 137 0 0 0 0 0 i\n"
"MouseMoveEvent 97 137 0 0 0 0 0 i\n"
"RenderEvent 97 137 0 0 0 0 0 i\n"
"MouseMoveEvent 164 113 0 0 0 0 t i\n"
"RenderEvent 164 113 0 0 0 0 t i\n"
"MouseMoveEvent 163 113 0 0 0 0 t i\n"
"RenderEvent 163 113 0 0 0 0 t i\n"
"MouseMoveEvent 162 113 0 0 0 0 t i\n"
"RenderEvent 162 113 0 0 0 0 t i\n"
"MouseMoveEvent 161 113 0 0 0 0 t i\n"
"RenderEvent 161 113 0 0 0 0 t i\n"
"MouseMoveEvent 161 114 0 0 0 0 t i\n"
"RenderEvent 161 114 0 0 0 0 t i\n"
"LeftButtonPressEvent 161 114 0 0 0 0 t i\n"
"RenderEvent 161 114 0 0 0 0 t i\n"
"LeftButtonReleaseEvent 161 114 0 0 0 0 t i\n"
"MouseMoveEvent 161 115 0 0 0 0 t i\n"
"RenderEvent 161 115 0 0 0 0 t i\n"
"MouseMoveEvent 161 116 0 0 0 0 t i\n"
"RenderEvent 161 116 0 0 0 0 t i\n"
"MouseMoveEvent 161 117 0 0 0 0 t i\n"
"RenderEvent 161 117 0 0 0 0 t i\n"
"MouseMoveEvent 185 158 0 0 0 0 t i\n"
"RenderEvent 185 158 0 0 0 0 t i\n"
"MouseMoveEvent 185 159 0 0 0 0 t i\n"
"RenderEvent 185 159 0 0 0 0 t i\n"
"MouseMoveEvent 186 159 0 0 0 0 t i\n"
"RenderEvent 186 159 0 0 0 0 t i\n"
"LeftButtonPressEvent 186 159 0 0 0 0 t i\n"
"RenderEvent 186 159 0 0 0 0 t i\n"
"LeftButtonReleaseEvent 186 159 0 0 0 0 t i\n"
"MouseMoveEvent 185 159 0 0 0 0 t i\n"
"RenderEvent 185 159 0 0 0 0 t i\n"
"MouseMoveEvent 184 159 0 0 0 0 t i\n"
"RenderEvent 184 159 0 0 0 0 t i\n"
"MouseMoveEvent 183 159 0 0 0 0 t i\n"
"RenderEvent 183 159 0 0 0 0 t i\n"
"MouseMoveEvent 182 159 0 0 0 0 t i\n"
"RenderEvent 182 159 0 0 0 0 t i\n"
"MouseMoveEvent 181 160 0 0 0 0 t i\n"
"RenderEvent 181 160 0 0 0 0 t i\n"
"MouseMoveEvent 131 176 0 0 0 0 t i\n"
"RenderEvent 131 176 0 0 0 0 t i\n"
"MouseMoveEvent 130 176 0 0 0 0 t i\n"
"RenderEvent 130 176 0 0 0 0 t i\n"
"MouseMoveEvent 130 177 0 0 0 0 t i\n"
"RenderEvent 130 177 0 0 0 0 t i\n"
"MouseMoveEvent 129 177 0 0 0 0 t i\n"
"RenderEvent 129 177 0 0 0 0 t i\n"
"MouseMoveEvent 128 177 0 0 0 0 t i\n"
"RenderEvent 128 177 0 0 0 0 t i\n"
"MouseMoveEvent 128 178 0 0 0 0 t i\n"
"RenderEvent 128 178 0 0 0 0 t i\n"
"MouseMoveEvent 127 179 0 0 0 0 t i\n"
"RenderEvent 127 179 0 0 0 0 t i\n"
"MouseMoveEvent 127 180 0 0 0 0 t i\n"
"RenderEvent 127 180 0 0 0 0 t i\n"
"LeftButtonPressEvent 127 180 0 0 0 0 t i\n"
"RenderEvent 127 180 0 0 0 0 t i\n"
"MouseMoveEvent 127 179 0 0 0 0 t i\n"
"RenderEvent 127 179 0 0 0 0 t i\n"
"MouseMoveEvent 128 178 0 0 0 0 t i\n"
"RenderEvent 128 178 0 0 0 0 t i\n"
"MouseMoveEvent 129 177 0 0 0 0 t i\n"
"RenderEvent 129 177 0 0 0 0 t i\n"
"MouseMoveEvent 129 176 0 0 0 0 t i\n"
"RenderEvent 129 176 0 0 0 0 t i\n"
"MouseMoveEvent 130 175 0 0 0 0 t i\n"
"RenderEvent 130 175 0 0 0 0 t i\n"
"MouseMoveEvent 131 173 0 0 0 0 t i\n"
"RenderEvent 131 173 0 0 0 0 t i\n"
"MouseMoveEvent 132 172 0 0 0 0 t i\n"
"RenderEvent 132 172 0 0 0 0 t i\n"
"MouseMoveEvent 133 171 0 0 0 0 t i\n"
"RenderEvent 133 171 0 0 0 0 t i\n"
"MouseMoveEvent 137 167 0 0 0 0 t i\n"
"RenderEvent 137 167 0 0 0 0 t i\n"
"MouseMoveEvent 138 166 0 0 0 0 t i\n"
"RenderEvent 138 166 0 0 0 0 t i\n"
"MouseMoveEvent 138 164 0 0 0 0 t i\n"
"RenderEvent 138 164 0 0 0 0 t i\n"
"MouseMoveEvent 140 163 0 0 0 0 t i\n"
"RenderEvent 140 163 0 0 0 0 t i\n"
"MouseMoveEvent 140 162 0 0 0 0 t i\n"
"RenderEvent 140 162 0 0 0 0 t i\n"
"MouseMoveEvent 141 161 0 0 0 0 t i\n"
"RenderEvent 141 161 0 0 0 0 t i\n"
"MouseMoveEvent 142 160 0 0 0 0 t i\n"
"RenderEvent 142 160 0 0 0 0 t i\n"
"MouseMoveEvent 143 159 0 0 0 0 t i\n"
"RenderEvent 143 159 0 0 0 0 t i\n"
"MouseMoveEvent 144 158 0 0 0 0 t i\n"
"RenderEvent 144 158 0 0 0 0 t i\n"
"MouseMoveEvent 144 157 0 0 0 0 t i\n"
"RenderEvent 144 157 0 0 0 0 t i\n"
"MouseMoveEvent 145 156 0 0 0 0 t i\n"
"RenderEvent 145 156 0 0 0 0 t i\n"
"MouseMoveEvent 146 155 0 0 0 0 t i\n"
"RenderEvent 146 155 0 0 0 0 t i\n"
"MouseMoveEvent 147 154 0 0 0 0 t i\n"
"RenderEvent 147 154 0 0 0 0 t i\n"
"MouseMoveEvent 148 153 0 0 0 0 t i\n"
"RenderEvent 148 153 0 0 0 0 t i\n"
"MouseMoveEvent 148 152 0 0 0 0 t i\n"
"RenderEvent 148 152 0 0 0 0 t i\n"
"MouseMoveEvent 149 151 0 0 0 0 t i\n"
"RenderEvent 149 151 0 0 0 0 t i\n"
"MouseMoveEvent 150 150 0 0 0 0 t i\n"
"RenderEvent 150 150 0 0 0 0 t i\n"
"MouseMoveEvent 151 149 0 0 0 0 t i\n"
"RenderEvent 151 149 0 0 0 0 t i\n"
"MouseMoveEvent 152 147 0 0 0 0 t i\n"
"RenderEvent 152 147 0 0 0 0 t i\n"
"MouseMoveEvent 153 146 0 0 0 0 t i\n"
"RenderEvent 153 146 0 0 0 0 t i\n"
"MouseMoveEvent 154 144 0 0 0 0 t i\n"
"RenderEvent 154 144 0 0 0 0 t i\n"
"MouseMoveEvent 156 143 0 0 0 0 t i\n"
"RenderEvent 156 143 0 0 0 0 t i\n"
"MouseMoveEvent 157 142 0 0 0 0 t i\n"
"RenderEvent 157 142 0 0 0 0 t i\n"
"MouseMoveEvent 158 141 0 0 0 0 t i\n"
"RenderEvent 158 141 0 0 0 0 t i\n"
"MouseMoveEvent 159 140 0 0 0 0 t i\n"
"RenderEvent 159 140 0 0 0 0 t i\n"
"MouseMoveEvent 160 139 0 0 0 0 t i\n"
"RenderEvent 160 139 0 0 0 0 t i\n"
"MouseMoveEvent 161 138 0 0 0 0 t i\n"
"RenderEvent 161 138 0 0 0 0 t i\n"
"MouseMoveEvent 162 138 0 0 0 0 t i\n"
"RenderEvent 162 138 0 0 0 0 t i\n"
"MouseMoveEvent 163 137 0 0 0 0 t i\n"
"RenderEvent 163 137 0 0 0 0 t i\n"
"MouseMoveEvent 164 136 0 0 0 0 t i\n"
"RenderEvent 164 136 0 0 0 0 t i\n"
"MouseMoveEvent 165 135 0 0 0 0 t i\n"
"RenderEvent 165 135 0 0 0 0 t i\n"
"MouseMoveEvent 171 133 0 0 0 0 t i\n"
"RenderEvent 171 133 0 0 0 0 t i\n"
"MouseMoveEvent 172 131 0 0 0 0 t i\n"
"RenderEvent 172 131 0 0 0 0 t i\n"
"MouseMoveEvent 174 130 0 0 0 0 t i\n"
"RenderEvent 174 130 0 0 0 0 t i\n"
"MouseMoveEvent 176 129 0 0 0 0 t i\n"
"RenderEvent 176 129 0 0 0 0 t i\n"
"MouseMoveEvent 180 125 0 0 0 0 t i\n"
"RenderEvent 180 125 0 0 0 0 t i\n"
"MouseMoveEvent 181 124 0 0 0 0 t i\n"
"RenderEvent 181 124 0 0 0 0 t i\n"
"MouseMoveEvent 183 123 0 0 0 0 t i\n"
"RenderEvent 183 123 0 0 0 0 t i\n"
"MouseMoveEvent 184 122 0 0 0 0 t i\n"
"RenderEvent 184 122 0 0 0 0 t i\n"
"MouseMoveEvent 186 121 0 0 0 0 t i\n"
"RenderEvent 186 121 0 0 0 0 t i\n"
"MouseMoveEvent 187 121 0 0 0 0 t i\n"
"RenderEvent 187 121 0 0 0 0 t i\n"
"MouseMoveEvent 188 120 0 0 0 0 t i\n"
"RenderEvent 188 120 0 0 0 0 t i\n"
"MouseMoveEvent 189 120 0 0 0 0 t i\n"
"RenderEvent 189 120 0 0 0 0 t i\n"
"MouseMoveEvent 189 119 0 0 0 0 t i\n"
"RenderEvent 189 119 0 0 0 0 t i\n"
"MouseMoveEvent 190 119 0 0 0 0 t i\n"
"RenderEvent 190 119 0 0 0 0 t i\n"
"MouseMoveEvent 191 119 0 0 0 0 t i\n"
"RenderEvent 191 119 0 0 0 0 t i\n"
"MouseMoveEvent 191 118 0 0 0 0 t i\n"
"RenderEvent 191 118 0 0 0 0 t i\n"
"MouseMoveEvent 192 118 0 0 0 0 t i\n"
"RenderEvent 192 118 0 0 0 0 t i\n"
"MouseMoveEvent 193 118 0 0 0 0 t i\n"
"RenderEvent 193 118 0 0 0 0 t i\n"
"MouseMoveEvent 194 118 0 0 0 0 t i\n"
"RenderEvent 194 118 0 0 0 0 t i\n"
"MouseMoveEvent 194 117 0 0 0 0 t i\n"
"RenderEvent 194 117 0 0 0 0 t i\n"
"MouseMoveEvent 195 117 0 0 0 0 t i\n"
"RenderEvent 195 117 0 0 0 0 t i\n"
"LeftButtonReleaseEvent 195 117 0 0 0 0 t i\n"
"RenderEvent 195 117 0 0 0 0 t i\n"
"MouseMoveEvent 194 117 0 0 0 0 t i\n"
"RenderEvent 194 117 0 0 0 0 t i\n"
"MouseMoveEvent 193 117 0 0 0 0 t i\n"
"RenderEvent 193 117 0 0 0 0 t i\n"
"MouseMoveEvent 192 117 0 0 0 0 t i\n"
"RenderEvent 192 117 0 0 0 0 t i\n"
"MouseMoveEvent 191 117 0 0 0 0 t i\n"
"RenderEvent 191 117 0 0 0 0 t i\n"
"MouseMoveEvent 190 117 0 0 0 0 t i\n"
"RenderEvent 190 117 0 0 0 0 t i\n"
"MouseMoveEvent 189 117 0 0 0 0 t i\n"
"RenderEvent 189 117 0 0 0 0 t i\n"
"MouseMoveEvent 188 117 0 0 0 0 t i\n"
"RenderEvent 188 117 0 0 0 0 t i\n"
"MouseMoveEvent 187 117 0 0 0 0 t i\n"
"RenderEvent 187 117 0 0 0 0 t i\n"
"MouseMoveEvent 186 116 0 0 0 0 t i\n"
"RenderEvent 186 116 0 0 0 0 t i\n"
"MouseMoveEvent 185 116 0 0 0 0 t i\n"
"RenderEvent 185 116 0 0 0 0 t i\n"
"MouseMoveEvent 184 116 0 0 0 0 t i\n"
"RenderEvent 184 116 0 0 0 0 t i\n"
"MouseMoveEvent 184 115 0 0 0 0 t i\n"
"RenderEvent 184 115 0 0 0 0 t i\n"
"MouseMoveEvent 183 115 0 0 0 0 t i\n"
"RenderEvent 183 115 0 0 0 0 t i\n"
"MouseMoveEvent 182 115 0 0 0 0 t i\n"
"RenderEvent 182 115 0 0 0 0 t i\n"
"MouseMoveEvent 181 114 0 0 0 0 t i\n"
"RenderEvent 181 114 0 0 0 0 t i\n"
"MouseMoveEvent 180 114 0 0 0 0 t i\n"
"RenderEvent 180 114 0 0 0 0 t i\n"
"MouseMoveEvent 179 114 0 0 0 0 t i\n"
"RenderEvent 179 114 0 0 0 0 t i\n"
"MouseMoveEvent 178 114 0 0 0 0 t i\n"
"RenderEvent 178 114 0 0 0 0 t i\n"
"MouseMoveEvent 177 113 0 0 0 0 t i\n"
"RenderEvent 177 113 0 0 0 0 t i\n"
"MouseMoveEvent 176 113 0 0 0 0 t i\n"
"RenderEvent 176 113 0 0 0 0 t i\n"
"MouseMoveEvent 174 112 0 0 0 0 t i\n"
"RenderEvent 174 112 0 0 0 0 t i\n"
"MouseMoveEvent 173 112 0 0 0 0 t i\n"
"RenderEvent 173 112 0 0 0 0 t i\n"
"MouseMoveEvent 171 112 0 0 0 0 t i\n"
"RenderEvent 171 112 0 0 0 0 t i\n"
"MouseMoveEvent 170 112 0 0 0 0 t i\n"
"RenderEvent 170 112 0 0 0 0 t i\n"
"MouseMoveEvent 169 112 0 0 0 0 t i\n"
"RenderEvent 169 112 0 0 0 0 t i\n"
"MouseMoveEvent 167 112 0 0 0 0 t i\n"
"RenderEvent 167 112 0 0 0 0 t i\n"
"MouseMoveEvent 166 111 0 0 0 0 t i\n"
"RenderEvent 166 111 0 0 0 0 t i\n"
"MouseMoveEvent 165 111 0 0 0 0 t i\n"
"RenderEvent 165 111 0 0 0 0 t i\n"
"MouseMoveEvent 164 111 0 0 0 0 t i\n"
"RenderEvent 164 111 0 0 0 0 t i\n"
"MouseMoveEvent 163 111 0 0 0 0 t i\n"
"RenderEvent 163 111 0 0 0 0 t i\n"
"MouseMoveEvent 162 110 0 0 0 0 t i\n"
"RenderEvent 162 110 0 0 0 0 t i\n"
"MouseMoveEvent 161 110 0 0 0 0 t i\n"
"RenderEvent 161 110 0 0 0 0 t i\n"
"MouseMoveEvent 160 110 0 0 0 0 t i\n"
"RenderEvent 160 110 0 0 0 0 t i\n"
"MouseMoveEvent 160 111 0 0 0 0 t i\n"
"RenderEvent 160 111 0 0 0 0 t i\n"
"MouseMoveEvent 159 111 0 0 0 0 t i\n"
"RenderEvent 159 111 0 0 0 0 t i\n"
"MouseMoveEvent 159 112 0 0 0 0 t i\n"
"RenderEvent 159 112 0 0 0 0 t i\n"
"MouseMoveEvent 159 113 0 0 0 0 t i\n"
"RenderEvent 159 113 0 0 0 0 t i\n"
"MouseMoveEvent 159 114 0 0 0 0 t i\n"
"RenderEvent 159 114 0 0 0 0 t i\n"
"LeftButtonPressEvent 159 114 0 0 0 0 t i\n"
"RenderEvent 159 114 0 0 0 0 t i\n"
"MouseMoveEvent 136 178 0 0 0 0 t i\n"
"RenderEvent 136 178 0 0 0 0 t i\n"
"MouseMoveEvent 135 179 0 0 0 0 t i\n"
"RenderEvent 135 179 0 0 0 0 t i\n"
"MouseMoveEvent 135 180 0 0 0 0 t i\n"
"RenderEvent 135 180 0 0 0 0 t i\n"
"MouseMoveEvent 134 181 0 0 0 0 t i\n"
"RenderEvent 134 181 0 0 0 0 t i\n"
"MouseMoveEvent 134 182 0 0 0 0 t i\n"
"RenderEvent 134 182 0 0 0 0 t i\n"
"LeftButtonReleaseEvent 134 182 0 0 0 0 t i\n"
"RenderEvent 134 182 0 0 0 0 t i\n"
"MouseMoveEvent 134 181 0 0 0 0 t i\n"
"RenderEvent 134 181 0 0 0 0 t i\n"
"MouseMoveEvent 72 222 0 0 0 0 t i\n"
"RenderEvent 72 222 0 0 0 0 t i\n"
"MouseMoveEvent 71 223 0 0 0 0 t i\n"
"RenderEvent 71 223 0 0 0 0 t i\n"
"MouseMoveEvent 71 224 0 0 0 0 t i\n"
"RenderEvent 71 224 0 0 0 0 t i\n"
"MouseMoveEvent 71 225 0 0 0 0 t i\n"
"RenderEvent 71 225 0 0 0 0 t i\n"
"LeftButtonPressEvent 71 225 0 0 0 0 t i\n"
"RenderEvent 71 225 0 0 0 0 t i\n"
"LeftButtonReleaseEvent 71 225 0 0 0 0 t i\n"
"MouseMoveEvent 70 225 0 0 0 0 t i\n"
"RenderEvent 70 225 0 0 0 0 t i\n"
"MouseMoveEvent 70 224 0 0 0 0 t i\n"
"RenderEvent 70 224 0 0 0 0 t i\n"
"MouseMoveEvent 69 223 0 0 0 0 t i\n"
"RenderEvent 69 223 0 0 0 0 t i\n"
"MouseMoveEvent 185 162 0 0 0 0 t i\n"
"RenderEvent 185 162 0 0 0 0 t i\n"
"MouseMoveEvent 184 162 0 0 0 0 t i\n"
"RenderEvent 184 162 0 0 0 0 t i\n"
"MouseMoveEvent 183 162 0 0 0 0 t i\n"
"RenderEvent 183 162 0 0 0 0 t i\n"
"MouseMoveEvent 182 162 0 0 0 0 t i\n"
"RenderEvent 182 162 0 0 0 0 t i\n"
"MouseMoveEvent 183 162 0 0 0 0 t i\n"
"RenderEvent 183 162 0 0 0 0 t i\n"
"MouseMoveEvent 184 162 0 0 0 0 t i\n"
"RenderEvent 184 162 0 0 0 0 t i\n"
"MouseMoveEvent 184 161 0 0 0 0 t i\n"
"RenderEvent 184 161 0 0 0 0 t i\n"
"MouseMoveEvent 185 161 0 0 0 0 t i\n"
"RenderEvent 185 161 0 0 0 0 t i\n"
"LeftButtonPressEvent 185 161 0 0 0 0 t i\n"
"RenderEvent 185 161 0 0 0 0 t i\n"
"MouseMoveEvent 185 160 0 0 0 0 t i\n"
"RenderEvent 185 160 0 0 0 0 t i\n"
"MouseMoveEvent 129 108 0 0 0 0 t i\n"
"RenderEvent 129 108 0 0 0 0 t i\n"
"MouseMoveEvent 129 107 0 0 0 0 t i\n"
"RenderEvent 129 107 0 0 0 0 t i\n"
"MouseMoveEvent 127 107 0 0 0 0 t i\n"
"RenderEvent 127 107 0 0 0 0 t i\n"
"MouseMoveEvent 126 106 0 0 0 0 t i\n"
"RenderEvent 126 106 0 0 0 0 t i\n"
"MouseMoveEvent 125 105 0 0 0 0 t i\n"
"RenderEvent 125 105 0 0 0 0 t i\n"
"MouseMoveEvent 124 105 0 0 0 0 t i\n"
"RenderEvent 124 105 0 0 0 0 t i\n"
"MouseMoveEvent 124 104 0 0 0 0 t i\n"
"RenderEvent 124 104 0 0 0 0 t i\n"
"LeftButtonReleaseEvent 124 104 0 0 0 0 t i\n"
;
// This callback is responsible for setting the seed label.
class vtkSeedCallback : public vtkCommand
{
public:
static vtkSeedCallback *New()
{ return new vtkSeedCallback; }
virtual void Execute(vtkObject*, unsigned long event, void *calldata)
{
if (event == vtkCommand::PlacePointEvent)
{
std::cout << "Point placed, total of: "
<< this->SeedRepresentation->GetNumberOfSeeds() << std::endl;
}
if (event == vtkCommand::InteractionEvent)
{
if (calldata)
{
std::cout << "Interacting with seed : "
<< *(static_cast< int * >(calldata)) << std::endl;
}
}
}
vtkSeedCallback() : SeedRepresentation(0) {}
vtkSeedRepresentation *SeedRepresentation;
};
// The actual test function
int TestSeedWidget(int argc, char *argv[])
{
// Create the RenderWindow, Renderer and both Actors
//
vtkSmartPointer<vtkRenderer> ren1 =
vtkSmartPointer<vtkRenderer>::New();
vtkSmartPointer<vtkRenderWindow> renWin =
vtkSmartPointer<vtkRenderWindow>::New();
renWin->AddRenderer(ren1);
vtkSmartPointer<vtkRenderWindowInteractor> iren =
vtkSmartPointer<vtkRenderWindowInteractor>::New();
iren->SetRenderWindow(renWin);
vtkSmartPointer<vtkInteractorStyleTrackballCamera> style =
vtkSmartPointer<vtkInteractorStyleTrackballCamera>::New();
iren->SetInteractorStyle(style);
// Create a test pipeline
//
vtkSmartPointer<vtkSphereSource> ss =
vtkSmartPointer<vtkSphereSource>::New();
vtkSmartPointer<vtkPolyDataMapper> mapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapper->SetInputConnection(ss->GetOutputPort());
vtkSmartPointer<vtkActor> actor =
vtkSmartPointer<vtkActor>::New();
actor->SetMapper(mapper);
// Create the widget and its representation
vtkSmartPointer<vtkPointHandleRepresentation2D> handle =
vtkSmartPointer<vtkPointHandleRepresentation2D>::New();
handle->GetProperty()->SetColor(1,0,0);
vtkSmartPointer<vtkSeedRepresentation> rep =
vtkSmartPointer<vtkSeedRepresentation>::New();
rep->SetHandleRepresentation(handle);
vtkSmartPointer<vtkSeedWidget> widget =
vtkSmartPointer<vtkSeedWidget>::New();
widget->SetInteractor(iren);
widget->SetRepresentation(rep);
vtkSmartPointer<vtkSeedCallback> scbk =
vtkSmartPointer<vtkSeedCallback>::New();
scbk->SeedRepresentation = rep;
widget->AddObserver(vtkCommand::PlacePointEvent,scbk);
widget->AddObserver(vtkCommand::InteractionEvent,scbk);
// Add the actors to the renderer, set the background and size
//
ren1->AddActor(actor);
ren1->SetBackground(0.1, 0.2, 0.4);
renWin->SetSize(300, 300);
renWin->SetMultiSamples(0);
// render the image
iren->Initialize();
renWin->Render();
int retVal = vtkTesting::InteractorEventLoop(
argc, argv, iren, TestSeedWidgetEventLog );
// test removing seeds
const int startNumSeeds = rep->GetNumberOfSeeds();
for (int s = 0; s < startNumSeeds; s++)
{
widget->DeleteSeed(0);
}
const int endNumSeeds = rep->GetNumberOfSeeds();
if (endNumSeeds != 0)
{
std::cerr << "After deleting " << startNumSeeds << ", now have "
<< endNumSeeds << std::endl;
retVal = EXIT_FAILURE;
if (widget->GetSeed(0) != NULL)
{
vtkSeedRepresentation *seedRep = vtkSeedRepresentation::SafeDownCast(
widget->GetRepresentation());
const int widgetStartNumSeeds = seedRep->GetNumberOfSeeds();
std::cerr << "Still have a seed 0 after deleting all seeds, "
<< "widget thinks it's rep has " << widgetStartNumSeeds <<
std::endl;
}
}
return retVal;
}
| 36.901515 | 77 | 0.657924 | [
"render"
] |
107708c0d802c5147aa8136c29ed0994eb696313 | 3,617 | cpp | C++ | test/unit/math/opencl/rev/bernoulli_cdf_test.cpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | null | null | null | test/unit/math/opencl/rev/bernoulli_cdf_test.cpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | null | null | null | test/unit/math/opencl/rev/bernoulli_cdf_test.cpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | null | null | null | #ifdef STAN_OPENCL
#include <stan/math/opencl/rev.hpp>
#include <stan/math.hpp>
#include <gtest/gtest.h>
#include <test/unit/math/opencl/util.hpp>
#include <vector>
TEST(ProbDistributionsBernoulliCdf, error_checking) {
int N = 3;
std::vector<int> n{1, -2, 11};
std::vector<int> n_size{1, 0, 1, 0};
Eigen::VectorXd theta(N);
theta << 0.0, 0.8, 1.0;
Eigen::VectorXd theta_size(N - 1);
theta_size << 0.3, 0.8;
Eigen::VectorXd theta_value1(N);
theta_value1 << 0.3, -0.8, 0.5;
Eigen::VectorXd theta_value2(N);
theta_value2 << 0.3, 10.8, 0.5;
stan::math::matrix_cl<int> n_cl(n);
stan::math::matrix_cl<int> n_size_cl(n_size);
stan::math::matrix_cl<double> theta_cl(theta);
stan::math::matrix_cl<double> theta_size_cl(theta_size);
stan::math::matrix_cl<double> theta_value1_cl(theta_value1);
stan::math::matrix_cl<double> theta_value2_cl(theta_value2);
EXPECT_NO_THROW(stan::math::bernoulli_cdf(n_cl, theta_cl));
EXPECT_THROW(stan::math::bernoulli_cdf(n_size_cl, theta_cl),
std::invalid_argument);
EXPECT_THROW(stan::math::bernoulli_cdf(n_cl, theta_size_cl),
std::invalid_argument);
EXPECT_THROW(stan::math::bernoulli_cdf(n_cl, theta_value1_cl),
std::domain_error);
EXPECT_THROW(stan::math::bernoulli_cdf(n_cl, theta_value2_cl),
std::domain_error);
}
auto bernoulli_cdf_functor = [](const auto& n, const auto& theta) {
return stan::math::bernoulli_cdf(n, theta);
};
TEST(ProbDistributionsBernoulliCdf, opencl_matches_cpu_small) {
int N = 3;
int M = 2;
std::vector<int> n{0, 1, 3};
Eigen::VectorXd theta(N);
theta << 0.3, 0.8, 1.0;
stan::math::test::compare_cpu_opencl_prim_rev(bernoulli_cdf_functor, n,
theta);
stan::math::test::compare_cpu_opencl_prim_rev(bernoulli_cdf_functor, n,
theta.transpose().eval());
}
TEST(ProbDistributionsBernoulliCdf, opencl_matches_cpu_small_n_negative) {
int N = 3;
int M = 2;
std::vector<int> n{0, 1, -5};
Eigen::VectorXd theta(N);
theta << 0.3, 0.8, 1.0;
stan::math::test::compare_cpu_opencl_prim_rev(bernoulli_cdf_functor, n,
theta);
stan::math::test::compare_cpu_opencl_prim_rev(bernoulli_cdf_functor, n,
theta.transpose().eval());
}
TEST(ProbDistributionsBernoulliCdf, opencl_broadcast_n) {
int N = 3;
int n_scal = 1;
Eigen::VectorXd theta(N);
theta << 0.3, 0.8, 1.0;
stan::math::test::test_opencl_broadcasting_prim_rev<0>(bernoulli_cdf_functor,
n_scal, theta);
}
TEST(ProbDistributionsBernoulliCdf, opencl_broadcast_theta) {
int N = 3;
std::vector<int> n{0, 1, 0};
double theta_scal = 0.4;
stan::math::test::test_opencl_broadcasting_prim_rev<1>(bernoulli_cdf_functor,
n, theta_scal);
}
TEST(ProbDistributionsBernoulliCdf, opencl_matches_cpu_big) {
int N = 153;
std::vector<int> n(N);
for (int i = 0; i < N; i++) {
n[i] = Eigen::Array<int, Eigen::Dynamic, 1>::Random(1, 1).abs()(0) % 2;
}
Eigen::Matrix<double, Eigen::Dynamic, 1> theta
= Eigen::Array<double, Eigen::Dynamic, 1>::Random(N, 1).abs();
stan::math::test::compare_cpu_opencl_prim_rev(bernoulli_cdf_functor, n,
theta);
stan::math::test::compare_cpu_opencl_prim_rev(bernoulli_cdf_functor, n,
theta.transpose().eval());
}
#endif
| 32.294643 | 79 | 0.620127 | [
"vector"
] |
1077d9cfb63fb5eb25e21fa7831cb8b9ccecfe10 | 6,927 | cpp | C++ | src/storage/LocalFileLoader.cpp | n-krueger/faasm | 093cb032a3d938d3a41d8aa9644bb5efbc632a95 | [
"Apache-2.0"
] | 1 | 2021-03-03T09:54:21.000Z | 2021-03-03T09:54:21.000Z | src/storage/LocalFileLoader.cpp | n-krueger/faasm | 093cb032a3d938d3a41d8aa9644bb5efbc632a95 | [
"Apache-2.0"
] | null | null | null | src/storage/LocalFileLoader.cpp | n-krueger/faasm | 093cb032a3d938d3a41d8aa9644bb5efbc632a95 | [
"Apache-2.0"
] | null | null | null | #include "storage/LocalFileLoader.h"
#include <iostream>
#include <faabric/util/bytes.h>
#include <faabric/util/files.h>
#include <faabric/util/func.h>
#include <faabric/util/logging.h>
#include <boost/filesystem.hpp>
namespace storage {
std::vector<uint8_t> LocalFileLoader::loadFunctionWasm(
const faabric::Message& msg)
{
std::string filePath = faabric::util::getFunctionFile(msg);
return loadFileBytes(filePath);
}
std::vector<uint8_t> LocalFileLoader::loadFunctionObjectFile(
const faabric::Message& msg)
{
std::string objectFilePath = faabric::util::getFunctionObjectFile(msg);
return loadFileBytes(objectFilePath);
}
std::vector<uint8_t> LocalFileLoader::loadFunctionWamrAotFile(
const faabric::Message& msg)
{
std::string objectFilePath = faabric::util::getFunctionAotFile(msg);
return loadFileBytes(objectFilePath);
}
std::vector<uint8_t> LocalFileLoader::loadSharedObjectObjectFile(
const std::string& path)
{
std::string objFilePath = faabric::util::getSharedObjectObjectFile(path);
return loadFileBytes(objFilePath);
}
std::vector<uint8_t> LocalFileLoader::loadSharedObjectWasm(
const std::string& path)
{
return loadFileBytes(path);
}
std::vector<uint8_t> LocalFileLoader::loadHashForPath(const std::string& path)
{
std::string hashFile = getHashFilePath(path);
if (boost::filesystem::exists(hashFile)) {
return faabric::util::readFileToBytes(hashFile);
} else {
std::vector<uint8_t> empty;
return empty;
}
}
std::vector<uint8_t> LocalFileLoader::loadFunctionObjectHash(
const faabric::Message& msg)
{
std::string outputFile = faabric::util::getFunctionObjectFile(msg);
return loadHashForPath(outputFile);
}
std::vector<uint8_t> LocalFileLoader::loadFunctionWamrAotHash(
const faabric::Message& msg)
{
std::string outputFile = faabric::util::getFunctionAotFile(msg);
return loadHashForPath(outputFile);
}
std::vector<uint8_t> LocalFileLoader::loadSharedObjectObjectHash(
const std::string& path)
{
std::string outputFile = faabric::util::getSharedObjectObjectFile(path);
return loadHashForPath(outputFile);
}
std::vector<uint8_t> LocalFileLoader::loadSharedFile(const std::string& path)
{
const std::string fullPath = faabric::util::getSharedFileFile(path);
if (!boost::filesystem::exists(fullPath)) {
const std::shared_ptr<spdlog::logger>& logger =
faabric::util::getLogger();
logger->debug("Local file loader could not find file at {}", fullPath);
std::vector<uint8_t> empty;
return empty;
}
if (boost::filesystem::is_directory(fullPath)) {
throw SharedFileIsDirectoryException(fullPath);
}
return loadFileBytes(fullPath);
}
void LocalFileLoader::uploadFunction(faabric::Message& msg)
{
const std::shared_ptr<spdlog::logger>& logger = faabric::util::getLogger();
const std::string funcStr = faabric::util::funcToString(msg, false);
// Here the msg input data is actually the file
const std::string& fileBody = msg.inputdata();
if (fileBody.empty()) {
logger->error("Uploaded empty file to {}", funcStr);
throw std::runtime_error("Uploaded empty file");
}
logger->debug("Uploading wasm file {}", funcStr);
std::string outputFile = faabric::util::getFunctionFile(msg);
std::ofstream out(outputFile);
out.write(fileBody.c_str(), fileBody.size());
out.flush();
out.close();
// Build the object file from the file we've just received
logger->debug("Generating object file for {}", funcStr);
codegenForFunction(msg);
}
void LocalFileLoader::uploadPythonFunction(faabric::Message& msg)
{
const std::string& fileBody = msg.inputdata();
const std::shared_ptr<spdlog::logger>& logger = faabric::util::getLogger();
// Message will have user/ function set as python user and python function
faabric::util::convertMessageToPython(msg);
std::string outputFile = faabric::util::getPythonFunctionFile(msg);
logger->debug("Uploading python file {}/{} to {}",
msg.pythonuser(),
msg.pythonfunction(),
outputFile);
std::ofstream out(outputFile);
out.write(fileBody.c_str(), fileBody.size());
out.flush();
out.close();
}
void LocalFileLoader::uploadFunctionObjectFile(
const faabric::Message& msg,
const std::vector<uint8_t>& objBytes)
{
// Write the file
std::string objFilePath = faabric::util::getFunctionObjectFile(msg);
faabric::util::writeBytesToFile(objFilePath, objBytes);
}
void LocalFileLoader::uploadFunctionAotFile(
const faabric::Message& msg,
const std::vector<uint8_t>& objBytes)
{
std::string objFilePath = faabric::util::getFunctionAotFile(msg);
faabric::util::writeBytesToFile(objFilePath, objBytes);
}
void LocalFileLoader::uploadSharedObjectObjectFile(
const std::string& path,
const std::vector<uint8_t>& objBytes)
{
std::string outputPath = faabric::util::getSharedObjectObjectFile(path);
faabric::util::writeBytesToFile(outputPath, objBytes);
}
void LocalFileLoader::uploadSharedObjectAotFile(
const std::string& path,
const std::vector<uint8_t>& objBytes)
{
throw std::runtime_error("Not yet implemented WAMR shared objects");
}
void LocalFileLoader::uploadSharedFile(const std::string& path,
const std::vector<uint8_t>& objBytes)
{
const std::string fullPath = faabric::util::getSharedFileFile(path);
faabric::util::writeBytesToFile(fullPath, objBytes);
}
void LocalFileLoader::flushFunctionFiles()
{
// In local file mode, we do not need to flush anything as the files on this
// host are the master copies.
}
void LocalFileLoader::writeHashForFile(const std::string& path,
const std::vector<uint8_t>& hash)
{
// Write the hash
std::string hashPath = getHashFilePath(path);
faabric::util::writeBytesToFile(hashPath, hash);
}
void LocalFileLoader::uploadFunctionObjectHash(const faabric::Message& msg,
const std::vector<uint8_t>& hash)
{
std::string objFilePath = faabric::util::getFunctionObjectFile(msg);
writeHashForFile(objFilePath, hash);
}
void LocalFileLoader::uploadFunctionWamrAotHash(
const faabric::Message& msg,
const std::vector<uint8_t>& hash)
{
std::string objFilePath = faabric::util::getFunctionAotFile(msg);
writeHashForFile(objFilePath, hash);
}
void LocalFileLoader::uploadSharedObjectObjectHash(
const std::string& path,
const std::vector<uint8_t>& hash)
{
std::string outputPath = faabric::util::getSharedObjectObjectFile(path);
writeHashForFile(outputPath, hash);
}
void LocalFileLoader::uploadSharedObjectAotHash(
const std::string& path,
const std::vector<uint8_t>& hash)
{
throw std::runtime_error("Not yet implemented WAMR shared objects");
}
}
| 30.786667 | 80 | 0.705789 | [
"object",
"vector"
] |
107facac747e97976e5f4c5790d1377dc95fdbd4 | 98,707 | cpp | C++ | toonz/sources/toonz/subscenecommand.cpp | rozhuk-im/opentoonz | ad5b632512746b97fd526aa79660fbaedf934fad | [
"BSD-3-Clause"
] | 1 | 2020-06-12T17:46:49.000Z | 2020-06-12T17:46:49.000Z | toonz/sources/toonz/subscenecommand.cpp | rozhuk-im/opentoonz | ad5b632512746b97fd526aa79660fbaedf934fad | [
"BSD-3-Clause"
] | 2 | 2019-12-07T02:14:35.000Z | 2019-12-18T17:38:00.000Z | toonz/sources/toonz/subscenecommand.cpp | rozhuk-im/opentoonz | ad5b632512746b97fd526aa79660fbaedf934fad | [
"BSD-3-Clause"
] | 1 | 2018-12-11T02:01:18.000Z | 2018-12-11T02:01:18.000Z |
// TnzCore includes
#include "tconst.h"
#include "tundo.h"
// TnzBase includes
#include "tfx.h"
#include "tfxattributes.h"
#include "tparamcontainer.h"
#include "tparamset.h"
// TnzLib includes
#include "toonz/tframehandle.h"
#include "toonz/tcolumnhandle.h"
#include "toonz/txsheethandle.h"
#include "toonz/tobjecthandle.h"
#include "toonz/tscenehandle.h"
#include "toonz/txshcell.h"
#include "toonz/txsheet.h"
#include "toonz/toonzscene.h"
#include "toonz/childstack.h"
#include "toonz/txshleveltypes.h"
#include "toonz/txshchildlevel.h"
#include "toonz/tstageobject.h"
#include "toonz/tcolumnfx.h"
#include "toonz/fxcommand.h"
#include "toonz/tcolumnfxset.h"
#include "toonz/fxdag.h"
#include "toonz/tstageobjecttree.h"
#include "toonz/tstageobjectspline.h"
#include "toonz/tcamera.h"
#include "toonz/expressionreferencemonitor.h"
// TnzQt includes
#include "toonzqt/menubarcommand.h"
#include "toonzqt/icongenerator.h"
#include "toonzqt/tselectionhandle.h"
#include "toonzqt/selection.h"
#include "toonzqt/dvdialog.h"
#include "toonzqt/stageobjectsdata.h"
#include "historytypes.h"
// Toonz includes
#include "columncommand.h"
#include "menubarcommandids.h"
#include "celldata.h"
#include "tapp.h"
#include "columnselection.h"
#include "cellselection.h"
#include "expressionreferencemanager.h"
#include "subscenecommand.h"
//*****************************************************************************
// Local namespace
//*****************************************************************************
namespace {
struct GroupData {
public:
QStack<int> m_groupIds;
QStack<std::wstring> m_groupNames;
int m_editingGroup;
GroupData(const QStack<int> &groupIds, const QStack<std::wstring> &groupNames,
int editingGroup)
: m_groupIds(groupIds)
, m_groupNames(groupNames)
, m_editingGroup(editingGroup) {}
};
//-----------------------------------------------------------------------------
// Zerary fxs and zerary COLUMN fxs are separate, and fx port connections
// are stored in the actual zerary fx.
TFx *getActualFx(TFx *fx) {
TZeraryColumnFx *zeraryColumnFx = dynamic_cast<TZeraryColumnFx *>(fx);
return zeraryColumnFx ? zeraryColumnFx->getZeraryFx() : fx;
}
//-----------------------------------------------------------------------------
void setFxParamToCurrentScene(TFx *fx, TXsheet *xsh) {
for (int i = 0; i < fx->getParams()->getParamCount(); i++) {
TParam *param = fx->getParams()->getParam(i);
if (TDoubleParam *dp = dynamic_cast<TDoubleParam *>(param))
xsh->getStageObjectTree()->setGrammar(dp);
else if (dynamic_cast<TPointParam *>(param) ||
dynamic_cast<TRangeParam *>(param) ||
dynamic_cast<TPixelParam *>(param)) {
TParamSet *paramSet = dynamic_cast<TParamSet *>(param);
assert(paramSet);
int f;
for (f = 0; f < paramSet->getParamCount(); f++) {
TDoubleParam *dp =
dynamic_cast<TDoubleParam *>(paramSet->getParam(f).getPointer());
if (!dp) continue;
xsh->getStageObjectTree()->setGrammar(dp);
}
}
}
}
//-----------------------------------------------------------------------------
std::vector<TStageObjectId> getRoots(const QList<TStageObjectId> &objIds,
TXsheetHandle *xshHandle) {
std::vector<TStageObjectId> roots;
std::map<TStageObjectId, std::string> parentHandles;
TStageObjectTree *pegTree = xshHandle->getXsheet()->getStageObjectTree();
for (int i = 0; i < objIds.size(); i++) {
TStageObject *obj = pegTree->getStageObject(objIds.at(i), false);
TStageObjectId parentId = obj->getParent();
bool parentIsColumn = parentId.isColumn() && !objIds.contains(parentId);
std::string parentHandle = obj->getParentHandle();
if (!parentIsColumn && !objIds.contains(parentId) &&
(parentHandles.count(parentId) == 0 ||
parentHandles[parentId] != parentHandle)) {
parentHandles[parentId] = parentHandle;
roots.push_back(parentId);
}
}
return roots;
}
//-----------------------------------------------------------------------------
std::vector<TStageObjectId> isConnected(
const std::set<int> &indices, const std::set<TStageObjectId> &pegbarIds,
TXsheetHandle *xshHandle) {
std::vector<TStageObjectId> roots;
std::map<TStageObjectId, std::string> parentHandles;
TStageObjectTree *pegTree = xshHandle->getXsheet()->getStageObjectTree();
std::set<int>::const_iterator it;
for (it = indices.begin(); it != indices.end(); it++) {
TStageObjectId id = TStageObjectId::ColumnId(*it);
TStageObject *obj = pegTree->getStageObject(id, false);
TStageObjectId parentId = obj->getParent();
std::string parentHandle = obj->getParentHandle();
bool parentIsColumn = parentId.isColumn() &&
indices.find(parentId.getIndex()) != indices.end();
if (!parentIsColumn && pegbarIds.find(parentId) == pegbarIds.end() &&
(parentHandles.count(parentId) == 0 ||
parentHandles[parentId] != parentHandle)) {
parentHandles[parentId] = parentHandle;
roots.push_back(parentId);
}
}
std::set<TStageObjectId>::const_iterator it2;
for (it2 = pegbarIds.begin(); it2 != pegbarIds.end(); it2++) {
TStageObject *obj = pegTree->getStageObject(*it2, false);
TStageObjectId parentId = obj->getParent();
bool parentIsColumn = parentId.isColumn() &&
indices.find(parentId.getIndex()) != indices.end();
std::string parentHandle = obj->getParentHandle();
if (!parentIsColumn && pegbarIds.find(parentId) == pegbarIds.end() &&
(parentHandles.count(parentId) == 0 ||
parentHandles[parentId] != parentHandle)) {
parentHandles[parentId] = parentHandle;
roots.push_back(parentId);
}
}
return roots;
}
//-----------------------------------------------------------------------------
std::map<TFx *, std::vector<TFxPort *>> isConnected(
const std::set<int> &indices, const std::set<TFx *> &internalFxs,
TXsheetHandle *xshHandle) {
TXsheet *xsh = xshHandle->getXsheet();
std::set<int>::const_iterator it;
std::map<TFx *, std::vector<TFxPort *>> roots;
for (it = indices.begin(); it != indices.end(); it++) {
TFx *fx = xsh->getColumn(*it)->getFx();
int i, outputCount = fx->getOutputConnectionCount();
for (i = 0; i < outputCount; i++) {
TFx *outFx = fx->getOutputConnection(i)->getOwnerFx();
if (internalFxs.find(outFx) == internalFxs.end())
roots[fx].push_back(fx->getOutputConnection(i));
}
}
std::set<TFx *>::const_iterator it2;
for (it2 = internalFxs.begin(); it2 != internalFxs.end(); it2++) {
int i, outputCount = (*it2)->getOutputConnectionCount();
for (i = 0; i < outputCount; i++) {
TFx *outFx = (*it2)->getOutputConnection(i)->getOwnerFx();
if (internalFxs.find(outFx) == internalFxs.end())
roots[*it2].push_back((*it2)->getOutputConnection(i));
}
}
return roots;
}
//-----------------------------------------------------------------------------
// returns true if the column indexed with col contains only the childLevel.
// if not, false is returned and in from and to is put the frame range contained
// the frame indexed with row.
bool mustRemoveColumn(int &from, int &to, TXshChildLevel *childLevel,
TXsheet *xsh, int col, int row) {
bool removeColumn = true;
bool rangeFound = false;
from = -1;
to = -1;
int i, r0, r1;
xsh->getColumn(col)->getRange(r0, r1);
for (i = r0; i <= r1; i++) {
TXshCell cell = xsh->getCell(i, col);
TXshChildLevel *app = cell.getChildLevel();
if (app != childLevel) {
removeColumn = false;
if (from != -1 && to != -1) {
rangeFound = from <= row && row <= to;
if (!rangeFound) from = to = -1;
}
continue;
}
if (from == -1 && !rangeFound) {
from = to = i;
} else if (from != -1 && !rangeFound) {
to = i;
}
}
return removeColumn;
}
//-----------------------------------------------------------------------------
class FxConnections {
bool m_isTerminal;
QMap<int, TFx *> m_inputLinks;
QMap<TFx *, int> m_outputLinks;
QList<TFx *> m_notTerminalInputFxs;
public:
FxConnections() {}
~FxConnections() {}
void setIsTerminal(bool isTerminal) { m_isTerminal = isTerminal; }
void setInputLink(int portIndex, TFx *inputFx) {
m_inputLinks[portIndex] = inputFx;
}
void setOutputLink(TFx *outputFx, int portIndex) {
m_outputLinks[outputFx] = portIndex;
}
void addNotTerminalInputFx(TFx *fx) { m_notTerminalInputFxs.append(fx); }
QMap<int, TFx *> getInputLinks() { return m_inputLinks; }
QMap<TFx *, int> getOutputLinks() { return m_outputLinks; }
QList<TFx *> getNotTerminalInputFxs() { return m_notTerminalInputFxs; }
bool isTerminal() { return m_isTerminal; }
};
//-----------------------------------------------------------------------------
void getFxConnections(QMap<TFx *, FxConnections> &fxConnetcions,
const std::set<TFx *> &fxs, TXsheet *xsh) {
TFxSet *terminalFxs = xsh->getFxDag()->getTerminalFxs();
for (auto const &fx : fxs) {
FxConnections connections;
connections.setIsTerminal(terminalFxs->containsFx(fx));
int i;
for (i = 0; i < fx->getInputPortCount(); i++) {
TFx *inputFx = fx->getInputPort(i)->getFx();
connections.setInputLink(i, inputFx);
if (connections.isTerminal()) connections.addNotTerminalInputFx(inputFx);
}
for (i = 0; i < fx->getOutputConnectionCount(); i++) {
TFx *outputFx = fx->getOutputConnection(i)->getOwnerFx();
int j, inputCount = outputFx->getInputPortCount();
if (inputCount == 0) continue;
for (j = 0; j < inputCount; j++) {
TFx *inputFx = outputFx->getInputPort(j)->getFx();
if (inputFx == fx) break;
}
connections.setOutputLink(outputFx, j);
}
fxConnetcions[fx] = connections;
}
}
//-----------------------------------------------------------------------------
void changeSaveSubXsheetAsCommand() {
ToonzScene *scene = TApp::instance()->getCurrentScene()->getScene();
bool isSubxsheet = scene->getChildStack()->getAncestorCount() > 0;
CommandManager::instance()->enable(MI_SaveSubxsheetAs, isSubxsheet);
}
//-----------------------------------------------------------------------------
void getColumnOutputConnections(
const std::set<int> &indices,
QMap<TFx *, QList<TFxPort *>> &columnOutputConnections) {
TXsheet *xsh = TApp::instance()->getCurrentXsheet()->getXsheet();
std::set<int>::const_iterator it;
for (it = indices.begin(); it != indices.end(); it++) {
int i = *it;
TXshColumn *column = xsh->getColumn(i);
if (!column) continue;
TFx *columnFx = column->getFx();
if (!columnFx) continue;
QList<TFxPort *> ports;
int j;
for (j = 0; j < columnFx->getOutputConnectionCount(); j++)
ports.append(columnFx->getOutputConnection(j));
columnOutputConnections[columnFx] = ports;
}
}
//-----------------------------------------------------------------------------
void getChildren(const std::set<int> &indices,
QMap<TStageObjectId, QList<TStageObjectId>> &children) {
TXsheet *xsh = TApp::instance()->getCurrentXsheet()->getXsheet();
std::set<int>::const_iterator it;
for (it = indices.begin(); it != indices.end(); it++) {
TStageObjectId id = TStageObjectId::ColumnId(*it);
TStageObject *obj = xsh->getStageObjectTree()->getStageObject(id, false);
assert(obj);
if (obj && !obj->getChildren().empty()) {
std::list<TStageObject *> childrenObj = obj->getChildren();
std::list<TStageObject *>::iterator it2;
for (it2 = childrenObj.begin(); it2 != childrenObj.end(); it2++) {
TStageObjectId childId = (*it2)->getId();
children[id].append(childId);
}
}
}
}
//-----------------------------------------------------------------------------
void getParents(const std::set<int> &indices,
QMap<TStageObjectId, TStageObjectId> &parents) {
TXsheet *xsh = TApp::instance()->getCurrentXsheet()->getXsheet();
std::set<int>::const_iterator it;
for (it = indices.begin(); it != indices.end(); it++) {
TStageObjectId id = TStageObjectId::ColumnId(*it);
TStageObject *obj = xsh->getStageObjectTree()->getStageObject(id, false);
assert(obj);
if (obj) parents[id] = obj->getParent();
}
}
//-----------------------------------------------------------------------------
void setColumnOutputConnections(
const QMap<TFx *, QList<TFxPort *>> &columnOutputConnections) {
QMap<TFx *, QList<TFxPort *>>::const_iterator it;
for (it = columnOutputConnections.begin();
it != columnOutputConnections.end(); it++) {
TFx *columnFx = it.key();
QList<TFxPort *> ports = it.value();
int i;
for (i = 0; i < ports.size(); i++) ports.at(i)->setFx(columnFx);
}
}
//-----------------------------------------------------------------------------
void setChildren(const QMap<TStageObjectId, QList<TStageObjectId>> &children) {
TXsheet *xsh = TApp::instance()->getCurrentXsheet()->getXsheet();
QMap<TStageObjectId, QList<TStageObjectId>>::const_iterator it;
for (it = children.begin(); it != children.end(); it++) {
TStageObjectId id = it.key();
QList<TStageObjectId> childrenIds = it.value();
QList<TStageObjectId>::iterator it2;
for (it2 = childrenIds.begin(); it2 != childrenIds.end(); it2++)
xsh->setStageObjectParent(*it2, id);
}
}
//-----------------------------------------------------------------------------
void setParents(const QMap<TStageObjectId, TStageObjectId> &parents) {
TXsheet *xsh = TApp::instance()->getCurrentXsheet()->getXsheet();
QMap<TStageObjectId, TStageObjectId>::const_iterator it;
for (it = parents.begin(); it != parents.end(); it++)
xsh->setStageObjectParent(it.key(), it.value());
}
//-----------------------------------------------------------------------------
bool isConnectedToXsheet(TFx *fx) {
if (!fx) return false;
int i, count = fx->getInputPortCount();
bool xsheetConnected = false;
for (i = 0; i < count; i++) {
TFx *inputFx = fx->getInputPort(i)->getFx();
if (dynamic_cast<TXsheetFx *>(inputFx)) return true;
xsheetConnected = xsheetConnected || isConnectedToXsheet(inputFx);
}
return xsheetConnected;
}
//-----------------------------------------------------------------------------
// clones in outerDag fx and all effects contained in the subtree with root in
// fx
void bringFxOut(TFx *fx, QMap<TFx *, QPair<TFx *, int>> &fxs, FxDag *outerDag,
const GroupData &fxGroupData) {
if (!fx) return;
TFx *actualFx = getActualFx(fx);
if (fx != actualFx) {
// Zerary Column case
TFx *outerFx = getActualFx(fxs[fx].first);
int i, inputPortsCount = actualFx->getInputPortCount();
for (i = 0; i < inputPortsCount; ++i) {
TFx *inputFx = actualFx->getInputPort(i)->getFx();
if (!inputFx) continue;
bringFxOut(inputFx, fxs, outerDag, fxGroupData);
outerFx->getInputPort(i)->setFx(fxs[inputFx].first);
}
return;
}
// Common case
if (fxs.contains(fx)) return;
TFx *outerFx = fx->clone(false);
TOutputFx *outFx = dynamic_cast<TOutputFx *>(outerFx);
if (!outFx) {
outerDag->getInternalFxs()->addFx(outerFx);
outerDag->assignUniqueId(outerFx);
} else
outerDag->addOutputFx(outFx);
TFxAttributes *attr = outerFx->getAttributes();
attr->setDagNodePos(fx->getAttributes()->getDagNodePos());
// Put in the right Fx group if needed
attr->removeFromAllGroup();
if (!fxGroupData.m_groupIds.empty()) {
int i;
for (i = 0; i < fxGroupData.m_groupIds.size(); i++) {
attr->setGroupId(fxGroupData.m_groupIds[i]);
attr->setGroupName(fxGroupData.m_groupNames[i]);
}
for (i = 0;
i < fxGroupData.m_groupIds.size() && fxGroupData.m_editingGroup >= 0;
i++)
attr->editGroup();
}
int columnIndex = -1;
bool firstIndex = true;
int i, inputPortsCount = fx->getInputPortCount();
for (i = 0; i < inputPortsCount; ++i) {
TFx *inputFx = fx->getInputPort(i)->getFx();
if (!inputFx) continue;
bringFxOut(inputFx, fxs, outerDag, fxGroupData);
outerFx->getInputPort(i)->setFx(fxs[inputFx].first);
if (firstIndex) {
columnIndex = fxs[inputFx].second;
firstIndex = false;
}
}
fxs[fx] = QPair<TFx *, int>(outerFx, columnIndex);
}
//-----------------------------------------------------------------------------
TFx *explodeFxSubTree(TFx *innerFx, QMap<TFx *, QPair<TFx *, int>> &fxs,
FxDag *outerDag, TXsheet *outerXsheet, FxDag *innerDag,
const GroupData &fxGroupData,
const std::vector<TFxPort *> &outPorts) {
TXsheetFx *xsheetFx = dynamic_cast<TXsheetFx *>(innerFx);
if (!xsheetFx) {
if (innerDag->getCurrentOutputFx() == innerFx)
innerFx = innerFx->getInputPort(0)->getFx();
if (!innerFx) return nullptr;
bringFxOut(innerFx, fxs, outerDag, fxGroupData);
TOutputFx *outFx = dynamic_cast<TOutputFx *>(innerFx);
if (outFx)
return fxs[outFx->getInputPort(0)->getFx()].first;
else
return fxs[innerFx].first;
} else {
TFxSet *innerTerminals = innerDag->getTerminalFxs();
int i, terminalCount = innerTerminals->getFxCount();
QMultiMap<int, TFx *> sortedFx;
for (i = 0; i < terminalCount; i++) {
TFx *terminalFx = innerTerminals->getFx(i);
bringFxOut(terminalFx, fxs, outerDag, fxGroupData);
sortedFx.insert(fxs[terminalFx].second, fxs[terminalFx].first);
}
// Xsheet nodes can be "merged" if:
// a) the subxsheet node is directly connected to the Xsheet node in the
// parent fxdag, AND b) only the active output node is connected to the
// Xsheet node in the child fxdag
if (outPorts.empty() && xsheetFx->getOutputConnectionCount() == 1) {
if (innerDag->getCurrentOutputFx() ==
xsheetFx->getOutputConnection(0)->getOwnerFx())
return nullptr;
}
// in case no nodes connected to the xsheet the xsheet node will not be
// merged, but will just be removed
if (terminalCount == 0) {
fxs[innerFx] = QPair<TFx *, int>(nullptr, -1);
return innerFx; // just to return non-zero value
}
TFx *root = sortedFx.begin().value();
// If only one node is connected to the Xsheet node, then skip bringing it
// out.
if (terminalCount == 1) {
fxs[innerFx] = QPair<TFx *, int>(root, sortedFx.begin().key());
return root;
}
// Replace the child Xsheet node by the Over Fx node
TFx *overFx = TFx::create("overFx");
outerDag->assignUniqueId(overFx);
outerDag->getInternalFxs()->addFx(overFx);
setFxParamToCurrentScene(overFx, outerXsheet);
TPointD pos = root->getAttributes()->getDagNodePos();
overFx->getAttributes()->setDagNodePos((pos == TConst::nowhere)
? TConst::nowhere
: TPointD(pos.x + 150, pos.y));
const TFxPortDG *group = overFx->dynamicPortGroup(0);
for (int i = 0; i < sortedFx.size(); i++) {
TFxPort *port = new TRasterFxPort;
if (!overFx->addInputPort(
group->portsPrefix() + QString::number(i + 1).toStdString(), port,
0))
delete port;
}
int portId = sortedFx.size() - 1;
int columnIndex = -1;
for (auto it = sortedFx.begin(); it != sortedFx.end(); ++it, --portId) {
TFx *fx = it.value();
assert(fx);
overFx->getInputPort(portId)->setFx(fx);
outerDag->removeFromXsheet(fx);
// set the firstly-found column index
if (columnIndex == -1) columnIndex = it.key();
}
// register fx
fxs[innerFx] = QPair<TFx *, int>(overFx, columnIndex);
return overFx;
}
}
//-----------------------------------------------------------------------------
// brings in xsh obj and all objects contained in the subtree with root in obj
void bringObjectOut(TStageObject *obj, TXsheet *xsh,
QMap<TStageObjectId, TStageObjectId> &ids,
QMap<TStageObjectSpline *, TStageObjectSpline *> &splines,
QList<TStageObject *> &pegObjects, int &pegbarIndex,
const GroupData &objGroupData, int groupId) {
if (!obj->hasChildren()) return;
std::list<TStageObject *> children = obj->getChildren();
std::list<TStageObject *>::iterator it;
for (it = children.begin(); it != children.end(); it++) {
TStageObjectId id = (*it)->getId();
if (id.isColumn()) continue;
assert(id.isPegbar());
pegbarIndex++;
TStageObjectId outerId = TStageObjectId::PegbarId(pegbarIndex);
// find the first available pegbar id
while (xsh->getStageObjectTree()->getStageObject(outerId, false)) {
pegbarIndex++;
outerId = TStageObjectId::PegbarId(pegbarIndex);
}
TStageObject *outerObj =
xsh->getStageObjectTree()->getStageObject(outerId, true);
outerObj->setDagNodePos((*it)->getDagNodePos());
ids[id] = outerId;
pegObjects.append(outerObj);
outerObj->addRef(); // undo make release!!!
TStageObjectParams *params = (*it)->getParams();
if (params->m_spline) {
if (splines.contains(params->m_spline))
params->m_spline = splines[params->m_spline];
else {
TStageObjectSpline *spline = params->m_spline->clone();
splines[params->m_spline] = spline;
xsh->getStageObjectTree()->assignUniqueSplineId(spline);
xsh->getStageObjectTree()->insertSpline(spline);
params->m_spline = spline;
}
}
outerObj->assignParams(params);
delete params;
outerObj->setParent(ids[obj->getId()]);
outerObj->removeFromAllGroup();
if (groupId != -1) {
outerObj->setGroupId(groupId);
outerObj->setGroupName(L"Group " + std::to_wstring(groupId));
}
if (!objGroupData.m_groupIds.empty()) {
int i;
for (i = 0; i < objGroupData.m_groupIds.size(); i++) {
outerObj->setGroupId(objGroupData.m_groupIds[i]);
outerObj->setGroupName(objGroupData.m_groupNames[i]);
}
for (i = 0; i < objGroupData.m_groupIds.size() &&
objGroupData.m_editingGroup >= 0;
i++)
outerObj->editGroup();
}
bringObjectOut(*it, xsh, ids, splines, pegObjects, pegbarIndex,
objGroupData, groupId);
}
}
//-----------------------------------------------------------------------------
std::set<int> explodeStageObjects(
TXsheet *xsh, TXsheet *subXsh, int index, const TStageObjectId &parentId,
const GroupData &objGroupData, const TPointD &subPos,
const GroupData &fxGroupData, QList<TStageObject *> &pegObjects,
QMap<TFx *, QPair<TFx *, int>> &fxs,
QMap<TStageObjectSpline *, TStageObjectSpline *> &splines,
QMap<TStageObjectId, TStageObjectId> &ids, bool onlyColumn) {
/*- SubXsheet, 親Xsheet両方のツリーを取得 -*/
TStageObjectTree *innerTree = subXsh->getStageObjectTree();
TStageObjectTree *outerTree = xsh->getStageObjectTree();
// innerSpline->outerSpline
int groupId = -1; // outerTree->getNewGroupId();
/*- Pegbarも持ち出す場合 -*/
if (!onlyColumn) {
// add a pegbar to represent the table
TStageObject *table = subXsh->getStageObject(TStageObjectId::TableId);
// find the first available pegbar index
int pegbarIndex = 0;
while (
outerTree->getStageObject(TStageObjectId::PegbarId(pegbarIndex), false))
pegbarIndex++;
/*- 空いてるIndexのPegbarに、SubXsheetのTableを対応させる -*/
TStageObjectId id = TStageObjectId::PegbarId(pegbarIndex);
TStageObject *obj = outerTree->getStageObject(id, true);
/*- 対応表に追加 -*/
obj->setDagNodePos(table->getDagNodePos());
ids[TStageObjectId::TableId] = id;
pegObjects.append(obj);
obj->addRef(); // undo make release!!!!
/*- SubのTableの情報を、今作ったPegbarにコピーする -*/
TStageObjectParams *params = table->getParams();
if (params->m_spline) {
if (splines.contains(params->m_spline))
params->m_spline = splines[params->m_spline];
else {
TStageObjectSpline *spline = params->m_spline->clone();
splines[params->m_spline] = spline;
outerTree->assignUniqueSplineId(spline);
outerTree->insertSpline(spline);
params->m_spline = spline;
}
}
obj->assignParams(params);
delete params;
// a pegbar cannot be a child of column
if (parentId.isColumn())
obj->setParent(TStageObjectId::TableId);
else
obj->setParent(parentId);
// Put in the right StageObject group if needed
obj->removeFromAllGroup();
groupId = outerTree->getNewGroupId();
obj->setGroupId(groupId);
obj->setGroupName(L"Group " + std::to_wstring(groupId));
if (!objGroupData.m_groupIds.empty()) {
int i;
for (i = 0; i < objGroupData.m_groupIds.size(); i++) {
obj->setGroupId(objGroupData.m_groupIds[i]);
obj->setGroupName(objGroupData.m_groupNames[i]);
}
for (i = 0; i < objGroupData.m_groupIds.size() &&
objGroupData.m_editingGroup >= 0;
i++)
obj->editGroup();
}
// add all pegbar
bringObjectOut(table, xsh, ids, splines, pegObjects, pegbarIndex,
objGroupData, groupId);
}
// add columns;
FxDag *innerDag = subXsh->getFxDag();
FxDag *outerDag = xsh->getFxDag();
TStageObjectId tmpParentId = parentId;
std::set<int> indexes;
int i;
for (i = 0; i < subXsh->getColumnCount(); i++) {
TXshColumn *innerColumn = subXsh->getColumn(i);
TXshColumn *outerColumn = innerColumn->clone();
TFx *innerFx = innerColumn->getFx();
TFx *outerFx = outerColumn->getFx();
xsh->insertColumn(index, outerColumn);
// the above insertion operation may increment the parentId, in case that
// 1, the parent object is column, and
// 2, the parent column is placed on the right side of the inserted column
// ( i.e. index of the parent column is equal to or higher than "index")
if (onlyColumn && tmpParentId.isColumn() && tmpParentId.getIndex() >= index)
tmpParentId = TStageObjectId::ColumnId(tmpParentId.getIndex() + 1);
if (innerFx && outerFx) {
outerFx->getAttributes()->setDagNodePos(
innerFx->getAttributes()->getDagNodePos());
fxs[innerColumn->getFx()] =
QPair<TFx *, int>(outerColumn->getFx(), outerColumn->getIndex());
if (!innerDag->getTerminalFxs()->containsFx(innerColumn->getFx()))
outerDag->getTerminalFxs()->removeFx(outerColumn->getFx());
}
TStageObjectId innerId = TStageObjectId::ColumnId(i);
TStageObjectId outerId = TStageObjectId::ColumnId(index);
TStageObject *innerCol = innerTree->getStageObject(innerId, false);
TStageObject *outerCol = outerTree->getStageObject(outerId, false);
TStageObjectParams *params = innerCol->getParams();
if (params->m_spline) {
if (splines.contains(params->m_spline))
params->m_spline = splines[params->m_spline];
else {
TStageObjectSpline *spline = params->m_spline->clone();
splines[params->m_spline] = spline;
outerTree->assignUniqueSplineId(spline);
outerTree->insertSpline(spline);
params->m_spline = spline;
}
}
outerCol->assignParams(params);
outerCol->setDagNodePos(innerCol->getDagNodePos());
delete params;
assert(outerCol && innerCol);
ids[innerId] = outerId;
outerCol->removeFromAllGroup();
if (groupId != -1) {
outerCol->setGroupId(groupId);
outerCol->setGroupName(L"Group " + std::to_wstring(groupId));
}
if (onlyColumn) outerCol->setParent(tmpParentId);
// Put in the right StageObject group if needed
if (!objGroupData.m_groupIds.empty()) {
int j;
for (j = 0; j < objGroupData.m_groupIds.size(); j++) {
outerCol->setGroupId(objGroupData.m_groupIds[j]);
outerCol->setGroupName(objGroupData.m_groupNames[j]);
}
for (j = 0; j < objGroupData.m_groupIds.size() &&
objGroupData.m_editingGroup >= 0;
j++)
outerCol->editGroup();
}
// Put in the right Fx group if needed
if (outerFx && !fxGroupData.m_groupIds.empty()) {
int j;
for (j = 0; j < fxGroupData.m_groupIds.size(); j++) {
outerColumn->getFx()->getAttributes()->setGroupId(
fxGroupData.m_groupIds[j]);
outerColumn->getFx()->getAttributes()->setGroupName(
fxGroupData.m_groupNames[j]);
}
for (j = 0;
j < fxGroupData.m_groupIds.size() && fxGroupData.m_editingGroup >= 0;
j++)
outerColumn->getFx()->getAttributes()->editGroup();
}
indexes.insert(index);
index++;
}
// setting column parents
for (i = 0; i < subXsh->getColumnCount() && !onlyColumn; i++) {
TStageObjectId innerId = TStageObjectId::ColumnId(i);
TStageObject *innerCol = innerTree->getStageObject(innerId, false);
xsh->setStageObjectParent(ids[innerId], ids[innerCol->getParent()]);
}
TPointD middlePoint;
int objCount = 0;
QMap<TStageObjectId, TStageObjectId>::iterator it;
for (it = ids.begin(); it != ids.end(); it++) {
TStageObject *innerObj = innerTree->getStageObject(it.key(), false);
if (!innerObj) continue;
const TPointD &pos = innerObj->getDagNodePos();
if (pos == TConst::nowhere) continue;
middlePoint = middlePoint + pos;
++objCount;
}
middlePoint = TPointD(middlePoint.x / objCount, middlePoint.y / objCount);
// faccio in modo che tutti i nodi estratti siano centrati in middlePoint
// Li metto poi in un gruppo
TPointD offset = middlePoint - subPos;
for (it = ids.begin(); it != ids.end(); it++) {
TStageObject *outerObj = outerTree->getStageObject(it.value(), false);
if (!outerObj) continue;
/*outerObj->setGroupId(groupId);
outerObj->setGroupName(L"Group "+toWideString(groupId));*/
TPointD outerPos = outerObj->getDagNodePos();
if (outerPos != TConst::nowhere) outerObj->setDagNodePos(outerPos - offset);
}
return indexes;
}
//-----------------------------------------------------------------------------
void explodeFxs(TXsheet *xsh, TXsheet *subXsh, const GroupData &fxGroupData,
QMap<TFx *, QPair<TFx *, int>> &fxs, const TPointD &subPos,
const std::vector<TFxPort *> &outPorts, bool linkToXsheet) {
FxDag *innerDag = subXsh->getFxDag();
FxDag *outerDag = xsh->getFxDag();
bool explosionLinked = false;
// taking out all the effects that start from the xsheet.
// xsheet node will be replaced by the over fx node if necessary.
// root will be null if the xsheet node will not bring out to the parent
// fxdag.
TFx *root = explodeFxSubTree(innerDag->getXsheetFx(), fxs, outerDag, xsh,
innerDag, fxGroupData, outPorts);
// in case the child and parent Xsheet nodes will be "merged"
if (!root) {
TFxSet *internals = innerDag->getTerminalFxs();
for (int j = 0; j < internals->getFxCount(); j++) {
TFx *fx = internals->getFx(j);
outerDag->addToXsheet(fxs[fx].first);
}
explosionLinked = true;
}
// taking out all the effects that start from output nodes
for (int i = 0; i < innerDag->getOutputFxCount(); i++) {
TOutputFx *outFx = innerDag->getOutputFx(i);
bool isCurrent = (outFx == innerDag->getCurrentOutputFx());
// the link is done before tracing from the current out put node.
// it means that all the fxs before the output node are already exploded and
// connected.
if (isCurrent && explosionLinked) continue;
TFx *root = explodeFxSubTree(outFx, fxs, outerDag, xsh, innerDag,
fxGroupData, outPorts);
// If the output node is not connected to any other node
if (!root) continue;
if (isCurrent) {
// link the root node to the xsheet node if:
// a) the subxsheet column is connected to the xsheet node, OR
// b) the original subxsheet column will not be deleted and the exploded
// column will be inserted.
// (this case happens when the subxsheet column contains multiple
// levels. outPorts is empty in such case)
if (linkToXsheet)
outerDag->addToXsheet(root); // connect to the xsheet node
for (int j = 0; j < outPorts.size(); j++) outPorts[j]->setFx(root);
explosionLinked = true;
}
}
// taking out all the other effects!
TFxSet *innerInternals = innerDag->getInternalFxs();
for (int i = 0; i < innerInternals->getFxCount(); i++) {
TFx *fx = innerInternals->getFx(i);
if (fxs.contains(fx)) continue;
explodeFxSubTree(fx, fxs, outerDag, xsh, innerDag, fxGroupData, outPorts);
}
assert(explosionLinked);
// cerco il punto medio tra tutti i nodi
TPointD middlePoint(0.0, 0.0);
int fxsCount = 0;
QMap<TFx *, QPair<TFx *, int>>::iterator it;
for (it = fxs.begin(); it != fxs.end(); it++) {
TFx *innerFx = it.key();
if (!innerFx) continue;
assert(innerFx->getAttributes());
const TPointD &pos = innerFx->getAttributes()->getDagNodePos();
if (pos == TConst::nowhere) continue;
middlePoint = middlePoint + pos;
++fxsCount;
}
if (fxsCount > 0)
middlePoint = TPointD(middlePoint.x / fxsCount, middlePoint.y / fxsCount);
else
middlePoint = TPointD(25000, 25000); // center of the scene
// faccio in modo che tutti i nodi estratti siano centrati in middlePoint
// Li metto poi in un gruppo
TPointD offset = middlePoint - subPos;
int groupId = outerDag->getNewGroupId();
for (it = fxs.begin(); it != fxs.end(); it++) {
QPair<TFx *, int> pair = it.value();
TFx *outerFx = pair.first;
// skip redundant item. in case when only one node is input to the xsheet
// node in the inner dag
if (!outerFx) continue;
if (outerFx->getAttributes()->getGroupId() == groupId) continue;
outerFx->getAttributes()->setGroupId(groupId);
outerFx->getAttributes()->setGroupName(L"Group " +
std::to_wstring(groupId));
TPointD outerFxPos = outerFx->getAttributes()->getDagNodePos();
if (outerFxPos != TConst::nowhere)
outerFx->getAttributes()->setDagNodePos(outerFxPos - offset);
}
}
//-----------------------------------------------------------------------------
template <typename ParamCont>
void setGrammerToParams(const ParamCont *cont,
const TSyntax::Grammar *grammer) {
for (int p = 0; p != cont->getParamCount(); ++p) {
TParam ¶m = *cont->getParam(p);
if (TDoubleParam *dp = dynamic_cast<TDoubleParam *>(¶m))
dp->setGrammar(grammer);
else if (TParamSet *paramSet = dynamic_cast<TParamSet *>(¶m))
setGrammerToParams(paramSet, grammer);
}
}
//-----------------------------------------------------------------------------
std::set<int> explode(TXsheet *xsh, TXsheet *subXsh, int index,
const TStageObjectId &parentId,
const GroupData &objGroupData, const TPointD &stageSubPos,
const GroupData &fxGroupData, const TPointD &fxSubPos,
QList<TStageObject *> &pegObjects,
QMap<TStageObjectSpline *, TStageObjectSpline *> &splines,
const std::vector<TFxPort *> &outPorts, bool onlyColumn,
bool linkToXsheet) {
// innerFx->outerFxs
QMap<TFx *, QPair<TFx *, int>> fxs;
// inner id->outer id
QMap<TStageObjectId, TStageObjectId> objIds;
std::set<int> indexes = explodeStageObjects(
xsh, subXsh, index, parentId, objGroupData, stageSubPos, fxGroupData,
pegObjects, fxs, splines, objIds, onlyColumn);
explodeFxs(xsh, subXsh, fxGroupData, fxs, fxSubPos, outPorts, linkToXsheet);
assert(TApp::instance()->getCurrentXsheet()->getXsheet() == xsh);
// reset grammers for all parameters brought out to the parent xsheet
TSyntax::Grammar *grammer = xsh->getStageObjectTree()->getGrammar();
for (auto id : objIds.values()) {
TStageObject *obj = xsh->getStageObject(id);
for (int c = 0; c != TStageObject::T_ChannelCount; ++c)
obj->getParam((TStageObject::Channel)c)->setGrammar(grammer);
if (const PlasticSkeletonDeformationP &sd =
obj->getPlasticSkeletonDeformation())
sd->setGrammar(grammer);
}
QMap<TFx *, TFx *> fxMap;
for (auto it = fxs.constBegin(); it != fxs.constEnd(); ++it) {
if (it.value().first == nullptr) continue;
setGrammerToParams(it.value().first->getParams(), grammer);
fxMap.insert(it.key(), it.value().first);
}
ExpressionReferenceManager::instance()->transferReference(subXsh, xsh, objIds,
fxMap);
return indexes;
}
//=============================================================================
// OpenChildUndo
//-----------------------------------------------------------------------------
class OpenChildUndo final : public TUndo {
int m_row, m_col;
public:
OpenChildUndo() {
TApp *app = TApp::instance();
m_row = app->getCurrentFrame()->getFrame();
m_col = app->getCurrentColumn()->getColumnIndex();
TXsheet *xsh = app->getCurrentXsheet()->getXsheet();
TXshCell cell = xsh->getCell(m_row, m_col);
}
void undo() const override {
TApp *app = TApp::instance();
ToonzScene *scene = app->getCurrentScene()->getScene();
int row, col;
scene->getChildStack()->closeChild(row, col);
app->getCurrentXsheet()->setXsheet(scene->getXsheet());
changeSaveSubXsheetAsCommand();
}
void redo() const override {
TApp *app = TApp::instance();
ToonzScene *scene = app->getCurrentScene()->getScene();
scene->getChildStack()->openChild(m_row, m_col);
app->getCurrentXsheet()->setXsheet(scene->getXsheet());
changeSaveSubXsheetAsCommand();
}
int getSize() const override { return sizeof(*this); }
};
//=============================================================================
// CloseChildUndo
//-----------------------------------------------------------------------------
class CloseChildUndo final : public TUndo {
std::vector<std::pair<int, int>> m_cells;
public:
CloseChildUndo(const std::vector<std::pair<int, int>> &cells)
: m_cells(cells) {}
void undo() const override {
TApp *app = TApp::instance();
ToonzScene *scene = app->getCurrentScene()->getScene();
for (int i = m_cells.size() - 1; i >= 0; i--) {
std::pair<int, int> rowCol = m_cells[i];
scene->getChildStack()->openChild(rowCol.first, rowCol.second);
}
app->getCurrentXsheet()->setXsheet(scene->getXsheet());
changeSaveSubXsheetAsCommand();
}
void redo() const override {
TApp *app = TApp::instance();
ToonzScene *scene = app->getCurrentScene()->getScene();
for (int i = 0; i < (int)m_cells.size(); i++) {
int row, col;
scene->getChildStack()->closeChild(row, col);
}
app->getCurrentXsheet()->setXsheet(scene->getXsheet());
changeSaveSubXsheetAsCommand();
}
int getSize() const override { return sizeof(*this); }
QString getHistoryString() override { return QObject::tr("Close SubXsheet"); }
int getHistoryType() override { return HistoryType::Xsheet; }
};
//=============================================================================
void openSubXsheet() {
TApp *app = TApp::instance();
/*- Enter only when ChildLevel exists in selected cell or selected column -*/
TCellSelection *cellSelection =
dynamic_cast<TCellSelection *>(TSelection::getCurrent());
TColumnSelection *columnSelection =
dynamic_cast<TColumnSelection *>(TSelection::getCurrent());
bool ret = false;
ToonzScene *scene = app->getCurrentScene()->getScene();
int row = app->getCurrentFrame()->getFrame();
int col = app->getCurrentColumn()->getColumnIndex();
TXsheet *currentXsheet = app->getCurrentXsheet()->getXsheet();
TXshCell targetCell;
/*- For column selection -*/
if (columnSelection && !columnSelection->isEmpty()) {
int sceneLength = currentXsheet->getFrameCount();
std::set<int> columnIndices = columnSelection->getIndices();
/*- Try openChild on each cell for each Column -*/
for (auto const &c : columnIndices) {
// See if the current row indicator is on an exposed sub-xsheet frame
// If so, use that.
targetCell = currentXsheet->getCell(row, c);
if (!targetCell.isEmpty() &&
(ret = scene->getChildStack()->openChild(row, c)))
break;
/*- For each Cell in the Column, if contents are found break -*/
for (int r = 0; r < sceneLength; r++) {
ret = scene->getChildStack()->openChild(r, c);
if (ret) {
targetCell = currentXsheet->getCell(r, c);
break;
}
}
if (ret) break;
}
}
/*- In other cases (cell selection or other) -*/
else {
TRect selectedArea;
/*- If it is not cell selection, see current frame / column -*/
if (!cellSelection || cellSelection->isEmpty()) {
/*- When it is not cell selection, 1 × 1 selection range -*/
selectedArea = TRect(col, row, col, row);
}
/*- In case of cell selection -*/
else {
int r0, c0, r1, c1;
cellSelection->getSelectedCells(r0, c0, r1, c1);
selectedArea = TRect(c0, r0, c1, r1);
}
/*- Try openChild on each cell in Rect -*/
for (int c = selectedArea.x0; c <= selectedArea.x1; c++) {
for (int r = selectedArea.y0; r <= selectedArea.y1; r++) {
ret = scene->getChildStack()->openChild(r, c);
if (ret) {
// When opening based on cell selection use the 1st
// exposed frame in the sub-xsheet it finds
targetCell = currentXsheet->getCell(r, c);
break;
}
}
if (ret) break;
}
}
/*- When subXsheet Level is found -*/
if (ret) {
int subXsheetFrame = 0;
if (!targetCell.isEmpty())
subXsheetFrame = targetCell.getFrameId().getNumber() - 1;
if (TSelection::getCurrent()) TSelection::getCurrent()->selectNone();
TUndoManager::manager()->add(new OpenChildUndo());
app->getCurrentXsheet()->setXsheet(scene->getXsheet());
app->getCurrentXsheet()->notifyXsheetChanged();
app->getCurrentColumn()->setColumnIndex(0);
app->getCurrentFrame()->setFrameIndex(subXsheetFrame);
changeSaveSubXsheetAsCommand();
} else
DVGui::error(QObject::tr("Select a sub-xsheet cell."));
}
//=============================================================================
void closeSubXsheet(int dlevel) {
if (dlevel < 1) return;
TApp *app = TApp::instance();
TSelection *selection =
TApp::instance()->getCurrentSelection()->getSelection();
if (selection) selection->selectNone();
ToonzScene *scene = app->getCurrentScene()->getScene();
int ancestorCount = scene->getChildStack()->getAncestorCount();
if (ancestorCount == 0) return;
if (dlevel > ancestorCount) dlevel = ancestorCount;
std::vector<std::pair<int, int>> cells;
for (int i = 0; i < dlevel; i++) {
std::pair<int, int> rowCol;
scene->getChildStack()->closeChild(rowCol.first, rowCol.second);
TXsheet *xsh = scene->getXsheet();
IconGenerator::instance()->invalidate(
xsh->getCell(rowCol.first, rowCol.second).m_level.getPointer(),
TFrameId(1));
cells.push_back(rowCol);
}
if (cells.empty()) return;
TUndoManager::manager()->add(new CloseChildUndo(cells));
app->getCurrentXsheet()->setXsheet(scene->getXsheet());
app->getCurrentXsheet()->notifyXsheetChanged();
app->getCurrentColumn()->setColumnIndex(cells[0].second);
app->getCurrentFrame()->setFrameIndex(cells[0].first);
changeSaveSubXsheetAsCommand();
}
//=============================================================================
// returns true if there is at least one pegbar to be brought inside subxsheet
// on collase in order to see if the confirmation dialog is needed
bool hasPegbarsToBringInsideChildXsheet(TXsheet *xsh,
const std::set<int> &indices) {
for (auto itr = indices.cbegin(); itr != indices.cend(); itr++) {
TStageObjectId id =
xsh->getStageObjectParent(TStageObjectId::ColumnId(*itr));
// check the parent node
if (id.isPegbar() || id.isCamera()) return true;
}
return false;
}
//-----------------------------------------------------------------------------
void bringPegbarsInsideChildXsheet(
TXsheet *xsh, TXsheet *childXsh, std::set<int> indices,
std::set<int> newIndices, QMap<TStageObjectId, TStageObjectId> &idTable) {
// columns in the child xsheet are all connected to the table for now.
// so we need to take parental connection information from the parent xsheet.
// retrieve all pegbars used from copied columns
std::set<TStageObjectId> pegbarIds;
std::set<int>::iterator itr = indices.begin();
std::set<int>::iterator new_itr = newIndices.begin();
while (itr != indices.end()) {
TStageObjectId id =
xsh->getStageObjectParent(TStageObjectId::ColumnId(*itr));
TStageObjectId newCol = TStageObjectId::ColumnId(*new_itr);
if (id.isPegbar() || id.isCamera())
childXsh->setStageObjectParent(newCol, id);
/*- Columnの上流のPegbar/Cameraを格納していく -*/
while (id.isPegbar() || id.isCamera()) {
pegbarIds.insert(id);
id = xsh->getStageObjectParent(id);
}
itr++;
new_itr++;
}
std::set<TStageObjectId>::iterator pegbarIt;
for (pegbarIt = pegbarIds.begin(); pegbarIt != pegbarIds.end(); ++pegbarIt) {
TStageObjectId id = *pegbarIt;
TStageObjectParams *data = xsh->getStageObject(id)->getParams();
TStageObject *obj = childXsh->getStageObject(id);
obj->assignParams(data);
delete data;
obj->setParent(xsh->getStageObjectParent(id));
// reset grammers of all parameters or they fails to refer to other
// parameters via expression
for (int c = 0; c != TStageObject::T_ChannelCount; ++c)
childXsh->getStageObjectTree()->setGrammar(
obj->getParam((TStageObject::Channel)c));
// register pegbars to the table
idTable.insert(id, id);
}
}
//-----------------------------------------------------------------------------
void removeFx(TXsheet *xsh, TFx *fx) {
TOutputFx *outFx = dynamic_cast<TOutputFx *>(fx);
if (outFx) {
xsh->getFxDag()->removeOutputFx(outFx);
return;
}
TFxSet *internalFx = xsh->getFxDag()->getInternalFxs();
TFxSet *terminalFx = xsh->getFxDag()->getTerminalFxs();
int j;
for (j = 0; j < fx->getInputPortCount(); j++) {
TFxPort *inputPort = fx->getInputPort(j);
TFx *inputFx = inputPort->getFx();
if (inputFx && j == 0) {
int k;
for (k = fx->getOutputConnectionCount() - 1; k >= 0; k--) {
TFxPort *outputPort = fx->getOutputConnection(k);
outputPort->setFx(inputFx);
}
if (terminalFx->containsFx(fx)) {
terminalFx->removeFx(fx);
terminalFx->addFx(inputFx);
}
}
int i;
for (i = fx->getOutputConnectionCount() - 1; i >= 0; i--)
fx->getOutputConnection(i)->setFx(inputPort->getFx());
inputPort->setFx(0);
}
internalFx->removeFx(fx);
}
//-----------------------------------------------------------------------------
void collapseColumns(std::set<int> indices, bool columnsOnly) {
// return if there is no selected columns
if (indices.empty()) return;
int index = *indices.begin();
TApp *app = TApp::instance();
TXsheet *xsh = app->getCurrentXsheet()->getXsheet();
std::set<int> oldIndices = indices;
StageObjectsData *data = new StageObjectsData();
// store xsheet data to be collapsed
data->storeColumns(indices, xsh, StageObjectsData::eDoClone);
data->storeColumnFxs(indices, xsh, StageObjectsData::eDoClone);
// ExpressionReferenceMonitor *monitor = xsh->getExpRefMonitor()->clone();
ToonzScene *scene = app->getCurrentScene()->getScene();
TXshLevel *xl = scene->createNewLevel(CHILD_XSHLEVEL);
assert(xl);
TXshChildLevel *childLevel = xl->getChildLevel();
assert(childLevel);
TXsheet *childXsh = childLevel->getXsheet();
std::set<int> newIndices;
std::list<int> restoredSplineIds;
QMap<TStageObjectId, TStageObjectId> idTable;
QMap<TFx *, TFx *> fxTable;
// restore data into sub xsheet
data->restoreObjects(newIndices, restoredSplineIds, childXsh, 0, idTable,
fxTable);
// bring pegbars into sub xsheet
if (!columnsOnly)
bringPegbarsInsideChildXsheet(xsh, childXsh, indices, newIndices, idTable);
ExpressionReferenceManager::instance()->refreshXsheetRefInfo(childXsh);
ExpressionReferenceManager::instance()->transferReference(xsh, childXsh,
idTable, fxTable);
childXsh->updateFrameCount();
app->getCurrentXsheet()->blockSignals(true);
app->getCurrentObject()->blockSignals(true);
// remove columns in the parent xsheet
ColumnCmd::deleteColumns(indices, false, true);
app->getCurrentXsheet()->blockSignals(false);
app->getCurrentObject()->blockSignals(false);
// insert subxsheet column at the leftmost of the deleted columns
xsh->insertColumn(index);
// set subxsheet cells in the parent xhseet
int r, rowCount = childXsh->getFrameCount();
for (r = 0; r < rowCount; ++r)
xsh->setCell(r, index, TXshCell(xl, TFrameId(r + 1)));
// the subxsheet node will always be connected to the table
// regardless of the "columns only" option
xsh->getStageObject(TStageObjectId::ColumnId(index))
->setParent(TStageObjectId::TableId);
xsh->updateFrameCount();
// copy camera info
// xsh -> childXsh
TStageObjectTree *parentTree = xsh->getStageObjectTree();
TStageObjectTree *childTree = childXsh->getStageObjectTree();
int tmpCamId = 0;
for (int cam = 0; cam < parentTree->getCameraCount();) {
TStageObject *parentCamera =
parentTree->getStageObject(TStageObjectId::CameraId(tmpCamId), false);
// skip the deleted camera
if (!parentCamera) {
tmpCamId++;
continue;
}
// if the camera exists
if (parentCamera->getCamera()) {
// obtain the correspondent camera in subxsheet. create it if it does not
// exist
TCamera *childCamera =
childTree->getStageObject(TStageObjectId::CameraId(tmpCamId))
->getCamera();
if (parentCamera && childCamera) {
childCamera->setRes(parentCamera->getCamera()->getRes());
childCamera->setSize(parentCamera->getCamera()->getSize());
}
}
tmpCamId++;
cam++;
}
// sync the current camera
childTree->setCurrentCameraId(parentTree->getCurrentCameraId());
app->getCurrentXsheet()->notifyXsheetChanged();
app->getCurrentScene()->setDirtyFlag(true);
app->getCurrentObject()->notifyObjectIdSwitched();
}
//-----------------------------------------------------------------------------
void collapseColumns(std::set<int> indices,
const QList<TStageObjectId> &objIds) {
if (indices.empty()) return;
TApp *app = TApp::instance();
TXsheet *xsh = app->getCurrentXsheet()->getXsheet();
std::set<int> oldIndices = indices;
int index = *indices.begin();
std::vector<TStageObjectId> roots = getRoots(objIds, app->getCurrentXsheet());
TStageObject *rootObj = 0;
if (roots.size() == 1) {
rootObj = xsh->getStageObjectTree()->getStageObject(roots[0], false);
assert(rootObj);
}
StageObjectsData *data = new StageObjectsData();
data->storeObjects(objIds.toVector().toStdVector(), xsh,
StageObjectsData::eDoClone);
data->storeColumnFxs(indices, xsh, StageObjectsData::eDoClone);
// ExpressionReferenceMonitor *monitor = xsh->getExpRefMonitor()->clone();
ToonzScene *scene = app->getCurrentScene()->getScene();
TXshLevel *xl = scene->createNewLevel(CHILD_XSHLEVEL);
assert(xl);
TXshChildLevel *childLevel = xl->getChildLevel();
assert(childLevel);
TXsheet *childXsh = childLevel->getXsheet();
std::set<int> newIndices;
std::list<int> restoredSplineIds;
QMap<TStageObjectId, TStageObjectId> idTable;
QMap<TFx *, TFx *> fxTable;
data->restoreObjects(newIndices, restoredSplineIds, childXsh, 0, idTable,
fxTable);
childXsh->updateFrameCount();
ExpressionReferenceManager::instance()->refreshXsheetRefInfo(childXsh);
ExpressionReferenceManager::instance()->transferReference(xsh, childXsh,
idTable, fxTable);
app->getCurrentXsheet()->blockSignals(true);
app->getCurrentObject()->blockSignals(true);
ColumnCmd::deleteColumns(indices, false, true);
app->getCurrentXsheet()->blockSignals(false);
app->getCurrentObject()->blockSignals(false);
xsh->insertColumn(index);
int r, rowCount = childXsh->getFrameCount();
for (r = 0; r < rowCount; r++)
xsh->setCell(r, index, TXshCell(xl, TFrameId(r + 1)));
if (roots.size() == 1 && rootObj)
xsh->getStageObject(TStageObjectId::ColumnId(index))
->setParent(rootObj->getId());
else
xsh->getStageObject(TStageObjectId::ColumnId(index))
->setParent(TStageObjectId::TableId);
xsh->updateFrameCount();
app->getCurrentXsheet()->notifyXsheetChanged();
app->getCurrentScene()->setDirtyFlag(true);
app->getCurrentObject()->notifyObjectIdSwitched();
}
//-----------------------------------------------------------------------------
void collapseColumns(std::set<int> indices, const std::set<TFx *> &fxs,
bool columnsOnly) {
if (indices.empty()) return;
int index = *indices.begin();
TApp *app = TApp::instance();
TXsheet *xsh = app->getCurrentXsheet()->getXsheet();
std::set<int> oldIndices = indices;
//++++++++++++++++++++++++++++++
StageObjectsData *data = new StageObjectsData();
data->storeColumns(indices, xsh, StageObjectsData::eDoClone);
data->storeFxs(fxs, xsh, StageObjectsData::eDoClone);
// ExpressionReferenceMonitor *monitor = xsh->getExpRefMonitor()->clone();
ToonzScene *scene = app->getCurrentScene()->getScene();
TXshLevel *xl = scene->createNewLevel(CHILD_XSHLEVEL);
assert(xl);
TXshChildLevel *childLevel = xl->getChildLevel();
assert(childLevel);
TXsheet *childXsh = childLevel->getXsheet();
std::set<int> newIndices;
std::list<int> restoredSplineIds;
QMap<TStageObjectId, TStageObjectId> idTable;
QMap<TFx *, TFx *> fxTable;
data->restoreObjects(newIndices, restoredSplineIds, childXsh, 0, idTable,
fxTable);
if (!columnsOnly)
bringPegbarsInsideChildXsheet(xsh, childXsh, indices, newIndices, idTable);
ExpressionReferenceManager::instance()->refreshXsheetRefInfo(childXsh);
ExpressionReferenceManager::instance()->transferReference(xsh, childXsh,
idTable, fxTable);
childXsh->updateFrameCount();
std::map<TFx *, std::vector<TFxPort *>> roots =
isConnected(indices, fxs, app->getCurrentXsheet());
app->getCurrentXsheet()->blockSignals(true);
app->getCurrentObject()->blockSignals(true);
ColumnCmd::deleteColumns(indices, true, true);
app->getCurrentXsheet()->blockSignals(false);
app->getCurrentObject()->blockSignals(false);
xsh->insertColumn(index);
std::set<TFx *>::const_iterator it;
for (it = fxs.begin(); it != fxs.end(); it++) {
TOutputFx *output = dynamic_cast<TOutputFx *>(*it);
if (output) xsh->getFxDag()->removeOutputFx(output);
}
int rowCount = childXsh->getFrameCount();
int r;
for (r = 0; r < rowCount; r++)
xsh->setCell(r, index, TXshCell(xl, TFrameId(r + 1)));
//++++++++++++++++++++++++++++++
// Rimuovo gli effetti che sono in fxs dall'xsheet
std::set<TFx *>::const_iterator it2;
for (it2 = fxs.begin(); it2 != fxs.end(); it2++) removeFx(xsh, *it2);
xsh->getStageObject(TStageObjectId::ColumnId(index))
->setParent(TStageObjectId::TableId);
if (roots.size() == 1) {
TFx *fx = xsh->getColumn(index)->getFx();
std::vector<TFxPort *> rootPorts = roots.begin()->second;
int i;
for (i = 0; i < rootPorts.size(); i++) rootPorts[i]->setFx(fx);
xsh->getFxDag()->getTerminalFxs()->removeFx(fx);
}
xsh->updateFrameCount();
app->getCurrentXsheet()->notifyXsheetChanged();
app->getCurrentScene()->setDirtyFlag(true);
app->getCurrentObject()->notifyObjectIdSwitched();
}
//-----------------------------------------------------------------------------
void getColumnIndexes(const QList<TStageObjectId> &objects,
std::set<int> &indeces) {
int i;
for (i = 0; i < objects.size(); i++) {
if (objects[i].isColumn()) indeces.insert(objects[i].getIndex());
}
}
//-----------------------------------------------------------------------------
void getColumnIndexesAndPegbarIds(const QList<TStageObjectId> &objects,
std::set<int> &indeces,
std::set<TStageObjectId> &pegbarIds) {
int i;
for (i = 0; i < objects.size(); i++) {
if (objects[i].isColumn()) indeces.insert(objects[i].getIndex());
if (objects[i].isPegbar()) pegbarIds.insert(objects[i]);
}
}
//-----------------------------------------------------------------------------
void getColumnIndexesAndInternalFxs(const QList<TFxP> &fxs,
std::set<int> &indices,
std::set<TFx *> &internalFx) {
int i;
for (i = 0; i < fxs.size(); i++) {
TFx *fx = fxs[i].getPointer();
TColumnFx *cFx = dynamic_cast<TColumnFx *>(fx);
if (cFx)
indices.insert(cFx->getColumnIndex());
else {
TXsheetFx *xshFx = dynamic_cast<TXsheetFx *>(fx);
TOutputFx *outFx = dynamic_cast<TOutputFx *>(fx);
if (xshFx) continue;
if (outFx) {
TXsheetFx *xshFx =
dynamic_cast<TXsheetFx *>(outFx->getInputPort(0)->getFx());
if (xshFx) continue;
}
internalFx.insert(fx);
fx->addRef();
}
}
}
//=============================================================================
// CollapseUndo
//-----------------------------------------------------------------------------
class CollapseUndo : public TUndo {
protected:
std::set<int> m_indices;
StageObjectsData *m_data;
StageObjectsData *m_newData;
int m_columnIndex;
QMap<TFx *, QList<TFxPort *>> m_columnOutputConnections;
QMap<TStageObjectId, QList<TStageObjectId>> m_children;
// id->parentId
QMap<TStageObjectId, TStageObjectId> m_parents;
void doUndo() const {
TApp *app = TApp::instance();
TXsheet *xsh = app->getCurrentXsheet()->getXsheet();
xsh->removeColumn(m_columnIndex);
std::set<int> indices = m_indices;
std::list<int> restoredSplineIds;
m_data->restoreObjects(indices, restoredSplineIds, xsh, 0);
setColumnOutputConnections(m_columnOutputConnections);
setChildren(m_children);
setParents(m_parents);
TColumnSelection *selection = dynamic_cast<TColumnSelection *>(
app->getCurrentSelection()->getSelection());
if (selection) {
selection->selectNone();
std::set<int> selectIndices = m_indices;
std::set<int>::const_iterator indicesIt = selectIndices.begin();
while (indicesIt != selectIndices.end())
selection->selectColumn(*indicesIt++);
}
}
void doRedo(bool deleteOnlyColumns) const {
TApp *app = TApp::instance();
TXsheet *xsh = app->getCurrentXsheet()->getXsheet();
std::set<int> indicesToRemove = m_indices;
QMap<TFx *, QList<TFxPort *>> columnOutputConnections;
getColumnOutputConnections(m_indices, columnOutputConnections);
app->getCurrentXsheet()->blockSignals(true);
app->getCurrentObject()->blockSignals(true);
ColumnCmd::deleteColumns(indicesToRemove, deleteOnlyColumns, true);
app->getCurrentXsheet()->blockSignals(false);
app->getCurrentObject()->blockSignals(false);
setColumnOutputConnections(columnOutputConnections);
std::set<int> indices;
indices.insert(m_columnIndex);
std::list<int> restoredSplineIds;
m_newData->restoreObjects(indices, restoredSplineIds, xsh, 0);
TColumnSelection *selection = dynamic_cast<TColumnSelection *>(
app->getCurrentSelection()->getSelection());
if (selection) {
selection->selectNone();
selection->selectColumn(m_columnIndex);
}
}
public:
CollapseUndo(const std::set<int> indices, int c0, StageObjectsData *data,
StageObjectsData *newData,
const QMap<TFx *, QList<TFxPort *>> &columnOutputConnections,
const QMap<TStageObjectId, QList<TStageObjectId>> &children,
const QMap<TStageObjectId, TStageObjectId> &parents)
: m_indices(indices)
, m_columnIndex(c0)
, m_data(data)
, m_newData(newData)
, m_columnOutputConnections(columnOutputConnections)
, m_children(children)
, m_parents(parents) {}
~CollapseUndo() {
delete m_data;
delete m_newData;
}
void undo() const override {
doUndo();
TApp *app = TApp::instance();
app->getCurrentXsheet()->notifyXsheetChanged();
app->getCurrentObject()->notifyObjectIdSwitched();
changeSaveSubXsheetAsCommand();
}
void redo() const override {
doRedo(false);
TApp *app = TApp::instance();
app->getCurrentXsheet()->notifyXsheetChanged();
app->getCurrentObject()->notifyObjectIdSwitched();
changeSaveSubXsheetAsCommand();
}
int getSize() const override { return sizeof(*this); }
QString getHistoryString() override { return QObject::tr("Collapse"); }
int getHistoryType() override { return HistoryType::Xsheet; }
};
//=============================================================================
// CollapseFxUndo
//-----------------------------------------------------------------------------
class CollapseFxUndo final : public CollapseUndo {
std::set<TFx *> m_fxs;
QMap<TFx *, FxConnections> m_fxConnections;
public:
CollapseFxUndo(const std::set<int> indices, int c0, StageObjectsData *data,
StageObjectsData *newData,
const QMap<TFx *, QList<TFxPort *>> &columnOutputConnections,
const QMap<TStageObjectId, QList<TStageObjectId>> children,
const QMap<TStageObjectId, TStageObjectId> &parents,
const std::set<TFx *> &fxs,
const QMap<TFx *, FxConnections> fxConnections)
: CollapseUndo(indices, c0, data, newData, columnOutputConnections,
children, parents)
, m_fxs(fxs)
, m_fxConnections(fxConnections) {}
~CollapseFxUndo() {
for (auto const &e : m_fxs) e->release();
}
void undo() const override {
doUndo();
TApp *app = TApp::instance();
TXsheet *xsh = app->getCurrentXsheet()->getXsheet();
TFxSet *internalFxs = xsh->getFxDag()->getInternalFxs();
TFxSet *terminalFxs = xsh->getFxDag()->getTerminalFxs();
for (auto const &e : m_fxs)
if (!internalFxs->containsFx(e)) {
TOutputFx *outFx = dynamic_cast<TOutputFx *>(e);
if (outFx)
xsh->getFxDag()->addOutputFx(outFx);
else
internalFxs->addFx(e);
}
QMap<TFx *, FxConnections>::const_iterator it2;
for (it2 = m_fxConnections.begin(); it2 != m_fxConnections.end(); it2++) {
TFx *fx = it2.key();
FxConnections connections = it2.value();
QMap<int, TFx *> inputLinks = connections.getInputLinks();
QMap<int, TFx *>::const_iterator it3;
for (it3 = inputLinks.begin(); it3 != inputLinks.end(); it3++)
fx->getInputPort(it3.key())->setFx(it3.value());
if (connections.isTerminal()) {
terminalFxs->addFx(fx);
QList<TFx *> noTerminalInputFxs = connections.getNotTerminalInputFxs();
int i;
for (i = 0; i < noTerminalInputFxs.size(); i++)
if (terminalFxs->containsFx(noTerminalInputFxs[i]))
terminalFxs->removeFx(noTerminalInputFxs[i]);
}
QMap<TFx *, int> outputLinks = connections.getOutputLinks();
QMap<TFx *, int>::const_iterator it4;
for (it4 = outputLinks.begin(); it4 != outputLinks.end(); it4++)
it4.key()->getInputPort(it4.value())->setFx(fx);
}
app->getCurrentXsheet()->notifyXsheetChanged();
app->getCurrentObject()->notifyObjectIdSwitched();
changeSaveSubXsheetAsCommand();
}
void redo() const override {
TApp *app = TApp::instance();
TXsheet *xsh = app->getCurrentXsheet()->getXsheet();
std::map<TFx *, std::vector<TFxPort *>> roots =
isConnected(m_indices, m_fxs, app->getCurrentXsheet());
doRedo(true);
std::set<TFx *>::const_iterator it2;
for (it2 = m_fxs.begin(); it2 != m_fxs.end(); it2++) removeFx(xsh, *it2);
if (roots.size() == 1) {
TFx *fx = xsh->getColumn(m_columnIndex)->getFx();
std::vector<TFxPort *> rootPorts = roots.begin()->second;
int i;
for (i = 0; i < rootPorts.size(); i++) rootPorts[i]->setFx(fx);
xsh->getFxDag()->getTerminalFxs()->removeFx(fx);
}
app->getCurrentXsheet()->notifyXsheetChanged();
app->getCurrentObject()->notifyObjectIdSwitched();
changeSaveSubXsheetAsCommand();
}
int getSize() const override { return sizeof(*this); }
QString getHistoryString() override { return QObject::tr("Collapse (Fx)"); }
};
//=============================================================================
// ExplodeChildUndoRemovingColumn
//-----------------------------------------------------------------------------
class ExplodeChildUndoRemovingColumn final : public TUndo {
std::set<int> m_newIndexs;
int m_index;
StageObjectsData *m_oldData;
StageObjectsData *m_newData;
QMap<TFx *, QList<TFxPort *>> m_oldColumnOutputConnections;
QMap<TFx *, QList<TFxPort *>> m_newColumnOutputConnections;
// objId->parentObjId
QMap<TStageObjectId, TStageObjectId> m_parentIds;
QList<TStageObject *> m_pegObjects;
QMap<TStageObjectSpline *, TStageObjectSpline *> m_splines;
TFx *m_root;
std::set<TFx *> m_oldInternalFxs;
std::set<TOutputFx *> m_oldOutFxs;
std::set<TOutputFx *> m_newOutFxs;
// to handle grouping for the subxsheet
QStack<int> m_objGroupIds;
QStack<std::wstring> m_objGroupNames;
public:
ExplodeChildUndoRemovingColumn(
const std::set<int> &newIndexs, int index, StageObjectsData *oldData,
StageObjectsData *newData,
const QMap<TFx *, QList<TFxPort *>> &columnOutputConnections,
const QList<TStageObject *> &pegObjects,
const QMap<TStageObjectSpline *, TStageObjectSpline *> &splines,
const std::set<TFx *> &oldInternalFxs,
const std::set<TOutputFx *> oldOutFxs, TFx *root,
const QStack<int> &objGroupIds, const QStack<std::wstring> &objGroupNames)
: m_newIndexs(newIndexs)
, m_index(index)
, m_oldData(oldData)
, m_newData(newData)
, m_oldColumnOutputConnections(columnOutputConnections)
, m_pegObjects(pegObjects)
, m_splines(splines)
, m_root(root)
, m_oldInternalFxs(oldInternalFxs)
, m_oldOutFxs(oldOutFxs)
, m_objGroupIds(objGroupIds)
, m_objGroupNames(objGroupNames) {
TApp *app = TApp::instance();
TXsheet *xsh = app->getCurrentXsheet()->getXsheet();
std::set<int>::iterator it;
for (it = m_newIndexs.begin(); it != m_newIndexs.end(); it++) {
TXshColumn *column = xsh->getColumn(*it);
TStageObjectId colId = TStageObjectId::ColumnId(*it);
m_parentIds[colId] = xsh->getStageObjectParent(colId);
TFx *columnFx = column->getFx();
if (!columnFx) continue;
QList<TFxPort *> outputConnections;
int i;
for (i = 0; i < columnFx->getOutputConnectionCount(); i++)
outputConnections.append(columnFx->getOutputConnection(i));
m_newColumnOutputConnections[columnFx] = outputConnections;
}
std::set<TOutputFx *>::iterator it2;
for (it2 = m_oldOutFxs.begin(); it2 != m_oldOutFxs.end(); it2++)
(*it2)->addRef();
int i, outFxCount = xsh->getFxDag()->getOutputFxCount();
for (i = 0; i < outFxCount; i++) {
TOutputFx *outFx = xsh->getFxDag()->getOutputFx(i);
m_newOutFxs.insert(outFx);
outFx->addRef();
}
for (int i = 0; i < m_pegObjects.size(); i++)
m_parentIds[m_pegObjects[i]->getId()] = m_pegObjects[i]->getParent();
QMap<TStageObjectSpline *, TStageObjectSpline *>::iterator it3;
for (it3 = m_splines.begin(); it3 != m_splines.end(); it3++)
it3.value()->addRef();
}
~ExplodeChildUndoRemovingColumn() {
delete m_oldData;
delete m_newData;
int i;
for (i = m_pegObjects.size() - 1; i >= 0; i--) m_pegObjects[i]->release();
std::set<TOutputFx *>::iterator it2;
for (it2 = m_oldOutFxs.begin(); it2 != m_oldOutFxs.end(); it2++)
(*it2)->release();
for (it2 = m_newOutFxs.begin(); it2 != m_newOutFxs.end(); it2++)
(*it2)->release();
QMap<TStageObjectSpline *, TStageObjectSpline *>::iterator it3;
for (it3 = m_splines.begin(); it3 != m_splines.end(); it3++)
it3.value()->release();
}
void setEditingFxGroup(TFx *fx, int editingGroup,
const QStack<int> &fxGroupIds) const {
fx->getAttributes()->closeEditingGroup(fxGroupIds.top());
while (fx->getAttributes()->getEditingGroupId() != editingGroup)
fx->getAttributes()->editGroup();
for (int i = 0; i < fx->getInputPortCount(); i++) {
TFx *inputFx = fx->getInputPort(i)->getFx();
if (inputFx) setEditingFxGroup(inputFx, editingGroup, fxGroupIds);
}
}
void setEditingObjGroup(TStageObject *obj, int editingGroup,
const QStack<int> &objGroupIds) const {
obj->closeEditingGroup(objGroupIds.top());
while (obj->getEditingGroupId() != editingGroup) obj->editGroup();
std::list<TStageObject *> children = obj->getChildren();
std::list<TStageObject *>::iterator it;
for (it = children.begin(); it != children.end(); it++) {
TStageObject *childeObj = *it;
if (childeObj) setEditingObjGroup(childeObj, editingGroup, objGroupIds);
}
}
void undo() const override {
TApp *app = TApp::instance();
TXsheet *xsh = app->getCurrentXsheet()->getXsheet();
int editingGroup = -1;
TStageObjectId parentId = TStageObjectId::NoneId;
if (m_root && m_root->getOutputConnectionCount() > 0)
editingGroup = m_root->getOutputConnection(0)
->getOwnerFx()
->getAttributes()
->getEditingGroupId();
std::set<int> indexesToRemove = m_newIndexs;
app->getCurrentXsheet()->blockSignals(true);
app->getCurrentObject()->blockSignals(true);
ColumnCmd::deleteColumns(indexesToRemove, false, true);
app->getCurrentXsheet()->blockSignals(false);
app->getCurrentObject()->blockSignals(false);
int i;
for (i = m_pegObjects.size() - 1; i >= 0; i--) {
TStageObjectId pegObjectId = m_pegObjects[i]->getId();
TStageObjectId _parentId = xsh->getStageObjectParent(pegObjectId);
if (!m_pegObjects.contains(xsh->getStageObject(_parentId)))
parentId = _parentId;
if (app->getCurrentObject()->getObjectId() == pegObjectId)
app->getCurrentObject()->setObjectId(TStageObjectId::TableId);
xsh->getStageObjectTree()->removeStageObject(pegObjectId);
}
QMap<TStageObjectSpline *, TStageObjectSpline *>::const_iterator it;
for (it = m_splines.begin(); it != m_splines.end(); it++) {
TStageObjectSpline *spline = it.value();
xsh->getStageObjectTree()->removeSpline(spline);
}
std::set<int> indexes;
indexes.insert(m_index);
std::list<int> restoredSplineIds;
m_oldData->restoreObjects(indexes, restoredSplineIds, xsh, 0);
setColumnOutputConnections(m_oldColumnOutputConnections);
TFxSet *internals = xsh->getFxDag()->getInternalFxs();
for (i = internals->getFxCount() - 1; i >= 0; i--) {
TFx *fx = internals->getFx(i);
if (m_oldInternalFxs.find(fx) == m_oldInternalFxs.end())
internals->removeFx(fx);
}
std::set<TOutputFx *>::const_iterator it2;
for (it2 = m_newOutFxs.begin(); it2 != m_newOutFxs.end(); it2++) {
if (m_oldOutFxs.find(*it2) == m_oldOutFxs.end())
xsh->getFxDag()->removeOutputFx(*it2);
}
TColumnSelection *selection = dynamic_cast<TColumnSelection *>(
app->getCurrentSelection()->getSelection());
if (selection) {
selection->selectNone();
selection->selectColumn(m_index);
}
// reinsert in groups
TStageObject *obj = xsh->getStageObject(TStageObjectId::ColumnId(m_index));
if (parentId != TStageObjectId::NoneId) obj->setParent(parentId);
if (!m_objGroupIds.empty()) {
TStageObjectId parentId = obj->getParent();
TStageObject *parentObj = xsh->getStageObject(parentId);
int i;
for (i = 0; i < m_objGroupIds.size(); i++) {
obj->setGroupId(m_objGroupIds[i]);
obj->setGroupName(m_objGroupNames[i]);
}
for (i = 0;
i < m_objGroupIds.size() && parentObj->getEditingGroupId() >= 0; i++)
obj->editGroup();
}
QStack<int> fxGroupIds;
if (m_root) fxGroupIds = m_root->getAttributes()->getGroupIdStack();
if (!fxGroupIds.empty()) {
// recupero l'id del gruppo che si sta editando!
TFx *colFx = xsh->getColumn(m_index)->getFx();
assert(colFx);
colFx->getAttributes()->closeEditingGroup(fxGroupIds.top());
while (colFx->getAttributes()->getEditingGroupId() != editingGroup)
colFx->getAttributes()->editGroup();
}
app->getCurrentXsheet()->notifyXsheetChanged();
}
void redo() const override {
TApp *app = TApp::instance();
TXsheet *xsh = app->getCurrentXsheet()->getXsheet();
TStageObject *obj = xsh->getStageObject(TStageObjectId::ColumnId(m_index));
TStageObjectId parentId = obj->getParent();
TStageObject *parentObj = xsh->getStageObject(parentId);
int objEditingGroup = -1;
if (parentObj->isGrouped())
objEditingGroup = parentObj->getEditingGroupId();
TXshColumn *column = xsh->getColumn(m_index);
assert(column);
TFx *columnFx = column->getFx();
assert(columnFx);
int i;
std::vector<TFxPort *> outPorts;
for (i = 0; i < columnFx->getOutputConnectionCount(); i++)
outPorts.push_back(columnFx->getOutputConnection(i));
xsh->removeColumn(m_index);
std::set<int> indexes = m_newIndexs;
for (i = m_pegObjects.size() - 1; i >= 0; i--)
xsh->getStageObjectTree()->insertStageObject(m_pegObjects[i]);
QMap<TStageObjectSpline *, TStageObjectSpline *>::const_iterator it3;
for (it3 = m_splines.begin(); it3 != m_splines.end(); it3++)
xsh->getStageObjectTree()->insertSpline(it3.value());
std::list<int> restoredSplineIds;
m_newData->restoreObjects(indexes, restoredSplineIds, xsh, 0);
for (i = 0; i < m_pegObjects.size(); i++)
xsh->setStageObjectParent(m_pegObjects[i]->getId(),
m_parentIds[m_pegObjects[i]->getId()]);
std::set<int>::const_iterator it;
for (it = m_newIndexs.begin(); it != m_newIndexs.end(); it++) {
TStageObjectId colId = TStageObjectId::ColumnId(*it);
TStageObjectId parentId = m_parentIds[colId];
xsh->setStageObjectParent(colId, m_parentIds[colId]);
TStageObject *obj = xsh->getStageObject(colId);
TStageObject *parentObj = xsh->getStageObject(parentId);
if (parentObj->isGrouped()) {
QStack<int> idStack = parentObj->getGroupIdStack();
QStack<std::wstring> groupstack = parentObj->getGroupNameStack();
for (int i = 0; i < idStack.size(); i++) {
obj->setGroupId(idStack[i]);
obj->setGroupName(groupstack[i]);
}
int editedGroup = parentObj->getEditingGroupId();
while (editedGroup != -1 && obj->getEditingGroupId() != editedGroup)
obj->editGroup();
}
}
setColumnOutputConnections(m_newColumnOutputConnections);
for (i = 0; i < outPorts.size() && m_root; i++) outPorts[i]->setFx(m_root);
std::set<TOutputFx *>::const_iterator it2;
for (it2 = m_newOutFxs.begin(); it2 != m_newOutFxs.end(); it2++) {
if (m_oldOutFxs.find(*it2) == m_oldOutFxs.end())
xsh->getFxDag()->addOutputFx(*it2);
}
TColumnSelection *selection = dynamic_cast<TColumnSelection *>(
app->getCurrentSelection()->getSelection());
if (selection) {
selection->selectNone();
std::set<int> selectIndices = m_newIndexs;
std::set<int>::const_iterator indicesIt = selectIndices.begin();
while (indicesIt != selectIndices.end())
selection->selectColumn(*indicesIt++);
}
QStack<int> fxGroupIds;
if (m_root) fxGroupIds = m_root->getAttributes()->getGroupIdStack();
if (!fxGroupIds.empty()) {
// recupero l'id del gruppo che si sta editando!
int editingGroup = -1;
if (m_root->getOutputConnectionCount() > 0)
editingGroup = m_root->getOutputConnection(0)
->getOwnerFx()
->getAttributes()
->getEditingGroupId();
setEditingFxGroup(m_root, editingGroup, fxGroupIds);
}
app->getCurrentXsheet()->notifyXsheetChanged();
}
int getSize() const override { return sizeof(*this); }
QString getHistoryString() override { return QObject::tr("Explode"); }
int getHistoryType() override { return HistoryType::Xsheet; }
};
//=============================================================================
// ExplodeChildUndo
//-----------------------------------------------------------------------------
class ExplodeChildUndoWithoutRemovingColumn final : public TUndo {
std::set<int> m_newIndexs;
int m_index, m_from, m_to;
TCellData *m_cellData;
StageObjectsData *m_newData;
QMap<TFx *, QList<TFxPort *>> m_newColumnOutputConnections;
QList<TStageObject *> m_pegObjects;
QMap<TStageObjectSpline *, TStageObjectSpline *> m_splines;
std::set<TFx *> m_oldInternalFxs;
std::set<TOutputFx *> m_oldOutFxs;
std::set<TOutputFx *> m_newOutFxs;
// to handle grouping for the subxsheet
QStack<int> m_objGroupIds;
QStack<std::wstring> m_objGroupNames;
public:
ExplodeChildUndoWithoutRemovingColumn(
const std::set<int> &newIndexs, int index, int from, int to,
TCellData *cellData, StageObjectsData *newData,
QList<TStageObject *> pegObjects,
const QMap<TStageObjectSpline *, TStageObjectSpline *> &splines,
const std::set<TFx *> &oldInternalFxs,
const std::set<TOutputFx *> oldOutFxs, const QStack<int> &objGroupIds,
const QStack<std::wstring> &objGroupNames)
: m_newIndexs(newIndexs)
, m_index(index)
, m_from(from)
, m_to(to)
, m_cellData(cellData)
, m_newData(newData)
, m_pegObjects(pegObjects)
, m_splines(splines)
, m_oldInternalFxs(oldInternalFxs)
, m_oldOutFxs(oldOutFxs)
, m_objGroupIds(objGroupIds)
, m_objGroupNames(objGroupNames) {
TApp *app = TApp::instance();
TXsheet *xsh = app->getCurrentXsheet()->getXsheet();
std::set<int>::iterator it;
for (it = m_newIndexs.begin(); it != m_newIndexs.end(); it++) {
TXshColumn *column = xsh->getColumn(*it);
TFx *columnFx = column->getFx();
QList<TFxPort *> outputConnections;
int i;
for (i = 0; i < columnFx->getOutputConnectionCount(); i++)
outputConnections.append(columnFx->getOutputConnection(i));
m_newColumnOutputConnections[columnFx] = outputConnections;
}
std::set<TOutputFx *>::iterator it2;
for (it2 = m_oldOutFxs.begin(); it2 != m_oldOutFxs.end(); it2++)
(*it2)->addRef();
int i, outFxCount = xsh->getFxDag()->getOutputFxCount();
for (i = 0; i < outFxCount; i++) {
TOutputFx *outFx = xsh->getFxDag()->getOutputFx(i);
m_newOutFxs.insert(outFx);
outFx->addRef();
}
}
~ExplodeChildUndoWithoutRemovingColumn() {
delete m_cellData;
delete m_newData;
int i;
for (i = m_pegObjects.size() - 1; i >= 0; i--) m_pegObjects[i]->release();
std::set<TOutputFx *>::iterator it2;
for (it2 = m_oldOutFxs.begin(); it2 != m_oldOutFxs.end(); it2++)
(*it2)->release();
for (it2 = m_newOutFxs.begin(); it2 != m_newOutFxs.end(); it2++)
(*it2)->release();
}
void undo() const override {
TApp *app = TApp::instance();
TXsheet *xsh = app->getCurrentXsheet()->getXsheet();
std::set<int> indexesToRemove = m_newIndexs;
app->getCurrentXsheet()->blockSignals(true);
app->getCurrentObject()->blockSignals(true);
ColumnCmd::deleteColumns(indexesToRemove, false, true);
app->getCurrentXsheet()->blockSignals(false);
app->getCurrentObject()->blockSignals(false);
int i;
for (i = m_pegObjects.size() - 1; i >= 0; i--)
xsh->getStageObjectTree()->removeStageObject(m_pegObjects[i]->getId());
std::set<int> indexes;
indexes.insert(m_index);
int to = m_to;
int index = m_index;
m_cellData->getCells(xsh, m_from, m_index, to, index, false, false);
TFxSet *internals = xsh->getFxDag()->getInternalFxs();
for (i = internals->getFxCount() - 1; i >= 0; i--) {
TFx *fx = internals->getFx(i);
if (m_oldInternalFxs.find(fx) == m_oldInternalFxs.end())
internals->removeFx(fx);
}
std::set<TOutputFx *>::const_iterator it;
for (it = m_newOutFxs.begin(); it != m_newOutFxs.end(); it++) {
if (m_oldOutFxs.find(*it) == m_oldOutFxs.end())
xsh->getFxDag()->removeOutputFx(*it);
}
TColumnSelection *selection = dynamic_cast<TColumnSelection *>(
app->getCurrentSelection()->getSelection());
if (selection) {
selection->selectNone();
selection->selectColumn(m_index);
}
// reinsert in groups
if (!m_objGroupIds.empty()) {
TStageObject *obj =
xsh->getStageObject(TStageObjectId::ColumnId(m_index));
TStageObjectId parentId = obj->getParent();
TStageObject *parentObj = xsh->getStageObject(parentId);
int i;
for (i = 0; i < m_objGroupIds.size(); i++) {
obj->setGroupId(m_objGroupIds[i]);
obj->setGroupName(m_objGroupNames[i]);
}
for (i = 0;
i < m_objGroupIds.size() && parentObj->getEditingGroupId() >= 0; i++)
obj->editGroup();
}
app->getCurrentXsheet()->notifyXsheetChanged();
}
void redo() const override {
TApp *app = TApp::instance();
TXsheet *xsh = app->getCurrentXsheet()->getXsheet();
xsh->clearCells(m_from, m_index, m_to - m_from + 1);
std::set<int> indexes = m_newIndexs;
int i;
for (i = m_pegObjects.size() - 1; i >= 0; i--)
xsh->getStageObjectTree()->insertStageObject(m_pegObjects[i]);
std::list<int> restoredSplineIds;
m_newData->restoreObjects(indexes, restoredSplineIds, xsh, 0);
setColumnOutputConnections(m_newColumnOutputConnections);
std::set<TOutputFx *>::const_iterator it;
for (it = m_newOutFxs.begin(); it != m_newOutFxs.end(); it++) {
if (m_oldOutFxs.find(*it) == m_oldOutFxs.end())
xsh->getFxDag()->addOutputFx(*it);
}
TColumnSelection *selection = dynamic_cast<TColumnSelection *>(
app->getCurrentSelection()->getSelection());
if (selection) {
selection->selectNone();
std::set<int> selectIndices = m_newIndexs;
std::set<int>::const_iterator indicesIt = selectIndices.begin();
while (indicesIt != selectIndices.end())
selection->selectColumn(*indicesIt++);
}
// reinsert in groups
if (!m_objGroupIds.empty()) {
for (auto const &e : indexes) {
TStageObject *obj = xsh->getStageObject(TStageObjectId::ColumnId(e));
TStageObjectId parentId = obj->getParent();
TStageObject *parentObj = xsh->getStageObject(parentId);
int i;
for (i = 0; i < m_objGroupIds.size(); i++) {
obj->setGroupId(m_objGroupIds[i]);
obj->setGroupName(m_objGroupNames[i]);
}
for (i = 0;
i < m_objGroupIds.size() && parentObj->getEditingGroupId() >= 0;
i++)
obj->editGroup();
}
}
app->getCurrentXsheet()->notifyXsheetChanged();
}
int getSize() const override { return sizeof(*this); }
QString getHistoryString() override { return QObject::tr("Explode"); }
int getHistoryType() override { return HistoryType::Xsheet; }
};
} // namespace
//=============================================================================
// OpenChildCommand
//-----------------------------------------------------------------------------
class OpenChildCommand final : public MenuItemHandler {
public:
OpenChildCommand() : MenuItemHandler(MI_OpenChild) {}
void execute() override { openSubXsheet(); }
} openChildCommand;
//=============================================================================
// CloseChildCommand
//-----------------------------------------------------------------------------
class CloseChildCommand final : public MenuItemHandler {
public:
CloseChildCommand() : MenuItemHandler(MI_CloseChild) {}
void execute() override { closeSubXsheet(1); }
} closeChildCommand;
//=============================================================================
// collapseColumns
//-----------------------------------------------------------------------------
//! Collapses the specified column indices in current XSheet.
void SubsceneCmd::collapse(std::set<int> &indices) {
if (indices.empty()) return;
TXsheet *xsh = TApp::instance()->getCurrentXsheet()->getXsheet();
bool onlyColumns = true;
if (hasPegbarsToBringInsideChildXsheet(xsh, indices)) {
// User must decide if pegbars must be collapsed too
QString question(QObject::tr("Collapsing columns: what you want to do?"));
QList<QString> list;
list.append(QObject::tr(
"Maintain parenting relationships in the sub-xsheet as well."));
list.append(
QObject::tr("Include the selected columns in the sub-xsheet without "
"parenting info."));
int ret = DVGui::RadioButtonMsgBox(DVGui::WARNING, question, list);
if (ret == 0) return;
onlyColumns = (ret == 2);
}
if (!ColumnCmd::checkExpressionReferences(indices, onlyColumns, true)) return;
std::set<int> oldIndices = indices;
int index = *indices.begin();
// Retrieve current status to backup it in the UNDO
StageObjectsData *oldData = new StageObjectsData();
oldData->storeColumns(indices, xsh, 0);
oldData->storeColumnFxs(indices, xsh, 0);
QMap<TFx *, QList<TFxPort *>> columnOutputConnections;
getColumnOutputConnections(indices, columnOutputConnections);
QMap<TStageObjectId, QList<TStageObjectId>> children;
getChildren(indices, children);
QMap<TStageObjectId, TStageObjectId> parents;
getParents(indices, parents);
// Perform the collapse
collapseColumns(indices, onlyColumns);
setColumnOutputConnections(columnOutputConnections);
// Retrieve current status to backup it in the REDO
indices.clear();
indices.insert(index);
StageObjectsData *newData = new StageObjectsData();
newData->storeColumns(indices, xsh, 0);
newData->storeColumnFxs(indices, xsh, 0);
// Build the undo
CollapseUndo *undo =
new CollapseUndo(oldIndices, index, oldData, newData,
columnOutputConnections, children, parents);
TUndoManager::manager()->add(undo);
changeSaveSubXsheetAsCommand();
}
//-----------------------------------------------------------------------------
void SubsceneCmd::collapse(const QList<TStageObjectId> &objects) {
if (objects.isEmpty()) return;
std::set<int> indices;
getColumnIndexes(objects, indices);
if (!ColumnCmd::checkExpressionReferences(objects)) return;
std::set<int> oldIndices = indices;
int index = *indices.begin();
StageObjectsData *oldData = new StageObjectsData();
TXsheet *xsh = TApp::instance()->getCurrentXsheet()->getXsheet();
oldData->storeColumns(indices, xsh, 0);
oldData->storeColumnFxs(indices, xsh, 0);
QMap<TFx *, QList<TFxPort *>> columnOutputConnections;
getColumnOutputConnections(indices, columnOutputConnections);
QMap<TStageObjectId, QList<TStageObjectId>> children;
getChildren(indices, children);
QMap<TStageObjectId, TStageObjectId> parents;
getParents(indices, parents);
collapseColumns(indices, objects);
setColumnOutputConnections(columnOutputConnections);
indices.clear();
indices.insert(index);
StageObjectsData *newData = new StageObjectsData();
newData->storeColumns(indices, xsh, 0);
newData->storeColumnFxs(indices, xsh, 0);
CollapseUndo *undo =
new CollapseUndo(oldIndices, index, oldData, newData,
columnOutputConnections, children, parents);
TUndoManager::manager()->add(undo);
changeSaveSubXsheetAsCommand();
}
//-----------------------------------------------------------------------------
void SubsceneCmd::collapse(const QList<TFxP> &fxs) {
if (fxs.isEmpty()) return;
std::set<int> indices;
std::set<TFx *> internalFx;
getColumnIndexesAndInternalFxs(fxs, indices, internalFx);
TXsheet *xsh = TApp::instance()->getCurrentXsheet()->getXsheet();
bool onlyColumns = true;
if (hasPegbarsToBringInsideChildXsheet(xsh, indices)) {
// User must decide if pegbars must be collapsed too
QString question(QObject::tr("Collapsing columns: what you want to do?"));
QList<QString> list;
list.append(QObject::tr(
"Maintain parenting relationships in the sub-xsheet as well."));
list.append(
QObject::tr("Include the selected columns in the sub-xsheet without "
"parenting info."));
int ret = DVGui::RadioButtonMsgBox(DVGui::WARNING, question, list);
if (ret == 0) return;
onlyColumns = (ret == 2);
}
if (!ColumnCmd::checkExpressionReferences(indices, internalFx, onlyColumns,
true))
return;
std::set<int> oldIndices = indices;
int index = *indices.begin();
StageObjectsData *oldData = new StageObjectsData();
oldData->storeColumns(indices, xsh, 0);
oldData->storeColumnFxs(indices, xsh, 0);
QMap<TFx *, QList<TFxPort *>> columnOutputConnections;
getColumnOutputConnections(indices, columnOutputConnections);
QMap<TStageObjectId, QList<TStageObjectId>> children;
getChildren(indices, children);
QMap<TStageObjectId, TStageObjectId> parents;
getParents(indices, parents);
QMap<TFx *, FxConnections> fxConnections;
getFxConnections(fxConnections, internalFx, xsh);
collapseColumns(indices, internalFx, onlyColumns);
indices.clear();
indices.insert(index);
StageObjectsData *newData = new StageObjectsData();
newData->storeColumns(indices, xsh, 0);
newData->storeColumnFxs(indices, xsh, 0);
CollapseFxUndo *undo = new CollapseFxUndo(oldIndices, index, oldData, newData,
columnOutputConnections, children,
parents, internalFx, fxConnections);
TUndoManager::manager()->add(undo);
changeSaveSubXsheetAsCommand();
}
//-----------------------------------------------------------------------------
void SubsceneCmd::explode(int index) {
TApp *app = TApp::instance();
TXsheet *xsh = app->getCurrentXsheet()->getXsheet();
TFrameHandle *frameHandle = app->getCurrentFrame();
assert(frameHandle->getFrameType() == TFrameHandle::SceneFrame);
int frameIndex = app->getCurrentFrame()->getFrame();
/*- これからExplodeするセルを取得 -*/
TXshCell cell = xsh->getCell(frameIndex, index);
TXshChildLevel *childLevel = cell.getChildLevel();
if (!childLevel) return;
// Cannot remove the column if it contains frames of a TXshSimpleLevel.
int from, to;
// removeColumn is true if the column contains only one subXsheetLevel (i.e.
// the column will be removed) removeColumn is false if there is another level
// in the same column (i.e. the column will remain)
bool removeColumn =
mustRemoveColumn(from, to, childLevel, xsh, index, frameIndex);
/*- Pegbarを親Sheetに持って出るか?の質問ダイアログ -*/
QString question(QObject::tr("Exploding Sub-xsheet: what you want to do?"));
QList<QString> list;
list.append(
QObject::tr("Maintain parenting relationships in the main xsheet."));
list.append(
QObject::tr("Bring columns in the main xsheet without parenting."));
int ret = DVGui::RadioButtonMsgBox(DVGui::WARNING, question, list);
if (ret == 0) return;
if (!ExpressionReferenceManager::instance()->checkExplode(
childLevel->getXsheet(), index, removeColumn, ret == 2))
return;
// Collect column stage object information
TStageObjectId colId = TStageObjectId::ColumnId(index);
TStageObjectId parentId = xsh->getStageObjectParent(colId);
TStageObject *obj = xsh->getStageObjectTree()->getStageObject(colId, false);
assert(obj);
// Collect StageObjects group information
QStack<int> objGroupIds;
QStack<std::wstring> objGroupNames;
int objEditingGroup = obj->getEditingGroupId();
if (obj->isGrouped()) {
int i = 0;
objGroupIds = obj->getGroupIdStack();
objGroupNames = obj->getGroupNameStack();
while (objGroupIds.empty() && objEditingGroup >= 0 &&
objGroupIds[i] != objEditingGroup) {
objGroupIds.remove(i);
objGroupNames.remove(i);
i++;
}
}
GroupData objGroupData(objGroupIds, objGroupNames, objEditingGroup);
// Collect column fx information
/*- FxのGroupの管理 -*/
TXshColumn *column = xsh->getColumn(index);
TFx *columnFx = column->getFx();
TFxAttributes *attr = columnFx->getAttributes();
// Collect Fx group information
QStack<int> fxGroupIds;
QStack<std::wstring> fxGroupNames;
int fxEditingGroup = attr->getEditingGroupId();
if (attr->isGrouped()) {
int i = 0;
fxGroupIds = attr->getGroupIdStack();
fxGroupNames = attr->getGroupNameStack();
while (!fxGroupIds.empty() && fxEditingGroup >= 0 &&
fxGroupIds[i] != fxEditingGroup) {
fxGroupIds.remove(i);
fxGroupNames.remove(i);
i++;
}
}
GroupData fxGroupData(fxGroupIds, fxGroupNames, fxEditingGroup);
/*- Explode前のOutputFxのリストを取得 (oldOutFxs) -*/
std::set<TOutputFx *> oldOutFxs;
int i, outFxCount = xsh->getFxDag()->getOutputFxCount();
for (i = 0; i < outFxCount; i++)
oldOutFxs.insert(xsh->getFxDag()->getOutputFx(i));
std::vector<TFxPort *> outPorts;
QList<TStageObject *> pegObjects;
QMap<TStageObjectSpline *, TStageObjectSpline *> splines;
TPointD fxSubPos = attr->getDagNodePos();
TPointD stageSubPos = obj->getDagNodePos();
if (removeColumn) {
/*- SubXsheetカラムノードから繋がっているFxPortのリストを取得 (outPorts) -*/
for (i = 0; i < columnFx->getOutputConnectionCount(); i++)
outPorts.push_back(columnFx->getOutputConnection(i));
bool wasLinkedToXsheet =
xsh->getFxDag()->getTerminalFxs()->containsFx(columnFx);
// Collect data for undo
std::set<int> indexes;
indexes.insert(index);
/*- Undoのためのデータの取得 -*/
StageObjectsData *oldData = new StageObjectsData();
oldData->storeColumns(indexes, xsh, 0);
oldData->storeColumnFxs(indexes, xsh, 0);
QMap<TFx *, QList<TFxPort *>> columnOutputConnections;
getColumnOutputConnections(indexes, columnOutputConnections);
TFxSet *internals = xsh->getFxDag()->getInternalFxs();
std::set<TFx *> oldInternalFxs;
internals->getFxs(oldInternalFxs);
// Remove column
xsh->removeColumn(index);
// The above removing operation may decrement the parentId, in case that
// 1, the parent object is column, and
// 2, the parent column is placed on the right side of the removed column
// ( i.e. index of the parent column is higher than "index")
if (parentId.isColumn() && parentId.getIndex() > index)
parentId = TStageObjectId::ColumnId(parentId.getIndex() - 1);
// Explode
std::set<int> newIndexes =
::explode(xsh, childLevel->getXsheet(), index, parentId, objGroupData,
stageSubPos, fxGroupData, fxSubPos, pegObjects, splines,
outPorts, ret == 2, wasLinkedToXsheet);
/*- Redoのためのデータの取得 -*/
StageObjectsData *newData = new StageObjectsData();
newData->storeColumns(newIndexes, xsh, 0);
newData->storeColumnFxs(newIndexes, xsh, 0);
TFx *root = 0;
assert(!columnOutputConnections.empty());
QList<TFxPort *> ports = columnOutputConnections.begin().value();
if (!ports.empty()) root = (*ports.begin())->getFx();
ExplodeChildUndoRemovingColumn *undo = new ExplodeChildUndoRemovingColumn(
newIndexes, index, oldData, newData, columnOutputConnections,
pegObjects, splines, oldInternalFxs, oldOutFxs, root, objGroupIds,
objGroupNames);
TUndoManager::manager()->add(undo);
} else {
// keep outPorts empty since the exploded node will be re-connected to the
// xsheet node
// Collect information for undo
TCellData *cellData = new TCellData();
cellData->setCells(xsh, from, index, to, index);
TFxSet *internals = xsh->getFxDag()->getInternalFxs();
std::set<TFx *> oldInternalFxs;
internals->getFxs(oldInternalFxs);
// Remove cells
xsh->clearCells(from, index, to - from + 1);
// Explode
std::set<int> newIndexes = ::explode(
xsh, childLevel->getXsheet(), index + 1, parentId, objGroupData,
stageSubPos + TPointD(10, 10), fxGroupData, fxSubPos + TPointD(10, 10),
pegObjects, splines, outPorts, ret == 2, true);
StageObjectsData *newData = new StageObjectsData();
newData->storeColumns(newIndexes, xsh, 0);
newData->storeColumnFxs(newIndexes, xsh, 0);
ExplodeChildUndoWithoutRemovingColumn *undo =
new ExplodeChildUndoWithoutRemovingColumn(
newIndexes, index, from, to, cellData, newData, pegObjects, splines,
oldInternalFxs, oldOutFxs, objGroupIds, objGroupNames);
TUndoManager::manager()->add(undo);
}
app->getCurrentXsheet()->notifyXsheetChanged();
}
| 37.304233 | 80 | 0.619237 | [
"object",
"vector"
] |
10831a8b614307275658ee165933abd1c6977c79 | 58,459 | cpp | C++ | src/extractor/edge_based_graph_factory.cpp | AugustoQueiroz/pedalavel-backend | c7fa405ff6f6823bdc9d4bb857eddc7197be1f4f | [
"BSD-2-Clause"
] | null | null | null | src/extractor/edge_based_graph_factory.cpp | AugustoQueiroz/pedalavel-backend | c7fa405ff6f6823bdc9d4bb857eddc7197be1f4f | [
"BSD-2-Clause"
] | null | null | null | src/extractor/edge_based_graph_factory.cpp | AugustoQueiroz/pedalavel-backend | c7fa405ff6f6823bdc9d4bb857eddc7197be1f4f | [
"BSD-2-Clause"
] | 1 | 2019-09-23T22:49:07.000Z | 2019-09-23T22:49:07.000Z | #include "extractor/edge_based_graph_factory.hpp"
#include "extractor/conditional_turn_penalty.hpp"
#include "extractor/edge_based_edge.hpp"
#include "extractor/files.hpp"
#include "extractor/intersection/intersection_analysis.hpp"
#include "extractor/scripting_environment.hpp"
#include "extractor/serialization.hpp"
#include "extractor/suffix_table.hpp"
#include "storage/io.hpp"
#include "util/assert.hpp"
#include "util/bearing.hpp"
#include "util/connectivity_checksum.hpp"
#include "util/coordinate.hpp"
#include "util/coordinate_calculation.hpp"
#include "util/exception.hpp"
#include "util/integer_range.hpp"
#include "util/log.hpp"
#include "util/percent.hpp"
#include "util/timing_util.hpp"
#include <boost/assert.hpp>
#include <boost/crc.hpp>
#include <boost/functional/hash.hpp>
#include <boost/numeric/conversion/cast.hpp>
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <limits>
#include <sstream>
#include <string>
#include <tuple>
#include <unordered_map>
#include <tbb/blocked_range.h>
#include <tbb/parallel_for.h>
#include <tbb/pipeline.h>
#include <tbb/task_scheduler_init.h>
namespace std
{
template <> struct hash<std::pair<NodeID, NodeID>>
{
std::size_t operator()(const std::pair<NodeID, NodeID> &mk) const noexcept
{
std::size_t seed = 0;
boost::hash_combine(seed, mk.first);
boost::hash_combine(seed, mk.second);
return seed;
}
};
}
// Buffer size of turn_indexes_write_buffer to reduce number of write(v) syscals
const constexpr int TURN_INDEX_WRITE_BUFFER_SIZE = 1000;
namespace osrm
{
namespace extractor
{
// Configuration to find representative candidate for turn angle calculations
EdgeBasedGraphFactory::EdgeBasedGraphFactory(
const util::NodeBasedDynamicGraph &node_based_graph,
EdgeBasedNodeDataContainer &node_data_container,
const CompressedEdgeContainer &compressed_edge_container,
const std::unordered_set<NodeID> &barrier_nodes,
const std::unordered_set<NodeID> &traffic_lights,
const std::vector<util::Coordinate> &coordinates,
const util::NameTable &name_table,
const std::unordered_set<EdgeID> &segregated_edges,
const extractor::LaneDescriptionMap &lane_description_map)
: m_edge_based_node_container(node_data_container), m_connectivity_checksum(0),
m_number_of_edge_based_nodes(0), m_coordinates(coordinates),
m_node_based_graph(std::move(node_based_graph)), m_barrier_nodes(barrier_nodes),
m_traffic_lights(traffic_lights), m_compressed_edge_container(compressed_edge_container),
name_table(name_table), segregated_edges(segregated_edges),
lane_description_map(lane_description_map)
{
}
void EdgeBasedGraphFactory::GetEdgeBasedEdges(
util::DeallocatingVector<EdgeBasedEdge> &output_edge_list)
{
BOOST_ASSERT_MSG(0 == output_edge_list.size(), "Vector is not empty");
using std::swap; // Koenig swap
swap(m_edge_based_edge_list, output_edge_list);
}
void EdgeBasedGraphFactory::GetEdgeBasedNodeSegments(std::vector<EdgeBasedNodeSegment> &nodes)
{
using std::swap; // Koenig swap
swap(nodes, m_edge_based_node_segments);
}
void EdgeBasedGraphFactory::GetStartPointMarkers(std::vector<bool> &node_is_startpoint)
{
using std::swap; // Koenig swap
swap(m_edge_based_node_is_startpoint, node_is_startpoint);
}
void EdgeBasedGraphFactory::GetEdgeBasedNodeWeights(std::vector<EdgeWeight> &output_node_weights)
{
using std::swap; // Koenig swap
swap(m_edge_based_node_weights, output_node_weights);
}
std::uint32_t EdgeBasedGraphFactory::GetConnectivityChecksum() const
{
return m_connectivity_checksum;
}
std::uint64_t EdgeBasedGraphFactory::GetNumberOfEdgeBasedNodes() const
{
return m_number_of_edge_based_nodes;
}
NBGToEBG EdgeBasedGraphFactory::InsertEdgeBasedNode(const NodeID node_u, const NodeID node_v)
{
// merge edges together into one EdgeBasedNode
BOOST_ASSERT(node_u != SPECIAL_NODEID);
BOOST_ASSERT(node_v != SPECIAL_NODEID);
// find forward edge id and
const EdgeID edge_id_1 = m_node_based_graph.FindEdge(node_u, node_v);
BOOST_ASSERT(edge_id_1 != SPECIAL_EDGEID);
const EdgeData &forward_data = m_node_based_graph.GetEdgeData(edge_id_1);
// find reverse edge id and
const EdgeID edge_id_2 = m_node_based_graph.FindEdge(node_v, node_u);
BOOST_ASSERT(edge_id_2 != SPECIAL_EDGEID);
const EdgeData &reverse_data = m_node_based_graph.GetEdgeData(edge_id_2);
BOOST_ASSERT(nbe_to_ebn_mapping[edge_id_1] != SPECIAL_NODEID ||
nbe_to_ebn_mapping[edge_id_2] != SPECIAL_NODEID);
if (nbe_to_ebn_mapping[edge_id_1] != SPECIAL_NODEID &&
nbe_to_ebn_mapping[edge_id_2] == SPECIAL_NODEID)
m_edge_based_node_weights[nbe_to_ebn_mapping[edge_id_1]] = INVALID_EDGE_WEIGHT;
BOOST_ASSERT(m_compressed_edge_container.HasEntryForID(edge_id_1) ==
m_compressed_edge_container.HasEntryForID(edge_id_2));
BOOST_ASSERT(m_compressed_edge_container.HasEntryForID(edge_id_1));
BOOST_ASSERT(m_compressed_edge_container.HasEntryForID(edge_id_2));
const auto &forward_geometry = m_compressed_edge_container.GetBucketReference(edge_id_1);
BOOST_ASSERT(forward_geometry.size() ==
m_compressed_edge_container.GetBucketReference(edge_id_2).size());
const auto segment_count = forward_geometry.size();
// There should always be some geometry
BOOST_ASSERT(0 != segment_count);
// const unsigned packed_geometry_id = m_compressed_edge_container.ZipEdges(edge_id_1,
// edge_id_2);
NodeID current_edge_source_coordinate_id = node_u;
const auto edge_id_to_segment_id = [](const NodeID edge_based_node_id) {
if (edge_based_node_id == SPECIAL_NODEID)
{
return SegmentID{SPECIAL_SEGMENTID, false};
}
return SegmentID{edge_based_node_id, true};
};
// Add edge-based node data for forward and reverse nodes indexed by edge_id
BOOST_ASSERT(nbe_to_ebn_mapping[edge_id_1] != SPECIAL_EDGEID);
m_edge_based_node_container.nodes[nbe_to_ebn_mapping[edge_id_1]].geometry_id =
forward_data.geometry_id;
m_edge_based_node_container.nodes[nbe_to_ebn_mapping[edge_id_1]].annotation_id =
forward_data.annotation_data;
m_edge_based_node_container.nodes[nbe_to_ebn_mapping[edge_id_1]].segregated =
segregated_edges.count(edge_id_1) > 0;
if (nbe_to_ebn_mapping[edge_id_2] != SPECIAL_EDGEID)
{
m_edge_based_node_container.nodes[nbe_to_ebn_mapping[edge_id_2]].geometry_id =
reverse_data.geometry_id;
m_edge_based_node_container.nodes[nbe_to_ebn_mapping[edge_id_2]].annotation_id =
reverse_data.annotation_data;
m_edge_based_node_container.nodes[nbe_to_ebn_mapping[edge_id_2]].segregated =
segregated_edges.count(edge_id_2) > 0;
}
// Add segments of edge-based nodes
for (const auto i : util::irange(std::size_t{0}, segment_count))
{
BOOST_ASSERT(
current_edge_source_coordinate_id ==
m_compressed_edge_container.GetBucketReference(edge_id_2)[segment_count - 1 - i]
.node_id);
const NodeID current_edge_target_coordinate_id = forward_geometry[i].node_id;
// don't add node-segments for penalties
if (current_edge_target_coordinate_id == current_edge_source_coordinate_id)
continue;
BOOST_ASSERT(current_edge_target_coordinate_id != current_edge_source_coordinate_id);
// build edges
m_edge_based_node_segments.emplace_back(
edge_id_to_segment_id(nbe_to_ebn_mapping[edge_id_1]),
edge_id_to_segment_id(nbe_to_ebn_mapping[edge_id_2]),
current_edge_source_coordinate_id,
current_edge_target_coordinate_id,
i);
m_edge_based_node_is_startpoint.push_back(forward_data.flags.startpoint ||
reverse_data.flags.startpoint);
current_edge_source_coordinate_id = current_edge_target_coordinate_id;
}
BOOST_ASSERT(current_edge_source_coordinate_id == node_v);
return NBGToEBG{node_u, node_v, nbe_to_ebn_mapping[edge_id_1], nbe_to_ebn_mapping[edge_id_2]};
}
void EdgeBasedGraphFactory::Run(
ScriptingEnvironment &scripting_environment,
const std::string &turn_weight_penalties_filename,
const std::string &turn_duration_penalties_filename,
const std::string &turn_penalties_index_filename,
const std::string &cnbg_ebg_mapping_path,
const std::string &conditional_penalties_filename,
const std::string &maneuver_overrides_filename,
const RestrictionMap &node_restriction_map,
const ConditionalRestrictionMap &conditional_node_restriction_map,
const WayRestrictionMap &way_restriction_map,
const std::vector<UnresolvedManeuverOverride> &unresolved_maneuver_overrides)
{
TIMER_START(renumber);
m_number_of_edge_based_nodes =
LabelEdgeBasedNodes() + way_restriction_map.NumberOfDuplicatedNodes();
TIMER_STOP(renumber);
// Allocate memory for edge-based nodes
// In addition to the normal edges, allocate enough space for copied edges from
// via-way-restrictions, see calculation above
m_edge_based_node_container.nodes.resize(m_number_of_edge_based_nodes);
TIMER_START(generate_nodes);
{
auto mapping = GenerateEdgeExpandedNodes(way_restriction_map);
files::writeNBGMapping(cnbg_ebg_mapping_path, mapping);
}
TIMER_STOP(generate_nodes);
TIMER_START(generate_edges);
GenerateEdgeExpandedEdges(scripting_environment,
turn_weight_penalties_filename,
turn_duration_penalties_filename,
turn_penalties_index_filename,
conditional_penalties_filename,
maneuver_overrides_filename,
node_restriction_map,
conditional_node_restriction_map,
way_restriction_map,
unresolved_maneuver_overrides);
TIMER_STOP(generate_edges);
util::Log() << "Timing statistics for edge-expanded graph:";
util::Log() << "Renumbering edges: " << TIMER_SEC(renumber) << "s";
util::Log() << "Generating nodes: " << TIMER_SEC(generate_nodes) << "s";
util::Log() << "Generating edges: " << TIMER_SEC(generate_edges) << "s";
}
/// Renumbers all _forward_ edges and sets the edge_id.
/// A specific numbering is not important. Any unique ID will do.
/// Returns the number of edge-based nodes.
unsigned EdgeBasedGraphFactory::LabelEdgeBasedNodes()
{
// heuristic: node-based graph node is a simple intersection with four edges
// (edge-based nodes)
m_edge_based_node_weights.reserve(4 * m_node_based_graph.GetNumberOfNodes());
nbe_to_ebn_mapping.resize(m_node_based_graph.GetEdgeCapacity(), SPECIAL_NODEID);
// renumber edge based node of outgoing edges
unsigned numbered_edges_count = 0;
for (const auto current_node : util::irange(0u, m_node_based_graph.GetNumberOfNodes()))
{
for (const auto current_edge : m_node_based_graph.GetAdjacentEdgeRange(current_node))
{
const EdgeData &edge_data = m_node_based_graph.GetEdgeData(current_edge);
// only number incoming edges
if (edge_data.reversed)
{
continue;
}
m_edge_based_node_weights.push_back(edge_data.weight);
BOOST_ASSERT(numbered_edges_count < m_node_based_graph.GetNumberOfEdges());
nbe_to_ebn_mapping[current_edge] = numbered_edges_count;
++numbered_edges_count;
}
}
return numbered_edges_count;
}
// Creates the nodes in the edge expanded graph from edges in the node-based graph.
std::vector<NBGToEBG>
EdgeBasedGraphFactory::GenerateEdgeExpandedNodes(const WayRestrictionMap &way_restriction_map)
{
std::vector<NBGToEBG> mapping;
util::Log() << "Generating edge expanded nodes ... ";
// indicating a normal node within the edge-based graph. This node represents an edge in the
// node-based graph
{
util::UnbufferedLog log;
util::Percent progress(log, m_node_based_graph.GetNumberOfNodes());
// m_compressed_edge_container.InitializeBothwayVector();
// loop over all edges and generate new set of nodes
for (const auto nbg_node_u : util::irange(0u, m_node_based_graph.GetNumberOfNodes()))
{
BOOST_ASSERT(nbg_node_u != SPECIAL_NODEID);
progress.PrintStatus(nbg_node_u);
for (EdgeID nbg_edge_id : m_node_based_graph.GetAdjacentEdgeRange(nbg_node_u))
{
BOOST_ASSERT(nbg_edge_id != SPECIAL_EDGEID);
const NodeID nbg_node_v = m_node_based_graph.GetTarget(nbg_edge_id);
BOOST_ASSERT(nbg_node_v != SPECIAL_NODEID);
BOOST_ASSERT(nbg_node_u != nbg_node_v);
// pick only every other edge, since we have every edge as an outgoing and incoming
// egde
if (nbg_node_u >= nbg_node_v)
{
continue;
}
// if we found a non-forward edge reverse and try again
if (nbe_to_ebn_mapping[nbg_edge_id] == SPECIAL_NODEID)
{
mapping.push_back(InsertEdgeBasedNode(nbg_node_v, nbg_node_u));
}
else
{
mapping.push_back(InsertEdgeBasedNode(nbg_node_u, nbg_node_v));
}
}
}
}
util::Log() << "Expanding via-way turn restrictions ... ";
// Add copies of the nodes
{
util::UnbufferedLog log;
const auto via_ways = way_restriction_map.DuplicatedNodeRepresentatives();
util::Percent progress(log, via_ways.size());
NodeID edge_based_node_id =
NodeID(m_number_of_edge_based_nodes - way_restriction_map.NumberOfDuplicatedNodes());
std::size_t progress_counter = 0;
// allocate enough space for the mapping
for (const auto way : via_ways)
{
const auto node_u = way.from;
const auto node_v = way.to;
// we know that the edge exists as non-reversed edge
const auto eid = m_node_based_graph.FindEdge(node_u, node_v);
BOOST_ASSERT(nbe_to_ebn_mapping[eid] != SPECIAL_NODEID);
// merge edges together into one EdgeBasedNode
BOOST_ASSERT(node_u != SPECIAL_NODEID);
BOOST_ASSERT(node_v != SPECIAL_NODEID);
// find node in the edge based graph, we only require one id:
const EdgeData &edge_data = m_node_based_graph.GetEdgeData(eid);
// BOOST_ASSERT(edge_data.edge_id < m_edge_based_node_container.Size());
m_edge_based_node_container.nodes[edge_based_node_id].geometry_id =
edge_data.geometry_id;
m_edge_based_node_container.nodes[edge_based_node_id].annotation_id =
edge_data.annotation_data;
m_edge_based_node_container.nodes[edge_based_node_id].segregated =
segregated_edges.count(eid) > 0;
const auto ebn_weight = m_edge_based_node_weights[nbe_to_ebn_mapping[eid]];
BOOST_ASSERT(ebn_weight == INVALID_EDGE_WEIGHT || ebn_weight == edge_data.weight);
m_edge_based_node_weights.push_back(ebn_weight);
edge_based_node_id++;
progress.PrintStatus(progress_counter++);
}
}
BOOST_ASSERT(m_edge_based_node_segments.size() == m_edge_based_node_is_startpoint.size());
BOOST_ASSERT(m_number_of_edge_based_nodes == m_edge_based_node_weights.size());
util::Log() << "Generated " << m_number_of_edge_based_nodes << " nodes ("
<< way_restriction_map.NumberOfDuplicatedNodes()
<< " of which are duplicates) and " << m_edge_based_node_segments.size()
<< " segments in edge-expanded graph";
return mapping;
}
/// Actually it also generates turn data and serializes them...
void EdgeBasedGraphFactory::GenerateEdgeExpandedEdges(
ScriptingEnvironment &scripting_environment,
const std::string &turn_weight_penalties_filename,
const std::string &turn_duration_penalties_filename,
const std::string &turn_penalties_index_filename,
const std::string &conditional_penalties_filename,
const std::string &maneuver_overrides_filename,
const RestrictionMap &node_restriction_map,
const ConditionalRestrictionMap &conditional_restriction_map,
const WayRestrictionMap &way_restriction_map,
const std::vector<UnresolvedManeuverOverride> &unresolved_maneuver_overrides)
{
util::Log() << "Generating edge-expanded edges ";
std::size_t node_based_edge_counter = 0;
storage::io::FileWriter turn_penalties_index_file(turn_penalties_index_filename,
storage::io::FileWriter::HasNoFingerprint);
SuffixTable street_name_suffix_table(scripting_environment);
const auto &turn_lanes_data = transformTurnLaneMapIntoArrays(lane_description_map);
intersection::MergableRoadDetector mergable_road_detector(m_node_based_graph,
m_edge_based_node_container,
m_coordinates,
m_compressed_edge_container,
node_restriction_map,
m_barrier_nodes,
turn_lanes_data,
name_table,
street_name_suffix_table);
// FIXME these need to be tuned in pre-allocated size
std::vector<TurnPenalty> turn_weight_penalties;
std::vector<TurnPenalty> turn_duration_penalties;
// Now, renumber all our maneuver overrides to use edge-based-nodes
std::vector<StorageManeuverOverride> storage_maneuver_overrides;
std::vector<NodeID> maneuver_override_sequences;
const auto weight_multiplier =
scripting_environment.GetProfileProperties().GetWeightMultiplier();
// filled in during next stage, kept alive through following scope
std::vector<Conditional> conditionals;
// The following block generates the edge-based-edges using a parallel processing pipeline.
// Sets of intersection IDs are batched in groups of GRAINSIZE (100) `generator_stage`, then
// those groups are processed in parallel `processor_stage`. Finally, results are appended to
// the various buffer vectors by the `output_stage` in the same order that the `generator_stage`
// created them in (tbb::filter::serial_in_order creates this guarantee). The order needs to be
// maintained because we depend on it later in the processing pipeline.
{
const NodeID node_count = m_node_based_graph.GetNumberOfNodes();
// Because we write TurnIndexBlock data as we go, we'll
// buffer them into groups of 1000 to reduce the syscall
// count by 1000x. This doesn't need much memory, but
// greatly reduces the syscall overhead of writing lots
// of small objects
std::vector<lookup::TurnIndexBlock> turn_indexes_write_buffer;
turn_indexes_write_buffer.reserve(TURN_INDEX_WRITE_BUFFER_SIZE);
// This struct is the buffered output of the `processor_stage`. This data is
// appended to the various output arrays/files by the `output_stage`.
// same as IntersectionData, but grouped with edge to allow sorting after creating.
struct EdgeWithData
{
EdgeBasedEdge edge;
lookup::TurnIndexBlock turn_index;
TurnPenalty turn_weight_penalty;
TurnPenalty turn_duration_penalty;
};
auto const transfer_data = [&](const EdgeWithData &edge_with_data) {
m_edge_based_edge_list.push_back(edge_with_data.edge);
turn_weight_penalties.push_back(edge_with_data.turn_weight_penalty);
turn_duration_penalties.push_back(edge_with_data.turn_duration_penalty);
turn_indexes_write_buffer.push_back(edge_with_data.turn_index);
};
struct EdgesPipelineBuffer
{
std::size_t nodes_processed = 0;
std::vector<EdgeWithData> continuous_data; // may need this
std::vector<EdgeWithData> delayed_data; // may need this
std::vector<Conditional> conditionals;
std::unordered_map<NodeBasedTurn, std::pair<NodeID, NodeID>> turn_to_ebn_map;
util::ConnectivityChecksum checksum;
};
using EdgesPipelineBufferPtr = std::shared_ptr<EdgesPipelineBuffer>;
m_connectivity_checksum = 0;
std::unordered_map<NodeBasedTurn, std::pair<NodeID, NodeID>> global_turn_to_ebn_map;
// going over all nodes (which form the center of an intersection), we compute all possible
// turns along these intersections.
NodeID current_node = 0;
// Handle intersections in sets of 100. The pipeline below has a serial bottleneck during
// the writing phase, so we want to make the parallel workers do more work to give the
// serial final stage time to complete its tasks.
const constexpr unsigned GRAINSIZE = 100;
// First part of the pipeline generates iterator ranges of IDs in sets of GRAINSIZE
tbb::filter_t<void, tbb::blocked_range<NodeID>> generator_stage(
tbb::filter::serial_in_order, [&](tbb::flow_control &fc) {
if (current_node < node_count)
{
auto next_node = std::min(current_node + GRAINSIZE, node_count);
auto result = tbb::blocked_range<NodeID>(current_node, next_node);
current_node = next_node;
return result;
}
else
{
fc.stop();
return tbb::blocked_range<NodeID>(node_count, node_count);
}
});
// Generate edges for either artificial nodes or the main graph
const auto generate_edge = [this,
&scripting_environment,
weight_multiplier,
&conditional_restriction_map](
// what nodes will be used? In most cases this will be the id
// stored in the edge_data. In case of duplicated nodes (e.g.
// due to via-way restrictions), one/both of these might
// refer to a newly added edge based node
const auto edge_based_node_from,
const auto edge_based_node_to,
// the situation of the turn
const auto node_along_road_entering,
const auto node_based_edge_from,
const auto intersection_node,
const auto node_based_edge_to,
const auto &turn_angle,
const auto &road_legs_on_the_right,
const auto &road_legs_on_the_left,
const auto &edge_geometries) {
const auto node_restricted =
isRestricted(node_along_road_entering,
intersection_node,
m_node_based_graph.GetTarget(node_based_edge_to),
conditional_restriction_map);
boost::optional<Conditional> conditional = boost::none;
if (node_restricted.first)
{
auto const &conditions = node_restricted.second->condition;
// get conditions of the restriction limiting the node
conditional = {{edge_based_node_from,
edge_based_node_to,
{static_cast<std::uint64_t>(-1),
m_coordinates[intersection_node],
conditions}}};
}
const auto &edge_data1 = m_node_based_graph.GetEdgeData(node_based_edge_from);
const auto &edge_data2 = m_node_based_graph.GetEdgeData(node_based_edge_to);
BOOST_ASSERT(nbe_to_ebn_mapping[node_based_edge_from] !=
nbe_to_ebn_mapping[node_based_edge_to]);
BOOST_ASSERT(!edge_data1.reversed);
BOOST_ASSERT(!edge_data2.reversed);
// compute weight and duration penalties
const auto is_traffic_light = m_traffic_lights.count(intersection_node);
const auto is_uturn =
guidance::getTurnDirection(turn_angle) == guidance::DirectionModifier::UTurn;
ExtractionTurn extracted_turn(
// general info
turn_angle,
road_legs_on_the_right.size() + road_legs_on_the_left.size() + 2 - is_uturn,
is_uturn,
is_traffic_light,
m_edge_based_node_container.GetAnnotation(edge_data1.annotation_data)
.is_left_hand_driving,
// source info
edge_data1.flags.restricted,
m_edge_based_node_container.GetAnnotation(edge_data1.annotation_data).travel_mode,
edge_data1.flags.road_classification.IsMotorwayClass(),
edge_data1.flags.road_classification.IsLinkClass(),
edge_data1.flags.road_classification.GetNumberOfLanes(),
edge_data1.flags.highway_turn_classification,
edge_data1.flags.access_turn_classification,
((double)intersection::findEdgeLength(edge_geometries, node_based_edge_from) /
edge_data1.duration) *
36,
edge_data1.flags.road_classification.GetPriority(),
// target info
edge_data2.flags.restricted,
m_edge_based_node_container.GetAnnotation(edge_data2.annotation_data).travel_mode,
edge_data2.flags.road_classification.IsMotorwayClass(),
edge_data2.flags.road_classification.IsLinkClass(),
edge_data2.flags.road_classification.GetNumberOfLanes(),
edge_data2.flags.highway_turn_classification,
edge_data2.flags.access_turn_classification,
((double)intersection::findEdgeLength(edge_geometries, node_based_edge_to) /
edge_data2.duration) *
36,
edge_data2.flags.road_classification.GetPriority(),
// connected roads
road_legs_on_the_right,
road_legs_on_the_left);
scripting_environment.ProcessTurn(extracted_turn);
// turn penalties are limited to [-2^15, 2^15) which roughly translates to 54 minutes
// and fits signed 16bit deci-seconds
auto weight_penalty =
boost::numeric_cast<TurnPenalty>(extracted_turn.weight * weight_multiplier);
auto duration_penalty = boost::numeric_cast<TurnPenalty>(extracted_turn.duration * 10.);
BOOST_ASSERT(SPECIAL_NODEID != nbe_to_ebn_mapping[node_based_edge_from]);
BOOST_ASSERT(SPECIAL_NODEID != nbe_to_ebn_mapping[node_based_edge_to]);
// auto turn_id = m_edge_based_edge_list.size();
auto weight = boost::numeric_cast<EdgeWeight>(edge_data1.weight + weight_penalty);
auto duration = boost::numeric_cast<EdgeWeight>(edge_data1.duration + duration_penalty);
EdgeBasedEdge edge_based_edge = {
edge_based_node_from,
edge_based_node_to,
SPECIAL_NODEID, // This will be updated once the main loop
// completes!
weight,
duration,
true,
false};
// We write out the mapping between the edge-expanded edges and the original nodes.
// Since each edge represents a possible maneuver, external programs can use this to
// quickly perform updates to edge weights in order to penalize certain turns.
// If this edge is 'trivial' -- where the compressed edge corresponds exactly to an
// original OSM segment -- we can pull the turn's preceding node ID directly with
// `node_along_road_entering`;
// otherwise, we need to look up the node immediately preceding the turn from the
// compressed edge container.
const bool isTrivial = m_compressed_edge_container.IsTrivial(node_based_edge_from);
const auto &from_node =
isTrivial ? node_along_road_entering
: m_compressed_edge_container.GetLastEdgeSourceID(node_based_edge_from);
const auto &to_node =
m_compressed_edge_container.GetFirstEdgeTargetID(node_based_edge_to);
lookup::TurnIndexBlock turn_index_block = {from_node, intersection_node, to_node};
// insert data into the designated buffer
return std::make_pair(
EdgeWithData{edge_based_edge, turn_index_block, weight_penalty, duration_penalty},
conditional);
};
//
// Edge-based-graph stage
//
tbb::filter_t<tbb::blocked_range<NodeID>, EdgesPipelineBufferPtr> processor_stage(
tbb::filter::parallel, [&](const tbb::blocked_range<NodeID> &intersection_node_range) {
auto buffer = std::make_shared<EdgesPipelineBuffer>();
buffer->nodes_processed = intersection_node_range.size();
for (auto intersection_node = intersection_node_range.begin(),
end = intersection_node_range.end();
intersection_node < end;
++intersection_node)
{
// We capture the thread-local work in these objects, then flush them in a
// controlled manner at the end of the parallel range
const auto &incoming_edges =
intersection::getIncomingEdges(m_node_based_graph, intersection_node);
const auto &outgoing_edges =
intersection::getOutgoingEdges(m_node_based_graph, intersection_node);
intersection::IntersectionEdgeGeometries edge_geometries;
std::unordered_set<EdgeID> merged_edge_ids;
std::tie(edge_geometries, merged_edge_ids) =
intersection::getIntersectionGeometries(m_node_based_graph,
m_compressed_edge_container,
m_coordinates,
mergable_road_detector,
intersection_node);
buffer->checksum.process_byte(incoming_edges.size());
buffer->checksum.process_byte(outgoing_edges.size());
// all nodes in the graph are connected in both directions. We check all
// outgoing nodes to find the incoming edge. This is a larger search overhead,
// but the cost we need to pay to generate edges here is worth the additional
// search overhead.
//
// a -> b <-> c
// |
// v
// d
//
// will have:
// a: b,rev=0
// b: a,rev=1 c,rev=0 d,rev=0
// c: b,rev=0
//
// From the flags alone, we cannot determine which nodes are connected to `b` by
// an outgoing edge. Therefore, we have to search all connected edges for edges
// entering `b`
for (const auto &incoming_edge : incoming_edges)
{
++node_based_edge_counter;
const auto intersection_view =
convertToIntersectionView(m_node_based_graph,
m_edge_based_node_container,
node_restriction_map,
m_barrier_nodes,
edge_geometries,
turn_lanes_data,
incoming_edge,
outgoing_edges,
merged_edge_ids);
// check if we are turning off a via way
const auto turning_off_via_way =
way_restriction_map.IsViaWay(incoming_edge.node, intersection_node);
for (const auto &outgoing_edge : outgoing_edges)
{
auto is_turn_allowed =
intersection::isTurnAllowed(m_node_based_graph,
m_edge_based_node_container,
node_restriction_map,
m_barrier_nodes,
edge_geometries,
turn_lanes_data,
incoming_edge,
outgoing_edge);
buffer->checksum.process_bit(is_turn_allowed);
if (!is_turn_allowed)
continue;
const auto turn =
std::find_if(intersection_view.begin(),
intersection_view.end(),
[edge = outgoing_edge.edge](const auto &road) {
return road.eid == edge;
});
OSRM_ASSERT(turn != intersection_view.end(),
m_coordinates[intersection_node]);
std::vector<ExtractionTurnLeg> road_legs_on_the_right;
std::vector<ExtractionTurnLeg> road_legs_on_the_left;
auto get_connected_road_info = [&](const auto &connected_edge) {
const auto &edge_data =
m_node_based_graph.GetEdgeData(connected_edge.eid);
return ExtractionTurnLeg(
edge_data.flags.restricted,
edge_data.flags.road_classification.IsMotorwayClass(),
edge_data.flags.road_classification.IsLinkClass(),
edge_data.flags.road_classification.GetNumberOfLanes(),
edge_data.flags.highway_turn_classification,
edge_data.flags.access_turn_classification,
((double)intersection::findEdgeLength(edge_geometries,
connected_edge.eid) /
edge_data.duration) *
36,
edge_data.flags.road_classification.GetPriority(),
!connected_edge.entry_allowed ||
(edge_data.flags.forward &&
edge_data.flags.backward), // is incoming
connected_edge.entry_allowed);
};
// all connected roads on the right of a u turn
const auto is_uturn = guidance::getTurnDirection(turn->angle) ==
guidance::DirectionModifier::UTurn;
if (is_uturn)
{
if (turn != intersection_view.begin())
{
std::transform(intersection_view.begin() + 1,
turn,
std::back_inserter(road_legs_on_the_right),
get_connected_road_info);
}
std::transform(turn + 1,
intersection_view.end(),
std::back_inserter(road_legs_on_the_right),
get_connected_road_info);
}
else
{
if (intersection_view.begin() != turn)
{
std::transform(intersection_view.begin() + 1,
turn,
std::back_inserter(road_legs_on_the_right),
get_connected_road_info);
}
std::transform(turn + 1,
intersection_view.end(),
std::back_inserter(road_legs_on_the_left),
get_connected_road_info);
}
if (is_uturn && turn != intersection_view.begin())
{
util::Log(logWARNING)
<< "Turn is a u turn but not turning to the first connected "
"edge of the intersection. Node ID: "
<< intersection_node << ", OSM link: "
<< toOSMLink(m_coordinates[intersection_node]);
}
else if (turn == intersection_view.begin() && !is_uturn)
{
util::Log(logWARNING)
<< "Turn is a u turn but not classified as a u turn. Node ID: "
<< intersection_node << ", OSM link: "
<< toOSMLink(m_coordinates[intersection_node]);
}
// In case a way restriction starts at a given location, add a turn onto
// every artificial node eminating here.
//
// e - f
// |
// a - b
// |
// c - d
//
// ab via bc to cd
// ab via be to ef
//
// has two artifical nodes (be/bc) with restrictions starting at `ab`.
// Since every restriction group (abc | abe) refers to the same
// artificial node, we simply have to find a single representative for
// the turn. Here we check whether the turn in question is the start of
// a via way restriction. If that should be the case, we switch the id
// of the edge-based-node for the target to the ID of the duplicated
// node associated with the turn. (e.g. ab via bc switches bc to bc_dup)
auto const target_id = way_restriction_map.RemapIfRestricted(
nbe_to_ebn_mapping[outgoing_edge.edge],
incoming_edge.node,
outgoing_edge.node,
m_node_based_graph.GetTarget(outgoing_edge.edge),
m_number_of_edge_based_nodes);
/***************************/
const auto edgetarget =
m_node_based_graph.GetTarget(outgoing_edge.edge);
// TODO: this loop is not optimized - once we have a few
// overrides available, we should index this for faster
// lookups
for (auto & override : unresolved_maneuver_overrides)
{
for (auto &turn : override.turn_sequence)
{
if (turn.from == incoming_edge.node &&
turn.via == intersection_node && turn.to == edgetarget)
{
const auto &ebn_from =
nbe_to_ebn_mapping[incoming_edge.edge];
const auto &ebn_to = target_id;
buffer->turn_to_ebn_map[turn] =
std::make_pair(ebn_from, ebn_to);
}
}
}
{ // scope to forget edge_with_data after
const auto edge_with_data_and_condition =
generate_edge(nbe_to_ebn_mapping[incoming_edge.edge],
target_id,
incoming_edge.node,
incoming_edge.edge,
outgoing_edge.node,
outgoing_edge.edge,
turn->angle,
road_legs_on_the_right,
road_legs_on_the_left,
edge_geometries);
buffer->continuous_data.push_back(
edge_with_data_and_condition.first);
if (edge_with_data_and_condition.second)
{
buffer->conditionals.push_back(
*edge_with_data_and_condition.second);
}
}
// when turning off a a via-way turn restriction, we need to not only
// handle the normal edges for the way, but also add turns for every
// duplicated node. This process is integrated here to avoid doing the
// turn analysis multiple times.
if (turning_off_via_way)
{
const auto duplicated_nodes = way_restriction_map.DuplicatedNodeIDs(
incoming_edge.node, intersection_node);
// next to the normal restrictions tracked in `entry_allowed`, via
// ways might introduce additional restrictions. These are handled
// here when turning off a via-way
for (auto duplicated_node_id : duplicated_nodes)
{
const auto from_id =
NodeID(m_number_of_edge_based_nodes -
way_restriction_map.NumberOfDuplicatedNodes() +
duplicated_node_id);
auto const node_at_end_of_turn =
m_node_based_graph.GetTarget(outgoing_edge.edge);
const auto is_way_restricted = way_restriction_map.IsRestricted(
duplicated_node_id, node_at_end_of_turn);
if (is_way_restricted)
{
auto const restriction = way_restriction_map.GetRestriction(
duplicated_node_id, node_at_end_of_turn);
if (restriction.condition.empty())
continue;
// add into delayed data
auto edge_with_data_and_condition =
generate_edge(from_id,
nbe_to_ebn_mapping[outgoing_edge.edge],
incoming_edge.node,
incoming_edge.edge,
outgoing_edge.node,
outgoing_edge.edge,
turn->angle,
road_legs_on_the_right,
road_legs_on_the_left,
edge_geometries);
buffer->delayed_data.push_back(
edge_with_data_and_condition.first);
if (edge_with_data_and_condition.second)
{
buffer->conditionals.push_back(
*edge_with_data_and_condition.second);
}
// also add the conditions for the way
if (is_way_restricted && !restriction.condition.empty())
{
// add a new conditional for the edge we just created
buffer->conditionals.push_back(
{from_id,
nbe_to_ebn_mapping[outgoing_edge.edge],
{static_cast<std::uint64_t>(-1),
m_coordinates[intersection_node],
restriction.condition}});
}
}
else
{
auto edge_with_data_and_condition =
generate_edge(from_id,
nbe_to_ebn_mapping[outgoing_edge.edge],
incoming_edge.node,
incoming_edge.edge,
outgoing_edge.node,
outgoing_edge.edge,
turn->angle,
road_legs_on_the_right,
road_legs_on_the_left,
edge_geometries);
buffer->delayed_data.push_back(
edge_with_data_and_condition.first);
if (edge_with_data_and_condition.second)
{
buffer->conditionals.push_back(
*edge_with_data_and_condition.second);
}
}
}
}
}
}
}
return buffer;
});
// Last part of the pipeline puts all the calculated data into the serial buffers
util::UnbufferedLog log;
util::Percent routing_progress(log, node_count);
std::vector<EdgeWithData> delayed_data;
tbb::filter_t<EdgesPipelineBufferPtr, void> output_stage(
tbb::filter::serial_in_order, [&](auto buffer) {
routing_progress.PrintAddition(buffer->nodes_processed);
m_connectivity_checksum = buffer->checksum.update_checksum(m_connectivity_checksum);
// Copy data from local buffers into global EBG data
std::for_each(
buffer->continuous_data.begin(), buffer->continuous_data.end(), transfer_data);
conditionals.insert(
conditionals.end(), buffer->conditionals.begin(), buffer->conditionals.end());
// NOTE: potential overflow here if we hit 2^32 routable edges
BOOST_ASSERT(m_edge_based_edge_list.size() <= std::numeric_limits<NodeID>::max());
// Buffer writes to reduce syscall count
if (turn_indexes_write_buffer.size() >= TURN_INDEX_WRITE_BUFFER_SIZE)
{
turn_penalties_index_file.WriteFrom(turn_indexes_write_buffer.data(),
turn_indexes_write_buffer.size());
turn_indexes_write_buffer.clear();
}
// Copy via-way restrictions delayed data
delayed_data.insert(
delayed_data.end(), buffer->delayed_data.begin(), buffer->delayed_data.end());
std::for_each(buffer->turn_to_ebn_map.begin(),
buffer->turn_to_ebn_map.end(),
[&global_turn_to_ebn_map](const auto &p) {
// TODO: log conflicts here
global_turn_to_ebn_map.insert(p);
});
});
// Now, execute the pipeline. The value of "5" here was chosen by experimentation
// on a 16-CPU machine and seemed to give the best performance. This value needs
// to be balanced with the GRAINSIZE above - ideally, the pipeline puts as much work
// as possible in the `intersection_handler` step so that those parallel workers don't
// get blocked too much by the slower (io-performing) `buffer_storage`
tbb::parallel_pipeline(tbb::task_scheduler_init::default_num_threads() * 5,
generator_stage & processor_stage & output_stage);
// NOTE: buffer.delayed_data and buffer.delayed_turn_data have the same index
std::for_each(delayed_data.begin(), delayed_data.end(), transfer_data);
// Now, replace node-based-node ID values in the `node_sequence` with
// the edge-based-node values we found and stored in the `turn_to_ebn_map`
for (auto &unresolved_override : unresolved_maneuver_overrides)
{
StorageManeuverOverride storage_override;
storage_override.instruction_node = unresolved_override.instruction_node;
storage_override.override_type = unresolved_override.override_type;
storage_override.direction = unresolved_override.direction;
std::vector<NodeID> node_sequence(unresolved_override.turn_sequence.size() + 1,
SPECIAL_NODEID);
for (std::int64_t i = unresolved_override.turn_sequence.size() - 1; i >= 0; --i)
{
const auto v = global_turn_to_ebn_map.find(unresolved_override.turn_sequence[i]);
if (v != global_turn_to_ebn_map.end())
{
node_sequence[i] = v->second.first;
node_sequence[i + 1] = v->second.second;
}
}
storage_override.node_sequence_offset_begin = maneuver_override_sequences.size();
storage_override.node_sequence_offset_end =
maneuver_override_sequences.size() + node_sequence.size();
storage_override.start_node = node_sequence.front();
maneuver_override_sequences.insert(
maneuver_override_sequences.end(), node_sequence.begin(), node_sequence.end());
storage_maneuver_overrides.push_back(storage_override);
}
// Flush the turn_indexes_write_buffer if it's not empty
if (!turn_indexes_write_buffer.empty())
{
turn_penalties_index_file.WriteFrom(turn_indexes_write_buffer.data(),
turn_indexes_write_buffer.size());
turn_indexes_write_buffer.clear();
}
}
{
util::Log() << "Sorting and writing " << storage_maneuver_overrides.size()
<< " maneuver overrides...";
// Sort by `from_node`, so that later lookups can be done with a binary search.
std::sort(storage_maneuver_overrides.begin(),
storage_maneuver_overrides.end(),
[](const auto &a, const auto &b) { return a.start_node < b.start_node; });
files::writeManeuverOverrides(
maneuver_overrides_filename, storage_maneuver_overrides, maneuver_override_sequences);
}
util::Log() << "done.";
util::Log() << "Renumbering turns";
// Now, update the turn_id property on every EdgeBasedEdge - it will equal the position in the
// m_edge_based_edge_list array for each object.
tbb::parallel_for(tbb::blocked_range<NodeID>(0, m_edge_based_edge_list.size()),
[this](const tbb::blocked_range<NodeID> &range) {
for (auto x = range.begin(), end = range.end(); x != end; ++x)
{
m_edge_based_edge_list[x].data.turn_id = x;
}
});
// re-hash conditionals to connect to their respective edge-based edges. Due to the ordering, we
// do not really have a choice but to index the conditional penalties and walk over all
// edge-based-edges to find the ID of the edge
auto const indexed_conditionals = IndexConditionals(std::move(conditionals));
{
util::Log() << "Writing " << indexed_conditionals.size()
<< " conditional turn penalties...";
// write conditional turn penalties into the restrictions file
storage::io::FileWriter writer(conditional_penalties_filename,
storage::io::FileWriter::GenerateFingerprint);
extractor::serialization::write(writer, indexed_conditionals);
}
// write weight penalties per turn
BOOST_ASSERT(turn_weight_penalties.size() == turn_duration_penalties.size());
{
storage::io::FileWriter writer(turn_weight_penalties_filename,
storage::io::FileWriter::GenerateFingerprint);
storage::serialization::write(writer, turn_weight_penalties);
}
{
storage::io::FileWriter writer(turn_duration_penalties_filename,
storage::io::FileWriter::GenerateFingerprint);
storage::serialization::write(writer, turn_duration_penalties);
}
util::Log() << "Generated " << m_edge_based_node_segments.size() << " edge based node segments";
util::Log() << "Node-based graph contains " << node_based_edge_counter << " edges";
util::Log() << "Edge-expanded graph ...";
util::Log() << " contains " << m_edge_based_edge_list.size() << " edges";
}
std::vector<ConditionalTurnPenalty>
EdgeBasedGraphFactory::IndexConditionals(std::vector<Conditional> &&conditionals) const
{
boost::unordered_multimap<std::pair<NodeID, NodeID>, ConditionalTurnPenalty *> index;
// build and index of all conditional restrictions
for (auto &conditional : conditionals)
index.insert(std::make_pair(std::make_pair(conditional.from_node, conditional.to_node),
&conditional.penalty));
std::vector<ConditionalTurnPenalty> indexed_restrictions;
for (auto const &edge : m_edge_based_edge_list)
{
auto const range = index.equal_range(std::make_pair(edge.source, edge.target));
for (auto itr = range.first; itr != range.second; ++itr)
{
itr->second->turn_offset = edge.data.turn_id;
indexed_restrictions.push_back(*itr->second);
}
}
return indexed_restrictions;
}
} // namespace extractor
} // namespace osrm
| 49.290894 | 100 | 0.553739 | [
"geometry",
"object",
"vector",
"transform"
] |
108943486f73c18655dd65269afb6fca39fd01fa | 1,562 | cpp | C++ | uva/11447 - Reservoir Logs .cpp | taufique71/sports-programming | c29a92b5e5424c7de6f94e302fc6783561de9b3d | [
"MIT"
] | null | null | null | uva/11447 - Reservoir Logs .cpp | taufique71/sports-programming | c29a92b5e5424c7de6f94e302fc6783561de9b3d | [
"MIT"
] | null | null | null | uva/11447 - Reservoir Logs .cpp | taufique71/sports-programming | c29a92b5e5424c7de6f94e302fc6783561de9b3d | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
struct Point
{
int x;
int y;
};
vector<Point> points;
int width;
double ini_pc;
double ini_vol;
double used_vol;
double mid_vol;
double rained_vol;
int final_pc;
double volume;
void calculate_volume()
{
double area = 0;
int i;
int len;
points.push_back(points[0]);
len = points.size();
for(i = 0 ; i < (len-1) ; i++)
{
area += (points[i+1].x + points[i].x) * (points[i+1].y - points[i].y);
}
area /= 2;
volume = area * width;
}
int main()
{
int n_case;
int n_vertex;
Point input;
cin >> n_case;
while(n_case--)
{
cin >> n_vertex;
points.clear();
while(n_vertex--)
{
cin >> input.x >> input.y;
points.push_back(input);
}
cin >> width;
cin >> ini_pc >> used_vol >> rained_vol;
calculate_volume();
ini_vol = (volume * ini_pc) / 100;
if(used_vol > ini_vol) cout << "Lack of water. ";
if(ini_vol <= used_vol) mid_vol = 0.00;
else mid_vol = ini_vol - used_vol;
if((mid_vol + rained_vol)>volume) cout << "Excess of water. ";
if((mid_vol + rained_vol)>volume) cout << "Final percentage: 100%" << endl;
else
{
final_pc = (mid_vol + rained_vol)/volume * 100;
printf("Final percentage: %d",final_pc);
cout << '%' << endl;
}
}
return 0;
}
| 19.772152 | 84 | 0.503201 | [
"vector"
] |
108ae30655849b3789699e5b763e01fd79888ef6 | 45,696 | cc | C++ | ui/base/x/x11_util.cc | 7kbird/chrome | f56688375530f1003e34c34f441321977c5af3c3 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2019-01-16T03:57:39.000Z | 2019-01-16T03:57:39.000Z | ui/base/x/x11_util.cc | 7kbird/chrome | f56688375530f1003e34c34f441321977c5af3c3 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2018-02-10T21:00:08.000Z | 2018-03-20T05:09:50.000Z | ui/base/x/x11_util.cc | aranajhonny/chromium | caf5bcb822f79b8997720e589334266551a50a13 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-11-04T07:23:37.000Z | 2020-11-04T07:23:37.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file defines utility functions for X11 (Linux only). This code has been
// ported from XCB since we can't use XCB on Ubuntu while its 32-bit support
// remains woefully incomplete.
#include "ui/base/x/x11_util.h"
#include <ctype.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <list>
#include <map>
#include <utility>
#include <vector>
#include <X11/extensions/shape.h>
#include <X11/extensions/XInput2.h>
#include <X11/Xcursor/Xcursor.h>
#include "base/bind.h"
#include "base/debug/trace_event.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/singleton.h"
#include "base/message_loop/message_loop.h"
#include "base/metrics/histogram.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/sys_byteorder.h"
#include "base/threading/thread.h"
#include "skia/ext/image_operations.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkPostConfig.h"
#include "ui/base/x/x11_menu_list.h"
#include "ui/base/x/x11_util_internal.h"
#include "ui/events/event_utils.h"
#include "ui/events/keycodes/keyboard_code_conversion_x.h"
#include "ui/events/x/device_data_manager_x11.h"
#include "ui/events/x/touch_factory_x11.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/gfx/image/image_skia_rep.h"
#include "ui/gfx/point.h"
#include "ui/gfx/point_conversions.h"
#include "ui/gfx/rect.h"
#include "ui/gfx/size.h"
#include "ui/gfx/skia_util.h"
#include "ui/gfx/x/x11_error_tracker.h"
#if defined(OS_FREEBSD)
#include <sys/sysctl.h>
#include <sys/types.h>
#endif
namespace ui {
namespace {
int DefaultX11ErrorHandler(XDisplay* d, XErrorEvent* e) {
if (base::MessageLoop::current()) {
base::MessageLoop::current()->PostTask(
FROM_HERE, base::Bind(&LogErrorEventDescription, d, *e));
} else {
LOG(ERROR)
<< "X error received: "
<< "serial " << e->serial << ", "
<< "error_code " << static_cast<int>(e->error_code) << ", "
<< "request_code " << static_cast<int>(e->request_code) << ", "
<< "minor_code " << static_cast<int>(e->minor_code);
}
return 0;
}
int DefaultX11IOErrorHandler(XDisplay* d) {
// If there's an IO error it likely means the X server has gone away
LOG(ERROR) << "X IO error received (X server probably went away)";
_exit(1);
}
// Note: The caller should free the resulting value data.
bool GetProperty(XID window, const std::string& property_name, long max_length,
XAtom* type, int* format, unsigned long* num_items,
unsigned char** property) {
XAtom property_atom = GetAtom(property_name.c_str());
unsigned long remaining_bytes = 0;
return XGetWindowProperty(gfx::GetXDisplay(),
window,
property_atom,
0, // offset into property data to read
max_length, // max length to get
False, // deleted
AnyPropertyType,
type,
format,
num_items,
&remaining_bytes,
property);
}
// A process wide singleton that manages the usage of X cursors.
class XCursorCache {
public:
XCursorCache() {}
~XCursorCache() {
Clear();
}
::Cursor GetCursor(int cursor_shape) {
// Lookup cursor by attempting to insert a null value, which avoids
// a second pass through the map after a cache miss.
std::pair<std::map<int, ::Cursor>::iterator, bool> it = cache_.insert(
std::make_pair(cursor_shape, 0));
if (it.second) {
XDisplay* display = gfx::GetXDisplay();
it.first->second = XCreateFontCursor(display, cursor_shape);
}
return it.first->second;
}
void Clear() {
XDisplay* display = gfx::GetXDisplay();
for (std::map<int, ::Cursor>::iterator it =
cache_.begin(); it != cache_.end(); ++it) {
XFreeCursor(display, it->second);
}
cache_.clear();
}
private:
// Maps X11 font cursor shapes to Cursor IDs.
std::map<int, ::Cursor> cache_;
DISALLOW_COPY_AND_ASSIGN(XCursorCache);
};
XCursorCache* cursor_cache = NULL;
// A process wide singleton cache for custom X cursors.
class XCustomCursorCache {
public:
static XCustomCursorCache* GetInstance() {
return Singleton<XCustomCursorCache>::get();
}
::Cursor InstallCustomCursor(XcursorImage* image) {
XCustomCursor* custom_cursor = new XCustomCursor(image);
::Cursor xcursor = custom_cursor->cursor();
cache_[xcursor] = custom_cursor;
return xcursor;
}
void Ref(::Cursor cursor) {
cache_[cursor]->Ref();
}
void Unref(::Cursor cursor) {
if (cache_[cursor]->Unref())
cache_.erase(cursor);
}
void Clear() {
cache_.clear();
}
const XcursorImage* GetXcursorImage(::Cursor cursor) const {
return cache_.find(cursor)->second->image();
}
private:
friend struct DefaultSingletonTraits<XCustomCursorCache>;
class XCustomCursor {
public:
// This takes ownership of the image.
XCustomCursor(XcursorImage* image)
: image_(image),
ref_(1) {
cursor_ = XcursorImageLoadCursor(gfx::GetXDisplay(), image);
}
~XCustomCursor() {
XcursorImageDestroy(image_);
XFreeCursor(gfx::GetXDisplay(), cursor_);
}
::Cursor cursor() const { return cursor_; }
void Ref() {
++ref_;
}
// Returns true if the cursor was destroyed because of the unref.
bool Unref() {
if (--ref_ == 0) {
delete this;
return true;
}
return false;
}
const XcursorImage* image() const {
return image_;
};
private:
XcursorImage* image_;
int ref_;
::Cursor cursor_;
DISALLOW_COPY_AND_ASSIGN(XCustomCursor);
};
XCustomCursorCache() {}
~XCustomCursorCache() {
Clear();
}
std::map< ::Cursor, XCustomCursor*> cache_;
DISALLOW_COPY_AND_ASSIGN(XCustomCursorCache);
};
} // namespace
bool IsXInput2Available() {
return DeviceDataManagerX11::GetInstance()->IsXInput2Available();
}
static SharedMemorySupport DoQuerySharedMemorySupport(XDisplay* dpy) {
int dummy;
Bool pixmaps_supported;
// Query the server's support for XSHM.
if (!XShmQueryVersion(dpy, &dummy, &dummy, &pixmaps_supported))
return SHARED_MEMORY_NONE;
#if defined(OS_FREEBSD)
// On FreeBSD we can't access the shared memory after it was marked for
// deletion, unless this behaviour is explicitly enabled by the user.
// In case it's not enabled disable shared memory support.
int allow_removed;
size_t length = sizeof(allow_removed);
if ((sysctlbyname("kern.ipc.shm_allow_removed", &allow_removed, &length,
NULL, 0) < 0) || allow_removed < 1) {
return SHARED_MEMORY_NONE;
}
#endif
// Next we probe to see if shared memory will really work
int shmkey = shmget(IPC_PRIVATE, 1, 0600);
if (shmkey == -1) {
LOG(WARNING) << "Failed to get shared memory segment.";
return SHARED_MEMORY_NONE;
} else {
VLOG(1) << "Got shared memory segment " << shmkey;
}
void* address = shmat(shmkey, NULL, 0);
// Mark the shared memory region for deletion
shmctl(shmkey, IPC_RMID, NULL);
XShmSegmentInfo shminfo;
memset(&shminfo, 0, sizeof(shminfo));
shminfo.shmid = shmkey;
gfx::X11ErrorTracker err_tracker;
bool result = XShmAttach(dpy, &shminfo);
if (result)
VLOG(1) << "X got shared memory segment " << shmkey;
else
LOG(WARNING) << "X failed to attach to shared memory segment " << shmkey;
if (err_tracker.FoundNewError())
result = false;
shmdt(address);
if (!result) {
LOG(WARNING) << "X failed to attach to shared memory segment " << shmkey;
return SHARED_MEMORY_NONE;
}
VLOG(1) << "X attached to shared memory segment " << shmkey;
XShmDetach(dpy, &shminfo);
return pixmaps_supported ? SHARED_MEMORY_PIXMAP : SHARED_MEMORY_PUTIMAGE;
}
SharedMemorySupport QuerySharedMemorySupport(XDisplay* dpy) {
static SharedMemorySupport shared_memory_support = SHARED_MEMORY_NONE;
static bool shared_memory_support_cached = false;
if (shared_memory_support_cached)
return shared_memory_support;
shared_memory_support = DoQuerySharedMemorySupport(dpy);
shared_memory_support_cached = true;
return shared_memory_support;
}
bool QueryRenderSupport(Display* dpy) {
int dummy;
// We don't care about the version of Xrender since all the features which
// we use are included in every version.
static bool render_supported = XRenderQueryExtension(dpy, &dummy, &dummy);
return render_supported;
}
::Cursor GetXCursor(int cursor_shape) {
if (!cursor_cache)
cursor_cache = new XCursorCache;
return cursor_cache->GetCursor(cursor_shape);
}
::Cursor CreateReffedCustomXCursor(XcursorImage* image) {
return XCustomCursorCache::GetInstance()->InstallCustomCursor(image);
}
void RefCustomXCursor(::Cursor cursor) {
XCustomCursorCache::GetInstance()->Ref(cursor);
}
void UnrefCustomXCursor(::Cursor cursor) {
XCustomCursorCache::GetInstance()->Unref(cursor);
}
XcursorImage* SkBitmapToXcursorImage(const SkBitmap* cursor_image,
const gfx::Point& hotspot) {
DCHECK(cursor_image->colorType() == kN32_SkColorType);
gfx::Point hotspot_point = hotspot;
SkBitmap scaled;
// X11 seems to have issues with cursors when images get larger than 64
// pixels. So rescale the image if necessary.
const float kMaxPixel = 64.f;
bool needs_scale = false;
if (cursor_image->width() > kMaxPixel || cursor_image->height() > kMaxPixel) {
float scale = 1.f;
if (cursor_image->width() > cursor_image->height())
scale = kMaxPixel / cursor_image->width();
else
scale = kMaxPixel / cursor_image->height();
scaled = skia::ImageOperations::Resize(*cursor_image,
skia::ImageOperations::RESIZE_BETTER,
static_cast<int>(cursor_image->width() * scale),
static_cast<int>(cursor_image->height() * scale));
hotspot_point = gfx::ToFlooredPoint(gfx::ScalePoint(hotspot, scale));
needs_scale = true;
}
const SkBitmap* bitmap = needs_scale ? &scaled : cursor_image;
XcursorImage* image = XcursorImageCreate(bitmap->width(), bitmap->height());
image->xhot = std::min(bitmap->width() - 1, hotspot_point.x());
image->yhot = std::min(bitmap->height() - 1, hotspot_point.y());
if (bitmap->width() && bitmap->height()) {
bitmap->lockPixels();
// The |bitmap| contains ARGB image, so just copy it.
memcpy(image->pixels,
bitmap->getPixels(),
bitmap->width() * bitmap->height() * 4);
bitmap->unlockPixels();
}
return image;
}
int CoalescePendingMotionEvents(const XEvent* xev,
XEvent* last_event) {
XIDeviceEvent* xievent = static_cast<XIDeviceEvent*>(xev->xcookie.data);
int num_coalesced = 0;
XDisplay* display = xev->xany.display;
int event_type = xev->xgeneric.evtype;
DCHECK(event_type == XI_Motion || event_type == XI_TouchUpdate);
while (XPending(display)) {
XEvent next_event;
XPeekEvent(display, &next_event);
// If we can't get the cookie, abort the check.
if (!XGetEventData(next_event.xgeneric.display, &next_event.xcookie))
return num_coalesced;
// If this isn't from a valid device, throw the event away, as
// that's what the message pump would do. Device events come in pairs
// with one from the master and one from the slave so there will
// always be at least one pending.
if (!ui::TouchFactory::GetInstance()->ShouldProcessXI2Event(&next_event)) {
XFreeEventData(display, &next_event.xcookie);
XNextEvent(display, &next_event);
continue;
}
if (next_event.type == GenericEvent &&
next_event.xgeneric.evtype == event_type &&
!ui::DeviceDataManagerX11::GetInstance()->IsCMTGestureEvent(
&next_event)) {
XIDeviceEvent* next_xievent =
static_cast<XIDeviceEvent*>(next_event.xcookie.data);
// Confirm that the motion event is targeted at the same window
// and that no buttons or modifiers have changed.
if (xievent->event == next_xievent->event &&
xievent->child == next_xievent->child &&
xievent->detail == next_xievent->detail &&
xievent->buttons.mask_len == next_xievent->buttons.mask_len &&
(memcmp(xievent->buttons.mask,
next_xievent->buttons.mask,
xievent->buttons.mask_len) == 0) &&
xievent->mods.base == next_xievent->mods.base &&
xievent->mods.latched == next_xievent->mods.latched &&
xievent->mods.locked == next_xievent->mods.locked &&
xievent->mods.effective == next_xievent->mods.effective) {
XFreeEventData(display, &next_event.xcookie);
// Free the previous cookie.
if (num_coalesced > 0)
XFreeEventData(display, &last_event->xcookie);
// Get the event and its cookie data.
XNextEvent(display, last_event);
XGetEventData(display, &last_event->xcookie);
++num_coalesced;
continue;
}
}
// This isn't an event we want so free its cookie data.
XFreeEventData(display, &next_event.xcookie);
break;
}
if (event_type == XI_Motion && num_coalesced > 0) {
base::TimeDelta delta = ui::EventTimeFromNative(last_event) -
ui::EventTimeFromNative(const_cast<XEvent*>(xev));
UMA_HISTOGRAM_COUNTS_10000("Event.CoalescedCount.Mouse", num_coalesced);
UMA_HISTOGRAM_TIMES("Event.CoalescedLatency.Mouse", delta);
}
return num_coalesced;
}
void HideHostCursor() {
CR_DEFINE_STATIC_LOCAL(XScopedCursor, invisible_cursor,
(CreateInvisibleCursor(), gfx::GetXDisplay()));
XDefineCursor(gfx::GetXDisplay(), DefaultRootWindow(gfx::GetXDisplay()),
invisible_cursor.get());
}
::Cursor CreateInvisibleCursor() {
XDisplay* xdisplay = gfx::GetXDisplay();
::Cursor invisible_cursor;
char nodata[] = { 0, 0, 0, 0, 0, 0, 0, 0 };
XColor black;
black.red = black.green = black.blue = 0;
Pixmap blank = XCreateBitmapFromData(xdisplay,
DefaultRootWindow(xdisplay),
nodata, 8, 8);
invisible_cursor = XCreatePixmapCursor(xdisplay, blank, blank,
&black, &black, 0, 0);
XFreePixmap(xdisplay, blank);
return invisible_cursor;
}
void SetUseOSWindowFrame(XID window, bool use_os_window_frame) {
// This data structure represents additional hints that we send to the window
// manager and has a direct lineage back to Motif, which defined this de facto
// standard. This struct doesn't seem 64-bit safe though, but it's what GDK
// does.
typedef struct {
unsigned long flags;
unsigned long functions;
unsigned long decorations;
long input_mode;
unsigned long status;
} MotifWmHints;
MotifWmHints motif_hints;
memset(&motif_hints, 0, sizeof(motif_hints));
// Signals that the reader of the _MOTIF_WM_HINTS property should pay
// attention to the value of |decorations|.
motif_hints.flags = (1L << 1);
motif_hints.decorations = use_os_window_frame ? 1 : 0;
XAtom hint_atom = GetAtom("_MOTIF_WM_HINTS");
XChangeProperty(gfx::GetXDisplay(),
window,
hint_atom,
hint_atom,
32,
PropModeReplace,
reinterpret_cast<unsigned char*>(&motif_hints),
sizeof(MotifWmHints)/sizeof(long));
}
bool IsShapeExtensionAvailable() {
int dummy;
static bool is_shape_available =
XShapeQueryExtension(gfx::GetXDisplay(), &dummy, &dummy);
return is_shape_available;
}
XID GetX11RootWindow() {
return DefaultRootWindow(gfx::GetXDisplay());
}
bool GetCurrentDesktop(int* desktop) {
return GetIntProperty(GetX11RootWindow(), "_NET_CURRENT_DESKTOP", desktop);
}
void SetHideTitlebarWhenMaximizedProperty(XID window,
HideTitlebarWhenMaximized property) {
// XChangeProperty() expects "hide" to be long.
unsigned long hide = property;
XChangeProperty(gfx::GetXDisplay(),
window,
GetAtom("_GTK_HIDE_TITLEBAR_WHEN_MAXIMIZED"),
XA_CARDINAL,
32, // size in bits
PropModeReplace,
reinterpret_cast<unsigned char*>(&hide),
1);
}
void ClearX11DefaultRootWindow() {
XDisplay* display = gfx::GetXDisplay();
XID root_window = GetX11RootWindow();
gfx::Rect root_bounds;
if (!GetWindowRect(root_window, &root_bounds)) {
LOG(ERROR) << "Failed to get the bounds of the X11 root window";
return;
}
XGCValues gc_values = {0};
gc_values.foreground = BlackPixel(display, DefaultScreen(display));
GC gc = XCreateGC(display, root_window, GCForeground, &gc_values);
XFillRectangle(display, root_window, gc,
root_bounds.x(),
root_bounds.y(),
root_bounds.width(),
root_bounds.height());
XFreeGC(display, gc);
}
bool IsWindowVisible(XID window) {
TRACE_EVENT0("ui", "IsWindowVisible");
XWindowAttributes win_attributes;
if (!XGetWindowAttributes(gfx::GetXDisplay(), window, &win_attributes))
return false;
if (win_attributes.map_state != IsViewable)
return false;
// Minimized windows are not visible.
std::vector<XAtom> wm_states;
if (GetAtomArrayProperty(window, "_NET_WM_STATE", &wm_states)) {
XAtom hidden_atom = GetAtom("_NET_WM_STATE_HIDDEN");
if (std::find(wm_states.begin(), wm_states.end(), hidden_atom) !=
wm_states.end()) {
return false;
}
}
// Some compositing window managers (notably kwin) do not actually unmap
// windows on desktop switch, so we also must check the current desktop.
int window_desktop, current_desktop;
return (!GetWindowDesktop(window, &window_desktop) ||
!GetCurrentDesktop(¤t_desktop) ||
window_desktop == kAllDesktops ||
window_desktop == current_desktop);
}
bool GetWindowRect(XID window, gfx::Rect* rect) {
Window root, child;
int x, y;
unsigned int width, height;
unsigned int border_width, depth;
if (!XGetGeometry(gfx::GetXDisplay(), window, &root, &x, &y,
&width, &height, &border_width, &depth))
return false;
if (!XTranslateCoordinates(gfx::GetXDisplay(), window, root,
0, 0, &x, &y, &child))
return false;
*rect = gfx::Rect(x, y, width, height);
std::vector<int> insets;
if (GetIntArrayProperty(window, "_NET_FRAME_EXTENTS", &insets) &&
insets.size() == 4) {
rect->Inset(-insets[0], -insets[2], -insets[1], -insets[3]);
}
// Not all window managers support _NET_FRAME_EXTENTS so return true even if
// requesting the property fails.
return true;
}
bool WindowContainsPoint(XID window, gfx::Point screen_loc) {
TRACE_EVENT0("ui", "WindowContainsPoint");
gfx::Rect window_rect;
if (!GetWindowRect(window, &window_rect))
return false;
if (!window_rect.Contains(screen_loc))
return false;
if (!IsShapeExtensionAvailable())
return true;
// According to http://www.x.org/releases/X11R7.6/doc/libXext/shapelib.html,
// if an X display supports the shape extension the bounds of a window are
// defined as the intersection of the window bounds and the interior
// rectangles. This means to determine if a point is inside a window for the
// purpose of input handling we have to check the rectangles in the ShapeInput
// list.
// According to http://www.x.org/releases/current/doc/xextproto/shape.html,
// we need to also respect the ShapeBounding rectangles.
// The effective input region of a window is defined to be the intersection
// of the client input region with both the default input region and the
// client bounding region. Any portion of the client input region that is not
// included in both the default input region and the client bounding region
// will not be included in the effective input region on the screen.
int rectangle_kind[] = {ShapeInput, ShapeBounding};
for (size_t kind_index = 0;
kind_index < arraysize(rectangle_kind);
kind_index++) {
int dummy;
int shape_rects_size = 0;
XRectangle* shape_rects = XShapeGetRectangles(gfx::GetXDisplay(),
window,
rectangle_kind[kind_index],
&shape_rects_size,
&dummy);
if (!shape_rects) {
// The shape is empty. This can occur when |window| is minimized.
DCHECK_EQ(0, shape_rects_size);
return false;
}
bool is_in_shape_rects = false;
for (int i = 0; i < shape_rects_size; ++i) {
// The ShapeInput and ShapeBounding rects are to be in window space, so we
// have to translate by the window_rect's offset to map to screen space.
gfx::Rect shape_rect =
gfx::Rect(shape_rects[i].x + window_rect.x(),
shape_rects[i].y + window_rect.y(),
shape_rects[i].width, shape_rects[i].height);
if (shape_rect.Contains(screen_loc)) {
is_in_shape_rects = true;
break;
}
}
XFree(shape_rects);
if (!is_in_shape_rects)
return false;
}
return true;
}
bool PropertyExists(XID window, const std::string& property_name) {
XAtom type = None;
int format = 0; // size in bits of each item in 'property'
unsigned long num_items = 0;
unsigned char* property = NULL;
int result = GetProperty(window, property_name, 1,
&type, &format, &num_items, &property);
if (result != Success)
return false;
XFree(property);
return num_items > 0;
}
bool GetRawBytesOfProperty(XID window,
XAtom property,
scoped_refptr<base::RefCountedMemory>* out_data,
size_t* out_data_items,
XAtom* out_type) {
// Retrieve the data from our window.
unsigned long nitems = 0;
unsigned long nbytes = 0;
XAtom prop_type = None;
int prop_format = 0;
unsigned char* property_data = NULL;
if (XGetWindowProperty(gfx::GetXDisplay(), window, property,
0, 0x1FFFFFFF /* MAXINT32 / 4 */, False,
AnyPropertyType, &prop_type, &prop_format,
&nitems, &nbytes, &property_data) != Success) {
return false;
}
if (prop_type == None)
return false;
size_t bytes = 0;
// So even though we should theoretically have nbytes (and we can't
// pass NULL there), we need to manually calculate the byte length here
// because nbytes always returns zero.
switch (prop_format) {
case 8:
bytes = nitems;
break;
case 16:
bytes = sizeof(short) * nitems;
break;
case 32:
bytes = sizeof(long) * nitems;
break;
default:
NOTREACHED();
break;
}
if (out_data)
*out_data = new XRefcountedMemory(property_data, bytes);
else
XFree(property_data);
if (out_data_items)
*out_data_items = nitems;
if (out_type)
*out_type = prop_type;
return true;
}
bool GetIntProperty(XID window, const std::string& property_name, int* value) {
XAtom type = None;
int format = 0; // size in bits of each item in 'property'
unsigned long num_items = 0;
unsigned char* property = NULL;
int result = GetProperty(window, property_name, 1,
&type, &format, &num_items, &property);
if (result != Success)
return false;
if (format != 32 || num_items != 1) {
XFree(property);
return false;
}
*value = static_cast<int>(*(reinterpret_cast<long*>(property)));
XFree(property);
return true;
}
bool GetXIDProperty(XID window, const std::string& property_name, XID* value) {
XAtom type = None;
int format = 0; // size in bits of each item in 'property'
unsigned long num_items = 0;
unsigned char* property = NULL;
int result = GetProperty(window, property_name, 1,
&type, &format, &num_items, &property);
if (result != Success)
return false;
if (format != 32 || num_items != 1) {
XFree(property);
return false;
}
*value = *(reinterpret_cast<XID*>(property));
XFree(property);
return true;
}
bool GetIntArrayProperty(XID window,
const std::string& property_name,
std::vector<int>* value) {
XAtom type = None;
int format = 0; // size in bits of each item in 'property'
unsigned long num_items = 0;
unsigned char* properties = NULL;
int result = GetProperty(window, property_name,
(~0L), // (all of them)
&type, &format, &num_items, &properties);
if (result != Success)
return false;
if (format != 32) {
XFree(properties);
return false;
}
long* int_properties = reinterpret_cast<long*>(properties);
value->clear();
for (unsigned long i = 0; i < num_items; ++i) {
value->push_back(static_cast<int>(int_properties[i]));
}
XFree(properties);
return true;
}
bool GetAtomArrayProperty(XID window,
const std::string& property_name,
std::vector<XAtom>* value) {
XAtom type = None;
int format = 0; // size in bits of each item in 'property'
unsigned long num_items = 0;
unsigned char* properties = NULL;
int result = GetProperty(window, property_name,
(~0L), // (all of them)
&type, &format, &num_items, &properties);
if (result != Success)
return false;
if (type != XA_ATOM) {
XFree(properties);
return false;
}
XAtom* atom_properties = reinterpret_cast<XAtom*>(properties);
value->clear();
value->insert(value->begin(), atom_properties, atom_properties + num_items);
XFree(properties);
return true;
}
bool GetStringProperty(
XID window, const std::string& property_name, std::string* value) {
XAtom type = None;
int format = 0; // size in bits of each item in 'property'
unsigned long num_items = 0;
unsigned char* property = NULL;
int result = GetProperty(window, property_name, 1024,
&type, &format, &num_items, &property);
if (result != Success)
return false;
if (format != 8) {
XFree(property);
return false;
}
value->assign(reinterpret_cast<char*>(property), num_items);
XFree(property);
return true;
}
bool SetIntProperty(XID window,
const std::string& name,
const std::string& type,
int value) {
std::vector<int> values(1, value);
return SetIntArrayProperty(window, name, type, values);
}
bool SetIntArrayProperty(XID window,
const std::string& name,
const std::string& type,
const std::vector<int>& value) {
DCHECK(!value.empty());
XAtom name_atom = GetAtom(name.c_str());
XAtom type_atom = GetAtom(type.c_str());
// XChangeProperty() expects values of type 32 to be longs.
scoped_ptr<long[]> data(new long[value.size()]);
for (size_t i = 0; i < value.size(); ++i)
data[i] = value[i];
gfx::X11ErrorTracker err_tracker;
XChangeProperty(gfx::GetXDisplay(),
window,
name_atom,
type_atom,
32, // size in bits of items in 'value'
PropModeReplace,
reinterpret_cast<const unsigned char*>(data.get()),
value.size()); // num items
return !err_tracker.FoundNewError();
}
bool SetAtomProperty(XID window,
const std::string& name,
const std::string& type,
XAtom value) {
std::vector<XAtom> values(1, value);
return SetAtomArrayProperty(window, name, type, values);
}
bool SetAtomArrayProperty(XID window,
const std::string& name,
const std::string& type,
const std::vector<XAtom>& value) {
DCHECK(!value.empty());
XAtom name_atom = GetAtom(name.c_str());
XAtom type_atom = GetAtom(type.c_str());
// XChangeProperty() expects values of type 32 to be longs.
scoped_ptr<XAtom[]> data(new XAtom[value.size()]);
for (size_t i = 0; i < value.size(); ++i)
data[i] = value[i];
gfx::X11ErrorTracker err_tracker;
XChangeProperty(gfx::GetXDisplay(),
window,
name_atom,
type_atom,
32, // size in bits of items in 'value'
PropModeReplace,
reinterpret_cast<const unsigned char*>(data.get()),
value.size()); // num items
return !err_tracker.FoundNewError();
}
bool SetStringProperty(XID window,
XAtom property,
XAtom type,
const std::string& value) {
gfx::X11ErrorTracker err_tracker;
XChangeProperty(gfx::GetXDisplay(),
window,
property,
type,
8,
PropModeReplace,
reinterpret_cast<const unsigned char*>(value.c_str()),
value.size());
return !err_tracker.FoundNewError();
}
XAtom GetAtom(const char* name) {
// TODO(derat): Cache atoms to avoid round-trips to the server.
return XInternAtom(gfx::GetXDisplay(), name, false);
}
void SetWindowClassHint(XDisplay* display,
XID window,
const std::string& res_name,
const std::string& res_class) {
XClassHint class_hints;
// const_cast is safe because XSetClassHint does not modify the strings.
// Just to be safe, the res_name and res_class parameters are local copies,
// not const references.
class_hints.res_name = const_cast<char*>(res_name.c_str());
class_hints.res_class = const_cast<char*>(res_class.c_str());
XSetClassHint(display, window, &class_hints);
}
void SetWindowRole(XDisplay* display, XID window, const std::string& role) {
if (role.empty()) {
XDeleteProperty(display, window, GetAtom("WM_WINDOW_ROLE"));
} else {
char* role_c = const_cast<char*>(role.c_str());
XChangeProperty(display, window, GetAtom("WM_WINDOW_ROLE"), XA_STRING, 8,
PropModeReplace,
reinterpret_cast<unsigned char*>(role_c),
role.size());
}
}
bool GetCustomFramePrefDefault() {
// Ideally, we'd use the custom frame by default and just fall back on using
// system decorations for the few (?) tiling window managers where the custom
// frame doesn't make sense (e.g. awesome, ion3, ratpoison, xmonad, etc.) or
// other WMs where it has issues (e.g. Fluxbox -- see issue 19130). The EWMH
// _NET_SUPPORTING_WM property makes it easy to look up a name for the current
// WM, but at least some of the WMs in the latter group don't set it.
// Instead, we default to using system decorations for all WMs and
// special-case the ones where the custom frame should be used.
ui::WindowManagerName wm_type = GuessWindowManager();
return (wm_type == WM_BLACKBOX ||
wm_type == WM_COMPIZ ||
wm_type == WM_ENLIGHTENMENT ||
wm_type == WM_METACITY ||
wm_type == WM_MUFFIN ||
wm_type == WM_MUTTER ||
wm_type == WM_OPENBOX ||
wm_type == WM_XFWM4);
}
bool GetWindowDesktop(XID window, int* desktop) {
return GetIntProperty(window, "_NET_WM_DESKTOP", desktop);
}
std::string GetX11ErrorString(XDisplay* display, int err) {
char buffer[256];
XGetErrorText(display, err, buffer, arraysize(buffer));
return buffer;
}
// Returns true if |window| is a named window.
bool IsWindowNamed(XID window) {
XTextProperty prop;
if (!XGetWMName(gfx::GetXDisplay(), window, &prop) || !prop.value)
return false;
XFree(prop.value);
return true;
}
bool EnumerateChildren(EnumerateWindowsDelegate* delegate, XID window,
const int max_depth, int depth) {
if (depth > max_depth)
return false;
std::vector<XID> windows;
std::vector<XID>::iterator iter;
if (depth == 0) {
XMenuList::GetInstance()->InsertMenuWindowXIDs(&windows);
// Enumerate the menus first.
for (iter = windows.begin(); iter != windows.end(); iter++) {
if (delegate->ShouldStopIterating(*iter))
return true;
}
windows.clear();
}
XID root, parent, *children;
unsigned int num_children;
int status = XQueryTree(gfx::GetXDisplay(), window, &root, &parent, &children,
&num_children);
if (status == 0)
return false;
for (int i = static_cast<int>(num_children) - 1; i >= 0; i--)
windows.push_back(children[i]);
XFree(children);
// XQueryTree returns the children of |window| in bottom-to-top order, so
// reverse-iterate the list to check the windows from top-to-bottom.
for (iter = windows.begin(); iter != windows.end(); iter++) {
if (IsWindowNamed(*iter) && delegate->ShouldStopIterating(*iter))
return true;
}
// If we're at this point, we didn't find the window we're looking for at the
// current level, so we need to recurse to the next level. We use a second
// loop because the recursion and call to XQueryTree are expensive and is only
// needed for a small number of cases.
if (++depth <= max_depth) {
for (iter = windows.begin(); iter != windows.end(); iter++) {
if (EnumerateChildren(delegate, *iter, max_depth, depth))
return true;
}
}
return false;
}
bool EnumerateAllWindows(EnumerateWindowsDelegate* delegate, int max_depth) {
XID root = GetX11RootWindow();
return EnumerateChildren(delegate, root, max_depth, 0);
}
void EnumerateTopLevelWindows(ui::EnumerateWindowsDelegate* delegate) {
std::vector<XID> stack;
if (!ui::GetXWindowStack(ui::GetX11RootWindow(), &stack)) {
// Window Manager doesn't support _NET_CLIENT_LIST_STACKING, so fall back
// to old school enumeration of all X windows. Some WMs parent 'top-level'
// windows in unnamed actual top-level windows (ion WM), so extend the
// search depth to all children of top-level windows.
const int kMaxSearchDepth = 1;
ui::EnumerateAllWindows(delegate, kMaxSearchDepth);
return;
}
XMenuList::GetInstance()->InsertMenuWindowXIDs(&stack);
std::vector<XID>::iterator iter;
for (iter = stack.begin(); iter != stack.end(); iter++) {
if (delegate->ShouldStopIterating(*iter))
return;
}
}
bool GetXWindowStack(Window window, std::vector<XID>* windows) {
windows->clear();
Atom type;
int format;
unsigned long count;
unsigned char *data = NULL;
if (GetProperty(window,
"_NET_CLIENT_LIST_STACKING",
~0L,
&type,
&format,
&count,
&data) != Success) {
return false;
}
bool result = false;
if (type == XA_WINDOW && format == 32 && data && count > 0) {
result = true;
XID* stack = reinterpret_cast<XID*>(data);
for (long i = static_cast<long>(count) - 1; i >= 0; i--)
windows->push_back(stack[i]);
}
if (data)
XFree(data);
return result;
}
bool CopyAreaToCanvas(XID drawable,
gfx::Rect source_bounds,
gfx::Point dest_offset,
gfx::Canvas* canvas) {
ui::XScopedImage scoped_image(
XGetImage(gfx::GetXDisplay(), drawable,
source_bounds.x(), source_bounds.y(),
source_bounds.width(), source_bounds.height(),
AllPlanes, ZPixmap));
XImage* image = scoped_image.get();
if (!image) {
LOG(ERROR) << "XGetImage failed";
return false;
}
if (image->bits_per_pixel == 32) {
if ((0xff << SK_R32_SHIFT) != image->red_mask ||
(0xff << SK_G32_SHIFT) != image->green_mask ||
(0xff << SK_B32_SHIFT) != image->blue_mask) {
LOG(WARNING) << "XImage and Skia byte orders differ";
return false;
}
// Set the alpha channel before copying to the canvas. Otherwise, areas of
// the framebuffer that were cleared by ply-image rather than being obscured
// by an image during boot may end up transparent.
// TODO(derat|marcheu): Remove this if/when ply-image has been updated to
// set the framebuffer's alpha channel regardless of whether the device
// claims to support alpha or not.
for (int i = 0; i < image->width * image->height * 4; i += 4)
image->data[i + 3] = 0xff;
SkBitmap bitmap;
bitmap.installPixels(SkImageInfo::MakeN32Premul(image->width,
image->height),
image->data, image->bytes_per_line);
gfx::ImageSkia image_skia;
gfx::ImageSkiaRep image_rep(bitmap, canvas->image_scale());
image_skia.AddRepresentation(image_rep);
canvas->DrawImageInt(image_skia, dest_offset.x(), dest_offset.y());
} else {
NOTIMPLEMENTED() << "Unsupported bits-per-pixel " << image->bits_per_pixel;
return false;
}
return true;
}
bool GetWindowManagerName(std::string* wm_name) {
DCHECK(wm_name);
int wm_window = 0;
if (!GetIntProperty(GetX11RootWindow(),
"_NET_SUPPORTING_WM_CHECK",
&wm_window)) {
return false;
}
// It's possible that a window manager started earlier in this X session left
// a stale _NET_SUPPORTING_WM_CHECK property when it was replaced by a
// non-EWMH window manager, so we trap errors in the following requests to
// avoid crashes (issue 23860).
// EWMH requires the supporting-WM window to also have a
// _NET_SUPPORTING_WM_CHECK property pointing to itself (to avoid a stale
// property referencing an ID that's been recycled for another window), so we
// check that too.
gfx::X11ErrorTracker err_tracker;
int wm_window_property = 0;
bool result = GetIntProperty(
wm_window, "_NET_SUPPORTING_WM_CHECK", &wm_window_property);
if (err_tracker.FoundNewError() || !result ||
wm_window_property != wm_window) {
return false;
}
result = GetStringProperty(
static_cast<XID>(wm_window), "_NET_WM_NAME", wm_name);
return !err_tracker.FoundNewError() && result;
}
WindowManagerName GuessWindowManager() {
std::string name;
if (GetWindowManagerName(&name)) {
// These names are taken from the WMs' source code.
if (name == "Blackbox")
return WM_BLACKBOX;
if (name == "chromeos-wm")
return WM_CHROME_OS;
if (name == "Compiz" || name == "compiz")
return WM_COMPIZ;
if (name == "e16")
return WM_ENLIGHTENMENT;
if (StartsWithASCII(name, "IceWM", true))
return WM_ICE_WM;
if (name == "KWin")
return WM_KWIN;
if (name == "Metacity")
return WM_METACITY;
if (name == "Mutter (Muffin)")
return WM_MUFFIN;
if (name == "GNOME Shell")
return WM_MUTTER; // GNOME Shell uses Mutter
if (name == "Mutter")
return WM_MUTTER;
if (name == "Openbox")
return WM_OPENBOX;
if (name == "Xfwm4")
return WM_XFWM4;
}
return WM_UNKNOWN;
}
void SetDefaultX11ErrorHandlers() {
SetX11ErrorHandlers(NULL, NULL);
}
bool IsX11WindowFullScreen(XID window) {
// If _NET_WM_STATE_FULLSCREEN is in _NET_SUPPORTED, use the presence or
// absence of _NET_WM_STATE_FULLSCREEN in _NET_WM_STATE to determine
// whether we're fullscreen.
XAtom fullscreen_atom = GetAtom("_NET_WM_STATE_FULLSCREEN");
if (WmSupportsHint(fullscreen_atom)) {
std::vector<XAtom> atom_properties;
if (GetAtomArrayProperty(window,
"_NET_WM_STATE",
&atom_properties)) {
return std::find(atom_properties.begin(),
atom_properties.end(),
fullscreen_atom) !=
atom_properties.end();
}
}
gfx::Rect window_rect;
if (!ui::GetWindowRect(window, &window_rect))
return false;
// We can't use gfx::Screen here because we don't have an aura::Window. So
// instead just look at the size of the default display.
//
// TODO(erg): Actually doing this correctly would require pulling out xrandr,
// which we don't even do in the desktop screen yet.
::XDisplay* display = gfx::GetXDisplay();
::Screen* screen = DefaultScreenOfDisplay(display);
int width = WidthOfScreen(screen);
int height = HeightOfScreen(screen);
return window_rect.size() == gfx::Size(width, height);
}
bool WmSupportsHint(XAtom atom) {
std::vector<XAtom> supported_atoms;
if (!GetAtomArrayProperty(GetX11RootWindow(),
"_NET_SUPPORTED",
&supported_atoms)) {
return false;
}
return std::find(supported_atoms.begin(), supported_atoms.end(), atom) !=
supported_atoms.end();
}
const unsigned char* XRefcountedMemory::front() const {
return x11_data_;
}
size_t XRefcountedMemory::size() const {
return length_;
}
XRefcountedMemory::~XRefcountedMemory() {
XFree(x11_data_);
}
XScopedString::~XScopedString() {
XFree(string_);
}
XScopedImage::~XScopedImage() {
reset(NULL);
}
void XScopedImage::reset(XImage* image) {
if (image_ == image)
return;
if (image_)
XDestroyImage(image_);
image_ = image;
}
XScopedCursor::XScopedCursor(::Cursor cursor, XDisplay* display)
: cursor_(cursor),
display_(display) {
}
XScopedCursor::~XScopedCursor() {
reset(0U);
}
::Cursor XScopedCursor::get() const {
return cursor_;
}
void XScopedCursor::reset(::Cursor cursor) {
if (cursor_)
XFreeCursor(display_, cursor_);
cursor_ = cursor;
}
namespace test {
void ResetXCursorCache() {
delete cursor_cache;
cursor_cache = NULL;
}
const XcursorImage* GetCachedXcursorImage(::Cursor cursor) {
return XCustomCursorCache::GetInstance()->GetXcursorImage(cursor);
}
}
// ----------------------------------------------------------------------------
// These functions are declared in x11_util_internal.h because they require
// XLib.h to be included, and it conflicts with many other headers.
XRenderPictFormat* GetRenderARGB32Format(XDisplay* dpy) {
static XRenderPictFormat* pictformat = NULL;
if (pictformat)
return pictformat;
// First look for a 32-bit format which ignores the alpha value
XRenderPictFormat templ;
templ.depth = 32;
templ.type = PictTypeDirect;
templ.direct.red = 16;
templ.direct.green = 8;
templ.direct.blue = 0;
templ.direct.redMask = 0xff;
templ.direct.greenMask = 0xff;
templ.direct.blueMask = 0xff;
templ.direct.alphaMask = 0;
static const unsigned long kMask =
PictFormatType | PictFormatDepth |
PictFormatRed | PictFormatRedMask |
PictFormatGreen | PictFormatGreenMask |
PictFormatBlue | PictFormatBlueMask |
PictFormatAlphaMask;
pictformat = XRenderFindFormat(dpy, kMask, &templ, 0 /* first result */);
if (!pictformat) {
// Not all X servers support xRGB32 formats. However, the XRENDER spec says
// that they must support an ARGB32 format, so we can always return that.
pictformat = XRenderFindStandardFormat(dpy, PictStandardARGB32);
CHECK(pictformat) << "XRENDER ARGB32 not supported.";
}
return pictformat;
}
void SetX11ErrorHandlers(XErrorHandler error_handler,
XIOErrorHandler io_error_handler) {
XSetErrorHandler(error_handler ? error_handler : DefaultX11ErrorHandler);
XSetIOErrorHandler(
io_error_handler ? io_error_handler : DefaultX11IOErrorHandler);
}
void LogErrorEventDescription(XDisplay* dpy,
const XErrorEvent& error_event) {
char error_str[256];
char request_str[256];
XGetErrorText(dpy, error_event.error_code, error_str, sizeof(error_str));
strncpy(request_str, "Unknown", sizeof(request_str));
if (error_event.request_code < 128) {
std::string num = base::UintToString(error_event.request_code);
XGetErrorDatabaseText(
dpy, "XRequest", num.c_str(), "Unknown", request_str,
sizeof(request_str));
} else {
int num_ext;
char** ext_list = XListExtensions(dpy, &num_ext);
for (int i = 0; i < num_ext; i++) {
int ext_code, first_event, first_error;
XQueryExtension(dpy, ext_list[i], &ext_code, &first_event, &first_error);
if (error_event.request_code == ext_code) {
std::string msg = base::StringPrintf(
"%s.%d", ext_list[i], error_event.minor_code);
XGetErrorDatabaseText(
dpy, "XRequest", msg.c_str(), "Unknown", request_str,
sizeof(request_str));
break;
}
}
XFreeExtensionList(ext_list);
}
LOG(WARNING)
<< "X error received: "
<< "serial " << error_event.serial << ", "
<< "error_code " << static_cast<int>(error_event.error_code)
<< " (" << error_str << "), "
<< "request_code " << static_cast<int>(error_event.request_code) << ", "
<< "minor_code " << static_cast<int>(error_event.minor_code)
<< " (" << request_str << ")";
}
// ----------------------------------------------------------------------------
// End of x11_util_internal.h
} // namespace ui
| 32.112439 | 80 | 0.64231 | [
"shape",
"vector"
] |
c806ad6b2d9ed6f6f0a4069c3953306e7e397b83 | 9,618 | cpp | C++ | Neon/src/Neon/Platform/Vulkan/VulkanGuiContext.cpp | FilipHusnjak/Neon | 3981a76f4a35302e0fc70d4e32b2b2ac19b53089 | [
"Apache-2.0"
] | 8 | 2020-09-11T10:36:38.000Z | 2021-12-16T12:59:31.000Z | Neon/src/Neon/Platform/Vulkan/VulkanGuiContext.cpp | FilipHusnjak/Neon | 3981a76f4a35302e0fc70d4e32b2b2ac19b53089 | [
"Apache-2.0"
] | null | null | null | Neon/src/Neon/Platform/Vulkan/VulkanGuiContext.cpp | FilipHusnjak/Neon | 3981a76f4a35302e0fc70d4e32b2b2ac19b53089 | [
"Apache-2.0"
] | 1 | 2021-01-06T13:36:56.000Z | 2021-01-06T13:36:56.000Z | #include "neopch.h"
#include "Neon/Core/Application.h"
#include "Neon/Platform/Vulkan/VulkanContext.h"
#include "VulkanGuiContext.h"
#include <backends/imgui_impl_glfw.h>
#include <backends/imgui_impl_vulkan.h>
namespace Neon
{
static void CheckVkResult(VkResult err)
{
if (err == 0)
{
return;
}
NEO_CORE_ERROR("[vulkan] Error: VkResult = %d", err);
if (err < 0)
{
abort();
}
}
void VulkanGuiContext::Init()
{
// Setup Dear ImGui context
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking
io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows
ImFont* pFont = io.Fonts->AddFontFromFileTTF(R"(C:\Windows\Fonts\segoeui.ttf)", 15.f);
io.FontDefault = io.Fonts->Fonts.back();
// Setup Dear ImGui style
ImGui::StyleColorsDark();
// When viewports are enabled we tweak WindowRounding/WindowBg so platform windows can look identical to regular ones.
ImGuiStyle& style = ImGui::GetStyle();
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
{
style.WindowRounding = 0.0f;
style.Colors[ImGuiCol_WindowBg].w = 1.0f;
}
auto& colors = ImGui::GetStyle().Colors;
colors[ImGuiCol_WindowBg] = ImVec4{0.1f, 0.105f, 0.11f, 1.0f};
// Headers
colors[ImGuiCol_Header] = ImVec4{0.2f, 0.205f, 0.21f, 1.0f};
colors[ImGuiCol_HeaderHovered] = ImVec4{0.3f, 0.305f, 0.31f, 1.0f};
colors[ImGuiCol_HeaderActive] = ImVec4{0.15f, 0.1505f, 0.151f, 1.0f};
// Buttons
colors[ImGuiCol_Button] = ImVec4{0.2f, 0.205f, 0.21f, 1.0f};
colors[ImGuiCol_ButtonHovered] = ImVec4{0.3f, 0.305f, 0.31f, 1.0f};
colors[ImGuiCol_ButtonActive] = ImVec4{0.15f, 0.1505f, 0.151f, 1.0f};
// Frame BG
colors[ImGuiCol_FrameBg] = ImVec4{0.2f, 0.205f, 0.21f, 1.0f};
colors[ImGuiCol_FrameBgHovered] = ImVec4{0.3f, 0.305f, 0.31f, 1.0f};
colors[ImGuiCol_FrameBgActive] = ImVec4{0.15f, 0.1505f, 0.151f, 1.0f};
// Tabs
colors[ImGuiCol_Tab] = ImVec4{0.15f, 0.1505f, 0.151f, 1.0f};
colors[ImGuiCol_TabHovered] = ImVec4{0.38f, 0.3805f, 0.381f, 1.0f};
colors[ImGuiCol_TabActive] = ImVec4{0.28f, 0.2805f, 0.281f, 1.0f};
colors[ImGuiCol_TabUnfocused] = ImVec4{0.15f, 0.1505f, 0.151f, 1.0f};
colors[ImGuiCol_TabUnfocusedActive] = ImVec4{0.2f, 0.205f, 0.21f, 1.0f};
// Title
colors[ImGuiCol_TitleBg] = ImVec4{0.15f, 0.1505f, 0.151f, 1.0f};
colors[ImGuiCol_TitleBgActive] = ImVec4{0.15f, 0.1505f, 0.151f, 1.0f};
colors[ImGuiCol_TitleBgCollapsed] = ImVec4{0.15f, 0.1505f, 0.151f, 1.0f};
// Resize Grip
colors[ImGuiCol_ResizeGrip] = ImVec4(0.91f, 0.91f, 0.91f, 0.25f);
colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.81f, 0.81f, 0.81f, 0.67f);
colors[ImGuiCol_ResizeGripActive] = ImVec4(0.46f, 0.46f, 0.46f, 0.95f);
// Scrollbar
colors[ImGuiCol_ScrollbarBg] = ImVec4(0.02f, 0.02f, 0.02f, 0.53f);
colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.31f, 0.31f, 0.31f, 1.0f);
colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.41f, 0.41f, 0.41f, 1.0f);
colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.51f, 0.51f, 0.51f, 1.0f);
// Check Mark
colors[ImGuiCol_CheckMark] = ImVec4(0.94f, 0.94f, 0.94f, 1.0f);
// Slider
colors[ImGuiCol_SliderGrab] = ImVec4(0.51f, 0.51f, 0.51f, 0.7f);
colors[ImGuiCol_SliderGrabActive] = ImVec4(0.66f, 0.66f, 0.66f, 1.0f);
Application& app = Application::Get();
GLFWwindow* window = static_cast<GLFWwindow*>(app.GetWindow().GetHandle());
auto vulkanContext = VulkanContext::Get();
auto device = VulkanContext::GetDevice();
// Create Descriptor Pool
vk::DescriptorPoolSize poolSizes[] = {{vk::DescriptorType::eSampler, 1000},
{vk::DescriptorType::eCombinedImageSampler, 1000},
{vk::DescriptorType::eSampledImage, 1000},
{vk::DescriptorType::eStorageImage, 1000},
{vk::DescriptorType::eUniformTexelBuffer, 1000},
{vk::DescriptorType::eStorageTexelBuffer, 1000},
{vk::DescriptorType::eUniformBuffer, 1000},
{vk::DescriptorType::eStorageBuffer, 1000},
{vk::DescriptorType::eUniformBufferDynamic, 1000},
{vk::DescriptorType::eStorageBufferDynamic, 1000},
{vk::DescriptorType::eInputAttachment, 1000}};
vk::DescriptorPoolCreateInfo imguiPoolCreateInfo = {};
imguiPoolCreateInfo.flags = vk::DescriptorPoolCreateFlagBits::eFreeDescriptorSet;
imguiPoolCreateInfo.maxSets = 1000 * IM_ARRAYSIZE(poolSizes);
imguiPoolCreateInfo.poolSizeCount = (uint32)IM_ARRAYSIZE(poolSizes);
imguiPoolCreateInfo.pPoolSizes = poolSizes;
m_ImGuiDescPool = device->GetHandle().createDescriptorPoolUnique(imguiPoolCreateInfo);
// Setup Platform/Renderer bindings
ImGui_ImplGlfw_InitForVulkan(window, true);
ImGui_ImplVulkan_InitInfo imguiInitInfo = {};
imguiInitInfo.Instance = VulkanContext::GetInstance();
imguiInitInfo.PhysicalDevice = device->GetPhysicalDevice()->GetHandle();
imguiInitInfo.Device = device->GetHandle();
imguiInitInfo.QueueFamily = device->GetPhysicalDevice()->GetGraphicsQueueIndex();
imguiInitInfo.Queue = device->GetGraphicsQueue();
imguiInitInfo.PipelineCache = nullptr;
imguiInitInfo.DescriptorPool = m_ImGuiDescPool.get();
imguiInitInfo.Allocator = nullptr;
imguiInitInfo.MinImageCount = 2;
imguiInitInfo.ImageCount = vulkanContext->GetSwapChain().GetImageCount();
imguiInitInfo.CheckVkResultFn = CheckVkResult;
ImGui_ImplVulkan_Init(&imguiInitInfo, vulkanContext->GetSwapChain().GetRenderPass());
// Load Fonts
// - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
// - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
// - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
// - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
// - Read 'docs/FONTS.md' for more instructions and details.
// - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
/*io.Fonts->AddFontDefault();
io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f);
io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f);
io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f);
io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f);
ImFont* font = io.Fonts->AddFontFromFileTTF(R"(c:\Windows\Fonts\ArialUni.ttf)", 18.0f, nullptr, io.Fonts->GetGlyphRangesJapanese());
//IM_ASSERT(font != NULL);*/
// Upload Fonts
auto& commandBuffer = VulkanContext::Get()->GetCommandBuffer(CommandBufferType::Graphics, true);
ImGui_ImplVulkan_CreateFontsTexture((VkCommandBuffer)commandBuffer->GetHandle());
VulkanContext::Get()->SubmitCommandBuffer(commandBuffer);
device->GetHandle().waitIdle();
ImGui_ImplVulkan_DestroyFontUploadObjects();
}
void VulkanGuiContext::Shutdown()
{
auto device = VulkanContext::GetDevice()->GetHandle();
device.waitIdle();
ImGui_ImplVulkan_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
m_ImGuiDescPool.reset();
}
void VulkanGuiContext::Begin()
{
ImGui_ImplVulkan_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
}
void VulkanGuiContext::End()
{
const VulkanSwapChain& swapChain = VulkanContext::Get()->GetSwapChain();
uint32 width = swapChain.GetWidth();
uint32 height = swapChain.GetHeight();
vk::CommandBuffer renderCommandBuffer = (VkCommandBuffer)VulkanContext::Get()->GetPrimaryRenderCommandBuffer()->GetHandle();
// Update viewport state
vk::Viewport viewport = {};
viewport.x = 0.f;
viewport.y = 0.f;
viewport.width = (float)width;
viewport.height = (float)height;
viewport.minDepth = 0.f;
viewport.maxDepth = 1.f;
// Update scissor state
vk::Rect2D scissor = {};
scissor.offset.x = 0;
scissor.offset.y = 0;
scissor.extent.width = width;
scissor.extent.height = height;
vk::ClearValue clearValues[2];
std::array<float, 4> clearColor = {0.2f, 0.2f, 0.2f, 1.0f};
clearValues[0].color = vk::ClearColorValue(clearColor);
clearValues[1].depthStencil = {1.0f, 0};
vk::RenderPassBeginInfo renderPassBeginInfo = {};
renderPassBeginInfo.renderPass = swapChain.GetRenderPass();
renderPassBeginInfo.renderArea.offset.x = 0;
renderPassBeginInfo.renderArea.offset.y = 0;
renderPassBeginInfo.renderArea.extent.width = width;
renderPassBeginInfo.renderArea.extent.height = height;
renderPassBeginInfo.clearValueCount = 2;
renderPassBeginInfo.pClearValues = clearValues;
renderPassBeginInfo.framebuffer = swapChain.GetCurrentFramebuffer();
renderCommandBuffer.beginRenderPass(renderPassBeginInfo, vk::SubpassContents::eInline);
renderCommandBuffer.setViewport(0, 1, &viewport);
renderCommandBuffer.setScissor(0, 1, &scissor);
ImGui::Render();
ImGui_ImplVulkan_RenderDrawData(ImGui::GetDrawData(), renderCommandBuffer);
renderCommandBuffer.endRenderPass();
ImGuiIO& io = ImGui::GetIO();
// Update and Render additional Platform Windows
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
{
ImGui::UpdatePlatformWindows();
ImGui::RenderPlatformWindowsDefault();
}
}
} // namespace Neon
| 39.743802 | 196 | 0.724475 | [
"render"
] |
c80b60785a8b3f7691ced13c15a67e5e15ad5fef | 7,680 | cpp | C++ | c++/Assignment 3 - Trees/BSTree.cpp | branjwong/portfolio | 1900293edc3dd99a0e50c6812fd5b74a0ab31085 | [
"MIT"
] | null | null | null | c++/Assignment 3 - Trees/BSTree.cpp | branjwong/portfolio | 1900293edc3dd99a0e50c6812fd5b74a0ab31085 | [
"MIT"
] | null | null | null | c++/Assignment 3 - Trees/BSTree.cpp | branjwong/portfolio | 1900293edc3dd99a0e50c6812fd5b74a0ab31085 | [
"MIT"
] | null | null | null | /*
* BSTree.cpp
*
* Created on: Mar 5, 2010
* Author: Brandon J Wong
*/
#include "BSTree.h"
BSTree::BSTree() {
root = 0;
}
// Copy constructor
BSTree::BSTree(const BSTree & rbt){
recBuild(rbt.root);
}
BSTree::~BSTree() {
// recDestroy(root);
}
// inserts a customer into the tree
bool BSTree::insert(string x, char y, int z) {
bool found = true; // evaluates to true if a duplicate is found
int treeCase = -1; // used for removal, ignore for insertion
Node *parent = 0;
Customer *c = new Customer(x,y,z);
// target points to the node pointer that will point to the newly inserted node
Node **target = bstSearch(&root, c, found, treeCase, parent);
if (found == false){
// attach a node to the node pointer (e.g. root, or a left/rightChild pointer)
*target = new Node(c, parent);
return true;
}
else {
// duplicates don't work
return false;
}
}
bool BSTree::remove(string x, char y) {
int treeCase = 0;
bool found = false;
Customer toRem(x,y);
Node *parent;
// target points to the node that will be deleted
Node *target = *bstSearch(&root, &toRem, found, treeCase, parent);
// set parent to the parent of the node to be deleted
parent = target->parent;
// only run removal if a match to (x,y) is found
if (found == true){
// Case 1: target is a leaf
if (treeCase == 1){
//compare target with parent
if (*target->data < *parent->data){
// set target's parent's left child to null
target->parent->leftChild = 0;
delete target;
target = 0;
return true;
}
else if (*target->data > *parent->data){
// set target's parent's right child to null
target->parent->rightChild = 0;
delete target;
target = 0;
return true;
}
}
// Case 2: target has a leftchild
else if (treeCase == 2){
//compare target with parent
if (parent != 0 && *target->data < *parent->data){
//replace parent's left child with *target's subtree
parent->leftChild = target->leftChild;
delete target;
target = 0;
return true;
}
else if (parent != 0 && *target->data > *parent->data){
//replace parent's right child with *target's subtree
parent->rightChild = target->leftChild;
delete target;
target = 0;
return true;
}
else {
root = target->leftChild;
delete target;
target = 0;
return true;
}
}
// Case 3: target has a rightchild
else if (treeCase == 3){
//compare target with parent
if (parent != 0 && *target->data < *parent->data){
//replace parent's left child with *target's subtree
parent->leftChild = target->rightChild;
delete target;
target = 0;
return true;
}
else if (parent != 0 && *target->data > *parent->data){
//replace parent's right child with *target's subtree
parent->rightChild = target->rightChild;
delete target;
target = 0;
return true;
}
else {
root = target->rightChild;
delete target;
target = 0;
return true;
}
}
// Case 4: target has 2 children
else if (treeCase == 4){
// find successor
vector<Customer> vc = rangeSearch(target->data->get_name(), target->data->get_initial(), target->rightChild->data->get_name(), target->rightChild->data->get_initial());
Customer successor(vc[1].get_name(), vc[1].get_initial());
Node *tempParent;
Node *temp = *bstSearch(&root, &successor, found, treeCase, tempParent);
// detatch successor
tempParent->leftChild = 0;
// attach target node's children to successor
temp->leftChild = target->leftChild;
temp->rightChild = target->rightChild;
// make successor child of target's parent
// if target < target's parent, make successor left child of target's parent
if (parent != 0 && *target->data < *parent->data){
parent->leftChild = temp;
delete target;
target = 0;
return true;
}
// if target > target's parent, make successor right child of target's parent
else if (parent != 0 && *target->data > *parent->data){
parent->rightChild = temp;
delete target;
target = 0;
return true;
} else {
root = temp;
delete target;
target = 0;
return true;
}
}
}
// do not run removal if no match to (x,y) is found
else {
return false;
}
}
bool BSTree::search(string x, char y) {
Customer *toFind = new Customer(x,y);
bool found = false;
int treeCase = -1;
Node *parent;
// treeCase, parent, and return value are unused
// found is modified during bstSearch
bstSearch(&root, toFind, found, treeCase, parent);
delete toFind;
if (found == true){
return true;
}
else {
return false;
}
}
vector<Customer> BSTree::rangeSearch(string x, char y, string z, char a) {
vector<Customer> result;
// initialize two customers for use in bstSearch w/ (x,y) and (z,a)
Customer leftTest(x,y);
Customer rightTest(z,a);
rangeHelper(root, result, leftTest, rightTest);
return result;
}
// recursively adds to vector<Customer>
void BSTree::rangeHelper(Node *n, vector<Customer> &v, Customer &leftTest, Customer &rightTest){
if (n != 0){
// if (n->leftChild != 0 && *n->leftChild->data >= leftTest){
rangeHelper(n->leftChild, v, leftTest, rightTest);
// }
if (leftTest <= *n->data && *n->data <= rightTest){
v.push_back(*n->data);
}
// if (n->rightChild != 0 && *n->rightChild->data <= rightTest){
rangeHelper(n->rightChild, v, leftTest, rightTest);
// }
}
}
void BSTree::inOrderPrint() {
inOrderPrintRec(root);
}
// basic inOrder traversal
void BSTree::inOrderPrintRec(Node *n) {
if (n != 0) {
inOrderPrintRec(n->leftChild);
cout << *n->data << endl; //visit
inOrderPrintRec(n->rightChild);
}
}
void BSTree::treePrint() {
treePrintRec(root,0);
}
// basically, a reverse inOrder traversal
void BSTree::treePrintRec(Node *n, int depth) {
if (n != 0) {
treePrintRec(n->rightChild, depth+1);
for (int i=0; i<2*depth; i++) {
cout << " ";
}
cout << "-" << *n->data << endl;
treePrintRec(n->leftChild, depth+1);
}
}
// if c is in tree:
// returns the address of the node pointer that points to the node that has the data
// if c isn't in tree:
// returns the address of the node pointer that points to the node where the data should go
Node** BSTree::bstSearch(Node **n, Customer *c, bool &found, int &treeCase, Node *&parent){
// If the node points to no data, return the node
if (*n == 0){
found = false;
return n;
}
// If the target is less than the data in the node search its left subtree
if (*c < *((*n)->data)){
parent = *n;
return bstSearch(&(*n)->leftChild, c, found, treeCase, parent);
}
// If the target is greater than the data in the node search its right subtree
else if (*c > *((*n)->data)){
parent = *n;
return bstSearch(&(*n)->rightChild, c, found, treeCase, parent);
}
else {
found = true;
// has no children
if ((*n)->leftChild == 0 && (*n)->rightChild == 0){
treeCase = 1;
}
// has a left child
else if ((*n)->leftChild != 0 && (*n)->rightChild == 0){
treeCase = 2;
}
// has a right child
else if ((*n)->leftChild == 0 && (*n)->rightChild != 0){
treeCase = 3;
}
// has two children
else if ((*n)->leftChild != 0 && (*n)->rightChild != 0){
treeCase = 4;
}
return n;
}
}
// preOrder traversal
void BSTree::recBuild(Node *n){
if (n != 0){
insert(n->data->get_name(), n->data->get_initial(), n->data->get_account());
recBuild(n->leftChild);
recBuild(n->rightChild);
}
}
// postOrder traversal
void BSTree::recDestroy(Node *n){
if (n != 0){
recDestroy(n->leftChild);
recDestroy(n->rightChild);
remove(n->data->get_name(), n->data->get_initial());
}
} | 25.346535 | 171 | 0.626432 | [
"vector"
] |
c8121e71ce861063521f953b82ce67dbd379af89 | 3,841 | hpp | C++ | include/tao/json/binding/internal/array.hpp | robinchrist/json | 99c57818ba1644a58f0535ff3e98bd2ae0e75b52 | [
"BSD-3-Clause",
"Apache-2.0",
"MIT"
] | null | null | null | include/tao/json/binding/internal/array.hpp | robinchrist/json | 99c57818ba1644a58f0535ff3e98bd2ae0e75b52 | [
"BSD-3-Clause",
"Apache-2.0",
"MIT"
] | null | null | null | include/tao/json/binding/internal/array.hpp | robinchrist/json | 99c57818ba1644a58f0535ff3e98bd2ae0e75b52 | [
"BSD-3-Clause",
"Apache-2.0",
"MIT"
] | null | null | null | // Copyright (c) 2018-2019 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/json/
#ifndef TAO_JSON_BINDING_INTERNAL_ARRAY_HPP
#define TAO_JSON_BINDING_INTERNAL_ARRAY_HPP
#include <utility>
#include <vector>
#include "../../basic_value.hpp"
#include "../../forward.hpp"
#include "../../internal/format.hpp"
#include "../../internal/type_traits.hpp"
namespace tao::json::binding::internal
{
template< typename T, typename L = std::make_index_sequence< T::size > >
struct array;
template< typename... As, std::size_t... Is >
struct array< json::internal::type_list< As... >, std::index_sequence< Is... > >
{
using elements = json::internal::type_list< As... >;
template< template< typename... > class Traits, typename C >
static const std::vector< basic_value< Traits > >& get_array_impl( const basic_value< Traits >& v )
{
const auto& a = v.get_array();
if( a.size() != sizeof...( As ) ) {
throw std::runtime_error( json::internal::format( "array size mismatch for type ", pegtl::internal::demangle< C >(), " -- expected ", sizeof...( As ), " received ", a.size(), json::message_extension( v ) ) );
}
return a;
}
template< template< typename... > class Traits, typename C >
static std::enable_if_t< std::is_constructible_v< C, typename As::value_t... >, C > as_type( const basic_value< Traits >& v )
{
const auto& a = get_array_impl< Traits, C >( v );
return C( a[ Is ].template as< typename As::value_t >()... );
}
template< template< typename... > class Traits, typename C >
static void to( const basic_value< Traits >& v, C& x ) // TODO: std::enable_if_t< WHAT?, void >
{
const auto& a = get_array_impl< Traits, C >( v );
( As::to( a[ Is ], x ), ... );
}
template< template< typename... > class Traits, typename C >
static void assign( basic_value< Traits >& v, const C& x )
{
v.emplace_array();
( v.emplace_back( As::read( x ) ), ... );
}
template< typename A, template< typename... > class Traits = traits, typename Producer, typename C, typename State >
static void consume_element( Producer& parser, C& x, State& s )
{
parser.element( s );
A::template consume< Traits >( parser, x );
}
template< template< typename... > class Traits = traits, typename Producer, typename C >
static void consume( Producer& parser, C& x )
{
auto s = parser.begin_array();
( consume_element< As, Traits >( parser, x, s ), ... );
parser.end_array( s );
}
template< typename A, template< typename... > class Traits, typename Consumer, typename C >
static void produce_element( Consumer& consumer, const C& x )
{
A::template produce< Traits >( consumer, x );
consumer.element();
}
template< template< typename... > class Traits = traits, typename Consumer, typename C >
static void produce( Consumer& consumer, const C& x )
{
consumer.begin_array( sizeof...( As ) );
( produce_element< As, Traits >( consumer, x ), ... );
consumer.end_array( sizeof...( As ) );
}
template< template< typename... > class Traits, typename C >
[[nodiscard]] static bool equal( const basic_value< Traits >& lhs, const C& rhs ) noexcept
{
const auto& p = lhs.skip_value_ptr();
if( p.is_array() ) {
const auto& a = p.get_array();
if( a.size() == sizeof...( As ) ) {
return ( ( a[ Is ] == As::read( rhs ) ) && ... );
}
}
return false;
}
};
} // namespace tao::json::binding::internal
#endif
| 36.932692 | 220 | 0.579537 | [
"vector"
] |
c8123a8faa7fad923b00eaf842c57b980664b786 | 15,936 | cpp | C++ | src/tests/class_tests/openms/source/AScore_test.cpp | tomas-pluskal/openms | 136ec9057435f6d45d65a8e1465b2a6cff9621a8 | [
"Zlib",
"Apache-2.0"
] | null | null | null | src/tests/class_tests/openms/source/AScore_test.cpp | tomas-pluskal/openms | 136ec9057435f6d45d65a8e1465b2a6cff9621a8 | [
"Zlib",
"Apache-2.0"
] | null | null | null | src/tests/class_tests/openms/source/AScore_test.cpp | tomas-pluskal/openms | 136ec9057435f6d45d65a8e1465b2a6cff9621a8 | [
"Zlib",
"Apache-2.0"
] | null | null | null | // --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2015.
//
// This software is released under a three-clause BSD license:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * 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.
// * Neither the name of any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// 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 ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS 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.
//
// --------------------------------------------------------------------------
// $Maintainer: David Wojnar $
// $Authors: David Wojnar $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/ANALYSIS/ID/AScore.h>
///////////////////////////
using namespace OpenMS;
using namespace std;
START_TEST(FalseDiscoveryRate, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
AScore* ptr = 0;
AScore* nullPointer = 0;
START_SECTION(AScore())
{
ptr = new AScore();
TEST_NOT_EQUAL(ptr, nullPointer)
}
END_SECTION
START_SECTION(~AScore())
{
delete ptr;
}
END_SECTION
ptr = new AScore();
START_SECTION((PeptideHit compute(PeptideHit & hit, RichPeakSpectrum &real_spectrum, double fragment_mass_tolerance, bool fragment_mass_unit_ppm)))
{
}
END_SECTION
START_SECTION((double computeCumulativeScore(Size N, Size n, double p)))
{
Size n = 5;
Size N = 1;
double p = 0.1;
TEST_PRECONDITION_VIOLATED(ptr->computeCumulativeScore(N,n,p));
n = 1;
double score = ptr->computeCumulativeScore(N,n,p);
TEST_REAL_SIMILAR(score,0.1);
N = 3;
score = ptr->computeCumulativeScore(N,n,p);
TEST_REAL_SIMILAR(score,0.271);
}
END_SECTION
START_SECTION((determineHighestScoringPermutations(const std::vector<std::vector<double> > & peptide_site_scores, std::vector<ProbablePhosphoSites> & sites, const std::vector<std::vector<Size> > & permutations)))
{
std::vector< std::vector<double> > peptide_site_scores_1;
std::vector< std::vector<double> > peptide_site_scores_2;
std::vector< std::vector<double> > peptide_site_scores_3;
peptide_site_scores_1.resize(4);
peptide_site_scores_2.resize(4);
peptide_site_scores_3.resize(4);
vector<double> temp;
temp.resize(10);
for(Size i = 0; i < 10; ++i)
{
temp[i] = 0.1;
}
peptide_site_scores_1[0] = temp;
peptide_site_scores_2[3] = temp;
peptide_site_scores_3[0] = temp;
temp.clear();
temp.resize(10);
for(Size i = 0; i < 10; ++i)
{
temp[i] = 0.2;
}
peptide_site_scores_1[1] = temp;
peptide_site_scores_2[0] = temp;
peptide_site_scores_3[3] = temp;
temp.clear();
temp.resize(10);
for(Size i = 0; i < 10; ++i)
{
temp[i] = 0.3;
}
peptide_site_scores_1[2] = temp;
peptide_site_scores_2[1] = temp;
peptide_site_scores_3[2] = temp;
temp.clear();
temp.resize(10);
for(Size i = 0; i < 10; ++i)
{
temp[i] = 0.4;
}
peptide_site_scores_1[3] = temp;
peptide_site_scores_2[2] = temp;
peptide_site_scores_3[1] = temp;
vector<vector<Size> > permutations;
vector<Size> per;
per.push_back(1);
per.push_back(3);
per.push_back(5);
permutations.push_back(per);
per.clear();
per.push_back(3);
per.push_back(5);
per.push_back(6);
permutations.push_back(per);
per.clear();
per.push_back(1);
per.push_back(3);
per.push_back(6);
permutations.push_back(per);
per.clear();
per.push_back(1);
per.push_back(5);
per.push_back(6);
permutations.push_back(per);
vector<ProbablePhosphoSites> sites;
ptr->determineHighestScoringPermutations(peptide_site_scores_1,sites,permutations);
TEST_EQUAL(sites.size(),3)
TEST_EQUAL(sites[0].seq_1, 3);
TEST_EQUAL(sites[0].seq_2,1);
TEST_EQUAL(sites[0].second, 3);
TEST_EQUAL(sites[0].first,1);
TEST_EQUAL(sites[0].peak_depth, 1)
TEST_EQUAL(sites[1].first,5);
TEST_EQUAL(sites[1].second,3);
TEST_EQUAL(sites[1].seq_1, 3);
TEST_EQUAL(sites[1].seq_2,2);
TEST_EQUAL(sites[1].peak_depth, 1)
TEST_EQUAL(sites[2].first,6);
TEST_EQUAL(sites[2].second,3);
TEST_EQUAL(sites[2].seq_1, 3);
TEST_EQUAL(sites[2].seq_2,0);
TEST_EQUAL(sites[2].peak_depth, 1)
ptr->determineHighestScoringPermutations(peptide_site_scores_3,sites,permutations);
TEST_EQUAL(sites.size(),3)
TEST_EQUAL(sites[0].seq_1, 1);
TEST_EQUAL(sites[0].seq_2,3);
TEST_EQUAL(sites[0].second,1 );
TEST_EQUAL(sites[0].first,3);
TEST_EQUAL(sites[0].peak_depth, 1)
TEST_EQUAL(sites[1].first,5);
TEST_EQUAL(sites[1].second,1);
TEST_EQUAL(sites[1].seq_1, 1);
TEST_EQUAL(sites[1].seq_2,2);
TEST_EQUAL(sites[1].peak_depth, 1)
TEST_EQUAL(sites[2].first,6);
TEST_EQUAL(sites[2].second,1);
TEST_EQUAL(sites[2].seq_1, 1);
TEST_EQUAL(sites[2].seq_2,0);
TEST_EQUAL(sites[2].peak_depth, 1)
ptr->determineHighestScoringPermutations(peptide_site_scores_2,sites,permutations);
TEST_EQUAL(sites.size(),3)
TEST_EQUAL(sites[0].seq_1, 2);
TEST_EQUAL(sites[0].seq_2,1);
TEST_EQUAL(sites[0].second,5 );
TEST_EQUAL(sites[0].first,1);
TEST_EQUAL(sites[0].peak_depth, 1)
TEST_EQUAL(sites[1].first,3);
TEST_EQUAL(sites[1].second,5);
TEST_EQUAL(sites[1].seq_1, 2);
TEST_EQUAL(sites[1].seq_2,3);
TEST_EQUAL(sites[1].peak_depth, 1)
TEST_EQUAL(sites[2].first,6);
TEST_EQUAL(sites[2].second,5);
TEST_EQUAL(sites[2].seq_1, 2);
TEST_EQUAL(sites[2].seq_2,0);
TEST_EQUAL(sites[2].peak_depth, 1)
peptide_site_scores_1.clear();
temp.clear();
temp.resize(10);
temp[0] = 55;
temp[1] = 60;
temp[2]= 75;
temp[3] = 100;
temp[4] = 90;
temp[5] = 120;
temp[6] =125;
temp[7] = 120;
temp[8] = 100;
temp[9] = 90;
peptide_site_scores_1.push_back(temp);
temp.clear();
temp.resize(10);
temp[0] = 40;
temp[1] = 50;
temp[2] = 53;
temp[3] = 60;
temp[4] = 50;
temp[5]= 53;
temp[6]= 59;
temp[7] = 53;
temp[8] = 50;
temp[9]= 40;
peptide_site_scores_1.push_back(temp);
permutations.clear();
per.clear();
per.push_back(3);
permutations.push_back(per);
per.clear();
per.push_back(6);
permutations.push_back(per);
ptr->determineHighestScoringPermutations(peptide_site_scores_1,sites,permutations);
TEST_EQUAL(sites.size(),1)
TEST_EQUAL(sites[0].seq_1,0)
TEST_EQUAL(sites[0].seq_2,1)
TEST_EQUAL(sites[0].first,3);
TEST_EQUAL(sites[0].second,6);
TEST_EQUAL(sites[0].peak_depth, 6)
permutations.clear();
per.clear();
per.push_back(3);
per.push_back(5);
permutations.push_back(per);
per.clear();
per.push_back(5);
per.push_back(6);
permutations.push_back(per);
per.clear();
per.push_back(3);
per.push_back(7);
permutations.push_back(per);
per.clear();
per.push_back(3);
per.push_back(6);
permutations.push_back(per);
per.clear();
per.push_back(5);
per.push_back(7);
permutations.push_back(per);
per.clear();
per.push_back(6);
per.push_back(7);
permutations.push_back(per);
std::vector< std::vector<double> > sec;
peptide_site_scores_1.push_back(temp);
peptide_site_scores_1.push_back(temp);
peptide_site_scores_1.push_back(temp);
peptide_site_scores_1.push_back(temp);
ptr->determineHighestScoringPermutations(peptide_site_scores_1,sites,permutations);
TEST_EQUAL(sites.size(),2)
TEST_EQUAL(sites[0].seq_1,0)
TEST_EQUAL(sites[0].seq_2,4)
TEST_EQUAL(sites[0].first,3);
TEST_EQUAL(sites[0].second,7);
TEST_EQUAL(sites[0].peak_depth, 6)
TEST_EQUAL(sites[1].seq_1,0)
TEST_EQUAL(sites[1].seq_2,3)
TEST_EQUAL(sites[1].first,5);
TEST_EQUAL(sites[1].second,6);
TEST_EQUAL(sites[1].peak_depth, 6)
}
END_SECTION
START_SECTION((computeSiteDeterminingIons(std::vector<RichPeakSpectrum> & th_spectra, ProbablePhosphoSites & candidates, Int charge, std::vector<RichPeakSpectrum> & site_determining_ions)))
{
vector<RichPeakSpectrum> th_spectra;
RichPeakSpectrum temp1,temp2;
temp1.setName("VT(Phospho)EQSP");
temp2.setName("VTEQS(Phospho)P");
ProbablePhosphoSites candidates;
candidates.seq_1 = 0;
candidates.seq_2 = 1;
candidates.first = 1;
candidates.second = 4;
candidates.peak_depth = 1;
th_spectra.push_back(temp1);
th_spectra.push_back(temp2);
vector<RichPeakSpectrum> site_determining_ions;
ptr->computeSiteDeterminingIons(th_spectra,candidates,1,site_determining_ions);
TEST_EQUAL(site_determining_ions.size(),2)
TEST_EQUAL(site_determining_ions[0].size(),6)
TEST_EQUAL(site_determining_ions[1].size(),6)
candidates.first = 4;
candidates.second = 1;
candidates.seq_1 = 1;
candidates.seq_2 = 0;
TEST_REAL_SIMILAR(site_determining_ions[0][0].getMZ(),203.102)
TEST_REAL_SIMILAR(site_determining_ions[0][site_determining_ions[0].size()-1].getMZ(),538.19)
TEST_REAL_SIMILAR(site_determining_ions[1][0].getMZ(),201.123)
TEST_REAL_SIMILAR(site_determining_ions[1][site_determining_ions[1].size()-1].getMZ(),540.17)
ptr->computeSiteDeterminingIons(th_spectra,candidates,1,site_determining_ions);
TEST_EQUAL(site_determining_ions.size(),2)
TEST_EQUAL(site_determining_ions[0].size(),6)
TEST_EQUAL(site_determining_ions[1].size(),6)
TEST_REAL_SIMILAR(site_determining_ions[1][0].getMZ(),203.102)
TEST_REAL_SIMILAR(site_determining_ions[1][site_determining_ions[1].size()-1].getMZ(),538.19)
TEST_REAL_SIMILAR(site_determining_ions[0][0].getMZ(),201.123)
TEST_REAL_SIMILAR(site_determining_ions[0][site_determining_ions[0].size()-1].getMZ(),540.17)
temp1.setName("T(Phospho)YQYS");
temp2.setName("TYQYS(Phospho)");
th_spectra.clear();
th_spectra.push_back(temp1);
th_spectra.push_back(temp2);
candidates.seq_1 = 0;
candidates.seq_2 = 1;
candidates.first = 0;
candidates.second = 4;
ptr->computeSiteDeterminingIons(th_spectra,candidates,1,site_determining_ions);
TEST_EQUAL(site_determining_ions.size(),2)
TEST_EQUAL(site_determining_ions[0].size(),7)
TEST_EQUAL(site_determining_ions[1].size(),7)
TEST_REAL_SIMILAR(site_determining_ions[0][0].getMZ(),106.05)
TEST_REAL_SIMILAR(site_determining_ions[0][site_determining_ions[0].size()-1].getMZ(),636.206)
TEST_REAL_SIMILAR(site_determining_ions[1][0].getMZ(),186.016)
TEST_REAL_SIMILAR(site_determining_ions[1][site_determining_ions[1].size()-1].getMZ(),640.201)
candidates.first = 4;
candidates.second = 0;
candidates.seq_1 = 1;
candidates.seq_2 = 0;
ptr->computeSiteDeterminingIons(th_spectra,candidates,1,site_determining_ions);
TEST_EQUAL(site_determining_ions.size(),2)
TEST_EQUAL(site_determining_ions[0].size(),7)
TEST_EQUAL(site_determining_ions[1].size(),7)
TEST_REAL_SIMILAR(site_determining_ions[1][0].getMZ(),106.05)
TEST_REAL_SIMILAR(site_determining_ions[1][site_determining_ions[1].size()-1].getMZ(),636.206)
TEST_REAL_SIMILAR(site_determining_ions[0][0].getMZ(),186.016)
TEST_REAL_SIMILAR(site_determining_ions[0][site_determining_ions[0].size()-1].getMZ(),640.201)
temp1.setName("TST(Phospho)YQYSYPP");
temp2.setName("TSTYQYS(Phospho)YPP");
th_spectra.clear();
th_spectra.push_back(temp1);
th_spectra.push_back(temp2);
candidates.seq_1 = 0;
candidates.seq_2 = 1;
candidates.first = 2;
candidates.second = 6;
ptr->computeSiteDeterminingIons(th_spectra,candidates,1,site_determining_ions);
TEST_EQUAL(site_determining_ions.size(),2)
TEST_EQUAL(site_determining_ions[0].size(),9)
TEST_EQUAL(site_determining_ions[1].size(),9)
TEST_REAL_SIMILAR(site_determining_ions[0][0].getMZ(),370.101)
TEST_REAL_SIMILAR(site_determining_ions[0][site_determining_ions[0].size()-1].getMZ(),917.403)
TEST_REAL_SIMILAR(site_determining_ions[1][0].getMZ(),290.135)
TEST_REAL_SIMILAR(site_determining_ions[1][site_determining_ions[1].size()-1].getMZ(),997.37)
candidates.seq_1 = 1;
candidates.seq_2 = 0;
candidates.first = 6;
candidates.second = 2;
ptr->computeSiteDeterminingIons(th_spectra,candidates,1,site_determining_ions);
TEST_EQUAL(site_determining_ions.size(),2)
TEST_EQUAL(site_determining_ions[0].size(),9)
TEST_EQUAL(site_determining_ions[1].size(),9)
TEST_REAL_SIMILAR(site_determining_ions[1][0].getMZ(),370.101)
TEST_REAL_SIMILAR(site_determining_ions[1][site_determining_ions[1].size()-1].getMZ(),917.403)
TEST_REAL_SIMILAR(site_determining_ions[0][0].getMZ(),290.135)
TEST_REAL_SIMILAR(site_determining_ions[0][site_determining_ions[0].size()-1].getMZ(),997.37)
}
END_SECTION
START_SECTION((std::vector<Size> getSites(AASequence& without_phospho)))
AASequence phospho = AASequence::fromString("VTQSPSSP");
vector<Size> tupel(ptr->getSites(phospho));
TEST_EQUAL(4, tupel.size())
TEST_EQUAL(1, tupel[0])
TEST_EQUAL(3,tupel[1])
TEST_EQUAL(5,tupel[2])
TEST_EQUAL(6,tupel[3])
END_SECTION
START_SECTION((std::vector<std::vector<Size> > computePermutations(std::vector<Size>& tupel,Int number_of_phospho_sites)))
vector<Size> tupel;
tupel.push_back(1);
tupel.push_back(2);
tupel.push_back(3);
tupel.push_back(4);
vector<vector<Size> > permutations;
permutations = ptr->computePermutations(tupel,1);
TEST_EQUAL(4,permutations.size())
TEST_EQUAL(1,permutations[0][0])
TEST_EQUAL(2,permutations[1][0])
TEST_EQUAL(3,permutations[2][0])
TEST_EQUAL(4,permutations[3][0])
permutations = ptr->computePermutations(tupel,2);
TEST_EQUAL(6,permutations.size())
TEST_EQUAL(1,permutations[0][0])
TEST_EQUAL(2,permutations[0][1])
TEST_EQUAL(1,permutations[1][0])
TEST_EQUAL(3,permutations[1][1])
TEST_EQUAL(1,permutations[2][0])
TEST_EQUAL(4,permutations[2][1])
TEST_EQUAL(2,permutations[3][0])
TEST_EQUAL(3,permutations[3][1])
TEST_EQUAL(2,permutations[4][0])
TEST_EQUAL(4,permutations[4][1])
TEST_EQUAL(3,permutations[5][0])
TEST_EQUAL(4,permutations[5][1])
permutations = ptr->computePermutations(tupel,3);
TEST_EQUAL(4,permutations.size())
TEST_EQUAL(1,permutations[0][0])
TEST_EQUAL(2,permutations[0][1])
TEST_EQUAL(3,permutations[0][2])
TEST_EQUAL(1,permutations[1][0])
TEST_EQUAL(2,permutations[1][1])
TEST_EQUAL(4,permutations[1][2])
TEST_EQUAL(1,permutations[2][0])
TEST_EQUAL(3,permutations[2][1])
TEST_EQUAL(4,permutations[2][2])
TEST_EQUAL(2,permutations[3][0])
TEST_EQUAL(3,permutations[3][1])
TEST_EQUAL(4,permutations[3][2])
permutations = ptr->computePermutations(tupel,4);
TEST_EQUAL(1,permutations.size())
TEST_EQUAL(1,permutations[0][0])
TEST_EQUAL(2,permutations[0][1])
TEST_EQUAL(3,permutations[0][2])
TEST_EQUAL(4,permutations[0][3])
END_SECTION
delete ptr;
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
| 33.549474 | 212 | 0.704506 | [
"vector"
] |
c817183f1abe8ce439f7f74e86c9233ba6a35715 | 6,393 | hpp | C++ | include/nil/crypto3/hash/find_group_hash.hpp | JasonCoombs/crypto3-hash | a4f330d14029b0b0330a5697ef24e825137ffded | [
"MIT"
] | null | null | null | include/nil/crypto3/hash/find_group_hash.hpp | JasonCoombs/crypto3-hash | a4f330d14029b0b0330a5697ef24e825137ffded | [
"MIT"
] | null | null | null | include/nil/crypto3/hash/find_group_hash.hpp | JasonCoombs/crypto3-hash | a4f330d14029b0b0330a5697ef24e825137ffded | [
"MIT"
] | null | null | null | //---------------------------------------------------------------------------//
// Copyright (c) 2021 Mikhail Komarov <nemo@nil.foundation>
// Copyright (c) 2021 Ilias Khairullin <ilias@nil.foundation>
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//---------------------------------------------------------------------------//
#ifndef CRYPTO3_HASH_FIND_GROUP_HASH_HPP
#define CRYPTO3_HASH_FIND_GROUP_HASH_HPP
#include <string>
#include <array>
#include <vector>
#include <nil/crypto3/algebra/curves/jubjub.hpp>
#include <nil/marshalling/status_type.hpp>
#include <nil/marshalling/field_type.hpp>
#include <nil/marshalling/endianness.hpp>
#include <nil/marshalling/algorithms/pack.hpp>
#include <nil/crypto3/marshalling/algebra/types/curve_element.hpp>
#include <nil/crypto3/hash/algorithm/hash.hpp>
#include <nil/crypto3/hash/sha2.hpp>
namespace nil {
namespace crypto3 {
namespace hashes {
struct find_group_hash_default_params {
static constexpr std::size_t dst_bits = 8 * 8;
using dst_type = std::vector<std::uint8_t>;
static inline dst_type dst = []() {
std::string default_tag_str = "Zcash_PH";
dst_type dst(default_tag_str.begin(), default_tag_str.end());
assert(dst.size() == 8);
return dst;
}();
};
/*!
* @brief Hashing to elliptic curve Jubjub according to FindGroupHash Zcash algorithm
* https://zips.z.cash/protocol/protocol.pdf#concretegrouphashjubjub
*
* @tparam Group
* @tparam Params
*/
// TODO: use blake2s by default
template<typename Params = find_group_hash_default_params,
typename Hash = sha2<256>,
typename Group = algebra::curves::jubjub::template g1_type<
nil::crypto3::algebra::curves::coordinates::affine,
nil::crypto3::algebra::curves::forms::twisted_edwards>>
struct find_group_hash {
using params = Params;
using hash_type = Hash;
using group_type = Group;
using curve_type = typename group_type::curve_type;
using group_value_type = typename group_type::value_type;
using internal_accumulator_type = accumulator_set<hash_type>;
using result_type = group_value_type;
static inline std::vector<std::uint8_t> urs = {
0x30, 0x39, 0x36, 0x62, 0x33, 0x36, 0x61, 0x35, 0x38, 0x30, 0x34, 0x62, 0x66, 0x61, 0x63, 0x65,
0x66, 0x31, 0x36, 0x39, 0x31, 0x65, 0x31, 0x37, 0x33, 0x63, 0x33, 0x36, 0x36, 0x61, 0x34, 0x37,
0x66, 0x66, 0x35, 0x62, 0x61, 0x38, 0x34, 0x61, 0x34, 0x34, 0x66, 0x32, 0x36, 0x64, 0x64, 0x64,
0x37, 0x65, 0x38, 0x64, 0x39, 0x66, 0x37, 0x39, 0x64, 0x35, 0x62, 0x34, 0x32, 0x64, 0x66, 0x30};
static inline void init_accumulator(internal_accumulator_type &acc) {
hash<hash_type>(params::dst, acc);
hash<hash_type>(urs, acc);
}
template<typename InputRange>
static inline void update(internal_accumulator_type &acc, const InputRange &range) {
hash<hash_type>(range, acc);
}
template<typename InputIterator>
static inline void update(internal_accumulator_type &acc, InputIterator first, InputIterator last) {
hash<hash_type>(first, last, acc);
}
static inline result_type process(internal_accumulator_type &acc) {
nil::marshalling::status_type status;
group_value_type point;
std::uint8_t i = 0;
while (true) {
auto acc_copy = acc;
hash<hash_type>(
{
i++,
},
acc_copy);
typename hash_type::digest_type H =
nil::crypto3::accumulators::extract::hash<hash_type>(acc_copy);
// TODO: generalize pack interface to accept arbitrary containers
std::vector<std::uint8_t> H_vec(std::cbegin(H), std::cend(H));
point = nil::marshalling::pack<nil::marshalling::option::little_endian>(H_vec, status);
if (status == nil::marshalling::status_type::success) {
break;
}
// TODO: return status
assert(i < 256);
}
point = typename group_type::field_type::value_type(group_type::params_type::cofactor) * point;
// TODO: return status
assert(!point.is_zero());
assert(point.is_well_formed());
return point;
}
};
} // namespace hashes
} // namespace crypto3
} // namespace nil
#endif // CRYPTO3_HASH_FIND_GROUP_HASH_HPP
| 46.326087 | 116 | 0.563272 | [
"vector"
] |
c817f7eef0d812f89e9ad50786bfd056d348a3b6 | 23,698 | cpp | C++ | src/PlayerManager.cpp | Eperty123/OpenFusion | cd42f181e648ae0b4dc52f74ae263e0ece7393e3 | [
"MIT"
] | 3 | 2021-09-01T04:02:54.000Z | 2022-03-23T19:55:28.000Z | src/PlayerManager.cpp | Eperty123/OpenFusion | cd42f181e648ae0b4dc52f74ae263e0ece7393e3 | [
"MIT"
] | null | null | null | src/PlayerManager.cpp | Eperty123/OpenFusion | cd42f181e648ae0b4dc52f74ae263e0ece7393e3 | [
"MIT"
] | 1 | 2022-02-07T05:20:14.000Z | 2022-02-07T05:20:14.000Z | #include "core/Core.hpp"
#include "core/CNShared.hpp"
#include "servers/CNShardServer.hpp"
#include "db/Database.hpp"
#include "PlayerManager.hpp"
#include "NPCManager.hpp"
#include "Missions.hpp"
#include "Items.hpp"
#include "Nanos.hpp"
#include "Groups.hpp"
#include "Chat.hpp"
#include "Buddies.hpp"
#include "Combat.hpp"
#include "Racing.hpp"
#include "BuiltinCommands.hpp"
#include "Abilities.hpp"
#include "Eggs.hpp"
#include "settings.hpp"
#include <assert.h>
#include <algorithm>
#include <vector>
#include <cmath>
using namespace PlayerManager;
std::map<CNSocket*, Player*> PlayerManager::players;
static void addPlayer(CNSocket* key, Player plr) {
Player *p = new Player();
// copy object into heap memory
*p = plr;
players[key] = p;
p->chunkPos = std::make_tuple(0, 0, 0); // TODO: maybe replace with specialized "no chunk" value
p->lastHeartbeat = 0;
std::cout << getPlayerName(p) << " has joined!" << std::endl;
std::cout << players.size() << " players" << std::endl;
}
void PlayerManager::removePlayer(CNSocket* key) {
Player* plr = getPlayer(key);
uint64_t fromInstance = plr->instanceID;
Groups::groupKickPlayer(plr);
// remove player's bullets
Combat::Bullets.erase(plr->iID);
// remove player's ongoing race, if it exists
Racing::EPRaces.erase(key);
// save player to DB
Database::updatePlayer(plr);
// remove player visually and untrack
EntityRef ref = {key};
Chunking::removeEntityFromChunks(Chunking::getViewableChunks(plr->chunkPos), ref);
Chunking::untrackEntity(plr->chunkPos, ref);
std::cout << getPlayerName(plr) << " has left!" << std::endl;
delete plr;
players.erase(key);
// if the player was in a lair, clean it up
Chunking::destroyInstanceIfEmpty(fromInstance);
// remove player's buffs from the server
auto it = Eggs::EggBuffs.begin();
while (it != Eggs::EggBuffs.end()) {
if (it->first.first == key) {
it = Eggs::EggBuffs.erase(it);
}
else
it++;
}
std::cout << players.size() << " players" << std::endl;
}
void PlayerManager::updatePlayerPosition(CNSocket* sock, int X, int Y, int Z, uint64_t I, int angle) {
Player* plr = getPlayer(sock);
plr->angle = angle;
ChunkPos oldChunk = plr->chunkPos;
ChunkPos newChunk = Chunking::chunkPosAt(X, Y, I);
plr->x = X;
plr->y = Y;
plr->z = Z;
plr->instanceID = I;
if (oldChunk == newChunk)
return; // didn't change chunks
Chunking::updateEntityChunk({sock}, oldChunk, newChunk);
}
void PlayerManager::sendPlayerTo(CNSocket* sock, int X, int Y, int Z, uint64_t I) {
Player* plr = getPlayer(sock);
plr->onMonkey = false;
if (plr->instanceID == INSTANCE_OVERWORLD) {
// save last uninstanced coords
plr->lastX = plr->x;
plr->lastY = plr->y;
plr->lastZ = plr->z;
plr->lastAngle = plr->angle;
}
Missions::failInstancedMissions(sock); // fail any instanced missions
uint64_t fromInstance = plr->instanceID; // pre-warp instance, saved for post-warp
if (I == INSTANCE_OVERWORLD || (I != fromInstance && fromInstance != 0)) {
// annoying but necessary to set the flag back
INITSTRUCT(sP_FE2CL_REP_PC_WARP_USE_NPC_SUCC, resp);
resp.iX = X;
resp.iY = Y;
resp.iZ = Z;
resp.iCandy = plr->money;
resp.eIL = 4; // do not take away any items
sock->sendPacket(resp, P_FE2CL_REP_PC_WARP_USE_NPC_SUCC);
}
if (I != INSTANCE_OVERWORLD) {
INITSTRUCT(sP_FE2CL_INSTANCE_MAP_INFO, pkt);
pkt.iInstanceMapNum = (int32_t)MAPNUM(I); // lower 32 bits are mapnum
if (I != fromInstance // do not retransmit MAP_INFO on recall
&& Racing::EPData.find(pkt.iInstanceMapNum) != Racing::EPData.end()) {
EPInfo* ep = &Racing::EPData[pkt.iInstanceMapNum];
pkt.iEP_ID = ep->EPID;
pkt.iMapCoordX_Min = ep->zoneX * 51200;
pkt.iMapCoordX_Max = (ep->zoneX + 1) * 51200;
pkt.iMapCoordY_Min = ep->zoneY * 51200;
pkt.iMapCoordY_Max = (ep->zoneY + 1) * 51200;
pkt.iMapCoordZ_Min = INT32_MIN;
pkt.iMapCoordZ_Max = INT32_MAX;
}
sock->sendPacket(pkt, P_FE2CL_INSTANCE_MAP_INFO);
}
INITSTRUCT(sP_FE2CL_REP_PC_GOTO_SUCC, pkt2);
pkt2.iX = X;
pkt2.iY = Y;
pkt2.iZ = Z;
sock->sendPacket(pkt2, P_FE2CL_REP_PC_GOTO_SUCC);
Chunking::updateEntityChunk({sock}, plr->chunkPos, std::make_tuple(0, 0, 0)); // force player to reload chunks
updatePlayerPosition(sock, X, Y, Z, I, plr->angle);
// post-warp: check if the source instance has no more players in it and delete it if so
Chunking::destroyInstanceIfEmpty(fromInstance);
// clean up EPRaces if we were likely in an IZ and left
if (fromInstance != INSTANCE_OVERWORLD && fromInstance != I
&& Racing::EPRaces.find(sock) != Racing::EPRaces.end())
Racing::EPRaces.erase(sock);
}
void PlayerManager::sendPlayerTo(CNSocket* sock, int X, int Y, int Z) {
sendPlayerTo(sock, X, Y, Z, getPlayer(sock)->instanceID);
}
/*
* Sends all nanos, from 0 to 58 (the contents of the Nanos array in PC_ENTER_SUCC are totally irrelevant).
* The first Nano in the in-game nanobook is the Unstable Nano, which is Van Kleiss.
* 0 (in plr->Nanos) is the null nano entry.
* 58 is a "Coming Soon" duplicate entry for an actual Van Kleiss nano, identical to the Unstable Nano.
* Nanos the player hasn't unlocked will (and should) be greyed out. Thus, all nanos should be accounted
* for in these packets, even if the player hasn't unlocked them.
*/
static void sendNanoBookSubset(CNSocket *sock) {
#ifdef ACADEMY
Player *plr = getPlayer(sock);
int16_t id = 0;
INITSTRUCT(sP_FE2CL_REP_NANO_BOOK_SUBSET, pkt);
pkt.PCUID = plr->iID;
pkt.bookSize = NANO_COUNT;
while (id < NANO_COUNT) {
pkt.elementOffset = id;
for (int i = id - pkt.elementOffset; id < NANO_COUNT && i < 10; id++, i = id - pkt.elementOffset)
pkt.element[i] = plr->Nanos[id];
sock->sendPacket(pkt, P_FE2CL_REP_NANO_BOOK_SUBSET);
}
#endif
}
static void enterPlayer(CNSocket* sock, CNPacketData* data) {
auto enter = (sP_CL2FE_REQ_PC_ENTER*)data->buf;
INITSTRUCT(sP_FE2CL_REP_PC_ENTER_SUCC, response);
// TODO: check if serialkey exists, if it doesn't send sP_FE2CL_REP_PC_ENTER_FAIL
Player plr = CNSharedData::getPlayer(enter->iEnterSerialKey);
plr.groupCnt = 1;
plr.iIDGroup = plr.groupIDs[0] = plr.iID;
DEBUGLOG(
std::cout << "P_CL2FE_REQ_PC_ENTER:" << std::endl;
std::cout << "\tID: " << AUTOU16TOU8(enter->szID) << std::endl;
std::cout << "\tSerial: " << enter->iEnterSerialKey << std::endl;
std::cout << "\tTemp: " << enter->iTempValue << std::endl;
std::cout << "\tPC_UID: " << plr.PCStyle.iPC_UID << std::endl;
)
// check if account is already in use
if (isAccountInUse(plr.accountId)) {
// kick the other player
exitDuplicate(plr.accountId);
}
response.iID = plr.iID;
response.uiSvrTime = getTime();
response.PCLoadData2CL.iUserLevel = plr.accountLevel;
response.PCLoadData2CL.iHP = plr.HP;
response.PCLoadData2CL.iLevel = plr.level;
response.PCLoadData2CL.iCandy = plr.money;
response.PCLoadData2CL.iFusionMatter = plr.fusionmatter;
response.PCLoadData2CL.iMentor = plr.mentor;
response.PCLoadData2CL.iMentorCount = 1; // how many guides the player has had
response.PCLoadData2CL.iX = plr.x;
response.PCLoadData2CL.iY = plr.y;
response.PCLoadData2CL.iZ = plr.z;
response.PCLoadData2CL.iAngle = plr.angle;
response.PCLoadData2CL.iBatteryN = plr.batteryN;
response.PCLoadData2CL.iBatteryW = plr.batteryW;
response.PCLoadData2CL.iBuddyWarpTime = 60; // sets 60s warp cooldown on login
response.PCLoadData2CL.iWarpLocationFlag = plr.iWarpLocationFlag;
response.PCLoadData2CL.aWyvernLocationFlag[0] = plr.aSkywayLocationFlag[0];
response.PCLoadData2CL.aWyvernLocationFlag[1] = plr.aSkywayLocationFlag[1];
response.PCLoadData2CL.iActiveNanoSlotNum = -1;
response.PCLoadData2CL.iFatigue = 50;
response.PCLoadData2CL.PCStyle = plr.PCStyle;
// client doesnt read this, it gets it from charinfo
// response.PCLoadData2CL.PCStyle2 = plr.PCStyle2;
// inventory
for (int i = 0; i < AEQUIP_COUNT; i++)
response.PCLoadData2CL.aEquip[i] = plr.Equip[i];
for (int i = 0; i < AINVEN_COUNT; i++)
response.PCLoadData2CL.aInven[i] = plr.Inven[i];
// quest inventory
for (int i = 0; i < AQINVEN_COUNT; i++)
response.PCLoadData2CL.aQInven[i] = plr.QInven[i];
// nanos
for (int i = 1; i < SIZEOF_NANO_BANK_SLOT; i++) {
response.PCLoadData2CL.aNanoBank[i] = plr.Nanos[i];
//response.PCLoadData2CL.aNanoBank[i] = plr.Nanos[i] = {0};
}
for (int i = 0; i < 3; i++) {
response.PCLoadData2CL.aNanoSlots[i] = plr.equippedNanos[i];
}
// missions in progress
for (int i = 0; i < ACTIVE_MISSION_COUNT; i++) {
if (plr.tasks[i] == 0)
break;
response.PCLoadData2CL.aRunningQuest[i].m_aCurrTaskID = plr.tasks[i];
TaskData &task = *Missions::Tasks[plr.tasks[i]];
for (int j = 0; j < 3; j++) {
response.PCLoadData2CL.aRunningQuest[i].m_aKillNPCID[j] = (int)task["m_iCSUEnemyID"][j];
response.PCLoadData2CL.aRunningQuest[i].m_aKillNPCCount[j] = plr.RemainingNPCCount[i][j];
/*
* client doesn't care about NeededItem ID and Count,
* it gets Count from Quest Inventory
*
* KillNPCCount sets RemainEnemyNum in the client
* Yes, this is extraordinary stupid.
*/
}
}
response.PCLoadData2CL.iCurrentMissionID = plr.CurrentMissionID;
// completed missions
// the packet requires 32 items, but the client only checks the first 16 (shrug)
for (int i = 0; i < 16; i++) {
response.PCLoadData2CL.aQuestFlag[i] = plr.aQuestFlag[i];
}
// Computress tips
if (settings::DISABLEFIRSTUSEFLAG) {
response.PCLoadData2CL.iFirstUseFlag1 = UINT64_MAX;
response.PCLoadData2CL.iFirstUseFlag2 = UINT64_MAX;
}
else {
response.PCLoadData2CL.iFirstUseFlag1 = plr.iFirstUseFlag[0];
response.PCLoadData2CL.iFirstUseFlag2 = plr.iFirstUseFlag[1];
}
plr.SerialKey = enter->iEnterSerialKey;
plr.instanceID = INSTANCE_OVERWORLD; // the player should never be in an instance on enter
sock->setEKey(CNSocketEncryption::createNewKey(response.uiSvrTime, response.iID + 1, response.PCLoadData2CL.iFusionMatter + 1));
sock->setFEKey(plr.FEKey);
sock->setActiveKey(SOCKETKEY_FE); // send all packets using the FE key from now on
sock->sendPacket(response, P_FE2CL_REP_PC_ENTER_SUCC);
// transmit MOTD after entering the game, so the client hopefully changes modes on time
Chat::sendServerMessage(sock, settings::MOTDSTRING);
addPlayer(sock, plr);
// check if there is an expiring vehicle
Items::checkItemExpire(sock, getPlayer(sock));
// set player equip stats
Items::setItemStats(getPlayer(sock));
Missions::failInstancedMissions(sock);
sendNanoBookSubset(sock);
// initial buddy sync
Buddies::refreshBuddyList(sock);
for (auto& pair : players)
if (pair.second->notify)
Chat::sendServerMessage(pair.first, "[ADMIN]" + getPlayerName(&plr) + " has joined.");
}
void PlayerManager::sendToViewable(CNSocket* sock, void* buf, uint32_t type, size_t size) {
Player* plr = getPlayer(sock);
for (auto it = plr->viewableChunks.begin(); it != plr->viewableChunks.end(); it++) {
Chunk* chunk = *it;
for (const EntityRef& ref : chunk->entities) {
if (ref.type != EntityType::PLAYER || ref.sock == sock)
continue;
ref.sock->sendPacket(buf, type, size);
}
}
}
static void loadPlayer(CNSocket* sock, CNPacketData* data) {
sP_CL2FE_REQ_PC_LOADING_COMPLETE* complete = (sP_CL2FE_REQ_PC_LOADING_COMPLETE*)data->buf;
INITSTRUCT(sP_FE2CL_REP_PC_LOADING_COMPLETE_SUCC, response);
Player *plr = getPlayer(sock);
DEBUGLOG(
std::cout << "P_CL2FE_REQ_PC_LOADING_COMPLETE:" << std::endl;
std::cout << "\tPC_ID: " << complete->iPC_ID << std::endl;
)
response.iPC_ID = complete->iPC_ID;
updatePlayerPosition(sock, plr->x, plr->y, plr->z, plr->instanceID, plr->angle);
sock->sendPacket(response, P_FE2CL_REP_PC_LOADING_COMPLETE_SUCC);
}
static void heartbeatPlayer(CNSocket* sock, CNPacketData* data) {
getPlayer(sock)->lastHeartbeat = getTime();
}
static void exitGame(CNSocket* sock, CNPacketData* data) {
auto exitData = (sP_CL2FE_REQ_PC_EXIT*)data->buf;
INITSTRUCT(sP_FE2CL_REP_PC_EXIT_SUCC, response);
response.iID = exitData->iID;
response.iExitCode = 1;
sock->sendPacket(response, P_FE2CL_REP_PC_EXIT_SUCC);
}
static void revivePlayer(CNSocket* sock, CNPacketData* data) {
Player *plr = getPlayer(sock);
WarpLocation* target = getRespawnPoint(plr);
auto reviveData = (sP_CL2FE_REQ_PC_REGEN*)data->buf;
INITSTRUCT(sP_FE2CL_REP_PC_REGEN_SUCC, response);
INITSTRUCT(sP_FE2CL_PC_REGEN, resp2);
int activeSlot = -1;
bool move = false;
if (reviveData->iRegenType == 3 && plr->iConditionBitFlag & CSB_BIT_PHOENIX) {
// nano revive
plr->Nanos[plr->activeNano].iStamina = 0;
plr->HP = PC_MAXHEALTH(plr->level);
Nanos::applyBuff(sock, plr->Nanos[plr->activeNano].iSkillID, 2, 1, 0);
} else if (reviveData->iRegenType == 4) {
plr->HP = PC_MAXHEALTH(plr->level);
} else {
move = true;
if (reviveData->iRegenType != 5)
plr->HP = PC_MAXHEALTH(plr->level);
}
for (int i = 0; i < 3; i++) {
int nanoID = plr->equippedNanos[i];
// halve nano health if respawning
// all revives not 3-5 are normal respawns.
if (reviveData->iRegenType < 3 || reviveData->iRegenType > 5)
plr->Nanos[nanoID].iStamina = 75; // max is 150, so 75 is half
response.PCRegenData.Nanos[i] = plr->Nanos[nanoID];
if (plr->activeNano == nanoID)
activeSlot = i;
}
int x, y, z;
if (move && target != nullptr) {
// go to Resurrect 'Em
x = target->x;
y = target->y;
z = target->z;
} else if (PLAYERID(plr->instanceID)) {
// respawn at entrance to the Lair
x = plr->recallX;
y = plr->recallY;
z = plr->recallZ;
} else {
// no other choice; respawn in place
x = plr->x;
y = plr->y;
z = plr->z;
}
// Response parameters
response.PCRegenData.iActiveNanoSlotNum = activeSlot;
response.PCRegenData.iX = x;
response.PCRegenData.iY = y;
response.PCRegenData.iZ = z;
response.PCRegenData.iHP = plr->HP;
response.iFusionMatter = plr->fusionmatter;
response.bMoveLocation = 0;
response.PCRegenData.iMapNum = MAPNUM(plr->instanceID);
sock->sendPacket(response, P_FE2CL_REP_PC_REGEN_SUCC);
// Update other players
resp2.PCRegenDataForOtherPC.iPC_ID = plr->iID;
resp2.PCRegenDataForOtherPC.iX = x;
resp2.PCRegenDataForOtherPC.iY = y;
resp2.PCRegenDataForOtherPC.iZ = z;
resp2.PCRegenDataForOtherPC.iHP = plr->HP;
resp2.PCRegenDataForOtherPC.iAngle = plr->angle;
Player *otherPlr = getPlayerFromID(plr->iIDGroup);
if (otherPlr != nullptr) {
int bitFlag = Groups::getGroupFlags(otherPlr);
resp2.PCRegenDataForOtherPC.iConditionBitFlag = plr->iConditionBitFlag = plr->iSelfConditionBitFlag | bitFlag;
resp2.PCRegenDataForOtherPC.iPCState = plr->iPCState;
resp2.PCRegenDataForOtherPC.iSpecialState = plr->iSpecialState;
resp2.PCRegenDataForOtherPC.Nano = plr->Nanos[plr->activeNano];
sendToViewable(sock, resp2, P_FE2CL_PC_REGEN);
}
if (!move)
return;
Chunking::updateEntityChunk({sock}, plr->chunkPos, std::make_tuple(0, 0, 0)); // force player to reload chunks
updatePlayerPosition(sock, x, y, z, plr->instanceID, plr->angle);
}
static void enterPlayerVehicle(CNSocket* sock, CNPacketData* data) {
Player* plr = getPlayer(sock);
// vehicles are only allowed in the overworld
if (plr->instanceID != 0)
return;
bool expired = plr->Equip[8].iTimeLimit < getTimestamp() && plr->Equip[8].iTimeLimit != 0;
if (plr->Equip[8].iID > 0 && !expired) {
INITSTRUCT(sP_FE2CL_PC_VEHICLE_ON_SUCC, response);
sock->sendPacket(response, P_FE2CL_PC_VEHICLE_ON_SUCC);
// send to other players
plr->iPCState |= 8;
INITSTRUCT(sP_FE2CL_PC_STATE_CHANGE, response2);
response2.iPC_ID = plr->iID;
response2.iState = plr->iPCState;
sendToViewable(sock, response2, P_FE2CL_PC_STATE_CHANGE);
} else {
INITSTRUCT(sP_FE2CL_PC_VEHICLE_ON_FAIL, response);
sock->sendPacket(response, P_FE2CL_PC_VEHICLE_ON_FAIL);
// check if vehicle didn't expire
if (expired) {
plr->toRemoveVehicle.eIL = 0;
plr->toRemoveVehicle.iSlotNum = 8;
Items::checkItemExpire(sock, plr);
}
}
}
static void exitPlayerVehicle(CNSocket* sock, CNPacketData* data) {
Player* plr = getPlayer(sock);
if (plr->iPCState & 8) {
INITSTRUCT(sP_FE2CL_PC_VEHICLE_OFF_SUCC, response);
sock->sendPacket(response, P_FE2CL_PC_VEHICLE_OFF_SUCC);
// send to other players
plr->iPCState &= ~8;
INITSTRUCT(sP_FE2CL_PC_STATE_CHANGE, response2);
response2.iPC_ID = plr->iID;
response2.iState = plr->iPCState;
sendToViewable(sock, response2, P_FE2CL_PC_STATE_CHANGE);
}
}
static void setSpecialSwitchPlayer(CNSocket* sock, CNPacketData* data) {
BuiltinCommands::setSpecialState(sock, data);
}
static void changePlayerGuide(CNSocket *sock, CNPacketData *data) {
auto pkt = (sP_CL2FE_REQ_PC_CHANGE_MENTOR*)data->buf;
INITSTRUCT(sP_FE2CL_REP_PC_CHANGE_MENTOR_SUCC, resp);
Player *plr = getPlayer(sock);
resp.iMentor = pkt->iMentor;
resp.iMentorCnt = 1;
resp.iFusionMatter = plr->fusionmatter; // no cost
sock->sendPacket(resp, P_FE2CL_REP_PC_CHANGE_MENTOR_SUCC);
// if it's changed from computress
if (plr->mentor == 5) {
// we're warping to the past
plr->PCStyle2.iPayzoneFlag = 1;
// remove all active missions
for (int i = 0; i < ACTIVE_MISSION_COUNT; i++) {
if (plr->tasks[i] != 0)
Missions::quitTask(sock, plr->tasks[i], true);
}
// start Blossom nano mission if applicable
Missions::updateFusionMatter(sock, 0);
}
// save it on player
plr->mentor = pkt->iMentor;
}
static void setFirstUseFlag(CNSocket* sock, CNPacketData* data) {
auto flag = (sP_CL2FE_REQ_PC_FIRST_USE_FLAG_SET*)data->buf;
Player* plr = getPlayer(sock);
if (flag->iFlagCode < 1 || flag->iFlagCode > 128) {
std::cout << "[WARN] Client submitted invalid first use flag number?!" << std::endl;
return;
}
if (flag->iFlagCode <= 64)
plr->iFirstUseFlag[0] |= (1ULL << (flag->iFlagCode - 1));
else
plr->iFirstUseFlag[1] |= (1ULL << (flag->iFlagCode - 65));
}
#pragma region Helper methods
Player *PlayerManager::getPlayer(CNSocket* key) {
if (players.find(key) != players.end())
return players[key];
// this should never happen
assert(false);
}
std::string PlayerManager::getPlayerName(Player *plr, bool id) {
// the print in CNShardServer can print packets from players that haven't yet joined
if (plr == nullptr)
return "NOT IN GAME";
std::string ret = "";
if (id && plr->accountLevel <= 30)
ret += "(GM) ";
ret += AUTOU16TOU8(plr->PCStyle.szFirstName) + " " + AUTOU16TOU8(plr->PCStyle.szLastName);
if (id)
ret += " [" + std::to_string(plr->iID) + "]";
return ret;
}
bool PlayerManager::isAccountInUse(int accountId) {
std::map<CNSocket*, Player*>::iterator it;
for (it = players.begin(); it != players.end(); it++) {
if (it->second->accountId == accountId)
return true;
}
return false;
}
void PlayerManager::exitDuplicate(int accountId) {
std::map<CNSocket*, Player*>::iterator it;
// disconnect any duplicate players
for (it = players.begin(); it != players.end(); it++) {
if (it->second->accountId == accountId) {
CNSocket* sock = it->first;
INITSTRUCT(sP_FE2CL_REP_PC_EXIT_DUPLICATE, resp);
resp.iErrorCode = 0;
sock->sendPacket(resp, P_FE2CL_REP_PC_EXIT_DUPLICATE);
sock->kill();
CNShardServer::_killConnection(sock);
break;
}
}
}
// TODO: just call getPlayer() after getSockFromID()?
Player *PlayerManager::getPlayerFromID(int32_t iID) {
for (auto& pair : players)
if (pair.second->iID == iID)
return pair.second;
return nullptr;
}
CNSocket *PlayerManager::getSockFromID(int32_t iID) {
for (auto& pair : players)
if (pair.second->iID == iID)
return pair.first;
return nullptr;
}
CNSocket *PlayerManager::getSockFromName(std::string firstname, std::string lastname) {
for (auto& pair : players)
if (AUTOU16TOU8(pair.second->PCStyle.szFirstName) == firstname
&& AUTOU16TOU8(pair.second->PCStyle.szLastName) == lastname)
return pair.first;
return nullptr;
}
CNSocket *PlayerManager::getSockFromAny(int by, int id, int uid, std::string firstname, std::string lastname) {
switch (by) {
case eCN_GM_TargetSearchBy__PC_ID:
assert(id != 0);
return getSockFromID(id);
case eCN_GM_TargetSearchBy__PC_UID: // account id; not player id
assert(uid != 0);
for (auto& pair : players)
if (pair.second->accountId == uid)
return pair.first;
case eCN_GM_TargetSearchBy__PC_Name:
assert(firstname != "" && lastname != ""); // XXX: remove this if we start messing around with edited names?
return getSockFromName(firstname, lastname);
}
// not found
return nullptr;
}
WarpLocation *PlayerManager::getRespawnPoint(Player *plr) {
WarpLocation* best = nullptr;
uint32_t curDist, bestDist = UINT32_MAX;
for (auto& targ : NPCManager::RespawnPoints) {
curDist = sqrt(pow(plr->x - targ.x, 2) + pow(plr->y - targ.y, 2));
if (curDist < bestDist && targ.instanceID == MAPNUM(plr->instanceID)) { // only mapNum needs to match
best = &targ;
bestDist = curDist;
}
}
return best;
}
#pragma endregion
void PlayerManager::init() {
// register packet types
REGISTER_SHARD_PACKET(P_CL2FE_REQ_PC_ENTER, enterPlayer);
REGISTER_SHARD_PACKET(P_CL2FE_REQ_PC_LOADING_COMPLETE, loadPlayer);
REGISTER_SHARD_PACKET(P_CL2FE_REP_LIVE_CHECK, heartbeatPlayer);
REGISTER_SHARD_PACKET(P_CL2FE_REQ_PC_REGEN, revivePlayer);
REGISTER_SHARD_PACKET(P_CL2FE_REQ_PC_EXIT, exitGame);
REGISTER_SHARD_PACKET(P_CL2FE_REQ_PC_SPECIAL_STATE_SWITCH, setSpecialSwitchPlayer);
REGISTER_SHARD_PACKET(P_CL2FE_REQ_PC_VEHICLE_ON, enterPlayerVehicle);
REGISTER_SHARD_PACKET(P_CL2FE_REQ_PC_VEHICLE_OFF, exitPlayerVehicle);
REGISTER_SHARD_PACKET(P_CL2FE_REQ_PC_CHANGE_MENTOR, changePlayerGuide);
REGISTER_SHARD_PACKET(P_CL2FE_REQ_PC_FIRST_USE_FLAG_SET, setFirstUseFlag);
}
| 34.295224 | 132 | 0.651236 | [
"object",
"vector"
] |
c81e4b89048e59f04ca3c57a7c22bafcd5ccc800 | 30,127 | cpp | C++ | src/EvtGenModels/EvtbTosllMSFF.cpp | qdcampagna/BTODSTARLNUNP_EVTGEN_Model | 9623a0ffe2625450a1228a80d6baae74ed6c0965 | [
"CC0-1.0"
] | null | null | null | src/EvtGenModels/EvtbTosllMSFF.cpp | qdcampagna/BTODSTARLNUNP_EVTGEN_Model | 9623a0ffe2625450a1228a80d6baae74ed6c0965 | [
"CC0-1.0"
] | null | null | null | src/EvtGenModels/EvtbTosllMSFF.cpp | qdcampagna/BTODSTARLNUNP_EVTGEN_Model | 9623a0ffe2625450a1228a80d6baae74ed6c0965 | [
"CC0-1.0"
] | null | null | null |
/***********************************************************************
* Copyright 1998-2020 CERN for the benefit of the EvtGen authors *
* *
* This file is part of EvtGen. *
* *
* EvtGen is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* EvtGen is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with EvtGen. If not, see <https://www.gnu.org/licenses/>. *
***********************************************************************/
#include "EvtGenModels/EvtbTosllMSFF.hh"
#include "EvtGenBase/EvtComplex.hh"
#include "EvtGenBase/EvtPDL.hh"
#include "EvtGenBase/EvtPatches.hh"
#include "EvtGenBase/EvtReport.hh"
#include <cmath>
#include <cstdlib>
EvtbTosllMSFF::EvtbTosllMSFF()
{
}
double EvtbTosllMSFF::equation9_10( double ff0, double M2, double q2,
double sigma1, double sigma2, int eq_num )
{
double ff = 1.0;
switch ( eq_num ) {
case 9:
ff = 1. / ( 1. - q2 / M2 );
[[fallthrough]];
case 10:
ff = ff * ff0 /
( 1. - sigma1 * q2 / M2 + sigma2 * pow( q2, 2 ) / pow( M2, 2 ) );
break;
default:
EvtGenReport( EVTGEN_ERROR, "EvtGen" )
<< "In the function EvtbTosllMSFF::equation9_10 \n"
<< "the parameter eq_num non equal to the 9 or 10! \n"
<< "eq_num =" << eq_num << std::endl;
::abort();
}
return ff;
}
void EvtbTosllMSFF::getScalarFF( EvtId parent, EvtId daught, double t,
double& fp, double& f0, double& ft )
{
int models_counter = 0; // counter of the accepted models
// B -> K transition form factors
if ( ( parent == EvtPDL::getId( std::string( "B+" ) ) &&
daught == EvtPDL::getId( std::string( "K+" ) ) ) ||
( parent == EvtPDL::getId( std::string( "B-" ) ) &&
daught == EvtPDL::getId( std::string( "K-" ) ) ) ||
( parent == EvtPDL::getId( std::string( "B0" ) ) &&
daught == EvtPDL::getId( std::string( "K0" ) ) ) ||
( parent == EvtPDL::getId( std::string( "anti-B0" ) ) &&
daught == EvtPDL::getId( std::string( "anti-K0" ) ) ) ||
( parent == EvtPDL::getId( std::string( "B0" ) ) &&
daught == EvtPDL::getId( std::string( "K_S0" ) ) ) ||
( parent == EvtPDL::getId( std::string( "anti-B0" ) ) &&
daught == EvtPDL::getId( std::string( "K_S0" ) ) ) ||
( parent == EvtPDL::getId( std::string( "B0" ) ) &&
daught == EvtPDL::getId( std::string( "K_L0" ) ) ) ||
( parent == EvtPDL::getId( std::string( "anti-B0" ) ) &&
daught == EvtPDL::getId( std::string( "K_L0" ) ) ) ) {
double ff0[] = {0.36, 0.36, 0.35};
double sigma1[] = {0.43, 0.70, 0.43};
double sigma2[] = {0.00, 0.27, 0.00};
int eq_num[] = {9, 10, 9};
double M_P2 = 5.37 * 5.37; // GeV^2 for B^0_s - meson
double M_V2 = 5.42 * 5.42; // GeV^2 for B^*_s - meson
fp = equation9_10( ff0[0], M_P2, t, sigma1[0], sigma2[0], eq_num[0] );
f0 = equation9_10( ff0[1], M_V2, t, sigma1[1], sigma2[1], eq_num[1] );
ft = equation9_10( ff0[2], M_P2, t, sigma1[2], sigma2[2], eq_num[2] );
models_counter = models_counter + 1;
// EvtGenReport(EVTGEN_NOTICE,"EvtGen") <<"\n The function EvtbTosllMSFF::getVectorFF(...) passed."
// << "\n B -> K transition form factors"
// << std::endl;
}
// B -> \pi transition form factors
if ( ( parent == EvtPDL::getId( std::string( "B+" ) ) &&
daught == EvtPDL::getId( std::string( "pi+" ) ) ) ||
( parent == EvtPDL::getId( std::string( "B-" ) ) &&
daught == EvtPDL::getId( std::string( "pi-" ) ) ) ||
( parent == EvtPDL::getId( std::string( "B0" ) ) &&
daught == EvtPDL::getId( std::string( "pi0" ) ) ) ||
( parent == EvtPDL::getId( std::string( "anti-B0" ) ) &&
daught == EvtPDL::getId( std::string( "pi0" ) ) ) ) {
double ff0[] = {0.29, 0.29, 0.28};
double sigma1[] = {0.48, 0.76, 0.48};
double sigma2[] = {0.00, 0.28, 0.00};
int eq_num[] = {9, 10, 9};
double M_P2 = 5.27 * 5.27; // GeV^2 for B^0 - meson
double M_V2 = 5.32 * 5.32; // GeV^2 for B^* - meson
fp = equation9_10( ff0[0], M_P2, t, sigma1[0], sigma2[0], eq_num[0] );
f0 = equation9_10( ff0[1], M_V2, t, sigma1[1], sigma2[1], eq_num[1] );
ft = equation9_10( ff0[2], M_P2, t, sigma1[2], sigma2[2], eq_num[2] );
models_counter = models_counter + 1;
// EvtGenReport(EVTGEN_NOTICE,"EvtGen") <<"\n The function EvtbTosllMSFF::getVectorFF(...) passed."
// << "\n B -> pi transition form factors"
// << std::endl;
}
// B_d -> \eta transition form factors
if ( ( parent == EvtPDL::getId( std::string( "B0" ) ) &&
daught == EvtPDL::getId( std::string( "eta" ) ) ) ||
( parent == EvtPDL::getId( std::string( "anti-B0" ) ) &&
daught == EvtPDL::getId( std::string( "eta" ) ) ) ) {
double ff0[] = {0.36, 0.36, 0.36};
double sigma1[] = {0.60, 0.80, 0.58};
double sigma2[] = {0.20, 0.40, 0.18};
int eq_num[] = {9, 10, 9};
double M_P2 = 5.27 * 5.27; // GeV^2 for B_d^0 - meson
double M_V2 = 5.32 * 5.32; // GeV^2 for B_d^* - meson
fp = equation9_10( ff0[0], M_P2, t, sigma1[0], sigma2[0], eq_num[0] );
fp = -0.5 * fp;
f0 = equation9_10( ff0[1], M_V2, t, sigma1[1], sigma2[1], eq_num[1] );
f0 = -0.5 * f0;
ft = equation9_10( ff0[2], M_P2, t, sigma1[2], sigma2[2], eq_num[2] );
ft = -0.5 * ft;
models_counter = models_counter + 1;
// EvtGenReport(EVTGEN_NOTICE,"EvtGen") <<"\n The function EvtbTosllMSFF::getVectorFF(...) passed."
// << "\n Bd -> eta transition form factors"
// << std::endl;
}
// B_d -> \eta' transition form factors
if ( ( parent == EvtPDL::getId( std::string( "B0" ) ) &&
daught == EvtPDL::getId( std::string( "eta'" ) ) ) ||
( parent == EvtPDL::getId( std::string( "anti-B0" ) ) &&
daught == EvtPDL::getId( std::string( "eta'" ) ) ) ) {
double ff0[] = {0.36, 0.36, 0.39};
double sigma1[] = {0.60, 0.80, 0.58};
double sigma2[] = {0.20, 0.45, 0.18};
int eq_num[] = {9, 10, 9};
double M_P2 = 5.27 * 5.27; // GeV^2 for B_d^0 - meson
double M_V2 = 5.32 * 5.32; // GeV^2 for B_d^* - meson
fp = equation9_10( ff0[0], M_P2, t, sigma1[0], sigma2[0], eq_num[0] );
f0 = equation9_10( ff0[1], M_V2, t, sigma1[1], sigma2[1], eq_num[1] );
ft = equation9_10( ff0[2], M_P2, t, sigma1[2], sigma2[2], eq_num[2] );
models_counter = models_counter + 1;
// EvtGenReport(EVTGEN_NOTICE,"EvtGen") <<"\n The function EvtbTosllMSFF::getVectorFF(...) passed."
// << "\n Bd -> eta transition form factors"
// << std::endl;
}
// B_s -> \eta transition form factors
if ( ( parent == EvtPDL::getId( std::string( "B_s0" ) ) &&
daught == EvtPDL::getId( std::string( "eta" ) ) ) ||
( parent == EvtPDL::getId( std::string( "anti-B_s0" ) ) &&
daught == EvtPDL::getId( std::string( "eta" ) ) ) ) {
double ff0[] = {0.36, 0.36, 0.36};
double sigma1[] = {0.60, 0.80, 0.58};
double sigma2[] = {0.20, 0.40, 0.18};
int eq_num[] = {9, 10, 9};
double M_P2 = 5.37 * 5.37; // GeV^2 for B_s^0 - meson
double M_V2 = 5.42 * 5.42; // GeV^2 for B_s^* - meson
fp = equation9_10( ff0[0], M_P2, t, sigma1[0], sigma2[0], eq_num[0] );
f0 = equation9_10( ff0[1], M_V2, t, sigma1[1], sigma2[1], eq_num[1] );
ft = equation9_10( ff0[2], M_P2, t, sigma1[2], sigma2[2], eq_num[2] );
models_counter = models_counter + 1;
// EvtGenReport(EVTGEN_NOTICE,"EvtGen") <<"\n The function EvtbTosllMSFF::getVectorFF(...) passed."
// << "\n Bs -> eta transition form factors"
// << std::endl;
}
// B_s -> \eta' transition form factors
if ( ( parent == EvtPDL::getId( std::string( "B_s0" ) ) &&
daught == EvtPDL::getId( std::string( "eta'" ) ) ) ||
( parent == EvtPDL::getId( std::string( "anti-B_s0" ) ) &&
daught == EvtPDL::getId( std::string( "eta'" ) ) ) ) {
double ff0[] = {0.36, 0.36, 0.39};
double sigma1[] = {0.60, 0.80, 0.58};
double sigma2[] = {0.20, 0.45, 0.18};
int eq_num[] = {9, 10, 9};
double M_P2 = 5.37 * 5.37; // GeV^2 for B_s^0 - meson
double M_V2 = 5.42 * 5.42; // GeV^2 for B_s^* - meson
fp = equation9_10( ff0[0], M_P2, t, sigma1[0], sigma2[0], eq_num[0] );
f0 = equation9_10( ff0[1], M_V2, t, sigma1[1], sigma2[1], eq_num[1] );
ft = equation9_10( ff0[2], M_P2, t, sigma1[2], sigma2[2], eq_num[2] );
models_counter = models_counter + 1;
// EvtGenReport(EVTGEN_NOTICE,"EvtGen") <<"\n The function EvtbTosllMSFF::getVectorFF(...) passed."
// << "\n Bs -> eta transition form factors"
// << std::endl;
}
// B_s -> f_0(980) transition form factors
if ( ( parent == EvtPDL::getId( std::string( "B_s0" ) ) &&
daught == EvtPDL::getId( std::string( "f_0" ) ) ) ||
( parent == EvtPDL::getId( std::string( "anti-B_s0" ) ) &&
daught == EvtPDL::getId( std::string( "f_0" ) ) ) ) {
double ff0[] = {0.238, 0.238, 0.308};
double sigma1[] = {1.50, 0.53, 1.46};
double sigma2[] = {0.58, -0.36, 0.58};
int eq_num[] = {10, 10, 10};
double M_P2 = 5.366 * 5.366; // GeV^2 for B_s^0 - meson
fp = 0.0 -
equation9_10( ff0[0], M_P2, t, sigma1[0], sigma2[0], eq_num[0] );
f0 = 0.0 -
equation9_10( ff0[1], M_P2, t, sigma1[1], sigma2[1], eq_num[1] );
ft = equation9_10( ff0[2], M_P2, t, sigma1[2], sigma2[2], eq_num[2] );
models_counter = models_counter + 1;
// EvtGenReport(EVTGEN_NOTICE,"EvtGen") <<"\n The function EvtbTosllMSFF::getVectorFF(...) passed."
// << "\n Bs -> eta transition form factors"
// << std::endl;
}
// EvtGenReport(EVTGEN_NOTICE,"EvtGen") << "\n models_counter = " << models_counter
// << "\n Scalar form-factors at q^2 = " << t
// << " for B -> P transition:"
// << "\n fp = " << fp
// << "\n f0 = " << f0
// << "\n ft = " << ft << std::endl;
if ( models_counter != 1 ) {
EvtGenReport( EVTGEN_ERROR, "EvtGen" )
<< "\n In the function EvtbTosllMSFF::getScalarFF(...) \n"
<< "the parameter models_counter not equal 1! \n"
<< "models_counter = " << models_counter << std::endl;
::abort();
}
}
void EvtbTosllMSFF::getVectorFF( EvtId parent, EvtId daught, double t,
double& a1, double& a2, double& a0, double& v,
double& t1, double& t2, double& t3 )
{
int models_counter = 0; // counter of the accepted models
double thetaK = -34.0 * 3.14159 / 180; // K_1(1270) - K_1(1400) mixing angle
// \bar B -> \bar K* transition form factors
if ( ( parent == EvtPDL::getId( std::string( "B+" ) ) &&
daught == EvtPDL::getId( std::string( "K*+" ) ) ) ||
( parent == EvtPDL::getId( std::string( "B-" ) ) &&
daught == EvtPDL::getId( std::string( "K*-" ) ) ) ||
( parent == EvtPDL::getId( std::string( "B0" ) ) &&
daught == EvtPDL::getId( std::string( "K*0" ) ) ) ||
( parent == EvtPDL::getId( std::string( "anti-B0" ) ) &&
daught == EvtPDL::getId( std::string( "anti-K*0" ) ) ) ) {
double ff0[] = {0.44, 0.45, 0.36, 0.32, 0.39, 0.39, 0.27};
double sigma1[] = {0.45, 0.46, 0.64, 1.23, 0.45, 0.72, 1.31};
double sigma2[] = {0.00, 0.00, 0.36, 0.38, 0.00, 0.62, 0.41};
int eq_num[] = {9, 9, 10, 10, 9, 10, 10};
double M_P2 = 5.37 * 5.37; // GeV^2 for B^0_s - meson
double M_V2 = 5.42 * 5.42; // GeV^2 for B^*_s - meson
v = equation9_10( ff0[0], M_P2, t, sigma1[0], sigma2[0], eq_num[0] );
a0 = equation9_10( ff0[1], M_P2, t, sigma1[1], sigma2[1], eq_num[1] );
a1 = equation9_10( ff0[2], M_V2, t, sigma1[2], sigma2[2], eq_num[2] );
a2 = equation9_10( ff0[3], M_V2, t, sigma1[3], sigma2[3], eq_num[3] );
t1 = equation9_10( ff0[4], M_P2, t, sigma1[4], sigma2[4], eq_num[4] );
t2 = equation9_10( ff0[5], M_V2, t, sigma1[5], sigma2[5], eq_num[5] );
t3 = equation9_10( ff0[6], M_V2, t, sigma1[6], sigma2[6], eq_num[6] );
models_counter = models_counter + 1;
// EvtGenReport(EVTGEN_NOTICE,"EvtGen") <<"\n The function EvtbTosllMSFF::getVectorFF(...) passed."
// << "\n barB -> barK* transition form factors"
// << std::endl;
}
// \bar B -> \bar\rho transition form factors
if ( ( parent == EvtPDL::getId( std::string( "B+" ) ) &&
daught == EvtPDL::getId( std::string( "rho+" ) ) ) ||
( parent == EvtPDL::getId( std::string( "B-" ) ) &&
daught == EvtPDL::getId( std::string( "rho-" ) ) ) ||
( parent == EvtPDL::getId( std::string( "B0" ) ) &&
daught == EvtPDL::getId( std::string( "rho0" ) ) ) ||
( parent == EvtPDL::getId( std::string( "anti-B0" ) ) &&
daught == EvtPDL::getId( std::string( "rho0" ) ) ) ) {
double ff0[] = {0.31, 0.30, 0.26, 0.24, 0.27, 0.27, 0.19};
double sigma1[] = {0.59, 0.54, 0.73, 1.40, 0.60, 0.74, 1.42};
double sigma2[] = {0.00, 0.00, 0.10, 0.50, 0.00, 0.19, 0.51};
int eq_num[] = {9, 9, 10, 10, 9, 10, 10};
double M_P2 = 5.27 * 5.27; // GeV^2 for B - meson
double M_V2 = 5.32 * 5.32; // GeV^2 for B^* - meson
v = equation9_10( ff0[0], M_P2, t, sigma1[0], sigma2[0], eq_num[0] );
a0 = equation9_10( ff0[1], M_P2, t, sigma1[1], sigma2[1], eq_num[1] );
a1 = equation9_10( ff0[2], M_V2, t, sigma1[2], sigma2[2], eq_num[2] );
a2 = equation9_10( ff0[3], M_V2, t, sigma1[3], sigma2[3], eq_num[3] );
t1 = equation9_10( ff0[4], M_P2, t, sigma1[4], sigma2[4], eq_num[4] );
t2 = equation9_10( ff0[5], M_V2, t, sigma1[5], sigma2[5], eq_num[5] );
t3 = equation9_10( ff0[6], M_V2, t, sigma1[6], sigma2[6], eq_num[6] );
models_counter = models_counter + 1;
// EvtGenReport(EVTGEN_NOTICE,"EvtGen") <<"\n The function EvtbTosllMSFF::getVectorFF(...) passed."
// << "\n barB -> bar rho transition form factors"
// << std::endl;
}
// \bar B -> \omega transition form factors (exactly as for \bar B -> \rho^0 ff!)
if ( ( parent == EvtPDL::getId( std::string( "B0" ) ) &&
daught == EvtPDL::getId( std::string( "omega" ) ) ) ||
( parent == EvtPDL::getId( std::string( "anti-B0" ) ) &&
daught == EvtPDL::getId( std::string( "omega" ) ) ) ) {
double ff0[] = {0.31, 0.30, 0.26, 0.24, 0.27, 0.27, 0.19};
double sigma1[] = {0.59, 0.54, 0.73, 1.40, 0.60, 0.74, 1.42};
double sigma2[] = {0.00, 0.00, 0.10, 0.50, 0.00, 0.19, 0.51};
int eq_num[] = {9, 9, 10, 10, 9, 10, 10};
double M_P2 = 5.27 * 5.27; // GeV^2 for B - meson
double M_V2 = 5.32 * 5.32; // GeV^2 for B^* - meson
v = equation9_10( ff0[0], M_P2, t, sigma1[0], sigma2[0], eq_num[0] );
a0 = equation9_10( ff0[1], M_P2, t, sigma1[1], sigma2[1], eq_num[1] );
a1 = equation9_10( ff0[2], M_V2, t, sigma1[2], sigma2[2], eq_num[2] );
a2 = equation9_10( ff0[3], M_V2, t, sigma1[3], sigma2[3], eq_num[3] );
t1 = equation9_10( ff0[4], M_P2, t, sigma1[4], sigma2[4], eq_num[4] );
t2 = equation9_10( ff0[5], M_V2, t, sigma1[5], sigma2[5], eq_num[5] );
t3 = equation9_10( ff0[6], M_V2, t, sigma1[6], sigma2[6], eq_num[6] );
models_counter = models_counter + 1;
// EvtGenReport(EVTGEN_NOTICE,"EvtGen") <<"\n The function EvtbTosllMSFF::getVectorFF(...) passed."
// << "\n barB -> omega transition form factors"
// << std::endl;
}
// \bar Bs -> phi transition form factors
if ( ( parent == EvtPDL::getId( std::string( "B_s0" ) ) &&
daught == EvtPDL::getId( std::string( "phi" ) ) ) ||
( parent == EvtPDL::getId( std::string( "anti-B_s0" ) ) &&
daught == EvtPDL::getId( std::string( "phi" ) ) ) ) {
double ff0[] = {0.44, 0.42, 0.34, 0.31, 0.38, 0.38, 0.26};
double sigma1[] = {0.62, 0.55, 0.73, 1.30, 0.62, 0.83, 1.41};
double sigma2[] = {0.20, 0.12, 0.42, 0.52, 0.20, 0.71, 0.57};
int eq_num[] = {9, 9, 10, 10, 9, 10, 10};
double M_P2 = 5.37 * 5.37; // GeV^2 for B^0_s - meson
double M_V2 = 5.42 * 5.42; // GeV^2 for B^*_s - meson
v = equation9_10( ff0[0], M_P2, t, sigma1[0], sigma2[0], eq_num[0] );
a0 = equation9_10( ff0[1], M_P2, t, sigma1[1], sigma2[1], eq_num[1] );
a1 = equation9_10( ff0[2], M_V2, t, sigma1[2], sigma2[2], eq_num[2] );
a2 = equation9_10( ff0[3], M_V2, t, sigma1[3], sigma2[3], eq_num[3] );
t1 = equation9_10( ff0[4], M_P2, t, sigma1[4], sigma2[4], eq_num[4] );
t2 = equation9_10( ff0[5], M_V2, t, sigma1[5], sigma2[5], eq_num[5] );
t3 = equation9_10( ff0[6], M_V2, t, sigma1[6], sigma2[6], eq_num[6] );
models_counter = models_counter + 1;
// EvtGenReport(EVTGEN_NOTICE,"EvtGen") <<"\n The function EvtbTosllMSFF::getVectorFF(...) passed."
// << "\n barBs -> phi transition form factors"
// << std::endl;
}
// \bar Bs -> K* (without \bar !) transition form factors
if ( ( parent == EvtPDL::getId( std::string( "B_s0" ) ) &&
daught == EvtPDL::getId( std::string( "anti-K*0" ) ) ) ||
( parent == EvtPDL::getId( std::string( "anti-B_s0" ) ) &&
daught == EvtPDL::getId( std::string( "K*0" ) ) ) ) {
double ff0[] = {0.38, 0.37, 0.29, 0.26, 0.32, 0.32, 0.23};
double sigma1[] = {0.66, 0.60, 0.86, 1.32, 0.66, 0.98, 1.42};
double sigma2[] = {0.30, 0.16, 0.60, 0.54, 0.31, 0.90, 0.62};
int eq_num[] = {9, 9, 10, 10, 9, 10, 10};
double M_P2 = 5.27 * 5.27; // GeV^2 for B - meson
double M_V2 = 5.32 * 5.32; // GeV^2 for B^* - meson
v = equation9_10( ff0[0], M_P2, t, sigma1[0], sigma2[0], eq_num[0] );
a0 = equation9_10( ff0[1], M_P2, t, sigma1[1], sigma2[1], eq_num[1] );
a1 = equation9_10( ff0[2], M_V2, t, sigma1[2], sigma2[2], eq_num[2] );
a2 = equation9_10( ff0[3], M_V2, t, sigma1[3], sigma2[3], eq_num[3] );
t1 = equation9_10( ff0[4], M_P2, t, sigma1[4], sigma2[4], eq_num[4] );
t2 = equation9_10( ff0[5], M_V2, t, sigma1[5], sigma2[5], eq_num[5] );
t3 = equation9_10( ff0[6], M_V2, t, sigma1[6], sigma2[6], eq_num[6] );
models_counter = models_counter + 1;
// EvtGenReport(EVTGEN_NOTICE,"EvtGen") <<"\n The function EvtbTosllMSFF::getVectorFF(...) passed."
// << "\n barBs -> K* transition form factors"
// << std::endl;
}
// \bar B -> \bar K_1(1270) transition form factors
// See the paper: H.Hatanaka and Kwei-Chou Yang, PRD78, 074007 (2008)
if ( ( parent == EvtPDL::getId( std::string( "B+" ) ) &&
daught == EvtPDL::getId( std::string( "K_1+" ) ) ) ||
( parent == EvtPDL::getId( std::string( "B-" ) ) &&
daught == EvtPDL::getId( std::string( "K_1-" ) ) ) ||
( parent == EvtPDL::getId( std::string( "B0" ) ) &&
daught == EvtPDL::getId( std::string( "K_10" ) ) ) ||
( parent == EvtPDL::getId( std::string( "anti-B0" ) ) &&
daught == EvtPDL::getId( std::string( "anti-K_10" ) ) ) ) {
double ff0A[] = {0.450, 0.340, 0.41, 0.22, 0.31, 0.310, 0.28};
double sigma1A[] = {1.600, 0.635, 1.51, 2.40, 2.01, 0.629, 1.36};
double sigma2A[] = {0.974, 0.211, 1.18, 1.78, 1.50, 0.387, 0.72};
double ff0B[] = {-0.37, -0.29, -0.17, -0.45, -0.25, -0.250, -0.11};
double sigma1B[] = {1.72, 0.729, 0.919, 1.34, 1.59, 0.378, -1.61};
double sigma2B[] = {0.912, 0.074, 0.855, 0.69, 0.79, -0.755, 10.2};
int eq_num[] = {10, 10, 10, 10, 10, 10, 10};
double MM2 = 5.279 * 5.279; // GeV^2
double MB = 5.279; // GeV
double MK1 = 1.272; // GeV
double MK1A = 1.31; // GeV
double MK1B = 1.34; // GeV
double sinK = sin( thetaK ); // sin(-34^o)
double cosK = cos( thetaK ); // cos(-34^o)
double a, v0, v1, v2;
a = sinK *
equation9_10( ff0A[0], MM2, t, sigma1A[0], sigma2A[0], eq_num[0] ) *
( MB + MK1 ) / ( MB + MK1A );
a = a + cosK *
equation9_10( ff0B[0], MM2, t, sigma1B[0], sigma2B[0],
eq_num[0] ) *
( MB + MK1 ) / ( MB + MK1B );
v0 = sinK *
equation9_10( ff0A[1], MM2, t, sigma1A[1], sigma2A[1], eq_num[1] ) *
MK1A / MK1;
v0 = v0 + cosK *
equation9_10( ff0B[1], MM2, t, sigma1B[1], sigma2B[1],
eq_num[1] ) *
MK1B / MK1;
v1 = sinK *
equation9_10( ff0A[2], MM2, t, sigma1A[2], sigma2A[2], eq_num[2] ) *
( MB + MK1A ) / ( MB + MK1 );
v1 = v1 + cosK *
equation9_10( ff0B[2], MM2, t, sigma1B[2], sigma2B[2],
eq_num[2] ) *
( MB + MK1B ) / ( MB + MK1 );
v2 = sinK *
equation9_10( ff0A[3], MM2, t, sigma1A[3], sigma2A[3], eq_num[3] ) *
( MB + MK1 ) / ( MB + MK1A );
v2 = v2 + cosK *
equation9_10( ff0B[3], MM2, t, sigma1B[3], sigma2B[3],
eq_num[3] ) *
( MB + MK1 ) / ( MB + MK1B );
v = a;
a0 = v0;
a1 = v1;
a2 = v2;
t1 = sinK *
equation9_10( ff0A[4], MM2, t, sigma1A[4], sigma2A[4], eq_num[4] );
t1 = t1 + cosK * equation9_10( ff0B[4], MM2, t, sigma1B[4], sigma2B[4],
eq_num[4] );
t2 = sinK *
equation9_10( ff0A[5], MM2, t, sigma1A[5], sigma2A[5], eq_num[5] ) *
( MB * MB - MK1A * MK1A ) / ( MB * MB - MK1 * MK1 );
t2 = t2 + cosK *
equation9_10( ff0B[5], MM2, t, sigma1B[5], sigma2B[5],
eq_num[5] ) *
( MB * MB - MK1B * MK1B ) / ( MB * MB - MK1 * MK1 );
t3 = sinK *
equation9_10( ff0A[6], MM2, t, sigma1A[6], sigma2A[6], eq_num[6] );
t3 = t3 + cosK * equation9_10( ff0B[6], MM2, t, sigma1B[6], sigma2B[6],
eq_num[6] );
models_counter = models_counter + 1;
// EvtGenReport(EVTGEN_NOTICE,"EvtGen") <<"\n The function EvtbTosllMSFF::getVectorFF(...) passed."
// << "\n barB -> bar K_1(1270) transition form factors"
// << std::endl;
}
// \bar B -> \bar K_1(1400) transition form factors
// See the paper: H.Hatanaka and Kwei-Chou Yang, PRD78, 074007 (2008)
if ( ( parent == EvtPDL::getId( std::string( "B+" ) ) &&
daught == EvtPDL::getId( std::string( "K'_1+" ) ) ) ||
( parent == EvtPDL::getId( std::string( "B-" ) ) &&
daught == EvtPDL::getId( std::string( "K'_1-" ) ) ) ||
( parent == EvtPDL::getId( std::string( "B0" ) ) &&
daught == EvtPDL::getId( std::string( "K'_10" ) ) ) ||
( parent == EvtPDL::getId( std::string( "anti-B0" ) ) &&
daught == EvtPDL::getId( std::string( "anti-K'_10" ) ) ) ) {
double ff0A[] = {0.450, 0.340, 0.41, 0.22, 0.31, 0.310, 0.28};
double sigma1A[] = {1.600, 0.635, 1.51, 2.40, 2.01, 0.629, 1.36};
double sigma2A[] = {0.974, 0.211, 1.18, 1.78, 1.50, 0.387, 0.72};
double ff0B[] = {-0.37, -0.29, -0.17, -0.45, -0.25, -0.250, -0.11};
double sigma1B[] = {1.72, 0.729, 0.919, 1.34, 1.59, 0.378, -1.61};
double sigma2B[] = {0.912, 0.074, 0.855, 0.69, 0.79, -0.755, 10.2};
int eq_num[] = {10, 10, 10, 10, 10, 10, 10};
double MM2 = 5.279 * 5.279; // GeV^2
double MB = 5.279; // GeV
double MK1 = 1.403; // GeV
double MK1A = 1.31; // GeV
double MK1B = 1.34; // GeV
double sinK = sin( thetaK ); // sin(-34^o)
double cosK = cos( thetaK ); // cos(-34^o)
double a, v0, v1, v2;
a = cosK *
equation9_10( ff0A[0], MM2, t, sigma1A[0], sigma2A[0], eq_num[0] ) *
( MB + MK1 ) / ( MB + MK1A );
a = a - sinK *
equation9_10( ff0B[0], MM2, t, sigma1B[0], sigma2B[0],
eq_num[0] ) *
( MB + MK1 ) / ( MB + MK1B );
v0 = cosK *
equation9_10( ff0A[1], MM2, t, sigma1A[1], sigma2A[1], eq_num[1] ) *
MK1A / MK1;
v0 = v0 - sinK *
equation9_10( ff0B[1], MM2, t, sigma1B[1], sigma2B[1],
eq_num[1] ) *
MK1B / MK1;
v1 = cosK *
equation9_10( ff0A[2], MM2, t, sigma1A[2], sigma2A[2], eq_num[2] ) *
( MB + MK1A ) / ( MB + MK1 );
v1 = v1 - sinK *
equation9_10( ff0B[2], MM2, t, sigma1B[2], sigma2B[2],
eq_num[2] ) *
( MB + MK1B ) / ( MB + MK1 );
v2 = cosK *
equation9_10( ff0A[3], MM2, t, sigma1A[3], sigma2A[3], eq_num[3] ) *
( MB + MK1 ) / ( MB + MK1A );
v2 = v2 - sinK *
equation9_10( ff0B[3], MM2, t, sigma1B[3], sigma2B[3],
eq_num[3] ) *
( MB + MK1 ) / ( MB + MK1B );
v = a;
a0 = v0;
a1 = v1;
a2 = v2;
t1 = cosK *
equation9_10( ff0A[4], MM2, t, sigma1A[4], sigma2A[4], eq_num[4] );
t1 = t1 - sinK * equation9_10( ff0B[4], MM2, t, sigma1B[4], sigma2B[4],
eq_num[4] );
t2 = cosK *
equation9_10( ff0A[5], MM2, t, sigma1A[5], sigma2A[5], eq_num[5] ) *
( MB * MB - MK1A * MK1A ) / ( MB * MB - MK1 * MK1 );
t2 = t2 - sinK *
equation9_10( ff0B[5], MM2, t, sigma1B[5], sigma2B[5],
eq_num[5] ) *
( MB * MB - MK1B * MK1B ) / ( MB * MB - MK1 * MK1 );
t3 = cosK *
equation9_10( ff0A[6], MM2, t, sigma1A[6], sigma2A[6], eq_num[6] );
t3 = t3 - sinK * equation9_10( ff0B[6], MM2, t, sigma1B[6], sigma2B[6],
eq_num[6] );
models_counter = models_counter + 1;
// EvtGenReport(EVTGEN_NOTICE,"EvtGen") <<"\n The function EvtbTosllMSFF::getVectorFF(...) passed."
// << "\n barB -> bar K_1(1270) transition form factors"
// << std::endl;
}
// EvtGenReport(EVTGEN_NOTICE,"EvtGen") << "\n models_counter = " << models_counter
// << "\n Vector form-factors at q^2 = " << t
// << " for B -> V transition:"
// << "\n v = " << v
// << "\n a0 = " << a0
// << "\n a1 = " << a1
// << "\n a2 = " << a2
// << "\n t1 = " << t1
// << "\n t2 = " << t2
// << "\n t3 = " << t3 << std::endl;
if ( models_counter != 1 ) {
EvtGenReport( EVTGEN_ERROR, "EvtGen" )
<< "\n In the function EvtbTosllMSFF::getVectorFF(...) \n"
<< "the parameter models_counter not equal 1! \n"
<< "models_counter = " << models_counter << std::endl;
::abort();
}
}
// Getting the quark mass (in GeV) using to the dispersion quark model
// of D.Melikhov, B.Stech, PRD62, 014006 (2000).
//
// i=1 => return m_u;
// i=2 => return m_d;
// i=3 => return m_s;
// i=4 => return m_c;
// i=5 => return m_b;
double EvtbTosllMSFF::getQuarkMass( int i )
{
double qm = 0.0;
switch ( i ) {
case 1:
qm = 0.23; // m_u
break;
case 2:
qm = 0.23; // m_d = m_u
break;
case 3:
qm = 0.35; // m_s
break;
case 4:
qm = 1.45; // m_c
break;
case 5:
qm = 4.85; // m_b
break;
default:
EvtGenReport( EVTGEN_ERROR, "EvtGen" )
<< "In the function EvtbTosllMSFF::getQuarkMass \n"
<< "the parameter i not equal 1, 2, 3, 4 or 5! \n"
<< "i =" << i << std::endl;
::abort();
}
return qm;
}
| 45.925305 | 112 | 0.472666 | [
"vector",
"model"
] |
c81ee138432601692aa0fb0c288ea6004b287b29 | 3,724 | cpp | C++ | src/execution/physical_plan/plan_distinct.cpp | frankier/duckdb | 96b83f280db61aeb553d8283c08344e46dacb157 | [
"MIT"
] | null | null | null | src/execution/physical_plan/plan_distinct.cpp | frankier/duckdb | 96b83f280db61aeb553d8283c08344e46dacb157 | [
"MIT"
] | null | null | null | src/execution/physical_plan/plan_distinct.cpp | frankier/duckdb | 96b83f280db61aeb553d8283c08344e46dacb157 | [
"MIT"
] | null | null | null | #include "duckdb/execution/operator/aggregate/physical_hash_aggregate.hpp"
#include "duckdb/execution/operator/projection/physical_projection.hpp"
#include "duckdb/execution/physical_plan_generator.hpp"
#include "duckdb/function/aggregate/distributive_functions.hpp"
#include "duckdb/planner/expression/bound_aggregate_expression.hpp"
#include "duckdb/planner/expression/bound_reference_expression.hpp"
#include "duckdb/planner/operator/logical_distinct.hpp"
namespace duckdb {
unique_ptr<PhysicalOperator> PhysicalPlanGenerator::CreateDistinctOn(unique_ptr<PhysicalOperator> child,
vector<unique_ptr<Expression>> distinct_targets) {
D_ASSERT(child);
D_ASSERT(distinct_targets.size() > 0);
auto &types = child->GetTypes();
vector<unique_ptr<Expression>> groups, aggregates, projections;
idx_t group_count = distinct_targets.size();
unordered_map<idx_t, idx_t> group_by_references;
vector<LogicalType> aggregate_types;
// creates one group per distinct_target
for (idx_t i = 0; i < distinct_targets.size(); i++) {
auto &target = distinct_targets[i];
if (target->type == ExpressionType::BOUND_REF) {
auto &bound_ref = (BoundReferenceExpression &)*target;
group_by_references[bound_ref.index] = i;
}
aggregate_types.push_back(target->return_type);
groups.push_back(move(target));
}
bool requires_projection = false;
if (types.size() != group_count) {
requires_projection = true;
}
// we need to create one aggregate per column in the select_list
for (idx_t i = 0; i < types.size(); ++i) {
auto logical_type = types[i];
// check if we can directly refer to a group, or if we need to push an aggregate with FIRST
auto entry = group_by_references.find(i);
if (entry != group_by_references.end()) {
auto group_index = entry->second;
// entry is found: can directly refer to a group
projections.push_back(make_unique<BoundReferenceExpression>(logical_type, group_index));
if (group_index != i) {
// we require a projection only if this group element is out of order
requires_projection = true;
}
} else {
// entry is not one of the groups: need to push a FIRST aggregate
auto bound = make_unique<BoundReferenceExpression>(logical_type, i);
vector<unique_ptr<Expression>> first_children;
first_children.push_back(move(bound));
auto first_aggregate = AggregateFunction::BindAggregateFunction(
context, FirstFun::GetFunction(logical_type), move(first_children), nullptr, false);
// add the projection
projections.push_back(make_unique<BoundReferenceExpression>(logical_type, group_count + aggregates.size()));
// push it to the list of aggregates
aggregate_types.push_back(logical_type);
aggregates.push_back(move(first_aggregate));
requires_projection = true;
}
}
child = ExtractAggregateExpressions(move(child), aggregates, groups);
// we add a physical hash aggregation in the plan to select the distinct groups
auto groupby = make_unique<PhysicalHashAggregate>(context, aggregate_types, move(aggregates), move(groups));
groupby->children.push_back(move(child));
if (!requires_projection) {
return move(groupby);
}
// we add a physical projection on top of the aggregation to project all members in the select list
auto aggr_projection = make_unique<PhysicalProjection>(types, move(projections));
aggr_projection->children.push_back(move(groupby));
return move(aggr_projection);
}
unique_ptr<PhysicalOperator> PhysicalPlanGenerator::CreatePlan(LogicalDistinct &op) {
D_ASSERT(op.children.size() == 1);
auto plan = CreatePlan(*op.children[0]);
return CreateDistinctOn(move(plan), move(op.distinct_targets));
}
} // namespace duckdb
| 43.302326 | 119 | 0.751611 | [
"vector"
] |
c81f2d3a3eff09c385138a0a2d350b98e191248b | 30,036 | cpp | C++ | third_party/WebKit/Source/platform/weborigin/KURL.cpp | google-ar/chromium | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 777 | 2017-08-29T15:15:32.000Z | 2022-03-21T05:29:41.000Z | third_party/WebKit/Source/platform/weborigin/KURL.cpp | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 66 | 2017-08-30T18:31:18.000Z | 2021-08-02T10:59:35.000Z | third_party/WebKit/Source/platform/weborigin/KURL.cpp | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 123 | 2017-08-30T01:19:34.000Z | 2022-03-17T22:55:31.000Z | /*
* Copyright (C) 2004, 2007, 2008, 2011, 2012 Apple Inc. All rights reserved.
* Copyright (C) 2012 Research In Motion Limited. All rights reserved.
* Copyright (C) 2008, 2009, 2011 Google Inc. 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE COMPUTER, INC. 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.
*/
#include "platform/weborigin/KURL.h"
#include "platform/weborigin/KnownPorts.h"
#include "url/url_util.h"
#include "wtf/MathExtras.h"
#include "wtf/PtrUtil.h"
#include "wtf/StdLibExtras.h"
#include "wtf/text/CString.h"
#include "wtf/text/StringHash.h"
#include "wtf/text/StringStatics.h"
#include "wtf/text/StringUTF8Adaptor.h"
#include "wtf/text/TextEncoding.h"
#include <algorithm>
#ifndef NDEBUG
#include <stdio.h>
#endif
namespace blink {
static const int maximumValidPortNumber = 0xFFFE;
static const int invalidPortNumber = 0xFFFF;
static void assertProtocolIsGood(const char* protocol) {
#if DCHECK_IS_ON()
DCHECK_NE(protocol, "");
const char* p = protocol;
while (*p) {
ASSERT(*p > ' ' && *p < 0x7F && !(*p >= 'A' && *p <= 'Z'));
++p;
}
#endif
}
// Note: You must ensure that |spec| is a valid canonicalized URL before calling
// this function.
static const char* asURLChar8Subtle(const String& spec) {
ASSERT(spec.is8Bit());
// characters8 really return characters in Latin-1, but because we
// canonicalize URL strings, we know that everything before the fragment
// identifier will actually be ASCII, which means this cast is safe as long as
// you don't look at the fragment component.
return reinterpret_cast<const char*>(spec.characters8());
}
// Returns the characters for the given string, or a pointer to a static empty
// string if the input string is null. This will always ensure we have a non-
// null character pointer since ReplaceComponents has special meaning for null.
static const char* charactersOrEmpty(const StringUTF8Adaptor& string) {
static const char zero = 0;
return string.data() ? string.data() : &zero;
}
static bool isSchemeFirstChar(char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
static bool isSchemeChar(char c) {
return isSchemeFirstChar(c) || (c >= '0' && c <= '9') || c == '.' ||
c == '-' || c == '+';
}
static bool isUnicodeEncoding(const WTF::TextEncoding* encoding) {
return encoding->encodingForFormSubmission() == UTF8Encoding();
}
namespace {
class KURLCharsetConverter final : public url::CharsetConverter {
DISALLOW_NEW();
public:
// The encoding parameter may be 0, but in this case the object must not be
// called.
explicit KURLCharsetConverter(const WTF::TextEncoding* encoding)
: m_encoding(encoding) {}
void ConvertFromUTF16(const base::char16* input,
int inputLength,
url::CanonOutput* output) override {
CString encoded = m_encoding->encode(
String(input, inputLength), WTF::URLEncodedEntitiesForUnencodables);
output->Append(encoded.data(), static_cast<int>(encoded.length()));
}
private:
const WTF::TextEncoding* m_encoding;
};
} // namespace
bool isValidProtocol(const String& protocol) {
// RFC3986: ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
if (protocol.isEmpty())
return false;
if (!isSchemeFirstChar(protocol[0]))
return false;
unsigned protocolLength = protocol.length();
for (unsigned i = 1; i < protocolLength; i++) {
if (!isSchemeChar(protocol[i]))
return false;
}
return true;
}
void KURL::initialize() {
// This must be called before we create other threads to
// avoid racy static local initialization.
blankURL();
}
String KURL::strippedForUseAsReferrer() const {
if (!protocolIsInHTTPFamily())
return String();
if (m_parsed.username.is_nonempty() || m_parsed.password.is_nonempty() ||
m_parsed.ref.is_valid()) {
KURL referrer(*this);
referrer.setUser(String());
referrer.setPass(String());
referrer.removeFragmentIdentifier();
return referrer.getString();
}
return getString();
}
String KURL::strippedForUseAsHref() const {
if (m_parsed.username.is_nonempty() || m_parsed.password.is_nonempty()) {
KURL href(*this);
href.setUser(String());
href.setPass(String());
return href.getString();
}
return getString();
}
bool KURL::isLocalFile() const {
// Including feed here might be a bad idea since drag and drop uses this check
// and including feed would allow feeds to potentially let someone's blog
// read the contents of the clipboard on a drag, even without a drop.
// Likewise with using the FrameLoader::shouldTreatURLAsLocal() function.
return protocolIs("file");
}
bool protocolIsJavaScript(const String& url) {
return protocolIs(url, "javascript");
}
const KURL& blankURL() {
DEFINE_STATIC_LOCAL(KURL, staticBlankURL, (ParsedURLString, "about:blank"));
return staticBlankURL;
}
bool KURL::isAboutBlankURL() const {
return *this == blankURL();
}
const KURL& srcdocURL() {
DEFINE_STATIC_LOCAL(KURL, staticSrcdocURL, (ParsedURLString, "about:srcdoc"));
return staticSrcdocURL;
}
bool KURL::isAboutSrcdocURL() const {
return *this == srcdocURL();
}
String KURL::elidedString() const {
if (getString().length() <= 1024)
return getString();
return getString().left(511) + "..." + getString().right(510);
}
KURL::KURL() : m_isValid(false), m_protocolIsInHTTPFamily(false) {}
// Initializes with a string representing an absolute URL. No encoding
// information is specified. This generally happens when a KURL is converted
// to a string and then converted back. In this case, the URL is already
// canonical and in proper escaped form so needs no encoding. We treat it as
// UTF-8 just in case.
KURL::KURL(ParsedURLStringTag, const String& url) {
if (!url.isNull())
init(KURL(), url, 0);
else {
// WebCore expects us to preserve the nullness of strings when this
// constructor is used. In all other cases, it expects a non-null
// empty string, which is what init() will create.
m_isValid = false;
m_protocolIsInHTTPFamily = false;
}
}
KURL KURL::createIsolated(ParsedURLStringTag, const String& url) {
// FIXME: We should be able to skip this extra copy and created an
// isolated KURL more efficiently.
return KURL(ParsedURLString, url).copy();
}
// Constructs a new URL given a base URL and a possibly relative input URL.
// This assumes UTF-8 encoding.
KURL::KURL(const KURL& base, const String& relative) {
init(base, relative, 0);
}
// Constructs a new URL given a base URL and a possibly relative input URL.
// Any query portion of the relative URL will be encoded in the given encoding.
KURL::KURL(const KURL& base,
const String& relative,
const WTF::TextEncoding& encoding) {
init(base, relative, &encoding.encodingForFormSubmission());
}
KURL::KURL(const AtomicString& canonicalString,
const url::Parsed& parsed,
bool isValid)
: m_isValid(isValid),
m_protocolIsInHTTPFamily(false),
m_parsed(parsed),
m_string(canonicalString) {
initProtocolMetadata();
initInnerURL();
}
KURL::KURL(WTF::HashTableDeletedValueType)
: m_isValid(false),
m_protocolIsInHTTPFamily(false),
m_string(WTF::HashTableDeletedValue) {}
KURL::KURL(const KURL& other)
: m_isValid(other.m_isValid),
m_protocolIsInHTTPFamily(other.m_protocolIsInHTTPFamily),
m_protocol(other.m_protocol),
m_parsed(other.m_parsed),
m_string(other.m_string) {
if (other.m_innerURL.get())
m_innerURL = WTF::wrapUnique(new KURL(other.m_innerURL->copy()));
}
KURL::~KURL() {}
KURL& KURL::operator=(const KURL& other) {
m_isValid = other.m_isValid;
m_protocolIsInHTTPFamily = other.m_protocolIsInHTTPFamily;
m_protocol = other.m_protocol;
m_parsed = other.m_parsed;
m_string = other.m_string;
if (other.m_innerURL)
m_innerURL = WTF::wrapUnique(new KURL(other.m_innerURL->copy()));
else
m_innerURL.reset();
return *this;
}
KURL KURL::copy() const {
KURL result;
result.m_isValid = m_isValid;
result.m_protocolIsInHTTPFamily = m_protocolIsInHTTPFamily;
result.m_protocol = m_protocol.isolatedCopy();
result.m_parsed = m_parsed;
result.m_string = m_string.isolatedCopy();
if (m_innerURL)
result.m_innerURL = WTF::wrapUnique(new KURL(m_innerURL->copy()));
return result;
}
bool KURL::isNull() const {
return m_string.isNull();
}
bool KURL::isEmpty() const {
return m_string.isEmpty();
}
bool KURL::isValid() const {
return m_isValid;
}
bool KURL::hasPort() const {
return hostEnd() < pathStart();
}
bool KURL::protocolIsInHTTPFamily() const {
return m_protocolIsInHTTPFamily;
}
bool KURL::hasPath() const {
// Note that http://www.google.com/" has a path, the path is "/". This can
// return false only for invalid or nonstandard URLs.
return m_parsed.path.len >= 0;
}
String KURL::lastPathComponent() const {
if (!m_isValid)
return stringViewForInvalidComponent().toString();
ASSERT(!m_string.isNull());
// When the output ends in a slash, WebCore has different expectations than
// the GoogleURL library. For "/foo/bar/" the library will return the empty
// string, but WebCore wants "bar".
url::Component path = m_parsed.path;
if (path.len > 0 && m_string[path.end() - 1] == '/')
path.len--;
url::Component file;
if (m_string.is8Bit())
url::ExtractFileName(asURLChar8Subtle(m_string), path, &file);
else
url::ExtractFileName(m_string.characters16(), path, &file);
// Bug: https://bugs.webkit.org/show_bug.cgi?id=21015 this function returns
// a null string when the path is empty, which we duplicate here.
if (!file.is_nonempty())
return String();
return componentString(file);
}
String KURL::protocol() const {
DCHECK_EQ(componentString(m_parsed.scheme), m_protocol);
return m_protocol;
}
String KURL::host() const {
return componentString(m_parsed.host);
}
// Returns 0 when there is no port.
//
// We treat URL's with out-of-range port numbers as invalid URLs, and they will
// be rejected by the canonicalizer. KURL.cpp will allow them in parsing, but
// return invalidPortNumber from this port() function, so we mirror that
// behavior here.
unsigned short KURL::port() const {
if (!m_isValid || m_parsed.port.len <= 0)
return 0;
ASSERT(!m_string.isNull());
int port = m_string.is8Bit()
? url::ParsePort(asURLChar8Subtle(m_string), m_parsed.port)
: url::ParsePort(m_string.characters16(), m_parsed.port);
ASSERT(port != url::PORT_UNSPECIFIED); // Checked port.len <= 0 before.
if (port == url::PORT_INVALID ||
port > maximumValidPortNumber) // Mimic KURL::port()
port = invalidPortNumber;
return static_cast<unsigned short>(port);
}
// TODO(csharrison): Migrate pass() and user() to return a StringView. Most
// consumers just need to know if the string is empty.
String KURL::pass() const {
// Bug: https://bugs.webkit.org/show_bug.cgi?id=21015 this function returns
// a null string when the password is empty, which we duplicate here.
if (!m_parsed.password.is_nonempty())
return String();
return componentString(m_parsed.password);
}
String KURL::user() const {
return componentString(m_parsed.username);
}
String KURL::fragmentIdentifier() const {
// Empty but present refs ("foo.com/bar#") should result in the empty
// string, which componentString will produce. Nonexistent refs
// should be the null string.
if (!m_parsed.ref.is_valid())
return String();
return componentString(m_parsed.ref);
}
bool KURL::hasFragmentIdentifier() const {
return m_parsed.ref.len >= 0;
}
String KURL::baseAsString() const {
// FIXME: There is probably a more efficient way to do this?
return m_string.left(pathAfterLastSlash());
}
String KURL::query() const {
if (m_parsed.query.len >= 0)
return componentString(m_parsed.query);
// Bug: https://bugs.webkit.org/show_bug.cgi?id=21015 this function returns
// an empty string when the query is empty rather than a null (not sure
// which is right).
// Returns a null if the query is not specified, instead of empty.
if (m_parsed.query.is_valid())
return emptyString();
return String();
}
String KURL::path() const {
return componentString(m_parsed.path);
}
bool KURL::setProtocol(const String& protocol) {
// Firefox and IE remove everything after the first ':'.
int separatorPosition = protocol.find(':');
String newProtocol = protocol.substring(0, separatorPosition);
StringUTF8Adaptor newProtocolUTF8(newProtocol);
// If KURL is given an invalid scheme, it returns failure without modifying
// the URL at all. This is in contrast to most other setters which modify
// the URL and set "m_isValid."
url::RawCanonOutputT<char> canonProtocol;
url::Component protocolComponent;
if (!url::CanonicalizeScheme(newProtocolUTF8.data(),
url::Component(0, newProtocolUTF8.length()),
&canonProtocol, &protocolComponent) ||
!protocolComponent.is_nonempty())
return false;
url::Replacements<char> replacements;
replacements.SetScheme(charactersOrEmpty(newProtocolUTF8),
url::Component(0, newProtocolUTF8.length()));
replaceComponents(replacements);
// isValid could be false but we still return true here. This is because
// WebCore or JS scripts can build up a URL by setting individual
// components, and a JS exception is based on the return value of this
// function. We want to throw the exception and stop the script only when
// its trying to set a bad protocol, and not when it maybe just hasn't
// finished building up its final scheme.
return true;
}
void KURL::setHost(const String& host) {
StringUTF8Adaptor hostUTF8(host);
url::Replacements<char> replacements;
replacements.SetHost(charactersOrEmpty(hostUTF8),
url::Component(0, hostUTF8.length()));
replaceComponents(replacements);
}
static String parsePortFromStringPosition(const String& value,
unsigned portStart) {
// "008080junk" needs to be treated as port "8080" and "000" as "0".
size_t length = value.length();
unsigned portEnd = portStart;
while (isASCIIDigit(value[portEnd]) && portEnd < length)
++portEnd;
while (value[portStart] == '0' && portStart < portEnd - 1)
++portStart;
// Required for backwards compat.
// https://www.w3.org/Bugs/Public/show_bug.cgi?id=23463
if (portStart == portEnd)
return "0";
return value.substring(portStart, portEnd - portStart);
}
void KURL::setHostAndPort(const String& hostAndPort) {
size_t separator = hostAndPort.find(':');
if (!separator)
return;
if (separator == kNotFound) {
url::Replacements<char> replacements;
StringUTF8Adaptor hostUTF8(hostAndPort);
replacements.SetHost(charactersOrEmpty(hostUTF8),
url::Component(0, hostUTF8.length()));
replaceComponents(replacements);
return;
}
String host = hostAndPort.substring(0, separator);
String port = parsePortFromStringPosition(hostAndPort, separator + 1);
StringUTF8Adaptor hostUTF8(host);
StringUTF8Adaptor portUTF8(port);
url::Replacements<char> replacements;
replacements.SetHost(charactersOrEmpty(hostUTF8),
url::Component(0, hostUTF8.length()));
replacements.SetPort(charactersOrEmpty(portUTF8),
url::Component(0, portUTF8.length()));
replaceComponents(replacements);
}
void KURL::removePort() {
if (!hasPort())
return;
url::Replacements<char> replacements;
replacements.ClearPort();
replaceComponents(replacements);
}
void KURL::setPort(const String& port) {
String parsedPort = parsePortFromStringPosition(port, 0);
setPort(parsedPort.toUInt());
}
void KURL::setPort(unsigned short port) {
if (isDefaultPortForProtocol(port, protocol())) {
removePort();
return;
}
String portString = String::number(port);
ASSERT(portString.is8Bit());
url::Replacements<char> replacements;
replacements.SetPort(reinterpret_cast<const char*>(portString.characters8()),
url::Component(0, portString.length()));
replaceComponents(replacements);
}
void KURL::setUser(const String& user) {
// This function is commonly called to clear the username, which we
// normally don't have, so we optimize this case.
if (user.isEmpty() && !m_parsed.username.is_valid())
return;
// The canonicalizer will clear any usernames that are empty, so we
// don't have to explicitly call ClearUsername() here.
StringUTF8Adaptor userUTF8(user);
url::Replacements<char> replacements;
replacements.SetUsername(charactersOrEmpty(userUTF8),
url::Component(0, userUTF8.length()));
replaceComponents(replacements);
}
void KURL::setPass(const String& pass) {
// This function is commonly called to clear the password, which we
// normally don't have, so we optimize this case.
if (pass.isEmpty() && !m_parsed.password.is_valid())
return;
// The canonicalizer will clear any passwords that are empty, so we
// don't have to explicitly call ClearUsername() here.
StringUTF8Adaptor passUTF8(pass);
url::Replacements<char> replacements;
replacements.SetPassword(charactersOrEmpty(passUTF8),
url::Component(0, passUTF8.length()));
replaceComponents(replacements);
}
void KURL::setFragmentIdentifier(const String& fragment) {
// This function is commonly called to clear the ref, which we
// normally don't have, so we optimize this case.
if (fragment.isNull() && !m_parsed.ref.is_valid())
return;
StringUTF8Adaptor fragmentUTF8(fragment);
url::Replacements<char> replacements;
if (fragment.isNull())
replacements.ClearRef();
else
replacements.SetRef(charactersOrEmpty(fragmentUTF8),
url::Component(0, fragmentUTF8.length()));
replaceComponents(replacements);
}
void KURL::removeFragmentIdentifier() {
url::Replacements<char> replacements;
replacements.ClearRef();
replaceComponents(replacements);
}
void KURL::setQuery(const String& query) {
StringUTF8Adaptor queryUTF8(query);
url::Replacements<char> replacements;
if (query.isNull()) {
// KURL.cpp sets to null to clear any query.
replacements.ClearQuery();
} else if (query.length() > 0 && query[0] == '?') {
// WebCore expects the query string to begin with a question mark, but
// GoogleURL doesn't. So we trim off the question mark when setting.
replacements.SetQuery(charactersOrEmpty(queryUTF8),
url::Component(1, queryUTF8.length() - 1));
} else {
// When set with the empty string or something that doesn't begin with
// a question mark, KURL.cpp will add a question mark for you. The only
// way this isn't compatible is if you call this function with an empty
// string. KURL.cpp will leave a '?' with nothing following it in the
// URL, whereas we'll clear it.
// FIXME We should eliminate this difference.
replacements.SetQuery(charactersOrEmpty(queryUTF8),
url::Component(0, queryUTF8.length()));
}
replaceComponents(replacements);
}
void KURL::setPath(const String& path) {
// Empty paths will be canonicalized to "/", so we don't have to worry
// about calling ClearPath().
StringUTF8Adaptor pathUTF8(path);
url::Replacements<char> replacements;
replacements.SetPath(charactersOrEmpty(pathUTF8),
url::Component(0, pathUTF8.length()));
replaceComponents(replacements);
}
String decodeURLEscapeSequences(const String& string) {
return decodeURLEscapeSequences(string, UTF8Encoding());
}
String decodeURLEscapeSequences(const String& string,
const WTF::TextEncoding& encoding) {
StringUTF8Adaptor stringUTF8(string);
url::RawCanonOutputT<base::char16> unescaped;
url::DecodeURLEscapeSequences(stringUTF8.data(), stringUTF8.length(),
&unescaped);
return StringImpl::create8BitIfPossible(
reinterpret_cast<UChar*>(unescaped.data()), unescaped.length());
}
String encodeWithURLEscapeSequences(const String& notEncodedString) {
CString utf8 = UTF8Encoding().encode(notEncodedString,
WTF::URLEncodedEntitiesForUnencodables);
url::RawCanonOutputT<char> buffer;
int inputLength = utf8.length();
if (buffer.capacity() < inputLength * 3)
buffer.Resize(inputLength * 3);
url::EncodeURIComponent(utf8.data(), inputLength, &buffer);
String escaped(buffer.data(), buffer.length());
// Unescape '/'; it's safe and much prettier.
escaped.replace("%2F", "/");
return escaped;
}
bool KURL::isHierarchical() const {
if (m_string.isNull() || !m_parsed.scheme.is_nonempty())
return false;
return m_string.is8Bit()
? url::IsStandard(asURLChar8Subtle(m_string), m_parsed.scheme)
: url::IsStandard(m_string.characters16(), m_parsed.scheme);
}
bool equalIgnoringFragmentIdentifier(const KURL& a, const KURL& b) {
// Compute the length of each URL without its ref. Note that the reference
// begin (if it exists) points to the character *after* the '#', so we need
// to subtract one.
int aLength = a.m_string.length();
if (a.m_parsed.ref.len >= 0)
aLength = a.m_parsed.ref.begin - 1;
int bLength = b.m_string.length();
if (b.m_parsed.ref.len >= 0)
bLength = b.m_parsed.ref.begin - 1;
if (aLength != bLength)
return false;
const String& aString = a.m_string;
const String& bString = b.m_string;
// FIXME: Abstraction this into a function in WTFString.h.
for (int i = 0; i < aLength; ++i) {
if (aString[i] != bString[i])
return false;
}
return true;
}
unsigned KURL::hostStart() const {
return m_parsed.CountCharactersBefore(url::Parsed::HOST, false);
}
unsigned KURL::hostEnd() const {
return m_parsed.CountCharactersBefore(url::Parsed::PORT, true);
}
unsigned KURL::pathStart() const {
return m_parsed.CountCharactersBefore(url::Parsed::PATH, false);
}
unsigned KURL::pathEnd() const {
return m_parsed.CountCharactersBefore(url::Parsed::QUERY, true);
}
unsigned KURL::pathAfterLastSlash() const {
if (m_string.isNull())
return 0;
if (!m_isValid || !m_parsed.path.is_valid())
return m_parsed.CountCharactersBefore(url::Parsed::PATH, false);
url::Component filename;
if (m_string.is8Bit())
url::ExtractFileName(asURLChar8Subtle(m_string), m_parsed.path, &filename);
else
url::ExtractFileName(m_string.characters16(), m_parsed.path, &filename);
return filename.begin;
}
bool protocolIs(const String& url, const char* protocol) {
assertProtocolIsGood(protocol);
if (url.isNull())
return false;
if (url.is8Bit())
return url::FindAndCompareScheme(asURLChar8Subtle(url), url.length(),
protocol, 0);
return url::FindAndCompareScheme(url.characters16(), url.length(), protocol,
0);
}
void KURL::init(const KURL& base,
const String& relative,
const WTF::TextEncoding* queryEncoding) {
// As a performance optimization, we do not use the charset converter
// if encoding is UTF-8 or other Unicode encodings. Note that this is
// per HTML5 2.5.3 (resolving URL). The URL canonicalizer will be more
// efficient with no charset converter object because it can do UTF-8
// internally with no extra copies.
StringUTF8Adaptor baseUTF8(base.getString());
// We feel free to make the charset converter object every time since it's
// just a wrapper around a reference.
KURLCharsetConverter charsetConverterObject(queryEncoding);
KURLCharsetConverter* charsetConverter =
(!queryEncoding || isUnicodeEncoding(queryEncoding))
? 0
: &charsetConverterObject;
// Clamp to int max to avoid overflow.
url::RawCanonOutputT<char> output;
if (!relative.isNull() && relative.is8Bit()) {
StringUTF8Adaptor relativeUTF8(relative);
m_isValid = url::ResolveRelative(baseUTF8.data(), baseUTF8.length(),
base.m_parsed, relativeUTF8.data(),
clampTo<int>(relativeUTF8.length()),
charsetConverter, &output, &m_parsed);
} else {
m_isValid = url::ResolveRelative(baseUTF8.data(), baseUTF8.length(),
base.m_parsed, relative.characters16(),
clampTo<int>(relative.length()),
charsetConverter, &output, &m_parsed);
}
// AtomicString::fromUTF8 will re-hash the raw output and check the
// AtomicStringTable (addWithTranslator) for the string. This can be very
// expensive for large URLs. However, since many URLs are generated from
// existing AtomicStrings (which already have their hashes computed), this
// fast path is used if the input string is already canonicalized.
//
// Because this optimization does not apply to non-AtomicStrings, explicitly
// check that the input is Atomic before moving forward with it. If we mark
// non-Atomic input as Atomic here, we will render the (const) input string
// thread unsafe.
if (!relative.isNull() && relative.impl()->isAtomic() &&
StringView(output.data(), static_cast<unsigned>(output.length())) ==
relative) {
m_string = relative;
} else {
m_string = AtomicString::fromUTF8(output.data(), output.length());
}
initProtocolMetadata();
initInnerURL();
}
void KURL::initInnerURL() {
if (!m_isValid) {
m_innerURL.reset();
return;
}
if (url::Parsed* innerParsed = m_parsed.inner_parsed())
m_innerURL = WTF::wrapUnique(new KURL(
ParsedURLString,
m_string.substring(innerParsed->scheme.begin,
innerParsed->Length() - innerParsed->scheme.begin)));
else
m_innerURL.reset();
}
void KURL::initProtocolMetadata() {
if (!m_isValid) {
m_protocolIsInHTTPFamily = false;
m_protocol = componentString(m_parsed.scheme);
return;
}
DCHECK(!m_string.isNull());
StringView protocol = componentStringView(m_parsed.scheme);
m_protocolIsInHTTPFamily = true;
if (protocol == WTF::httpsAtom) {
m_protocol = WTF::httpsAtom;
} else if (protocol == WTF::httpAtom) {
m_protocol = WTF::httpAtom;
} else {
m_protocol = protocol.toAtomicString();
m_protocolIsInHTTPFamily =
m_protocol == "http-so" || m_protocol == "https-so";
}
DCHECK_EQ(m_protocol, m_protocol.lower());
}
bool KURL::protocolIs(const char* protocol) const {
assertProtocolIsGood(protocol);
// JavaScript URLs are "valid" and should be executed even if KURL decides
// they are invalid. The free function protocolIsJavaScript() should be used
// instead.
// FIXME: Chromium code needs to be fixed for this assert to be enabled.
// ASSERT(strcmp(protocol, "javascript"));
return m_protocol == protocol;
}
StringView KURL::stringViewForInvalidComponent() const {
return m_string.isNull() ? StringView() : StringView("", 0);
}
StringView KURL::componentStringView(const url::Component& component) const {
if (!m_isValid || component.len <= 0)
return stringViewForInvalidComponent();
// begin and len are in terms of bytes which do not match
// if string() is UTF-16 and input contains non-ASCII characters.
// However, the only part in urlString that can contain non-ASCII
// characters is 'ref' at the end of the string. In that case,
// begin will always match the actual value and len (in terms of
// byte) will be longer than what's needed by 'mid'. However, mid
// truncates len to avoid go past the end of a string so that we can
// get away without doing anything here.
int maxLength = getString().length() - component.begin;
return StringView(getString(), component.begin,
component.len > maxLength ? maxLength : component.len);
}
String KURL::componentString(const url::Component& component) const {
return componentStringView(component).toString();
}
template <typename CHAR>
void KURL::replaceComponents(const url::Replacements<CHAR>& replacements) {
url::RawCanonOutputT<char> output;
url::Parsed newParsed;
StringUTF8Adaptor utf8(m_string);
m_isValid = url::ReplaceComponents(utf8.data(), utf8.length(), m_parsed,
replacements, 0, &output, &newParsed);
m_parsed = newParsed;
m_string = AtomicString::fromUTF8(output.data(), output.length());
initProtocolMetadata();
}
bool KURL::isSafeToSendToAnotherThread() const {
return m_string.isSafeToSendToAnotherThread() &&
(!m_innerURL || m_innerURL->isSafeToSendToAnotherThread());
}
} // namespace blink
| 34.326857 | 80 | 0.694067 | [
"render",
"object"
] |
c81f686d264c4b8a9ace5d59d9417f90c547e679 | 18,468 | cpp | C++ | Source/Urho3D/Math/Ray.cpp | pat2nav/Urho3D | cc0346f39bd365782d825e2e337a1f33bb225308 | [
"MIT"
] | null | null | null | Source/Urho3D/Math/Ray.cpp | pat2nav/Urho3D | cc0346f39bd365782d825e2e337a1f33bb225308 | [
"MIT"
] | null | null | null | Source/Urho3D/Math/Ray.cpp | pat2nav/Urho3D | cc0346f39bd365782d825e2e337a1f33bb225308 | [
"MIT"
] | null | null | null | // Copyright (c) 2008-2022 the Urho3D project
// License: MIT
#include "../Precompiled.h"
#include "../Math/BoundingBox.h"
#include "../Math/Frustum.h"
#include "../Math/Ray.h"
#include "../DebugNew.h"
namespace Urho3D
{
Vector3 Ray::ClosestPoint(const Ray& ray) const
{
// Algorithm based on http://paulbourke.net/geometry/lineline3d/
Vector3 p13 = origin_ - ray.origin_;
Vector3 p43 = ray.direction_;
Vector3 p21 = direction_;
float d1343 = p13.DotProduct(p43);
float d4321 = p43.DotProduct(p21);
float d1321 = p13.DotProduct(p21);
float d4343 = p43.DotProduct(p43);
float d2121 = p21.DotProduct(p21);
float d = d2121 * d4343 - d4321 * d4321;
if (Abs(d) < M_EPSILON)
return origin_;
float n = d1343 * d4321 - d1321 * d4343;
float a = n / d;
return origin_ + a * direction_;
}
float Ray::HitDistance(const Plane& plane) const
{
float d = plane.normal_.DotProduct(direction_);
if (Abs(d) >= M_EPSILON)
{
float t = -(plane.normal_.DotProduct(origin_) + plane.d_) / d;
if (t >= 0.0f)
return t;
else
return M_INFINITY;
}
else
return M_INFINITY;
}
float Ray::HitDistance(const BoundingBox& box) const
{
// If undefined, no hit (infinite distance)
if (!box.Defined())
return M_INFINITY;
// Check for ray origin being inside the box
if (box.IsInside(origin_))
return 0.0f;
float dist = M_INFINITY;
// Check for intersecting in the X-direction
if (origin_.x_ < box.min_.x_ && direction_.x_ > 0.0f)
{
float x = (box.min_.x_ - origin_.x_) / direction_.x_;
if (x < dist)
{
Vector3 point = origin_ + x * direction_;
if (point.y_ >= box.min_.y_ && point.y_ <= box.max_.y_ && point.z_ >= box.min_.z_ && point.z_ <= box.max_.z_)
dist = x;
}
}
if (origin_.x_ > box.max_.x_ && direction_.x_ < 0.0f)
{
float x = (box.max_.x_ - origin_.x_) / direction_.x_;
if (x < dist)
{
Vector3 point = origin_ + x * direction_;
if (point.y_ >= box.min_.y_ && point.y_ <= box.max_.y_ && point.z_ >= box.min_.z_ && point.z_ <= box.max_.z_)
dist = x;
}
}
// Check for intersecting in the Y-direction
if (origin_.y_ < box.min_.y_ && direction_.y_ > 0.0f)
{
float x = (box.min_.y_ - origin_.y_) / direction_.y_;
if (x < dist)
{
Vector3 point = origin_ + x * direction_;
if (point.x_ >= box.min_.x_ && point.x_ <= box.max_.x_ && point.z_ >= box.min_.z_ && point.z_ <= box.max_.z_)
dist = x;
}
}
if (origin_.y_ > box.max_.y_ && direction_.y_ < 0.0f)
{
float x = (box.max_.y_ - origin_.y_) / direction_.y_;
if (x < dist)
{
Vector3 point = origin_ + x * direction_;
if (point.x_ >= box.min_.x_ && point.x_ <= box.max_.x_ && point.z_ >= box.min_.z_ && point.z_ <= box.max_.z_)
dist = x;
}
}
// Check for intersecting in the Z-direction
if (origin_.z_ < box.min_.z_ && direction_.z_ > 0.0f)
{
float x = (box.min_.z_ - origin_.z_) / direction_.z_;
if (x < dist)
{
Vector3 point = origin_ + x * direction_;
if (point.x_ >= box.min_.x_ && point.x_ <= box.max_.x_ && point.y_ >= box.min_.y_ && point.y_ <= box.max_.y_)
dist = x;
}
}
if (origin_.z_ > box.max_.z_ && direction_.z_ < 0.0f)
{
float x = (box.max_.z_ - origin_.z_) / direction_.z_;
if (x < dist)
{
Vector3 point = origin_ + x * direction_;
if (point.x_ >= box.min_.x_ && point.x_ <= box.max_.x_ && point.y_ >= box.min_.y_ && point.y_ <= box.max_.y_)
dist = x;
}
}
return dist;
}
float Ray::HitDistance(const Frustum& frustum, bool solidInside) const
{
float maxOutside = 0.0f;
float minInside = M_INFINITY;
bool allInside = true;
for (const auto& plane : frustum.planes_)
{
float distance = HitDistance(plane);
if (plane.Distance(origin_) < 0.0f)
{
maxOutside = Max(maxOutside, distance);
allInside = false;
}
else
minInside = Min(minInside, distance);
}
if (allInside)
return solidInside ? 0.0f : minInside;
else if (maxOutside <= minInside)
return maxOutside;
else
return M_INFINITY;
}
float Ray::HitDistance(const Sphere& sphere) const
{
Vector3 centeredOrigin = origin_ - sphere.center_;
float squaredRadius = sphere.radius_ * sphere.radius_;
// Check if ray originates inside the sphere
if (centeredOrigin.LengthSquared() <= squaredRadius)
return 0.0f;
// Calculate intersection by quadratic equation
float a = direction_.DotProduct(direction_);
float b = 2.0f * centeredOrigin.DotProduct(direction_);
float c = centeredOrigin.DotProduct(centeredOrigin) - squaredRadius;
float d = b * b - 4.0f * a * c;
// No solution
if (d < 0.0f)
return M_INFINITY;
// Get the nearer solution
float dSqrt = sqrtf(d);
float dist = (-b - dSqrt) / (2.0f * a);
if (dist >= 0.0f)
return dist;
else
return (-b + dSqrt) / (2.0f * a);
}
float Ray::HitDistance(const Vector3& v0, const Vector3& v1, const Vector3& v2, Vector3* outNormal, Vector3* outBary) const
{
// Based on Fast, Minimum Storage Ray/Triangle Intersection by Möller & Trumbore
// http://www.graphics.cornell.edu/pubs/1997/MT97.pdf
// Calculate edge vectors
Vector3 edge1(v1 - v0);
Vector3 edge2(v2 - v0);
// Calculate determinant & check backfacing
Vector3 p(direction_.CrossProduct(edge2));
float det = edge1.DotProduct(p);
if (det >= M_EPSILON)
{
// Calculate u & v parameters and test
Vector3 t(origin_ - v0);
float u = t.DotProduct(p);
if (u >= 0.0f && u <= det)
{
Vector3 q(t.CrossProduct(edge1));
float v = direction_.DotProduct(q);
if (v >= 0.0f && u + v <= det)
{
float distance = edge2.DotProduct(q) / det;
// Discard hits behind the ray
if (distance >= 0.0f)
{
// There is an intersection, so calculate distance & optional normal
if (outNormal)
*outNormal = edge1.CrossProduct(edge2);
if (outBary)
*outBary = Vector3(1 - (u / det) - (v / det), u / det, v / det);
return distance;
}
}
}
}
return M_INFINITY;
}
float Ray::HitDistance(const void* vertexData, unsigned vertexStride, unsigned vertexStart, unsigned vertexCount,
Vector3* outNormal, Vector2* outUV, unsigned uvOffset) const
{
float nearest = M_INFINITY;
const unsigned char* vertices = ((const unsigned char*)vertexData) + vertexStart * vertexStride;
unsigned index = 0, nearestIdx = M_MAX_UNSIGNED;
Vector3 tempNormal;
Vector3* tempNormalPtr = outNormal ? &tempNormal : nullptr;
Vector3 barycentric;
Vector3 tempBarycentric;
Vector3* tempBarycentricPtr = outUV ? &tempBarycentric : nullptr;
while (index + 2 < vertexCount)
{
const Vector3& v0 = *((const Vector3*)(&vertices[index * vertexStride]));
const Vector3& v1 = *((const Vector3*)(&vertices[(index + 1) * vertexStride]));
const Vector3& v2 = *((const Vector3*)(&vertices[(index + 2) * vertexStride]));
float distance = HitDistance(v0, v1, v2, tempNormalPtr, tempBarycentricPtr);
if (distance < nearest)
{
nearestIdx = index;
nearest = distance;
if (outNormal)
*outNormal = tempNormal;
if (outUV)
barycentric = tempBarycentric;
}
index += 3;
}
if (outUV)
{
if (nearestIdx == M_MAX_UNSIGNED)
*outUV = Vector2::ZERO;
else
{
// Interpolate the UV coordinate using barycentric coordinate
const Vector2& uv0 = *((const Vector2*)(&vertices[uvOffset + nearestIdx * vertexStride]));
const Vector2& uv1 = *((const Vector2*)(&vertices[uvOffset + (nearestIdx + 1) * vertexStride]));
const Vector2& uv2 = *((const Vector2*)(&vertices[uvOffset + (nearestIdx + 2) * vertexStride]));
*outUV = Vector2(uv0.x_ * barycentric.x_ + uv1.x_ * barycentric.y_ + uv2.x_ * barycentric.z_,
uv0.y_ * barycentric.x_ + uv1.y_ * barycentric.y_ + uv2.y_ * barycentric.z_);
}
}
return nearest;
}
float Ray::HitDistance(const void* vertexData, unsigned vertexStride, const void* indexData, unsigned indexSize,
unsigned indexStart, unsigned indexCount, Vector3* outNormal, Vector2* outUV, unsigned uvOffset) const
{
float nearest = M_INFINITY;
const auto* vertices = (const unsigned char*)vertexData;
Vector3 tempNormal;
Vector3* tempNormalPtr = outNormal ? &tempNormal : nullptr;
Vector3 barycentric;
Vector3 tempBarycentric;
Vector3* tempBarycentricPtr = outUV ? &tempBarycentric : nullptr;
// 16-bit indices
if (indexSize == sizeof(unsigned short))
{
const unsigned short* indices = ((const unsigned short*)indexData) + indexStart;
const unsigned short* indicesEnd = indices + indexCount;
const unsigned short* nearestIndices = nullptr;
while (indices < indicesEnd)
{
const Vector3& v0 = *((const Vector3*)(&vertices[indices[0] * vertexStride]));
const Vector3& v1 = *((const Vector3*)(&vertices[indices[1] * vertexStride]));
const Vector3& v2 = *((const Vector3*)(&vertices[indices[2] * vertexStride]));
float distance = HitDistance(v0, v1, v2, tempNormalPtr, tempBarycentricPtr);
if (distance < nearest)
{
nearestIndices = indices;
nearest = distance;
if (outNormal)
*outNormal = tempNormal;
if (outUV)
barycentric = tempBarycentric;
}
indices += 3;
}
if (outUV)
{
if (nearestIndices == nullptr)
*outUV = Vector2::ZERO;
else
{
// Interpolate the UV coordinate using barycentric coordinate
const Vector2& uv0 = *((const Vector2*)(&vertices[uvOffset + nearestIndices[0] * vertexStride]));
const Vector2& uv1 = *((const Vector2*)(&vertices[uvOffset + nearestIndices[1] * vertexStride]));
const Vector2& uv2 = *((const Vector2*)(&vertices[uvOffset + nearestIndices[2] * vertexStride]));
*outUV = Vector2(uv0.x_ * barycentric.x_ + uv1.x_ * barycentric.y_ + uv2.x_ * barycentric.z_,
uv0.y_ * barycentric.x_ + uv1.y_ * barycentric.y_ + uv2.y_ * barycentric.z_);
}
}
}
// 32-bit indices
else
{
const unsigned* indices = ((const unsigned*)indexData) + indexStart;
const unsigned* indicesEnd = indices + indexCount;
const unsigned* nearestIndices = nullptr;
while (indices < indicesEnd)
{
const Vector3& v0 = *((const Vector3*)(&vertices[indices[0] * vertexStride]));
const Vector3& v1 = *((const Vector3*)(&vertices[indices[1] * vertexStride]));
const Vector3& v2 = *((const Vector3*)(&vertices[indices[2] * vertexStride]));
float distance = HitDistance(v0, v1, v2, tempNormalPtr, tempBarycentricPtr);
if (distance < nearest)
{
nearestIndices = indices;
nearest = distance;
if (outNormal)
*outNormal = tempNormal;
if (outUV)
barycentric = tempBarycentric;
}
indices += 3;
}
if (outUV)
{
if (nearestIndices == nullptr)
*outUV = Vector2::ZERO;
else
{
// Interpolate the UV coordinate using barycentric coordinate
const Vector2& uv0 = *((const Vector2*)(&vertices[uvOffset + nearestIndices[0] * vertexStride]));
const Vector2& uv1 = *((const Vector2*)(&vertices[uvOffset + nearestIndices[1] * vertexStride]));
const Vector2& uv2 = *((const Vector2*)(&vertices[uvOffset + nearestIndices[2] * vertexStride]));
*outUV = Vector2(uv0.x_ * barycentric.x_ + uv1.x_ * barycentric.y_ + uv2.x_ * barycentric.z_,
uv0.y_ * barycentric.x_ + uv1.y_ * barycentric.y_ + uv2.y_ * barycentric.z_);
}
}
}
return nearest;
}
bool Ray::InsideGeometry(const void* vertexData, unsigned vertexSize, unsigned vertexStart, unsigned vertexCount) const
{
float currentFrontFace = M_INFINITY;
float currentBackFace = M_INFINITY;
const unsigned char* vertices = ((const unsigned char*)vertexData) + vertexStart * vertexSize;
unsigned index = 0;
while (index + 2 < vertexCount)
{
const Vector3& v0 = *((const Vector3*)(&vertices[index * vertexSize]));
const Vector3& v1 = *((const Vector3*)(&vertices[(index + 1) * vertexSize]));
const Vector3& v2 = *((const Vector3*)(&vertices[(index + 2) * vertexSize]));
float frontFaceDistance = HitDistance(v0, v1, v2);
float backFaceDistance = HitDistance(v2, v1, v0);
currentFrontFace = Min(frontFaceDistance > 0.0f ? frontFaceDistance : M_INFINITY, currentFrontFace);
// A backwards face is just a regular one, with the vertices in the opposite order. This essentially checks backfaces by
// checking reversed frontfaces
currentBackFace = Min(backFaceDistance > 0.0f ? backFaceDistance : M_INFINITY, currentBackFace);
index += 3;
}
// If the closest face is a backface, that means that the ray originates from the inside of the geometry
// NOTE: there may be cases where both are equal, as in, no collision to either. This is prevented in the most likely case
// (ray doesn't hit either) by this conditional
if (currentFrontFace != M_INFINITY || currentBackFace != M_INFINITY)
return currentBackFace < currentFrontFace;
// It is still possible for two triangles to be equally distant from the triangle, however, this is extremely unlikely.
// As such, it is safe to assume they are not
return false;
}
bool Ray::InsideGeometry(const void* vertexData, unsigned vertexSize, const void* indexData, unsigned indexSize,
unsigned indexStart, unsigned indexCount) const
{
float currentFrontFace = M_INFINITY;
float currentBackFace = M_INFINITY;
const auto* vertices = (const unsigned char*)vertexData;
// 16-bit indices
if (indexSize == sizeof(unsigned short))
{
const unsigned short* indices = ((const unsigned short*)indexData) + indexStart;
const unsigned short* indicesEnd = indices + indexCount;
while (indices < indicesEnd)
{
const Vector3& v0 = *((const Vector3*)(&vertices[indices[0] * vertexSize]));
const Vector3& v1 = *((const Vector3*)(&vertices[indices[1] * vertexSize]));
const Vector3& v2 = *((const Vector3*)(&vertices[indices[2] * vertexSize]));
float frontFaceDistance = HitDistance(v0, v1, v2);
float backFaceDistance = HitDistance(v2, v1, v0);
currentFrontFace = Min(frontFaceDistance > 0.0f ? frontFaceDistance : M_INFINITY, currentFrontFace);
// A backwards face is just a regular one, with the vertices in the opposite order. This essentially checks backfaces by
// checking reversed frontfaces
currentBackFace = Min(backFaceDistance > 0.0f ? backFaceDistance : M_INFINITY, currentBackFace);
indices += 3;
}
}
// 32-bit indices
else
{
const unsigned* indices = ((const unsigned*)indexData) + indexStart;
const unsigned* indicesEnd = indices + indexCount;
while (indices < indicesEnd)
{
const Vector3& v0 = *((const Vector3*)(&vertices[indices[0] * vertexSize]));
const Vector3& v1 = *((const Vector3*)(&vertices[indices[1] * vertexSize]));
const Vector3& v2 = *((const Vector3*)(&vertices[indices[2] * vertexSize]));
float frontFaceDistance = HitDistance(v0, v1, v2);
float backFaceDistance = HitDistance(v2, v1, v0);
currentFrontFace = Min(frontFaceDistance > 0.0f ? frontFaceDistance : M_INFINITY, currentFrontFace);
// A backwards face is just a regular one, with the vertices in the opposite order. This essentially checks backfaces by
// checking reversed frontfaces
currentBackFace = Min(backFaceDistance > 0.0f ? backFaceDistance : M_INFINITY, currentBackFace);
indices += 3;
}
}
// If the closest face is a backface, that means that the ray originates from the inside of the geometry
// NOTE: there may be cases where both are equal, as in, no collision to either. This is prevented in the most likely case
// (ray doesn't hit either) by this conditional
if (currentFrontFace != M_INFINITY || currentBackFace != M_INFINITY)
return currentBackFace < currentFrontFace;
// It is still possible for two triangles to be equally distant from the triangle, however, this is extremely unlikely.
// As such, it is safe to assume they are not
return false;
}
Ray Ray::Transformed(const Matrix3x4& transform) const
{
Ray ret;
ret.origin_ = transform * origin_;
ret.direction_ = transform * Vector4(direction_, 0.0f);
return ret;
}
}
| 38.475 | 133 | 0.579164 | [
"geometry",
"transform"
] |
c82032d149edce4dc4b6e5895e0ac938fbb7d66f | 12,111 | hpp | C++ | src/common/PropertySet.hpp | maujin111/Dotto | dd7c2a6a76d9b0d5cea632ed84fb9237a6741482 | [
"MIT"
] | 151 | 2021-12-28T21:22:42.000Z | 2022-03-30T13:53:28.000Z | src/common/PropertySet.hpp | maujin111/Dotto | dd7c2a6a76d9b0d5cea632ed84fb9237a6741482 | [
"MIT"
] | 9 | 2021-12-29T13:20:00.000Z | 2022-03-18T12:47:19.000Z | src/common/PropertySet.hpp | maujin111/Dotto | dd7c2a6a76d9b0d5cea632ed84fb9237a6741482 | [
"MIT"
] | 18 | 2021-12-28T19:58:49.000Z | 2022-03-31T16:38:14.000Z | // Copyright (c) 2021 LibreSprite Authors (cf. AUTHORS.md)
// This file is released under the terms of the MIT license.
// Read LICENSE.txt for more information.
#pragma once
#include <type_traits>
#include <common/inject.hpp>
#include <common/String.hpp>
#include <common/Value.hpp>
#include <log/Log.hpp>
class PropertySet {
friend class Serializable;
mutable HashMap<String, std::shared_ptr<Value>> properties;
static inline bool debug = false;
public:
PropertySet() = default;
PropertySet(const PropertySet& other) = default;
PropertySet(PropertySet&& other) : properties{std::move(other.properties)} {}
PropertySet(const std::initializer_list<std::pair<String, Value>>& args) {
for (auto& entry : args) {
set(entry.first, entry.second);
}
}
void print() const {
for (auto& entry : properties) {
logI("[", entry.first, "] = [", entry.second->toString(), "]");
}
}
std::size_t size() const {
return properties.size();
}
const HashMap<String, std::shared_ptr<Value>>& getMap() const {
return properties;
}
HashMap<String, std::shared_ptr<Value>>& getMap() {
return properties;
}
template<typename Type>
static bool assignProperty(Value& from, Type& out) {
if (from.has<Type>()) {
out = from.get<Type>();
return true;
}
if constexpr (std::is_same_v<Type, bool>) {
if (from.has<String>()) {
String str = tolower(from.get<String>());
out = str.size() && (str[0] == 't' || str[0] == 'y');
} else if (from.has<decltype(1)>()) {
out = from.get<decltype(1)>();
} else if (from.has<U32>()) {
out = from.get<U32>();
} else if (from.has<S32>()) {
out = from.get<S32>();
} else if (from.has<U64>()) {
out = from.get<U64>();
} else if (from.has<S64>()) {
out = from.get<S64>();
} else if (from.has<F32>()) {
out = from.get<F32>();
} else if (from.has<F64>()) {
out = from.get<F64>();
} else return false;
} else if constexpr (std::is_integral_v<Type>) {
if (from.has<F32>()) out = from.get<F32>();
else if (from.has<decltype(1)>()) out = from.get<decltype(1)>();
else if (from.has<S32>()) out = from.get<S32>();
else if (from.has<U32>()) out = from.get<U32>();
else if (from.has<U64>()) out = from.get<U64>();
else if (from.has<S64>()) out = from.get<S64>();
else if (from.has<double>()) out = from.get<double>();
else if (from.has<String>()) out = std::atol(from.get<String>().c_str());
else return false;
} else if constexpr (std::is_floating_point_v<Type>) {
if (from.has<F32>()) out = from.get<F32>();
else if (from.has<decltype(1)>()) out = from.get<decltype(1)>();
else if (from.has<S32>()) out = from.get<S32>();
else if (from.has<U32>()) out = from.get<U32>();
else if (from.has<U64>()) out = from.get<U64>();
else if (from.has<S64>()) out = from.get<S64>();
else if (from.has<double>()) out = from.get<double>();
else if (from.has<String>()) out = std::atof(from.get<String>().c_str());
else return false;
} else if constexpr (std::is_constructible_v<Type, std::shared_ptr<Value>>) {
out = Type{from};
} else if constexpr (std::is_assignable_v<Type, std::shared_ptr<Value>>) {
out = Type{from};
} else if constexpr (std::is_assignable_v<Type, String>) {
if (from.has<String>()) out = from.get<String>();
else if (from.has<F32>()) out = tostring(from.get<F32>());
else if (from.has<decltype(1)>()) out = std::to_string(from.get<decltype(1)>());
else if (from.has<S32>()) out = std::to_string(from.get<S32>());
else if (from.has<U32>()) out = std::to_string(from.get<U32>());
else if (from.has<U64>()) out = std::to_string(from.get<U64>());
else if (from.has<S64>()) out = std::to_string(from.get<S64>());
else if (from.has<double>()) out = std::to_string(from.get<double>());
else if (from.has<bool>()) out = String(from.get<bool>() ? "true" : "false");
else return false;
} else if constexpr (std::is_constructible_v<Type, String>) {
if (!from.has<String>())
return false;
out = Type{from.get<String>()};
} else if constexpr (std::is_assignable_v<Type, Value>) {
out = from;
} else if constexpr (std::is_constructible_v<Type, Value>) {
out = Type{from};
} else {
return false;
}
from = out;
return true;
}
template<typename Type>
bool get(const String& key, Type& out) const {
auto it = properties.find(key);
if (it == properties.end())
it = properties.find(tolower(key));
if (it == properties.end())
return false;
bool success = assignProperty(*it->second, out);
if (!success && debug)
logE("Could not assign ", it->second->typeName(), " to ", typeid(Type).name());
return success;
}
template<typename Type>
Type get(const String& key) const {
Type value{};
get(key, value);
return value;
}
template<typename Type>
void set(const String& key, Type&& value) {
auto it = properties.find(key);
if (it == properties.end()) {
properties.insert({key, std::make_shared<Value>(std::forward<Type>(value))});
} else {
*it->second = value;
}
}
template<typename Type>
void push(Type&& value) {
auto key = std::to_string(size());
auto it = properties.find(key);
if (it == properties.end()) {
properties.insert({key, std::make_shared<Value>(std::forward<Type>(value))});
} else {
*it->second = value;
}
}
void append(const PropertySet& other) {
for (auto& entry : other.properties) {
properties.insert_or_assign(entry.first, entry.second);
}
}
void prepend(const PropertySet& other) {
for (auto& entry : other.properties) {
properties.insert({entry.first, entry.second});
}
}
void append(std::shared_ptr<PropertySet> other) {
if (other)
append(*other);
}
void prepend(std::shared_ptr<PropertySet> other) {
if (other)
prepend(*other);
}
};
class Serializable {
struct PropertySerializer {
void* property;
const String* key;
std::function<void()>* (*load)(void* property, Value&);
void (*store)(void* property, PropertySet&);
};
Vector<PropertySerializer> propertySerializers;
public:
virtual ~Serializable() {}
template<typename _Type, bool Debug = false>
class Property {
public:
using Type = _Type;
Type value;
const String name;
std::function<void()> change;
template<typename ParentType, typename InitType = Type>
Property(ParentType* parent, const String& name, InitType&& value = InitType{}, void (ParentType::*change)() = nullptr) : name{name}, value(std::forward<InitType>(value)) {
if (change) {
this->change = [=]{(parent->*change)();};
}
parent->propertySerializers.push_back(PropertySerializer{
this,
&this->name,
+[](void* data, Value& value) {
auto prop = static_cast<Property<Type>*>(data);
auto oldValue = prop->value;
bool didAssign = PropertySet::assignProperty(value, prop->value);
bool didChange = !(prop->value == oldValue);
#ifdef _DEBUG
if (Debug || PropertySet::debug) {
if (!didAssign)
logE("Assign to ", prop->name, ": Could not assign ", value.typeName(), " to ", typeid(Type).name());
else if (!didChange)
logE("Assign to ", prop->name, ": Value did not change (", value.toString(), ")");
else if (!prop->change)
logE("Assign to ", prop->name, ": No trigger");
else
logE("Assign to ", prop->name, ": triggered");
}
#endif
return (didAssign && prop->change && didChange) ? &prop->change : nullptr;
},
+[](void* data, PropertySet& set) {
auto prop = static_cast<Property<Type>*>(data);
set.set(prop->name, prop->value);
}
});
}
Type& operator * () {
return value;
}
const Type* operator -> () {
return &value;
}
operator const Type& () {
return value;
}
};
public:
void set(const String& key, const Value& value, bool debug = false) {
Value copy = value;
set(key, copy, debug);
}
virtual void set(const String& key, Value& value, bool debug = false) {
PropertySet::debug = debug;
for (auto& serializer : propertySerializers) {
if (key == *serializer.key) {
if (auto trigger = serializer.load(serializer.property, value)) {
(*trigger)();
}
return;
}
}
#ifdef _DEBUG
if (debug) {
logI("Could not set ", key, " to [", value.toString(), "]");
}
#endif
}
virtual void load(const PropertySet& set) {
Vector<std::function<void()>*> queue;
for (auto& serializer : propertySerializers) {
auto it = set.properties.find(*serializer.key);
if (it != set.properties.end()) {
if (auto trigger = serializer.load(serializer.property, *it->second)) {
queue.push_back(trigger);
}
}
}
for (auto trigger : queue) {
(*trigger)();
}
}
void store(PropertySet& set) {
for (auto& serializer : propertySerializers) {
serializer.store(serializer.property, set);
}
}
const Vector<String> getPropertyNames() {
Vector<String> names;
names.resize(propertySerializers.size());
for (auto& serializer : propertySerializers)
names.push_back(*serializer.key);
return names;
}
};
class Model : public Serializable {
PropertySet model;
protected:
void loadSilent(const PropertySet& set) {
if (&set != &model)
model.append(set);
}
public:
void load(const PropertySet& set) {
loadSilent(set);
Serializable::load(set);
}
std::shared_ptr<Value> get(const String& key) {
auto& map = model.getMap();
auto it = map.find(key);
if (it == map.end())
return nullptr;
return it->second;
}
void set(const String& key, const Value& value, bool debug = false) {
Value copy = value;
set(key, copy, debug);
}
void set(const String& key, Value& value, bool debug = false) {
model.set(key, value);
Serializable::set(key, value, debug);
}
const PropertySet& getPropertySet() const {
return model;
}
};
class InjectableModel : public Model,
public Injectable<InjectableModel>,
public std::enable_shared_from_this<InjectableModel> {
public:
};
| 34.115493 | 180 | 0.518537 | [
"vector",
"model"
] |
c82a0ed91867b8aee551e63bad1c93df5bd496c7 | 1,076 | hpp | C++ | raptor/krylov/bicgstab.hpp | lukeolson/raptor | 526c88d0801634e6fb41375ae077f2d4aa3241a4 | [
"BSD-2-Clause"
] | 25 | 2017-11-20T21:45:43.000Z | 2019-01-27T15:03:25.000Z | raptor/krylov/bicgstab.hpp | lukeolson/raptor | 526c88d0801634e6fb41375ae077f2d4aa3241a4 | [
"BSD-2-Clause"
] | 3 | 2017-11-21T01:20:20.000Z | 2018-11-16T17:33:06.000Z | raptor/krylov/bicgstab.hpp | lukeolson/raptor | 526c88d0801634e6fb41375ae077f2d4aa3241a4 | [
"BSD-2-Clause"
] | 5 | 2017-11-20T22:03:57.000Z | 2018-12-05T10:30:22.000Z | #ifndef RAPTOR_KRYLOV_BICGSTAB_HPP
#define RAPTOR_KRYLOV_BICGSTAB_HPP
#include "core/types.hpp"
#include "core/matrix.hpp"
#include "core/vector.hpp"
#include <vector>
using namespace raptor;
void BiCGStab(CSRMatrix* A, Vector& x, Vector& b, std::vector<double>& res, double tol = 1e-05, int max_iter = -1);
void test(CSRMatrix* A, Vector& x, Vector&b, std::vector<double>& res, std::vector<double>& Apr_list,
std::vector<double>& alpha_list, std::vector<double>& Ass_list, std::vector<double>& AsAs_list,
std::vector<double>& omega_list, std::vector<double>& rr_list, std::vector<double>& beta_list,
std::vector<double>& norm_list, double tol=1e-05, int max_iter = -1);
void Test_BiCGStab(CSRMatrix* A, Vector& x, Vector& b, std::vector<double>& res, std::vector<double>& Apr_list,
std::vector<double>& alpha_list, std::vector<double>& Ass_list, std::vector<double>& AsAs_list,
std::vector<double>& omega_list, std::vector<double>& rr_list, std::vector<double>& beta_list,
std::vector<double>& norm_list, double tol = 1e-05, int max_iter = -1);
#endif
| 43.04 | 115 | 0.723978 | [
"vector"
] |
c82a714b6736fbda3304a5a994479c54da8c1c76 | 3,955 | cpp | C++ | src/httpc/request.cpp | igagis/httpcpp | 723fa19399d38880b7c43d295383982f4f005f77 | [
"MIT"
] | 1 | 2021-02-03T07:35:42.000Z | 2021-02-03T07:35:42.000Z | src/httpc/request.cpp | igagis/httpcpp | 723fa19399d38880b7c43d295383982f4f005f77 | [
"MIT"
] | 1 | 2020-12-07T16:04:13.000Z | 2020-12-07T16:04:13.000Z | src/httpc/request.cpp | igagis/httpcpp | 723fa19399d38880b7c43d295383982f4f005f77 | [
"MIT"
] | 1 | 2020-12-15T01:48:55.000Z | 2020-12-15T01:48:55.000Z | /*
MIT License
Copyright (c) 2020-2021 Ivan Gagis
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/* ================ LICENSE END ================ */
#include "request.hpp"
#include "init_guard.hpp"
#include <curl/curl.h>
using namespace httpc;
size_t request::write_data(void *buffer, size_t size, size_t nmemb, void *userp){
ASSERT(userp)
auto r = reinterpret_cast<request*>(userp);
auto s = utki::make_span(reinterpret_cast<uint8_t*>(buffer), nmemb);
if(r->data_handler){
return r->data_handler(s);
}else{
r->resp.body.reserve(r->resp.body.size() + s.size());
r->resp.body.insert(r->resp.body.end(), s.begin(), s.end());
return s.size();
}
}
request::request(decltype(completed_handler)&& ch) :
CURL_handle(curl_easy_init()),
completed_handler(std::move(ch))
{
// curl_easy_setopt(this->handle, CURLOPT_VERBOSE, 1);
curl_easy_setopt(this->CURL_handle, CURLOPT_WRITEFUNCTION, &write_data);
curl_easy_setopt(this->CURL_handle, CURLOPT_WRITEDATA, this);
}
request::~request()noexcept{
ASSERT(this->is_idle)
curl_easy_cleanup(this->CURL_handle);
this->free_headers();
}
void request::start(){
if(!this->is_idle){
throw std::logic_error("request is already running");
}
this->is_idle = false; // this should go before start_request()
init_guard::inst().start_request(this->shared_from_this());
}
bool request::cancel()noexcept{
return init_guard::inst().cancel_request(*this);
}
void request::set_url(const std::string& url){
if(!this->is_idle){
throw std::logic_error("could not set request URL: request is running");
}
curl_easy_setopt(this->CURL_handle, CURLOPT_URL, url.c_str());
}
void request::set_data_handler(decltype(data_handler)&& handler){
if(!this->is_idle){
throw std::logic_error("could not set request data handler: request is running");
}
this->data_handler = std::move(handler);
}
void request::free_headers()noexcept{
ASSERT(this->is_idle)
if(this->curl_slist_handle){
curl_slist_free_all(reinterpret_cast<curl_slist*>(this->curl_slist_handle));
}
}
void request::set_headers(const std::map<std::string, std::string>& name_value, utki::span<const std::string> name){
curl_easy_setopt(this->CURL_handle, CURLOPT_HTTPHEADER, nullptr);
this->free_headers();
this->curl_slist_handle = nullptr; // curl_slist_append() creates a new curl_slist object when nullptr is passed as firsdt argument
for(auto& nv : name_value){
std::stringstream ss;
ss << nv.first << ":";
if(!nv.second.empty()){
ss << " " << nv.second;
}
auto res = curl_slist_append(reinterpret_cast<curl_slist*>(this->curl_slist_handle), ss.str().c_str());
if(res){
this->curl_slist_handle = res;
}
}
for(auto& n : name){
std::stringstream ss;
ss << n << ";";
auto res = curl_slist_append(reinterpret_cast<curl_slist*>(this->curl_slist_handle), ss.str().c_str());
if(res){
this->curl_slist_handle = res;
}
}
curl_easy_setopt(this->CURL_handle, CURLOPT_HTTPHEADER, this->curl_slist_handle);
}
| 30.658915 | 132 | 0.732743 | [
"object"
] |
c82e45f2ba237e0624912981fadfcd0da05c2a1e | 7,834 | cpp | C++ | Arrow.cpp | victorgscorreia/Evolutivos | c0fa63b5451af353ed9ac25a1f401b06d44f469e | [
"MIT"
] | null | null | null | Arrow.cpp | victorgscorreia/Evolutivos | c0fa63b5451af353ed9ac25a1f401b06d44f469e | [
"MIT"
] | null | null | null | Arrow.cpp | victorgscorreia/Evolutivos | c0fa63b5451af353ed9ac25a1f401b06d44f469e | [
"MIT"
] | null | null | null | #include "Arrow.h"
/*
Construtor da classe arrow
@PARAMETROS
coordenadas* coord - endereco do vetor com os vertices para serem envidos a GPU
int vertice_inicial - posicao do vertice inical no vetor de vertices
int num_vertices - numero de vertices da figura
double x - posicao no eixo x da flecha
double y - posicao no eixo y da flecha
double tx - translacao em x
double ty - translacao em y
double s - escala da flecha
double theta - algulo de lancamento da flecha
double velocity - velocidade inical da flecha
double gravity - velocidade da gravidade sobre a flecha
Target* targetLocal - referencia para o alvo
Obstacle* obstacle - referencia para o obstaculo
OBS: alterar os parametro de translacao e escala nao alteram as propriedades da flecha na simulacao
somente de forma visual.
*/
Arrow::Arrow(coordenadas* vertices, int vertice_inicial, int num_vertices, double x, double y, double tx, double ty, double s, double theta, const double velocity, double gravity, Target* targetLocal, Obstacle* obstacle) : Object(vertice_inicial, num_vertices, x, y, tx, ty, s, theta)
{
this->initX = tx;
this->initY = ty;
this->targetLocal = targetLocal;
this->obstacle = obstacle;
this->gravity = gravity*(-1);
this->xColision = 1;
this->velocityX = velocity*cos(theta);
this->velocityY = velocity*sin(theta);
this->status = false;
this->time = 0;
// calcula a colisao com o obstaculo
double xObstacle = obstacle->getX();
double timeColisionObstacle = ((xObstacle-this->initX)/velocityX);
double yObstacle = this->initY+(this->velocityY*timeColisionObstacle)+((this->gravity*(timeColisionObstacle*timeColisionObstacle))/2);
int hit = this->obstacle->checkColision(yObstacle);
if(hit){
this->xColision = xObstacle;
this->score = 0;
}
// caso nao tenha colidido com o obstaculo calcula a colisao com o alvo
else
{
double xTarget = targetLocal->getX();
double timeColisionTarget = ((xTarget-this->initX)/velocityX);
double yTarget = this->initY+(this->velocityY*timeColisionTarget)+((this->gravity*(timeColisionTarget*timeColisionTarget))/2);
this->score = this->targetLocal->checkColision(yTarget);
if (this->score > 0)
{
this->xColision = xTarget;
}
}
// adiciona os pontos ao vetor
int atual = this->vertice_inicial;
//Ponta
vertices[atual].x = 0.00f;
vertices[atual].y = 0.00f;
atual++;
vertices[atual].x = -0.20f;
vertices[atual].y = 0.06f;
atual++;
vertices[atual].x = -0.20f;
vertices[atual].y = -0.06f;
atual++;
//Corpo
vertices[atual].x = -0.50f;
vertices[atual].y = 0.010f;
atual++;
vertices[atual].x = -0.20f;
vertices[atual].y = 0.010f;
atual++;
vertices[atual].x = -0.50f;
vertices[atual].y = -0.010f;
atual++;
vertices[atual].x = -0.20f;
vertices[atual].y = -0.010f;
atual++;
//Rabiola
vertices[atual].x = -0.55f;
vertices[atual].y = 0.00f;
atual++;
vertices[atual].x = -0.60f;
vertices[atual].y = 0.04f;
atual++;
vertices[atual].x = -0.50f;
vertices[atual].y = 0.04f;
atual++;
vertices[atual].x = -0.45f;
vertices[atual].y = 0.01f;
atual++;
vertices[atual].x = -0.45f;
vertices[atual].y = -0.01f;
atual++;
vertices[atual].x = -0.50f;
vertices[atual].y = -0.04f;
atual++;
vertices[atual].x = -0.60f;
vertices[atual].y = -0.04f;
atual++;
this->num_vertices = atual - this->vertice_inicial;
return;
}
Arrow::~Arrow()
{
return;
}
/*
Desenha o objeto na tela. Cria a matriz de transformacao e faz
chamadas ao openGL para desenha o objeto na tela
@PARAMETROS
GLint loc_color - variavel associada a variavel color na GPU
GLint loc_matriz - variavel associada a variavel matriz na GPU
@RETORNO
int ret - 0 funcao finalizada com sucesso
*/
int Arrow::draw(GLint loc_color, GLint loc_matriz)
{
matriz_transformacao_objeto(loc_matriz);
int atual = this->vertice_inicial;
glUniform4f(loc_color, 184.0/256.0, 184.0/256.0, 184.0/256.0, 1);
desenha_triangulo(atual);
atual += 3;
glUniform4f(loc_color, 158.0/256.0, 132.0/256.0, 90.0/256.0, 1);
desenha_quadrado(atual);
atual += 4;
glUniform4f(loc_color, 1, 0, 0, 1);
desenha_circulo(atual, 7);
return 0;
}
/*
Dado um tempo, a funcao arruma a posicao da flecha para e passdos esse tempo
na animacao
@PARAMETROS
double time - tempo para a flecha avancar na animacao
*/
void Arrow::Move(const double time)
{
double time_temp;
//verifica se a flecha ja colidiu
if (GetStatus())
{
this->time += time;
return;
}
// adiciona o tempo para a flecha
this->time += time;
time_temp = this->time;
//calcula a nova posicao em x
this->tx = this->initX+this->velocityX*this->time;
//verifica se colidiu com o alvo
if (this->tx > this->xColision)
{
this->tx = this->xColision;
//calculando ty baseado no tx
time_temp = (this->tx - this->initX)/this->velocityX;
this->status = true;
}
//verifica se colidiu com o chao
else if(this->ty <= -1)
{
this->ty = -1;
this->status = true;
}
// calcula y
this->ty = this->velocityY*time_temp + ((this->gravity*(time_temp*time_temp))/2) + this->initY;
// faz o calculo do angulo da flecha no ponto
double tangente = (this->velocityY + (this->gravity*this->tx) - (this->gravity*this->initX))/this->velocityX;
this->theta = atan(tangente);
return;
}
/*
Atualiza a flecha para uma nova flecha, tambem reinicia os valores de sua animacao
@RETORNO
double theta - valor do angulo da nova flecha
double velocity - valor da velocidada inicial da nova flecha
*/
void Arrow::Update(double theta, double velocity){
this->tx = this->initX;
this->ty = this->initY;
this->velocityX = velocity*cos(theta);
this->velocityY = velocity*sin(theta);
this->status = false;
this->time = 0;
this->xColision = 1;
double xObstacle = obstacle->getX();
// calcula a colisao com o obstaculo
double timeColisionObstacle = ((xObstacle-this->initX)/velocityX);
double yObstacle = this->initY+(this->velocityY*timeColisionObstacle)+((this->gravity*(timeColisionObstacle*timeColisionObstacle))/2);
int hit = this->obstacle->checkColision(yObstacle);
if(hit)
{
this->xColision = xObstacle;
this->score = 0;
}
// caso nao tenha colidido com o obstaculo calcula a colisao com o alvo
else
{
double xTarget = targetLocal->getX();
double timeColisionTarget = ((xTarget-this->initX)/velocityX);
double yTarget = this->initY+(this->velocityY*timeColisionTarget)+((this->gravity*(timeColisionTarget*timeColisionTarget))/2);
this->score = this->targetLocal->checkColision(yTarget);
if (this->score > 0)
{
this->xColision = xTarget;
}
}
return;
}
/*
Retorna o status da flecha na animacao, se ela colidiu ou nao
@RETORNO
bool status -
true - se colidiu
false - se nao colidiu
*/
bool Arrow::GetStatus()
{
return this->status;
}
/*
O valor da pontuacao feita pela flecha
@RETORNO
double score - pontuacao feita pela flecha
*/
double Arrow::GetScore()
{
return this->score;
}
/*
O valor do x duratande a colicao da flecha
@RETORNO
double x - coordenada x da colisao
*/
double Arrow::GetXColision()
{
return this->xColision;
} | 26.828767 | 284 | 0.628287 | [
"object"
] |
c835093ab8af13fca3b3d8a0dbfc85904940e7ba | 8,642 | cpp | C++ | src/Omega_h_coarsen.cpp | overfelt/omega_h | dfc19cc3ea0e183692ca6c548dda39f7892301b5 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | src/Omega_h_coarsen.cpp | overfelt/omega_h | dfc19cc3ea0e183692ca6c548dda39f7892301b5 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | src/Omega_h_coarsen.cpp | overfelt/omega_h | dfc19cc3ea0e183692ca6c548dda39f7892301b5 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | #include "Omega_h_coarsen.hpp"
#include <iostream>
#include <cstdlib>
#include "Omega_h_array_ops.hpp"
#include "Omega_h_collapse.hpp"
#include "Omega_h_for.hpp"
#include "Omega_h_indset.hpp"
#include "Omega_h_map.hpp"
#include "Omega_h_mesh.hpp"
#include "Omega_h_modify.hpp"
#include "Omega_h_transfer.hpp"
#include "Omega_h_verify.hpp"
namespace Omega_h {
static Read<I8> get_edge_codes(Mesh* mesh) {
auto edge_cand_codes = mesh->get_array<I8>(EDGE, "collapse_code");
mesh->remove_tag(EDGE, "collapse_code");
return edge_cand_codes;
}
static void put_edge_codes(Mesh* mesh, LOs cands2edges, Read<I8> cand_codes) {
auto edge_codes =
map_onto(cand_codes, cands2edges, mesh->nedges(), I8(DONT_COLLAPSE), 1);
mesh->add_tag(EDGE, "collapse_code", 1, edge_codes);
}
static bool coarsen_element_based1(Mesh* mesh) {
auto comm = mesh->comm();
auto edge_cand_codes = get_edge_codes(mesh);
auto edges_are_cands = each_neq_to(edge_cand_codes, I8(DONT_COLLAPSE));
auto cands2edges = collect_marked(edges_are_cands);
auto cand_codes = read(unmap(cands2edges, edge_cand_codes, 1));
cand_codes = check_collapse_class(mesh, cands2edges, cand_codes);
/* edge and endpoints classification check */
if (get_max(comm, cand_codes) <= DONT_COLLAPSE) return false;
put_edge_codes(mesh, cands2edges, cand_codes);
return true;
}
static void filter_coarsen_candidates(
LOs* cands2edges, Read<I8>* cand_codes, Reals* cand_quals = nullptr) {
auto keep = each_neq_to(*cand_codes, I8(DONT_COLLAPSE));
auto new2old = collect_marked(keep);
*cands2edges = unmap(new2old, *cands2edges, 1);
*cand_codes = unmap(new2old, *cand_codes, 1);
if (cand_quals) *cand_quals = unmap(new2old, *cand_quals, 2);
}
enum OvershootLimit { DESIRED, ALLOWED };
enum Improve { DONT_IMPROVE, IMPROVE_LOCALLY };
static bool coarsen_ghosted(Mesh* mesh, AdaptOpts const& opts,
OvershootLimit overshoot, Improve improve) {
auto comm = mesh->comm();
auto edge_cand_codes = get_edge_codes(mesh);
auto edges_are_cands = each_neq_to(edge_cand_codes, I8(DONT_COLLAPSE));
auto cands2edges = collect_marked(edges_are_cands);
auto cand_edge_codes = read(unmap(cands2edges, edge_cand_codes, 1));
/* surface exposure (classification) checks */
cand_edge_codes = check_collapse_exposure(mesh, cands2edges, cand_edge_codes);
filter_coarsen_candidates(&cands2edges, &cand_edge_codes);
/* edge length overshoot check */
auto max_length = (overshoot == DESIRED) ? opts.max_length_desired
: opts.max_length_allowed;
cand_edge_codes =
prevent_coarsen_overshoot(mesh, max_length, cands2edges, cand_edge_codes);
filter_coarsen_candidates(&cands2edges, &cand_edge_codes);
if (comm->reduce_and(cands2edges.size() == 0)) return false;
if (opts.should_prevent_coarsen_flip) {
cand_edge_codes = prevent_coarsen_flip(mesh, cands2edges, cand_edge_codes);
filter_coarsen_candidates(&cands2edges, &cand_edge_codes);
if (comm->reduce_and(cands2edges.size() == 0)) return false;
}
/* cavity quality checks */
auto cand_edge_quals = coarsen_qualities(mesh, cands2edges, cand_edge_codes);
cand_edge_codes = filter_coarsen_min_qual(
cand_edge_codes, cand_edge_quals, opts.min_quality_allowed);
if (improve == IMPROVE_LOCALLY) {
cand_edge_codes = filter_coarsen_improve(
mesh, cands2edges, cand_edge_codes, cand_edge_quals);
}
filter_coarsen_candidates(&cands2edges, &cand_edge_codes, &cand_edge_quals);
/* finished cavity quality checks */
if (comm->reduce_and(cands2edges.size() == 0)) return false;
auto verts_are_cands = Read<I8>();
auto vert_quals = Reals();
auto vert_rails = Read<GO>();
choose_rails(mesh, cands2edges, cand_edge_codes, cand_edge_quals,
&verts_are_cands, &vert_quals, &vert_rails);
auto verts_are_keys = find_indset(mesh, VERT, vert_quals, verts_are_cands);
Graph verts2cav_elems;
verts2cav_elems = mesh->ask_up(VERT, mesh->dim());
mesh->add_tag(VERT, "key", 1, verts_are_keys);
mesh->add_tag(VERT, "collapse_quality", 1, vert_quals);
mesh->add_tag(VERT, "collapse_rail", 1, vert_rails);
auto keys2verts = collect_marked(verts_are_keys);
set_owners_by_indset(mesh, VERT, keys2verts, verts2cav_elems);
return true;
}
static void coarsen_element_based2(Mesh* mesh, AdaptOpts const& opts) {
auto comm = mesh->comm();
auto verts_are_keys = mesh->get_array<I8>(VERT, "key");
auto vert_quals = mesh->get_array<Real>(VERT, "collapse_quality");
auto vert_rails = mesh->get_array<GO>(VERT, "collapse_rail");
mesh->remove_tag(VERT, "collapse_rail");
auto keys2verts = collect_marked(verts_are_keys);
auto nkeys = keys2verts.size();
if (opts.verbosity >= EACH_REBUILD) {
auto ntotal_keys = comm->allreduce(GO(nkeys), OMEGA_H_SUM);
if (comm->rank() == 0) {
std::cout << "coarsening " << ntotal_keys << " vertices\n";
}
}
auto rails2edges = LOs();
auto rail_col_dirs = Read<I8>();
find_rails(mesh, keys2verts, vert_rails, &rails2edges, &rail_col_dirs);
auto dead_ents = mark_dead_ents(mesh, rails2edges, rail_col_dirs);
auto keys2verts_onto = get_verts_onto(mesh, rails2edges, rail_col_dirs);
auto new_mesh = mesh->copy_meta();
auto old_verts2new_verts = LOs();
auto old_lows2new_lows = LOs();
for (Int ent_dim = 0; ent_dim <= mesh->dim(); ++ent_dim) {
auto keys2prods = LOs();
auto prod_verts2verts = LOs();
auto keys2doms = Adj();
if (ent_dim == VERT) {
keys2prods = LOs(nkeys + 1, 0);
} else {
keys2doms =
find_coarsen_domains(mesh, keys2verts, ent_dim, dead_ents[ent_dim]);
keys2prods = keys2doms.a2ab;
prod_verts2verts = coarsen_topology(
mesh, keys2verts_onto, ent_dim, keys2doms, old_verts2new_verts);
}
auto prods2new_ents = LOs();
auto same_ents2old_ents = LOs();
auto same_ents2new_ents = LOs();
auto old_ents2new_ents = LOs();
modify_ents_adapt(mesh, &new_mesh, ent_dim, VERT, keys2verts, keys2prods,
prod_verts2verts, old_lows2new_lows, &prods2new_ents,
&same_ents2old_ents, &same_ents2new_ents, &old_ents2new_ents);
if (ent_dim == VERT) {
old_verts2new_verts = old_ents2new_ents;
}
transfer_coarsen(mesh, opts.xfer_opts, &new_mesh, keys2verts, keys2doms,
ent_dim, prods2new_ents, same_ents2old_ents, same_ents2new_ents);
old_lows2new_lows = old_ents2new_ents;
}
*mesh = new_mesh;
}
static bool coarsen(Mesh* mesh, AdaptOpts const& opts, OvershootLimit overshoot,
Improve improve) {
begin_code("coarsen");
auto ret = coarsen_element_based1(mesh);
if (ret) {
mesh->set_parting(OMEGA_H_GHOSTED);
ret = coarsen_ghosted(mesh, opts, overshoot, improve);
}
if (ret) {
mesh->set_parting(OMEGA_H_ELEM_BASED, false);
coarsen_element_based2(mesh, opts);
}
end_code();
return ret;
}
static bool coarsen_verts(Mesh* mesh, AdaptOpts const& opts,
Read<I8> vert_marks, OvershootLimit overshoot, Improve improve) {
auto ev2v = mesh->ask_verts_of(EDGE);
Write<I8> edge_codes_w(mesh->nedges(), DONT_COLLAPSE);
auto f = OMEGA_H_LAMBDA(LO e) {
I8 code = DONT_COLLAPSE;
for (Int eev = 0; eev < 2; ++eev) {
if (vert_marks[ev2v[e * 2 + eev]]) {
code = do_collapse(code, eev);
}
}
edge_codes_w[e] = code;
};
parallel_for(mesh->nedges(), f, "coarsen_verts(edge_codes)");
mesh->add_tag(EDGE, "collapse_code", 1, Read<I8>(edge_codes_w));
return coarsen(mesh, opts, overshoot, improve);
}
static bool coarsen_ents(Mesh* mesh, AdaptOpts const& opts, Int ent_dim,
Read<I8> marks, OvershootLimit overshoot, Improve improve) {
auto vert_marks = mark_down(mesh, ent_dim, VERT, marks);
return coarsen_verts(mesh, opts, vert_marks, overshoot, improve);
}
bool coarsen_by_size(Mesh* mesh, AdaptOpts const& opts) {
begin_code("coarsen_by_size");
auto comm = mesh->comm();
auto lengths = mesh->ask_lengths();
auto edge_is_cand = each_lt(lengths, opts.min_length_desired);
auto ret = (get_max(comm, edge_is_cand) == 1);
if (ret) {
ret = coarsen_ents(mesh, opts, EDGE, edge_is_cand, DESIRED, DONT_IMPROVE);
}
end_code();
return ret;
}
bool coarsen_slivers(Mesh* mesh, AdaptOpts const& opts) {
begin_code("coarsen_slivers");
mesh->set_parting(OMEGA_H_GHOSTED);
auto comm = mesh->comm();
auto elems_are_cands =
mark_sliver_layers(mesh, opts.min_quality_desired, opts.nsliver_layers);
OMEGA_H_CHECK(get_max(comm, elems_are_cands) == 1);
auto ret = coarsen_ents(
mesh, opts, mesh->dim(), elems_are_cands, ALLOWED, IMPROVE_LOCALLY);
end_code();
return ret;
}
} // end namespace Omega_h
| 38.580357 | 80 | 0.720204 | [
"mesh"
] |
c835d7f7553dc6820dfbd67bce00e39494ca9ebf | 3,840 | cpp | C++ | EzAcc/DemoProject/Input Combos/Motor2D/ctGui.cpp | Wilhelman/EzAcc-EasyAccessibilityFramework | d785c5f9c36367f6da7a89d10b1b80bd8b382173 | [
"MIT"
] | null | null | null | EzAcc/DemoProject/Input Combos/Motor2D/ctGui.cpp | Wilhelman/EzAcc-EasyAccessibilityFramework | d785c5f9c36367f6da7a89d10b1b80bd8b382173 | [
"MIT"
] | null | null | null | EzAcc/DemoProject/Input Combos/Motor2D/ctGui.cpp | Wilhelman/EzAcc-EasyAccessibilityFramework | d785c5f9c36367f6da7a89d10b1b80bd8b382173 | [
"MIT"
] | null | null | null | #include "ctDefs.h"
#include "ctLog.h"
#include "ctApp.h"
#include "ctRender.h"
#include "ctTextures.h"
//#include "ctFonts.h"
#include "ctInput.h"
#include "ctGui.h"
#include "UILabel.h"
#include "UIImage.h"
#include "UIButton.h"
#include "UIElement.h"
ctGui::ctGui() : ctModule()
{
name = "gui";
}
// Destructor
ctGui::~ctGui()
{}
// Called before render is available
bool ctGui::Awake(pugi::xml_node& conf)
{
LOG("Loading GUI atlas");
bool ret = true;
atlas_file_name = conf.child("atlas").attribute("file").as_string("");
return ret;
}
// Called before the first frame
bool ctGui::Start()
{
//atlas = App->tex->Load(atlas_file_name.c_str()nullptr);
return true;
}
// Update all guis
bool ctGui::PreUpdate()
{
for (int i = 0; i < ui_elements.capacity(); i++)
if (ui_elements.at(i) != nullptr) ui_elements[i]->Update();
return true;
}
// Called after all Updates
bool ctGui::PostUpdate()
{
for (int i = 0; i < ui_elements.capacity(); i++)
if (ui_elements.at(i) != nullptr) ui_elements[i]->Draw(atlas);
for (int i = 0; i < ui_elements.capacity(); i++) {
if (ui_elements[i]->to_destroy) {
delete(ui_elements[i]);
ui_elements[i] = nullptr;
ui_elements.erase(ui_elements.cbegin() + i);
ui_elements.shrink_to_fit();
}
}
//LOG("NUM ELEM: %i", ui_elements.size());
return true;
}
// Called before quitting
bool ctGui::CleanUp()
{
LOG("Freeing GUI");
//TODO unload tex
for (uint i = 0; i < ui_elements.capacity(); ++i)
{
if (ui_elements[i] != nullptr)
{
delete ui_elements[i];
ui_elements[i] = nullptr;
ui_elements.erase(ui_elements.cbegin() + i);
ui_elements.shrink_to_fit();
}
}
ui_elements.clear();
return true;
}
// const getter for atlas
const SDL_Texture* ctGui::GetAtlas() const
{
return atlas;
}
bool ctGui::DeleteUIElement(UIElement &element) {
for (int i = 0; i < ui_elements.capacity(); i++) {
if (ui_elements.at(i) == &element) {
ui_elements[i]->to_destroy = true;
return true;
}
}
return false;
}
bool ctGui::DeleteAllUIElements() {
bool ret = false;
for (int i = 0; i < ui_elements.capacity(); i++) {
if (ui_elements.at(i) != nullptr) ui_elements[i]->to_destroy = true;
ret = true;
}
return ret;
}
UIElement* ctGui::AddUIImage(int position_x, int position_y, SDL_Rect rect, ctModule* callback, UIElement* parent) {
UIElement* tmp_img = new UIImage(position_x, position_y, IMAGE, rect, callback, parent);
ui_elements.push_back(tmp_img);
return tmp_img;
LOG("Error: Cant add the UIImage");
return nullptr;
}
UIElement* ctGui::AddUIButton(int position_x, int position_y, SDL_Rect normal_rect, SDL_Rect focused_rect, SDL_Rect pressed_rect, ctModule* callback, UIElement* parent) {
UIElement* tmpBtn = new UIButton(position_x, position_y, BUTTON, normal_rect, focused_rect, pressed_rect, callback, parent);
ui_elements.push_back(tmpBtn);
return tmpBtn;
LOG("Error: Cant add the UIButton");
return nullptr;
}
UIElement* ctGui::AddUILabel(int position_x, int position_y, std::string text, SDL_Color color, UIElement* parent) {
UIElement* tmp_lbl = new UILabel(position_x, position_y, LABEL, text, color, parent);
ui_elements.push_back(tmp_lbl);
return tmp_lbl;
LOG("Error: Cant add the UILabel");
return nullptr;
}
UIElement* ctGui::GetElementUnderMouse(int x, int y)
{
for (int i = ui_elements.capacity() - 1; i >= 0; i--) {
if (ui_elements[i] != nullptr)
{
if ((x > ui_elements[i]->GetScreenPosition().x && x < ui_elements[i]->GetScreenPosition().x + ui_elements[i]->GetRect().w) && (y > ui_elements[i]->GetScreenPosition().y && y < ui_elements[i]->GetScreenPosition().y + ui_elements[i]->GetRect().h))
{
UIElement* tmp_element_to_return = ui_elements[i];
return tmp_element_to_return;
}
}
}
return nullptr;
}
// class Gui ---------------------------------------------------
| 22.196532 | 248 | 0.673698 | [
"render"
] |
c83631cc6eeb362f27a172ee709c14b4b1e3b837 | 4,767 | cc | C++ | third_party/blink/renderer/core/animation/animation_sim_test.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | third_party/blink/renderer/core/animation/animation_sim_test.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | third_party/blink/renderer/core/animation/animation_sim_test.cc | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/public/web/web_script_source.h"
#include "third_party/blink/renderer/core/animation/document_timeline.h"
#include "third_party/blink/renderer/core/animation/keyframe_effect.h"
#include "third_party/blink/renderer/core/animation/keyframe_effect_model.h"
#include "third_party/blink/renderer/core/animation/string_keyframe.h"
#include "third_party/blink/renderer/core/css/css_style_sheet.h"
#include "third_party/blink/renderer/core/css/css_test_helpers.h"
#include "third_party/blink/renderer/core/dom/element.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/web_local_frame_impl.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/testing/sim/sim_compositor.h"
#include "third_party/blink/renderer/core/testing/sim/sim_request.h"
#include "third_party/blink/renderer/core/testing/sim/sim_test.h"
#include "third_party/blink/renderer/platform/heap/garbage_collected.h"
#include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h"
namespace blink {
class AnimationSimTest : public SimTest {};
TEST_F(AnimationSimTest, CustomPropertyBaseComputedStyle) {
// This is a regression test for bug where custom property animations failed
// to disable the baseComputedStyle optimisation. When custom property
// animations are in effect we lose the guarantee that the baseComputedStyle
// optimisation relies on where the non-animated style rules always produce
// the same ComputedStyle. This is not the case if they use var() references
// to custom properties that are being animated.
// The bug was that we never cleared the existing baseComputedStyle during a
// custom property animation so the stale ComputedStyle object would hang
// around and not be valid in the exit frame of the next custom property
// animation.
ScopedWebAnimationsAPIForTest web_animations(true);
SimRequest main_resource("https://example.com/", "text/html");
LoadURL("https://example.com/");
main_resource.Complete("<div id=\"target\"></div>");
Element* target = GetDocument().getElementById("target");
// CSS.registerProperty({
// name: '--x',
// syntax: '<percentage>',
// initialValue: '0%',
// inherits: false
// })
css_test_helpers::RegisterProperty(GetDocument(), "--x", "<percentage>", "0%",
false);
DummyExceptionStateForTesting exception_state;
// target.style.setProperty('--x', '100%');
target->style()->setProperty(GetDocument().GetExecutionContext(), "--x",
"100%", g_empty_string, exception_state);
EXPECT_FALSE(exception_state.HadException());
// target.animate({'--x': '100%'}, 1000);
auto* keyframe = MakeGarbageCollected<StringKeyframe>();
keyframe->SetCSSPropertyValue("--x", "100%", Window().GetSecureContextMode(),
GetDocument().ElementSheet().Contents());
StringKeyframeVector keyframes;
keyframes.push_back(keyframe);
Timing timing;
timing.iteration_duration = ANIMATION_TIME_DELTA_FROM_SECONDS(1);
auto* keyframe_effect = MakeGarbageCollected<KeyframeEffect>(
target, MakeGarbageCollected<StringKeyframeEffectModel>(keyframes),
timing);
target->GetDocument().Timeline().Play(keyframe_effect);
// This sets the baseComputedStyle on the animation exit frame.
Compositor().BeginFrame(1);
Compositor().BeginFrame(1);
// target.style.setProperty('--x', '0%');
target->style()->setProperty(GetDocument().GetExecutionContext(), "--x", "0%",
g_empty_string, exception_state);
EXPECT_FALSE(exception_state.HadException());
// target.animate({'--x': '100%'}, 1000);
keyframe = MakeGarbageCollected<StringKeyframe>();
keyframe->SetCSSPropertyValue("--x", "100%", Window().GetSecureContextMode(),
GetDocument().ElementSheet().Contents());
keyframes.clear();
keyframes.push_back(std::move(keyframe));
timing = Timing();
timing.iteration_duration = ANIMATION_TIME_DELTA_FROM_SECONDS(1);
keyframe_effect = MakeGarbageCollected<KeyframeEffect>(
target, MakeGarbageCollected<StringKeyframeEffectModel>(keyframes),
timing);
target->GetDocument().Timeline().Play(keyframe_effect);
// This (previously) would not clear the existing baseComputedStyle and would
// crash on the equality assertion in the exit frame when it tried to update
// it.
Compositor().BeginFrame(1);
Compositor().BeginFrame(1);
}
} // namespace blink
| 44.971698 | 94 | 0.732326 | [
"object"
] |
c83680e3d766caff033c21890173657a7c580d86 | 12,865 | cpp | C++ | app/src/main/cpp/source/MainApplication.cpp | Mike-meixu/hms-computer-graphics-demo | ebc995429eec10706b93be47a6fef486f70725ba | [
"Apache-2.0"
] | null | null | null | app/src/main/cpp/source/MainApplication.cpp | Mike-meixu/hms-computer-graphics-demo | ebc995429eec10706b93be47a6fef486f70725ba | [
"Apache-2.0"
] | null | null | null | app/src/main/cpp/source/MainApplication.cpp | Mike-meixu/hms-computer-graphics-demo | ebc995429eec10706b93be47a6fef486f70725ba | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) Hisilicon Technologies Co., Ltd. 2020-2020. All rights reserved.
* Description: A sample that illustrates the rendering of a demo scene.
*/
#include "MainApplication.h"
MainApplication::MainApplication() {}
MainApplication::~MainApplication() {}
void MainApplication::Start(void *param)
{
BaseApplication::Start(param);
}
void MainApplication::Initialize(void *winHandle, u32 width, u32 height)
{
BaseApplication::Initialize(winHandle, width, height);
}
void MainApplication::UnInitialize()
{
gSceneManager.DeleteObject(m_sceneObject);
BaseApplication::UnInitialize();
}
void MainApplication::InitScene()
{
LOGINFO("MainApplication InitScene.");
BaseApplication::InitScene();
// add camera
LOGINFO("Enter init main camera.");
SceneObject *cameraObj = CG_NEW SceneObject(nullptr);
if (cameraObj == nullptr) {
LOGERROR("Failed to create camera object.");
return;
}
Camera *mainCamera = cameraObj->AddComponent<Camera>();
if (mainCamera == nullptr) {
CG_SAFE_DELETE(cameraObj);
LOGERROR("Failed to create main camera.");
return;
}
const f32 FOV = 60.f;
const f32 NEAR = 0.1f;
const f32 FAR = 500.0f;
const Vector3 EYE_POSITION(0.0f, 0.0f, 0.0f);
cameraObj->SetPosition(EYE_POSITION);
mainCamera->SetProjectionType(ProjectionType::PROJECTION_TYPE_PERSPECTIVE);
mainCamera->SetProjection(FOV, gCGKitInterface.GetAspectRadio(), NEAR, FAR);
mainCamera->SetViewport(0, 0, gCGKitInterface.GetScreenWidth(), gCGKitInterface.GetScreenHeight());
gSceneManager.SetMainCamera(mainCamera);
LOGINFO("Left init main camera.");
// Load default model
String modelName = "models/Avatar/body.obj";
Model *model = static_cast<Model *>(gResourceManager.Get(modelName));
// Add to scene
MeshRenderer *meshRenderer = nullptr;
SceneObject *object = gSceneManager.CreateSceneObject();
if (object != nullptr) {
meshRenderer = object->AddComponent<MeshRenderer>();
if (meshRenderer != nullptr && model != nullptr && model->GetMesh() != nullptr) {
meshRenderer->SetMesh(model->GetMesh());
} else {
LOGERROR("Failed to add mesh renderer.");
}
} else {
LOGERROR("Failed to create scene object.");
}
if (model != nullptr) {
const Mesh *mesh = model->GetMesh();
if (mesh != nullptr) {
LOGINFO("Model submesh count %d.", mesh->GetSubMeshCount());
LOGINFO("Model vertex count %d.", mesh->GetVertexCount());
// load Texture
String texAlbedo = "models/Avatar/Albedo_01.png";
String texNormal = "models/Avatar/Normal_01.png";
String texPbr = "models/Avatar/Pbr_01.png";
String texEmissive = "shaders/pbr_brdf.png";
u32 subMeshCnt = mesh->GetSubMeshCount();
for (u32 i = 0; i < subMeshCnt; ++i) {
SubMesh *subMesh = mesh->GetSubMesh(i);
if (subMesh == nullptr) {
LOGERROR("Failed to get submesh.");
continue;
}
Material *material =
dynamic_cast<Material *>(gResourceManager.Get(ResourceType::RESOURCE_TYPE_MATERIAL));
if (material == nullptr) {
LOGERROR("Failed to create new material.");
return;
}
material->Init();
material->SetSubMesh(subMesh);
material->SetTexture(TextureType::TEXTURE_TYPE_ALBEDO, texAlbedo);
material->SetSamplerParam(TextureType::TEXTURE_TYPE_ALBEDO,
SAMPLER_FILTER_BILINEAR,
SAMPLER_FILTER_BILINEAR,
SAMPLER_MIPMAP_BILINEAR,
SAMPLER_ADDRESS_CLAMP);
material->SetTexture(TextureType::TEXTURE_TYPE_NORMAL, texNormal);
material->SetSamplerParam(TextureType::TEXTURE_TYPE_NORMAL,
SAMPLER_FILTER_BILINEAR,
SAMPLER_FILTER_BILINEAR,
SAMPLER_MIPMAP_BILINEAR,
SAMPLER_ADDRESS_CLAMP);
material->SetTexture(TextureType::TEXTURE_TYPE_PBRTEXTURE, texPbr);
material->SetSamplerParam(TextureType::TEXTURE_TYPE_PBRTEXTURE,
SAMPLER_FILTER_BILINEAR,
SAMPLER_FILTER_BILINEAR,
SAMPLER_MIPMAP_BILINEAR,
SAMPLER_ADDRESS_CLAMP);
material->SetTexture(TextureType::TEXTURE_TYPE_EMISSION, texEmissive);
material->SetSamplerParam(TextureType::TEXTURE_TYPE_EMISSION,
SAMPLER_FILTER_BILINEAR,
SAMPLER_FILTER_BILINEAR,
SAMPLER_MIPMAP_BILINEAR,
SAMPLER_ADDRESS_CLAMP);
material->SetTexture(TextureType::TEXTURE_TYPE_ENVIRONMENTMAP, m_envMap);
material->SetSamplerParam(TextureType::TEXTURE_TYPE_ENVIRONMENTMAP,
SAMPLER_FILTER_BILINEAR,
SAMPLER_FILTER_BILINEAR,
SAMPLER_MIPMAP_BILINEAR,
SAMPLER_ADDRESS_CLAMP);
material->AttachShaderStage(ShaderStageType::SHADER_STAGE_TYPE_VERTEX, "shaders/pbr_vert.spv");
material->AttachShaderStage(ShaderStageType::SHADER_STAGE_TYPE_FRAGMENT, "shaders/pbr_frag.spv");
material->SetCullMode(CULL_MODE_NONE);
material->SetDepthTestEnable(true);
material->SetDepthWriteEnable(true);
material->Create();
meshRenderer->SetMaterial(i, material);
}
} else {
LOGERROR("Failed to get mesh.");
}
} else {
LOGERROR("Failed to load model.");
}
m_sceneObject = object;
if (m_sceneObject != nullptr) {
m_sceneObject->SetPosition(SCENE_OBJECT_POSITION);
m_sceneObject->SetScale(SCENE_OBJECT_SCALE);
}
m_objectRotation = Math::PI;
// create sky box
SceneObject *skyboxObj = CreateSkybox();
if (skyboxObj != nullptr) {
skyboxObj->SetScale(Vector3(100.f, 100.f, 100.f));
}
// add light
LOGINFO("Enter init light.");
SceneObject *lightObject = CG_NEW SceneObject(nullptr);
if (lightObject != nullptr) {
Light *lightCom = lightObject->AddComponent<Light>();
if (lightCom != nullptr) {
lightCom->SetColor(Vector3::ONE);
const Vector3 DIRECTION_LIGHT_DIR(0.1f, 0.2f, 1.0f);
lightCom->SetDirection(DIRECTION_LIGHT_DIR);
lightCom->SetLightType(LIGHT_TYPE_DIRECTIONAL);
LOGINFO("Left init light.");
} else {
LOGERROR("Failed to add component light.");
}
} else {
LOG_ALLOC_ERROR("New light object failed.");
}
SceneObject *pointLightObject = CG_NEW SceneObject(nullptr);
if (pointLightObject != nullptr) {
m_pointLightObject = pointLightObject;
Light *lightCom = pointLightObject->AddComponent<Light>();
if (lightCom != nullptr) {
const Vector3 POINT_LIGHT_COLOR(0.0, 10000.0f, 10000.0f);
lightCom->SetColor(POINT_LIGHT_COLOR);
lightCom->SetLightType(LIGHT_TYPE_POINT);
} else {
LOGERROR("Failed to add component light.");
}
} else {
LOG_ALLOC_ERROR("New light object failed.");
}
}
void MainApplication::Update(float deltaTime)
{
LOGINFO("Update %f.", deltaTime);
m_deltaTime = deltaTime;
m_deltaAccumulate += m_deltaTime;
if (m_sceneObject != nullptr) {
m_sceneObject->SetRotation(Vector3(0.0, m_objectRotation, 0.0));
m_sceneObject->SetScale(SCENE_OBJECT_SCALE * m_objectScale);
}
const float POINT_HZ_X = 0.2f;
const float POINT_HZ_Y = 0.5f;
const float POINT_LIGHT_CIRCLE = 50.f;
if (m_pointLightObject) {
m_pointLightObject->SetPosition(
Vector3(sin(m_deltaAccumulate * POINT_HZ_X) * POINT_LIGHT_CIRCLE,
sin(m_deltaAccumulate * POINT_HZ_Y) * POINT_LIGHT_CIRCLE + POINT_LIGHT_CIRCLE,
cos(m_deltaAccumulate * POINT_HZ_X) * POINT_LIGHT_CIRCLE));
}
BaseApplication::Update(deltaTime);
}
void MainApplication::Resize(u32 width, u32 height)
{
BaseApplication::Resize(width, height);
}
void MainApplication::ProcessInputEvent(const InputEvent *inputEvent)
{
BaseApplication::ProcessInputEvent(inputEvent);
LOGINFO("MainApplication ProcessInputEvent.");
EventSource source = inputEvent->GetSource();
if (source == EVENT_SOURCE_TOUCHSCREEN) {
const TouchInputEvent *touchEvent = reinterpret_cast<const TouchInputEvent *>(inputEvent);
if (touchEvent == nullptr) {
LOGERROR("Failed to get touch event.");
return;
}
if (touchEvent->GetAction() == TOUCH_ACTION_DOWN) {
LOGINFO("Action move start.");
m_touchBegin = true;
} else if (touchEvent->GetAction() == TOUCH_ACTION_MOVE) {
float touchPosDeltaX = touchEvent->GetPosX(touchEvent->GetTouchIndex()) - m_touchPosX;
float touchPosDeltaY = touchEvent->GetPosY(touchEvent->GetTouchIndex()) - m_touchPosY;
if (m_touchBegin) {
if (fabs(touchPosDeltaX) > 2.f) {
if (touchPosDeltaX > 0.f) {
m_objectRotation -= 2.f * m_deltaTime;
} else {
m_objectRotation += 2.f * m_deltaTime;
}
LOGINFO("Set rotation start.");
}
if (fabs(touchPosDeltaY) > 3.f) {
if (touchPosDeltaY > 0.f) {
m_objectScale -= 0.25f * m_deltaTime;
} else {
m_objectScale += 0.25f * m_deltaTime;
}
m_objectScale = min(1.25f, max(0.75f, m_objectScale));
LOGINFO("Set scale start.");
}
}
} else if (touchEvent->GetAction() == TOUCH_ACTION_UP) {
LOGINFO("Action up.");
m_touchBegin = false;
} else if (touchEvent->GetAction() == TOUCH_ACTION_CANCEL) {
LOGINFO("Action cancel.");
m_touchBegin = false;
}
m_touchPosX = touchEvent->GetPosX(touchEvent->GetTouchIndex());
m_touchPosY = touchEvent->GetPosY(touchEvent->GetTouchIndex());
}
}
SceneObject *MainApplication::CreateSkybox()
{
String modelName = "models/test-cube.obj";
Model *model = static_cast<Model *>(gResourceManager.Get(modelName));
const Mesh *mesh = model->GetMesh();
// load Texture
u32 subMeshCnt = mesh->GetSubMeshCount();
// Add to scene
SceneObject *sceneObj = gSceneManager.CreateSceneObject();
MeshRenderer *meshRenderer = sceneObj->AddComponent<MeshRenderer>();
meshRenderer->SetMesh(model->GetMesh());
for (u32 i = 0; i < subMeshCnt; ++i) {
SubMesh *subMesh = mesh->GetSubMesh(i);
// add Material
Material *material = dynamic_cast<Material *>(gResourceManager.Get(ResourceType::RESOURCE_TYPE_MATERIAL));
material->Init();
material->SetSubMesh(subMesh);
material->SetTexture(TextureType::TEXTURE_TYPE_ENVIRONMENTMAP, m_envMap);
material->SetSamplerParam(TextureType::TEXTURE_TYPE_ENVIRONMENTMAP,
SAMPLER_FILTER_BILINEAR,
SAMPLER_FILTER_BILINEAR,
SAMPLER_MIPMAP_BILINEAR,
SAMPLER_ADDRESS_CLAMP);
material->AttachShaderStage(ShaderStageType::SHADER_STAGE_TYPE_VERTEX, "shaders/sky_vert.spv");
material->AttachShaderStage(ShaderStageType::SHADER_STAGE_TYPE_FRAGMENT, "shaders/sky_frag.spv");
material->SetCullMode(CULL_MODE_NONE);
material->SetDepthTestEnable(true);
material->SetDepthWriteEnable(true);
material->Create();
meshRenderer->SetMaterial(i, material);
}
sceneObj->SetScale(Vector3(1.f, 1.f, 1.f));
sceneObj->SetPosition(Vector3(0.0f, 0.0f, 0.0f));
sceneObj->SetRotation(Vector3(0.0f, 0.0, 0.0));
return sceneObj;
}
BaseApplication *CreateMainApplication()
{
return new MainApplication();
}
| 41.5 | 114 | 0.589973 | [
"mesh",
"object",
"model"
] |
c83ce7ddf4f306af60d3e072eea8696a717d8a81 | 5,317 | hpp | C++ | src/core/utils/otns.hpp | vikram998/openthread | 82ca038eec25863032e673581b4395201b851c77 | [
"BSD-3-Clause"
] | 1 | 2020-08-12T06:15:53.000Z | 2020-08-12T06:15:53.000Z | src/core/utils/otns.hpp | soburi/openthread | 34ac7c751a655caff5e2cdd5bb694d8f7735221d | [
"BSD-3-Clause"
] | 1 | 2020-10-11T01:45:28.000Z | 2020-10-11T01:45:28.000Z | src/core/utils/otns.hpp | soburi/openthread | 34ac7c751a655caff5e2cdd5bb694d8f7735221d | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2020, The OpenThread Authors.
* 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 the copyright holder 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.
*/
/**
* @file
* This file wraps the calls to platform OTNS abstrations.
*/
#ifndef UTILS_OTNS_HPP_
#define UTILS_OTNS_HPP_
#include "openthread-core-config.h"
#if (OPENTHREAD_MTD || OPENTHREAD_FTD) && OPENTHREAD_CONFIG_OTNS_ENABLE
#include <openthread/thread.h>
#include <openthread/thread_ftd.h>
#include <openthread/platform/otns.h>
#include "common/locator.hpp"
#include "common/non_copyable.hpp"
#include "common/notifier.hpp"
#include "mac/mac_types.hpp"
#include "net/ip6_address.hpp"
#include "thread/neighbor_table.hpp"
#include "thread/topology.hpp"
namespace ot {
namespace Utils {
/**
* This class implements the OTNS Stub that interacts with OTNS.
*
*/
class Otns : public InstanceLocator, private NonCopyable
{
friend class ot::Notifier;
public:
/**
* This constructor initializes the object.
*
* @param[in] aInstance A reference to the OpenThread instance.
*
*/
explicit Otns(Instance &aInstance)
: InstanceLocator(aInstance)
{
}
/**
* This function emits radio short address to OTNS when changed.
*
* @param[in] aShortAddress The new short address.
*
*/
static void EmitShortAddress(uint16_t aShortAddress);
/**
* This function emits radio extended address to OTNS when changed.
*
* @param[in] aExtAddress The new extended address.
*
*/
static void EmitExtendedAddress(const Mac::ExtAddress &aExtAddress);
/**
* This function emits ping request information to OTNS when sending.
*
* @param[in] aPeerAddress The peer address of the ping request.
* @param[in] aPingLength The data length of the ping request.
* @param[in] aTimestamp The timestamp of the ping request.
* @param[in] aHopLimit The hop limit of the ping request.
*
*/
static void EmitPingRequest(const Ip6::Address &aPeerAddress,
uint16_t aPingLength,
uint32_t aTimestamp,
uint8_t aHopLimit);
/**
* This function emits ping reply information to OTNS when received.
*
* @param[in] aPeerAddress The peer address of the ping request.
* @param[in] aPingLength The data length of the ping reply.
* @param[in] aTimestamp The timestamp of the ping reply.
* @param[in] aHopLimit The hop limit of the ping reply.
*
*/
static void EmitPingReply(const Ip6::Address &aPeerAddress,
uint16_t aPingLength,
uint32_t aTimestamp,
uint8_t aHopLimit);
/**
* This function emits a neighbor table event to OTNS when a neighbor is added or removed.
*
* @param[in] aEvent The event type.
* @param[in] aNeighbor The neighbor that is added or removed.
*
*/
static void EmitNeighborChange(NeighborTable::Event aEvent, const Neighbor &aNeighbor);
/**
* This function emits a transmit event to OTNS.
*
* @param[in] aFrame The frame of the transmission.
*
*/
static void EmitTransmit(const Mac::TxFrame &aFrame);
/**
* This function emits the device mode to OTNS.
*
* @param[in] aMode The device mode.
*
*/
static void EmitDeviceMode(Mle::DeviceMode aMode);
private:
static void EmitStatus(const char *aFmt, ...);
void HandleNotifierEvents(Events aEvents);
};
} // namespace Utils
} // namespace ot
#endif //(OPENTHREAD_MTD || OPENTHREAD_FTD) && OPENTHREAD_CONFIG_OTNS_ENABLE
#endif // UTILS_OTNS_HPP_
| 34.083333 | 94 | 0.664849 | [
"object"
] |
c83e41329c8e5052b38a035499b1bb83855b5586 | 2,954 | cpp | C++ | src/CoreGenerator.cpp | aesophor/CRAXplusplus | caacbeb4fadb5452ac3bf2faf5aff33580d19cca | [
"MIT"
] | 13 | 2021-12-08T02:53:13.000Z | 2021-12-30T14:45:16.000Z | src/CoreGenerator.cpp | aesophor/CRAXplusplus | caacbeb4fadb5452ac3bf2faf5aff33580d19cca | [
"MIT"
] | null | null | null | src/CoreGenerator.cpp | aesophor/CRAXplusplus | caacbeb4fadb5452ac3bf2faf5aff33580d19cca | [
"MIT"
] | null | null | null | // Copyright 2021-2022 Software Quality Laboratory, NYCU.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <s2e/Plugins/CRAX/CRAX.h>
#include <s2e/Plugins/CRAX/Expr/BinaryExprEval.h>
#include <s2e/Plugins/CRAX/Utils/StringUtil.h>
#include "CoreGenerator.h"
using namespace klee;
namespace s2e::plugins::crax {
void CoreGenerator::generateMainFunction(S2EExecutionState *state,
const std::vector<RopPayload> &ropPayload,
const std::vector<uint8_t> &stage1) {
handleStage1(ropPayload);
g_crax->getExploit().writeline("proc.recvrepeat(0)\n");
handleStage2(ropPayload);
}
void CoreGenerator::handleStage1(const std::vector<RopPayload> &ropPayload) {
Exploit &exploit = g_crax->getExploit();
Process &process = exploit.getProcess();
assert(ropPayload[0].size() == 1);
std::string stage1 = evaluate<std::string>(ropPayload[0][0]);
exploit.writelines({
format("payload = %s", stage1.c_str()),
process.toDeclStmt(),
});
// If the proxy in use is SYM_STDIN, then we have to explicitly
// send our payload to the stdin of the target process.
if (g_crax->getProxy() == CRAX::Proxy::SYM_STDIN) {
exploit.writelines({
"proc.send(payload)",
"time.sleep(0.2)"
});
}
}
void CoreGenerator::handleStage2(const std::vector<RopPayload> &ropPayload) {
Exploit &exploit = g_crax->getExploit();
for (size_t i = 1; i < ropPayload.size(); i++) {
if (auto le = dyn_cast<LambdaExpr>(ropPayload[i][0])) {
assert(ropPayload[i].size() == 1);
std::invoke(*le);
} else {
for (const ref<Expr> &e : ropPayload[i]) {
exploit.appendRopPayload(evaluate<std::string>(e));
}
exploit.flushRopPayload();
}
}
}
} // namespace s2e::plugins::crax
| 37.871795 | 83 | 0.665538 | [
"vector"
] |
c844e351615218a2eaec5ded8b5e5af5e159cab5 | 2,029 | cpp | C++ | deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgPlugins/ive/ColorMask.cpp | UM-ARM-Lab/mab_ms | f199f05b88060182cfbb47706bd1ff3479032c43 | [
"BSD-2-Clause"
] | 3 | 2018-08-20T12:12:43.000Z | 2021-06-06T09:43:27.000Z | deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgPlugins/ive/ColorMask.cpp | UM-ARM-Lab/mab_ms | f199f05b88060182cfbb47706bd1ff3479032c43 | [
"BSD-2-Clause"
] | null | null | null | deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgPlugins/ive/ColorMask.cpp | UM-ARM-Lab/mab_ms | f199f05b88060182cfbb47706bd1ff3479032c43 | [
"BSD-2-Clause"
] | 1 | 2022-03-31T03:12:23.000Z | 2022-03-31T03:12:23.000Z | /**********************************************************************
*
* FILE: ColorMask.cpp
*
* DESCRIPTION: Read/Write osg::ColorMask in binary format to disk.
*
* CREATED BY: Auto generated by iveGenerator
* and later modified by Rune Schmidt Jensen.
*
* HISTORY: Created 27.3.2003
*
* Copyright 2003 VR-C
**********************************************************************/
#include "Exception.h"
#include "ColorMask.h"
#include "Object.h"
using namespace ive;
void ColorMask::write(DataOutputStream* out){
// Write ColorMask's identification.
out->writeInt(IVECOLORMASK);
// If the osg class is inherited by any other class we should also write this to file.
osg::Object* obj = dynamic_cast<osg::Object*>(this);
if(obj){
((ive::Object*)(obj))->write(out);
}
else
throw Exception("ColorMask::write(): Could not cast this osg::ColorMask to an osg::Object.");
// Write ColorMask's properties.
out->writeBool(getRedMask());
out->writeBool(getGreenMask());
out->writeBool(getBlueMask());
out->writeBool(getAlphaMask());
}
void ColorMask::read(DataInputStream* in){
// Peek on ColorMask's identification.
int id = in->peekInt();
if(id == IVECOLORMASK){
// Read ColorMask's identification.
id = in->readInt();
// If the osg class is inherited by any other class we should also read this from file.
osg::Object* obj = dynamic_cast<osg::Object*>(this);
if(obj){
((ive::Object*)(obj))->read(in);
}
else
throw Exception("ColorMask::read(): Could not cast this osg::ColorMask to an osg::Object.");
// Read ColorMask's properties
setRedMask(in->readBool());
setGreenMask(in->readBool());
setBlueMask(in->readBool());
setAlphaMask(in->readBool());
}
else{
throw Exception("ColorMask::read(): Expected ColorMask identification.");
}
}
| 32.206349 | 104 | 0.567767 | [
"object"
] |
c845ea9a4d0c61fb19a557f80cc56060616c1026 | 15,994 | cxx | C++ | Common/DataModel/vtkBiQuadraticQuad.cxx | dsleep/VTK | cbf9c453cf50a954ab5d6a2448b8a0391bde9378 | [
"BSD-3-Clause"
] | 1 | 2020-03-24T14:08:58.000Z | 2020-03-24T14:08:58.000Z | Common/DataModel/vtkBiQuadraticQuad.cxx | dsleep/VTK | cbf9c453cf50a954ab5d6a2448b8a0391bde9378 | [
"BSD-3-Clause"
] | null | null | null | Common/DataModel/vtkBiQuadraticQuad.cxx | dsleep/VTK | cbf9c453cf50a954ab5d6a2448b8a0391bde9378 | [
"BSD-3-Clause"
] | 2 | 2020-03-24T14:09:05.000Z | 2021-09-17T09:30:26.000Z | /*=========================================================================
Program: Visualization Toolkit
Module: vtkBiQuadraticQuad.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// Thanks to Soeren Gebbert who developed this class and
// integrated it into VTK 5.0.
#include "vtkBiQuadraticQuad.h"
#include "vtkDoubleArray.h"
#include "vtkMath.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkPoints.h"
#include "vtkQuad.h"
#include "vtkQuadraticEdge.h"
vtkStandardNewMacro(vtkBiQuadraticQuad);
//----------------------------------------------------------------------------
// Construct the quad with nine points.
vtkBiQuadraticQuad::vtkBiQuadraticQuad()
{
this->Edge = vtkQuadraticEdge::New();
this->Quad = vtkQuad::New();
this->Points->SetNumberOfPoints(9);
this->PointIds->SetNumberOfIds(9);
for (int i = 0; i < 9; i++)
{
this->Points->SetPoint(i, 0.0, 0.0, 0.0);
this->PointIds->SetId(i, 0);
}
this->Scalars = vtkDoubleArray::New();
this->Scalars->SetNumberOfTuples(4);
}
//----------------------------------------------------------------------------
vtkBiQuadraticQuad::~vtkBiQuadraticQuad()
{
this->Edge->Delete();
this->Quad->Delete();
this->Scalars->Delete();
}
//----------------------------------------------------------------------------
vtkCell* vtkBiQuadraticQuad::GetEdge(int edgeId)
{
edgeId = (edgeId < 0 ? 0 : (edgeId > 3 ? 3 : edgeId));
int p = (edgeId + 1) % 4;
// load point id's
this->Edge->PointIds->SetId(0, this->PointIds->GetId(edgeId));
this->Edge->PointIds->SetId(1, this->PointIds->GetId(p));
this->Edge->PointIds->SetId(2, this->PointIds->GetId(edgeId + 4));
// load coordinates
this->Edge->Points->SetPoint(0, this->Points->GetPoint(edgeId));
this->Edge->Points->SetPoint(1, this->Points->GetPoint(p));
this->Edge->Points->SetPoint(2, this->Points->GetPoint(edgeId + 4));
return this->Edge;
}
//----------------------------------------------------------------------------
static int LinearQuads[4][4] = { { 0, 4, 8, 7 }, { 4, 1, 5, 8 }, { 8, 5, 2, 6 }, { 7, 8, 6, 3 } };
//----------------------------------------------------------------------------
int vtkBiQuadraticQuad::EvaluatePosition(const double x[3], double* closestPoint, int& subId,
double pcoords[3], double& minDist2, double* weights)
{
double pc[3], dist2;
int ignoreId, i, returnStatus = 0, status;
double tempWeights[4];
double closest[3];
// four linear quads are used
for (minDist2 = VTK_DOUBLE_MAX, i = 0; i < 4; i++)
{
this->Quad->Points->SetPoint(0, this->Points->GetPoint(LinearQuads[i][0]));
this->Quad->Points->SetPoint(1, this->Points->GetPoint(LinearQuads[i][1]));
this->Quad->Points->SetPoint(2, this->Points->GetPoint(LinearQuads[i][2]));
this->Quad->Points->SetPoint(3, this->Points->GetPoint(LinearQuads[i][3]));
status = this->Quad->EvaluatePosition(x, closest, ignoreId, pc, dist2, tempWeights);
if (status != -1 && dist2 < minDist2)
{
returnStatus = status;
minDist2 = dist2;
subId = i;
pcoords[0] = pc[0];
pcoords[1] = pc[1];
}
}
// adjust parametric coordinates
if (returnStatus != -1)
{
if (subId == 0)
{
pcoords[0] /= 2.0;
pcoords[1] /= 2.0;
}
else if (subId == 1)
{
pcoords[0] = 0.5 + (pcoords[0] / 2.0);
pcoords[1] /= 2.0;
}
else if (subId == 2)
{
pcoords[0] = 0.5 + (pcoords[0] / 2.0);
pcoords[1] = 0.5 + (pcoords[1] / 2.0);
}
else
{
pcoords[0] /= 2.0;
pcoords[1] = 0.5 + (pcoords[1] / 2.0);
}
pcoords[2] = 0.0;
if (closestPoint != nullptr)
{
// Compute both closestPoint and weights
this->EvaluateLocation(subId, pcoords, closestPoint, weights);
}
else
{
// Compute weights only
this->InterpolationFunctionsPrivate(pcoords, weights);
}
}
return returnStatus;
}
//----------------------------------------------------------------------------
void vtkBiQuadraticQuad::EvaluateLocation(
int& vtkNotUsed(subId), const double pcoords[3], double x[3], double* weights)
{
int i, j;
double pt[3];
this->InterpolationFunctionsPrivate(pcoords, weights);
x[0] = x[1] = x[2] = 0.0;
for (i = 0; i < 9; i++)
{
this->Points->GetPoint(i, pt);
for (j = 0; j < 3; j++)
{
x[j] += pt[j] * weights[i];
}
}
}
//----------------------------------------------------------------------------
int vtkBiQuadraticQuad::CellBoundary(int subId, const double pcoords[3], vtkIdList* pts)
{
return this->Quad->CellBoundary(subId, pcoords, pts);
}
//----------------------------------------------------------------------------
void vtkBiQuadraticQuad::Contour(double value, vtkDataArray* cellScalars,
vtkIncrementalPointLocator* locator, vtkCellArray* verts, vtkCellArray* lines,
vtkCellArray* polys, vtkPointData* inPd, vtkPointData* outPd, vtkCellData* inCd, vtkIdType cellId,
vtkCellData* outCd)
{
// contour each linear quad separately
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
this->Quad->Points->SetPoint(j, this->Points->GetPoint(LinearQuads[i][j]));
this->Quad->PointIds->SetId(j, this->PointIds->GetId(LinearQuads[i][j]));
this->Scalars->SetValue(j, cellScalars->GetTuple1(LinearQuads[i][j]));
}
this->Quad->Contour(
value, this->Scalars, locator, verts, lines, polys, inPd, outPd, inCd, cellId, outCd);
}
}
//----------------------------------------------------------------------------
// Clip this quadratic quad using scalar value provided. Like contouring,
// except that it cuts the quad to produce other quads and triangles.
void vtkBiQuadraticQuad::Clip(double value, vtkDataArray* cellScalars,
vtkIncrementalPointLocator* locator, vtkCellArray* polys, vtkPointData* inPd, vtkPointData* outPd,
vtkCellData* inCd, vtkIdType cellId, vtkCellData* outCd, int insideOut)
{
// contour each linear quad separately
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++) // for each of the four vertices of the linear quad
{
this->Quad->Points->SetPoint(j, this->Points->GetPoint(LinearQuads[i][j]));
this->Quad->PointIds->SetId(j, this->PointIds->GetId(LinearQuads[i][j]));
this->Scalars->SetValue(j, cellScalars->GetTuple1(LinearQuads[i][j]));
}
this->Quad->Clip(
value, this->Scalars, locator, polys, inPd, outPd, inCd, cellId, outCd, insideOut);
}
}
//----------------------------------------------------------------------------
// Line-line intersection. Intersection has to occur within [0,1] parametric
// coordinates and with specified tolerance.
int vtkBiQuadraticQuad::IntersectWithLine(
const double* p1, const double* p2, double tol, double& t, double* x, double* pcoords, int& subId)
{
int subTest, i;
subId = 0;
// intersect the four linear quads
for (i = 0; i < 4; i++)
{
this->Quad->Points->SetPoint(0, this->Points->GetPoint(LinearQuads[i][0]));
this->Quad->Points->SetPoint(1, this->Points->GetPoint(LinearQuads[i][1]));
this->Quad->Points->SetPoint(2, this->Points->GetPoint(LinearQuads[i][2]));
this->Quad->Points->SetPoint(3, this->Points->GetPoint(LinearQuads[i][3]));
if (this->Quad->IntersectWithLine(p1, p2, tol, t, x, pcoords, subTest))
{
return 1;
}
}
return 0;
}
//----------------------------------------------------------------------------
int vtkBiQuadraticQuad::Triangulate(int vtkNotUsed(index), vtkIdList* ptIds, vtkPoints* pts)
{
pts->SetNumberOfPoints(24);
ptIds->SetNumberOfIds(24);
// First the corner vertices
ptIds->SetId(0, this->PointIds->GetId(0));
ptIds->SetId(1, this->PointIds->GetId(4));
ptIds->SetId(2, this->PointIds->GetId(7));
pts->SetPoint(0, this->Points->GetPoint(0));
pts->SetPoint(1, this->Points->GetPoint(4));
pts->SetPoint(2, this->Points->GetPoint(7));
ptIds->SetId(3, this->PointIds->GetId(4));
ptIds->SetId(4, this->PointIds->GetId(1));
ptIds->SetId(5, this->PointIds->GetId(5));
pts->SetPoint(3, this->Points->GetPoint(4));
pts->SetPoint(4, this->Points->GetPoint(1));
pts->SetPoint(5, this->Points->GetPoint(5));
ptIds->SetId(6, this->PointIds->GetId(5));
ptIds->SetId(7, this->PointIds->GetId(2));
ptIds->SetId(8, this->PointIds->GetId(6));
pts->SetPoint(6, this->Points->GetPoint(5));
pts->SetPoint(7, this->Points->GetPoint(2));
pts->SetPoint(8, this->Points->GetPoint(6));
ptIds->SetId(9, this->PointIds->GetId(6));
ptIds->SetId(10, this->PointIds->GetId(3));
ptIds->SetId(11, this->PointIds->GetId(7));
pts->SetPoint(9, this->Points->GetPoint(6));
pts->SetPoint(10, this->Points->GetPoint(3));
pts->SetPoint(11, this->Points->GetPoint(7));
// Now the triangles in the middle
ptIds->SetId(12, this->PointIds->GetId(4));
ptIds->SetId(13, this->PointIds->GetId(8));
ptIds->SetId(14, this->PointIds->GetId(7));
pts->SetPoint(12, this->Points->GetPoint(4));
pts->SetPoint(13, this->Points->GetPoint(8));
pts->SetPoint(14, this->Points->GetPoint(7));
ptIds->SetId(15, this->PointIds->GetId(4));
ptIds->SetId(16, this->PointIds->GetId(5));
ptIds->SetId(17, this->PointIds->GetId(8));
pts->SetPoint(15, this->Points->GetPoint(4));
pts->SetPoint(16, this->Points->GetPoint(5));
pts->SetPoint(17, this->Points->GetPoint(8));
ptIds->SetId(18, this->PointIds->GetId(5));
ptIds->SetId(19, this->PointIds->GetId(6));
ptIds->SetId(20, this->PointIds->GetId(8));
pts->SetPoint(18, this->Points->GetPoint(5));
pts->SetPoint(19, this->Points->GetPoint(6));
pts->SetPoint(20, this->Points->GetPoint(8));
ptIds->SetId(21, this->PointIds->GetId(6));
ptIds->SetId(22, this->PointIds->GetId(7));
ptIds->SetId(23, this->PointIds->GetId(8));
pts->SetPoint(21, this->Points->GetPoint(6));
pts->SetPoint(22, this->Points->GetPoint(7));
pts->SetPoint(23, this->Points->GetPoint(8));
return 1;
}
//----------------------------------------------------------------------------
void vtkBiQuadraticQuad::Derivatives(
int vtkNotUsed(subId), const double pcoords[3], const double* values, int dim, double* derivs)
{
double sum[3], weights[9];
double functionDerivs[18];
double elemNodes[9][3];
double *J[3], J0[3], J1[3], J2[3];
double *JI[3], JI0[3], JI1[3], JI2[3];
for (int i = 0; i < 9; i++)
{
this->Points->GetPoint(i, elemNodes[i]);
}
this->InterpolationFunctionsPrivate(pcoords, weights);
this->InterpolationDerivsPrivate(pcoords, functionDerivs);
// Compute transposed Jacobian and inverse Jacobian
J[0] = J0;
J[1] = J1;
J[2] = J2;
JI[0] = JI0;
JI[1] = JI1;
JI[2] = JI2;
for (int k = 0; k < 3; k++)
{
J0[k] = J1[k] = 0.0;
}
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 2; j++)
{
for (int k = 0; k < 3; k++)
{
J[j][k] += elemNodes[i][k] * functionDerivs[j * 9 + i];
}
}
}
// Compute third row vector in transposed Jacobian and normalize it, so that Jacobian determinant
// stays the same.
vtkMath::Cross(J0, J1, J2);
if (vtkMath::Normalize(J2) == 0.0 || !vtkMath::InvertMatrix(J, JI, 3)) // degenerate
{
for (int j = 0; j < dim; j++)
{
for (int i = 0; i < 3; i++)
{
derivs[j * dim + i] = 0.0;
}
}
return;
}
// Loop over "dim" derivative values. For each set of values,
// compute derivatives
// in local system and then transform into modelling system.
// First compute derivatives in local x'-y' coordinate system
for (int j = 0; j < dim; j++)
{
sum[0] = sum[1] = sum[2] = 0.0;
for (int i = 0; i < 9; i++) // loop over interp. function derivatives
{
sum[0] += functionDerivs[i] * values[dim * i + j];
sum[1] += functionDerivs[9 + i] * values[dim * i + j];
}
// dBydx = sum[0]*JI[0][0] + sum[1]*JI[0][1];
// dBydy = sum[0]*JI[1][0] + sum[1]*JI[1][1];
// Transform into global system (dot product with global axes)
derivs[3 * j] = sum[0] * JI[0][0] + sum[1] * JI[0][1];
derivs[3 * j + 1] = sum[0] * JI[1][0] + sum[1] * JI[1][1];
derivs[3 * j + 2] = sum[0] * JI[2][0] + sum[1] * JI[2][1];
}
}
//----------------------------------------------------------------------------
// Compute interpolation functions. The first four nodes are the corner
// vertices; the others are mid-edge nodes, the last one is the mid-center
// node.
void vtkBiQuadraticQuad::InterpolationFunctionsPrivate(const double pcoords[3], double weights[9])
{
// Normally these coordinates are named r and s, but I chose x and y,
// because you can easily mark and paste these functions to the
// gnuplot splot function. :D
double x = pcoords[0];
double y = pcoords[1];
// midedge weights
weights[0] = 4.0 * (1.0 - x) * (x - 0.5) * (1.0 - y) * (y - 0.5);
weights[1] = -4.0 * (x) * (x - 0.5) * (1.0 - y) * (y - 0.5);
weights[2] = 4.0 * (x) * (x - 0.5) * (y) * (y - 0.5);
weights[3] = -4.0 * (1.0 - x) * (x - 0.5) * (y) * (y - 0.5);
// corner weights
weights[4] = 8.0 * (x) * (1.0 - x) * (1.0 - y) * (0.5 - y);
weights[5] = -8.0 * (x) * (0.5 - x) * (1.0 - y) * (y);
weights[6] = -8.0 * (x) * (1.0 - x) * (y) * (0.5 - y);
weights[7] = 8.0 * (1.0 - x) * (0.5 - x) * (1.0 - y) * (y);
// surface center weight
weights[8] = 16.0 * (x) * (1.0 - x) * (1.0 - y) * (y);
}
//----------------------------------------------------------------------------
// Derivatives in parametric space.
void vtkBiQuadraticQuad::InterpolationDerivsPrivate(const double pcoords[3], double derivs[18])
{
// Coordinate conversion
double x = pcoords[0];
double y = pcoords[1];
// Derivatives in the x-direction
// edge
derivs[0] = 4.0 * (1.5 - 2.0 * x) * (1.0 - y) * (y - 0.5);
derivs[1] = -4.0 * (2.0 * x - 0.5) * (1.0 - y) * (y - 0.5);
derivs[2] = 4.0 * (2.0 * x - 0.5) * (y) * (y - 0.5);
derivs[3] = -4.0 * (1.5 - 2.0 * x) * (y) * (y - 0.5);
// midedge
derivs[4] = 8.0 * (1.0 - 2.0 * x) * (1.0 - y) * (0.5 - y);
derivs[5] = -8.0 * (0.5 - 2.0 * x) * (1.0 - y) * (y);
derivs[6] = -8.0 * (1.0 - 2.0 * x) * (y) * (0.5 - y);
derivs[7] = 8.0 * (2.0 * x - 1.5) * (1.0 - y) * (y);
// center
derivs[8] = 16.0 * (1.0 - 2.0 * x) * (1.0 - y) * (y);
// Derivatives in the y-direction
// edge
derivs[9] = 4.0 * (1.0 - x) * (x - 0.5) * (1.5 - 2.0 * y);
derivs[10] = -4.0 * (x) * (x - 0.5) * (1.5 - 2.0 * y);
derivs[11] = 4.0 * (x) * (x - 0.5) * (2.0 * y - 0.5);
derivs[12] = -4.0 * (1.0 - x) * (x - 0.5) * (2.0 * y - 0.5);
// midedge
derivs[13] = 8.0 * (x) * (1.0 - x) * (2.0 * y - 1.5);
derivs[14] = -8.0 * (x) * (0.5 - x) * (1.0 - 2.0 * y);
derivs[15] = -8.0 * (x) * (1.0 - x) * (0.5 - 2.0 * y);
derivs[16] = 8.0 * (1.0 - x) * (0.5 - x) * (1.0 - 2.0 * y);
// center
derivs[17] = 16.0 * (x) * (1.0 - x) * (1.0 - 2.0 * y);
}
//----------------------------------------------------------------------------
static double vtkQQuadCellPCoords[27] = { 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0,
0.0, 0.5, 0.0, 0.0, 1.0, 0.5, 0.0, 0.5, 1.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.0 };
double* vtkBiQuadraticQuad::GetParametricCoords()
{
return vtkQQuadCellPCoords;
}
//----------------------------------------------------------------------------
void vtkBiQuadraticQuad::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "Edge:\n";
this->Edge->PrintSelf(os, indent.GetNextIndent());
os << indent << "Quad:\n";
this->Quad->PrintSelf(os, indent.GetNextIndent());
os << indent << "Scalars:\n";
this->Scalars->PrintSelf(os, indent.GetNextIndent());
}
| 34.029787 | 100 | 0.548768 | [
"vector",
"transform"
] |
c847784eb22980c6ce4cb6e792fcca5ec37a3ff5 | 1,279 | cpp | C++ | src/Access/EnabledRoles.cpp | evryfs/ClickHouse | a9648af0b9e2506ce783106315814ed8dbd0a952 | [
"Apache-2.0"
] | 18 | 2021-05-29T01:12:33.000Z | 2021-11-18T12:34:48.000Z | src/Access/EnabledRoles.cpp | evryfs/ClickHouse | a9648af0b9e2506ce783106315814ed8dbd0a952 | [
"Apache-2.0"
] | 13 | 2019-06-06T09:45:53.000Z | 2020-05-15T12:03:45.000Z | src/Access/EnabledRoles.cpp | evryfs/ClickHouse | a9648af0b9e2506ce783106315814ed8dbd0a952 | [
"Apache-2.0"
] | 22 | 2019-06-14T10:31:51.000Z | 2020-10-12T14:57:44.000Z | #include <Access/EnabledRoles.h>
#include <Access/Role.h>
#include <Access/EnabledRolesInfo.h>
#include <boost/range/algorithm/copy.hpp>
namespace DB
{
EnabledRoles::EnabledRoles(const Params & params_) : params(params_)
{
}
EnabledRoles::~EnabledRoles() = default;
std::shared_ptr<const EnabledRolesInfo> EnabledRoles::getRolesInfo() const
{
std::lock_guard lock{mutex};
return info;
}
ext::scope_guard EnabledRoles::subscribeForChanges(const OnChangeHandler & handler) const
{
std::lock_guard lock{mutex};
handlers.push_back(handler);
auto it = std::prev(handlers.end());
return [this, it]
{
std::lock_guard lock2{mutex};
handlers.erase(it);
};
}
void EnabledRoles::setRolesInfo(const std::shared_ptr<const EnabledRolesInfo> & info_, ext::scope_guard & notifications)
{
std::lock_guard lock{mutex};
if (info && info_ && *info == *info_)
return;
info = info_;
std::vector<OnChangeHandler> handlers_to_notify;
boost::range::copy(handlers, std::back_inserter(handlers_to_notify));
notifications.join(ext::scope_guard([info = info, handlers_to_notify = std::move(handlers_to_notify)]
{
for (const auto & handler : handlers_to_notify)
handler(info);
}));
}
}
| 22.438596 | 120 | 0.688038 | [
"vector"
] |
c84990f445b884f662c0e0239649f7953f17054b | 1,983 | cpp | C++ | src/analysis/util/laguerre.cpp | dequis/in-formant | 129b9b399c75cdbd834b68f04dabcb1d406af250 | [
"Apache-2.0"
] | null | null | null | src/analysis/util/laguerre.cpp | dequis/in-formant | 129b9b399c75cdbd834b68f04dabcb1d406af250 | [
"Apache-2.0"
] | null | null | null | src/analysis/util/laguerre.cpp | dequis/in-formant | 129b9b399c75cdbd834b68f04dabcb1d406af250 | [
"Apache-2.0"
] | null | null | null | #include "util.h"
#include "laguerre.h"
std::complex<double> Analysis::laguerreRoot(const std::vector<std::complex<double>>& P, std::complex<double> xk, double accuracy)
{
constexpr int maxIt = 5000;
std::vector<std::complex<double>> ys(3);
ys = evaluatePolynomialDerivatives(P, xk, 2);
const int n = P.size() - 1;
for (int it = 0; it < maxIt; ++it) {
if (std::abs(ys[0]) < accuracy)
return xk;
auto g = ys[1] / ys[0];
auto h = g * g - ys[2] / ys[0];
auto f = std::sqrt(((double) n - 1) * ((double) n * h - g * g));
std::complex<double> dx;
if (std::abs(g + f) > std::abs(g - f)) {
dx = (double) n / (g + f);
}
else {
dx = (double) n / (g - f);
}
xk -= dx;
if (std::abs(dx) < accuracy) {
return xk;
}
ys = evaluatePolynomialDerivatives(P, xk, 2);
}
return xk;
}
std::vector<std::complex<double>> Analysis::laguerreDeflate(const std::vector<std::complex<double>>& P, const std::complex<double>& root)
{
const int n = P.size() - 1;
std::vector<std::complex<double>> Q(n);
Q[n - 1] = P[n];
for (int i = n - 2; i >= 0; --i) {
Q[i] = std::complex<double>(
std::complex<long double>(P[i + 1])
+ std::complex<long double>(root) * std::complex<long double>(Q[i + 1]));
}
return Q;
}
std::vector<std::complex<double>> Analysis::laguerreSolve(const std::vector<double>& realP)
{
std::vector<std::complex<double>> P(realP.rbegin(), realP.rend());
auto Pi = P;
const int N = P.size() - 1;
std::vector<std::complex<double>> R(N);
for (int i = 0; i < N; ++i) {
R[i] = laguerreRoot(Pi, 0.0, 1e-6);
Pi = laguerreDeflate(Pi, R[i]);
}
for (int i = 0; i < N; ++i) {
R[i] = laguerreRoot(P, R[i], 1e-12);
}
return std::vector<std::complex<double>>(R.begin(), R.end());
}
| 26.092105 | 137 | 0.509329 | [
"vector"
] |
c84b49d4df843623246a38c00267685cfbb64c6a | 1,653 | hpp | C++ | tests/mghfuns/gaussian.hpp | ptillet/umintl | 605da5703d36c2150fd1c2b979ff6e631b4cad47 | [
"MIT"
] | null | null | null | tests/mghfuns/gaussian.hpp | ptillet/umintl | 605da5703d36c2150fd1c2b979ff6e631b4cad47 | [
"MIT"
] | null | null | null | tests/mghfuns/gaussian.hpp | ptillet/umintl | 605da5703d36c2150fd1c2b979ff6e631b4cad47 | [
"MIT"
] | null | null | null | /* ===========================
Copyright (c) 2013 Philippe Tillet
UMinTL - Unconstrained Minimization Template Library
License : MIT X11 - See the LICENSE file in the root folder
* ===========================*/
#ifndef UMINTL_GAUSSIAN_HPP_
#define UMINTL_GAUSSIAN_HPP_
#include <cmath>
#include <vector>
#include "sum_square.hpp"
template<class BackendType>
class gaussian : public sum_square<BackendType>{
typedef typename BackendType::VectorType VectorType;
typedef double ScalarType;
typedef sum_square<BackendType> base_type;
using base_type::M_;
using base_type::N_;
using base_type::get;
public:
gaussian() : base_type("Gaussian",15,3,1.12793e-8){ }
void init(VectorType & X) const
{
X[0] = 0.4;
X[1] = 1;
X[2] = 0;
}
void fill_dym_dxn(VectorType const & V, ScalarType * res) const
{
for(std::size_t m = 0 ; m < M_ ; ++m){
ScalarType t = (ScalarType)(8-(int)(m+1))/2;
ScalarType e = exp(-0.5*V[1]*pow(t-V[2],2));
get(res,m,0) = e;
get(res,m,1) = -0.5*V[0]*pow(t-V[2],2)*e;
get(res,m,2) = V[0]*V[1]*(t-V[2])*e;
}
}
void fill_ym(VectorType const & V, ScalarType * res) const
{
ScalarType y[15] = {0.0009, 0.0044, 0.0175, 0.0540, 0.1295, 0.2420, 0.3521, 0.3989,
0.3521, 0.2420, 0.1295, 0.0540, 0.0175, 0.0044, 0.0009};
for(std::size_t m = 0 ; m < M_ ; ++m){
ScalarType t = (ScalarType)(8-(int)(m+1))/2;
ScalarType e = exp(-0.5*V[1]*pow(t-V[2],2));
res[m] = V[0]*e - y[m];
}
}
};
#endif
| 30.611111 | 91 | 0.54144 | [
"vector"
] |
c8506e26f9e334eac85a97017fec90ba54891212 | 753 | cpp | C++ | Array/huyang/07之前/嵌套数组.cpp | JessonYue/LeetCodeLearning | 3c22a4fcdfe8b47f9f64b939c8b27742c4e30b79 | [
"MIT"
] | 39 | 2020-05-31T06:14:39.000Z | 2021-01-09T11:06:39.000Z | Array/huyang/07之前/嵌套数组.cpp | JessonYue/LeetCodeLearning | 3c22a4fcdfe8b47f9f64b939c8b27742c4e30b79 | [
"MIT"
] | 7 | 2020-06-02T11:04:14.000Z | 2020-06-11T14:11:58.000Z | Array/huyang/07之前/嵌套数组.cpp | JessonYue/LeetCodeLearning | 3c22a4fcdfe8b47f9f64b939c8b27742c4e30b79 | [
"MIT"
] | 20 | 2020-05-31T06:21:57.000Z | 2020-10-01T04:48:38.000Z | //索引从0开始长度为N的数组A,包含0到N - 1的所有整数。找到最大的集合S并返回其大小,其中 S[i] = {A[i], A[A[i]], A[A[A[i]]], ... }且遵守以下的规则。
//假设选择索引为i的元素A[i]为S的第一个元素,S的下一个元素应该是A[A[i]],之后是A[A[A[i]]]... 以此类推,不断添加直到S出现重复的元素。
//思路:环上的任一元素开始遍历都会有相同的结果,在for循环中,使用 while(nums[pos] < len ){
// nums[pos] += len;
//跳过环上的元素
class Solution {
public:
int arrayNesting(vector<int>& nums) {
int len = nums.size(), count = 0, temp_count = 0, pos=0;
for(int i =0 ; i < len; i ++){
pos = i;
temp_count = 0;
while(nums[pos] < len ){
nums[pos] += len;
pos = nums[pos] - len;
temp_count++;
}
count = max(count,temp_count);
}
return count;
}
}; | 26.892857 | 99 | 0.495352 | [
"vector"
] |
c8514a569694f5fb3db83dd6003c22f3e4d30165 | 47,211 | cpp | C++ | src/topp/MzTabExporter.cpp | andreott/OpenMS | 718fa2e8a91280ff65e4cf834a3d825811dce1dc | [
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | 1 | 2021-07-06T09:15:10.000Z | 2021-07-06T09:15:10.000Z | src/topp/MzTabExporter.cpp | andreott/OpenMS | 718fa2e8a91280ff65e4cf834a3d825811dce1dc | [
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | null | null | null | src/topp/MzTabExporter.cpp | andreott/OpenMS | 718fa2e8a91280ff65e4cf834a3d825811dce1dc | [
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | null | null | null | // --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2018.
//
// This software is released under a three-clause BSD license:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * 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.
// * Neither the name of any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// 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 ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS 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.
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Timo Sachsenberg $
// --------------------------------------------------------------------------
#include <OpenMS/APPLICATIONS/TOPPBase.h>
#include <OpenMS/DATASTRUCTURES/StringListUtils.h>
#include <OpenMS/MATH/MISC/MathFunctions.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/FORMAT/FileTypes.h>
#include <OpenMS/FORMAT/ConsensusXMLFile.h>
#include <OpenMS/FORMAT/FeatureXMLFile.h>
#include <OpenMS/METADATA/MetaInfoInterfaceUtils.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/METADATA/ProteinHit.h>
#include <OpenMS/METADATA/PeptideEvidence.h>
#include <OpenMS/FORMAT/IdXMLFile.h>
#include <OpenMS/FORMAT/MzIdentMLFile.h>
#include <OpenMS/CHEMISTRY/ModificationsDB.h>
#include <OpenMS/FORMAT/MzTabFile.h>
#include <OpenMS/FORMAT/MzTab.h>
#include <vector>
#include <algorithm>
using namespace OpenMS;
using namespace std;
//-------------------------------------------------------------
//Doxygen docu
//-------------------------------------------------------------
/**
@page TOPP_MzTabExporter MzTabExporter
@brief This application converts several %OpenMS XML formats (featureXML, consensusXML, and idXML) to mzTab.
<CENTER>
<table>
<tr>
<td ALIGN = "center" BGCOLOR="#EBEBEB"> pot. predecessor tools </td>
<td VALIGN="middle" ROWSPAN=2> \f$ \longrightarrow \f$ MzTabExporter \f$ \longrightarrow \f$</td>
<td ALIGN = "center" BGCOLOR="#EBEBEB"> potential successor tools </td>
</tr>
<tr>
<td VALIGN="middle" ALIGN = "center" ROWSPAN=1> Any tool producing one of the input formats </td>
<td VALIGN="middle" ALIGN = "center" ROWSPAN=1> External tools (MS Excel, OpenOffice, Notepad)</td>
</tr>
</table>
</CENTER>
See the mzTab specification for details on the format.
@experimental This algorithm and underlying format is work in progress and might change.
@note Currently mzIdentML (mzid) is not directly supported as an input/output format of this tool. Convert mzid files to/from idXML using @ref TOPP_IDFileConverter if necessary.
<B>The command line parameters of this tool are:</B>
@verbinclude TOPP_MzTabExporter.cli
<B>INI file documentation of this tool:</B>
@htmlinclude TOPP_MzTabExporter.html
*/
// We do not want this class to show up in the docu:
/// @cond TOPPCLASSES
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wshadow"
namespace OpenMS
{
class TOPPMzTabExporter :
public TOPPBase
{
public:
TOPPMzTabExporter() :
TOPPBase("MzTabExporter", "Exports various XML formats to an mzTab file.")
{
}
protected:
void registerOptionsAndFlags_() override
{
registerInputFile_("in", "<file>", "", "Input files used to generate the mzTab file.", false);
setValidFormats_("in", ListUtils::create<String>("featureXML,consensusXML,idXML,mzid"));
registerOutputFile_("out", "<file>", "", "Output file (mzTab)", true);
setValidFormats_("out", ListUtils::create<String>("mzTab"));
}
/**
@brief Gets peptide_evidences with data from internal structures adds their info to an MzTabPSMSectionRow (pre- or unfilled)
@param peptide_evidences Vector of PeptideEvidence holding internal data.
@param row Pre- or unfilled MzTabPSMSectionRow to be filled with the data.
@param rows Vector of MzTabPSMSectionRow to add the differently updated rows to.
*/
static void addPepEvidenceToRows(const vector<PeptideEvidence>& peptide_evidences, MzTabPSMSectionRow& row, MzTabPSMSectionRows& rows)
{
if (!peptide_evidences.empty())
{
for (Size i = 0; i != peptide_evidences.size(); ++i)
{
// get AABefore and AAAfter as well as start and end for all pep evidences
// pre/post
// from spec: Amino acid preceding the peptide (coming from the PSM) in the protein
// sequence. If unknown “null” MUST be used, if the peptide is N-terminal “-“
// MUST be used.
if (peptide_evidences[i].getAABefore() == PeptideEvidence::UNKNOWN_AA)
{
row.pre = MzTabString("null");
}
else if (peptide_evidences[i].getAABefore() == PeptideEvidence::N_TERMINAL_AA)
{
row.pre = MzTabString("-");
}
else
{
row.pre = MzTabString(String(peptide_evidences[i].getAABefore()));
}
if (peptide_evidences[i].getAAAfter() == PeptideEvidence::UNKNOWN_AA)
{
row.post = MzTabString("null");
}
else if (peptide_evidences[i].getAAAfter() == PeptideEvidence::C_TERMINAL_AA)
{
row.post = MzTabString("-");
}
else
{
row.post = MzTabString(String(peptide_evidences[i].getAAAfter()));
}
// start/end
if (peptide_evidences[i].getStart() == PeptideEvidence::UNKNOWN_POSITION)
{
row.start = MzTabString("null");
}
else
{
row.start = MzTabString(String(peptide_evidences[i].getStart() + 1)); // counting in mzTab starts at 1
}
if (peptide_evidences[i].getEnd() == PeptideEvidence::UNKNOWN_POSITION)
{
row.end = MzTabString("null");
}
else
{
row.end = MzTabString(String(peptide_evidences[i].getEnd() + 1)); // counting in mzTab starts at 1
}
row.accession = MzTabString(peptide_evidences[i].getProteinAccession());
rows.push_back(row);
}
}
else
{ // report without pep evidence information
row.pre = MzTabString("null");
row.post = MzTabString("null");
row.start = MzTabString("null");
row.end = MzTabString("null");
rows.push_back(row);
}
}
/**
@brief Inserts values from MetaInfoInterface objects matching a (precalculated or filtered) set of keys to optional columns of an MzTab row.
@param keys Only values matching those keys will be extracted from the object inheriting from MetaInfoInterface.
@param opt A vector of optional columns to add to.
@param id The identifier for this optional value according to the mzTab standard (like global, MS_Run, assay, etc.)
@param meta The object holding the MetaInformation (like PeptideHit, ProteinHit, etc.)
@return void: Only updates the values of the columns in opt
*/
static void addMetaInfoToOptionalColumns(const set<String>& keys, vector<MzTabOptionalColumnEntry>& opt, const String id, const MetaInfoInterface meta)
{
for (set<String>::const_iterator sit = keys.begin(); sit != keys.end(); ++sit)
{
const String& key = *sit;
MzTabOptionalColumnEntry opt_entry;
opt_entry.first = String("opt_") + id + String("_") + String(key).substitute(' ','_');
if (meta.metaValueExists(key))
{
opt_entry.second = MzTabString(meta.getMetaValue(key).toString().substitute(' ','_'));
} // otherwise it is default ("null")
opt.push_back(opt_entry);
}
}
static map<Size, MzTabModificationMetaData> generateMzTabStringFromModifications(const vector<String>& mods)
{
map<Size, MzTabModificationMetaData> mods_mztab;
for (vector<String>::const_iterator sit = mods.begin(); sit != mods.end(); ++sit)
{
Size index = (sit - mods.begin()) + 1;
MzTabModificationMetaData mod;
MzTabParameter mp;
mp.setCVLabel("UNIMOD");
ModificationsDB* mod_db = ModificationsDB::getInstance();
// MzTab standard is to just report Unimod accession.
ResidueModification m = mod_db->getModification(*sit);
String unimod_accession = m.getUniModAccession();
mp.setAccession(unimod_accession.toUpper());
mp.setName(m.getId());
mod.modification = mp;
if (m.getTermSpecificity() == ResidueModification::C_TERM)
{
mod.position = MzTabString("Any C-term");
}
else if (m.getTermSpecificity() == ResidueModification::N_TERM)
{
mod.position = MzTabString("Any N-term");
}
else if (m.getTermSpecificity() == ResidueModification::ANYWHERE)
{
mod.position = MzTabString("Anywhere");
}
else if (m.getTermSpecificity() == ResidueModification::PROTEIN_C_TERM)
{
mod.position = MzTabString("Protein C-term");
}
else if (m.getTermSpecificity() == ResidueModification::PROTEIN_N_TERM)
{
mod.position = MzTabString("Protein N-term");
}
mod.site = MzTabString(m.getOrigin());
mods_mztab[index] = mod;
}
return mods_mztab;
}
static map<Size, MzTabModificationMetaData> generateMzTabStringFromVariableModifications(const vector<String>& mods)
{
if (mods.empty())
{
map<Size, MzTabModificationMetaData> mods_mztab;
MzTabModificationMetaData mod_mtd;
mod_mtd.modification.fromCellString("[MS, MS:1002454, No variable modifications searched, ]");
mods_mztab.insert(make_pair(1, mod_mtd));
return mods_mztab;
}
else
{
return generateMzTabStringFromModifications(mods);
}
}
static map<Size, MzTabModificationMetaData> generateMzTabStringFromFixedModifications(const vector<String>& mods)
{
if (mods.empty())
{
map<Size, MzTabModificationMetaData> mods_mztab;
MzTabModificationMetaData mod_mtd;
mod_mtd.modification.fromCellString("[MS, MS:1002453, No fixed modifications searched, ]");
mods_mztab.insert(make_pair(1, mod_mtd));
return mods_mztab;
}
else
{
return generateMzTabStringFromModifications(mods);
}
}
static MzTab exportFeatureMapToMzTab(const FeatureMap& feature_map, const String& filename)
{
LOG_INFO << "exporting feature map: \"" << filename << "\" to mzTab: " << std::endl;
MzTab mztab;
MzTabMetaData meta_data;
vector<ProteinIdentification> prot_ids = feature_map.getProteinIdentifications();
vector<String> var_mods, fixed_mods;
MzTabString db, db_version;
if (!prot_ids.empty())
{
ProteinIdentification::SearchParameters sp = prot_ids[0].getSearchParameters();
var_mods = sp.variable_modifications;
fixed_mods = sp.fixed_modifications;
db = sp.db.empty() ? MzTabString() : MzTabString(sp.db);
db_version = sp.db_version.empty() ? MzTabString() : MzTabString(sp.db_version);
}
meta_data.variable_mod = generateMzTabStringFromVariableModifications(var_mods);
meta_data.fixed_mod = generateMzTabStringFromFixedModifications(fixed_mods);
// mandatory meta values
meta_data.mz_tab_type = MzTabString("Quantification");
meta_data.mz_tab_mode = MzTabString("Summary");
meta_data.description = MzTabString("Export from featureXML");
MzTabMSRunMetaData ms_run;
StringList spectra_data;
feature_map.getPrimaryMSRunPath(spectra_data);
ms_run.location = spectra_data.empty() ? MzTabString("null") : MzTabString(spectra_data[0]);
meta_data.ms_run[1] = ms_run;
meta_data.uri[1] = MzTabString(filename);
meta_data.psm_search_engine_score[1] = MzTabParameter(); // TODO: we currently only support psm search engine scores annotated to the identification run
meta_data.peptide_search_engine_score[1] = MzTabParameter();
mztab.setMetaData(meta_data);
// pre-analyze data for occuring meta values at feature and peptide hit level
// these are used to build optional columns containing the meta values in internal data structures
set<String> feature_user_value_keys;
set<String> peptide_hit_user_value_keys;
for (Size i = 0; i < feature_map.size(); ++i)
{
const Feature& f = feature_map[i];
vector<String> keys;
f.getKeys(keys); //TODO: why not just return it?
feature_user_value_keys.insert(keys.begin(), keys.end());
const vector<PeptideIdentification>& pep_ids = f.getPeptideIdentifications();
for (vector<PeptideIdentification>::const_iterator it = pep_ids.begin(); it != pep_ids.end(); ++it)
{
for (vector<PeptideHit>::const_iterator hit = it->getHits().begin(); hit != it->getHits().end(); ++hit)
{
vector<String> ph_keys;
hit->getKeys(ph_keys);
peptide_hit_user_value_keys.insert(ph_keys.begin(), ph_keys.end());
}
}
}
MzTabPeptideSectionRows rows;
for (Size i = 0; i < feature_map.size(); ++i)
{
MzTabPeptideSectionRow row;
const Feature& f = feature_map[i];
row.mass_to_charge = MzTabDouble(f.getMZ());
MzTabDoubleList rt_list;
vector<MzTabDouble> rts;
rts.push_back(MzTabDouble(f.getRT()));
rt_list.set(rts);
row.retention_time = rt_list;
// set rt window if a bounding box has been set
vector<MzTabDouble> window;
if (f.getConvexHull().getBoundingBox() != DBoundingBox<2>())
{
window.push_back(MzTabDouble(f.getConvexHull().getBoundingBox().minX()));
window.push_back(MzTabDouble(f.getConvexHull().getBoundingBox().maxX()));
}
MzTabDoubleList rt_window;
rt_window.set(window);
row.retention_time_window = rt_window;
row.charge = MzTabInteger(f.getCharge());
row.peptide_abundance_stdev_study_variable[1];
row.peptide_abundance_std_error_study_variable[1];
row.peptide_abundance_study_variable[1] = MzTabDouble(f.getIntensity());
row.best_search_engine_score[1] = MzTabDouble();
row.search_engine_score_ms_run[1][1] = MzTabDouble();
// create opt_ column for peptide sequence containing modification
MzTabOptionalColumnEntry opt_global_modified_sequence;
opt_global_modified_sequence.first = String("opt_global_modified_sequence");
row.opt_.push_back(opt_global_modified_sequence);
// create and fill opt_ columns for feature (peptide) user values
addMetaInfoToOptionalColumns(feature_user_value_keys, row.opt_, String("global"), f);
const vector<PeptideIdentification>& pep_ids = f.getPeptideIdentifications();
if (pep_ids.empty())
{
rows.push_back(row);
continue;
}
// TODO: here we assume that all have the same score type etc.
vector<PeptideHit> all_hits;
for (vector<PeptideIdentification>::const_iterator it = pep_ids.begin(); it != pep_ids.end(); ++it)
{
all_hits.insert(all_hits.end(), it->getHits().begin(), it->getHits().end());
}
if (all_hits.empty())
{
rows.push_back(row);
continue;
}
// create new peptide id object to assist in sorting
PeptideIdentification new_pep_id = pep_ids[0];
new_pep_id.setHits(all_hits);
new_pep_id.assignRanks();
const PeptideHit& best_ph = new_pep_id.getHits()[0];
const AASequence& aas = best_ph.getSequence();
row.sequence = MzTabString(aas.toUnmodifiedString());
row.modifications = extractModificationListFromAASequence(aas, fixed_mods);
const set<String>& accessions = best_ph.extractProteinAccessionsSet();
const vector<PeptideEvidence> peptide_evidences = best_ph.getPeptideEvidences();
row.unique = accessions.size() == 1 ? MzTabBoolean(true) : MzTabBoolean(false);
// select accession of first peptide_evidence as representative ("leading") accession
row.accession = peptide_evidences.empty() ? MzTabString("null") : MzTabString(peptide_evidences[0].getProteinAccession());
row.best_search_engine_score[1] = MzTabDouble(best_ph.getScore());
row.search_engine_score_ms_run[1][1] = MzTabDouble(best_ph.getScore());
// find opt_global_modified_sequence in opt_ and set it to the OpenMS amino acid string (easier human readable than unimod accessions)
for (Size i = 0; i != row.opt_.size(); ++i)
{
MzTabOptionalColumnEntry& opt_entry = row.opt_[i];
if (opt_entry.first == String("opt_global_modified_sequence"))
{
opt_entry.second = MzTabString(aas.toString());
}
}
// create and fill opt_ columns for psm (PeptideHit) user values
addMetaInfoToOptionalColumns(peptide_hit_user_value_keys, row.opt_, String("global"), best_ph);
rows.push_back(row);
}
mztab.setPeptideSectionRows(rows);
return mztab;
}
static MzTab exportIdentificationsToMzTab(const vector<ProteinIdentification>& prot_ids, const vector<PeptideIdentification>& peptide_ids, const String& filename)
{
LOG_INFO << "exporting identifications: \"" << filename << "\" to mzTab: " << std::endl;
vector<PeptideIdentification> pep_ids = peptide_ids;
MzTab mztab;
MzTabMetaData meta_data;
vector<String> var_mods, fixed_mods;
MzTabString db, db_version;
String search_engine;
String search_engine_version;
if (!prot_ids.empty())
{
search_engine = prot_ids[0].getSearchEngine();
search_engine_version = prot_ids[0].getSearchEngineVersion();
}
// helper to map between peptide identifications and MS run
map<size_t, size_t> map_pep_idx_2_run;
if (!prot_ids.empty())
{
// map peptide ids back to their MS run
map<String, size_t> map_id_to_run;
// first: map run identifier to run index
size_t run_index(1);
for (auto it = prot_ids.begin(); it != prot_ids.end(); ++it, ++run_index)
{
map_id_to_run[it->getIdentifier()] = run_index;
}
// second: map peptide index to run index
size_t psm_idx(0);
for (auto it = peptide_ids.begin(); it != peptide_ids.end(); ++it, ++psm_idx)
{
size_t run_idx = map_id_to_run[it->getIdentifier()];
map_pep_idx_2_run[psm_idx] = run_idx;
}
MzTabParameter protein_score_type;
protein_score_type.fromCellString("[,,custom score,]"); // TODO at least it should be noted if higher score is better. Better document type of score
meta_data.protein_search_engine_score[1] = protein_score_type; // TODO add meta value to ProteinIdentification
ProteinIdentification::SearchParameters sp = prot_ids[0].getSearchParameters();
var_mods = sp.variable_modifications;
fixed_mods = sp.fixed_modifications;
db = sp.db.empty() ? MzTabString() : MzTabString(sp.db);
db_version = sp.db_version.empty() ? MzTabString() : MzTabString(sp.db_version);
//sp.digestion_enzyme
//sp.missed_cleavages
// generate protein section
MzTabProteinSectionRows protein_rows;
Size current_run_index(1);
for (auto it = prot_ids.begin(); it != prot_ids.end(); ++it, ++current_run_index)
{
const std::vector<ProteinIdentification::ProteinGroup> protein_groups = it->getProteinGroups();
const std::vector<ProteinIdentification::ProteinGroup> indist_groups = it->getIndistinguishableProteins();
const std::vector<ProteinHit> protein_hits = it->getHits();
MzTabMSRunMetaData ms_run;
StringList ms_run_in_data;
it->getPrimaryMSRunPath(ms_run_in_data);
ms_run.location = ms_run_in_data.empty() ? MzTabString("null") : MzTabString(ms_run_in_data[0]);
// TODO: add processing information that this file has been exported from "filename"
meta_data.ms_run[current_run_index] = ms_run;
// pre-analyze data for occuring meta values at protein hit level
// these are used to build optional columns containing the meta values in internal data structures
set<String> protein_hit_user_value_keys =
MetaInfoInterfaceUtils::findCommonMetaKeys<vector<ProteinHit>, set<String> >(protein_hits.begin(), protein_hits.end(), 100.0);
// we do not want descriptions twice
protein_hit_user_value_keys.erase("Description");
for (Size i = 0; i != protein_hits.size(); ++i)
{
const ProteinHit& hit = protein_hits[i];
MzTabProteinSectionRow protein_row;
protein_row.accession = MzTabString(hit.getAccession());
protein_row.description = MzTabString(hit.getDescription());
// protein_row.taxid = hit.getTaxonomyID(); // TODO add as meta value to protein hitNEWT taxonomy for the species.
// MzTabString species = hit.getSpecies(); // Human readable name of the species
protein_row.database = db; // Name of the protein database.
protein_row.database_version = db_version; // String Version of the protein database.
protein_row.best_search_engine_score[1] = MzTabDouble(hit.getScore());
// MzTabParameterList search_engine; // Search engine(s) identifying the protein.
// std::map<Size, MzTabDouble> best_search_engine_score; // best_search_engine_score[1-n]
// std::map<Size, std::map<Size, MzTabDouble> > search_engine_score_ms_run; // search_engine_score[index1]_ms_run[index2]
// MzTabInteger reliability;
// std::map<Size, MzTabInteger> num_psms_ms_run;
// std::map<Size, MzTabInteger> num_peptides_distinct_ms_run;
// std::map<Size, MzTabInteger> num_peptides_unique_ms_run;
// MzTabModificationList modifications; // Modifications identified in the protein.
// MzTabString uri; // Location of the protein’s source entry.
// MzTabStringList go_terms; // List of GO terms for the protein.
double coverage = hit.getCoverage();
protein_row.protein_coverage = coverage >= 0 ? MzTabDouble(coverage) : MzTabDouble(); // (0-1) Amount of protein sequence identified.
// std::vector<MzTabOptionalColumnEntry> opt_; // Optional Columns must start with “opt_”
// create and fill opt_ columns for protein hit user values
addMetaInfoToOptionalColumns(protein_hit_user_value_keys, protein_row.opt_, String("global"), hit);
// optional column for protein groups
MzTabOptionalColumnEntry opt_column_entry;
opt_column_entry.first = "opt_global_protein_group_type";
opt_column_entry.second = MzTabString("single_protein");
protein_row.opt_.push_back(opt_column_entry);
protein_rows.push_back(protein_row);
}
// Protein groups are currently simply PRT rows with extra opt columns
for (Size i = 0; i != protein_groups.size(); ++i)
{
const ProteinIdentification::ProteinGroup& group = protein_groups[i];
MzTabProteinSectionRow protein_row;
protein_row.database = db; // Name of the protein database.
protein_row.database_version = db_version; // String Version of the protein database.
MzTabStringList ambiguity_members;
ambiguity_members.setSeparator(',');
vector<MzTabString> entries;
for (Size j = 0; j != group.accessions.size() ; ++j)
{
// set accession and description to first element of group
if (j == 0)
{
protein_row.accession = MzTabString(group.accessions[j]);
// protein_row.description // TODO: how to set description? information not contained in group
}
entries.push_back(MzTabString(group.accessions[j]));
}
ambiguity_members.set(entries);
protein_row.ambiguity_members = ambiguity_members; // Alternative protein identifications.
protein_row.best_search_engine_score[1] = MzTabDouble(group.probability);
MzTabOptionalColumnEntry opt_column_entry;
opt_column_entry.first = "opt_global_protein_group_type";
opt_column_entry.second = MzTabString("protein_group");
protein_row.opt_.push_back(opt_column_entry);
protein_rows.push_back(protein_row);
}
for (Size i = 0; i != indist_groups.size(); ++i)
{
const ProteinIdentification::ProteinGroup& group = indist_groups[i];
MzTabProteinSectionRow protein_row;
protein_row.database = db; // Name of the protein database.
protein_row.database_version = db_version; // String Version of the protein database.
MzTabStringList ambiguity_members;
ambiguity_members.setSeparator(',');
vector<MzTabString> entries;
for (Size j = 0; j != group.accessions.size() ; ++j)
{
// set accession and description to first element of group
if (j == 0)
{
protein_row.accession = MzTabString(group.accessions[j]);
}
entries.push_back(MzTabString(group.accessions[j]));
}
ambiguity_members.set(entries);
protein_row.ambiguity_members = ambiguity_members; // Alternative protein identifications.
MzTabOptionalColumnEntry opt_column_entry;
opt_column_entry.first = "opt_global_protein_group_type";
opt_column_entry.second = MzTabString("indistinguishable_group");
protein_row.opt_.push_back(opt_column_entry);
protein_row.best_search_engine_score[1] = MzTabDouble(group.probability);
//std::vector<MzTabOptionalColumnEntry> opt_; // Optional Columns must start with “opt_”
protein_rows.push_back(protein_row);
}
}
mztab.setProteinSectionRows(protein_rows);
}
// end protein groups
// start PSMs
// mandatory meta values
meta_data.mz_tab_type = MzTabString("Identification");
meta_data.mz_tab_mode = MzTabString("Summary");
meta_data.description = MzTabString("Export from idXML");
meta_data.variable_mod = generateMzTabStringFromModifications(var_mods);
meta_data.fixed_mod = generateMzTabStringFromModifications(fixed_mods);
MzTabParameter psm_search_engine_score;
psm_search_engine_score.fromCellString("[,," + search_engine + "," + search_engine_version + "]");
meta_data.psm_search_engine_score[1] = psm_search_engine_score;
mztab.setMetaData(meta_data);
MzTabPSMSectionRows rows;
Size psm_id(0);
for (auto it = pep_ids.begin(); it != pep_ids.end(); ++it, ++psm_id)
{
// skip empty peptide identification objects
if (it->getHits().empty())
{
continue;
}
// sort by rank
it->assignRanks();
MzTabPSMSectionRow row;
// link to MS run
size_t run_index = map_pep_idx_2_run[psm_id];
String spectrum_nativeID = it->getMetaValue("spectrum_reference").toString();
MzTabSpectraRef spec_ref;
row.spectra_ref.setMSFile(run_index);
row.spectra_ref.setSpecRef(spectrum_nativeID);
// only consider best peptide hit for export
const PeptideHit& best_ph = it->getHits()[0];
const AASequence& aas = best_ph.getSequence();
row.sequence = MzTabString(aas.toUnmodifiedString());
// extract all modifications in the current sequence for reporting. In contrast to peptide and protein section all modifications are reported.
row.modifications = extractModificationListFromAASequence(aas);
row.PSM_ID = MzTabInteger(psm_id);
row.database = db;
row.database_version = db_version;
MzTabParameterList search_engines;
search_engines.fromCellString("[,," + search_engine + "," + search_engine_version + "]");
row.search_engine = search_engines;
row.search_engine_score[1] = MzTabDouble(best_ph.getScore());
vector<MzTabDouble> rts_vector;
rts_vector.push_back(MzTabDouble(it->getRT()));
MzTabDoubleList rts;
rts.set(rts_vector);
row.retention_time = rts;
row.charge = MzTabInteger(best_ph.getCharge());
row.exp_mass_to_charge = MzTabDouble(it->getMZ());
row.calc_mass_to_charge = best_ph.getCharge() != 0 ? MzTabDouble(aas.getMonoWeight(Residue::Full, best_ph.getCharge()) / best_ph.getCharge()) : MzTabDouble();
// add opt_global_modified_sequence in opt_ and set it to the OpenMS amino acid string (easier human readable than unimod accessions)
MzTabOptionalColumnEntry opt_entry;
opt_entry.first = String("opt_global_modified_sequence");
opt_entry.second = MzTabString(aas.toString());
row.opt_.push_back(opt_entry);
// currently write all keys
// TODO: percentage procedure with MetaInfoInterfaceUtils
vector<String> ph_keys;
best_ph.getKeys(ph_keys);
// TODO: no conversion but make function on collections
set<String> ph_key_set(ph_keys.begin(), ph_keys.end());
addMetaInfoToOptionalColumns(ph_key_set, row.opt_, String("global"), best_ph);
// TODO Think about if the uniqueness can be determined by # of peptide evidences
// b/c this would only differ when evidences come from different DBs
const set<String>& accessions = best_ph.extractProteinAccessionsSet();
row.unique = accessions.size() == 1 ? MzTabBoolean(true) : MzTabBoolean(false);
// create row for every PeptideEvidence entry (mapping to a protein)
const vector<PeptideEvidence> peptide_evidences = best_ph.getPeptideEvidences();
// pass common row entries and create rows for all peptide evidences
addPepEvidenceToRows(peptide_evidences, row, rows);
}
mztab.setPSMSectionRows(rows);
return mztab;
}
// Generate MzTab style list of PTMs from AASequence object.
// All passed fixed modifications are not reported (as suggested by the standard for the PRT and PEP section).
// In contrast, all modifications are reported in the PSM section (see standard document for details).
static MzTabModificationList extractModificationListFromAASequence(const AASequence& aas, const vector<String>& fixed_mods = vector<String>())
{
MzTabModificationList mod_list;
vector<MzTabModification> mods;
if (aas.isModified())
{
if (aas.hasNTerminalModification())
{
MzTabModification mod;
const ResidueModification& res_mod = *(aas.getNTerminalModification());
if (std::find(fixed_mods.begin(), fixed_mods.end(), res_mod.getId()) == fixed_mods.end())
{
MzTabString unimod_accession = MzTabString(res_mod.getUniModAccession());
vector<std::pair<Size, MzTabParameter> > pos;
pos.push_back(make_pair(0, MzTabParameter()));
mod.setModificationIdentifier(unimod_accession);
mod.setPositionsAndParameters(pos);
mods.push_back(mod);
}
}
for (Size ai = 0; ai != aas.size(); ++ai)
{
if (aas[ai].isModified())
{
MzTabModification mod;
const ResidueModification& res_mod = *(aas[ai].getModification());
if (std::find(fixed_mods.begin(), fixed_mods.end(), res_mod.getId()) == fixed_mods.end())
{
// MzTab standard is to just report Unimod accession.
MzTabString unimod_accession = MzTabString(res_mod.getUniModAccession());
vector<std::pair<Size, MzTabParameter> > pos;
pos.push_back(make_pair(ai + 1, MzTabParameter()));
mod.setPositionsAndParameters(pos);
mod.setModificationIdentifier(unimod_accession);
mods.push_back(mod);
}
}
}
if (aas.hasCTerminalModification())
{
MzTabModification mod;
const ResidueModification& res_mod = *(aas.getCTerminalModification());
if (std::find(fixed_mods.begin(), fixed_mods.end(), res_mod.getId()) == fixed_mods.end())
{
MzTabString unimod_accession = MzTabString(res_mod.getUniModAccession());
vector<std::pair<Size, MzTabParameter> > pos;
pos.push_back(make_pair(aas.size() + 1, MzTabParameter()));
mod.setPositionsAndParameters(pos);
mod.setModificationIdentifier(unimod_accession);
mods.push_back(mod);
}
}
}
mod_list.set(mods);
return mod_list;
}
static MzTab exportConsensusMapToMzTab(const ConsensusMap& consensus_map, const String& filename)
{
LOG_INFO << "exporting consensus map: \"" << filename << "\" to mzTab: " << std::endl;
MzTab mztab;
vector<ProteinIdentification> prot_ids = consensus_map.getProteinIdentifications();
vector<String> var_mods, fixed_mods;
MzTabString db, db_version;
if (!prot_ids.empty())
{
ProteinIdentification::SearchParameters sp = prot_ids[0].getSearchParameters();
var_mods = sp.variable_modifications;
fixed_mods = sp.fixed_modifications;
db = sp.db.empty() ? MzTabString() : MzTabString(sp.db);
db_version = sp.db_version.empty() ? MzTabString() : MzTabString(sp.db_version);
}
// determine number of quant. columns
Size n_study_variables = consensus_map.getColumnHeaders().size();
MzTabMetaData meta_data;
// mandatory meta values
meta_data.mz_tab_type = MzTabString("Quantification");
meta_data.mz_tab_mode = MzTabString("Summary");
meta_data.description = MzTabString("Export from consensusXML");
// For consensusXML we export a "Summary Quantification" file. This means we don't need to report feature quantification values at the assay level
// but only at the study variable variable level.
meta_data.variable_mod = generateMzTabStringFromModifications(var_mods);
meta_data.fixed_mod = generateMzTabStringFromModifications(fixed_mods);
meta_data.peptide_search_engine_score[1] = MzTabParameter();
meta_data.psm_search_engine_score[1] = MzTabParameter(); // TODO insert search engine information
StringList ms_runs;
consensus_map.getPrimaryMSRunPath(ms_runs);
// condense consecutive unique MS runs to get the different MS files
auto it = std::unique(ms_runs.begin(), ms_runs.end());
ms_runs.resize(std::distance(ms_runs.begin(), it));
// set run meta data
Size run_index{1};
for (auto const & m : ms_runs)
{
MzTabMSRunMetaData mztab_run_metadata;
mztab_run_metadata.format.fromCellString("[MS,MS:1000584,mzML file,]");
mztab_run_metadata.id_format.fromCellString("[MS,MS:1001530,mzML unique identifier,]");
mztab_run_metadata.location = MzTabString(m);
meta_data.ms_run[run_index] = mztab_run_metadata;
LOG_DEBUG << "Adding MS run for file: " << m << endl;
++run_index;
}
mztab.setMetaData(meta_data);
// pre-analyze data for occurring meta values at consensus feature and peptide hit level
// these are used to build optional columns containing the meta values in internal data structures
set<String> consensus_feature_user_value_keys;
set<String> peptide_hit_user_value_keys;
for (Size i = 0; i < consensus_map.size(); ++i)
{
const ConsensusFeature& c = consensus_map[i];
vector<String> keys;
c.getKeys(keys);
consensus_feature_user_value_keys.insert(keys.begin(), keys.end());
const vector<PeptideIdentification>& pep_ids = c.getPeptideIdentifications();
for (vector<PeptideIdentification>::const_iterator it = pep_ids.begin(); it != pep_ids.end(); ++it)
{
for (vector<PeptideHit>::const_iterator hit = it->getHits().begin(); hit != it->getHits().end(); ++hit)
{
vector<String> ph_keys;
hit->getKeys(ph_keys);
peptide_hit_user_value_keys.insert(ph_keys.begin(), ph_keys.end());
}
}
}
MzTabPeptideSectionRows rows;
for (Size i = 0; i < consensus_map.size(); ++i)
{
MzTabPeptideSectionRow row;
const ConsensusFeature& c = consensus_map[i];
// create opt_ column for peptide sequence containing modification
MzTabOptionalColumnEntry opt_global_modified_sequence;
opt_global_modified_sequence.first = String("opt_global_modified_sequence");
row.opt_.push_back(opt_global_modified_sequence);
// create opt_ columns for consensus feature (peptide) user values
for (set<String>::const_iterator mit = consensus_feature_user_value_keys.begin(); mit != consensus_feature_user_value_keys.end(); ++mit)
{
MzTabOptionalColumnEntry opt_entry;
const String& key = *mit;
opt_entry.first = String("opt_global_") + key;
if (c.metaValueExists(key))
{
opt_entry.second = MzTabString(c.getMetaValue(key).toString());
} // otherwise it is default ("null")
row.opt_.push_back(opt_entry);
}
// create opt_ columns for psm (PeptideHit) user values
for (set<String>::const_iterator mit = peptide_hit_user_value_keys.begin(); mit != peptide_hit_user_value_keys.end(); ++mit)
{
MzTabOptionalColumnEntry opt_entry;
const String& key = *mit;
opt_entry.first = String("opt_global_") + key;
// leave value empty as we have to fill it with the value from the best peptide hit
row.opt_.push_back(opt_entry);
}
row.mass_to_charge = MzTabDouble(c.getMZ());
MzTabDoubleList rt_list;
vector<MzTabDouble> rts;
rts.push_back(MzTabDouble(c.getRT()));
rt_list.set(rts);
row.retention_time = rt_list;
MzTabDoubleList rt_window;
row.retention_time_window = rt_window;
row.charge = MzTabInteger(c.getCharge());
row.best_search_engine_score[1] = MzTabDouble();
// initialize columns
for (Size study_variable = 1; study_variable <= n_study_variables; ++study_variable)
{
row.peptide_abundance_stdev_study_variable[study_variable] = MzTabDouble();
row.peptide_abundance_std_error_study_variable[study_variable] = MzTabDouble();
row.peptide_abundance_study_variable[study_variable] = MzTabDouble();
}
for (Size ms_run = 1; ms_run <= ms_runs.size(); ++ms_run)
{
row.search_engine_score_ms_run[1][ms_run] = MzTabDouble();
}
ConsensusFeature::HandleSetType fs = c.getFeatures();
for (ConsensusFeature::HandleSetType::const_iterator fit = fs.begin(); fit != fs.end(); ++fit)
{
Size study_variable = fit->getMapIndex() + 1;
row.peptide_abundance_stdev_study_variable[study_variable];
row.peptide_abundance_std_error_study_variable[study_variable];
row.peptide_abundance_study_variable[study_variable] = MzTabDouble(fit->getIntensity());
}
vector<PeptideIdentification> pep_ids = c.getPeptideIdentifications();
if (!pep_ids.empty())
{
if (pep_ids.size() != 1)
{
throw OpenMS::Exception::IllegalArgument(__FILE__, __LINE__, __FUNCTION__, "Consensus features may contain at most one identification. Run IDConflictResolver first to remove ambiguities!");
}
pep_ids[0].assignRanks();
const PeptideHit& best_ph = pep_ids[0].getHits()[0];
const AASequence& aas = best_ph.getSequence();
row.sequence = MzTabString(aas.toUnmodifiedString());
row.modifications = extractModificationListFromAASequence(aas, fixed_mods);
const set<String>& accessions = best_ph.extractProteinAccessionsSet();
const vector<PeptideEvidence> peptide_evidences = best_ph.getPeptideEvidences();
row.unique = accessions.size() == 1 ? MzTabBoolean(true) : MzTabBoolean(false);
// select accession of first peptide_evidence as representative ("leading") accession
row.accession = peptide_evidences.empty() ? MzTabString("null") : MzTabString(peptide_evidences[0].getProteinAccession());
row.best_search_engine_score[1] = MzTabDouble(best_ph.getScore());
// TODO: support run level scores - for now we assume we got the same score from every ms run
for (Size ms_run = 1; ms_run <= ms_runs.size(); ++ms_run)
{
row.search_engine_score_ms_run[1][ms_run] = MzTabDouble(best_ph.getScore());
}
// fill opt_ columns
// find opt_global_modified_sequence in opt_ and set it to the OpenMS amino acid string (easier human readable than unimod accessions)
for (Size i = 0; i != row.opt_.size(); ++i)
{
MzTabOptionalColumnEntry& opt_entry = row.opt_[i];
if (opt_entry.first == String("opt_global_modified_sequence"))
{
opt_entry.second = MzTabString(aas.toString());
}
}
// fill opt_ column of psm
vector<String> ph_keys;
best_ph.getKeys(ph_keys);
for (Size k = 0; k != ph_keys.size(); ++k)
{
const String& key = ph_keys[k];
// find matching entry in opt_ (TODO: speed this up)
for (Size i = 0; i != row.opt_.size(); ++i)
{
MzTabOptionalColumnEntry& opt_entry = row.opt_[i];
if (opt_entry.first == String("opt_global_") + key)
{
opt_entry.second = MzTabString(best_ph.getMetaValue(key).toString());
}
}
}
}
rows.push_back(row);
}
mztab.setPeptideSectionRows(rows);
return mztab;
}
ExitCodes main_(int, const char**) override
{
// parameter handling
String in = getStringOption_("in");
FileTypes::Type in_type = FileHandler().getType(in);
String out = getStringOption_("out");
MzTab mztab;
if (in_type == FileTypes::FEATUREXML)
{
// For featureXML we export a "Summary Quantification" file. This means we don't need to report feature quantification values at the assay level
// but only at the (single) study variable variable level.
// load featureXML
FeatureMap feature_map;
FeatureXMLFile f;
f.load(in, feature_map);
// calculate coverage
vector<PeptideIdentification> pep_ids;
vector<ProteinIdentification> prot_ids = feature_map.getProteinIdentifications();
for (Size i = 0; i < feature_map.size(); ++i) // collect all (assigned and unassigned to a feature) peptide ids
{
vector<PeptideIdentification> pep_ids_bf = feature_map[i].getPeptideIdentifications();
pep_ids.insert(pep_ids.end(), pep_ids_bf.begin(), pep_ids_bf.end());
}
pep_ids.insert(pep_ids.end(), feature_map.getUnassignedPeptideIdentifications().begin(), feature_map.getUnassignedPeptideIdentifications().end());
try // might throw Exception::MissingInformation()
{
for (Size i = 0; i < prot_ids.size(); ++i)
{
prot_ids[i].computeCoverage(pep_ids);
}
}
catch (Exception::MissingInformation& e)
{
LOG_WARN << "Non-critical exception: " << e.what() << "\n";
}
feature_map.setProteinIdentifications(prot_ids);
mztab = exportFeatureMapToMzTab(feature_map, in);
}
// export identification data from idXML
if (in_type == FileTypes::IDXML)
{
String document_id;
vector<ProteinIdentification> prot_ids;
vector<PeptideIdentification> pep_ids;
IdXMLFile().load(in, prot_ids, pep_ids, document_id);
mztab = exportIdentificationsToMzTab(prot_ids, pep_ids, in);
}
// export identification data from mzIdentML
if (in_type == FileTypes::MZIDENTML)
{
String document_id;
vector<ProteinIdentification> prot_ids;
vector<PeptideIdentification> pep_ids;
MzIdentMLFile().load(in, prot_ids, pep_ids);
mztab = exportIdentificationsToMzTab(prot_ids, pep_ids, in);
}
// export quantification data
if (in_type == FileTypes::CONSENSUSXML)
{
ConsensusMap consensus_map;
ConsensusXMLFile c;
c.load(in, consensus_map);
mztab = exportConsensusMapToMzTab(consensus_map, in);
}
MzTabFile().store(out, mztab);
return EXECUTION_OK;
}
};
} //namespace OpenMS
#pragma clang diagnostic pop
int main(int argc, const char** argv)
{
TOPPMzTabExporter t;
return t.main(argc, argv);
}
/// @endcond
| 42.455935 | 201 | 0.646057 | [
"object",
"vector"
] |
c8553709bd85602b7b482194eb613d4bb416707f | 1,911 | cpp | C++ | uva.onlinejudge.org/Frogger.cpp | facug91/OJ-Solutions | 9aa55be066ce5596e4e64737c28cd3ff84e092fe | [
"Apache-2.0"
] | 6 | 2016-09-10T03:16:34.000Z | 2020-04-07T14:45:32.000Z | uva.onlinejudge.org/Frogger.cpp | facug91/OJ-Solutions | 9aa55be066ce5596e4e64737c28cd3ff84e092fe | [
"Apache-2.0"
] | null | null | null | uva.onlinejudge.org/Frogger.cpp | facug91/OJ-Solutions | 9aa55be066ce5596e4e64737c28cd3ff84e092fe | [
"Apache-2.0"
] | 2 | 2018-08-11T20:55:35.000Z | 2020-01-15T23:23:11.000Z | /*
By: facug91
From: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=475
Name: Frogger
Date: 17/10/2015
*/
#include <bits/stdc++.h>
#define y1 nd03dnqwuidg1odbnw9uddu0132d
#define clock asoudh219udhjdgausdhs9udy433
#define left dfgag34gsfaf342rf23fgwrf42ff
#define middle lk78k6ujkj76kjk88kkummnhh456
#define right apidwcojbl213f80sjb3y8efjfas
#define move df53y5fgsf43fdsfsdtg4j6hfdg4
#define count nkwdfj111afbjdfsbj32r8yfwejb
#define prev asdnklgbgbjfasdbhksdva4t9jds
#define endl "\n"
#define EPS 1e-9
#define MP make_pair
#define F first
#define S second
#define DB(x) cerr << " #" << (#x) << ": " << (x)
#define DBL(x) cerr << " #" << (#x) << ": " << (x) << endl
const double PI = 2.0*acos(0.0);
#define INF 1000000000
//#define MOD 1000000007ll
//#define MAXN 1100000000000000ll
using namespace std;
typedef long long ll;
typedef unsigned long long llu;
typedef pair<int, int> ii; typedef pair<ii, ii> iiii;
typedef vector<int> vi; typedef vector<ii> vii; typedef vector<iiii> viiii;
int n;
double x, y, adj[205][205];
vector<pair<double, double> > coor;
double dist (int i, int j) {
return hypot(coor[i].first-coor[j].first, coor[i].second-coor[j].second);
}
int main () {
ios_base::sync_with_stdio(0); cin.tie(0);
cout<<fixed<<setprecision(3); cerr<<fixed<<setprecision(3); //cin.ignore(INT_MAX, ' '); //cout << setfill('0') << setw(5) << 25
int tc = 1, i, j, k;
while (cin>>n, n) {
coor.clear();
for (i=0; i<n; i++) {
cin>>x>>y;
coor.push_back(MP(x, y));
}
for (i=0; i<n; i++) adj[i][i] = 0;
for (i=0; i<n; i++) for (j=0; j<n; j++) adj[i][j] = dist(i, j);
for (k=0; k<n; k++)
for (i=0; i<n; i++)
for (j=0; j<n; j++)
adj[i][j] = min(adj[i][j], max(adj[i][k], adj[k][j]));
cout<<"Scenario #"<<tc++<<endl;
cout<<"Frog Distance = "<<adj[0][1]<<endl<<endl;
}
return 0;
}
| 28.522388 | 128 | 0.641549 | [
"vector"
] |
c85720704c5964066f1d3b15c2885ae88ca76926 | 13,925 | hxx | C++ | include/opengm/inference/alphaexpansion.hxx | yanlend/opengm | 910cba0323ddafd1f1b8bb5d4483d77dba234efd | [
"MIT"
] | null | null | null | include/opengm/inference/alphaexpansion.hxx | yanlend/opengm | 910cba0323ddafd1f1b8bb5d4483d77dba234efd | [
"MIT"
] | null | null | null | include/opengm/inference/alphaexpansion.hxx | yanlend/opengm | 910cba0323ddafd1f1b8bb5d4483d77dba234efd | [
"MIT"
] | null | null | null | #pragma once
#ifndef OPENGM_ALPHAEXPANSION_HXX
#define OPENGM_ALPHAEXPANSION_HXX
#include "opengm/inference/inference.hxx"
#include "opengm/inference/new_visitors/new_visitors.hxx"
namespace opengm {
/// Alpha-Expansion Algorithm
/// \ingroup inference
template<class GM, class INF>
class AlphaExpansion
: public Inference<GM, typename INF::AccumulationType>
{
public:
typedef GM GraphicalModelType;
typedef INF InferenceType;
typedef typename INF::AccumulationType AccumulationType;
OPENGM_GM_TYPE_TYPEDEFS;
typedef visitors::VerboseVisitor<AlphaExpansion<GM,INF> > VerboseVisitorType;
typedef visitors::EmptyVisitor<AlphaExpansion<GM,INF> > EmptyVisitorType;
typedef visitors::TimingVisitor<AlphaExpansion<GM,INF> > TimingVisitorType;
struct Parameter {
typedef typename InferenceType::Parameter InferenceParameter;
enum LabelingIntitialType {DEFAULT_LABEL, RANDOM_LABEL, LOCALOPT_LABEL, EXPLICIT_LABEL};
enum OrderType {DEFAULT_ORDER, RANDOM_ORDER, EXPLICIT_ORDER};
Parameter
(
const size_t maxNumberOfSteps = 1000,
const InferenceParameter& para = InferenceParameter()
)
: parameter_(para),
maxNumberOfSteps_(maxNumberOfSteps),
labelInitialType_(DEFAULT_LABEL),
orderType_(DEFAULT_ORDER),
randSeedOrder_(0),
randSeedLabel_(0),
labelOrder_(),
label_()
{}
InferenceParameter parameter_;
size_t maxNumberOfSteps_;
LabelingIntitialType labelInitialType_;
OrderType orderType_;
unsigned int randSeedOrder_;
unsigned int randSeedLabel_;
std::vector<LabelType> labelOrder_;
std::vector<LabelType> label_;
};
AlphaExpansion(const GraphicalModelType&, Parameter para = Parameter());
std::string name() const;
const GraphicalModelType& graphicalModel() const;
template<class StateIterator>
void setState(StateIterator, StateIterator);
InferenceTermination infer();
void reset();
template<class Visitor>
InferenceTermination infer(Visitor& visitor);
void setStartingPoint(typename std::vector<LabelType>::const_iterator);
InferenceTermination arg(std::vector<LabelType>&, const size_t = 1) const;
private:
const GraphicalModelType& gm_;
Parameter parameter_;
std::vector<LabelType> label_;
std::vector<LabelType> labelList_;
size_t maxState_;
size_t alpha_;
size_t counter_;
void incrementAlpha();
void setLabelOrder(std::vector<LabelType>& l);
void setLabelOrderRandom(unsigned int);
void setInitialLabel(std::vector<LabelType>& l);
void setInitialLabelLocalOptimal();
void setInitialLabelRandom(unsigned int);
void addUnary(INF&, const size_t var, const ValueType v0, const ValueType v1);
void addPairwise(INF&, const size_t var1, const size_t var2, const ValueType v0, const ValueType v1, const ValueType v2, const ValueType v3);
};
template<class GM, class INF>
inline std::string
AlphaExpansion<GM, INF>::name() const
{
return "Alpha-Expansion";
}
template<class GM, class INF>
inline const typename AlphaExpansion<GM, INF>::GraphicalModelType&
AlphaExpansion<GM, INF>::graphicalModel() const
{
return gm_;
}
template<class GM, class INF>
template<class StateIterator>
inline void
AlphaExpansion<GM, INF>::setState
(
StateIterator begin,
StateIterator end
)
{
label_.assign(begin, end);
}
template<class GM, class INF>
inline void
AlphaExpansion<GM,INF>::setStartingPoint
(
typename std::vector<typename AlphaExpansion<GM,INF>::LabelType>::const_iterator begin
) {
try{
label_.assign(begin, begin+gm_.numberOfVariables());
}
catch(...) {
throw RuntimeError("unsuitable starting point");
}
}
template<class GM, class INF>
inline
AlphaExpansion<GM, INF>::AlphaExpansion
(
const GraphicalModelType& gm,
Parameter para
)
: gm_(gm),
parameter_(para),
maxState_(0)
{
for(size_t j=0; j<gm_.numberOfFactors(); ++j) {
if(gm_[j].numberOfVariables() > 2) {
throw RuntimeError("This implementation of Alpha-Expansion supports only factors of order <= 2.");
}
}
for(size_t i=0; i<gm_.numberOfVariables(); ++i) {
size_t numSt = gm_.numberOfLabels(i);
if(numSt > maxState_) {
maxState_ = numSt;
}
}
if(parameter_.labelInitialType_ == Parameter::RANDOM_LABEL) {
setInitialLabelRandom(parameter_.randSeedLabel_);
}
else if(parameter_.labelInitialType_ == Parameter::LOCALOPT_LABEL) {
setInitialLabelLocalOptimal();
}
else if(parameter_.labelInitialType_ == Parameter::EXPLICIT_LABEL) {
setInitialLabel(parameter_.label_);
}
else{
label_.resize(gm_.numberOfVariables(), 0);
}
if(parameter_.orderType_ == Parameter::RANDOM_ORDER) {
setLabelOrderRandom(parameter_.randSeedOrder_);
}
else if(parameter_.orderType_ == Parameter::EXPLICIT_ORDER) {
setLabelOrder(parameter_.labelOrder_);
}
else{
labelList_.resize(maxState_);
for(size_t i=0; i<maxState_; ++i)
labelList_[i] = i;
}
counter_ = 0;
alpha_ = labelList_[counter_];
}
// reset assumes that the structure of
// the graphical model has not changed
template<class GM, class INF>
inline void
AlphaExpansion<GM, INF>::reset() {
if(parameter_.labelInitialType_ == Parameter::RANDOM_LABEL) {
setInitialLabelRandom(parameter_.randSeedLabel_);
}
else if(parameter_.labelInitialType_ == Parameter::LOCALOPT_LABEL) {
setInitialLabelLocalOptimal();
}
else if(parameter_.labelInitialType_ == Parameter::EXPLICIT_LABEL) {
setInitialLabel(parameter_.label_);
}
else{
std::fill(label_.begin(),label_.end(),0);
}
if(parameter_.orderType_ == Parameter::RANDOM_ORDER) {
setLabelOrderRandom(parameter_.randSeedOrder_);
}
else if(parameter_.orderType_ == Parameter::EXPLICIT_ORDER) {
setLabelOrder(parameter_.labelOrder_);
}
else{
for(size_t i=0; i<maxState_; ++i)
labelList_[i] = i;
}
counter_ = 0;
alpha_ = labelList_[counter_];
}
template<class GM, class INF>
inline void
AlphaExpansion<GM, INF>::addUnary
(
INF& inf,
const size_t var1,
const ValueType v0,
const ValueType v1
) {
const size_t shape[] = {2};
size_t vars[] = {var1};
opengm::IndependentFactor<ValueType,IndexType,LabelType> fac(vars, vars+1, shape, shape+1);
fac(0) = v0;
fac(1) = v1;
inf.addFactor(fac);
}
template<class GM, class INF>
inline void
AlphaExpansion<GM, INF>::addPairwise
(
INF& inf,
const size_t var1,
const size_t var2,
const ValueType v0,
const ValueType v1,
const ValueType v2,
const ValueType v3
) {
const LabelType shape[] = {2, 2};
const IndexType vars[] = {var1, var2};
opengm::IndependentFactor<ValueType,IndexType,LabelType> fac(vars, vars+2, shape, shape+2);
fac(0, 0) = v0;
fac(0, 1) = v1;
fac(1, 0) = v2;
fac(1, 1) = v3;
inf.addFactor(fac);
}
template<class GM, class INF>
inline InferenceTermination
AlphaExpansion<GM, INF>::infer()
{
EmptyVisitorType visitor;
return infer(visitor);
}
template<class GM, class INF>
template<class Visitor>
InferenceTermination
AlphaExpansion<GM, INF>::infer
(
Visitor& visitor
)
{
bool exitInf = false;
size_t it = 0;
size_t countUnchanged = 0;
size_t numberOfVariables = gm_.numberOfVariables();
std::vector<size_t> variable2Node(numberOfVariables);
ValueType energy = gm_.evaluate(label_);
visitor.begin(*this);
LabelType vecA[1];
LabelType vecX[1];
LabelType vecAA[2];
LabelType vecAX[2];
LabelType vecXA[2];
LabelType vecXX[2];
while(it++ < parameter_.maxNumberOfSteps_ && countUnchanged < maxState_ && exitInf == false) {
size_t numberOfAuxiliaryNodes = 0;
for(size_t k=0 ; k<gm_.numberOfFactors(); ++k) {
const FactorType& factor = gm_[k];
if(factor.numberOfVariables() == 2) {
size_t var1 = factor.variableIndex(0);
size_t var2 = factor.variableIndex(1);
if(label_[var1] != label_[var2] && label_[var1] != alpha_ && label_[var2] != alpha_ ) {
++numberOfAuxiliaryNodes;
}
}
}
std::vector<size_t> numFacDim(4, 0);
INF inf(numberOfVariables + numberOfAuxiliaryNodes, numFacDim, parameter_.parameter_);
size_t varX = numberOfVariables;
size_t countAlphas = 0;
for (size_t k=0 ; k<gm_.numberOfVariables(); ++k) {
if (label_[k] == alpha_ ) {
addUnary(inf, k, 0, std::numeric_limits<ValueType>::infinity());
++countAlphas;
}
}
if(countAlphas < gm_.numberOfVariables()) {
for (size_t k=0 ; k<gm_.numberOfFactors(); ++k) {
const FactorType& factor = gm_[k];
if(factor.numberOfVariables() == 1) {
size_t var = factor.variableIndex(0);
vecA[0] = alpha_;
vecX[0] = label_[var];
if (label_[var] != alpha_ ) {
addUnary(inf, var, factor(vecA), factor(vecX));
}
}
else if (factor.numberOfVariables() == 2) {
size_t var1 = factor.variableIndex(0);
size_t var2 = factor.variableIndex(1);
std::vector<IndexType> vars(2); vars[0]=var1;vars[1]=var2;
vecAA[0] = vecAA[1] = alpha_;
vecAX[0] = alpha_; vecAX[1] = label_[var2];
vecXA[0] = label_[var1]; vecXA[1] = alpha_;
vecXX[0] = label_[var1]; vecXX[1] = label_[var2];
if(label_[var1]==alpha_ && label_[var2]==alpha_) {
continue;
}
else if(label_[var1]==alpha_) {
addUnary(inf, var2, factor(vecAA), factor(vecAX));
}
else if(label_[var2]==alpha_) {
addUnary(inf, var1, factor(vecAA), factor(vecXA));
}
else if(label_[var1]==label_[var2]) {
addPairwise(inf, var1, var2, factor(vecAA), factor(vecAX), factor(vecXA), factor(vecXX));
}
else{
OPENGM_ASSERT(varX < numberOfVariables + numberOfAuxiliaryNodes);
addPairwise(inf, var1, varX, 0, factor(vecAX), 0, 0);
addPairwise(inf, var2, varX, 0, factor(vecXA), 0, 0);
addUnary(inf, varX, factor(vecAA), factor(vecXX));
++varX;
}
}
}
std::vector<LabelType> state;
inf.infer();
inf.arg(state);
OPENGM_ASSERT(state.size() == numberOfVariables + numberOfAuxiliaryNodes);
for(size_t var=0; var<numberOfVariables ; ++var) {
if (label_[var] != alpha_ && state[var]==0) {
label_[var] = alpha_;
}
OPENGM_ASSERT(label_[var] < gm_.numberOfLabels(var));
}
}
OPENGM_ASSERT(gm_.numberOfVariables() == label_.size());
ValueType energy2 = gm_.evaluate(label_);
//visitor(*this,energy2,energy,alpha_);
if( visitor(*this) != visitors::VisitorReturnFlag::ContinueInf ){
exitInf=true;
}
// OPENGM_ASSERT(!AccumulationType::ibop(energy2, energy));
if(AccumulationType::bop(energy2, energy)) {
energy=energy2;
countUnchanged = 0;
}
else{
++countUnchanged;
}
incrementAlpha();
OPENGM_ASSERT(alpha_ < maxState_);
}
visitor.end(*this);
return NORMAL;
}
template<class GM, class INF>
inline InferenceTermination
AlphaExpansion<GM, INF>::arg
(
std::vector<LabelType>& arg,
const size_t n
) const
{
if(n > 1) {
return UNKNOWN;
}
else {
OPENGM_ASSERT(label_.size() == gm_.numberOfVariables());
arg.resize(label_.size());
for(size_t i=0; i<label_.size(); ++i) {
arg[i] = label_[i];
}
return NORMAL;
}
}
template<class GM, class INF>
inline void
AlphaExpansion<GM, INF>::setLabelOrder
(
std::vector<LabelType>& l
) {
if(l.size() == maxState_) {
labelList_=l;
}
}
template<class GM, class INF>
inline void
AlphaExpansion<GM, INF>::setLabelOrderRandom
(
unsigned int seed
) {
srand(seed);
labelList_.resize(maxState_);
for (size_t i=0; i<maxState_;++i) {
labelList_[i]=i;
}
random_shuffle(labelList_.begin(), labelList_.end());
}
template<class GM, class INF>
inline void
AlphaExpansion<GM, INF>::setInitialLabel
(
std::vector<LabelType>& l
) {
label_.resize(gm_.numberOfVariables());
if(l.size() == label_.size()) {
for(size_t i=0; i<l.size();++i) {
if(l[i]>=gm_.numberOfLabels(i)) return;
}
for(size_t i=0; i<l.size();++i) {
label_[i] = l[i];
}
}
}
template<class GM, class INF>
inline void
AlphaExpansion<GM, INF>::setInitialLabelLocalOptimal() {
label_.resize(gm_.numberOfVariables(), 0);
std::vector<size_t> accVec;
for(size_t i=0; i<gm_.numberOfFactors();++i) {
if(gm_[i].numberOfVariables()==1) {
std::vector<size_t> state(1, 0);
ValueType value = gm_[i](state.begin());
for(state[0]=1; state[0]<gm_.numberOfLabels(i); ++state[0]) {
if(AccumulationType::bop(gm_[i](state.begin()), value)) {
value = gm_[i](state.begin());
label_[i] = state[0];
}
}
}
}
}
template<class GM, class INF>
inline void
AlphaExpansion<GM, INF>::setInitialLabelRandom
(
unsigned int seed
) {
srand(seed);
label_.resize(gm_.numberOfVariables());
for(size_t i=0; i<gm_.numberOfVariables();++i) {
label_[i] = rand() % gm_.numberOfLabels(i);
}
}
template<class GM, class INF>
inline void
AlphaExpansion<GM, INF>::incrementAlpha() {
counter_ = (counter_+1) % maxState_;
alpha_ = labelList_[counter_];
}
} // namespace opengm
#endif // #ifndef OPENGM_ALPHAEXPANSION_HXX
| 29.070981 | 144 | 0.636697 | [
"shape",
"vector",
"model"
] |
c859909813132faa613aa39da9d0d65ca322de0b | 17,919 | cpp | C++ | divide/shared/zip.cpp | carboncopycatgames/divide | 9d62f52a8ff79e90ed4d8f5aa799e28c737f2a40 | [
"MIT"
] | 3 | 2019-12-06T13:38:52.000Z | 2020-02-17T20:06:40.000Z | divide/shared/zip.cpp | carboncopycatgames/divide | 9d62f52a8ff79e90ed4d8f5aa799e28c737f2a40 | [
"MIT"
] | null | null | null | divide/shared/zip.cpp | carboncopycatgames/divide | 9d62f52a8ff79e90ed4d8f5aa799e28c737f2a40 | [
"MIT"
] | 1 | 2021-07-20T05:08:33.000Z | 2021-07-20T05:08:33.000Z | #include "cube.h"
enum
{
ZIP_LOCAL_FILE_SIGNATURE = 0x04034B50,
ZIP_LOCAL_FILE_SIZE = 30,
ZIP_FILE_SIGNATURE = 0x02014B50,
ZIP_FILE_SIZE = 46,
ZIP_DIRECTORY_SIGNATURE = 0x06054B50,
ZIP_DIRECTORY_SIZE = 22
};
struct ziplocalfileheader
{
uint signature;
ushort version, flags, compression, modtime, moddate;
uint crc32, compressedsize, uncompressedsize;
ushort namelength, extralength;
};
struct zipfileheader
{
uint signature;
ushort version, needversion, flags, compression, modtime, moddate;
uint crc32, compressedsize, uncompressedsize;
ushort namelength, extralength, commentlength, disknumber, internalattribs;
uint externalattribs, offset;
};
struct zipdirectoryheader
{
uint signature;
ushort disknumber, directorydisk, diskentries, entries;
uint size, offset;
ushort commentlength;
};
struct zipfile
{
char *name;
uint header, offset, size, compressedsize;
zipfile() : name(NULL), header(0), offset(~0U), size(0), compressedsize(0)
{
}
~zipfile()
{
DELETEA(name);
}
};
struct zipstream;
struct ziparchive
{
char *name;
FILE *data;
hashnameset<zipfile> files;
int openfiles;
zipstream *owner;
ziparchive() : name(NULL), data(NULL), files(512), openfiles(0), owner(NULL)
{
}
~ziparchive()
{
DELETEA(name);
if(data) { fclose(data); data = NULL; }
}
};
static bool findzipdirectory(FILE *f, zipdirectoryheader &hdr)
{
if(fseek(f, 0, SEEK_END) < 0) return false;
long offset = ftell(f);
if(offset < 0) return false;
uchar buf[1024], *src = NULL;
long end = max(offset - 0xFFFFL - ZIP_DIRECTORY_SIZE, 0L);
size_t len = 0;
const uint signature = lilswap<uint>(ZIP_DIRECTORY_SIGNATURE);
while(offset > end)
{
size_t carry = min(len, size_t(ZIP_DIRECTORY_SIZE-1)), next = min(sizeof(buf) - carry, size_t(offset - end));
offset -= next;
memmove(&buf[next], buf, carry);
if(next + carry < ZIP_DIRECTORY_SIZE || fseek(f, offset, SEEK_SET) < 0 || fread(buf, 1, next, f) != next) return false;
len = next + carry;
uchar *search = &buf[next-1];
for(; search >= buf; search--) if(*(uint *)search == signature) break;
if(search >= buf) { src = search; break; }
}
if(!src || &buf[len] - src < ZIP_DIRECTORY_SIZE) return false;
hdr.signature = lilswap(*(uint *)src); src += 4;
hdr.disknumber = lilswap(*(ushort *)src); src += 2;
hdr.directorydisk = lilswap(*(ushort *)src); src += 2;
hdr.diskentries = lilswap(*(ushort *)src); src += 2;
hdr.entries = lilswap(*(ushort *)src); src += 2;
hdr.size = lilswap(*(uint *)src); src += 4;
hdr.offset = lilswap(*(uint *)src); src += 4;
hdr.commentlength = lilswap(*(ushort *)src); src += 2;
if(hdr.signature != ZIP_DIRECTORY_SIGNATURE || hdr.disknumber != hdr.directorydisk || hdr.diskentries != hdr.entries) return false;
return true;
}
#ifndef STANDALONE
VAR(dbgzip, 0, 0, 1);
#endif
static bool readzipdirectory(const char *archname, FILE *f, int entries, int offset, uint size, vector<zipfile> &files)
{
uchar *buf = new (false) uchar[size], *src = buf;
if(!buf || fseek(f, offset, SEEK_SET) < 0 || fread(buf, 1, size, f) != size) { delete[] buf; return false; }
loopi(entries)
{
if(src + ZIP_FILE_SIZE > &buf[size]) break;
zipfileheader hdr;
hdr.signature = lilswap(*(uint *)src); src += 4;
hdr.version = lilswap(*(ushort *)src); src += 2;
hdr.needversion = lilswap(*(ushort *)src); src += 2;
hdr.flags = lilswap(*(ushort *)src); src += 2;
hdr.compression = lilswap(*(ushort *)src); src += 2;
hdr.modtime = lilswap(*(ushort *)src); src += 2;
hdr.moddate = lilswap(*(ushort *)src); src += 2;
hdr.crc32 = lilswap(*(uint *)src); src += 4;
hdr.compressedsize = lilswap(*(uint *)src); src += 4;
hdr.uncompressedsize = lilswap(*(uint *)src); src += 4;
hdr.namelength = lilswap(*(ushort *)src); src += 2;
hdr.extralength = lilswap(*(ushort *)src); src += 2;
hdr.commentlength = lilswap(*(ushort *)src); src += 2;
hdr.disknumber = lilswap(*(ushort *)src); src += 2;
hdr.internalattribs = lilswap(*(ushort *)src); src += 2;
hdr.externalattribs = lilswap(*(uint *)src); src += 4;
hdr.offset = lilswap(*(uint *)src); src += 4;
if(hdr.signature != ZIP_FILE_SIGNATURE) break;
if(!hdr.namelength || !hdr.uncompressedsize || (hdr.compression && (hdr.compression != Z_DEFLATED || !hdr.compressedsize)))
{
src += hdr.namelength + hdr.extralength + hdr.commentlength;
continue;
}
if(src + hdr.namelength > &buf[size]) break;
string pname;
int namelen = min((int)hdr.namelength, (int)sizeof(pname)-1);
memcpy(pname, src, namelen);
pname[namelen] = '\0';
path(pname);
char *name = newstring(pname);
zipfile &f = files.add();
f.name = name;
f.header = hdr.offset;
f.size = hdr.uncompressedsize;
f.compressedsize = hdr.compression ? hdr.compressedsize : 0;
#ifndef STANDALONE
if(dbgzip) conoutf(CON_DEBUG, "%s: file %s, size %d, compress %d, flags %x", archname, name, hdr.uncompressedsize, hdr.compression, hdr.flags);
#endif
src += hdr.namelength + hdr.extralength + hdr.commentlength;
}
delete[] buf;
return files.length() > 0;
}
static bool readlocalfileheader(FILE *f, ziplocalfileheader &h, uint offset)
{
uchar buf[ZIP_LOCAL_FILE_SIZE];
if(fseek(f, offset, SEEK_SET) < 0 || fread(buf, 1, ZIP_LOCAL_FILE_SIZE, f) != ZIP_LOCAL_FILE_SIZE)
return false;
uchar *src = buf;
h.signature = lilswap(*(uint *)src); src += 4;
h.version = lilswap(*(ushort *)src); src += 2;
h.flags = lilswap(*(ushort *)src); src += 2;
h.compression = lilswap(*(ushort *)src); src += 2;
h.modtime = lilswap(*(ushort *)src); src += 2;
h.moddate = lilswap(*(ushort *)src); src += 2;
h.crc32 = lilswap(*(uint *)src); src += 4;
h.compressedsize = lilswap(*(uint *)src); src += 4;
h.uncompressedsize = lilswap(*(uint *)src); src += 4;
h.namelength = lilswap(*(ushort *)src); src += 2;
h.extralength = lilswap(*(ushort *)src); src += 2;
if(h.signature != ZIP_LOCAL_FILE_SIGNATURE) return false;
// h.uncompressedsize or h.compressedsize may be zero - so don't validate
return true;
}
static vector<ziparchive *> archives;
ziparchive *findzip(const char *name)
{
loopv(archives) if(!strcmp(name, archives[i]->name)) return archives[i];
return NULL;
}
static bool checkprefix(vector<zipfile> &files, const char *prefix, int prefixlen)
{
loopv(files)
{
if(!strncmp(files[i].name, prefix, prefixlen)) return false;
}
return true;
}
static void mountzip(ziparchive &arch, vector<zipfile> &files, const char *mountdir, const char *stripdir)
{
string packagesdir = "media/";
path(packagesdir);
size_t striplen = stripdir ? strlen(stripdir) : 0;
if(!mountdir && !stripdir) loopv(files)
{
zipfile &f = files[i];
const char *foundpackages = strstr(f.name, packagesdir);
if(foundpackages)
{
if(foundpackages > f.name)
{
stripdir = f.name;
striplen = foundpackages - f.name;
}
break;
}
const char *foundogz = strstr(f.name, ".ogz");
if(foundogz)
{
const char *ogzdir = foundogz;
while(--ogzdir >= f.name && *ogzdir != PATHDIV);
if(ogzdir < f.name || checkprefix(files, f.name, ogzdir + 1 - f.name))
{
if(ogzdir >= f.name)
{
stripdir = f.name;
striplen = ogzdir + 1 - f.name;
}
if(!mountdir) mountdir = "media/map/";
break;
}
}
}
string mdir = "", fname;
if(mountdir)
{
copystring(mdir, mountdir);
if(fixpackagedir(mdir) <= 1) mdir[0] = '\0';
}
loopv(files)
{
zipfile &f = files[i];
formatstring(fname, "%s%s", mdir, striplen && !strncmp(f.name, stripdir, striplen) ? &f.name[striplen] : f.name);
if(arch.files.access(fname)) continue;
char *mname = newstring(fname);
zipfile &mf = arch.files[mname];
mf = f;
mf.name = mname;
}
}
bool addzip(const char *name, const char *mount = NULL, const char *strip = NULL)
{
string pname;
copystring(pname, name);
path(pname);
size_t plen = strlen(pname);
if(plen < 4 || !strchr(&pname[plen-4], '.')) concatstring(pname, ".zip");
ziparchive *exists = findzip(pname);
if(exists)
{
conoutf(CON_ERROR, "already added zip %s", pname);
return true;
}
FILE *f = fopen(findfile(pname, "rb"), "rb");
if(!f)
{
conoutf(CON_ERROR, "could not open file %s", pname);
return false;
}
zipdirectoryheader h;
vector<zipfile> files;
if(!findzipdirectory(f, h) || !readzipdirectory(pname, f, h.entries, h.offset, h.size, files))
{
conoutf(CON_ERROR, "could not read directory in zip %s", pname);
fclose(f);
return false;
}
ziparchive *arch = new ziparchive;
arch->name = newstring(pname);
arch->data = f;
mountzip(*arch, files, mount, strip);
archives.add(arch);
conoutf("added zip %s", pname);
return true;
}
bool removezip(const char *name)
{
string pname;
copystring(pname, name);
path(pname);
int plen = (int)strlen(pname);
if(plen < 4 || !strchr(&pname[plen-4], '.')) concatstring(pname, ".zip");
ziparchive *exists = findzip(pname);
if(!exists)
{
conoutf(CON_ERROR, "zip %s is not loaded", pname);
return false;
}
if(exists->openfiles)
{
conoutf(CON_ERROR, "zip %s has open files", pname);
return false;
}
conoutf("removed zip %s", exists->name);
archives.removeobj(exists);
delete exists;
return true;
}
struct zipstream : stream
{
enum
{
BUFSIZE = 16384
};
ziparchive *arch;
zipfile *info;
z_stream zfile;
uchar *buf;
uint reading;
bool ended;
zipstream() : arch(NULL), info(NULL), buf(NULL), reading(~0U), ended(false)
{
zfile.zalloc = NULL;
zfile.zfree = NULL;
zfile.opaque = NULL;
zfile.next_in = zfile.next_out = NULL;
zfile.avail_in = zfile.avail_out = 0;
}
~zipstream()
{
close();
}
void readbuf(uint size = BUFSIZE)
{
if(!zfile.avail_in) zfile.next_in = (Bytef *)buf;
size = min(size, uint(&buf[BUFSIZE] - &zfile.next_in[zfile.avail_in]));
if(arch->owner != this)
{
arch->owner = NULL;
if(fseek(arch->data, reading, SEEK_SET) >= 0) arch->owner = this;
else return;
}
uint remaining = info->offset + info->compressedsize - reading,
n = arch->owner == this ? fread(zfile.next_in + zfile.avail_in, 1, min(size, remaining), arch->data) : 0U;
zfile.avail_in += n;
reading += n;
}
bool open(ziparchive *a, zipfile *f)
{
if(f->offset == ~0U)
{
ziplocalfileheader h;
a->owner = NULL;
if(!readlocalfileheader(a->data, h, f->header)) return false;
f->offset = f->header + ZIP_LOCAL_FILE_SIZE + h.namelength + h.extralength;
}
if(f->compressedsize && inflateInit2(&zfile, -MAX_WBITS) != Z_OK) return false;
a->openfiles++;
arch = a;
info = f;
reading = f->offset;
ended = false;
if(f->compressedsize) buf = new uchar[BUFSIZE];
return true;
}
void stopreading()
{
if(reading == ~0U) return;
#ifndef STANDALONE
if(dbgzip) conoutf(CON_DEBUG, info->compressedsize ? "%s: zfile.total_out %u, info->size %u" : "%s: reading %u, info->size %u", info->name, info->compressedsize ? uint(zfile.total_out) : reading - info->offset, info->size);
#endif
if(info->compressedsize) inflateEnd(&zfile);
reading = ~0U;
}
void close()
{
stopreading();
DELETEA(buf);
if(arch) { arch->owner = NULL; arch->openfiles--; arch = NULL; }
}
offset size() { return info->size; }
bool end() { return reading == ~0U || ended; }
offset tell() { return reading != ~0U ? (info->compressedsize ? zfile.total_out : reading - info->offset) : offset(-1); }
bool seek(offset pos, int whence)
{
if(reading == ~0U) return false;
if(!info->compressedsize)
{
switch(whence)
{
case SEEK_END: pos += info->offset + info->size; break;
case SEEK_CUR: pos += reading; break;
case SEEK_SET: pos += info->offset; break;
default: return false;
}
pos = clamp(pos, offset(info->offset), offset(info->offset + info->size));
arch->owner = NULL;
if(fseek(arch->data, int(pos), SEEK_SET) < 0) return false;
arch->owner = this;
reading = pos;
ended = false;
return true;
}
switch(whence)
{
case SEEK_END: pos += info->size; break;
case SEEK_CUR: pos += zfile.total_out; break;
case SEEK_SET: break;
default: return false;
}
if(pos >= (offset)info->size)
{
reading = info->offset + info->compressedsize;
zfile.next_in += zfile.avail_in;
zfile.avail_in = 0;
zfile.total_in = info->compressedsize;
zfile.total_out = info->size;
arch->owner = NULL;
ended = false;
return true;
}
if(pos < 0) return false;
if(pos >= (offset)zfile.total_out) pos -= zfile.total_out;
else
{
if(zfile.next_in && zfile.total_in <= uint(zfile.next_in - buf))
{
zfile.avail_in += zfile.total_in;
zfile.next_in -= zfile.total_in;
}
else
{
arch->owner = NULL;
zfile.avail_in = 0;
zfile.next_in = NULL;
reading = info->offset;
}
inflateReset(&zfile);
}
uchar skip[512];
while(pos > 0)
{
size_t skipped = (size_t)min(pos, (offset)sizeof(skip));
if(read(skip, skipped) != skipped) return false;
pos -= skipped;
}
ended = false;
return true;
}
size_t read(void *buf, size_t len)
{
if(reading == ~0U || !buf || !len) return 0;
if(!info->compressedsize)
{
if(arch->owner != this)
{
arch->owner = NULL;
if(fseek(arch->data, reading, SEEK_SET) < 0) { stopreading(); return 0; }
arch->owner = this;
}
size_t n = fread(buf, 1, min(len, size_t(info->size + info->offset - reading)), arch->data);
reading += n;
if(n < len) ended = true;
return n;
}
zfile.next_out = (Bytef *)buf;
zfile.avail_out = len;
while(zfile.avail_out > 0)
{
if(!zfile.avail_in) readbuf(BUFSIZE);
int err = inflate(&zfile, Z_NO_FLUSH);
if(err != Z_OK)
{
if(err == Z_STREAM_END) ended = true;
else
{
#ifndef STANDALONE
if(dbgzip) conoutf(CON_DEBUG, "inflate error: %s", zError(err));
#endif
stopreading();
}
break;
}
}
return len - zfile.avail_out;
}
};
stream *openzipfile(const char *name, const char *mode)
{
for(; *mode; mode++) if(*mode=='w' || *mode=='a') return NULL;
loopvrev(archives)
{
ziparchive *arch = archives[i];
zipfile *f = arch->files.access(name);
if(!f) continue;
zipstream *s = new zipstream;
if(s->open(arch, f)) return s;
delete s;
}
return NULL;
}
bool findzipfile(const char *name)
{
loopvrev(archives)
{
ziparchive *arch = archives[i];
if(arch->files.access(name)) return true;
}
return false;
}
int listzipfiles(const char *dir, const char *ext, vector<char *> &files)
{
size_t extsize = ext ? strlen(ext)+1 : 0, dirsize = strlen(dir);
int dirs = 0;
loopvrev(archives)
{
ziparchive *arch = archives[i];
int oldsize = files.length();
enumerate(arch->files, zipfile, f,
{
if(strncmp(f.name, dir, dirsize)) continue;
const char *name = f.name + dirsize;
if(name[0] == PATHDIV) name++;
if(strchr(name, PATHDIV)) continue;
if(!ext) files.add(newstring(name));
else
{
size_t namelen = strlen(name);
if(namelen > extsize)
{
namelen -= extsize;
if(name[namelen] == '.' && strncmp(name+namelen+1, ext, extsize-1)==0)
files.add(newstring(name, namelen));
}
}
});
if(files.length() > oldsize) dirs++;
}
return dirs;
}
#ifndef STANDALONE
ICOMMAND(addzip, "sss", (const char *name, const char *mount, const char *strip), addzip(name, mount[0] ? mount : NULL, strip[0] ? strip : NULL));
ICOMMAND(removezip, "s", (const char *name), removezip(name));
#endif
| 30.42275 | 231 | 0.551258 | [
"vector"
] |
c85b8a26d5799712de7230261eb585f3cc78cbf3 | 6,350 | cc | C++ | deps/leveldb/leveldb-basho/db/penalty_test.cc | andris9/leveldown-basho-andris | 611673f94e517f02ac15567a48fcc18c61cb46d2 | [
"MIT"
] | null | null | null | deps/leveldb/leveldb-basho/db/penalty_test.cc | andris9/leveldown-basho-andris | 611673f94e517f02ac15567a48fcc18c61cb46d2 | [
"MIT"
] | null | null | null | deps/leveldb/leveldb-basho/db/penalty_test.cc | andris9/leveldown-basho-andris | 611673f94e517f02ac15567a48fcc18c61cb46d2 | [
"MIT"
] | null | null | null | // -------------------------------------------------------------------
//
// penalty_test.cc
//
// Copyright (c) 2016 Basho Technologies, Inc. All Rights Reserved.
//
// This file is provided to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
// -------------------------------------------------------------------
#include "util/testharness.h"
#include "util/testutil.h"
#include "leveldb/comparator.h"
#include "db/version_set.h"
/**
* Execution routine
*/
int main(int argc, char** argv)
{
return leveldb::test::RunAllTests();
}
namespace leveldb {
class TestVersion : public Version
{
public:
TestVersion()
: Version(NULL)
{
int loop;
for (loop=0; loop<config::kNumLevels; ++loop)
{
m_FalseFile[loop].file_size=0;
m_LevelFileCount[loop]=0;
} // for
};
virtual size_t NumFiles(int level) const {return(m_LevelFileCount[level]);};
virtual const std::vector<FileMetaData*> & GetFileList(int level) const
{
m_FalseVector.clear();
m_FalseVector.push_back(&m_FalseFile[level]);
return(m_FalseVector);
};
mutable std::vector<FileMetaData*> m_FalseVector;
mutable FileMetaData m_FalseFile[config::kNumLevels];
size_t m_LevelFileCount[config::kNumLevels];
}; // class TestVersion
/**
* Wrapper class for tests. Holds working variables
* and helper functions.
*/
class PenaltyTester : public VersionSet
{
public:
PenaltyTester()
: m_IntCompare(m_Options.comparator), VersionSet("", &m_Options, NULL, &m_IntCompare)
{
};
~PenaltyTester()
{
};
Options m_Options;
InternalKeyComparator m_IntCompare;
}; // class PenaltyTester
/*******************
* Form note:
* using ASSERT_TRUE(0==version.WritePenalty());
* instead of ASSERT_EQ / ASSERT_NE because WritePenalty
* returns a volatile int, which older compilers believe is
* not an equivalent type to a constant. RedHat 5, Solaris,
* and SmartOS were giving grief.
*******************/
/**
* Debug 1
*/
#if 0
TEST(PenaltyTester, Debug1)
{
TestVersion version;
int penalty;
m_Options.write_buffer_size=46416847;
version.m_FalseFile[2].file_size=1075676398;
version.m_LevelFileCount[1]=1;
UpdatePenalty(&version);
ASSERT_TRUE(0==version.WritePenalty());
} // test Debug1
#endif
/**
* No penalty scenarios
*/
TEST(PenaltyTester, NoPenalty)
{
TestVersion version;
int level;
m_Options.write_buffer_size=46416847;
// nothing
UpdatePenalty(&version);
ASSERT_TRUE(0==version.WritePenalty());
/**
* Level 0
* (overlapped level, penalty is count based)
*/
// no penalty
version.m_LevelFileCount[0]=config::kL0_CompactionTrigger;
UpdatePenalty(&version);
ASSERT_TRUE(0==version.WritePenalty());
version.m_LevelFileCount[0]=config::kL0_SlowdownWritesTrigger;
UpdatePenalty(&version);
ASSERT_TRUE(0==version.WritePenalty());
// threshold reached ... some penalty
version.m_LevelFileCount[0]=config::kL0_SlowdownWritesTrigger+1;
UpdatePenalty(&version);
ASSERT_TRUE(0!=version.WritePenalty());
// clean up
version.m_LevelFileCount[0]=0;
/**
* Level 1
* (overlapped level, penalty is count based)
*/
// no penalty
version.m_LevelFileCount[1]=config::kL0_CompactionTrigger;
UpdatePenalty(&version);
ASSERT_TRUE(0==version.WritePenalty());
version.m_LevelFileCount[1]=config::kL0_SlowdownWritesTrigger;
UpdatePenalty(&version);
ASSERT_TRUE(0==version.WritePenalty());
// threshold reached ... some penalty
version.m_LevelFileCount[1]=config::kL0_SlowdownWritesTrigger+1;
UpdatePenalty(&version);
ASSERT_TRUE(0!=version.WritePenalty());
// clean up
version.m_LevelFileCount[1]=0;
/**
* Level 2
* (landing level, penalty size based)
*/
// no penalty
version.m_FalseFile[2].file_size=0;
UpdatePenalty(&version);
ASSERT_TRUE(0==version.WritePenalty());
version.m_FalseFile[2].file_size=VersionSet::DesiredBytesForLevel(2);
UpdatePenalty(&version);
ASSERT_TRUE(0==version.WritePenalty());
version.m_FalseFile[2].file_size=VersionSet::MaxBytesForLevel(2)-1;
UpdatePenalty(&version);
ASSERT_TRUE(0==version.WritePenalty());
version.m_FalseFile[2].file_size=VersionSet::MaxBytesForLevel(2);
UpdatePenalty(&version);
ASSERT_TRUE(0!=version.WritePenalty());
// interaction rule with level 1
version.m_FalseFile[2].file_size=VersionSet::MaxBytesForLevel(2)-1;
version.m_LevelFileCount[1]=config::kL0_CompactionTrigger/2;
UpdatePenalty(&version);
ASSERT_TRUE(0!=version.WritePenalty());
// clean up
version.m_LevelFileCount[1]=0;
version.m_FalseFile[2].file_size=0;
/**
* Level 3+
* (landing level, penalty size based)
*/
for (level=3; level<config::kNumLevels; ++level)
{
// no penalty
version.m_FalseFile[level].file_size=0;
UpdatePenalty(&version);
ASSERT_TRUE(0==version.WritePenalty());
version.m_FalseFile[level].file_size=VersionSet::DesiredBytesForLevel(level);
UpdatePenalty(&version);
ASSERT_TRUE(0==version.WritePenalty());
version.m_FalseFile[level].file_size=VersionSet::MaxBytesForLevel(level)-1;
UpdatePenalty(&version);
ASSERT_TRUE(0==version.WritePenalty());
version.m_FalseFile[level].file_size=VersionSet::MaxBytesForLevel(level);
UpdatePenalty(&version);
if ((config::kNumLevels-1)!=level)
ASSERT_TRUE(0!=version.WritePenalty());
else
ASSERT_TRUE(0==version.WritePenalty());
// clean up
version.m_FalseFile[level].file_size=0;
} // for
} // test NoPenalty
} // namespace leveldb
| 25.604839 | 93 | 0.657008 | [
"vector"
] |
c85c5f50c476d18fc8e0b246fd878021d51046d2 | 8,976 | cpp | C++ | src/Professor.cpp | svasighi/UMIS | 4d930bbc6749e92ce1b8889bf8556ec3c68f50e0 | [
"MIT"
] | 1 | 2020-01-08T19:57:08.000Z | 2020-01-08T19:57:08.000Z | src/Professor.cpp | svasighi/UMIS | 4d930bbc6749e92ce1b8889bf8556ec3c68f50e0 | [
"MIT"
] | null | null | null | src/Professor.cpp | svasighi/UMIS | 4d930bbc6749e92ce1b8889bf8556ec3c68f50e0 | [
"MIT"
] | null | null | null | #include "Professor.h"
void Professor::setCourses(const std::vector<PresentedCourse*>& _courses) {
courses = _courses;
}
std::vector<PresentedCourse*> Professor::getCourses(void) const {
return courses;
}
void Professor::addCourse(PresentedCourse* course) {
if (std::find(courses.begin(), courses.end(), course) == courses.end()) {
courses.push_back(course);
}
}
void Professor::removeCourse(PresentedCourse* course) {
std::vector<PresentedCourse*>::iterator position = std::find(courses.begin(), courses.end(), course);
if (position != courses.end()) {
courses.erase(position);
}
}
void Professor::replyToObjecton(Student* _student, PresentedCourse* _course, std::string _objection_reply_text) {
_student->setObjectionReplyTextofCourse(_course, _objection_reply_text);
}
std::string Professor::viewObjectonReply(Student* _student, PresentedCourse* _course) const {
return _student->getObjectionReplyTextofCourse(_course);
}
bool AdjunctProfessor::changePassword(std::string current_pass, std::string new_pass) {
if (checkPassword(current_pass)) {
setPassword(new_pass);
return true;
}
else {
return false;
}
}
void Faculty::setDegree(int _degree) {
degree = _degree;
}
int Faculty::getDegree(void) const {
return degree;
}
void Faculty::setAsSupervisor(bool _is_supervisor) {
is_supervisor = _is_supervisor;
}
bool Faculty::getisSupervisor(void) const {
return is_supervisor;
}
void Faculty::setSupervisedStudents(const std::vector<Student*>& _supervised_students) {
supervised_students = _supervised_students;
}
std::vector<Student*> Faculty::getSupervisedStudents(void) const {
return supervised_students;
}
void Faculty::addSupervisedStudent(Student* student) {
if (std::find(supervised_students.begin(), supervised_students.end(), student) == supervised_students.end()) {
supervised_students.push_back(student);
}
}
void Faculty::removeSupervisedStudent(Student* student) {
std::vector<Student*>::iterator position = std::find(supervised_students.begin(), supervised_students.end(), student);
if (position != supervised_students.end()) {
supervised_students.erase(position);
}
}
bool Faculty::changePassword(std::string current_pass, std::string new_pass) {
if (checkPassword(current_pass)) {
setPassword(new_pass);
return true;
}
else {
return false;
}
}
void GroupManager::setGroupCourses(std::map<int, Course*> _group_courses) {
group_courses = _group_courses;
}
std::map<int, Course*> GroupManager::getGroupCourses() {
return group_courses;
}
void GroupManager::setGroupPresentedCourses(std::map<int, PresentedCourse*> _group_presentedcourses) {
group_presentedcourses = _group_presentedcourses;
}
std::map<int, PresentedCourse*> GroupManager::getGroupPresentedCourses() {
return group_presentedcourses;
}
bool GroupManager::addGroupCourse(short coursecode, std::string name, char credit, char type, std::vector<Course*> prerequisites, std::vector<Course*> corequisites) {
Course* course = new Course(departmentcode, groupcode, coursecode, credit, name, type);
if (group_courses.count(course->getCourseID()) == 0) {
course->setCorequisites(corequisites);
course->setPrerequisites(prerequisites);
group_courses.insert(std::make_pair(course->getCourseID(), course));
return true;
}
else {
delete course;
return false;
}
}
bool GroupManager::deleteGroupCourse(Course* _course) {
if (group_courses.count(_course->getCourseID())) {
group_courses.erase(_course->getCourseID());
delete _course;
return true;
}
return false;
}
void GroupManager::deleteAllGroupCourses() {
for (auto& c : group_courses) {
delete c.second;
}
group_courses.clear();
}
bool GroupManager::addGroupPresentedCourse(Course* course, int term_no, char group_no, Professor* course_professor, int capacity,
CourseTime course_time, std::string course_location, ExamTime finalexam_time, std::string finalexam_location) {
if (group_courses.count(course->getCourseID()) == 0) {
return false;
}
PresentedCourse* presented_course = new PresentedCourse(course, term_no, group_no, course_professor, capacity);
if (group_presentedcourses.count(presented_course->getPresentedCourseID()) == 0) {
presented_course->setCourseTime(course_time);
presented_course->setCourseLocation(course_location);
presented_course->setFinalExamTime(finalexam_time);
presented_course->setFinalExamLocation(finalexam_location);
group_presentedcourses.insert(std::make_pair(presented_course->getPresentedCourseID(), presented_course));
return true;
}
else {
delete presented_course;
return false;
}
}
bool GroupManager::deleteGroupPresentedCourse(PresentedCourse* _presentedcourse) {
if (group_presentedcourses.count(_presentedcourse->getPresentedCourseID())) {
group_presentedcourses.erase(_presentedcourse->getPresentedCourseID());
delete _presentedcourse;
return true;
}
return false;
}
void GroupManager::deleteAllGroupPresentedCourses() {
for (auto& c : group_presentedcourses) {
delete c.second;
}
group_presentedcourses.clear();
}
DepartmentHead::DepartmentHead(Faculty* _faculty) {
username = _faculty->getUserName();
password = _faculty->getPassword();
firstname = _faculty->getFirstName();
lastname = _faculty->getLastName();
departmentcode = _faculty->getDepartmentCode();
groupcode = _faculty->getGroupCode();
courses = _faculty->getCourses();
degree = _faculty->getDegree();
is_supervisor = _faculty->getisSupervisor();
supervised_students = _faculty->getSupervisedStudents();
}
void DepartmentHead::setDepartmentProfessors(std::map<int, Professor*> _professors) {
professors = _professors;
}
std::map<int, Professor*> DepartmentHead::getDepartmentProfessors(void) const {
return professors;
}
// returns an int <= 5 which shows each professor assessment
int DepartmentHead::calculateProfessorAssessmentSum(Professor* _professor) const {
std::vector<PresentedCourse*> _courses = _professor->getCourses();
int students_count = 0, assessments_sum = 0;
for (int i = 0; i < _courses.size(); i++) {
std::vector<Student*> students = _courses[i]->getCourseStudents();
for (int j = 0; j < students.size(); j++) {
std::vector<char> assessment = students[j]->getAssessmentAnswersofCourse(_courses[i]);
int temp = 0;
for (int k = 0; k < assessment.size(); k++)
temp += assessment[k];
assessments_sum += (temp / assessment.size());
students_count++;
}
}
return assessments_sum / students_count;
}
void DepartmentHead::addFaculty(int _username, std::string _password, std::string _firstname, std::string _lastname) {
Professor* faculty = new Faculty(_username, _password, _firstname, _lastname, this->departmentcode);
professors.insert(std::make_pair(faculty->getUserName(), faculty));
}
void DepartmentHead::addAdjunctProfessor(int _username, std::string _password, std::string _firstname, std::string _lastname ,int groupcode) {
Professor* adjunct_professor(new AdjunctProfessor(_username, _password, _firstname, _lastname, this->departmentcode, groupcode));
professors.insert(std::make_pair(adjunct_professor->getUserName(), adjunct_professor));
}
void DepartmentHead::deleteProfessor(Professor* _professor) {
if (professors.count(_professor->getUserName())) {
professors.erase(_professor->getUserName());
}
}
std::map<PresentedCourse*, std::vector<char>> DepartmentHead::ProfessorAssessment(Professor* _professor) const {
std::vector<PresentedCourse*> _courses = _professor->getCourses();
std::map<PresentedCourse*, std::vector<char>> assessments;
for (int i = 0; i < _courses.size(); i++) {
std::vector<Student*> students = _courses[i]->getCourseStudents();
for (int j = 0; j < students.size(); j++) {
std::vector<char> assessment_sum;
std::vector<char> assessment_temp = students[j]->getAssessmentAnswersofCourse(_courses[i]);
for (int k = 0; k < assessment_temp.size(); k++) {
assessment_sum[k] += assessment_temp[k];
if (j == (students.size() - 1))
assessment_sum[k] /= assessment_temp.size();
}
assessments.insert(std::make_pair(_courses[i], assessment_sum));
}
}
return assessments;
}
void DepartmentHead::calcSalary(int* _degree_base_pay, int _max_assesment_addition) const {
std::map<int, Professor*> professors = getDepartmentProfessors();
for (std::map<int, Professor*>::iterator it = professors.begin(); it != professors.end(); it++) {
Faculty* faculty = dynamic_cast<Faculty*> (it->second);
int salary = 0;
if (faculty) {
salary = _degree_base_pay[faculty->getDegree()] + (calculateProfessorAssessmentSum(it->second) / 5) * _max_assesment_addition;
}
else {
salary = _degree_base_pay[0] + (calculateProfessorAssessmentSum(it->second) / 5) * _max_assesment_addition;
}
}
}
| 33.492537 | 167 | 0.729055 | [
"vector"
] |
c85dbecab1b7c4778e04c5a9a56a982720d8f326 | 5,371 | cpp | C++ | source/vkbinding/source/Binding.cpp | cginternals/vkbinding-poc | 83d776a2f7d960b3da5881c581eaafe01f79091e | [
"MIT"
] | null | null | null | source/vkbinding/source/Binding.cpp | cginternals/vkbinding-poc | 83d776a2f7d960b3da5881c581eaafe01f79091e | [
"MIT"
] | null | null | null | source/vkbinding/source/Binding.cpp | cginternals/vkbinding-poc | 83d776a2f7d960b3da5881c581eaafe01f79091e | [
"MIT"
] | null | null | null |
#include <vkbinding/Binding.h>
#include <cassert>
#include <iostream>
#include <vkbinding/State.h>
#include <vkbinding/AbstractFunction.h>
namespace vkbinding
{
void Binding::setCallbackMask(const CallbackMask mask)
{
for (auto function : Binding::functions())
{
function->setCallbackMask(mask);
}
}
void Binding::setCallbackMaskExcept(const CallbackMask mask, const std::set<std::string> & blackList)
{
for (auto function : Binding::functions())
{
if (blackList.find(function->name()) == blackList.end())
{
function->setCallbackMask(mask);
}
}
}
void Binding::addCallbackMask(const CallbackMask mask)
{
for (auto function : Binding::functions())
{
function->addCallbackMask(mask);
}
}
void Binding::addCallbackMaskExcept(const CallbackMask mask, const std::set<std::string> & blackList)
{
for (auto function : Binding::functions())
{
if (blackList.find(function->name()) == blackList.end())
{
function->addCallbackMask(mask);
}
}
}
void Binding::removeCallbackMask(const CallbackMask mask)
{
for (auto function : Binding::functions())
{
function->removeCallbackMask(mask);
}
}
void Binding::removeCallbackMaskExcept(const CallbackMask mask, const std::set<std::string> & blackList)
{
for (auto function : Binding::functions())
{
if (blackList.find(function->name()) == blackList.end())
{
function->removeCallbackMask(mask);
}
}
}
Binding::SimpleFunctionCallback Binding::unresolvedCallback()
{
return s_unresolvedCallback();
}
void Binding::setUnresolvedCallback(SimpleFunctionCallback callback)
{
s_unresolvedCallback() = std::move(callback);
}
Binding::FunctionCallback Binding::beforeCallback()
{
return s_beforeCallback();
}
void Binding::setBeforeCallback(FunctionCallback callback)
{
s_beforeCallback() = std::move(callback);
}
Binding::FunctionCallback Binding::afterCallback()
{
return s_afterCallback();
}
void Binding::setAfterCallback(FunctionCallback callback)
{
s_afterCallback() = std::move(callback);
}
Binding::FunctionLogCallback Binding::logCallback()
{
return s_logCallback();
}
void Binding::setLogCallback(Binding::FunctionLogCallback callback)
{
s_logCallback() = std::move(callback);
}
void Binding::unresolved(const AbstractFunction * function)
{
if (s_unresolvedCallback())
{
s_unresolvedCallback()(*function);
}
}
void Binding::before(const FunctionCall & call)
{
if (s_beforeCallback())
{
s_beforeCallback()(call);
}
}
void Binding::after(const FunctionCall & call)
{
if (s_afterCallback())
{
s_afterCallback()(call);
}
}
void Binding::log(FunctionCall && call)
{
if (s_logCallback())
{
s_logCallback()(new FunctionCall(std::move(call)));
}
}
const std::vector<AbstractFunction *> & Binding::additionalFunctions()
{
return s_additionalFunctions();
}
size_t Binding::size()
{
return Binding::functions().size() + s_additionalFunctions().size();
}
void Binding::initialize(const vkbinding::GetProcAddress functionPointerResolver, const bool _resolveFunctions)
{
std_boost::lock_guard<std_boost::recursive_mutex> lock(s_mutex());
s_getProcAddress() = functionPointerResolver;
for (AbstractFunction * function : Binding::functions())
{
function->resizeStates(1);
}
for (AbstractFunction * function : Binding::additionalFunctions())
{
function->resizeStates(1);
}
if (_resolveFunctions)
{
resolveFunctions();
}
}
ProcAddress Binding::resolveFunction(const char * name)
{
if (s_getProcAddress() != nullptr)
{
return s_getProcAddress()(name);
}
return nullptr;
}
void Binding::registerAdditionalFunction(AbstractFunction * function)
{
s_additionalFunctions().push_back(function);
}
void Binding::resolveFunctions()
{
for (auto function : Binding::functions())
{
function->resolveAddress();
}
for (auto function : Binding::additionalFunctions())
{
function->resolveAddress();
}
}
const Binding::array_t & Binding::functions()
{
return s_functions;
}
std::vector<AbstractFunction *> & Binding::s_additionalFunctions()
{
static std::vector<AbstractFunction *> additionalFunctions;
return additionalFunctions;
}
Binding::SimpleFunctionCallback & Binding::s_unresolvedCallback()
{
static SimpleFunctionCallback unresolvedCallback;
return unresolvedCallback;
}
Binding::FunctionCallback & Binding::s_beforeCallback()
{
static FunctionCallback beforeCallback;
return beforeCallback;
}
Binding::FunctionCallback & Binding::s_afterCallback()
{
static FunctionCallback afterCallback;
return afterCallback;
}
Binding::FunctionLogCallback & Binding::s_logCallback()
{
static FunctionLogCallback logCallback;
return logCallback;
}
vkbinding::GetProcAddress & Binding::s_getProcAddress()
{
static vkbinding::GetProcAddress getProcAddress = nullptr;
return getProcAddress;
}
std_boost::recursive_mutex & Binding::s_mutex()
{
static std_boost::recursive_mutex mutex;
return mutex;
}
int Binding::currentPos()
{
return 0;
}
int Binding::maxPos()
{
return 0;
}
} // namespace vkbinding | 19.966543 | 111 | 0.686092 | [
"vector"
] |
c8630002ee57721a1a9836740b2d2b44b0d962ed | 6,168 | cpp | C++ | Engine/source/console/simPersistSet.cpp | Torque3D/BadBehaviour | 9fd487314d4636f7e91834acb2994aa56a63f8a7 | [
"Unlicense"
] | 1 | 2021-03-29T00:18:51.000Z | 2021-03-29T00:18:51.000Z | Engine/source/console/simPersistSet.cpp | Torque3D/BadBehaviour | 9fd487314d4636f7e91834acb2994aa56a63f8a7 | [
"Unlicense"
] | null | null | null | Engine/source/console/simPersistSet.cpp | Torque3D/BadBehaviour | 9fd487314d4636f7e91834acb2994aa56a63f8a7 | [
"Unlicense"
] | 1 | 2021-03-29T00:18:46.000Z | 2021-03-29T00:18:46.000Z | //-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "console/simPersistSet.h"
#include "console/simPersistID.h"
#include "console/consoleTypes.h"
IMPLEMENT_CONOBJECT( SimPersistSet );
ConsoleDocClass( SimPersistSet,
"@brief A SimSet that can be safely persisted.\n\n"
"Uses SimPersistIDs to reference objects in the set "
"while persisted on disk. This allows the set to resolve "
"its references no matter whether they are loaded before or "
"after the set is created.\n\n"
"Not intended for game development, for editors or internal use only.\n\n "
"@internal");
//-----------------------------------------------------------------------------
SimPersistSet::SimPersistSet()
: mIsResolvingPIDs( false )
{
VECTOR_SET_ASSOCIATION( mUnresolvedPIDs );
}
//-----------------------------------------------------------------------------
bool SimPersistSet::processArguments( S32 argc, ConsoleValueRef *argv )
{
for( U32 i = 0; i < argc; ++ i )
{
// Parse the UUID.
Torque::UUID uuid;
if( !uuid.fromString( argv[ i ] ) )
{
Con::errorf( "SimPersistSet::processArguments - could not read UUID at index %i: %s", i, (const char*)argv[ i ] );
continue;
}
// Find or create the respective persistent ID.
SimPersistID* pid = SimPersistID::findOrCreate( uuid );
if( pid->getObject() )
{
// There's already an object attached to this PID so just
// add the object to the set.
addObject( pid->getObject() );
}
else
{
// There not yet an object attached to the PID so push it
// onto the stack to resolve it later.
pid->incRefCount();
mUnresolvedPIDs.push_back( pid );
}
}
return true;
}
//-----------------------------------------------------------------------------
void SimPersistSet::write( Stream& stream, U32 tabStop, U32 flags )
{
if( ( flags & SelectedOnly ) && !isSelected() )
return;
// If the selection is transient, we cannot really save it.
// Just invoke the default SimObject::write and return.
if( !getCanSave() )
{
Con::errorf( "SimPersistSet::write - transient set being saved: %d:%s (%s)",
getId(), getClassName(), getName() );
Parent::write( stream, tabStop, flags );
return;
}
// If there are unresolved PIDs, give resolving them one last
// chance before writing out the set.
if( !mUnresolvedPIDs.empty() )
resolvePIDs();
// Write the set out.
stream.writeTabs( tabStop );
StringBuilder buffer;
buffer.format( "new %s(%s", getClassName(), getName() ? getName() : "" );
// Write the persistent IDs of all child objects into the set's
// object constructor so we see them passed back to us through
// processArguments when the object gets read in.
const U32 numChildren = size();
for( U32 i = 0; i < numChildren; ++ i )
{
SimObject* child = at( i );
SimPersistID* pid = child->getPersistentId();
AssertWarn( pid != NULL, "SimPersistSet::write - object without pid in persistent selection!" );
if( !pid )
continue;
buffer.append( ',' );
buffer.append( '"' );
buffer.append( pid->getUUID().toString() );
buffer.append( '"' );
}
buffer.append( ") {\r\n" );
stream.write( buffer.length(), buffer.data() );
// Write our object fields.
writeFields( stream, tabStop + 1 );
// Close our object definition.
stream.writeTabs( tabStop );
stream.write( 4, "};\r\n" );
}
//-----------------------------------------------------------------------------
void SimPersistSet::resolvePIDs()
{
if( mIsResolvingPIDs )
return;
lock();
mIsResolvingPIDs = true;
for( U32 i = 0; i < mUnresolvedPIDs.size(); ++ i )
if( mUnresolvedPIDs[ i ]->getObject() != NULL )
{
addObject( mUnresolvedPIDs[ i ]->getObject() );
mUnresolvedPIDs[i]->decRefCount();
mUnresolvedPIDs.erase( i );
-- i;
}
mIsResolvingPIDs = false;
unlock();
}
//-----------------------------------------------------------------------------
void SimPersistSet::addObject( SimObject* object )
{
// If this set isn't transient, make sure the object has a valid
// persistent ID.
if( getCanSave() )
object->getOrCreatePersistentId();
Parent::addObject( object );
}
//=============================================================================
// Console Methods.
//=============================================================================
// MARK: ---- Console Methods ----
//-----------------------------------------------------------------------------
ConsoleMethod( SimPersistSet, resolvePersistentIds, void, 2, 2, "() - Try to bind unresolved persistent IDs in the set." )
{
object->resolvePIDs();
}
| 31.958549 | 123 | 0.558528 | [
"object"
] |
c864ee51279e16e5490359a8b0c991296997ea5f | 7,906 | hpp | C++ | android/scanlibrary/src/main/jni/sdk/native/jni/include/opencv2/objdetect/detection_based_tracker.hpp | PatrykMis/OpenScan | b4c9029f6c851517944b9184980f2509b63aad58 | [
"BSD-3-Clause"
] | 1,103 | 2020-07-11T15:34:50.000Z | 2022-03-31T20:07:10.000Z | OpenCV-android-sdk/sdk/native/jni/include/opencv2/objdetect/detection_based_tracker.hpp | skumailraza/Tess4OCR | 26001172d5d856b0553cb36e3ae9eb64f1631cb0 | [
"Apache-2.0"
] | 69 | 2020-08-06T10:15:08.000Z | 2022-03-31T12:14:39.000Z | OpenCV-android-sdk/sdk/native/jni/include/opencv2/objdetect/detection_based_tracker.hpp | skumailraza/Tess4OCR | 26001172d5d856b0553cb36e3ae9eb64f1631cb0 | [
"Apache-2.0"
] | 58 | 2020-07-14T21:48:49.000Z | 2022-03-29T07:09:16.000Z | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#ifndef __OPENCV_OBJDETECT_DBT_HPP__
#define __OPENCV_OBJDETECT_DBT_HPP__
// After this condition removal update blacklist for bindings: modules/python/common.cmake
#if defined(__linux__) || defined(LINUX) || defined(__APPLE__) || defined(__ANDROID__) || \
(defined(__cplusplus) && __cplusplus > 201103L) || (defined(_MSC_VER) && _MSC_VER >= 1700)
#include <vector>
namespace cv
{
//! @addtogroup objdetect
//! @{
class CV_EXPORTS DetectionBasedTracker
{
public:
struct Parameters
{
int maxTrackLifetime;
int minDetectionPeriod; //the minimal time between run of the big object detector (on the whole frame) in ms (1000 mean 1 sec), default=0
Parameters();
};
class IDetector
{
public:
IDetector():
minObjSize(96, 96),
maxObjSize(INT_MAX, INT_MAX),
minNeighbours(2),
scaleFactor(1.1f)
{}
virtual void detect(const cv::Mat& image, std::vector<cv::Rect>& objects) = 0;
void setMinObjectSize(const cv::Size& min)
{
minObjSize = min;
}
void setMaxObjectSize(const cv::Size& max)
{
maxObjSize = max;
}
cv::Size getMinObjectSize() const
{
return minObjSize;
}
cv::Size getMaxObjectSize() const
{
return maxObjSize;
}
float getScaleFactor()
{
return scaleFactor;
}
void setScaleFactor(float value)
{
scaleFactor = value;
}
int getMinNeighbours()
{
return minNeighbours;
}
void setMinNeighbours(int value)
{
minNeighbours = value;
}
virtual ~IDetector() {}
protected:
cv::Size minObjSize;
cv::Size maxObjSize;
int minNeighbours;
float scaleFactor;
};
DetectionBasedTracker(cv::Ptr<IDetector> mainDetector, cv::Ptr<IDetector> trackingDetector, const Parameters& params);
virtual ~DetectionBasedTracker();
virtual bool run();
virtual void stop();
virtual void resetTracking();
virtual void process(const cv::Mat& imageGray);
bool setParameters(const Parameters& params);
const Parameters& getParameters() const;
typedef std::pair<cv::Rect, int> Object;
virtual void getObjects(std::vector<cv::Rect>& result) const;
virtual void getObjects(std::vector<Object>& result) const;
enum ObjectStatus
{
DETECTED_NOT_SHOWN_YET,
DETECTED,
DETECTED_TEMPORARY_LOST,
WRONG_OBJECT
};
struct ExtObject
{
int id;
cv::Rect location;
ObjectStatus status;
ExtObject(int _id, cv::Rect _location, ObjectStatus _status)
:id(_id), location(_location), status(_status)
{
}
};
virtual void getObjects(std::vector<ExtObject>& result) const;
virtual int addObject(const cv::Rect& location); //returns id of the new object
protected:
class SeparateDetectionWork;
cv::Ptr<SeparateDetectionWork> separateDetectionWork;
friend void* workcycleObjectDetectorFunction(void* p);
struct InnerParameters
{
int numLastPositionsToTrack;
int numStepsToWaitBeforeFirstShow;
int numStepsToTrackWithoutDetectingIfObjectHasNotBeenShown;
int numStepsToShowWithoutDetecting;
float coeffTrackingWindowSize;
float coeffObjectSizeToTrack;
float coeffObjectSpeedUsingInPrediction;
InnerParameters();
};
Parameters parameters;
InnerParameters innerParameters;
struct TrackedObject
{
typedef std::vector<cv::Rect> PositionsVector;
PositionsVector lastPositions;
int numDetectedFrames;
int numFramesNotDetected;
int id;
TrackedObject(const cv::Rect& rect):numDetectedFrames(1), numFramesNotDetected(0)
{
lastPositions.push_back(rect);
id=getNextId();
};
static int getNextId()
{
static int _id=0;
return _id++;
}
};
int numTrackedSteps;
std::vector<TrackedObject> trackedObjects;
std::vector<float> weightsPositionsSmoothing;
std::vector<float> weightsSizesSmoothing;
cv::Ptr<IDetector> cascadeForTracking;
void updateTrackedObjects(const std::vector<cv::Rect>& detectedObjects);
cv::Rect calcTrackedObjectPositionToShow(int i) const;
cv::Rect calcTrackedObjectPositionToShow(int i, ObjectStatus& status) const;
void detectInRegion(const cv::Mat& img, const cv::Rect& r, std::vector<cv::Rect>& detectedObjectsInRegions);
};
//! @} objdetect
} //end of cv namespace
#endif
#endif
| 34.982301 | 150 | 0.57956 | [
"object",
"vector"
] |
c86503719104185ba4ec3ec4f82d773e9791b45f | 4,737 | cpp | C++ | code/components/gta-net-five/src/ObjectIdManager.cpp | MyNameIsYesgo/fivem | 6def381fa0a992261a4414fae700c1c077e59327 | [
"MIT"
] | 5 | 2020-07-26T16:06:24.000Z | 2021-05-01T14:29:40.000Z | code/components/gta-net-five/src/ObjectIdManager.cpp | MyNameIsYesgo/fivem | 6def381fa0a992261a4414fae700c1c077e59327 | [
"MIT"
] | 6 | 2021-05-11T09:09:11.000Z | 2022-03-23T18:34:23.000Z | code/components/gta-net-five/src/ObjectIdManager.cpp | MyNameIsYesgo/fivem | 6def381fa0a992261a4414fae700c1c077e59327 | [
"MIT"
] | 3 | 2020-11-09T12:41:05.000Z | 2022-01-24T23:16:15.000Z | #include <StdInc.h>
#include <Hooking.h>
#include <NetBuffer.h>
#include <NetLibrary.h>
#include <GameInit.h>
#include <ICoreGameInit.h>
#include <nutsnbolts.h>
#include <CloneManager.h>
#include <MinHook.h>
static std::list<int> g_objectIds;
static std::set<int> g_usedObjectIds;
static std::set<int> g_stolenObjectIds;
static uint32_t(*g_origAssignObjectId)(void*);
static uint32_t AssignObjectId(void* objectIds)
{
if (!Instance<ICoreGameInit>::Get()->OneSyncEnabled)
{
return g_origAssignObjectId(objectIds);
}
if (g_objectIds.empty())
{
trace("No free object ID!\n");
return 0;
}
auto it = g_objectIds.begin();
auto objectId = *it;
g_objectIds.erase(it);
g_usedObjectIds.insert(objectId);
TheClones->Log("%s: id %d\n", __func__, objectId);
return objectId;
}
static bool(*g_origReturnObjectId)(void*, uint16_t);
static bool ReturnObjectId(void* objectIds, uint16_t objectId)
{
if (!Instance<ICoreGameInit>::Get()->OneSyncEnabled)
{
return g_origReturnObjectId(objectIds, objectId);
}
if (g_usedObjectIds.find(objectId) != g_usedObjectIds.end())
{
TheClones->Log("%s: id %d\n", __func__, objectId);
g_usedObjectIds.erase(objectId);
// only return it to ourselves if it was ours to begin with
// (and only use this for network protocol version 0x201903031957 or above - otherwise server bookkeeping will go out of sync)
if (Instance<ICoreGameInit>::Get()->NetProtoVersion < 0x201903031957 || g_stolenObjectIds.find(objectId) == g_stolenObjectIds.end())
{
g_objectIds.push_back(objectId);
}
g_stolenObjectIds.erase(objectId);
return true;
}
return false;
}
void ObjectIds_ReturnObjectId(uint16_t objectId)
{
ReturnObjectId(nullptr, objectId);
}
static bool(*g_origHasSpaceForObjectId)(void*, int, bool);
static bool HasSpaceForObjectId(void* objectIds, int num, bool unkScript)
{
if (!Instance<ICoreGameInit>::Get()->OneSyncEnabled)
{
return g_origHasSpaceForObjectId(objectIds, num, unkScript);
}
return (g_objectIds.size() >= num);
}
void ObjectIds_AddObjectId(int objectId)
{
// track 'stolen' migration object IDs so we can return them to the server once they get deleted
bool wasOurs = false;
// this is ours now
g_usedObjectIds.insert(objectId);
// remove this object ID from our free list
for (auto it = g_objectIds.begin(); it != g_objectIds.end(); it++)
{
if (*it == objectId)
{
wasOurs = true;
g_objectIds.erase(it);
break;
}
}
if (!wasOurs)
{
g_stolenObjectIds.insert(objectId);
}
TheClones->Log("%s: id %d\n", __func__, objectId);
}
void ObjectIds_RemoveObjectId(int objectId)
{
// this is no longer ours
g_usedObjectIds.erase(objectId);
// we don't have to care if it got stolen anymore
g_stolenObjectIds.erase(objectId);
TheClones->Log("%s: id %d\n", __func__, objectId);
}
static NetLibrary* g_netLibrary;
static bool g_requestedIds;
void ObjectIds_BindNetLibrary(NetLibrary* netLibrary)
{
g_netLibrary = netLibrary;
netLibrary->AddReliableHandler("msgObjectIds", [](const char* data, size_t len)
{
net::Buffer buffer(reinterpret_cast<const uint8_t*>(data), len);
auto numIds = buffer.Read<uint16_t>();
int last = 0;
for (int i = 0; i < numIds; i++)
{
auto skip = buffer.Read<uint16_t>();
auto take = buffer.Read<uint16_t>();
last += skip + 1;
for (int j = 0; j <= take; j++)
{
int objectId = last++;
TheClones->Log("got object id %d\n", objectId);
g_objectIds.push_back(objectId);
g_stolenObjectIds.erase(objectId);
}
}
g_requestedIds = false;
});
}
static HookFunction hookFunction([]()
{
OnMainGameFrame.Connect([]()
{
if (g_netLibrary->GetConnectionState() != NetLibrary::CS_ACTIVE)
{
return;
}
if (!Instance<ICoreGameInit>::Get()->OneSyncEnabled)
{
return;
}
int reqCount = 16;
if (Instance<ICoreGameInit>::Get()->HasVariable("onesync_big"))
{
reqCount = 4;
}
if (g_objectIds.size() < reqCount)
{
if (!g_requestedIds)
{
net::Buffer outBuffer;
outBuffer.Write<uint16_t>(32);
g_netLibrary->SendReliableCommand("msgRequestObjectIds", (const char*)outBuffer.GetData().data(), outBuffer.GetCurOffset());
g_requestedIds = true;
}
}
});
OnKillNetworkDone.Connect([]()
{
g_objectIds.clear();
g_usedObjectIds.clear();
g_requestedIds = false;
});
MH_Initialize();
MH_CreateHook(hook::get_pattern("FF 89 C4 3E 00 00 33 D2", -12), AssignObjectId, (void**)&g_origAssignObjectId);
MH_CreateHook(hook::get_pattern("44 8B 91 C4 3E 00 00", -0x14), ReturnObjectId, (void**)&g_origReturnObjectId);
MH_CreateHook(hook::get_pattern("48 83 EC 20 8B B1 C4 3E 00 00", -0xB), HasSpaceForObjectId, (void**)&g_origHasSpaceForObjectId);
MH_EnableHook(MH_ALL_HOOKS);
});
| 21.729358 | 134 | 0.702343 | [
"object"
] |
c865f1fe2d9b7488eee63895ccf2ed02dfaba1cc | 3,405 | hpp | C++ | Code_Examples/Chapter_08/openmp/src/ELLMatrix.hpp | OpenACCUserGroup/openacc_concept_strategies_book | 7547260d6d845d34b1f28bbb64ab93226c705207 | [
"CC-BY-4.0",
"CC0-1.0"
] | 26 | 2017-07-17T08:28:48.000Z | 2021-07-20T19:05:55.000Z | Code_Examples/Chapter_08/openmp/src/ELLMatrix.hpp | OpenACCUserGroup/openacc_concept_strategies_book | 7547260d6d845d34b1f28bbb64ab93226c705207 | [
"CC-BY-4.0",
"CC0-1.0"
] | 2 | 2017-11-18T17:30:28.000Z | 2018-11-08T12:39:27.000Z | Code_Examples/Chapter_08/tbb/src/ELLMatrix.hpp | OpenACCUserGroup/openacc_concept_strategies_book | 7547260d6d845d34b1f28bbb64ab93226c705207 | [
"CC-BY-4.0",
"CC0-1.0"
] | 16 | 2017-08-17T13:46:26.000Z | 2021-02-03T16:09:34.000Z | #ifndef _ELLMatrix_hpp_
#define _ELLMatrix_hpp_
//@HEADER
// ************************************************************************
//
// MiniFE: Simple Finite Element Assembly and Solve
// Copyright (2006-2013) Sandia Corporation
//
// Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive
// license for use of this work by or on behalf of the U.S. Government.
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 2.1 of the
// License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
// USA
//
// ************************************************************************
//@HEADER
#include <cstddef>
#include <vector>
#include <algorithm>
namespace miniFE {
template<typename Scalar,
typename LocalOrdinal,
typename GlobalOrdinal>
struct
ELLMatrix {
ELLMatrix()
: has_local_indices(false),
rows(),
cols(), coefs(),
num_cols(0),
num_cols_per_row(0)
{
}
~ELLMatrix()
{}
typedef Scalar ScalarType;
typedef LocalOrdinal LocalOrdinalType;
typedef GlobalOrdinal GlobalOrdinalType;
bool has_local_indices;
std::vector<GlobalOrdinal> rows;
std::vector<GlobalOrdinal> cols;
std::vector<Scalar> coefs;
LocalOrdinal num_cols;
LocalOrdinal num_cols_per_row;
size_t num_nonzeros() const
{
return rows.size()*num_cols_per_row;
}
void reserve_space(unsigned nrows, unsigned ncols_per_row)
{
rows.resize(nrows);
cols.resize(nrows * ncols_per_row);
coefs.resize(nrows * ncols_per_row);
num_cols_per_row = ncols_per_row;
}
void get_row_pointers(GlobalOrdinalType row, size_t& row_length,
GlobalOrdinalType*& cols_ptr,
ScalarType*& coefs_ptr)
{
ptrdiff_t local_row = -1;
//first see if we can get the local-row index using fast direct lookup:
if (rows.size() >= 1) {
ptrdiff_t idx = row - rows[0];
if (idx < rows.size() && rows[idx] == row) {
local_row = idx;
}
}
//if we didn't get the local-row index using direct lookup, try a
//more expensive binary-search:
if (local_row == -1) {
typename std::vector<GlobalOrdinal>::iterator row_iter =
std::lower_bound(rows.begin(), rows.end(), row);
//if we still haven't found row, it's not local so jump out:
if (row_iter == rows.end() || *row_iter != row) {
row_length = 0;
return;
}
local_row = row_iter - rows.begin();
}
cols_ptr = &cols[local_row*num_cols_per_row];
coefs_ptr = &coefs[local_row*num_cols_per_row];
int idx = num_cols_per_row-1;
while(idx>=0) {
if (cols_ptr[idx] != 0) break;
--idx;
}
row_length = idx+1;
}
};
}//namespace miniFE
#endif
| 27.682927 | 75 | 0.626138 | [
"vector"
] |
c8671bcdde5804defae495aa588c5fcef1fef768 | 61,520 | cpp | C++ | B2G/gecko/parser/html/nsHtml5StreamParser.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-08-31T15:24:31.000Z | 2020-04-24T20:31:29.000Z | B2G/gecko/parser/html/nsHtml5StreamParser.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | null | null | null | B2G/gecko/parser/html/nsHtml5StreamParser.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-07-29T07:17:15.000Z | 2020-11-04T06:55:37.000Z | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set sw=2 ts=2 et tw=79: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "nsHtml5StreamParser.h"
#include "nsICharsetConverterManager.h"
#include "nsCharsetAlias.h"
#include "nsServiceManagerUtils.h"
#include "nsEncoderDecoderUtils.h"
#include "nsContentUtils.h"
#include "nsHtml5Tokenizer.h"
#include "nsIHttpChannel.h"
#include "nsHtml5Parser.h"
#include "nsHtml5TreeBuilder.h"
#include "nsHtml5AtomTable.h"
#include "nsHtml5Module.h"
#include "nsHtml5RefPtr.h"
#include "nsIScriptError.h"
#include "mozilla/Preferences.h"
#include "nsHtml5Highlighter.h"
#include "expat_config.h"
#include "expat.h"
#include "nsINestedURI.h"
#include "nsCharsetSource.h"
using namespace mozilla;
int32_t nsHtml5StreamParser::sTimerInitialDelay = 120;
int32_t nsHtml5StreamParser::sTimerSubsequentDelay = 120;
// static
void
nsHtml5StreamParser::InitializeStatics()
{
Preferences::AddIntVarCache(&sTimerInitialDelay,
"html5.flushtimer.initialdelay");
Preferences::AddIntVarCache(&sTimerSubsequentDelay,
"html5.flushtimer.subsequentdelay");
}
/*
* Note that nsHtml5StreamParser implements cycle collecting AddRef and
* Release. Therefore, nsHtml5StreamParser must never be refcounted from
* the parser thread!
*
* To work around this limitation, runnables posted by the main thread to the
* parser thread hold their reference to the stream parser in an
* nsHtml5RefPtr. Upon creation, nsHtml5RefPtr addrefs the object it holds
* just like a regular nsRefPtr. This is OK, since the creation of the
* runnable and the nsHtml5RefPtr happens on the main thread.
*
* When the runnable is done on the parser thread, the destructor of
* nsHtml5RefPtr runs there. It doesn't call Release on the held object
* directly. Instead, it posts another runnable back to the main thread where
* that runnable calls Release on the wrapped object.
*
* When posting runnables in the other direction, the runnables have to be
* created on the main thread when nsHtml5StreamParser is instantiated and
* held for the lifetime of the nsHtml5StreamParser. This works, because the
* same runnabled can be dispatched multiple times and currently runnables
* posted from the parser thread to main thread don't need to wrap any
* runnable-specific data. (In the other direction, the runnables most notably
* wrap the byte data of the stream.)
*/
NS_IMPL_CYCLE_COLLECTING_ADDREF(nsHtml5StreamParser)
NS_IMPL_CYCLE_COLLECTING_RELEASE(nsHtml5StreamParser)
NS_INTERFACE_TABLE_HEAD(nsHtml5StreamParser)
NS_INTERFACE_TABLE2(nsHtml5StreamParser,
nsIStreamListener,
nsICharsetDetectionObserver)
NS_INTERFACE_TABLE_TO_MAP_SEGUE_CYCLE_COLLECTION(nsHtml5StreamParser)
NS_INTERFACE_MAP_END
NS_IMPL_CYCLE_COLLECTION_CLASS(nsHtml5StreamParser)
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsHtml5StreamParser)
tmp->DropTimer();
NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mObserver)
NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mRequest)
tmp->mOwner = nullptr;
tmp->mExecutorFlusher = nullptr;
tmp->mLoadFlusher = nullptr;
tmp->mExecutor = nullptr;
NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mChardet)
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsHtml5StreamParser)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mObserver)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mRequest)
if (tmp->mOwner) {
NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "mOwner");
cb.NoteXPCOMChild(static_cast<nsIParser*> (tmp->mOwner));
}
// hack: count the strongly owned edge wrapped in the runnable
if (tmp->mExecutorFlusher) {
NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "mExecutorFlusher->mExecutor");
cb.NoteXPCOMChild(static_cast<nsIContentSink*> (tmp->mExecutor));
}
// hack: count the strongly owned edge wrapped in the runnable
if (tmp->mLoadFlusher) {
NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "mLoadFlusher->mExecutor");
cb.NoteXPCOMChild(static_cast<nsIContentSink*> (tmp->mExecutor));
}
// hack: count self if held by mChardet
if (tmp->mChardet) {
NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb,
"mChardet->mObserver");
cb.NoteXPCOMChild(static_cast<nsIStreamListener*>(tmp));
}
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
class nsHtml5ExecutorFlusher : public nsRunnable
{
private:
nsRefPtr<nsHtml5TreeOpExecutor> mExecutor;
public:
nsHtml5ExecutorFlusher(nsHtml5TreeOpExecutor* aExecutor)
: mExecutor(aExecutor)
{}
NS_IMETHODIMP Run()
{
if (!mExecutor->isInList()) {
mExecutor->RunFlushLoop();
}
return NS_OK;
}
};
class nsHtml5LoadFlusher : public nsRunnable
{
private:
nsRefPtr<nsHtml5TreeOpExecutor> mExecutor;
public:
nsHtml5LoadFlusher(nsHtml5TreeOpExecutor* aExecutor)
: mExecutor(aExecutor)
{}
NS_IMETHODIMP Run()
{
mExecutor->FlushSpeculativeLoads();
return NS_OK;
}
};
nsHtml5StreamParser::nsHtml5StreamParser(nsHtml5TreeOpExecutor* aExecutor,
nsHtml5Parser* aOwner,
eParserMode aMode)
: mFirstBuffer(nullptr) // Will be filled when starting
, mLastBuffer(nullptr) // Will be filled when starting
, mExecutor(aExecutor)
, mTreeBuilder(new nsHtml5TreeBuilder((aMode == VIEW_SOURCE_HTML ||
aMode == VIEW_SOURCE_XML) ?
nullptr : mExecutor->GetStage(),
aMode == NORMAL ?
mExecutor->GetStage() : nullptr))
, mTokenizer(new nsHtml5Tokenizer(mTreeBuilder, aMode == VIEW_SOURCE_XML))
, mTokenizerMutex("nsHtml5StreamParser mTokenizerMutex")
, mOwner(aOwner)
, mSpeculationMutex("nsHtml5StreamParser mSpeculationMutex")
, mTerminatedMutex("nsHtml5StreamParser mTerminatedMutex")
, mThread(nsHtml5Module::GetStreamParserThread())
, mExecutorFlusher(new nsHtml5ExecutorFlusher(aExecutor))
, mLoadFlusher(new nsHtml5LoadFlusher(aExecutor))
, mFlushTimer(do_CreateInstance("@mozilla.org/timer;1"))
, mMode(aMode)
{
NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
mFlushTimer->SetTarget(mThread);
mAtomTable.Init(); // we aren't checking for OOM anyway...
#ifdef DEBUG
mAtomTable.SetPermittedLookupThread(mThread);
#endif
mTokenizer->setInterner(&mAtomTable);
mTokenizer->setEncodingDeclarationHandler(this);
if (aMode == VIEW_SOURCE_HTML || aMode == VIEW_SOURCE_XML) {
nsHtml5Highlighter* highlighter =
new nsHtml5Highlighter(mExecutor->GetStage());
mTokenizer->EnableViewSource(highlighter); // takes ownership
mTreeBuilder->EnableViewSource(highlighter); // doesn't own
}
// Chardet instantiation adapted from nsDOMFile.
// Chardet is initialized here even if it turns out to be useless
// to make the chardet refcount its observer (nsHtml5StreamParser)
// on the main thread.
const nsAdoptingCString& detectorName =
Preferences::GetLocalizedCString("intl.charset.detector");
if (!detectorName.IsEmpty()) {
nsAutoCString detectorContractID;
detectorContractID.AssignLiteral(NS_CHARSET_DETECTOR_CONTRACTID_BASE);
detectorContractID += detectorName;
if ((mChardet = do_CreateInstance(detectorContractID.get()))) {
(void) mChardet->Init(this);
mFeedChardet = true;
}
}
// There's a zeroing operator new for everything else
}
nsHtml5StreamParser::~nsHtml5StreamParser()
{
NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
mTokenizer->end();
NS_ASSERTION(!mFlushTimer, "Flush timer was not dropped before dtor!");
#ifdef DEBUG
mRequest = nullptr;
mObserver = nullptr;
mUnicodeDecoder = nullptr;
mSniffingBuffer = nullptr;
mMetaScanner = nullptr;
mFirstBuffer = nullptr;
mExecutor = nullptr;
mTreeBuilder = nullptr;
mTokenizer = nullptr;
mOwner = nullptr;
#endif
}
nsresult
nsHtml5StreamParser::GetChannel(nsIChannel** aChannel)
{
NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
return mRequest ? CallQueryInterface(mRequest, aChannel) :
NS_ERROR_NOT_AVAILABLE;
}
NS_IMETHODIMP
nsHtml5StreamParser::Notify(const char* aCharset, nsDetectionConfident aConf)
{
NS_ASSERTION(IsParserThread(), "Wrong thread!");
if (aConf == eBestAnswer || aConf == eSureAnswer) {
mFeedChardet = false; // just in case
if (HasDecoder()) {
if (mCharset.Equals(aCharset)) {
NS_ASSERTION(mCharsetSource < kCharsetFromAutoDetection,
"Why are we running chardet at all?");
mCharsetSource = kCharsetFromAutoDetection;
mTreeBuilder->SetDocumentCharset(mCharset, mCharsetSource);
} else {
// We've already committed to a decoder. Request a reload from the
// docshell.
nsAutoCString charset(aCharset);
mTreeBuilder->NeedsCharsetSwitchTo(charset,
kCharsetFromAutoDetection,
0);
FlushTreeOpsAndDisarmTimer();
Interrupt();
}
} else {
// Got a confident answer from the sniffing buffer. That code will
// take care of setting up the decoder.
mCharset.Assign(aCharset);
mCharsetSource = kCharsetFromAutoDetection;
mTreeBuilder->SetDocumentCharset(mCharset, mCharsetSource);
}
}
return NS_OK;
}
void
nsHtml5StreamParser::SetViewSourceTitle(nsIURI* aURL)
{
if (aURL) {
nsCOMPtr<nsIURI> temp;
bool isViewSource;
aURL->SchemeIs("view-source", &isViewSource);
if (isViewSource) {
nsCOMPtr<nsINestedURI> nested = do_QueryInterface(aURL);
nested->GetInnerURI(getter_AddRefs(temp));
} else {
temp = aURL;
}
bool isData;
temp->SchemeIs("data", &isData);
if (isData) {
// Avoid showing potentially huge data: URLs. The three last bytes are
// UTF-8 for an ellipsis.
mViewSourceTitle.AssignLiteral("data:\xE2\x80\xA6");
} else {
temp->GetSpec(mViewSourceTitle);
}
}
}
nsresult
nsHtml5StreamParser::SetupDecodingAndWriteSniffingBufferAndCurrentSegment(const uint8_t* aFromSegment, // can be null
uint32_t aCount,
uint32_t* aWriteCount)
{
NS_ASSERTION(IsParserThread(), "Wrong thread!");
nsresult rv = NS_OK;
nsCOMPtr<nsICharsetConverterManager> convManager = do_GetService(NS_CHARSETCONVERTERMANAGER_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
rv = convManager->GetUnicodeDecoder(mCharset.get(), getter_AddRefs(mUnicodeDecoder));
if (rv == NS_ERROR_UCONV_NOCONV) {
mCharset.AssignLiteral("windows-1252"); // lower case is the raw form
mCharsetSource = kCharsetFromWeakDocTypeDefault;
rv = convManager->GetUnicodeDecoderRaw(mCharset.get(), getter_AddRefs(mUnicodeDecoder));
mTreeBuilder->SetDocumentCharset(mCharset, mCharsetSource);
}
NS_ENSURE_SUCCESS(rv, rv);
mUnicodeDecoder->SetInputErrorBehavior(nsIUnicodeDecoder::kOnError_Recover);
return WriteSniffingBufferAndCurrentSegment(aFromSegment, aCount, aWriteCount);
}
nsresult
nsHtml5StreamParser::WriteSniffingBufferAndCurrentSegment(const uint8_t* aFromSegment, // can be null
uint32_t aCount,
uint32_t* aWriteCount)
{
NS_ASSERTION(IsParserThread(), "Wrong thread!");
nsresult rv = NS_OK;
if (mSniffingBuffer) {
uint32_t writeCount;
rv = WriteStreamBytes(mSniffingBuffer, mSniffingLength, &writeCount);
NS_ENSURE_SUCCESS(rv, rv);
mSniffingBuffer = nullptr;
}
mMetaScanner = nullptr;
if (aFromSegment) {
rv = WriteStreamBytes(aFromSegment, aCount, aWriteCount);
}
return rv;
}
nsresult
nsHtml5StreamParser::SetupDecodingFromBom(const char* aCharsetName, const char* aDecoderCharsetName)
{
NS_ASSERTION(IsParserThread(), "Wrong thread!");
nsresult rv = NS_OK;
nsCOMPtr<nsICharsetConverterManager> convManager = do_GetService(NS_CHARSETCONVERTERMANAGER_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
rv = convManager->GetUnicodeDecoderRaw(aDecoderCharsetName, getter_AddRefs(mUnicodeDecoder));
NS_ENSURE_SUCCESS(rv, rv);
mUnicodeDecoder->SetInputErrorBehavior(nsIUnicodeDecoder::kOnError_Recover);
mCharset.Assign(aCharsetName);
mCharsetSource = kCharsetFromByteOrderMark;
mFeedChardet = false;
mTreeBuilder->SetDocumentCharset(mCharset, mCharsetSource);
mSniffingBuffer = nullptr;
mMetaScanner = nullptr;
mBomState = BOM_SNIFFING_OVER;
return rv;
}
void
nsHtml5StreamParser::SniffBOMlessUTF16BasicLatin(const uint8_t* aFromSegment,
uint32_t aCountToSniffingLimit)
{
// Avoid underspecified heuristic craziness for XHR
if (mMode == LOAD_AS_DATA) {
return;
}
// Make sure there's enough data. Require room for "<title></title>"
if (mSniffingLength + aCountToSniffingLimit < 30) {
return;
}
// even-numbered bytes tracked at 0, odd-numbered bytes tracked at 1
bool byteZero[2] = { false, false };
bool byteNonZero[2] = { false, false };
uint32_t i = 0;
if (mSniffingBuffer) {
for (; i < mSniffingLength; ++i) {
if (mSniffingBuffer[i]) {
if (byteNonZero[1 - (i % 2)]) {
return;
}
byteNonZero[i % 2] = true;
} else {
if (byteZero[1 - (i % 2)]) {
return;
}
byteZero[i % 2] = true;
}
}
}
if (aFromSegment) {
for (uint32_t j = 0; j < aCountToSniffingLimit; ++j) {
if (aFromSegment[j]) {
if (byteNonZero[1 - ((i + j) % 2)]) {
return;
}
byteNonZero[(i + j) % 2] = true;
} else {
if (byteZero[1 - ((i + j) % 2)]) {
return;
}
byteZero[(i + j) % 2] = true;
}
}
}
if (byteNonZero[0]) {
mCharset.Assign("UTF-16LE");
} else {
mCharset.Assign("UTF-16BE");
}
mCharsetSource = kCharsetFromIrreversibleAutoDetection;
mTreeBuilder->SetDocumentCharset(mCharset, mCharsetSource);
mFeedChardet = false;
mTreeBuilder->MaybeComplainAboutCharset("EncBomlessUtf16",
true,
0);
}
void
nsHtml5StreamParser::SetEncodingFromExpat(const PRUnichar* aEncoding)
{
if (aEncoding) {
nsDependentString utf16(aEncoding);
nsAutoCString utf8;
CopyUTF16toUTF8(utf16, utf8);
if (PreferredForInternalEncodingDecl(utf8)) {
mCharset.Assign(utf8);
mCharsetSource = kCharsetFromMetaTag; // closest for XML
return;
}
// else the page declared an encoding Gecko doesn't support and we'd
// end up defaulting to UTF-8 anyway. Might as well fall through here
// right away and let the encoding be set to UTF-8 which we'd default to
// anyway.
}
mCharset.AssignLiteral("UTF-8"); // XML defaults to UTF-8 without a BOM
mCharsetSource = kCharsetFromMetaTag; // means confident
}
// A separate user data struct is used instead of passing the
// nsHtml5StreamParser instance as user data in order to avoid including
// expat.h in nsHtml5StreamParser.h. Doing that would cause naming conflicts.
// Using a separate user data struct also avoids bloating nsHtml5StreamParser
// by one pointer.
struct UserData {
XML_Parser mExpat;
nsHtml5StreamParser* mStreamParser;
};
// Using no-namespace handler callbacks to avoid including expat.h in
// nsHtml5StreamParser.h, since doing so would cause naming conclicts.
static void
HandleXMLDeclaration(void* aUserData,
const XML_Char* aVersion,
const XML_Char* aEncoding,
int aStandalone)
{
UserData* ud = static_cast<UserData*>(aUserData);
ud->mStreamParser->SetEncodingFromExpat(
reinterpret_cast<const PRUnichar*>(aEncoding));
XML_StopParser(ud->mExpat, false);
}
static void
HandleStartElement(void* aUserData,
const XML_Char* aName,
const XML_Char **aAtts)
{
UserData* ud = static_cast<UserData*>(aUserData);
XML_StopParser(ud->mExpat, false);
}
static void
HandleEndElement(void* aUserData,
const XML_Char* aName)
{
UserData* ud = static_cast<UserData*>(aUserData);
XML_StopParser(ud->mExpat, false);
}
static void
HandleComment(void* aUserData,
const XML_Char* aName)
{
UserData* ud = static_cast<UserData*>(aUserData);
XML_StopParser(ud->mExpat, false);
}
static void
HandleProcessingInstruction(void* aUserData,
const XML_Char* aTarget,
const XML_Char* aData)
{
UserData* ud = static_cast<UserData*>(aUserData);
XML_StopParser(ud->mExpat, false);
}
nsresult
nsHtml5StreamParser::FinalizeSniffing(const uint8_t* aFromSegment, // can be null
uint32_t aCount,
uint32_t* aWriteCount,
uint32_t aCountToSniffingLimit)
{
NS_ASSERTION(IsParserThread(), "Wrong thread!");
NS_ASSERTION(mCharsetSource < kCharsetFromMetaTag,
"Should not finalize sniffing when already confident.");
if (mMode == VIEW_SOURCE_XML) {
static const XML_Memory_Handling_Suite memsuite =
{
(void *(*)(size_t))moz_xmalloc,
(void *(*)(void *, size_t))moz_xrealloc,
moz_free
};
static const PRUnichar kExpatSeparator[] = { 0xFFFF, '\0' };
static const PRUnichar kISO88591[] =
{ 'I', 'S', 'O', '-', '8', '8', '5', '9', '-', '1', '\0' };
UserData ud;
ud.mStreamParser = this;
// If we got this far, the stream didn't have a BOM. UTF-16-encoded XML
// documents MUST begin with a BOM. We don't support EBCDIC and such.
// Thus, at this point, what we have is garbage or something encoded using
// a rough ASCII superset. ISO-8859-1 allows us to decode ASCII bytes
// without throwing errors when bytes have the most significant bit set
// and without triggering expat's unknown encoding code paths. This is
// enough to be able to use expat to parse the XML declaration in order
// to extract the encoding name from it.
ud.mExpat = XML_ParserCreate_MM(kISO88591, &memsuite, kExpatSeparator);
XML_SetXmlDeclHandler(ud.mExpat, HandleXMLDeclaration);
XML_SetElementHandler(ud.mExpat, HandleStartElement, HandleEndElement);
XML_SetCommentHandler(ud.mExpat, HandleComment);
XML_SetProcessingInstructionHandler(ud.mExpat, HandleProcessingInstruction);
XML_SetUserData(ud.mExpat, static_cast<void*>(&ud));
XML_Status status = XML_STATUS_OK;
// aFromSegment points to the data obtained from the current network
// event. mSniffingBuffer (if it exists) contains the data obtained before
// the current event. Thus, mSniffingLenth bytes of mSniffingBuffer
// followed by aCountToSniffingLimit bytes from aFromSegment are the
// first 1024 bytes of the file (or the file as a whole if the file is
// 1024 bytes long or shorter). Thus, we parse both buffers, but if the
// first call succeeds already, we skip parsing the second buffer.
if (mSniffingBuffer) {
status = XML_Parse(ud.mExpat,
reinterpret_cast<const char*>(mSniffingBuffer.get()),
mSniffingLength,
false);
}
if (status == XML_STATUS_OK &&
mCharsetSource < kCharsetFromMetaTag &&
aFromSegment) {
status = XML_Parse(ud.mExpat,
reinterpret_cast<const char*>(aFromSegment),
aCountToSniffingLimit,
false);
}
XML_ParserFree(ud.mExpat);
if (mCharsetSource < kCharsetFromMetaTag) {
// Failed to get an encoding from the XML declaration. XML defaults
// confidently to UTF-8 in this case.
// It is also possible that the document has an XML declaration that is
// longer than 1024 bytes, but that case is not worth worrying about.
mCharset.AssignLiteral("UTF-8");
mCharsetSource = kCharsetFromMetaTag; // means confident
}
return SetupDecodingAndWriteSniffingBufferAndCurrentSegment(aFromSegment,
aCount,
aWriteCount);
}
// meta scan failed.
if (mCharsetSource >= kCharsetFromHintPrevDoc) {
mFeedChardet = false;
return SetupDecodingAndWriteSniffingBufferAndCurrentSegment(aFromSegment, aCount, aWriteCount);
}
// Check for BOMless UTF-16 with Basic
// Latin content for compat with IE. See bug 631751.
SniffBOMlessUTF16BasicLatin(aFromSegment, aCountToSniffingLimit);
// the charset may have been set now
// maybe try chardet now;
if (mFeedChardet) {
bool dontFeed;
nsresult rv;
if (mSniffingBuffer) {
rv = mChardet->DoIt((const char*)mSniffingBuffer.get(), mSniffingLength, &dontFeed);
mFeedChardet = !dontFeed;
NS_ENSURE_SUCCESS(rv, rv);
}
if (mFeedChardet && aFromSegment) {
rv = mChardet->DoIt((const char*)aFromSegment,
// Avoid buffer boundary-dependent behavior when
// reparsing is forbidden. If reparse is forbidden,
// act as if we only saw the first 1024 bytes.
// When reparsing isn't forbidden, buffer boundaries
// can have an effect on whether the page is loaded
// once or twice. :-(
mReparseForbidden ? aCountToSniffingLimit : aCount,
&dontFeed);
mFeedChardet = !dontFeed;
NS_ENSURE_SUCCESS(rv, rv);
}
if (mFeedChardet && (!aFromSegment || mReparseForbidden)) {
// mReparseForbidden is checked so that we get to use the sniffing
// buffer with the best guess so far if we aren't allowed to guess
// better later.
mFeedChardet = false;
rv = mChardet->Done();
NS_ENSURE_SUCCESS(rv, rv);
}
// fall thru; callback may have changed charset
}
if (mCharsetSource == kCharsetUninitialized) {
// Hopefully this case is never needed, but dealing with it anyway
mCharset.AssignLiteral("windows-1252");
mCharsetSource = kCharsetFromWeakDocTypeDefault;
mTreeBuilder->SetDocumentCharset(mCharset, mCharsetSource);
} else if (mMode == LOAD_AS_DATA &&
mCharsetSource == kCharsetFromWeakDocTypeDefault) {
NS_ASSERTION(mReparseForbidden, "Reparse should be forbidden for XHR");
NS_ASSERTION(!mFeedChardet, "Should not feed chardet for XHR");
NS_ASSERTION(mCharset.EqualsLiteral("UTF-8"),
"XHR should default to UTF-8");
// Now mark charset source as non-weak to signal that we have a decision
mCharsetSource = kCharsetFromDocTypeDefault;
mTreeBuilder->SetDocumentCharset(mCharset, mCharsetSource);
}
return SetupDecodingAndWriteSniffingBufferAndCurrentSegment(aFromSegment, aCount, aWriteCount);
}
nsresult
nsHtml5StreamParser::SniffStreamBytes(const uint8_t* aFromSegment,
uint32_t aCount,
uint32_t* aWriteCount)
{
NS_ASSERTION(IsParserThread(), "Wrong thread!");
nsresult rv = NS_OK;
uint32_t writeCount;
for (uint32_t i = 0; i < aCount && mBomState != BOM_SNIFFING_OVER; i++) {
switch (mBomState) {
case BOM_SNIFFING_NOT_STARTED:
NS_ASSERTION(i == 0, "Bad BOM sniffing state.");
switch (*aFromSegment) {
case 0xEF:
mBomState = SEEN_UTF_8_FIRST_BYTE;
break;
case 0xFF:
mBomState = SEEN_UTF_16_LE_FIRST_BYTE;
break;
case 0xFE:
mBomState = SEEN_UTF_16_BE_FIRST_BYTE;
break;
default:
mBomState = BOM_SNIFFING_OVER;
break;
}
break;
case SEEN_UTF_16_LE_FIRST_BYTE:
if (aFromSegment[i] == 0xFE) {
rv = SetupDecodingFromBom("UTF-16", "UTF-16LE"); // upper case is the raw form
NS_ENSURE_SUCCESS(rv, rv);
uint32_t count = aCount - (i + 1);
rv = WriteStreamBytes(aFromSegment + (i + 1), count, &writeCount);
NS_ENSURE_SUCCESS(rv, rv);
*aWriteCount = writeCount + (i + 1);
return rv;
}
mBomState = BOM_SNIFFING_OVER;
break;
case SEEN_UTF_16_BE_FIRST_BYTE:
if (aFromSegment[i] == 0xFF) {
rv = SetupDecodingFromBom("UTF-16", "UTF-16BE"); // upper case is the raw form
NS_ENSURE_SUCCESS(rv, rv);
uint32_t count = aCount - (i + 1);
rv = WriteStreamBytes(aFromSegment + (i + 1), count, &writeCount);
NS_ENSURE_SUCCESS(rv, rv);
*aWriteCount = writeCount + (i + 1);
return rv;
}
mBomState = BOM_SNIFFING_OVER;
break;
case SEEN_UTF_8_FIRST_BYTE:
if (aFromSegment[i] == 0xBB) {
mBomState = SEEN_UTF_8_SECOND_BYTE;
} else {
mBomState = BOM_SNIFFING_OVER;
}
break;
case SEEN_UTF_8_SECOND_BYTE:
if (aFromSegment[i] == 0xBF) {
rv = SetupDecodingFromBom("UTF-8", "UTF-8"); // upper case is the raw form
NS_ENSURE_SUCCESS(rv, rv);
uint32_t count = aCount - (i + 1);
rv = WriteStreamBytes(aFromSegment + (i + 1), count, &writeCount);
NS_ENSURE_SUCCESS(rv, rv);
*aWriteCount = writeCount + (i + 1);
return rv;
}
mBomState = BOM_SNIFFING_OVER;
break;
default:
mBomState = BOM_SNIFFING_OVER;
break;
}
}
// if we get here, there either was no BOM or the BOM sniffing isn't complete yet
if (!mMetaScanner && (mMode == NORMAL ||
mMode == VIEW_SOURCE_HTML ||
mMode == LOAD_AS_DATA)) {
mMetaScanner = new nsHtml5MetaScanner();
}
if (mSniffingLength + aCount >= NS_HTML5_STREAM_PARSER_SNIFFING_BUFFER_SIZE) {
// this is the last buffer
uint32_t countToSniffingLimit =
NS_HTML5_STREAM_PARSER_SNIFFING_BUFFER_SIZE - mSniffingLength;
if (mMode == NORMAL || mMode == VIEW_SOURCE_HTML || mMode == LOAD_AS_DATA) {
nsHtml5ByteReadable readable(aFromSegment, aFromSegment +
countToSniffingLimit);
mMetaScanner->sniff(&readable, getter_AddRefs(mUnicodeDecoder), mCharset);
if (mUnicodeDecoder) {
mUnicodeDecoder->SetInputErrorBehavior(
nsIUnicodeDecoder::kOnError_Recover);
// meta scan successful
mCharsetSource = kCharsetFromMetaPrescan;
mFeedChardet = false;
mTreeBuilder->SetDocumentCharset(mCharset, mCharsetSource);
mMetaScanner = nullptr;
return WriteSniffingBufferAndCurrentSegment(aFromSegment, aCount,
aWriteCount);
}
}
return FinalizeSniffing(aFromSegment, aCount, aWriteCount,
countToSniffingLimit);
}
// not the last buffer
if (mMode == NORMAL || mMode == VIEW_SOURCE_HTML || mMode == LOAD_AS_DATA) {
nsHtml5ByteReadable readable(aFromSegment, aFromSegment + aCount);
mMetaScanner->sniff(&readable, getter_AddRefs(mUnicodeDecoder), mCharset);
if (mUnicodeDecoder) {
// meta scan successful
mUnicodeDecoder->SetInputErrorBehavior(
nsIUnicodeDecoder::kOnError_Recover);
mCharsetSource = kCharsetFromMetaPrescan;
mFeedChardet = false;
mTreeBuilder->SetDocumentCharset(mCharset, mCharsetSource);
mMetaScanner = nullptr;
return WriteSniffingBufferAndCurrentSegment(aFromSegment,
aCount,
aWriteCount);
}
}
if (!mSniffingBuffer) {
const mozilla::fallible_t fallible = mozilla::fallible_t();
mSniffingBuffer = new (fallible)
uint8_t[NS_HTML5_STREAM_PARSER_SNIFFING_BUFFER_SIZE];
if (!mSniffingBuffer) {
return NS_ERROR_OUT_OF_MEMORY;
}
}
memcpy(mSniffingBuffer + mSniffingLength, aFromSegment, aCount);
mSniffingLength += aCount;
*aWriteCount = aCount;
return NS_OK;
}
nsresult
nsHtml5StreamParser::WriteStreamBytes(const uint8_t* aFromSegment,
uint32_t aCount,
uint32_t* aWriteCount)
{
NS_ASSERTION(IsParserThread(), "Wrong thread!");
// mLastBuffer always points to a buffer of the size
// NS_HTML5_STREAM_PARSER_READ_BUFFER_SIZE.
if (mLastBuffer->getEnd() == NS_HTML5_STREAM_PARSER_READ_BUFFER_SIZE) {
nsRefPtr<nsHtml5OwningUTF16Buffer> newBuf =
nsHtml5OwningUTF16Buffer::FalliblyCreate(
NS_HTML5_STREAM_PARSER_READ_BUFFER_SIZE);
if (!newBuf) {
return NS_ERROR_OUT_OF_MEMORY;
}
mLastBuffer = (mLastBuffer->next = newBuf.forget());
}
int32_t totalByteCount = 0;
for (;;) {
int32_t end = mLastBuffer->getEnd();
int32_t byteCount = aCount - totalByteCount;
int32_t utf16Count = NS_HTML5_STREAM_PARSER_READ_BUFFER_SIZE - end;
NS_ASSERTION(utf16Count, "Trying to convert into a buffer with no free space!");
// byteCount may be zero to force the decoder to output a pending surrogate
// pair.
nsresult convResult = mUnicodeDecoder->Convert((const char*)aFromSegment, &byteCount, mLastBuffer->getBuffer() + end, &utf16Count);
end += utf16Count;
mLastBuffer->setEnd(end);
totalByteCount += byteCount;
aFromSegment += byteCount;
NS_ASSERTION(end <= NS_HTML5_STREAM_PARSER_READ_BUFFER_SIZE,
"The Unicode decoder wrote too much data.");
NS_ASSERTION(byteCount >= -1, "The decoder consumed fewer than -1 bytes.");
if (NS_FAILED(convResult)) {
// Using the more generic NS_FAILED test above in case there are still
// decoders around that don't use NS_ERROR_ILLEGAL_INPUT properly.
NS_ASSERTION(convResult == NS_ERROR_ILLEGAL_INPUT,
"The decoder signaled an error other than NS_ERROR_ILLEGAL_INPUT.");
// There's an illegal byte in the input. It's now the responsibility
// of this calling code to output a U+FFFD REPLACEMENT CHARACTER and
// reset the decoder.
if (totalByteCount < (int32_t)aCount) {
// advance over the bad byte
++totalByteCount;
++aFromSegment;
} else {
NS_NOTREACHED("The decoder signaled an error but consumed all input.");
// Recovering from this situation in case there are still broken
// decoders, since nsScanner had recovery code, too.
totalByteCount = (int32_t)aCount;
}
// Emit the REPLACEMENT CHARACTER
if (end >= NS_HTML5_STREAM_PARSER_READ_BUFFER_SIZE) {
nsRefPtr<nsHtml5OwningUTF16Buffer> newBuf =
nsHtml5OwningUTF16Buffer::FalliblyCreate(
NS_HTML5_STREAM_PARSER_READ_BUFFER_SIZE);
if (!newBuf) {
return NS_ERROR_OUT_OF_MEMORY;
}
mLastBuffer = (mLastBuffer->next = newBuf.forget());
end = 0;
}
mLastBuffer->getBuffer()[end] = 0xFFFD;
++end;
mLastBuffer->setEnd(end);
if (end >= NS_HTML5_STREAM_PARSER_READ_BUFFER_SIZE) {
nsRefPtr<nsHtml5OwningUTF16Buffer> newBuf =
nsHtml5OwningUTF16Buffer::FalliblyCreate(
NS_HTML5_STREAM_PARSER_READ_BUFFER_SIZE);
if (!newBuf) {
return NS_ERROR_OUT_OF_MEMORY;
}
mLastBuffer = (mLastBuffer->next = newBuf.forget());
}
mUnicodeDecoder->Reset();
if (totalByteCount == (int32_t)aCount) {
*aWriteCount = (uint32_t)totalByteCount;
return NS_OK;
}
} else if (convResult == NS_PARTIAL_MORE_OUTPUT) {
nsRefPtr<nsHtml5OwningUTF16Buffer> newBuf =
nsHtml5OwningUTF16Buffer::FalliblyCreate(
NS_HTML5_STREAM_PARSER_READ_BUFFER_SIZE);
if (!newBuf) {
return NS_ERROR_OUT_OF_MEMORY;
}
mLastBuffer = (mLastBuffer->next = newBuf.forget());
// All input may have been consumed if there is a pending surrogate pair
// that doesn't fit in the output buffer. Loop back to push a zero-length
// input to the decoder in that case.
} else {
NS_ASSERTION(totalByteCount == (int32_t)aCount,
"The Unicode decoder consumed the wrong number of bytes.");
*aWriteCount = (uint32_t)totalByteCount;
return NS_OK;
}
}
}
// nsIRequestObserver methods:
nsresult
nsHtml5StreamParser::OnStartRequest(nsIRequest* aRequest, nsISupports* aContext)
{
NS_PRECONDITION(STREAM_NOT_STARTED == mStreamState,
"Got OnStartRequest when the stream had already started.");
NS_PRECONDITION(!mExecutor->HasStarted(),
"Got OnStartRequest at the wrong stage in the executor life cycle.");
NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
if (mObserver) {
mObserver->OnStartRequest(aRequest, aContext);
}
mRequest = aRequest;
mStreamState = STREAM_BEING_READ;
if (mMode == VIEW_SOURCE_HTML || mMode == VIEW_SOURCE_XML) {
mTokenizer->StartViewSource(NS_ConvertUTF8toUTF16(mViewSourceTitle));
}
// For View Source, the parser should run with scripts "enabled" if a normal
// load would have scripts enabled.
bool scriptingEnabled = mMode == LOAD_AS_DATA ?
false : mExecutor->IsScriptEnabled();
mOwner->StartTokenizer(scriptingEnabled);
mTreeBuilder->setScriptingEnabled(scriptingEnabled);
mTreeBuilder->SetPreventScriptExecution(!((mMode == NORMAL) &&
scriptingEnabled));
mTokenizer->start();
mExecutor->Start();
mExecutor->StartReadingFromStage();
if (mMode == PLAIN_TEXT) {
mTreeBuilder->StartPlainText();
mTokenizer->StartPlainText();
} else if (mMode == VIEW_SOURCE_PLAIN) {
mTreeBuilder->StartPlainTextViewSource(NS_ConvertUTF8toUTF16(mViewSourceTitle));
mTokenizer->StartPlainText();
}
/*
* If you move the following line, be very careful not to cause
* WillBuildModel to be called before the document has had its
* script global object set.
*/
mExecutor->WillBuildModel(eDTDMode_unknown);
nsRefPtr<nsHtml5OwningUTF16Buffer> newBuf =
nsHtml5OwningUTF16Buffer::FalliblyCreate(
NS_HTML5_STREAM_PARSER_READ_BUFFER_SIZE);
if (!newBuf) {
// marks this stream parser as terminated,
// which prevents entry to code paths that
// would use mFirstBuffer or mLastBuffer.
return mExecutor->MarkAsBroken(NS_ERROR_OUT_OF_MEMORY);
}
NS_ASSERTION(!mFirstBuffer, "How come we have the first buffer set?");
NS_ASSERTION(!mLastBuffer, "How come we have the last buffer set?");
mFirstBuffer = mLastBuffer = newBuf;
nsresult rv = NS_OK;
// The line below means that the encoding can end up being wrong if
// a view-source URL is loaded without having the encoding hint from a
// previous normal load in the history.
mReparseForbidden = !(mMode == NORMAL || mMode == PLAIN_TEXT);
nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(mRequest, &rv));
if (NS_SUCCEEDED(rv)) {
nsAutoCString method;
httpChannel->GetRequestMethod(method);
// XXX does Necko have a way to renavigate POST, etc. without hitting
// the network?
if (!method.EqualsLiteral("GET")) {
// This is the old Gecko behavior but the HTML5 spec disagrees.
// Don't reparse on POST.
mReparseForbidden = true;
mFeedChardet = false; // can't restart anyway
}
}
if (mCharsetSource == kCharsetFromParentFrame) {
// Remember this in case chardet overwrites mCharsetSource
mInitialEncodingWasFromParentFrame = true;
}
if (mCharsetSource >= kCharsetFromAutoDetection) {
mFeedChardet = false;
}
if (mCharsetSource <= kCharsetFromMetaPrescan) {
// we aren't ready to commit to an encoding yet
// leave converter uninstantiated for now
return NS_OK;
}
nsCOMPtr<nsICharsetConverterManager> convManager = do_GetService(NS_CHARSETCONVERTERMANAGER_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
rv = convManager->GetUnicodeDecoder(mCharset.get(), getter_AddRefs(mUnicodeDecoder));
// if we failed to get a decoder, there will be fallback, so don't propagate
// the error.
if (NS_SUCCEEDED(rv)) {
mUnicodeDecoder->SetInputErrorBehavior(nsIUnicodeDecoder::kOnError_Recover);
} else {
mCharsetSource = kCharsetFromWeakDocTypeDefault;
}
return NS_OK;
}
void
nsHtml5StreamParser::DoStopRequest()
{
NS_ASSERTION(IsParserThread(), "Wrong thread!");
NS_PRECONDITION(STREAM_BEING_READ == mStreamState,
"Stream ended without being open.");
mTokenizerMutex.AssertCurrentThreadOwns();
if (IsTerminated()) {
return;
}
mStreamState = STREAM_ENDED;
if (!mUnicodeDecoder) {
uint32_t writeCount;
if (NS_FAILED(FinalizeSniffing(nullptr, 0, &writeCount, 0))) {
MarkAsBroken();
return;
}
} else if (mFeedChardet) {
mChardet->Done();
}
if (IsTerminatedOrInterrupted()) {
return;
}
ParseAvailableData();
}
class nsHtml5RequestStopper : public nsRunnable
{
private:
nsHtml5RefPtr<nsHtml5StreamParser> mStreamParser;
public:
nsHtml5RequestStopper(nsHtml5StreamParser* aStreamParser)
: mStreamParser(aStreamParser)
{}
NS_IMETHODIMP Run()
{
mozilla::MutexAutoLock autoLock(mStreamParser->mTokenizerMutex);
mStreamParser->DoStopRequest();
return NS_OK;
}
};
nsresult
nsHtml5StreamParser::OnStopRequest(nsIRequest* aRequest,
nsISupports* aContext,
nsresult status)
{
NS_ASSERTION(mRequest == aRequest, "Got Stop on wrong stream.");
NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
if (mObserver) {
mObserver->OnStopRequest(aRequest, aContext, status);
}
nsCOMPtr<nsIRunnable> stopper = new nsHtml5RequestStopper(this);
if (NS_FAILED(mThread->Dispatch(stopper, nsIThread::DISPATCH_NORMAL))) {
NS_WARNING("Dispatching StopRequest event failed.");
}
return NS_OK;
}
void
nsHtml5StreamParser::DoDataAvailable(uint8_t* aBuffer, uint32_t aLength)
{
NS_ASSERTION(IsParserThread(), "Wrong thread!");
NS_PRECONDITION(STREAM_BEING_READ == mStreamState,
"DoDataAvailable called when stream not open.");
mTokenizerMutex.AssertCurrentThreadOwns();
if (IsTerminated()) {
return;
}
uint32_t writeCount;
nsresult rv;
if (HasDecoder()) {
if (mFeedChardet) {
bool dontFeed;
mChardet->DoIt((const char*)aBuffer, aLength, &dontFeed);
mFeedChardet = !dontFeed;
}
rv = WriteStreamBytes(aBuffer, aLength, &writeCount);
} else {
rv = SniffStreamBytes(aBuffer, aLength, &writeCount);
}
if (NS_FAILED(rv)) {
MarkAsBroken();
return;
}
NS_ASSERTION(writeCount == aLength, "Wrong number of stream bytes written/sniffed.");
if (IsTerminatedOrInterrupted()) {
return;
}
ParseAvailableData();
if (mFlushTimerArmed || mSpeculating) {
return;
}
mFlushTimer->InitWithFuncCallback(nsHtml5StreamParser::TimerCallback,
static_cast<void*> (this),
mFlushTimerEverFired ?
sTimerInitialDelay :
sTimerSubsequentDelay,
nsITimer::TYPE_ONE_SHOT);
mFlushTimerArmed = true;
}
class nsHtml5DataAvailable : public nsRunnable
{
private:
nsHtml5RefPtr<nsHtml5StreamParser> mStreamParser;
nsAutoArrayPtr<uint8_t> mData;
uint32_t mLength;
public:
nsHtml5DataAvailable(nsHtml5StreamParser* aStreamParser,
uint8_t* aData,
uint32_t aLength)
: mStreamParser(aStreamParser)
, mData(aData)
, mLength(aLength)
{}
NS_IMETHODIMP Run()
{
mozilla::MutexAutoLock autoLock(mStreamParser->mTokenizerMutex);
mStreamParser->DoDataAvailable(mData, mLength);
return NS_OK;
}
};
// nsIStreamListener method:
nsresult
nsHtml5StreamParser::OnDataAvailable(nsIRequest* aRequest,
nsISupports* aContext,
nsIInputStream* aInStream,
uint64_t aSourceOffset,
uint32_t aLength)
{
nsresult rv;
if (NS_FAILED(rv = mExecutor->IsBroken())) {
return rv;
}
NS_ASSERTION(mRequest == aRequest, "Got data on wrong stream.");
uint32_t totalRead;
const mozilla::fallible_t fallible = mozilla::fallible_t();
nsAutoArrayPtr<uint8_t> data(new (fallible) uint8_t[aLength]);
if (!data) {
return mExecutor->MarkAsBroken(NS_ERROR_OUT_OF_MEMORY);
}
rv = aInStream->Read(reinterpret_cast<char*>(data.get()),
aLength, &totalRead);
NS_ENSURE_SUCCESS(rv, rv);
NS_ASSERTION(totalRead <= aLength, "Read more bytes than were available?");
nsCOMPtr<nsIRunnable> dataAvailable = new nsHtml5DataAvailable(this,
data.forget(),
totalRead);
if (NS_FAILED(mThread->Dispatch(dataAvailable, nsIThread::DISPATCH_NORMAL))) {
NS_WARNING("Dispatching DataAvailable event failed.");
}
return rv;
}
bool
nsHtml5StreamParser::PreferredForInternalEncodingDecl(nsACString& aEncoding)
{
nsAutoCString newEncoding(aEncoding);
newEncoding.Trim(" \t\r\n\f");
if (newEncoding.LowerCaseEqualsLiteral("utf-16") ||
newEncoding.LowerCaseEqualsLiteral("utf-16be") ||
newEncoding.LowerCaseEqualsLiteral("utf-16le")) {
mTreeBuilder->MaybeComplainAboutCharset("EncMetaUtf16",
true,
mTokenizer->getLineNumber());
newEncoding.Assign("UTF-8");
}
nsresult rv = NS_OK;
bool eq;
rv = nsCharsetAlias::Equals(newEncoding, mCharset, &eq);
if (NS_FAILED(rv)) {
// the encoding name is bogus
mTreeBuilder->MaybeComplainAboutCharset("EncMetaUnsupported",
true,
mTokenizer->getLineNumber());
return false;
}
if (eq) {
if (mCharsetSource < kCharsetFromMetaPrescan) {
if (mInitialEncodingWasFromParentFrame) {
mTreeBuilder->MaybeComplainAboutCharset("EncLateMetaFrame",
false,
mTokenizer->getLineNumber());
} else {
mTreeBuilder->MaybeComplainAboutCharset("EncLateMeta",
false,
mTokenizer->getLineNumber());
}
}
mCharsetSource = kCharsetFromMetaTag; // become confident
mFeedChardet = false; // don't feed chardet when confident
return false;
}
// XXX check HTML5 non-IANA aliases here
nsAutoCString preferred;
rv = nsCharsetAlias::GetPreferred(newEncoding, preferred);
if (NS_FAILED(rv)) {
// This charset has been blacklisted for permitting XSS smuggling.
// EncMetaNonRoughSuperset is a reasonable approximation to the
// right error message.
mTreeBuilder->MaybeComplainAboutCharset("EncMetaNonRoughSuperset",
true,
mTokenizer->getLineNumber());
return false;
}
// ??? Explicit further blacklist of character sets that are not
// "rough supersets" of ASCII. Some of these are handled above (utf-16),
// some by the XSS smuggling blacklist in charsetData.properties,
// maybe all of the remainder should also be blacklisted there.
if (preferred.LowerCaseEqualsLiteral("utf-16") ||
preferred.LowerCaseEqualsLiteral("utf-16be") ||
preferred.LowerCaseEqualsLiteral("utf-16le") ||
preferred.LowerCaseEqualsLiteral("utf-7") ||
preferred.LowerCaseEqualsLiteral("jis_x0212-1990") ||
preferred.LowerCaseEqualsLiteral("x-jis0208") ||
preferred.LowerCaseEqualsLiteral("x-imap4-modified-utf7") ||
preferred.LowerCaseEqualsLiteral("x-user-defined")) {
// Not a rough ASCII superset
mTreeBuilder->MaybeComplainAboutCharset("EncMetaNonRoughSuperset",
true,
mTokenizer->getLineNumber());
return false;
}
aEncoding.Assign(preferred);
return true;
}
bool
nsHtml5StreamParser::internalEncodingDeclaration(nsString* aEncoding)
{
// This code needs to stay in sync with
// nsHtml5MetaScanner::tryCharset. Unfortunately, the
// trickery with member fields there leads to some copy-paste reuse. :-(
NS_ASSERTION(IsParserThread(), "Wrong thread!");
if (mCharsetSource >= kCharsetFromMetaTag) { // this threshold corresponds to "confident" in the HTML5 spec
return false;
}
nsAutoCString newEncoding;
CopyUTF16toUTF8(*aEncoding, newEncoding);
if (!PreferredForInternalEncodingDecl(newEncoding)) {
return false;
}
if (mReparseForbidden) {
// This mReparseForbidden check happens after the call to
// PreferredForInternalEncodingDecl so that if that method calls
// MaybeComplainAboutCharset, its charset complaint wins over the one
// below.
mTreeBuilder->MaybeComplainAboutCharset("EncLateMetaTooLate",
true,
mTokenizer->getLineNumber());
return false; // not reparsing even if we wanted to
}
// Avoid having the chardet ask for another restart after this restart
// request.
mFeedChardet = false;
mTreeBuilder->NeedsCharsetSwitchTo(newEncoding,
kCharsetFromMetaTag,
mTokenizer->getLineNumber());
FlushTreeOpsAndDisarmTimer();
Interrupt();
// the tree op executor will cause the stream parser to terminate
// if the charset switch request is accepted or it'll uninterrupt
// if the request failed. Note that if the restart request fails,
// we don't bother trying to make chardet resume. Might as well
// assume that chardet-requested restarts would fail, too.
return true;
}
void
nsHtml5StreamParser::FlushTreeOpsAndDisarmTimer()
{
NS_ASSERTION(IsParserThread(), "Wrong thread!");
if (mFlushTimerArmed) {
// avoid calling Cancel if the flush timer isn't armed to avoid acquiring
// a mutex
mFlushTimer->Cancel();
mFlushTimerArmed = false;
}
if (mMode == VIEW_SOURCE_HTML || mMode == VIEW_SOURCE_XML) {
mTokenizer->FlushViewSource();
}
mTreeBuilder->Flush();
if (NS_FAILED(NS_DispatchToMainThread(mExecutorFlusher))) {
NS_WARNING("failed to dispatch executor flush event");
}
}
void
nsHtml5StreamParser::ParseAvailableData()
{
NS_ASSERTION(IsParserThread(), "Wrong thread!");
mTokenizerMutex.AssertCurrentThreadOwns();
if (IsTerminatedOrInterrupted()) {
return;
}
for (;;) {
if (!mFirstBuffer->hasMore()) {
if (mFirstBuffer == mLastBuffer) {
switch (mStreamState) {
case STREAM_BEING_READ:
// never release the last buffer.
if (!mSpeculating) {
// reuse buffer space if not speculating
mFirstBuffer->setStart(0);
mFirstBuffer->setEnd(0);
}
mTreeBuilder->FlushLoads();
// Dispatch this runnable unconditionally, because the loads
// that need flushing may have been flushed earlier even if the
// flush right above here did nothing.
if (NS_FAILED(NS_DispatchToMainThread(mLoadFlusher))) {
NS_WARNING("failed to dispatch load flush event");
}
return; // no more data for now but expecting more
case STREAM_ENDED:
if (mAtEOF) {
return;
}
mAtEOF = true;
if (mCharsetSource < kCharsetFromMetaTag) {
if (mInitialEncodingWasFromParentFrame) {
// Unfortunately, this check doesn't take effect for
// cross-origin frames, so cross-origin ad frames that have
// no text and only an image or a Flash embed get the more
// severe message from the next if block. The message is
// technically accurate, though.
mTreeBuilder->MaybeComplainAboutCharset("EncNoDeclarationFrame",
false,
0);
} else if (mMode == NORMAL) {
mTreeBuilder->MaybeComplainAboutCharset("EncNoDeclaration",
true,
0);
} else if (mMode == PLAIN_TEXT) {
mTreeBuilder->MaybeComplainAboutCharset("EncNoDeclarationPlain",
true,
0);
}
}
mTokenizer->eof();
mTreeBuilder->StreamEnded();
if (mMode == VIEW_SOURCE_HTML || mMode == VIEW_SOURCE_XML) {
mTokenizer->EndViewSource();
}
FlushTreeOpsAndDisarmTimer();
return; // no more data and not expecting more
default:
NS_NOTREACHED("It should be impossible to reach this.");
return;
}
}
mFirstBuffer = mFirstBuffer->next;
continue;
}
// now we have a non-empty buffer
mFirstBuffer->adjust(mLastWasCR);
mLastWasCR = false;
if (mFirstBuffer->hasMore()) {
mLastWasCR = mTokenizer->tokenizeBuffer(mFirstBuffer);
// At this point, internalEncodingDeclaration() may have called
// Terminate, but that never happens together with script.
// Can't assert that here, though, because it's possible that the main
// thread has called Terminate() while this thread was parsing.
if (mTreeBuilder->HasScript()) {
// HasScript() cannot return true if the tree builder is preventing
// script execution.
MOZ_ASSERT(mMode == NORMAL);
mozilla::MutexAutoLock speculationAutoLock(mSpeculationMutex);
nsHtml5Speculation* speculation =
new nsHtml5Speculation(mFirstBuffer,
mFirstBuffer->getStart(),
mTokenizer->getLineNumber(),
mTreeBuilder->newSnapshot());
mTreeBuilder->AddSnapshotToScript(speculation->GetSnapshot(),
speculation->GetStartLineNumber());
FlushTreeOpsAndDisarmTimer();
mTreeBuilder->SetOpSink(speculation);
mSpeculations.AppendElement(speculation); // adopts the pointer
mSpeculating = true;
}
if (IsTerminatedOrInterrupted()) {
return;
}
}
continue;
}
}
class nsHtml5StreamParserContinuation : public nsRunnable
{
private:
nsHtml5RefPtr<nsHtml5StreamParser> mStreamParser;
public:
nsHtml5StreamParserContinuation(nsHtml5StreamParser* aStreamParser)
: mStreamParser(aStreamParser)
{}
NS_IMETHODIMP Run()
{
mozilla::MutexAutoLock autoLock(mStreamParser->mTokenizerMutex);
mStreamParser->Uninterrupt();
mStreamParser->ParseAvailableData();
return NS_OK;
}
};
void
nsHtml5StreamParser::ContinueAfterScripts(nsHtml5Tokenizer* aTokenizer,
nsHtml5TreeBuilder* aTreeBuilder,
bool aLastWasCR)
{
NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
NS_ASSERTION(!(mMode == VIEW_SOURCE_HTML || mMode == VIEW_SOURCE_XML),
"ContinueAfterScripts called in view source mode!");
if (NS_FAILED(mExecutor->IsBroken())) {
return;
}
#ifdef DEBUG
mExecutor->AssertStageEmpty();
#endif
bool speculationFailed = false;
{
mozilla::MutexAutoLock speculationAutoLock(mSpeculationMutex);
if (mSpeculations.IsEmpty()) {
NS_NOTREACHED("ContinueAfterScripts called without speculations.");
return;
}
nsHtml5Speculation* speculation = mSpeculations.ElementAt(0);
if (aLastWasCR ||
!aTokenizer->isInDataState() ||
!aTreeBuilder->snapshotMatches(speculation->GetSnapshot())) {
speculationFailed = true;
// We've got a failed speculation :-(
Interrupt(); // Make the parser thread release the tokenizer mutex sooner
// now fall out of the speculationAutoLock into the tokenizerAutoLock block
} else {
// We've got a successful speculation!
if (mSpeculations.Length() > 1) {
// the first speculation isn't the current speculation, so there's
// no need to bother the parser thread.
speculation->FlushToSink(mExecutor);
NS_ASSERTION(!mExecutor->IsScriptExecuting(),
"ParseUntilBlocked() was supposed to ensure we don't come "
"here when scripts are executing.");
NS_ASSERTION(mExecutor->IsInFlushLoop(), "How are we here if "
"RunFlushLoop() didn't call ParseUntilBlocked() which is the "
"only caller of this method?");
mSpeculations.RemoveElementAt(0);
return;
}
// else
Interrupt(); // Make the parser thread release the tokenizer mutex sooner
// now fall through
// the first speculation is the current speculation. Need to
// release the the speculation mutex and acquire the tokenizer
// mutex. (Just acquiring the other mutex here would deadlock)
}
}
{
mozilla::MutexAutoLock tokenizerAutoLock(mTokenizerMutex);
#ifdef DEBUG
{
nsCOMPtr<nsIThread> mainThread;
NS_GetMainThread(getter_AddRefs(mainThread));
mAtomTable.SetPermittedLookupThread(mainThread);
}
#endif
// In principle, the speculation mutex should be acquired here,
// but there's no point, because the parser thread only acquires it
// when it has also acquired the tokenizer mutex and we are already
// holding the tokenizer mutex.
if (speculationFailed) {
// Rewind the stream
mAtEOF = false;
nsHtml5Speculation* speculation = mSpeculations.ElementAt(0);
mFirstBuffer = speculation->GetBuffer();
mFirstBuffer->setStart(speculation->GetStart());
mTokenizer->setLineNumber(speculation->GetStartLineNumber());
nsContentUtils::ReportToConsole(nsIScriptError::warningFlag,
"DOM Events",
mExecutor->GetDocument(),
nsContentUtils::eDOM_PROPERTIES,
"SpeculationFailed",
nullptr, 0,
nullptr,
EmptyString(),
speculation->GetStartLineNumber());
nsHtml5OwningUTF16Buffer* buffer = mFirstBuffer->next;
while (buffer) {
buffer->setStart(0);
buffer = buffer->next;
}
mSpeculations.Clear(); // potentially a huge number of destructors
// run here synchronously on the main thread...
mTreeBuilder->flushCharacters(); // empty the pending buffer
mTreeBuilder->ClearOps(); // now get rid of the failed ops
mTreeBuilder->SetOpSink(mExecutor->GetStage());
mExecutor->StartReadingFromStage();
mSpeculating = false;
// Copy state over
mLastWasCR = aLastWasCR;
mTokenizer->loadState(aTokenizer);
mTreeBuilder->loadState(aTreeBuilder, &mAtomTable);
} else {
// We've got a successful speculation and at least a moment ago it was
// the current speculation
mSpeculations.ElementAt(0)->FlushToSink(mExecutor);
NS_ASSERTION(!mExecutor->IsScriptExecuting(),
"ParseUntilBlocked() was supposed to ensure we don't come "
"here when scripts are executing.");
NS_ASSERTION(mExecutor->IsInFlushLoop(), "How are we here if "
"RunFlushLoop() didn't call ParseUntilBlocked() which is the "
"only caller of this method?");
mSpeculations.RemoveElementAt(0);
if (mSpeculations.IsEmpty()) {
// yes, it was still the only speculation. Now stop speculating
// However, before telling the executor to read from stage, flush
// any pending ops straight to the executor, because otherwise
// they remain unflushed until we get more data from the network.
mTreeBuilder->SetOpSink(mExecutor);
mTreeBuilder->Flush(true);
mTreeBuilder->SetOpSink(mExecutor->GetStage());
mExecutor->StartReadingFromStage();
mSpeculating = false;
}
}
nsCOMPtr<nsIRunnable> event = new nsHtml5StreamParserContinuation(this);
if (NS_FAILED(mThread->Dispatch(event, nsIThread::DISPATCH_NORMAL))) {
NS_WARNING("Failed to dispatch nsHtml5StreamParserContinuation");
}
// A stream event might run before this event runs, but that's harmless.
#ifdef DEBUG
mAtomTable.SetPermittedLookupThread(mThread);
#endif
}
}
void
nsHtml5StreamParser::ContinueAfterFailedCharsetSwitch()
{
NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
nsCOMPtr<nsIRunnable> event = new nsHtml5StreamParserContinuation(this);
if (NS_FAILED(mThread->Dispatch(event, nsIThread::DISPATCH_NORMAL))) {
NS_WARNING("Failed to dispatch nsHtml5StreamParserContinuation");
}
}
class nsHtml5TimerKungFu : public nsRunnable
{
private:
nsHtml5RefPtr<nsHtml5StreamParser> mStreamParser;
public:
nsHtml5TimerKungFu(nsHtml5StreamParser* aStreamParser)
: mStreamParser(aStreamParser)
{}
NS_IMETHODIMP Run()
{
if (mStreamParser->mFlushTimer) {
mStreamParser->mFlushTimer->Cancel();
mStreamParser->mFlushTimer = nullptr;
}
return NS_OK;
}
};
void
nsHtml5StreamParser::DropTimer()
{
NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
/*
* Simply nulling out the timer wouldn't work, because if the timer is
* armed, it needs to be canceled first. Simply canceling it first wouldn't
* work, because nsTimerImpl::Cancel is not safe for calling from outside
* the thread where nsTimerImpl::Fire would run. It's not safe to
* dispatch a runnable to cancel the timer from the destructor of this
* class, because the timer has a weak (void*) pointer back to this instance
* of the stream parser and having the timer fire before the runnable
* cancels it would make the timer access a deleted object.
*
* This DropTimer method addresses these issues. This method must be called
* on the main thread before the destructor of this class is reached.
* The nsHtml5TimerKungFu object has an nsHtml5RefPtr that addrefs this
* stream parser object to keep it alive until the runnable is done.
* The runnable cancels the timer on the parser thread, drops the timer
* and lets nsHtml5RefPtr send a runnable back to the main thread to
* release the stream parser.
*/
if (mFlushTimer) {
nsCOMPtr<nsIRunnable> event = new nsHtml5TimerKungFu(this);
if (NS_FAILED(mThread->Dispatch(event, nsIThread::DISPATCH_NORMAL))) {
NS_WARNING("Failed to dispatch TimerKungFu event");
}
}
}
// Using a static, because the method name Notify is taken by the chardet
// callback.
void
nsHtml5StreamParser::TimerCallback(nsITimer* aTimer, void* aClosure)
{
(static_cast<nsHtml5StreamParser*> (aClosure))->TimerFlush();
}
void
nsHtml5StreamParser::TimerFlush()
{
NS_ASSERTION(IsParserThread(), "Wrong thread!");
mozilla::MutexAutoLock autoLock(mTokenizerMutex);
NS_ASSERTION(!mSpeculating, "Flush timer fired while speculating.");
// The timer fired if we got here. No need to cancel it. Mark it as
// not armed, though.
mFlushTimerArmed = false;
mFlushTimerEverFired = true;
if (IsTerminatedOrInterrupted()) {
return;
}
if (mMode == VIEW_SOURCE_HTML || mMode == VIEW_SOURCE_XML) {
mTreeBuilder->Flush(); // delete useless ops
if (mTokenizer->FlushViewSource()) {
if (NS_FAILED(NS_DispatchToMainThread(mExecutorFlusher))) {
NS_WARNING("failed to dispatch executor flush event");
}
}
} else {
// we aren't speculating and we don't know when new data is
// going to arrive. Send data to the main thread.
if (mTreeBuilder->Flush(true)) {
if (NS_FAILED(NS_DispatchToMainThread(mExecutorFlusher))) {
NS_WARNING("failed to dispatch executor flush event");
}
}
}
}
void
nsHtml5StreamParser::MarkAsBroken()
{
NS_ASSERTION(IsParserThread(), "Wrong thread!");
mTokenizerMutex.AssertCurrentThreadOwns();
Terminate();
mTreeBuilder->MarkAsBroken();
mozilla::DebugOnly<bool> hadOps = mTreeBuilder->Flush(false);
NS_ASSERTION(hadOps, "Should have had the markAsBroken op!");
if (NS_FAILED(NS_DispatchToMainThread(mExecutorFlusher))) {
NS_WARNING("failed to dispatch executor flush event");
}
}
| 36.860395 | 135 | 0.655575 | [
"object"
] |
c868e61b616e295b45164d32ba3b82e886958bef | 9,447 | cc | C++ | tensorflow/lite/tools/optimize/quantize_model.cc | yxd886/tensorflow | 2eebcc63a6cd3aad483bf7c1cb25df2b8780ef67 | [
"Apache-2.0"
] | 1 | 2019-03-28T07:24:14.000Z | 2019-03-28T07:24:14.000Z | tensorflow/lite/tools/optimize/quantize_model.cc | yxd886/tensorflow | 2eebcc63a6cd3aad483bf7c1cb25df2b8780ef67 | [
"Apache-2.0"
] | null | null | null | tensorflow/lite/tools/optimize/quantize_model.cc | yxd886/tensorflow | 2eebcc63a6cd3aad483bf7c1cb25df2b8780ef67 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/tools/optimize/quantize_model.h"
#include <algorithm>
#include <cstdint>
#include <limits>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include "flatbuffers/flexbuffers.h"
#include "tensorflow/lite/context.h"
#include "tensorflow/lite/core/api/error_reporter.h"
#include "tensorflow/lite/model.h"
#include "tensorflow/lite/schema/schema_generated.h"
#include "tensorflow/lite/tools/optimize/model_utils.h"
#include "tensorflow/lite/tools/optimize/subgraph_quantizer.h"
namespace tflite {
namespace optimize {
namespace {
// True if the tensor type has to be modified.
bool TensorTypeChangeRequired(const TensorT* tensor, const TensorType& type) {
// The quantized model is type INT8, so if the user provided type is INT8, we
// do not have to do any custom logic. Additionally, if the current tensor
// isn't INT8 quantized, the custom type doesn't apply.
return (type != TensorType_INT8 && tensor->type == TensorType_INT8 &&
!tensor->quantization->scale.empty());
}
// Sets the input type, adding a Leading Op node at the start of the model if
// necessary.
// Returns the new input tensor index.
int32_t SetInputType(ModelT* model, SubGraphT* subgraph,
const int32_t tensor_idx, const TensorType& input_type) {
TensorT* tensor = subgraph->tensors[tensor_idx].get();
if (!TensorTypeChangeRequired(tensor, input_type)) {
return -1;
}
if (input_type == TensorType_FLOAT32 || input_type == TensorType_UINT8) {
// Create a new tensor to be the input of the leading Op.
std::unique_ptr<TensorT> leading_op_input;
if (input_type == TensorType_FLOAT32) {
// Add tensor for quantize operator. Scales and zero points are not
// needed.
const string leading_op_name = tensor->name + "_quantize";
utils::MakeTensor(leading_op_name, tensor->shape, input_type,
&leading_op_input);
} else {
// Get scale and zero point from the first tensor.
const float scale = subgraph->tensors[tensor_idx]->quantization->scale[0];
const int64_t zero_point =
subgraph->tensors[tensor_idx]->quantization->zero_point[0];
// Add tensor for requantize operator. Scale is the existing scale and
// zero point is shifted by +128.
TFLITE_DCHECK_GE(zero_point, -128);
TFLITE_DCHECK_LE(zero_point, 127);
const string leading_op_name = tensor->name + "_requantize";
utils::MakeTensorWithQuantParam(leading_op_name, tensor->shape,
input_type, scale, zero_point + 128,
&leading_op_input);
}
const int32_t leading_op_input_idx = subgraph->tensors.size();
subgraph->tensors.push_back(std::move(leading_op_input));
// Create the leading op, which is Quantize Op that quantize or requantize
// the input.
std::unique_ptr<OperatorT> leading_op;
utils::MakeQuantizeOperator(model, &leading_op, leading_op_input_idx,
tensor_idx);
// Insert the new op at the start of the model.
subgraph->operators.insert(subgraph->operators.begin(),
std::move(leading_op));
return leading_op_input_idx;
}
return -1;
}
// Sets the output type, adding a Tailing Op node at the end of the model if
// necessary.
// Returns the new output tensor index.
int32_t SetOutputType(ModelT* model, SubGraphT* subgraph,
const int32_t tensor_idx, const TensorType& output_type) {
TensorT* tensor = subgraph->tensors[tensor_idx].get();
if (!TensorTypeChangeRequired(tensor, output_type)) {
return -1;
}
if (output_type == TensorType_FLOAT32 || output_type == TensorType_UINT8) {
// Create a new tensor to be the output of the tailing op.
std::unique_ptr<TensorT> tailing_op_output;
if (output_type == TensorType_FLOAT32) {
const string tailing_op_name = tensor->name + "_dequantize";
utils::MakeTensor(tailing_op_name, tensor->shape, output_type,
&tailing_op_output);
} else {
// Get scale and zero point from the last tensor.
const float scale = subgraph->tensors[tensor_idx]->quantization->scale[0];
const int64_t zero_point =
subgraph->tensors[tensor_idx]->quantization->zero_point[0];
// Add tensor for requantize operator. Scale is the existing scale and
// zero point is shifted by +128.
TFLITE_DCHECK_GE(zero_point, -128);
TFLITE_DCHECK_LE(zero_point, 127);
const string tailing_op_name = tensor->name + "_requantize";
utils::MakeTensorWithQuantParam(tailing_op_name, tensor->shape,
output_type, scale, zero_point + 128,
&tailing_op_output);
}
const int32_t tailing_op_output_idx = subgraph->tensors.size();
subgraph->tensors.push_back(std::move(tailing_op_output));
// Create the tailing operation.
std::unique_ptr<OperatorT> tailing_op;
if (output_type == TensorType_FLOAT32) {
// Tailing Op is Dequantize Op.
utils::MakeDequantizeOperator(model, &tailing_op, tensor_idx,
tailing_op_output_idx);
} else {
// Tailing Op is Quantize Op that does requantization.
utils::MakeQuantizeOperator(model, &tailing_op, tensor_idx,
tailing_op_output_idx);
}
// Add the operator at the end of the model.
subgraph->operators.push_back(std::move(tailing_op));
return tailing_op_output_idx;
}
return -1;
}
// Sets the input and output types to the provided types. Leading and
// tailing operations will be added if needed.
// For Float input and output, leading op is Quantize and tailing op is
// Dequantize.
// For Uint8 input and output, leading op is Quantize (uint8 to
// int8, can be thought as "requant") and tailing op is also Quantize (int8 to
// uint8, can be thought as "requant").
void SetInputAndOutputTypes(ModelT* model, SubGraphT* subgraph,
const TensorType& input_type,
const TensorType& output_type) {
for (int i = 0; i < subgraph->inputs.size(); ++i) {
const int32_t input_idx =
SetInputType(model, subgraph, subgraph->inputs[i], input_type);
if (input_idx < 0) {
continue;
}
subgraph->inputs[i] = input_idx;
}
for (int i = 0; i < subgraph->outputs.size(); ++i) {
const int32_t output_idx =
SetOutputType(model, subgraph, subgraph->outputs[i], output_type);
if (output_idx < 0) {
continue;
}
subgraph->outputs[i] = output_idx;
}
}
} // namespace
TfLiteStatus QuantizeModel(flatbuffers::FlatBufferBuilder* builder,
ModelT* model, const TensorType& input_type,
const TensorType& output_type,
ErrorReporter* error_reporter) {
for (size_t subgraph_idx = 0; subgraph_idx < model->subgraphs.size();
subgraph_idx++) {
SubGraphT* subgraph = model->subgraphs.at(subgraph_idx).get();
internal::SubgraphQuantizer quantizer(model, subgraph, error_reporter);
for (size_t op_idx = 0; op_idx < subgraph->operators.size(); op_idx++) {
auto status = quantizer.QuantizeOperator(op_idx);
if (status != kTfLiteOk) {
OperatorT* op = subgraph->operators[op_idx].get();
const BuiltinOperator op_code =
model->operator_codes[op->opcode_index]->builtin_code;
error_reporter->Report(
"Failed to quantized operator: %s in subgraph %d, node: %d",
EnumNameBuiltinOperator(op_code), subgraph_idx, op_idx);
return kTfLiteError;
}
}
// For each subgraph, set the types of quantize inputs and outputs to the
// user defined ones.
if ((input_type != TensorType_FLOAT32 && input_type != TensorType_INT8 &&
input_type != TensorType_UINT8) ||
(output_type != TensorType_FLOAT32 && output_type != TensorType_INT8 &&
input_type != TensorType_UINT8)) {
error_reporter->Report("Provided input and output type not supported");
return kTfLiteError;
}
SetInputAndOutputTypes(model, subgraph, input_type, output_type);
}
flatbuffers::Offset<Model> output_model_location =
Model::Pack(*builder, model);
FinishModelBuffer(*builder, output_model_location);
return kTfLiteOk;
}
TfLiteStatus QuantizeModel(flatbuffers::FlatBufferBuilder* builder,
ModelT* model, ErrorReporter* error_reporter) {
return QuantizeModel(builder, model, TensorType_FLOAT32, TensorType_FLOAT32,
error_reporter);
}
} // namespace optimize
} // namespace tflite
| 41.800885 | 80 | 0.669101 | [
"shape",
"vector",
"model"
] |
c86aa1a2bb55be7b491a6c20e0e72f1104e03667 | 13,274 | cc | C++ | p2p/base/regathering_controller_unittest.cc | webrtc-uwp/webrtc2 | d1b53b61fb41a3aec58668f07e230f0b54560029 | [
"BSD-3-Clause"
] | 97 | 2016-11-10T08:22:35.000Z | 2021-12-19T05:42:40.000Z | p2p/base/regathering_controller_unittest.cc | webrtc-uwp/webrtc2 | d1b53b61fb41a3aec58668f07e230f0b54560029 | [
"BSD-3-Clause"
] | 9 | 2017-02-23T05:10:25.000Z | 2020-10-13T08:58:26.000Z | p2p/base/regathering_controller_unittest.cc | webrtc-uwp/webrtc2 | d1b53b61fb41a3aec58668f07e230f0b54560029 | [
"BSD-3-Clause"
] | 72 | 2016-10-14T03:35:04.000Z | 2022-03-10T01:08:15.000Z | /*
* Copyright 2018 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "api/scoped_refptr.h"
#include "p2p/base/fake_port_allocator.h"
#include "p2p/base/mock_ice_transport.h"
#include "p2p/base/p2p_constants.h"
#include "p2p/base/port.h"
#include "p2p/base/regathering_controller.h"
#include "p2p/base/stun_server.h"
#include "rtc_base/gunit.h"
#include "rtc_base/ref_counted_object.h"
#include "rtc_base/socket_address.h"
#include "rtc_base/thread.h"
#include "rtc_base/virtual_socket_server.h"
namespace {
const int kOnlyLocalPorts = cricket::PORTALLOCATOR_DISABLE_STUN |
cricket::PORTALLOCATOR_DISABLE_RELAY |
cricket::PORTALLOCATOR_DISABLE_TCP;
// The address of the public STUN server.
const rtc::SocketAddress kStunAddr("99.99.99.1", cricket::STUN_SERVER_PORT);
// The addresses for the public TURN server.
const rtc::SocketAddress kTurnUdpIntAddr("99.99.99.3",
cricket::STUN_SERVER_PORT);
const cricket::RelayCredentials kRelayCredentials("test", "test");
const char kIceUfrag[] = "UF00";
const char kIcePwd[] = "TESTICEPWD00000000000000";
} // namespace
namespace webrtc {
class RegatheringControllerTest : public ::testing::Test,
public sigslot::has_slots<> {
public:
RegatheringControllerTest()
: vss_(new rtc::VirtualSocketServer()),
thread_(vss_.get()),
ice_transport_(new cricket::MockIceTransport()),
allocator_(
new cricket::FakePortAllocator(rtc::Thread::Current(), nullptr)) {
BasicRegatheringController::Config regathering_config(absl::nullopt, 0);
regathering_controller_.reset(new BasicRegatheringController(
regathering_config, ice_transport_.get(), rtc::Thread::Current()));
}
// Initializes the allocator and gathers candidates once by StartGettingPorts.
void InitializeAndGatherOnce() {
cricket::ServerAddresses stun_servers;
stun_servers.insert(kStunAddr);
cricket::RelayServerConfig turn_server(cricket::RELAY_TURN);
turn_server.credentials = kRelayCredentials;
turn_server.ports.push_back(
cricket::ProtocolAddress(kTurnUdpIntAddr, cricket::PROTO_UDP));
std::vector<cricket::RelayServerConfig> turn_servers(1, turn_server);
allocator_->set_flags(kOnlyLocalPorts);
allocator_->SetConfiguration(stun_servers, turn_servers, 0 /* pool size */,
false /* prune turn ports */);
allocator_session_ = allocator_->CreateSession(
"test", cricket::ICE_CANDIDATE_COMPONENT_RTP, kIceUfrag, kIcePwd);
// The gathering will take place on the current thread and the following
// call of StartGettingPorts is blocking. We will not ClearGettingPorts
// prematurely.
allocator_session_->StartGettingPorts();
allocator_session_->SignalIceRegathering.connect(
this, &RegatheringControllerTest::OnIceRegathering);
regathering_controller_->set_allocator_session(allocator_session_.get());
}
// The regathering controller is initialized with the allocator session
// cleared. Only after clearing the session, we would be able to regather. See
// the comments for BasicRegatheringController in regatheringcontroller.h.
void InitializeAndGatherOnceWithSessionCleared() {
InitializeAndGatherOnce();
allocator_session_->ClearGettingPorts();
}
void OnIceRegathering(cricket::PortAllocatorSession* allocator_session,
cricket::IceRegatheringReason reason) {
++count_[reason];
}
int GetRegatheringReasonCount(cricket::IceRegatheringReason reason) {
return count_[reason];
}
BasicRegatheringController* regathering_controller() {
return regathering_controller_.get();
}
private:
std::unique_ptr<rtc::VirtualSocketServer> vss_;
rtc::AutoSocketServerThread thread_;
std::unique_ptr<cricket::IceTransportInternal> ice_transport_;
std::unique_ptr<BasicRegatheringController> regathering_controller_;
std::unique_ptr<cricket::PortAllocator> allocator_;
std::unique_ptr<cricket::PortAllocatorSession> allocator_session_;
std::map<cricket::IceRegatheringReason, int> count_;
};
// Tests that ICE regathering occurs only if the port allocator session is
// cleared. A port allocation session is not cleared if the initial gathering is
// still in progress or the continual gathering is not enabled.
TEST_F(RegatheringControllerTest,
IceRegatheringDoesNotOccurIfSessionNotCleared) {
rtc::ScopedFakeClock clock;
InitializeAndGatherOnce(); // Session not cleared.
rtc::IntervalRange regather_all_networks_interval_range(2000, 2000);
BasicRegatheringController::Config config(
regather_all_networks_interval_range, 2000);
regathering_controller()->SetConfig(config);
regathering_controller()->Start();
SIMULATED_WAIT(false, 10000, clock);
// Expect no regathering in the last 10s.
EXPECT_EQ(0, GetRegatheringReasonCount(
cricket::IceRegatheringReason::OCCASIONAL_REFRESH));
EXPECT_EQ(0, GetRegatheringReasonCount(
cricket::IceRegatheringReason::NETWORK_FAILURE));
}
TEST_F(RegatheringControllerTest, IceRegatheringRepeatsAsScheduled) {
rtc::ScopedFakeClock clock;
InitializeAndGatherOnceWithSessionCleared();
rtc::IntervalRange regather_all_networks_interval_range(2000, 2000);
BasicRegatheringController::Config config(
regather_all_networks_interval_range, 2000);
regathering_controller()->SetConfig(config);
regathering_controller()->Start();
SIMULATED_WAIT(false, 2000 - 1, clock);
// Expect no regathering.
EXPECT_EQ(0, GetRegatheringReasonCount(
cricket::IceRegatheringReason::OCCASIONAL_REFRESH));
EXPECT_EQ(0, GetRegatheringReasonCount(
cricket::IceRegatheringReason::NETWORK_FAILURE));
SIMULATED_WAIT(false, 2, clock);
// Expect regathering on all networks and on failed networks to happen once
// respectively in that last 2s with 2s interval.
EXPECT_EQ(1, GetRegatheringReasonCount(
cricket::IceRegatheringReason::OCCASIONAL_REFRESH));
EXPECT_EQ(1, GetRegatheringReasonCount(
cricket::IceRegatheringReason::NETWORK_FAILURE));
SIMULATED_WAIT(false, 11000, clock);
// Expect regathering to happen for another 5 times in 11s with 2s interval.
EXPECT_EQ(6, GetRegatheringReasonCount(
cricket::IceRegatheringReason::OCCASIONAL_REFRESH));
EXPECT_EQ(6, GetRegatheringReasonCount(
cricket::IceRegatheringReason::NETWORK_FAILURE));
}
// Tests that the schedule of ICE regathering on all networks can be started
// when not scheduled initially.
TEST_F(RegatheringControllerTest,
IceRegatheringOnAllNetworksCanBeScheduledAfterStart) {
rtc::ScopedFakeClock clock;
InitializeAndGatherOnceWithSessionCleared();
BasicRegatheringController::Config config(absl::nullopt, 2000);
regathering_controller()->SetConfig(config);
regathering_controller()->Start();
SIMULATED_WAIT(false, 3000, clock);
// Expect no regathering on all networks.
EXPECT_EQ(0, GetRegatheringReasonCount(
cricket::IceRegatheringReason::OCCASIONAL_REFRESH));
config.regather_on_all_networks_interval_range =
rtc::IntervalRange(2000, 2000);
regathering_controller()->SetConfig(config);
SIMULATED_WAIT(false, 11000, clock);
// Expect regathering to happen for 5 times on all networks in the last 11s
// with 2s interval.
EXPECT_EQ(5, GetRegatheringReasonCount(
cricket::IceRegatheringReason::OCCASIONAL_REFRESH));
}
// Tests that ICE regathering on all networks can be canceled by changing the
// config.
TEST_F(RegatheringControllerTest, IceRegatheringOnAllNetworksCanBeCanceled) {
rtc::ScopedFakeClock clock;
InitializeAndGatherOnceWithSessionCleared();
rtc::IntervalRange regather_all_networks_interval_range(2000, 2000);
BasicRegatheringController::Config config(
regather_all_networks_interval_range, 2000);
regathering_controller()->SetConfig(config);
regathering_controller()->Start();
config.regather_on_all_networks_interval_range.reset();
// Set the regathering interval range on all networks to nullopt should cancel
// the schedule on all networks.
regathering_controller()->SetConfig(config);
SIMULATED_WAIT(false, 10000, clock);
// Expect no regathering on all networks happened in the last 10s.
EXPECT_EQ(0, GetRegatheringReasonCount(
cricket::IceRegatheringReason::OCCASIONAL_REFRESH));
}
// Tests that canceling the regathering on all networks does not cancel the
// schedule on failed networks.
TEST_F(RegatheringControllerTest,
CancelingRegatheringOnAllNetworksDoesNotCancelOnFailedNetworks) {
rtc::ScopedFakeClock clock;
InitializeAndGatherOnceWithSessionCleared();
rtc::IntervalRange regather_all_networks_interval_range(2000, 2000);
BasicRegatheringController::Config config(
regather_all_networks_interval_range, 2000);
regathering_controller()->SetConfig(config);
regathering_controller()->Start();
config.regather_on_all_networks_interval_range =
rtc::IntervalRange(20000, 20000);
// Canceling and rescheduling the regathering on all networks should not
// impact the schedule for failed networks.
regathering_controller()->SetConfig(config);
SIMULATED_WAIT(false, 11000, clock);
// Expect regathering to happen for 5 times for failed networks in the last
// 11s with 2s interval.
EXPECT_EQ(5, GetRegatheringReasonCount(
cricket::IceRegatheringReason::NETWORK_FAILURE));
}
// Tests that canceling the regathering on failed networks does not cancel the
// schedule on all networks.
TEST_F(RegatheringControllerTest,
CancelingRegatheringOnFailedNetworksDoesNotCancelOnAllNetworks) {
rtc::ScopedFakeClock clock;
InitializeAndGatherOnceWithSessionCleared();
rtc::IntervalRange regather_all_networks_interval_range(2000, 2000);
BasicRegatheringController::Config config(
regather_all_networks_interval_range, 2000);
regathering_controller()->SetConfig(config);
regathering_controller()->Start();
config.regather_on_failed_networks_interval = 20000;
// Canceling and rescheduling the regathering on failed networks should not
// impact the schedule for all networks.
regathering_controller()->SetConfig(config);
SIMULATED_WAIT(false, 11000, clock);
// Expect regathering to happen for 5 times for all networks in the last 11s
// with 2s interval.
EXPECT_EQ(5, GetRegatheringReasonCount(
cricket::IceRegatheringReason::OCCASIONAL_REFRESH));
}
// Tests that the schedule of ICE regathering on all networks can be canceled
// and replaced by a new recurring schedule.
TEST_F(RegatheringControllerTest,
ScheduleOfIceRegatheringOnAllNetworksCanBeReplaced) {
rtc::ScopedFakeClock clock;
InitializeAndGatherOnceWithSessionCleared();
rtc::IntervalRange regather_all_networks_interval_range(2000, 2000);
BasicRegatheringController::Config config(
regather_all_networks_interval_range, 2000);
regathering_controller()->SetConfig(config);
regathering_controller()->Start();
config.regather_on_all_networks_interval_range =
rtc::IntervalRange(5000, 5000);
regathering_controller()->SetConfig(config);
SIMULATED_WAIT(false, 3000, clock);
// Expect no regathering from the previous schedule.
EXPECT_EQ(0, GetRegatheringReasonCount(
cricket::IceRegatheringReason::OCCASIONAL_REFRESH));
SIMULATED_WAIT(false, 11000 - 3000, clock);
// Expect regathering to happen twice in the last 11s with 5s interval.
EXPECT_EQ(2, GetRegatheringReasonCount(
cricket::IceRegatheringReason::OCCASIONAL_REFRESH));
}
// Tests that the schedule of ICE regathering on failed networks can be canceled
// and replaced by a new recurring schedule.
TEST_F(RegatheringControllerTest,
ScheduleOfIceRegatheringOnFailedNetworksCanBeReplaced) {
rtc::ScopedFakeClock clock;
InitializeAndGatherOnceWithSessionCleared();
rtc::IntervalRange regather_all_networks_interval_range(2000, 2000);
BasicRegatheringController::Config config(
regather_all_networks_interval_range, 2000);
regathering_controller()->SetConfig(config);
regathering_controller()->Start();
config.regather_on_failed_networks_interval = 5000;
regathering_controller()->SetConfig(config);
SIMULATED_WAIT(false, 3000, clock);
// Expect no regathering from the previous schedule.
EXPECT_EQ(0, GetRegatheringReasonCount(
cricket::IceRegatheringReason::NETWORK_FAILURE));
SIMULATED_WAIT(false, 11000 - 3000, clock);
// Expect regathering to happen twice in the last 11s with 5s interval.
EXPECT_EQ(2, GetRegatheringReasonCount(
cricket::IceRegatheringReason::NETWORK_FAILURE));
}
} // namespace webrtc
| 43.097403 | 80 | 0.756366 | [
"vector"
] |
c86e3641d7ba3658ccae6b0d82ac4e885b7f7dd7 | 2,514 | hpp | C++ | sstd_tcp/server.hpp | admiswalker/forBlog_sstd_tcp_Ver00.11_00 | a85a86f827b281291d35c014e15f5a09f47be931 | [
"MIT"
] | null | null | null | sstd_tcp/server.hpp | admiswalker/forBlog_sstd_tcp_Ver00.11_00 | a85a86f827b281291d35c014e15f5a09f47be931 | [
"MIT"
] | null | null | null | sstd_tcp/server.hpp | admiswalker/forBlog_sstd_tcp_Ver00.11_00 | a85a86f827b281291d35c014e15f5a09f47be931 | [
"MIT"
] | null | null | null | #pragma once
#include <sstd/sstd.hpp>
#include <netinet/in.h> // for sockaddr_in
#include <sys/epoll.h> // for epoll
//-----------------------------------------------------------------------------------------------------------------------------------------------
struct fdState{
private:
public:
fdState();
~fdState();
std::string writeMsg;
};
//-----------------------------------------------------------------------------------------------------------------------------------------------
namespace sstd{ class tcpSrv_nonblocking; }
class sstd::tcpSrv_nonblocking{
private:
// settings
int numOfListenLimits;
uint maxEvents;
// for init
struct sockaddr_in sIn;
// for all
int sock; // listening socket
int cFd; // current feed
int eNum; // event number
uint sNum; // state number
struct fdState* pState; // status set
// for epoll
int epFd; // epoll feed
int nFd; // number of feeds
int fd_offset; // offset of feed number
struct epoll_event* pEvents; // events set
struct epoll_event cEv; // current epoll event
// for event loop
bool isProc;
bool new_fd();
bool del_fd(int delFd);
bool workerRecv(std::vector<uchar>& retOut, const uint& limitSize);
bool printInfo_fd(const struct sockaddr_storage& ss, socklen_t& ssLen);
bool isEvent();
bool ctlState_setR (const int& setFd); // control state: set read
bool ctlState_setW (const int& setFd); // control state: set write
bool ctlState_setRW(const int& setFd); // control state: set read and write
bool ctlState_rmR (const int& rmFd); // control state: remove read
bool ctlState_rmW (const int& rmFd); // control state: remove write
bool ctlState_rmRW (const int& rmFd); // control state: remove read and write
bool ctlState_addR (const int& addFd); // control state: add read
bool ctlState_addW (const int& addFd); // control state: add write
bool ctlState_addRW(const int& addFd); // control state: add read and write
public:
tcpSrv_nonblocking(const uint maxEvents_in);
~tcpSrv_nonblocking();
bool open(const uint portNum);
bool wait();
bool isRedy4recv();
bool isRedy4send();
bool recv(std::vector<uchar>& retOut, const uint& limitSize);
bool setSend(std::string& msg);
bool setSend(const char*& pMsg);
bool send();
};
//-----------------------------------------------------------------------------------------------------------------------------------------------
| 30.658537 | 145 | 0.558075 | [
"vector"
] |
c872393aea8ad2527221eff87bcab779d5b352c2 | 33,494 | cpp | C++ | astronomy/orbit_analysis_test.cpp | erplsf/Principia | 1f2a1fc53f8a73c1bc67f12213169e6969c8488f | [
"MIT"
] | null | null | null | astronomy/orbit_analysis_test.cpp | erplsf/Principia | 1f2a1fc53f8a73c1bc67f12213169e6969c8488f | [
"MIT"
] | null | null | null | astronomy/orbit_analysis_test.cpp | erplsf/Principia | 1f2a1fc53f8a73c1bc67f12213169e6969c8488f | [
"MIT"
] | null | null | null |
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "astronomy/orbit_ground_track.hpp"
#include "astronomy/orbit_recurrence.hpp"
#include "astronomy/orbital_elements.hpp"
#include "astronomy/standard_product_3.hpp"
#include "base/not_null.hpp"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "mathematica/mathematica.hpp"
#include "numerics/polynomial.hpp"
#include "physics/body_centred_non_rotating_dynamic_frame.hpp"
#include "physics/ephemeris.hpp"
#include "physics/solar_system.hpp"
#include "testing_utilities/approximate_quantity.hpp"
#include "testing_utilities/is_near.hpp"
#include "testing_utilities/matchers.hpp"
#include "testing_utilities/numerics_matchers.hpp"
namespace principia {
namespace astronomy {
using base::make_not_null_unique;
using base::not_null;
using geometry::Instant;
using geometry::Interval;
using geometry::Position;
using integrators::SymmetricLinearMultistepIntegrator;
using integrators::methods::QuinlanTremaine1990Order12;
using numerics::EstrinEvaluator;
using numerics::PolynomialInMonomialBasis;
using physics::BodyCentredNonRotatingDynamicFrame;
using physics::BodySurfaceDynamicFrame;
using physics::DiscreteTrajectory;
using physics::Ephemeris;
using physics::MasslessBody;
using physics::RotatingBody;
using physics::SolarSystem;
using quantities::Angle;
using quantities::Mod;
using quantities::Pow;
using quantities::Time;
using quantities::astronomy::JulianYear;
using quantities::astronomy::TerrestrialEquatorialRadius;
using quantities::si::ArcMinute;
using quantities::si::ArcSecond;
using quantities::si::Day;
using quantities::si::Degree;
using quantities::si::Hour;
using quantities::si::Kilo;
using quantities::si::Metre;
using quantities::si::Micro;
using quantities::si::Milli;
using quantities::si::Minute;
using quantities::si::Radian;
using quantities::si::Second;
using testing_utilities::AbsoluteErrorFrom;
using testing_utilities::DifferenceFrom;
using testing_utilities::IsNear;
using testing_utilities::IsOk;
using testing_utilities::RelativeErrorFrom;
using testing_utilities::operator""_⑴;
using ::testing::AllOf;
using ::testing::Field;
using ::testing::Lt;
using ::testing::Property;
namespace {
struct SP3Files {
std::vector<std::string> names;
StandardProduct3::Dialect dialect;
static SP3Files const& GNSS();
static SP3Files const& SPOT5();
static SP3Files const& Sentinel3A();
static SP3Files const& TOPEXPoséidon();
};
struct SP3Orbit {
StandardProduct3::SatelliteIdentifier satellite;
SP3Files files;
};
SP3Files const& SP3Files::GNSS() {
static const SP3Files files = {{"WUM0MGXFIN_20190970000_01D_15M_ORB.SP3",
"WUM0MGXFIN_20190980000_01D_15M_ORB.SP3",
"WUM0MGXFIN_20190990000_01D_15M_ORB.SP3",
"WUM0MGXFIN_20191000000_01D_15M_ORB.SP3",
"WUM0MGXFIN_20191010000_01D_15M_ORB.SP3",
"WUM0MGXFIN_20191020000_01D_15M_ORB.SP3",
"WUM0MGXFIN_20191030000_01D_15M_ORB.SP3",
"WUM0MGXFIN_20191040000_01D_15M_ORB.SP3",
"WUM0MGXFIN_20191050000_01D_15M_ORB.SP3",
"WUM0MGXFIN_20191060000_01D_15M_ORB.SP3"},
StandardProduct3::Dialect::ChineseMGEX};
return files;
}
SP3Files const& SP3Files::SPOT5() {
static const SP3Files files = {{"ssasp501.b10170.e10181.D__.sp3"},
StandardProduct3::Dialect::Standard};
return files;
}
SP3Files const& SP3Files::Sentinel3A() {
static const SP3Files files = {{"ssas3a20.b18358.e19003.DG_.sp3"},
StandardProduct3::Dialect::Standard};
return files;
}
SP3Files const& SP3Files::TOPEXPoséidon() {
static const SP3Files files = {{"grgtop03.b97344.e97348.D_S.sp3"},
StandardProduct3::Dialect::GRGS};
return files;
}
} // namespace
class OrbitAnalysisTest : public ::testing::Test {
protected:
OrbitAnalysisTest()
: earth_1957_(RemoveAllButEarth(SolarSystem<ICRS>(
SOLUTION_DIR / "astronomy" / "sol_gravity_model.proto.txt",
SOLUTION_DIR / "astronomy" /
"sol_initial_state_jd_2436116_311504629.proto.txt"))),
// As there is only one body left in this ephemeris, integration is
// exact up to roundoff error regardless of the step size. Use a long
// step so that we do not waste time computing the ephemeris (it starts
// in 1957, and we need it until 2019).
ephemeris_(earth_1957_.MakeEphemeris(
/*accuracy_parameters=*/{/*fitting_tolerance=*/1 * Milli(Metre),
/*geopotential_tolerance=*/0x1p-24},
Ephemeris<ICRS>::FixedStepParameters(
SymmetricLinearMultistepIntegrator<QuinlanTremaine1990Order12,
Position<ICRS>>(),
/*step=*/1 * JulianYear))),
earth_(*earth_1957_.rotating_body(*ephemeris_, "Earth")) {}
// Returns a GCRS trajectory obtained by stitching together the trajectories
// of |sp3_orbit.satellites| in |sp3_orbit.files|.
not_null<std::unique_ptr<DiscreteTrajectory<GCRS>>> EarthCentredTrajectory(
SP3Orbit const& sp3_orbit) {
BodyCentredNonRotatingDynamicFrame<ICRS, GCRS> gcrs{ephemeris_.get(),
&earth_};
BodySurfaceDynamicFrame<ICRS, ITRS> itrs{ephemeris_.get(), &earth_};
auto result = make_not_null_unique<DiscreteTrajectory<GCRS>>();
for (auto const& file : sp3_orbit.files.names) {
StandardProduct3 sp3(
SOLUTION_DIR / "astronomy" / "standard_product_3" / file,
sp3_orbit.files.dialect);
std::vector<not_null<DiscreteTrajectory<ITRS> const*>> const& orbit =
sp3.orbit(sp3_orbit.satellite);
CHECK_EQ(orbit.size(), 1);
auto const& arc = *orbit.front();
for (auto const& [time, degrees_of_freedom] : arc) {
ephemeris_->Prolong(time);
result->Append(
time,
gcrs.ToThisFrameAtTime(time)(
itrs.FromThisFrameAtTime(time)(degrees_of_freedom)));
}
}
return result;
}
std::tuple<OrbitalElements, OrbitRecurrence, OrbitGroundTrack>
ElementsAndRecurrence(SP3Orbit const& orbit) {
auto const earth_centred_trajectory = EarthCentredTrajectory(orbit);
auto elements = OrbitalElements::ForTrajectory(
*earth_centred_trajectory,
earth_,
MasslessBody{}).ValueOrDie();
{
auto const identifier = (std::stringstream() << orbit.satellite).str();
mathematica::Logger logger(SOLUTION_DIR / "mathematica" /
(identifier + "_elements.generated.wl"),
/*make_unique=*/false);
logger.Set(identifier + "osculatingEquinoctialElements",
elements.osculating_equinoctial_elements(),
mathematica::ExpressIn(Metre, Second, Radian));
logger.Set(identifier + "meanEquinoctialElements",
elements.mean_equinoctial_elements(),
mathematica::ExpressIn(Metre, Second, Radian));
}
auto const recurrence =
OrbitRecurrence::ClosestRecurrence(elements.nodal_period(),
elements.nodal_precession(),
earth_,
/*max_abs_Cᴛₒ=*/100);
// Since our ITRS-to-ICRS conversion disregards the precession of the
// equinoxes, it is not completely clear which year we should be dealing
// with here. Given that the SP3 files have data in the ITRS (whose equator
// is the equator of date), and that we map that to the ICRS equator, our
// IRCS here is more like an equator-of-date frame (although it is not clear
// whether its x axis resembles the equinox of the date), so we pick
// the tropical year.
// We use values based on Newcomb's formula for the mean longitude of the
// sun, L = 279°41′48″.04 + 129 602 768″.13 T + 1.089″ T², where T is in
// Julian centuries since 1900, January 0, Greenwich Mean noon. Ephemeris
// time (ET) was defined by the IAU (10th general assembly (1958),
// commissions 4 and 31, recommendation 2) from Newcomb's tables, with 1900,
// January 0 at 12 ET being the instant at which the mean longitude of the
// sun was 279°41′48″.08, and the ET second being 1/31 556 925.9747 of the
// tropical year at that epoch—where 31 556 925.9747 s =
// 2π rad / (129 602 768″.13 / 100 a). TDT, and later TT, were then defined
// in such a way as to achieve approximate continuity with ET, see 16th
// general assembly (1976), commission 4, recommendation 5, note 2, and 21st
// general assembly (1991), resolution A4, recommendation IV, note 4. We
// can therefore work with this formula in TT.
PolynomialInMonomialBasis<Angle, Instant, 2, EstrinEvaluator> const
newcomb_mean_longitude(
{279 * Degree + 41 * ArcMinute + 48.04 * ArcSecond,
129'602'768.13 * ArcSecond / (100 * JulianYear),
1.089 * ArcSecond / Pow<2>(100 * JulianYear)},
"1899-12-31T12:00:00"_TT);
auto ground_track = OrbitGroundTrack::ForTrajectory(
*earth_centred_trajectory,
earth_,
{{/*epoch=*/J2000,
/*mean_longitude_at_epoch=*/newcomb_mean_longitude(J2000),
/*year*/ 2 * π * Radian /
newcomb_mean_longitude.EvaluateDerivative(J2000)}}).ValueOrDie();
return {std::move(elements), recurrence, std::move(ground_track)};
}
SolarSystem<ICRS> earth_1957_;
not_null<std::unique_ptr<Ephemeris<ICRS>>> ephemeris_;
RotatingBody<ICRS> const& earth_;
private:
SolarSystem<ICRS> RemoveAllButEarth(SolarSystem<ICRS> solar_system) {
std::vector<std::string> const names = solar_system.names();
for (auto const& name : names) {
if (name != "Earth") {
solar_system.RemoveMassiveBody(name);
}
}
return solar_system;
}
};
#if !defined(_DEBUG)
// COSPAR ID 2010-001A, SVN C003.
// 北斗二號 GEO01.
// PRN C01, GEO, 140.0° E.
TEST_F(OrbitAnalysisTest, 北斗GEO) {
auto const [elements, recurrence, ground_track] = ElementsAndRecurrence(
{{StandardProduct3::SatelliteGroup::北斗, 1}, SP3Files::GNSS()});
EXPECT_THAT(recurrence,
AllOf(Property(&OrbitRecurrence::νₒ, 1),
Property(&OrbitRecurrence::Dᴛₒ, 0),
Property(&OrbitRecurrence::Cᴛₒ, 1)));
EXPECT_THAT(elements.mean_semimajor_axis_interval().midpoint(),
IsNear(42'166_⑴ * Kilo(Metre)));
EXPECT_THAT(elements.mean_inclination_interval().midpoint(),
IsNear(1.42_⑴ * Degree));
EXPECT_THAT(elements.mean_eccentricity_interval().midpoint(),
IsNear(0.000186_⑴));
EXPECT_THAT(elements.mean_argument_of_periapsis_interval().midpoint(),
IsNear(166_⑴ * Degree));
}
// COSPAR ID 2010-036A, SVN C005.
// 北斗二號 IGSO01.
// PRN C06, IGSO, 117°E.
TEST_F(OrbitAnalysisTest, 北斗IGSO) {
auto const [elements, recurrence, ground_track] = ElementsAndRecurrence(
{{StandardProduct3::SatelliteGroup::北斗, 6}, SP3Files::GNSS()});
EXPECT_THAT(recurrence,
AllOf(Property(&OrbitRecurrence::νₒ, 1),
Property(&OrbitRecurrence::Dᴛₒ, 0),
Property(&OrbitRecurrence::Cᴛₒ, 1)));
EXPECT_THAT(elements.mean_semimajor_axis_interval().midpoint(),
IsNear(42'161_⑴ * Kilo(Metre)));
EXPECT_THAT(elements.mean_inclination_interval().midpoint(),
IsNear(54.19_⑴ * Degree));
EXPECT_THAT(elements.mean_eccentricity_interval().midpoint(),
IsNear(0.0078_⑴));
EXPECT_THAT(elements.mean_argument_of_periapsis_interval().midpoint(),
IsNear(232_⑴ * Degree));
}
// COSPAR ID 2010-045A, SVN J001.
// Block I-Q, みちびき初号機.
// PRN J01, quasi-zenith orbit.
TEST_F(OrbitAnalysisTest, みちびきQZO) {
auto const [elements, recurrence, ground_track] = ElementsAndRecurrence(
{{StandardProduct3::SatelliteGroup::みちびき, 1}, SP3Files::GNSS()});
EXPECT_THAT(recurrence,
AllOf(Property(&OrbitRecurrence::νₒ, 1),
Property(&OrbitRecurrence::Dᴛₒ, 0),
Property(&OrbitRecurrence::Cᴛₒ, 1)));
// Expected orbital elements from the Quasi-Zenith Satellite System
// Performance Standard (PS-QZSS-001).
EXPECT_THAT(
elements.mean_semimajor_axis_interval().midpoint(),
AbsoluteErrorFrom(42'165 * Kilo(Metre), IsNear(6.3_⑴ * Kilo(Metre))));
EXPECT_THAT(elements.mean_inclination_interval().midpoint(),
IsNear(41_⑴ * Degree));
EXPECT_THAT(elements.mean_eccentricity_interval().midpoint(),
IsNear(0.075_⑴));
// The operational range is 270° ± 2.5°.
EXPECT_THAT(elements.mean_argument_of_periapsis_interval().midpoint(),
IsNear(270_⑴ * Degree));
EXPECT_THAT(elements.mean_argument_of_periapsis_interval().measure(),
IsNear(0.12_⑴ * Degree));
}
// COSPAR ID 2017-048A, SVN J003.
// Block II-G, みちびき3号機.
// PRN J07, GEO.
TEST_F(OrbitAnalysisTest, みちびきGEO) {
auto j07_files = SP3Files::GNSS();
// J07 is missing from the last two files.
j07_files.names.resize(j07_files.names.size() - 2);
auto const [elements, recurrence, ground_track] = ElementsAndRecurrence(
{{StandardProduct3::SatelliteGroup::みちびき, 7}, j07_files});
EXPECT_THAT(recurrence,
AllOf(Property(&OrbitRecurrence::νₒ, 1),
Property(&OrbitRecurrence::Dᴛₒ, 0),
Property(&OrbitRecurrence::Cᴛₒ, 1)));
EXPECT_THAT(elements.mean_semimajor_axis_interval().midpoint(),
IsNear(42'166_⑴ * Kilo(Metre)));
EXPECT_THAT(elements.mean_inclination_interval().midpoint(),
IsNear(0.067_⑴ * Degree));
EXPECT_THAT(elements.mean_eccentricity_interval().midpoint(),
IsNear(0.00023_⑴));
EXPECT_THAT(elements.mean_argument_of_periapsis_interval().midpoint(),
IsNear(224_⑴ * Degree));
}
// COSPAR ID 2018-078B, SVN C216.
// 北斗三號 MEO15 (Shanghai Engineering Center for Microsatellites).
// PRN C34, slot A-7.
TEST_F(OrbitAnalysisTest, 北斗MEO) {
auto const [elements, recurrence, ground_track] = ElementsAndRecurrence(
{{StandardProduct3::SatelliteGroup::北斗, 34}, SP3Files::GNSS()});
EXPECT_THAT(recurrence,
AllOf(Property(&OrbitRecurrence::νₒ, 2),
Property(&OrbitRecurrence::Dᴛₒ, -1),
Property(&OrbitRecurrence::Cᴛₒ, 7)));
EXPECT_THAT(elements.mean_semimajor_axis_interval().midpoint(),
IsNear(27'906_⑴ * Kilo(Metre)));
EXPECT_THAT(elements.mean_inclination_interval().midpoint(),
IsNear(55.10_⑴ * Degree));
EXPECT_THAT(elements.mean_eccentricity_interval().midpoint(),
IsNear(0.000558_⑴));
EXPECT_THAT(elements.mean_argument_of_periapsis_interval().midpoint(),
IsNear(1.003_⑴ * Degree));
}
// COSPAR ID 2016-030A.
// Galileo-Full Operational Capability Flight Model 10 (GSAT0210) “Danielė”.
// PRN E01, slot A02.
TEST_F(OrbitAnalysisTest, GalileoNominalSlot) {
auto const [elements, recurrence, ground_track] = ElementsAndRecurrence(
{{StandardProduct3::SatelliteGroup::Galileo, 1}, SP3Files::GNSS()});
EXPECT_THAT(recurrence,
AllOf(Property(&OrbitRecurrence::νₒ, 2),
Property(&OrbitRecurrence::Dᴛₒ, -3),
Property(&OrbitRecurrence::Cᴛₒ, 10)));
// Reference elements from
// https://www.gsc-europa.eu/system-status/orbital-and-technical-parameters.
Instant const reference_epoch = "2016-11-21T00:00:00"_UTC;
Instant const initial_time = elements.mean_elements().front().time;
Instant const mean_time =
initial_time + (elements.mean_elements().back().time - initial_time) / 2;
auto const nominal_nodal_precession = -0.02764398 * Degree / Day;
auto const nominal_anomalistic_mean_motion = 613.72253566 * Degree / Day;
EXPECT_THAT(
elements.nodal_precession(),
AllOf(AbsoluteErrorFrom(nominal_nodal_precession,
IsNear(0.00032_⑴ * Degree / Day)),
RelativeErrorFrom(nominal_nodal_precession, IsNear(0.011_⑴))));
EXPECT_THAT(2 * π * Radian / elements.anomalistic_period(),
AllOf(AbsoluteErrorFrom(nominal_anomalistic_mean_motion,
IsNear(0.53_⑴ * Degree / Day)),
RelativeErrorFrom(nominal_anomalistic_mean_motion,
IsNear(0.00086_⑴))));
EXPECT_THAT(
elements.mean_semimajor_axis_interval().midpoint(),
AbsoluteErrorFrom(29'599.8 * Kilo(Metre), IsNear(0.35_⑴ * Kilo(Metre))));
EXPECT_THAT(elements.mean_semimajor_axis_interval().measure(),
IsNear(00'000.084_⑴ * Kilo(Metre)));
EXPECT_THAT(elements.mean_eccentricity_interval().midpoint(),
IsNear(0.000'17_⑴)); // Nominal: 0.0.
EXPECT_THAT(elements.mean_eccentricity_interval().measure(),
IsNear(0.000'015_⑴));
EXPECT_THAT(elements.mean_inclination_interval().midpoint(),
AbsoluteErrorFrom(56.0 * Degree, IsNear(0.61_⑴ * Degree)));
EXPECT_THAT(elements.mean_inclination_interval().measure(),
IsNear(00.01_⑴ * Degree));
EXPECT_THAT(
Mod(elements.mean_longitude_of_ascending_node_interval().midpoint() -
nominal_nodal_precession * (mean_time - reference_epoch),
2 * π * Radian),
AbsoluteErrorFrom(317.632 * Degree, IsNear(0.082_⑴ * Degree)));
// Note that the reference parameters have e = 0, and therefore conventionally
// set ω = 0, ω′ = 0.
// However, e is never quite 0; we can compute a mean ω.
EXPECT_THAT(elements.mean_argument_of_periapsis_interval().midpoint(),
IsNear(88_⑴ * Degree));
EXPECT_THAT(elements.mean_argument_of_periapsis_interval().measure(),
IsNear(6.3_⑴ * Degree));
// Since the reference parameters conventionally set ω = 0, the given mean
// anomaly is actually the mean argument of latitude; in order to get numbers
// consistent with theirs, we must look at ω + M.
EXPECT_THAT(Mod(elements.mean_elements().front().argument_of_periapsis +
elements.mean_elements().front().mean_anomaly -
nominal_anomalistic_mean_motion *
(initial_time - reference_epoch),
2 * π * Radian),
AbsoluteErrorFrom(225.153 * Degree, IsNear(0.53_⑴ * Degree)));
}
// COSPAR ID 2014-050B, SVN E202
// Galileo-Full Operational Capability Flight Model 2 (GSAT0202) “Milena”.
// PRN E14, slot Ext02.
TEST_F(OrbitAnalysisTest, GalileoExtendedSlot) {
auto const [elements, recurrence, ground_track] = ElementsAndRecurrence(
{{StandardProduct3::SatelliteGroup::Galileo, 14}, SP3Files::GNSS()});
EXPECT_THAT(recurrence,
AllOf(Property(&OrbitRecurrence::νₒ, 2),
Property(&OrbitRecurrence::Dᴛₒ, -3),
Property(&OrbitRecurrence::Cᴛₒ, 20)));
// Reference elements from
// https://www.gsc-europa.eu/system-status/orbital-and-technical-parameters.
Instant const reference_epoch = "2016-11-21T00:00:00"_UTC;
Instant const initial_time = elements.mean_elements().front().time;
Instant const mean_time =
initial_time + (elements.mean_elements().back().time - initial_time) / 2;
auto const nominal_nodal_precession = -0.03986760 * Degree / Day;
auto const nominal_apsidal_precession = 0.03383184 * Degree / Day;
auto const nominal_anomalistic_mean_motion = 667.86467481 * Degree / Day;
EXPECT_THAT(
elements.nodal_precession(),
AllOf(AbsoluteErrorFrom(nominal_nodal_precession,
IsNear(0.00023_⑴ * Degree / Day)),
RelativeErrorFrom(nominal_nodal_precession, IsNear(0.0059_⑴))));
EXPECT_THAT(2 * π * Radian / elements.anomalistic_period(),
AllOf(AbsoluteErrorFrom(nominal_anomalistic_mean_motion,
IsNear(0.00047_⑴ * Degree / Day)),
RelativeErrorFrom(nominal_anomalistic_mean_motion,
IsNear(7.1e-07_⑴))));
EXPECT_THAT(elements.mean_semimajor_axis_interval().midpoint(),
AbsoluteErrorFrom(27'977.6 * Kilo(Metre),
IsNear(0.0997_⑴ * Kilo(Metre))));
EXPECT_THAT(elements.mean_semimajor_axis_interval().measure(),
IsNear(00'000.096_⑴ * Kilo(Metre)));
EXPECT_THAT(elements.mean_eccentricity_interval().midpoint(),
AbsoluteErrorFrom(0.162, IsNear(0.0041_⑴)));
EXPECT_THAT(elements.mean_eccentricity_interval().measure(),
IsNear(0.000'15_⑴));
EXPECT_THAT(elements.mean_inclination_interval().midpoint(),
AbsoluteErrorFrom(49.850 * Degree, IsNear(0.77_⑴ * Degree)));
EXPECT_THAT(elements.mean_inclination_interval().measure(),
IsNear(00.0044_⑴ * Degree));
EXPECT_THAT(
Mod(elements.mean_longitude_of_ascending_node_interval().midpoint() -
nominal_nodal_precession * (mean_time - reference_epoch),
2 * π * Radian),
AbsoluteErrorFrom(52.521 * Degree, IsNear(0.29_⑴ * Degree)));
EXPECT_THAT(
Mod(elements.mean_argument_of_periapsis_interval().midpoint() -
nominal_apsidal_precession * (mean_time - reference_epoch),
2 * π * Radian),
AbsoluteErrorFrom(56.198 * Degree, IsNear(0.48_⑴ * Degree)));
EXPECT_THAT(Mod(elements.mean_elements().front().mean_anomaly -
nominal_anomalistic_mean_motion *
(initial_time - reference_epoch),
2 * π * Radian),
AbsoluteErrorFrom(136.069 * Degree, IsNear(2.5_⑴ * Degree)));
}
// COSPAR ID 2009-070A, SVN R730.
// ГЛОНАСС-М Космос 2456, Ураган-М № 730.
// PRN R01, plane 1.
TEST_F(OrbitAnalysisTest, ГЛОНАСС) {
auto const [elements, recurrence, ground_track] = ElementsAndRecurrence(
{{StandardProduct3::SatelliteGroup::ГЛОНАСС, 1}, SP3Files::GNSS()});
EXPECT_THAT(recurrence,
AllOf(Property(&OrbitRecurrence::νₒ, 2),
Property(&OrbitRecurrence::Dᴛₒ, 1),
Property(&OrbitRecurrence::Cᴛₒ, 8)));
EXPECT_THAT(elements.mean_semimajor_axis_interval().midpoint(),
IsNear(25'507_⑴ * Kilo(Metre)));
EXPECT_THAT(elements.mean_inclination_interval().midpoint(),
IsNear(64.20_⑴ * Degree));
EXPECT_THAT(elements.mean_eccentricity_interval().midpoint(),
IsNear(0.00040_⑴));
EXPECT_THAT(elements.mean_argument_of_periapsis_interval().midpoint(),
IsNear(330_⑴ * Degree));
}
// COSPAR ID 2011-036A, SVN G063.
// GPS block IIF satellite.
// PRN G01, plane D, slot 2.
TEST_F(OrbitAnalysisTest, GPS) {
auto const [elements, recurrence, ground_track] = ElementsAndRecurrence(
{{StandardProduct3::SatelliteGroup::GPS, 1}, SP3Files::GNSS()});
EXPECT_THAT(recurrence,
AllOf(Property(&OrbitRecurrence::νₒ, 2),
Property(&OrbitRecurrence::Dᴛₒ, 0),
Property(&OrbitRecurrence::Cᴛₒ, 1)));
EXPECT_THAT(elements.mean_semimajor_axis_interval().midpoint(),
IsNear(26'560_⑴ * Kilo(Metre)));
EXPECT_THAT(elements.mean_inclination_interval().midpoint(),
IsNear(55.86_⑴ * Degree));
EXPECT_THAT(elements.mean_eccentricity_interval().midpoint(),
IsNear(0.0086_⑴));
EXPECT_THAT(elements.mean_argument_of_periapsis_interval().midpoint(),
IsNear(39_⑴ * Degree));
}
// COSPAR ID 1992-052A, TOPEX/Poséidon.
TEST_F(OrbitAnalysisTest, TOPEXPoséidon) {
// The references for these orbital characteristics are [BSFL98], [Ben97] and
// [BS96].
auto const [elements, recurrence, ground_track] =
ElementsAndRecurrence({{StandardProduct3::SatelliteGroup::General, 1},
SP3Files::TOPEXPoséidon()});
EXPECT_THAT(recurrence,
AllOf(Property(&OrbitRecurrence::νₒ, 13),
Property(&OrbitRecurrence::Dᴛₒ, -3),
Property(&OrbitRecurrence::Cᴛₒ, 10)));
// Reference semimajor axis from the legend of figure 7 of Bhat et al.; that
// value is given as 7 714.42942 in table 1 of Bhat et al., 7 714.4278 km in
// Blanc et al., and 7 714.43 km in Benada.
// Figure 7 of Bhat et al. shows that the mean semimajor axis varies by up to
// 6 m either side of the reference value. Our test data is from cycle 198;
// reading the graph around that time shows that the mean semimajor axis was a
// bit less than 3 m above the nominal value around that time.
EXPECT_THAT(elements.mean_semimajor_axis_interval().midpoint(),
DifferenceFrom(7714.42938 * Kilo(Metre), IsNear(2.93_⑴ * Metre)));
// Reference inclination from the legend of figure 9 of Bhat et al.; that
// value is given as 66.040° in table 1 of Bhat et al., 66.039° in Blanc et
// al., and 66.04° in Benada.
// Figure 9 of Bhat et al. shows that the observed values of the mean
// inclination vary between 66.0375° and 66.0455° over the course of the
// mission (66.0408° ± 0.0040° according to the abstract). We can see from
// the graph that during the period under test, in early December 1997, the
// inclination is below the reference value, and varies by several thousandths
// of a degree in a matter of days; the minimum and maximum that we compute
// below therefore seem plausible.
EXPECT_THAT(elements.mean_inclination_interval().midpoint(),
DifferenceFrom(66.0408 * Degree, IsNear(-0.0025_⑴ * Degree)));
EXPECT_THAT(elements.mean_inclination_interval(),
AllOf(Field(&Interval<Angle>::min, IsNear(66.0365_⑴ * Degree)),
Field(&Interval<Angle>::max, IsNear(66.0401_⑴ * Degree))));
// The same nominal values are given by Blanc et al., Benada, and Bhat et al:
// e = 0.000095, ω = 90.0°.
// However, these values are only meaningful if we take mean elements that are
// free of variations over one 127-revolution ground track cycle (rather than
// simply over one revolution). Figure 8 of Bhat et al. shows that both the
// theoretical and observed mean e and ω vary between 40 ppm and 140 ppm, and
// between 60° and 120°, respectively.
EXPECT_THAT(elements.mean_eccentricity_interval(),
AllOf(Field(&Interval<double>::min, IsNear(88e-6_⑴)),
Field(&Interval<double>::max, IsNear(110e-6_⑴))));
EXPECT_THAT(elements.mean_argument_of_periapsis_interval(),
AllOf(Field(&Interval<Angle>::min, IsNear(74.7_⑴ * Degree)),
Field(&Interval<Angle>::max, IsNear(98.5_⑴ * Degree))));
// Nominal longitude of the equatorial crossing of the first ascending pass
// East of the ITRF zero-meridian (pass 135), as given in section 2 of Benada.
// Blanc et al. round these longitudes to a hundredth of a degree, thus 0.71°
// for pass 135.
// We can see from figure 6 of Bhat et al. that, during the period under test,
// the equatorial crossing is about 600 m east of the reference.
EXPECT_THAT(
ground_track
.equator_crossing_longitudes(recurrence,
/*first_ascending_pass_index=*/135)
.longitudes_reduced_to_pass(135)
.midpoint(),
DifferenceFrom(0.7117 * Degree,
AllOf(IsNear(0.0051_⑴ * Degree),
IsNear(573_⑴ * Metre *
(Radian / TerrestrialEquatorialRadius)))));
// Nominal longitude of the equatorial crossing of the following (descending)
// pass (pass 136), as given in section 2 of Benada. Blanc et al. round these
// longitudes to a hundredth of a degree, thus 166.54° for pass 136.
EXPECT_THAT(ground_track
.equator_crossing_longitudes(
recurrence, /*first_ascending_pass_index=*/135)
.longitudes_reduced_to_pass(136)
.midpoint(),
DifferenceFrom(166.5385 * Degree, IsNear(0.0071_⑴ * Degree)));
// Nominal longitude of the equatorial crossing of pass 1, as given in the
// auxiliary data table in Blanc et al. The reference grid there lists that
// longitude as 99.92°, and the table of equator crossing longitudes in Benada
// lists it as 99.9249°. However, the auxiliary data table in Benada gives a
// longitude of 99.947° for pass 1, which looks like a typo.
EXPECT_THAT(ground_track
.equator_crossing_longitudes(
recurrence, /*first_ascending_pass_index=*/135)
.longitudes_reduced_to_pass(1)
.midpoint(),
DifferenceFrom(99.9242 * Degree, IsNear(0.0052_⑴ * Degree)));
// Variability over the period under test (3.5 days).
EXPECT_THAT(ground_track
.equator_crossing_longitudes(
recurrence, /*first_ascending_pass_index=*/135)
.longitudes_reduced_to_pass(1)
.measure(),
IsNear(0.0025_⑴ * Degree));
EXPECT_THAT(ground_track
.equator_crossing_longitudes(
recurrence, /*first_ascending_pass_index=*/135)
.longitudes_reduced_to_pass(1)
.measure() *
TerrestrialEquatorialRadius / Radian,
IsNear(273_⑴ * Metre));
// TOPEX/Poséidon is not sun-synchronous.
EXPECT_THAT(ground_track.mean_solar_times_of_ascending_nodes()->measure() *
(1 * Day / (2 * π * Radian)),
IsNear(42_⑴ * Minute));
EXPECT_THAT(ground_track.mean_solar_times_of_descending_nodes()->measure() *
(1 * Day / (2 * π * Radian)),
IsNear(42_⑴ * Minute));
}
// The following two satellites are sun-synchronous.
// COSPAR ID 2002-021A, SPOT-5 (Satellite Pour l’Observation de la Terre).
TEST_F(OrbitAnalysisTest, SPOT5) {
auto const [elements, recurrence, ground_track] = ElementsAndRecurrence(
{{StandardProduct3::SatelliteGroup::General, 94}, SP3Files::SPOT5()});
EXPECT_THAT(recurrence,
AllOf(Property(&OrbitRecurrence::νₒ, 14),
Property(&OrbitRecurrence::Dᴛₒ, 5),
Property(&OrbitRecurrence::Cᴛₒ, 26)));
EXPECT_THAT(elements.mean_semimajor_axis_interval().midpoint(),
IsNear(7'200_⑴ * Kilo(Metre)));
EXPECT_THAT(elements.mean_inclination_interval().midpoint(),
IsNear(98.73_⑴ * Degree));
EXPECT_THAT(elements.mean_eccentricity_interval().midpoint(),
IsNear(0.0012_⑴));
EXPECT_THAT(elements.mean_argument_of_periapsis_interval().midpoint(),
IsNear(89.38_⑴ * Degree));
// The nominal mean solar times of the nodes are 22:30 ascending, 10:30
// descending.
EXPECT_THAT(ground_track.mean_solar_times_of_ascending_nodes()->midpoint() *
(1 * Day / (2 * π * Radian)),
IsNear(22.452_⑴ * Hour));
EXPECT_THAT(ground_track.mean_solar_times_of_descending_nodes()->midpoint() *
(1 * Day / (2 * π * Radian)),
IsNear(10.452_⑴ * Hour));
EXPECT_THAT(ground_track.mean_solar_times_of_ascending_nodes()->measure() *
(1 * Day / (2 * π * Radian)),
IsNear(3.91_⑴ * Second));
EXPECT_THAT(ground_track.mean_solar_times_of_descending_nodes()->measure() *
(1 * Day / (2 * π * Radian)),
IsNear(3.91_⑴ * Second));
}
// COSPAR ID 2016-011A, Sentinel-3A.
TEST_F(OrbitAnalysisTest, Sentinel3A) {
auto const [elements, recurrence, ground_track] =
ElementsAndRecurrence({{StandardProduct3::SatelliteGroup::General, 74},
SP3Files::Sentinel3A()});
EXPECT_THAT(recurrence,
AllOf(Property(&OrbitRecurrence::νₒ, 14),
Property(&OrbitRecurrence::Dᴛₒ, 7),
Property(&OrbitRecurrence::Cᴛₒ, 27)));
EXPECT_THAT(elements.mean_semimajor_axis_interval().midpoint(),
IsNear(7'177_⑴ * Kilo(Metre)));
EXPECT_THAT(elements.mean_inclination_interval().midpoint(),
IsNear(98.63_⑴ * Degree));
EXPECT_THAT(elements.mean_eccentricity_interval().midpoint(),
IsNear(0.0011_⑴));
EXPECT_THAT(elements.mean_argument_of_periapsis_interval().midpoint(),
IsNear(90.01_⑴ * Degree));
// The nominal mean solar times of the nodes are 22:00 ascending, 10:00
// descending.
EXPECT_THAT(ground_track.mean_solar_times_of_ascending_nodes()->midpoint() *
(1 * Day / (2 * π * Radian)),
IsNear(21.987_⑴ * Hour));
EXPECT_THAT(ground_track.mean_solar_times_of_descending_nodes()->midpoint() *
(1 * Day / (2 * π * Radian)),
IsNear(09.987_⑴ * Hour));
EXPECT_THAT(ground_track.mean_solar_times_of_ascending_nodes()->measure() *
(1 * Day / (2 * π * Radian)),
IsNear(1.70_⑴ * Second));
EXPECT_THAT(ground_track.mean_solar_times_of_descending_nodes()->measure() *
(1 * Day / (2 * π * Radian)),
IsNear(1.63_⑴ * Second));
}
#endif
} // namespace astronomy
} // namespace principia
| 45.262162 | 80 | 0.65349 | [
"geometry",
"vector",
"model"
] |
c875f5f46d85f26d1d7c153a4260057b05b7cfc4 | 48,801 | cpp | C++ | copasi/sbml/UnitConversionFactory.cpp | bmoreau/COPASI | d0bbec8947b1266ffd2b0ecf2566da7cf2c3e5ba | [
"Artistic-2.0"
] | null | null | null | copasi/sbml/UnitConversionFactory.cpp | bmoreau/COPASI | d0bbec8947b1266ffd2b0ecf2566da7cf2c3e5ba | [
"Artistic-2.0"
] | null | null | null | copasi/sbml/UnitConversionFactory.cpp | bmoreau/COPASI | d0bbec8947b1266ffd2b0ecf2566da7cf2c3e5ba | [
"Artistic-2.0"
] | null | null | null | // Begin CVS Header
// $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/sbml/UnitConversionFactory.cpp,v $
// $Revision: 1.11 $
// $Name: $
// $Author: ssahle $
// $Date: 2012/04/22 15:41:48 $
// End CVS Header
// Copyright (C) 2012 - 2010 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
// Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.
class UnitDefinition;
#include "UnitConversionFactory.hpp"
#include "sbml/UnitKind.h"
#include <cmath>
#include <sstream>
/**
* The SBML Level that is passed to constructors of unit definitions.
*/
unsigned int UnitConversionFactory::SBML_LEVEL = 2;
/**
* The SBML Version that is passed to constructors of unit definitions.
*/
unsigned int UnitConversionFactory::SBML_VERSION = 1;
/*
* Vector that holds the ids for UnitDefinitions that have been created
* by the conversion framework so that no two UnitDefinitions produced
* have the same id.
*/
std::vector<std::string> UnitConversionFactory::usedIds = std::vector<std::string>();
/*
* Converts a Unit into the corresponding UnitDefinition that consists
* only of SI units.
* Possible offsets are ignored.
* Freeing the memory for the returned UnitDefinition is up to the
* receiver.
* On failure a NULL pointer is returned.
* @param const Unit& unit
* @return UnitDefinition* result
*/
LIBSBML_EXTERN
UnitDefinition* UnitConversionFactory::convertToSI(const Unit& unit)
{
UnitDefinition* pUdef = NULL;
Unit* pU = NULL;
if (!unit.isSetKind()) return pUdef;
UnitKind_t uKind = unit.getKind();
switch (uKind)
{
case UNIT_KIND_AMPERE:
pUdef = convertAmpereToSI(unit);
break;
case UNIT_KIND_BECQUEREL:
case UNIT_KIND_HERTZ:
pUdef = convertFrequencyToSI(unit);
break;
case UNIT_KIND_CANDELA:
pUdef = convertCandelaToSI(unit);
break;
case UNIT_KIND_CELSIUS:
pUdef = convertCelsiusToSI(unit);
break;
case UNIT_KIND_COULOMB:
pUdef = convertCoulombToSI(unit);
break;
case UNIT_KIND_DIMENSIONLESS:
case UNIT_KIND_ITEM:
case UNIT_KIND_RADIAN:
case UNIT_KIND_STERADIAN:
pUdef = convertDimensionlessToSI(unit);
break;
case UNIT_KIND_FARAD:
pUdef = convertFaradToSI(unit);
break;
case UNIT_KIND_GRAM:
pU = new Unit(unit);
pU->setScale(pU->getScale() - 3);
pU->setKind(UNIT_KIND_KILOGRAM);
pUdef = convertKilogramToSI(*pU);
delete pU;
break;
case UNIT_KIND_GRAY:
case UNIT_KIND_SIEVERT:
pUdef = convertDoseToSI(unit);
break;
case UNIT_KIND_HENRY:
pUdef = convertHenryToSI(unit);
break;
case UNIT_KIND_JOULE:
pUdef = convertJouleToSI(unit);
break;
case UNIT_KIND_KATAL:
pUdef = convertKatalToSI(unit);
break;
case UNIT_KIND_KELVIN:
pUdef = convertKelvinToSI(unit);
break;
case UNIT_KIND_KILOGRAM:
pUdef = convertKilogramToSI(unit);
break;
case UNIT_KIND_LITER:
case UNIT_KIND_LITRE:
pU = new Unit(unit);
pU->setKind(UNIT_KIND_METER);
pU->setExponent(pU->getExponent()*3);
pU->setScale(pU->getScale() - 3);
pUdef = convertMeterToSI(*pU);
delete pU;
break;
case UNIT_KIND_LUMEN:
pUdef = convertLumenToSI(unit);
break;
case UNIT_KIND_LUX:
pUdef = convertLuxToSI(unit);
break;
case UNIT_KIND_METER:
case UNIT_KIND_METRE:
pUdef = convertMeterToSI(unit);
break;
case UNIT_KIND_MOLE:
#if LIBSBML_VERSION >= 40100
// this may be not totally correct, but this is the way we currently intend to
// handle it in COPASI
case UNIT_KIND_AVOGADRO:
#endif // LIBSBML_VERSION
pUdef = convertMoleToSI(unit);
break;
case UNIT_KIND_NEWTON:
pUdef = convertNewtonToSI(unit);
break;
case UNIT_KIND_OHM:
pUdef = convertOhmToSI(unit);
break;
case UNIT_KIND_PASCAL:
pUdef = convertPascalToSI(unit);
break;
case UNIT_KIND_SECOND:
pUdef = convertSecondToSI(unit);
break;
case UNIT_KIND_SIEMENS:
pUdef = convertSiemensToSI(unit);
break;
case UNIT_KIND_TESLA:
pUdef = convertTeslaToSI(unit);
break;
case UNIT_KIND_VOLT:
pUdef = convertVoltToSI(unit);
break;
case UNIT_KIND_WATT:
pUdef = convertWattToSI(unit);
break;
case UNIT_KIND_WEBER:
pUdef = convertWeberToSI(unit);
break;
case UNIT_KIND_INVALID:
delete pUdef;
pUdef = NULL;
break;
}
if (pUdef != NULL)
{
unsigned int num = 1;
std::stringstream ss;
ss << "UnitDefinition_" << num;
while (!UnitConversionFactory::isIdUnused(ss.str()))
{
++num;
ss.str("");
ss << "UnitDefinition_" << num;
}
std::string id = ss.str();
usedIds.push_back(id);
pUdef->setId(id);
UnitKind_t uKind = unit.getKind();
pUdef->setName(UnitKind_toString(uKind));
}
return pUdef;
}
/*
* Converts an Ampere Unit into the corresponding UnitDefinition
* consisting only of SI units.
* If the given unit does not have the correct kind, a NULL pointer is
* returned.
* It is up to the receiver to free the memory of the returned
* UnitDefinition.
* @param const Unit& unit
* @return UnitDefinition* result
*/
LIBSBML_EXTERN
UnitDefinition* UnitConversionFactory::convertAmpereToSI(const Unit& unit)
{
UnitKind_t uKind = unit.getKind();
if (uKind != UNIT_KIND_AMPERE) return NULL;
UnitDefinition* pUdef = new UnitDefinition(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
Unit* pU = new Unit(unit);
pU->setOffset(0.0);
pUdef->addUnit(pU);
delete pU;
return pUdef;
}
/*
* Converts a frequency Unit into the corresponding UnitDefinition
* consisting only of SI units. This could be e.g. a Hertz or Bequerel unit.
* If the given unit does not have the correct kind, a NULL pointer is
* returned.
* It is up to the receiver to free the memory of the returned
* UnitDefinition.
* @param const Unit& unit
* @return UnitDefinition* result
*/
LIBSBML_EXTERN
UnitDefinition* UnitConversionFactory::convertFrequencyToSI(const Unit& unit)
{
UnitKind_t uKind = unit.getKind();
if (uKind != UNIT_KIND_HERTZ && uKind != UNIT_KIND_BECQUEREL) return NULL;
UnitDefinition* pUdef = new UnitDefinition(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
Unit* pU = new Unit(unit);
pU->setKind(UNIT_KIND_SECOND);
pU->setOffset(0.0);
pU->setExponent(-1*pU->getExponent());
return pUdef;
}
/*
* Converts a Candela Unit into the corresponding UnitDefinition
* consisting only of SI units.
* If the given unit does not have the correct kind, a NULL pointer is
* returned.
* It is up to the receiver to free the memory of the returned
* UnitDefinition.
* @param const Unit& unit
* @return UnitDefinition* result
*/
LIBSBML_EXTERN
UnitDefinition* UnitConversionFactory::convertCandelaToSI(const Unit& unit)
{
UnitKind_t uKind = unit.getKind();
if (uKind != UNIT_KIND_CANDELA) return NULL;
UnitDefinition* pUdef = new UnitDefinition(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
Unit* pU = new Unit(unit);
pU->setOffset(0.0);
pUdef->addUnit(pU);
delete pU;
return pUdef;
}
/*
* Converts a Celsius Unit into the corresponding UnitDefinition
* consisting only of SI units.
* If the given unit does not have the correct kind, a NULL pointer is
* returned.
* It is up to the receiver to free the memory of the returned
* UnitDefinition.
* @param const Unit& unit
* @return UnitDefinition* result
*/
LIBSBML_EXTERN
UnitDefinition* UnitConversionFactory::convertCelsiusToSI(const Unit& unit)
{
UnitKind_t uKind = unit.getKind();
if (uKind != UNIT_KIND_CELSIUS) return NULL;
UnitDefinition* pUdef = new UnitDefinition(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
Unit* pU = new Unit(unit);
pU->setKind(UNIT_KIND_KELVIN);
pU->setOffset(0.0);
pUdef->addUnit(pU);
delete pU;
return pUdef;
}
/*
* Converts a Coulomb Unit into the corresponding UnitDefinition
* consisting only of SI units.
* If the given unit does not have the correct kind, a NULL pointer is
* returned.
* It is up to the receiver to free the memory of the returned
* UnitDefinition.
* @param const Unit& unit
* @return UnitDefinition* result
*/
LIBSBML_EXTERN
UnitDefinition* UnitConversionFactory::convertCoulombToSI(const Unit& unit)
{
UnitKind_t uKind = unit.getKind();
if (uKind != UNIT_KIND_COULOMB) return NULL;
UnitDefinition* pUdef = new UnitDefinition(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
Unit* pU = new Unit(unit);
pU->setKind(UNIT_KIND_AMPERE);
pU->setOffset(0.0);
pUdef->addUnit(pU);
delete pU;
pU = new Unit(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
pU->setKind(UNIT_KIND_SECOND);
pU->setExponent(unit.getExponent());
pUdef->addUnit(pU);
delete pU;
return pUdef;
}
/*
* Converts a "Dimensionless" Unit into the corresponding UnitDefinition
* consisting only of SI units. This would include e.g. the Radian unit.
* If the given unit does not have the correct kind, a NULL pointer is
* returned.
* It is up to the receiver to free the memory of the returned
* UnitDefinition.
* @param const Unit& unit
* @return UnitDefinition* result
*/
LIBSBML_EXTERN
UnitDefinition* UnitConversionFactory::convertDimensionlessToSI(const Unit& unit)
{
UnitKind_t uKind = unit.getKind();
if (uKind != UNIT_KIND_DIMENSIONLESS && uKind != UNIT_KIND_ITEM && uKind != UNIT_KIND_RADIAN && uKind != UNIT_KIND_STERADIAN) return NULL;
UnitDefinition* pUdef = new UnitDefinition(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
Unit* pU = new Unit(unit);
pU->setKind(UNIT_KIND_DIMENSIONLESS);
pU->setOffset(0.0);
pUdef->addUnit(pU);
delete pU;
return pUdef;
}
/*
* Converts a Farad Unit into the corresponding UnitDefinition
* consisting only of SI units.
* If the given unit does not have the correct kind, a NULL pointer is
* returned.
* It is up to the receiver to free the memory of the returned
* UnitDefinition.
* @param const Unit& unit
* @return UnitDefinition* result
*/
LIBSBML_EXTERN
UnitDefinition* UnitConversionFactory::convertFaradToSI(const Unit& unit)
{
UnitKind_t uKind = unit.getKind();
if (uKind != UNIT_KIND_FARAD) return NULL;
UnitDefinition* pUdef = new UnitDefinition(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
Unit* pU = new Unit(unit);
pU->setOffset(0.0);
pU->setKind(UNIT_KIND_AMPERE);
pU->setExponent(2*unit.getExponent());
pUdef->addUnit(pU);
delete pU;
pU = new Unit(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
pU->setKind(UNIT_KIND_KILOGRAM);
pU->setExponent(-1*unit.getExponent());
pUdef->addUnit(pU);
delete pU;
pU = new Unit(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
pU->setKind(UNIT_KIND_METER);
pU->setExponent(-2*unit.getExponent());
pUdef->addUnit(pU);
delete pU;
pU = new Unit(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
pU->setKind(UNIT_KIND_SECOND);
pU->setExponent(4*unit.getExponent());
pUdef->addUnit(pU);
delete pU;
return pUdef;
}
/*
* Converts a Kilogram Unit into the corresponding UnitDefinition
* consisting only of SI units.
* If the given unit does not have the correct kind, a NULL pointer is
* returned.
* It is up to the receiver to free the memory of the returned
* UnitDefinition.
* @param const Unit& unit
* @return UnitDefinition* result
*/
LIBSBML_EXTERN
UnitDefinition* UnitConversionFactory::convertKilogramToSI(const Unit& unit)
{
UnitKind_t uKind = unit.getKind();
if (uKind != UNIT_KIND_KILOGRAM) return NULL;
UnitDefinition* pUdef = new UnitDefinition(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
Unit* pU = new Unit(unit);
pU->setOffset(0.0);
pUdef->addUnit(pU);
delete pU;
return pUdef;
}
/*
* Converts a dose Unit into the corresponding UnitDefinition
* consisting only of SI units.
* Dose units are e.g. gray and sievert.
* If the given unit does not have the correct kind, a NULL pointer is
* returned.
* It is up to the receiver to free the memory of the returned
* UnitDefinition.
* @param const Unit& unit
* @return UnitDefinition* result
*/
LIBSBML_EXTERN
UnitDefinition* UnitConversionFactory::convertDoseToSI(const Unit& unit)
{
UnitKind_t uKind = unit.getKind();
if (uKind != UNIT_KIND_GRAM && uKind != UNIT_KIND_SIEVERT) return NULL;
UnitDefinition* pUdef = new UnitDefinition(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
Unit* pU = new Unit(unit);
pU->setOffset(0.0);
pU->setKind(UNIT_KIND_METER);
pU->setExponent(2*unit.getExponent());
pUdef->addUnit(pU);
delete pU;
pU = new Unit(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
pU->setKind(UNIT_KIND_SECOND);
pU->setExponent(-2*unit.getExponent());
pUdef->addUnit(pU);
delete pU;
return pUdef;
}
/*
* Converts a Henry Unit into the corresponding UnitDefinition
* consisting only of SI units.
* If the given unit does not have the correct kind, a NULL pointer is
* returned.
* It is up to the receiver to free the memory of the returned
* UnitDefinition.
* @param const Unit& unit
* @return UnitDefinition* result
*/
LIBSBML_EXTERN
UnitDefinition* UnitConversionFactory::convertHenryToSI(const Unit& unit)
{
UnitKind_t uKind = unit.getKind();
if (uKind != UNIT_KIND_HENRY) return NULL;
UnitDefinition* pUdef = new UnitDefinition(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
Unit* pU = new Unit(unit);
pU->setOffset(0.0);
pU->setKind(UNIT_KIND_AMPERE);
pU->setExponent(-2*unit.getExponent());
pUdef->addUnit(pU);
delete pU;
pU = new Unit(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
pU->setKind(UNIT_KIND_KILOGRAM);
pU->setExponent(unit.getExponent());
pUdef->addUnit(pU);
delete pU;
pU = new Unit(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
pU->setKind(UNIT_KIND_METER);
pU->setExponent(2*unit.getExponent());
pUdef->addUnit(pU);
delete pU;
pU = new Unit(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
pU->setKind(UNIT_KIND_SECOND);
pU->setExponent(-2*unit.getExponent());
pUdef->addUnit(pU);
delete pU;
return pUdef;
}
/*
* Converts a Joule Unit into the corresponding UnitDefinition
* consisting only of SI units.
* If the given unit does not have the correct kind, a NULL pointer is
* returned.
* It is up to the receiver to free the memory of the returned
* UnitDefinition.
* @param const Unit& unit
* @return UnitDefinition* result
*/
LIBSBML_EXTERN
UnitDefinition* UnitConversionFactory::convertJouleToSI(const Unit& unit)
{
UnitKind_t uKind = unit.getKind();
if (uKind != UNIT_KIND_JOULE) return NULL;
UnitDefinition* pUdef = new UnitDefinition(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
Unit* pU = new Unit(unit);
pU->setOffset(0.0);
pU->setKind(UNIT_KIND_KILOGRAM);
pU->setExponent(unit.getExponent());
pUdef->addUnit(pU);
delete pU;
pU = new Unit(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
pU->setKind(UNIT_KIND_METER);
pU->setExponent(2*unit.getExponent());
pUdef->addUnit(pU);
delete pU;
pU = new Unit(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
pU->setKind(UNIT_KIND_SECOND);
pU->setExponent(-2*unit.getExponent());
pUdef->addUnit(pU);
delete pU;
return pUdef;
}
/*
* Converts a Katal Unit into the corresponding UnitDefinition
* consisting only of SI units.
* If the given unit does not have the correct kind, a NULL pointer is
* returned.
* It is up to the receiver to free the memory of the returned
* UnitDefinition.
* @param const Unit& unit
* @return UnitDefinition* result
*/
LIBSBML_EXTERN
UnitDefinition* UnitConversionFactory::convertKatalToSI(const Unit& unit)
{
UnitKind_t uKind = unit.getKind();
if (uKind != UNIT_KIND_KATAL) return NULL;
UnitDefinition* pUdef = new UnitDefinition(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
Unit* pU = new Unit(unit);
pU->setOffset(0.0);
pU->setKind(UNIT_KIND_MOLE);
pU->setExponent(unit.getExponent());
pUdef->addUnit(pU);
delete pU;
pU = new Unit(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
pU->setKind(UNIT_KIND_SECOND);
pU->setExponent(-1*unit.getExponent());
pUdef->addUnit(pU);
delete pU;
return pUdef;
}
/*
* Converts a Kelvin Unit into the corresponding UnitDefinition
* consisting only of SI units.
* If the given unit does not have the correct kind, a NULL pointer is
* returned.
* It is up to the receiver to free the memory of the returned
* UnitDefinition.
* @param const Unit& unit
* @return UnitDefinition* result
*/
LIBSBML_EXTERN
UnitDefinition* UnitConversionFactory::convertKelvinToSI(const Unit& unit)
{
UnitKind_t uKind = unit.getKind();
if (uKind != UNIT_KIND_KELVIN) return NULL;
UnitDefinition* pUdef = new UnitDefinition(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
Unit* pU = new Unit(unit);
pU->setOffset(0.0);
pUdef->addUnit(pU);
delete pU;
return pUdef;
}
/*
* Converts a Lumen Unit into the corresponding UnitDefinition
* consisting only of SI units.
* If the given unit does not have the correct kind, a NULL pointer is
* returned.
* It is up to the receiver to free the memory of the returned
* UnitDefinition.
* @param const Unit& unit
* @return UnitDefinition* result
*/
LIBSBML_EXTERN
UnitDefinition* UnitConversionFactory::convertLumenToSI(const Unit& unit)
{
UnitKind_t uKind = unit.getKind();
if (uKind != UNIT_KIND_LUMEN) return NULL;
Unit* pU = new Unit(unit);
pU->setKind(UNIT_KIND_CANDELA);
UnitDefinition* pUdef = convertCandelaToSI(*pU);
delete pU;
return pUdef;
}
/*
* Converts a Lux Unit into the corresponding UnitDefinition
* consisting only of SI units.
* If the given unit does not have the correct kind, a NULL pointer is
* returned.
* It is up to the receiver to free the memory of the returned
* UnitDefinition.
* @param const Unit& unit
* @return UnitDefinition* result
*/
LIBSBML_EXTERN
UnitDefinition* UnitConversionFactory::convertLuxToSI(const Unit& unit)
{
UnitKind_t uKind = unit.getKind();
if (uKind != UNIT_KIND_LUX) return NULL;
UnitDefinition* pUdef = new UnitDefinition(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
Unit* pU = new Unit(unit);
pU->setKind(UNIT_KIND_CANDELA);
pU->setOffset(0.0);
pUdef->addUnit(pU);
delete pU;
pU = new Unit(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
pU->setKind(UNIT_KIND_METER);
pU->setExponent(-2*unit.getExponent());
pUdef->addUnit(pU);
delete pU;
return pUdef;
}
/*
* Converts a Meter Unit into the corresponding UnitDefinition
* consisting only of SI units.
* If the given unit does not have the correct kind, a NULL pointer is
* returned.
* It is up to the receiver to free the memory of the returned
* UnitDefinition.
* @param const Unit& unit
* @return UnitDefinition* result
*/
LIBSBML_EXTERN
UnitDefinition* UnitConversionFactory::convertMeterToSI(const Unit& unit)
{
UnitKind_t uKind = unit.getKind();
if (uKind != UNIT_KIND_METER) return NULL;
UnitDefinition* pUdef = new UnitDefinition(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
Unit* pU = new Unit(unit);
pU->setOffset(0.0);
pUdef->addUnit(pU);
delete pU;
return pUdef;
}
/*
* Converts a Mole Unit into the corresponding UnitDefinition
* consisting only of SI units.
* If the given unit does not have the correct kind, a NULL pointer is
* returned.
* It is up to the receiver to free the memory of the returned
* UnitDefinition.
* @param const Unit& unit
* @return UnitDefinition* result
*/
LIBSBML_EXTERN
UnitDefinition* UnitConversionFactory::convertMoleToSI(const Unit& unit)
{
UnitKind_t uKind = unit.getKind();
if (uKind != UNIT_KIND_MOLE) return NULL;
UnitDefinition* pUdef = new UnitDefinition(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
Unit* pU = new Unit(unit);
pU->setOffset(0.0);
pUdef->addUnit(pU);
delete pU;
return pUdef;
}
/*
* Converts a Newton Unit into the corresponding UnitDefinition
* consisting only of SI units.
* If the given unit does not have the correct kind, a NULL pointer is
* returned.
* It is up to the receiver to free the memory of the returned
* UnitDefinition.
* @param const Unit& unit
* @return UnitDefinition* result
*/
LIBSBML_EXTERN
UnitDefinition* UnitConversionFactory::convertNewtonToSI(const Unit& unit)
{
UnitKind_t uKind = unit.getKind();
if (uKind != UNIT_KIND_NEWTON) return NULL;
UnitDefinition* pUdef = new UnitDefinition(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
Unit* pU = new Unit(unit);
pU->setOffset(0.0);
pU->setKind(UNIT_KIND_KILOGRAM);
pUdef->addUnit(pU);
delete pU;
pU = new Unit(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
pU->setKind(UNIT_KIND_METER);
pU->setExponent(unit.getExponent());
pUdef->addUnit(pU);
delete pU;
pU = new Unit(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
pU->setKind(UNIT_KIND_SECOND);
pU->setExponent(-2*unit.getExponent());
pUdef->addUnit(pU);
delete pU;
return pUdef;
}
/*
* Converts a Ohm Unit into the corresponding UnitDefinition
* consisting only of SI units.
* If the given unit does not have the correct kind, a NULL pointer is
* returned.
* It is up to the receiver to free the memory of the returned
* UnitDefinition.
* @param const Unit& unit
* @return UnitDefinition* result
*/
LIBSBML_EXTERN
UnitDefinition* UnitConversionFactory::convertOhmToSI(const Unit& unit)
{
UnitKind_t uKind = unit.getKind();
if (uKind != UNIT_KIND_OHM) return NULL;
UnitDefinition* pUdef = new UnitDefinition(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
Unit* pU = new Unit(unit);
pU->setOffset(0.0);
pU->setKind(UNIT_KIND_AMPERE);
pU->setExponent(-2*unit.getExponent());
pUdef->addUnit(pU);
delete pU;
pU = new Unit(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
pU->setKind(UNIT_KIND_KILOGRAM);
pU->setExponent(unit.getExponent());
pUdef->addUnit(pU);
delete pU;
pU = new Unit(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
pU->setKind(UNIT_KIND_METER);
pU->setExponent(2*unit.getExponent());
pUdef->addUnit(pU);
delete pU;
pU = new Unit(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
pU->setKind(UNIT_KIND_SECOND);
pU->setExponent(-3*unit.getExponent());
pUdef->addUnit(pU);
delete pU;
return pUdef;
}
/*
* Converts a Pascal Unit into the corresponding UnitDefinition
* consisting only of SI units.
* If the given unit does not have the correct kind, a NULL pointer is
* returned.
* It is up to the receiver to free the memory of the returned
* UnitDefinition.
* @param const Unit& unit
* @return UnitDefinition* result
*/
LIBSBML_EXTERN
UnitDefinition* UnitConversionFactory::convertPascalToSI(const Unit& unit)
{
UnitKind_t uKind = unit.getKind();
if (uKind != UNIT_KIND_PASCAL) return NULL;
UnitDefinition* pUdef = new UnitDefinition(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
Unit* pU = new Unit(unit);
pU->setKind(UNIT_KIND_KILOGRAM);
pU->setOffset(0.0);
pUdef->addUnit(pU);
delete pU;
pU = new Unit(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
pU->setKind(UNIT_KIND_METER);
pU->setExponent(-1*unit.getExponent());
pUdef->addUnit(pU);
delete pU;
pU = new Unit(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
pU->setKind(UNIT_KIND_SECOND);
pU->setExponent(-2*unit.getExponent());
pUdef->addUnit(pU);
delete pU;
return pUdef;
}
/*
* Converts a Second Unit into the corresponding UnitDefinition
* consisting only of SI units.
* If the given unit does not have the correct kind, a NULL pointer is
* returned.
* It is up to the receiver to free the memory of the returned
* UnitDefinition.
* @param const Unit& unit
* @return UnitDefinition* result
*/
LIBSBML_EXTERN
UnitDefinition* UnitConversionFactory::convertSecondToSI(const Unit& unit)
{
UnitKind_t uKind = unit.getKind();
if (uKind != UNIT_KIND_SECOND) return NULL;
UnitDefinition* pUdef = new UnitDefinition(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
Unit* pU = new Unit(unit);
pU->setOffset(0.0);
pUdef->addUnit(pU);
delete pU;
return pUdef;
}
/*
* Converts a Siemens Unit into the corresponding UnitDefinition
* consisting only of SI units.
* If the given unit does not have the correct kind, a NULL pointer is
* returned.
* It is up to the receiver to free the memory of the returned
* UnitDefinition.
* @param const Unit& unit
* @return UnitDefinition* result
*/
LIBSBML_EXTERN
UnitDefinition* UnitConversionFactory::convertSiemensToSI(const Unit& unit)
{
UnitKind_t uKind = unit.getKind();
if (uKind != UNIT_KIND_SIEMENS) return NULL;
UnitDefinition* pUdef = new UnitDefinition(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
Unit* pU = new Unit(unit);
pU->setOffset(0.0);
pU->setKind(UNIT_KIND_AMPERE);
pU->setExponent(2*unit.getExponent());
pUdef->addUnit(pU);
delete pU;
pU = new Unit(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
pU->setKind(UNIT_KIND_KILOGRAM);
pU->setExponent(-1*unit.getExponent());
pUdef->addUnit(pU);
delete pU;
pU = new Unit(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
pU->setKind(UNIT_KIND_METER);
pU->setExponent(-2*unit.getExponent());
pUdef->addUnit(pU);
delete pU;
pU = new Unit(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
pU->setKind(UNIT_KIND_SECOND);
pU->setExponent(3*unit.getExponent());
pUdef->addUnit(pU);
delete pU;
return pUdef;
}
/*
* Converts a Tesla Unit into the corresponding UnitDefinition
* consisting only of SI units.
* If the given unit does not have the correct kind, a NULL pointer is
* returned.
* It is up to the receiver to free the memory of the returned
* UnitDefinition.
* @param const Unit& unit
* @return UnitDefinition* result
*/
LIBSBML_EXTERN
UnitDefinition* UnitConversionFactory::convertTeslaToSI(const Unit& unit)
{
UnitKind_t uKind = unit.getKind();
if (uKind != UNIT_KIND_TESLA) return NULL;
UnitDefinition* pUdef = new UnitDefinition(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
Unit* pU = new Unit(unit);
pU->setOffset(0.0);
pU->setKind(UNIT_KIND_AMPERE);
pU->setExponent(-1*unit.getExponent());
pUdef->addUnit(pU);
delete pU;
pU = new Unit(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
pU->setKind(UNIT_KIND_KILOGRAM);
pU->setExponent(unit.getExponent());
pUdef->addUnit(pU);
delete pU;
pU = new Unit(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
pU->setKind(UNIT_KIND_SECOND);
pU->setExponent(-2*unit.getExponent());
pUdef->addUnit(pU);
delete pU;
return pUdef;
}
/*
* Converts a Volt Unit into the corresponding UnitDefinition
* consisting only of SI units.
* If the given unit does not have the correct kind, a NULL pointer is
* returned.
* It is up to the receiver to free the memory of the returned
* UnitDefinition.
* @param const Unit& unit
* @return UnitDefinition* result
*/
LIBSBML_EXTERN
UnitDefinition* UnitConversionFactory::convertVoltToSI(const Unit& unit)
{
UnitKind_t uKind = unit.getKind();
if (uKind != UNIT_KIND_VOLT) return NULL;
UnitDefinition* pUdef = new UnitDefinition(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
Unit* pU = new Unit(unit);
pU->setOffset(0.0);
pU->setKind(UNIT_KIND_AMPERE);
pU->setExponent(-1*unit.getExponent());
pUdef->addUnit(pU);
delete pU;
pU = new Unit(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
pU->setKind(UNIT_KIND_KILOGRAM);
pU->setExponent(unit.getExponent());
pUdef->addUnit(pU);
delete pU;
pU = new Unit(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
pU->setKind(UNIT_KIND_METER);
pU->setExponent(2*unit.getExponent());
pUdef->addUnit(pU);
delete pU;
pU = new Unit(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
pU->setKind(UNIT_KIND_SECOND);
pU->setExponent(-3*unit.getExponent());
pUdef->addUnit(pU);
delete pU;
return pUdef;
}
/*
* Converts a Watt Unit into the corresponding UnitDefinition
* consisting only of SI units.
* If the given unit does not have the correct kind, a NULL pointer is
* returned.
* It is up to the receiver to free the memory of the returned
* UnitDefinition.
* @param const Unit& unit
* @return UnitDefinition* result
*/
LIBSBML_EXTERN
UnitDefinition* UnitConversionFactory::convertWattToSI(const Unit& unit)
{
UnitKind_t uKind = unit.getKind();
if (uKind != UNIT_KIND_WATT) return NULL;
UnitDefinition* pUdef = new UnitDefinition(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
Unit* pU = new Unit(unit);
pU->setOffset(0.0);
pU->setKind(UNIT_KIND_KILOGRAM);
pU->setExponent(unit.getExponent());
pUdef->addUnit(pU);
delete pU;
pU = new Unit(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
pU->setKind(UNIT_KIND_METER);
pU->setExponent(2*unit.getExponent());
pUdef->addUnit(pU);
delete pU;
pU = new Unit(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
pU->setKind(UNIT_KIND_SECOND);
pU->setExponent(-3*unit.getExponent());
pUdef->addUnit(pU);
delete pU;
return pUdef;
}
/*
* Converts a Weber Unit into the corresponding UnitDefinition
* consisting only of SI units.
* If the given unit does not have the correct kind, a NULL pointer is
* returned.
* It is up to the receiver to free the memory of the returned
* UnitDefinition.
* @param const Unit& unit
* @return UnitDefinition* result
*/
LIBSBML_EXTERN
UnitDefinition* UnitConversionFactory::convertWeberToSI(const Unit& unit)
{
UnitKind_t uKind = unit.getKind();
if (uKind != UNIT_KIND_WATT) return NULL;
UnitDefinition* pUdef = new UnitDefinition(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
Unit* pU = new Unit(unit);
pU->setOffset(0.0);
pU->setKind(UNIT_KIND_AMPERE);
pU->setExponent(-1*unit.getExponent());
pUdef->addUnit(pU);
delete pU;
pU = new Unit(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
pU->setKind(UNIT_KIND_KILOGRAM);
pU->setExponent(unit.getExponent());
pUdef->addUnit(pU);
delete pU;
pU = new Unit(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
pU->setKind(UNIT_KIND_METER);
pU->setExponent(2*unit.getExponent());
pUdef->addUnit(pU);
delete pU;
pU = new Unit(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
pU->setKind(UNIT_KIND_SECOND);
pU->setExponent(-2*unit.getExponent());
pUdef->addUnit(pU);
delete pU;
return pUdef;
}
/*
LIBSBML_EXTERN
UnitDefinition* UnitConversionFactory::normalize(const UnitDefinition& uDef)
{
// convert all units to SI units
// see if units other then the first one have a scale and/or a multiplier
// if so, combine those with the scale and/or multiplier of the first unit
UnitDefinition* pResult = NULL;
unsigned int maxUnits = uDef.getNumUnits();
unsigned int counter = 0;
while (counter < maxUnits)
{
Unit* pU = uDef.getUnit(counter);
UnitDefinition* pTempUdef = UnitConversionFactory::convertToSI(*pU);
if (pTempUdef == NULL)
{
pResult = NULL;
break;
}
UnitDefinition* pTempUdef2 = UnitConversionFactory::combine(*pResult, *pTempUdef);
delete pTempUdef;
delete pResult;
pResult = pTempUdef2;
if (pResult == NULL)
{
break;
}
++counter;
}
if (pResult != NULL)
{
pResult->setName(uDef.getName());
pResult->setId(uDef.getId());
maxUnits = pResult->getNumUnits();
counter = 1;
if (maxUnits > 0)
{
Unit* pFirst = pResult->getUnit(0);
while (counter < maxUnits)
{
Unit* pU = pResult->getUnit(counter);
int scale = pU->getScale();
if (scale != 0)
{
pFirst->setScale(scale + pFirst->getScale());
}
double multiplier = pU->getMultiplier();
if (multiplier != 1.0)
{
// if the multiplier is 0, the unit definition does not make sense
// we treat this as an error rather than returning a dimensionless
// UnitDefinition
if (multiplier == 0.0)
{
delete pResult;
pResult = NULL;
break;
}
pFirst->setMultiplier(multiplier*pFirst->getMultiplier());
}
++counter;
}
}
}
return pResult;
}
*/
/*
* Combines two UnitDefinitions by combining the equivalent units from
* both UnitDefinitions.
* A new UnitDefinition containing the combination is returned.
* If two eqivalent units have a different offset, the function returns a
* NULL pointer.
* It is up to the receiver to free the memory of the returned UnitDefinition.
* @param const UnitDefinition& uDef1
* @param const UnitDefinition& uDef2
* @return UnitDefinition* result
*/
LIBSBML_EXTERN
UnitDefinition* UnitConversionFactory::combine(const UnitDefinition& uDef1, const UnitDefinition& uDef2)
{
// take all Units from the first UnitDefinition make copies and put them into the new UnitDefinition
// go through all Units in the second UnitDefinition, if the same unit already exists in the new
// UnitDefinition combine them, else add a copy of the Unit to the new UnitDefinition
UnitDefinition* pResult = new UnitDefinition(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
unsigned int maxUnits = uDef1.getNumUnits();
unsigned int i;
for (i = 0; i < maxUnits; ++i)
{
const Unit* pSrcUnit = uDef1.getUnit(i);
unsigned int maxUnits2 = pResult->getNumUnits();
unsigned int j;
bool exists = false;
for (j = 0; j < maxUnits2; ++j)
{
Unit* pResultUnit = pResult->getUnit(j);
if (pResultUnit->getKind() == pSrcUnit->getKind())
{
exists = true;
// if the offsets are different, we can not combine the units
if (pResultUnit->getOffset() != pSrcUnit->getOffset())
{
delete pResult;
return NULL;
}
pResultUnit->setMultiplier(pResultUnit->getMultiplier()*pSrcUnit->getMultiplier()*pow(10.0, pResultUnit->getScale() - pSrcUnit->getScale()));
pResultUnit->setExponent(pResultUnit->getExponent() + pSrcUnit->getExponent());
// if the resulting scale is 0, the units have canceled each other out
// and we set the kind to dimensionless so that it can be eliminated
// later on
if (pResultUnit->getExponent() == 0)
{
pResultUnit->setKind(UNIT_KIND_DIMENSIONLESS);
}
}
}
if (!exists)
{
Unit* tmpUnit = new Unit(*pSrcUnit);
pResult->addUnit(tmpUnit);
delete tmpUnit;
}
}
maxUnits = uDef2.getNumUnits();
for (i = 0; i < maxUnits; ++i)
{
const Unit* pSrcUnit = uDef2.getUnit(i);
unsigned int maxUnits2 = pResult->getNumUnits();
unsigned int j;
bool exists = false;
for (j = 0; j < maxUnits2; ++j)
{
Unit* pResultUnit = pResult->getUnit(j);
if (pResultUnit->getKind() == pSrcUnit->getKind())
{
exists = true;
// if the offsets are different, we can not combine the units
if (pResultUnit->getOffset() != pSrcUnit->getOffset())
{
delete pResult;
return NULL;
}
pResultUnit->setMultiplier(pResultUnit->getMultiplier()*pSrcUnit->getMultiplier()*pow(10.0, pResultUnit->getScale() - pSrcUnit->getScale()));
pResultUnit->setExponent(pResultUnit->getExponent() + pSrcUnit->getExponent());
// if the resulting scale is 0, the units have canceled each other out
// and we set the kind to dimensionless so that it can be eliminated
// later on
if (pResultUnit->getExponent() == 0)
{
pResultUnit->setKind(UNIT_KIND_DIMENSIONLESS);
}
}
}
if (!exists)
{
Unit* tmpUnit = new Unit(*pSrcUnit);
pResult->addUnit(tmpUnit);
delete tmpUnit;
}
}
UnitDefinition* pTmp = UnitConversionFactory::eliminateDimensionless(pResult);
if (pTmp)
{
delete pResult;
pResult = pTmp;
}
return pResult;
}
/*
* Eliminate all dimensionless units from the given UnitDefinition.
* A new UnitDefinition without the dimensionless units is returned.
* The scale and multiplier are preserved. If the UnitDefinition has only
* one unit the is a dimensionless, it is not deleted.
* @param UnitDefinition* pUdef
* @return UnitDefinition* result
*/
LIBSBML_EXTERN
UnitDefinition* UnitConversionFactory::eliminateDimensionless(UnitDefinition* pUdef)
{
unsigned int maxUnits = pUdef->getNumUnits();
UnitDefinition* pTmpUdef = NULL;
Unit* pU = NULL;
if (maxUnits > 1)
{
int scale = 0;
double multiplier = 1.0;
unsigned int i = 0;
pTmpUdef = new UnitDefinition(UnitConversionFactory::SBML_LEVEL, UnitConversionFactory::SBML_VERSION);
while (i < maxUnits)
{
pU = new Unit(*(pUdef->getUnit(i)));
if (pU->getKind() != UNIT_KIND_DIMENSIONLESS)
{
pTmpUdef->addUnit(pU);
}
else
{
// conserve scale and multiplier
scale = scale + pU->getScale();
multiplier = multiplier * pU->getMultiplier();
}
delete pU;
++i;
}
i = pTmpUdef->getNumUnits();
if (i > 0 && i < maxUnits)
{
pTmpUdef->setName(pUdef->getName());
pTmpUdef->setId(pUdef->getId());
pU = pTmpUdef->getUnit(0);
pU->setScale(pU->getScale() + scale);
pU->setMultiplier(pU->getMultiplier()*multiplier);
}
else
{
delete pTmpUdef;
pTmpUdef = NULL;
}
}
return pTmpUdef;
}
/*
* Converts a UnitDefinition into the corresponding UnitDefinition that consists
* only of SI units.
* Possible offsets are ignored.
* Freeing the memory for the returned UnitDefinition is up to the
* receiver.
* On failure a NULL pointer is returned.
* @param const UnitDefinition& uDef
* @return UnitDefinition* result
*/
LIBSBML_EXTERN
UnitDefinition* UnitConversionFactory::convertToSI(const UnitDefinition& uDef)
{
// convert all contained units to SI units
// combine the resulting unitdefinitions
UnitDefinition* pResult = NULL;
UnitDefinition* pTmpDef = NULL;
unsigned int i;
unsigned int maxUnits = uDef.getNumUnits();
if (maxUnits > 0)
{
pTmpDef = UnitConversionFactory::convertToSI(*(uDef.getUnit(0)));
pResult = pTmpDef;
for (i = 1; i < maxUnits; ++i)
{
UnitDefinition* pTmpDef2 = UnitConversionFactory::convertToSI(*(uDef.getUnit(i)));
pResult = UnitConversionFactory::combine(*pTmpDef, *pTmpDef2);
delete pTmpDef;
delete pTmpDef2;
// stop if the result was a NULL pointer
if (!pResult) break;
pTmpDef = pResult;
}
}
return pResult;
}
/*
* Checks if two UnitDefinitions are equivalent, i.e. wether they are
* interconvertible.
* This is the case if they consist of the same set of units
* with the same exponents after being
* converted to SI units. The scales of the equivalent units may differ.
* If the offset of two equivalent units differ, false is returned.
* @param const UnitDefinition& uDef1
* @param const UnitDefinition& uDef2
* @return bool areEquivalent
*/
LIBSBML_EXTERN
bool UnitConversionFactory::areEquivalent(const UnitDefinition& uDef1, const UnitDefinition& uDef2)
{
bool equivalent = true;
UnitDefinition* pTmpUdef1 = UnitConversionFactory::convertToSI(uDef1);
UnitDefinition* pTmpUdef2 = UnitConversionFactory::convertToSI(uDef2);
if (pTmpUdef1 && pTmpUdef2)
{
unsigned int maxUnits = pTmpUdef1->getNumUnits();
if (maxUnits == pTmpUdef2->getNumUnits())
{
unsigned int i;
// for all units the UnitKind and the exponent must be the same for the unit
// definitions to be interconvertible
for (i = 0; i < maxUnits; ++i)
{
Unit* pUnit1 = pTmpUdef1->getUnit(i);
Unit* pUnit2 = pTmpUdef2->getUnit(i);
if (pUnit1->getKind() != pUnit2->getKind())
{
equivalent = false;
break;
}
if (pUnit1->getExponent() != pUnit2->getExponent())
{
equivalent = false;
break;
}
}
}
else
{
equivalent = false;
}
delete pTmpUdef1;
delete pTmpUdef2;
}
else
{
equivalent = false;
}
return equivalent;
}
/*
* Checks if two UnitDefinitions are equal.
* This is the case if they consist of the same set of units with the same scale and exponent
* after being converted to SI units.
* If the offset of two equivalent units differ, false is returned.
* @param const UnitDefinition& uDef1
* @param const UnitDefinition& uDef2
* @return bool areEqual
*/
LIBSBML_EXTERN
bool UnitConversionFactory::areEqual(const UnitDefinition& uDef1, const UnitDefinition& uDef2)
{
bool equal = true;
UnitDefinition* pTmpUdef1 = UnitConversionFactory::convertToSI(uDef1);
UnitDefinition* pTmpUdef2 = UnitConversionFactory::convertToSI(uDef2);
if (pTmpUdef1 && pTmpUdef2)
{
unsigned int maxUnits = pTmpUdef1->getNumUnits();
if (maxUnits == pTmpUdef2->getNumUnits())
{
unsigned int i;
// for all units the UnitKind and the exponent must be the same for the unit
// definitions to be interconvertible
for (i = 0; i < maxUnits; ++i)
{
Unit* pUnit1 = pTmpUdef1->getUnit(i);
Unit* pUnit2 = pTmpUdef2->getUnit(i);
if (pUnit1->getKind() != pUnit2->getKind())
{
equal = false;
break;
}
if (pUnit1->getExponent() != pUnit2->getExponent())
{
equal = false;
break;
}
if (pUnit1->getScale() != pUnit2->getScale())
{
equal = false;
break;
}
}
}
else
{
equal = false;
}
delete pTmpUdef1;
delete pTmpUdef2;
}
else
{
equal = false;
}
return equal;
}
/*
* Converts the given value from the given source UnitDefinition to the
* given destination UnitDefinition if the two UnitDefinitions are
* equivalent.
* The original value is changed. On success the functions returns true,
* otherwise it returns false.
* @param const double* value
* @param const UnitDefinition& srcUdef
* @param const UnitDefinition& destUdef
* @return bool success
*/
LIBSBML_EXTERN
bool UnitConversionFactory::convertValue(double *value, const UnitDefinition& srcUdef, const UnitDefinition& destUdef)
{
bool success = true;
if (UnitConversionFactory::areEquivalent(srcUdef, destUdef))
{
UnitDefinition* pTmpUdef1 = UnitConversionFactory::convertToSI(srcUdef);
UnitDefinition* pTmpUdef2 = UnitConversionFactory::convertToSI(destUdef);
// both UnitDefinitions should only differ in the multiplier of the first unit
double factor = pTmpUdef1->getUnit(0)->getMultiplier() / pTmpUdef2->getUnit(0)->getMultiplier();
int scaleDiff = pTmpUdef1->getUnit(0)->getScale() - pTmpUdef2->getUnit(0)->getScale();
factor = factor * pow(10.0, scaleDiff);
*value = (*value) * factor;
delete pTmpUdef1;
delete pTmpUdef2;
}
else
{
success = false;
}
return success;
}
/*
* The functions determins wether the given UnitDefinition contains only
* units from the list given as the second argument.
* @param const UnitDefinition& uDef
* @param const ListOf& unitList
* @return bool containsOnlyGivenUnits
*/
LIBSBML_EXTERN
bool UnitConversionFactory::containsOnlyGivenUnits(const UnitDefinition& uDef, const ListOf& unitList)
{
bool result = true;
UnitDefinition* pTmpUdef = UnitConversionFactory::convertToSI(uDef);
if (pTmpUdef)
{
unsigned int i;
unsigned int maxUnits = pTmpUdef->getNumUnits();
for (i = 0; i < maxUnits; ++i)
{
Unit* pU = pTmpUdef->getUnit(i);
UnitKind_t kind = pU->getKind();
unsigned int j;
unsigned int maxUnits2 = unitList.size();
bool found = false;
for (j = 0; j < maxUnits2; ++j)
{
const Unit* pU2 = dynamic_cast<const Unit*>(unitList.get(j));
if (!pU2) break;
if (pU2->getKind() == kind)
{
found = true;
break;
}
}
if (!found)
{
result = false;
break;
}
}
delete pTmpUdef;
}
else
{
result = false;
}
return result;
}
/*
* Checks wether a given id is has already been used by the conversion
* framework.
* @param const std::string id
* @return bool isUnused
*/
LIBSBML_EXTERN
bool UnitConversionFactory::isIdUnused(const std::string& id)
{
bool unused = true;
size_t i;
size_t maxIds = usedIds.size();
for (i = 0; i < maxIds; ++i)
{
if (id == usedIds[i])
{
unused = false;
break;
}
}
return unused;
}
/*
* Returns a string representation of the given Unit. THis function is
* only for debugging purposes.
* @param const UnitDefinition& uDef
* @return std::string unitDefinitionRepresentation
*/
LIBSBML_EXTERN
std::string UnitConversionFactory::toString(const UnitDefinition& uDef)
{
unsigned int maxUnits = uDef.getNumUnits();
unsigned int i;
std::stringstream ss;
for (i = 0; i < maxUnits; ++i)
{
ss << "(" << UnitConversionFactory::toString(*(uDef.getUnit(i))) << ") ";
}
return ss.str();
}
/*
* Returns a string representation of the given Unit. THis function is
* only for debugging purposes.
* @param const Unit& unit
* @return std::string unitRepresentation
*/
LIBSBML_EXTERN
std::string UnitConversionFactory::toString(const Unit& unit)
{
double multiplier = unit.getMultiplier();
double offset = unit.getOffset();
int scale = unit.getScale();
int exponent = unit.getExponent();
UnitKind_t kind = unit.getKind();
std::stringstream ss;
ss << multiplier << " * (" << UnitKind_toString(kind) << " * 10^" << scale << " + " << offset << ")^" << exponent;
return ss.str();
}
/**
* Returns the SBML level that is passed to constructors of unit definitions.
*/
unsigned int UnitConversionFactory::getSBMLLevel()
{
return SBML_LEVEL;
}
/**
* Returns the SBML version that is passed to constructors of unit definitions.
*/
unsigned int UnitConversionFactory::getSBMLVersion()
{
return SBML_VERSION;
}
/**
* Changes the SBML level that is passed to constructors of unit definitions.
*/
void UnitConversionFactory::setSBMLLevel(unsigned int level)
{
SBML_LEVEL = level;
}
/**
* Changes the SBML version that is passed to constructors of unit definitions.
*/
void UnitConversionFactory::setSBMLVersion(unsigned int version)
{
SBML_VERSION = version;
}
| 29.204668 | 155 | 0.688531 | [
"vector"
] |
c877b0c837ccbb25d21ea044deca6ba36c664844 | 1,660 | cc | C++ | lib/jxl/enc_toc.cc | zond/libjxl | 04267a8780d1600d2bc9a79d161d7f769b5db93c | [
"BSD-3-Clause"
] | 453 | 2021-05-25T15:53:07.000Z | 2022-03-30T05:32:31.000Z | lib/jxl/enc_toc.cc | zond/libjxl | 04267a8780d1600d2bc9a79d161d7f769b5db93c | [
"BSD-3-Clause"
] | 659 | 2021-05-25T16:33:46.000Z | 2022-03-31T14:59:34.000Z | lib/jxl/enc_toc.cc | zond/libjxl | 04267a8780d1600d2bc9a79d161d7f769b5db93c | [
"BSD-3-Clause"
] | 105 | 2021-05-25T16:11:10.000Z | 2022-03-29T09:52:09.000Z | // Copyright (c) the JPEG XL Project Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#include "lib/jxl/enc_toc.h"
#include <stdint.h>
#include "lib/jxl/aux_out_fwd.h"
#include "lib/jxl/coeff_order.h"
#include "lib/jxl/coeff_order_fwd.h"
#include "lib/jxl/common.h"
#include "lib/jxl/enc_coeff_order.h"
#include "lib/jxl/field_encodings.h"
#include "lib/jxl/fields.h"
#include "lib/jxl/toc.h"
namespace jxl {
Status WriteGroupOffsets(const std::vector<BitWriter>& group_codes,
const std::vector<coeff_order_t>* permutation,
BitWriter* JXL_RESTRICT writer, AuxOut* aux_out) {
BitWriter::Allotment allotment(writer, MaxBits(group_codes.size()));
if (permutation && !group_codes.empty()) {
// Don't write a permutation at all for an empty group_codes.
writer->Write(1, 1); // permutation
JXL_DASSERT(permutation->size() == group_codes.size());
EncodePermutation(permutation->data(), /*skip=*/0, permutation->size(),
writer, /* layer= */ 0, aux_out);
} else {
writer->Write(1, 0); // no permutation
}
writer->ZeroPadToByte(); // before TOC entries
for (size_t i = 0; i < group_codes.size(); i++) {
JXL_ASSERT(group_codes[i].BitsWritten() % kBitsPerByte == 0);
const size_t group_size = group_codes[i].BitsWritten() / kBitsPerByte;
JXL_RETURN_IF_ERROR(U32Coder::Write(kTocDist, group_size, writer));
}
writer->ZeroPadToByte(); // before first group
ReclaimAndCharge(writer, &allotment, kLayerTOC, aux_out);
return true;
}
} // namespace jxl
| 35.319149 | 75 | 0.677711 | [
"vector"
] |
c87b7eebd018fe66853b30ea0d1a4d197d2184d9 | 423 | cpp | C++ | libs/object/src/object.cpp | andreasbrueck/BoostObject | 07cab717513b71332baa766fdcd0b07d8c0a320f | [
"BSL-1.0"
] | null | null | null | libs/object/src/object.cpp | andreasbrueck/BoostObject | 07cab717513b71332baa766fdcd0b07d8c0a320f | [
"BSL-1.0"
] | null | null | null | libs/object/src/object.cpp | andreasbrueck/BoostObject | 07cab717513b71332baa766fdcd0b07d8c0a320f | [
"BSL-1.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////
//
// (C) Copyright 2015 Andreas Brück
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_OBJECT_HEADER_ONLY
#define BOOST_OBJECT__IN_OBJECT_CPP
#include <boost/object/object.hpp>
#endif
| 35.25 | 75 | 0.624113 | [
"object"
] |
c87e7a1199f86ec4e12032124e41c182cd397fb2 | 63,817 | cpp | C++ | src/opr/impl/basic_arith.cpp | chenls/MegEngine | 3f783aba4b81ab628ad911d0c66a49d163a8aaf6 | [
"Apache-2.0"
] | null | null | null | src/opr/impl/basic_arith.cpp | chenls/MegEngine | 3f783aba4b81ab628ad911d0c66a49d163a8aaf6 | [
"Apache-2.0"
] | null | null | null | src/opr/impl/basic_arith.cpp | chenls/MegEngine | 3f783aba4b81ab628ad911d0c66a49d163a8aaf6 | [
"Apache-2.0"
] | null | null | null | /**
* \file src/opr/impl/basic_arith.cpp
* MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
*
* Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#include "megbrain/opr/basic_arith.h"
#include "megbrain/opr/basic_arith_wrapper.h"
#include "megbrain/opr/utility.h"
#include "megbrain/opr/io.h"
#include "megbrain/opr/cond.h"
#include "megbrain/opr/tensor_manip.h"
#include "megbrain/gopt/basic_arith.h"
#include "megbrain/gopt/gtrans.h"
#include "megbrain/utils/arith_helper.h"
#include "megbrain/graph/grad_impl.h"
#include "./internal/megdnn_opr_wrapper.inl"
#include <cmath>
using namespace mgb;
using namespace opr;
namespace {
//! global operator instance for static inference
template<class Opr>
class StaticInferOpr {
intl::UniqPtrWithCN<Opr> m_opr;
std::mutex m_mtx;
public:
class Lock {
friend class StaticInferOpr;
StaticInferOpr *m_owner;
explicit Lock(StaticInferOpr *owner):
m_owner{owner}
{
m_owner->m_mtx.lock();
}
public:
Lock(Lock &&rhs):
m_owner{rhs.m_owner}
{
rhs.m_owner = nullptr;
}
~Lock() {
if (m_owner)
m_owner->m_mtx.unlock();
}
Lock& operator = (const Lock &) = delete;
Lock& operator = (Lock&&) = delete;
intl::UniqPtrWithCN<Opr>& operator() () {
return m_owner->m_opr;
}
};
//! lock and acquire the operator
Lock lock() {
Lock ret{this};
if (!m_opr) {
m_opr = intl::create_megdnn_opr<Opr>(
CompNode::default_cpu());
}
return ret;
}
};
} // anonymous namespace
/* ========================= BatchedDTypePromotion ========================= */
intl::BatchedDTypePromotion::BatchedDTypePromotion(const VarNodeArrayView& vars)
: m_orig_vars{vars} {
mgb_assert(!vars.empty());
DType final_dtype;
bool changed = false;
for (size_t i = 0; i < vars.size(); ++i) {
auto cur = vars[i]->dtype();
if (!i) {
final_dtype = cur;
} else {
auto promoted = dtype_promotion(final_dtype, cur);
changed |= promoted != final_dtype || promoted != cur;
final_dtype = promoted;
}
}
m_changed = changed;
m_final_dtype = final_dtype;
}
void intl::BatchedDTypePromotion::set_dtype(DType dtype) {
mgb_assert(!m_finalized);
if (m_final_dtype != dtype) {
m_final_dtype = dtype;
m_changed = true;
}
}
const VarNodeArrayView& intl::BatchedDTypePromotion::get_vars() {
m_finalized = true;
if (!m_changed) {
return m_orig_vars;
}
if (!m_cvt_vars_view.valid()) {
m_cvt_vars.resize(m_orig_vars.size());
auto dtype = m_final_dtype;
for (size_t i = 0; i < m_cvt_vars.size(); ++i) {
m_cvt_vars[i] = TypeCvt::make(m_orig_vars[i], dtype).node();
}
m_cvt_vars_view.emplace(m_cvt_vars);
}
return m_cvt_vars_view.val();
}
/* =========================== Elemwise =========================== */
MGB_DYN_TYPE_OBJ_FINAL_IMPL(Elemwise);
Elemwise::Elemwise(
const ModeTrait &mode_trait,
const VarNodeArrayView &inputs, Param param,
const OperatorNodeConfig &config):
Super{inputs.at(0)->owner_graph(), config, mode_trait.name, inputs}
{
init_megdnn_opr(*this, param);
output(0)->add_flag(VarNode::Flag::ALLOW_EMPTY_SHAPE);
if (mode_trait.commutable) {
mgb_assert(inputs.size() == 2);
add_input({inputs[0], inputs[1]}, AddInputSortType::CUR_ADDED);
} else {
if (param.mode == Mode::FUSE_MUL_ADD3) {
add_input({inputs[0], inputs[1]}, AddInputSortType::CUR_ADDED);
add_input({inputs[2]});
} else if (param.mode == Mode::FUSE_MUL_ADD4) {
auto i0 = inputs[0], i1 = inputs[1], i2 = inputs[2], i3 = inputs[3];
if (i0->id() > i1->id())
std::swap(i0, i1);
if (i2->id() > i3->id())
std::swap(i2, i3);
if (i0->id() > i2->id()) {
std::swap(i0, i2);
std::swap(i1, i3);
}
add_input({i0, i1, i2, i3});
} else {
for (auto i: inputs)
add_input({i});
}
}
mgb_assert(m_input_broadcastable.size() >= inputs.size());
for (size_t i = 0; i < inputs.size(); ++ i) {
if (input()[i]->owner_opr()->same_type<
opr::MarkNoBroadcastElemwise>()) {
m_input_broadcastable[i] = false;
} else {
m_input_broadcastable[i] = true;
}
}
if (inputs.size() == 1) {
m_input_broadcastable[0] = false;
} else {
Maybe<size_t> non_scalar;
using namespace cg::static_infer;
auto &&mgr = owner_graph()->static_infer_manager();
for (size_t i = 0; i < input().size(); ++ i) {
auto it = mgr.get_infer_type(input(i));
if (!((it.shape & InferType::CONST) &&
mgr.infer_shape(input(i)).is_scalar())) {
if (non_scalar.valid()) {
non_scalar.invalidate();
break;
}
non_scalar = i;
}
}
if (non_scalar.valid()) {
// exactly one input is non-scalar
m_input_broadcastable[non_scalar.val()] = false;
}
}
if (inputs.size() &&
inputs[0]->dtype().category() == DTypeCategory::QUANTIZED) {
mgb_assert(param.mode == Param::Mode::ADD ||
param.mode == Param::Mode::SUB ||
param.mode == Param::Mode::NEGATE ||
param.mode == Param::Mode::RELU ||
param.mode == Param::Mode::MAX ||
param.mode == Param::Mode::MIN,
"Only ADD, SUB, NEGATE, RELU, MAX and MIN is guaranteed "
"to be supported on Elemwise for quantized DType, no support %d", (int)param.mode);
}
}
SymbolVar Elemwise::make(const VarNodeArrayView& inputs, Param param,
const OperatorNodeConfig& config) {
auto trait = ModeTrait::from_mode(param.mode);
mgb_assert(inputs.size() == trait.arity,
"%s expects %u inputs; got %zu actually", trait.name,
trait.arity, inputs.size());
intl::BatchedDTypePromotion dtp{inputs};
if (dtp.get_dtype().category() == DTypeCategory::INT && !trait.allow_int) {
dtp.set_dtype(dtype::Float32());
}
mgb_throw_if(dtp.get_dtype().category() == DTypeCategory::FLOAT &&
!trait.allow_float,
ConversionError,
"elemwise mode %s does not allow float input; "
"got inputs: %s",
trait.name, cg::dump_var_info(inputs).c_str());
#if !MGB_BUILD_SLIM_SERVING
auto&& options = inputs[0]->owner_graph()->options();
if (options.graph_opt_level && !(options.disable_inplace_arith_opt)) {
auto repl = gopt::optimize_elemwise_expr_inplace(dtp.get_vars(), param,
config);
if (repl)
return repl;
}
#endif
return SymbolVar{inputs[0]}.insert_single_output_opr<Elemwise>(
trait, dtp.get_vars(), param, config);
}
TensorShape Elemwise::get_output_var_shape(
Mode mode, const TensorShapeArray &input_shapes) {
mgb_assert(input_shapes.size() == ModeTrait::from_mode(mode).arity);
TensorShape ret;
megdnn::Elemwise::deduce_shape(input_shapes, ret);
return ret;
}
void Elemwise::perform(
Mode mode, DeviceTensorND &dest,
const SmallVector<DeviceTensorND> &inputs,
intl::UniqPtrWithCN<megdnn::Elemwise> &opr) {
megdnn::TensorNDArray dnn_inputs(inputs.size());
TensorShapeArray inp_shapes(inputs.size());
DType out_dt;
CompNode out_cn;
for (size_t i = 0; i < inputs.size(); ++ i) {
auto &&t = inputs[i];
if (!i) {
out_cn = t.comp_node();
out_dt = t.dtype();
} else {
mgb_assert(t.comp_node() == out_cn);
mgb_assert(t.dtype() == out_dt);
}
if (t.shape().is_empty()) {
mgb_assert(dest.empty());
return;
}
inp_shapes[i] = t.shape();
}
if (!opr) {
opr = intl::create_megdnn_opr<megdnn::Elemwise>(out_cn);
} else {
mgb_assert(out_cn == opr.comp_node());
}
out_cn.activate();
for (size_t i = 0; i < inputs.size(); ++ i)
dnn_inputs[i] = inputs[i].as_megdnn();
dest.comp_node(out_cn).dtype(out_dt).resize(
get_output_var_shape(mode, inp_shapes));
opr->param() = {mode};
call_megdnn_opr_exec(out_cn, dnn_inputs, dest.as_megdnn(), opr.get(),
nullptr);
}
TensorLayoutArray Elemwise::collective_collapse(
const TensorLayoutArray& layouts) {
TensorLayoutPtrArray inp(layouts.size());
TensorLayoutArray result(inp.size());
for (size_t i = 0; i < layouts.size(); ++ i) {
result[i] = layouts[i];
inp[i] = &result[i];
}
collective_collapse_inplace(inp);
return result;
}
void Elemwise::collective_collapse_inplace(
const TensorLayoutPtrArray& layouts) {
mgb_assert(layouts.size());
size_t ndim = layouts[0]->ndim;
for (auto i: layouts) {
if (i->ndim != ndim)
mgb_throw(MegBrainError, "ndims must be same");
}
auto update_all = [&layouts](size_t axis) {
for (auto i: layouts) {
i->shape[axis] *= i->shape[axis + 1];
i->stride[axis] = i->stride[axis + 1];
i->remove_axis_inplace(axis + 1);
}
};
auto check = [&layouts](size_t axis) -> bool {
auto std_p = std::make_pair(
layouts[0]->shape[axis], layouts[0]->shape[axis + 1]);
for (auto i: layouts) {
auto cur_p = std::make_pair(i->shape[axis], i->shape[axis + 1]);
if (std_p != cur_p) return false;
if (i->stride[axis] != i->stride[axis + 1] *
static_cast<ptrdiff_t>(i->shape[axis+1]) )
return false;
}
return true;
};
for (int i = static_cast<int>(ndim) - 2; i >= 0; i--) {
if (check(i)) {
update_all(i);
}
}
}
void Elemwise::broadcast_collective_collapse(
const TensorLayoutPtrArray &inp_layouts, TensorLayout *target_layout) {
for (auto &&p: inp_layouts) {
*p = p->broadcast(*target_layout);
}
TensorLayoutPtrArray buf(inp_layouts.size() + 1);
buf[0] = target_layout;
for (size_t i = 0; i < inp_layouts.size(); i++) {
buf[i+1] = inp_layouts[i];
}
collective_collapse_inplace(buf);
}
void Elemwise::mem_plan_fwd_in2out_writable() {
mixin_mem_plan_fwd_in2out_writable(*this);
}
void Elemwise::scn_do_execute() {
auto&& inp = input();
megdnn::TensorNDArray dnn_inp;
mgb_assert(dnn_inp.capacity() >= inp.size(),
"heap allocation in elemwise exec");
dnn_inp.resize(inp.size());
for (size_t i = 0; i < inp.size(); ++i) {
if (inp[i]->dev_tensor().empty()) {
mgb_assert(output(0)->dev_tensor().empty());
return;
}
dnn_inp[i] = (inp[i]->dev_tensor().as_megdnn());
}
mgb_assert(!output(0)->dev_tensor().empty());
megdnn_opr()->param() = param();
call_megdnn_opr_exec(comp_node(), dnn_inp,
output(0)->dev_tensor().as_megdnn(), megdnn_opr(),
this);
}
void Elemwise::init_output_static_infer_desc() {
Super::init_output_static_infer_desc();
static StaticInferOpr<megdnn::Elemwise> static_infer_opr;
using namespace cg::static_infer;
auto infer_value = [this](DeviceTensorND &dest, const InpVal &inp) {
SmallVector<DeviceTensorND> inp_vals(inp.val.size());
for (size_t i = 0; i < inp_vals.size(); ++ i)
inp_vals[i] = inp.val[i].value();
auto sopr = static_infer_opr.lock();
perform(param().mode, dest, inp_vals, sopr());
return true;
};
DepVal deps(input().size());
for (size_t i = 0; i < input().size(); ++ i)
deps[i] = {input(i), DepType::VALUE};
owner_graph()->static_infer_manager().register_value_infer(
output(0), {SourceType::DEP, deps, infer_value});
}
void Elemwise::get_output_var_shape(
const TensorShapeArray &inp_shape, TensorShapeArray &out_shape) const {
out_shape.at(0) = get_output_var_shape(param().mode, inp_shape);
for (size_t i = 0; i < input().size(); ++ i) {
mgb_throw_if(!m_input_broadcastable[i] &&
!out_shape[0].eq_shape(inp_shape[i]), GraphError,
"input %zu declared to be non-broadcastable but broacast "
"actually happened", i);
}
}
void Elemwise::add_input_layout_constraint() {
for (auto i: input()) {
i->add_layout_constraint_monotone();
}
}
void Elemwise::call_megdnn_opr_exec(
CompNode comp_node,
megdnn::TensorNDArray &inp, const megdnn::TensorND &out,
megdnn::Elemwise *opr, Elemwise *caller) {
if (opr->param().mode == Mode::FUSE_MUL_ADD3 &&
!(inp[2].layout.eq_layout(inp[0].layout) ||
inp[2].layout.eq_layout(inp[1].layout) ||
inp[2].layout.is_scalar())) {
if (caller && !caller->fuse_badlayout_warn_printed()) {
mgb_log_debug("%s: FUSE_MUL_ADD3 input layouts mismatch: %s %s %s; "
"fallback to normal computing",
caller->cname(),
inp[0].layout.to_string().c_str(),
inp[1].layout.to_string().c_str(),
inp[2].layout.to_string().c_str()
);
caller->m_fuse_badlayout_warn_printed = true;
}
for (auto &&i: inp) {
i.layout = i.layout.broadcast(out.layout);
}
megdnn::TensorNDArray run_inp(2);
auto run = [&](Mode mode,
const megdnn::TensorND &i0, const megdnn::TensorND &i1,
const megdnn::TensorND &out) {
run_inp[0] = i0;
run_inp[1] = i1;
opr->param() = {mode};
opr->exec(run_inp, out);
};
auto tmp =
intl::get_temp_tensor(caller ? caller->owner_graph() : nullptr,
comp_node, out.layout);
auto tmpv = tmp.as_megdnn();
MGB_TRY {
run(Mode::MUL, inp[0], inp[1], tmpv);
run(Mode::ADD, inp[2], tmpv, out);
} MGB_FINALLY(opr->param() = {Mode::FUSE_MUL_ADD3});
return;
}
if (opr->param().mode == Mode::FUSE_MUL_ADD4 &&
!(inp[0].layout.eq_layout(inp[2].layout) &&
inp[1].layout.eq_layout(inp[3].layout)) &&
!(inp[0].layout.eq_layout(inp[3].layout) &&
inp[1].layout.eq_layout(inp[2].layout))) {
if (caller && !caller->fuse_badlayout_warn_printed()) {
mgb_log_debug(
"%s: FUSE_MUL_ADD4 input layouts mismatch: %s %s %s %s; "
"fallback to normal computing",
caller->cname(),
inp[0].layout.to_string().c_str(),
inp[1].layout.to_string().c_str(),
inp[2].layout.to_string().c_str(),
inp[3].layout.to_string().c_str()
);
caller->m_fuse_badlayout_warn_printed = true;
}
for (auto &&i: inp) {
i.layout = i.layout.broadcast(out.layout);
}
megdnn::TensorNDArray run_inp(2);
auto run = [&](Mode mode,
const megdnn::TensorND &i0, const megdnn::TensorND &i1,
const megdnn::TensorND &out) {
run_inp[0] = i0;
run_inp[1] = i1;
opr->param() = {mode};
opr->exec(run_inp, out);
};
auto tmp =
intl::get_temp_tensor(caller ? caller->owner_graph() : nullptr,
comp_node, out.layout);
auto tmpv = tmp.as_megdnn();
MGB_TRY {
run(Mode::MUL, inp[0], inp[1], tmpv);
run(Mode::MUL, inp[2], inp[3], out);
run(Mode::ADD, out, tmpv, out);
} MGB_FINALLY(opr->param() = {Mode::FUSE_MUL_ADD4});
return;
}
// All Elemwise operations on QuantizedS32/QuantizedS8 are not related to
// scale. MegDNN does not support computing Elemwise for
// QuantizedS32/QuantizedS8, we translate the data type to Int32/Int8 before
// passing to MegDNN.
if (inp.size() &&
inp[0].layout.dtype.category() == DTypeCategory::QUANTIZED) {
auto inp_dtype = inp[0].layout.dtype;
DType compute_dtype;
if (inp_dtype.enumv() == DTypeEnum::QuantizedS32) {
compute_dtype = dtype::Int32();
} else if (inp_dtype.enumv() == DTypeEnum::QuantizedS8) {
compute_dtype = dtype::Int8();
} else {
mgb_throw(MegBrainError,
"Unsupported Quantized Elemwise Mode %s: %d on %s",
inp[0].layout.dtype.name(), int(opr->param().mode),
comp_node.to_string().c_str());
}
megdnn::TensorNDArray run_inp(inp);
for (size_t i = 0; i < inp.size(); i++) {
run_inp[i].layout.dtype = compute_dtype;
}
megdnn::TensorND run_out = out;
run_out.layout.dtype = compute_dtype;
opr->exec(run_inp, run_out);
return;
}
opr->exec(inp, out);
}
#if MGB_ENABLE_GRAD
MGB_IMPL_OPR_GRAD(Elemwise) {
SymbolVar i[5];
SymbolVar i0(opr.input(0)), i1, i2, out(opr.output(0)),
og{out_grad.at(0)}, result;
for (size_t t = 0; t < opr.input().size(); ++ t)
i[t] = opr.input()[t];
if (opr.input().size() >= 2)
i1 = opr.input(1);
if (opr.input().size() >= 3)
i2 = opr.input(2);
// negate after reduce, for better performance
bool negate_result = false;
#define RET(_v) result = (_v); break
#define EL1(_mode, _a) Elemwise::make({_a}, Mode::_mode)
#define EL2(_mode, _a, _b) Elemwise::make({_a, _b}, Mode::_mode)
#define EL3(_mode, _a, _b, _c) Elemwise::make({_a, _b, _c}, Mode::_mode)
#define RET_INVALID() return InvalidGrad::make(opr, wrt_idx)
using Mode = Elemwise::Mode;
switch (opr.param().mode) {
// unary
case Mode::RELU:
case Mode::FUSE_ADD_RELU:
RET(EL2(SWITCH_GT0, out, og));
case Mode::ABS:
RET(EL2(ABS_GRAD, i0, og));
case Mode::ACOS:
negate_result = true;
RET(og / EL1(SIN, out));
case Mode::ASIN:
RET(og / EL1(COS, out));
case Mode::ATAN2:
if (wrt_idx) {
negate_result = true;
}
RET(og * i[!wrt_idx] / (i0 * i0 + i1 * i1));
case Mode::CEIL:
return nullptr;
case Mode::COS:
negate_result = true;
RET(EL1(SIN, i0) * og);
case Mode::EXP:
RET(og * out);
case Mode::EXPM1:
RET(og * EL1(EXP, i0));
case Mode::FLOOR:
return nullptr;
case Mode::LOG:
RET(og / i0);
case Mode::LOG1P:
RET(og / (i0 + 1));
case Mode::NEGATE:
negate_result = true;
RET(og);
case Mode::SIGMOID:
case Mode::FUSE_ADD_SIGMOID:
RET(EL2(SIGMOID_GRAD, out, og));
case Mode::SIN:
RET(EL1(COS, i0) * og);
case Mode::TANH:
case Mode::FUSE_ADD_TANH:
RET(EL2(TANH_GRAD, out, og));
case Mode::FAST_TANH:
RET(EL2(FAST_TANH_GRAD, i0, og));
case Mode::ROUND:
return nullptr;
case Mode::ERF:
RET(EL1(EXP, - i0 * i0) * 2 / static_cast<float>(sqrt(M_PI)) * og);
case Mode::ERFINV:
RET(EL1(EXP, out * out) * static_cast<float>(sqrt(M_PI)) / 2 * og);
case Mode::ERFC:
RET(-EL1(EXP, -i0 * i0) * 2 / static_cast<float>(sqrt(M_PI)) * og);
case Mode::H_SWISH:
RET(EL2(H_SWISH_GRAD, i0, og));
case Mode::FUSE_ADD_H_SWISH:
RET(EL2(H_SWISH_GRAD, (i0 + i1), og));
case Mode::NOT:
return nullptr;
// binary
case Mode::ABS_GRAD:
if (wrt_idx == 0) {
return nullptr;
}
RET(EL2(ABS_GRAD, i0, og));
case Mode::ADD:
RET(og);
case Mode::FLOOR_DIV:
return nullptr;
case Mode::MAX:
RET(EL3(COND_LEQ_MOV, i[!wrt_idx], i[wrt_idx], og));
case Mode::MIN:
RET(EL3(COND_LEQ_MOV, i[wrt_idx], i[!wrt_idx], og));
case Mode::MOD:
if (wrt_idx == 0) {
RET(og);
}
RET_INVALID();
case Mode::MUL:
RET(og * i[!wrt_idx]);
case Mode::POW:
if (wrt_idx) {
RET(out * EL1(LOG, i0) * og);
}
RET(og * i1 * EL2(POW, i0, i1 - 1));
case Mode::SIGMOID_GRAD:
if (wrt_idx == 0) {
auto one = i0.make_scalar_dt(1), two = i0.make_scalar_dt(2);
RET((one - i0 * two) * i1 * og);
}
RET(EL2(SIGMOID_GRAD, i0, og));
case Mode::SUB:
negate_result = wrt_idx;
RET(og);
case Mode::SWITCH_GT0:
if (!wrt_idx)
return nullptr;
RET(EL2(SWITCH_GT0, i0, og));
case Mode::TANH_GRAD:
if (wrt_idx == 0) {
auto mtwo = i0.make_scalar_dt(-2);
RET(mtwo * i0 * i1 * og);
}
RET(EL2(TANH_GRAD, i0, og));
case Mode::TRUE_DIV:
if (wrt_idx == 0) {
RET(og / i1);
}
negate_result = true;
RET((og * i0) * EL2(POW, i1, i1.make_scalar(-2)));
case Mode::LOG_SUM_EXP:
if (wrt_idx == 0) {
RET(og * EL1(SIGMOID, i0 - i1));
}
RET(og * EL1(SIGMOID, i1 - i0));
case Mode::LT:
case Mode::LEQ:
return nullptr;
case Mode::EQ:
RET_INVALID();
case Mode::OR:
case Mode::XOR:
case Mode::AND:
return nullptr;
// ternary
case Mode::COND_LEQ_MOV:
if (wrt_idx <= 1)
return nullptr;
RET(EL3(COND_LEQ_MOV, i0, i1, og));
// fuse oprs
case Mode::FUSE_MUL_ADD3:
if (wrt_idx < 2) {
RET(og * i[wrt_idx ^ 1]);
} else {
RET(og);
}
case Mode::FUSE_MUL_ADD4:
RET(og * i[wrt_idx ^ 1]);
default:
mgb_throw(GraphError, "grad for elemwise mode %s unimplemented",
megdnn::Elemwise::ModeTrait::from_mode(
opr.param().mode).name);
}
#undef EL3
#undef EL2
#undef EL1
#undef RET
if (opr.input_broadcastable()[wrt_idx]) {
result = reduce_sum(result,
opr::GetVarShape::make(opr.input(wrt_idx)));
} else if (result.node()->owner_opr()->same_type<Broadcast>()) {
// forward broadcast for optimizer to work
result = opr::Broadcast::make(result.node()->owner_opr()->input(0),
opr::GetVarShape::make(i[wrt_idx]));
}
if (negate_result)
result = -result;
return result.node();
}
#endif
VarNode* Elemwise::sum_grad_list(VarNode *wrt, VarNodeArray &grads) {
mgb_assert(!grads.empty());
if (grads.size() == 1)
return grads[0];
#if MGB_ENABLE_COND_EXEC
CondExecMerge::modify_grad_sum_list(wrt, grads);
#endif
VarNodeArray mid_results;
VarNode *ret;
if (wrt->owner_graph()->options().graph_opt_level) {
ret = gopt::GradSumListOptimizer{wrt, grads, mid_results}.get_sum();
} else {
ret = gopt::elemwise_reduce_var_list(
grads, Elemwise::Mode::ADD, &mid_results);
}
mid_results.swap(grads);
return ret;
}
void Elemwise::record_execute_deps(ExecDependencyArray& deps) {
record_megdnn_opr(deps);
}
Elemwise::NodeProp* Elemwise::do_make_node_prop() const {
auto ret = Super::do_make_node_prop();
for (auto& inp : input()) {
ret->add_dep_type_existing_var(inp,
NodeProp::DepType::VALUE_ALLOW_EMPTY);
}
return ret;
}
/* =========================== TypeCvt =========================== */
MGB_DYN_TYPE_OBJ_FINAL_IMPL(TypeCvt);
TypeCvt::TypeCvt(
VarNode *inp, DType dest_type, const OperatorNodeConfig &config):
Super{inp->owner_graph(), config, std::string("as") + dest_type.name(),
{inp}}
{
init_megdnn_opr(*this, {});
mgb_assert(dest_type.valid());
add_input({inp});
add_equivalence_component<ScalarHash<const void*>>(dest_type.handle());
output(0)->dtype(dest_type).add_flag(VarNode::Flag::ALLOW_EMPTY_SHAPE);
}
SymbolVar TypeCvt::make(
SymbolVar input, DType dest_type, const OperatorNodeConfig &config) {
if (input.dtype() == dest_type)
return input;
return input.insert_single_output_opr<TypeCvt>(
input.node(), dest_type, config);
}
void TypeCvt::perform(DeviceTensorND &dest,
DType dest_type, const DeviceTensorND &src,
intl::UniqPtrWithCN<megdnn::TypeCvt> &opr) {
mgb_assert(src.comp_node() == opr.comp_node());
mgb_assert(dest_type.valid());
if (src.empty()) {
mgb_assert(dest.empty());
return;
}
if (src.dtype() == dest_type) {
dest.copy_from(src);
return;
}
src.comp_node().activate();
dest.comp_node(src.comp_node()).dtype(dest_type).resize(src.shape());
opr->exec(src.as_megdnn(), dest.as_megdnn());
}
void TypeCvt::add_input_layout_constraint() {
for (auto i: input()) {
i->add_layout_constraint_contiguous();
}
}
TypeCvt::NodeProp* TypeCvt::do_make_node_prop() const {
auto ret = Super::do_make_node_prop();
ret->add_dep_type_existing_var(input(0),
NodeProp::DepType::VALUE_ALLOW_EMPTY);
return ret;
}
#if MGB_ENABLE_GRAD
MGB_IMPL_OPR_GRAD(TypeCvt) {
MGB_MARK_USED_VAR(wrt_idx);
auto itype = opr.input(0)->dtype(), otype = opr.output(0)->dtype();
if (itype.category() == DTypeCategory::FLOAT &&
otype.category() == DTypeCategory::INT) {
return nullptr;
}
if (itype.category() != DTypeCategory::FLOAT) {
return InvalidGrad::make(opr, 0);
}
return TypeCvt::make(out_grad[0], opr.input(0)->dtype()).node();
}
#endif
void TypeCvt::mem_plan_fwd_in2out_writable() {
bool cond_low_bit =
input(0)->dtype().is_low_bit() && output(0)->dtype().is_low_bit() &&
input(0)->dtype().low_bit() == output(0)->dtype().low_bit();
bool cond_normal = !input(0)->dtype().is_low_bit() &&
!output(0)->dtype().is_low_bit() &&
input(0)->dtype().size() == output(0)->dtype().size();
if ((cond_low_bit || cond_normal) && input(0)->layout().is_contiguous()) {
output(0)->set_fwd_in2out_writable(input(0));
}
}
void TypeCvt::scn_do_execute() {
auto ovar = output(0)->dev_tensor().as_megdnn();
for (size_t i = 0; i < ovar.layout.ndim; ++i) {
if (!ovar.layout[i]) {
// skip execution for empty var
return;
}
}
megdnn_opr()->exec(input(0)->dev_tensor().as_megdnn(), ovar);
}
void TypeCvt::init_output_static_infer_desc() {
static StaticInferOpr<megdnn::TypeCvt> static_infer_opr;
Super::init_output_static_infer_desc();
using namespace cg::static_infer;
auto infer_value = [this](DeviceTensorND &dest, const InpVal &inp) {
auto sopr = static_infer_opr.lock();
perform(dest, output(0)->dtype(), inp.val.at(0).value(), sopr());
return true;
};
owner_graph()->static_infer_manager().register_value_infer(
output(0), {SourceType::DEP, {{input(0), DepType::VALUE}},
infer_value});
}
void TypeCvt::record_execute_deps(ExecDependencyArray& deps) {
record_megdnn_opr(deps);
}
/* =========================== AddUpdate =========================== */
MGB_DYN_TYPE_OBJ_FINAL_IMPL(AddUpdate);
AddUpdate::AddUpdate(VarNode *dest, VarNode *delta,
const Param ¶m,
const OperatorNodeConfig &config):
Super{dest->owner_graph(), config, "inplace_add", {dest, delta}},
m_param{param}
{
auto dest_opr = dest->owner_opr();
mgb_throw_if(dest_opr->same_type<ImmutableTensor>(),
GraphError,
"AddUpdate cannot be applied on ImmutableTensor; ");
add_input({dest, delta});
/*
* here we tell the system that output(0) would force-update input(0); the
* topo-sorting system would ensure that all the readers finish before
* executing this AddUpdate operation
*/
add_output(None)->
set_fwd_in2out_writable_force(input(0)).
add_flag(VarNode::Flag::NO_MEM_RECLAIM);
mgb_assert(m_param.disable->dtype() == dtype::Int32{},
"dtype of disable flag on AddUpdate must be Int32, got %s actually.",
m_param.disable->dtype().name());
add_equivalence_component<ScalarHash<void*>>(m_param.alpha.get());
add_equivalence_component<ScalarHash<void*>>(m_param.beta.get());
add_equivalence_component<ScalarHash<void*>>(m_param.bias.get());
add_equivalence_component<ScalarHash<void*>>(m_param.disable.get());
}
SymbolVar AddUpdate::make(SymbolVar dest, SymbolVar delta,
const Param ¶m, const OperatorNodeConfig &config) {
delta = opr::TypeCvt::make(delta, dest.dtype());
return dest.insert_single_output_opr<AddUpdate>(
dest.node(), delta.node(), param, config);
}
cg::OperatorNodeBase::NodeProp* AddUpdate::do_make_node_prop() const {
auto ret = Super::do_make_node_prop();
ret->add_flag(NodeProp::Flag::FORCE_UPDATE_INPUT_VAR);
return ret;
}
void AddUpdate::create_megdnn_opr() {
set_megdnn_opr(intl::get_megdnn_handle(comp_node())->
create_operator<megdnn::AddUpdate>());
}
void AddUpdate::scn_do_execute() {
mgb_assert(m_param.disable->dtype() == dtype::Int32{},
"dtype of disable flag on AddUpdate must be Int32, got %s actually.",
m_param.disable->dtype().name());
auto disable = m_param.disable->get_cast<int>();
if(disable == 1) return;
mgb_assert(disable == 0, "disable flag on AddUpdate can only be 0 or 1,"
" got %d actually.", disable);
auto &&dest = output(0)->dev_tensor();
auto &&delta_nobrd = input(1)->dev_tensor();
auto delta = delta_nobrd.sub(SubTensorSpec::make_from_offset_elem(
delta_nobrd.layout().broadcast(dest.shape()), 0));
mgb_assert(input(0)->dev_tensor().raw_ptr() == dest.raw_ptr());
auto beta = m_param.beta->get_cast<float>();
if (!m_param.alpha->get_cast<bool>() && beta == 1 &&
!m_param.bias->get_cast<bool>()) {
dest.copy_from_fixlayout(delta);
} else {
auto opr = static_cast<megdnn::AddUpdate*>(megdnn_opr());
opr->param() = {
m_param.alpha->get_cast<float>(),
beta,
m_param.bias->get_cast<float>()};
opr->exec(dest.as_megdnn(), delta.as_megdnn());
}
}
void AddUpdate::init_output_static_infer_desc() {
using namespace cg::static_infer;
owner_graph()->static_infer_manager().register_shape_infer(
output(0), ShapeInferDesc::make_identity(input(0)));
}
void AddUpdate::record_execute_deps(ExecDependencyArray& deps) {
record_megdnn_opr(deps);
}
#if MGB_ENABLE_GRAD
MGB_IMPL_OPR_GRAD(AddUpdate) {
// actually valid, just not implemented
return InvalidGrad::make(opr, wrt_idx);
}
#endif
/* =========================== Reduce =========================== */
class Reduce::KernScheduler {
class ValueDep final : public ExecDependency {
DeviceTensorStorage m_val;
public:
explicit ValueDep(DeviceTensorStorage val) : m_val(std::move(val)) {}
};
public:
bool has_actual_computing() const {
mgb_assert(m_shape_computed);
return !m_kern_param.empty() || m_apply_side_effect;
}
size_t workspace_size() const {
return m_workspace_spec[2].end();
}
bool shape_computed() const {
return m_shape_computed;
}
//! init shapes in kern param
void init_shapes(
megdnn::Reduce *opr, CompNode comp_node, DType dtype, Mode mode,
TensorShape ishp, TensorShape oshp, const Param::DataType data_type);
void setup_kern_params_layout_and_mode(Mode mode, DType inp_dtype,
TensorShape& inp_shp,
const Param::DataType);
void check_shapes(const TensorShape &ishp, const TensorShape &oshp) {
mgb_assert(m_prev_ishp.eq_shape(ishp) &&
m_prev_oshp.eq_shape(oshp));
}
//! update pointers in kern param; the tensors must have been allocated
void update_ptr(
const DeviceTensorND &input, const DeviceTensorND &dest,
const DeviceTensorND &workspace);
void execute(megdnn::Reduce *opr,
const DeviceTensorND &input, const DeviceTensorND &dest);
void record_execute_deps(ExecDependencyArray& deps) {
if (m_elemwise_trans_opr) {
deps.emplace_back(std::make_unique<intl::MegDNNGraphDep>(
std::move(m_elemwise_trans_opr)));
}
if (m_typecvt_opr) {
deps.emplace_back(std::make_unique<intl::MegDNNGraphDep>(
std::move(m_typecvt_opr)));
}
deps.emplace_back(
std::make_unique<ValueDep>(m_side_affect_wkspc.storage()));
}
private:
struct KernParam {
megdnn::TensorND input, output;
//! param passed to megdnn
megdnn::param::Reduce kparam;
megdnn::Workspace workspace;
KernParam(Mode mode, int32_t ra):
kparam{mode, ra}
{
}
};
struct SubWorkspace {
size_t size, offset;
size_t end() const {
return size + offset;
}
};
void update_kparam_for_elemwise_side_effect(
CompNode comp_node, Mode mode, const Param::DataType data_type);
bool m_shape_computed = false;
std::vector<KernParam> m_kern_param;
TensorShape m_prev_ishp, m_prev_oshp;
SubWorkspace m_workspace_spec[3]; //! tmp output[2], kern workspce
/*!
* some reduce mode (like SUM_SQR) has side effect of element-wise
* trans. If this is the case and there is no kernel param,
* m_apply_side_effect would be non-null
*/
thin_function<void(const DeviceTensorND &in,
const DeviceTensorND &out)>
m_apply_side_effect;
std::unique_ptr<megdnn::Elemwise> m_elemwise_trans_opr;
std::unique_ptr<megdnn::TypeCvt> m_typecvt_opr;
DeviceTensorND m_side_affect_wkspc;
};
void Reduce::KernScheduler::setup_kern_params_layout_and_mode(Mode mode,
DType inp_dtype,
TensorShape& ishp,
const Param::DataType data_type) {
auto prev_dtype = inp_dtype;
for (size_t idx = 0; idx < m_kern_param.size(); ++idx) {
auto&& i = m_kern_param[idx];
#if !MEGDNN_DISABLE_FLOAT16
if (idx == 0 && data_type == Param::DataType::FLOAT_O32xC32) {
i.input.layout.dtype = inp_dtype;
i.output.layout.dtype = dtype::Float32();
i.kparam.data_type = data_type;
} else if (data_type == Param::DataType::FLOAT_O16xC32) {
i.input.layout.dtype = prev_dtype;
if (idx + 1 == m_kern_param.size()) {
i.output.layout.dtype = dtype::Float16();
i.kparam.data_type = data_type;
}
else {
i.output.layout.dtype = dtype::Float32();
i.kparam.data_type = Param::DataType::FLOAT_O32xC32;
}
} else
#endif
{
mgb_assert(data_type == Param::DataType::DEFAULT || (
data_type == Param::DataType::FLOAT_O32xC32 &&
idx));
i.input.layout.dtype = prev_dtype;
i.output.layout.dtype = prev_dtype;
i.kparam.data_type = Param::DataType::DEFAULT;
}
prev_dtype = i.output.layout.dtype;
i.input.layout.init_contiguous_stride(ishp);
ishp.shape[i.kparam.axis] = 1;
i.output.layout.init_contiguous_stride(ishp);
}
if (mode == Mode::SUM_SQR) {
for (size_t i = 1; i < m_kern_param.size(); ++ i)
m_kern_param[i].kparam.mode = Mode::SUM;
}
}
void Reduce::KernScheduler::init_shapes(
megdnn::Reduce *opr, CompNode comp_node, DType inp_dtype, Mode mode,
TensorShape ishp, TensorShape oshp, const Param::DataType data_type) {
mgb_assert(ishp.ndim && oshp.ndim);
if (ishp.eq_shape(m_prev_ishp) && oshp.eq_shape(m_prev_oshp))
return;
m_prev_ishp = ishp;
m_prev_oshp = oshp;
m_kern_param.clear();
if (oshp.is_scalar()) {
// if ishp is non-contiguous, add_layout_constraint_contiguous would be
// added; so we do not have to worry about this
ishp.shape[0] = ishp.total_nr_elems();
ishp.ndim = 1;
}
mgb_assert(oshp.ndim == ishp.ndim,
"input and output ndim mismatch for reduction: ishp=%s oshp=%s",
ishp.to_string().c_str(), oshp.to_string().c_str());
for (size_t i = 0; i < ishp.ndim; ++ i) {
if (ishp.shape[i] != oshp.shape[i]) {
mgb_assert(oshp.shape[i] == 1,
"input and output shape mismatch for reduction: "
"ishp=%s oshp=%s",
ishp.to_string().c_str(), oshp.to_string().c_str());
}
}
auto remove_axis = [](TensorShape &shp, size_t ax) {
mgb_assert(shp.ndim > 1);
for (auto i = ax + 1; i < shp.ndim; ++ i)
shp.shape[i - 1] = shp.shape[i];
-- shp.ndim;
};
// collapse consecutive shape-1 axes in oshp
for (size_t i = 0; i < oshp.ndim; ++ i) {
auto start = i;
while (i < oshp.ndim && oshp.shape[i] == 1)
++ i;
if (start + 1 < i) {
for (auto j = start + 1; j < i; ++ j)
ishp.shape[start] *= ishp.shape[j];
for (auto j = start + 1; j < i; ++ j) {
remove_axis(ishp, start + 1);
remove_axis(oshp, start + 1);
}
i = start;
}
}
for (uint32_t i = 0; i < ishp.ndim; ++ i) {
if (ishp.shape[i] != oshp.shape[i]) {
mgb_assert(oshp.shape[i] == 1);
m_kern_param.push_back({mode, static_cast<int32_t>(i)});
}
}
// sort according to reduction size, so workspace can be smaller
small_sort(m_kern_param.begin(), m_kern_param.end(),
[&](const KernParam &a, const KernParam &b) {
return ishp.shape[a.kparam.axis] > ishp.shape[b.kparam.axis];
});
// init kparam input/output layout
setup_kern_params_layout_and_mode(mode, inp_dtype, ishp, data_type);
// init workspace size
memset(m_workspace_spec, 0, sizeof(m_workspace_spec));
for (auto&& i : m_kern_param) {
opr->param() = i.kparam;
i.workspace.size = opr->get_workspace_in_bytes(
i.input.layout, i.output.layout);
update_max(m_workspace_spec[2].size, i.workspace.size);
}
mgb_assert(ishp.eq_shape(oshp));
if (m_kern_param.size() >= 2) {
m_workspace_spec[0].size =
m_kern_param[1].input.layout.span().high_byte;
}
if (m_kern_param.size() >= 3) {
m_workspace_spec[1].size =
m_kern_param[2].input.layout.span().high_byte;
}
auto align = comp_node.get_mem_addr_alignment();
for (int i = 0; i < 2; ++ i) {
m_workspace_spec[i + 1].offset = get_aligned_power2(
m_workspace_spec[i].end(), align);
}
update_kparam_for_elemwise_side_effect(comp_node, mode, data_type);
m_shape_computed = true;
}
void Reduce::KernScheduler::update_kparam_for_elemwise_side_effect(
CompNode comp_node, Mode mode, const Param::DataType data_type) {
m_apply_side_effect = nullptr;
m_elemwise_trans_opr.reset();
m_typecvt_opr.reset();
if (!m_kern_param.empty()) {
// no need to set m_apply_side_effect
return;
} /* else */
// case A: input.layout == output.layout
// case B: input.total_nr_elems == 1 and output is a scalar
if (mode == Mode::SUM_SQR) {
m_elemwise_trans_opr = intl::get_megdnn_handle(comp_node)->
create_operator<megdnn::Elemwise>();
m_elemwise_trans_opr->param() = {Elemwise::Mode::MUL};
}
if (data_type != Param::DataType::DEFAULT) {
m_side_affect_wkspc = DeviceTensorND{comp_node, dtype::Float32()};
m_typecvt_opr = intl::get_megdnn_handle(comp_node)->
create_operator<megdnn::TypeCvt>();
}
if (!m_typecvt_opr && !m_elemwise_trans_opr)
return;
m_apply_side_effect = [this](const DeviceTensorND &in,
const DeviceTensorND &out) {
if (m_typecvt_opr) {
m_side_affect_wkspc.resize(in.shape());
}
if (!m_elemwise_trans_opr) {
mgb_assert(m_typecvt_opr);
m_typecvt_opr->exec(in.as_megdnn(), out.as_megdnn());
return;
}
auto im = in.as_megdnn();
megdnn::TensorND wm;
if (m_typecvt_opr && in.dtype() != m_side_affect_wkspc.dtype()) {
m_side_affect_wkspc.resize(in.shape());
wm = m_side_affect_wkspc.as_megdnn();
m_typecvt_opr->exec(im, wm);
} else {
wm = im;
}
if (m_typecvt_opr && wm.layout.dtype != out.dtype()) {
m_elemwise_trans_opr->exec({wm, wm}, wm);
m_typecvt_opr->exec(wm, out.as_megdnn());
} else {
auto &&wshp = wm.layout;
if (wshp.ndim != out.layout().ndim) {
// to ensure that wkspc.ndim equals out.ndim in the case:
// wkspc.shape=(1, 1, ..., 1) and out.shape=(1), otherwise it
// may lead the 'TensorShape Dimension' assertion failed in
// the following broadcast operator
mgb_assert(wshp.total_nr_elems() == 1 && out.layout().ndim == 1);
wshp.ndim = 1;
}
m_elemwise_trans_opr->exec({wm, wm}, out.as_megdnn());
}
};
}
void Reduce::KernScheduler::update_ptr(
const DeviceTensorND &input, const DeviceTensorND &dest,
const DeviceTensorND &workspace) {
auto dtype = dest.layout().dtype;
mgb_assert(dtype.valid());
mgb_assert(m_shape_computed);
if (workspace_size()) {
mgb_assert(workspace.layout().dtype == dtype::Byte() &&
workspace.layout().ndim == 1 &&
workspace.shape()[0] >= workspace_size());
}
if (m_kern_param.empty())
return;
mgb_assert(input.layout().total_nr_elems() ==
m_kern_param[0].input.layout.total_nr_elems());
mgb_assert(dest.shape().total_nr_elems() ==
m_kern_param.back().output.layout.total_nr_elems());
m_kern_param[0].input.raw_ptr = const_cast<dt_byte*>(input.raw_ptr());
dt_byte
*workspace_begin = workspace_size() ?
const_cast<dt_byte*>(workspace.raw_ptr()) : nullptr,
*tmp_reduce_ptr[2] = {
workspace_begin + m_workspace_spec[0].offset,
workspace_begin + m_workspace_spec[1].offset},
*kern_workspace = workspace_begin + m_workspace_spec[2].offset;
for (size_t i = 0; i < m_kern_param.size() - 1; ++ i) {
auto optr = tmp_reduce_ptr[i % 2];
m_kern_param[i].output.raw_ptr = optr;
m_kern_param[i + 1].input.raw_ptr = optr;
}
for (auto &&i: m_kern_param)
i.workspace.raw_ptr = kern_workspace;
m_kern_param.back().output.raw_ptr = const_cast<dt_byte*>(dest.raw_ptr());
}
void Reduce::KernScheduler::execute(
megdnn::Reduce *opr,
const DeviceTensorND &input, const DeviceTensorND &dest) {
if (m_apply_side_effect) {
mgb_assert(m_kern_param.empty());
m_apply_side_effect(input, dest);
return;
}
mgb_assert(!m_kern_param.empty());
mgb_assert(input.layout().is_contiguous() &&
input.raw_ptr() == m_kern_param[0].input.raw_ptr &&
dest.raw_ptr() == m_kern_param.back().output.raw_ptr);
for (auto &&i: m_kern_param) {
opr->param() = i.KernParam::kparam;
opr->exec(i.input, i.output, i.workspace);
}
}
class Reduce::OutTensorShapeExtender {
public:
OutTensorShapeExtender(const TensorShape& ishp, const TensorShape& oshp)
: m_oshp(oshp) {
mgb_assert(oshp.ndim <= ishp.ndim,
"output ndim should be less and equal than input ndim for "
"reduction: "
"ishp=%s oshp=%s",
ishp.to_string().c_str(), oshp.to_string().c_str());
// Ex. ishp = (a, b, c, d), oshp = (c, d)
if (!oshp.is_scalar() && ishp.ndim != oshp.ndim) {
size_t ndim_diff = ishp.ndim - oshp.ndim;
auto&& canonized_oshp = m_canonized_oshp_storage.emplace(oshp);
for (size_t i = 0; i < ishp.ndim; ++i)
if (i < ndim_diff)
canonized_oshp[i] = 1;
else
canonized_oshp[i] = oshp[i - ndim_diff];
canonized_oshp.ndim = ishp.ndim;
}
}
const TensorShape& get() const {
return m_canonized_oshp_storage.valid() ? m_canonized_oshp_storage.val()
: m_oshp;
}
private:
Maybe<TensorShape> m_canonized_oshp_storage;
const TensorShape& m_oshp;
};
MGB_DYN_TYPE_OBJ_FINAL_IMPL(Reduce);
Reduce::Reduce(VarNode *inp, VarNode *target_shape, const Param ¶m,
const OperatorNodeConfig &config):
Super{inp->owner_graph(), config,
ssprintf("reduce%d", static_cast<int>(param.mode)), {inp}},
m_param{param}, m_kern_scheduler{std::make_unique<KernScheduler>()}
{
add_input({inp});
if (inp->dtype().enumv() == DTypeEnum::Quantized8Asymm &&
inp->dtype().category() == DTypeCategory::QUANTIZED) {
mgb_assert(param.mode != Param::Mode::PRODUCT,
"Reduce does not support PRODUCT mode on quantized input");
mgb_assert(param.mode != Param::Mode::SUM_SQR,
"Reduce does not support SUM_SQR mode on quantized input");
mgb_assert(param.mode != Param::Mode::SUM,
"Reduce does not support SUM mode on quantized input");
}
DType out_dtype;
switch (param.data_type) {
case Param::DataType::DEFAULT:
out_dtype = inp->dtype();
break;
#if !MEGDNN_DISABLE_FLOAT16
case Param::DataType::FLOAT_O16xC32:
out_dtype = dtype::Float16();
break;
case Param::DataType::FLOAT_IO16xC32:
mgb_assert(false);
#endif
case Param::DataType::FLOAT_O32xC32:
out_dtype = dtype::Float32();
break;
case Param::DataType::QUINT_I8xO32:
out_dtype = dtype::QuantizedS32(
inp->dtype().param<dtype::Quantized8Asymm>().scale);
break;
case Param::DataType::QINT_I8xO32:
out_dtype = dtype::QuantizedS32(
inp->dtype().param<dtype::QuantizedS8>().scale);
break;
default:
mgb_throw(GraphError, "invalid param data_type: %d",
int(param.data_type));
}
add_output(None)->dtype(out_dtype);
cg::add_workspace_output(this);
add_equivalence_component<PODHash<Param>>(&m_param);
if (param.axis >= -MEGDNN_MAX_NDIM && param.axis < MEGDNN_MAX_NDIM) {
mgb_throw_if(target_shape, GraphError,
"could not specify both axis and target shape");
m_is_symtshp = false;
} else {
mgb_throw_if(!target_shape, GraphError,
"neither axis or target_shape specified");
add_input({target_shape});
m_is_symtshp = true;
outshape_by_symvar_enable(0, 1);
}
}
Reduce::~Reduce() = default;
SymbolVar Reduce::make(
SymbolVar src, Param param, SymbolVar target_shape,
const OperatorNodeConfig &config) {
if (param.data_type == Param::DataType::FLOAT_IO16xC32) {
mgb_log_warn("DataType FLOAT_IO16xC32 has been deprecated "
"use FLOAT_O16xC32 instead");
param.data_type = Param::DataType::FLOAT_O16xC32;
}
if (param.mode == Mode::SUM &&
src.node()->owner_opr()->same_type<Elemwise>()) {
// replace sum(x^2) by sum_sqr(x)
auto &&opr = src.node()->owner_opr()->cast_final<Elemwise>();
if (opr.param().mode == Elemwise::Mode::POW) {
mgb_assert(opr.input().size() == 2);
auto pow = SymbolVar{opr.input(1)}.as_immutable_scalar();
if (pow.valid() && pow->get_cast<float>() == 2) {
src = opr.input(0);
param.mode = Mode::SUM_SQR;
}
}
}
return src.insert_single_output_opr<Reduce>(
src.node(), target_shape.node(), param, config);
}
void Reduce::outshape_by_symvar_do_get_output_shape(
TensorShape &dest, const ShapeInferInfo &shpinfo) {
cg::copy_tensor_value_to_shape(dest, *shpinfo.shpval_inp_val.at(0));
}
void Reduce::init_output_static_infer_desc() {
using namespace cg::static_infer;
auto &&mgr = owner_graph()->static_infer_manager();
// infer output shape
if (m_is_symtshp) {
// reduce to target shape
Super::init_output_static_infer_desc();
} else {
// reduce along axis
auto infer_shape = [this](TensorShape &dest, const InpVal &inp) {
dest = inp.val.at(0).shape();
mgb_assert(m_param.axis < static_cast<int>(dest.ndim) &&
m_param.axis >= -static_cast<int>(dest.ndim),
"invalid axis for reduction: shape=%s axis=%d",
dest.to_string().c_str(), m_param.axis);
int real_axis = m_param.axis;
if (real_axis < 0)
real_axis += dest.ndim;
dest.shape[real_axis] = 1;
return true;
};
mgr.register_shape_infer(
output(0), {
SourceType::DEP, {{input(0), DepType::SHAPE}}, infer_shape});
}
// infer workspace
auto infer_workspace = [this](TensorShape &dest, const InpVal &inp) {
init_kern_sched_shape(inp.val[0].shape(), inp.val[1].shape());
dest.ndim = 1;
dest.shape[0] = m_kern_scheduler->workspace_size();
return true;
};
mgr.register_shape_infer(output(1),
{SourceType::DEP,
{{input(0), DepType::SHAPE}, {output(0), DepType::SHAPE}},
infer_workspace});
// infer value
static StaticInferOpr<megdnn::Reduce> static_infer_opr;
auto infer_value = [this](DeviceTensorND &dest, const InpVal &inp) {
DeviceTensorND workspace;
auto sopr = static_infer_opr.lock();
perform(m_param.mode, dest, workspace, inp.val[0].value(),
output(0)->dtype(), inp.val.at(1).shape(), sopr(),
m_param.data_type);
return true;
};
mgr.register_value_infer(output(0),
{SourceType::DEP,
{{input(0), DepType::VALUE}, {output(0), DepType::SHAPE}},
infer_value});
}
void Reduce::init_kern_sched_shape(const TensorShape& ishp,
const TensorShape& oshp) {
OutTensorShapeExtender extender(ishp, oshp);
auto&& canonized_oshp = extender.get();
m_kern_scheduler->init_shapes(static_cast<megdnn::Reduce*>(megdnn_opr()),
comp_node(), input(0)->dtype(), m_param.mode,
ishp, canonized_oshp, m_param.data_type);
}
cg::OperatorNodeBase::OprEventCallback Reduce::get_opr_event_callback() {
auto on_mem_status_changed = [this]() {
auto&& ishp = input(0)->shape();
auto&& oshp = output(0)->shape();
OutTensorShapeExtender extender(ishp, oshp);
auto&& canonized_oshp = extender.get();
m_kern_scheduler->check_shapes(input(0)->shape(), canonized_oshp);
m_kern_scheduler->update_ptr(
input(0)->dev_tensor(), output(0)->dev_tensor(),
output(1)->shape()[0] ? output(1)->dev_tensor()
: DeviceTensorND{});
};
return {on_mem_status_changed};
}
void Reduce::mem_plan_fwd_in2out_readonly() {
init_kern_sched_shape(input(0)->shape(), output(0)->shape());
if (!m_kern_scheduler->has_actual_computing()) {
// forward memory if no actual computing needed
if (!output(0)->mem_plan().valid()) {
// output(0) is dynamic but current is staic alloc phase (for
// workspace)
return;
}
auto&& ily = input(0)->layout();
auto&& oly = output(0)->layout();
const TensorLayout* fwd_spec = nullptr;
Maybe<TensorLayout> ily_modified_storage;
if (!ily.eq_shape(oly)) {
auto&& ily_modified = ily_modified_storage.emplace(ily);
mgb_assert(ily.ndim > oly.ndim);
for (size_t i = 0; i < ily.ndim - oly.ndim; ++i)
mgb_assert(ily.shape[i] == 1);
ily_modified = ily_modified.reshape(oly);
fwd_spec = &ily_modified;
} else {
fwd_spec = &ily;
}
m_mem_fwd_success = output(0)->set_fwd_in2out_readonly(
input(0), SubTensorSpec::make_from_layout(*fwd_spec));
}
}
void Reduce::add_input_layout_constraint() {
if (!cg::is_static_var_shape(output(0))) {
// output shape can not be inferred; require contiguous to be safe
input(0)->add_layout_constraint_contiguous();
} else {
auto check = [this](const TensorLayout &ily) {
auto &&mgr = owner_graph()->static_infer_manager();
auto oshp = mgr.infer_shape(output(0));
init_kern_sched_shape(ily, oshp);
if (m_kern_scheduler->has_actual_computing())
return ily.is_contiguous();
return true;
};
input(0)->add_layout_constraint(check);
}
}
void Reduce::scn_do_execute() {
auto&& inp = input(0)->dev_tensor();
auto&& out = output(0)->dev_tensor();
auto&& ishp = input(0)->shape();
auto&& oshp = output(0)->shape();
const DeviceTensorND* out_ptr;
Maybe<DeviceTensorND> canonized_storage;
OutTensorShapeExtender extender(ishp, oshp);
auto&& canonized_oshp = extender.get();
if (canonized_oshp.ndim != out.shape().ndim) {
auto&& canonized_out = canonized_storage.emplace(out);
canonized_out.reset(
canonized_out.storage(),
canonized_out.layout().reshape(canonized_oshp));
out_ptr = &canonized_out;
} else {
out_ptr = &out;
}
// shape initialized either in deducing workspace,
// mem_plan_fwd_in2out_readonly, or check input layout
m_kern_scheduler->check_shapes(inp.shape(), out_ptr->shape());
if (m_kern_scheduler->has_actual_computing()) {
m_kern_scheduler->execute(static_cast<megdnn::Reduce*>(megdnn_opr()),
inp, *out_ptr);
} else {
// no reduction needed, just forward
if (m_mem_fwd_success) {
mgb_assert(inp.raw_ptr() == out_ptr->raw_ptr() &&
out_ptr->layout().total_nr_elems() ==
inp.layout().total_nr_elems());
} else {
if (!out_ptr->shape().eq_shape(inp.shape())) {
mgb_assert(out_ptr->shape().is_scalar() &&
inp.shape().total_nr_elems() == 1);
out_ptr->sub(SubTensorSpec::make_from_layout(inp.layout()))
.copy_from_fixlayout(inp);
} else {
out_ptr->copy_from_fixlayout(inp);
}
}
}
}
void Reduce::perform(
Mode mode,
DeviceTensorND &dest, DeviceTensorND &workspace,
const DeviceTensorND &input,
const DType &target_dtype,
const TensorShape &target_shape,
intl::UniqPtrWithCN<megdnn::Reduce> &opr, const Param::DataType data_type) {
mgb_assert(!dest.storage().comp_node_valid() ||
opr.comp_node() == dest.comp_node());
KernScheduler ksched;
OutTensorShapeExtender extender(input.shape(), target_shape);
auto&& canonized_oshp = extender.get();
ksched.init_shapes(opr.get(), opr.comp_node(), input.layout().dtype,
mode, input.shape(), canonized_oshp, data_type);
if (!ksched.has_actual_computing()) {
mgb_assert(target_shape.total_nr_elems() ==
input.layout().total_nr_elems());
dest.copy_from(input);
dest.reset(dest.storage(), {target_shape, dest.dtype()});
return;
}
workspace.
comp_node(opr.comp_node()).
dtype(dtype::Byte());
size_t workspace_size = ksched.workspace_size();
DeviceTensorND input_contig_storage;
const DeviceTensorND *input_contig = &input;
if (!input.layout().is_contiguous()) {
auto offset = get_aligned_power2(
workspace_size, opr.comp_node().get_mem_addr_alignment());
workspace_size = offset +
input.dtype().size(input.shape().total_nr_elems());
workspace.resize({workspace_size});
input_contig_storage.
reset(workspace.storage().sub(offset), {
input.shape(), input.dtype()}).
copy_from(input);
input_contig = &input_contig_storage;
} else {
workspace.resize({workspace_size});
}
opr.comp_node().activate();
dest.comp_node(opr.comp_node()).dtype(target_dtype).resize(target_shape);
ksched.update_ptr(*input_contig, dest, workspace);
ksched.execute(opr.get(), *input_contig, dest);
}
void Reduce::create_megdnn_opr() {
set_megdnn_opr(intl::get_megdnn_handle(comp_node())->
create_operator<megdnn::Reduce>());
}
#if MGB_ENABLE_GRAD
MGB_IMPL_OPR_GRAD(Reduce) {
for (size_t i = 1; i < opr.output().size(); ++ i)
mgb_assert(!out_grad[i]);
if (wrt_idx || opr.input(0)->dtype().category() != DTypeCategory::FLOAT)
return InvalidGrad::make(opr, wrt_idx);
SymbolVar og{out_grad[0]}, iv{opr.input(0)}, ov{opr.output(0)};
constexpr auto cmv = Elemwise::Mode::COND_LEQ_MOV;
using Mode = Reduce::Mode;
SymbolVar grad = [&]() {
switch (opr.param().mode) {
case Mode::SUM:
return Broadcast::make(og, GetVarShape::make(iv));
case Mode::SUM_SQR:
return (og * og.make_scalar_dt(2) * iv);
case Mode::PRODUCT:
return ((og * ov) / iv);
case Mode::MIN:
return Elemwise::make({iv, ov, og}, cmv);
case Mode::MAX:
return Elemwise::make({ov, iv, og}, cmv);
case Mode::MEAN: {
auto og_shape = opr::GetVarShape::make(og),
iv_shape = opr::GetVarShape::make(iv),
scale = div(
opr::reduce_prod(og_shape, og_shape.make_scalar(1)),
opr::reduce_prod(iv_shape, iv_shape.make_scalar(1)));
return scale * Broadcast::make(og, GetVarShape::make(iv));
}
default:
mgb_throw(MegBrainError, "bad reduce mode");
}
}();
grad = TypeCvt::make(grad, iv.dtype());
return grad.node();
}
#endif
void Reduce::record_execute_deps(ExecDependencyArray& deps) {
record_megdnn_opr(deps);
m_kern_scheduler->record_execute_deps(deps);
}
/* =========================== PowC =========================== */
MGB_DYN_TYPE_OBJ_FINAL_IMPL(PowC);
PowC::PowC(VarNode *i0, const Param ¶m, const OperatorNodeConfig &config)
: Super(OperatorNodeBaseCtorParam{ i0->owner_graph(), config, ssprintf("powc_%g", param.exp), {i0}} ) {
init_megdnn_opr(*this, param);
add_input({i0});
output(0)->add_flag(VarNode::Flag::ALLOW_EMPTY_SHAPE);
intl::MegDNNOprInitPostCtor<PowC>::apply(*this);
}
SymbolVar PowC::make(SymbolVar x, const Param& param,
const OperatorNodeConfig& config) {
if (almost_equal(param.exp, 1.f)) {
return x;
}
if (almost_equal(param.exp, 0.f)) {
return x.make_scalar_dt(1).broadcast(x.symshape());
}
return x.insert_single_output_opr<PowC>(x.node(), param, config);
}
void PowC::add_input_layout_constraint() {
input(0)->add_layout_constraint_monotone();
}
void PowC::mem_plan_fwd_in2out_writable() {
output(0)->set_fwd_in2out_writable(input(0));
}
void PowC::init_output_static_infer_desc() {
Super::init_output_static_infer_desc();
static StaticInferOpr<megdnn::PowC> static_infer_opr;
using namespace cg::static_infer;
auto infer_value = [this](DeviceTensorND& dest, const InpVal& inp) {
auto infer_opr_lock = static_infer_opr.lock();
auto&& infer_opr = infer_opr_lock();
infer_opr->param() = this->param();
auto&& ival = inp.val[0].value().as_megdnn();
infer_opr->exec(ival, dest.resize(ival.layout).as_megdnn());
return true;
};
owner_graph()->static_infer_manager().register_value_infer(
output(0),
{SourceType::DEP, {{input(0), DepType::VALUE}}, infer_value});
}
void PowC::scn_do_execute() {
if (input(0)->dev_tensor().empty()) {
mgb_assert(output(0)->dev_tensor().empty());
return;
}
mgb_assert(!output(0)->dev_tensor().empty());
Super::scn_do_execute();
}
PowC::NodeProp* PowC::do_make_node_prop() const {
auto ret = Super::do_make_node_prop();
ret->add_dep_type_existing_var(input(0),
NodeProp::DepType::VALUE_ALLOW_EMPTY);
return ret;
}
#if MGB_ENABLE_GRAD
MGB_IMPL_OPR_GRAD(PowC) {
auto exp = opr.param().exp;
return (exp * SymbolVar{out_grad[0]} *
PowC::make(opr.input(0), exp - 1, opr.config()))
.node();
}
#endif
// vim: syntax=cpp.doxygen foldmethod=marker foldmarker=f{{{,f}}}
| 35.04503 | 111 | 0.567169 | [
"shape",
"vector"
] |
c87f34355f308783bba42e8c1cc1dba9b216f365 | 903 | cpp | C++ | problems19dec/vases/2.cpp | Gomango999/codebreaker | 407c4ac7a69c8db52cc7d2a57034cdda243c9134 | [
"MIT"
] | 1 | 2021-12-11T01:43:27.000Z | 2021-12-11T01:43:27.000Z | problems19dec/vases/2.cpp | Gomango999/codebreaker | 407c4ac7a69c8db52cc7d2a57034cdda243c9134 | [
"MIT"
] | null | null | null | problems19dec/vases/2.cpp | Gomango999/codebreaker | 407c4ac7a69c8db52cc7d2a57034cdda243c9134 | [
"MIT"
] | 1 | 2021-12-15T07:04:29.000Z | 2021-12-15T07:04:29.000Z | #include <iostream>
#include <vector>
using namespace std;
int N;
// Apparently you could do vector<int>(3, 0); to prefill the vector.
vector<int> v;
bool invalid() {
bool ok = true;
ok &= v[0] + v[1] + v[2] == N;
for(int i = 0; i < 3; i++) {
ok &= v[i] > 0 && v[i] < N;
ok &= v[i] != v[(i+1)%3];
}
return !ok;
}
int main() {
v.push_back(0);
v.push_back(0);
v.push_back(0);
cin >> N;
// Evenly spread them out
for(int i = 0; i < N; i++) {
v[i%3] += 1;
}
// Fiddle with it if it's broken
if(v[0] == v[1]) {
v[0] += 1;
v[1] -= 1;
}
if(v[1] == v[2]) {
v[1] += 3;
v[2] -= 3;
}
if(v[2] == v[0]) {
v[2] += 7;
v[0] -= 7;
}
if(invalid()) {
cout << "-1 -1 -1\n";
} else {
cout << v[0] << " " << v[1] << " " << v[2] << "\n";
}
}
| 17.365385 | 68 | 0.378738 | [
"vector"
] |
c880dfc9505e97f79024c576d74d692fa795db5e | 3,568 | cxx | C++ | Qt/Components/pqDataInformationModelSelectionAdaptor.cxx | matthb2/ParaView-beforekitwareswtichedtogit | e47e57d6ce88444d9e6af9ab29f9db8c23d24cef | [
"BSD-3-Clause"
] | 1 | 2021-07-31T19:38:03.000Z | 2021-07-31T19:38:03.000Z | Qt/Components/pqDataInformationModelSelectionAdaptor.cxx | matthb2/ParaView-beforekitwareswtichedtogit | e47e57d6ce88444d9e6af9ab29f9db8c23d24cef | [
"BSD-3-Clause"
] | null | null | null | Qt/Components/pqDataInformationModelSelectionAdaptor.cxx | matthb2/ParaView-beforekitwareswtichedtogit | e47e57d6ce88444d9e6af9ab29f9db8c23d24cef | [
"BSD-3-Clause"
] | 2 | 2019-01-22T19:51:40.000Z | 2021-07-31T19:38:05.000Z | /*=========================================================================
Program: ParaView
Module: $RCSfile$
Copyright (c) 2005-2008 Sandia Corporation, Kitware Inc.
All rights reserved.
ParaView is a free software; you can redistribute it and/or modify it
under the terms of the ParaView license version 1.2.
See License_v1.2.txt for the full ParaView license.
A copy of this license can be obtained by contacting
Kitware Inc.
28 Corporate Drive
Clifton Park, NY 12065
USA
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 AUTHORS 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.
=========================================================================*/
#include "pqDataInformationModelSelectionAdaptor.h"
// Qt includes.
#include <QItemSelectionModel>
#include <QtDebug>
// ParaView includes.
#include "pqDataInformationModel.h"
#include "pqOutputPort.h"
#include "pqPipelineSource.h"
#include "pqServerManagerSelectionModel.h"
//-----------------------------------------------------------------------------
pqDataInformationModelSelectionAdaptor::pqDataInformationModelSelectionAdaptor(
QItemSelectionModel* qModel,
pqServerManagerSelectionModel* smSelectionModel, QObject* _parent/*=0*/)
: pqSelectionAdaptor(qModel, smSelectionModel, _parent)
{
const QAbstractItemModel* model = this->getQModel();
if (!qobject_cast<const pqDataInformationModel*>(model))
{
qDebug() << "QItemSelectionModel must be a selection model for "
" pqDataInformationModel.";
return;
}
}
//-----------------------------------------------------------------------------
pqDataInformationModelSelectionAdaptor::~pqDataInformationModelSelectionAdaptor()
{
}
//-----------------------------------------------------------------------------
QModelIndex pqDataInformationModelSelectionAdaptor::mapFromSMModel(
pqServerManagerModelItem* item) const
{
const pqDataInformationModel* pM = qobject_cast<const pqDataInformationModel*>(
this->getQModel());
pqOutputPort* outputPort = qobject_cast<pqOutputPort*>(item);
if (outputPort)
{
return pM->getIndexFor(outputPort);
}
pqPipelineSource* src = qobject_cast<pqPipelineSource*>(item);
return pM->getIndexFor(src? src->getOutputPort(0) : 0);
}
//-----------------------------------------------------------------------------
pqServerManagerModelItem* pqDataInformationModelSelectionAdaptor::mapToSMModel(
const QModelIndex& index) const
{
const pqDataInformationModel* pM = qobject_cast<const pqDataInformationModel*>(
this->getQModel());
return pM->getItemFor(index);
}
//-----------------------------------------------------------------------------
QItemSelectionModel::SelectionFlag
pqDataInformationModelSelectionAdaptor::qtSelectionFlags() const
{
return QItemSelectionModel::Rows;
}
//-----------------------------------------------------------------------------
| 35.68 | 81 | 0.639013 | [
"model"
] |
c882ca2f1b48229205c4849bdcd456bbafea4201 | 1,754 | hpp | C++ | ql/methods/finitedifferences/fdtypedefs.hpp | zhengyuzhang1/QuantLib | 65867ab7c44419b69e40e553b41230744b83cff9 | [
"BSD-3-Clause"
] | 76 | 2017-06-28T21:24:38.000Z | 2021-12-19T18:07:37.000Z | ql/methods/finitedifferences/fdtypedefs.hpp | zhengyuzhang1/QuantLib | 65867ab7c44419b69e40e553b41230744b83cff9 | [
"BSD-3-Clause"
] | 10 | 2017-04-02T14:34:07.000Z | 2021-01-13T05:31:12.000Z | ql/methods/finitedifferences/fdtypedefs.hpp | zhengyuzhang1/QuantLib | 65867ab7c44419b69e40e553b41230744b83cff9 | [
"BSD-3-Clause"
] | 34 | 2017-07-02T14:49:21.000Z | 2021-11-26T15:32:04.000Z | /* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2000, 2001, 2002, 2003 RiskMap srl
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
/*! \file fdtypedefs.hpp
\brief default choices for template instantiations
*/
#ifndef quantlib_fd_typedefs_hpp
#define quantlib_fd_typedefs_hpp
#include <ql/methods/finitedifferences/cranknicolson.hpp>
#include <ql/methods/finitedifferences/parallelevolver.hpp>
namespace QuantLib {
//! default choice for finite-difference model
typedef FiniteDifferenceModel<
CrankNicolson<TridiagonalOperator> >
StandardFiniteDifferenceModel;
//! default choice for parallel finite-difference model
typedef FiniteDifferenceModel<ParallelEvolver<
CrankNicolson<TridiagonalOperator> > >
StandardSystemFiniteDifferenceModel;
//! default choice for step condition
typedef StepCondition<Array> StandardStepCondition;
typedef CurveDependentStepCondition<Array> StandardCurveDependentStepCondition;
}
#endif
| 35.08 | 83 | 0.732611 | [
"model"
] |
c888d4acadbf916b79fa7c6121b49d8ce48799f8 | 8,619 | hpp | C++ | include/Mono/Security/X509/X501.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/Mono/Security/X509/X501.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/Mono/Security/X509/X501.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
#include "beatsaber-hook/shared/utils/typedefs-array.hpp"
#include "beatsaber-hook/shared/utils/typedefs-string.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: Mono::Security
namespace Mono::Security {
// Forward declaring type: ASN1
class ASN1;
}
// Forward declaring namespace: System::Text
namespace System::Text {
// Forward declaring type: StringBuilder
class StringBuilder;
}
// Completed forward declares
// Type namespace: Mono.Security.X509
namespace Mono::Security::X509 {
// Forward declaring type: X501
class X501;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::Mono::Security::X509::X501);
DEFINE_IL2CPP_ARG_TYPE(::Mono::Security::X509::X501*, "Mono.Security.X509", "X501");
// Type namespace: Mono.Security.X509
namespace Mono::Security::X509 {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: Mono.Security.X509.X501
// [TokenAttribute] Offset: FFFFFFFF
class X501 : public ::Il2CppObject {
public:
// Get static field: static private System.Byte[] countryName
static ::ArrayW<uint8_t> _get_countryName();
// Set static field: static private System.Byte[] countryName
static void _set_countryName(::ArrayW<uint8_t> value);
// Get static field: static private System.Byte[] organizationName
static ::ArrayW<uint8_t> _get_organizationName();
// Set static field: static private System.Byte[] organizationName
static void _set_organizationName(::ArrayW<uint8_t> value);
// Get static field: static private System.Byte[] organizationalUnitName
static ::ArrayW<uint8_t> _get_organizationalUnitName();
// Set static field: static private System.Byte[] organizationalUnitName
static void _set_organizationalUnitName(::ArrayW<uint8_t> value);
// Get static field: static private System.Byte[] commonName
static ::ArrayW<uint8_t> _get_commonName();
// Set static field: static private System.Byte[] commonName
static void _set_commonName(::ArrayW<uint8_t> value);
// Get static field: static private System.Byte[] localityName
static ::ArrayW<uint8_t> _get_localityName();
// Set static field: static private System.Byte[] localityName
static void _set_localityName(::ArrayW<uint8_t> value);
// Get static field: static private System.Byte[] stateOrProvinceName
static ::ArrayW<uint8_t> _get_stateOrProvinceName();
// Set static field: static private System.Byte[] stateOrProvinceName
static void _set_stateOrProvinceName(::ArrayW<uint8_t> value);
// Get static field: static private System.Byte[] streetAddress
static ::ArrayW<uint8_t> _get_streetAddress();
// Set static field: static private System.Byte[] streetAddress
static void _set_streetAddress(::ArrayW<uint8_t> value);
// Get static field: static private System.Byte[] domainComponent
static ::ArrayW<uint8_t> _get_domainComponent();
// Set static field: static private System.Byte[] domainComponent
static void _set_domainComponent(::ArrayW<uint8_t> value);
// Get static field: static private System.Byte[] userid
static ::ArrayW<uint8_t> _get_userid();
// Set static field: static private System.Byte[] userid
static void _set_userid(::ArrayW<uint8_t> value);
// Get static field: static private System.Byte[] email
static ::ArrayW<uint8_t> _get_email();
// Set static field: static private System.Byte[] email
static void _set_email(::ArrayW<uint8_t> value);
// Get static field: static private System.Byte[] dnQualifier
static ::ArrayW<uint8_t> _get_dnQualifier();
// Set static field: static private System.Byte[] dnQualifier
static void _set_dnQualifier(::ArrayW<uint8_t> value);
// Get static field: static private System.Byte[] title
static ::ArrayW<uint8_t> _get_title();
// Set static field: static private System.Byte[] title
static void _set_title(::ArrayW<uint8_t> value);
// Get static field: static private System.Byte[] surname
static ::ArrayW<uint8_t> _get_surname();
// Set static field: static private System.Byte[] surname
static void _set_surname(::ArrayW<uint8_t> value);
// Get static field: static private System.Byte[] givenName
static ::ArrayW<uint8_t> _get_givenName();
// Set static field: static private System.Byte[] givenName
static void _set_givenName(::ArrayW<uint8_t> value);
// Get static field: static private System.Byte[] initial
static ::ArrayW<uint8_t> _get_initial();
// Set static field: static private System.Byte[] initial
static void _set_initial(::ArrayW<uint8_t> value);
// static private System.Void .cctor()
// Offset: 0x2A593AC
static void _cctor();
// static public System.String ToString(Mono.Security.ASN1 seq)
// Offset: 0x2A5898C
static ::StringW ToString(::Mono::Security::ASN1* seq);
// static public System.String ToString(Mono.Security.ASN1 seq, System.Boolean reversed, System.String separator, System.Boolean quotes)
// Offset: 0x2A591E4
static ::StringW ToString(::Mono::Security::ASN1* seq, bool reversed, ::StringW separator, bool quotes);
// static private System.Void AppendEntry(System.Text.StringBuilder sb, Mono.Security.ASN1 entry, System.Boolean quotes)
// Offset: 0x2A58ABC
static void AppendEntry(::System::Text::StringBuilder* sb, ::Mono::Security::ASN1* entry, bool quotes);
}; // Mono.Security.X509.X501
#pragma pack(pop)
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: Mono::Security::X509::X501::_cctor
// Il2CppName: .cctor
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)()>(&Mono::Security::X509::X501::_cctor)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(Mono::Security::X509::X501*), ".cctor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: Mono::Security::X509::X501::ToString
// Il2CppName: ToString
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (*)(::Mono::Security::ASN1*)>(&Mono::Security::X509::X501::ToString)> {
static const MethodInfo* get() {
static auto* seq = &::il2cpp_utils::GetClassFromName("Mono.Security", "ASN1")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Mono::Security::X509::X501*), "ToString", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{seq});
}
};
// Writing MetadataGetter for method: Mono::Security::X509::X501::ToString
// Il2CppName: ToString
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (*)(::Mono::Security::ASN1*, bool, ::StringW, bool)>(&Mono::Security::X509::X501::ToString)> {
static const MethodInfo* get() {
static auto* seq = &::il2cpp_utils::GetClassFromName("Mono.Security", "ASN1")->byval_arg;
static auto* reversed = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* separator = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* quotes = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Mono::Security::X509::X501*), "ToString", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{seq, reversed, separator, quotes});
}
};
// Writing MetadataGetter for method: Mono::Security::X509::X501::AppendEntry
// Il2CppName: AppendEntry
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(::System::Text::StringBuilder*, ::Mono::Security::ASN1*, bool)>(&Mono::Security::X509::X501::AppendEntry)> {
static const MethodInfo* get() {
static auto* sb = &::il2cpp_utils::GetClassFromName("System.Text", "StringBuilder")->byval_arg;
static auto* entry = &::il2cpp_utils::GetClassFromName("Mono.Security", "ASN1")->byval_arg;
static auto* quotes = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Mono::Security::X509::X501*), "AppendEntry", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{sb, entry, quotes});
}
};
| 55.606452 | 187 | 0.707275 | [
"vector"
] |
c88aa30cb9df9bb451f6842afce01f63e4bc7b04 | 17,173 | cpp | C++ | engine/input/emscripten/InputSystemEm.cpp | codingwatching/ouzel | 07f09aefd3832801826441cd049b149c24a06b58 | [
"Unlicense"
] | 1 | 2021-11-08T09:49:10.000Z | 2021-11-08T09:49:10.000Z | engine/input/emscripten/InputSystemEm.cpp | codingwatching/ouzel | 07f09aefd3832801826441cd049b149c24a06b58 | [
"Unlicense"
] | null | null | null | engine/input/emscripten/InputSystemEm.cpp | codingwatching/ouzel | 07f09aefd3832801826441cd049b149c24a06b58 | [
"Unlicense"
] | null | null | null | // Ouzel by Elviss Strazdins
#include <map>
#include <emscripten.h>
#include "InputSystemEm.hpp"
#include "GamepadDeviceEm.hpp"
#include "../../core/Engine.hpp"
#include "../../utils/Log.hpp"
namespace ouzel::input::emscripten
{
namespace
{
const std::map<std::string, Keyboard::Key> keyMap = {
{"Backspace", Keyboard::Key::backspace},
{"Tab", Keyboard::Key::tab},
{"Enter", Keyboard::Key::enter},
{"ShiftLeft", Keyboard::Key::leftShift},
{"ShiftRight", Keyboard::Key::rightShift},
{"ControlLeft", Keyboard::Key::leftControl},
{"ControlRight", Keyboard::Key::rightControl},
{"AltLeft", Keyboard::Key::leftAlt},
{"AltRight", Keyboard::Key::rightAlt},
{"MetaLeft", Keyboard::Key::leftSuper},
{"MetaRight", Keyboard::Key::rightSuper},
{"Pause", Keyboard::Key::pause},
{"CapsLock", Keyboard::Key::capsLock},
{"Escape", Keyboard::Key::escape},
{"PageUp", Keyboard::Key::pageUp},
{"PageDown", Keyboard::Key::pageDown},
{"ContextMenu", Keyboard::Key::menu},
{"Help", Keyboard::Key::help},
{"Home", Keyboard::Key::home},
{"End", Keyboard::Key::end},
{"ArrowLeft", Keyboard::Key::left},
{"ArrowUp", Keyboard::Key::up},
{"ArrowRight", Keyboard::Key::right},
{"ArrowDown", Keyboard::Key::down},
{"Insert", Keyboard::Key::insert},
{"Delete", Keyboard::Key::del},
{"Digit0", Keyboard::Key::num0},
{"Digit1", Keyboard::Key::num1},
{"Digit2", Keyboard::Key::num2},
{"Digit3", Keyboard::Key::num3},
{"Digit4", Keyboard::Key::num4},
{"Digit5", Keyboard::Key::num5},
{"Digit6", Keyboard::Key::num6},
{"Digit7", Keyboard::Key::num7},
{"Digit8", Keyboard::Key::num8},
{"Digit9", Keyboard::Key::num9},
{"KeyA", Keyboard::Key::a},
{"KeyB", Keyboard::Key::b},
{"KeyC", Keyboard::Key::c},
{"KeyD", Keyboard::Key::d},
{"KeyE", Keyboard::Key::e},
{"KeyF", Keyboard::Key::f},
{"KeyG", Keyboard::Key::g},
{"KeyH", Keyboard::Key::h},
{"KeyI", Keyboard::Key::i},
{"KeyJ", Keyboard::Key::j},
{"KeyK", Keyboard::Key::k},
{"KeyL", Keyboard::Key::l},
{"KeyM", Keyboard::Key::m},
{"KeyN", Keyboard::Key::n},
{"KeyO", Keyboard::Key::o},
{"KeyP", Keyboard::Key::p},
{"KeyQ", Keyboard::Key::q},
{"KeyR", Keyboard::Key::r},
{"KeyS", Keyboard::Key::s},
{"KeyT", Keyboard::Key::t},
{"KeyU", Keyboard::Key::u},
{"KeyV", Keyboard::Key::v},
{"KeyW", Keyboard::Key::w},
{"KeyX", Keyboard::Key::x},
{"KeyY", Keyboard::Key::y},
{"KeyZ", Keyboard::Key::z},
{"OSLeft", Keyboard::Key::leftSuper},
{"OSRight", Keyboard::Key::rightSuper},
{"Delete", Keyboard::Key::del},
{"NumLock", Keyboard::Key::numLock},
{"NumpadEnter", Keyboard::Key::numpadEnter},
{"Numpad0", Keyboard::Key::numpad0},
{"Numpad1", Keyboard::Key::numpad1},
{"Numpad2", Keyboard::Key::numpad2},
{"Numpad3", Keyboard::Key::numpad3},
{"Numpad4", Keyboard::Key::numpad4},
{"Numpad5", Keyboard::Key::numpad5},
{"Numpad6", Keyboard::Key::numpad6},
{"Numpad7", Keyboard::Key::numpad7},
{"Numpad8", Keyboard::Key::numpad8},
{"Numpad9", Keyboard::Key::numpad9},
{"NumpadMultiply", Keyboard::Key::numpadMultiply},
{"NumpadAdd", Keyboard::Key::numpadPlus},
{"NumpadSubtract", Keyboard::Key::numpadMinus},
{"NumpadComma", Keyboard::Key::numpadSeparator},
{"NumpadDecimal", Keyboard::Key::numpadDecimal},
{"NumpadDivide", Keyboard::Key::numpadDivide},
{"NumpadEqual", Keyboard::Key::numpadEqual},
{"F1", Keyboard::Key::f1},
{"F2", Keyboard::Key::f2},
{"F3", Keyboard::Key::f3},
{"F4", Keyboard::Key::f4},
{"F5", Keyboard::Key::f5},
{"F6", Keyboard::Key::f6},
{"F7", Keyboard::Key::f7},
{"F8", Keyboard::Key::f8},
{"F9", Keyboard::Key::f9},
{"F10", Keyboard::Key::f10},
{"F11", Keyboard::Key::f11},
{"F12", Keyboard::Key::f12},
{"F13", Keyboard::Key::f13},
{"F14", Keyboard::Key::f14},
{"F15", Keyboard::Key::f15},
{"F16", Keyboard::Key::f16},
{"F17", Keyboard::Key::f17},
{"F18", Keyboard::Key::f18},
{"F19", Keyboard::Key::f19},
{"F20", Keyboard::Key::f20},
{"F21", Keyboard::Key::f21},
{"F22", Keyboard::Key::f22},
{"F23", Keyboard::Key::f23},
{"F24", Keyboard::Key::f24},
{"ScrollLock", Keyboard::Key::scrollLock},
{"Semicolon", Keyboard::Key::semicolon},
{"Equal", Keyboard::Key::equal},
{"Comma", Keyboard::Key::comma},
{"Minus", Keyboard::Key::minus},
{"Period", Keyboard::Key::period},
{"Slash", Keyboard::Key::slash},
{"Backquote", Keyboard::Key::grave},
{"BracketLeft", Keyboard::Key::leftBracket},
{"Backslash", Keyboard::Key::backslash},
{"BracketRight", Keyboard::Key::rightBracket},
{"Quote", Keyboard::Key::quote},
{"IntlBackslash", Keyboard::Key::intlBackslash},
{"PrintScreen", Keyboard::Key::printScreen},
{"IntlRo", Keyboard::Key::ro},
{"IntlYen", Keyboard::Key::yen}
};
Keyboard::Key convertKeyCode(const EM_UTF8 key[32])
{
auto i = keyMap.find(key);
if (i != keyMap.end())
return i->second;
else
return Keyboard::Key::none;
}
EM_BOOL emKeyCallback(int eventType, const EmscriptenKeyboardEvent* keyEvent, void* userData)
{
const auto keyboardDevice = static_cast<KeyboardDevice*>(userData);
switch (eventType)
{
case EMSCRIPTEN_EVENT_KEYPRESS:
case EMSCRIPTEN_EVENT_KEYDOWN:
keyboardDevice->handleKeyPress(convertKeyCode(keyEvent->code));
return EM_TRUE;
case EMSCRIPTEN_EVENT_KEYUP:
keyboardDevice->handleKeyRelease(convertKeyCode(keyEvent->code));
return EM_TRUE;
}
return EM_FALSE;
}
EM_BOOL emMouseCallback(int eventType, const EmscriptenMouseEvent* mouseEvent, void* userData)
{
const auto mouseDevice = static_cast<MouseDevice*>(userData);
Mouse::Button button;
switch (mouseEvent->button)
{
case 0:
button = Mouse::Button::left;
break;
case 1:
button = Mouse::Button::middle;
break;
case 2:
button = Mouse::Button::right;
break;
default:
button = Mouse::Button::none;
break;
}
const ouzel::Vector<float, 2> position{
static_cast<float>(mouseEvent->canvasX),
static_cast<float>(mouseEvent->canvasY)
};
switch (eventType)
{
case EMSCRIPTEN_EVENT_MOUSEDOWN:
mouseDevice->handleButtonPress(button,
ouzel::engine->getWindow()->convertWindowToNormalizedLocation(position));
return EM_TRUE;
case EMSCRIPTEN_EVENT_MOUSEUP:
mouseDevice->handleButtonRelease(button,
ouzel::engine->getWindow()->convertWindowToNormalizedLocation(position));
return EM_TRUE;
case EMSCRIPTEN_EVENT_MOUSEMOVE:
mouseDevice->handleMove(ouzel::engine->getWindow()->convertWindowToNormalizedLocation(position));
return EM_TRUE;
}
return EM_FALSE;
}
EM_BOOL emWheelCallback(int eventType, const EmscriptenWheelEvent* wheelEvent, void* userData)
{
const auto mouseDevice = static_cast<MouseDevice*>(userData);
if (eventType == EMSCRIPTEN_EVENT_WHEEL)
{
const ouzel::Vector<float, 2> position{
static_cast<float>(wheelEvent->mouse.canvasX),
static_cast<float>(wheelEvent->mouse.canvasY)
};
mouseDevice->handleScroll(ouzel::Vector<float, 2>{static_cast<float>(wheelEvent->deltaX), static_cast<float>(wheelEvent->deltaY)},
ouzel::engine->getWindow()->convertWindowToNormalizedLocation(position));
return EM_TRUE;
}
return EM_FALSE;
}
EM_BOOL emPointerLockChangeCallback(int eventType, const EmscriptenPointerlockChangeEvent* pointerlockChangeEvent, void* userData)
{
const auto mouseDevice = static_cast<MouseDevice*>(userData);
if (eventType == EMSCRIPTEN_EVENT_POINTERLOCKCHANGE)
{
mouseDevice->handleCursorLockChange(pointerlockChangeEvent->isActive);
return EM_TRUE;
}
return EM_FALSE;
}
EM_BOOL emGamepadCallback(int eventType, const EmscriptenGamepadEvent* gamepadEvent, void* userData)
{
const auto inputSystemEm = static_cast<InputSystem*>(userData);
if (eventType == EMSCRIPTEN_EVENT_GAMEPADCONNECTED)
{
inputSystemEm->handleGamepadConnected(gamepadEvent->index);
return EM_TRUE;
}
else if (eventType == EMSCRIPTEN_EVENT_GAMEPADDISCONNECTED)
{
inputSystemEm->handleGamepadDisconnected(gamepadEvent->index);
return EM_TRUE;
}
return EM_FALSE;
}
EM_BOOL emTouchCallback(int eventType, const EmscriptenTouchEvent* touchEvent, void* userData)
{
const auto touchpadDevice = static_cast<TouchpadDevice*>(userData);
for (int i = 0; i < touchEvent->numTouches; ++i)
{
if (touchEvent->touches[i].isChanged)
{
const ouzel::Vector<float, 2> position{
static_cast<float>(touchEvent->touches[i].canvasX),
static_cast<float>(touchEvent->touches[i].canvasY)
};
switch (eventType)
{
case EMSCRIPTEN_EVENT_TOUCHSTART:
touchpadDevice->handleTouchBegin(static_cast<std::uint64_t>(touchEvent->touches[i].identifier),
ouzel::engine->getWindow()->convertWindowToNormalizedLocation(position),
1.0F);
break;
case EMSCRIPTEN_EVENT_TOUCHEND:
touchpadDevice->handleTouchEnd(static_cast<std::uint64_t>(touchEvent->touches[i].identifier),
ouzel::engine->getWindow()->convertWindowToNormalizedLocation(position),
1.0F);
break;
case EMSCRIPTEN_EVENT_TOUCHMOVE:
touchpadDevice->handleTouchMove(static_cast<std::uint64_t>(touchEvent->touches[i].identifier),
ouzel::engine->getWindow()->convertWindowToNormalizedLocation(position),
1.0F);
break;
case EMSCRIPTEN_EVENT_TOUCHCANCEL:
touchpadDevice->handleTouchCancel(static_cast<std::uint64_t>(touchEvent->touches[i].identifier),
ouzel::engine->getWindow()->convertWindowToNormalizedLocation(position),
1.0F);
break;
}
}
}
return EM_FALSE;
}
}
InputSystem::InputSystem(const std::function<std::future<bool>(const Event&)>& initCallback):
input::InputSystem{initCallback},
keyboardDevice{std::make_unique<KeyboardDevice>(*this, getNextDeviceId())},
mouseDevice{std::make_unique<MouseDevice>(*this, getNextDeviceId())},
touchpadDevice{std::make_unique<TouchpadDevice>(*this, getNextDeviceId(), true)}
{
emscripten_set_keypress_callback(nullptr, keyboardDevice.get(), EM_TRUE, emKeyCallback);
emscripten_set_keydown_callback(nullptr, keyboardDevice.get(), EM_TRUE, emKeyCallback);
emscripten_set_keyup_callback(nullptr, keyboardDevice.get(), EM_TRUE, emKeyCallback);
emscripten_set_mousedown_callback("#canvas", mouseDevice.get(), EM_TRUE, emMouseCallback);
emscripten_set_mouseup_callback("#canvas", mouseDevice.get(), EM_TRUE, emMouseCallback);
emscripten_set_mousemove_callback("#canvas", mouseDevice.get(), EM_TRUE, emMouseCallback);
emscripten_set_wheel_callback("#canvas", mouseDevice.get(), EM_TRUE, emWheelCallback);
emscripten_set_pointerlockchange_callback(nullptr, mouseDevice.get(), EM_TRUE, emPointerLockChangeCallback);
emscripten_set_gamepadconnected_callback(this, EM_TRUE, emGamepadCallback);
emscripten_set_gamepaddisconnected_callback(this, EM_TRUE, emGamepadCallback);
emscripten_set_touchstart_callback("#canvas", touchpadDevice.get(), EM_TRUE, emTouchCallback);
emscripten_set_touchend_callback("#canvas", touchpadDevice.get(), EM_TRUE, emTouchCallback);
emscripten_set_touchmove_callback("#canvas", touchpadDevice.get(), EM_TRUE, emTouchCallback);
emscripten_set_touchcancel_callback("#canvas", touchpadDevice.get(), EM_TRUE, emTouchCallback);
const int result = emscripten_get_num_gamepads();
if (result == EMSCRIPTEN_RESULT_NOT_SUPPORTED)
logger.log(Log::Level::info) << "Gamepads not supported";
else
{
for (long index = 0; index < result; ++index)
handleGamepadConnected(index);
}
}
void InputSystem::executeCommand(const Command& command)
{
switch (command.type)
{
case Command::Type::setPlayerIndex:
{
break;
}
case Command::Type::setVibration:
{
break;
}
case Command::Type::setPosition:
{
break;
}
case Command::Type::setCursor:
{
break;
}
case Command::Type::setCursorVisible:
{
if (InputDevice* inputDevice = getInputDevice(command.deviceId))
{
if (inputDevice == mouseDevice.get())
mouseDevice->setCursorVisible(command.locked);
}
break;
}
case Command::Type::setCursorLocked:
{
if (InputDevice* inputDevice = getInputDevice(command.deviceId))
{
if (inputDevice == mouseDevice.get())
mouseDevice->setCursorLocked(command.locked);
}
break;
}
case Command::Type::showVirtualKeyboard:
break;
case Command::Type::hideVirtualKeyboard:
break;
default:
break;
}
}
void InputSystem::update()
{
for (const auto& i : gamepadDevices)
{
const auto gamepadDevice = static_cast<GamepadDevice*>(i.second.get());
gamepadDevice->update();
}
}
void InputSystem::handleGamepadConnected(long index)
{
auto gamepadDevice = std::make_unique<GamepadDevice>(*this, getNextDeviceId(), index);
gamepadDevices.insert(std::pair(index, std::move(gamepadDevice)));
}
void InputSystem::handleGamepadDisconnected(long index)
{
auto i = gamepadDevices.find(index);
if (i != gamepadDevices.end())
gamepadDevices.erase(i);
}
}
| 41.682039 | 146 | 0.521982 | [
"vector"
] |
c88b684f4a6fafa56e738048894e7af87190d85b | 27,366 | hpp | C++ | Granite/third_party/shaderc/libshaderc/include/shaderc/shaderc.hpp | dmrlawson/parallel-rdp | f18e00728bb45e3a769ab7ad3b9064359ef82209 | [
"MIT"
] | 1,582 | 2019-05-31T01:48:29.000Z | 2022-03-30T12:37:03.000Z | Morpheus-Core/Vendor/VULKAN/Include/shaderc/shaderc.hpp | LegendaryDelta/Morpheus-Engine | f9ddc2ab4bac5f6f8b2f7334358c47dcc558eec4 | [
"Apache-2.0"
] | 48 | 2019-06-02T16:26:57.000Z | 2021-09-21T10:10:42.000Z | Morpheus-Core/Vendor/VULKAN/Include/shaderc/shaderc.hpp | LegendaryDelta/Morpheus-Engine | f9ddc2ab4bac5f6f8b2f7334358c47dcc558eec4 | [
"Apache-2.0"
] | 83 | 2019-07-11T09:55:24.000Z | 2022-03-30T03:04:01.000Z | // Copyright 2015 The Shaderc Authors. All rights reserved.
//
// 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.
#ifndef SHADERC_SHADERC_HPP_
#define SHADERC_SHADERC_HPP_
#include <memory>
#include <string>
#include <vector>
#include "shaderc.h"
namespace shaderc {
// A CompilationResult contains the compiler output, compilation status,
// and messages.
//
// The compiler output is stored as an array of elements and accessed
// via random access iterators provided by cbegin() and cend(). The iterators
// are contiguous in the sense of "Contiguous Iterators: A Refinement of
// Random Access Iterators", Nevin Liber, C++ Library Evolution Working
// Group Working Paper N3884.
// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n3884.pdf
//
// Methods begin() and end() are also provided to enable range-based for.
// They are synonyms to cbegin() and cend(), respectively.
template <typename OutputElementType>
class CompilationResult {
public:
typedef OutputElementType element_type;
// The type used to describe the begin and end iterators on the
// compiler output.
typedef const OutputElementType* const_iterator;
// Upon creation, the CompilationResult takes ownership of the
// shaderc_compilation_result instance. During destruction of the
// CompilationResult, the shaderc_compilation_result will be released.
explicit CompilationResult(shaderc_compilation_result_t compilation_result)
: compilation_result_(compilation_result) {}
CompilationResult() : compilation_result_(nullptr) {}
~CompilationResult() { shaderc_result_release(compilation_result_); }
CompilationResult(CompilationResult&& other) : compilation_result_(nullptr) {
*this = std::move(other);
}
CompilationResult& operator=(CompilationResult&& other) {
if (compilation_result_) {
shaderc_result_release(compilation_result_);
}
compilation_result_ = other.compilation_result_;
other.compilation_result_ = nullptr;
return *this;
}
// Returns any error message found during compilation.
std::string GetErrorMessage() const {
if (!compilation_result_) {
return "";
}
return shaderc_result_get_error_message(compilation_result_);
}
// Returns the compilation status, indicating whether the compilation
// succeeded, or failed due to some reasons, like invalid shader stage or
// compilation errors.
shaderc_compilation_status GetCompilationStatus() const {
if (!compilation_result_) {
return shaderc_compilation_status_null_result_object;
}
return shaderc_result_get_compilation_status(compilation_result_);
}
// Returns a random access (contiguous) iterator pointing to the start
// of the compilation output. It is valid for the lifetime of this object.
// If there is no compilation result, then returns nullptr.
const_iterator cbegin() const {
if (!compilation_result_) return nullptr;
return reinterpret_cast<const_iterator>(
shaderc_result_get_bytes(compilation_result_));
}
// Returns a random access (contiguous) iterator pointing to the end of
// the compilation output. It is valid for the lifetime of this object.
// If there is no compilation result, then returns nullptr.
const_iterator cend() const {
if (!compilation_result_) return nullptr;
return cbegin() +
shaderc_result_get_length(compilation_result_) /
sizeof(OutputElementType);
}
// Returns the same iterator as cbegin().
const_iterator begin() const { return cbegin(); }
// Returns the same iterator as cend().
const_iterator end() const { return cend(); }
// Returns the number of warnings generated during the compilation.
size_t GetNumWarnings() const {
if (!compilation_result_) {
return 0;
}
return shaderc_result_get_num_warnings(compilation_result_);
}
// Returns the number of errors generated during the compilation.
size_t GetNumErrors() const {
if (!compilation_result_) {
return 0;
}
return shaderc_result_get_num_errors(compilation_result_);
}
private:
CompilationResult(const CompilationResult& other) = delete;
CompilationResult& operator=(const CompilationResult& other) = delete;
shaderc_compilation_result_t compilation_result_;
};
// A compilation result for a SPIR-V binary module, which is an array
// of uint32_t words.
using SpvCompilationResult = CompilationResult<uint32_t>;
// A compilation result in SPIR-V assembly syntax.
using AssemblyCompilationResult = CompilationResult<char>;
// Preprocessed source text.
using PreprocessedSourceCompilationResult = CompilationResult<char>;
// Contains any options that can have default values for a compilation.
class CompileOptions {
public:
CompileOptions() { options_ = shaderc_compile_options_initialize(); }
~CompileOptions() { shaderc_compile_options_release(options_); }
CompileOptions(const CompileOptions& other) {
options_ = shaderc_compile_options_clone(other.options_);
}
CompileOptions(CompileOptions&& other) {
options_ = other.options_;
other.options_ = nullptr;
}
// Adds a predefined macro to the compilation options. It behaves the same as
// shaderc_compile_options_add_macro_definition in shaderc.h.
void AddMacroDefinition(const char* name, size_t name_length,
const char* value, size_t value_length) {
shaderc_compile_options_add_macro_definition(options_, name, name_length,
value, value_length);
}
// Adds a valueless predefined macro to the compilation options.
void AddMacroDefinition(const std::string& name) {
AddMacroDefinition(name.c_str(), name.size(), nullptr, 0u);
}
// Adds a predefined macro to the compilation options.
void AddMacroDefinition(const std::string& name, const std::string& value) {
AddMacroDefinition(name.c_str(), name.size(), value.c_str(), value.size());
}
// Sets the compiler mode to generate debug information in the output.
void SetGenerateDebugInfo() {
shaderc_compile_options_set_generate_debug_info(options_);
}
// Sets the compiler optimization level to the given level. Only the last one
// takes effect if multiple calls of this function exist.
void SetOptimizationLevel(shaderc_optimization_level level) {
shaderc_compile_options_set_optimization_level(options_, level);
}
// A C++ version of the libshaderc includer interface.
class IncluderInterface {
public:
// Handles shaderc_include_resolver_fn callbacks.
virtual shaderc_include_result* GetInclude(const char* requested_source,
shaderc_include_type type,
const char* requesting_source,
size_t include_depth) = 0;
// Handles shaderc_include_result_release_fn callbacks.
virtual void ReleaseInclude(shaderc_include_result* data) = 0;
virtual ~IncluderInterface() = default;
};
// Sets the includer instance for libshaderc to call during compilation, as
// described in shaderc_compile_options_set_include_callbacks(). Callbacks
// are routed to this includer's methods.
void SetIncluder(std::unique_ptr<IncluderInterface>&& includer) {
includer_ = std::move(includer);
shaderc_compile_options_set_include_callbacks(
options_,
[](void* user_data, const char* requested_source, int type,
const char* requesting_source, size_t include_depth) {
auto* sub_includer = static_cast<IncluderInterface*>(user_data);
return sub_includer->GetInclude(requested_source,
(shaderc_include_type)type,
requesting_source, include_depth);
},
[](void* user_data, shaderc_include_result* include_result) {
auto* sub_includer = static_cast<IncluderInterface*>(user_data);
return sub_includer->ReleaseInclude(include_result);
},
includer_.get());
}
// Forces the GLSL language version and profile to a given pair. The version
// number is the same as would appear in the #version annotation in the
// source. Version and profile specified here overrides the #version
// annotation in the source. Use profile: 'shaderc_profile_none' for GLSL
// versions that do not define profiles, e.g. versions below 150.
void SetForcedVersionProfile(int version, shaderc_profile profile) {
shaderc_compile_options_set_forced_version_profile(options_, version,
profile);
}
// Sets the compiler mode to suppress warnings. Note this option overrides
// warnings-as-errors mode. When both suppress-warnings and warnings-as-errors
// modes are turned on, warning messages will be inhibited, and will not be
// emitted as error message.
void SetSuppressWarnings() {
shaderc_compile_options_set_suppress_warnings(options_);
}
// Sets the source language. The default is GLSL.
void SetSourceLanguage(shaderc_source_language lang) {
shaderc_compile_options_set_source_language(options_, lang);
}
// Sets the target shader environment, affecting which warnings or errors will
// be issued. The version will be for distinguishing between different
// versions of the target environment. The version value should be either 0
// or a value listed in shaderc_env_version. The 0 value maps to Vulkan 1.0
// if |target| is Vulkan, and it maps to OpenGL 4.5 if |target| is OpenGL.
void SetTargetEnvironment(shaderc_target_env target, uint32_t version) {
shaderc_compile_options_set_target_env(options_, target, version);
}
// Sets the target SPIR-V version. The generated module will use this version
// of SPIR-V. Each target environment determines what versions of SPIR-V
// it can consume. Defaults to the highest version of SPIR-V 1.0 which is
// required to be supported by the target environment. E.g. Default to SPIR-V
// 1.0 for Vulkan 1.0 and SPIR-V 1.3 for Vulkan 1.1.
void SetTargetSpirv(shaderc_spirv_version version) {
shaderc_compile_options_set_target_spirv(options_, version);
}
// Sets the compiler mode to make all warnings into errors. Note the
// suppress-warnings mode overrides this option, i.e. if both
// warning-as-errors and suppress-warnings modes are set on, warnings will not
// be emitted as error message.
void SetWarningsAsErrors() {
shaderc_compile_options_set_warnings_as_errors(options_);
}
// Sets a resource limit.
void SetLimit(shaderc_limit limit, int value) {
shaderc_compile_options_set_limit(options_, limit, value);
}
// Sets whether the compiler should automatically assign bindings to uniforms
// that aren't already explicitly bound in the shader source.
void SetAutoBindUniforms(bool auto_bind) {
shaderc_compile_options_set_auto_bind_uniforms(options_, auto_bind);
}
// Sets whether the compiler should use HLSL IO mapping rules for bindings.
// Defaults to false.
void SetHlslIoMapping(bool hlsl_iomap) {
shaderc_compile_options_set_hlsl_io_mapping(options_, hlsl_iomap);
}
// Sets whether the compiler should determine block member offsets using HLSL
// packing rules instead of standard GLSL rules. Defaults to false. Only
// affects GLSL compilation. HLSL rules are always used when compiling HLSL.
void SetHlslOffsets(bool hlsl_offsets) {
shaderc_compile_options_set_hlsl_offsets(options_, hlsl_offsets);
}
// Sets the base binding number used for for a uniform resource type when
// automatically assigning bindings. For GLSL compilation, sets the lowest
// automatically assigned number. For HLSL compilation, the regsiter number
// assigned to the resource is added to this specified base.
void SetBindingBase(shaderc_uniform_kind kind, uint32_t base) {
shaderc_compile_options_set_binding_base(options_, kind, base);
}
// Like SetBindingBase, but only takes effect when compiling a given shader
// stage. The stage is assumed to be one of vertex, fragment, tessellation
// evaluation, tesselation control, geometry, or compute.
void SetBindingBaseForStage(shaderc_shader_kind shader_kind,
shaderc_uniform_kind kind, uint32_t base) {
shaderc_compile_options_set_binding_base_for_stage(options_, shader_kind,
kind, base);
}
// Sets whether the compiler automatically assigns locations to
// uniform variables that don't have explicit locations.
void SetAutoMapLocations(bool auto_map) {
shaderc_compile_options_set_auto_map_locations(options_, auto_map);
}
// Sets a descriptor set and binding for an HLSL register in the given stage.
// Copies the parameter strings.
void SetHlslRegisterSetAndBindingForStage(shaderc_shader_kind shader_kind,
const std::string& reg,
const std::string& set,
const std::string& binding) {
shaderc_compile_options_set_hlsl_register_set_and_binding_for_stage(
options_, shader_kind, reg.c_str(), set.c_str(), binding.c_str());
}
// Sets a descriptor set and binding for an HLSL register in any stage.
// Copies the parameter strings.
void SetHlslRegisterSetAndBinding(const std::string& reg,
const std::string& set,
const std::string& binding) {
shaderc_compile_options_set_hlsl_register_set_and_binding(
options_, reg.c_str(), set.c_str(), binding.c_str());
}
// Sets whether the compiler should enable extension
// SPV_GOOGLE_hlsl_functionality1.
void SetHlslFunctionality1(bool enable) {
shaderc_compile_options_set_hlsl_functionality1(options_, enable);
}
// Sets whether the compiler should invert position.Y output in vertex shader.
void SetInvertY(bool enable) {
shaderc_compile_options_set_invert_y(options_, enable);
}
// Sets whether the compiler should generates code for max an min which,
// if given a NaN operand, will return the other operand. Similarly, the
// clamp builtin will favour the non-NaN operands, as if clamp were
// implemented as a composition of max and min.
void SetNanClamp(bool enable) {
shaderc_compile_options_set_nan_clamp(options_, enable);
}
private:
CompileOptions& operator=(const CompileOptions& other) = delete;
shaderc_compile_options_t options_;
std::unique_ptr<IncluderInterface> includer_;
friend class Compiler;
};
// The compilation context for compiling source to SPIR-V.
class Compiler {
public:
Compiler() : compiler_(shaderc_compiler_initialize()) {}
~Compiler() { shaderc_compiler_release(compiler_); }
Compiler(Compiler&& other) {
compiler_ = other.compiler_;
other.compiler_ = nullptr;
}
bool IsValid() const { return compiler_ != nullptr; }
// Compiles the given source GLSL and returns a SPIR-V binary module
// compilation result.
// The source_text parameter must be a valid pointer.
// The source_text_size parameter must be the length of the source text.
// The shader_kind parameter either forces the compilation to be done with a
// specified shader kind, or hint the compiler how to determine the exact
// shader kind. If the shader kind is set to shaderc_glslc_infer_from_source,
// the compiler will try to deduce the shader kind from the source string and
// a failure in this proess will generate an error. Currently only #pragma
// annotation is supported. If the shader kind is set to one of the default
// shader kinds, the compiler will fall back to the specified default shader
// kind in case it failed to deduce the shader kind from the source string.
// The input_file_name is a null-termintated string. It is used as a tag to
// identify the source string in cases like emitting error messages. It
// doesn't have to be a 'file name'.
// The entry_point_name parameter is a null-terminated string specifying
// the entry point name for HLSL compilation. For GLSL compilation, the
// entry point name is assumed to be "main".
// The compilation is passed any options specified in the CompileOptions
// parameter.
// It is valid for the returned CompilationResult object to outlive this
// compiler object.
// Note when the options_ has disassembly mode or preprocessing only mode set
// on, the returned CompilationResult will hold a text string, instead of a
// SPIR-V binary generated with default options.
SpvCompilationResult CompileGlslToSpv(const char* source_text,
size_t source_text_size,
shaderc_shader_kind shader_kind,
const char* input_file_name,
const char* entry_point_name,
const CompileOptions& options) const {
shaderc_compilation_result_t compilation_result = shaderc_compile_into_spv(
compiler_, source_text, source_text_size, shader_kind, input_file_name,
entry_point_name, options.options_);
return SpvCompilationResult(compilation_result);
}
// Compiles the given source shader and returns a SPIR-V binary module
// compilation result.
// Like the first CompileGlslToSpv method but assumes the entry point name
// is "main".
SpvCompilationResult CompileGlslToSpv(const char* source_text,
size_t source_text_size,
shaderc_shader_kind shader_kind,
const char* input_file_name,
const CompileOptions& options) const {
return CompileGlslToSpv(source_text, source_text_size, shader_kind,
input_file_name, "main", options);
}
// Compiles the given source GLSL and returns a SPIR-V binary module
// compilation result.
// Like the previous CompileGlslToSpv method but uses default options.
SpvCompilationResult CompileGlslToSpv(const char* source_text,
size_t source_text_size,
shaderc_shader_kind shader_kind,
const char* input_file_name) const {
shaderc_compilation_result_t compilation_result =
shaderc_compile_into_spv(compiler_, source_text, source_text_size,
shader_kind, input_file_name, "main", nullptr);
return SpvCompilationResult(compilation_result);
}
// Compiles the given source shader and returns a SPIR-V binary module
// compilation result.
// Like the first CompileGlslToSpv method but the source is provided as
// a std::string, and we assume the entry point is "main".
SpvCompilationResult CompileGlslToSpv(const std::string& source_text,
shaderc_shader_kind shader_kind,
const char* input_file_name,
const CompileOptions& options) const {
return CompileGlslToSpv(source_text.data(), source_text.size(), shader_kind,
input_file_name, options);
}
// Compiles the given source shader and returns a SPIR-V binary module
// compilation result.
// Like the first CompileGlslToSpv method but the source is provided as
// a std::string.
SpvCompilationResult CompileGlslToSpv(const std::string& source_text,
shaderc_shader_kind shader_kind,
const char* input_file_name,
const char* entry_point_name,
const CompileOptions& options) const {
return CompileGlslToSpv(source_text.data(), source_text.size(), shader_kind,
input_file_name, entry_point_name, options);
}
// Compiles the given source GLSL and returns a SPIR-V binary module
// compilation result.
// Like the previous CompileGlslToSpv method but assumes the entry point
// name is "main".
SpvCompilationResult CompileGlslToSpv(const std::string& source_text,
shaderc_shader_kind shader_kind,
const char* input_file_name) const {
return CompileGlslToSpv(source_text.data(), source_text.size(), shader_kind,
input_file_name);
}
// Assembles the given SPIR-V assembly and returns a SPIR-V binary module
// compilation result.
// The assembly should follow the syntax defined in the SPIRV-Tools project
// (https://github.com/KhronosGroup/SPIRV-Tools/blob/master/syntax.md).
// It is valid for the returned CompilationResult object to outlive this
// compiler object.
// The assembling will pick options suitable for assembling specified in the
// CompileOptions parameter.
SpvCompilationResult AssembleToSpv(const char* source_assembly,
size_t source_assembly_size,
const CompileOptions& options) const {
return SpvCompilationResult(shaderc_assemble_into_spv(
compiler_, source_assembly, source_assembly_size, options.options_));
}
// Assembles the given SPIR-V assembly and returns a SPIR-V binary module
// compilation result.
// Like the first AssembleToSpv method but uses the default compiler options.
SpvCompilationResult AssembleToSpv(const char* source_assembly,
size_t source_assembly_size) const {
return SpvCompilationResult(shaderc_assemble_into_spv(
compiler_, source_assembly, source_assembly_size, nullptr));
}
// Assembles the given SPIR-V assembly and returns a SPIR-V binary module
// compilation result.
// Like the first AssembleToSpv method but the source is provided as a
// std::string.
SpvCompilationResult AssembleToSpv(const std::string& source_assembly,
const CompileOptions& options) const {
return SpvCompilationResult(
shaderc_assemble_into_spv(compiler_, source_assembly.data(),
source_assembly.size(), options.options_));
}
// Assembles the given SPIR-V assembly and returns a SPIR-V binary module
// compilation result.
// Like the first AssembleToSpv method but the source is provided as a
// std::string and also uses default compiler options.
SpvCompilationResult AssembleToSpv(const std::string& source_assembly) const {
return SpvCompilationResult(shaderc_assemble_into_spv(
compiler_, source_assembly.data(), source_assembly.size(), nullptr));
}
// Compiles the given source GLSL and returns the SPIR-V assembly text
// compilation result.
// Options are similar to the first CompileToSpv method.
AssemblyCompilationResult CompileGlslToSpvAssembly(
const char* source_text, size_t source_text_size,
shaderc_shader_kind shader_kind, const char* input_file_name,
const char* entry_point_name, const CompileOptions& options) const {
shaderc_compilation_result_t compilation_result =
shaderc_compile_into_spv_assembly(
compiler_, source_text, source_text_size, shader_kind,
input_file_name, entry_point_name, options.options_);
return AssemblyCompilationResult(compilation_result);
}
// Compiles the given source GLSL and returns the SPIR-V assembly text
// compilation result.
// Similare to the previous method, but assumes entry point name is "main".
AssemblyCompilationResult CompileGlslToSpvAssembly(
const char* source_text, size_t source_text_size,
shaderc_shader_kind shader_kind, const char* input_file_name,
const CompileOptions& options) const {
return CompileGlslToSpvAssembly(source_text, source_text_size, shader_kind,
input_file_name, "main", options);
}
// Compiles the given source GLSL and returns the SPIR-V assembly text
// result. Like the first CompileGlslToSpvAssembly method but the source
// is provided as a std::string. Options are otherwise similar to
// the first CompileToSpv method.
AssemblyCompilationResult CompileGlslToSpvAssembly(
const std::string& source_text, shaderc_shader_kind shader_kind,
const char* input_file_name, const char* entry_point_name,
const CompileOptions& options) const {
return CompileGlslToSpvAssembly(source_text.data(), source_text.size(),
shader_kind, input_file_name,
entry_point_name, options);
}
// Compiles the given source GLSL and returns the SPIR-V assembly text
// result. Like the previous CompileGlslToSpvAssembly method but assumes
// the entry point name is "main".
AssemblyCompilationResult CompileGlslToSpvAssembly(
const std::string& source_text, shaderc_shader_kind shader_kind,
const char* input_file_name, const CompileOptions& options) const {
return CompileGlslToSpvAssembly(source_text, shader_kind, input_file_name,
"main", options);
}
// Preprocesses the given source GLSL and returns the preprocessed
// source text as a compilation result.
// Options are similar to the first CompileToSpv method.
PreprocessedSourceCompilationResult PreprocessGlsl(
const char* source_text, size_t source_text_size,
shaderc_shader_kind shader_kind, const char* input_file_name,
const CompileOptions& options) const {
shaderc_compilation_result_t compilation_result =
shaderc_compile_into_preprocessed_text(
compiler_, source_text, source_text_size, shader_kind,
input_file_name, "main", options.options_);
return PreprocessedSourceCompilationResult(compilation_result);
}
// Preprocesses the given source GLSL and returns text result. Like the first
// PreprocessGlsl method but the source is provided as a std::string.
// Options are otherwise similar to the first CompileToSpv method.
PreprocessedSourceCompilationResult PreprocessGlsl(
const std::string& source_text, shaderc_shader_kind shader_kind,
const char* input_file_name, const CompileOptions& options) const {
return PreprocessGlsl(source_text.data(), source_text.size(), shader_kind,
input_file_name, options);
}
private:
Compiler(const Compiler&) = delete;
Compiler& operator=(const Compiler& other) = delete;
shaderc_compiler_t compiler_;
};
} // namespace shaderc
#endif // SHADERC_SHADERC_HPP_
| 45.916107 | 80 | 0.70858 | [
"geometry",
"object",
"vector"
] |
c88c7f956e4855d1ab742c70b8fd2064f4b11285 | 777 | cpp | C++ | cpp/src/121.cpp | Triple-Z/LeetCode | e470de54086cdedd4738fe62fe735d89089227dd | [
"MIT"
] | 1 | 2021-05-28T16:46:14.000Z | 2021-05-28T16:46:14.000Z | cpp/src/121.cpp | Triple-Z/LeetCode | e470de54086cdedd4738fe62fe735d89089227dd | [
"MIT"
] | 12 | 2020-09-17T16:25:24.000Z | 2021-11-16T15:08:44.000Z | cpp/src/121.cpp | Triple-Z/LeetCode | e470de54086cdedd4738fe62fe735d89089227dd | [
"MIT"
] | 1 | 2021-12-19T07:33:22.000Z | 2021-12-19T07:33:22.000Z | #include <iostream>
#include <vector>
#include <climits>
#include <cassert>
using namespace std;
class Solution {
public:
int maxProfit(vector<int>& prices) {
int min_price = INT_MAX;
int max_profit = 0;
for (int price: prices) {
if (price < min_price)
min_price = price;
if (price - min_price > max_profit)
max_profit = price - min_price;
}
return max_profit;
}
};
int main() {
vector<int> in = {7, 1, 5, 3, 6, 4};
Solution solution = Solution();
int ret = solution.maxProfit(in);
assert(ret == 5);
in = {7, 6, 4, 3, 1};
ret = solution.maxProfit(in);
assert(ret == 0);
cout << "Success" << endl;
return 0;
}
| 18.95122 | 48 | 0.526384 | [
"vector"
] |
c88e4839e0b908a422c11def5b45b7f4d31d24c3 | 15,845 | cc | C++ | chrome/services/sharing/nearby/platform/bluetooth_socket.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | chrome/services/sharing/nearby/platform/bluetooth_socket.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | chrome/services/sharing/nearby/platform/bluetooth_socket.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/services/sharing/nearby/platform/bluetooth_socket.h"
#include <stdint.h>
#include <limits>
#include <vector>
#include "base/metrics/histogram_functions.h"
#include "base/synchronization/waitable_event.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "third_party/nearby/src/cpp/platform/public/count_down_latch.h"
namespace location {
namespace nearby {
namespace chrome {
namespace {
void LogSocketReadResult(bool success) {
base::UmaHistogramBoolean("Nearby.Connections.Bluetooth.Socket.Read.Result",
success);
}
void LogSocketWriteResult(bool success) {
base::UmaHistogramBoolean("Nearby.Connections.Bluetooth.Socket.Write.Result",
success);
}
// Concrete InputStream implementation, tightly coupled to BluetoothSocket.
class InputStreamImpl : public InputStream {
public:
InputStreamImpl(scoped_refptr<base::SequencedTaskRunner> task_runner,
mojo::ScopedDataPipeConsumerHandle receive_stream)
: task_runner_(std::move(task_runner)),
receive_stream_(std::move(receive_stream)),
receive_stream_watcher_(FROM_HERE,
mojo::SimpleWatcher::ArmingPolicy::MANUAL,
task_runner_) {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
receive_stream_watcher_.Watch(
receive_stream_.get(),
MOJO_HANDLE_SIGNAL_READABLE | MOJO_HANDLE_SIGNAL_PEER_CLOSED,
MOJO_TRIGGER_CONDITION_SIGNALS_SATISFIED,
base::BindRepeating(&InputStreamImpl::ReceiveMore,
base::Unretained(this)));
}
~InputStreamImpl() override { this->Close(); }
InputStreamImpl(const InputStreamImpl&) = delete;
InputStreamImpl& operator=(const InputStreamImpl&) = delete;
// InputStream:
ExceptionOr<ByteArray> Read(std::int64_t size) override {
bool invalid_size =
size <= 0 || size > std::numeric_limits<uint32_t>::max();
if (!receive_stream_ || invalid_size) {
if (invalid_size) {
// Only log it as a read failure when |size| is out of range as in
// reality a null |receive_stream_| is an expected state after Close()
// was called normally.
LogSocketReadResult(false);
}
return {Exception::kIo};
}
pending_read_buffer_ = std::make_unique<ByteArray>(size);
pending_read_buffer_pos_ = 0;
read_waitable_event_.emplace();
task_runner_->PostTask(
FROM_HERE, base::BindOnce(&mojo::SimpleWatcher::ArmOrNotify,
base::Unretained(&receive_stream_watcher_)));
read_waitable_event_->Wait();
read_waitable_event_.reset();
pending_read_buffer_.reset();
pending_read_buffer_pos_ = 0;
// |receive_stream_| might have been reset in Close() while
// |read_waitable_event_| was waiting.
if (!receive_stream_)
return {Exception::kIo};
LogSocketReadResult(exception_or_received_byte_array_.ok());
return exception_or_received_byte_array_;
}
Exception Close() override {
if (!receive_stream_)
return {Exception::kSuccess};
// Must cancel |receive_stream_watcher_| on the same sequence it was
// initialized on.
base::WaitableEvent task_run;
task_runner_->PostTask(FROM_HERE,
base::BindOnce(
[](mojo::SimpleWatcher* receive_stream_watcher,
base::WaitableEvent* task_run) {
receive_stream_watcher->Cancel();
task_run->Signal();
},
&receive_stream_watcher_, &task_run));
task_run.Wait();
receive_stream_.reset();
// It is possible that a Read() call could still be blocking a different
// sequence via |read_waitable_event_| when Close() is called. Notably, this
// happens on the receiving device when a Nearby Share transfer finishes. If
// we only cancel the stream watcher, the Read() call will block forever. We
// trigger the event manually here, which will cause an IO exception to be
// returned from Read().
if (read_waitable_event_)
read_waitable_event_->Signal();
return {Exception::kSuccess};
}
private:
void ReceiveMore(MojoResult result, const mojo::HandleSignalsState& state) {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
DCHECK_NE(result, MOJO_RESULT_SHOULD_WAIT);
DCHECK(receive_stream_.is_valid());
DCHECK(pending_read_buffer_);
DCHECK_LT(pending_read_buffer_pos_, pending_read_buffer_->size());
DCHECK(read_waitable_event_);
if (state.peer_closed()) {
exception_or_received_byte_array_ =
ExceptionOr<ByteArray>(Exception::kIo);
read_waitable_event_->Signal();
return;
}
if (result == MOJO_RESULT_OK) {
uint32_t num_bytes = static_cast<uint32_t>(pending_read_buffer_->size() -
pending_read_buffer_pos_);
result = receive_stream_->ReadData(
pending_read_buffer_->data() + pending_read_buffer_pos_, &num_bytes,
MOJO_READ_DATA_FLAG_NONE);
if (result == MOJO_RESULT_OK)
pending_read_buffer_pos_ += num_bytes;
}
if (result == MOJO_RESULT_SHOULD_WAIT ||
pending_read_buffer_pos_ < pending_read_buffer_->size()) {
receive_stream_watcher_.ArmOrNotify();
return;
}
if (result == MOJO_RESULT_OK) {
exception_or_received_byte_array_ =
ExceptionOr<ByteArray>(std::move(*pending_read_buffer_));
} else {
exception_or_received_byte_array_ =
ExceptionOr<ByteArray>(Exception::kIo);
}
read_waitable_event_->Signal();
}
scoped_refptr<base::SequencedTaskRunner> task_runner_;
mojo::ScopedDataPipeConsumerHandle receive_stream_;
mojo::SimpleWatcher receive_stream_watcher_;
std::unique_ptr<ByteArray> pending_read_buffer_;
uint32_t pending_read_buffer_pos_ = 0;
ExceptionOr<ByteArray> exception_or_received_byte_array_;
base::Optional<base::WaitableEvent> read_waitable_event_;
};
// Concrete OutputStream implementation, tightly coupled to BluetoothSocket.
class OutputStreamImpl : public OutputStream {
public:
OutputStreamImpl(scoped_refptr<base::SequencedTaskRunner> task_runner,
mojo::ScopedDataPipeProducerHandle send_stream)
: task_runner_(std::move(task_runner)),
send_stream_(std::move(send_stream)),
send_stream_watcher_(FROM_HERE,
mojo::SimpleWatcher::ArmingPolicy::MANUAL,
task_runner_) {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
send_stream_watcher_.Watch(
send_stream_.get(),
MOJO_HANDLE_SIGNAL_WRITABLE | MOJO_HANDLE_SIGNAL_PEER_CLOSED,
MOJO_TRIGGER_CONDITION_SIGNALS_SATISFIED,
base::BindRepeating(&OutputStreamImpl::SendMore,
base::Unretained(this)));
}
~OutputStreamImpl() override { this->Close(); }
OutputStreamImpl(const OutputStreamImpl&) = delete;
OutputStreamImpl& operator=(const OutputStreamImpl&) = delete;
// OutputStream:
Exception Write(const ByteArray& data) override {
if (!send_stream_)
return {Exception::kIo};
DCHECK(!write_success_);
pending_write_buffer_ = std::make_unique<ByteArray>(data);
pending_write_buffer_pos_ = 0;
write_waitable_event_.emplace();
task_runner_->PostTask(
FROM_HERE, base::BindOnce(&mojo::SimpleWatcher::ArmOrNotify,
base::Unretained(&send_stream_watcher_)));
write_waitable_event_->Wait();
Exception result = {write_success_ ? Exception::kSuccess : Exception::kIo};
write_success_ = false;
pending_write_buffer_.reset();
pending_write_buffer_pos_ = 0;
write_waitable_event_.reset();
// |send_stream_| might have been reset in Close() while
// |write_waitable_event_| was waiting.
if (!send_stream_)
return {Exception::kIo};
// Ignore a null |send_stream_| when logging since it might be an expected
// state as mentioned above.
LogSocketWriteResult(result.Ok());
return result;
}
Exception Flush() override {
// TODO(hansberry): Unsure if anything can reasonably be done here. Need to
// ask a reviewer from the Nearby team.
return {Exception::kSuccess};
}
Exception Close() override {
if (!send_stream_)
return {Exception::kSuccess};
// Must cancel |send_stream_watcher_| on the same sequence it was
// initialized on.
base::WaitableEvent task_run;
task_runner_->PostTask(FROM_HERE,
base::BindOnce(
[](mojo::SimpleWatcher* send_stream_watcher,
base::WaitableEvent* task_run) {
send_stream_watcher->Cancel();
task_run->Signal();
},
&send_stream_watcher_, &task_run));
task_run.Wait();
send_stream_.reset();
// It is possible that a Write() call could still be blocking a different
// sequence via |write_waitable_event_| when Close() is called. If we only
// cancel the stream watcher, the Write() call will block forever. We
// trigger the event manually here, which will cause an IO exception to be
// returned from Write().
if (write_waitable_event_)
write_waitable_event_->Signal();
return {Exception::kSuccess};
}
private:
void SendMore(MojoResult result, const mojo::HandleSignalsState& state) {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
DCHECK_NE(result, MOJO_RESULT_SHOULD_WAIT);
DCHECK(send_stream_.is_valid());
DCHECK(pending_write_buffer_);
DCHECK_LT(pending_write_buffer_pos_, pending_write_buffer_->size());
DCHECK(write_waitable_event_);
if (state.peer_closed()) {
write_success_ = false;
write_waitable_event_->Signal();
return;
}
if (result == MOJO_RESULT_OK) {
uint32_t num_bytes = static_cast<uint32_t>(pending_write_buffer_->size() -
pending_write_buffer_pos_);
result = send_stream_->WriteData(
pending_write_buffer_->data() + pending_write_buffer_pos_, &num_bytes,
MOJO_WRITE_DATA_FLAG_NONE);
if (result == MOJO_RESULT_OK)
pending_write_buffer_pos_ += num_bytes;
}
if (result == MOJO_RESULT_SHOULD_WAIT ||
pending_write_buffer_pos_ < pending_write_buffer_->size()) {
send_stream_watcher_.ArmOrNotify();
return;
}
write_success_ = result == MOJO_RESULT_OK;
write_waitable_event_->Signal();
}
scoped_refptr<base::SequencedTaskRunner> task_runner_;
mojo::ScopedDataPipeProducerHandle send_stream_;
mojo::SimpleWatcher send_stream_watcher_;
std::unique_ptr<ByteArray> pending_write_buffer_;
uint32_t pending_write_buffer_pos_ = 0;
bool write_success_ = false;
base::Optional<base::WaitableEvent> write_waitable_event_;
};
} // namespace
BluetoothSocket::BluetoothSocket(
bluetooth::mojom::DeviceInfoPtr device,
mojo::PendingRemote<bluetooth::mojom::Socket> socket,
mojo::ScopedDataPipeConsumerHandle receive_stream,
mojo::ScopedDataPipeProducerHandle send_stream)
: remote_device_(std::move(device)),
remote_device_ref_(*remote_device_),
task_runner_(
base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})),
socket_(std::move(socket), task_runner_) {
InitializeStreams(std::move(receive_stream), std::move(send_stream));
}
BluetoothSocket::BluetoothSocket(
api::BluetoothDevice& remote_device,
mojo::PendingRemote<bluetooth::mojom::Socket> socket,
mojo::ScopedDataPipeConsumerHandle receive_stream,
mojo::ScopedDataPipeProducerHandle send_stream)
: remote_device_ref_(remote_device),
task_runner_(
base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})),
socket_(std::move(socket), task_runner_) {
InitializeStreams(std::move(receive_stream), std::move(send_stream));
}
BluetoothSocket::~BluetoothSocket() {
Close();
// These properties must be destroyed on the same sequence they are later run
// on. See |task_runner_|.
CountDownLatch latch(2);
auto count_down_latch_callback = base::BindRepeating(
[](CountDownLatch* latch) { latch->CountDown(); }, &latch);
task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&BluetoothSocket::DestroyInputStream,
base::Unretained(this), count_down_latch_callback));
task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&BluetoothSocket::DestroyOutputStream,
base::Unretained(this), count_down_latch_callback));
latch.Await();
}
InputStream& BluetoothSocket::GetInputStream() {
DCHECK(input_stream_);
return *input_stream_;
}
OutputStream& BluetoothSocket::GetOutputStream() {
DCHECK(output_stream_);
return *output_stream_;
}
Exception BluetoothSocket::Close() {
if (socket_) {
socket_->Disconnect();
socket_.reset();
}
Exception input_exception = input_stream_->Close();
Exception output_exception = output_stream_->Close();
if (input_exception.Ok() && output_exception.Ok())
return {Exception::kSuccess};
if (!input_exception.Ok())
return input_exception;
if (!output_exception.Ok())
return output_exception;
NOTREACHED();
return {Exception::kFailed};
}
api::BluetoothDevice* BluetoothSocket::GetRemoteDevice() {
return &remote_device_ref_;
}
void BluetoothSocket::InitializeStreams(
mojo::ScopedDataPipeConsumerHandle receive_stream,
mojo::ScopedDataPipeProducerHandle send_stream) {
// These properties must be created on the same sequence they are later run
// on. See |task_runner_|.
CountDownLatch latch(2);
auto count_down_latch_callback = base::BindRepeating(
[](CountDownLatch* latch) { latch->CountDown(); }, &latch);
task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&BluetoothSocket::CreateInputStream,
base::Unretained(this), std::move(receive_stream),
count_down_latch_callback));
task_runner_->PostTask(
FROM_HERE, base::BindOnce(&BluetoothSocket::CreateOutputStream,
base::Unretained(this), std::move(send_stream),
count_down_latch_callback));
latch.Await();
}
void BluetoothSocket::CreateInputStream(
mojo::ScopedDataPipeConsumerHandle receive_stream,
base::OnceClosure callback) {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
input_stream_ = std::make_unique<InputStreamImpl>(task_runner_,
std::move(receive_stream));
std::move(callback).Run();
}
void BluetoothSocket::DestroyInputStream(base::OnceClosure callback) {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
input_stream_.reset();
std::move(callback).Run();
}
void BluetoothSocket::CreateOutputStream(
mojo::ScopedDataPipeProducerHandle send_stream,
base::OnceClosure callback) {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
output_stream_ =
std::make_unique<OutputStreamImpl>(task_runner_, std::move(send_stream));
std::move(callback).Run();
}
void BluetoothSocket::DestroyOutputStream(base::OnceClosure callback) {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
output_stream_.reset();
std::move(callback).Run();
}
} // namespace chrome
} // namespace nearby
} // namespace location
| 35.447427 | 80 | 0.682108 | [
"vector"
] |
c88e7476d3110169f30da2563d03b6ea2bf5d9c4 | 7,653 | cpp | C++ | src/base.cpp | lorenzosquadrani/plasticity | 6ae648fe537ebbff8432ec04beb58e4acac5871e | [
"MIT"
] | 5 | 2020-11-06T16:30:24.000Z | 2022-02-09T21:20:41.000Z | src/base.cpp | Nico-Curti/plasticity | 8159871d0aa31b096788e5aab785a1a969725ddf | [
"MIT"
] | null | null | null | src/base.cpp | Nico-Curti/plasticity | 8159871d0aa31b096788e5aab785a1a969725ddf | [
"MIT"
] | 4 | 2020-11-25T14:22:48.000Z | 2021-08-07T10:45:22.000Z | #include <base.h>
float BasePlasticity :: precision = 1e-30f;
BasePlasticity :: BasePlasticity () : optimizer (), w_init (), weights (), history (), theta (), activation (nullptr), gradient (nullptr),
batch (100), outputs (100), epochs_for_convergency (0), convergency_atol (0.f),
decay (0.f)
{
}
BasePlasticity :: BasePlasticity (const int & outputs, const int & batch_size, int activation,
update_args optimizer,
weights_initialization weights_init,
int epochs_for_convergency, float convergency_atol,
float decay
) : optimizer (optimizer), w_init (weights_init), weights (), history (), theta (), activation (nullptr), gradient (nullptr),
batch (batch_size), outputs (outputs), epochs_for_convergency (epochs_for_convergency), convergency_atol (convergency_atol),
decay (decay)
{
// correct epochs_for_convergency
//this->epochs_for_convergency = std :: max(this->epochs_for_convergency, 1);
this->activation = transfer :: activate( activation );
this->gradient = transfer :: gradient( activation );
}
BasePlasticity :: BasePlasticity (const BasePlasticity & b)
{
this->activation = b.activation;
this->gradient = b.gradient;
this->batch = b.batch;
this->outputs = b.outputs;
this->epochs_for_convergency = b.epochs_for_convergency;
this->convergency_atol = b.convergency_atol;
this->optimizer = b.optimizer;
this->w_init = b.w_init;
this->weights = b.weights;
//this->theta = b.theta; // it is useless
}
BasePlasticity & BasePlasticity :: operator = (const BasePlasticity & b)
{
this->activation = b.activation;
this->gradient = b.gradient;
this->batch = b.batch;
this->outputs = b.outputs;
this->epochs_for_convergency = b.epochs_for_convergency;
this->convergency_atol = b.convergency_atol;
this->optimizer = b.optimizer;
this->w_init = b.w_init;
this->weights = b.weights;
//this->theta = b.theta; // it is useless
return *this;
}
float * BasePlasticity :: predict (float * X, const int & n_samples, const int & n_features)
{
// convert the input array to Eigen matrix
Eigen :: Map < Eigen :: Matrix < float, Eigen :: Dynamic, Eigen :: Dynamic, Eigen :: RowMajor > > data(X, n_samples, n_features);
// call the "real" function
return this->predict(data);
}
float * BasePlasticity :: predict (const Eigen :: MatrixXf & X)
{
// extracthe the number of features as the number of columns of the input matrix
const int n_features = X.cols();
// check if the model has already stored the weights matrix (aka the fit function has already run)
this->check_is_fitted ();
// check if the input dimensions are consistent with the training ones
this->check_dims (n_features);
// perform the prediction using the core (overrided) function
Eigen :: MatrixXf output = this->_predict (X);
return output.data();
}
void BasePlasticity :: save_weights (const std :: string & filename)
{
// check if the model has already stored the weights matrix (aka the fit function has already run)
this->check_is_fitted ();
// open the output stream file as binary
std :: ofstream os(filename, std :: ios :: out | std :: ios :: binary | std :: ios :: trunc);
// temporary variables for the matrix shape
typename Eigen :: MatrixXf :: Index rows = this->weights.rows();
typename Eigen :: MatrixXf :: Index cols = this->weights.cols();
// dump the shape variables
os.write((char *) (&rows), sizeof ( typename Eigen :: MatrixXf :: Index ) );
os.write((char *) (&cols), sizeof ( typename Eigen :: MatrixXf :: Index ) );
// dump the matrix data buffer
os.write((char *) this->weights.data(), rows * cols * sizeof ( typename Eigen :: MatrixXf :: Scalar) );
// close the file stream
os.close();
}
void BasePlasticity :: load_weights (const std :: string & filename)
{
// check if the provided file exists trying to open it
if ( ! utils :: file_exists(filename) )
// throw the exception with the appropriated error
throw std :: runtime_error("File not found. Given : " + filename);
// open the file stream as binary
std :: ifstream is(filename, std :: ios :: in | std :: ios :: binary);
// temporary variables for the matrix shape
typename Eigen :: MatrixXf :: Index rows = 0;
typename Eigen :: MatrixXf :: Index cols = 0;
// read the shape variables
is.read((char*) (&rows), sizeof ( typename Eigen :: MatrixXf :: Index ) );
is.read((char*) (&cols), sizeof ( typename Eigen :: MatrixXf :: Index ) );
// resize the weights matrix
this->weights.resize(rows, cols);
// read the matrix data buffer
is.read( (char *) this->weights.data(), rows * cols * sizeof ( typename Eigen :: MatrixXf :: Scalar) );
// close the file stream
is.close();
}
float * BasePlasticity :: get_weights ()
{
// extract the pointer to the data stored into the weight Eigen Matrix
return this->weights.data();
}
// Private members
void BasePlasticity :: check_dims (const int & n_features)
{
// Check the shape consistency between the input data (n_samples, n_features)
// and the weights matrix (outputs, n_features)
// This function is used just to be sure that the dataset provided for the
// prediction are consistent with the data (shape) provided for the training
if ( this->outputs * n_features != this->weights.size() )
throw std :: runtime_error("Invalid dimensions found. The input (n_samples, n_features) shape is inconsistent with the number of weights (" + std :: to_string(this->weights.size()) + ")");
}
void BasePlasticity :: check_is_fitted ()
{
// If the model has not yet called the fit function the weights matrix is empty!
if ( this->weights.rows() == 0 && this->weights.cols() == 0 )
throw std :: runtime_error("Fitted error. The model is not fitted yet.\n"
"Please call the fit function before using the predict member.");
}
void BasePlasticity :: check_params ()
{
// the number of epochs for the convergency must be a positive non null integer!
if ( this->epochs_for_convergency <= 0 )
throw std :: runtime_error("epochs_for_convergency must be an integer bigger or equal than 1");
}
bool BasePlasticity :: check_convergence (const Eigen :: ArrayXf & vec)
{
// If the history queue is not full append the last (current) vector to the history
if ( static_cast < int >(this->history.size()) < this->epochs_for_convergency )
{
this->history.emplace_back(vec);
return false;
}
// Otherwise evaluate the distances between the current vector
// and the history arrays. The distance is evaluated as the abs differences
// between each historical vector and the current one.
// If the maximum value of the differences is lower than the given tollerance
// the convergency is reached and a stop is returned.
for (int i = 0; i < this->epochs_for_convergency; ++i)
{
// compute the vector of abs differences
const bool equal = vec.isApprox(this->history[i], this->convergency_atol);
if ( !equal )
return true;
}
// Since this is the case in which the history queue is full
// we have to remove the older vector and append the current one (LIFO behavior)
this->history.pop_front();
this->history.emplace_back(vec);
return false;
}
Eigen :: MatrixXf BasePlasticity :: _predict (__unused const Eigen :: MatrixXf & data)
{
return Eigen :: MatrixXf {};
}
| 36.793269 | 192 | 0.665099 | [
"shape",
"vector",
"model"
] |
c88e8503ccd121338212e19cb73b6f4887bca73c | 3,568 | hh | C++ | extern/glow/src/glow/common/array_view.hh | rovedit/Fort-Candle | 445fb94852df56c279c71b95c820500e7fb33cf7 | [
"MIT"
] | null | null | null | extern/glow/src/glow/common/array_view.hh | rovedit/Fort-Candle | 445fb94852df56c279c71b95c820500e7fb33cf7 | [
"MIT"
] | null | null | null | extern/glow/src/glow/common/array_view.hh | rovedit/Fort-Candle | 445fb94852df56c279c71b95c820500e7fb33cf7 | [
"MIT"
] | null | null | null | #pragma once
#include <cstddef>
#include <initializer_list>
#include <type_traits>
#include <utility>
#include <typed-geometry/feature/assert.hh>
namespace glow
{
template <class T>
struct array_view;
namespace detail
{
template <class Range, class T, class = void>
struct convertible_to_array_view_t : std::false_type
{
};
template <class Range, class T>
struct convertible_to_array_view_t<Range,
T,
std::void_t<decltype(static_cast<T*>(std::declval<Range>().data()), static_cast<size_t>(std::declval<Range>().size()))>>
: std::true_type
{
};
template <class Range, class T>
static constexpr inline bool convertible_to_array_view = convertible_to_array_view_t<Range, T>::value;
}
// A non-owning wrapper around contiguous data
// CAUTION: only use this as a parameter, never as a member!
template <class T>
struct array_view
{
using element_type = T;
using value_type = std::remove_cv_t<T>;
using index_type = size_t;
using different_type = std::ptrdiff_t;
using pointer = T*;
using const_pointer = T const*;
using reference = T&;
using const_reference = T const&;
using iterator = T*;
using const_iterator = T const*;
using void_t = std::conditional_t<std::is_const_v<T>, void const, void>;
constexpr array_view() = default;
template <size_t N>
constexpr array_view(T (&a)[N]) : _data(a), _size(N)
{
}
constexpr array_view(std::initializer_list<std::remove_const_t<T>> l) : _data(l.begin()), _size(l.size())
{
static_assert(std::is_const_v<T>, "the initializer_list ctor only works for const types");
}
constexpr explicit array_view(T* data, size_t size) : _data(data), _size(size) {}
constexpr explicit array_view(void_t* data, size_t size) : _data(reinterpret_cast<T*>(data)), _size(size) {}
template <class Range, class = std::enable_if_t<detail::convertible_to_array_view<Range, T>>>
constexpr array_view(Range&& r) : _data(static_cast<T*>(r.data())), _size(static_cast<size_t>(r.size()))
{
}
constexpr T* data() const { return _data; }
constexpr size_t size() const { return _size; }
constexpr T* begin() const { return _data; }
constexpr T* end() const { return _data + _size; }
constexpr T& operator[](size_t s) const
{
TG_ASSERT(s < _size && "out of bounds");
return _data[s];
}
constexpr bool empty() const { return _size == 0; }
array_view<std::byte const> as_bytes() const
{
#ifndef GLOW_HAS_GLM
static_assert(std::is_trivially_copyable_v<T>, "cannot make byte view for non-trivial type");
#endif
return array_view<std::byte const>{reinterpret_cast<std::byte const*>(_data), _size * sizeof(T)};
}
private:
T* _data = nullptr;
size_t _size = 0;
};
namespace detail
{
template <class Range>
constexpr bool can_make_array_view = convertible_to_array_view<Range, void const>;
}
template <class Range, class = std::enable_if_t<detail::can_make_array_view<Range>>>
auto make_array_view(Range&& r)
{
using T = std::remove_reference_t<decltype(r.data()[0])>;
return array_view<T>(std::forward<Range>(r));
}
template <class T>
array_view<std::byte const> as_byte_view(T const& v)
{
if constexpr (detail::can_make_array_view<T const&>)
return make_array_view(v).as_bytes();
else
{
#ifndef GLOW_HAS_GLM
static_assert(std::is_trivially_copyable_v<T>, "type must be trivial");
#endif
return array_view<T const>(&v, 1).as_bytes();
}
}
}
| 28.774194 | 155 | 0.673487 | [
"geometry"
] |
c890d6538406f7017a4f44a6e6f694352e91a210 | 4,567 | cpp | C++ | Source/Game/GunObjects/Bullet.cpp | nathanlink169/3D-Shaders-Test | 2493fb71664d75100fbb4a80ac70f657a189593d | [
"MIT"
] | null | null | null | Source/Game/GunObjects/Bullet.cpp | nathanlink169/3D-Shaders-Test | 2493fb71664d75100fbb4a80ac70f657a189593d | [
"MIT"
] | null | null | null | Source/Game/GunObjects/Bullet.cpp | nathanlink169/3D-Shaders-Test | 2493fb71664d75100fbb4a80ac70f657a189593d | [
"MIT"
] | null | null | null | #include "CommonHeader.h"
Bullet::Bullet(unsigned int renderOrder,Scene* aScene, std::string aName, std::string aTag, Vector3 aPosition, Vector3 aRotation, Vector3 aScale, Mesh* aMesh, ShaderProgram* aShader, Material* aTexture)
: GameObject(renderOrder, aScene, aName, aTag, aPosition, aRotation, aScale, aMesh, aShader, aTexture)
{
AddPhysicsBox(vec2(0.1f, 0.1f), true,true);
GetPhysicsBody()->SetGravityScale(0.0f);
GetPhysicsBody()->SetActive(false);
SetFilterData(BULLET, ENEMY | BLOCKS);
m_BasePosition = vec2(0, 0);
m_Velocity = vec2(0, 0);
}
Bullet::~Bullet()
{
npw::SafeDeleteVector(m_Modifiers);
}
void Bullet::Update(double TimePassed)
{
GameObject::Update(TimePassed);
for (uint i = 0; i < m_Modifiers.size(); i++)
m_Modifiers[i]->Update(TimePassed);
m_BasePosition += m_Velocity * (float)TimePassed;
vec2 pos = GetPositionOffset();
float mag = pos.Length();
float angle = (float)npw::ToDegrees(pos.Angle());
angle += (float)npw::ToDegrees(m_BasePosition.Angle());
angle = (float)npw::ToRadians(angle);
pos = vec2(cos(angle) * mag, sin(angle) * mag) + m_BasePosition;
SetPosition(vec3(pos.x, pos.y, 0));
m_TimeRemaining -= (float)TimePassed;
if (m_TimeRemaining < 0.0f)
{
ReturnToPool();
}
}
void Bullet::ReturnToPool()
{
GameScene* pTest = (GameScene*)m_Scene;
pTest->ReturnBullet(this);
}
void Bullet::SetModifiers(std::vector<BulletModifier*> aModifiers)
{
// Ensure that there are no modifiers already in
npw::SafeDeleteVector(m_Modifiers);
for (uint i = 0; i < aModifiers.size(); i++)
{
BulletModifier* mod;
switch (aModifiers[i]->GetType())
{
case BM_Sin:
mod = new SinBulletModifier(aModifiers[i]);
break;
case BM_Speed:
mod = new SpeedBulletModifier(aModifiers[i]);
break;
case BM_AirMine:
mod = new AirMineBulletModifier(aModifiers[i]);
break;
case BM_Circle:
mod = new CircleBulletModifier(aModifiers[i]);
break;
case BM_Bouncy:
mod = new BouncyBulletModifier(aModifiers[i]);
break;
case BM_Fire:
mod = new FireBulletModifier(aModifiers[i]);
break;
case BM_Freeze:
mod = new FreezeBulletModifer(aModifiers[i]);
break;
case BM_Poison:
mod = new PoisonBulletModifer(aModifiers[i]);
break;
case BM_SuperSin:
mod = new SuperSinusoidalBulletModifier(aModifiers[i]);
break;
case BM_Damage:
mod = new DamageBulletModifier(aModifiers[i]);
break;
default:
npw::BreakIfTrue(true);
break;
}
m_Modifiers.push_back(mod);
}
}
float Bullet::GetAttackPower()
{
float power = BULLET_BASE_ATTACK_POWER;
for (unsigned int i = 0; i < m_Modifiers.size(); i++)
power *= m_Modifiers[i]->GetAttackModifier();
return power;
}
float Bullet::GetAttackSpeed()
{
float speed = BULLET_BASE_ATTACK_SPEED;
for (unsigned int i = 0; i < m_Modifiers.size(); i++)
speed *= m_Modifiers[i]->GetSpeedModifier();
return speed;
}
void Bullet::Initialize(vec2 aPosition, vec2 aVelocity, std::vector<BulletModifier*> aModifiers)
{
SetModifiers(aModifiers);
m_BasePosition = aPosition;
GetPhysicsBody()->SetLinearVelocity(b2Vec2(0.0f, 0.0f));
SetPosition(vec3(aPosition.x, aPosition.y, 0));
aVelocity = aVelocity.Normalize();
GetPhysicsBody()->ApplyLinearImpulse(npw::vec2_To_b2Vec2(aVelocity * GetAttackSpeed()), GetPhysicsBody()->GetWorldCenter(), true);
GetPhysicsBody()->SetActive(true);
m_Velocity = npw::b2Vec2_To_vec2(GetPhysicsBody()->GetLinearVelocity());
m_TimeRemaining = BULLET_LIFETIME;
}
vec2 Bullet::GetPositionOffset()
{
vec2 offset;
offset.x = 0;
offset.y = 0;
for (unsigned int i = 0; i < m_Modifiers.size(); i++)
{
offset.x += m_Modifiers[i]->GetPositionOffset().x;
offset.y += m_Modifiers[i]->GetPositionOffset().y;
}
return offset;
}
std::vector<Effect*> Bullet::GetEffects(bool copy)
{
std::vector<Effect*> effects;
for (uint i = 0; i < m_Modifiers.size(); i++)
{
Effect* effect = m_Modifiers[i]->GetEffect();
if (effect != nullptr)
effects.push_back(effect);
}
if (!copy)
return effects;
else
{
std::vector<Effect*> newEffects;
for (uint i = 0; i < effects.size(); i++)
newEffects.push_back(new Effect(effects[i]));
return newEffects;
}
}
void Bullet::Reset()
{
SetPosition(Vector3(0, 300, 0));
} | 25.372222 | 202 | 0.648128 | [
"mesh",
"vector"
] |
c89139f5e361a7238b5960a5d28aaedaf1399021 | 1,200 | cpp | C++ | Engine/Graphics/GXM/GXMVertexArray.cpp | guimeixen/Engine | fcea39d2099b613b32b20462586e1c932bbb24fc | [
"MIT"
] | null | null | null | Engine/Graphics/GXM/GXMVertexArray.cpp | guimeixen/Engine | fcea39d2099b613b32b20462586e1c932bbb24fc | [
"MIT"
] | 17 | 2021-03-12T18:19:07.000Z | 2021-08-06T21:25:35.000Z | Engine/Graphics/GXM/GXMVertexArray.cpp | guimeixen/Engine | fcea39d2099b613b32b20462586e1c932bbb24fc | [
"MIT"
] | null | null | null | #include "GXMVertexArray.h"
#include "Graphics/Buffers.h"
namespace Engine
{
GXMVertexArray::GXMVertexArray(const VertexInputDesc &desc, Buffer *vertexBuffer, Buffer *indexBuffer)
{
if (!vertexBuffer)
return;
if (indexBuffer)
{
this->indexBuffer = indexBuffer;
}
vertexBuffer->AddReference();
vertexBuffers.push_back(vertexBuffer); // Limit vertex buffers? To avoid the dynamic memory allocation
vertexInputDescs.push_back(desc);
}
GXMVertexArray::GXMVertexArray(const VertexInputDesc *descs, unsigned int descCount, const std::vector<Buffer*> &vertexBuffers, Buffer *indexBuffer)
{
if (vertexBuffers.size() == 0 || !descs)
return;
if (indexBuffer)
{
this->indexBuffer = indexBuffer;
}
for (size_t i = 0; i < vertexBuffers.size(); i++)
{
vertexBuffers[i]->AddReference();
this->vertexBuffers.push_back(vertexBuffers[i]);
}
for (unsigned int i = 0; i < descCount; i++)
{
vertexInputDescs.push_back(descs[i]);
}
}
GXMVertexArray::~GXMVertexArray()
{
}
void GXMVertexArray::AddVertexBuffer(Buffer *vertexBuffer)
{
if (!vertexBuffer)
return;
vertexBuffer->AddReference();
vertexBuffers.push_back(vertexBuffer);
}
}
| 20.689655 | 149 | 0.706667 | [
"vector"
] |
c891b64ec2392c4e77d4761c65cc66f7a1600dc3 | 9,716 | cc | C++ | src/loginsvr/interface.cc | lujingwei002/coord-cproj-minigame | 06c0afa8c23382aa566cbd2fb514c1a58382c0a4 | [
"MIT"
] | null | null | null | src/loginsvr/interface.cc | lujingwei002/coord-cproj-minigame | 06c0afa8c23382aa566cbd2fb514c1a58382c0a4 | [
"MIT"
] | null | null | null | src/loginsvr/interface.cc | lujingwei002/coord-cproj-minigame | 06c0afa8c23382aa566cbd2fb514c1a58382c0a4 | [
"MIT"
] | null | null | null | /*
** Lua binding: loginsvr
** Generated automatically by tolua++-1.0.92 on Thu Oct 28 15:11:36 2021.
*/
#ifndef __cplusplus
#include "stdlib.h"
#endif
#include "string.h"
#include "tolua++.h"
/* Exported function */
TOLUA_API int tolua_loginsvr_open (lua_State* tolua_S);
#include "loginsvr.h"
/* function to release collected object via destructor */
#ifdef __cplusplus
static int tolua_collect_loginsvr__LoginSvr (lua_State* tolua_S)
{
loginsvr::LoginSvr* self = (loginsvr::LoginSvr*) tolua_tousertype(tolua_S,1,0);
delete self;
return 0;
}
#endif
/* function to register type */
static void tolua_reg_types (lua_State* tolua_S)
{
tolua_usertype(tolua_S,"coord::Component");
tolua_usertype(tolua_S,"loginsvr::LoginSvrConfig");
tolua_usertype(tolua_S,"loginsvr::LoginSvr");
tolua_usertype(tolua_S,"coord::Coord");
}
/* get function: Host of class loginsvr::LoginSvrConfig */
#ifndef TOLUA_DISABLE_tolua_get_loginsvr__LoginSvrConfig_Host
static int tolua_get_loginsvr__LoginSvrConfig_Host(lua_State* tolua_S)
{
loginsvr::LoginSvrConfig* self = (loginsvr::LoginSvrConfig*) tolua_tousertype(tolua_S,1,0);
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in accessing variable 'Host'",NULL);
#endif
tolua_pushcppstring(tolua_S,(const char*)self->Host);
return 1;
}
#endif //#ifndef TOLUA_DISABLE
/* set function: Host of class loginsvr::LoginSvrConfig */
#ifndef TOLUA_DISABLE_tolua_set_loginsvr__LoginSvrConfig_Host
static int tolua_set_loginsvr__LoginSvrConfig_Host(lua_State* tolua_S)
{
loginsvr::LoginSvrConfig* self = (loginsvr::LoginSvrConfig*) tolua_tousertype(tolua_S,1,0);
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (!self) tolua_error(tolua_S,"invalid 'self' in accessing variable 'Host'",NULL);
if (!tolua_iscppstring(tolua_S,2,0,&tolua_err))
tolua_error(tolua_S,"#vinvalid type in variable assignment.",&tolua_err);
#endif
self->Host = ((std::string) tolua_tocppstring(tolua_S,2,0))
;
return 0;
}
#endif //#ifndef TOLUA_DISABLE
/* get function: Port of class loginsvr::LoginSvrConfig */
#ifndef TOLUA_DISABLE_tolua_get_loginsvr__LoginSvrConfig_Port
static int tolua_get_loginsvr__LoginSvrConfig_Port(lua_State* tolua_S)
{
loginsvr::LoginSvrConfig* self = (loginsvr::LoginSvrConfig*) tolua_tousertype(tolua_S,1,0);
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in accessing variable 'Port'",NULL);
#endif
tolua_pushnumber(tolua_S,(lua_Number)self->Port);
return 1;
}
#endif //#ifndef TOLUA_DISABLE
/* set function: Port of class loginsvr::LoginSvrConfig */
#ifndef TOLUA_DISABLE_tolua_set_loginsvr__LoginSvrConfig_Port
static int tolua_set_loginsvr__LoginSvrConfig_Port(lua_State* tolua_S)
{
loginsvr::LoginSvrConfig* self = (loginsvr::LoginSvrConfig*) tolua_tousertype(tolua_S,1,0);
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (!self) tolua_error(tolua_S,"invalid 'self' in accessing variable 'Port'",NULL);
if (!tolua_isnumber(tolua_S,2,0,&tolua_err))
tolua_error(tolua_S,"#vinvalid type in variable assignment.",&tolua_err);
#endif
self->Port = ((uint16_t) tolua_tonumber(tolua_S,2,0))
;
return 0;
}
#endif //#ifndef TOLUA_DISABLE
/* get function: User of class loginsvr::LoginSvrConfig */
#ifndef TOLUA_DISABLE_tolua_get_loginsvr__LoginSvrConfig_User
static int tolua_get_loginsvr__LoginSvrConfig_User(lua_State* tolua_S)
{
loginsvr::LoginSvrConfig* self = (loginsvr::LoginSvrConfig*) tolua_tousertype(tolua_S,1,0);
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in accessing variable 'User'",NULL);
#endif
tolua_pushcppstring(tolua_S,(const char*)self->User);
return 1;
}
#endif //#ifndef TOLUA_DISABLE
/* set function: User of class loginsvr::LoginSvrConfig */
#ifndef TOLUA_DISABLE_tolua_set_loginsvr__LoginSvrConfig_User
static int tolua_set_loginsvr__LoginSvrConfig_User(lua_State* tolua_S)
{
loginsvr::LoginSvrConfig* self = (loginsvr::LoginSvrConfig*) tolua_tousertype(tolua_S,1,0);
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (!self) tolua_error(tolua_S,"invalid 'self' in accessing variable 'User'",NULL);
if (!tolua_iscppstring(tolua_S,2,0,&tolua_err))
tolua_error(tolua_S,"#vinvalid type in variable assignment.",&tolua_err);
#endif
self->User = ((std::string) tolua_tocppstring(tolua_S,2,0))
;
return 0;
}
#endif //#ifndef TOLUA_DISABLE
/* get function: Password of class loginsvr::LoginSvrConfig */
#ifndef TOLUA_DISABLE_tolua_get_loginsvr__LoginSvrConfig_Password
static int tolua_get_loginsvr__LoginSvrConfig_Password(lua_State* tolua_S)
{
loginsvr::LoginSvrConfig* self = (loginsvr::LoginSvrConfig*) tolua_tousertype(tolua_S,1,0);
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in accessing variable 'Password'",NULL);
#endif
tolua_pushcppstring(tolua_S,(const char*)self->Password);
return 1;
}
#endif //#ifndef TOLUA_DISABLE
/* set function: Password of class loginsvr::LoginSvrConfig */
#ifndef TOLUA_DISABLE_tolua_set_loginsvr__LoginSvrConfig_Password
static int tolua_set_loginsvr__LoginSvrConfig_Password(lua_State* tolua_S)
{
loginsvr::LoginSvrConfig* self = (loginsvr::LoginSvrConfig*) tolua_tousertype(tolua_S,1,0);
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (!self) tolua_error(tolua_S,"invalid 'self' in accessing variable 'Password'",NULL);
if (!tolua_iscppstring(tolua_S,2,0,&tolua_err))
tolua_error(tolua_S,"#vinvalid type in variable assignment.",&tolua_err);
#endif
self->Password = ((std::string) tolua_tocppstring(tolua_S,2,0))
;
return 0;
}
#endif //#ifndef TOLUA_DISABLE
/* method: new of class loginsvr::LoginSvr */
#ifndef TOLUA_DISABLE_tolua_loginsvr_loginsvr_LoginSvr_new00
static int tolua_loginsvr_loginsvr_LoginSvr_new00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertable(tolua_S,1,"loginsvr::LoginSvr",0,&tolua_err) ||
!tolua_isusertype(tolua_S,2,"coord::Coord",0,&tolua_err) ||
!tolua_isnoobj(tolua_S,3,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
coord::Coord* coord = ((coord::Coord*) tolua_tousertype(tolua_S,2,0));
{
loginsvr::LoginSvr* tolua_ret = (loginsvr::LoginSvr*) new loginsvr::LoginSvr(coord);
tolua_pushusertype(tolua_S,(void*)tolua_ret,"loginsvr::LoginSvr");
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'new'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: new_local of class loginsvr::LoginSvr */
#ifndef TOLUA_DISABLE_tolua_loginsvr_loginsvr_LoginSvr_new00_local
static int tolua_loginsvr_loginsvr_LoginSvr_new00_local(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertable(tolua_S,1,"loginsvr::LoginSvr",0,&tolua_err) ||
!tolua_isusertype(tolua_S,2,"coord::Coord",0,&tolua_err) ||
!tolua_isnoobj(tolua_S,3,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
coord::Coord* coord = ((coord::Coord*) tolua_tousertype(tolua_S,2,0));
{
loginsvr::LoginSvr* tolua_ret = (loginsvr::LoginSvr*) new loginsvr::LoginSvr(coord);
tolua_pushusertype_and_takeownership(tolua_S,(void *)tolua_ret,"loginsvr::LoginSvr");
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'new'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* function: loginsvr::NewLoginSvr */
#ifndef TOLUA_DISABLE_tolua_loginsvr_loginsvr_NewLoginSvr00
static int tolua_loginsvr_loginsvr_NewLoginSvr00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isnoobj(tolua_S,1,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
{
loginsvr::LoginSvr* tolua_ret = (loginsvr::LoginSvr*) loginsvr::NewLoginSvr();
tolua_pushusertype(tolua_S,(void*)tolua_ret,"loginsvr::LoginSvr");
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'NewLoginSvr'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* Open function */
TOLUA_API int tolua_loginsvr_open (lua_State* tolua_S)
{
tolua_open(tolua_S);
tolua_reg_types(tolua_S);
tolua_module(tolua_S,NULL,0);
tolua_beginmodule(tolua_S,NULL);
tolua_module(tolua_S,"loginsvr",0);
tolua_beginmodule(tolua_S,"loginsvr");
tolua_cclass(tolua_S,"LoginSvrConfig","loginsvr::LoginSvrConfig","",NULL);
tolua_beginmodule(tolua_S,"LoginSvrConfig");
tolua_variable(tolua_S,"Host",tolua_get_loginsvr__LoginSvrConfig_Host,tolua_set_loginsvr__LoginSvrConfig_Host);
tolua_variable(tolua_S,"Port",tolua_get_loginsvr__LoginSvrConfig_Port,tolua_set_loginsvr__LoginSvrConfig_Port);
tolua_variable(tolua_S,"User",tolua_get_loginsvr__LoginSvrConfig_User,tolua_set_loginsvr__LoginSvrConfig_User);
tolua_variable(tolua_S,"Password",tolua_get_loginsvr__LoginSvrConfig_Password,tolua_set_loginsvr__LoginSvrConfig_Password);
tolua_endmodule(tolua_S);
#ifdef __cplusplus
tolua_cclass(tolua_S,"LoginSvr","loginsvr::LoginSvr","coord::Component",tolua_collect_loginsvr__LoginSvr);
#else
tolua_cclass(tolua_S,"LoginSvr","loginsvr::LoginSvr","coord::Component",NULL);
#endif
tolua_beginmodule(tolua_S,"LoginSvr");
tolua_function(tolua_S,"new",tolua_loginsvr_loginsvr_LoginSvr_new00);
tolua_function(tolua_S,"new_local",tolua_loginsvr_loginsvr_LoginSvr_new00_local);
tolua_function(tolua_S,".call",tolua_loginsvr_loginsvr_LoginSvr_new00_local);
tolua_endmodule(tolua_S);
tolua_function(tolua_S,"NewLoginSvr",tolua_loginsvr_loginsvr_NewLoginSvr00);
tolua_endmodule(tolua_S);
tolua_endmodule(tolua_S);
return 1;
}
#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 501
extern "C"{
TOLUA_API int luaopen_loginsvr (lua_State* tolua_S) {
return tolua_loginsvr_open(tolua_S);
};
}
#endif
| 33.853659 | 127 | 0.776142 | [
"object"
] |
c8971f762dce988778f37cc928af2fc1459b088d | 8,557 | cpp | C++ | toonz/sources/stdfx/iwa_bokehreffx.cpp | rozhuk-im/opentoonz | ad5b632512746b97fd526aa79660fbaedf934fad | [
"BSD-3-Clause"
] | 3,710 | 2016-03-26T00:40:48.000Z | 2022-03-31T21:35:12.000Z | toonz/sources/stdfx/iwa_bokehreffx.cpp | rozhuk-im/opentoonz | ad5b632512746b97fd526aa79660fbaedf934fad | [
"BSD-3-Clause"
] | 4,246 | 2016-03-26T01:21:45.000Z | 2022-03-31T23:10:47.000Z | toonz/sources/stdfx/iwa_bokehreffx.cpp | rozhuk-im/opentoonz | ad5b632512746b97fd526aa79660fbaedf934fad | [
"BSD-3-Clause"
] | 633 | 2016-03-26T00:42:25.000Z | 2022-03-17T02:55:13.000Z | #include "iwa_bokehreffx.h"
#include "trop.h"
#include <QReadWriteLock>
#include <QSet>
#include <QMap>
#include <math.h>
namespace {
QReadWriteLock lock;
QMutex fx_mutex;
template <typename T>
TRasterGR8P allocateRasterAndLock(T** buf, TDimensionI dim) {
TRasterGR8P ras(dim.lx * sizeof(T), dim.ly);
ras->lock();
*buf = (T*)ras->getRawData();
return ras;
}
// release all registered raster memories
void releaseAllRasters(QList<TRasterGR8P>& rasterList) {
for (int r = 0; r < rasterList.size(); r++) rasterList.at(r)->unlock();
}
// release all registered raster memories and free all fft plans
void releaseAllRastersAndPlans(QList<TRasterGR8P>& rasterList,
QList<kiss_fftnd_cfg>& planList) {
releaseAllRasters(rasterList);
for (int p = 0; p < planList.size(); p++) kiss_fft_free(planList.at(p));
}
}; // namespace
//============================================================
//------------------------------------------------------------
// normalize brightness of the depth reference image to unsigned char
// and store into detMem
//------------------------------------------------------------
template <typename RASTER, typename PIXEL>
void Iwa_BokehRefFx::setDepthRaster(const RASTER srcRas, unsigned char* dstMem,
TDimensionI dim) {
unsigned char* depth_p = dstMem;
for (int j = 0; j < dim.ly; j++) {
PIXEL* pix = srcRas->pixels(j);
for (int i = 0; i < dim.lx; i++, pix++, depth_p++) {
// normalize brightness to 0-1
double val = ((double)pix->r * 0.3 + (double)pix->g * 0.59 +
(double)pix->b * 0.11) /
(double)PIXEL::maxChannelValue;
// convert to unsigned char
(*depth_p) = (unsigned char)(val * (double)UCHAR_MAX + 0.5);
}
}
}
template <typename RASTER, typename PIXEL>
void Iwa_BokehRefFx::setDepthRasterGray(const RASTER srcRas,
unsigned char* dstMem,
TDimensionI dim) {
unsigned char* depth_p = dstMem;
for (int j = 0; j < dim.ly; j++) {
PIXEL* pix = srcRas->pixels(j);
for (int i = 0; i < dim.lx; i++, pix++, depth_p++) {
// normalize brightness to 0-1
double val = (double)pix->value / (double)PIXEL::maxChannelValue;
// convert to unsigned char
(*depth_p) = (unsigned char)(val * (double)UCHAR_MAX + 0.5);
}
}
}
//--------------------------------------------
Iwa_BokehRefFx::Iwa_BokehRefFx()
: m_distancePrecision(10), m_fillGap(true), m_doMedian(true) {
// Bind parameters
addInputPort("Source", m_source);
addInputPort("Depth", m_depth);
bindParam(this, "on_focus_distance", m_onFocusDistance, false);
bindParam(this, "bokeh_amount", m_bokehAmount, false);
bindParam(this, "hardness", m_hardness, false);
bindParam(this, "distance_precision", m_distancePrecision, false);
bindParam(this, "fill_gap", m_fillGap, false);
bindParam(this, "fill_gap_with_median_filter", m_doMedian, false);
m_distancePrecision->setValueRange(3, 128);
}
//--------------------------------------------
void Iwa_BokehRefFx::doCompute(TTile& tile, double frame,
const TRenderSettings& settings) {
// If any of input is not connected, then do nothing
if (!m_iris.isConnected() || !m_source.isConnected() ||
!m_depth.isConnected()) {
tile.getRaster()->clear();
return;
}
QList<TRasterGR8P> rasterList;
// Get the pixel size of bokehAmount ( referenced ino_blur.cpp )
double bokehPixelAmount = BokehUtils::getBokehPixelAmount(
m_bokehAmount->getValue(frame), settings.m_affine);
// Obtain the larger size of bokeh between the nearest (black) point and
// the farthest (white) point, based on the focus distance.
double onFocusDistance = m_onFocusDistance->getValue(frame);
double maxIrisSize =
bokehPixelAmount * std::max((1.0 - onFocusDistance), onFocusDistance);
int margin =
(maxIrisSize > 1.0f) ? (int)(std::ceil((maxIrisSize - 1.0) / 2.0)) : 0;
// Range of computation
TRectD rectOut(tile.m_pos, TDimensionD(tile.getRaster()->getLx(),
tile.getRaster()->getLy()));
rectOut = rectOut.enlarge(static_cast<double>(margin));
TDimensionI dimOut(static_cast<int>(rectOut.getLx() + 0.5),
static_cast<int>(rectOut.getLy() + 0.5));
// Enlarge the size to the "fast size" for kissfft which has no factors other
// than 2,3, or 5.
if (dimOut.lx < 10000 && dimOut.ly < 10000) {
int new_x = kiss_fft_next_fast_size(dimOut.lx);
int new_y = kiss_fft_next_fast_size(dimOut.ly);
// margin should be integer
while ((new_x - dimOut.lx) % 2 != 0)
new_x = kiss_fft_next_fast_size(new_x + 1);
while ((new_y - dimOut.ly) % 2 != 0)
new_y = kiss_fft_next_fast_size(new_y + 1);
rectOut = rectOut.enlarge(static_cast<double>(new_x - dimOut.lx) / 2.0,
static_cast<double>(new_y - dimOut.ly) / 2.0);
dimOut.lx = new_x;
dimOut.ly = new_y;
}
// - - - Compute the input tiles - - -
// source image buffer
// double4* source_buff;
// rasterList.append(allocateRasterAndLock<double4>(&source_buff, dimOut));
LayerValue layerValue;
TRenderSettings infoOnInput(settings);
infoOnInput.m_bpp = 64;
// source tile is used only in this focus.
// normalized source image data is stored in source_buff.
layerValue.sourceTile = new TTile();
m_source->allocateAndCompute(*layerValue.sourceTile, rectOut.getP00(), dimOut,
0, frame, infoOnInput);
// - - - iris image - - -
// Get the original size of Iris image
TRectD irisBBox;
m_iris->getBBox(frame, irisBBox, settings);
// Compute the iris tile.
TTile irisTile;
m_iris->allocateAndCompute(
irisTile, irisBBox.getP00(),
TDimension(static_cast<int>(irisBBox.getLx() + 0.5),
static_cast<int>(irisBBox.getLy() + 0.5)),
tile.getRaster(), frame, settings);
// cancel check
if (settings.m_isCanceled && *settings.m_isCanceled) {
releaseAllRasters(rasterList);
tile.getRaster()->clear();
return;
}
// compute the reference image
std::vector<TRasterGR8P> ctrl_rasters; // to be stored in uchar
QMap<int, unsigned char*>
ctrls; // container of [port number, reference image buffer in uchar]
unsigned char* depth_buff;
rasterList.append(allocateRasterAndLock<unsigned char>(&depth_buff, dimOut));
{
TTile depthTile;
m_depth->allocateAndCompute(depthTile, rectOut.getP00(), dimOut,
tile.getRaster(), frame, settings);
// cancel check
if (settings.m_isCanceled && *settings.m_isCanceled) {
releaseAllRasters(rasterList);
tile.getRaster()->clear();
return;
}
// normalize brightness of the depth reference image to unsigned char
// and store into depth_buff
TRasterGR8P rasGR8 = (TRasterGR8P)depthTile.getRaster();
TRasterGR16P rasGR16 = (TRasterGR16P)depthTile.getRaster();
TRaster32P ras32 = (TRaster32P)depthTile.getRaster();
TRaster64P ras64 = (TRaster64P)depthTile.getRaster();
lock.lockForRead();
if (rasGR8)
setDepthRasterGray<TRasterGR8P, TPixelGR8>(rasGR8, depth_buff, dimOut);
else if (rasGR16)
setDepthRasterGray<TRasterGR16P, TPixelGR16>(rasGR16, depth_buff, dimOut);
else if (ras32)
BokehUtils::setDepthRaster<TRaster32P, TPixel32>(ras32, depth_buff,
dimOut);
else if (ras64)
BokehUtils::setDepthRaster<TRaster64P, TPixel64>(ras64, depth_buff,
dimOut);
lock.unlock();
}
ctrls[1] = depth_buff;
layerValue.premultiply = 2; // auto
layerValue.layerHardness = m_hardness->getValue(frame);
layerValue.depth_ref = 1;
layerValue.distance = 0.5;
layerValue.bokehAdjustment = 1.0;
layerValue.depthRange = 1.0;
layerValue.distancePrecision = m_distancePrecision->getValue();
layerValue.fillGap = m_fillGap->getValue();
layerValue.doMedian = m_doMedian->getValue();
QList<LayerValue> layerValues;
layerValues.append(layerValue);
Iwa_BokehCommonFx::doFx(tile, frame, settings, bokehPixelAmount, margin,
dimOut, irisBBox, irisTile, layerValues, ctrls);
releaseAllRasters(rasterList);
delete layerValue.sourceTile;
}
FX_PLUGIN_IDENTIFIER(Iwa_BokehRefFx, "iwa_BokehRefFx") | 36.258475 | 80 | 0.627556 | [
"vector"
] |
c8985455a6283d6378c6c74ebc0e8b96ef5fb92e | 396 | cpp | C++ | async/support/string_util.cpp | smallsunsun1/async_lib | d1e88aa73a1084a9549f884241266c8bdf568411 | [
"Apache-2.0",
"MIT"
] | null | null | null | async/support/string_util.cpp | smallsunsun1/async_lib | d1e88aa73a1084a9549f884241266c8bdf568411 | [
"Apache-2.0",
"MIT"
] | null | null | null | async/support/string_util.cpp | smallsunsun1/async_lib | d1e88aa73a1084a9549f884241266c8bdf568411 | [
"Apache-2.0",
"MIT"
] | null | null | null | #include "async/support/string_util.h"
#include <regex>
namespace sss {
std::vector<std::string> async::StrSplit(const std::string &s,
const std::string &delimer) {
std::regex re(delimer);
std::vector<std::string> v(
std::sregex_token_iterator(s.begin(), s.end(), re, -1),
std::sregex_token_iterator());
return v;
}
} // namespace sss | 28.285714 | 70 | 0.60101 | [
"vector"
] |
c899d7ac042ef721b0281207f1ad3d75557dccec | 34,165 | cpp | C++ | src/qt/qtwebkit/Source/WebCore/platform/win/PasteboardWin.cpp | viewdy/phantomjs | eddb0db1d253fd0c546060a4555554c8ee08c13c | [
"BSD-3-Clause"
] | 1 | 2015-05-27T13:52:20.000Z | 2015-05-27T13:52:20.000Z | src/qt/qtwebkit/Source/WebCore/platform/win/PasteboardWin.cpp | mrampersad/phantomjs | dca6f77a36699eb4e1c46f7600cca618f01b0ac3 | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtwebkit/Source/WebCore/platform/win/PasteboardWin.cpp | mrampersad/phantomjs | dca6f77a36699eb4e1c46f7600cca618f01b0ac3 | [
"BSD-3-Clause"
] | 1 | 2022-02-18T10:41:38.000Z | 2022-02-18T10:41:38.000Z | /*
* Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
* Copyright (C) 2013 Xueqing Huang <huangxueqing@baidu.com>
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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.
*/
#include "config.h"
#include "Pasteboard.h"
#include "BitmapInfo.h"
#include "CachedImage.h"
#include "ClipboardUtilitiesWin.h"
#include "Document.h"
#include "DocumentFragment.h"
#include "Editor.h"
#include "Element.h"
#include "Frame.h"
#include "HTMLNames.h"
#include "HTMLParserIdioms.h"
#include "HWndDC.h"
#include "HitTestResult.h"
#include "Image.h"
#include "KURL.h"
#include "NotImplemented.h"
#include "Page.h"
#include "Range.h"
#include "RenderImage.h"
#include "SharedBuffer.h"
#include "TextEncoding.h"
#include "WebCoreInstanceHandle.h"
#include "WindowsExtras.h"
#include "markup.h"
#include <wtf/text/CString.h>
namespace WebCore {
// We provide the IE clipboard types (URL and Text), and the clipboard types specified in the WHATWG Web Applications 1.0 draft
// see http://www.whatwg.org/specs/web-apps/current-work/ Section 6.3.5.3
static UINT HTMLClipboardFormat = 0;
static UINT BookmarkClipboardFormat = 0;
static UINT WebSmartPasteFormat = 0;
static LRESULT CALLBACK PasteboardOwnerWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
LRESULT lresult = 0;
switch (message) {
case WM_RENDERFORMAT:
// This message comes when SetClipboardData was sent a null data handle
// and now it's come time to put the data on the clipboard.
break;
case WM_RENDERALLFORMATS:
// This message comes when SetClipboardData was sent a null data handle
// and now this application is about to quit, so it must put data on
// the clipboard before it exits.
break;
case WM_DESTROY:
break;
#if !OS(WINCE)
case WM_DRAWCLIPBOARD:
break;
case WM_CHANGECBCHAIN:
break;
#endif
default:
lresult = DefWindowProc(hWnd, message, wParam, lParam);
break;
}
return lresult;
}
Pasteboard* Pasteboard::generalPasteboard()
{
static Pasteboard* pasteboard = new Pasteboard;
return pasteboard;
}
PassOwnPtr<Pasteboard> Pasteboard::createForCopyAndPaste()
{
OwnPtr<Pasteboard> pasteboard = adoptPtr(new Pasteboard);
COMPtr<IDataObject> clipboardData;
#if !OS(WINCE)
if (!SUCCEEDED(OleGetClipboard(&clipboardData)))
clipboardData = 0;
#endif
pasteboard->setExternalDataObject(clipboardData.get());
return pasteboard.release();
}
PassOwnPtr<Pasteboard> Pasteboard::createPrivate()
{
// Windows has no "Private pasteboard" concept.
return createForCopyAndPaste();
}
#if ENABLE(DRAG_SUPPORT)
PassOwnPtr<Pasteboard> Pasteboard::createForDragAndDrop()
{
COMPtr<WCDataObject> dataObject;
WCDataObject::createInstance(&dataObject);
return adoptPtr(new Pasteboard(dataObject.get()));
}
// static
PassOwnPtr<Pasteboard> Pasteboard::createForDragAndDrop(const DragData& dragData)
{
if (dragData.platformData())
return adoptPtr(new Pasteboard(dragData.platformData()));
// FIXME: Should add a const overload of dragDataMap so we don't need a const_cast here.
return adoptPtr(new Pasteboard(const_cast<DragData&>(dragData).dragDataMap()));
}
#endif
void Pasteboard::finishCreatingPasteboard()
{
WNDCLASS wc;
memset(&wc, 0, sizeof(WNDCLASS));
wc.lpfnWndProc = PasteboardOwnerWndProc;
wc.hInstance = WebCore::instanceHandle();
wc.lpszClassName = L"PasteboardOwnerWindowClass";
RegisterClass(&wc);
m_owner = ::CreateWindow(L"PasteboardOwnerWindowClass", L"PasteboardOwnerWindow", 0, 0, 0, 0, 0,
HWND_MESSAGE, 0, 0, 0);
HTMLClipboardFormat = ::RegisterClipboardFormat(L"HTML Format");
BookmarkClipboardFormat = ::RegisterClipboardFormat(L"UniformResourceLocatorW");
WebSmartPasteFormat = ::RegisterClipboardFormat(L"WebKit Smart Paste Format");
}
Pasteboard::Pasteboard()
: m_dataObject(0)
, m_writableDataObject(0)
{
finishCreatingPasteboard();
}
Pasteboard::Pasteboard(IDataObject* dataObject)
: m_dataObject(dataObject)
, m_writableDataObject(0)
{
finishCreatingPasteboard();
}
Pasteboard::Pasteboard(WCDataObject* dataObject)
: m_dataObject(dataObject)
, m_writableDataObject(dataObject)
{
finishCreatingPasteboard();
}
Pasteboard::Pasteboard(const DragDataMap& dataMap)
: m_dataObject(0)
, m_writableDataObject(0)
, m_dragDataMap(dataMap)
{
finishCreatingPasteboard();
}
void Pasteboard::clear()
{
if (::OpenClipboard(m_owner)) {
::EmptyClipboard();
::CloseClipboard();
}
}
enum ClipboardDataType { ClipboardDataTypeNone, ClipboardDataTypeURL, ClipboardDataTypeText, ClipboardDataTypeTextHTML };
static ClipboardDataType clipboardTypeFromMIMEType(const String& type)
{
String qType = type.stripWhiteSpace().lower();
// two special cases for IE compatibility
if (qType == "text" || qType == "text/plain" || qType.startsWith("text/plain;"))
return ClipboardDataTypeText;
if (qType == "url" || qType == "text/uri-list")
return ClipboardDataTypeURL;
if (qType == "text/html")
return ClipboardDataTypeTextHTML;
return ClipboardDataTypeNone;
}
void Pasteboard::clear(const String& type)
{
if (!m_writableDataObject)
return;
ClipboardDataType dataType = clipboardTypeFromMIMEType(type);
if (dataType == ClipboardDataTypeURL) {
m_writableDataObject->clearData(urlWFormat()->cfFormat);
m_writableDataObject->clearData(urlFormat()->cfFormat);
}
if (dataType == ClipboardDataTypeText) {
m_writableDataObject->clearData(plainTextFormat()->cfFormat);
m_writableDataObject->clearData(plainTextWFormat()->cfFormat);
}
}
bool Pasteboard::hasData()
{
if (!m_dataObject && m_dragDataMap.isEmpty())
return false;
if (m_dataObject) {
COMPtr<IEnumFORMATETC> itr;
if (FAILED(m_dataObject->EnumFormatEtc(DATADIR_GET, &itr)))
return false;
if (!itr)
return false;
FORMATETC data;
// IEnumFORMATETC::Next returns S_FALSE if there are no more items.
if (itr->Next(1, &data, 0) == S_OK) {
// There is at least one item in the IDataObject
return true;
}
return false;
}
return !m_dragDataMap.isEmpty();
}
static void addMimeTypesForFormat(ListHashSet<String>& results, const FORMATETC& format)
{
// URL and Text are provided for compatibility with IE's model
if (format.cfFormat == urlFormat()->cfFormat || format.cfFormat == urlWFormat()->cfFormat) {
results.add("URL");
results.add("text/uri-list");
}
if (format.cfFormat == plainTextWFormat()->cfFormat || format.cfFormat == plainTextFormat()->cfFormat) {
results.add("Text");
results.add("text/plain");
}
}
ListHashSet<String> Pasteboard::types()
{
ListHashSet<String> results;
if (!m_dataObject && m_dragDataMap.isEmpty())
return results;
if (m_dataObject) {
COMPtr<IEnumFORMATETC> itr;
if (FAILED(m_dataObject->EnumFormatEtc(DATADIR_GET, &itr)))
return results;
if (!itr)
return results;
FORMATETC data;
// IEnumFORMATETC::Next returns S_FALSE if there are no more items.
while (itr->Next(1, &data, 0) == S_OK)
addMimeTypesForFormat(results, data);
} else {
for (DragDataMap::const_iterator it = m_dragDataMap.begin(); it != m_dragDataMap.end(); ++it) {
FORMATETC data;
data.cfFormat = (*it).key;
addMimeTypesForFormat(results, data);
}
}
return results;
}
String Pasteboard::readString(const String& type)
{
if (!m_dataObject && m_dragDataMap.isEmpty())
return "";
ClipboardDataType dataType = clipboardTypeFromMIMEType(type);
if (dataType == ClipboardDataTypeText)
return m_dataObject ? getPlainText(m_dataObject.get()) : getPlainText(&m_dragDataMap);
if (dataType == ClipboardDataTypeURL)
return m_dataObject ? getURL(m_dataObject.get(), DragData::DoNotConvertFilenames) : getURL(&m_dragDataMap, DragData::DoNotConvertFilenames);
if (dataType == ClipboardDataTypeTextHTML) {
String data = m_dataObject ? getTextHTML(m_dataObject.get()) : getTextHTML(&m_dragDataMap);
if (!data.isEmpty())
return data;
return m_dataObject ? getCFHTML(m_dataObject.get()) : getCFHTML(&m_dragDataMap);
}
return "";
}
Vector<String> Pasteboard::readFilenames()
{
Vector<String> fileNames;
#if USE(CF)
if (m_dataObject) {
STGMEDIUM medium;
if (FAILED(m_dataObject->GetData(cfHDropFormat(), &medium)))
return fileNames;
HDROP hdrop = reinterpret_cast<HDROP>(GlobalLock(medium.hGlobal));
if (!hdrop)
return fileNames;
WCHAR filename[MAX_PATH];
UINT fileCount = DragQueryFileW(hdrop, 0xFFFFFFFF, 0, 0);
for (UINT i = 0; i < fileCount; i++) {
if (!DragQueryFileW(hdrop, i, filename, WTF_ARRAY_LENGTH(filename)))
continue;
fileNames.append(filename);
}
GlobalUnlock(medium.hGlobal);
ReleaseStgMedium(&medium);
return fileNames;
}
if (!m_dragDataMap.contains(cfHDropFormat()->cfFormat))
return fileNames;
return m_dragDataMap.get(cfHDropFormat()->cfFormat);
#else
notImplemented();
return fileNames;
#endif
}
static bool writeURL(WCDataObject *data, const KURL& url, String title, bool withPlainText, bool withHTML)
{
ASSERT(data);
if (url.isEmpty())
return false;
if (title.isEmpty()) {
title = url.lastPathComponent();
if (title.isEmpty())
title = url.host();
}
STGMEDIUM medium = {0};
medium.tymed = TYMED_HGLOBAL;
medium.hGlobal = createGlobalData(url, title);
bool success = false;
if (medium.hGlobal && FAILED(data->SetData(urlWFormat(), &medium, TRUE)))
::GlobalFree(medium.hGlobal);
else
success = true;
if (withHTML) {
Vector<char> cfhtmlData;
markupToCFHTML(urlToMarkup(url, title), "", cfhtmlData);
medium.hGlobal = createGlobalData(cfhtmlData);
if (medium.hGlobal && FAILED(data->SetData(htmlFormat(), &medium, TRUE)))
::GlobalFree(medium.hGlobal);
else
success = true;
}
if (withPlainText) {
medium.hGlobal = createGlobalData(url.string());
if (medium.hGlobal && FAILED(data->SetData(plainTextWFormat(), &medium, TRUE)))
::GlobalFree(medium.hGlobal);
else
success = true;
}
return success;
}
bool Pasteboard::writeString(const String& type, const String& data)
{
if (!m_writableDataObject)
return false;
ClipboardDataType winType = clipboardTypeFromMIMEType(type);
if (winType == ClipboardDataTypeURL)
return WebCore::writeURL(m_writableDataObject.get(), KURL(KURL(), data), String(), false, true);
if (winType == ClipboardDataTypeText) {
STGMEDIUM medium = {0};
medium.tymed = TYMED_HGLOBAL;
medium.hGlobal = createGlobalData(data);
if (!medium.hGlobal)
return false;
if (FAILED(m_writableDataObject->SetData(plainTextWFormat(), &medium, TRUE))) {
::GlobalFree(medium.hGlobal);
return false;
}
return true;
}
return false;
}
#if ENABLE(DRAG_SUPPORT)
void Pasteboard::setDragImage(DragImageRef, const IntPoint&)
{
// Do nothing in Windows.
}
#endif
void Pasteboard::writeRangeToDataObject(Range* selectedRange, Frame* frame)
{
ASSERT(selectedRange);
if (!m_writableDataObject)
return;
STGMEDIUM medium = {0};
medium.tymed = TYMED_HGLOBAL;
Vector<char> data;
markupToCFHTML(createMarkup(selectedRange, 0, AnnotateForInterchange),
selectedRange->startContainer()->document()->url().string(), data);
medium.hGlobal = createGlobalData(data);
if (medium.hGlobal && FAILED(m_writableDataObject->SetData(htmlFormat(), &medium, TRUE)))
::GlobalFree(medium.hGlobal);
String str = frame->editor().selectedTextForClipboard();
replaceNewlinesWithWindowsStyleNewlines(str);
replaceNBSPWithSpace(str);
medium.hGlobal = createGlobalData(str);
if (medium.hGlobal && FAILED(m_writableDataObject->SetData(plainTextWFormat(), &medium, TRUE)))
::GlobalFree(medium.hGlobal);
medium.hGlobal = 0;
if (frame->editor().canSmartCopyOrDelete())
m_writableDataObject->SetData(smartPasteFormat(), &medium, TRUE);
}
void Pasteboard::writeSelection(Range* selectedRange, bool canSmartCopyOrDelete, Frame* frame, ShouldSerializeSelectedTextForClipboard shouldSerializeSelectedTextForClipboard)
{
clear();
// Put CF_HTML format on the pasteboard
if (::OpenClipboard(m_owner)) {
Vector<char> data;
markupToCFHTML(createMarkup(selectedRange, 0, AnnotateForInterchange),
selectedRange->startContainer()->document()->url().string(), data);
HGLOBAL cbData = createGlobalData(data);
if (!::SetClipboardData(HTMLClipboardFormat, cbData))
::GlobalFree(cbData);
::CloseClipboard();
}
// Put plain string on the pasteboard. CF_UNICODETEXT covers CF_TEXT as well
String str = shouldSerializeSelectedTextForClipboard == IncludeImageAltTextForClipboard ? frame->editor().selectedTextForClipboard() : frame->editor().selectedText();
replaceNewlinesWithWindowsStyleNewlines(str);
replaceNBSPWithSpace(str);
if (::OpenClipboard(m_owner)) {
HGLOBAL cbData = createGlobalData(str);
if (!::SetClipboardData(CF_UNICODETEXT, cbData))
::GlobalFree(cbData);
::CloseClipboard();
}
// enable smart-replacing later on by putting dummy data on the pasteboard
if (canSmartCopyOrDelete) {
if (::OpenClipboard(m_owner)) {
::SetClipboardData(WebSmartPasteFormat, 0);
::CloseClipboard();
}
}
writeRangeToDataObject(selectedRange, frame);
}
void Pasteboard::writePlainTextToDataObject(const String& text, SmartReplaceOption smartReplaceOption)
{
if (!m_writableDataObject)
return;
STGMEDIUM medium = {0};
medium.tymed = TYMED_HGLOBAL;
String str = text;
replaceNewlinesWithWindowsStyleNewlines(str);
replaceNBSPWithSpace(str);
medium.hGlobal = createGlobalData(str);
if (medium.hGlobal && FAILED(m_writableDataObject->SetData(plainTextWFormat(), &medium, TRUE)))
::GlobalFree(medium.hGlobal);
medium.hGlobal = 0;
}
void Pasteboard::writePlainText(const String& text, SmartReplaceOption smartReplaceOption)
{
clear();
// Put plain string on the pasteboard. CF_UNICODETEXT covers CF_TEXT as well
String str = text;
replaceNewlinesWithWindowsStyleNewlines(str);
if (::OpenClipboard(m_owner)) {
HGLOBAL cbData = createGlobalData(str);
if (!::SetClipboardData(CF_UNICODETEXT, cbData))
::GlobalFree(cbData);
::CloseClipboard();
}
// enable smart-replacing later on by putting dummy data on the pasteboard
if (smartReplaceOption == CanSmartReplace) {
if (::OpenClipboard(m_owner)) {
::SetClipboardData(WebSmartPasteFormat, 0);
::CloseClipboard();
}
}
writePlainTextToDataObject(text, smartReplaceOption);
}
#if !OS(WINCE)
static inline void pathRemoveBadFSCharacters(PWSTR psz, size_t length)
{
size_t writeTo = 0;
size_t readFrom = 0;
while (readFrom < length) {
UINT type = PathGetCharType(psz[readFrom]);
if (!psz[readFrom] || type & (GCT_LFNCHAR | GCT_SHORTCHAR))
psz[writeTo++] = psz[readFrom];
readFrom++;
}
psz[writeTo] = 0;
}
#endif
static String filesystemPathFromUrlOrTitle(const String& url, const String& title, const UChar* extension, bool isLink)
{
#if OS(WINCE)
notImplemented();
return String();
#else
static const size_t fsPathMaxLengthExcludingNullTerminator = MAX_PATH - 1;
bool usedURL = false;
WCHAR fsPathBuffer[MAX_PATH];
fsPathBuffer[0] = 0;
int extensionLen = extension ? lstrlen(extension) : 0;
int fsPathMaxLengthExcludingExtension = fsPathMaxLengthExcludingNullTerminator - extensionLen;
if (!title.isEmpty()) {
size_t len = std::min<size_t>(title.length(), fsPathMaxLengthExcludingExtension);
CopyMemory(fsPathBuffer, title.characters(), len * sizeof(UChar));
fsPathBuffer[len] = 0;
pathRemoveBadFSCharacters(fsPathBuffer, len);
}
if (!lstrlen(fsPathBuffer)) {
KURL kurl(KURL(), url);
usedURL = true;
// The filename for any content based drag or file url should be the last element of
// the path. If we can't find it, or we're coming up with the name for a link
// we just use the entire url.
DWORD len = fsPathMaxLengthExcludingExtension;
String lastComponent = kurl.lastPathComponent();
if (kurl.isLocalFile() || (!isLink && !lastComponent.isEmpty())) {
len = std::min<DWORD>(fsPathMaxLengthExcludingExtension, lastComponent.length());
CopyMemory(fsPathBuffer, lastComponent.characters(), len * sizeof(UChar));
} else {
len = std::min<DWORD>(fsPathMaxLengthExcludingExtension, url.length());
CopyMemory(fsPathBuffer, url.characters(), len * sizeof(UChar));
}
fsPathBuffer[len] = 0;
pathRemoveBadFSCharacters(fsPathBuffer, len);
}
if (!extension)
return String(static_cast<UChar*>(fsPathBuffer));
if (!isLink && usedURL) {
PathRenameExtension(fsPathBuffer, extension);
return String(static_cast<UChar*>(fsPathBuffer));
}
return makeString(static_cast<const UChar*>(fsPathBuffer), extension);
#endif
}
// writeFileToDataObject takes ownership of fileDescriptor and fileContent
static HRESULT writeFileToDataObject(IDataObject* dataObject, HGLOBAL fileDescriptor, HGLOBAL fileContent, HGLOBAL hDropContent)
{
HRESULT hr = S_OK;
FORMATETC* fe;
STGMEDIUM medium = {0};
medium.tymed = TYMED_HGLOBAL;
if (!fileDescriptor || !fileContent)
goto exit;
// Descriptor
fe = fileDescriptorFormat();
medium.hGlobal = fileDescriptor;
if (FAILED(hr = dataObject->SetData(fe, &medium, TRUE)))
goto exit;
// Contents
fe = fileContentFormatZero();
medium.hGlobal = fileContent;
if (FAILED(hr = dataObject->SetData(fe, &medium, TRUE)))
goto exit;
#if USE(CF)
// HDROP
if (hDropContent) {
medium.hGlobal = hDropContent;
hr = dataObject->SetData(cfHDropFormat(), &medium, TRUE);
}
#endif
exit:
if (FAILED(hr)) {
if (fileDescriptor)
GlobalFree(fileDescriptor);
if (fileContent)
GlobalFree(fileContent);
if (hDropContent)
GlobalFree(hDropContent);
}
return hr;
}
void Pasteboard::writeURLToDataObject(const KURL& kurl, const String& titleStr, Frame* frame)
{
if (!m_writableDataObject)
return;
WebCore::writeURL(m_writableDataObject.get(), kurl, titleStr, true, true);
String url = kurl.string();
ASSERT(url.containsOnlyASCII()); // KURL::string() is URL encoded.
String fsPath = filesystemPathFromUrlOrTitle(url, titleStr, L".URL", true);
String contentString("[InternetShortcut]\r\nURL=" + url + "\r\n");
CString content = contentString.latin1();
if (fsPath.length() <= 0)
return;
HGLOBAL urlFileDescriptor = GlobalAlloc(GPTR, sizeof(FILEGROUPDESCRIPTOR));
if (!urlFileDescriptor)
return;
HGLOBAL urlFileContent = GlobalAlloc(GPTR, content.length());
if (!urlFileContent) {
GlobalFree(urlFileDescriptor);
return;
}
FILEGROUPDESCRIPTOR* fgd = static_cast<FILEGROUPDESCRIPTOR*>(GlobalLock(urlFileDescriptor));
ZeroMemory(fgd, sizeof(FILEGROUPDESCRIPTOR));
fgd->cItems = 1;
fgd->fgd[0].dwFlags = FD_FILESIZE;
fgd->fgd[0].nFileSizeLow = content.length();
unsigned maxSize = std::min<unsigned>(fsPath.length(), WTF_ARRAY_LENGTH(fgd->fgd[0].cFileName));
CopyMemory(fgd->fgd[0].cFileName, fsPath.characters(), maxSize * sizeof(UChar));
GlobalUnlock(urlFileDescriptor);
char* fileContents = static_cast<char*>(GlobalLock(urlFileContent));
CopyMemory(fileContents, content.data(), content.length());
GlobalUnlock(urlFileContent);
writeFileToDataObject(m_writableDataObject.get(), urlFileDescriptor, urlFileContent, 0);
}
void Pasteboard::writeURL(const KURL& url, const String& titleStr, Frame* frame)
{
ASSERT(!url.isEmpty());
clear();
String title(titleStr);
if (title.isEmpty()) {
title = url.lastPathComponent();
if (title.isEmpty())
title = url.host();
}
// write to clipboard in format com.apple.safari.bookmarkdata to be able to paste into the bookmarks view with appropriate title
if (::OpenClipboard(m_owner)) {
HGLOBAL cbData = createGlobalData(url, title);
if (!::SetClipboardData(BookmarkClipboardFormat, cbData))
::GlobalFree(cbData);
::CloseClipboard();
}
// write to clipboard in format CF_HTML to be able to paste into contenteditable areas as a link
if (::OpenClipboard(m_owner)) {
Vector<char> data;
markupToCFHTML(urlToMarkup(url, title), "", data);
HGLOBAL cbData = createGlobalData(data);
if (!::SetClipboardData(HTMLClipboardFormat, cbData))
::GlobalFree(cbData);
::CloseClipboard();
}
// bare-bones CF_UNICODETEXT support
if (::OpenClipboard(m_owner)) {
HGLOBAL cbData = createGlobalData(url.string());
if (!::SetClipboardData(CF_UNICODETEXT, cbData))
::GlobalFree(cbData);
::CloseClipboard();
}
writeURLToDataObject(url, titleStr, frame);
}
void Pasteboard::writeImage(Node* node, const KURL&, const String&)
{
ASSERT(node);
if (!(node->renderer() && node->renderer()->isImage()))
return;
RenderImage* renderer = toRenderImage(node->renderer());
CachedImage* cachedImage = renderer->cachedImage();
if (!cachedImage || cachedImage->errorOccurred())
return;
Image* image = cachedImage->imageForRenderer(renderer);
ASSERT(image);
clear();
HWndDC dc(0);
HDC compatibleDC = CreateCompatibleDC(0);
HDC sourceDC = CreateCompatibleDC(0);
OwnPtr<HBITMAP> resultBitmap = adoptPtr(CreateCompatibleBitmap(dc, image->width(), image->height()));
HGDIOBJ oldBitmap = SelectObject(compatibleDC, resultBitmap.get());
BitmapInfo bmInfo = BitmapInfo::create(image->size());
HBITMAP coreBitmap = CreateDIBSection(dc, &bmInfo, DIB_RGB_COLORS, 0, 0, 0);
HGDIOBJ oldSource = SelectObject(sourceDC, coreBitmap);
image->getHBITMAP(coreBitmap);
BitBlt(compatibleDC, 0, 0, image->width(), image->height(), sourceDC, 0, 0, SRCCOPY);
SelectObject(sourceDC, oldSource);
DeleteObject(coreBitmap);
SelectObject(compatibleDC, oldBitmap);
DeleteDC(sourceDC);
DeleteDC(compatibleDC);
if (::OpenClipboard(m_owner)) {
::SetClipboardData(CF_BITMAP, resultBitmap.leakPtr());
::CloseClipboard();
}
}
void Pasteboard::writePasteboard(const Pasteboard& sourcePasteboard)
{
notImplemented();
}
void Pasteboard::writeClipboard(Clipboard*)
{
notImplemented();
}
bool Pasteboard::canSmartReplace()
{
return ::IsClipboardFormatAvailable(WebSmartPasteFormat);
}
String Pasteboard::plainText(Frame* frame)
{
if (::IsClipboardFormatAvailable(CF_UNICODETEXT) && ::OpenClipboard(m_owner)) {
HANDLE cbData = ::GetClipboardData(CF_UNICODETEXT);
if (cbData) {
UChar* buffer = static_cast<UChar*>(GlobalLock(cbData));
String fromClipboard(buffer);
GlobalUnlock(cbData);
::CloseClipboard();
return fromClipboard;
}
::CloseClipboard();
}
if (::IsClipboardFormatAvailable(CF_TEXT) && ::OpenClipboard(m_owner)) {
HANDLE cbData = ::GetClipboardData(CF_TEXT);
if (cbData) {
char* buffer = static_cast<char*>(GlobalLock(cbData));
String fromClipboard(buffer);
GlobalUnlock(cbData);
::CloseClipboard();
return fromClipboard;
}
::CloseClipboard();
}
return String();
}
PassRefPtr<DocumentFragment> Pasteboard::documentFragment(Frame* frame, PassRefPtr<Range> context, bool allowPlainText, bool& chosePlainText)
{
chosePlainText = false;
if (::IsClipboardFormatAvailable(HTMLClipboardFormat) && ::OpenClipboard(m_owner)) {
// get data off of clipboard
HANDLE cbData = ::GetClipboardData(HTMLClipboardFormat);
if (cbData) {
SIZE_T dataSize = ::GlobalSize(cbData);
String cfhtml(UTF8Encoding().decode(static_cast<char*>(GlobalLock(cbData)), dataSize));
GlobalUnlock(cbData);
::CloseClipboard();
PassRefPtr<DocumentFragment> fragment = fragmentFromCFHTML(frame->document(), cfhtml);
if (fragment)
return fragment;
} else
::CloseClipboard();
}
if (allowPlainText && ::IsClipboardFormatAvailable(CF_UNICODETEXT)) {
chosePlainText = true;
if (::OpenClipboard(m_owner)) {
HANDLE cbData = ::GetClipboardData(CF_UNICODETEXT);
if (cbData) {
UChar* buffer = static_cast<UChar*>(GlobalLock(cbData));
String str(buffer);
GlobalUnlock(cbData);
::CloseClipboard();
RefPtr<DocumentFragment> fragment = createFragmentFromText(context.get(), str);
if (fragment)
return fragment.release();
} else
::CloseClipboard();
}
}
if (allowPlainText && ::IsClipboardFormatAvailable(CF_TEXT)) {
chosePlainText = true;
if (::OpenClipboard(m_owner)) {
HANDLE cbData = ::GetClipboardData(CF_TEXT);
if (cbData) {
char* buffer = static_cast<char*>(GlobalLock(cbData));
String str(buffer);
GlobalUnlock(cbData);
::CloseClipboard();
RefPtr<DocumentFragment> fragment = createFragmentFromText(context.get(), str);
if (fragment)
return fragment.release();
} else
::CloseClipboard();
}
}
return 0;
}
void Pasteboard::setExternalDataObject(IDataObject *dataObject)
{
m_writableDataObject = 0;
m_dataObject = dataObject;
}
static CachedImage* getCachedImage(Element* element)
{
// Attempt to pull CachedImage from element
ASSERT(element);
RenderObject* renderer = element->renderer();
if (!renderer || !renderer->isImage())
return 0;
RenderImage* image = toRenderImage(renderer);
if (image->cachedImage() && !image->cachedImage()->errorOccurred())
return image->cachedImage();
return 0;
}
static HGLOBAL createGlobalImageFileDescriptor(const String& url, const String& title, CachedImage* image)
{
ASSERT_ARG(image, image);
ASSERT(image->image()->data());
HRESULT hr = S_OK;
HGLOBAL memObj = 0;
String fsPath;
memObj = GlobalAlloc(GPTR, sizeof(FILEGROUPDESCRIPTOR));
if (!memObj)
return 0;
FILEGROUPDESCRIPTOR* fgd = (FILEGROUPDESCRIPTOR*)GlobalLock(memObj);
memset(fgd, 0, sizeof(FILEGROUPDESCRIPTOR));
fgd->cItems = 1;
fgd->fgd[0].dwFlags = FD_FILESIZE;
fgd->fgd[0].nFileSizeLow = image->image()->data()->size();
const String& preferredTitle = title.isEmpty() ? image->response().suggestedFilename() : title;
String extension = image->image()->filenameExtension();
if (extension.isEmpty()) {
// Do not continue processing in the rare and unusual case where a decoded image is not able
// to provide a filename extension. Something tricky (like a bait-n-switch) is going on
return 0;
}
extension.insert(".", 0);
fsPath = filesystemPathFromUrlOrTitle(url, preferredTitle, extension.charactersWithNullTermination().data(), false);
if (fsPath.length() <= 0) {
GlobalUnlock(memObj);
GlobalFree(memObj);
return 0;
}
int maxSize = std::min<int>(fsPath.length(), WTF_ARRAY_LENGTH(fgd->fgd[0].cFileName));
CopyMemory(fgd->fgd[0].cFileName, (LPCWSTR)fsPath.characters(), maxSize * sizeof(UChar));
GlobalUnlock(memObj);
return memObj;
}
static HGLOBAL createGlobalImageFileContent(SharedBuffer* data)
{
HGLOBAL memObj = GlobalAlloc(GPTR, data->size());
if (!memObj)
return 0;
char* fileContents = (PSTR)GlobalLock(memObj);
CopyMemory(fileContents, data->data(), data->size());
GlobalUnlock(memObj);
return memObj;
}
static HGLOBAL createGlobalHDropContent(const KURL& url, String& fileName, SharedBuffer* data)
{
if (fileName.isEmpty() || !data)
return 0;
WCHAR filePath[MAX_PATH];
if (url.isLocalFile()) {
String localPath = decodeURLEscapeSequences(url.path());
// windows does not enjoy a leading slash on paths
if (localPath[0] == '/')
localPath = localPath.substring(1);
const Vector<UChar>& localPathWide = localPath.charactersWithNullTermination();
LPCWSTR localPathStr = localPathWide.data();
if (wcslen(localPathStr) + 1 < MAX_PATH)
wcscpy_s(filePath, MAX_PATH, localPathStr);
else
return 0;
} else {
#if OS(WINCE)
notImplemented();
return 0;
#else
WCHAR tempPath[MAX_PATH];
WCHAR extension[MAX_PATH];
if (!::GetTempPath(WTF_ARRAY_LENGTH(tempPath), tempPath))
return 0;
if (!::PathAppend(tempPath, fileName.charactersWithNullTermination().data()))
return 0;
LPCWSTR foundExtension = ::PathFindExtension(tempPath);
if (foundExtension) {
if (wcscpy_s(extension, MAX_PATH, foundExtension))
return 0;
} else
*extension = 0;
::PathRemoveExtension(tempPath);
for (int i = 1; i < 10000; i++) {
if (swprintf_s(filePath, MAX_PATH, TEXT("%s-%d%s"), tempPath, i, extension) == -1)
return 0;
if (!::PathFileExists(filePath))
break;
}
HANDLE tempFileHandle = CreateFile(filePath, GENERIC_READ | GENERIC_WRITE, 0, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
if (tempFileHandle == INVALID_HANDLE_VALUE)
return 0;
// Write the data to this temp file.
DWORD written;
BOOL tempWriteSucceeded = WriteFile(tempFileHandle, data->data(), data->size(), &written, 0);
CloseHandle(tempFileHandle);
if (!tempWriteSucceeded)
return 0;
#endif
}
SIZE_T dropFilesSize = sizeof(DROPFILES) + (sizeof(WCHAR) * (wcslen(filePath) + 2));
HGLOBAL memObj = GlobalAlloc(GHND | GMEM_SHARE, dropFilesSize);
if (!memObj)
return 0;
DROPFILES* dropFiles = (DROPFILES*) GlobalLock(memObj);
dropFiles->pFiles = sizeof(DROPFILES);
dropFiles->fWide = TRUE;
wcscpy((LPWSTR)(dropFiles + 1), filePath);
GlobalUnlock(memObj);
return memObj;
}
void Pasteboard::writeImageToDataObject(Element* element, const KURL& url)
{
// Shove image data into a DataObject for use as a file
CachedImage* cachedImage = getCachedImage(element);
if (!cachedImage || !cachedImage->imageForRenderer(element->renderer()) || !cachedImage->isLoaded())
return;
SharedBuffer* imageBuffer = cachedImage->imageForRenderer(element->renderer())->data();
if (!imageBuffer || !imageBuffer->size())
return;
HGLOBAL imageFileDescriptor = createGlobalImageFileDescriptor(url.string(), element->getAttribute(HTMLNames::altAttr), cachedImage);
if (!imageFileDescriptor)
return;
HGLOBAL imageFileContent = createGlobalImageFileContent(imageBuffer);
if (!imageFileContent) {
GlobalFree(imageFileDescriptor);
return;
}
String fileName = cachedImage->response().suggestedFilename();
HGLOBAL hDropContent = createGlobalHDropContent(url, fileName, imageBuffer);
if (!hDropContent) {
GlobalFree(hDropContent);
return;
}
writeFileToDataObject(m_writableDataObject.get(), imageFileDescriptor, imageFileContent, hDropContent);
}
void Pasteboard::writeURLToWritableDataObject(const KURL& url, const String& title)
{
WebCore::writeURL(m_writableDataObject.get(), url, title, true, false);
}
} // namespace WebCore
| 32.231132 | 175 | 0.662666 | [
"vector",
"model"
] |
c89ad75eb79ab34f2b44616341ff05c1eea4e433 | 6,257 | cpp | C++ | source/Variant.cpp | sys-bio/Archive_roadRunner | 611bd5338bf842fb5708a9ad75a316bbcc44c902 | [
"Apache-2.0"
] | null | null | null | source/Variant.cpp | sys-bio/Archive_roadRunner | 611bd5338bf842fb5708a9ad75a316bbcc44c902 | [
"Apache-2.0"
] | null | null | null | source/Variant.cpp | sys-bio/Archive_roadRunner | 611bd5338bf842fb5708a9ad75a316bbcc44c902 | [
"Apache-2.0"
] | null | null | null | /*
* Variant.cpp
*
* Created on: Apr 26, 2014
* Author: andy
*/
#include "Variant.h"
#include "rrLogger.h"
#include <exception>
#include <iostream>
#include <stdexcept>
#include <cctype>
#include <cstdlib>
#include <algorithm>
#include <assert.h>
#include <Poco/Dynamic/Var.h>
#include <stdint.h>
using namespace std;
using Poco::Dynamic::Var;
namespace rr
{
struct VariantImpl
{
Var var;
unsigned size;
};
Variant::Variant()
{
alloc();
}
Variant::Variant(const Variant& other)
{
alloc();
self->var = other.self->var;
self->size = other.self->size;
}
Variant& Variant::operator =(const Variant& other)
{
self->var = other.self->var;
self->size = other.self->size;
return *this;
}
Variant::~Variant()
{
delete self;
}
const std::type_info& Variant::typeInfo() const
{
return self->var.type();
}
void Variant::alloc()
{
self = new VariantImpl();
}
#define TRY_ASSIGN(type) \
if (info == typeid(type)) { \
const type *val = static_cast<const type*>(p); \
self->var = *val; \
self->size = sizeof(type); \
return; \
}
void Variant::assign(const std::type_info& info, const void* p)
{
TRY_ASSIGN(std::string);
TRY_ASSIGN(long);
TRY_ASSIGN(bool);
TRY_ASSIGN(float);
TRY_ASSIGN(double);
TRY_ASSIGN(unsigned long);
TRY_ASSIGN(int);
TRY_ASSIGN(unsigned int);
TRY_ASSIGN(char);
TRY_ASSIGN(unsigned char);
TRY_ASSIGN(int32_t);
TRY_ASSIGN(uint32_t);
TRY_ASSIGN(int64_t);
TRY_ASSIGN(uint64_t);
string msg = "could not assign type ";
msg += info.name();
msg += " to Variant";
throw invalid_argument(msg);
}
/**
* strip any leading or trailing whitespace
*/
static std::string strip(const std::string& in)
{
std::string out;
std::string::const_iterator b = in.begin(), e = in.end();
// skipping leading spaces
while (std::isspace(*b)){
++b;
}
if (b != e){
// skipping trailing spaces
while (std::isspace(*(e-1))){
--e;
}
}
out.assign(b, e);
return out;
}
Variant Variant::parse(const std::string& s)
{
string str = strip(s);
const char* input = str.c_str();
char* end = 0;
// check for int
int i = strtol(input, &end, 0);
if (*input != '\0' && end != input && *end == '\0')
{
return Variant(i);
}
// check for double
double d = strtod(input, &end);
if (*input != '\0' && end != input && *end == '\0')
{
return Variant(d);
}
// check for bool
std::string bstr = str;
std::transform(bstr.begin(), bstr.end(),bstr.begin(), ::toupper);
if (bstr == "TRUE") {
return Variant(true);
}
if (bstr == "FALSE") {
return Variant(false);
}
// its a string
Variant result;
result.self->var = Var::parse(str);
return result;
}
std::string Variant::toString() const
{
return Var::toString(self->var);
}
std::string Variant::pythonRepr() const
{
if (isBool()) {
switch (convert<bool>()) {
case true:
return "True";
case false:
return "False";
};
} else if (isString()) {
return "'" + toString() + "'";
} else
return toString();
}
bool Variant::isString() const
{
return self->var.isString();
}
bool Variant::isInteger() const
{
return self->var.isInteger();
}
bool Variant::isNumeric() const
{
return self->var.isNumeric();
}
bool Variant::isBool() const
{
return self->var.type() == typeid(bool);
}
#define TRY_CONVERT_TO(type) \
if (info == typeid(type)) { \
type* out = static_cast<type*>(p); \
*out = self->var.convert<type>(); \
return; \
}
bool Variant::isEmpty() const
{
return self->var.isEmpty();
}
bool Variant::isSigned() const
{
return self->var.isSigned();
}
#define TYPE_KIND(t, tid) if (info == typeid(t)) return tid;
Variant::TypeId Variant::type() const
{
const std::type_info& info = self->var.type();
TYPE_KIND(std::string, STRING);
TYPE_KIND(int32_t, INT32);
TYPE_KIND(uint32_t, UINT32);
TYPE_KIND(int64_t, INT64);
TYPE_KIND(uint64_t, UINT64);
TYPE_KIND(float, FLOAT);
TYPE_KIND(double, DOUBLE);
TYPE_KIND(char, CHAR);
TYPE_KIND(unsigned char, UCHAR);
TYPE_KIND(bool, BOOL);
if(info == typeid(int)) {
if(self->size == 4) return INT32;
if(self->size == 8) return INT64;
}
if(info == typeid(long)) {
if(self->size == 4) return INT32;
if(self->size == 8) return INT64;
}
if(info == typeid(unsigned int)) {
if(self->size == 4) return UINT32;
if(self->size == 8) return UINT64;
}
if(info == typeid(unsigned long)) {
if(self->size == 4) return UINT32;
if(self->size == 8) return UINT64;
}
return EMPTY;
}
void Variant::convert_to(const std::type_info& info, void* p) const
{
try
{
TRY_CONVERT_TO(std::string);
TRY_CONVERT_TO(long);
TRY_CONVERT_TO(bool);
TRY_CONVERT_TO(float);
TRY_CONVERT_TO(double);
TRY_CONVERT_TO(unsigned long);
TRY_CONVERT_TO(int);
TRY_CONVERT_TO(unsigned int);
TRY_CONVERT_TO(char);
TRY_CONVERT_TO(unsigned char);
TRY_CONVERT_TO(int32_t);
TRY_CONVERT_TO(uint32_t);
}
catch(Poco::SyntaxException& ex)
{
string msg = "Could not convert variant with typeid ";
msg += self->var.type().name();
msg += " to type";
msg += info.name();
msg += "error: ";
msg += ex.what();
msg += ", string value: " + self->var.toString();
throw std::logic_error(msg);
}
string msg = "Could not convert variant with typeid ";
msg += self->var.type().name();
msg += " to type";
msg += info.name();
throw invalid_argument(msg);
}
} /* namespace rr */
| 19.07622 | 69 | 0.54499 | [
"transform"
] |
c89b83f5e7885c5c005e252e69ec5ac9f19044d6 | 13,150 | cpp | C++ | Atum/SceneObjects/Other/Demo/tank.cpp | ENgineE777/Atum | 3e9417e2a7deda83bf937612fd070566eb932484 | [
"Zlib"
] | 23 | 2017-11-01T14:47:26.000Z | 2021-12-30T08:04:31.000Z | Atum/SceneObjects/Other/Demo/tank.cpp | ENgineE777/Atum | 3e9417e2a7deda83bf937612fd070566eb932484 | [
"Zlib"
] | 1 | 2018-12-06T14:19:55.000Z | 2018-12-07T04:06:35.000Z | Atum/SceneObjects/Other/Demo/tank.cpp | ENgineE777/Atum | 3e9417e2a7deda83bf937612fd070566eb932484 | [
"Zlib"
] | 4 | 2017-11-30T10:25:58.000Z | 2019-04-21T14:11:40.000Z | #include "tank.h"
#include "tankclient.h"
#include "Services/Controls/Controls.h"
#include "SceneObjects/3D/GenericMarker.h"
CLASSREG(SceneObject, Tank, "Tank")
META_DATA_DESC(Tank)
BASE_SCENE_OBJ_PROP(Tank)
META_DATA_DESC_END()
float Tank::Projectile::maxTimeLife = 4.0f;
float Tank::Projectile::speed = 50.0f;
float Tank::Projectile::splashTime = 0.35f;
float Tank::Projectile::splashMaxRadius = 5.0f;
void Tank::Init()
{
Tasks(false)->AddTask(0, this, (Object::Delegate)&Tank::Update);
Tasks(false)->AddTask(0, this, (Object::Delegate)&Tank::SendServerState, 1.0f / 15.0f);
Tasks(false)->AddTask(0, this, (Object::Delegate)&Tank::SendClientState, 1.0f / 15.0f);
}
void Tank::AddInstance(int id, Vector3 pos, bool is_bot)
{
client->AddIsntance(id, clientID == id);
if (!is_server)
{
return;
}
PhysControllerDesc cdesc;
cdesc.height = 1.0f;
cdesc.radius = 1.0f;
cdesc.pos = pos;
cdesc.slopeLimit = cosf(Math::Radian * 60.0f);
ServerState& state = client->instances[client->instances.size() - 1].serverState;
state.pos = pos;
state.is_ai = is_bot;
state.controller = PScene()->CreateController(cdesc, 1);
}
Matrix* Tank::Trans()
{
return &transform;
}
bool Tank::Is3DObject()
{
return true;
}
bool Tank::Play()
{
time = 0.0f;
vector<Scene::Group*> out_groups;
GetScene()->GetGroup(out_groups, "TankClient");
for (auto group : out_groups)
{
if (group->objects.size() > 0)
{
client = (TankClient*)group->objects[0];
break;
}
}
/* if (netClient.Connect("192.168.0.19", 7890))
{
netClient.delegedate = this;
is_server = false;
}
else*/
{
//netServer.Start("192.168.0.19", 7890);
netServer.delegedate = this;
is_server = true;
clientID = 0;
OnClientConnected(0);
}
return true;
}
void Tank::OnClientConnected(int id)
{
AddInstance(id, Vector3(transform.Pos().x + id * 10.0f, transform.Pos().y, transform.Pos().z), false);
char packet[256];
{
char* ptr = packet;
*((int*)ptr) = CLIENTID;
ptr += 4;
*((int*)ptr) = id;
ptr += 4;
*((float*)ptr) = time;
ptr += 4;
netServer.Send2Client(id, packet, 12);
}
for (auto& inst : client->instances)
{
if (inst.id == id)
{
continue;
}
char* ptr = packet;
*((int*)ptr) = ADDINSTANCE;
ptr += 4;
*((int*)ptr) = inst.id;
ptr += 4;
netServer.Send2Client(id, packet, 8);
}
{
char* ptr = packet;
*((int*)ptr) = ADDINSTANCE;
ptr += 4;
*((int*)ptr) = id;
ptr += 4;
netServer.Send2All(packet, 8);
}
SendServerState(0.0f);
SendClientState(0.0f);
}
void Tank::OnDataRecieved(int id, void* data, int size)
{
char* ptr = (char*)data;
while (ptr - (char*)data < size)
{
int packetID = *((int*)ptr);
ptr += 4;
switch (packetID)
{
case CLIENTID:
{
clientID = *((int*)ptr);
ptr += 4;
time = *((float*)ptr);
ptr += 4;
break;
}
case ADDINSTANCE:
{
AddInstance(*((int*)ptr), Vector3(transform.Pos().x + *((int*)ptr) * 10.0f, transform.Pos().y, transform.Pos().z), false);
ptr += 4;
break;
}
case CLIENTSTATE:
{
int id = *((int*)ptr);
ptr += 4;
for (auto& inst : client->instances)
{
if (inst.id != id)
{
continue;
}
memcpy(&inst.clientState, ptr, sizeof(ClientState));
ptr += sizeof(ClientState);
break;
}
break;
}
case SERVERSTATE:
{
int id = *((int*)ptr);
ptr += 4;
for (auto& inst : client->instances)
{
if (inst.id != id)
{
continue;
}
memcpy(&inst.serverState, ptr, sizeof(ServerState));
ptr += sizeof(ServerState);
break;
}
break;
}
}
}
}
void Tank::SendServerState(float dt)
{
if (!GetScene()->Playing())
{
return;
}
if (!is_server)
{
return;
}
char packet[256];
for (auto& inst : client->instances)
{
char* ptr = packet;
*((int*)ptr) = SERVERSTATE;
ptr += 4;
*((int*)ptr) = inst.id;
ptr += 4;
inst.serverState.timeStamp = time;
memcpy(ptr, &inst.serverState, sizeof(ServerState));
netServer.Send2All(packet, sizeof(ServerState) + 8);
}
}
void Tank::SendClientState(float dt)
{
if (!GetScene()->Playing())
{
return;
}
if (is_server)
{
return;
}
char packet[256];
for (auto& inst : client->instances)
{
if (!inst.is_contralable)
{
continue;
}
char* ptr = packet;
*((int*)ptr) = CLIENTSTATE;
ptr += 4;
*((int*)ptr) = inst.id;
ptr += 4;
inst.clientState.timeStamp = time;
memcpy(ptr, &inst.clientState, sizeof(ClientState));
netClient.Send(packet, sizeof(ClientState) + 8);
}
}
void Tank::Update(float dt)
{
if (!GetScene()->Playing())
{
return;
}
if (!bonuses_places)
{
vector<Scene::Group*> out_group_bot;
GetScene()->GetGroup(out_group_bot, "Bot");
int index = 100;
for (auto group : out_group_bot)
{
for (auto& obj : group->objects)
{
GenericMarker* marker = (GenericMarker*)obj;
for (auto& inst : marker->instances)
{
AddInstance(index, inst.transform.Pos(), false);
}
index++;
}
}
vector<Scene::Group*> out_group;
GetScene()->GetGroup(out_group, "Terrain");
PhysScene::RaycastDesc rcdesc;
for (auto group : out_group)
{
if (group->objects.size() > 0)
{
Terrain* terrain = (Terrain*)group->objects[0];
float square = 25.0f;
float gap = 10.0f;
float z = -terrain->hheight * 0.5f * terrain->scaleh + gap;
while (z + square < terrain->hheight * 0.5f * terrain->scaleh)
{
float x = -terrain->hwidth * 0.5f * terrain->scaleh + gap;
while (x + square < terrain->hwidth * 0.5f * terrain->scaleh)
{
bonuses.push_back(Bonus());
Bonus& bonus = bonuses[bonuses.size() - 1];
bonus.type = (int)(3.0f * Math::Rand() * 0.999f);
bonus.pos = Vector3(x + square * Math::Rand(), 25.0f, z + square * Math::Rand());
rcdesc.origin = bonus.pos;
rcdesc.dir = Vector3(0.0f, -1.0f, 0.0f);
rcdesc.length = 100.0f;
rcdesc.group = 1;
if (PScene()->RayCast(rcdesc))
{
bonus.pos.y = rcdesc.hitPos.y + 0.75f;
}
x += square + gap;
}
z += square + gap;
}
}
}
bonuses_places = true;
}
time += dt;
if (is_server)
{
netServer.Update();
}
else
{
netClient.Update();
return;
}
for (auto& inst : client->instances)
{
Matrix mat;
mat.RotateY(inst.serverState.angle);
inst.serverState.controller->GetPosition(mat.Pos());
inst.serverState.pos = mat.Pos();
Vector3 dir = mat.Vx();
dir.y = 0;
dir.Normalize();
if (inst.clientState.up == 1)
{
inst.serverState.move_speed += 20 * dt;
if (inst.serverState.move_speed > 30)
{
inst.serverState.move_speed = 30;
}
}
else
if (inst.clientState.up == -1)
{
inst.serverState.move_speed -= 15 * dt;
if (inst.serverState.move_speed < -20)
{
inst.serverState.move_speed = -20;
}
}
else
{
if (inst.serverState.move_speed > 0.1f)
{
inst.serverState.move_speed -= 30 * dt;
if (inst.serverState.move_speed < 0)
{
inst.serverState.move_speed = 0;
}
}
else
if (inst.serverState.move_speed < 0.1f)
{
inst.serverState.move_speed += 30 * dt;
if (inst.serverState.move_speed > 0)
{
inst.serverState.move_speed = 0;
}
}
}
if (inst.clientState.rotate == 1)
{
inst.serverState.strafe_speed += 15 * dt;
if (inst.serverState.strafe_speed > 3)
{
inst.serverState.strafe_speed = 3;
}
}
else
if (inst.clientState.rotate == -1)
{
inst.serverState.strafe_speed -= 15 * dt;
if (inst.serverState.strafe_speed < -3)
{
inst.serverState.strafe_speed = -3;
}
}
else
{
if (inst.serverState.strafe_speed > 0.1f)
{
inst.serverState.strafe_speed -= 15 * dt;
if (inst.serverState.strafe_speed < 0)
{
inst.serverState.strafe_speed = 0;
}
}
else
if (inst.serverState.strafe_speed < 0.1f)
{
inst.serverState.strafe_speed += 15 * dt;
if (inst.serverState.strafe_speed > 0)
{
inst.serverState.strafe_speed = 0;
}
}
}
inst.serverState.angle += inst.serverState.strafe_speed * dt;
if (inst.clientState.needed_tower_angel > -999.9f)
{
if (inst.serverState.tower_angel < Math::PI * 0.5f && inst.clientState.needed_tower_angel > Math::PI)
{
inst.clientState.needed_tower_angel -= Math::PI * 2.0f;
}
if (inst.clientState.needed_tower_angel > inst.serverState.tower_angel)
{
inst.serverState.tower_angel += 1.0f * dt;
if (inst.clientState.needed_tower_angel < inst.serverState.tower_angel)
{
inst.clientState.needed_tower_angel = inst.serverState.tower_angel;
}
}
else
{
inst.serverState.tower_angel -= 1.0f * dt;
if (inst.clientState.needed_tower_angel > inst.serverState.tower_angel)
{
inst.clientState.needed_tower_angel = inst.serverState.tower_angel;
}
}
inst.serverState.angle += inst.serverState.strafe_speed * dt;
}
else
{
inst.serverState.tower_angel = inst.serverState.angle;
}
core.render.DebugPrintText(Vector2(10.0f, 30.0f), ScreenCorner::LeftTop, COLOR_GREEN, "%4.3f %4.3f \n", inst.clientState.needed_tower_angel, inst.serverState.tower_angel);
dir *= inst.serverState.move_speed;
dir.y = -9.8f;
dir *= dt;
inst.serverState.controller->Move(dir, 1, 0);
if (inst.serverState.shoot_cooldown > 0.0f)
{
inst.serverState.shoot_cooldown -= dt;
}
if (((inst.clientState.special_fired && inst.serverState.special == 100) || (inst.clientState.fired && inst.serverState.ammo > 0)) && inst.serverState.shoot_cooldown <= 0.0f)
{
projectiles.push_back(Projectile());
Projectile& proj = projectiles[projectiles.size() - 1];
proj.pos = inst.clientState.gun_pos;
proj.dir = inst.clientState.gun_dir;
proj.lifetime = Projectile::maxTimeLife;
proj.state = 0;
inst.serverState.shoot_cooldown = 1.5f;
proj.special = inst.clientState.special_fired;
if (proj.special)
{
inst.serverState.special = 1;
proj.special = true;
}
else
{
inst.serverState.ammo--;
proj.special = false;
}
}
}
PhysScene::RaycastDesc rcdesc;
for (int i = 0; i < projectiles.size(); i++)
{
Projectile& proj = projectiles[i];
float len = Projectile::speed * dt * 1.01f;
proj.lifetime -= dt;
float r = 0.35f;
if (proj.state == 0)
{
if (proj.lifetime > 0.0f)
{
rcdesc.origin = proj.pos;
rcdesc.dir = proj.dir;
rcdesc.length = len;
rcdesc.group = 1;
if (PScene()->RayCast(rcdesc))
{
proj.pos = rcdesc.hitPos;
proj.state = 1;
proj.lifetime = Projectile::splashTime;
if (proj.special)
{
for (int i = 0; i < 5; i++)
{
proj.claster_pos[i] = proj.pos + Vector3(-2.0f + 4.0f * Math::Rand(), 0.0f, -2.0f + 4.0f * Math::Rand());
AddSplash(proj.claster_pos[i], Projectile::splashMaxRadius, 200);
}
}
else
{
AddSplash(proj.pos, Projectile::splashMaxRadius, 400);
}
}
else
{
proj.pos += proj.dir * len;
}
}
else
{
proj.state = 1;
proj.lifetime = Projectile::splashTime;
}
}
else
{
if (proj.lifetime > 0.0f)
{
r = (1.0f - proj.lifetime / Projectile::splashTime) * Projectile::splashMaxRadius;
}
else
{
projectiles[i] = projectiles[projectiles.size() - 1];
projectiles.pop_back();
i--;
continue;
}
}
if (proj.special && proj.state == 1)
{
for (int i = 0; i < 5; i++)
{
core.render.DebugSphere(proj.claster_pos[i], COLOR_MAGNETA, r * 0.5f);
}
}
else
{
core.render.DebugSphere(proj.pos, COLOR_RED, r);
}
}
for (auto& bonus : bonuses)
{
if (bonus.cooldown > 0.0f)
{
bonus.cooldown -= dt;
if (bonus.cooldown < 0.0f)
{
bonus.cooldown = -1.0f;
}
continue;
}
for (auto& inst : client->instances)
{
if (inst.serverState.hp <= 0)
{
continue;
}
if ((inst.serverState.pos - bonus.pos).Length2() < 9)
{
if (bonus.type == 0 && inst.serverState.hp < 100)
{
inst.serverState.hp = (int)fmin(inst.serverState.hp + 40, 100);
bonus.cooldown = 10.0f;
}
else
if (bonus.type == 1 && inst.serverState.ammo < 100)
{
inst.serverState.ammo = (int)fmin(inst.serverState.ammo + 40, 100);
bonus.cooldown = 10.0f;
}
else
if (bonus.type == 2 && inst.serverState.special < 100)
{
inst.serverState.special = (int)fmin(inst.serverState.special + 40, 100);
bonus.cooldown = 10.0f;
}
}
}
Color colors[] = { COLOR_GREEN, COLOR_CYAN, COLOR_YELLOW };
core.render.DebugSphere(bonus.pos, colors[bonus.type], 0.5f);
}
}
void Tank::AddSplash(Vector3& pos, float radius, float force)
{
vector<Scene::Group*> out_group;
GetScene()->GetGroup(out_group, "PhysBox");
for (auto group : out_group)
{
for (int i = 0; i < group->objects.size(); i++)
{
PhysBox* box = (PhysBox*)group->objects[i];
if (box->isStatic)
{
continue;
}
Vector3 dir = box->Trans()->Pos() - pos;
float len = dir.Normalize();
if (len < radius)
{
box->body.body->AddForceAt(pos, dir * len / radius * force);
}
}
}
} | 18.758916 | 176 | 0.603878 | [
"render",
"object",
"vector",
"transform",
"3d"
] |
c8a2472d69a61ab1a22f9c74adfb0275797e6465 | 512 | hpp | C++ | src/client/headers.hpp | Fenex330/surv-royale | 4b5264a346e44e7460221cc23c8aaf9a10c4a4d7 | [
"MIT"
] | 2 | 2022-03-01T18:57:26.000Z | 2022-03-20T18:20:13.000Z | src/client/headers.hpp | Fenex330/surv-royale | 4b5264a346e44e7460221cc23c8aaf9a10c4a4d7 | [
"MIT"
] | null | null | null | src/client/headers.hpp | Fenex330/surv-royale | 4b5264a346e44e7460221cc23c8aaf9a10c4a4d7 | [
"MIT"
] | 1 | 2021-11-11T19:01:18.000Z | 2021-11-11T19:01:18.000Z | #pragma once
#include <utility>
#include <iostream>
#include <fstream>
#include <string>
#include <stack>
#include <vector>
#include <unordered_map>
#include <random>
#include <filesystem>
#include <cstdlib>
#include <cassert>
#include <cmath>
#include <SFML/Graphics.hpp>
#include <SFML/Network.hpp>
#include <SFML/Audio.hpp>
#include "../imgui/imgui.h"
#include "../imgui/imgui-SFML.h"
#include "../dxTarRead.h"
#include "../common.hpp"
#include "Projectile.hpp"
#include "Player.hpp"
#include "Game.hpp"
| 17.655172 | 32 | 0.714844 | [
"vector"
] |
c8a5244c63edb3defbeacae770b00c9ed394cac6 | 8,401 | cpp | C++ | src/effect.cpp | Olddies710/The-Forgotten-Client | 8b7979619ea76bc29581122440d09f241afc175d | [
"Zlib"
] | 1 | 2022-01-15T00:00:27.000Z | 2022-01-15T00:00:27.000Z | src/effect.cpp | Olddies710/The-Forgotten-Client | 8b7979619ea76bc29581122440d09f241afc175d | [
"Zlib"
] | null | null | null | src/effect.cpp | Olddies710/The-Forgotten-Client | 8b7979619ea76bc29581122440d09f241afc175d | [
"Zlib"
] | 3 | 2021-10-14T02:36:56.000Z | 2022-03-22T21:03:31.000Z | /*
The Forgotten Client
Copyright (C) 2020 Saiyans King
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "effect.h"
#include "engine.h"
#include "thingManager.h"
#include "light.h"
extern Engine g_engine;
extern ThingManager g_thingManager;
extern LightSystem g_light;
extern Uint32 g_frameTime;
std::vector<Effect*> Effect::effects;
Uint32 Effect::effectCount = 0;
Effect::Effect(const Position& pos, Uint16 delay, ThingType* type) : m_thingType(type), m_position(pos)
{
m_startTime = g_frameTime + delay;
++effectCount;
effects.push_back(this);
}
Effect::~Effect()
{
auto it = std::find(effects.begin(), effects.end(), this);
if(it != effects.end())
{
*it = effects.back();
effects.pop_back();
}
--effectCount;
}
Effect* Effect::createEffect(const Position& pos, Uint16 delay, Uint16 type)
{
if(effectCount >= EFFECT_MAX_INGAME_EFFECTS)
return NULL;
Effect* newEffect = NULL;
ThingType* ttype = g_thingManager.getThingType(ThingCategory_Effect, type);
if(ttype)
{
Uint8 animCount = ttype->m_frameGroup[ThingFrameGroup_Default].m_animCount;
Uint8 xPattern = UTIL_safeMod<Uint8>(SDL_static_cast(Uint8, pos.x), ttype->m_frameGroup[ThingFrameGroup_Default].m_patternX);
Uint8 yPattern = UTIL_safeMod<Uint8>(SDL_static_cast(Uint8, pos.y), ttype->m_frameGroup[ThingFrameGroup_Default].m_patternY);
Uint8 zPattern = UTIL_safeMod<Uint8>(SDL_static_cast(Uint8, pos.z), ttype->m_frameGroup[ThingFrameGroup_Default].m_patternZ);
if(animCount <= EFFECT_MAX_CACHED_ANIMATIONS)
{
Uint8 width = ttype->m_frameGroup[ThingFrameGroup_Default].m_width;
Uint8 height = ttype->m_frameGroup[ThingFrameGroup_Default].m_height;
if(width == 1 && height == 1)
{
auto newEffectX = new Effect1X1(pos, delay, ttype);
for(Uint8 a = 0; a < animCount; ++a)
newEffectX->m_1X1Sprites[a] = ttype->getSprite(ThingFrameGroup_Default, 0, 0, 0, xPattern, yPattern, zPattern, a);
newEffect = newEffectX;
}
else if(width == 2 && height == 1)
{
auto newEffectX = new Effect2X1(pos, delay, ttype);
for(Uint8 a = 0; a < animCount; ++a)
{
newEffectX->m_2X1Sprites[a][0] = ttype->getSprite(ThingFrameGroup_Default, 0, 0, 0, xPattern, yPattern, zPattern, a);
newEffectX->m_2X1Sprites[a][1] = ttype->getSprite(ThingFrameGroup_Default, 1, 0, 0, xPattern, yPattern, zPattern, a);
}
newEffect = newEffectX;
}
else if(width == 1 && height == 2)
{
auto newEffectX = new Effect1X2(pos, delay, ttype);
for(Uint8 a = 0; a < animCount; ++a)
{
newEffectX->m_1X2Sprites[a][0] = ttype->getSprite(ThingFrameGroup_Default, 0, 0, 0, xPattern, yPattern, zPattern, a);
newEffectX->m_1X2Sprites[a][1] = ttype->getSprite(ThingFrameGroup_Default, 0, 1, 0, xPattern, yPattern, zPattern, a);
}
newEffect = newEffectX;
}
else if(width == 2 && height == 2)
{
auto newEffectX = new Effect2X2(pos, delay, ttype);
for(Uint8 a = 0; a < animCount; ++a)
{
newEffectX->m_2X2Sprites[a][0] = ttype->getSprite(ThingFrameGroup_Default, 0, 0, 0, xPattern, yPattern, zPattern, a);
newEffectX->m_2X2Sprites[a][1] = ttype->getSprite(ThingFrameGroup_Default, 1, 0, 0, xPattern, yPattern, zPattern, a);
newEffectX->m_2X2Sprites[a][2] = ttype->getSprite(ThingFrameGroup_Default, 0, 1, 0, xPattern, yPattern, zPattern, a);
newEffectX->m_2X2Sprites[a][3] = ttype->getSprite(ThingFrameGroup_Default, 1, 1, 0, xPattern, yPattern, zPattern, a);
}
newEffect = newEffectX;
}
}
if(!newEffect)
newEffect = new Effect(pos, delay, ttype);
newEffect->m_animator = ttype->m_frameGroup[ThingFrameGroup_Default].m_animator;
newEffect->m_animCount = animCount;
newEffect->m_xPattern = xPattern;
newEffect->m_yPattern = yPattern;
newEffect->m_zPattern = zPattern;
newEffect->m_topEffect = ttype->hasFlag(ThingAttribute_TopEffect);
if(newEffect->m_animator)
newEffect->m_animator->resetAnimation(newEffect->m_animation);
}
else
newEffect = new EffectNULL(pos, delay, ttype);
return newEffect;
}
Uint16 Effect::getID()
{
if(m_thingType)
return m_thingType->m_id;
return 0;
}
bool Effect::canBeDeleted()
{
if(m_currentAnim >= m_animCount)
return true;
else
return false;
}
bool Effect::isDelayed()
{
return (g_frameTime < m_startTime);
}
void Effect::update()
{
for(std::vector<Effect*>::iterator it = effects.begin(), end = effects.end(); it != end; ++it)
(*it)->m_currentAnim = (*it)->calculateAnimationPhase();
}
void Effect::render(Sint32 posX, Sint32 posY)
{
auto& renderer = g_engine.getRender();
if(g_engine.getLightMode() != CLIENT_LIGHT_MODE_NONE)
{
Uint16* light = m_thingType->m_light;
if(light[0] > 0)
g_light.addLightSource(posX, posY, light);
}
for(Uint8 y = 0; y < m_thingType->m_frameGroup[ThingFrameGroup_Default].m_height; ++y)
{
Sint32 posXc = posX;
for(Uint8 x = 0; x < m_thingType->m_frameGroup[ThingFrameGroup_Default].m_width; ++x)
{
Uint32 sprite = m_thingType->getSprite(ThingFrameGroup_Default, x, y, 0, m_xPattern, m_yPattern, m_zPattern, m_currentAnim);
if(sprite != 0)
renderer->drawSprite(sprite, posXc, posY);
posXc -= 32;
}
posY -= 32;
}
}
Uint8 Effect::calculateAnimationPhase()
{
if(m_animator)
{
Uint8 currentAnimation = SDL_static_cast(Uint8, m_animator->getPhase(m_animation));
return (m_animator->isComplete(m_animation) ? m_animCount : currentAnimation);
}
return SDL_static_cast(Uint8, (g_frameTime - m_startTime) / EFFECT_TICKS_PER_FRAME);
}
void Effect1X1::render(Sint32 posX, Sint32 posY)
{
if(g_engine.getLightMode() != CLIENT_LIGHT_MODE_NONE)
{
Uint16* light = m_thingType->m_light;
if(light[0] > 0)
g_light.addLightSource(posX, posY, light);
}
Uint32 drawSprite = m_1X1Sprites[m_currentAnim];
if(drawSprite != 0)
g_engine.getRender()->drawSprite(drawSprite, posX, posY);
}
void Effect2X1::render(Sint32 posX, Sint32 posY)
{
auto& renderer = g_engine.getRender();
if(g_engine.getLightMode() != CLIENT_LIGHT_MODE_NONE)
{
Uint16* light = m_thingType->m_light;
if(light[0] > 0)
g_light.addLightSource(posX, posY, light);
}
Uint32 drawSprite = m_2X1Sprites[m_currentAnim][0];
if(drawSprite != 0)
renderer->drawSprite(drawSprite, posX, posY);
drawSprite = m_2X1Sprites[m_currentAnim][1];
if(drawSprite != 0)
renderer->drawSprite(drawSprite, posX - 32, posY);
}
void Effect1X2::render(Sint32 posX, Sint32 posY)
{
auto& renderer = g_engine.getRender();
if(g_engine.getLightMode() != CLIENT_LIGHT_MODE_NONE)
{
Uint16* light = m_thingType->m_light;
if(light[0] > 0)
g_light.addLightSource(posX, posY, light);
}
Uint32 drawSprite = m_1X2Sprites[m_currentAnim][0];
if(drawSprite != 0)
renderer->drawSprite(drawSprite, posX, posY);
drawSprite = m_1X2Sprites[m_currentAnim][1];
if(drawSprite != 0)
renderer->drawSprite(drawSprite, posX, posY - 32);
}
void Effect2X2::render(Sint32 posX, Sint32 posY)
{
auto& renderer = g_engine.getRender();
if(g_engine.getLightMode() != CLIENT_LIGHT_MODE_NONE)
{
Uint16* light = m_thingType->m_light;
if(light[0] > 0)
g_light.addLightSource(posX, posY, light);
}
Uint32 drawSprite = m_2X2Sprites[m_currentAnim][0];
if(drawSprite != 0)
renderer->drawSprite(drawSprite, posX, posY);
drawSprite = m_2X2Sprites[m_currentAnim][1];
if(drawSprite != 0)
renderer->drawSprite(drawSprite, posX - 32, posY);
posY -= 32;
drawSprite = m_2X2Sprites[m_currentAnim][2];
if(drawSprite != 0)
renderer->drawSprite(drawSprite, posX, posY);
drawSprite = m_2X2Sprites[m_currentAnim][3];
if(drawSprite != 0)
renderer->drawSprite(drawSprite, posX - 32, posY);
}
| 30.886029 | 127 | 0.716343 | [
"render",
"vector"
] |
c8a607a46047957b7f5c61d8eac7d7ab417603f5 | 7,059 | cpp | C++ | Source/ProceduralMeshes/Private/HeightFieldAnimatedActor.cpp | Drezil/ProceduralMeshes | 2838d45e29a3133dd5fba08596e1e5a0ac68227e | [
"MIT"
] | null | null | null | Source/ProceduralMeshes/Private/HeightFieldAnimatedActor.cpp | Drezil/ProceduralMeshes | 2838d45e29a3133dd5fba08596e1e5a0ac68227e | [
"MIT"
] | null | null | null | Source/ProceduralMeshes/Private/HeightFieldAnimatedActor.cpp | Drezil/ProceduralMeshes | 2838d45e29a3133dd5fba08596e1e5a0ac68227e | [
"MIT"
] | null | null | null | // Copyright Sigurdur Gunnarsson. All Rights Reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
// Example heightfield grid animated with sine and cosine waves
#include "ProceduralMeshesPrivatePCH.h"
#include "HeightFieldAnimatedActor.h"
AHeightFieldAnimatedActor::AHeightFieldAnimatedActor()
{
RootNode = CreateDefaultSubobject<USceneComponent>("Root");
RootComponent = RootNode;
MeshComponent = CreateDefaultSubobject<URuntimeMeshComponent>(TEXT("ProceduralMesh"));
MeshComponent->SetupAttachment(RootComponent);
PrimaryActorTick.bCanEverTick = true;
}
// This is called when actor is spawned (at runtime or when you drop it into the world in editor)
void AHeightFieldAnimatedActor::PostActorCreated()
{
Super::PostActorCreated();
GenerateMesh();
}
// This is called when actor is already in level and map is opened
void AHeightFieldAnimatedActor::PostLoad()
{
Super::PostLoad();
GenerateMesh();
}
void AHeightFieldAnimatedActor::SetupMeshBuffers()
{
int32 NumberOfPoints = (LengthSections + 1) * (WidthSections + 1);
int32 NumberOfTriangles = LengthSections * WidthSections * 2 * 3; // 2x3 vertex indexes per quad
Vertices.AddUninitialized(NumberOfPoints);
Triangles.AddUninitialized(NumberOfTriangles);
HeightValues.AddUninitialized(NumberOfPoints);
}
void AHeightFieldAnimatedActor::GeneratePoints()
{
// Setup example height data
int32 NumberOfPoints = (LengthSections + 1) * (WidthSections + 1);
// Combine variations of sine and cosine to create some variable waves
// TODO Convert this to use a parallel for
int32 PointIndex = 0;
for (int32 X = 0; X < LengthSections + 1; X++)
{
for (int32 Y = 0; Y < WidthSections + 1; Y++)
{
// Just some quick hardcoded offset numbers in there
float ValueOne = FMath::Cos((X + CurrentAnimationFrameX)*ScaleFactor) * FMath::Sin((Y + CurrentAnimationFrameY)*ScaleFactor);
float ValueTwo = FMath::Cos((X + CurrentAnimationFrameX*0.7f)*ScaleFactor*2.5f) * FMath::Sin((Y - CurrentAnimationFrameY*0.7f)*ScaleFactor*2.5f);
float AvgValue = ((ValueOne + ValueTwo) / 2) * Size.Z;
HeightValues[PointIndex++] = AvgValue;
if (AvgValue > MaxHeightValue)
{
MaxHeightValue = AvgValue;
}
}
}
}
void AHeightFieldAnimatedActor::Tick(float DeltaSeconds)
{
if (AnimateMesh)
{
CurrentAnimationFrameX += DeltaSeconds * AnimationSpeedX;
CurrentAnimationFrameY += DeltaSeconds * AnimationSpeedY;
GenerateMesh();
}
}
void AHeightFieldAnimatedActor::GenerateMesh()
{
if (Size.X < 1 || Size.Y < 1 || LengthSections < 1 || WidthSections < 1)
{
MeshComponent->ClearAllMeshSections();
return;
}
// The number of vertices or polygons wont change at runtime, so we'll just allocate the arrays once
if (!bHaveBuffersBeenInitialized)
{
SetupMeshBuffers();
bHaveBuffersBeenInitialized = true;
}
GeneratePoints();
// TODO Convert this to use fast-past updates instead of regenerating the mesh every frame
GenerateGrid(Vertices, Triangles, FVector2D(Size.X, Size.Y), LengthSections, WidthSections, HeightValues);
FBox BoundingBox = FBox(FVector(0, 0, -MaxHeightValue), FVector(Size.X, Size.Y, MaxHeightValue));
MeshComponent->ClearAllMeshSections();
MeshComponent->CreateMeshSection(0, Vertices, Triangles, BoundingBox, false, EUpdateFrequency::Frequent);
MeshComponent->SetMaterial(0, Material);
}
void AHeightFieldAnimatedActor::GenerateGrid(TArray<FRuntimeMeshVertexSimple>& InVertices, TArray<int32>& InTriangles, FVector2D InSize, int32 InLengthSections, int32 InWidthSections, const TArray<float>& InHeightValues)
{
// Note the coordinates are a bit weird here since I aligned it to the transform (X is forwards or "up", which Y is to the right)
// Should really fix this up and use standard X, Y coords then transform into object space?
FVector2D SectionSize = FVector2D(InSize.X / InLengthSections, InSize.Y / InWidthSections);
int32 VertexIndex = 0;
int32 TriangleIndex = 0;
for (int32 X = 0; X < InLengthSections + 1; X++)
{
for (int32 Y = 0; Y < InWidthSections + 1; Y++)
{
// Create a new vertex
int32 NewVertIndex = VertexIndex++;
FVector newVertex = FVector(X * SectionSize.X, Y * SectionSize.Y, InHeightValues[NewVertIndex]);
InVertices[NewVertIndex].Position = newVertex;
// Note that Unreal UV origin (0,0) is top left
float U = (float)X / (float)InLengthSections;
float V = (float)Y / (float)InWidthSections;
InVertices[NewVertIndex].UV0 = FVector2D(U, V);
// Once we've created enough verts we can start adding polygons
if (X > 0 && Y > 0)
{
// Each row is InWidthSections+1 number of points.
// And we have InLength+1 rows
// Index of current vertex in position is thus: (X * (InWidthSections + 1)) + Y;
int32 bTopRightIndex = (X * (InWidthSections + 1)) + Y; // Should be same as VertIndex1!
int32 bTopLeftIndex = bTopRightIndex - 1;
int32 pBottomRightIndex = ((X - 1) * (InWidthSections + 1)) + Y;
int32 pBottomLeftIndex = pBottomRightIndex - 1;
// Now create two triangles from those four vertices
// The order of these (clockwise/counter-clockwise) dictates which way the normal will face.
InTriangles[TriangleIndex++] = pBottomLeftIndex;
InTriangles[TriangleIndex++] = bTopRightIndex;
InTriangles[TriangleIndex++] = bTopLeftIndex;
InTriangles[TriangleIndex++] = pBottomLeftIndex;
InTriangles[TriangleIndex++] = pBottomRightIndex;
InTriangles[TriangleIndex++] = bTopRightIndex;
// Normals
FVector NormalCurrent = FVector::CrossProduct(InVertices[pBottomLeftIndex].Position - InVertices[bTopLeftIndex].Position, InVertices[bTopLeftIndex].Position - InVertices[bTopRightIndex].Position).GetSafeNormal();
InVertices[pBottomLeftIndex].Normal = InVertices[pBottomRightIndex].Normal = InVertices[bTopRightIndex].Normal = InVertices[bTopLeftIndex].Normal = FPackedNormal(NormalCurrent);
}
}
}
}
#if WITH_EDITOR
void AHeightFieldAnimatedActor::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent)
{
Super::PostEditChangeProperty(PropertyChangedEvent);
FName MemberPropertyChanged = (PropertyChangedEvent.MemberProperty ? PropertyChangedEvent.MemberProperty->GetFName() : NAME_None);
if ((MemberPropertyChanged == GET_MEMBER_NAME_CHECKED(AHeightFieldAnimatedActor, Size)) || (MemberPropertyChanged == GET_MEMBER_NAME_CHECKED(AHeightFieldAnimatedActor, ScaleFactor)))
{
// Same vert count, so just regen mesh with same buffers
GenerateMesh();
}
else if ((MemberPropertyChanged == GET_MEMBER_NAME_CHECKED(AHeightFieldAnimatedActor, LengthSections)) || (MemberPropertyChanged == GET_MEMBER_NAME_CHECKED(AHeightFieldAnimatedActor, WidthSections)))
{
// Vertice count has changed, so reset buffer and then regen mesh
Vertices.Empty();
Triangles.Empty();
HeightValues.Empty();
bHaveBuffersBeenInitialized = false;
GenerateMesh();
}
else if ((MemberPropertyChanged == GET_MEMBER_NAME_CHECKED(AHeightFieldAnimatedActor, Material)))
{
MeshComponent->SetMaterial(0, Material);
}
}
#endif // WITH_EDITOR
| 38.785714 | 220 | 0.751806 | [
"mesh",
"object",
"transform"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.