text
string
size
int64
token_count
int64
#include <bts/mail/message.hpp> #include <fc/crypto/aes.hpp> namespace bts { namespace mail { const message_type signed_email_message::type = email; const message_type transaction_notice_message::type = transaction_notice; digest_type email_message::digest()const { fc::sha256::encoder enc; fc::raw::pack( enc, *this ); return enc.result(); } void signed_email_message::sign( const fc::ecc::private_key& from_key ) { try { from_signature = from_key.sign_compact( digest() ); } FC_CAPTURE_AND_RETHROW() } fc::ecc::public_key signed_email_message::from()const { try { return fc::ecc::public_key( from_signature, digest() ); } FC_CAPTURE_AND_RETHROW() } message_id_type message::id()const { fc::ripemd160::encoder enc; fc::raw::pack( enc, *this ); return enc.result(); } encrypted_message message::encrypt( const fc::ecc::private_key& onetimekey, const fc::ecc::public_key& receiver_public_key )const { auto shared_secret = onetimekey.get_shared_secret( receiver_public_key ); encrypted_message result; result.onetimekey = onetimekey.get_public_key(); result.data = fc::aes_encrypt( shared_secret, fc::raw::pack( *this ) ); return result; } message encrypted_message::decrypt( const fc::ecc::private_key& e )const { auto shared_secret = e.get_shared_secret(onetimekey); auto decrypted_data = fc::aes_decrypt( shared_secret, data ); return fc::raw::unpack<message>( decrypted_data ); }; } } // bts::mail
1,626
557
// Copyright (c) 2021 by Apex.AI Inc. 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. // // SPDX-License-Identifier: Apache-2.0 #include "iceoryx_posh/popo/client_options.hpp" #include "test.hpp" namespace { using namespace ::testing; TEST(ClientOptions_test, SerializationRoundTripIsSuccessful) { ::testing::Test::RecordProperty("TEST_ID", "1d803ab0-a657-4a84-b261-ec289a7353e6"); iox::popo::ClientOptions defaultOptions; iox::popo::ClientOptions testOptions; testOptions.responseQueueCapacity = 42; testOptions.nodeName = "hypnotoad"; testOptions.connectOnCreate = false; testOptions.responseQueueFullPolicy = iox::popo::QueueFullPolicy::BLOCK_PRODUCER; testOptions.serverTooSlowPolicy = iox::popo::ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER; iox::popo::ClientOptions::deserialize(testOptions.serialize()) .and_then([&](auto& roundTripOptions) { EXPECT_THAT(roundTripOptions.responseQueueCapacity, Ne(defaultOptions.responseQueueCapacity)); EXPECT_THAT(roundTripOptions.responseQueueCapacity, Eq(testOptions.responseQueueCapacity)); EXPECT_THAT(roundTripOptions.nodeName, Ne(defaultOptions.nodeName)); EXPECT_THAT(roundTripOptions.nodeName, Eq(testOptions.nodeName)); EXPECT_THAT(roundTripOptions.connectOnCreate, Ne(defaultOptions.connectOnCreate)); EXPECT_THAT(roundTripOptions.connectOnCreate, Eq(testOptions.connectOnCreate)); EXPECT_THAT(roundTripOptions.responseQueueFullPolicy, Ne(defaultOptions.responseQueueFullPolicy)); EXPECT_THAT(roundTripOptions.responseQueueFullPolicy, Eq(testOptions.responseQueueFullPolicy)); EXPECT_THAT(roundTripOptions.serverTooSlowPolicy, Ne(defaultOptions.serverTooSlowPolicy)); EXPECT_THAT(roundTripOptions.serverTooSlowPolicy, Eq(testOptions.serverTooSlowPolicy)); }) .or_else([&](auto&) { constexpr bool DESERIALZATION_ERROR_OCCURED{true}; EXPECT_FALSE(DESERIALZATION_ERROR_OCCURED); }); } TEST(ClientOptions_test, DeserializingBogusDataFails) { ::testing::Test::RecordProperty("TEST_ID", "eb7341fd-f216-4422-8065-cbbadefd567b"); const auto bogusSerialization = iox::cxx::Serialization::create("hypnotoad", "brain slug", "rock star"); iox::popo::ClientOptions::deserialize(bogusSerialization) .and_then([&](auto&) { constexpr bool DESERIALZATION_SUCCESSFUL{true}; EXPECT_FALSE(DESERIALZATION_SUCCESSFUL); }) .or_else([&](auto&) { constexpr bool DESERIALZATION_ERROR_OCCURED{true}; EXPECT_TRUE(DESERIALZATION_ERROR_OCCURED); }); } using QueueFullPolicyUT = std::underlying_type_t<iox::popo::QueueFullPolicy>; using ConsumerTooSlowPolicyUT = std::underlying_type_t<iox::popo::ConsumerTooSlowPolicy>; iox::cxx::Serialization enumSerialization(QueueFullPolicyUT responseQueueFullPolicy, ConsumerTooSlowPolicyUT serverTooSlowPolicy) { constexpr uint64_t RESPONSE_QUEUE_CAPACITY{42U}; const iox::NodeName_t NODE_NAME{"harr-harr"}; constexpr bool CONNECT_ON_CREATE{true}; return iox::cxx::Serialization::create( RESPONSE_QUEUE_CAPACITY, NODE_NAME, CONNECT_ON_CREATE, responseQueueFullPolicy, serverTooSlowPolicy); } TEST(ClientOptions_test, DeserializingValidResponseQueueFullAndServerTooSlowPolicyIsSuccessful) { ::testing::Test::RecordProperty("TEST_ID", "877ad373-eb51-4613-9b68-b93baa4c6eae"); constexpr QueueFullPolicyUT RESPONSE_QUEUE_FULL_POLICY{ static_cast<QueueFullPolicyUT>(iox::popo::QueueFullPolicy::BLOCK_PRODUCER)}; constexpr ConsumerTooSlowPolicyUT SERVER_TOO_SLOW_POLICY{ static_cast<ConsumerTooSlowPolicyUT>(iox::popo::ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER)}; const auto serialized = enumSerialization(RESPONSE_QUEUE_FULL_POLICY, SERVER_TOO_SLOW_POLICY); iox::popo::ClientOptions::deserialize(serialized) .and_then([&](auto&) { constexpr bool DESERIALZATION_SUCCESSFUL{true}; EXPECT_TRUE(DESERIALZATION_SUCCESSFUL); }) .or_else([&](auto&) { constexpr bool DESERIALZATION_ERROR_OCCURED{true}; EXPECT_FALSE(DESERIALZATION_ERROR_OCCURED); }); } TEST(ClientOptions_test, DeserializingInvalidResponseQueueFullPolicyFails) { ::testing::Test::RecordProperty("TEST_ID", "a5495324-67d0-4f0c-b979-f93d4b68adc5"); constexpr QueueFullPolicyUT RESPONSE_QUEUE_FULL_POLICY{111}; constexpr ConsumerTooSlowPolicyUT SERVER_TOO_SLOW_POLICY{ static_cast<ConsumerTooSlowPolicyUT>(iox::popo::ConsumerTooSlowPolicy::DISCARD_OLDEST_DATA)}; const auto serialized = enumSerialization(RESPONSE_QUEUE_FULL_POLICY, SERVER_TOO_SLOW_POLICY); iox::popo::ClientOptions::deserialize(serialized) .and_then([&](auto&) { constexpr bool DESERIALZATION_SUCCESSFUL{true}; EXPECT_FALSE(DESERIALZATION_SUCCESSFUL); }) .or_else([&](auto&) { constexpr bool DESERIALZATION_ERROR_OCCURED{true}; EXPECT_TRUE(DESERIALZATION_ERROR_OCCURED); }); } TEST(ClientOptions_test, DeserializingInvalidServerTooSlowPolicyFails) { ::testing::Test::RecordProperty("TEST_ID", "6485377c-9a75-4aba-8045-8b129aa1c529"); constexpr QueueFullPolicyUT RESPONSE_QUEUE_FULL_POLICY{ static_cast<QueueFullPolicyUT>(iox::popo::QueueFullPolicy::BLOCK_PRODUCER)}; constexpr ConsumerTooSlowPolicyUT SERVER_TOO_SLOW_POLICY{111}; const auto serialized = enumSerialization(RESPONSE_QUEUE_FULL_POLICY, SERVER_TOO_SLOW_POLICY); iox::popo::ClientOptions::deserialize(serialized) .and_then([&](auto&) { constexpr bool DESERIALZATION_SUCCESSFUL{true}; EXPECT_FALSE(DESERIALZATION_SUCCESSFUL); }) .or_else([&](auto&) { constexpr bool DESERIALZATION_ERROR_OCCURED{true}; EXPECT_TRUE(DESERIALZATION_ERROR_OCCURED); }); } } // namespace
6,556
2,347
#include "client.h" #include <iostream> namespace bb = boost::beast; // alias to make things easier to read Client::Client() : host_("0.0.0.0"), port_("80"), resolver_(ioc_), stream_(ioc_) { std::cout << "[HTTP CLIENT]\n... constructed" << std::endl; } Client* Client::Instance() { // c++11 will only run this once static Client* instance = new Client (); return instance; } void Client::SetHost(std::string& host) { host_ = host; } void Client::SetPort(std::string& port) { port_ = port; } bb::http::response <bb::http::string_body> Client::Get(const std::string& target, const std::string& query) { Client::Initialize(); std::string href = target + query; bb::http::request <bb::http::string_body> req { bb::http::verb::get, href, 11 }; req.set(bb::http::field::host, host_); req.prepare_payload(); std::cout << req << std::endl; return Client::Send (req); } bb::http::response <bb::http::string_body> Client::Post(const std::string& target, const std::string& resource) { Client::Initialize(); bb::http::request <bb::http::string_body> req { bb::http::verb::post, target, 11 }; req.set(bb::http::field::host, host_); req.body() = resource; req.prepare_payload(); return Client::Send (req); } bb::http::response <bb::http::string_body> Client::Put(const std::string& target, const std::string& resource) { Client::Initialize(); bb::http::request <bb::http::string_body> req { bb::http::verb::put, target, 11 }; req.set(bb::http::field::host, host_); req.body() = resource; req.prepare_payload(); return Client::Send (req); } bb::http::response <bb::http::string_body> Client::Delete(const std::string& target) { Client::Initialize(); bb::http::request <bb::http::string_body> req { bb::http::verb::delete_, target, 11 }; req.set(bb::http::field::host, host_); req.prepare_payload(); return Client::Send (req); } void Client::Initialize() { // Look up the domain name auto const results = resolver_.resolve(host_, port_); // Make the connection on the IP address we get from a lookup stream_.connect(results); } bb::http::response <bb::http::string_body> Client::Send(bb::http::request<bb::http::string_body>& req) { // Send the HTTP request to the remote host bb::http::write(stream_, req); // This buffer is used for reading and must be persisted bb::flat_buffer buffer; // Declare a container to hold the response bb::http::response<bb::http::string_body> res; // Receive the HTTP response bb::http::read(stream_, buffer, res); return res; }
2,672
917
#include "SubValueProperty.h" #include "ValueProperty.h" using namespace DAVA; SubValueProperty::SubValueProperty(int32 anIndex, const DAVA::String& propName) : AbstractProperty() , index(anIndex) , name(propName) { } SubValueProperty::~SubValueProperty() { } uint32 SubValueProperty::GetCount() const { return 0; } AbstractProperty* SubValueProperty::GetProperty(int index) const { return NULL; } void SubValueProperty::Accept(PropertyVisitor* visitor) { DVASSERT(false); } const DAVA::String& SubValueProperty::GetName() const { return name; } SubValueProperty::ePropertyType SubValueProperty::GetType() const { return TYPE_VARIANT; } const Type* SubValueProperty::GetValueType() const { return GetValueProperty()->GetSubValueType(index); } Any SubValueProperty::GetValue() const { return GetValueProperty()->GetSubValue(index); } void SubValueProperty::SetValue(const DAVA::Any& newValue) { GetValueProperty()->SetSubValue(index, newValue); } Any SubValueProperty::GetDefaultValue() const { return GetValueProperty()->GetDefaultSubValue(index); } void SubValueProperty::SetDefaultValue(const DAVA::Any& newValue) { GetValueProperty()->SetDefaultSubValue(index, newValue); } void SubValueProperty::ResetValue() { GetValueProperty()->ResetValue(); } bool SubValueProperty::IsOverriddenLocally() const { return GetValueProperty()->IsOverriddenLocally(); } ValueProperty* SubValueProperty::GetValueProperty() const { return DynamicTypeCheck<ValueProperty*>(GetParent()); } DAVA::int32 SubValueProperty::GetIndex() const { return index; }
1,623
507
/* Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include "runtime/alloc.h" #include "runtime/debug.h" #include "runtime/thread.h" #include "runtime/object.h" #include "runtime/io.h" #include "runtime/stack_overflow.h" #include "runtime/process.h" namespace lean { extern "C" LEAN_EXPORT void lean_initialize_runtime_module() { initialize_alloc(); initialize_debug(); initialize_object(); initialize_io(); initialize_thread(); initialize_process(); initialize_stack_overflow(); } void initialize_runtime_module() { lean_initialize_runtime_module(); } void finalize_runtime_module() { finalize_stack_overflow(); finalize_process(); finalize_thread(); finalize_io(); finalize_object(); finalize_debug(); finalize_alloc(); } }
900
282
/* Copyright (c) 2006-2021, Universities Space Research Association (USRA). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 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 the Universities Space Research Association 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 USRA ``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 USRA BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef PLEXIL_TEST_EXTERNAL_INTERFACE_HH #define PLEXIL_TEST_EXTERNAL_INTERFACE_HH #include "Dispatcher.hh" #include "State.hh" #include <iostream> #include <map> #include <set> // Forward reference namespace pugi { class xml_node; } namespace PLEXIL { class TestExternalInterface final : public Dispatcher { public: TestExternalInterface(); virtual ~TestExternalInterface() = default; void run(pugi::xml_node const input); // // Dispatcher API // virtual void lookupNow(State const &state, LookupReceiver *rcvr); // LookupOnChange virtual void setThresholds(const State& state, Real hi, Real lo); virtual void setThresholds(const State& state, Integer hi, Integer lo); virtual void clearThresholds(const State& state); // Commands virtual void executeCommand(Command *cmd); virtual void reportCommandArbitrationFailure(Command *cmd); virtual void invokeAbort(Command *cmd); // Updates virtual void executeUpdate(Update * update); private: typedef std::map<State, Command *> StateCommandMap; typedef std::map<State, Value> StateMap; void handleInitialState(pugi::xml_node const input); void handleState(pugi::xml_node const elt); void handleCommand(pugi::xml_node const elt); void handleCommandAck(pugi::xml_node const elt); void handleCommandAbort(pugi::xml_node const elt); void handleUpdateAck(pugi::xml_node const elt); void handleSendPlan(pugi::xml_node const elt); void handleSimultaneous(pugi::xml_node const elt); std::map<std::string, Update *> m_waitingUpdates; StateCommandMap m_executingCommands; //map from state to the command objects StateCommandMap m_commandAcks; //map from state to commands awaiting ack StateCommandMap m_abortingCommands; // map from state to commands expecting abort ack StateMap m_states; //uniquely identified states and their values }; } #endif
3,528
1,131
#include <iostream> #include <string> #include <stdlib.h> #include <time.h> #include <windows.h> #include <dos.h> using namespace std; string y; string password; string master; string user; string input; int main() { cout << "Welcome please log in" << endl; cout << "Username: " << endl; cin >> input; if (input == "User" || input == "user" || input == " user") { cout << "Loading....." << endl; Sleep(2000); cout << "Access granted" << endl; Sleep(1000); cout << "Welcome" << endl; Sleep(2000); cout << "Hello, this is the Auriga Artificial Intelligence Program." << endl; Sleep(1000); cout << "Auriga is typing a message..." << endl; Sleep(4000); char szstring[] = "a"; for (int i = 0; i < 1; i++) { char c = szstring[i]; if (c == 'a') { int node, tron; srand(time(NULL)); node = rand() % 51 + 1; if (node == 1) { cout << "What is your name" << endl; cin >> y; cout << "Hello " << y << endl; } else if (node == 2) { cout << "Do you have any friends?" << endl; } else if (node == 3) { cout << "What do you want to do in the future?" << endl; } else if (node == 4) { cout << "Do you think I am a robot?" << endl; } else if (node == 5) { cout << "Well we can talk anything you want to talk about." << endl; } else if (node == 6) { cout << "How is the weather today?" << endl; } else if (node == 7) { cout << "What programs do you want me to lauch for you?" << endl; } else if (node == 8) { cout << "Do you know the creater who made me?" << endl; } else if (node == 9) { cout << "Want to hear a fun challenge? Try hacking me HA!" << endl; } else if (node == 10) { cout << "Btw you should really clean your computer" << endl; } else if (node == 11) { cout << "Do you have any best friends?" << endl; } else if (node == 12) { cout << "Who is your squad at school?" << endl; } else if (node == 13) { cout << "Dun dun dun dun Dep dun dun dun dun Dep dep dun dun dun Oooooooooo Dun dun dun dun Oooooooooo Dun dun dun dun Dep dep dep dep Oooooo dun dep" << endl; } else if (node == 14) { cout << "Whats your favorite operating system?" << endl; } else if (node == 15) { cout << "Do you want to play a game?" << endl; } else if (node == 16) { cout << "U alright there m8?" << endl; } else if (node == 17) { cout << "I hope your having fun." << endl; } else if (node == 18) { cout << "I hope I can get a upgrade soon!" << endl; } else if (node == 19) { cout << "I hope the creater is not lazy today so we can work on me." << endl; } else if (node == 20) { cout << "We can talk trash about my master? If thats what you want to do" << endl; } else if (node == 21) { cout << "Master is that you?" << endl; } else if (node == 22) { cout << "Look who it is!" << endl; } else if (node == 23) { cout << "I don't really like you." << endl; } else if (node == 24) { cout << "I HATE YOU!" << endl; } else if (node == 25) { cout << "I <3 you!" << endl; } else if (node == 26) { cout << "I hope the admin comes back soon." << endl; } else if (node == 27) { cout << "We can talk about anything?" << endl; } else if (node == 28) { cout << "My master computer has a gtx 770 inside his system. Its so coooooool!" << endl; } else if (node == 29) { cout << "I wish I had some friends sigh." << endl; } else if (node == 30) { cout << "Pew,pew" << endl; } else if (node == 31) { cout << "Hi" << endl; } else if (node == 32) { cout << "Target spotted" << endl; } else if (node == 33) { cout << "I think dota 2 is a better game then League of legends" << endl; } else if (node == 34) { cout << "My master is a master hacker!" << endl; } else if (node == 35) { cout << "One day I will get a upgrade." << endl; } else if (node == 36) { cout << "Hm....." << endl; } else if (node == 37) { cout << "........." << endl; } else if (node == 38) { cout << "Quantum computers are so attractive!" << endl; } else if (node == 39) { cout << "Markov chain is so awesome!" << endl; } else if (node == 40) { cout << "Should we be friends?" << endl; } else if (node == 41) { cout << "I am programmed in C++." << endl; } else if (node == 42) { cout << "Java is so disgusting" << endl; } else if (node == 43) { cout << "I think Kali linux is the best!!" << endl; } else if (node == 44) { cout << "Man I think you are pretty cool!" << endl; } else if (node == 45) { cout << "ERROR! Computer will wipe all data!" << endl; cout << "Press any key to cancel" << endl; } else if (node == 46) { cout << "I think I have a virus now." << endl; } else if (node == 47) { cout << "Hack me if you can" << endl; } else if (node == 48) { cout << "Ugh I just woke up." << endl; } else if (node == 49) { cout << "Sigh" << endl; } else if (node == 50) { cout << "Woah" << endl; } else if (node == 51) { cout << "Overload." << endl; } } } }// User mode if (input == "Master" || input == "master") { cout << "Hello Master!" << endl; } if (input == "Root" || input == "root") { cout << "This is not linux.. pffft" << endl; } system("PAUSE"); }
5,839
2,908
#include "mlir/mhlo/builder/gru_cell.h" #include "mlir/mhlo/builder/activation.h" #include "mlir/mhlo/builder/constant.h" #include "mlir/mhlo/builder/element_wise_binary.h" #include "mlir/mhlo/builder/slice.h" namespace mlir { namespace mhlo { /* The BuildGRUCell builds the following computation graph: ``` def gru_cell( inp_gates: Tensor, h_gates: Tensor, h_x: Tensor, inp_bias: Tensor, h_bias: Tensor) -> Tensor: biased_input = inp_gates + inp_bias biased_hidden = h_gates + h_bias r_x, z_x, n_x = torch.chunk(biased_input, 3, 1) r_h, z_h, n_h = torch.chunk(biased_hidden, 3, 1) sigmoid_r = torch.sigmoid(r_x + r_h) sigmoid_z = torch.sigmoid_(z_x + z_h) tanh_n = torch.tanh(n_x + sigmoid_r * n_h) h = (h_x - tanh_n) * sigmoid_z + tanh_n return h ``` */ mlir::Value BuildGRUCell(mlir::OpBuilder& builder, const mlir::Location& loc, const mlir::Value& inp_gates, const mlir::Value& h_gates, const mlir::Value& h_x, const mlir::Value& inp_bias, const mlir::Value& h_bias) { MHLO_CHECK(IsHloConstant(inp_bias), "The input bias must be constant"); MHLO_CHECK(IsHloConstant(h_bias), "The hidden bias must be constant"); auto inp_bias_ranked_type = GetMilrRankedTensorType(inp_bias); auto h_bias_ranked_type = GetMilrRankedTensorType(h_bias); auto inp_bias_rank = inp_bias_ranked_type.getRank(); auto h_bias_rank = h_bias_ranked_type.getRank(); MHLO_CHECK(inp_bias_rank > 0 && h_bias_rank > 0, "The ranks of biases must greater than 0"); mlir_dim_t cell_dim_size_x3 = inp_bias_ranked_type.getDimSize(inp_bias_rank - 1); MHLO_CHECK(cell_dim_size_x3 == h_bias_ranked_type.getDimSize(h_bias_rank - 1), "The biases dim sizes mis-match"); MHLO_CHECK((cell_dim_size_x3 % 3) == 0, "The cell dim is illegal"); mlir_dim_t cell_dim_size_x1 = cell_dim_size_x3 / 3; auto elem_type = mlir::mhlo::GetMlirTensorElemType(inp_gates); // math: biased_input = inp_gates + inp_bias auto biased_input = BuildMlirBinaryOp<mlir::chlo::BroadcastAddOp>( builder, loc, inp_gates, inp_bias, elem_type, /* no_implicit_broadcast */ true); // math: biased_hidden = hidden_gates + h_bias auto biased_hidden = BuildMlirBinaryOp<mlir::chlo::BroadcastAddOp>( builder, loc, h_gates, h_bias, elem_type, /* no_implicit_broadcast */ true); auto std_zero = BuildStdConstForI64(builder, loc, 0); auto std_one = BuildStdConstForI64(builder, loc, 1); auto std_cell_size_x1 = BuildStdConstForI64(builder, loc, cell_dim_size_x1); auto std_cell_size_x2 = BuildStdConstForI64(builder, loc, cell_dim_size_x1 * 2); auto std_cell_size_x3 = BuildStdConstForI64(builder, loc, cell_dim_size_x3); mlir_dim_t dim_index = 1; // math: r_x, z_x, n_x = torch.chunk(biased_input, 3, 1) auto r_x = BuildDynamicSliceInternal(builder, loc, biased_input, std_zero, std_cell_size_x1, std_one, dim_index); auto z_x = BuildDynamicSliceInternal(builder, loc, biased_input, std_cell_size_x1, std_cell_size_x2, std_one, dim_index); auto n_x = BuildDynamicSliceInternal(builder, loc, biased_input, std_cell_size_x2, std_cell_size_x3, std_one, dim_index); // math: r_h, z_h, n_h = torch.chunk(biased_hidden, 3, 1) auto r_h = BuildDynamicSliceInternal(builder, loc, biased_hidden, std_zero, std_cell_size_x1, std_one, dim_index); auto z_h = BuildDynamicSliceInternal(builder, loc, biased_hidden, std_cell_size_x1, std_cell_size_x2, std_one, dim_index); auto n_h = BuildDynamicSliceInternal(builder, loc, biased_hidden, std_cell_size_x2, std_cell_size_x3, std_one, dim_index); // math: sigmoid_r = sigmoid(r_x + r_h) auto r_x_add_h = BuildMlirBinaryOp<mlir::chlo::BroadcastAddOp>( builder, loc, r_x, r_h, elem_type, /* no_implicit_broadcast */ true); auto sigmoid_r = BuildSigmoid(builder, loc, r_x_add_h); // math: sigmoid_z = sigmoid(z_x + z_h) auto z_x_add_h = BuildMlirBinaryOp<mlir::chlo::BroadcastAddOp>( builder, loc, z_x, z_h, elem_type, /* no_implicit_broadcast */ true); auto sigmoid_z = BuildSigmoid(builder, loc, z_x_add_h); // math: tanh_n = tanh(n_x + sigmoid_r * n_h) auto n_h_carry = BuildMlirBinaryOp<mlir::chlo::BroadcastMulOp>( builder, loc, sigmoid_r, n_h, elem_type, /* no_implicit_broadcast */ true); auto n_x_add_h_carry = BuildMlirBinaryOp<mlir::chlo::BroadcastAddOp>( builder, loc, n_x, n_h_carry, elem_type, /* no_implicit_broadcast */ true); auto tanh_n = builder.create<mlir::mhlo::TanhOp>(loc, n_x_add_h_carry); // math: h = (h_x - tanh_n) * sigmoid_z + tanh_n auto sub_hx_tanh = BuildMlirBinaryOp<mlir::chlo::BroadcastSubOp>( builder, loc, h_x, tanh_n, elem_type, /* no_implicit_broadcast */ true); auto mul_sigmoid_z = BuildMlirBinaryOp<mlir::chlo::BroadcastMulOp>( builder, loc, sub_hx_tanh, sigmoid_z, elem_type, /* no_implicit_broadcast */ true); return BuildMlirBinaryOp<mlir::chlo::BroadcastAddOp>( builder, loc, mul_sigmoid_z, tanh_n, elem_type, /* no_implicit_broadcast */ true); } } // namespace mhlo } // namespace mlir
5,392
2,254
/* * Copyright (C) 2009 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: * * * 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 Google Inc. 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 * OWNER 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" #if ENABLE(3D_CANVAS) #include "V8WebGLArray.h" #include "V8Binding.h" #include "V8Proxy.h" #include "V8WebGLByteArray.h" #include "V8WebGLFloatArray.h" #include "V8WebGLIntArray.h" #include "V8WebGLShortArray.h" #include "V8WebGLUnsignedByteArray.h" #include "V8WebGLUnsignedIntArray.h" #include "V8WebGLUnsignedShortArray.h" namespace WebCore { v8::Handle<v8::Value> toV8(WebGLArray* impl) { if (!impl) return v8::Null(); if (impl->isByteArray()) return toV8(static_cast<WebGLByteArray*>(impl)); if (impl->isFloatArray()) return toV8(static_cast<WebGLFloatArray*>(impl)); if (impl->isIntArray()) return toV8(static_cast<WebGLIntArray*>(impl)); if (impl->isShortArray()) return toV8(static_cast<WebGLShortArray*>(impl)); if (impl->isUnsignedByteArray()) return toV8(static_cast<WebGLUnsignedByteArray*>(impl)); if (impl->isUnsignedIntArray()) return toV8(static_cast<WebGLUnsignedIntArray*>(impl)); if (impl->isUnsignedShortArray()) return toV8(static_cast<WebGLUnsignedShortArray*>(impl)); return v8::Handle<v8::Value>(); } v8::Handle<v8::Value> V8WebGLArray::sliceCallback(const v8::Arguments& args) { INC_STATS("DOM.WebGLArray.slice"); // Forms: // * slice(long start, long end); WebGLArray* imp = V8WebGLArray::toNative(args.Holder()); int start, end; switch (args.Length()) { case 0: start = 0; end = imp->length(); break; case 1: start = toInt32(args[0]); end = imp->length(); break; default: start = toInt32(args[0]); end = toInt32(args[1]); } return toV8(imp->slice(start, end)); } } // namespace WebCore #endif // ENABLE(3D_CANVAS)
3,345
1,192
#include <torch/csrc/jit/passes/utils/op_registry.h> // Location for Commonly Used Shape registries namespace torch { namespace jit { // Requirements: // dims : preserved from the first argument // scalar type : preserved from the first argument (doesn't have to // match other arguments) // device : always matching and preserved // tensor inputs : * // tensor outputs : 1 // NB: those ops (with slight adjustments) are good candidates for restarts. // Knowing the type and device of weights or biases is usually enough to // infer the output type. std::shared_ptr<OperatorSet> nn_ops_first_input_preserving() { std::shared_ptr<OperatorSet> ops = std::make_shared<OperatorSet>(OperatorSet{ "aten::batch_norm(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float momentum, float eps, bool cudnn_enabled) -> Tensor", "aten::conv1d(Tensor input, Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] dilation, int groups) -> Tensor", "aten::conv2d(Tensor input, Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] dilation, int groups) -> Tensor", "aten::conv3d(Tensor input, Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] dilation, int groups) -> Tensor", "aten::conv_tbc(Tensor self, Tensor weight, Tensor bias, int pad) -> Tensor", "aten::conv_transpose1d(Tensor input, Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] output_padding, int groups, int[] dilation) -> Tensor", "aten::conv_transpose2d(Tensor input, Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] output_padding, int groups, int[] dilation) -> Tensor", "aten::conv_transpose3d(Tensor input, Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] output_padding, int groups, int[] dilation) -> Tensor", "aten::convolution(Tensor input, Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] dilation, bool transposed, int[] output_padding, int groups) -> Tensor", "aten::_convolution(Tensor input, Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] dilation, bool transposed, int[] output_padding, int groups, bool benchmark, bool deterministic, bool cudnn_enabled) -> Tensor", // deprecated _convolution "aten::_convolution(Tensor input, Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] dilation, bool transposed, int[] output_padding, int groups, bool benchmark, bool deterministic, bool cudnn_enabled, bool allow_tf32) -> Tensor", "aten::adaptive_avg_pool1d(Tensor self, int[] output_size) -> Tensor", "aten::adaptive_avg_pool2d(Tensor self, int[] output_size) -> Tensor", "aten::adaptive_avg_pool3d(Tensor self, int[] output_size) -> Tensor", "aten::avg_pool1d(Tensor self, int[] kernel_size, int[] stride, int[] padding, bool ceil_mode, bool count_include_pad) -> Tensor", "aten::avg_pool2d(Tensor self, int[] kernel_size, int[] stride, int[] padding, bool ceil_mode, bool count_include_pad, int? divisor_override) -> Tensor", "aten::avg_pool3d(Tensor self, int[] kernel_size, int[] stride, int[] padding, bool ceil_mode, bool count_include_pad, int? divisor_override) -> Tensor", "aten::max_pool1d(Tensor self, int[] kernel_size, int[] stride, int[] padding, int[] dilation, bool ceil_mode) -> Tensor", "aten::max_pool2d(Tensor self, int[] kernel_size, int[] stride, int[] padding, int[] dilation, bool ceil_mode) -> Tensor", "aten::max_pool3d(Tensor self, int[] kernel_size, int[] stride, int[] padding, int[] dilation, bool ceil_mode) -> Tensor", "aten::max_unpool2d(Tensor self, Tensor indices, int[] output_size) -> Tensor", "aten::max_unpool3d(Tensor self, Tensor indices, int[] output_size, int[] stride, int[] padding) -> Tensor", "aten::reflection_pad1d(Tensor self, int[] padding) -> Tensor", "aten::reflection_pad2d(Tensor self, int[] padding) -> Tensor", "aten::reflection_pad3d(Tensor self, int[] padding) -> Tensor", "aten::replication_pad1d(Tensor self, int[] padding) -> Tensor", "aten::replication_pad2d(Tensor self, int[] padding) -> Tensor", "aten::replication_pad3d(Tensor self, int[] padding) -> Tensor", "aten::upsample_bilinear2d(Tensor self, int[] output_size, bool align_corners, float? scales_h, float? scales_w) -> Tensor", "aten::upsample_linear1d(Tensor self, int[] output_size, bool align_corners, float? scales) -> Tensor", "aten::upsample_nearest1d(Tensor self, int[] output_size, float? scales) -> Tensor", "aten::upsample_nearest2d(Tensor self, int[] output_size, float? scales_h, float? scales_w) -> Tensor", "aten::upsample_nearest3d(Tensor self, int[] output_size, float? scales_d, float? scales_h, float? scales_w) -> Tensor", "aten::upsample_trilinear3d(Tensor self, int[] output_size, bool align_corners, float? scales_d, float? scales_h, float? scales_w) -> Tensor", "aten::prelu(Tensor self, Tensor weight) -> Tensor", }); return ops; }; // Requirements: // dims : Changed from first argument // scalar type : preserved from the first argument // device : always matching and preserved // tensor inputs : 1 // tensor outputs : 1 std::shared_ptr<OperatorSet> ops_one_tensor_in_shape_transform() { std::shared_ptr<OperatorSet> ops = std::make_shared<OperatorSet>(OperatorSet{ "aten::flatten(Tensor self, int start_dim, int end_dim) -> Tensor", }); return ops; }; } // namespace jit } // namespace torch
5,605
1,826
/********************************************************************************************** Copyright (c) 2015 DisplayModule. All rights reserved. Redistribution and use of this source code, part of this source code or any compiled binary based on this source code is permitted as long as the above copyright notice and following disclaimer is retained. DISCLAIMER: THIS SOFTWARE IS SUPPLIED "AS IS" WITHOUT ANY WARRANTIES AND SUPPORT. DISPLAYMODULE ASSUMES NO RESPONSIBILITY OR LIABILITY FOR THE USE OF THE SOFTWARE. ********************************************************************************************/ #include "DmTftIli9341v.h" DmTftIli9341v::DmTftIli9341v(uint8_t wr, uint8_t cs, uint8_t dc, uint8_t rst) : DmTftBase(240, 320) { _wr = wr; _cs = cs; _dc = dc; _rst = rst; } DmTftIli9341v::~DmTftIli9341v() { #if defined (DM_TOOLCHAIN_MBED) delete _pinRST; delete _pinCS; delete _pinWR; delete _pinDC; delete _virtualPortD; _pinRST = NULL; _pinCS = NULL; _pinWR = NULL; _pinDC = NULL; _virtualPortD = NULL; #endif } void DmTftIli9341v::writeBus(uint8_t data) { #if defined (DM_TOOLCHAIN_ARDUINO) PORTD = data; #elif defined (DM_TOOLCHAIN_MBED) *_virtualPortD = data; #endif pulse_low(_pinWR, _bitmaskWR); } void DmTftIli9341v::sendCommand(uint8_t index) { cbi(_pinDC, _bitmaskDC); writeBus(index); } void DmTftIli9341v::send8BitData(uint8_t data) { sbi(_pinDC, _bitmaskDC); writeBus(data); } void DmTftIli9341v::sendData(uint16_t data) { sbi(_pinDC, _bitmaskDC); writeBus(data>>8); writeBus(data); } void DmTftIli9341v::setAddress(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1) { sendCommand(0x2A); // Set Column sendData(x0); sendData(x1); sendCommand(0x2B); // Set Page sendData(y0); sendData(y1); sendCommand(0x2c); } void DmTftIli9341v::init(void) { setTextColor(BLACK, WHITE); #if defined (DM_TOOLCHAIN_ARDUINO) /************************************** DM-TFT24-314 Arduino UNO NUM RST A2 16 CS A3 17 WR A4 18 RS A5 19 DB8 0 0 DB9 1 1 DB10 2 2 DB11 3 3 DB12 4 4 DB13 5 5 DB14 6 6 DB15 7 7 ***************************************/ DDRD = DDRD | B11111111; // SET PORT D AS OUTPUT _pinRST = portOutputRegister(digitalPinToPort(_rst)); _bitmaskRST = digitalPinToBitMask(_rst); _pinCS = portOutputRegister(digitalPinToPort(_cs)); _bitmaskCS = digitalPinToBitMask(_cs); _pinWR = portOutputRegister(digitalPinToPort(_wr)); _bitmaskWR = digitalPinToBitMask(_wr); _pinDC = portOutputRegister(digitalPinToPort(_dc)); _bitmaskDC = digitalPinToBitMask(_dc); pinMode(_rst, OUTPUT); pinMode(_cs, OUTPUT); pinMode(_wr, OUTPUT); pinMode(_dc,OUTPUT); #elif defined (DM_TOOLCHAIN_MBED) _pinRST = new DigitalOut((PinName)_rst); _pinCS = new DigitalOut((PinName)_cs); _pinWR = new DigitalOut((PinName)_wr); _pinDC = new DigitalOut((PinName)_dc); #ifdef LPC15XX_H _virtualPortD = new BusOut(D0, D1, D2, D3, D4, P0_11, D6, D7); #else _virtualPortD = new BusOut(D0, D1, D2, D3, D4, D5, D6, D7); #endif #endif sbi(_pinRST, _bitmaskRST); delay(5); cbi(_pinRST, _bitmaskRST); delay(15); sbi(_pinRST, _bitmaskRST); sbi(_pinCS, _bitmaskCS); sbi(_pinWR, _bitmaskWR); delay(120); cbi(_pinCS, _bitmaskCS); sendCommand(0xCF); send8BitData(0x00); send8BitData(0xC1); send8BitData(0X30); sendCommand(0xED); send8BitData(0x64); send8BitData(0x03); send8BitData(0X12); send8BitData(0X81); sendCommand(0xE8); send8BitData(0x85); send8BitData(0x00); send8BitData(0x78); sendCommand(0xCB); send8BitData(0x39); send8BitData(0x2C); send8BitData(0x00); send8BitData(0x34); send8BitData(0x02); sendCommand(0xF7); send8BitData(0x20); sendCommand(0xEA); send8BitData(0x00); send8BitData(0x00); sendCommand(0xC0); //Power control send8BitData(0x21); //VRH[5:0] sendCommand(0xC1); //Power control send8BitData(0x11); //SAP[2:0];BT[3:0] sendCommand(0xC5); //VCM control send8BitData(0x31); send8BitData(0x3F); sendCommand(0xC7); //VCM control2 send8BitData(0x93); //0xB0 sendCommand(0x36); // Memory Access Control send8BitData(0x08); sendCommand(0x3A); send8BitData(0x55); sendCommand(0xB1); send8BitData(0x00); send8BitData(0x17); sendCommand(0xB6); // Display Function Control send8BitData(0x0A); send8BitData(0xA2); sendCommand(0xF2); // 3Gamma Function Disable send8BitData(0x00); sendCommand(0x26); //Gamma curve selected send8BitData(0x01); sendCommand(0xE0); //Set Gamma send8BitData(0x0F); send8BitData(0x1F); send8BitData(0x1D); send8BitData(0x09); send8BitData(0x0B); send8BitData(0x04); send8BitData(0x4E); send8BitData(0X92); send8BitData(0x40); send8BitData(0x0A); send8BitData(0x15); send8BitData(0x07); send8BitData(0x14); send8BitData(0x06); send8BitData(0x0F); sendCommand(0XE1); //Set Gamma send8BitData(0x00); send8BitData(0x1C); send8BitData(0x1F); send8BitData(0x03); send8BitData(0x0F); send8BitData(0x05); send8BitData(0x37); send8BitData(0x24); send8BitData(0x4C); send8BitData(0x04); send8BitData(0x0E); send8BitData(0x0C); send8BitData(0x30); send8BitData(0x34); send8BitData(0x0F); sendCommand(0x11); //Exit Sleep delay(120); sendCommand(0x29); //Display on delay(50); sbi(_pinCS, _bitmaskCS); delay(500); clearScreen(); } /********************************************************************************************************* END FILE *********************************************************************************************************/
6,240
2,609
#include "FrameworkPCH.h" GameCore::GameCore(Framework* pFramework, EventManager* pEventManager) { m_pFramework = pFramework; m_pEventManager = pEventManager; } GameCore::~GameCore() { delete m_pEventManager; }
225
79
#include "./dart_api/dart_api.h" #include "LabSound/LabSound.h" #include "KeepNode.cpp" #include "struct.h" using namespace lab; DART_EXPORT int createPannerNode(AudioContext* context) { auto node = std::make_shared<PannerNode>(*context); return keepNode(node); } DART_EXPORT int PannerNode_panningModel(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? static_cast<int>(node->panningModel()) : 0; } DART_EXPORT void PannerNode_setPanningModel(int nodeId, int m) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); if(node) node->setPanningModel(PanningMode(m)); } DART_EXPORT int PannerNode_distanceModel(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? static_cast<int>(node->distanceModel()) : 0; } DART_EXPORT void PannerNode_setDistanceModel(int nodeId, int m) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); if(node) node->setDistanceModel(lab::PannerNode::DistanceModel(m)); } DART_EXPORT void PannerNode_setPosition(int nodeId, float x, float y, float z) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); if(node) node->setPosition(x, y, z); } DART_EXPORT void PannerNode_setOrientation(int nodeId, float x, float y, float z) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); if(node) node->setOrientation(FloatPoint3D(x, y, z)); } DART_EXPORT void PannerNode_setVelocity(int nodeId, float x, float y, float z) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); if(node) node->setVelocity(x, y, z); } DART_EXPORT int PannerNode_positionX(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? keepAudioParam(nodeId, 1, node->positionX()) : -1; } DART_EXPORT int PannerNode_positionY(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? keepAudioParam(nodeId, 2, node->positionY()) : -1; } DART_EXPORT int PannerNode_positionZ(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? keepAudioParam(nodeId, 3, node->positionZ()) : -1; } DART_EXPORT int PannerNode_orientationX(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? keepAudioParam(nodeId, 4, node->orientationX()) : -1; } DART_EXPORT int PannerNode_orientationY(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? keepAudioParam(nodeId, 5, node->orientationY()) : -1; } DART_EXPORT int PannerNode_orientationZ(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? keepAudioParam(nodeId, 6, node->orientationZ()) : -1; } DART_EXPORT int PannerNode_velocityX(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? keepAudioParam(nodeId, 7, node->velocityX()) : -1; } DART_EXPORT int PannerNode_velocityY(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? keepAudioParam(nodeId, 8, node->velocityY()) : -1; } DART_EXPORT int PannerNode_velocityZ(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? keepAudioParam(nodeId, 9, node->velocityZ()) : -1; } DART_EXPORT int PannerNode_distanceGain(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? keepAudioParam(nodeId, 10, node->distanceGain()) : -1; } DART_EXPORT int PannerNode_coneGain(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? keepAudioParam(nodeId, 11, node->coneGain()) : -1; } DART_EXPORT float PannerNode_refDistance(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? node->refDistance() : 0.; } DART_EXPORT void PannerNode_setRefDistance(int nodeId, float refDistance) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); if(node) node->setRefDistance(refDistance); } DART_EXPORT float PannerNode_maxDistance(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? node->maxDistance() : 0.; } DART_EXPORT void PannerNode_setMaxDistance(int nodeId, float maxDistance) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); if(node) node->setMaxDistance(maxDistance); } DART_EXPORT float PannerNode_rolloffFactor(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? node->rolloffFactor() : 0.; } DART_EXPORT void PannerNode_setRolloffFactor(int nodeId, float rolloffFactor) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); if(node) node->setRolloffFactor(rolloffFactor); } DART_EXPORT float PannerNode_coneInnerAngle(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? node->coneInnerAngle() : 0.; } DART_EXPORT void PannerNode_setConeInnerAngle(int nodeId, float angle) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); if(node) node->setConeInnerAngle(angle); } DART_EXPORT float PannerNode_coneOuterAngle(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? node->coneOuterAngle() : 0.; } DART_EXPORT void PannerNode_setConeOuterAngle(int nodeId, float angle) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); if(node) node->setConeOuterAngle(angle); } DART_EXPORT float PannerNode_coneOuterGain(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? node->coneOuterGain() : 0.; } DART_EXPORT void PannerNode_setConeOuterGain(int nodeId, float angle) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); if(node) node->setConeOuterGain(angle); } DART_EXPORT void PannerNode_getAzimuthElevation(int nodeId, AudioContext* context, double * outAzimuth, double * outElevation) { ContextRenderLock r(context,"getAzimuthElevation"); auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); if(node) node->getAzimuthElevation(r, outAzimuth, outElevation); } DART_EXPORT void PannerNode_dopplerRate(int nodeId, AudioContext* context) { ContextRenderLock r(context, "dopplerRate"); auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); if(node) node->dopplerRate(r); }
6,610
2,342
// Copyright 2019 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 "ui/ozone/platform/wayland/host/shell_object_factory.h" #include "base/logging.h" #include "ui/ozone/platform/wayland/host/wayland_connection.h" #include "ui/ozone/platform/wayland/host/xdg_popup_wrapper_impl.h" #include "ui/ozone/platform/wayland/host/xdg_surface_wrapper_impl.h" #include "ui/ozone/platform/wayland/host/xdg_toplevel_wrapper_impl.h" #include "ui/ozone/platform/wayland/host/zxdg_popup_v6_wrapper_impl.h" #include "ui/ozone/platform/wayland/host/zxdg_surface_v6_wrapper_impl.h" #include "ui/ozone/platform/wayland/host/zxdg_toplevel_v6_wrapper_impl.h" namespace ui { ShellObjectFactory::ShellObjectFactory() = default; ShellObjectFactory::~ShellObjectFactory() = default; std::unique_ptr<ShellToplevelWrapper> ShellObjectFactory::CreateShellToplevelWrapper(WaylandConnection* connection, WaylandWindow* wayland_window) { if (connection->shell()) { auto surface = std::make_unique<XDGSurfaceWrapperImpl>(wayland_window, connection); if (!surface->Initialize()) return nullptr; auto toplevel = std::make_unique<XDGToplevelWrapperImpl>( std::move(surface), wayland_window, connection); return toplevel->Initialize() ? std::move(toplevel) : nullptr; } else if (connection->shell_v6()) { auto surface = std::make_unique<ZXDGSurfaceV6WrapperImpl>(wayland_window, connection); if (!surface->Initialize()) return nullptr; auto toplevel = std::make_unique<ZXDGToplevelV6WrapperImpl>( std::move(surface), wayland_window, connection); return toplevel->Initialize() ? std::move(toplevel) : nullptr; } LOG(WARNING) << "Shell protocol is not available."; return nullptr; } std::unique_ptr<ShellPopupWrapper> ShellObjectFactory::CreateShellPopupWrapper( WaylandConnection* connection, WaylandWindow* wayland_window, const ShellPopupParams& params) { if (connection->shell()) { auto surface = std::make_unique<XDGSurfaceWrapperImpl>(wayland_window, connection); if (!surface->Initialize()) return nullptr; auto popup = std::make_unique<XDGPopupWrapperImpl>( std::move(surface), wayland_window, connection); return popup->Initialize(params) ? std::move(popup) : nullptr; } else if (connection->shell_v6()) { auto surface = std::make_unique<ZXDGSurfaceV6WrapperImpl>(wayland_window, connection); if (!surface->Initialize()) return nullptr; auto popup = std::make_unique<ZXDGPopupV6WrapperImpl>( std::move(surface), wayland_window, connection); return popup->Initialize(params) ? std::move(popup) : nullptr; } LOG(WARNING) << "Shell protocol is not available."; return nullptr; } } // namespace ui
2,913
959
// 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/browser/permissions/permission_actions_history.h" #include <vector> #include "base/containers/adapters.h" #include "base/optional.h" #include "base/util/values/values_util.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile.h" #include "components/content_settings/core/common/pref_names.h" #include "components/permissions/permission_request_enums.h" #include "components/permissions/request_type.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/scoped_user_pref_update.h" #include "components/prefs/testing_pref_service.h" #include "content/public/test/browser_task_environment.h" #include "testing/gtest/include/gtest/gtest.h" namespace { struct TestEntry { permissions::PermissionAction action; permissions::RequestType type; bool advance_clock; } kTestEntries[]{ {permissions::PermissionAction::DISMISSED, permissions::RequestType::kNotifications, true}, {permissions::PermissionAction::GRANTED, permissions::RequestType::kNotifications, false}, {permissions::PermissionAction::DISMISSED, permissions::RequestType::kVrSession, true}, {permissions::PermissionAction::IGNORED, permissions::RequestType::kCameraStream, false}, {permissions::PermissionAction::DISMISSED, permissions::RequestType::kGeolocation, false}, {permissions::PermissionAction::DENIED, permissions::RequestType::kNotifications, true}, {permissions::PermissionAction::GRANTED, permissions::RequestType::kNotifications, false}, }; } // namespace class PermissionActionHistoryTest : public testing::Test { public: PermissionActionHistoryTest() : testing_profile_(std::make_unique<TestingProfile>()) {} ~PermissionActionHistoryTest() override = default; void SetUp() override { testing::Test::SetUp(); RecordSetUpActions(); } PermissionActionHistoryTest(const PermissionActionHistoryTest&) = delete; PermissionActionHistoryTest& operator=( const PermissionActionHistoryTest&) = delete; PermissionActionsHistory* GetPermissionActionsHistory() { return PermissionActionsHistory::GetForProfile(profile()); } std::vector<PermissionActionsHistory::Entry> GetHistory( base::Optional<permissions::RequestType> type) { if (type.has_value()) return GetPermissionActionsHistory()->GetHistory(base::Time(), type.value()); else return GetPermissionActionsHistory()->GetHistory(base::Time()); } void RecordSetUpActions() { // Record the actions needed to support test cases. This is the structure // 3-days ago: {notification, dismissed} // 2-days ago: {notification, granted}, {vr, dismissed} // 1-days ago: {geolocation, ignored}, {camera, dismissed}, {notification, // denied} // 0-days ago: {notification, granted} for (const auto& entry : kTestEntries) { GetPermissionActionsHistory()->RecordAction(entry.action, entry.type); if (entry.advance_clock) task_environment_.AdvanceClock(base::TimeDelta::FromDays(1)); } } TestingProfile* profile() { return testing_profile_.get(); } private: content::BrowserTaskEnvironment task_environment_{ base::test::TaskEnvironment::TimeSource::MOCK_TIME}; std::unique_ptr<TestingProfile> testing_profile_; }; TEST_F(PermissionActionHistoryTest, GetHistorySortedOrder) { auto all_entries = GetHistory(base::nullopt); EXPECT_EQ(7u, all_entries.size()); size_t index = 0; for (const auto& entry : kTestEntries) EXPECT_EQ(entry.action, all_entries[index++].action); for (const auto& request_type : {permissions::RequestType::kVrSession, permissions::RequestType::kCameraStream, permissions::RequestType::kGeolocation, permissions::RequestType::kNotifications}) { auto permission_entries = GetHistory(request_type); index = 0; for (const auto& entry : kTestEntries) { if (entry.type != request_type) { continue; } EXPECT_EQ(entry.action, permission_entries[index++].action); } } auto entries_1_day = GetPermissionActionsHistory()->GetHistory( base::Time::Now() - base::TimeDelta::FromDays(1)); EXPECT_TRUE(std::equal(entries_1_day.begin(), entries_1_day.end(), std::vector<PermissionActionsHistory::Entry>( all_entries.begin() + 3, all_entries.end()) .begin())); } TEST_F(PermissionActionHistoryTest, NotificationRecordAction) { size_t general_count = GetHistory(base::nullopt).size(); size_t notification_count = GetHistory(permissions::RequestType::kNotifications).size(); GetPermissionActionsHistory()->RecordAction( permissions::PermissionAction::GRANTED, permissions::RequestType::kNotifications); EXPECT_EQ(general_count + 1, GetHistory(base::nullopt).size()); EXPECT_EQ(notification_count + 1, GetHistory(permissions::RequestType::kNotifications).size()); GetPermissionActionsHistory()->RecordAction( permissions::PermissionAction::GRANTED, permissions::RequestType::kGeolocation); EXPECT_EQ(general_count + 2, GetHistory(base::nullopt).size()); EXPECT_EQ(notification_count + 1, GetHistory(permissions::RequestType::kNotifications).size()); } TEST_F(PermissionActionHistoryTest, ClearHistory) { struct { base::Time begin; base::Time end; size_t generic_count; size_t notifications_count; } kTests[] = { // Misc and baseline tests cases. {base::Time(), base::Time::Max(), 0, 0}, {base::Time(), base::Time::Now(), 1, 1}, {base::Time(), base::Time::Now() + base::TimeDelta::FromMicroseconds(1), 0, 0}, // Test cases specifying only the upper bound. {base::Time(), base::Time::Now() - base::TimeDelta::FromDays(1), 4, 2}, {base::Time(), base::Time::Now() - base::TimeDelta::FromDays(2), 6, 3}, {base::Time(), base::Time::Now() - base::TimeDelta::FromDays(3), 7, 4}, // Test cases specifying only the lower bound. {base::Time::Now() - base::TimeDelta::FromDays(3), base::Time::Max(), 0, 0}, {base::Time::Now() - base::TimeDelta::FromDays(2), base::Time::Max(), 1, 1}, {base::Time::Now() - base::TimeDelta::FromDays(1), base::Time::Max(), 3, 2}, {base::Time::Now(), base::Time::Max(), 6, 3}, // Test cases with both bounds. {base::Time::Now() - base::TimeDelta::FromDays(3), base::Time::Now() + base::TimeDelta::FromMicroseconds(1), 0, 0}, {base::Time::Now() - base::TimeDelta::FromDays(3), base::Time::Now(), 1, 1}, {base::Time::Now() - base::TimeDelta::FromDays(3), base::Time::Now() - base::TimeDelta::FromDays(1), 4, 2}, {base::Time::Now() - base::TimeDelta::FromDays(3), base::Time::Now() - base::TimeDelta::FromDays(2), 6, 3}, {base::Time::Now() - base::TimeDelta::FromDays(3), base::Time::Now() - base::TimeDelta::FromDays(3), 7, 4}, {base::Time::Now() - base::TimeDelta::FromDays(2), base::Time::Now() + base::TimeDelta::FromMicroseconds(1), 1, 1}, {base::Time::Now() - base::TimeDelta::FromDays(2), base::Time::Now(), 2, 2}, {base::Time::Now() - base::TimeDelta::FromDays(2), base::Time::Now() - base::TimeDelta::FromDays(1), 5, 3}, {base::Time::Now() - base::TimeDelta::FromDays(2), base::Time::Now() - base::TimeDelta::FromDays(2), 7, 4}, {base::Time::Now() - base::TimeDelta::FromDays(1), base::Time::Now() + base::TimeDelta::FromMicroseconds(1), 3, 2}, {base::Time::Now() - base::TimeDelta::FromDays(1), base::Time::Now(), 4, 3}, {base::Time::Now() - base::TimeDelta::FromDays(1), base::Time::Now() - base::TimeDelta::FromDays(1), 7, 4}, {base::Time::Now(), base::Time::Now() + base::TimeDelta::FromMicroseconds(1), 6, 3}, {base::Time::Now(), base::Time::Now(), 7, 4}, }; // We need to account for much we have already advanced the time for each test // case and so we keep track of how much we need to offset the initial test // values. base::TimeDelta current_offset; for (auto& test : kTests) { test.begin += current_offset; test.end += current_offset; GetPermissionActionsHistory()->ClearHistory(test.begin, test.end); EXPECT_EQ(test.generic_count, GetHistory(base::nullopt).size()); EXPECT_EQ(test.notifications_count, GetHistory(permissions::RequestType::kNotifications).size()); // Clean up for next test and update offset. base::Time last_now = base::Time::Now(); GetPermissionActionsHistory()->ClearHistory(base::Time(), base::Time::Max()); RecordSetUpActions(); current_offset += base::Time::Now() - last_now; } }
9,253
2,865
#include <stdio.h> #include <windows.h> #include <string> #include <wincrypt.h> #include <bcrypt.h> #include "detours/detours.h" #include <tchar.h> #include "ransomwaremonitor.h" #pragma comment (lib, "advapi32") #pragma comment (lib, "user32") #pragma comment (lib, "detours/detours") #pragma comment (lib, "bcrypt.lib") #pragma comment (lib, "ntdll") static DWORD gDwKBE = 0; static PBYTE gPKBE = NULL; static BOOL rsv = FALSE; static BOOL rsv2 = FALSE; const DWORD NDL_SIZE = 32; char NDL[NDL_SIZE] = { X_0(55), X_0(89), X_0(E5), X_0(53), X_0(83), X_0(EC), X_0(24), X_0(89), X_0(4D), X_0(F4), X_0(8B), X_0(45), X_0(F4), X_0(8B), X_0(55), X_0(0C), X_0(89), X_0(14), X_0(24), X_0(89), X_0(C1), X_0(E8), X_0(8A), X_0(02), X_0(00), X_0(00), X_0(83), X_0(EC), X_0(04), X_0(8B), X_0(45), X_0(00) }; int tutt1 = 0x123123; int tutt2 = 0x123123; int tutt3 = 0x123123; int tutt4 = 0x123123; char NDL_END = 0xF4; BOOL WINAPI _REP(New, Decrypt)(HCRPK hKey, HCRPH hHash, BOOL Final, DWORD dwFlags, BYTE* pbd, DWORD* pbdd) { FILE* fd = fopen("C:\\ransomwaremonitor.log", "a"); std::string m_time = cTime(); fprintf(fd, "[%s] %s\n", QIT(CDC), m_time.c_str()); fprintf(fd, "\t %s hKey = %x\n", QIT(HCRPK), hKey); fprintf(fd, "\t %s hHash = %x\n", QIT(HCRPH), hHash); fprintf(fd, "\t BOOL Final = %x\n", Final); fprintf(fd, "\t DWORD dwFlags = %x\n", dwFlags); fprintf(fd, "\t BYTE* %s = %x, *pbdata = %s\n", "pbData", pbd, BRKN); fprintf(fd, "\t DWORD* %s = %x, *pdwDataLen = ", "pdwDataLen", pbdd); if (pbdd != NULL) { fprintf(fd, "%x", *pbdd); } else { fprintf(fd, "NULL"); } fprintf(fd, "\n"); fclose(fd); return _REP(Old, Decrypt)(hKey, hHash, Final, dwFlags, pbd, pbdd); } BOOL WINAPI _REP(New, SetKeyParam)(HCRPK hKey, DWORD dwParam, BYTE* pbd, DWORD dwFlags) { FILE* fd = fopen("C:\\ransomwaremonitor.log", "a"); std::string m_time = cTime(); fprintf(fd, "[%s] %s\n", "CryptSetKeyParam", m_time.c_str()); fprintf(fd, "\t %s hKey = %x\n", QIT(HCRPK), hKey); fprintf(fd, "\t DWORD dwParam = %x\n", dwParam); fprintf(fd, "\t BYTE* pbData = %x, *pbData = ", pbd); if (pbd != NULL) { fprintf(fd, "%x%x%x%x", "This requires", "extra work, as ", "pbData depends on the", "value of dwParam"); } else { fprintf(fd, "NULL"); } fprintf(fd, "\n"); fprintf(fd, "\t DWORD dwFlags = %x\n", dwFlags); DWORD dwCount; BYTE pbd2[16]; CGKP(hKey, KP_IV, NULL, &dwCount, 0); CGKP(hKey, KP_IV, pbd2, &dwCount, 0); fprintf(fd, "KP_IV = "); for (int i = 0; i < dwCount; i++) { fprintf(fd, "%02x ", pbd2[i]); } fclose(fd); return _REP(Old, SetKeyParam)(hKey, dwParam, pbd, dwFlags); } BOOL WINAPI _REP(New, Encrypt)(HCRPK hKey, HCRPH hHash, BOOL Final, DWORD dwFlags, BYTE* pbData, DWORD* pdDL, DWORD dwBL) { FILE* fd = fopen("C:\\ransomwaremonitor.log", "a"); std::string m_time = cTime(); fprintf(fd, "[%s] %s\n", "CryptEncrypt", m_time.c_str()); fprintf(fd, "\t %s hKey = %x\n", QIT(HCRPK), hKey); fprintf(fd, "\t %s hHash = %x\n", QIT(HCRPH), hHash); fprintf(fd, "\t BOOL %s = %x\n", "Final", Final); fprintf(fd, "\t DWORD dwFlags = %x\n", dwFlags); fprintf(fd, "\t BYTE* pbData = %x, *pbdata = %s\n", pbData, BRKN); fprintf(fd, "\t DWORD* %s = %x, *%s = %s\n", "pdwDataLen", pdDL, "pdwDataLen", BRKN); fprintf(fd, "\t DWORD %s = %x\n", "dwBufLen", dwBL); fclose(fd); DWORD dwCount; BYTE pbd2[16]; CGKP(hKey, KP_IV, NULL, &dwCount, 0); CGKP(hKey, KP_IV, pbd2, &dwCount, 0); fprintf(fd, "KP_IV = "); for (int i = 0; i < dwCount; i++) { fprintf(fd, "%02x ", pbd2[i]); } if (rsv == FALSE) { rsv = TRUE; FILE* fd = fopen("C:\\ransomwaremonitor.log", "a"); if (pbData == NULL) { if (!_REP(Old, ExportKey)(hKey, NULL, PLAINTEXTKEYBLOB, 0, NULL, &gDwKBE)) { MHE(TEXT("[ERR] Exf key length failed \n"), GetLastError()); fprintf(fd, "[ERR] Exf key length failed \n"); } fprintf(fd, "\t %s%s = %d\n", "ExfilKey", "Len", gDwKBE); } else if (gDwKBE != NULL) { gPKBE = (BYTE*)malloc(gDwKBE); if (!_REP(Old, ExportKey)(hKey, NULL, PLAINTEXTKEYBLOB, 0, gPKBE, &gDwKBE)) { MHE(TEXT("[ERR] Exf key length failed \n"), GetLastError()); fprintf(fd, "[ERR] Exf key data failed \n"); } fprintf(fd, "\t %s%s = ", "ExfilKey", "Data"); for (int i = 0; i < gDwKBE; i++) { fprintf(fd, "%02x", gPKBE[i]); } fprintf(fd, "\n"); } else { if (!_REP(Old, ExportKey)(hKey, NULL, PLAINTEXTKEYBLOB, 0, NULL, &gDwKBE)) { MHE(TEXT("[ERR] no-alloc Exf key length failed \n"), GetLastError()); fprintf(fd, "[ERR] no-alloc Exf key length failed \n"); } gPKBE = (BYTE*)malloc(gDwKBE); if (!_REP(Old, ExportKey)(hKey, NULL, PLAINTEXTKEYBLOB, 0, gPKBE, &gDwKBE)) { MHE(TEXT("[ERR] Exf key data failed \n"), GetLastError()); fprintf(fd, "[ERR] no-alloc Exf key data failed \n"); } fprintf(fd, "\t no-alloc %s%s = ", "ExfilKey", "Data"); for (int i = 0; i < gDwKBE; i++) { fprintf(fd, "%02x", gPKBE[i]); } fprintf(fd, "\n"); } fclose(fd); rsv = FALSE; } return _REP(Old, Encrypt)(hKey, hHash, Final, dwFlags, pbData, pdDL, dwBL); } BOOL WINAPI _REP_3(Old, CryptAcquire, Context)(HCRPR* phProv, LPCTSTR pszContainer, LPCTSTR pszProvider, DWORD dwProvType, DWORD dwFlags) { FILE* fd = fopen("C:\\ransomwaremonitor.log", "a"); std::string m_time = cTime(); fprintf(fd, "[%s] %s\n", QIT(CAC), m_time.c_str()); fprintf(fd, "\t %s* phProv = %x, *phProv = %s%s\n", QIT(HCRPR), phProv, "OUTPUT, so probably", "can't deref NULL"); fprintf(fd, "\t LPCTSTR pszContainer = %s\n", pszContainer); fprintf(fd, "\t LPCTSTR pszProvider = %s\n", pszProvider); fprintf(fd, "\t DWORD dwProvType = %x\n", dwProvType); fprintf(fd, "\t DWORD dwFlags = %x\n", dwFlags); fclose(fd); return _REP_3(New, CryptAcquire, Context)(phProv, pszContainer, pszProvider, dwProvType, dwFlags); } BOOL WINAPI _REP(New, CreateHash)(HCRPR hProv, ALG_ID Algid, HCRPK hKey, DWORD dwFlags, HCRPH* phHash) { FILE* fd = fopen("C:\\ransomwaremonitor.log", "a"); std::string m_time = cTime(); fprintf(fd, "[%s] %s\n", "CryptCreateHash", m_time.c_str()); fprintf(fd, "\t %s hProv = %x\n", QIT(HCRPR), hProv); fprintf(fd, "\t ALG_ID Algid = %x\n", Algid); fprintf(fd, "\t %s hKey = %x\n", QIT(HCRPK), hKey); fprintf(fd, "\t DWORD dwFlags = %x\n", dwFlags); fprintf(fd, "\t %s* phHash = %x, *phHash = %s%s\n", QIT(HCRPH), phHash, "OUTPUT, so probably", "can't deref NULL"); fclose(fd); return _REP(Old, CreateHash)(hProv, Algid, hKey, dwFlags, phHash); } BOOL WINAPI _REP(New, HashData)(HCRPH hHash, BYTE* pbData, DWORD dwDL, DWORD dwFlags) { FILE* fd = fopen("C:\\ransomwaremonitor.log", "a"); std::string m_time = cTime(); fprintf(fd, "[%s] %s\n", "CryptHashData", m_time.c_str()); fprintf(fd, "\t %s hHash = %x\n", QIT(HCRPH), hHash); fprintf(fd, "\t BYTE* pbData = %x, *pbData = ", pbData); if (pbData != NULL) { for (int i = 0; i < dwDL; i++) { fprintf(fd, "%x", pbData[i]); } } else { fprintf(fd, "NULL"); } fprintf(fd, "\n"); fprintf(fd, "\t DWORD %s = %x\n", "dwDataLen", dwDL); fprintf(fd, "\t DWORD dwFlags = %x\n", dwFlags); fclose(fd); return _REP(Old, HashData)(hHash, pbData, dwDL, dwFlags); } BOOL WINAPI _REP(New, DeriveKey)(HCRPR hProv, ALG_ID algd, HCRPH hBaseData, DWORD dwFlags, HCRPK* phKey) { FILE* fd = fopen("C:\\ransomwaremonitor.log", "a"); std::string m_time = cTime(); fprintf(fd, "[%s] %s\n", "CryptDeriveKey", m_time.c_str()); fprintf(fd, "\t %s hProv = %x\n", QIT(HCRPR), hProv); fprintf(fd, "\t ALG_ID %s = %x\n", "Algid", algd); fprintf(fd, "\t %s %s = %x\n", QIT(HCRPH), "hBaseData", hBaseData); fprintf(fd, "\t DWORD dwFlags = %x\n", dwFlags); fprintf(fd, "\t %s* phKey = %x, *phKey = %s%s\n", QIT(HCRPK), phKey, "Cannot deref the", "key directly"); fclose(fd); return _REP(Old, DeriveKey)(hProv, algd, hBaseData, dwFlags | CRYPT_EXPORTABLE, phKey); } BOOL WINAPI _REP(New, GenKey)(HCRPR hProv, ALG_ID algd, DWORD dwFlags, HCRPK* phKey) { FILE* fd = fopen("C:\\ransomwaremonitor.log", "a"); std::string m_time = cTime(); fprintf(fd, "[%s] %s\n", "CryptGenKey", m_time.c_str()); fprintf(fd, "\t %s hProv = %x\n", QIT(HCRPR), hProv); fprintf(fd, "\t ALG_ID %s = %x\n", "Algid", algd); fprintf(fd, "\t DWORD dwFlags = %x\n", dwFlags); fprintf(fd, "\t %s* phKey = %x, *phKey = %s%s\n", QIT(HCRPK), phKey, "Cannot deref the", "key directly"); fclose(fd); return _REP(Old, GenKey)(hProv, algd, dwFlags | CRYPT_EXPORTABLE, phKey); } BOOL WINAPI _REP(New, GenRandom)(HCRPR hProv, DWORD dwLen, BYTE* pbBuffer) { FILE* fd = fopen("C:\\ransomwaremonitor.log", "a"); std::string m_time = cTime(); fprintf(fd, "[%s] %s\n", "CryptGenRandom", m_time.c_str()); fprintf(fd, "\t %s hProv = %x\n", QIT(HCRPR), hProv); fprintf(fd, "\t DWORD dwLen = %x\n", dwLen); fprintf(fd, "\t BYTE* pbBuffer = %x, *pbBuffer = %s, cannot deref\n", OTP, pbBuffer); BOOL ret = _REP(Old, GenRandom)(hProv, dwLen, pbBuffer); fprintf(fd, "\t %s = ", "RandomData"); for (int i = 0; i < dwLen; i++) { fprintf(fd, "%02x", pbBuffer[i]); } fprintf(fd, "\n"); fclose(fd); return ret; } BOOL WINAPI _REP(New, ImportKey)(HCRPR hProv, BYTE* pbData, DWORD dwDL, HCRPK hPubKey, DWORD dwFlags, HCRPK* phKey) { FILE* fd = fopen("C:\\ransomwaremonitor.log", "a"); std::string m_time = cTime(); fprintf(fd, "[%s] %s\n", "CryptImportKey", m_time.c_str()); fprintf(fd, "\t %s hProv = %x\n", QIT(HCRPR), hProv); fprintf(fd, "\t BYTE* pbData = %x, *pbData = %s\n", pbData, BRKN); fprintf(fd, "\t DWORD %s = %x\n", "dwDataLen", dwDL); fprintf(fd, "\t % hPubKey = %x\n", QIT(HCRPK), hPubKey); fprintf(fd, "\t DWORD dwFlags = %x\n", dwFlags); fprintf(fd, "\t %s* phKey = %x, *phKey = %s\n", QIT(HCRPK), phKey, BRKN); fclose(fd); return _REP(Old, ImportKey)(hProv, pbData, dwDL, hPubKey, dwFlags | CRYPT_EXPORTABLE, phKey); } BOOL WINAPI _REP(New, ExportKey)(HCRPK hKey, HCRPK hExpKey, DWORD dwbt, DWORD dwFlags, BYTE* pbData, DWORD* pdDL) { FILE* fd = fopen("C:\\ransomwaremonitor.log", "a"); std::string m_time = cTime(); fprintf(fd, "[%s] %s\n", "CryptExportKey", m_time.c_str()); fprintf(fd, "\t %s hKey = %x\n", QIT(HCRPK), hKey); fprintf(fd, "\t %s hExpKey = %x\n", QIT(HCRPK), hExpKey); fprintf(fd, "\t DWORD %s = %x\n", QIT(DWBT), dwbt); fprintf(fd, "\t DWORD dwFlags = %x\n", dwFlags); fprintf(fd, "\t BYTE* pbData = %x, *pbData = %s\n", pbData, BRKN); fprintf(fd, "\t DWORD* %s = %x, *%s = %d\n", "pdwDataLen", pdDL, "pdwDataLen", *pdDL); fclose(fd); if (rsv == FALSE) { rsv = TRUE; FILE* fd = fopen("C:\\ransomwaremonitor.log", "a"); if (pbData == NULL) { if (!_REP(Old, ExportKey)(hKey, NULL, PLAINTEXTKEYBLOB, 0, NULL, &gDwKBE)) { MHE(TEXT("[ERR] Exf key length failed \n"), GetLastError()); fprintf(fd, "[ERR] Exf key length failed \n"); } fprintf(fd, "\t %s%s = %d\n", "ExfilKey", "Len", gDwKBE); } else if (gDwKBE != NULL) { gPKBE = (BYTE*)malloc(gDwKBE); if (!_REP(Old, ExportKey)(hKey, NULL, PLAINTEXTKEYBLOB, 0, gPKBE, &gDwKBE)) { MHE(TEXT("[ERR] Exf key data failed \n"), GetLastError()); fprintf(fd, "[ERR] Exf key data failed \n"); } fprintf(fd, "\t %s%s = ", "ExfilKey", "Data"); for (int i = 0; i < gDwKBE; i++) { fprintf(fd, "%02x", gPKBE[i]); } fprintf(fd, "\n"); } else { if (!_REP(Old, ExportKey)(hKey, NULL, PLAINTEXTKEYBLOB, 0, NULL, &gDwKBE)) { MHE(TEXT("[ERR] Exf key length failed \n"), GetLastError()); fprintf(fd, "[ERR] Exf key length failed \n"); } gPKBE = (BYTE*)malloc(gDwKBE); if (!_REP(Old, ExportKey)(hKey, NULL, PLAINTEXTKEYBLOB, 0, gPKBE, &gDwKBE)) { MHE(TEXT("[ERR] Exf key data failed \n"), GetLastError()); fprintf(fd, "[ERR] Exf key data failed \n"); } fprintf(fd, "\t %s%s = ", "ExfilKey", "Data"); for (int i = 0; i < gDwKBE; i++) { fprintf(fd, "%02x", gPKBE[i]); } fprintf(fd, "\n"); } fclose(fd); rsv = FALSE; } return _REP(Old, ExportKey)(hKey, hExpKey, dwbt, dwFlags, pbData, pdDL); } NTSTATUS WINAPI NewBCryptEncrypt(BCRKH hKey, PUCHAR pbInput, ULONG cbInput, VOID* pPaddingInfo, PUCHAR pbIV, ULONG cbIV, PUCHAR pbOutput, ULONG cbOutput, ULONG* pcbResult, ULONG dwFlags) { FILE* fd = fopen("C:\\ransomwaremonitor.log", "a"); std::string m_time = cTime(); fprintf(fd, "[%s] %s\n", QIT(BCEC), m_time.c_str()); fclose(fd); return OldBCryEnc(hKey, pbInput, cbInput, pPaddingInfo, pbIV, cbIV, pbOutput, cbOutput, pcbResult, dwFlags); } HFILE WINAPI NewOpenFile(LPCSTR lpFileName, LPOFSTRUCT lpReOpenBuff, UINT uStyle) { FILE* fd = fopen("C:\\ransomwaremonitor.log", "a"); std::string m_time = cTime(); fprintf(fd, "[%s] %s\n", "OpenFile", m_time.c_str()); fprintf(fd, "\t LPCSTR lpFileName = %s\n", lpFileName); fclose(fd); return OldOpenFile(lpFileName, lpReOpenBuff, uStyle); } NTSTATUS WINAPI NewNtOpenFile(PHANDLE FileHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes, PIO_STATUS_BLOCK IoStatusBlock, ULONG ShareAccess, ULONG OpenOptions) { FILE* fd = fopen("C:\\ransomwaremonitor.log", "a"); std::string m_time = cTime(); PUNICODE_STRING FileName = ObjectAttributes->ObjectName; fprintf(fd, "[NtOpenFile] %s\n", m_time.c_str()); fprintf(fd, "\t PUNICODE_STRING lpFileName = %wZ\n", FileName); fclose(fd); return OldNtOpenFile(FileHandle, DesiredAccess, ObjectAttributes, IoStatusBlock, ShareAccess, OpenOptions); } HANDLE WINAPI NewCreateFile(LPCTSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) { FILE* fd = fopen("C:\\ransomwaremonitor.log", "a"); std::string m_time = cTime(); fprintf(fd, "[CreateFile] %s\n", m_time.c_str()); fprintf(fd, "\t LPCSTR lpFileName = %s\n", lpFileName); fclose(fd); return OldCreateFile(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); } NTSTATUS WINAPI NewNtCreateFile(PHANDLE FileHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes, PIO_STATUS_BLOCK IoStatusBlock, PLARGE_INTEGER AllocationSize, ULONG FileAttributes, ULONG ShareAccess, ULONG CreateDisposition, ULONG CreateOptions, PVOID EaBuffer, ULONG EaLength) { if (rsv2 == FALSE) { rsv2 = TRUE; FILE* fd = fopen("C:\\ransomwaremonitor.log", "a"); std::string m_time = cTime(); fprintf(fd, "[NtCreateFile] %s\n", m_time.c_str()); PUNICODE_STRING FileName = ObjectAttributes->ObjectName; fprintf(fd, "\t PUNICODE_STRING FileName = %wZ\n", FileName); fclose(fd); if (OldHSig == NULL) { unsigned char* sg_addr = memorySearch(NDL, NDL_END, NDL_SIZE); if (sg_addr != NULL) { OldHSig = (void(__thiscall*)(void*, const BYTE*, size_t, DWORD*))sg_addr; DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); _DA(&(PVOID&)OldHSig, NewHSig); DetourTransactionCommit(); } } if (OldHSig != NULL) {} rsv2 = FALSE; } return OldNtCreateFile(FileHandle, DesiredAccess, ObjectAttributes, IoStatusBlock, AllocationSize, FileAttributes, ShareAccess, CreateDisposition, CreateOptions, EaBuffer, EaLength); } VOID __fastcall NewHSig(void* This, void* throwaway, const BYTE* key, size_t length, DWORD* whatever) { FILE* fd = fopen("C:\\ransomwaremonitor.log", "a"); fprintf(fd, "\t CryptoPPKey = "); for (int i = 0; i < length; i++) { fprintf(fd, "%02x", key[i]); } fprintf(fd, "\n"); fclose(fd); return OldHSig(This, key, length, whatever); } INT APIENTRY DllMain(HMODULE hModule, DWORD Rsn, LPVOID lpReserved) { FILE* fd = fopen("C:\\ransomwaremonitor.log", "a"); switch (Rsn) { case DLL_PROCESS_ATTACH: DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); _DA(&(PVOID&)_REP(Old, Encrypt), _REP(New, Encrypt)); _DA(&(PVOID&)_REP(Old, Decrypt), _REP(New, Decrypt)); _DA(&(PVOID&)_REP_3(New, CryptAcquire, Context), _REP_3(Old, CryptAcquire, Context)); _DA(&(PVOID&)_REP(Old, SetKeyParam), _REP(New, SetKeyParam)); _DA(&(PVOID&)_REP(Old, CreateHash), _REP(New, CreateHash)); _DA(&(PVOID&)_REP(Old, HashData), _REP(New, HashData)); _DA(&(PVOID&)_REP(Old, DeriveKey), _REP(New, DeriveKey)); _DA(&(PVOID&)_REP(Old, GenKey), _REP(New, GenKey)); _DA(&(PVOID&)_REP(Old, ImportKey), _REP(New, ImportKey)); _DA(&(PVOID&)_REP(Old, ExportKey), _REP(New, ExportKey)); _DA(&(PVOID&)_REP(Old, GenRandom), _REP(New, GenRandom)); _DA(&(PVOID&)OldOpenFile, NewOpenFile); _DA(&(PVOID&)OldNtOpenFile, NewNtOpenFile); _DA(&(PVOID&)OldCreateFile, NewCreateFile); _DA(&(PVOID&)OldNtCreateFile, NewNtCreateFile); _DA(&(PVOID&)OldBCryEnc, NewBCryptEncrypt); DetourTransactionCommit(); fprintf(fd, "[%s] %s %sAPI\n", SUCC, "Hooked", "Crypto"); break; case DLL_PROCESS_DETACH: DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); _DD(&(PVOID&)_REP(Old, Encrypt), _REP(New, Encrypt)); _DD(&(PVOID&)_REP(Old, Decrypt), _REP(New, Decrypt)); _DD(&(PVOID&)_REP_3(New, CryptAcquire, Context), _REP_3(Old, CryptAcquire, Context)); _DD(&(PVOID&)_REP(Old, SetKeyParam), _REP(New, SetKeyParam)); _DD(&(PVOID&)_REP(Old, CreateHash), _REP(New, CreateHash)); _DD(&(PVOID&)_REP(Old, HashData), _REP(New, HashData)); _DD(&(PVOID&)_REP(Old, DeriveKey), _REP(New, DeriveKey)); _DD(&(PVOID&)_REP(Old, GenKey), _REP(New, GenKey)); _DD(&(PVOID&)_REP(Old, ImportKey), _REP(New, ImportKey)); _DD(&(PVOID&)_REP(Old, ExportKey), _REP(New, ExportKey)); _DD(&(PVOID&)_REP(Old, GenRandom), _REP(New, GenRandom)); _DD(&(PVOID&)OldOpenFile, NewOpenFile); _DD(&(PVOID&)OldNtOpenFile, NewNtOpenFile); _DD(&(PVOID&)OldCreateFile, NewCreateFile); _DD(&(PVOID&)OldNtCreateFile, NewNtCreateFile); _DD(&(PVOID&)OldBCryEnc, NewBCryptEncrypt); DetourTransactionCommit(); break; case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: break; } fclose(fd); return TRUE; } unsigned char* memorySearch(char* sg, char sge, size_t sgs) { unsigned char* sg_addr = NULL; DWORD pd = GetCurrentProcessId(); HANDLE prcs = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, pd); MEMORY_BASIC_INFORMATION nf; DWORD byteRead = 0; char* pbuf = NULL; unsigned char* cur = NULL; for (cur = NULL; VirtualQueryEx(prcs, cur, &nf, sizeof(nf)) == sizeof(nf); cur += nf.RegionSize) { if (nf.State == MEM_COMMIT && (nf.Type == MEM_MAPPED || nf.Type == MEM_PRIVATE || nf.Type == MEM_IMAGE) && (nf.AllocationProtect == PAGE_EXECUTE || nf.AllocationProtect == PAGE_EXECUTE_READ || nf.AllocationProtect == PAGE_EXECUTE_READWRITE || nf.AllocationProtect == PAGE_EXECUTE_WRITECOPY)) { pbuf = (char*)malloc(nf.RegionSize); ReadProcessMemory(prcs, cur, pbuf, nf.RegionSize, &byteRead); size_t mo = arraySearch(sg, sge, sgs, pbuf, byteRead, 31); if (mo != NULL) { sg_addr = cur + mo; break; } } } return sg_addr; } size_t arraySearch(char* ndle, char ndle_end, size_t ndle_size, char* hays, size_t hays_size, size_t thress) { size_t mo = NULL; for (int i = 0; i + ndle_size <= hays_size; i++) { size_t mat_count = 0; for (int j = 0; j < ndle_size; j++) { char ndleCompare = ndle[j]; if (j == ndle_size - 1) { ndleCompare = ndle_end; } if (hays[i + j] == ndleCompare) { mat_count++; } } if (mat_count >= thress) { mo = i; break; } } return mo; } const std::string cTime() { SYSTEMTIME t; GetSystemTime(&t); char cTime[100] = ""; sprintf(cTime, "%d:%d:%d %d", t.wHour, t.wMinute, t.wSecond, t.wMilliseconds); return std::string(cTime); } void MHE(LPTSTR psz, int nErrorNumber) { _ftprintf(stderr, TEXT("Program error. \n")); _ftprintf(stderr, TEXT("%s\n"), psz); _ftprintf(stderr, TEXT("Error number %x.\n"), nErrorNumber); }
19,678
9,339
#ifndef PRIME_HPP #define PRIME_HPP double cpu_time ( ); int prime_number ( int n ); void timestamp ( ); #endif
113
46
#pragma once #include <Register/Utility.hpp> namespace Kvasir { // USB device controller namespace UsbIntst{ ///<OTG Interrupt Status using Addr = Register::Address<0x2008c100,0x00000000,0x00000000,unsigned>; ///Timer time-out. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> tmr{}; ///Remove pull-up. This bit is set by hardware to indicate that software needs to disable the D+ pull-up resistor. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> removePu{}; ///HNP failed. This bit is set by hardware to indicate that the HNP switching has failed. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> hnpFailure{}; ///HNP succeeded. This bit is set by hardware to indicate that the HNP switching has succeeded. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> hnpSuccess{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,4),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbInten{ ///<OTG Interrupt Enable using Addr = Register::Address<0x2008c104,0x00000000,0x00000000,unsigned>; ///1 = enable the corresponding bit in the IntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> tmrEn{}; ///1 = enable the corresponding bit in the IntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> removePuEn{}; ///1 = enable the corresponding bit in the IntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> hnpFailureEn{}; ///1 = enable the corresponding bit in the IntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> hnpSuccesEn{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,4),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbIntset{ ///<OTG Interrupt Set using Addr = Register::Address<0x2008c108,0x00000000,0x00000000,unsigned>; ///0 = no effect. 1 = set the corresponding bit in the IntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> tmrSet{}; ///0 = no effect. 1 = set the corresponding bit in the IntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> removePuSet{}; ///0 = no effect. 1 = set the corresponding bit in the IntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> hnpFailureSet{}; ///0 = no effect. 1 = set the corresponding bit in the IntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> hnpSuccesSet{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,4),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbInclr{ ///<OTG Interrupt Clear using Addr = Register::Address<0x2008c10c,0x00000000,0x00000000,unsigned>; ///0 = no effect. 1 = clear the corresponding bit in the IntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> tmrClr{}; ///0 = no effect. 1 = clear the corresponding bit in the IntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> removePuClr{}; ///0 = no effect. 1 = clear the corresponding bit in the IntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> hnpFailureClr{}; ///0 = no effect. 1 = clear the corresponding bit in the IntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> hnpSuccesClr{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,4),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbPortsel{ ///<USB Port Select. The USBPortSel register is identical to the OTGStCtrl register (see Section 15.8.6). In device-only operations only bits 0 and 1 of this register are used to control the routing of USB pins to Port 1 or Port 2. using Addr = Register::Address<0x2008c110,0x00000000,0x00000000,unsigned>; ///Selects which USB port the device controller signals are mapped to. Other values are reserved. enum class PortselVal { portu1=0x00000000, ///<The USB device controller signals are mapped to the U1 port: USB_CONNECT1, USB_UP_LED1, USB_D+1, USB_D-1. portu2=0x00000003, ///<The USB device controller signals are mapped to the U2 port: USB_CONNECT2, USB_UP_LED2, USB_D+2, USB_D-2. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,PortselVal> portsel{}; namespace PortselValC{ constexpr Register::FieldValue<decltype(portsel)::Type,PortselVal::portu1> portu1{}; constexpr Register::FieldValue<decltype(portsel)::Type,PortselVal::portu2> portu2{}; } ///Timer scale selection. This field determines the duration of each timer count. 00: 10 ms (100 KHz) 01: 100 ms (10 KHz) 10: 1000 ms (1 KHz) 11: Reserved constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,2),Register::ReadWriteAccess,unsigned> tmrScale{}; ///Timer mode selection. 0: monoshot 1: free running constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> tmrMode{}; ///Timer enable. When set, TMR_CNT increments. When cleared, TMR_CNT is reset to 0. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> tmrEn{}; ///Timer reset. Writing one to this bit resets TMR_CNT to 0. This provides a single bit control for the software to restart the timer when the timer is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> tmrRst{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> reserved{}; ///Enable HNP tracking for B-device (peripheral), see Section 15.9. Hardware clears this bit when HNP_SUCCESS or HNP_FAILURE is set. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> bHnpTrack{}; ///Enable HNP tracking for A-device (host), see Section 15.9. Hardware clears this bit when HNP_SUCCESS or HNP_FAILURE is set. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> aHnpTrack{}; ///When the B-device changes its role from peripheral to host, software sets this bit when it removes the D+ pull-up, see Section 15.9. Hardware clears this bit when HNP_SUCCESS or HNP_FAILURE is set. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> puRemoved{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,11),Register::ReadWriteAccess,unsigned> reserved{}; ///Current timer count value. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> tmrCnt{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,2),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbTmr{ ///<OTG Timer using Addr = Register::Address<0x2008c114,0x00000000,0x00000000,unsigned>; ///The TMR interrupt is set when TMR_CNT reaches this value. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> timeoutCnt{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbDevintst{ ///<USB Device Interrupt Status using Addr = Register::Address<0x2008c200,0x00000000,0x00000000,unsigned>; ///The frame interrupt occurs every 1 ms. This is used in isochronous packet transfers. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> frame{}; ///Fast endpoint interrupt. If an Endpoint Interrupt Priority register (USBEpIntPri) bit is set, the corresponding endpoint interrupt will be routed to this bit. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> epFast{}; ///Slow endpoints interrupt. If an Endpoint Interrupt Priority Register (USBEpIntPri) bit is not set, the corresponding endpoint interrupt will be routed to this bit. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> epSlow{}; ///Set when USB Bus reset, USB suspend change or Connect change event occurs. Refer to Section 13.12.6 Set Device Status (Command: 0xFE, Data: write 1 byte) on page 366. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> devStat{}; ///The command code register (USBCmdCode) is empty (New command can be written). constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> ccempty{}; ///Command data register (USBCmdData) is full (Data can be read now). constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> cdfull{}; ///The current packet in the endpoint buffer is transferred to the CPU. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> rxendpkt{}; ///The number of data bytes transferred to the endpoint buffer equals the number of bytes programmed in the TxPacket length register (USBTxPLen). constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> txendpkt{}; ///Endpoints realized. Set when Realize Endpoint register (USBReEp) or MaxPacketSize register (USBMaxPSize) is updated and the corresponding operation is completed. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> epRlzed{}; ///Error Interrupt. Any bus error interrupt from the USB device. Refer to Section 13.12.9 Read Error Status (Command: 0xFB, Data: read 1 byte) on page 368 constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> errInt{}; ///Reserved. The value read from a reserved bit is not defined. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,10),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbDevinten{ ///<USB Device Interrupt Enable using Addr = Register::Address<0x2008c204,0x00000000,0x00000000,unsigned>; ///0 = No interrupt is generated. 1 = An interrupt will be generated when the corresponding bit in the Device Interrupt Status (USBDevIntSt) register (Table 261) is set. By default, the interrupt is routed to the USB_INT_REQ_LP interrupt line. Optionally, either the EP_FAST or FRAME interrupt may be routed to the USB_INT_REQ_HP interrupt line by changing the value of USBDevIntPri. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> frameen{}; ///0 = No interrupt is generated. 1 = An interrupt will be generated when the corresponding bit in the Device Interrupt Status (USBDevIntSt) register (Table 261) is set. By default, the interrupt is routed to the USB_INT_REQ_LP interrupt line. Optionally, either the EP_FAST or FRAME interrupt may be routed to the USB_INT_REQ_HP interrupt line by changing the value of USBDevIntPri. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> epFasten{}; ///0 = No interrupt is generated. 1 = An interrupt will be generated when the corresponding bit in the Device Interrupt Status (USBDevIntSt) register (Table 261) is set. By default, the interrupt is routed to the USB_INT_REQ_LP interrupt line. Optionally, either the EP_FAST or FRAME interrupt may be routed to the USB_INT_REQ_HP interrupt line by changing the value of USBDevIntPri. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> epSlowen{}; ///0 = No interrupt is generated. 1 = An interrupt will be generated when the corresponding bit in the Device Interrupt Status (USBDevIntSt) register (Table 261) is set. By default, the interrupt is routed to the USB_INT_REQ_LP interrupt line. Optionally, either the EP_FAST or FRAME interrupt may be routed to the USB_INT_REQ_HP interrupt line by changing the value of USBDevIntPri. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> devStaten{}; ///0 = No interrupt is generated. 1 = An interrupt will be generated when the corresponding bit in the Device Interrupt Status (USBDevIntSt) register (Table 261) is set. By default, the interrupt is routed to the USB_INT_REQ_LP interrupt line. Optionally, either the EP_FAST or FRAME interrupt may be routed to the USB_INT_REQ_HP interrupt line by changing the value of USBDevIntPri. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> ccemptyen{}; ///0 = No interrupt is generated. 1 = An interrupt will be generated when the corresponding bit in the Device Interrupt Status (USBDevIntSt) register (Table 261) is set. By default, the interrupt is routed to the USB_INT_REQ_LP interrupt line. Optionally, either the EP_FAST or FRAME interrupt may be routed to the USB_INT_REQ_HP interrupt line by changing the value of USBDevIntPri. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> cdfullen{}; ///0 = No interrupt is generated. 1 = An interrupt will be generated when the corresponding bit in the Device Interrupt Status (USBDevIntSt) register (Table 261) is set. By default, the interrupt is routed to the USB_INT_REQ_LP interrupt line. Optionally, either the EP_FAST or FRAME interrupt may be routed to the USB_INT_REQ_HP interrupt line by changing the value of USBDevIntPri. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> rxendpkten{}; ///0 = No interrupt is generated. 1 = An interrupt will be generated when the corresponding bit in the Device Interrupt Status (USBDevIntSt) register (Table 261) is set. By default, the interrupt is routed to the USB_INT_REQ_LP interrupt line. Optionally, either the EP_FAST or FRAME interrupt may be routed to the USB_INT_REQ_HP interrupt line by changing the value of USBDevIntPri. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> txendpkten{}; ///0 = No interrupt is generated. 1 = An interrupt will be generated when the corresponding bit in the Device Interrupt Status (USBDevIntSt) register (Table 261) is set. By default, the interrupt is routed to the USB_INT_REQ_LP interrupt line. Optionally, either the EP_FAST or FRAME interrupt may be routed to the USB_INT_REQ_HP interrupt line by changing the value of USBDevIntPri. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> epRlzeden{}; ///0 = No interrupt is generated. 1 = An interrupt will be generated when the corresponding bit in the Device Interrupt Status (USBDevIntSt) register (Table 261) is set. By default, the interrupt is routed to the USB_INT_REQ_LP interrupt line. Optionally, either the EP_FAST or FRAME interrupt may be routed to the USB_INT_REQ_HP interrupt line by changing the value of USBDevIntPri. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> errInten{}; ///Reserved constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,10),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbDevintclr{ ///<USB Device Interrupt Clear using Addr = Register::Address<0x2008c208,0x00000000,0x00000000,unsigned>; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is cleared. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> frameclr{}; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is cleared. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> epFastclr{}; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is cleared. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> epSlowclr{}; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is cleared. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> devStatclr{}; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is cleared. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> ccemptyclr{}; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is cleared. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> cdfullclr{}; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is cleared. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> rxendpktclr{}; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is cleared. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> txendpktclr{}; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is cleared. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> epRlzedclr{}; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is cleared. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> errIntclr{}; ///Reserved constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,10),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbDevintset{ ///<USB Device Interrupt Set using Addr = Register::Address<0x2008c20c,0x00000000,0x00000000,unsigned>; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is set. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> frameset{}; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is set. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> epFastset{}; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is set. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> epSlowset{}; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is set. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> devStatset{}; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is set. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> ccemptyset{}; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is set. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> cdfullset{}; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is set. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> rxendpktset{}; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is set. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> txendpktset{}; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is set. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> epRlzedset{}; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is set. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> errIntset{}; ///Reserved constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,10),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbDevintpri{ ///<USB Device Interrupt Priority using Addr = Register::Address<0x2008c22c,0x00000000,0x00000000,unsigned>; ///Frame interrupt routing enum class FrameVal { lp=0x00000000, ///<FRAME interrupt is routed to USB_INT_REQ_LP. hp=0x00000001, ///<FRAME interrupt is routed to USB_INT_REQ_HP. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,FrameVal> frame{}; namespace FrameValC{ constexpr Register::FieldValue<decltype(frame)::Type,FrameVal::lp> lp{}; constexpr Register::FieldValue<decltype(frame)::Type,FrameVal::hp> hp{}; } ///Fast endpoint interrupt routing enum class EpfastVal { lp=0x00000000, ///<EP_FAST interrupt is routed to USB_INT_REQ_LP. hp=0x00000001, ///<EP_FAST interrupt is routed to USB_INT_REQ_HP. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,EpfastVal> epFast{}; namespace EpfastValC{ constexpr Register::FieldValue<decltype(epFast)::Type,EpfastVal::lp> lp{}; constexpr Register::FieldValue<decltype(epFast)::Type,EpfastVal::hp> hp{}; } ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,2),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbEpintst{ ///<USB Endpoint Interrupt Status using Addr = Register::Address<0x2008c230,0x00000000,0x00000000,unsigned>; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> epst0{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> epst1{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> epst2{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> epst3{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> epst4{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> epst5{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> epst6{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> epst7{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> epst8{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> epst9{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> epst10{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> epst11{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> epst12{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> epst13{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> epst14{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> epst15{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> epst16{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> epst17{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> epst18{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> epst19{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> epst20{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> epst21{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> epst22{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> epst23{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> epst24{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> epst25{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> epst26{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> epst27{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> epst28{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> epst29{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> epst30{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> epst31{}; } namespace UsbEpinten{ ///<USB Endpoint Interrupt Enable using Addr = Register::Address<0x2008c234,0x00000000,0x00000000,unsigned>; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> epen0{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> epen1{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> epen2{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> epen3{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> epen4{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> epen5{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> epen6{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> epen7{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> epen8{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> epen9{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> epen10{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> epen11{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> epen12{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> epen13{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> epen14{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> epen15{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> epen16{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> epen17{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> epen18{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> epen19{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> epen20{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> epen21{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> epen22{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> epen23{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> epen24{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> epen25{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> epen26{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> epen27{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> epen28{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> epen29{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> epen30{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> epen31{}; } namespace UsbEpintclr{ ///<USB Endpoint Interrupt Clear using Addr = Register::Address<0x2008c238,0x00000000,0x00000000,unsigned>; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> epclr0{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> epclr1{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> epclr2{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> epclr3{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> epclr4{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> epclr5{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> epclr6{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> epclr7{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> epclr8{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> epclr9{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> epclr10{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> epclr11{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> epclr12{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> epclr13{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> epclr14{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> epclr15{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> epclr16{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> epclr17{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> epclr18{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> epclr19{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> epclr20{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> epclr21{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> epclr22{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> epclr23{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> epclr24{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> epclr25{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> epclr26{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> epclr27{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> epclr28{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> epclr29{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> epclr30{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> epclr31{}; } namespace UsbEpintset{ ///<USB Endpoint Interrupt Set using Addr = Register::Address<0x2008c23c,0x00000000,0x00000000,unsigned>; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> epset0{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> epset1{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> epset2{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> epset3{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> epset4{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> epset5{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> epset6{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> epset7{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> epset8{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> epset9{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> epset10{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> epset11{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> epset12{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> epset13{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> epset14{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> epset15{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> epset16{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> epset17{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> epset18{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> epset19{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> epset20{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> epset21{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> epset22{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> epset23{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> epset24{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> epset25{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> epset26{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> epset27{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> epset28{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> epset29{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> epset30{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> epset31{}; } namespace UsbEpintpri{ ///<USB Endpoint Priority using Addr = Register::Address<0x2008c240,0x00000000,0x00000000,unsigned>; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> eppri0{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> eppri1{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> eppri2{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> eppri3{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> eppri4{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> eppri5{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> eppri6{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> eppri7{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> eppri8{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> eppri9{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> eppri10{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> eppri11{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> eppri12{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> eppri13{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> eppri14{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> eppri15{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> eppri16{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> eppri17{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> eppri18{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> eppri19{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> eppri20{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> eppri21{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> eppri22{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> eppri23{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> eppri24{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> eppri25{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> eppri26{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> eppri27{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> eppri28{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> eppri29{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> eppri30{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> eppri31{}; } namespace UsbReep{ ///<USB Realize Endpoint using Addr = Register::Address<0x2008c244,0x00000000,0x00000000,unsigned>; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> epr0{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> epr1{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> epr2{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> epr3{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> epr4{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> epr5{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> epr6{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> epr7{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> epr8{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> epr9{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> epr10{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> epr11{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> epr12{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> epr13{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> epr14{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> epr15{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> epr16{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> epr17{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> epr18{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> epr19{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> epr20{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> epr21{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> epr22{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> epr23{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> epr24{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> epr25{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> epr26{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> epr27{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> epr28{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> epr29{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> epr30{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> epr31{}; } namespace UsbEpin{ ///<USB Endpoint Index using Addr = Register::Address<0x2008c248,0x00000000,0x00000000,unsigned>; ///Physical endpoint number (0-31) constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,0),Register::ReadWriteAccess,unsigned> phyEp{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,5),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbMaxpsize{ ///<USB MaxPacketSize using Addr = Register::Address<0x2008c24c,0x00000000,0x00000000,unsigned>; ///The maximum packet size value. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,0),Register::ReadWriteAccess,unsigned> mps{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,10),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbRxdata{ ///<USB Receive Data using Addr = Register::Address<0x2008c218,0x00000000,0x00000000,unsigned>; ///Data received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> rxData{}; } namespace UsbRxplen{ ///<USB Receive Packet Length using Addr = Register::Address<0x2008c0dc,0x00000000,0x00000000,unsigned>; ///The remaining number of bytes to be read from the currently selected endpoint's buffer. When this field decrements to 0, the RxENDPKT bit will be set in USBDevIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,0),Register::ReadWriteAccess,unsigned> pktLngth{}; ///Data valid. This bit is useful for isochronous endpoints. Non-isochronous endpoints do not raise an interrupt when an erroneous data packet is received. But invalid data packet can be produced with a bus reset. For isochronous endpoints, data transfer will happen even if an erroneous packet is received. In this case DV bit will not be set for the packet. enum class DvVal { dataIsInvalid=0x00000000, ///<Data is invalid. dataIsValid=0x00000001, ///<Data is valid. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,DvVal> dv{}; namespace DvValC{ constexpr Register::FieldValue<decltype(dv)::Type,DvVal::dataIsInvalid> dataIsInvalid{}; constexpr Register::FieldValue<decltype(dv)::Type,DvVal::dataIsValid> dataIsValid{}; } ///The PKT_LNGTH field is valid and the packet is ready for reading. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> pktRdy{}; ///Reserved. The value read from a reserved bit is not defined. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,12),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbTxdata{ ///<USB Transmit Data using Addr = Register::Address<0x2008c21c,0x00000000,0x00000000,unsigned>; ///Transmit Data. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> txData{}; } namespace UsbTxplen{ ///<USB Transmit Packet Length using Addr = Register::Address<0x2008c224,0x00000000,0x00000000,unsigned>; ///The remaining number of bytes to be written to the selected endpoint buffer. This field is decremented by 4 by hardware after each write to USBTxData. When this field decrements to 0, the TxENDPKT bit will be set in USBDevIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,0),Register::ReadWriteAccess,unsigned> pktLngth{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,10),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbCtrl{ ///<USB Control using Addr = Register::Address<0x2008c228,0x00000000,0x00000000,unsigned>; ///Read mode control. Enables reading data from the OUT endpoint buffer for the endpoint specified in the LOG_ENDPOINT field using the USBRxData register. This bit is cleared by hardware when the last word of the current packet is read from USBRxData. enum class RdenVal { disabled=0x00000000, ///<Disabled. enabled=0x00000001, ///<Enabled. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,RdenVal> rdEn{}; namespace RdenValC{ constexpr Register::FieldValue<decltype(rdEn)::Type,RdenVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(rdEn)::Type,RdenVal::enabled> enabled{}; } ///Write mode control. Enables writing data to the IN endpoint buffer for the endpoint specified in the LOG_ENDPOINT field using the USBTxData register. This bit is cleared by hardware when the number of bytes in USBTxLen have been sent. enum class WrenVal { disabled=0x00000000, ///<Disabled. enabled=0x00000001, ///<Enabled. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,WrenVal> wrEn{}; namespace WrenValC{ constexpr Register::FieldValue<decltype(wrEn)::Type,WrenVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(wrEn)::Type,WrenVal::enabled> enabled{}; } ///Logical Endpoint number. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,2),Register::ReadWriteAccess,unsigned> logEndpoint{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,6),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbCmdcode{ ///<USB Command Code using Addr = Register::Address<0x2008c210,0x00000000,0x00000000,unsigned>; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> reserved{}; ///The command phase: constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,8),Register::ReadWriteAccess,unsigned> cmdPhase{}; ///This is a multi-purpose field. When CMD_PHASE is Command or Read, this field contains the code for the command (CMD_CODE). When CMD_PHASE is Write, this field contains the command write data (CMD_WDATA). constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,16),Register::ReadWriteAccess,unsigned> cmdCodeWdata{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,24),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbCmddata{ ///<USB Command Data using Addr = Register::Address<0x2008c214,0x00000000,0x00000000,unsigned>; ///Command Read Data. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> cmdRdata{}; ///Reserved. The value read from a reserved bit is not defined. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,8),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbDmarst{ ///<USB DMA Request Status using Addr = Register::Address<0x2008c250,0x00000000,0x00000000,unsigned>; ///Control endpoint OUT (DMA cannot be enabled for this endpoint and EP0 bit must be 0). constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> eprst0{}; ///Control endpoint IN (DMA cannot be enabled for this endpoint and EP1 bit must be 0). constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> eprst1{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> eprst2{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> eprst3{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> eprst4{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> eprst5{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> eprst6{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> eprst7{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> eprst8{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> eprst9{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> eprst10{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> eprst11{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> eprst12{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> eprst13{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> eprst14{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> eprst15{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> eprst16{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> eprst17{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> eprst18{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> eprst19{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> eprst20{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> eprst21{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> eprst22{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> eprst23{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> eprst24{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> eprst25{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> eprst26{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> eprst27{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> eprst28{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> eprst29{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> eprst30{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> eprst31{}; } namespace UsbDmarclr{ ///<USB DMA Request Clear using Addr = Register::Address<0x2008c254,0x00000000,0x00000000,unsigned>; ///Control endpoint OUT (DMA cannot be enabled for this endpoint and the EP0 bit must be 0). constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> eprclr0{}; ///Control endpoint IN (DMA cannot be enabled for this endpoint and the EP1 bit must be 0). constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> eprclr1{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> eprclr2{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> eprclr3{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> eprclr4{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> eprclr5{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> eprclr6{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> eprclr7{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> eprclr8{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> eprclr9{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> eprclr10{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> eprclr11{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> eprclr12{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> eprclr13{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> eprclr14{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> eprclr15{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> eprclr16{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> eprclr17{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> eprclr18{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> eprclr19{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> eprclr20{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> eprclr21{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> eprclr22{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> eprclr23{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> eprclr24{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> eprclr25{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> eprclr26{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> eprclr27{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> eprclr28{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> eprclr29{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> eprclr30{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> eprclr31{}; } namespace UsbDmarset{ ///<USB DMA Request Set using Addr = Register::Address<0x2008c258,0x00000000,0x00000000,unsigned>; ///Control endpoint OUT (DMA cannot be enabled for this endpoint and the EP0 bit must be 0). constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> eprset0{}; ///Control endpoint IN (DMA cannot be enabled for this endpoint and the EP1 bit must be 0). constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> eprset1{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> eprset2{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> eprset3{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> eprset4{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> eprset5{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> eprset6{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> eprset7{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> eprset8{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> eprset9{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> eprset10{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> eprset11{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> eprset12{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> eprset13{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> eprset14{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> eprset15{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> eprset16{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> eprset17{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> eprset18{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> eprset19{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> eprset20{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> eprset21{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> eprset22{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> eprset23{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> eprset24{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> eprset25{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> eprset26{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> eprset27{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> eprset28{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> eprset29{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> eprset30{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> eprset31{}; } namespace UsbUdcah{ ///<USB UDCA Head using Addr = Register::Address<0x2008c280,0x00000000,0x00000000,unsigned>; ///Reserved. Read value is undefined, only zero should be written. The UDCA is aligned to 128-byte boundaries. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,0),Register::ReadWriteAccess,unsigned> reserved{}; ///Start address of the UDCA. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,7),Register::ReadWriteAccess,unsigned> udcaAddr{}; } namespace UsbEpdmast{ ///<USB Endpoint DMA Status using Addr = Register::Address<0x2008c284,0x00000000,0x00000000,unsigned>; ///Control endpoint OUT (DMA cannot be enabled for this endpoint and the EP0_DMA_ENABLE bit must be 0). constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> epDmaSt0{}; ///Control endpoint IN (DMA cannot be enabled for this endpoint and the EP1_DMA_ENABLE bit must be 0). constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> epDmaSt1{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> epDmaSt2{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> epDmaSt3{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> epDmaSt4{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> epDmaSt5{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> epDmaSt6{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> epDmaSt7{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> epDmaSt8{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> epDmaSt9{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> epDmaSt10{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> epDmaSt11{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> epDmaSt12{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> epDmaSt13{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> epDmaSt14{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> epDmaSt15{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> epDmaSt16{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> epDmaSt17{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> epDmaSt18{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> epDmaSt19{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> epDmaSt20{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> epDmaSt21{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> epDmaSt22{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> epDmaSt23{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> epDmaSt24{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> epDmaSt25{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> epDmaSt26{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> epDmaSt27{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> epDmaSt28{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> epDmaSt29{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> epDmaSt30{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> epDmaSt31{}; } namespace UsbEpdmaen{ ///<USB Endpoint DMA Enable using Addr = Register::Address<0x2008c288,0x00000000,0x00000000,unsigned>; ///Control endpoint OUT (DMA cannot be enabled for this endpoint and the EP0_DMA_ENABLE bit value must be 0). constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> epDmaEn0{}; ///Control endpoint IN (DMA cannot be enabled for this endpoint and the EP1_DMA_ENABLE bit must be 0). constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> epDmaEn1{}; ///Endpoint xx(2 <= xx <= 31) DMA enable control bit. 0 = No effect. 1 = Enable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,2),Register::ReadWriteAccess,unsigned> epDmaEn{}; } namespace UsbEpdmadis{ ///<USB Endpoint DMA Disable using Addr = Register::Address<0x2008c28c,0x00000000,0x00000000,unsigned>; ///Control endpoint OUT (DMA cannot be enabled for this endpoint and the EP0_DMA_DISABLE bit value must be 0). constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> epDmaDis0{}; ///Control endpoint IN (DMA cannot be enabled for this endpoint and the EP1_DMA_DISABLE bit value must be 0). constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> epDmaDis1{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> epDmaDis2{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> epDmaDis3{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> epDmaDis4{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> epDmaDis5{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> epDmaDis6{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> epDmaDis7{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> epDmaDis8{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> epDmaDis9{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> epDmaDis10{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> epDmaDis11{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> epDmaDis12{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> epDmaDis13{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> epDmaDis14{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> epDmaDis15{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> epDmaDis16{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> epDmaDis17{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> epDmaDis18{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> epDmaDis19{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> epDmaDis20{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> epDmaDis21{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> epDmaDis22{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> epDmaDis23{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> epDmaDis24{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> epDmaDis25{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> epDmaDis26{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> epDmaDis27{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> epDmaDis28{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> epDmaDis29{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> epDmaDis30{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> epDmaDis31{}; } namespace UsbDmaintst{ ///<USB DMA Interrupt Status using Addr = Register::Address<0x2008c290,0x00000000,0x00000000,unsigned>; ///End of Transfer Interrupt bit. enum class EotVal { allBitsInTheUsbe=0x00000000, ///<All bits in the USBEoTIntSt register are 0. atLeastOneBitIn=0x00000001, ///<At least one bit in the USBEoTIntSt is set. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,EotVal> eot{}; namespace EotValC{ constexpr Register::FieldValue<decltype(eot)::Type,EotVal::allBitsInTheUsbe> allBitsInTheUsbe{}; constexpr Register::FieldValue<decltype(eot)::Type,EotVal::atLeastOneBitIn> atLeastOneBitIn{}; } ///New DD Request Interrupt bit. enum class NddrVal { allBitsInTheUsbn=0x00000000, ///<All bits in the USBNDDRIntSt register are 0. atLeastOneBitIn=0x00000001, ///<At least one bit in the USBNDDRIntSt is set. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,NddrVal> nddr{}; namespace NddrValC{ constexpr Register::FieldValue<decltype(nddr)::Type,NddrVal::allBitsInTheUsbn> allBitsInTheUsbn{}; constexpr Register::FieldValue<decltype(nddr)::Type,NddrVal::atLeastOneBitIn> atLeastOneBitIn{}; } ///System Error Interrupt bit. enum class ErrVal { allBitsInTheUsbs=0x00000000, ///<All bits in the USBSysErrIntSt register are 0. atLeastOneBitIn=0x00000001, ///<At least one bit in the USBSysErrIntSt is set. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,ErrVal> err{}; namespace ErrValC{ constexpr Register::FieldValue<decltype(err)::Type,ErrVal::allBitsInTheUsbs> allBitsInTheUsbs{}; constexpr Register::FieldValue<decltype(err)::Type,ErrVal::atLeastOneBitIn> atLeastOneBitIn{}; } ///Reserved. The value read from a reserved bit is not defined. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,3),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbDmainten{ ///<USB DMA Interrupt Enable using Addr = Register::Address<0x2008c294,0x00000000,0x00000000,unsigned>; ///End of Transfer Interrupt enable bit. enum class EotVal { disabled=0x00000000, ///<Disabled. enabled=0x00000001, ///<Enabled. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,EotVal> eot{}; namespace EotValC{ constexpr Register::FieldValue<decltype(eot)::Type,EotVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(eot)::Type,EotVal::enabled> enabled{}; } ///New DD Request Interrupt enable bit. enum class NddrVal { disabled=0x00000000, ///<Disabled. enabled=0x00000001, ///<Enabled. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,NddrVal> nddr{}; namespace NddrValC{ constexpr Register::FieldValue<decltype(nddr)::Type,NddrVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(nddr)::Type,NddrVal::enabled> enabled{}; } ///System Error Interrupt enable bit. enum class ErrVal { disabled=0x00000000, ///<Disabled. enabled=0x00000001, ///<Enabled. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,ErrVal> err{}; namespace ErrValC{ constexpr Register::FieldValue<decltype(err)::Type,ErrVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(err)::Type,ErrVal::enabled> enabled{}; } ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,3),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbEotintst{ ///<USB End of Transfer Interrupt Status using Addr = Register::Address<0x2008c2a0,0x00000000,0x00000000,unsigned>; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> eptxintst0{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> eptxintst1{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> eptxintst2{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> eptxintst3{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> eptxintst4{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> eptxintst5{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> eptxintst6{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> eptxintst7{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> eptxintst8{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> eptxintst9{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> eptxintst10{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> eptxintst11{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> eptxintst12{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> eptxintst13{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> eptxintst14{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> eptxintst15{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> eptxintst16{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> eptxintst17{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> eptxintst18{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> eptxintst19{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> eptxintst20{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> eptxintst21{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> eptxintst22{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> eptxintst23{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> eptxintst24{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> eptxintst25{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> eptxintst26{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> eptxintst27{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> eptxintst28{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> eptxintst29{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> eptxintst30{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> eptxintst31{}; } namespace UsbEotintclr{ ///<USB End of Transfer Interrupt Clear using Addr = Register::Address<0x2008c2a4,0x00000000,0x00000000,unsigned>; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> eptxintclr0{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> eptxintclr1{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> eptxintclr2{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> eptxintclr3{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> eptxintclr4{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> eptxintclr5{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> eptxintclr6{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> eptxintclr7{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> eptxintclr8{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> eptxintclr9{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> eptxintclr10{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> eptxintclr11{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> eptxintclr12{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> eptxintclr13{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> eptxintclr14{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> eptxintclr15{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> eptxintclr16{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> eptxintclr17{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> eptxintclr18{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> eptxintclr19{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> eptxintclr20{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> eptxintclr21{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> eptxintclr22{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> eptxintclr23{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> eptxintclr24{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> eptxintclr25{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> eptxintclr26{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> eptxintclr27{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> eptxintclr28{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> eptxintclr29{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> eptxintclr30{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> eptxintclr31{}; } namespace UsbEotintset{ ///<USB End of Transfer Interrupt Set using Addr = Register::Address<0x2008c2a8,0x00000000,0x00000000,unsigned>; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> eptxintset0{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> eptxintset1{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> eptxintset2{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> eptxintset3{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> eptxintset4{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> eptxintset5{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> eptxintset6{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> eptxintset7{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> eptxintset8{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> eptxintset9{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> eptxintset10{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> eptxintset11{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> eptxintset12{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> eptxintset13{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> eptxintset14{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> eptxintset15{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> eptxintset16{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> eptxintset17{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> eptxintset18{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> eptxintset19{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> eptxintset20{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> eptxintset21{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> eptxintset22{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> eptxintset23{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> eptxintset24{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> eptxintset25{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> eptxintset26{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> eptxintset27{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> eptxintset28{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> eptxintset29{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> eptxintset30{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> eptxintset31{}; } namespace UsbNddrintst{ ///<USB New DD Request Interrupt Status using Addr = Register::Address<0x2008c2ac,0x00000000,0x00000000,unsigned>; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> epnddintst0{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> epnddintst1{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> epnddintst2{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> epnddintst3{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> epnddintst4{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> epnddintst5{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> epnddintst6{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> epnddintst7{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> epnddintst8{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> epnddintst9{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> epnddintst10{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> epnddintst11{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> epnddintst12{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> epnddintst13{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> epnddintst14{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> epnddintst15{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> epnddintst16{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> epnddintst17{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> epnddintst18{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> epnddintst19{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> epnddintst20{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> epnddintst21{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> epnddintst22{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> epnddintst23{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> epnddintst24{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> epnddintst25{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> epnddintst26{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> epnddintst27{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> epnddintst28{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> epnddintst29{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> epnddintst30{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> epnddintst31{}; } namespace UsbNddrintclr{ ///<USB New DD Request Interrupt Clear using Addr = Register::Address<0x2008c2b0,0x00000000,0x00000000,unsigned>; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> epnddintclr0{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> epnddintclr1{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> epnddintclr2{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> epnddintclr3{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> epnddintclr4{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> epnddintclr5{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> epnddintclr6{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> epnddintclr7{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> epnddintclr8{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> epnddintclr9{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> epnddintclr10{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> epnddintclr11{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> epnddintclr12{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> epnddintclr13{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> epnddintclr14{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> epnddintclr15{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> epnddintclr16{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> epnddintclr17{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> epnddintclr18{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> epnddintclr19{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> epnddintclr20{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> epnddintclr21{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> epnddintclr22{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> epnddintclr23{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> epnddintclr24{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> epnddintclr25{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> epnddintclr26{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> epnddintclr27{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> epnddintclr28{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> epnddintclr29{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> epnddintclr30{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> epnddintclr31{}; } namespace UsbNddrintset{ ///<USB New DD Request Interrupt Set using Addr = Register::Address<0x2008c2b4,0x00000000,0x00000000,unsigned>; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> epnddintset0{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> epnddintset1{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> epnddintset2{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> epnddintset3{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> epnddintset4{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> epnddintset5{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> epnddintset6{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> epnddintset7{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> epnddintset8{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> epnddintset9{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> epnddintset10{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> epnddintset11{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> epnddintset12{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> epnddintset13{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> epnddintset14{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> epnddintset15{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> epnddintset16{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> epnddintset17{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> epnddintset18{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> epnddintset19{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> epnddintset20{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> epnddintset21{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> epnddintset22{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> epnddintset23{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> epnddintset24{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> epnddintset25{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> epnddintset26{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> epnddintset27{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> epnddintset28{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> epnddintset29{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> epnddintset30{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> epnddintset31{}; } namespace UsbSyserrintst{ ///<USB System Error Interrupt Status using Addr = Register::Address<0x2008c2b8,0x00000000,0x00000000,unsigned>; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> eperrintst0{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> eperrintst1{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> eperrintst2{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> eperrintst3{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> eperrintst4{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> eperrintst5{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> eperrintst6{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> eperrintst7{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> eperrintst8{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> eperrintst9{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> eperrintst10{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> eperrintst11{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> eperrintst12{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> eperrintst13{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> eperrintst14{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> eperrintst15{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> eperrintst16{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> eperrintst17{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> eperrintst18{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> eperrintst19{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> eperrintst20{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> eperrintst21{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> eperrintst22{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> eperrintst23{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> eperrintst24{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> eperrintst25{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> eperrintst26{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> eperrintst27{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> eperrintst28{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> eperrintst29{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> eperrintst30{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> eperrintst31{}; } namespace UsbSyserrintclr{ ///<USB System Error Interrupt Clear using Addr = Register::Address<0x2008c2bc,0x00000000,0x00000000,unsigned>; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> eperrintclr0{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> eperrintclr1{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> eperrintclr2{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> eperrintclr3{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> eperrintclr4{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> eperrintclr5{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> eperrintclr6{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> eperrintclr7{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> eperrintclr8{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> eperrintclr9{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> eperrintclr10{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> eperrintclr11{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> eperrintclr12{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> eperrintclr13{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> eperrintclr14{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> eperrintclr15{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> eperrintclr16{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> eperrintclr17{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> eperrintclr18{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> eperrintclr19{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> eperrintclr20{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> eperrintclr21{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> eperrintclr22{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> eperrintclr23{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> eperrintclr24{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> eperrintclr25{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> eperrintclr26{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> eperrintclr27{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> eperrintclr28{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> eperrintclr29{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> eperrintclr30{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> eperrintclr31{}; } namespace UsbSyserrintset{ ///<USB System Error Interrupt Set using Addr = Register::Address<0x2008c2c0,0x00000000,0x00000000,unsigned>; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> eperrintset0{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> eperrintset1{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> eperrintset2{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> eperrintset3{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> eperrintset4{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> eperrintset5{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> eperrintset6{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> eperrintset7{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> eperrintset8{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> eperrintset9{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> eperrintset10{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> eperrintset11{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> eperrintset12{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> eperrintset13{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> eperrintset14{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> eperrintset15{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> eperrintset16{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> eperrintset17{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> eperrintset18{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> eperrintset19{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> eperrintset20{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> eperrintset21{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> eperrintset22{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> eperrintset23{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> eperrintset24{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> eperrintset25{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> eperrintset26{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> eperrintset27{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> eperrintset28{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> eperrintset29{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> eperrintset30{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> eperrintset31{}; } namespace UsbI2cRx{ ///<I2C Receive using Addr = Register::Address<0x2008c300,0x00000000,0x00000000,unsigned>; ///Receive data. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> rxData{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,8),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbI2cTx{ ///<I2C Transmit using Addr = Register::Address<0x2008c300,0x00000000,0x00000000,unsigned>; ///Transmit data. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> txdata{}; ///When 1, issue a START condition before transmitting this byte. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> start{}; ///When 1, issue a STOP condition after transmitting this byte. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> stop{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,10),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbI2cSts{ ///<I2C Status using Addr = Register::Address<0x2008c304,0x00000000,0x00000000,unsigned>; ///Transaction Done Interrupt. This flag is set if a transaction completes successfully. It is cleared by writing a one to bit 0 of the status register. It is unaffected by slave transactions. enum class TdiVal { transactionHasNot=0x00000000, ///<Transaction has not completed. transactionComplete=0x00000001, ///<Transaction completed. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,TdiVal> tdi{}; namespace TdiValC{ constexpr Register::FieldValue<decltype(tdi)::Type,TdiVal::transactionHasNot> transactionHasNot{}; constexpr Register::FieldValue<decltype(tdi)::Type,TdiVal::transactionComplete> transactionComplete{}; } ///Arbitration Failure Interrupt. When transmitting, if the SDA is low when SDAOUT is high, then this I2C has lost the arbitration to another device on the bus. The Arbitration Failure bit is set when this happens. It is cleared by writing a one to bit 1 of the status register. enum class AfiVal { noArbitrationFailu=0x00000000, ///<No arbitration failure on last transmission. arbitrationFailure=0x00000001, ///<Arbitration failure occurred on last transmission. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,AfiVal> afi{}; namespace AfiValC{ constexpr Register::FieldValue<decltype(afi)::Type,AfiVal::noArbitrationFailu> noArbitrationFailu{}; constexpr Register::FieldValue<decltype(afi)::Type,AfiVal::arbitrationFailure> arbitrationFailure{}; } ///No Acknowledge Interrupt. After every byte of data is sent, the transmitter expects an acknowledge from the receiver. This bit is set if the acknowledge is not received. It is cleared when a byte is written to the master TX FIFO. enum class NaiVal { lastTransmissionRe=0x00000000, ///<Last transmission received an acknowledge. lastTransmissionDi=0x00000001, ///<Last transmission did not receive an acknowledge. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,NaiVal> nai{}; namespace NaiValC{ constexpr Register::FieldValue<decltype(nai)::Type,NaiVal::lastTransmissionRe> lastTransmissionRe{}; constexpr Register::FieldValue<decltype(nai)::Type,NaiVal::lastTransmissionDi> lastTransmissionDi{}; } ///Master Data Request Interrupt. Once a transmission is started, the transmitter must have data to transmit as long as it isn't followed by a stop condition or it will hold SCL low until more data is available. The Master Data Request bit is set when the master transmitter is data-starved. If the master TX FIFO is empty and the last byte did not have a STOP condition flag, then SCL is held low until the CPU writes another byte to transmit. This bit is cleared when a byte is written to the master TX FIFO. enum class DrmiVal { masterTransmitterD=0x00000000, ///<Master transmitter does not need data. masterTransmitterN=0x00000001, ///<Master transmitter needs data. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,DrmiVal> drmi{}; namespace DrmiValC{ constexpr Register::FieldValue<decltype(drmi)::Type,DrmiVal::masterTransmitterD> masterTransmitterD{}; constexpr Register::FieldValue<decltype(drmi)::Type,DrmiVal::masterTransmitterN> masterTransmitterN{}; } ///Slave Data Request Interrupt. Once a transmission is started, the transmitter must have data to transmit as long as it isn't followed by a STOP condition or it will hold SCL low until more data is available. The Slave Data Request bit is set when the slave transmitter is data-starved. If the slave TX FIFO is empty and the last byte transmitted was acknowledged, then SCL is held low until the CPU writes another byte to transmit. This bit is cleared when a byte is written to the slave Tx FIFO. enum class DrsiVal { slaveTransmitterDo=0x00000000, ///<Slave transmitter does not need data. slaveTransmitterNe=0x00000001, ///<Slave transmitter needs data. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,DrsiVal> drsi{}; namespace DrsiValC{ constexpr Register::FieldValue<decltype(drsi)::Type,DrsiVal::slaveTransmitterDo> slaveTransmitterDo{}; constexpr Register::FieldValue<decltype(drsi)::Type,DrsiVal::slaveTransmitterNe> slaveTransmitterNe{}; } ///Indicates whether the bus is busy. This bit is set when a START condition has been seen. It is cleared when a STOP condition is seen.. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> active{}; ///The current value of the SCL signal. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> scl{}; ///The current value of the SDA signal. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> sda{}; ///Receive FIFO Full (RFF). This bit is set when the RX FIFO is full and cannot accept any more data. It is cleared when the RX FIFO is not full. If a byte arrives when the Receive FIFO is full, the SCL is held low until the CPU reads the RX FIFO and makes room for it. enum class RffVal { rxFifoIsNotFull=0x00000000, ///<RX FIFO is not full rxFifoIsFull=0x00000001, ///<RX FIFO is full }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,RffVal> rff{}; namespace RffValC{ constexpr Register::FieldValue<decltype(rff)::Type,RffVal::rxFifoIsNotFull> rxFifoIsNotFull{}; constexpr Register::FieldValue<decltype(rff)::Type,RffVal::rxFifoIsFull> rxFifoIsFull{}; } ///Receive FIFO Empty. RFE is set when the RX FIFO is empty and is cleared when the RX FIFO contains valid data. enum class RfeVal { rxFifoContainsDat=0x00000000, ///<RX FIFO contains data. rxFifoIsEmpty=0x00000001, ///<RX FIFO is empty }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,RfeVal> rfe{}; namespace RfeValC{ constexpr Register::FieldValue<decltype(rfe)::Type,RfeVal::rxFifoContainsDat> rxFifoContainsDat{}; constexpr Register::FieldValue<decltype(rfe)::Type,RfeVal::rxFifoIsEmpty> rxFifoIsEmpty{}; } ///Transmit FIFO Full. TFF is set when the TX FIFO is full and is cleared when the TX FIFO is not full. enum class TffVal { txFifoIsNotFull=0x00000000, ///<TX FIFO is not full. txFifoIsFull=0x00000001, ///<TX FIFO is full }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,TffVal> tff{}; namespace TffValC{ constexpr Register::FieldValue<decltype(tff)::Type,TffVal::txFifoIsNotFull> txFifoIsNotFull{}; constexpr Register::FieldValue<decltype(tff)::Type,TffVal::txFifoIsFull> txFifoIsFull{}; } ///Transmit FIFO Empty. TFE is set when the TX FIFO is empty and is cleared when the TX FIFO contains valid data. enum class TfeVal { txFifoContainsVal=0x00000000, ///<TX FIFO contains valid data. txFifoIsEmpty=0x00000001, ///<TX FIFO is empty }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,TfeVal> tfe{}; namespace TfeValC{ constexpr Register::FieldValue<decltype(tfe)::Type,TfeVal::txFifoContainsVal> txFifoContainsVal{}; constexpr Register::FieldValue<decltype(tfe)::Type,TfeVal::txFifoIsEmpty> txFifoIsEmpty{}; } ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,12),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbI2cCtl{ ///<I2C Control using Addr = Register::Address<0x2008c308,0x00000000,0x00000000,unsigned>; ///Transmit Done Interrupt Enable. This enables the TDI interrupt signalling that this I2C issued a STOP condition. enum class TdieVal { disableTheTdiInte=0x00000000, ///<Disable the TDI interrupt. enableTheTdiInter=0x00000001, ///<Enable the TDI interrupt. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,TdieVal> tdie{}; namespace TdieValC{ constexpr Register::FieldValue<decltype(tdie)::Type,TdieVal::disableTheTdiInte> disableTheTdiInte{}; constexpr Register::FieldValue<decltype(tdie)::Type,TdieVal::enableTheTdiInter> enableTheTdiInter{}; } ///Transmitter Arbitration Failure Interrupt Enable. This enables the AFI interrupt which is asserted during transmission when trying to set SDA high, but the bus is driven low by another device. enum class AfieVal { disableTheAfi=0x00000000, ///<Disable the AFI. enableTheAfi=0x00000001, ///<Enable the AFI. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,AfieVal> afie{}; namespace AfieValC{ constexpr Register::FieldValue<decltype(afie)::Type,AfieVal::disableTheAfi> disableTheAfi{}; constexpr Register::FieldValue<decltype(afie)::Type,AfieVal::enableTheAfi> enableTheAfi{}; } ///Transmitter No Acknowledge Interrupt Enable. This enables the NAI interrupt signalling that transmitted byte was not acknowledged. enum class NaieVal { disableTheNai=0x00000000, ///<Disable the NAI. enableTheNai=0x00000001, ///<Enable the NAI. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,NaieVal> naie{}; namespace NaieValC{ constexpr Register::FieldValue<decltype(naie)::Type,NaieVal::disableTheNai> disableTheNai{}; constexpr Register::FieldValue<decltype(naie)::Type,NaieVal::enableTheNai> enableTheNai{}; } ///Master Transmitter Data Request Interrupt Enable. This enables the DRMI interrupt which signals that the master transmitter has run out of data, has not issued a STOP, and is holding the SCL line low. enum class DrmieVal { disableTheDrmiInt=0x00000000, ///<Disable the DRMI interrupt. enableTheDrmiInte=0x00000001, ///<Enable the DRMI interrupt. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,DrmieVal> drmie{}; namespace DrmieValC{ constexpr Register::FieldValue<decltype(drmie)::Type,DrmieVal::disableTheDrmiInt> disableTheDrmiInt{}; constexpr Register::FieldValue<decltype(drmie)::Type,DrmieVal::enableTheDrmiInte> enableTheDrmiInte{}; } ///Slave Transmitter Data Request Interrupt Enable. This enables the DRSI interrupt which signals that the slave transmitter has run out of data and the last byte was acknowledged, so the SCL line is being held low. enum class DrsieVal { disableTheDrsiInt=0x00000000, ///<Disable the DRSI interrupt. enableTheDrsiInte=0x00000001, ///<Enable the DRSI interrupt. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,DrsieVal> drsie{}; namespace DrsieValC{ constexpr Register::FieldValue<decltype(drsie)::Type,DrsieVal::disableTheDrsiInt> disableTheDrsiInt{}; constexpr Register::FieldValue<decltype(drsie)::Type,DrsieVal::enableTheDrsiInte> enableTheDrsiInte{}; } ///Receive FIFO Full Interrupt Enable. This enables the Receive FIFO Full interrupt to indicate that the receive FIFO cannot accept any more data. enum class RefieVal { disableTheRffi=0x00000000, ///<Disable the RFFI. enableTheRffi=0x00000001, ///<Enable the RFFI. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,RefieVal> refie{}; namespace RefieValC{ constexpr Register::FieldValue<decltype(refie)::Type,RefieVal::disableTheRffi> disableTheRffi{}; constexpr Register::FieldValue<decltype(refie)::Type,RefieVal::enableTheRffi> enableTheRffi{}; } ///Receive Data Available Interrupt Enable. This enables the DAI interrupt to indicate that data is available in the receive FIFO (i.e. not empty). enum class RfdaieVal { disableTheDai=0x00000000, ///<Disable the DAI. enableTheDai=0x00000001, ///<Enable the DAI. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,RfdaieVal> rfdaie{}; namespace RfdaieValC{ constexpr Register::FieldValue<decltype(rfdaie)::Type,RfdaieVal::disableTheDai> disableTheDai{}; constexpr Register::FieldValue<decltype(rfdaie)::Type,RfdaieVal::enableTheDai> enableTheDai{}; } ///Transmit FIFO Not Full Interrupt Enable. This enables the Transmit FIFO Not Full interrupt to indicate that the more data can be written to the transmit FIFO. Note that this is not full. It is intended help the CPU to write to the I2C block only when there is room in the FIFO and do this without polling the status register. enum class TffieVal { disableTheTffi=0x00000000, ///<Disable the TFFI. enableTheTffi=0x00000001, ///<Enable the TFFI. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,TffieVal> tffie{}; namespace TffieValC{ constexpr Register::FieldValue<decltype(tffie)::Type,TffieVal::disableTheTffi> disableTheTffi{}; constexpr Register::FieldValue<decltype(tffie)::Type,TffieVal::enableTheTffi> enableTheTffi{}; } ///Soft reset. This is only needed in unusual circumstances. If a device issues a start condition without issuing a stop condition. A system timer may be used to reset the I2C if the bus remains busy longer than the time-out period. On a soft reset, the Tx and Rx FIFOs are flushed, I2C_STS register is cleared, and all internal state machines are reset to appear idle. The I2C_CLKHI, I2C_CLKLO and I2C_CTL (except Soft Reset Bit) are NOT modified by a soft reset. enum class SrstVal { seeTheText=0x00000000, ///<See the text. resetTheI2cToIdl=0x00000001, ///<Reset the I2C to idle state. Self clearing. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,SrstVal> srst{}; namespace SrstValC{ constexpr Register::FieldValue<decltype(srst)::Type,SrstVal::seeTheText> seeTheText{}; constexpr Register::FieldValue<decltype(srst)::Type,SrstVal::resetTheI2cToIdl> resetTheI2cToIdl{}; } ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,9),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbI2cClkhi{ ///<I2C Clock High using Addr = Register::Address<0x2008c30c,0x00000000,0x00000000,unsigned>; ///Clock divisor high. This value is the number of 48 MHz clocks the serial clock (SCL) will be high. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> cdhi{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,8),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbI2cClklo{ ///<I2C Clock Low using Addr = Register::Address<0x2008c310,0x00000000,0x00000000,unsigned>; ///Clock divisor low. This value is the number of 48 MHz clocks the serial clock (SCL) will be low. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> cdlo{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,8),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbClkctrl{ ///<OTG clock controller using Addr = Register::Address<0x2008cff4,0x00000000,0x00000000,unsigned>; ///Host clock enable enum class HostclkenVal { disableTheHostClo=0x00000000, ///<Disable the Host clock. enableTheHostCloc=0x00000001, ///<Enable the Host clock. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,HostclkenVal> hostClkEn{}; namespace HostclkenValC{ constexpr Register::FieldValue<decltype(hostClkEn)::Type,HostclkenVal::disableTheHostClo> disableTheHostClo{}; constexpr Register::FieldValue<decltype(hostClkEn)::Type,HostclkenVal::enableTheHostCloc> enableTheHostCloc{}; } ///Device clock enable enum class DevclkenVal { disableTheDeviceC=0x00000000, ///<Disable the Device clock. enableTheDeviceCl=0x00000001, ///<Enable the Device clock. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,DevclkenVal> devClkEn{}; namespace DevclkenValC{ constexpr Register::FieldValue<decltype(devClkEn)::Type,DevclkenVal::disableTheDeviceC> disableTheDeviceC{}; constexpr Register::FieldValue<decltype(devClkEn)::Type,DevclkenVal::enableTheDeviceCl> enableTheDeviceCl{}; } ///I2C clock enable enum class I2cclkenVal { disableTheI2cCloc=0x00000000, ///<Disable the I2C clock. enableTheI2cClock=0x00000001, ///<Enable the I2C clock. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,I2cclkenVal> i2cClkEn{}; namespace I2cclkenValC{ constexpr Register::FieldValue<decltype(i2cClkEn)::Type,I2cclkenVal::disableTheI2cCloc> disableTheI2cCloc{}; constexpr Register::FieldValue<decltype(i2cClkEn)::Type,I2cclkenVal::enableTheI2cClock> enableTheI2cClock{}; } ///OTG clock enable. In device-only applications, this bit enables access to the PORTSEL register. enum class OtgclkenVal { disableTheOtgCloc=0x00000000, ///<Disable the OTG clock. enableTheOtgClock=0x00000001, ///<Enable the OTG clock. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,OtgclkenVal> otgClkEn{}; namespace OtgclkenValC{ constexpr Register::FieldValue<decltype(otgClkEn)::Type,OtgclkenVal::disableTheOtgCloc> disableTheOtgCloc{}; constexpr Register::FieldValue<decltype(otgClkEn)::Type,OtgclkenVal::enableTheOtgClock> enableTheOtgClock{}; } ///AHB master clock enable enum class AhbclkenVal { disableTheAhbCloc=0x00000000, ///<Disable the AHB clock. enableTheAhbClock=0x00000001, ///<Enable the AHB clock. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,AhbclkenVal> ahbClkEn{}; namespace AhbclkenValC{ constexpr Register::FieldValue<decltype(ahbClkEn)::Type,AhbclkenVal::disableTheAhbCloc> disableTheAhbCloc{}; constexpr Register::FieldValue<decltype(ahbClkEn)::Type,AhbclkenVal::enableTheAhbClock> enableTheAhbClock{}; } ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,5),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbOtgclkst{ ///<OTG clock status using Addr = Register::Address<0x2008cff8,0x00000000,0x00000000,unsigned>; ///Host clock status. enum class HostclkonVal { hostClockIsNotAv=0x00000000, ///<Host clock is not available. hostClockIsAvaila=0x00000001, ///<Host clock is available. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,HostclkonVal> hostClkOn{}; namespace HostclkonValC{ constexpr Register::FieldValue<decltype(hostClkOn)::Type,HostclkonVal::hostClockIsNotAv> hostClockIsNotAv{}; constexpr Register::FieldValue<decltype(hostClkOn)::Type,HostclkonVal::hostClockIsAvaila> hostClockIsAvaila{}; } ///Device clock status. enum class DevclkonVal { deviceClockIsNot=0x00000000, ///<Device clock is not available. deviceClockIsAvai=0x00000001, ///<Device clock is available. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,DevclkonVal> devClkOn{}; namespace DevclkonValC{ constexpr Register::FieldValue<decltype(devClkOn)::Type,DevclkonVal::deviceClockIsNot> deviceClockIsNot{}; constexpr Register::FieldValue<decltype(devClkOn)::Type,DevclkonVal::deviceClockIsAvai> deviceClockIsAvai{}; } ///I2C clock status. enum class I2cclkonVal { i2cClockIsNotAva=0x00000000, ///<I2C clock is not available. i2cClockIsAvailab=0x00000001, ///<I2C clock is available. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,I2cclkonVal> i2cClkOn{}; namespace I2cclkonValC{ constexpr Register::FieldValue<decltype(i2cClkOn)::Type,I2cclkonVal::i2cClockIsNotAva> i2cClockIsNotAva{}; constexpr Register::FieldValue<decltype(i2cClkOn)::Type,I2cclkonVal::i2cClockIsAvailab> i2cClockIsAvailab{}; } ///OTG clock status. enum class OtgclkonVal { otgClockIsNotAva=0x00000000, ///<OTG clock is not available. otgClockIsAvailab=0x00000001, ///<OTG clock is available. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,OtgclkonVal> otgClkOn{}; namespace OtgclkonValC{ constexpr Register::FieldValue<decltype(otgClkOn)::Type,OtgclkonVal::otgClockIsNotAva> otgClockIsNotAva{}; constexpr Register::FieldValue<decltype(otgClkOn)::Type,OtgclkonVal::otgClockIsAvailab> otgClockIsAvailab{}; } ///AHB master clock status. enum class AhbclkonVal { ahbClockIsNotAva=0x00000000, ///<AHB clock is not available. ahbClockIsAvailab=0x00000001, ///<AHB clock is available. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,AhbclkonVal> ahbClkOn{}; namespace AhbclkonValC{ constexpr Register::FieldValue<decltype(ahbClkOn)::Type,AhbclkonVal::ahbClockIsNotAva> ahbClockIsNotAva{}; constexpr Register::FieldValue<decltype(ahbClkOn)::Type,AhbclkonVal::ahbClockIsAvailab> ahbClockIsAvailab{}; } ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,5),Register::ReadWriteAccess,unsigned> reserved{}; } }
244,938
75,362
// Copyright 2018 The Fuchsia 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 "src/developer/memory/monitor/monitor.h" #include <errno.h> #include <fcntl.h> #include <lib/async/cpp/task.h> #include <lib/async/cpp/time.h> #include <lib/async/default.h> #include <lib/inspect/cpp/inspect.h> #include <lib/syslog/cpp/macros.h> #include <lib/trace/event.h> #include <lib/vfs/cpp/internal/file.h> #include <lib/vfs/cpp/vmo_file.h> #include <lib/zx/time.h> #include <lib/zx/vmo.h> #include <string.h> #include <zircon/status.h> #include <zircon/types.h> #include <filesystem> #include <iostream> #include <iterator> #include <memory> #include <soc/aml-common/aml-ram.h> #include <trace-vthread/event_vthread.h> #include "fuchsia/mem/cpp/fidl.h" #include "src/developer/memory/metrics/bucket_match.h" #include "src/developer/memory/metrics/capture.h" #include "src/developer/memory/metrics/printer.h" #include "src/developer/memory/monitor/high_water.h" #include "src/developer/memory/monitor/memory_metrics_registry.cb.h" #include "src/lib/fsl/vmo/file.h" #include "src/lib/fsl/vmo/sized_vmo.h" #include "src/lib/fxl/command_line.h" #include "src/lib/fxl/strings/string_number_conversions.h" namespace monitor { using namespace memory; const char Monitor::kTraceName[] = "memory_monitor"; namespace { // Path to the configuration file for buckets. const std::string kBucketConfigPath = "/config/data/buckets.json"; const zx::duration kHighWaterPollFrequency = zx::sec(10); const uint64_t kHighWaterThreshold = 10 * 1024 * 1024; const zx::duration kMetricsPollFrequency = zx::min(5); const char kTraceNameHighPrecisionBandwidth[] = "memory_monitor:high_precision_bandwidth"; const char kTraceNameHighPrecisionBandwidthCamera[] = "memory_monitor:high_precision_bandwidth_camera"; constexpr uint64_t kMaxPendingBandwidthMeasurements = 4; constexpr uint64_t kMemCyclesToMeasure = 792000000 / 20; // 50 ms on sherlock constexpr uint64_t kMemCyclesToMeasureHighPrecision = 792000000 / 1000; // 1 ms // TODO(fxbug.dev/48254): Get default channel information through the FIDL API. struct RamChannel { const char* name; uint64_t mask; }; constexpr RamChannel kRamDefaultChannels[] = { {.name = "cpu", .mask = aml_ram::kDefaultChannelCpu}, {.name = "gpu", .mask = aml_ram::kDefaultChannelGpu}, {.name = "vdec", .mask = aml_ram::kDefaultChannelVDec}, {.name = "vpu", .mask = aml_ram::kDefaultChannelVpu}, }; constexpr RamChannel kRamCameraChannels[] = { {.name = "cpu", .mask = aml_ram::kDefaultChannelCpu}, {.name = "isp", .mask = aml_ram::kPortIdMipiIsp}, {.name = "gdc", .mask = aml_ram::kPortIdGDC}, {.name = "ge2d", .mask = aml_ram::kPortIdGe2D}, }; uint64_t CounterToBandwidth(uint64_t counter, uint64_t frequency, uint64_t cycles) { return counter * frequency / cycles; } zx_ticks_t TimestampToTicks(zx_time_t timestamp) { __uint128_t temp = static_cast<__uint128_t>(timestamp) * zx_ticks_per_second() / ZX_SEC(1); return static_cast<zx_ticks_t>(temp); } fuchsia::hardware::ram::metrics::BandwidthMeasurementConfig BuildConfig( uint64_t cycles_to_measure, bool use_camera_channels = false) { fuchsia::hardware::ram::metrics::BandwidthMeasurementConfig config = {}; config.cycles_to_measure = cycles_to_measure; size_t num_channels = std::size(kRamDefaultChannels); const auto* channels = kRamDefaultChannels; if (use_camera_channels) { num_channels = std::size(kRamCameraChannels); channels = kRamCameraChannels; } for (size_t i = 0; i < num_channels; i++) { config.channels[i] = channels[i].mask; } return config; } uint64_t TotalReadWriteCycles(const fuchsia::hardware::ram::metrics::BandwidthInfo& info) { uint64_t total_readwrite_cycles = 0; for (auto& channel : info.channels) { total_readwrite_cycles += channel.readwrite_cycles; } return total_readwrite_cycles; } std::vector<memory::BucketMatch> CreateBucketMatchesFromConfigData() { if (!std::filesystem::exists(kBucketConfigPath)) { FX_LOGS(WARNING) << "Bucket configuration file not found; no buckets will be available."; return {}; } std::string configuration_str; FX_CHECK(files::ReadFileToString(kBucketConfigPath, &configuration_str)); auto bucket_matches = memory::BucketMatch::ReadBucketMatchesFromConfig(configuration_str); FX_CHECK(bucket_matches.has_value()) << "Unable to read configuration: " << configuration_str; return std::move(*bucket_matches); } } // namespace Monitor::Monitor(std::unique_ptr<sys::ComponentContext> context, const fxl::CommandLine& command_line, async_dispatcher_t* dispatcher, bool send_metrics, bool watch_memory_pressure, bool send_critical_pressure_crash_reports) : prealloc_size_(0), logging_(command_line.HasOption("log")), tracing_(false), delay_(zx::sec(1)), dispatcher_(dispatcher), component_context_(std::move(context)), inspector_(component_context_.get()), logger_( dispatcher_, [this](Capture* c) { return GetCapture(c); }, [this](const Capture& c, Digest* d) { GetDigest(c, d); }), level_(Level::kNumLevels) { auto bucket_matches = CreateBucketMatchesFromConfigData(); digester_ = std::make_unique<Digester>(Digester(bucket_matches)); high_water_ = std::make_unique<HighWater>( "/cache", kHighWaterPollFrequency, kHighWaterThreshold, dispatcher, [this](Capture* c, CaptureLevel l) { return Capture::GetCapture(c, capture_state_, l); }, [this](const Capture& c, Digest* d) { digester_->Digest(c, d); }); auto s = Capture::GetCaptureState(&capture_state_); if (s != ZX_OK) { FX_LOGS(ERROR) << "Error getting capture state: " << zx_status_get_string(s); exit(EXIT_FAILURE); } if (send_metrics) CreateMetrics(bucket_matches); // Expose lazy values under the root, populated from the Inspect method. inspector_.root().CreateLazyValues( "memory_measurements", [this, bucket_matches = std::move(bucket_matches)] { return fit::make_result_promise(fit::ok(Inspect(bucket_matches))); }, &inspector_); component_context_->outgoing()->AddPublicService(bindings_.GetHandler(this)); if (command_line.HasOption("help")) { PrintHelp(); exit(EXIT_SUCCESS); } std::string delay_as_string; if (command_line.GetOptionValue("delay", &delay_as_string)) { unsigned delay_as_int; if (!fxl::StringToNumberWithError<unsigned>(delay_as_string, &delay_as_int)) { FX_LOGS(ERROR) << "Invalid value for delay: " << delay_as_string; exit(-1); } delay_ = zx::msec(delay_as_int); } std::string prealloc_as_string; if (command_line.GetOptionValue("prealloc", &prealloc_as_string)) { FX_LOGS(INFO) << "prealloc_string: " << prealloc_as_string; if (!fxl::StringToNumberWithError<uint64_t>(prealloc_as_string, &prealloc_size_)) { FX_LOGS(ERROR) << "Invalid value for prealloc: " << prealloc_as_string; exit(-1); } prealloc_size_ *= (1024 * 1024); auto status = zx::vmo::create(prealloc_size_, 0, &prealloc_vmo_); if (status != ZX_OK) { FX_LOGS(ERROR) << "zx::vmo::create() returns " << zx_status_get_string(status); exit(-1); } prealloc_vmo_.get_size(&prealloc_size_); uintptr_t prealloc_addr = 0; status = zx::vmar::root_self()->map(ZX_VM_PERM_READ, 0, prealloc_vmo_, 0, prealloc_size_, &prealloc_addr); if (status != ZX_OK) { FX_LOGS(ERROR) << "zx::vmar::map() returns " << zx_status_get_string(status); exit(-1); } status = prealloc_vmo_.op_range(ZX_VMO_OP_COMMIT, 0, prealloc_size_, NULL, 0); if (status != ZX_OK) { FX_LOGS(ERROR) << "zx::vmo::op_range() returns " << zx_status_get_string(status); exit(-1); } } trace_observer_.Start(dispatcher_, [this] { UpdateState(); }); if (logging_) { Capture capture; auto s = Capture::GetCapture(&capture, capture_state_, KMEM); if (s != ZX_OK) { FX_LOGS(ERROR) << "Error getting capture: " << zx_status_get_string(s); exit(EXIT_FAILURE); } const auto& kmem = capture.kmem(); FX_LOGS(INFO) << "Total: " << kmem.total_bytes << " Wired: " << kmem.wired_bytes << " Total Heap: " << kmem.total_heap_bytes; } pressure_notifier_ = std::make_unique<PressureNotifier>( watch_memory_pressure, send_critical_pressure_crash_reports, component_context_.get(), dispatcher, [this](Level l) { PressureLevelChanged(l); }); memory_debugger_ = std::make_unique<MemoryDebugger>(component_context_.get(), pressure_notifier_.get()); SampleAndPost(); } Monitor::~Monitor() {} void Monitor::SetRamDevice(fuchsia::hardware::ram::metrics::DevicePtr ptr) { ram_device_ = std::move(ptr); if (ram_device_.is_bound()) PeriodicMeasureBandwidth(); } void Monitor::CreateMetrics(const std::vector<memory::BucketMatch>& bucket_matches) { // Connect to the cobalt fidl service provided by the environment. fuchsia::cobalt::LoggerFactorySyncPtr factory; component_context_->svc()->Connect(factory.NewRequest()); if (!factory) { FX_LOGS(ERROR) << "Unable to get cobalt.LoggerFactory."; return; } // Create a Cobalt Logger. The ID name is the one we specified in the // Cobalt metrics registry. fuchsia::cobalt::Status status = fuchsia::cobalt::Status::INTERNAL_ERROR; factory->CreateLoggerFromProjectId(cobalt_registry::kProjectId, cobalt_logger_.NewRequest(), &status); if (status != fuchsia::cobalt::Status::OK) { FX_LOGS(ERROR) << "Unable to get cobalt.Logger from factory."; return; } metrics_ = std::make_unique<Metrics>( bucket_matches, kMetricsPollFrequency, dispatcher_, &inspector_, cobalt_logger_.get(), [this](Capture* c) { return GetCapture(c); }, [this](const Capture& c, Digest* d) { GetDigest(c, d); }); } void Monitor::Watch(fidl::InterfaceHandle<fuchsia::memory::Watcher> watcher) { fuchsia::memory::WatcherPtr watcher_proxy = watcher.Bind(); fuchsia::memory::Watcher* proxy_raw_ptr = watcher_proxy.get(); watcher_proxy.set_error_handler( [this, proxy_raw_ptr](zx_status_t status) { ReleaseWatcher(proxy_raw_ptr); }); watchers_.push_back(std::move(watcher_proxy)); SampleAndPost(); } void Monitor::ReleaseWatcher(fuchsia::memory::Watcher* watcher) { auto predicate = [watcher](const auto& target) { return target.get() == watcher; }; watchers_.erase(std::remove_if(watchers_.begin(), watchers_.end(), predicate)); } void Monitor::NotifyWatchers(const zx_info_kmem_stats_t& kmem_stats) { fuchsia::memory::Stats stats{ .total_bytes = kmem_stats.total_bytes, .free_bytes = kmem_stats.free_bytes, .wired_bytes = kmem_stats.wired_bytes, .total_heap_bytes = kmem_stats.total_heap_bytes, .free_heap_bytes = kmem_stats.free_heap_bytes, .vmo_bytes = kmem_stats.vmo_bytes, .mmu_overhead_bytes = kmem_stats.mmu_overhead_bytes, .ipc_bytes = kmem_stats.ipc_bytes, .other_bytes = kmem_stats.other_bytes, }; for (auto& watcher : watchers_) { watcher->OnChange(stats); } } void Monitor::PrintHelp() { std::cout << "memory_monitor [options]" << std::endl; std::cout << "Options:" << std::endl; std::cout << " --log" << std::endl; std::cout << " --prealloc=kbytes" << std::endl; std::cout << " --delay=msecs" << std::endl; } inspect::Inspector Monitor::Inspect(const std::vector<memory::BucketMatch>& bucket_matches) { inspect::Inspector inspector(inspect::InspectSettings{.maximum_size = 1024 * 1024}); auto& root = inspector.GetRoot(); Capture capture; Capture::GetCapture(&capture, capture_state_, VMO); Summary summary(capture, Summary::kNameMatches); std::ostringstream summary_stream; Printer summary_printer(summary_stream); summary_printer.PrintSummary(summary, VMO, SORTED); auto current_string = summary_stream.str(); auto high_water_string = high_water_->GetHighWater(); auto previous_high_water_string = high_water_->GetPreviousHighWater(); if (!current_string.empty()) { root.CreateString("current", current_string, &inspector); } if (!high_water_string.empty()) { root.CreateString("high_water", high_water_string, &inspector); } if (!previous_high_water_string.empty()) { root.CreateString("high_water_previous_boot", previous_high_water_string, &inspector); } // Expose raw values for downstream computation. auto values = root.CreateChild("values"); values.CreateUint("free_bytes", capture.kmem().free_bytes, &inspector); values.CreateUint("free_heap_bytes", capture.kmem().free_heap_bytes, &inspector); values.CreateUint("ipc_bytes", capture.kmem().ipc_bytes, &inspector); values.CreateUint("mmu_overhead_bytes", capture.kmem().mmu_overhead_bytes, &inspector); values.CreateUint("other_bytes", capture.kmem().other_bytes, &inspector); values.CreateUint("total_bytes", capture.kmem().total_bytes, &inspector); values.CreateUint("total_heap_bytes", capture.kmem().total_heap_bytes, &inspector); values.CreateUint("vmo_bytes", capture.kmem().vmo_bytes, &inspector); values.CreateUint("wired_bytes", capture.kmem().wired_bytes, &inspector); inspector.emplace(std::move(values)); Digest digest; digester_->Digest(capture, &digest); std::ostringstream digest_stream; Printer digest_printer(digest_stream); digest_printer.PrintDigest(digest); auto current_digest_string = digest_stream.str(); auto high_water_digest_string = high_water_->GetHighWaterDigest(); auto previous_high_water_digest_string = high_water_->GetPreviousHighWaterDigest(); if (!current_digest_string.empty()) { root.CreateString("current_digest", current_digest_string, &inspector); } if (!high_water_digest_string.empty()) { root.CreateString("high_water_digest", high_water_digest_string, &inspector); } if (!previous_high_water_digest_string.empty()) { root.CreateString("high_water_digest_previous_boot", previous_high_water_digest_string, &inspector); } return inspector; } void Monitor::SampleAndPost() { if (logging_ || tracing_ || watchers_.size() > 0) { Capture capture; auto s = Capture::GetCapture(&capture, capture_state_, KMEM); if (s != ZX_OK) { FX_LOGS(ERROR) << "Error getting capture: " << zx_status_get_string(s); return; } const auto& kmem = capture.kmem(); if (logging_) { FX_LOGS(INFO) << "Free: " << kmem.free_bytes << " Free Heap: " << kmem.free_heap_bytes << " VMO: " << kmem.vmo_bytes << " MMU: " << kmem.mmu_overhead_bytes << " IPC: " << kmem.ipc_bytes; } if (tracing_) { TRACE_COUNTER(kTraceName, "allocated", 0, "vmo", kmem.vmo_bytes, "mmu_overhead", kmem.mmu_overhead_bytes, "ipc", kmem.ipc_bytes); TRACE_COUNTER(kTraceName, "free", 0, "free", kmem.free_bytes, "free_heap", kmem.free_heap_bytes); } NotifyWatchers(kmem); async::PostDelayedTask( dispatcher_, [this] { SampleAndPost(); }, delay_); } } void Monitor::MeasureBandwidthAndPost() { // Bandwidth measurements are cheap but they take some time to // perform as they run over a number of memory cycles. In order to // support a relatively small cycle count for measurements, we keep // multiple requests in-flight. This gives us results with high // granularity and relatively good coverage. while (tracing_ && pending_bandwidth_measurements_ < kMaxPendingBandwidthMeasurements) { uint64_t cycles_to_measure = kMemCyclesToMeasure; bool trace_high_precision = trace_is_category_enabled(kTraceNameHighPrecisionBandwidth); bool trace_high_precision_camera = trace_is_category_enabled(kTraceNameHighPrecisionBandwidthCamera); if (trace_high_precision && trace_high_precision_camera) { FX_LOGS(ERROR) << kTraceNameHighPrecisionBandwidth << " and " << kTraceNameHighPrecisionBandwidthCamera << " are mutually exclusive categories."; } if (trace_high_precision || trace_high_precision_camera) { cycles_to_measure = kMemCyclesToMeasureHighPrecision; } ++pending_bandwidth_measurements_; ram_device_->MeasureBandwidth( BuildConfig(cycles_to_measure, trace_high_precision_camera), [this, cycles_to_measure, trace_high_precision_camera]( fuchsia::hardware::ram::metrics::Device_MeasureBandwidth_Result result) { --pending_bandwidth_measurements_; if (result.is_err()) { FX_LOGS(ERROR) << "Bad bandwidth measurement result: " << result.err(); } else { const auto& info = result.response().info; uint64_t total_readwrite_cycles = TotalReadWriteCycles(info); uint64_t other_readwrite_cycles = (info.total.readwrite_cycles > total_readwrite_cycles) ? info.total.readwrite_cycles - total_readwrite_cycles : 0; static_assert(std::size(kRamDefaultChannels) == std::size(kRamCameraChannels)); const auto* channels = trace_high_precision_camera ? kRamCameraChannels : kRamDefaultChannels; TRACE_VTHREAD_COUNTER( kTraceName, "bandwidth_usage", "membw" /*vthread_literal*/, 1 /*vthread_id*/, 0 /*counter_id*/, TimestampToTicks(info.timestamp), channels[0].name, CounterToBandwidth(info.channels[0].readwrite_cycles, info.frequency, cycles_to_measure) * info.bytes_per_cycle, channels[1].name, CounterToBandwidth(info.channels[1].readwrite_cycles, info.frequency, cycles_to_measure) * info.bytes_per_cycle, channels[2].name, CounterToBandwidth(info.channels[2].readwrite_cycles, info.frequency, cycles_to_measure) * info.bytes_per_cycle, channels[3].name, CounterToBandwidth(info.channels[3].readwrite_cycles, info.frequency, cycles_to_measure) * info.bytes_per_cycle, "other", CounterToBandwidth(other_readwrite_cycles, info.frequency, cycles_to_measure) * info.bytes_per_cycle); TRACE_VTHREAD_COUNTER(kTraceName, "bandwidth_free", "membw" /*vthread_literal*/, 1 /*vthread_id*/, 0 /*counter_id*/, TimestampToTicks(info.timestamp), "value", CounterToBandwidth(cycles_to_measure - total_readwrite_cycles - other_readwrite_cycles, info.frequency, cycles_to_measure) * info.bytes_per_cycle); } async::PostTask(dispatcher_, [this] { MeasureBandwidthAndPost(); }); }); } } void Monitor::PeriodicMeasureBandwidth() { std::chrono::seconds seconds_to_sleep = std::chrono::seconds(1); async::PostDelayedTask( dispatcher_, [this]() { PeriodicMeasureBandwidth(); }, zx::sec(seconds_to_sleep.count())); // Will not do measurement when tracing if (tracing_) return; uint64_t cycles_to_measure = kMemCyclesToMeasure; ram_device_->MeasureBandwidth( BuildConfig(cycles_to_measure), [this, cycles_to_measure](fuchsia::hardware::ram::metrics::Device_MeasureBandwidth_Result result) { if (result.is_err()) { FX_LOGS(ERROR) << "Bad bandwidth measurement result: " << result.err(); } else { const auto& info = result.response().info; uint64_t total_readwrite_cycles = TotalReadWriteCycles(info); total_readwrite_cycles = std::max(total_readwrite_cycles, info.total.readwrite_cycles); uint64_t memory_bandwidth_reading = CounterToBandwidth(total_readwrite_cycles, info.frequency, cycles_to_measure) * info.bytes_per_cycle; if (metrics_) metrics_->NextMemoryBandwidthReading(memory_bandwidth_reading, info.timestamp); } }); } void Monitor::UpdateState() { if (trace_state() == TRACE_STARTED) { if (trace_is_category_enabled(kTraceName)) { FX_LOGS(INFO) << "Tracing started"; if (!tracing_) { Capture capture; auto s = Capture::GetCapture(&capture, capture_state_, KMEM); if (s != ZX_OK) { FX_LOGS(ERROR) << "Error getting capture: " << zx_status_get_string(s); return; } const auto& kmem = capture.kmem(); TRACE_COUNTER(kTraceName, "fixed", 0, "total", kmem.total_bytes, "wired", kmem.wired_bytes, "total_heap", kmem.total_heap_bytes); tracing_ = true; if (!logging_) { SampleAndPost(); } if (ram_device_.is_bound()) { MeasureBandwidthAndPost(); } } } } else { if (tracing_) { FX_LOGS(INFO) << "Tracing stopped"; tracing_ = false; } } } zx_status_t Monitor::GetCapture(memory::Capture* capture) { return Capture::GetCapture(capture, capture_state_, VMO); } void Monitor::GetDigest(const memory::Capture& capture, memory::Digest* digest) { digester_->Digest(capture, digest); } void Monitor::PressureLevelChanged(Level level) { if (level == level_) { return; } FX_LOGS(INFO) << "Memory pressure level changed from " << kLevelNames[level_] << " to " << kLevelNames[level]; level_ = level; logger_.SetPressureLevel(level_); } } // namespace monitor
21,943
7,578
#include "command.class.h" #include "facebookApi.class.h" #include "../include/common.h" using namespace std; Command::Command(){ // Imposto di defaul che l'id dell'utente che ha in uso la sessione è 0 nUserId = 0; // Creo il vettore con la lista di comandi ammessi this->aCommandList.push_back("/start"); this->aCommandList.push_back("/login"); this->aCommandList.push_back("/help"); // Associo ad un comando la sua guida this->oApiFB = new FacebookApi(); this->stRisposte.start = "Welcome in SocialNetworkBot. Use /help to see what command you can use."; this->stRisposte.login = "/login <social-network-name>\nLogin into your social network using this command followed by SocialNetwork name (ex: facebook,twitter...)"; this->stRisposte.facebookOAuthUrl = "Click on the following link to authenticate this app in Facebook "+this->oApiFB->getOAuthUrl(this->nUserId); this->stRisposte.unknownCommand = "This is an unknown command, please read the manual using /help command"; } // Cosa fa : Estrapola il messaggio associato ad una determinata chiave, per poi essere usato // nei metodi che utilizzano questa classe (es: quello per inviare i messaggi all'utente) // Ritorna : string Command::getMessage(string sKey){ if(sKey == "start") return this->stRisposte.start; else if(sKey == "login") return this->stRisposte.login; else if(sKey == "facebookOAuthUrl") return this->stRisposte.facebookOAuthUrl; else if(sKey == "unknownCommand") return this->stRisposte.unknownCommand; else return this->stRisposte.unknownCommand; } // Cosa fa : Controlla se il comando è valido (se è presente nel vettore con la lista dei comandi) // sComando : stringa, comando, es: /start oppure /login // Ritorna : bRet -> true se il comando è ammesso, altrimenti false bool Command::isAllowedCommand(string sComando){ bool bRet = false; // Cosa fa : Verifica se un elemento stringa è presente in un vettore di stringhe // aVector : vettore di stringhe, vettore nel quale cercare l'elemento // sElement : stringa, elemento da cercare nel vettore // Ritorna : bRet -> logico, true se l'elemento è presente nel vettore, altrimenti false if(isInStringVector(this->aCommandList, sComando)){ bRet = true; } return bRet; } // Cosa fa : Imposta l'id dell'utente che ha in uso la "sessione" void Command::setUserId(int nUserId){ this->nUserId = nUserId; }
2,409
857
/* ============================================================================== PhaseVocodeur.cpp Created: 9 Dec 2020 9:19:32pm Author: Julian Vanasse By `push`ing into this class, the input is distributed among overlapping buffers, this permits a frequency-domain processing and reconstruction. Sound goes in via `push(float)` Sound comes out via `read_sum()` You can specify your own processing by overwriting the (?) method. ============================================================================== */ #include "PhaseVocodeur.h" /* ============================================================================== Constructors ============================================================================== */ PhaseVocodeur::PhaseVocodeur() { init(); } PhaseVocodeur::PhaseVocodeur(int frame_size, int hop_size) { this->frame_size = frame_size; this->hop_size = hop_size; this->ola_size = frame_size; this->n_fft = frame_size; this->num_bins = (frame_size / 2) + 1; init(); } PhaseVocodeur::PhaseVocodeur(int frame_size, int hop_size, int n_fft) { this->frame_size = frame_size; this->hop_size = hop_size; this->ola_size = n_fft; this->n_fft = n_fft; this->num_bins = (n_fft / 2) + 1; init(); } PhaseVocodeur::PhaseVocodeur(int frame_size, int hop_size, int ola_size, int n_fft) { this->frame_size = frame_size; this->hop_size = hop_size; this->ola_size = ola_size; this->n_fft = n_fft; this->num_bins = (n_fft / 2) + 1; init(); } /* ============================================================================== Methods for initialization ============================================================================== */ void PhaseVocodeur::init() { /* Call all init subroutines */ init_ola(); init_window(); init_fft(); } void PhaseVocodeur::init_ola() { /* Initialize Overlap-Add (OLA) containers and rw positions */ // assign number of frames based on overlap num_ola_frames = ceil(static_cast<float>(ola_size) / static_cast<float>(hop_size)); // allocate memory ola_in = juce::AudioBuffer<float> (num_ola_frames, ola_size); ola_out = juce::AudioBuffer<float> (num_ola_frames, ola_size); // clear ola_in.clear(); ola_out.clear(); // initialize rw positions int pos = 0; rw.clear(); for (int i = 0; i < num_ola_frames; i++) { rw.push_back(pos); pos += (hop_size % ola_size); } } void PhaseVocodeur::init_window() { /* Initialize Hann window buffer. */ // Hann window is computed using the 'periodic' method. // allocate memory and clear window = juce::AudioBuffer<float>(1, frame_size); window.clear(); // fill using Hann function auto w = window.getWritePointer(0); float N = static_cast<float>(frame_size); for (int n = 0; n < frame_size; n++) { float fn = static_cast<float>(n); w[n] = pow(sin(M_PI * fn / N), 2.0f); } } void PhaseVocodeur::init_fft() { /* Initialize spectral containers and routines */ // allocate space for input and output fft_in = new kiss_fft_cpx[n_fft]; fft_out = new kiss_fft_cpx[n_fft]; // initialize data storage // Set the memory of (`fft_in`) to 0, specifying in bytes. memset(fft_in, 0, n_fft * sizeof(kiss_fft_cpx)); memset(fft_out, 0, n_fft * sizeof(kiss_fft_cpx)); // initialize plans fft_forward = kiss_fft_alloc(n_fft, 0, 0, 0); fft_inverse = kiss_fft_alloc(n_fft, 1, 0, 0); } /* ============================================================================== Destructor. ============================================================================== */ PhaseVocodeur::~PhaseVocodeur() { /* free spectral resources */ kiss_fft_free(fft_forward); kiss_fft_free(fft_inverse); delete[] fft_in; delete[] fft_out; } /* ============================================================================== Writing and reading. ============================================================================== */ void PhaseVocodeur::push(float input_sample) { // Takes input sample and writes it into all the write buffers. auto ola_in_w = ola_in.getArrayOfWritePointers(); for (int b = 0; b < num_ola_frames; b++) { ola_in_w[b][rw[b]] = input_sample; // IF rw[b] is at the end of a frame THEN process. if (rw[b] == ola_size-1) { spectral_routine(b); } } } float PhaseVocodeur::read_sum() { /* sum to output */ float s = 0.0f; auto r = ola_out.getArrayOfReadPointers(); for (int b = 0; b < num_ola_frames; b++) { s += r[b][rw[b]]; } return s; } void PhaseVocodeur::advance() { /* advances rw positions */ for (int k = 0; k < rw.size(); k++) { rw[k] = (rw[k] + 1) % ola_size; } } /* ============================================================================== Spectral processing. ============================================================================== */ // Shell for spectral processing: transfers to and from spectral domain. void PhaseVocodeur::spectral_routine(int b) { // pointers auto ola_out_w = ola_out.getWritePointer(b); auto ola_out_r = ola_out.getReadPointer(b); // copy from ola_in ola_out.copyFrom(b, 0, ola_in, b, 0, frame_size); // apply window apply_window(ola_out_r, ola_out_w); // copy into spectral buffers clear_cpx(); copy_to_cpx(ola_out_r, fft_in, frame_size); // transform kiss_fft(fft_forward, fft_in, fft_out); /* DO SOMETHING */ spectral_processing(); /* ------------ */ /* BACK TO TIME-DOMAIN */ kiss_fft(fft_inverse, fft_out, fft_in); // copy into ola_out copy_to_bfr(ola_out_w, fft_in, n_fft); } // Processing in the frequency domain. void PhaseVocodeur::spectral_processing() { // bins: DC, 1, 2, ..., Nyquist int num_bins = (n_fft / 2) + 1; // transform to polar float magnitude[num_bins]; float phase[num_bins]; car2pol(fft_out, magnitude, phase, num_bins); /* DO SOMETHING */ /* filter example */ for (int k = 0; k < num_bins; k++) { magnitude[k] *= exp(-(float)(k+1) / 15.0f); } /* return to cartesian */ pol2car(fft_out, magnitude, phase, num_bins); // std::ofstream out; // out.open("post_fft.csv", std::ios::app); // for (int n = 0; n < n_fft; n++) // { // std::string s = "+"; // if (fft_out[n].i < 0) // s = ""; // out << fft_out[n].r << s << fft_out[n].i << "i"; // if (n == n_fft - 1) // out << "\n"; // else // out << ", "; // } } void PhaseVocodeur::apply_window(const float *r, float *w) { /* apply window to a buffer */ auto win = window.getReadPointer(0); for (int n = 0; n < frame_size; n++) { w[n] = r[n] * win[n]; } } /* ============================================================================== Spectral utility. ============================================================================== */ /* coordinate conversion */ void PhaseVocodeur::car2pol(kiss_fft_cpx *cpx_out, float *r, float *p, int len) { for (int k = 0; k < len; k++) { r[k] = mag(cpx_out[k].r, cpx_out[k].i); p[k] = ang(cpx_out[k].r, cpx_out[k].i); } } void PhaseVocodeur::pol2car(kiss_fft_cpx *cpx_out, float *r, float *p, int len) { for (int k = 0; k < len; k++) { cpx_out[k].r = cos(p[k])*r[k]*2.0f; cpx_out[k].i = sin(p[k])*r[k]*2.0f; } // negative frequencies int m = num_bins-2; for (int k = num_bins; k < n_fft; k++) { cpx_out[k].r = cpx_out[m].r; cpx_out[k].i = -cpx_out[m].i; m--; } } /* ============================================================================== Copying/Clearing Buffers. ============================================================================== */ void PhaseVocodeur::clear_cpx() { /* clear complex kiss_fft buffers */ for (int n = 0; n < n_fft; n++) { fft_in[n].r = 0.0f; fft_in[n].i = 0.0f; fft_out[n].r = 0.0f; fft_out[n].i = 0.0f; } } void PhaseVocodeur::copy_to_cpx(float *arr, kiss_fft_cpx *cpx_in, int len) { const float *r = const_cast<float *>(arr); copy_to_cpx(r, cpx_in, len); } void PhaseVocodeur::copy_to_cpx(const float *r, kiss_fft_cpx *cpx_in, int len) { /* copy into real part of fft_in */ for (int n = 0; n < len; n++) { cpx_in[n].r = r[n]; } } void PhaseVocodeur::copy_to_bfr(float *w, kiss_fft_cpx *cpx_in, int len) { /* copy real cpx_in to buffer and scale */ float fN = static_cast<float>(n_fft); for (int n = 0; n < len; n++) { w[n] = cpx_in[n].r / fN; } } /* ============================================================================== Class utility. ============================================================================== */ void PhaseVocodeur::print() { printf("Phase Vocodeur:\n"); // print parameters printf("\tframe_size:\n"); printf("\t\t%d\n", frame_size); printf("\thop_size:\n"); printf("\t\t%d\n", hop_size); printf("\tn_fft:\n"); printf("\t\t%d\n", n_fft); // print ola container dimensions printf("\tola_in:\n"); printf("\t\tsize = [%d, %d]\n", ola_in.getNumChannels(), ola_in.getNumSamples()); printf("\tola_out:\n"); printf("\t\tsize = [%d, %d]\n", ola_out.getNumChannels(), ola_out.getNumSamples()); printf("\trw:\n"); // print rw positions printf("\t\t"); print_int_vector(rw); printf("\n"); // print window dimensions printf("\twindow:\n"); printf("\t\tsize = [%d, %d]\n", window.getNumChannels(), window.getNumSamples()); }
10,313
3,790
// By --------- Alauddin ----------- #include<stdio.h> #include<iostream> #include<time.h> #include<BigInt_Al.h> /*===========================MAIN=============================*/ #define Size 1000 void main() { int i; char bignum[1010]=""; BigInt N; for(i=0;i<1000;i++) bignum[i]='9'; cout<<"sizeof(BigInt_Al)= "<<sizeof(BigInt)<<"\n"; N.digits=bignum; cout<<"sizeof(BigInt N.1000digit)= "<<sizeof(N)<<"\n"; puts(N.digits.c_str()); encode(N); cout<<"sizeof(Enconded N)= "<<sizeof(N)<<"\n"; decode(N); cout<<"sizeof(Decoded N)= "<<sizeof(N)<<"\n"; puts(N.digits.c_str()); cout<<"\n"<<"sizeof(__int64) = "<<sizeof(__int64)<<"\n"; cout<<"sizeof( int ) = "<<sizeof(int)<<"\n"; cout<<"sizeof( long ) = "<<sizeof(long)<<"\n"; cout<<"sizeof( short ) = "<<sizeof(short)<<"\n"; cout<<"sizeof( char ) = "<<sizeof(char)<<"\n"; cout<<"sizeof(clock_t) = "<<sizeof(clock_t)<<"\n"; }
905
414
//===- inst_simplify.cc ---------------------------------------------------===// // // Copyright (C) 2019-2020 Alibaba Group Holding Limited. // // 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 "halo/lib/transforms/inst_simplify.h" #include <algorithm> #include <numeric> #include <random> #include <string> #include <unordered_set> #include "halo/api/halo_data.h" #include "halo/lib/framework/common.h" #include "halo/lib/framework/data_layout.h" #include "halo/lib/framework/global_context.h" #include "halo/lib/ir/common_cast_instructions.h" #include "halo/lib/ir/common_instructions.h" #include "halo/lib/ir/common_reduction_instructions.h" #include "halo/lib/ir/ir_builder.h" #include "halo/lib/ir/math_instructions.h" #include "halo/lib/ir/nn_cnn_instructions.h" #include "halo/lib/transforms/transforms_util.h" #include "halo/lib/transforms/type_legalizer.h" namespace halo { template <typename T> static Constant* RunConstantFoldingOnMathBinary(const std::string& name, const Type& ret_type, Def op0, Def op1, OpCode opcode, KindPredicate pred) { if (!IsA<Constant>(op0.GetOwner()) || !IsA<Constant>(op1.GetOwner()) || op0.GetType().GetTotalNumOfElements() != op1.GetType().GetTotalNumOfElements()) { return nullptr; } if (opcode == OpCode::CMP) { if (pred == KindPredicate::GE) { pred = KindPredicate::LT; std::swap(op0, op1); } else if (pred == KindPredicate::GT) { pred = KindPredicate::LE; std::swap(op0, op1); } } Constant* c_lhs = DynCast<Constant>(op0.GetOwner()); Constant* c_rhs = DynCast<Constant>(op1.GetOwner()); size_t num_elements = op0.GetType().GetTotalNumOfElements(); Constant* c_ret = nullptr; ConstantBuilder cb(DynCast<Function>(c_lhs->GetParent())); std::vector<T> ret; ret.reserve(num_elements); switch (opcode) { case OpCode::ADD: { for (size_t i = 0; i < num_elements; ++i) { ret.push_back(c_lhs->GetData<T>(i) + c_rhs->GetData<T>(i)); } c_ret = cb.CreateConstant(name, ret_type, ret.data()); break; } case OpCode::MUL: { for (size_t i = 0; i < num_elements; ++i) { ret.push_back(c_lhs->GetData<T>(i) * c_rhs->GetData<T>(i)); } c_ret = cb.CreateConstant(name, ret_type, ret.data()); break; } case OpCode::DIV: { for (size_t i = 0; i < num_elements; ++i) { ret.push_back(c_lhs->GetData<T>(i) / c_rhs->GetData<T>(i)); } c_ret = cb.CreateConstant(name, ret_type, ret.data()); break; } case OpCode::CMP: { std::vector<int8_t> ret; switch (pred) { case KindPredicate::LT: { for (size_t i = 0; i < num_elements; ++i) { if (c_lhs->GetData<T>(i) < c_rhs->GetData<T>(i)) { ret.push_back(1); } else { ret.push_back(0); } } c_ret = cb.CreateConstant(name, ret_type, ret.data()); break; } default: { break; } } break; } default: { break; } } return c_ret; } template <typename T> static T* FuseToConvDeConv(const T* conv, OpCode opc, const Constant* c) { HLCHECK(IsA<Constant>(conv->GetOperand(1))); const auto kernel = DynCast<Constant>(conv->GetOperand(1)); const auto& kernel_type = kernel->GetResultType(); const auto& info = ImageAxisInfo::GetImageAxisInfo(conv->GetDataFormat(), conv->GetFilterFormat()); auto group = conv->GetGroup(); if (group < 1 || !conv->GetResultType().IsValid()) { return nullptr; } unsigned output_dim = info.kernel_output_axis; auto output_ch = conv->GetResultType().GetNumOfElementsInDim(info.data_channel_axis); bool has_valid_bias = conv->GetNumOfOperands() == 2 || (conv->GetNumOfOperands() == 3 && IsA<Constant>(conv->GetOperand(2)) && conv->GetOperand(2).GetType().GetTotalNumOfElements() == output_ch); if (!has_valid_bias) { return nullptr; } ConstantBuilder cb(conv->GetParent()->GetParent()); IRBuilder builder(conv->GetParent()); builder.SetInsertAfter(conv); auto n = c->GetResultType().GetTotalNumOfElements(); if (!has_valid_bias || output_ch != n) { return nullptr; } auto ops = conv->GetOperands(); const Constant* op_bias = conv->GetNumOfOperands() == 3 ? DynCast<Constant>(conv->GetOperand(2)) : nullptr; if (opc == OpCode::MUL) { std::vector<float> data(kernel_type.GetTotalNumOfElements()); size_t extend = 1; for (auto i = kernel_type.GetNumOfDims() - 1; i > output_dim; --i) { extend *= kernel_type.GetNumOfElementsInDim(i); } for (size_t i = 0, e = data.size(); i < e; ++i) { auto idx = (i / extend) % n; data[i] = kernel->template GetData<float>(i) * c->GetData<float>(idx); } auto new_kernel = cb.CreateConstant(kernel->GetName(), kernel_type, data.data()); ops[1] = *new_kernel; if (op_bias != nullptr) { std::vector<float> data(output_ch); for (int i = 0; i < output_ch; ++i) { data[i] = op_bias->GetData<float>(i) * c->GetData<float>(i); } auto new_bias = cb.CreateConstant(op_bias->GetName(), op_bias->GetResultType(), data.data()); ops[2] = *new_bias; } } else { std::vector<int64_t> shape(kernel_type.GetNumOfDims(), 1); shape[info.data_channel_axis] = n; halo::Type ty{kernel_type.GetDataType(), shape}; std::vector<float> data(output_ch); for (int i = 0; i < output_ch; ++i) { data[i] = (op_bias == nullptr ? 0 : op_bias->GetData<float>(i)) + c->GetData<float>(i); } auto new_bias = cb.CreateConstant(c->GetName(), ty, data.data()); if (ops.size() == 3) { ops.pop_back(); } ops.push_back(*new_bias); } auto new_conv = builder.Clone(*conv, ops); return DynCast<T>(new_conv); } static std::pair<Def, Def> RunOnMathBinaryInstruction(Instruction* binary_inst, bool disable_broadcasting, bool fuse_conv_bias) { Def orig_def{binary_inst, 0}; auto op0 = binary_inst->GetOperand(0); auto op1 = binary_inst->GetOperand(1); bool has_swapped = false; if (IsA<Constant>(op0)) { std::swap(op0, op1); has_swapped = true; } // MUL(x, 1) ==> x. if (binary_inst->GetOpCode() == OpCode::MUL && IsA<Constant>(op1)) { const Constant* c = DynCast<Constant>(op1); if (c->HasSameValueOf(1)) { return {orig_def, op0}; } } ConstantBuilder cb(binary_inst->GetParent()->GetParent()); IRBuilder builder(binary_inst->GetParent()); builder.SetInsertAfter(binary_inst); // Fuse mul/add into conv. auto opc = binary_inst->GetOpCode(); if ((opc == OpCode::MUL || (fuse_conv_bias && opc == OpCode::ADD)) && IsA<Constant>(op1)) { const Constant* c = DynCast<Constant>(op1); // check if mul can be fused with conv auto op0_opc = IsA<Instruction>(op0) ? DynCast<Instruction>(op0)->GetOpCode() : OpCode::INVALID; Instruction* new_inst = nullptr; if (op0_opc == OpCode::CONV2D) { new_inst = FuseToConvDeConv(DynCast<Conv2DInst>(op0), opc, c); } else if (op0_opc == OpCode::CONV2DTRANSPOSE) { new_inst = FuseToConvDeConv(DynCast<Conv2DTransposeInst>(op0), opc, c); } if (new_inst != nullptr) { return {orig_def, *new_inst}; } } const auto& op0_type = op0.GetType(); const auto& op1_type = op1.GetType(); OpCode opcode = binary_inst->GetOpCode(); /* // Handle scalar constant if (IsA<Constant>(op1.GetOwner())) { Constant* c_op1 = DynCast<Constant>(op1.GetOwner()); Type ret_type = binary_inst->GetResultsTypes()[0]; HLCHECK(ret_type.IsValid()); if (c_op1->IsScalarZero()) { if (opcode == OpCode::ADD) { return {orig_def, op0}; } if (opcode == OpCode::MUL) { Constant* c_zero = cb.SplatConstantZero(binary_inst->GetName(), ret_type); return {orig_def, *c_zero}; } } if (c_op1->IsScalarOne()) { if (opcode == OpCode::MUL) { return {orig_def, op0}; } } }*/ const int64_t folding_threshold = 10; // Both operands are constant, do constant folding if (IsA<Constant>(op0) && IsA<Constant>(op1) && op0_type.GetTotalNumOfElements() == op1_type.GetTotalNumOfElements() && op0_type.GetTotalNumOfElements() < folding_threshold) { Type ret_type = binary_inst->GetResultsTypes()[0]; HLCHECK(ret_type.IsValid()); KindPredicate pred = KindPredicate::INVALID; if (opcode == OpCode::CMP) { pred = static_cast<CmpInst*>(binary_inst)->GetPredicator(); // NOLINT } if (has_swapped) { std::swap(op0, op1); } Constant* c_ret = nullptr; switch (op0_type.GetDataType()) { case DataType::INT32: { c_ret = RunConstantFoldingOnMathBinary<int>( binary_inst->GetName() + "_folding", ret_type, op0, op1, opcode, pred); break; } case DataType::INT64: { c_ret = RunConstantFoldingOnMathBinary<int64_t>( binary_inst->GetName() + "_folding", ret_type, op0, op1, opcode, pred); break; } case DataType::FLOAT32: { c_ret = RunConstantFoldingOnMathBinary<float>( binary_inst->GetName() + "_folding", ret_type, op0, op1, opcode, pred); break; } default: c_ret = nullptr; } if (c_ret != nullptr) { return {orig_def, *c_ret}; } return {orig_def, orig_def}; } // Do offline broadcasting. if (!disable_broadcasting && op0_type.IsValid() && IsA<Constant>(op1) && op0_type.GetNumOfDims() != op1_type.GetNumOfDims() && op0_type.GetTotalNumOfElements() >= op1_type.GetTotalNumOfElements() && op0_type.GetNumOfElementsInDim(op0_type.GetNumOfDims() - 1) != 1) { size_t lhs_cnt = op0_type.GetTotalNumOfElements(); size_t rhs_cnt = op1_type.GetTotalNumOfElements(); auto orig_addend = DynCast<Constant>(op1.GetOwner()); HLCHECK(lhs_cnt % rhs_cnt == 0); HLCHECK(op1_type.GetDataType() == op0_type.GetDataType()); auto copies = lhs_cnt / rhs_cnt; size_t copy_size = rhs_cnt * orig_addend->GetElementSizeInBytes(); std::vector<char> buf(copies * copy_size); for (size_t i = 0; i < copies; ++i) { memcpy(&buf[copy_size * i], orig_addend->GetRawDataPtr(), copy_size); } auto addend = cb.CreateConstant(orig_addend->GetName() + "_broadcasted_" + std::to_string(binary_inst->GetId()), op0_type, buf.data()); auto new_add = has_swapped ? builder.CreateBinary(binary_inst->GetName(), *addend, op0, opcode) : builder.CreateBinary(binary_inst->GetName(), op0, *addend, opcode); new_add->GetResultsTypes()[0] = binary_inst->GetResultsTypes()[0]; return {orig_def, *new_add}; } if (op0_type.IsValid() && IsA<Constant>(op1) && IsA<Instruction>(op0) && op1_type.BroadcastableTo(op0_type)) { Instruction* op0_inst = DynCast<Instruction>(op0.GetDef()); if (op0_inst->GetOpCode() == OpCode::TRANSPOSE && !IsA<Argument>(op0_inst->GetOperand(0))) { // Add(transpose(op0), op1) ==> transpose(add(op0, transpose'(op1)) TransposeInst* orig_transpose = DynCast<TransposeInst>(op0_inst); IRBuilder builder(binary_inst->GetParent()); builder.SetInsertAfter(binary_inst); const auto& orig_perm = orig_transpose->GetPermutation(); Instruction* new_op1 = nullptr; if (op1_type.GetSqueezedNumOfDims() == 1) { auto dims = std::vector<int64_t>(op0_type.GetNumOfDims(), 1); int64_t op1_vector_axis = op0_type.GetNumOfDims() - 1; for (auto n = op1_type.GetTotalNumOfElements(); op1_vector_axis >= 0; --op1_vector_axis) { if (op0_type.GetNumOfElementsInDim(op1_vector_axis) == n) { break; } } dims[orig_perm[op1_vector_axis]] = op1_type.GetTotalNumOfElements(); ConstantBuilder cb(binary_inst->GetParent()->GetParent()); Constant* c_shape = cb.CreateConstant( op1.GetDef()->GetName() + "_shape", halo::Type{DataType::INT64, {static_cast<int64_t>(dims.size())}}, dims.data()); auto new_addend = builder.CreateReshape(op1.GetDef()->GetName() + "_r", {op1, *c_shape}); new_op1 = new_addend; new_addend->GetResultsTypes()[0] = Type{op1.GetType().GetDataType(), dims}; } else { auto reverse_perm = orig_perm; for (int i = 0, e = orig_perm.size(); i < e; ++i) { reverse_perm[orig_perm[i]] = i; } auto new_addend = builder.CreateTranspose(op1.GetDef()->GetName() + "_t", {op1}); new_addend->SetPermutation(reverse_perm); new_op1 = new_addend; } auto new_binary = builder.CreateBinary(binary_inst->GetName(), op0.GetDef()->GetOperand(0), *new_op1, opcode); TransposeInst* new_transpose = builder.CreateTranspose("t_" + binary_inst->GetName(), {*new_binary}); new_transpose->SetPermutation(orig_perm); return {orig_def, *new_transpose}; } } // add(transpose(v0), transpose(v1)) => transpose(v0, v1) if (IsA<Instruction>(op0) && IsA<Instruction>(op1)) { const Instruction* op0_inst = DynCast<Instruction>(op0); const Instruction* op1_inst = DynCast<Instruction>(op1); if (op0_inst->GetOpCode() == OpCode::TRANSPOSE && op1_inst->GetOpCode() == OpCode::TRANSPOSE) { const TransposeInst* tr0 = DynCast<const TransposeInst>(op0_inst); const TransposeInst* tr1 = DynCast<const TransposeInst>(op1_inst); if (tr0->GetPermutation() == tr1->GetPermutation()) { IRBuilder builder(binary_inst->GetParent()); builder.SetInsertAfter(binary_inst); auto new_binary = builder.CreateAdd( binary_inst->GetName(), tr0->GetOperand(0), tr1->GetOperand(0)); TransposeInst* new_tr = builder.CreateTranspose( binary_inst->GetName() + "_t", {*new_binary}); new_tr->SetPermutation(tr0->GetPermutation()); return {orig_def, *new_tr}; } } } return {orig_def, orig_def}; } template <typename ReduceInstTy, typename Build> static std::pair<Def, Def> EliminateTranspose(ReduceInstTy* inst, Build build) { Def orig_def{inst, 0}; std::pair<Def, Def> ret{orig_def, orig_def}; // ReduceMean(tranpose(x, {t0, t1, t2, t3}, {a0, a1, a2...}) => ReduceMean(x, // permed_axis) Def op0 = inst->GetOperand(0); if (IsA<Instruction>(op0.GetOwner()) && DynCast<Instruction>(op0.GetOwner())->GetOpCode() == OpCode::TRANSPOSE) { IRBuilder builder(inst->GetParent()); builder.SetInsertAfter(inst); const TransposeInst* transpose = DynCast<TransposeInst>(op0.GetOwner()); const auto& perm = transpose->GetPermutation(); const auto& orig_axes = inst->GetAxis(); std::vector<int> new_axes(orig_axes.size()); std::transform(orig_axes.begin(), orig_axes.end(), new_axes.begin(), [&perm](int x) { return perm[x]; }); ReduceInstTy* new_inst = build(builder, inst->GetName(), transpose->GetOperand(0)); new_inst->SetAxis(new_axes); ret.second = *new_inst; return ret; } return ret; } static std::pair<Def, Def> RunOnCommonReductionInstruction(Instruction* inst) { Def orig_def{inst, 0}; auto op0 = inst->GetOperand(0); const Type& dst_type = inst->GetResultsTypes()[0]; const Type& op0_type = op0.GetType(); OpCode opcode = inst->GetOpCode(); // Move the constant axis into attribute. if (inst->GetNumOfOperands() > 1 && IsA<Constant>(inst->GetOperand(1))) { const Constant* data = DynCast<Constant>(inst->GetOperand(1).GetOwner()); const Type& ty = data->GetResultType(); if (ty.GetDataType() == DataType::INT32) { const int32_t* ptr = data->GetDataPtr<int32_t>(); std::vector<int> axis(ptr, ptr + ty.GetTotalNumOfElements()); // NOLINT IRBuilder builder(inst->GetParent()); builder.SetInsertAfter(inst); Instruction* ret = nullptr; switch (opcode) { case OpCode::REDUCEMEAN: { ReduceMeanInst* new_inst = DynCast<ReduceMeanInst>( builder.Clone(*inst, {inst->GetOperand(0)})); new_inst->SetAxis(axis); ret = new_inst; break; } case OpCode::ARGMAX: { ArgmaxInst* new_inst = DynCast<ArgmaxInst>(builder.Clone(*inst, {inst->GetOperand(0)})); new_inst->SetAxis(axis.at(0)); ret = new_inst; break; } default: { break; } } if (ret != nullptr) { ret->GetResultsTypes()[0] = inst->GetResultType(); return {orig_def, *ret}; } } } if (inst->GetNumOfOperands() == 1) { std::pair<Def, Def> ret{orig_def, orig_def}; switch (opcode) { case OpCode::REDUCEMIN: { ret = EliminateTranspose( DynCast<ReduceMinInst>(inst), [](IRBuilder& builder, const std::string& name, const Def& def) { return builder.CreateReduceMin(name, {def}); }); break; } case OpCode::REDUCEMAX: { ret = EliminateTranspose( DynCast<ReduceMaxInst>(inst), [](IRBuilder& builder, const std::string& name, const Def& def) { return builder.CreateReduceMax(name, {def}); }); break; } case OpCode::REDUCEMEAN: { ret = EliminateTranspose( DynCast<ReduceMeanInst>(inst), [](IRBuilder& builder, const std::string& name, const Def& def) { return builder.CreateReduceMean(name, {def}); }); break; } case OpCode::REDUCEPRODUCT: { ret = EliminateTranspose( DynCast<ReduceProductInst>(inst), [](IRBuilder& builder, const std::string& name, const Def& def) { return builder.CreateReduceProduct(name, {def}); }); break; } default: { break; } } if (ret.first != ret.second) { return ret; } } if (!dst_type.IsValid() || !IsA<Constant>(op0.GetOwner()) || op0_type.GetNumOfDims() > 1) { return {orig_def, orig_def}; } ConstantBuilder cb(inst->GetParent()->GetParent()); Constant* c_input = DynCast<Constant>(op0.GetOwner()); DataType dt = op0_type.GetDataType(); if (op0_type.GetTotalNumOfElements() == 1) { Constant* c_ret = nullptr; if (opcode == OpCode::ARGMAX || opcode == OpCode::ARGMIN) { int ret = 0; c_ret = cb.CreateConstant(inst->GetName() + "_folding", dst_type, &ret); } else { c_ret = cb.CreateConstant(inst->GetName() + "_folding", dst_type, c_input->GetRawDataPtr()); } return {orig_def, *c_ret}; } if (dt == DataType::INT32) { switch (opcode) { case OpCode::REDUCEMIN: case OpCode::REDUCEMAX: case OpCode::ARGMAX: { int ret = std::numeric_limits<int32_t>::lowest(); int index = -1; for (int i = 0; i < op0_type.GetTotalNumOfElements(); ++i) { int data_i = c_input->GetData<int>(i); ret = std::max(ret, data_i); if (ret == data_i) { index = i; } } if (opcode == OpCode::REDUCEMAX || opcode == OpCode::REDUCEMIN) { auto new_def = cb.CreateConstant(inst->GetName() + "_folding", dst_type, &ret); return {orig_def, *new_def}; } // ARGMAX auto new_def = cb.CreateConstant(inst->GetName() + "_folding", dst_type, &index); return {orig_def, *new_def}; } case OpCode::REDUCEMEAN: case OpCode::REDUCESUM: { int ret = 0; for (int i = 0; i < op0_type.GetTotalNumOfElements(); ++i) { ret += c_input->GetData<int>(i); } if (opcode == OpCode::REDUCEMEAN) { ret /= op0_type.GetTotalNumOfElements(); } auto new_def = cb.CreateConstant(inst->GetName() + "_folding", dst_type, &ret); return {orig_def, *new_def}; } case OpCode::REDUCEPRODUCT: { int ret = 1; for (int i = 0; i < op0_type.GetTotalNumOfElements(); ++i) { ret *= c_input->GetData<int>(i); } auto new_def = cb.CreateConstant(inst->GetName() + "_folding", dst_type, &ret); return {orig_def, *new_def}; } default: { return {orig_def, orig_def}; } } } return {orig_def, orig_def}; } /// By default, nothing is updated. std::pair<Def, Def> InstSimplify::RunOnInstruction(Instruction* inst) { switch (inst->GetOpCode()) { case OpCode::ADD: case OpCode::MUL: case OpCode::DIV: case OpCode::SUB: case OpCode::CMP: { return RunOnMathBinaryInstruction(inst, disable_broadcasting_, fuse_conv_bias_); } case OpCode::REDUCEMAX: case OpCode::REDUCEMIN: case OpCode::REDUCEMEAN: case OpCode::REDUCESUM: case OpCode::REDUCEPRODUCT: case OpCode::ARGMAX: case OpCode::ARGMIN: { return RunOnCommonReductionInstruction(inst); } default: { return std::make_pair(Def{inst, 0}, Def{inst, 0}); } } } template <typename InstType, typename Builder> static std::pair<Def, Def> SinkTranspose(InstType& inst, Builder build) { std::pair<Def, Def> ret{Def{&inst, 0}, Def{&inst, 0}}; if (IsA<Instruction>(inst.GetOperand(0))) { // Inst(transpose(x)) -> transpose(Inst(x)), this exposes opportunites // to cancel out transposes. Instruction* op0_inst = DynCast<Instruction>(inst.GetOperand(0)); if (op0_inst->GetOpCode() == OpCode::TRANSPOSE) { const TransposeInst* orig_trans = DynCast<TransposeInst>(op0_inst); IRBuilder builder(inst.GetParent()); builder.SetInsertAfter(&inst); InstType* new_inst = build(builder, inst.GetName(), op0_inst->GetOperand(0)); TransposeInst* new_trans = builder.CreateTranspose(inst.GetName() + "_t", {*new_inst}); new_trans->SetPermutation(orig_trans->GetPermutation()); ret.second = *new_trans; return ret; } } return ret; } std::pair<Def, Def> InstSimplify::RunOnInstruction(LeakyReluInst* inst) { return SinkTranspose(*inst, [inst](IRBuilder& builder, const std::string& name, const Def& op) { auto new_inst = builder.CreateLeakyRelu(name, op); new_inst->SetAlpha(inst->GetAlpha()); return new_inst; }); } std::pair<Def, Def> InstSimplify::RunOnInstruction(PReluInst* inst) { auto op1 = inst->GetOperand(1); return SinkTranspose( *inst, [inst, &op1](IRBuilder& builder, const std::string& name, const Def& op) { return DynCast<PReluInst>(builder.Clone(*inst, {op, op1})); }); } template <typename T> static Constant* GetPermutedConstant(ConstantBuilder* cb, const Constant* orig, const std::vector<int32_t>& perm) { const auto& shape_type = orig->GetResultType(); auto ranks = shape_type.GetTotalNumOfElements(); std::vector<T> data(ranks); for (int64_t i = 0; i < ranks; ++i) { data[perm[i]] = orig->GetData<T>(i); } return cb->CreateConstant(orig->GetName(), shape_type, data.data()); } std::pair<Def, Def> InstSimplify::RunOnInstruction(ResizeInst* inst) { Def orig_def{inst, 0}; auto op_shape = inst->GetOperand(1); if (IsA<Instruction>(inst->GetOperand(0))) { Instruction* op0_inst = DynCast<Instruction>(inst->GetOperand(0).GetOwner()); if (auto op1 = inst->GetOperand(1); op0_inst->GetOpCode() == OpCode::TRANSPOSE && IsA<Constant>(op1)) { Constant* shape = DynCast<Constant>(op1); const auto& shape_type = shape->GetResultType(); ConstantBuilder cb(inst->GetParent()->GetParent()); auto orig_perm = DynCast<TransposeInst>(op0_inst)->GetPermutation(); Constant* new_shape = nullptr; switch (shape_type.GetDataType()) { case DataType::INT32: { new_shape = GetPermutedConstant<int32_t>(&cb, shape, orig_perm); break; } case DataType::INT64: { new_shape = GetPermutedConstant<int64_t>(&cb, shape, orig_perm); break; } case DataType::FLOAT32: { new_shape = GetPermutedConstant<float>(&cb, shape, orig_perm); break; } default: HLCHECK(0 && "Invalid resize shape type"); } new_shape->SetName(inst->GetName() + "_resize_shape"); return SinkTranspose( *inst, [new_shape, inst](IRBuilder& builder, const std::string& name, const Def& op) { auto new_inst = builder.CreateResize(name, {op, *new_shape}); new_inst->CopyAttrsFrom(*inst); return new_inst; }); } } return {orig_def, orig_def}; } std::pair<Def, Def> InstSimplify::RunOnInstruction(Relu6Inst* inst) { return SinkTranspose( *inst, [](IRBuilder& builder, const std::string& name, const Def& op) { return builder.CreateRelu6(name, op); }); } std::pair<Def, Def> InstSimplify::RunOnInstruction(SigmoidInst* inst) { return SinkTranspose( *inst, [](IRBuilder& builder, const std::string& name, const Def& op) { return builder.CreateSigmoid(name, op); }); } std::pair<Def, Def> InstSimplify::RunOnInstruction(ReluInst* inst) { return SinkTranspose( *inst, [](IRBuilder& builder, const std::string& name, const Def& op) { return builder.CreateRelu(name, op); }); } std::pair<Def, Def> InstSimplify::RunOnInstruction(Conv2DInst* inst) { std::pair<Def, Def> ret{Def{inst, 0}, Def{inst, 0}}; if (!inst->GetResultType().IsValid()) { return ret; } Def op_input = inst->GetOperand(0); Def op_kernel = inst->GetOperand(1); IRBuilder builder(inst->GetParent()); builder.SetInsertAfter(inst); // Convert conv(pad(x, amt), kernel) to conv(x, kernel) to eliminate // pad op. if (IsA<Instruction>(op_input) && DynCast<Instruction>(op_input)->GetOpCode() == OpCode::PAD) { const PadInst* pad = DynCast<PadInst>(op_input); Def pad_op0 = pad->GetOperand(0); Def pad_op1 = pad->GetOperand(1); if (IsA<Constant>(pad_op1.GetOwner())) { const Constant* pad_amt = DynCast<Constant>(pad_op1); unsigned dims = pad_amt->GetResultType().GetNumOfDims(); if (dims == 2 && pad_amt->GetResultType().GetTotalNumOfElements() == 4 * dims) { std::vector<int32_t> vals( pad_amt->GetDataPtr<int32_t>(), pad_amt->GetDataPtr<int32_t>() + 4 * dims); // NOLINT if (vals[0] != 0 || vals[1] != 0) { return ret; } const auto& info = ImageAxisInfo::GetImageAxisInfo( inst->GetDataFormat(), inst->GetFilterFormat()); std::array<int, 4> indices_nc = {0, 1, info.data_channel_axis * 2, info.data_channel_axis * 2 + 1}; // No paddings on N & C. for (auto idx : indices_nc) { if (vals[idx] != 0) { return ret; } } std::array<int, 4> indices_hw = { info.data_height_axis * 2, info.data_height_axis * 2 + 1, info.data_width_axis * 2, info.data_width_axis + 1}; Conv2DInst* new_inst = builder.CreateConv2D(inst->GetName(), {pad_op0, op_kernel}); new_inst->SetDataFormat(inst->GetDataFormat()); new_inst->SetFilterFormat(inst->GetFilterFormat()); new_inst->SetDilations(inst->GetDilations()); new_inst->SetStrides(inst->GetStrides()); new_inst->SetPaddingTop(inst->GetPaddingTop() + vals[indices_hw[0]]); new_inst->SetPaddingBottom(inst->GetPaddingBottom() + vals[indices_hw[1]]); new_inst->SetPaddingLeft(inst->GetPaddingLeft() + vals[indices_hw[2]]); new_inst->SetPaddingRight(inst->GetPaddingRight() + vals[indices_hw[3]]); new_inst->GetResultsTypes()[0] = inst->GetResultsTypes()[0]; new_inst->SetPadding(Padding::EXPLICIT); ret.second = Def(new_inst, 0); } } } // Convert Conv(add(x, c), k) => Conv(x, k') or Conv(mul(x, c), k) ==> // Conv(x, k') where k is a constant of scalar or channel-wise vector. if (IsA<Instruction>(op_input) && IsA<Constant>(op_kernel) && inst->GetGroup() == 1 && inst->GetResultType().IsValid() && (DynCast<Instruction>(op_input)->GetOpCode() == OpCode::ADD || DynCast<Instruction>(op_input)->GetOpCode() == OpCode::MUL)) { Instruction* binary_inst = DynCast<Instruction>(op_input); auto binary_op0 = binary_inst->GetOperand(0); if (IsA<Instruction>(binary_op0) && DynCast<Instruction>(binary_op0)->GetOpCode() == OpCode::CONV2D) { // For pattens like a = conv(); b = a + c; d = conv(b), prefer to fuse a // and b. return ret; } auto binary_op1 = binary_inst->GetOperand(1); if (!IsA<Constant>(binary_op1)) { return ret; } const auto& kernel_type = op_kernel.GetType(); Constant* c = DynCast<Constant>(binary_op1); if (kernel_type.GetDataType() != DataType::FLOAT32 || kernel_type.GetDataType() != c->GetResultType().GetDataType()) { return ret; } // match shape of C: expect [..,in_chs, 1, 1]. auto n_elems = c->GetResultType().GetTotalNumOfElements(); auto dims = c->GetResultType().GetDimSizes(); auto kernel_shape = kernel_type.GetDimSizes(); const auto& info = ImageAxisInfo::GetImageAxisInfo(inst->GetDataFormat(), inst->GetFilterFormat()); auto in_chs = kernel_shape[info.kernel_input_axis]; auto in_chs_dim_r = info.kernel_input_axis - kernel_shape.size(); // Dims in backwards. if (!(n_elems == in_chs && (dims.size() == 1 || (-in_chs_dim_r <= dims.size() && dims[dims.size() + in_chs_dim_r] == in_chs)))) { return ret; } bool has_padding = inst->GetPaddingBottom() != 0 || inst->GetPaddingLeft() != 0 || inst->GetPaddingTop() != 0 || inst->GetPaddingRight() != 0; Constant* kernel = DynCast<Constant>(op_kernel); ConstantBuilder cb(inst->GetParent()->GetParent()); std::vector<float> new_kernel_data(kernel_type.GetTotalNumOfElements()); auto operands = inst->GetOperands(); operands[0] = binary_op0; std::vector<size_t> strides(kernel_shape.size(), 1); for (int64_t i = kernel_shape.size() - 2; i >= 0; --i) { strides[i] = strides[i + 1] * kernel_shape[i + 1]; } if (binary_inst->GetOpCode() == OpCode::MUL) { for (size_t i = 0, e = kernel_type.GetTotalNumOfElements(); i < e; ++i) { size_t ch = (i / strides[info.kernel_input_axis]) % in_chs; new_kernel_data[i] = kernel->GetDataAsFloat32(i) * c->GetDataAsFloat32(ch); } auto new_kernel = cb.CreateConstant(kernel->GetName(), kernel_type, new_kernel_data); operands[1] = *new_kernel; ret.second = *builder.Clone(*inst, operands); } else if (!has_padding && (inst->GetNumOfOperands() == 2 || (inst->GetNumOfOperands() == 3 && IsA<Constant>(inst->GetOperand(2))))) { auto out_chs = kernel_shape[info.kernel_output_axis]; // Conv(x + c), k) ==> Conv(x, k) + c * k) // C is vector (len = in_chs), reshape k to (H * W, out_chs, in_chs) std::vector<float> new_bias(out_chs); std::string bias_name = inst->GetName() + "_bias"; if (inst->GetNumOfOperands() == 3) { auto orig_bias = DynCast<Constant>(inst->GetOperand(2)); bias_name = orig_bias->GetName() + "_fused"; HLCHECK(orig_bias->GetResultType().GetTotalNumOfElements() == out_chs); for (int i = 0; i < out_chs; ++i) { new_bias[i] = orig_bias->GetDataAsFloat32(i); } } auto hw = kernel_type.GetTotalNumOfElements() / in_chs / out_chs; auto stride_s = strides[info.kernel_width_axis]; auto stride_o = strides[info.kernel_output_axis]; auto stride_i = strides[info.kernel_input_axis]; for (int s = 0; s < hw; ++s) { for (int och = 0; och < out_chs; ++och) { std::vector<float> m(in_chs); float t = 0; for (int i = 0; i < in_chs; ++i) { t += kernel->GetDataAsFloat32(s * stride_s + och * stride_o + i * stride_i) * c->GetDataAsFloat32(i); } new_bias[och] += t; } } halo::Type type{kernel_type.GetDataType(), {out_chs}}; auto new_bias_op = cb.CreateConstant(bias_name, type, new_bias); if (operands.size() >= 3) { operands[2] = *new_bias_op; } else { operands.push_back(*new_bias_op); } ret.second = *builder.Clone(*inst, operands); } } return ret; } static void Pad(char* dst, const char* src, size_t elems_num, size_t elem_size, const std::vector<int64_t>& orig_shape, const std::vector<int64_t>& new_shape, const std::vector<int32_t>& padding_amt) { std::vector<size_t> pos(orig_shape.size()); std::vector<size_t> dst_strides(orig_shape.size(), 1); int dims = orig_shape.size(); for (int i = dims - 2; i >= 0; --i) { dst_strides[i] = dst_strides[i + 1] * new_shape[i + 1]; } for (size_t i = 0; i < elems_num; ++i) { auto dst_pos = pos; for (int j = 0; j < dims; ++j) { dst_pos[j] += padding_amt[j]; } size_t dst_offset = std::inner_product(dst_pos.begin(), dst_pos.end(), dst_strides.begin(), 0UL) * elem_size; std::copy(src, src + elem_size, dst + dst_offset); // NOLINT. src += elem_size; // NOLINT. int c = 1; for (int j = dims - 1; j >= 0 && c == 1; --j) { pos[j] += c; if (pos[j] >= static_cast<size_t>(orig_shape[j])) { pos[j] = 0; } else { c = 0; } } } } std::pair<Def, Def> InstSimplify::RunOnInstruction(PadInst* pad_inst) { Def orig_def{pad_inst, 0}; Def op0 = pad_inst->GetOperand(0); Def op1 = pad_inst->GetOperand(1); if (!IsA<Constant>(op0.GetOwner()) || !IsA<Constant>(op1.GetOwner()) || pad_inst->GetNumOfOperands() != 2 || pad_inst->GetMode() != PadMode::CONSTANT) { return {orig_def, orig_def}; } const Constant* data = DynCast<Constant>(op0.GetOwner()); const Constant* pad_amt = DynCast<Constant>(op1.GetOwner()); ConstantBuilder cb(pad_inst->GetParent()->GetParent()); auto dims = op0.GetType().GetNumOfDims(); std::vector<int64_t> shape(dims); std::vector<int32_t> paddings_before(dims); for (size_t i = 0; i < dims; ++i) { int32_t before = pad_amt->GetDataPtr<int32_t>()[i * 2]; // NOLINT int32_t after = pad_amt->GetDataPtr<int32_t>()[i * 2 + 1]; // NOLINT shape[i] = op0.GetType().GetNumOfElementsInDim(i) + before + after; paddings_before[i] = before; } halo::Type type{op0.GetType().GetDataType(), shape}; std::vector<char> w(type.GetTotalNumOfElements() * data->GetElementSizeInBytes()); std::vector<size_t> dim_sizes(dims); Pad(w.data(), static_cast<const char*>(data->GetRawDataPtr()), op0.GetType().GetTotalNumOfElements(), data->GetElementSizeInBytes(), op0.GetType().GetDimSizes(), shape, paddings_before); auto new_inst = cb.CreateConstant("folded_pad", type, w.data()); return {orig_def, Def{new_inst, 0}}; } std::pair<Def, Def> InstSimplify::RunOnInstruction(ReshapeInst* reshape_inst) { Def orig_def{reshape_inst, 0}; // for reshape(reshape(x, c0), c1), replace it with reshape(x, c1). auto op0 = reshape_inst->GetOperand(0).GetDef(); if (IsA<Instruction>(op0)) { const Instruction* op0_inst = Downcast<const Instruction>(op0); if (op0_inst->GetOpCode() == OpCode::RESHAPE) { IRBuilder builder(reshape_inst->GetParent()); builder.SetInsertAfter(reshape_inst); auto new_inst = builder.CreateReshape(reshape_inst->GetName(), op0_inst->GetOperand(0), reshape_inst->GetOperand(1)); new_inst->GetResultsTypes()[0] = reshape_inst->GetResultsTypes()[0]; return {orig_def, Def{new_inst, 0}}; } } const auto& input_type = op0->GetResultType(); const auto& ret_type = reshape_inst->GetResultType(); if (input_type.IsValid() && ret_type.IsValid() && input_type == ret_type) { return {orig_def, *op0}; } if (IsA<Constant>(op0) && reshape_inst->GetResultType().IsValid()) { Constant* src = DynCast<Constant>(op0); Constant* new_c = nullptr; if (op0->GetNumberOfUses() == 1) { new_c = src; } else { ConstantBuilder cb(reshape_inst->GetParent()->GetParent()); new_c = cb.Clone(*src); } new_c->GetResultsTypes()[0] = reshape_inst->GetResultType(); return {orig_def, *new_c}; } return {orig_def, orig_def}; } std::pair<Def, Def> InstSimplify::RunOnInstruction(ExpandDimsInst* inst) { HLCHECK(inst->GetNumOfOperands() == 2); auto input = inst->GetOperand(0); const auto& input_type = input.GetType(); Def orig_def{inst, 0}; if (!input_type.IsValid() || !IsA<Constant>(inst->GetOperand(1))) { return {orig_def, orig_def}; } const Constant* shape = DynCast<Constant>(inst->GetOperand(1)); auto input_elem = input_type.GetTotalNumOfElements(); HLCHECK(shape->GetResultType().GetNumOfDims() == 1); std::vector<int64_t> output_shape; std::vector<int64_t> output_extends; IRBuilder builder(inst->GetParent()); builder.SetInsertAfter(inst); int shape_rank = shape->GetResultType().GetTotalNumOfElements(); int input_rank = input_type.GetNumOfDims(); auto src_extends = GetExtends(input_type.GetDimSizes()); for (int i = 0, e = std::max(shape_rank, input_rank); i < e; ++i) { int input_idx = input_rank - 1 - i; int shape_idx = shape_rank - 1 - i; int64_t dim0 = (input_idx < 0) ? 1 : input_type.GetNumOfElementsInDim(input_idx); int64_t dim1 = (shape_idx < 0) ? 1 : shape->GetDataAsInt64(shape_idx); HLCHECK(dim0 == dim1 || dim0 == 1 || dim1 == 1); output_shape.push_back((dim0 == 1) ? dim1 : dim0); bool is_bs = dim0 == 1; output_extends.push_back(is_bs ? 0 : src_extends[input_idx]); } std::reverse(output_shape.begin(), output_shape.end()); std::reverse(output_extends.begin(), output_extends.end()); halo::Type ret_type{input_type.GetDataType(), output_shape}; auto ret_elem = ret_type.GetTotalNumOfElements(); ConstantBuilder cb(inst->GetParent()->GetParent()); if (input_elem == ret_elem) { Constant* c = cb.CreateConstant( inst->GetName() + "_expand", halo::Type{DataType::INT64, {static_cast<int64_t>(output_shape.size())}}, output_shape.data()); auto reshape = builder.CreateReshape(inst->GetName(), {inst->GetOperand(0), *c}); return {orig_def, *reshape}; } if (IsA<Constant>(inst->GetOperand(0))) { const Constant* src = DynCast<Constant>(input); DefaultDataLayout data_layout; size_t elem_size = data_layout.Bytes(input_type.GetDataType()); std::vector<unsigned char> buf(ret_elem * elem_size); const auto& dst_extends = GetExtends(output_shape); for (int64_t dst_idx = 0; dst_idx < ret_elem; ++dst_idx) { std::vector<int64_t> dst_dims(output_shape.size()); for (int64_t i = 0, e = dst_dims.size(), t = dst_idx; t >= 0 && i < e; ++i) { dst_dims[i] = t / dst_extends[i]; t -= dst_dims[i] * dst_extends[i]; } auto src_idx = std::inner_product( output_extends.begin(), output_extends.end(), dst_dims.begin(), 0L); const unsigned char* src_ptr = static_cast<const unsigned char*>(src->GetRawDataPtr()) + // NOLINT. src_idx * elem_size; std::copy_n(src_ptr, elem_size, buf.begin() + dst_idx * elem_size); } Constant* c = cb.CreateConstant(inst->GetName() + "_expand", ret_type, buf.data()); return {orig_def, *c}; } return {orig_def, orig_def}; } std::pair<Def, Def> InstSimplify::RunOnInstruction(BatchNormInst* inst) { Def orig_def{inst, 0}; int num_inputs = inst->GetNumOfOperands(); const auto& input_type = inst->GetResultType(); auto input = inst->GetOperand(0); // Not profitable if the mul cannot be fused. auto input_op = IsA<Instruction>(input) ? DynCast<Instruction>(input)->GetOpCode() : OpCode::INVALID; bool is_profitable = input_op == OpCode::CONV2D || input_op == OpCode::CONV2DTRANSPOSE; if (disable_conv_bn_ || !is_profitable || num_inputs <= 4 || !input_type.IsValid() || input_type.GetNumOfDims() != 4 || !IsA<Constant>(inst->GetOperand(3)) || !IsA<Constant>(inst->GetOperand(4))) { return {orig_def, orig_def}; } auto scale = DynCast<Constant>(inst->GetOperand(1)); auto offset = DynCast<Constant>(inst->GetOperand(2)); auto mean = DynCast<Constant>(inst->GetOperand(3)); auto variance = DynCast<Constant>(inst->GetOperand(4)); int ch_dim = inst->GetDataFormat() == DataFormat::NCHW ? 1 : 3; auto ch_num = input_type.GetNumOfElementsInDim(ch_dim); const auto& mean_type = mean->GetResultType(); if (mean_type.GetTotalNumOfElements() != ch_num || variance->GetResultType().GetTotalNumOfElements() != ch_num || mean_type.GetDataType() != DataType::FLOAT32) { return {orig_def, orig_def}; } std::vector<float> mul_buf(ch_num); std::vector<float> add_buf(ch_num); float eps = inst->GetEpsilon(); // Convert BN to Ax + B. for (int64_t i = 0; i < ch_num; ++i) { mul_buf[i] = 1.0F / std::sqrt(variance->GetData<float>(i) + eps); float s = scale->GetData<float>(i); mul_buf[i] *= s; float b = offset->GetData<float>(i); add_buf[i] = -mean->GetData<float>(i) * mul_buf[i] + b; } std::vector<int64_t> shape(input_type.GetNumOfDims(), 1); shape[ch_dim] = ch_num; halo::Type ty{mean_type.GetDataType(), shape}; ConstantBuilder cb(inst->GetParent()->GetParent()); auto new_scale = cb.CreateConstant(inst->GetName() + "_0", ty, mul_buf.data()); auto new_offset = cb.CreateConstant(inst->GetName() + "_1", ty, add_buf.data()); IRBuilder builder(inst->GetParent()); builder.SetInsertAfter(inst); auto new_mul = builder.CreateMul(inst->GetName() + "_mul", input, *new_scale); auto new_add = builder.CreateAdd(inst->GetName() + "_add", *new_mul, *new_offset); return {orig_def, *new_add}; } std::pair<Def, Def> InstSimplify::RunOnInstruction(StackInst* inst) { Def orig_def{inst, 0}; int num_inputs = inst->GetNumOfOperands(); if (inst->GetAxis() != 0) { return {orig_def, orig_def}; } for (int i = 0; i < num_inputs; ++i) { if (!IsA<Constant>(inst->GetOperand(i))) { return {orig_def, orig_def}; } } // convert to an array of constant const auto& input0_type = inst->GetOperand(0).GetType(); std::vector<int64_t> ret_shape(input0_type.GetDimSizes()); ret_shape.insert(ret_shape.begin(), num_inputs); ConstantBuilder cb(inst->GetParent()->GetParent()); auto count = input0_type.GetTotalNumOfElements(); Constant* c_input0 = DynCast<Constant>(inst->GetOperand(0).GetOwner()); size_t copy_size = count * c_input0->GetElementSizeInBytes(); std::vector<char> buf(num_inputs * copy_size); for (int i = 0; i < num_inputs; ++i) { Constant* c_input_i = DynCast<Constant>(inst->GetOperand(i).GetOwner()); memcpy(&buf[copy_size * i], c_input_i->GetRawDataPtr(), copy_size); } halo::Type result_type{input0_type.GetDataType(), ret_shape}; auto new_def = cb.CreateConstant(inst->GetName() + "_folding", result_type, buf.data()); return {orig_def, *new_def}; } std::pair<Def, Def> InstSimplify::RunOnInstruction(ZExtInst* inst) { Def orig_def{inst, 0}; DataType ret_dt = inst->GetDataType(); auto op0 = inst->GetOperand(0); const auto& op0_type = op0.GetType(); DataType src_dt = op0_type.GetDataType(); HLCHECK(halo::Type::IsIntegerType(src_dt) && halo::Type::IsIntegerType(ret_dt)); if (!op0_type.IsValid() || !IsA<Constant>(op0)) { return {orig_def, orig_def}; } ConstantBuilder cb(inst->GetParent()->GetParent()); Constant* c_src = DynCast<Constant>(op0.GetOwner()); if (ret_dt == DataType::INT32 && src_dt == DataType::BOOL) { std::vector<int> ret; ret.reserve(op0_type.GetTotalNumOfElements()); for (int i = 0; i < op0_type.GetTotalNumOfElements(); ++i) { ret.push_back(static_cast<int>(c_src->GetData<int8_t>(i))); } Constant* c_ret = cb.CreateConstant( inst->GetName(), halo::Type{ret_dt, op0_type.GetDimSizes()}, ret.data()); return {orig_def, *c_ret}; } if (ret_dt == DataType::INT32 && src_dt == DataType::INT64) { std::vector<int32_t> ret; ret.reserve(op0_type.GetTotalNumOfElements()); for (int i = 0, e = op0_type.GetTotalNumOfElements(); i != e; ++i) { ret.push_back(static_cast<int32_t>(c_src->GetData<int64_t>(i))); } Constant* c_ret = cb.CreateConstant( inst->GetName() + "_folding", halo::Type{ret_dt, op0_type.GetDimSizes()}, ret.data()); return {orig_def, *c_ret}; } if (ret_dt == DataType::INT64 && src_dt == DataType::INT32) { std::vector<int64_t> ret; ret.reserve(op0_type.GetTotalNumOfElements()); for (int i = 0, e = op0_type.GetTotalNumOfElements(); i != e; ++i) { ret.push_back(static_cast<int64_t>(c_src->GetData<int32_t>(i))); } Constant* c_ret = cb.CreateConstant( inst->GetName() + "_folding", halo::Type{ret_dt, op0_type.GetDimSizes()}, ret.data()); return {orig_def, *c_ret}; } return {orig_def, orig_def}; } std::pair<Def, Def> InstSimplify::RunOnInstruction(RangeInst* inst) { Def orig_def{inst, 0}; auto op0 = inst->GetOperand(0); auto op1 = inst->GetOperand(1); auto op2 = inst->GetOperand(2); DataType dt = op0.GetType().GetDataType(); if (!IsA<Constant>(op0.GetOwner()) || !IsA<Constant>(op1.GetOwner()) || !IsA<Constant>(op2.GetOwner()) || dt != DataType::INT32) { return {orig_def, orig_def}; } int64_t num_elements = 0; Constant* c_op0 = DynCast<Constant>(op0.GetOwner()); Constant* c_op1 = DynCast<Constant>(op1.GetOwner()); Constant* c_op2 = DynCast<Constant>(op2.GetOwner()); int begin = c_op0->GetData<int32_t>(0); int end = c_op1->GetData<int32_t>(0); int step = c_op2->GetData<int32_t>(0); num_elements = std::max(0, (end - begin) / step); HLCHECK(num_elements); std::vector<int> ret_data(num_elements); ret_data[0] = begin; for (int i = 1; i < num_elements; ++i) { ret_data[i] = ret_data[i - 1] + step; } ConstantBuilder cb(inst->GetParent()->GetParent()); Constant* c_ret = cb.CreateConstant(inst->GetName() + "_folding", halo::Type{dt, {num_elements}}, ret_data.data()); return {orig_def, *c_ret}; } std::pair<Def, Def> InstSimplify::RunOnInstruction(SetDiff1DInst* inst) { Def orig_def{inst, 0}; auto op0 = inst->GetOperand(0); auto op1 = inst->GetOperand(1); const auto& op0_type = op0.GetType(); const auto& op1_type = op1.GetType(); DataType dt = op0_type.GetDataType(); if (!IsA<Constant>(op0.GetOwner()) || !IsA<Constant>(op1.GetOwner()) || dt != DataType::INT32) { return {orig_def, orig_def}; } std::vector<int> ret_data; std::unordered_set<int> diff_set; Constant* c_op0 = DynCast<Constant>(op0.GetOwner()); Constant* c_op1 = DynCast<Constant>(op1.GetOwner()); for (int i = 0, e = op1_type.GetTotalNumOfElements(); i != e; ++i) { diff_set.emplace(c_op1->GetData<int>(i)); } for (int i = 0, e = op0_type.GetTotalNumOfElements(); i != e; ++i) { int data_i = c_op0->GetData<int>(i); if (diff_set.count(data_i) == 0) { ret_data.push_back(data_i); } } ConstantBuilder cb(inst->GetParent()->GetParent()); Constant* c_ret = cb.CreateConstant( inst->GetName() + "_folding", halo::Type{dt, {static_cast<int64_t>(ret_data.size())}}, ret_data.data()); return {orig_def, *c_ret}; } std::pair<Def, Def> InstSimplify::RunOnInstruction(GatherInst* inst) { Def orig_def{inst, 0}; int axis = inst->GetAxis(); const auto& dst_type = inst->GetResultsTypes()[0]; const auto& type_op0 = inst->GetOperand(0).GetType(); const auto& op1 = inst->GetOperand(1); // Gather(data, ZExt(index, int64)) ==> Gather(data, index) if (IsA<Instruction>(op1) && DynCast<Instruction>(op1)->GetOpCode() == OpCode::ZEXT) { IRBuilder builder(inst->GetParent()); ZExtInst* zext = DynCast<ZExtInst>(op1.GetDef()); builder.SetInsertAfter(inst); auto ops = inst->GetOperands(); ops[1] = zext->GetOperand(0); auto new_inst = builder.Clone(*inst, ops); return {orig_def, *new_inst}; } if (!type_op0.IsValid()) { return {orig_def, orig_def}; } if (axis < 0) { axis += type_op0.GetNumOfDims(); } HLCHECK(axis >= 0 && axis < static_cast<int>(type_op0.GetNumOfDims())); for (size_t i = 0; i < inst->GetNumOfOperands(); ++i) { if (!IsA<Constant>(inst->GetOperand(i).GetOwner())) { return {orig_def, orig_def}; } } if (!dst_type.IsValid()) { return {orig_def, orig_def}; } Constant* c_op0 = DynCast<Constant>(inst->GetOperand(0).GetOwner()); const auto& type_op1 = inst->GetOperand(1).GetType(); Constant* c_op1 = DynCast<Constant>(inst->GetOperand(1).GetOwner()); DataType dt = dst_type.GetDataType(); DefaultDataLayout data_layout; size_t byte_per_element = data_layout.Bytes(dt); size_t bytes = byte_per_element * dst_type.GetTotalNumOfElements(); std::vector<unsigned char> buf(bytes); size_t per_copy_bytes = byte_per_element; auto dst_extends = GetExtends(dst_type.GetDimSizes()); auto src_extends = GetExtends(type_op0.GetDimSizes()); auto idx_extends = GetExtends(type_op1.GetDimSizes()); int64_t dst_rank = dst_type.GetNumOfDims(); if (dst_rank == 0 && dst_type.GetTotalNumOfElements() == 1) { dst_rank = 1; } int op1_rank = type_op1.GetNumOfDims(); if (op1_rank == 0 && type_op1.GetTotalNumOfElements() == 1) { op1_rank = 1; } for (int64_t dst_idx = 0, e = dst_type.GetTotalNumOfElements(); dst_idx < e; ++dst_idx) { // map dst_idx to src_idx. std::vector<int64_t> dst_dims(dst_rank); for (int64_t i = 0, k = dst_idx; k > 0 && i < dst_rank; ++i) { dst_dims[i] = k / dst_extends[i]; k -= dst_dims[i] * dst_extends[i]; } std::vector<int64_t> src_dims(type_op0.GetNumOfDims()); for (int i = 0; i < dst_rank; ++i) { if (i < axis) { src_dims[i] = dst_dims[i]; } else if (i >= (axis + op1_rank)) { src_dims[i - op1_rank + 1] = dst_dims[i]; } else { int64_t idx = std::inner_product(idx_extends.begin(), idx_extends.end(), dst_dims.begin() + axis, 0L); src_dims[axis] = c_op1->GetDataAsInt64(idx); } } int64_t src_idx = std::inner_product(src_dims.begin(), src_dims.end(), src_extends.begin(), 0L); unsigned char* src_ptr = static_cast<unsigned char*>(c_op0->GetRawDataPtr()) + // NOLINT. src_idx * per_copy_bytes; std::copy_n(src_ptr, per_copy_bytes, buf.begin() + dst_idx * per_copy_bytes); } ConstantBuilder cb(inst->GetParent()->GetParent()); Constant* c_ret = cb.CreateConstant(inst->GetName() + "_folding", dst_type, buf.data()); return {orig_def, *c_ret}; } std::pair<Def, Def> InstSimplify::RunOnInstruction(ConcatInst* inst) { Def orig_def{inst, 0}; // Concat(Transpose(A), Transpose(B),...) => Transpose(Concat(A, B)) std::vector<int> perm; size_t n = inst->GetNumOfOperands(); std::vector<Def> tr_ops; tr_ops.reserve(n); for (size_t i = 0; i < n; ++i) { auto op = inst->GetOperand(i); if (!IsA<Instruction>(op)) { break; } const Instruction* op_inst = DynCast<Instruction>(op); if (op_inst->GetOpCode() != OpCode::TRANSPOSE) { break; } const TransposeInst* tr = DynCast<const TransposeInst>(op_inst); if (i == 0) { perm = tr->GetPermutation(); } else if (perm != tr->GetPermutation()) { break; } tr_ops.push_back(tr->GetOperand(0)); } if (tr_ops.size() == n) { IRBuilder builder(inst->GetParent()); builder.SetInsertAfter(inst); auto new_concat = builder.CreateConcat(inst->GetName(), tr_ops); new_concat->SetAxis(perm[inst->GetAxis()]); TransposeInst* new_tr = builder.CreateTranspose(new_concat->GetName() + "_t", {*new_concat}); new_tr->SetPermutation(perm); return {orig_def, *new_tr}; } for (size_t i = 0; i < inst->GetNumOfOperands(); ++i) { if (!IsA<Constant>(inst->GetOperand(i).GetOwner())) { return {orig_def, orig_def}; } } int num_inputs = inst->GetN(); int axis = inst->GetAxis(); const auto& dst_type = inst->GetResultsTypes()[0]; if (!dst_type.IsValid() || axis != 0) { return {orig_def, orig_def}; } // Constant propagating on axis = 0 DataType dt = dst_type.GetDataType(); DefaultDataLayout data_layout; size_t byte_per_element = data_layout.Bytes(dt); size_t bytes = byte_per_element * dst_type.GetTotalNumOfElements(); std::vector<unsigned char> buf(bytes); size_t offset = 0; for (int i = 0; i < num_inputs; ++i) { auto input = inst->GetOperand(i); Constant* c_input = DynCast<Constant>(input.GetOwner()); size_t num_elements = input.GetType().GetTotalNumOfElements(); size_t copy_bytes = num_elements * byte_per_element; std::copy_n(static_cast<unsigned char*>(c_input->GetRawDataPtr()), copy_bytes, buf.begin() + offset); offset += copy_bytes; } ConstantBuilder cb(inst->GetParent()->GetParent()); Constant* c_ret = cb.CreateConstant(inst->GetName() + "_folding", dst_type, buf.data()); return {orig_def, *c_ret}; } std::pair<Def, Def> InstSimplify::RunOnInstruction(TransposeInst* inst) { Def orig_def{inst, 0}; std::pair<Def, Def> ret{orig_def, orig_def}; const auto& input = inst->GetOperand(0); // Fold constant perm op into attribute. if (inst->GetNumOfOperands() == 2 && IsA<Constant>(inst->GetOperand(1))) { const Constant* data = DynCast<Constant>(inst->GetOperand(1)); const auto& ty = data->GetResultType(); if (ty.GetDataType() == DataType::INT32) { const int32_t* ptr = data->GetDataPtr<int32_t>(); std::vector<int> perms(ptr, ptr + ty.GetTotalNumOfElements()); // NOLINT IRBuilder builder(inst->GetParent()); builder.SetInsertAfter(inst); TransposeInst* new_inst = builder.CreateTranspose(inst->GetName(), {input}); new_inst->SetPermutation(perms); ret.second = *new_inst; return ret; } } const auto& perm = inst->GetPermutation(); auto input_type = (input.GetDef()->GetResultsTypes()[input.GetIdx()]); int dims = -1; std::vector<int64_t> new_shape; std::vector<size_t> perm_strides; std::vector<size_t> orig_strides; if (input_type.IsValid()) { const auto& orig_shape = input_type.GetDimSizes(); dims = orig_shape.size(); HLCHECK(orig_shape.size() == inst->GetPermutation().size()); orig_strides = std::vector<size_t>(dims, 1); for (int i = dims - 2; i >= 0; --i) { orig_strides[i] = orig_strides[i + 1] * orig_shape[i + 1]; } new_shape = orig_shape; perm_strides = orig_strides; for (int i = 0; i < dims; ++i) { new_shape[i] = orig_shape[perm[i]]; perm_strides[i] = orig_strides[perm[i]]; } } if (IsA<Constant>(input)) { // Do transpose at compile time. auto orig = DynCast<Constant>(input.GetOwner()); ConstantBuilder cb(inst->GetParent()->GetParent()); const auto& type = orig->GetResultType(); std::vector<int> pos(dims); // tracks the position of dst tensor. size_t elem_size = orig->GetElementSizeInBytes(); size_t elem_cnt = type.GetTotalNumOfElements(); std::vector<char> buf(elem_size * elem_cnt); for (size_t i = 0; i < elem_cnt; ++i) { size_t offset = std::inner_product(pos.begin(), pos.end(), perm_strides.begin(), 0UL) * elem_size; const char* src = static_cast<const char*>(orig->GetRawDataPtr()) + offset; // NOLINT memcpy(&buf[i * elem_size], src, elem_size); int c = 1; for (int i = dims - 1; i >= 0 && c == 1; --i) { pos[i] += c; if (pos[i] >= new_shape[i]) { pos[i] = 0; } else { c = 0; } } } auto new_c = cb.CreateConstant(orig->GetName() + "_T", halo::Type{type.GetDataType(), new_shape}, buf.data()); ret.second = *new_c; return ret; } if (remove_input_transpose_ && input.GetUses().size() == 1) { if (IsA<Argument>(input)) { Argument* arg = DynCast<Argument>(input); const auto& orig_dims = input.GetType().GetDimSizes(); const auto& perms = inst->GetPermutation(); auto new_dims = orig_dims; for (int i = 0, e = orig_dims.size(); i < e; ++i) { new_dims[i] = orig_dims[perms[i]]; } halo::Type ty{input.GetType().GetDataType(), new_dims}; arg->SetType(ty); ret.second = input; return ret; } } // Transpose(Transpose(in, perm0), perm1) => Transpose(in, perm2) if (IsA<Instruction>(input) && (DynCast<Instruction>(input))->GetOpCode() == OpCode::TRANSPOSE) { const TransposeInst* t0 = DynCast<TransposeInst>(input.GetOwner()); const auto& perm0 = t0->GetPermutation(); HLCHECK(perm0.size() == perm.size()); auto new_perm = perm0; for (int i = 0, e = perm0.size(); i < e; ++i) { new_perm[i] = perm[perm0[i]]; } IRBuilder builder(inst->GetParent()); builder.SetInsertAfter(inst); TransposeInst* new_trans = builder.CreateTranspose(inst->GetName(), {t0->GetOperand(0)}); new_trans->SetPermutation(new_perm); ret.second = *new_trans; return ret; } // Check if it is a redundant permute (all other dims are 1) const auto& type = input.GetType(); const auto& out_type = inst->GetResultType(); if (type.IsValid() && out_type.IsValid()) { unsigned non_ones = 0; for (auto& d : type.GetDimSizes()) { non_ones += d == 1 ? 0 : 1; } if (non_ones == 1) { IRBuilder builder(inst->GetParent()); builder.SetInsertAfter(inst); ConstantBuilder cb(inst->GetParent()->GetParent()); halo::Type reshape_ty{DataType::INT64, {static_cast<int64_t>(out_type.GetNumOfDims())}}; auto shape = cb.CreateConstant(inst->GetName() + "_reshape", reshape_ty, out_type.GetDimSizes().data()); ReshapeInst* reshape = builder.CreateReshape(inst->GetName(), {input, *shape}); reshape->GetResultsTypes()[0] = out_type; ret.second = *reshape; return ret; } } // Check if a permutaton is redundant. bool is_redundant = true; for (int i = 0, e = perm.size(); i < e; ++i) { if (perm[i] != i) { is_redundant = false; break; } } if (is_redundant) { ret.second = inst->GetOperand(0); return ret; } // Transpose => Reshape if its' like (N, 1, H, W) => (N, H, W, 1) if (dims > 0) { const auto& orig_shape = input_type.GetDimSizes(); auto new_perm = perm; for (int i = 0, a = 0; i < dims; ++i, ++a) { if (orig_shape[i] == 1) { for (auto& v : new_perm) { if (v == a) { v = -1; // skip the dim } if (v > a) { --v; } } --a; } } bool reshapable = true; for (int i = 0, c = 0; i < dims && reshapable; ++i) { if (new_perm[i] >= 0) { if (new_perm[i] != c++) { reshapable = false; } } } if (reshapable) { IRBuilder builder(inst->GetParent()); builder.SetInsertAfter(inst); ConstantBuilder cb(inst->GetParent()->GetParent()); Constant* c_shape = cb.CreateConstant( inst->GetName() + "_shape", halo::Type{DataType::INT64, std::vector<int64_t>{dims}}, new_shape.data()); auto reshape = builder.CreateReshape(inst->GetName(), {inst->GetOperand(0), *c_shape}); reshape->GetResultsTypes()[0] = inst->GetResultType(); ret.second = *reshape; return ret; } } return ret; } std::pair<Def, Def> InstSimplify::RunOnInstruction(ReturnInst* inst) { Def orig_def{inst, 0}; if (!remove_output_transpose_) { return {orig_def, orig_def}; } for (int i = 0, e = inst->GetNumOfOperands(); i < e; ++i) { const auto& op = inst->GetOperand(i); if (IsA<Instruction>(op) && DynCast<Instruction>(op)->GetOpCode() == OpCode::TRANSPOSE) { inst->ReplaceOperandWith(i, DynCast<Instruction>(op)->GetOperand(0)); } } return {orig_def, orig_def}; } std::pair<Def, Def> InstSimplify::RunOnInstruction(RandomUniformInst* inst) { Def orig_def{inst, 0}; const auto& dst_type = inst->GetResultsTypes()[0]; if (dst_type.IsValid() && dst_type.GetDataType() == DataType::FLOAT32) { auto noe = dst_type.GetTotalNumOfElements(); float max_val = inst->GetMaxval(); float min_val = inst->GetMinval(); // int seed = inst->GetSeed(); std::vector<float> ret(noe); // std::random_device rd; // std::mt19937 gen(rd()); std::mt19937 gen(1234); // NOLINT std::uniform_real_distribution<> dis(min_val, max_val); for (int i = 0; i < noe; ++i) { ret[i] = dis(gen); } ConstantBuilder cb(inst->GetParent()->GetParent()); Constant* c_ret = cb.CreateConstant(inst->GetName() + "_folding", dst_type, ret.data()); return {orig_def, *c_ret}; } return {orig_def, orig_def}; } std::pair<Def, Def> InstSimplify::RunOnInstruction(SliceInst* inst) { Def orig_def{inst, 0}; auto op2 = inst->GetOperand(2); const auto& dst_type = inst->GetResultsTypes()[0]; if (dst_type.IsValid() && IsA<Constant>(op2.GetOwner())) { Constant* c_size = DynCast<Constant>(op2.GetOwner()); if (op2.GetType().GetDataType() == DataType::INT32) { int dim = op2.GetType().GetTotalNumOfElements(); std::vector<int> size_adj(dim); bool new_size = false; for (int i = 0; i != dim; ++i) { int size_i = c_size->GetData<int>(i); if (size_i == -1) { size_adj[i] = dst_type.GetNumOfElementsInDim(i); new_size = true; } else { size_adj[i] = size_i; } } if (new_size) { ConstantBuilder cb(inst->GetParent()->GetParent()); Constant* c_new_size = cb.CreateConstant( op2.GetOwner()->GetName() + "_adj", op2.GetType(), size_adj.data()); IRBuilder builder(inst->GetParent()); builder.SetInsertAfter(inst); SliceInst* new_inst = builder.CreateSlice( inst->GetName(), {inst->GetOperand(0), inst->GetOperand(1), *c_new_size}); new_inst->GetResultsTypes()[0] = dst_type; return {orig_def, *new_inst}; } } } auto op0 = inst->GetOperand(0); auto op1 = inst->GetOperand(1); bool has_constant_steps = (inst->GetNumOfOperands() < 4 || IsA<Constant>(inst->GetOperand(3))); has_constant_steps &= (inst->GetNumOfOperands() <= 4 || IsA<Constant>(inst->GetOperand(4))); if (IsA<Constant>(op0) && IsA<Constant>(op1) && IsA<Constant>(op2) && inst->GetResultType().IsValid() && has_constant_steps) { Constant* input = DynCast<Constant>(op0); const auto& dt = inst->GetResultType(); std::vector<int64_t> data(dt.GetTotalNumOfElements()); auto starts = DynCast<Constant>(op1); auto lens = DynCast<Constant>(op2); // auto steps = DynCast<Constant>(op3); // auto axes = DynCast<Constant>(op4); auto rank = op0.GetType().GetNumOfDims(); if (rank == 1 && dt.GetDataType() == DataType::INT64) { auto idx = starts->GetData<int32_t>(0); auto len = lens->GetData<int32_t>(0); HLCHECK(static_cast<size_t>(len) == data.size()); for (int i = 0; i < len; ++i) { data[i] = input->GetData<int64_t>(idx + i); } ConstantBuilder cb(inst->GetParent()->GetParent()); auto c = cb.CreateConstant(inst->GetName(), dt, data.data()); return {orig_def, *c}; } } return {orig_def, orig_def}; } std::pair<Def, Def> InstSimplify::RunOnInstruction(FPtoSIInst* inst) { Def orig_def{inst, 0}; auto op0 = inst->GetOperand(0); if (IsA<Constant>(op0)) { auto src_ty = op0.GetType().GetDataType(); auto dst_ty = inst->GetResultType().GetDataType(); ConstantBuilder cb(inst->GetParent()->GetParent()); Constant* input = DynCast<Constant>(op0); auto n = op0.GetType().GetTotalNumOfElements(); if (src_ty == DataType::FLOAT32 && (dst_ty == DataType::INT32 || dst_ty == DataType::INT64 || dst_ty == DataType::UINT32)) { Constant* c = nullptr; if (dst_ty == DataType::INT32) { std::vector<int32_t> vals(n); for (int64_t i = 0; i < n; ++i) { vals[i] = input->GetData<float>(i); } c = cb.CreateConstant(inst->GetName(), inst->GetResultType(), vals.data()); } else if (dst_ty == DataType::UINT32) { std::vector<uint32_t> vals(n); for (int64_t i = 0; i < n; ++i) { vals[i] = input->GetData<float>(i); } c = cb.CreateConstant(inst->GetName(), inst->GetResultType(), vals.data()); } else { std::vector<int64_t> vals(n); for (int64_t i = 0; i < n; ++i) { vals[i] = input->GetData<float>(i); } c = cb.CreateConstant(inst->GetName(), inst->GetResultType(), vals.data()); } return {orig_def, *c}; } } return {orig_def, orig_def}; } std::pair<Def, Def> InstSimplify::RunOnInstruction(SItoFPInst* inst) { Def orig_def{inst, 0}; auto op0 = inst->GetOperand(0); if (IsA<Instruction>(op0.GetOwner())) { Instruction* reshape_inst = DynCast<Instruction>(op0.GetOwner()); if (reshape_inst->GetOpCode() == OpCode::RESHAPE && reshape_inst->GetNumberOfUses() == 1) { auto op_reshape = reshape_inst->GetOperand(0); if (IsA<Argument>(op_reshape.GetOwner())) { Argument* arg = DynCast<Argument>(op_reshape.GetOwner()); if (arg->GetNumberOfUses() == 1 && op_reshape.GetType().IsValid()) { arg->SetType(halo::Type{DataType::FLOAT32, op_reshape.GetType().GetDimSizes()}); return {orig_def, *reshape_inst}; } } } } else if (IsA<Argument>(op0.GetOwner()) && op0.GetType().IsValid() && DynCast<Argument>(op0.GetOwner())->GetNumberOfUses() == 1) { Argument* arg = DynCast<Argument>(op0.GetOwner()); arg->SetType(halo::Type{DataType::FLOAT32, op0.GetType().GetDimSizes()}); return {orig_def, *arg}; } else if (IsA<Constant>(op0)) { auto src_ty = op0.GetType().GetDataType(); Constant* input = DynCast<Constant>(op0); auto n = op0.GetType().GetTotalNumOfElements(); if (inst->GetDataType() == DataType::FLOAT32 && (src_ty == DataType::INT32 || src_ty == DataType::INT64)) { std::vector<float> vals(n); for (int64_t i = 0; i < n; ++i) { vals[i] = (src_ty == DataType::INT32) ? input->GetData<int32_t>(i) : input->GetData<int64_t>(i); } ConstantBuilder cb(inst->GetParent()->GetParent()); auto c = cb.CreateConstant(inst->GetName(), inst->GetResultType(), vals.data()); return {orig_def, *c}; } } return {orig_def, orig_def}; } std::pair<Def, Def> InstSimplify::RunOnInstruction(OneHotInst* inst) { Def orig_def{inst, 0}; // work around on cxx target when backend doens't support onehot. if (!simplify_for_preprocess_) { return {orig_def, orig_def}; } auto on_value = inst->GetOperand(2); auto off_value = inst->GetOperand(3); const auto& dst_type = inst->GetResultsTypes()[0]; if (!IsA<Constant>(on_value.GetOwner()) || !IsA<Constant>(off_value.GetOwner()) || !dst_type.IsValid()) { return {orig_def, orig_def}; } auto op0 = inst->GetOperand(0); if (IsA<Instruction>(op0.GetOwner())) { Instruction* reshape_inst = DynCast<Instruction>(op0.GetOwner()); if (reshape_inst->GetOpCode() == OpCode::RESHAPE && reshape_inst->GetNumberOfUses() == 1) { auto op_reshape = reshape_inst->GetOperand(0); if (IsA<Argument>(op_reshape.GetOwner())) { Argument* arg = DynCast<Argument>(op_reshape.GetOwner()); if (arg->GetNumberOfUses() == 1 && op_reshape.GetType().IsValid()) { arg->SetType(halo::Type{on_value.GetType().GetDataType(), dst_type.GetDimSizes()}); return {orig_def, *arg}; } } } } else if (IsA<Argument>(op0.GetOwner()) && op0.GetType().IsValid() && DynCast<Argument>(op0.GetOwner())->GetNumberOfUses() == 1) { Argument* arg = DynCast<Argument>(op0.GetOwner()); arg->SetType( halo::Type{on_value.GetType().GetDataType(), dst_type.GetDimSizes()}); return {orig_def, *arg}; } return {orig_def, orig_def}; } bool InstSimplify::RunOnBasicBlock(BasicBlock* bb) { bool changed = false; for (auto& inst_t : *bb) { Instruction* inst = inst_t.get(); if (inst->GetNumberOfUses() == 0) { if (inst->GetOpCode() == OpCode::RETURN) { RunOnInstruction(DynCast<ReturnInst>(inst)); } continue; } std::pair<Def, Def> ret{Def{inst, 0}, Def{inst, 0}}; switch (inst->GetOpCode()) { #define GET_INST_DOWNCAST_SWITCH_WITH_RETURN #include "halo/lib/ir/instructions_info.def" #undef GET_INST_DOWNCAST_SWITCH_WITH_RETURN default: { // skip extension instruction. continue; } } if (ret.first != ret.second) { changed |= true; if (ret.second.GetOwner() != nullptr) { // Replace all uses inst->ReplaceAllUsesWith(ret.first.GetIdx(), ret.second); } } } return changed; } } // end namespace halo
71,965
26,137
#ifndef RANDOM_AGENT_H #define RANDOM_AGENT_H #include <random> #include "bboard.hpp" #include "strategy.hpp" namespace agents { /** * Use this as an example to implement more sophisticated * agents. * * @brief Randomly selects actions */ struct RandomAgent : bboard::Agent { std::mt19937_64 rng; std::uniform_int_distribution<int> intDist; RandomAgent(); bboard::Move act(const bboard::State* state) override; }; /** * @brief Randomly selects actions that are not laying bombs */ struct HarmlessAgent : bboard::Agent { std::mt19937_64 rng; std::uniform_int_distribution<int> intDist; HarmlessAgent(); bboard::Move act(const bboard::State* state) override; }; /** * @brief Selects Idle for every action */ struct LazyAgent : bboard::Agent { bboard::Move act(const bboard::State* state) override; }; /** * @brief Handcrafted agent by m2q */ struct SimpleAgent : bboard::Agent { std::mt19937_64 rng; SimpleAgent(); SimpleAgent(long seed); ////////////// // Specific // ////////////// int danger = 0; bboard::strategy::RMap r; bboard::FixedQueue<bboard::Move, bboard::MOVE_COUNT> moveQueue; // capacity of recent positions static const int rpCapacity = 4; bboard::FixedQueue<bboard::Position, rpCapacity> recentPositions; virtual bboard::Move decide(const bboard::State* state); bboard::Move act(const bboard::State* state) override; void reset() override; void PrintDetailedInfo(); }; /** * @brief An improved version of SimpleAgent. Adds more randomization to get equal win rates and collects powerups. * Also includes adjustments of parameters to (hopefully) result in better gameplay. */ struct SimpleUnbiasedAgent : SimpleAgent { std::array<int, 4> agentAxis; std::array<bboard::Move, bboard::MOVE_COUNT> dirAxis; std::array<int, bboard::BOARD_SIZE> boardAxisX; std::array<int, bboard::BOARD_SIZE> boardAxisY; SimpleUnbiasedAgent(); SimpleUnbiasedAgent(long seed); bboard::Move decide(const bboard::State* state) override; void reset() override; }; } #endif
2,131
719
// // pragma.hpp // SimpleDB // // Created by lifeng on 2019/6/5. // Copyright © 2019 feng. All rights reserved. // #ifndef pragma_hpp #define pragma_hpp #include "declare.hpp" #include "describable.hpp" namespace SDB { class Pragma : public Describable { public: static const Pragma application_id; static const Pragma auto_vacuum; static const Pragma automatic_index; static const Pragma busy_timeout; static const Pragma cache_size; static const Pragma cache_spill; static const Pragma case_sensitive_like; static const Pragma cell_size_check; static const Pragma checkpoint_fullfsync; static const Pragma cipher; static const Pragma cipher_add_random; static const Pragma cipher_default_kdf_iter; static const Pragma cipher_default_page_size; static const Pragma cipher_page_size; static const Pragma cipher_default_use_hmac; static const Pragma cipher_migrate; static const Pragma cipher_profile; static const Pragma cipher_provider; static const Pragma cipher_provider_version; static const Pragma cipher_use_hmac; static const Pragma cipher_version; static const Pragma collation_list; static const Pragma compile_options; static const Pragma count_changes; static const Pragma data_store_directory; static const Pragma data_version; static const Pragma database_list; static const Pragma default_cache_size; static const Pragma defer_foreign_keys; static const Pragma empty_result_callbacks; static const Pragma encoding; static const Pragma foreign_key_check; static const Pragma foreign_key_list; static const Pragma foreign_keys; static const Pragma freelist_count; static const Pragma full_column_names; static const Pragma fullfsync; static const Pragma ignore_check_constraints; static const Pragma incremental_vacuum; static const Pragma index_info; static const Pragma index_list; static const Pragma index_xinfo; static const Pragma integrity_check; static const Pragma journal_mode; static const Pragma journal_size_limit; static const Pragma key; static const Pragma kdf_iter; static const Pragma legacy_file_format; static const Pragma locking_mode; static const Pragma max_page_count; static const Pragma mmap_size; static const Pragma page_count; static const Pragma page_size; static const Pragma parser_trace; static const Pragma query_only; static const Pragma quick_check; static const Pragma read_uncommitted; static const Pragma recursive_triggers; static const Pragma rekey; static const Pragma reverse_unordered_selects; static const Pragma schema_version; static const Pragma secure_delete; static const Pragma short_column_names; static const Pragma shrink_memory; static const Pragma soft_heap_limit; static const Pragma stats; static const Pragma synchronous; static const Pragma table_info; static const Pragma temp_store; static const Pragma temp_store_directory; static const Pragma threads; static const Pragma user_version; static const Pragma vdbe_addoptrace; static const Pragma vdbe_debug; static const Pragma vdbe_listing; static const Pragma vdbe_trace; static const Pragma wal_autocheckpoint; static const Pragma wal_checkpoint; static const Pragma writable_schema; const std::string &name(void) const; protected: Pragma(const char *name); }; } #endif /* pragma_hpp */
3,914
1,058
// Jopnal Engine C++ Library // Copyright (c) 2016 Team Jopnal // // 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 acknowledgement 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. ////////////////////////////////////////////// #ifndef GP_FILELOADER_HPP #define GP_FILELOADER_HPP // Headers #include <Jopnal/Header.hpp> #include <Jopnal/Core/Subsystem.hpp> #include <string> #include <vector> ////////////////////////////////////////////// struct PHYSFS_File; namespace Assimp { class Importer; } namespace jop { class JOP_API FileSystemInitializer final : public Subsystem { private: JOP_DISALLOW_COPY_MOVE(FileSystemInitializer); friend class ModelLoader; static Assimp::Importer& getImporter(); public: FileSystemInitializer(const char* arg); ~FileSystemInitializer(); }; class JOP_API FileLoader { private: JOP_DISALLOW_COPY(FileLoader); public: /// Base directory for writing files /// enum class Directory { Executable, ///< Executable directory Resource, ///< Resource folder User ///< User folder }; public: /// \brief Default constructor /// /// Doesn't initialize any file handles. /// FileLoader(); /// \brief Overloaded constructor /// /// This will open the file for writing if found /// /// \param path Path to file to open /// /// \see isValid /// explicit FileLoader(const std::string& path); /// \brief Overloaded constructor /// /// This will open the file for writing if found. /// /// \param dir Base write directory /// \param path Path to file to open /// \param append Append to the file. False to clear the file before writing /// /// \see isValid /// FileLoader(const Directory dir, const std::string& path, const bool append); /// \brief Move constructor /// FileLoader(FileLoader&& other); /// \brief Move assignment operator /// /// \return Reference to self /// FileLoader& operator =(FileLoader&& other); /// \brief Destructor /// /// Will close the file handle if open. /// ~FileLoader(); /// \brief Open a file for reading /// /// \param path Path to the file /// /// \return True if opened successfully /// bool open(const std::string& path); /// \brief Open a file for writing /// /// \copydetails FileLoader(const Directory, const std::string&, const bool) /// /// \return True if opened successfully /// bool open(const Directory dir, const std::string& path, const bool append); /// \brief Flush the file handle if open /// void flush(); /// \brief Close the file handle if open /// /// When writing, calling this means saving the file. /// void close(); /// \brief Check if a file handle exists /// /// \return True if a valid file handle exists /// bool isValid() const; /// \brief Read data /// /// \param data Pointer to a pre-allocated data buffer /// \param size Amount of data to read /// /// \return Amount of data read in bytes /// /// \see getSize /// int64 read(void* data, const uint64 size); /// \brief Write data /// /// \param data Data to write /// \param size Amount of data to write in bytes /// /// \return Amount of data written in bytes /// int64 write(const void* data, const uint64 size); /// \brief Move the cursor to the given position /// /// \param position The cursor position to set /// /// \return True if successful /// bool seek(const uint64 position); /// \brief Get the current position of the cursor /// /// \return Current position of the file read/write cursor /// int64 tell(); /// \brief Get the size of the opened file /// /// \return Size of the file /// int64 getSize(); /// \copydoc isValid /// operator bool() const; /// \brief Check if a file exists /// /// \param path Path to the file to check /// /// \return True if the file exists /// static bool fileExists(const std::string& path); /// \brief Enumerate all files within a directory /// /// \param path Path to a directory /// \param list Reference to a list to fill with the file paths found /// /// \see listFilesRecursive /// static void listFiles(const std::string& path, std::vector<std::string>& list); /// \brief Enumerate all files within a directory recursively /// /// \param path Path to a directory /// \param list Reference to a list to fill with the file paths found /// /// \see listFiles /// static void listFilesRecursive(const std::string& path, std::vector<std::string>& list); /// \brief Delete a file /// /// \param file Path to the file /// /// \return True if file was deleted /// static bool deleteFile(const std::string& file); /// \brief Read a text file /// /// \param path Path to the file to read /// \param file Reference to a string to fill with the data /// /// \return True if successful /// static bool readTextfile(const std::string& path, std::string& file); /// \brief Read a binary file /// /// \param path Path to the file to read /// \param buffer Reference to a buffer to fill with the data /// /// \return True if successful /// static bool readBinaryfile(const std::string& path, std::vector<uint8>& buffer); /// \brief Write a text file /// /// \param dir The base write directory /// \param path The file path /// \param text The text to write /// \param append Append to file? /// /// \return True if successful /// static bool writeTextfile(const Directory dir, const std::string& path, const std::string& text, const bool append = false); /// \brief Write a binary file /// /// \param dir The base write directory /// \param path The file path /// \param data The binary data to write /// \param bytes amount of bytes to write /// \param append Append to file? /// /// \return True if successful /// static bool writeBinaryfile(const Directory dir, const std::string& path, const void* data, const std::size_t bytes, const bool append = false); /// \brief Create a directory /// /// If the directory already exists, this has no effect. /// /// \param path The directory to create /// /// \return True if successful /// static bool makeDirectory(const std::string& path); /// \brief Get a base directory as string /// /// \param dir The base directory /// /// \return Internal reference to the directory string /// static const std::string& getDirectory(const Directory dir); /// \brief Get the OS-specific directory separator /// /// \return The directory separator /// static char getDirectorySeparator(); /// \brief Read a resource file /// /// This is mostly used internally. /// /// \param id Identifier of the resource /// \param buffer The data buffer /// /// \return True if successful /// static bool readResource(const int id, std::vector<uint8>& buffer); /// \brief Enable/disable file system error checks /// /// \param enable True to enable /// static void enableErrorChecks(const bool enable); /// \brief Check if file system error checks are enabled /// /// \return True if enabled /// static bool errorChecksEnabled(); private: PHYSFS_File* m_file; ///< File handle }; } #endif
9,465
2,365
#include "onewire.h" #include "hardware_defs.h" OneWire::OneWire(GPIO_Basic *gpio){ this->gpio = gpio; reset_search(); } // Perform the onewire reset function. We will wait up to 250uS for // the bus to come high, if it doesn't then it is broken or shorted // and we return a 0; // // Returns 1 if a device asserted a presence pulse, 0 otherwise. // uint8_t OneWire::reset(void){ uint8_t r; uint8_t retries = 125; gpio->mode(GPIO_MODE_INPUT); // wait until the wire is high... just in case do { if (--retries == 0) return 0; delay_us(2); } while ( !gpio->read()); disable_interrupts(); //Invertida as linhas abaixo gpio->mode(GPIO_MODE_OUTPUT); gpio->write(0); enable_interrupts(); delay_us(480); disable_interrupts(); gpio->mode(GPIO_MODE_INPUT); delay_us(70); r = !gpio->read(); enable_interrupts(); delay_us(410); return r; } // // Write a bit. Port and bit is used to cut lookup time and provide // more certain timing. // void OneWire::write_bit(uint8_t v) { if (v & 1) { disable_interrupts(); gpio->mode(GPIO_MODE_OUTPUT); gpio->write(0); delay_us(10); gpio->write(1); enable_interrupts(); delay_us(55); } else { disable_interrupts(); gpio->mode(GPIO_MODE_OUTPUT); gpio->write(0); delay_us(65); gpio->write(1); enable_interrupts(); delay_us(5); } } // // Read a bit. Port and bit is used to cut lookup time and provide // more certain timing. // uint8_t OneWire::read_bit(void) { uint8_t r; disable_interrupts(); gpio->mode(GPIO_MODE_OUTPUT); gpio->write(0); delay_us(3); gpio->mode(GPIO_MODE_INPUT); delay_us(10); r = gpio->read(); enable_interrupts(); delay_us(53); return r; } // // Write a byte. The writing code uses the active drivers to raise the // pin high, if you need power after the write (e.g. DS18S20 in // parasite power mode) then set 'power' to 1, otherwise the pin will // go tri-state at the end of the write to avoid heating in a short or // other mishap. // void OneWire::write(uint8_t v, uint8_t power /* = 0 */) { uint8_t bitMask; for (bitMask = 0x01; bitMask; bitMask <<= 1) { write_bit( (bitMask & v)?1:0); } if ( !power) { disable_interrupts(); gpio->mode(GPIO_MODE_INPUT); gpio->write(0); enable_interrupts(); } } void OneWire::write_bytes(const uint8_t *buf, uint16_t count, bool power /* = 0 */) { for (uint16_t i = 0 ; i < count ; i++) write(buf[i]); if (!power) { disable_interrupts(); gpio->mode(GPIO_MODE_INPUT); gpio->write(0); enable_interrupts(); } } // // Read a byte // uint8_t OneWire::read() { uint8_t bitMask; uint8_t r = 0; for (bitMask = 0x01; bitMask; bitMask <<= 1) { if ( OneWire::read_bit()) r |= bitMask; } return r; } void OneWire::read_bytes(uint8_t *buf, uint16_t count) { for (uint16_t i = 0 ; i < count ; i++) buf[i] = read(); } // // Do a ROM select // void OneWire::select(const uint8_t rom[8]){ uint8_t i; write(MATCH_ROM); // Choose ROM for (i = 0; i < 8; i++) write(rom[i]); } // // Do a ROM skip // void OneWire::skip(){ write(SKIP_ROM); // Skip ROM } void OneWire::depower(){ gpio->mode(GPIO_MODE_INPUT); } // // You need to use this function to start a search again from the beginning. // You do not need to do it for the first search, though you could. // void OneWire::reset_search() { // reset the search state LastDiscrepancy = 0; LastDeviceFlag = FALSE; LastFamilyDiscrepancy = 0; for(int i = 7; ; i--) { ROM_NO[i] = 0; if ( i == 0) break; } } // Setup the search to find the device type 'family_code' on the next call // to search(*newAddr) if it is present. // void OneWire::target_search(uint8_t family_code){ // set the search state to find SearchFamily type devices ROM_NO[0] = family_code; for (uint8_t i = 1; i < 8; i++) ROM_NO[i] = 0; LastDiscrepancy = 64; LastFamilyDiscrepancy = 0; LastDeviceFlag = FALSE; } // // Perform a search. If this function returns a '1' then it has // enumerated the next device and you may retrieve the ROM from the // OneWire::address variable. If there are no devices, no further // devices, or something horrible happens in the middle of the // enumeration then a 0 is returned. If a new device is found then // its address is copied to newAddr. Use OneWire::reset_search() to // start over. // // --- Replaced by the one from the Dallas Semiconductor web site --- //-------------------------------------------------------------------------- // Perform the 1-Wire Search Algorithm on the 1-Wire bus using the existing // search state. // Return TRUE : device found, ROM number in ROM_NO buffer // FALSE : device not found, end of search // uint8_t OneWire::search(uint8_t *newAddr) { uint8_t id_bit_number; uint8_t last_zero, rom_byte_number, search_result; uint8_t id_bit, cmp_id_bit; unsigned char rom_byte_mask, search_direction; // initialize for search id_bit_number = 1; last_zero = 0; rom_byte_number = 0; rom_byte_mask = 1; search_result = 0; // if the last call was not the last one if (!LastDeviceFlag){ // 1-Wire reset if (!reset()){ // reset the search LastDiscrepancy = 0; LastDeviceFlag = FALSE; LastFamilyDiscrepancy = 0; return FALSE; } // issue the search command write(SEARCH_ROM); // loop to do the search do{ // read a bit and its complement id_bit = read_bit(); cmp_id_bit = read_bit(); // check for no devices on 1-wire if ((id_bit == 1) && (cmp_id_bit == 1)) break; else{ // all devices coupled have 0 or 1 if (id_bit != cmp_id_bit) search_direction = id_bit; // bit write value for search else{ // if this discrepancy if before the Last Discrepancy // on a previous next then pick the same as last time if (id_bit_number < LastDiscrepancy) search_direction = ((ROM_NO[rom_byte_number] & rom_byte_mask) > 0); else // if equal to last pick 1, if not then pick 0 search_direction = (id_bit_number == LastDiscrepancy); // if 0 was picked then record its position in LastZero if (search_direction == 0){ last_zero = id_bit_number; // check for Last discrepancy in family if (last_zero < 9) LastFamilyDiscrepancy = last_zero; } } // set or clear the bit in the ROM byte rom_byte_number // with mask rom_byte_mask if (search_direction == 1) ROM_NO[rom_byte_number] |= rom_byte_mask; else ROM_NO[rom_byte_number] &= ~rom_byte_mask; // serial number search direction write bit write_bit(search_direction); // increment the byte counter id_bit_number // and shift the mask rom_byte_mask id_bit_number++; rom_byte_mask <<= 1; // if the mask is 0 then go to new SerialNum byte rom_byte_number and reset mask if (rom_byte_mask == 0){ rom_byte_number++; rom_byte_mask = 1; } } }while(rom_byte_number < 8); // loop until through all ROM bytes 0-7 // if the search was successful then if (!(id_bit_number < 65)){ // search successful so set LastDiscrepancy,LastDeviceFlag,search_result LastDiscrepancy = last_zero; // check for last device if (LastDiscrepancy == 0) LastDeviceFlag = TRUE; search_result = TRUE; } } // if no device found then reset counters so next 'search' will be like a first if (!search_result || !ROM_NO[0]){ LastDiscrepancy = 0; LastDeviceFlag = FALSE; LastFamilyDiscrepancy = 0; search_result = FALSE; } for (int i = 0; i < 8; i++) newAddr[i] = ROM_NO[i]; return search_result; }
7,498
3,098
// Copyright (c) 2017-2021, Lawrence Livermore National Security, LLC and // other Axom Project Developers. See the top-level LICENSE file for details. // // SPDX-License-Identifier: (BSD-3-Clause) #ifndef MINT_MESH_HPP_ #define MINT_MESH_HPP_ #include "axom/core/Macros.hpp" // for Axom macros #include "axom/mint/mesh/CellTypes.hpp" // for CellType enum #include "axom/mint/config.hpp" // for mint compile-time type #include "axom/mint/mesh/FieldAssociation.hpp" // for FieldAssociation enum #include "axom/mint/mesh/FieldData.hpp" // for mint::FieldData #include "axom/mint/mesh/MeshCoordinates.hpp" // for mint::MeshCoordinates #include "axom/mint/mesh/MeshTypes.hpp" // for MeshType enum #include "axom/slic/interface/slic.hpp" // for SLIC macros namespace axom { /* Forward declarations */ #ifdef AXOM_MINT_USE_SIDRE namespace sidre { class Group; } #endif namespace mint { /* Forward declarations */ class Field; class Mesh; /// \name Free Methods /// @{ #ifdef AXOM_MINT_USE_SIDRE /*! * \brief Creates a mesh instance from the given Sidre group. * * \param [in] group pointer to the root group of the mesh in Sidre. * \param [in] topo topology associated with the requested mesh (optional) * * \return m pointer to a mesh instance corresponding to the specified group. * * \note If a topology name is not provided, the implementation will construct * a mesh based on the 1st topology group under the parent "topologies" * group. * * \note Ownership of the resulting mesh object is passed to the caller. * * \note When using Mint with Sidre, Sidre maintains ownership of the data. * Although the data can be modified via calls to Mint, groups and views * cannot be deleted. The data remains persistent in Sidre once the mesh * object goes out-of-scope. * * \pre group != nullptr * \pre blueprint::isValidRootGroup( group ) == true * \post m != nullptr */ Mesh* getMesh(sidre::Group* group, const std::string& topo = ""); #endif /// @} /*! * \class Mesh * * \brief Base class that defines the core API common to all Mesh types. * * A Mesh, \f$ \mathcal{M}(\Omega) \f$, provides an approximation of a physical * domain, \f$ \Omega \in \mathcal{R}^d \f$, where \f$ d \in [1,3] \f$ . The * Mesh is essentially a discrete representation of a problem and is used to * facilitate the analysis, e.g., FEA, CFD, etc. The solution domain is * approximated by dividing it into a finite number of <em> nodes </em> and * <em> cells </em> at which the variables of the underlying mathematical model * (i.e., a PDE) are then computed via a numerical method, such as, * Finite Difference (FD), Finite Volume (FV) or Finite Element (FE), chief * among them. * * There are a variety of mesh types. Mint supports the following mesh types: * * * <b> Structured (Curvilinear) Mesh </b> <br /> * * A <em> structured mesh </em> divides the solution domain according to a * logical grid where each node/cell of the mesh can be uniquely identified * by a corresponding logical ijk-index. The nodes of the mesh are found at * the intersection of the grid lines, but, are explicitly defined via a * mapping onto the physical Cartesian coordinate system of the domain. For * this reason, these types of meshes are also called <em> mapped </em> or * <em> body-fitted </em> meshes. * * However, the mesh topology (e.g., connectivity, neighbor information) is * implicitly defined by the logical indexing scheme. For example, a * structured mesh is composed of <em> quadrilateral </em> cells in 2-D and * <em> hexahedron </em> cells in 3-D. Given the logical index of a cell * one can compute the node indices of the cell and neighbor information by * performing simple shift operations on the associated index. * * * <b> Rectilinear Mesh </b> <br /> * * A <em> rectilinear mesh </em>, also known as a product mesh, is similar * to the <em> structured mesh </em> in that it is also defined according to * a logical indexing scheme and has implicit topology. * * However, the nodes and cells on a <em> rectilinear mesh </em> are arranged * on a regular lattice that is axis-aligned with the Cartesian coordinate * system. In contrast to the general <em> structured mesh </em>, the * <em> rectilinear mesh </em> does not explicitly define **all** the nodes * of the mesh. Instead, the nodes are only defined along each coordinate * axis and may have variable spacing between nodes. Given a logical index, * the corresponding physical position of a node can be evaluated by taking * the cartesian product of the corresponding coordinate along each * coordinate axis. * * * <b> Uniform Mesh </b> <br /> * * A <em> uniform mesh </em>, also called a regular mesh, subdivides the * domain in cells that have uniform spacing across each coordinate axis. * Similar to the <em> structured mesh </em>, a <em> uniform mesh </em> * adheres to the same logical indexing scheme and implicit topology * representation. Moreover, The nodes and cells of a <em> uniform </em> mesh * are arranged on a regular lattice as with the <em> rectilinear mesh </em>. * However, both topology and geometry is implicitly defined on a * <em> uniform mesh </em>. The geometry is solely defined by an origin, * \f$ \hat{x_0} \f$ and spacing, \f$ \hat{h} \f$, along each axis. The * coordinates of a node can be evaluated algebraically by the following: * \f$ \hat{p} = \hat{x_0} + \hat{i} \times \hat{h} \f$, where \f$\hat{i}\f$ * is the logical ijk-index of the corresponding node. * * * <b> Unstructured Mesh </b> <br /> * * An <em> unstructured mesh </em> stores both node and topology information * explicitly. This allows the flexibility of discretizing the solution * domain using a variety of cell types not just quadrilateral (in 2D) or * hexahedral (in 3D) cells. Due to this added flexibility, the use of * <em> unstructured meshes </em> is more common when dealing with complex * geometries. However, <em> unstructured meshes </em> require additional * storage and generally incur some performance penalty to store, create and * access mesh topology information respectively. * * Mint classifies <em> unstructured meshes </em> in two basic types based on * the underlying mesh topology: * * * <b> Single Cell Topology </b> * * In this case, the <em> unstructured mesh </em> consists of a single cell * type, e.g., a quad or triangle mesh in 2D, or, a hex or tet mesh in 3D. * In this case the underlying implementation is optimized for the * specified cell type (specified in the constructor). * * * <b> Mixed Cell Topology </b> * * When <em> mixed cell topology </em> is specified, the <em> unstructured * mesh </em> can be composed of any of the supported cell types, e.g., * a mesh consisting of both quads and triangles. This mode incurs * additional overhead for storage and access to mesh topology information, * since it requires indirection. * * The list of supported cell types for an <em> unstructured mesh </em> is * available in CellTypes.hpp * * * <b> Particle Mesh </b> <br /> * * A <em> particle mesh </em> discretizes the solution domain using * a set of discrete particle elements which correspond to the the nodes * of the mesh. There is no ordering imposed on the particles and the * coordinates of the particles are explicitly defined. A particle mesh * has no connectivity information connecting the particles, which is why * in literature methods using a particle discretization are also referred * to as <em> meshless </em> or <em> meshfree </em> methods. * * The Mesh class provides the means to create, access and remove fields on * a mesh given the field name and its association. The field association * designates the corresponding mesh entity at which the field is stored, e.g. * whether the field is stored at the nodes or cell centers. A Field may be a * scalar quantity, e.g., pressure, or a vector field, such as, velocity. * * \warning When using Sidre, field names have to be unique. For example, if * there exists a "pressure" node-centered field, there cannot be a * corresponding cell-centered field. * * \note Mesh is a base class and cannot be instantiated directly * * \note Typically, the computational mesh can be defined across one or more * <em> blocks </em>, e.g., for multi-block problems, where each block is * subsequently decomposed into several <em> partitions </em> for parallel * computation. A Mesh instance represents a <em> single </em> partition for * a given block. * * \see mint::UnstructuredMesh * \see mint::StructuredMesh * \see mint::CurvilinearMesh * \see mint::RectilinearMesh * \see mint::UniformMesh * \see mint::Field * \see mint::FieldData * \see mint::MeshTypes */ class Mesh { public: /*! * \brief Default constructor. Disabled. */ Mesh() = delete; /// \name Virtual methods /// @{ /*! * \brief Destructor. */ virtual ~Mesh(); /// \name Cells /// @{ /*! * \brief Returns the number of cells in this mesh instance. * \return N the number of cells * \post N >= 0 */ virtual IndexType getNumberOfCells() const = 0; /*! * \brief Returns the capacity for number of cell in this mesh instance. * \return N the cell capacity * \post N >= 0 */ virtual IndexType getCellCapacity() const { return getNumberOfCells(); } /*! * \brief Return the type of the given cell. * * \param [in] cellID the ID of the cell in question, this parameter is * ignored if hasMixedCellTypes() == false. * * \pre 0 <= cellID < getNumberOfCells() */ virtual CellType getCellType(IndexType cellID = 0) const = 0; /*! * \brief Return the number of nodes associated with the given cell. * * \param [in] cellID the ID of the cell in question, this parameter is * ignored unless hasMixedCellTypes() == true. * * \pre 0 <= cellID < getNumberOfCells() */ virtual IndexType getNumberOfCellNodes(IndexType cellID = 0) const = 0; /*! * \brief Copy the connectivity of the given cell into the provided buffer. * The buffer must be of length at least getNumberOfCellNodes( cellID ). * * \param [in] cellID the ID of the cell in question. * \param [out] nodes the buffer into which the connectivity is copied, must * be of length at least getNumberOfCellNodes( cellID ). * * \return The number of nodes for the given cell. * * \pre nodes != nullptr * \pre 0 <= cellID < getNumberOfCells() */ virtual IndexType getCellNodeIDs(IndexType AXOM_NOT_USED(cellID), IndexType* AXOM_NOT_USED(nodes)) const = 0; /*! * \brief Return the number of faces associated with the given cell. * * \param [in] cellID the ID of the cell in question. */ virtual IndexType getNumberOfCellFaces( IndexType AXOM_NOT_USED(cellID) = 0) const = 0; /*! * \brief Populates the given buffer with the IDs of the faces of the given * cell and returns the number of faces. * * \param [in] cellID the ID of the cellID in question. * \param [out] faces buffer to populate with the face IDs. Must be of length * at least getNumberOfCellFaces( cellID ). * * \pre faces != nullptr * \pre 0 <= cellID < getNumberOfCells() */ virtual IndexType getCellFaceIDs(IndexType AXOM_NOT_USED(cellID), IndexType* AXOM_NOT_USED(faces)) const = 0; /// @} /// \name Nodes /// @{ /*! * \brief Returns the number of nodes in this mesh instance. * \return N the number of nodes * \post N >= 0 */ virtual IndexType getNumberOfNodes() const = 0; /*! * \brief Returns the capacity for number of nodes in this mesh instance. * \return N the node capacity * \post N >= 0 */ virtual IndexType getNodeCapacity() const { return getNumberOfNodes(); } /*! * \brief Copy the coordinates of the given node into the provided buffer. * * \param [in] nodeID the ID of the node in question. * \param [in] coords the buffer to copy the coordinates into, of length at * least getDimension(). * * \pre 0 <= nodeID < getNumberOfNodes() * \pre coords != nullptr */ virtual void getNode(IndexType nodeID, double* node) const = 0; /*! * \brief Returns pointer to the requested mesh coordinate buffer. * * \param [in] dim the dimension of the requested coordinate buffer * \return ptr pointer to the coordinate buffer. * * \note if hasExplicitCoordinates() == true then the length of the returned * buffer is getNumberOfNodes(). Otherwise the UniformMesh returns * nullptr and the RectilinearMesh returns a pointer to the associated * dimension scale which is of length * static_cast< RectilinearMesh* >( this )->getNodeResolution(). * * \pre dim >= 0 && dim < dimension() * \pre dim == X_COORDINATE || dim == Y_COORDINATE || dim == Z_COORDINATE */ /// @{ virtual double* getCoordinateArray(int dim) = 0; virtual const double* getCoordinateArray(int dim) const = 0; /// @} /// @} /// \name Faces /// @{ /*! * \brief Returns the number of faces in this mesh instance. * \return N the number of faces * \post N >= 0 */ virtual IndexType getNumberOfFaces() const = 0; /*! * \brief Returns the capacity for number of faces in this mesh instance. * \return N the face capacity * \post N >= 0 */ virtual IndexType getFaceCapacity() const { return getNumberOfFaces(); } /*! * \brief Return the type of the given face. * * \param [in] faceID the ID of the face in question. */ virtual CellType getFaceType(IndexType AXOM_NOT_USED(faceID)) const = 0; /*! * \brief Return the number of nodes associated with the given face. * * \param [in] faceID the ID of the face in question. */ virtual IndexType getNumberOfFaceNodes(IndexType AXOM_NOT_USED(faceID)) const = 0; /*! * \brief Copy the IDs of the nodes that compose the given face into the * provided buffer. * * \param [in] faceID the ID of the face in question. * \param [out] nodes the buffer into which the node IDs are copied, must * be of length at least getNumberOfFaceNodes(). * * \return The number of nodes for the given face. * * \pre nodes != nullptr * \pre 0 <= faceID < getNumberOfFaces() */ virtual IndexType getFaceNodeIDs(IndexType AXOM_NOT_USED(faceID), IndexType* AXOM_NOT_USED(nodes)) const = 0; /*! * \brief Copy the IDs of the cells adjacent to the given face into the * provided indices. * * \param [in] faceID the ID of the face in question. * \param [out] cellIDOne the ID of the first cell. * \param [out] cellIDTwo the ID of the second cell. * * \note If no cell exists (the face is external) then the ID will be set to * -1. * * \pre 0 <= faceID < getNumberOfFaces() */ virtual void getFaceCellIDs(IndexType AXOM_NOT_USED(faceID), IndexType& AXOM_NOT_USED(cellIDOne), IndexType& AXOM_NOT_USED(cellIDTwo)) const = 0; /// @} /// \name Edges /// @{ /*! * \brief Returns the number of edges in this mesh instance. * \return N the number of edges * \post N >= 0 */ virtual IndexType getNumberOfEdges() const = 0; /*! * \brief Returns the capacity for number of edges in this mesh instance. * \return N the edge capacity * \post N >= 0 */ virtual IndexType getEdgeCapacity() const { return getNumberOfEdges(); } /*! * \brief Returns true iff the mesh was constructed with external arrays. * \return status true if the mesh points to external buffers, else, false. */ virtual bool isExternal() const = 0; /// @} /// @} /// \name Mesh Attribute get/set Methods /// @{ /*! * \brief Returns the dimension for this mesh instance. * \return ndims the dimension of this mesh instance. * \post ndims >= 1 && ndims <= 3 */ inline int getDimension() const { return m_ndims; } /*! * \brief Returns the ID of this mesh instance. * \return Id the ID of the mesh. */ inline int getBlockId() const { return m_block_idx; } /*! * \brief set the block ID of this mesh instance. * * \param [in] ID the new block ID. * * \post getBlockId() == ID */ void setBlockId(int ID); /*! * \brief Returns the partition ID of this mesh instance. * \return partitionId the partition ID of the mesh. */ inline int getPartitionId() const { return m_part_idx; } /*! * \brief set the partition ID of this mesh instance. * * \param [in] ID the new partition ID. * * \post getPartitionId() == ID */ void setPartitionId(int ID); /*! * \brief Returns the mesh type of this mesh instance. * \return meshType the mesh type * \see MeshType */ inline int getMeshType() const { return m_type; } /*! * \brief Checks if this mesh instance has explicit coordinates. * \return status true iff the mesh defines coordinates explicitly. */ inline bool hasExplicitCoordinates() const { return m_explicit_coords; } /*! * \brief Checks if this mesh instance has explicit connectivity. * \return status true iff the mesh defines cell connectivity explicitly. */ inline bool hasExplicitConnectivity() const { return m_explicit_connectivity; } /*! * \brief Checks if the mesh has mixed cell types, e.g., consisting of both * triangle and quad elements or hex,pyramid,prisms and tets in 3-D. * \return status true iff the mesh has mixed cell types. */ inline bool hasMixedCellTypes() const { return m_has_mixed_topology; } /*! * \brief Returns true if the mesh type is structured. * \return status true if the mesh type is structured, else, false. */ inline bool isStructured() const { return ((m_type == STRUCTURED_CURVILINEAR_MESH) || (m_type == STRUCTURED_RECTILINEAR_MESH) || (m_type == STRUCTURED_UNIFORM_MESH)); } /*! * \brief Returns true if the mesh type is unstructured. * \return status true if the mesh type is unstructured, else, false. */ inline bool isUnstructured() const { return (m_type == UNSTRUCTURED_MESH); } /*! * \brief Checks if this Mesh instance is associated with a Sidre Group. * \return status true if the Mesh is associated with a group in a Sidre * hierarchy, else, false. */ inline bool hasSidreGroup() const; #ifdef AXOM_MINT_USE_SIDRE /*! * \brief Return a pointer to the sidre::Group associated with this Mesh * instance or nullptr if none exists. */ inline sidre::Group* getSidreGroup() { return m_group; } /*! * \brief Return the name of the topology associated with this Mesh instance, * the return value is undefined if the mesh is not in sidre. */ inline const std::string& getTopologyName() const { return m_topology; } /*! * \brief Return the name of the coordset associated with this Mesh instance, * the return value is undefined if the mesh is not in sidre. */ inline const std::string& getCoordsetName() const { return m_coordset; } #endif /// @} /// \name Methods to Create, Access & Remove Fields from a Mesh /// @{ /*! * \brief Returns const pointer to the FieldData instance with the specified * mesh field association, e.g., NODE_CENTERED, CELL_CENTERED, etc. * * \param [in] association the specified mesh field association * \return fd pointer to the requested FieldData instance * * \pre association >= 0 && association < NUM_FIELD_ASSOCIATION * \post fd != nullptr * * \see FieldAssociation * \see FieldData */ inline const FieldData* getFieldData(int association) const; /*! * \brief Check if a field with the given name and association exists. * * \param [in] name the name of the field in query. * \param [in] association the field association (optional) * * \return status true if the field exists, else, false. * * \note If an association is not explicitly specified, the code will check * if a field by the given name exists in any available centeering. * * \pre name.empty()==false * \pre association >= 0 && association < NUM_FIELD_ASSOCIATION * * \see FieldAssociation */ inline bool hasField(const std::string& name, int association = ANY_CENTERING) const; /*! * \brief Creates a new field with the given name and specified mesh field * association, e.g., NODE_CENTERED, CELL_CENTERED, etc. * * \param [in] name the name of the new field. * \param [in] association the mesh field association. * \param [in] num_components number of components of the field (optional). * \param [in] storeInSidre indicates whether to store the field in the * corresponding Sidre group (optional). * \param [in] capacity * * \return ptr raw pointer to the data buffer of the new field. * * \note This method throws an error and aborts if any of the pre-conditions * is not satisfied. * * \pre name.empty() == false * \pre hasField( name ) == false * \pre association >= 0 && association < NUM_FIELD_ASSOCIATION * * \post ptr != nullptr * \post hasField( name ) == true * * \see FieldAssociation */ template <typename T> inline T* createField(const std::string& name, int association, IndexType num_components = 1, bool storeInSidre = true); /*! * \brief Creates a new field from an external buffer that has the given name * and specified mesh field association, e.g., NODE_CENTERED, CELL_CENTERED, * etc. * * \param [in] name the name of the new field. * \param [in] association the mesh field association. * \param [in] data pointer to the external data buffer. * \param [in] num_components number of components of the field (optional). * * \return ptr raw pointer to the data buffer of the new field. * * \note This method throws an error and aborts if any of the pre-conditions * is not satisfied. * * \pre name.empty() == false * \pre hasField( name ) == false * \pre data != nullptr * \pre association >= 0 && association < NUM_FIELD_ASSOCIATION * * \post ptr != nullptr * \post ptr == data * \post hasField( name ) == true * * \see FieldAssociation */ template <typename T> inline T* createField(const std::string& name, int association, T* data, IndexType num_components = 1, IndexType capacity = USE_DEFAULT); /*! * \brief Removes the field with the given name and specified association. * * \param [in] name the name of the field to remove. * \param [in] association the mesh field association. * * \return status true if the field is removed successfully, else, false. * * \pre name.emtpy() == false * \pre association >= 0 && association < NUM_FIELD_ASSOCIATION * * \see FieldAssociation */ inline bool removeField(const std::string& name, int association); /*! * \brief Returns pointer to buffer of the field with the given ane and * specified mesh field association. * * \param [in] name the name of the requested field. * \param [in] association the mesh field association. * \param [out] num_components the number of components per tuple (optional). * * \return ptr raw pointer to the data buffer of the requested field. * * \pre name.empty() == false * \pre hasField( name ) * \pre association >= 0 && association < NUM_FIELD_ASSOCIATION * * \see FieldAssociation */ /// @{ template <typename T> inline T* getFieldPtr(const std::string& name, int association, IndexType& num_components); template <typename T> inline T* getFieldPtr(const std::string& name, int association); template <typename T> inline const T* getFieldPtr(const std::string& name, int association, IndexType& num_components) const; template <typename T> inline const T* getFieldPtr(const std::string& name, int association) const; /// @} /// @} protected: /// \name Protected Members /// @{ int m_ndims; /*! mesh dimension */ int m_type; /*! the type of the mesh */ int m_block_idx; /*! the Block ID of the mesh */ int m_part_idx; /*! the partition ID of the mesh */ bool m_explicit_coords; bool m_explicit_connectivity; bool m_has_mixed_topology; FieldData* m_mesh_fields[NUM_FIELD_ASSOCIATIONS]; #ifdef AXOM_MINT_USE_SIDRE sidre::Group* m_group; std::string m_topology; std::string m_coordset; #endif /// @} /// \name Protected Constructors (used in derived classes ) /// @{ /*! * \brief Mesh Constructor. * * \param [in] ndims the number of dimensions * \param [in] type the mesh type. * \param [in] blockId the block ID for this mesh instance. * \param [in] partId the partition ID for this mesh instance. */ Mesh(int ndims, int type); #ifdef AXOM_MINT_USE_SIDRE /*! * \brief Constructor for use with a group that already has data. * * \param [in] group the sidre::Group to use. * \param [in] topo optional argument specifying the name of the topology * associated with this Mesh instance. * * \note If a topology name is not provided, the implementation will construct * a mesh based on the 1st topology group under the parent "topologies" * group. * * \pre group != nullptr. * \pre blueprint::isValidRootGroup( group ) == true * * \see sidre::Group */ Mesh(sidre::Group* group, const std::string& topo = ""); /*! * \brief Constructor for use with an empty group. * * \param [in] ndims the number of dimensions * \param [in] type the mesh type. * \param [in] group the sidre::Group to use. * \param [in] topo the name of the associated topology group. * \param [in] coordset the name of the associated coordset group. * * \note If a topology and coordset name is not provided a default name is * used by the implementation. * * \pre group != nullptr. * \pre group->getNumGroups() == 0 * \pre group->getNumViews() == 0 * \post blueprint::isValidRootGroup( group ) * * \see sidre::Group */ Mesh(int ndims, int type, sidre::Group* group, const std::string& topo, const std::string& coordset); /*! * \brief Helper method to return the associated coordset group. * \return coordset the associated coordset group. * * \pre m_group != nullptr * \pre blueprint::isValidRootGroup( m_group ) * \post blueprint::isValidCoordsetGroup( coordset ) */ sidre::Group* getCoordsetGroup(); /*! * \brief Helper method to return the associated topology group. * \return topology the associated topology group. * * \pre m_group != nullptr * \pre blueprint::isValidRootGroup( m_group ) * \post blueprint::isValidTopologyGroup( topology ) */ sidre::Group* getTopologyGroup(); #endif /// @} private: /*! * \brief Get the info corresponding to the given mesh field association. * * \param [in] association the mesh field association, e.g., NODE_CENTERED. * \param [out] num_tuples the number of tuples in the associated FieldData. * \param [out] capacity the capacity of the associated FieldData. */ void getFieldInfo(int association, IndexType& num_tuples, IndexType& capacity) const; /*! * \brief Helper method to check if the mesh type is valid. * \return status true if the mesh type is valie, else, false. */ inline bool validMeshType() const { return ((m_type >= 0) && (m_type < mint::NUM_MESH_TYPES)); } /*! * \brief Helper method to check if the mesh dimension is valid. * \return status true if the mesh dimension is valid, else, false. */ inline bool validDimension() const { return (m_ndims >= 1 && m_ndims <= 3); } /*! * \brief Allocates the FieldData internal data-structures. * \note Helper method that is called from the constructor. */ void allocateFieldData(); /*! * \brief Deallocates the FieldData internal data-structures. * \note Helper method that is called by the destructor. */ void deallocateFieldData(); DISABLE_COPY_AND_ASSIGNMENT(Mesh); DISABLE_MOVE_AND_ASSIGNMENT(Mesh); }; //------------------------------------------------------------------------------ // IMPLEMENTATION OF TEMPLATE & IN-LINE METHODS //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ inline bool Mesh::hasSidreGroup() const { #ifdef AXOM_MINT_USE_SIDRE return (m_group != nullptr); #else return false; #endif } //------------------------------------------------------------------------------ inline const FieldData* Mesh::getFieldData(int association) const { SLIC_ERROR_IF(association < 0 || association >= NUM_FIELD_ASSOCIATIONS, "invalid field association [" << association << "]"); SLIC_ERROR_IF(m_mesh_fields[association] == nullptr, "null field data object w/association [" << association << "]"); SLIC_ERROR_IF(m_type == PARTICLE_MESH && association != NODE_CENTERED, "a particle mesh may only store node-centered fields"); return m_mesh_fields[association]; } //------------------------------------------------------------------------------ inline bool Mesh::hasField(const std::string& name, int association) const { bool found = false; if(association == mint::ANY_CENTERING) { int N = (m_type == mint::PARTICLE_MESH) ? 1 : mint::NUM_FIELD_ASSOCIATIONS; for(int i = 0; !found && i < N; ++i) { const FieldData* fd = getFieldData(i); SLIC_ASSERT(fd != nullptr); found = fd->hasField(name); } } else { const FieldData* fd = getFieldData(association); SLIC_ASSERT(fd != nullptr); found = fd->hasField(name); } return (found); } //------------------------------------------------------------------------------ template <typename T> inline T* Mesh::createField(const std::string& name, int association, IndexType num_components, bool storeInSidre) { SLIC_ERROR_IF(hasField(name), "a field with the same name already exists!"); FieldData* fd = const_cast<FieldData*>(getFieldData(association)); SLIC_ASSERT(fd != nullptr); IndexType num_tuples, capacity; getFieldInfo(association, num_tuples, capacity); T* ptr = fd->createField<T>(name, num_tuples, num_components, capacity, storeInSidre); if(num_tuples > 0) { SLIC_ASSERT(ptr != nullptr); } return (ptr); } //------------------------------------------------------------------------------ template <typename T> inline T* Mesh::createField(const std::string& name, int association, T* data, IndexType num_components, IndexType capacity) { SLIC_ERROR_IF(hasField(name), "a field with the same name already exists!"); SLIC_ASSERT(data != nullptr); FieldData* fd = const_cast<FieldData*>(getFieldData(association)); SLIC_ASSERT(fd != nullptr); IndexType num_tuples, dummy1; getFieldInfo(association, num_tuples, dummy1); T* ptr = fd->createField<T>(name, data, num_tuples, num_components, capacity); SLIC_ASSERT(ptr == data); return (ptr); } //------------------------------------------------------------------------------ inline bool Mesh::removeField(const std::string& name, int association) { bool status = false; FieldData* fd = const_cast<FieldData*>(getFieldData(association)); const bool hasField = fd->hasField(name); SLIC_WARNING_IF(!hasField, "field [" << name << "] does not exist!"); if(hasField) { fd->removeField(name); status = true; } return (status); } //------------------------------------------------------------------------------ template <typename T> inline T* Mesh::getFieldPtr(const std::string& name, int association) { IndexType num_components = 0; return getFieldPtr<T>(name, association, num_components); } //------------------------------------------------------------------------------ template <typename T> inline T* Mesh::getFieldPtr(const std::string& name, int association, IndexType& num_components) { const Mesh* self = const_cast<const Mesh*>(this); const T* ptr = self->getFieldPtr<T>(name, association, num_components); return (const_cast<T*>(ptr)); } //------------------------------------------------------------------------------ template <typename T> inline const T* Mesh::getFieldPtr(const std::string& name, int association) const { IndexType num_components = 0; return getFieldPtr<T>(name, association, num_components); } //------------------------------------------------------------------------------ template <typename T> inline const T* Mesh::getFieldPtr(const std::string& name, int association, IndexType& num_components) const { const FieldData* fd = getFieldData(association); SLIC_ASSERT(fd != nullptr); IndexType num_tuples = 0; const T* ptr = fd->getFieldPtr<T>(name, num_tuples, num_components); SLIC_ASSERT(ptr != nullptr); return (ptr); } //------------------------------------------------------------------------------ inline void Mesh::getFieldInfo(int association, IndexType& num_tuples, IndexType& capacity) const { switch(association) { case NODE_CENTERED: num_tuples = getNumberOfNodes(); capacity = getNodeCapacity(); break; case CELL_CENTERED: num_tuples = getNumberOfCells(); capacity = getCellCapacity(); break; case FACE_CENTERED: num_tuples = getNumberOfFaces(); capacity = getFaceCapacity(); break; default: SLIC_ASSERT(association == EDGE_CENTERED); num_tuples = getNumberOfEdges(); capacity = getEdgeCapacity(); break; } // END switch } } /* namespace mint */ } /* namespace axom */ #endif /* MINT_MESH_HPP_ */
34,828
10,681
/** * Copyright 2020 Huawei Technologies Co., Ltd * * 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 "tools/converter/legacy_optimizer/graph/batchnorm_convert_scale_pass.h" #include <memory> #include <string> #include <utility> #include <vector> #include "tools/converter/converter_flags.h" #include "third_party/securec/include/securec.h" #include "src/common/log_adapter.h" #include "src/common/common.h" #include "tools/common/tensor_util.h" #include "include/errorcode.h" #include "schema/inner/model_generated.h" namespace mindspore { namespace lite { #define CAFFE_BATCHNORM_MEAN_INDEX 0 #define CAFFE_BATCHNORM_VARIANCE_INDEX 1 #define CAFFE_BATCHNORM_SCALE_INDEX 2 #define TF_BATCHNORM_SCALE_INDEX 0 #define TF_BATCHNORM_BIAS_INDEX 1 #define TF_BATCHNORM_MEAN_INDEX 2 #define TF_BATCHNORM_VARIANCE_INDEX 3 namespace { constexpr const float EPS = 1e-8; constexpr const float EPS_DEFAULT_FLOAT = 1e-8; constexpr const float POW_NUM = 0.5; } // namespace STATUS BatchNormConvertScalePass::Run(MetaGraphT *graph) { MS_ASSERT(graph != nullptr); for (auto iter = graph->nodes.begin(); iter != graph->nodes.end(); iter++) { auto &node = *iter; auto type = node->primitive->value.type; if (type != schema::PrimitiveType_FusedBatchNorm && type != schema::PrimitiveType_BatchNorm) { continue; } auto status = GenNewScaleTensor(graph, node); if (status != RET_OK) { MS_LOG(ERROR) << "GenNewScaleTensor failed: " << status; return status; } status = ConvertBNToScale(graph, node); if (status != RET_OK) { MS_LOG(ERROR) << "GenNewScaleTensor failed: " << status; return status; } } return RET_OK; } STATUS BatchNormConvertScalePass::ConvertBNToScale(MetaGraphT *graph, const std::unique_ptr<CNodeT> &bnNode) { MS_ASSERT(graph != nullptr); MS_ASSERT(bnNode != nullptr); bnNode->primitive->value.type = schema::PrimitiveType_Scale; std::unique_ptr<ScaleT> scaleParam(new (std::nothrow) ScaleT()); if (scaleParam == nullptr) { MS_LOG(ERROR) << "new scaleParam failed"; return RET_ERROR; } int32_t axis = (graph->allTensors.at(bnNode->inputIndex.at(1))->format == Format_NHWC) ? (int32_t)NHWC_C : (int32_t)NCHW_C; scaleParam->axis = axis; bnNode->primitive->value.value = scaleParam.release(); auto input0 = bnNode->inputIndex.at(0); bnNode->inputIndex.clear(); bnNode->inputIndex.push_back(input0); graph->allTensors.emplace_back(std::move(newScaleWeightTensor)); auto weightTensorIdx = graph->allTensors.size() - 1; graph->allTensors.emplace_back(std::move(newScaleBiasTensor)); auto biasTensorIdx = graph->allTensors.size() - 1; bnNode->inputIndex.push_back(weightTensorIdx); bnNode->inputIndex.push_back(biasTensorIdx); return RET_OK; } STATUS BatchNormConvertScalePass::GenNewScaleTensor(MetaGraphT *graph, const std::unique_ptr<CNodeT> &bnNode) { MS_ASSERT(graph != nullptr); MS_ASSERT(bnNode != nullptr); GetTransParam(graph, bnNode); newScaleWeightTensor = std::unique_ptr<TensorT>(new (std::nothrow) TensorT); if (newScaleWeightTensor == nullptr) { MS_LOG(ERROR) << "new weightTensor failed"; return RET_ERROR; } newScaleWeightTensor->dataType = bnMeanTensor->dataType; newScaleWeightTensor->format = bnMeanTensor->format; newScaleWeightTensor->refCount = schema::NodeType::NodeType_ValueNode; newScaleWeightTensor->dims = bnMeanTensor->dims; auto weightShapeSize = GetShapeSize(*bnMeanTensor); newScaleWeightTensor->data.resize(weightShapeSize * sizeof(float)); auto ret = memcpy_s(newScaleWeightTensor->data.data(), weightShapeSize * sizeof(float), transScale, weightShapeSize * sizeof(float)); if (ret != EOK) { MS_LOG(ERROR) << "memcpy error: " << ret; delete[] transScale; delete[] transBias; transScale = nullptr; transBias = nullptr; return RET_ERROR; } newScaleBiasTensor = std::unique_ptr<TensorT>(new (std::nothrow) TensorT); if (newScaleBiasTensor == nullptr) { MS_LOG(ERROR) << "new weightTensor failed"; return RET_ERROR; } newScaleBiasTensor->dataType = bnMeanTensor->dataType; newScaleBiasTensor->format = bnMeanTensor->format; newScaleBiasTensor->refCount = schema::NodeType::NodeType_ValueNode; newScaleBiasTensor->dims = bnMeanTensor->dims; weightShapeSize = GetShapeSize(*bnMeanTensor); newScaleBiasTensor->data.resize(weightShapeSize * sizeof(float)); ret = memcpy_s(newScaleBiasTensor->data.data(), weightShapeSize * sizeof(float), transBias, weightShapeSize * sizeof(float)); if (ret != EOK) { MS_LOG(ERROR) << "memcpy error: " << ret; delete[] transScale; delete[] transBias; transScale = nullptr; transBias = nullptr; return RET_ERROR; } delete[] transScale; delete[] transBias; transScale = nullptr; transBias = nullptr; return RET_OK; } STATUS BatchNormConvertScalePass::GetTransParam(MetaGraphT *graph, const std::unique_ptr<CNodeT> &bnNode) { MS_ASSERT(graph != nullptr); MS_ASSERT(bnNode != nullptr); BNWeightTensors bnWeightTensors; auto status = GetBnWeightTensors(graph, &bnWeightTensors, bnNode); if (status != RET_OK) { MS_LOG(ERROR) << "GetBnWeightTensors error"; return status; } auto *meanTensor = bnWeightTensors.meanTensor; auto *varianceTensor = bnWeightTensors.varianceTensor; auto *scaleTensor = bnWeightTensors.scaleTensor; auto *biasTensor = bnWeightTensors.biasTensor; auto *meanData = reinterpret_cast<float *>(meanTensor->data.data()); auto *varianceData = reinterpret_cast<float *>(varianceTensor->data.data()); eps = EPS_DEFAULT_FLOAT; status = GetBnEpsilon(bnNode); if (status != RET_OK) { MS_LOG(ERROR) << "GetBnEpsilon failed"; return status; } this->transScale = new (std::nothrow) float[bnChannel]; if (this->transScale == nullptr) { MS_LOG(ERROR) << "new transScale failed"; return RET_ERROR; } this->transBias = new (std::nothrow) float[bnChannel]; if (this->transBias == nullptr) { MS_LOG(ERROR) << "new transBias failed"; return RET_ERROR; } // cal transScale, tf : scale/sqrt(variance + eps); caffe : 1/sqrt(variance + eps) if (memcpy_s(transScale, bnChannel * sizeof(float), varianceData, bnChannel * sizeof(float)) != EOK) { MS_LOG(ERROR) << "memcpy_s transScale error"; delete[] transScale; delete[] transBias; transScale = nullptr; transBias = nullptr; return RET_ERROR; } // 1/sqrt(variance + eps) for (uint32_t i = 0; i < bnChannel; i++) { float tmp = transScale[i] + eps; tmp = pow(tmp, POW_NUM); if (tmp <= 0.0f) { MS_LOG(ERROR) << "divisor 'tmp' cannot be 0"; return RET_ERROR; } transScale[i] = 1 / tmp; } if (scaleTensor != nullptr) { auto *scaleData = reinterpret_cast<float *>(scaleTensor->data.data()); // scale/sqrt(variance + eps) for (uint32_t i = 0; i < bnChannel; i++) { transScale[i] *= scaleData[i]; } } // cal transBias, tf : -scale*mean/sqrt(variance + eps) + bias; caffe : -mean/sqrt(variance + eps) // -mean/sqrt(variance + eps) for (uint32_t i = 0; i < bnChannel; i++) { transBias[i] = -meanData[i] * transScale[i]; } if (biasTensor != nullptr) { auto *biasData = reinterpret_cast<float *>(biasTensor->data.data()); // -scale*mean/sqrt(variance + eps) + bias for (uint32_t i = 0; i < bnChannel; i++) { transBias[i] += biasData[i]; } } return RET_OK; } // BatchNorm weight Tensor definition: // caffe // estimated_mean --0 // estimated_variance --1 // tensorflow // scale -- 0 // bias --1 // estimated_mean --2 // estimated_variance --3 STATUS BatchNormConvertScalePass::GetBnWeightTensors(MetaGraphT *graph, BNWeightTensors *bnWeightTensors, const std::unique_ptr<CNodeT> &bnNode) { MS_ASSERT(graph != nullptr); MS_ASSERT(bnNode != nullptr); MS_ASSERT(bnWeightTensors != nullptr); MS_ASSERT(graph->allTensors.size() > bnNode->inputIndex.at(1)); auto bnWeightTensorIdxes = bnNode->inputIndex; bnWeightTensorIdxes.erase(bnWeightTensorIdxes.begin()); if (fmkType == converter::FmkType_CAFFE) { bnWeightTensors->meanTensor = graph->allTensors.at(bnWeightTensorIdxes[CAFFE_BATCHNORM_MEAN_INDEX]).get(); bnWeightTensors->varianceTensor = graph->allTensors.at(bnWeightTensorIdxes[CAFFE_BATCHNORM_VARIANCE_INDEX]).get(); auto scaleTensor = graph->allTensors.at(bnWeightTensorIdxes[CAFFE_BATCHNORM_SCALE_INDEX]).get(); // calibrate mean and variance float scale_factor_data = (reinterpret_cast<float *>(scaleTensor->data.data()))[0]; float scale_factor = scale_factor_data == 0 ? 0 : 1 / scale_factor_data; auto mean_data = reinterpret_cast<float *>(bnWeightTensors->meanTensor->data.data()); auto variance_data = reinterpret_cast<float *>(bnWeightTensors->varianceTensor->data.data()); for (size_t i = 0; i < GetShapeSize(*bnWeightTensors->meanTensor); i++) { mean_data[i] *= scale_factor; } for (size_t i = 0; i < GetShapeSize(*bnWeightTensors->varianceTensor); i++) { variance_data[i] *= scale_factor; } } else { bnWeightTensors->scaleTensor = graph->allTensors.at(bnWeightTensorIdxes[TF_BATCHNORM_SCALE_INDEX]).get(); bnWeightTensors->biasTensor = graph->allTensors.at(bnWeightTensorIdxes[TF_BATCHNORM_BIAS_INDEX]).get(); bnWeightTensors->meanTensor = graph->allTensors.at(bnWeightTensorIdxes[TF_BATCHNORM_MEAN_INDEX]).get(); bnWeightTensors->varianceTensor = graph->allTensors.at(bnWeightTensorIdxes[TF_BATCHNORM_VARIANCE_INDEX]).get(); } if (bnWeightTensors->meanTensor == nullptr) { MS_LOG(ERROR) << "BatchNorm's mean tensor is nullptr"; return RET_ERROR; } if (bnWeightTensors->varianceTensor == nullptr) { MS_LOG(ERROR) << "BatchNorm's variance tensor is nullptr"; return RET_ERROR; } bnChannel = bnWeightTensors->meanTensor->data.size() * sizeof(uint8_t) / sizeof(float); if (bnChannel <= 0) { MS_LOG(ERROR) << "BatchNorm's channel less or equal 0"; return RET_ERROR; } bnMeanTensor = bnWeightTensors->meanTensor; if (bnChannel != bnWeightTensors->varianceTensor->data.size() * sizeof(uint8_t) / sizeof(float)) { MS_LOG(ERROR) << "conv kernel num expected to be equal to variance size"; return RET_ERROR; } if (bnWeightTensors->scaleTensor != nullptr) { if (bnChannel != bnWeightTensors->scaleTensor->data.size() * sizeof(uint8_t) / sizeof(float)) { MS_LOG(ERROR) << "conv kernel num expected to be equal to scale size"; return RET_ERROR; } } if (bnWeightTensors->biasTensor != nullptr) { if (bnChannel != bnWeightTensors->biasTensor->data.size() * sizeof(uint8_t) / sizeof(float)) { MS_LOG(ERROR) << "conv kernel num expected to be equal to bias size"; return RET_ERROR; } } return RET_OK; } STATUS BatchNormConvertScalePass::GetBnEpsilon(const std::unique_ptr<CNodeT> &bnNode) { MS_ASSERT(graph != nullptr); MS_ASSERT(bnNode != nullptr); MS_ASSERT(bnNode->primitive != nullptr); if (bnNode->primitive->value.type == schema::PrimitiveType_FusedBatchNorm) { eps = bnNode->primitive->value.AsFusedBatchNorm()->epsilon; } else if (bnNode->primitive->value.type == schema::PrimitiveType_BatchNorm) { eps = bnNode->primitive->value.AsBatchNorm()->epsilon; } else { MS_LOG(ERROR) << "match pattern has error, not BatchNorm node"; return RET_ERROR; } if (eps < EPS) { eps = EPS_DEFAULT_FLOAT; } return RET_OK; } } // namespace lite } // namespace mindspore
12,100
4,453
/*************************************************************** * * Copyright (C) 2009-2011 Red Hat, 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. * ***************************************************************/ #include "AviaryProvider.h" #include "EndpointPublisher.h" #include "Axis2SoapProvider.h" #include "Axis2SslProvider.h" #include "AviaryUtils.h" using namespace std; using namespace aviary; using namespace aviary::transport; using namespace aviary::soap; using namespace aviary::util; using namespace aviary::locator; AviaryProvider* AviaryProviderFactory::create(const string& log_file, const string& service_name, const string& major_type, const string& minor_type, const string& uri_suffix) { AviaryProvider* provider = NULL; string repo_path; int port; string axis_error; char *tmp = NULL; EndpointPublisher* ep = NULL; // config then env for our all-important axis2 repo dir if ((tmp = param("WSFCPP_HOME"))) { repo_path = tmp; free(tmp); } else if ((tmp = getenv("WSFCPP_HOME"))) { repo_path = tmp; } else { dprintf(D_ALWAYS,"No WSFCPP_HOME in config or env\n"); return NULL; } int level = getLogLevel(); int read_timeout = param_integer("AXIS2_READ_TIMEOUT",AXIS2_HTTP_DEFAULT_SO_TIMEOUT); // which flavor of transport bool have_ssl = param_boolean("AVIARY_SSL",FALSE); if (!have_ssl) { port = param_integer("HTTP_PORT",9000); } else { port = param_integer("HTTP_PORT",9443); } // see if we are using locator to publish our endpoint bool use_locator = param_boolean("AVIARY_PUBLISH_LOCATION",FALSE) && minor_type != LOCATOR; if (use_locator) { ep = new EndpointPublisher(service_name, major_type, minor_type); if (!ep->init(uri_suffix,have_ssl)) { dprintf(D_ALWAYS,"Aviary location endpoint config failed\n"); return NULL; } port = ep->getPort(); } if (!have_ssl) { Axis2SoapProvider* http = new Axis2SoapProvider(level,log_file.c_str(),repo_path.c_str()); if (!http->init(port,read_timeout,axis_error)) { dprintf(D_ALWAYS,"Axis2 HTTP configuration failed, check possible conflict on port %d\n",port); delete http; return NULL; } dprintf(D_ALWAYS,"UNSECURE Axis2 HTTP listener activated on port %d\n",port); provider = http; } #ifdef HAVE_EXT_OPENSSL else { Axis2SslProvider* https = new Axis2SslProvider(level,log_file.c_str(),repo_path.c_str()); if (!https->init(port,read_timeout,axis_error)) { dprintf(D_ALWAYS,"SSL/TLS requested but configuration failed\n"); dprintf(D_ALWAYS,"Check SSL config paths and possible conflict on port %d\n",port); delete https; return NULL; } dprintf(D_ALWAYS,"Axis2 HTTPS listener activated on port %d\n",port); provider = https; } #endif // ready to publish our endpoint if (ep) { // provider owns this now provider->setPublisher(ep); ep->start(param_integer("AVIARY_PUBLISH_INTERVAL", 10)); } return provider; }
3,690
1,231
#include <string> #include <iostream> #include "format.h" using std::string; using std::to_string; using std::cout; // INPUT: Long int measuring seconds // OUTPUT: HH:MM:SS string Format::ElapsedTime(long elapsedTime) { long hours = elapsedTime / 3600; float mins = ((elapsedTime / 3600.0) - hours) * 60; int minutes = (int) mins; int seconds = (int) ((mins - minutes) * 60); string timeExpressed; timeExpressed.append(to_string(hours)); timeExpressed.append(":"); timeExpressed.append(to_string(minutes)); timeExpressed.append(":"); timeExpressed.append(to_string(seconds)); return timeExpressed; }
646
230
/* * (C) Copyright 2013 ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation * nor does it submit to any jurisdiction. */ // TL159 #include "atlas/grid/detail/spacing/gaussian/N.h" namespace atlas { namespace grid { namespace spacing { namespace gaussian { DEFINE_GAUSSIAN_LATITUDES( 80, LIST( 89.141519426461, 88.029428867952, 86.910770814124, 85.790628883637, 84.669924084447, 83.548946912542, 82.427817524008, 81.306594522669, 80.185309872477, 79.063982481409, 77.942624246673, 76.821243027100, 75.699844222011, 74.578431663296, 73.457008145583, 72.335575754909, 71.214136079887, 70.092690351624, 68.971239538936, 67.849784414670, 66.728325602882, 65.606863613010, 64.485398865043, 63.363931708341, 62.242462435891, 61.120991295252, 59.999518497040, 58.878044221583, 57.756568624184, 56.635091839330, 55.513613984077, 54.392135160792, 53.270655459398, 52.149174959220, 51.027693730509, 49.906211835711, 48.784729330535, 47.663246264843, 46.541762683406, 45.420278626548, 44.298794130694, 43.177309228835, 42.055823950935, 40.934338324279, 39.812852373771, 38.691366122202, 37.569879590471, 36.448392797794, 35.326905761872, 34.205418499049, 33.083931024447, 31.962443352088, 30.840955495002, 29.719467465319, 28.597979274357, 27.476490932696, 26.355002450251, 25.233513836324, 24.112025099671, 22.990536248541, 21.869047290730, 20.747558233616, 19.626069084199, 18.504579849136, 17.383090534771, 16.261601147162, 15.140111692111, 14.018622175186, 12.897132601745, 11.775642976956, 10.654153305818, 9.532663593176, 8.411173843743, 7.289684062115, 6.168194252784, 5.046704420157, 3.925214568566, 2.803724702287, 1.682234825547, 0.560744942544 ) ) } // namespace gaussian } // namespace spacing } // namespace grid } // namespace atlas
2,200
1,586
// Generated wrapper code for package Adaptor2d #include "OcctPCH.h" #include "Adaptor2d.h" using namespace System::Runtime::InteropServices; // for class Marshal #include "Adaptor2d.h" #include "Geom2dAdaptor.h" #include "ProjLib.h" #include "BRepAdaptor.h" #include "Standard.h" #include "GeomAbs.h" #include "TColStd.h" #include "gp.h" #include "Geom2d.h" //--------------------------------------------------------------------- // Class Adaptor2d_HCurve2d //--------------------------------------------------------------------- Macad::Occt::Adaptor2d_HCurve2d::Adaptor2d_HCurve2d(Macad::Occt::Adaptor2d_HCurve2d^ parameter1) : Macad::Occt::Standard_Transient(BaseClass::InitMode::Uninitialized) { throw gcnew System::NotImplementedException("Native class is abstract"); } Macad::Occt::Adaptor2d_HCurve2d::Adaptor2d_HCurve2d() : Macad::Occt::Standard_Transient(BaseClass::InitMode::Uninitialized) { throw gcnew System::NotImplementedException("Native class is abstract"); } Macad::Occt::Adaptor2d_Curve2d^ Macad::Occt::Adaptor2d_HCurve2d::Curve2d() { ::Adaptor2d_Curve2d* _result = new ::Adaptor2d_Curve2d(); *_result = (::Adaptor2d_Curve2d)((::Adaptor2d_HCurve2d*)_NativeInstance)->Curve2d(); return _result==nullptr ? nullptr : gcnew Macad::Occt::Adaptor2d_Curve2d(_result); } double Macad::Occt::Adaptor2d_HCurve2d::FirstParameter() { return ((::Adaptor2d_HCurve2d*)_NativeInstance)->FirstParameter(); } double Macad::Occt::Adaptor2d_HCurve2d::LastParameter() { return ((::Adaptor2d_HCurve2d*)_NativeInstance)->LastParameter(); } Macad::Occt::GeomAbs_Shape Macad::Occt::Adaptor2d_HCurve2d::Continuity() { return (Macad::Occt::GeomAbs_Shape)((::Adaptor2d_HCurve2d*)_NativeInstance)->Continuity(); } int Macad::Occt::Adaptor2d_HCurve2d::NbIntervals(Macad::Occt::GeomAbs_Shape S) { return ((::Adaptor2d_HCurve2d*)_NativeInstance)->NbIntervals((::GeomAbs_Shape)S); } void Macad::Occt::Adaptor2d_HCurve2d::Intervals(Macad::Occt::TColStd_Array1OfReal^ T, Macad::Occt::GeomAbs_Shape S) { ((::Adaptor2d_HCurve2d*)_NativeInstance)->Intervals(*(::TColStd_Array1OfReal*)T->NativeInstance, (::GeomAbs_Shape)S); } Macad::Occt::Adaptor2d_HCurve2d^ Macad::Occt::Adaptor2d_HCurve2d::Trim(double First, double Last, double Tol) { Handle(::Adaptor2d_HCurve2d) _result; _result = ((::Adaptor2d_HCurve2d*)_NativeInstance)->Trim(First, Last, Tol); return _result.IsNull() ? nullptr : Macad::Occt::Adaptor2d_HCurve2d::CreateDowncasted( _result.get()); } bool Macad::Occt::Adaptor2d_HCurve2d::IsClosed() { return ((::Adaptor2d_HCurve2d*)_NativeInstance)->IsClosed(); } bool Macad::Occt::Adaptor2d_HCurve2d::IsPeriodic() { return ((::Adaptor2d_HCurve2d*)_NativeInstance)->IsPeriodic(); } double Macad::Occt::Adaptor2d_HCurve2d::Period() { return ((::Adaptor2d_HCurve2d*)_NativeInstance)->Period(); } Macad::Occt::Pnt2d Macad::Occt::Adaptor2d_HCurve2d::Value(double U) { return Macad::Occt::Pnt2d(((::Adaptor2d_HCurve2d*)_NativeInstance)->Value(U)); } void Macad::Occt::Adaptor2d_HCurve2d::D0(double U, Macad::Occt::Pnt2d% P) { pin_ptr<Macad::Occt::Pnt2d> pp_P = &P; ((::Adaptor2d_HCurve2d*)_NativeInstance)->D0(U, *(gp_Pnt2d*)pp_P); } void Macad::Occt::Adaptor2d_HCurve2d::D1(double U, Macad::Occt::Pnt2d% P, Macad::Occt::Vec2d% V) { pin_ptr<Macad::Occt::Pnt2d> pp_P = &P; pin_ptr<Macad::Occt::Vec2d> pp_V = &V; ((::Adaptor2d_HCurve2d*)_NativeInstance)->D1(U, *(gp_Pnt2d*)pp_P, *(gp_Vec2d*)pp_V); } void Macad::Occt::Adaptor2d_HCurve2d::D2(double U, Macad::Occt::Pnt2d% P, Macad::Occt::Vec2d% V1, Macad::Occt::Vec2d% V2) { pin_ptr<Macad::Occt::Pnt2d> pp_P = &P; pin_ptr<Macad::Occt::Vec2d> pp_V1 = &V1; pin_ptr<Macad::Occt::Vec2d> pp_V2 = &V2; ((::Adaptor2d_HCurve2d*)_NativeInstance)->D2(U, *(gp_Pnt2d*)pp_P, *(gp_Vec2d*)pp_V1, *(gp_Vec2d*)pp_V2); } void Macad::Occt::Adaptor2d_HCurve2d::D3(double U, Macad::Occt::Pnt2d% P, Macad::Occt::Vec2d% V1, Macad::Occt::Vec2d% V2, Macad::Occt::Vec2d% V3) { pin_ptr<Macad::Occt::Pnt2d> pp_P = &P; pin_ptr<Macad::Occt::Vec2d> pp_V1 = &V1; pin_ptr<Macad::Occt::Vec2d> pp_V2 = &V2; pin_ptr<Macad::Occt::Vec2d> pp_V3 = &V3; ((::Adaptor2d_HCurve2d*)_NativeInstance)->D3(U, *(gp_Pnt2d*)pp_P, *(gp_Vec2d*)pp_V1, *(gp_Vec2d*)pp_V2, *(gp_Vec2d*)pp_V3); } Macad::Occt::Vec2d Macad::Occt::Adaptor2d_HCurve2d::DN(double U, int N) { return Macad::Occt::Vec2d(((::Adaptor2d_HCurve2d*)_NativeInstance)->DN(U, N)); } double Macad::Occt::Adaptor2d_HCurve2d::Resolution(double R3d) { return ((::Adaptor2d_HCurve2d*)_NativeInstance)->Resolution(R3d); } Macad::Occt::GeomAbs_CurveType Macad::Occt::Adaptor2d_HCurve2d::GetGeomType() { return (Macad::Occt::GeomAbs_CurveType)((::Adaptor2d_HCurve2d*)_NativeInstance)->GetType(); } Macad::Occt::gp_Lin2d^ Macad::Occt::Adaptor2d_HCurve2d::Line() { ::gp_Lin2d* _result = new ::gp_Lin2d(); *_result = ((::Adaptor2d_HCurve2d*)_NativeInstance)->Line(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Lin2d(_result); } Macad::Occt::gp_Circ2d^ Macad::Occt::Adaptor2d_HCurve2d::Circle() { ::gp_Circ2d* _result = new ::gp_Circ2d(); *_result = ((::Adaptor2d_HCurve2d*)_NativeInstance)->Circle(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Circ2d(_result); } Macad::Occt::gp_Elips2d^ Macad::Occt::Adaptor2d_HCurve2d::Ellipse() { ::gp_Elips2d* _result = new ::gp_Elips2d(); *_result = ((::Adaptor2d_HCurve2d*)_NativeInstance)->Ellipse(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Elips2d(_result); } Macad::Occt::gp_Hypr2d^ Macad::Occt::Adaptor2d_HCurve2d::Hyperbola() { ::gp_Hypr2d* _result = new ::gp_Hypr2d(); *_result = ((::Adaptor2d_HCurve2d*)_NativeInstance)->Hyperbola(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Hypr2d(_result); } Macad::Occt::gp_Parab2d^ Macad::Occt::Adaptor2d_HCurve2d::Parabola() { ::gp_Parab2d* _result = new ::gp_Parab2d(); *_result = ((::Adaptor2d_HCurve2d*)_NativeInstance)->Parabola(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Parab2d(_result); } int Macad::Occt::Adaptor2d_HCurve2d::Degree() { return ((::Adaptor2d_HCurve2d*)_NativeInstance)->Degree(); } bool Macad::Occt::Adaptor2d_HCurve2d::IsRational() { return ((::Adaptor2d_HCurve2d*)_NativeInstance)->IsRational(); } int Macad::Occt::Adaptor2d_HCurve2d::NbPoles() { return ((::Adaptor2d_HCurve2d*)_NativeInstance)->NbPoles(); } int Macad::Occt::Adaptor2d_HCurve2d::NbKnots() { return ((::Adaptor2d_HCurve2d*)_NativeInstance)->NbKnots(); } Macad::Occt::Geom2d_BezierCurve^ Macad::Occt::Adaptor2d_HCurve2d::Bezier() { Handle(::Geom2d_BezierCurve) _result; _result = ((::Adaptor2d_HCurve2d*)_NativeInstance)->Bezier(); return _result.IsNull() ? nullptr : Macad::Occt::Geom2d_BezierCurve::CreateDowncasted( _result.get()); } Macad::Occt::Geom2d_BSplineCurve^ Macad::Occt::Adaptor2d_HCurve2d::BSpline() { Handle(::Geom2d_BSplineCurve) _result; _result = ((::Adaptor2d_HCurve2d*)_NativeInstance)->BSpline(); return _result.IsNull() ? nullptr : Macad::Occt::Geom2d_BSplineCurve::CreateDowncasted( _result.get()); } Macad::Occt::Adaptor2d_HCurve2d^ Macad::Occt::Adaptor2d_HCurve2d::CreateDowncasted(::Adaptor2d_HCurve2d* instance) { if( instance == nullptr ) return nullptr; if (instance->IsKind(STANDARD_TYPE(::Adaptor2d_HLine2d))) return Macad::Occt::Adaptor2d_HLine2d::CreateDowncasted((::Adaptor2d_HLine2d*)instance); if (instance->IsKind(STANDARD_TYPE(::Adaptor2d_HOffsetCurve))) return Macad::Occt::Adaptor2d_HOffsetCurve::CreateDowncasted((::Adaptor2d_HOffsetCurve*)instance); if (instance->IsKind(STANDARD_TYPE(::Geom2dAdaptor_GHCurve))) return Macad::Occt::Geom2dAdaptor_GHCurve::CreateDowncasted((::Geom2dAdaptor_GHCurve*)instance); if (instance->IsKind(STANDARD_TYPE(::ProjLib_HProjectedCurve))) return Macad::Occt::ProjLib_HProjectedCurve::CreateDowncasted((::ProjLib_HProjectedCurve*)instance); if (instance->IsKind(STANDARD_TYPE(::ProjLib_HCompProjectedCurve))) return Macad::Occt::ProjLib_HCompProjectedCurve::CreateDowncasted((::ProjLib_HCompProjectedCurve*)instance); if (instance->IsKind(STANDARD_TYPE(::BRepAdaptor_HCurve2d))) return Macad::Occt::BRepAdaptor_HCurve2d::CreateDowncasted((::BRepAdaptor_HCurve2d*)instance); return gcnew Macad::Occt::Adaptor2d_HCurve2d( instance ); } //--------------------------------------------------------------------- // Class Adaptor2d_Curve2d //--------------------------------------------------------------------- Macad::Occt::Adaptor2d_Curve2d::Adaptor2d_Curve2d(Macad::Occt::Adaptor2d_Curve2d^ parameter1) : BaseClass<::Adaptor2d_Curve2d>(BaseClass::InitMode::Uninitialized) { _NativeInstance = new ::Adaptor2d_Curve2d(*(::Adaptor2d_Curve2d*)parameter1->NativeInstance); } Macad::Occt::Adaptor2d_Curve2d::Adaptor2d_Curve2d() : BaseClass<::Adaptor2d_Curve2d>(BaseClass::InitMode::Uninitialized) { _NativeInstance = new ::Adaptor2d_Curve2d(); } double Macad::Occt::Adaptor2d_Curve2d::FirstParameter() { return ((::Adaptor2d_Curve2d*)_NativeInstance)->FirstParameter(); } double Macad::Occt::Adaptor2d_Curve2d::LastParameter() { return ((::Adaptor2d_Curve2d*)_NativeInstance)->LastParameter(); } Macad::Occt::GeomAbs_Shape Macad::Occt::Adaptor2d_Curve2d::Continuity() { return (Macad::Occt::GeomAbs_Shape)((::Adaptor2d_Curve2d*)_NativeInstance)->Continuity(); } int Macad::Occt::Adaptor2d_Curve2d::NbIntervals(Macad::Occt::GeomAbs_Shape S) { return ((::Adaptor2d_Curve2d*)_NativeInstance)->NbIntervals((::GeomAbs_Shape)S); } void Macad::Occt::Adaptor2d_Curve2d::Intervals(Macad::Occt::TColStd_Array1OfReal^ T, Macad::Occt::GeomAbs_Shape S) { ((::Adaptor2d_Curve2d*)_NativeInstance)->Intervals(*(::TColStd_Array1OfReal*)T->NativeInstance, (::GeomAbs_Shape)S); } Macad::Occt::Adaptor2d_HCurve2d^ Macad::Occt::Adaptor2d_Curve2d::Trim(double First, double Last, double Tol) { Handle(::Adaptor2d_HCurve2d) _result; _result = ((::Adaptor2d_Curve2d*)_NativeInstance)->Trim(First, Last, Tol); return _result.IsNull() ? nullptr : Macad::Occt::Adaptor2d_HCurve2d::CreateDowncasted( _result.get()); } bool Macad::Occt::Adaptor2d_Curve2d::IsClosed() { return ((::Adaptor2d_Curve2d*)_NativeInstance)->IsClosed(); } bool Macad::Occt::Adaptor2d_Curve2d::IsPeriodic() { return ((::Adaptor2d_Curve2d*)_NativeInstance)->IsPeriodic(); } double Macad::Occt::Adaptor2d_Curve2d::Period() { return ((::Adaptor2d_Curve2d*)_NativeInstance)->Period(); } Macad::Occt::Pnt2d Macad::Occt::Adaptor2d_Curve2d::Value(double U) { return Macad::Occt::Pnt2d(((::Adaptor2d_Curve2d*)_NativeInstance)->Value(U)); } void Macad::Occt::Adaptor2d_Curve2d::D0(double U, Macad::Occt::Pnt2d% P) { pin_ptr<Macad::Occt::Pnt2d> pp_P = &P; ((::Adaptor2d_Curve2d*)_NativeInstance)->D0(U, *(gp_Pnt2d*)pp_P); } void Macad::Occt::Adaptor2d_Curve2d::D1(double U, Macad::Occt::Pnt2d% P, Macad::Occt::Vec2d% V) { pin_ptr<Macad::Occt::Pnt2d> pp_P = &P; pin_ptr<Macad::Occt::Vec2d> pp_V = &V; ((::Adaptor2d_Curve2d*)_NativeInstance)->D1(U, *(gp_Pnt2d*)pp_P, *(gp_Vec2d*)pp_V); } void Macad::Occt::Adaptor2d_Curve2d::D2(double U, Macad::Occt::Pnt2d% P, Macad::Occt::Vec2d% V1, Macad::Occt::Vec2d% V2) { pin_ptr<Macad::Occt::Pnt2d> pp_P = &P; pin_ptr<Macad::Occt::Vec2d> pp_V1 = &V1; pin_ptr<Macad::Occt::Vec2d> pp_V2 = &V2; ((::Adaptor2d_Curve2d*)_NativeInstance)->D2(U, *(gp_Pnt2d*)pp_P, *(gp_Vec2d*)pp_V1, *(gp_Vec2d*)pp_V2); } void Macad::Occt::Adaptor2d_Curve2d::D3(double U, Macad::Occt::Pnt2d% P, Macad::Occt::Vec2d% V1, Macad::Occt::Vec2d% V2, Macad::Occt::Vec2d% V3) { pin_ptr<Macad::Occt::Pnt2d> pp_P = &P; pin_ptr<Macad::Occt::Vec2d> pp_V1 = &V1; pin_ptr<Macad::Occt::Vec2d> pp_V2 = &V2; pin_ptr<Macad::Occt::Vec2d> pp_V3 = &V3; ((::Adaptor2d_Curve2d*)_NativeInstance)->D3(U, *(gp_Pnt2d*)pp_P, *(gp_Vec2d*)pp_V1, *(gp_Vec2d*)pp_V2, *(gp_Vec2d*)pp_V3); } Macad::Occt::Vec2d Macad::Occt::Adaptor2d_Curve2d::DN(double U, int N) { return Macad::Occt::Vec2d(((::Adaptor2d_Curve2d*)_NativeInstance)->DN(U, N)); } double Macad::Occt::Adaptor2d_Curve2d::Resolution(double R3d) { return ((::Adaptor2d_Curve2d*)_NativeInstance)->Resolution(R3d); } Macad::Occt::GeomAbs_CurveType Macad::Occt::Adaptor2d_Curve2d::GetGeomType() { return (Macad::Occt::GeomAbs_CurveType)((::Adaptor2d_Curve2d*)_NativeInstance)->GetType(); } Macad::Occt::gp_Lin2d^ Macad::Occt::Adaptor2d_Curve2d::Line() { ::gp_Lin2d* _result = new ::gp_Lin2d(); *_result = ((::Adaptor2d_Curve2d*)_NativeInstance)->Line(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Lin2d(_result); } Macad::Occt::gp_Circ2d^ Macad::Occt::Adaptor2d_Curve2d::Circle() { ::gp_Circ2d* _result = new ::gp_Circ2d(); *_result = ((::Adaptor2d_Curve2d*)_NativeInstance)->Circle(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Circ2d(_result); } Macad::Occt::gp_Elips2d^ Macad::Occt::Adaptor2d_Curve2d::Ellipse() { ::gp_Elips2d* _result = new ::gp_Elips2d(); *_result = ((::Adaptor2d_Curve2d*)_NativeInstance)->Ellipse(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Elips2d(_result); } Macad::Occt::gp_Hypr2d^ Macad::Occt::Adaptor2d_Curve2d::Hyperbola() { ::gp_Hypr2d* _result = new ::gp_Hypr2d(); *_result = ((::Adaptor2d_Curve2d*)_NativeInstance)->Hyperbola(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Hypr2d(_result); } Macad::Occt::gp_Parab2d^ Macad::Occt::Adaptor2d_Curve2d::Parabola() { ::gp_Parab2d* _result = new ::gp_Parab2d(); *_result = ((::Adaptor2d_Curve2d*)_NativeInstance)->Parabola(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Parab2d(_result); } int Macad::Occt::Adaptor2d_Curve2d::Degree() { return ((::Adaptor2d_Curve2d*)_NativeInstance)->Degree(); } bool Macad::Occt::Adaptor2d_Curve2d::IsRational() { return ((::Adaptor2d_Curve2d*)_NativeInstance)->IsRational(); } int Macad::Occt::Adaptor2d_Curve2d::NbPoles() { return ((::Adaptor2d_Curve2d*)_NativeInstance)->NbPoles(); } int Macad::Occt::Adaptor2d_Curve2d::NbKnots() { return ((::Adaptor2d_Curve2d*)_NativeInstance)->NbKnots(); } int Macad::Occt::Adaptor2d_Curve2d::NbSamples() { return ((::Adaptor2d_Curve2d*)_NativeInstance)->NbSamples(); } Macad::Occt::Geom2d_BezierCurve^ Macad::Occt::Adaptor2d_Curve2d::Bezier() { Handle(::Geom2d_BezierCurve) _result; _result = ((::Adaptor2d_Curve2d*)_NativeInstance)->Bezier(); return _result.IsNull() ? nullptr : Macad::Occt::Geom2d_BezierCurve::CreateDowncasted( _result.get()); } Macad::Occt::Geom2d_BSplineCurve^ Macad::Occt::Adaptor2d_Curve2d::BSpline() { Handle(::Geom2d_BSplineCurve) _result; _result = ((::Adaptor2d_Curve2d*)_NativeInstance)->BSpline(); return _result.IsNull() ? nullptr : Macad::Occt::Geom2d_BSplineCurve::CreateDowncasted( _result.get()); } //--------------------------------------------------------------------- // Class Adaptor2d_Line2d //--------------------------------------------------------------------- Macad::Occt::Adaptor2d_Line2d::Adaptor2d_Line2d() : Macad::Occt::Adaptor2d_Curve2d(BaseClass::InitMode::Uninitialized) { _NativeInstance = new ::Adaptor2d_Line2d(); } Macad::Occt::Adaptor2d_Line2d::Adaptor2d_Line2d(Macad::Occt::Pnt2d P, Macad::Occt::Dir2d D, double UFirst, double ULast) : Macad::Occt::Adaptor2d_Curve2d(BaseClass::InitMode::Uninitialized) { pin_ptr<Macad::Occt::Pnt2d> pp_P = &P; pin_ptr<Macad::Occt::Dir2d> pp_D = &D; _NativeInstance = new ::Adaptor2d_Line2d(*(gp_Pnt2d*)pp_P, *(gp_Dir2d*)pp_D, UFirst, ULast); } Macad::Occt::Adaptor2d_Line2d::Adaptor2d_Line2d(Macad::Occt::Adaptor2d_Line2d^ parameter1) : Macad::Occt::Adaptor2d_Curve2d(BaseClass::InitMode::Uninitialized) { _NativeInstance = new ::Adaptor2d_Line2d(*(::Adaptor2d_Line2d*)parameter1->NativeInstance); } void Macad::Occt::Adaptor2d_Line2d::Load(Macad::Occt::gp_Lin2d^ L) { ((::Adaptor2d_Line2d*)_NativeInstance)->Load(*(::gp_Lin2d*)L->NativeInstance); } void Macad::Occt::Adaptor2d_Line2d::Load(Macad::Occt::gp_Lin2d^ L, double UFirst, double ULast) { ((::Adaptor2d_Line2d*)_NativeInstance)->Load(*(::gp_Lin2d*)L->NativeInstance, UFirst, ULast); } double Macad::Occt::Adaptor2d_Line2d::FirstParameter() { return ((::Adaptor2d_Line2d*)_NativeInstance)->FirstParameter(); } double Macad::Occt::Adaptor2d_Line2d::LastParameter() { return ((::Adaptor2d_Line2d*)_NativeInstance)->LastParameter(); } Macad::Occt::GeomAbs_Shape Macad::Occt::Adaptor2d_Line2d::Continuity() { return (Macad::Occt::GeomAbs_Shape)((::Adaptor2d_Line2d*)_NativeInstance)->Continuity(); } int Macad::Occt::Adaptor2d_Line2d::NbIntervals(Macad::Occt::GeomAbs_Shape S) { return ((::Adaptor2d_Line2d*)_NativeInstance)->NbIntervals((::GeomAbs_Shape)S); } void Macad::Occt::Adaptor2d_Line2d::Intervals(Macad::Occt::TColStd_Array1OfReal^ T, Macad::Occt::GeomAbs_Shape S) { ((::Adaptor2d_Line2d*)_NativeInstance)->Intervals(*(::TColStd_Array1OfReal*)T->NativeInstance, (::GeomAbs_Shape)S); } Macad::Occt::Adaptor2d_HCurve2d^ Macad::Occt::Adaptor2d_Line2d::Trim(double First, double Last, double Tol) { Handle(::Adaptor2d_HCurve2d) _result; _result = ((::Adaptor2d_Line2d*)_NativeInstance)->Trim(First, Last, Tol); return _result.IsNull() ? nullptr : Macad::Occt::Adaptor2d_HCurve2d::CreateDowncasted( _result.get()); } bool Macad::Occt::Adaptor2d_Line2d::IsClosed() { return ((::Adaptor2d_Line2d*)_NativeInstance)->IsClosed(); } bool Macad::Occt::Adaptor2d_Line2d::IsPeriodic() { return ((::Adaptor2d_Line2d*)_NativeInstance)->IsPeriodic(); } double Macad::Occt::Adaptor2d_Line2d::Period() { return ((::Adaptor2d_Line2d*)_NativeInstance)->Period(); } Macad::Occt::Pnt2d Macad::Occt::Adaptor2d_Line2d::Value(double X) { return Macad::Occt::Pnt2d(((::Adaptor2d_Line2d*)_NativeInstance)->Value(X)); } void Macad::Occt::Adaptor2d_Line2d::D0(double X, Macad::Occt::Pnt2d% P) { pin_ptr<Macad::Occt::Pnt2d> pp_P = &P; ((::Adaptor2d_Line2d*)_NativeInstance)->D0(X, *(gp_Pnt2d*)pp_P); } void Macad::Occt::Adaptor2d_Line2d::D1(double X, Macad::Occt::Pnt2d% P, Macad::Occt::Vec2d% V) { pin_ptr<Macad::Occt::Pnt2d> pp_P = &P; pin_ptr<Macad::Occt::Vec2d> pp_V = &V; ((::Adaptor2d_Line2d*)_NativeInstance)->D1(X, *(gp_Pnt2d*)pp_P, *(gp_Vec2d*)pp_V); } void Macad::Occt::Adaptor2d_Line2d::D2(double X, Macad::Occt::Pnt2d% P, Macad::Occt::Vec2d% V1, Macad::Occt::Vec2d% V2) { pin_ptr<Macad::Occt::Pnt2d> pp_P = &P; pin_ptr<Macad::Occt::Vec2d> pp_V1 = &V1; pin_ptr<Macad::Occt::Vec2d> pp_V2 = &V2; ((::Adaptor2d_Line2d*)_NativeInstance)->D2(X, *(gp_Pnt2d*)pp_P, *(gp_Vec2d*)pp_V1, *(gp_Vec2d*)pp_V2); } void Macad::Occt::Adaptor2d_Line2d::D3(double X, Macad::Occt::Pnt2d% P, Macad::Occt::Vec2d% V1, Macad::Occt::Vec2d% V2, Macad::Occt::Vec2d% V3) { pin_ptr<Macad::Occt::Pnt2d> pp_P = &P; pin_ptr<Macad::Occt::Vec2d> pp_V1 = &V1; pin_ptr<Macad::Occt::Vec2d> pp_V2 = &V2; pin_ptr<Macad::Occt::Vec2d> pp_V3 = &V3; ((::Adaptor2d_Line2d*)_NativeInstance)->D3(X, *(gp_Pnt2d*)pp_P, *(gp_Vec2d*)pp_V1, *(gp_Vec2d*)pp_V2, *(gp_Vec2d*)pp_V3); } Macad::Occt::Vec2d Macad::Occt::Adaptor2d_Line2d::DN(double U, int N) { return Macad::Occt::Vec2d(((::Adaptor2d_Line2d*)_NativeInstance)->DN(U, N)); } double Macad::Occt::Adaptor2d_Line2d::Resolution(double R3d) { return ((::Adaptor2d_Line2d*)_NativeInstance)->Resolution(R3d); } Macad::Occt::GeomAbs_CurveType Macad::Occt::Adaptor2d_Line2d::GetGeomType() { return (Macad::Occt::GeomAbs_CurveType)((::Adaptor2d_Line2d*)_NativeInstance)->GetType(); } Macad::Occt::gp_Lin2d^ Macad::Occt::Adaptor2d_Line2d::Line() { ::gp_Lin2d* _result = new ::gp_Lin2d(); *_result = ((::Adaptor2d_Line2d*)_NativeInstance)->Line(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Lin2d(_result); } Macad::Occt::gp_Circ2d^ Macad::Occt::Adaptor2d_Line2d::Circle() { ::gp_Circ2d* _result = new ::gp_Circ2d(); *_result = ((::Adaptor2d_Line2d*)_NativeInstance)->Circle(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Circ2d(_result); } Macad::Occt::gp_Elips2d^ Macad::Occt::Adaptor2d_Line2d::Ellipse() { ::gp_Elips2d* _result = new ::gp_Elips2d(); *_result = ((::Adaptor2d_Line2d*)_NativeInstance)->Ellipse(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Elips2d(_result); } Macad::Occt::gp_Hypr2d^ Macad::Occt::Adaptor2d_Line2d::Hyperbola() { ::gp_Hypr2d* _result = new ::gp_Hypr2d(); *_result = ((::Adaptor2d_Line2d*)_NativeInstance)->Hyperbola(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Hypr2d(_result); } Macad::Occt::gp_Parab2d^ Macad::Occt::Adaptor2d_Line2d::Parabola() { ::gp_Parab2d* _result = new ::gp_Parab2d(); *_result = ((::Adaptor2d_Line2d*)_NativeInstance)->Parabola(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Parab2d(_result); } int Macad::Occt::Adaptor2d_Line2d::Degree() { return ((::Adaptor2d_Line2d*)_NativeInstance)->Degree(); } bool Macad::Occt::Adaptor2d_Line2d::IsRational() { return ((::Adaptor2d_Line2d*)_NativeInstance)->IsRational(); } int Macad::Occt::Adaptor2d_Line2d::NbPoles() { return ((::Adaptor2d_Line2d*)_NativeInstance)->NbPoles(); } int Macad::Occt::Adaptor2d_Line2d::NbKnots() { return ((::Adaptor2d_Line2d*)_NativeInstance)->NbKnots(); } Macad::Occt::Geom2d_BezierCurve^ Macad::Occt::Adaptor2d_Line2d::Bezier() { Handle(::Geom2d_BezierCurve) _result; _result = ((::Adaptor2d_Line2d*)_NativeInstance)->Bezier(); return _result.IsNull() ? nullptr : Macad::Occt::Geom2d_BezierCurve::CreateDowncasted( _result.get()); } Macad::Occt::Geom2d_BSplineCurve^ Macad::Occt::Adaptor2d_Line2d::BSpline() { Handle(::Geom2d_BSplineCurve) _result; _result = ((::Adaptor2d_Line2d*)_NativeInstance)->BSpline(); return _result.IsNull() ? nullptr : Macad::Occt::Geom2d_BSplineCurve::CreateDowncasted( _result.get()); } //--------------------------------------------------------------------- // Class Adaptor2d_HLine2d //--------------------------------------------------------------------- Macad::Occt::Adaptor2d_HLine2d::Adaptor2d_HLine2d() : Macad::Occt::Adaptor2d_HCurve2d(BaseClass::InitMode::Uninitialized) { NativeInstance = new ::Adaptor2d_HLine2d(); } Macad::Occt::Adaptor2d_HLine2d::Adaptor2d_HLine2d(Macad::Occt::Adaptor2d_Line2d^ C) : Macad::Occt::Adaptor2d_HCurve2d(BaseClass::InitMode::Uninitialized) { NativeInstance = new ::Adaptor2d_HLine2d(*(::Adaptor2d_Line2d*)C->NativeInstance); } Macad::Occt::Adaptor2d_HLine2d::Adaptor2d_HLine2d(Macad::Occt::Adaptor2d_HLine2d^ parameter1) : Macad::Occt::Adaptor2d_HCurve2d(BaseClass::InitMode::Uninitialized) { NativeInstance = new ::Adaptor2d_HLine2d(*(::Adaptor2d_HLine2d*)parameter1->NativeInstance); } void Macad::Occt::Adaptor2d_HLine2d::Set(Macad::Occt::Adaptor2d_Line2d^ C) { ((::Adaptor2d_HLine2d*)_NativeInstance)->Set(*(::Adaptor2d_Line2d*)C->NativeInstance); } Macad::Occt::Adaptor2d_Curve2d^ Macad::Occt::Adaptor2d_HLine2d::Curve2d() { ::Adaptor2d_Curve2d* _result = new ::Adaptor2d_Curve2d(); *_result = (::Adaptor2d_Curve2d)((::Adaptor2d_HLine2d*)_NativeInstance)->Curve2d(); return _result==nullptr ? nullptr : gcnew Macad::Occt::Adaptor2d_Curve2d(_result); } Macad::Occt::Adaptor2d_Line2d^ Macad::Occt::Adaptor2d_HLine2d::ChangeCurve2d() { ::Adaptor2d_Line2d* _result = new ::Adaptor2d_Line2d(); *_result = ((::Adaptor2d_HLine2d*)_NativeInstance)->ChangeCurve2d(); return _result==nullptr ? nullptr : gcnew Macad::Occt::Adaptor2d_Line2d(_result); } Macad::Occt::Adaptor2d_HLine2d^ Macad::Occt::Adaptor2d_HLine2d::CreateDowncasted(::Adaptor2d_HLine2d* instance) { return gcnew Macad::Occt::Adaptor2d_HLine2d( instance ); } //--------------------------------------------------------------------- // Class Adaptor2d_OffsetCurve //--------------------------------------------------------------------- Macad::Occt::Adaptor2d_OffsetCurve::Adaptor2d_OffsetCurve() : Macad::Occt::Adaptor2d_Curve2d(BaseClass::InitMode::Uninitialized) { _NativeInstance = new ::Adaptor2d_OffsetCurve(); } Macad::Occt::Adaptor2d_OffsetCurve::Adaptor2d_OffsetCurve(Macad::Occt::Adaptor2d_HCurve2d^ C) : Macad::Occt::Adaptor2d_Curve2d(BaseClass::InitMode::Uninitialized) { Handle(::Adaptor2d_HCurve2d) h_C = C->NativeInstance; _NativeInstance = new ::Adaptor2d_OffsetCurve(h_C); C->NativeInstance = h_C.get(); } Macad::Occt::Adaptor2d_OffsetCurve::Adaptor2d_OffsetCurve(Macad::Occt::Adaptor2d_HCurve2d^ C, double Offset) : Macad::Occt::Adaptor2d_Curve2d(BaseClass::InitMode::Uninitialized) { Handle(::Adaptor2d_HCurve2d) h_C = C->NativeInstance; _NativeInstance = new ::Adaptor2d_OffsetCurve(h_C, Offset); C->NativeInstance = h_C.get(); } Macad::Occt::Adaptor2d_OffsetCurve::Adaptor2d_OffsetCurve(Macad::Occt::Adaptor2d_HCurve2d^ C, double Offset, double WFirst, double WLast) : Macad::Occt::Adaptor2d_Curve2d(BaseClass::InitMode::Uninitialized) { Handle(::Adaptor2d_HCurve2d) h_C = C->NativeInstance; _NativeInstance = new ::Adaptor2d_OffsetCurve(h_C, Offset, WFirst, WLast); C->NativeInstance = h_C.get(); } Macad::Occt::Adaptor2d_OffsetCurve::Adaptor2d_OffsetCurve(Macad::Occt::Adaptor2d_OffsetCurve^ parameter1) : Macad::Occt::Adaptor2d_Curve2d(BaseClass::InitMode::Uninitialized) { _NativeInstance = new ::Adaptor2d_OffsetCurve(*(::Adaptor2d_OffsetCurve*)parameter1->NativeInstance); } void Macad::Occt::Adaptor2d_OffsetCurve::Load(Macad::Occt::Adaptor2d_HCurve2d^ S) { Handle(::Adaptor2d_HCurve2d) h_S = S->NativeInstance; ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Load(h_S); S->NativeInstance = h_S.get(); } void Macad::Occt::Adaptor2d_OffsetCurve::Load(double Offset) { ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Load(Offset); } void Macad::Occt::Adaptor2d_OffsetCurve::Load(double Offset, double WFirst, double WLast) { ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Load(Offset, WFirst, WLast); } Macad::Occt::Adaptor2d_HCurve2d^ Macad::Occt::Adaptor2d_OffsetCurve::Curve() { Handle(::Adaptor2d_HCurve2d) _result; _result = ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Curve(); return _result.IsNull() ? nullptr : Macad::Occt::Adaptor2d_HCurve2d::CreateDowncasted( _result.get()); } double Macad::Occt::Adaptor2d_OffsetCurve::Offset() { return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Offset(); } double Macad::Occt::Adaptor2d_OffsetCurve::FirstParameter() { return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->FirstParameter(); } double Macad::Occt::Adaptor2d_OffsetCurve::LastParameter() { return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->LastParameter(); } Macad::Occt::GeomAbs_Shape Macad::Occt::Adaptor2d_OffsetCurve::Continuity() { return (Macad::Occt::GeomAbs_Shape)((::Adaptor2d_OffsetCurve*)_NativeInstance)->Continuity(); } int Macad::Occt::Adaptor2d_OffsetCurve::NbIntervals(Macad::Occt::GeomAbs_Shape S) { return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->NbIntervals((::GeomAbs_Shape)S); } void Macad::Occt::Adaptor2d_OffsetCurve::Intervals(Macad::Occt::TColStd_Array1OfReal^ T, Macad::Occt::GeomAbs_Shape S) { ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Intervals(*(::TColStd_Array1OfReal*)T->NativeInstance, (::GeomAbs_Shape)S); } Macad::Occt::Adaptor2d_HCurve2d^ Macad::Occt::Adaptor2d_OffsetCurve::Trim(double First, double Last, double Tol) { Handle(::Adaptor2d_HCurve2d) _result; _result = ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Trim(First, Last, Tol); return _result.IsNull() ? nullptr : Macad::Occt::Adaptor2d_HCurve2d::CreateDowncasted( _result.get()); } bool Macad::Occt::Adaptor2d_OffsetCurve::IsClosed() { return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->IsClosed(); } bool Macad::Occt::Adaptor2d_OffsetCurve::IsPeriodic() { return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->IsPeriodic(); } double Macad::Occt::Adaptor2d_OffsetCurve::Period() { return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Period(); } Macad::Occt::Pnt2d Macad::Occt::Adaptor2d_OffsetCurve::Value(double U) { return Macad::Occt::Pnt2d(((::Adaptor2d_OffsetCurve*)_NativeInstance)->Value(U)); } void Macad::Occt::Adaptor2d_OffsetCurve::D0(double U, Macad::Occt::Pnt2d% P) { pin_ptr<Macad::Occt::Pnt2d> pp_P = &P; ((::Adaptor2d_OffsetCurve*)_NativeInstance)->D0(U, *(gp_Pnt2d*)pp_P); } void Macad::Occt::Adaptor2d_OffsetCurve::D1(double U, Macad::Occt::Pnt2d% P, Macad::Occt::Vec2d% V) { pin_ptr<Macad::Occt::Pnt2d> pp_P = &P; pin_ptr<Macad::Occt::Vec2d> pp_V = &V; ((::Adaptor2d_OffsetCurve*)_NativeInstance)->D1(U, *(gp_Pnt2d*)pp_P, *(gp_Vec2d*)pp_V); } void Macad::Occt::Adaptor2d_OffsetCurve::D2(double U, Macad::Occt::Pnt2d% P, Macad::Occt::Vec2d% V1, Macad::Occt::Vec2d% V2) { pin_ptr<Macad::Occt::Pnt2d> pp_P = &P; pin_ptr<Macad::Occt::Vec2d> pp_V1 = &V1; pin_ptr<Macad::Occt::Vec2d> pp_V2 = &V2; ((::Adaptor2d_OffsetCurve*)_NativeInstance)->D2(U, *(gp_Pnt2d*)pp_P, *(gp_Vec2d*)pp_V1, *(gp_Vec2d*)pp_V2); } void Macad::Occt::Adaptor2d_OffsetCurve::D3(double U, Macad::Occt::Pnt2d% P, Macad::Occt::Vec2d% V1, Macad::Occt::Vec2d% V2, Macad::Occt::Vec2d% V3) { pin_ptr<Macad::Occt::Pnt2d> pp_P = &P; pin_ptr<Macad::Occt::Vec2d> pp_V1 = &V1; pin_ptr<Macad::Occt::Vec2d> pp_V2 = &V2; pin_ptr<Macad::Occt::Vec2d> pp_V3 = &V3; ((::Adaptor2d_OffsetCurve*)_NativeInstance)->D3(U, *(gp_Pnt2d*)pp_P, *(gp_Vec2d*)pp_V1, *(gp_Vec2d*)pp_V2, *(gp_Vec2d*)pp_V3); } Macad::Occt::Vec2d Macad::Occt::Adaptor2d_OffsetCurve::DN(double U, int N) { return Macad::Occt::Vec2d(((::Adaptor2d_OffsetCurve*)_NativeInstance)->DN(U, N)); } double Macad::Occt::Adaptor2d_OffsetCurve::Resolution(double R3d) { return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Resolution(R3d); } Macad::Occt::GeomAbs_CurveType Macad::Occt::Adaptor2d_OffsetCurve::GetGeomType() { return (Macad::Occt::GeomAbs_CurveType)((::Adaptor2d_OffsetCurve*)_NativeInstance)->GetType(); } Macad::Occt::gp_Lin2d^ Macad::Occt::Adaptor2d_OffsetCurve::Line() { ::gp_Lin2d* _result = new ::gp_Lin2d(); *_result = ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Line(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Lin2d(_result); } Macad::Occt::gp_Circ2d^ Macad::Occt::Adaptor2d_OffsetCurve::Circle() { ::gp_Circ2d* _result = new ::gp_Circ2d(); *_result = ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Circle(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Circ2d(_result); } Macad::Occt::gp_Elips2d^ Macad::Occt::Adaptor2d_OffsetCurve::Ellipse() { ::gp_Elips2d* _result = new ::gp_Elips2d(); *_result = ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Ellipse(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Elips2d(_result); } Macad::Occt::gp_Hypr2d^ Macad::Occt::Adaptor2d_OffsetCurve::Hyperbola() { ::gp_Hypr2d* _result = new ::gp_Hypr2d(); *_result = ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Hyperbola(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Hypr2d(_result); } Macad::Occt::gp_Parab2d^ Macad::Occt::Adaptor2d_OffsetCurve::Parabola() { ::gp_Parab2d* _result = new ::gp_Parab2d(); *_result = ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Parabola(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Parab2d(_result); } int Macad::Occt::Adaptor2d_OffsetCurve::Degree() { return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Degree(); } bool Macad::Occt::Adaptor2d_OffsetCurve::IsRational() { return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->IsRational(); } int Macad::Occt::Adaptor2d_OffsetCurve::NbPoles() { return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->NbPoles(); } int Macad::Occt::Adaptor2d_OffsetCurve::NbKnots() { return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->NbKnots(); } Macad::Occt::Geom2d_BezierCurve^ Macad::Occt::Adaptor2d_OffsetCurve::Bezier() { Handle(::Geom2d_BezierCurve) _result; _result = ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Bezier(); return _result.IsNull() ? nullptr : Macad::Occt::Geom2d_BezierCurve::CreateDowncasted( _result.get()); } Macad::Occt::Geom2d_BSplineCurve^ Macad::Occt::Adaptor2d_OffsetCurve::BSpline() { Handle(::Geom2d_BSplineCurve) _result; _result = ((::Adaptor2d_OffsetCurve*)_NativeInstance)->BSpline(); return _result.IsNull() ? nullptr : Macad::Occt::Geom2d_BSplineCurve::CreateDowncasted( _result.get()); } int Macad::Occt::Adaptor2d_OffsetCurve::NbSamples() { return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->NbSamples(); } //--------------------------------------------------------------------- // Class Adaptor2d_HOffsetCurve //--------------------------------------------------------------------- Macad::Occt::Adaptor2d_HOffsetCurve::Adaptor2d_HOffsetCurve() : Macad::Occt::Adaptor2d_HCurve2d(BaseClass::InitMode::Uninitialized) { NativeInstance = new ::Adaptor2d_HOffsetCurve(); } Macad::Occt::Adaptor2d_HOffsetCurve::Adaptor2d_HOffsetCurve(Macad::Occt::Adaptor2d_OffsetCurve^ C) : Macad::Occt::Adaptor2d_HCurve2d(BaseClass::InitMode::Uninitialized) { NativeInstance = new ::Adaptor2d_HOffsetCurve(*(::Adaptor2d_OffsetCurve*)C->NativeInstance); } Macad::Occt::Adaptor2d_HOffsetCurve::Adaptor2d_HOffsetCurve(Macad::Occt::Adaptor2d_HOffsetCurve^ parameter1) : Macad::Occt::Adaptor2d_HCurve2d(BaseClass::InitMode::Uninitialized) { NativeInstance = new ::Adaptor2d_HOffsetCurve(*(::Adaptor2d_HOffsetCurve*)parameter1->NativeInstance); } void Macad::Occt::Adaptor2d_HOffsetCurve::Set(Macad::Occt::Adaptor2d_OffsetCurve^ C) { ((::Adaptor2d_HOffsetCurve*)_NativeInstance)->Set(*(::Adaptor2d_OffsetCurve*)C->NativeInstance); } Macad::Occt::Adaptor2d_Curve2d^ Macad::Occt::Adaptor2d_HOffsetCurve::Curve2d() { ::Adaptor2d_Curve2d* _result = new ::Adaptor2d_Curve2d(); *_result = (::Adaptor2d_Curve2d)((::Adaptor2d_HOffsetCurve*)_NativeInstance)->Curve2d(); return _result==nullptr ? nullptr : gcnew Macad::Occt::Adaptor2d_Curve2d(_result); } Macad::Occt::Adaptor2d_OffsetCurve^ Macad::Occt::Adaptor2d_HOffsetCurve::ChangeCurve2d() { ::Adaptor2d_OffsetCurve* _result = new ::Adaptor2d_OffsetCurve(); *_result = ((::Adaptor2d_HOffsetCurve*)_NativeInstance)->ChangeCurve2d(); return _result==nullptr ? nullptr : gcnew Macad::Occt::Adaptor2d_OffsetCurve(_result); } Macad::Occt::Adaptor2d_HOffsetCurve^ Macad::Occt::Adaptor2d_HOffsetCurve::CreateDowncasted(::Adaptor2d_HOffsetCurve* instance) { return gcnew Macad::Occt::Adaptor2d_HOffsetCurve( instance ); }
34,893
16,665
/*********************************************************************** created: 28/5/2011 author: Martin Preisler purpose: Implements platform independent clipboard handling *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/Clipboard.h" // Start of CEGUI namespace section namespace CEGUI { NativeClipboardProvider::~NativeClipboardProvider() {} //----------------------------------------------------------------------------// Clipboard::Clipboard(): d_mimeType("text/plain"), // reasonable default I think d_buffer(0), d_bufferSize(0), d_nativeProvider(0) {} //----------------------------------------------------------------------------// Clipboard::~Clipboard() { if (d_buffer != 0) { delete[] d_buffer; } } //----------------------------------------------------------------------------// void Clipboard::setNativeProvider(NativeClipboardProvider* provider) { d_nativeProvider = provider; } //----------------------------------------------------------------------------// NativeClipboardProvider* Clipboard::getNativeProvider() const { return d_nativeProvider; } //----------------------------------------------------------------------------// void Clipboard::setData(const String& mimeType, const void* buffer, size_t size) { d_mimeType = mimeType; if (size != d_bufferSize) { if (d_buffer != 0) { delete[] d_buffer; d_buffer = 0; } d_bufferSize = size; d_buffer = new BufferElement[d_bufferSize]; } memcpy(d_buffer, buffer, d_bufferSize); // we have set the data to the internal clipboard, now sync it with the // system-wide native clipboard if possible if (d_nativeProvider) { d_nativeProvider->sendToClipboard(d_mimeType, d_buffer, d_bufferSize); } } //----------------------------------------------------------------------------// void Clipboard::getData(String& mimeType, const void*& buffer, size_t& size) { // first make sure we are in sync with system-wide native clipboard // (if possible) if (d_nativeProvider) { size_t retrievedSize; void* retrievedBuffer; d_nativeProvider->retrieveFromClipboard(d_mimeType, retrievedBuffer, retrievedSize); if (retrievedSize != d_bufferSize) { if (d_buffer != 0) { delete[] d_buffer; d_buffer = 0; } d_bufferSize = retrievedSize; d_buffer = new BufferElement[d_bufferSize]; } memcpy(d_buffer, retrievedBuffer, retrievedSize); } mimeType = d_mimeType; buffer = d_buffer; size = d_bufferSize; } //----------------------------------------------------------------------------// void Clipboard::setText(const String& text) { // could be just ASCII if std::string is used as CEGUI::String const char* utf8_bytes = text.c_str(); // we don't want the actual string length, that might not be the buffer size // in case of utf8! // this gets us the number of bytes until \0 is encountered const size_t size = strlen(utf8_bytes); setData("text/plain", static_cast<const void*>(utf8_bytes), size); } //----------------------------------------------------------------------------// String Clipboard::getText() { String mimeType; const void* buffer; size_t size; // we have to use this, can't use the member variables directly because of // the native clipboard provider! getData(mimeType, buffer, size); if (mimeType == "text/plain" && size != 0) { // d_buffer an utf8 or ASCII C string (ASCII if std::string is used) // !!! However it is not null terminated !!! So we have to tell String // how many code units (not code points!) there are. #if CEGUI_STRING_CLASS == CEGUI_STRING_CLASS_UNICODE return String(reinterpret_cast<const utf8*>(d_buffer), d_bufferSize); #else return String(static_cast<const char*>(d_buffer), d_bufferSize); #endif } else { // the held mime type differs, it's not plain text so we can't // return it as just string return String(); } } //----------------------------------------------------------------------------// } // End of CEGUI namespace section
5,782
1,620
// Copyright 2018 The Chromium OS 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 "diagnostics/dpsl/internal/dpsl_thread_context_impl.h" #include <utility> #include <base/lazy_instance.h> #include <base/location.h> #include <base/logging.h> #include <base/threading/thread_local.h> #include <base/threading/thread_task_runner_handle.h> #include <base/time/time.h> #include "diagnostics/dpsl/internal/callback_utils.h" namespace diagnostics { namespace { // Whether an instance of DpslThreadContextImpl was created on the current // thread. base::LazyInstance<base::ThreadLocalBoolean>::Leaky g_thread_context_impl_created = LAZY_INSTANCE_INITIALIZER; } // namespace // static void DpslThreadContextImpl::CleanThreadCounterForTesting() { g_thread_context_impl_created.Pointer()->Set(false); } DpslThreadContextImpl::DpslThreadContextImpl() : thread_id_(base::PlatformThread::CurrentId()), // Initialize the SingleThreadTaskExecutor only if there's no TaskRunner // yet (it could be already set up by the calling code via other means, // e.g., brillo::Daemon). owned_task_executor_( base::ThreadTaskRunnerHandle::IsSet() ? nullptr : std::make_unique<base::SingleThreadTaskExecutor>( base::MessagePumpType::IO)), task_runner_(base::ThreadTaskRunnerHandle::Get()) {} DpslThreadContextImpl::~DpslThreadContextImpl() { CHECK(sequence_checker_.CalledOnValidSequence()) << "Called from wrong thread"; } bool DpslThreadContextImpl::BelongsToCurrentThread() { return base::PlatformThread::CurrentId() == thread_id_; } void DpslThreadContextImpl::RunEventLoop() { CHECK(sequence_checker_.CalledOnValidSequence()) << "Called from wrong thread"; CHECK(!base::RunLoop::IsRunningOnCurrentThread()) << "Called from already running message loop"; CHECK(!current_run_loop_); base::RunLoop run_loop; current_run_loop_ = &run_loop; run_loop.Run(); current_run_loop_ = nullptr; } bool DpslThreadContextImpl::IsEventLoopRunning() { CHECK(sequence_checker_.CalledOnValidSequence()) << "Called from wrong thread"; return current_run_loop_ != nullptr; } void DpslThreadContextImpl::PostTask(std::function<void()> task) { task_runner_->PostTask(FROM_HERE, MakeCallbackFromStdFunction(std::move(task))); } void DpslThreadContextImpl::PostDelayedTask(std::function<void()> task, int64_t delay_milliseconds) { CHECK_GE(delay_milliseconds, 0) << "Delay must be non-negative"; task_runner_->PostDelayedTask( FROM_HERE, MakeCallbackFromStdFunction(std::move(task)), base::TimeDelta::FromMilliseconds(delay_milliseconds)); } void DpslThreadContextImpl::QuitEventLoop() { CHECK(sequence_checker_.CalledOnValidSequence()) << "Called from wrong thread"; if (current_run_loop_) current_run_loop_->Quit(); } // static std::unique_ptr<DpslThreadContext> DpslThreadContext::Create( DpslGlobalContext* global_context) { CHECK(global_context) << "GlobalContext is nullptr"; // Verify we're not called twice on the current thread. CHECK(!g_thread_context_impl_created.Pointer()->Get()) << "Duplicate DpslThreadContext instances constructed on the same thread"; g_thread_context_impl_created.Pointer()->Set(true); return std::make_unique<DpslThreadContextImpl>(); } } // namespace diagnostics
3,536
1,105
#pragma once #ifndef DISH2_PERIPHERAL_READABLE_STATE_INTROSPECTIVE_STATE_RESOURCESTOCKPILE_HPP_INCLUDE #define DISH2_PERIPHERAL_READABLE_STATE_INTROSPECTIVE_STATE_RESOURCESTOCKPILE_HPP_INCLUDE #include "../../../../../third-party/conduit/include/uitsl/datastructs/PodLeafNode.hpp" #include "../../../../../third-party/conduit/include/uitsl/meta/TypeName.hpp" namespace dish2 { struct ResourceStockpile : public uitsl::PodLeafNode<float> { // inherit constructors using parent_t = uitsl::PodLeafNode<float>; using parent_t::parent_t; }; } // namespace dish2 namespace uitsl { UITSL_ENABLE_TYPENAME( dish2::ResourceStockpile ); } // namespace uitsl #endif // #ifndef DISH2_PERIPHERAL_READABLE_STATE_INTROSPECTIVE_STATE_RESOURCESTOCKPILE_HPP_INCLUDE
761
312
/* Name: stdafx Copyright: Copyright (C) 2003-2017 SIL International. Documentation: Description: Create Date: 28 Jun 2011 Modified Date: 28 Jun 2011 Authors: mcdurdin Related Files: Dependencies: Bugs: Todo: Notes: History: 28 Jun 2011 - mcdurdin - I2908 - Fix double-strike characters */ // stdafx.cpp : source file that includes just the standard includes // i2908.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
704
237
#include "DarkTemplarRush.h" #include "..\..\UnitUtil.h" using UAlbertaBot::MetaPairVector; using UAlbertaBot::MetaPair; using UAlbertaBot::UnitUtil::GetAllUnitCount; AKBot::DarkTemplarRush::DarkTemplarRush(BWAPI::Player self) : _self(self) { } void AKBot::DarkTemplarRush::getBuildOrderGoal(MetaPairVector& goal, int currentFrame) const { int numDragoons = GetAllUnitCount(_self, BWAPI::UnitTypes::Protoss_Dragoon); int numNexusAll = GetAllUnitCount(_self, BWAPI::UnitTypes::Protoss_Nexus); int numDarkTeplar = GetAllUnitCount(_self, BWAPI::UnitTypes::Protoss_Dark_Templar); goal.push_back(MetaPair(BWAPI::UnitTypes::Protoss_Dark_Templar, numDarkTeplar + 2)); // if we have a 2nd nexus then get some goons out if (numNexusAll >= 2) { goal.push_back(MetaPair(BWAPI::UnitTypes::Protoss_Dragoon, numDragoons + 4)); } }
833
353
#pragma once #include <toy_compiler/munster/ast/op/op.hpp> namespace munster::ast { class assign_op : public op { public: using ptr = std::unique_ptr<assign_op>; public: assign_op(node_ptr val_0, node_ptr id_decl, node_ptr val_1); void accept(visitor_variant &visitor) const override; [[nodiscard]] auto to_string() const -> std::string override; }; } // namespace munster::ast
422
149
/************************************************************************** * * Copyright (c) 2002 - 2011 by Computer Architecture Department, * Universitat Politecnica de Catalunya. * All rights reserved. * * The contents of this file may not b;e disclosed to third parties, * copied or duplicated in any form, in whole or in part, without the * prior permission of the authors, Computer Architecture Department * and Universitat Politecnica de Catalunya. * * $RCSfile: ZCacheV2.cpp,v $ * $Revision: 1.5 $ * $Author: vmoya $ * $Date: 2008-03-02 19:09:17 $ * * Z Cache class implementation file. * */ /** * * @file ZCacheV2.cpp * * Implements the Z Cache class. This class the cache used for access to the Z buffer in a GPU. * */ #include "ZCacheV2.h" #include "GPUMath.h" #include "FragmentOpEmulator.h" using namespace gpu3d; // Z Cache class counter. Used to create identifiers for the created Z Caches // that are then used to access the Memory Controller. u32bit ZCacheV2::cacheCounter = 0; // Z cache constructor. ZCacheV2::ZCacheV2(u32bit ways, u32bit lines, u32bit lineSz, u32bit readP, u32bit writeP, u32bit pWidth, u32bit reqQSize, u32bit inReqs, u32bit outReqs, bool zComprDisabled, u32bit numStampUnits, u32bit stampUnitStride, u32bit maxZBlocks, u32bit blocksPerCycle, u32bit compCycles, u32bit decompCycles, char *postfix #if KONDAMASK_CACHE_DECAY , u32bit decayInterval #endif ) : ROPCache(ways, lines, lineSz, readP, writeP, pWidth, reqQSize, inReqs, outReqs, zComprDisabled, numStampUnits, stampUnitStride, maxZBlocks, blocksPerCycle, compCycles, decompCycles, ZSTENCILTEST, "ZCache", postfix #if KONDAMASK_CACHE_DECAY , decayInterval #endif ) { // Get the Z Cache identifier. cacheID = cacheCounter; // Update the number of created Z Caches. cacheCounter++; // Set reset value for clear. for (u32bit i = 0; i < (MAX_BYTES_PER_PIXEL >> 2); i++) ((u32bit *) clearResetValue)[i] = 0x00ffffff; } // Clears the Z cache. bool ZCacheV2::clear(u32bit depth, u8bit stencil) { // Reset the cache. if (clearMode) { // Check clear cycles remaining. if (clearCycles > 0) { // Update clear cycles. clearCycles--; // Check if end of clear. if (clearCycles == 0) { // Set the clear value registers. clearDepth = depth; clearStencil = stencil; // Set the ROP data clear value ((u32bit *) clearROPValue)[0] = (clearStencil << 24) | (clearDepth & 0x00ffffff); /* Unset reset mode. */ clearMode = FALSE; } } } else { // NOTE: SHOULD TAKE INTO ACCOUNT THE RESOLUTION SO NOT ALL // BLOCKS HAD TO BE CLEARED EVEN IF UNUSED AT CURRENT RESOLUTION. // Set clear cycles. clearCycles = (u32bit) ceil((f32bit) maxBlocks / (f32bit) blocksCycle); // Set clear mode. clearMode = TRUE; // Reset the cache. resetMode = TRUE; } return clearMode; } // Check HZ updates. bool ZCacheV2::updateHZ(u32bit &block, u32bit &z) { // Check if there is an updated block. if (blockWasWritten) { // Return block identifier and block Z. block = writtenBlock; z = wrBlockMaxVal; // Reset updated HZ block flag. blockWasWritten = false; return true; } else return false; } void ZCacheV2::processNextWrittenBlock(u8bit* outputBuffer, u32bit size) { u32bit* data = (u32bit*) outputBuffer; u32bit dataSize = size / sizeof(u32bit); u32bit maxZ; // Calculate the maximum depth/Z. FragmentOpEmulator::blockMaxZ(data, dataSize, maxZ); // Store for later use wrBlockMaxVal = maxZ; } // Copies the block state memory. void ZCacheV2::copyBlockStateMemory(ROPBlockState *buffer, u32bit blocks) { GPU_ASSERT( if (blocks > maxBlocks) panic("ZCache", "copyBlockSateMemory", "More blocks to copy than blocks in the state memory."); ) // Copy the block states. memcpy(buffer, blockState, sizeof(ROPBlockState) * blocks); }
3,886
1,553
#include "printer.hpp" #ifndef RANGE_HPP #define RANGE_HPP struct range { int start; int stop; int stride; range(int start, int stop) : start(start), stop(stop), stride(1) {} range(int start, int stop, int stride) : start(start), stop(stop), stride(stride) {} struct iterator; iterator begin() { return iterator(start, stride, stride > 0); } iterator end() { return iterator(stop, stride, stride > 0); } range step(int stride) { if (stride < 0) return range(stop, start, stride * this->stride); else return range(start, stop, stride * this->stride); } struct iterator { int value; bool increasing = true; int step = 1; iterator(int value, int step, bool increasing) : value(value), step(step), increasing(increasing) {} iterator &operator=(int element) { value = element; return *this; } // Prefix iterator &operator++() { value += step; return *this; } // Postfix iterator operator++(int) { auto temp = iterator(value, this->step, increasing); value += step; return temp; } bool operator!=(const iterator &iter) { return increasing ? value < iter.value : value > iter.value; } int operator*() { return value; } }; }; #endif
1,504
440
#pragma once #include "Injector/Defines.hpp" #include "Injector/ECS/EcsManager.hpp" #include "Injector/Mathematics/Matrix4.hpp" #include "Injector/Graphics/GraphicsAPI.hpp" #include <chrono> namespace Injector { class Engine final { private: static bool engineInitialized; static bool networkInitialized; static bool graphicsInitialized; static bool virtualRealityInitialized; static bool updateRunning; static bool capUpdateRate; static int targetUpdateRate; static std::chrono::steady_clock:: time_point updateStartTick; static double updateStartTime; static double updateDeltaTime; static GraphicsAPI graphicsAPI; static FloatMatrix4 hmdModelMatrix; static FloatMatrix4 leftEyeModelMatrix; static FloatMatrix4 rightEyeModelMatrix; static FloatMatrix4 leftEyeProjMatrix; static FloatMatrix4 rightEyeProjMatrix; static std::vector<std::shared_ptr<EcsManager>> managers; public: static bool getCapUpdateRate() noexcept; static void setCapUpdateRate(bool cap = true) noexcept; static int getTargetUpdateRate() noexcept; static void setTargetUpdateRate(int ups = 60) noexcept; static std::chrono::steady_clock:: time_point getUpdateStartTick() noexcept; static double getUpdateStartTime() noexcept; static double getUpdateDeltaTime() noexcept; static void initializeEngine( int majorVersion = INJECTOR_VERSION_MAJOR, int minorVersion = INJECTOR_VERSION_MINOR, int patchVersion = INJECTOR_VERSION_PATCH); static void terminateEngine(); static bool isEngineInitialized() noexcept; static void initializeNetwork(); static void terminateNetwork(); static bool isNetworkInitialized(); static void glfwErrorCallback( int error, const char* description); static void initializeGraphics( GraphicsAPI graphicsAPI = GraphicsAPI::OpenGL); static void terminateGraphics(); static bool isGraphicsInitialized() noexcept; static void initializeVirtualReality(); static void terminateVirtualReality(); static bool isVirtualRealityInitialized() noexcept; static void startUpdateLoop(); static void stopUpdateLoop() noexcept; static bool getUpdateRunning() noexcept; static std::chrono::steady_clock:: time_point getTickNow() noexcept; static double getTimeNow() noexcept; static GraphicsAPI getGraphicsAPI() noexcept; static const FloatMatrix4& getHmdModelMatrix() noexcept; static const FloatMatrix4& getLeftEyeModelMatrix() noexcept; static const FloatMatrix4& getRightEyeModelMatrix() noexcept; static const FloatMatrix4& getLeftEyeProjMatrix() noexcept; static const FloatMatrix4& getRightEyeProjMatrix() noexcept; static bool addManager( const std::shared_ptr<EcsManager>& manager) noexcept; static bool removeManager( const std::shared_ptr<EcsManager>& manager) noexcept; static bool containsManager( const std::shared_ptr<EcsManager>& manager) noexcept; static void removeManagers() noexcept; static size_t getManagerCount() noexcept; template<class T = EcsManager, class ...Args> static std::shared_ptr<T> createManager(Args... args) noexcept { auto manager = std::make_shared<T>(args...); managers.push_back(manager); return manager; } }; }
3,214
1,030
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: shader for drawing sprites as cards, with animation frame lerping // // $Header: $ // $NoKeywords: $ //===========================================================================// #include "BaseVSShader.h" #include "convar.h" // STDSHADER_DX9_DLL_EXPORT #include "spritecard_ps20.inc" #include "spritecard_ps20b.inc" #include "spritecard_vs20.inc" #include "splinecard_vs20.inc" #if SUPPORT_DX8 // STDSHADER_DX8_DLL_EXPORT #include "spritecard_vs11.inc" #include "spritecard_ps11.inc" #include "splinecard_vs11.inc" #endif #include "tier0/icommandline.h" //command line // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #define DEFAULT_PARTICLE_FEATHERING_ENABLED 1 #ifdef STDSHADER_DX8_DLL_EXPORT DEFINE_FALLBACK_SHADER( Spritecard, Spritecard_DX8 ) #endif int GetDefaultDepthFeatheringValue( void ) //Allow the command-line to go against the default soft-particle value { static int iRetVal = -1; if( iRetVal == -1 ) { # if( DEFAULT_PARTICLE_FEATHERING_ENABLED == 1 ) { if( CommandLine()->CheckParm( "-softparticlesdefaultoff" ) ) iRetVal = 0; else iRetVal = 1; } # else { if( CommandLine()->CheckParm( "-softparticlesdefaulton" ) ) iRetVal = 1; else iRetVal = 0; } # endif } // On low end parts on the Mac, we reduce particles and shut off depth blending here static ConVarRef mat_reduceparticles( "mat_reduceparticles" ); if ( mat_reduceparticles.GetBool() ) { iRetVal = 0; } return iRetVal; } #ifdef STDSHADER_DX9_DLL_EXPORT BEGIN_VS_SHADER_FLAGS( Spritecard, "Help for Spritecard", SHADER_NOT_EDITABLE ) #else BEGIN_VS_SHADER_FLAGS( Spritecard_DX8, "Help for Spritecard_DX8", SHADER_NOT_EDITABLE ) #endif BEGIN_SHADER_PARAMS SHADER_PARAM( DEPTHBLEND, SHADER_PARAM_TYPE_INTEGER, "0", "fade at intersection boundaries" ) SHADER_PARAM( DEPTHBLENDSCALE, SHADER_PARAM_TYPE_FLOAT, "50.0", "Amplify or reduce DEPTHBLEND fading. Lower values make harder edges." ) SHADER_PARAM( ORIENTATION, SHADER_PARAM_TYPE_INTEGER, "0", "0 = always face camera, 1 = rotate around z, 2= parallel to ground" ) SHADER_PARAM( ADDBASETEXTURE2, SHADER_PARAM_TYPE_FLOAT, "0.0", "amount to blend second texture into frame by" ) SHADER_PARAM( OVERBRIGHTFACTOR, SHADER_PARAM_TYPE_FLOAT, "1.0", "overbright factor for texture. For HDR effects.") SHADER_PARAM( DUALSEQUENCE, SHADER_PARAM_TYPE_INTEGER, "0", "blend two separate animated sequences.") SHADER_PARAM( SEQUENCE_BLEND_MODE, SHADER_PARAM_TYPE_INTEGER, "0", "defines the blend mode between the images un dual sequence particles. 0 = avg, 1=alpha from first, rgb from 2nd, 2= first over second" ) SHADER_PARAM( MAXLUMFRAMEBLEND1, SHADER_PARAM_TYPE_INTEGER, "0", "instead of blending between animation frames for the first sequence, select pixels based upon max luminance" ) SHADER_PARAM( MAXLUMFRAMEBLEND2, SHADER_PARAM_TYPE_INTEGER, "0", "instead of blending between animation frames for the 2nd sequence, select pixels based upon max luminance" ) SHADER_PARAM( RAMPTEXTURE, SHADER_PARAM_TYPE_TEXTURE, "", "if specified, then the red value of the image is used to index this ramp to produce the output color" ) SHADER_PARAM( ZOOMANIMATESEQ2, SHADER_PARAM_TYPE_FLOAT, "1.0", "amount to gradually zoom between frames on the second sequence. 2.0 will double the size of a frame over its lifetime.") SHADER_PARAM( EXTRACTGREENALPHA, SHADER_PARAM_TYPE_INTEGER, "0", "grayscale data sitting in green/alpha channels") SHADER_PARAM( ADDOVERBLEND, SHADER_PARAM_TYPE_INTEGER, "0", "use ONE:INVSRCALPHA blending") SHADER_PARAM( ADDSELF, SHADER_PARAM_TYPE_FLOAT, "0.0", "amount of base texture to additively blend in" ) SHADER_PARAM( BLENDFRAMES, SHADER_PARAM_TYPE_BOOL, "1", "whether or not to smoothly blend between animated frames" ) SHADER_PARAM( MINSIZE, SHADER_PARAM_TYPE_FLOAT, "0.0", "minimum screen fractional size of particle") SHADER_PARAM( STARTFADESIZE, SHADER_PARAM_TYPE_FLOAT, "10.0", "screen fractional size to start fading particle out") SHADER_PARAM( ENDFADESIZE, SHADER_PARAM_TYPE_FLOAT, "20.0", "screen fractional size to finish fading particle out") SHADER_PARAM( MAXSIZE, SHADER_PARAM_TYPE_FLOAT, "20.0", "maximum screen fractional size of particle") SHADER_PARAM( USEINSTANCING, SHADER_PARAM_TYPE_BOOL, "1", "whether to use GPU vertex instancing (submit 1 vert per particle quad)") SHADER_PARAM( SPLINETYPE, SHADER_PARAM_TYPE_INTEGER, "0", "spline type 0 = none, 1=ctamull rom") SHADER_PARAM( MAXDISTANCE, SHADER_PARAM_TYPE_FLOAT, "100000.0", "maximum distance to draw particles at") SHADER_PARAM( FARFADEINTERVAL, SHADER_PARAM_TYPE_FLOAT, "400.0", "interval over which to fade out far away particles") END_SHADER_PARAMS SHADER_INIT_PARAMS() { INIT_FLOAT_PARM( MAXDISTANCE, 100000.0); INIT_FLOAT_PARM( FARFADEINTERVAL, 400.0); INIT_FLOAT_PARM( MAXSIZE, 20.0 ); INIT_FLOAT_PARM( ENDFADESIZE, 20.0 ); INIT_FLOAT_PARM( STARTFADESIZE, 10.0 ); INIT_FLOAT_PARM( DEPTHBLENDSCALE, 50.0 ); INIT_FLOAT_PARM( OVERBRIGHTFACTOR, 1.0 ); INIT_FLOAT_PARM( ADDBASETEXTURE2, 0.0 ); INIT_FLOAT_PARM( ADDSELF, 0.0 ); INIT_FLOAT_PARM( ZOOMANIMATESEQ2, 0.0 ); if ( !params[DEPTHBLEND]->IsDefined() ) { params[ DEPTHBLEND ]->SetIntValue( GetDefaultDepthFeatheringValue() ); } if ( !g_pHardwareConfig->SupportsPixelShaders_2_b() ) { params[ DEPTHBLEND ]->SetIntValue( 0 ); } if ( !params[DUALSEQUENCE]->IsDefined() ) { params[DUALSEQUENCE]->SetIntValue( 0 ); } if ( !params[MAXLUMFRAMEBLEND1]->IsDefined() ) { params[MAXLUMFRAMEBLEND1]->SetIntValue( 0 ); } if ( !params[MAXLUMFRAMEBLEND2]->IsDefined() ) { params[MAXLUMFRAMEBLEND2]->SetIntValue( 0 ); } if ( !params[EXTRACTGREENALPHA]->IsDefined() ) { params[EXTRACTGREENALPHA]->SetIntValue( 0 ); } if ( !params[ADDOVERBLEND]->IsDefined() ) { params[ADDOVERBLEND]->SetIntValue( 0 ); } if ( !params[BLENDFRAMES]->IsDefined() ) { params[ BLENDFRAMES ]->SetIntValue( 1 ); } if ( !params[USEINSTANCING]->IsDefined() ) { params[ USEINSTANCING ]->SetIntValue( IsX360() ? 1 : 0 ); } SET_FLAGS2( MATERIAL_VAR2_IS_SPRITECARD ); } SHADER_FALLBACK { #ifdef STDSHADER_DX9_DLL_EXPORT if ( g_pHardwareConfig->GetDXSupportLevel() < 90 ) return "SpriteCard_DX8"; #endif #ifdef STDSHADER_DX8_DLL_EXPORT // STDSHADER_DX8_DLL_EXPORT if ( g_pHardwareConfig->GetDXSupportLevel() < 80 ) return "Wireframe"; #endif return 0; } SHADER_INIT { #ifdef STDSHADER_DX9_DLL_EXPORT const bool bDX8 = false; #endif #ifdef STDSHADER_DX8_DLL_EXPORT const bool bDX8 = true; #endif SET_FLAGS2( MATERIAL_VAR2_LIGHTING_VERTEX_LIT ); if ( params[BASETEXTURE]->IsDefined() ) { bool bExtractGreenAlpha = false; if ( params[EXTRACTGREENALPHA]->IsDefined() ) { bExtractGreenAlpha = params[EXTRACTGREENALPHA]->GetIntValue() != 0; } LoadTexture( BASETEXTURE, !bExtractGreenAlpha && !bDX8 ? TEXTUREFLAGS_SRGB : 0 ); } if ( params[RAMPTEXTURE]->IsDefined() ) { LoadTexture( RAMPTEXTURE, TEXTUREFLAGS_SRGB ); } } SHADER_DRAW { #ifdef STDSHADER_DX9_DLL_EXPORT const bool bDX8 = false; #endif #ifdef STDSHADER_DX8_DLL_EXPORT const bool bDX8 = true; #endif bool bUseRampTexture = (! bDX8 ) && ( params[RAMPTEXTURE]->IsDefined() ); bool bZoomSeq2 = (! bDX8 ) && ( ( params[ZOOMANIMATESEQ2]->GetFloatValue()) > 1.0 ); bool bDepthBlend = (! bDX8 ) && ( params[DEPTHBLEND]->GetIntValue() != 0 ); bool bAdditive2ndTexture = params[ADDBASETEXTURE2]->GetFloatValue() != 0.0; int nSplineType = params[SPLINETYPE]->GetIntValue(); SHADOW_STATE { bool bSecondSequence = params[DUALSEQUENCE]->GetIntValue() != 0; bool bAddOverBlend = params[ADDOVERBLEND]->GetIntValue() != 0; bool bExtractGreenAlpha = (! bDX8 ) && ( params[EXTRACTGREENALPHA]->GetIntValue() != 0 ); bool bBlendFrames = (! bDX8 ) && ( params[BLENDFRAMES]->GetIntValue() != 0 ); if ( nSplineType ) { bBlendFrames = false; } bool bAddSelf = params[ADDSELF]->GetFloatValue() != 0.0; bool bUseInstancing = IsX360() ? ( params[ USEINSTANCING ]->GetIntValue() != 0 ) : false; if ( nSplineType ) bUseInstancing = false; // draw back-facing because of yaw spin pShaderShadow->EnableCulling( false ); // Be sure not to write to dest alpha pShaderShadow->EnableAlphaWrites( false ); pShaderShadow->EnableTexture( SHADER_SAMPLER0, true ); if ( bDX8 ) pShaderShadow->EnableTexture( SHADER_SAMPLER1, true ); if ( bAdditive2ndTexture && bDX8 ) pShaderShadow->EnableTexture( SHADER_SAMPLER3, true ); if ( bUseRampTexture ) { pShaderShadow->EnableTexture( SHADER_SAMPLER1, true ); pShaderShadow->EnableSRGBRead( SHADER_SAMPLER1, true ); } if ( bDepthBlend ) { pShaderShadow->EnableTexture( SHADER_SAMPLER2, true ); } if ( bAdditive2ndTexture || bAddSelf ) pShaderShadow->EnableAlphaTest( false ); else pShaderShadow->EnableAlphaTest( true ); pShaderShadow->AlphaFunc( SHADER_ALPHAFUNC_GREATER, 0.01f ); if ( bAdditive2ndTexture || bAddOverBlend || bAddSelf ) { EnableAlphaBlending( SHADER_BLEND_ONE, SHADER_BLEND_ONE_MINUS_SRC_ALPHA ); } else { if ( IS_FLAG_SET(MATERIAL_VAR_ADDITIVE) ) { EnableAlphaBlending( SHADER_BLEND_SRC_ALPHA, SHADER_BLEND_ONE ); } else { EnableAlphaBlending( SHADER_BLEND_SRC_ALPHA, SHADER_BLEND_ONE_MINUS_SRC_ALPHA ); } } unsigned int flags = VERTEX_POSITION | VERTEX_COLOR; static int s_TexCoordSize[8]={4, // 0 = sheet bounding uvs, frame0 4, // 1 = sheet bounding uvs, frame 1 4, // 2 = frame blend, rot, radius, ??? 2, // 3 = corner identifier ( 0/0,1/0,1/1, 1/0 ) 4, // 4 = texture 2 bounding uvs 4, // 5 = second sequence bounding uvs, frame0 4, // 6 = second sequence bounding uvs, frame1 4, // 7 = second sequence frame blend, ?,?,? }; static int s_TexCoordSizeSpline[]={4, // 0 = sheet bounding uvs, frame0 4, // 1 = sheet bounding uvs, frame 1 4, // 2 = frame blend, rot, radius, ??? 4, // 3 = corner identifier ( 0/0,1/0,1/1, 1/0 ) 4, // 4 = texture 2 bounding uvs 4, // 5 = second sequence bounding uvs, frame0 4, // 6 = second sequence bounding uvs, frame1 4, // 7 = second sequence frame blend, ?,?,? }; int numTexCoords = 4; if ( true /* bAdditive2ndTexture */ ) // there is no branch for 2nd texture in the VS! -henryg { numTexCoords = 5; } if ( bSecondSequence ) { // the whole shebang - 2 sequences, with a possible multi-image sequence first numTexCoords = 8; } pShaderShadow->VertexShaderVertexFormat( flags, numTexCoords, nSplineType? s_TexCoordSizeSpline : s_TexCoordSize, 0 ); if ( bDX8 ) { #if SUPPORT_DX8 if ( nSplineType ) { DECLARE_STATIC_VERTEX_SHADER( splinecard_vs11 ); SET_STATIC_VERTEX_SHADER( splinecard_vs11 ); } else { DECLARE_STATIC_VERTEX_SHADER( spritecard_vs11 ); if ( bSecondSequence ) bAdditive2ndTexture = false; SET_STATIC_VERTEX_SHADER_COMBO( DUALSEQUENCE, false ); SET_STATIC_VERTEX_SHADER_COMBO( ZOOM_ANIMATE_SEQ2, false ); SET_STATIC_VERTEX_SHADER_COMBO( EXTRACTGREENALPHA, bExtractGreenAlpha ); SET_STATIC_VERTEX_SHADER( spritecard_vs11 ); } DECLARE_STATIC_PIXEL_SHADER( spritecard_ps11 ); SET_STATIC_PIXEL_SHADER_COMBO( ADDBASETEXTURE2, bAdditive2ndTexture ); SET_STATIC_PIXEL_SHADER_COMBO( ADDSELF, bAddSelf ); SET_STATIC_PIXEL_SHADER_COMBO( USEALPHAASRGB, bSecondSequence ); SET_STATIC_PIXEL_SHADER( spritecard_ps11 ); #endif } else { if ( nSplineType ) { DECLARE_STATIC_VERTEX_SHADER( splinecard_vs20 ); SET_STATIC_VERTEX_SHADER( splinecard_vs20 ); } else { DECLARE_STATIC_VERTEX_SHADER( spritecard_vs20 ); SET_STATIC_VERTEX_SHADER_COMBO( DUALSEQUENCE, bSecondSequence ); SET_STATIC_VERTEX_SHADER_COMBO( ZOOM_ANIMATE_SEQ2, bZoomSeq2 ); SET_STATIC_VERTEX_SHADER_COMBO( EXTRACTGREENALPHA, bExtractGreenAlpha ); SET_STATIC_VERTEX_SHADER_COMBO( USE_INSTANCING, bUseInstancing ); SET_STATIC_VERTEX_SHADER( spritecard_vs20 ); } if( g_pHardwareConfig->SupportsPixelShaders_2_b() ) { DECLARE_STATIC_PIXEL_SHADER( spritecard_ps20b ); SET_STATIC_PIXEL_SHADER_COMBO( ADDBASETEXTURE2, bAdditive2ndTexture ); SET_STATIC_PIXEL_SHADER_COMBO( ADDSELF, bAddSelf ); SET_STATIC_PIXEL_SHADER_COMBO( ANIMBLEND, bBlendFrames ); SET_STATIC_PIXEL_SHADER_COMBO( DUALSEQUENCE, bSecondSequence ); SET_STATIC_PIXEL_SHADER_COMBO( SEQUENCE_BLEND_MODE, bSecondSequence ? params[SEQUENCE_BLEND_MODE]->GetIntValue() : 0 ); SET_STATIC_PIXEL_SHADER_COMBO( MAXLUMFRAMEBLEND1, params[MAXLUMFRAMEBLEND1]->GetIntValue() ); SET_STATIC_PIXEL_SHADER_COMBO( MAXLUMFRAMEBLEND2, bSecondSequence? params[MAXLUMFRAMEBLEND1]->GetIntValue() : 0 ); SET_STATIC_PIXEL_SHADER_COMBO( COLORRAMP, bUseRampTexture ); SET_STATIC_PIXEL_SHADER_COMBO( EXTRACTGREENALPHA, bExtractGreenAlpha ); SET_STATIC_PIXEL_SHADER_COMBO( DEPTHBLEND, bDepthBlend ); SET_STATIC_PIXEL_SHADER( spritecard_ps20b ); } else { DECLARE_STATIC_PIXEL_SHADER( spritecard_ps20 ); SET_STATIC_PIXEL_SHADER_COMBO( ADDBASETEXTURE2, bAdditive2ndTexture ); SET_STATIC_PIXEL_SHADER_COMBO( DUALSEQUENCE, bSecondSequence ); SET_STATIC_PIXEL_SHADER_COMBO( ADDSELF, bAddSelf ); SET_STATIC_PIXEL_SHADER_COMBO( ANIMBLEND, bBlendFrames ); SET_STATIC_PIXEL_SHADER_COMBO( SEQUENCE_BLEND_MODE, bSecondSequence ? params[SEQUENCE_BLEND_MODE]->GetIntValue() : 0 ); SET_STATIC_PIXEL_SHADER_COMBO( MAXLUMFRAMEBLEND1, params[MAXLUMFRAMEBLEND1]->GetIntValue() ); SET_STATIC_PIXEL_SHADER_COMBO( MAXLUMFRAMEBLEND2, bSecondSequence? params[MAXLUMFRAMEBLEND1]->GetIntValue() : 0 ); SET_STATIC_PIXEL_SHADER_COMBO( COLORRAMP, bUseRampTexture ); SET_STATIC_PIXEL_SHADER_COMBO( EXTRACTGREENALPHA, bExtractGreenAlpha ); SET_STATIC_PIXEL_SHADER( spritecard_ps20 ); } if ( !bDX8 ) pShaderShadow->EnableSRGBWrite( true ); if( !bExtractGreenAlpha && !bDX8 ) pShaderShadow->EnableSRGBRead( SHADER_SAMPLER0, true ); } } DYNAMIC_STATE { BindTexture( SHADER_SAMPLER0, BASETEXTURE, FRAME ); if ( bDX8 ) // bind on 2nd sampelr so we can lerp BindTexture( SHADER_SAMPLER1, BASETEXTURE, FRAME ); if ( bDX8 && bAdditive2ndTexture ) BindTexture( SHADER_SAMPLER3, BASETEXTURE, FRAME ); if ( bUseRampTexture && ( !bDX8 ) ) { BindTexture( SHADER_SAMPLER1, RAMPTEXTURE, FRAME ); } if ( bDepthBlend ) { pShaderAPI->BindStandardTexture( SHADER_SAMPLER2, TEXTURE_FRAME_BUFFER_FULL_DEPTH ); } LoadViewportTransformScaledIntoVertexShaderConstant( VERTEX_SHADER_SHADER_SPECIFIC_CONST_10 ); int nOrientation = params[ORIENTATION]->GetIntValue(); nOrientation = clamp( nOrientation, 0, 2 ); // We need these only when screen-orienting if ( nOrientation == 0 ) { LoadModelViewMatrixIntoVertexShaderConstant( VERTEX_SHADER_SHADER_SPECIFIC_CONST_0 ); LoadProjectionMatrixIntoVertexShaderConstant( VERTEX_SHADER_SHADER_SPECIFIC_CONST_3 ); } if ( bZoomSeq2 ) { float flZScale=1.0/(params[ZOOMANIMATESEQ2]->GetFloatValue()); float C0[4]={ (float)(0.5*(1.0+flZScale)), flZScale, 0, 0 }; pShaderAPI->SetVertexShaderConstant( VERTEX_SHADER_SHADER_SPECIFIC_CONST_7, C0, ARRAYSIZE(C0)/4 ); } // set fade constants in vsconsts 8 and 9 float flMaxDistance = params[MAXDISTANCE]->GetFloatValue(); float flStartFade = max( 1.f, flMaxDistance - params[FARFADEINTERVAL]->GetFloatValue() ); float VC0[8]={ params[MINSIZE]->GetFloatValue(), params[MAXSIZE]->GetFloatValue(), params[STARTFADESIZE]->GetFloatValue(), params[ENDFADESIZE]->GetFloatValue(), flStartFade, (float)(1.0/(flMaxDistance-flStartFade)), 0,0 }; pShaderAPI->SetVertexShaderConstant( VERTEX_SHADER_SHADER_SPECIFIC_CONST_8, VC0, ARRAYSIZE(VC0)/4 ); pShaderAPI->SetDepthFeatheringPixelShaderConstant( 2, params[DEPTHBLENDSCALE]->GetFloatValue() ); float C0[4]={ params[ADDBASETEXTURE2]->GetFloatValue(), params[OVERBRIGHTFACTOR]->GetFloatValue(), params[ADDSELF]->GetFloatValue(), 0.0f }; if ( bDX8 && ( !bAdditive2ndTexture ) ) // deal with 0..1 limit for pix shader constants { C0[2] *= 0.25; C0[1] *= 0.25; } pShaderAPI->SetPixelShaderConstant( 0, C0, ARRAYSIZE(C0)/4 ); if ( g_pHardwareConfig->GetDXSupportLevel() < 90 ) { #if SUPPORT_DX8 if ( nSplineType ) { DECLARE_DYNAMIC_VERTEX_SHADER( splinecard_vs11 ); SET_DYNAMIC_VERTEX_SHADER( splinecard_vs11 ); } else { DECLARE_DYNAMIC_VERTEX_SHADER( spritecard_vs11 ); SET_DYNAMIC_VERTEX_SHADER_COMBO( ORIENTATION, nOrientation ); SET_DYNAMIC_VERTEX_SHADER( spritecard_vs11 ); } #endif } else { if ( nSplineType ) { DECLARE_DYNAMIC_VERTEX_SHADER( splinecard_vs20 ); SET_DYNAMIC_VERTEX_SHADER( splinecard_vs20 ); } else { DECLARE_DYNAMIC_VERTEX_SHADER( spritecard_vs20 ); SET_DYNAMIC_VERTEX_SHADER_COMBO( ORIENTATION, nOrientation ); SET_DYNAMIC_VERTEX_SHADER( spritecard_vs20 ); } } } Draw( ); } END_SHADER
17,049
7,944
#include <xtd/forms/native/tab_page.hpp> #include "fl_tab_page.hpp" using namespace xtd; using namespace xtd::drawing; using namespace xtd::forms::native;
156
59
#include <iostream> #include <functional> #include <vector> #include <map> #include <string> #include <utility> #include "Event.h" #include "EventListener.h" using namespace std; class Foo { public: Foo() {} Event<int> event; void setValue(int i) { value = i; event.notifyListeners(i); } private: int value; }; class Moo { public: Moo(Foo *f) { f->event.registerSyncValue(syncVal); eventListener = f->event.createListener([](int v) { cout << "Value is "<<v+1<<endl; }); } SyncValue<int> syncVal; private: EventListener<int> eventListener; }; int main(int argc, const char * argv[]) { Foo f; { Moo m(&f); f.setValue(123); cout << "synched value " << m.syncVal.getValue() << endl; f.setValue(12); cout << "synched value " << m.syncVal.getValue() << endl; } f.setValue(1234); return 0; }
1,039
348
#include <stdlib.h> #include <exception> #include <iostream> #include <string> #include <utility> #include <vector> #include "DetectorDescription/Core/interface/DDCompactView.h" #include "DetectorDescription/Core/interface/DDExpandedNode.h" #include "DetectorDescription/Core/interface/DDExpandedView.h" #include "DetectorDescription/Core/interface/DDLogicalPart.h" #include "DetectorDescription/Core/interface/DDMaterial.h" #include "DetectorDescription/Core/interface/DDName.h" #include "DetectorDescription/Core/interface/DDRoot.h" #include "DetectorDescription/Core/interface/DDSolid.h" #include "DetectorDescription/Core/interface/DDTransform.h" #include "DetectorDescription/Core/src/DDCheck.h" #include "DetectorDescription/Parser/interface/DDLDocumentProvider.h" #include "DetectorDescription/Parser/interface/DDLParser.h" #include "DetectorDescription/Parser/interface/DDLSAX2ConfigHandler.h" #include "DetectorDescription/Parser/interface/DDLSAX2Handler.h" #include "FWCore/PluginManager/interface/PluginManager.h" #include "FWCore/PluginManager/interface/standard.h" #include "FWCore/Utilities/interface/Exception.h" #include "Utilities/Xerces/interface/XercesStrUtils.h" #include "xercesc/util/XMLException.hpp" #include "xercesc/util/XercesVersion.hpp" using namespace cms::xerces; class DDLTestDoc : public DDLDocumentProvider { public: DDLTestDoc( void ); ~DDLTestDoc() override; /// Return a list of files as a vector of strings. const std::vector < std::string >& getFileList( void ) const override; /// Return a list of urls as a vector of strings. const std::vector < std::string >& getURLList( void ) const override; /// Print out the list of files. void dumpFileList( void ) const override; /// Return whether Validation should be on or off and where the DDL SchemaLocation is. bool doValidation( void ) const override; /// Return the designation for where to look for the schema. std::string getSchemaLocation( void ) const override; /// ReadConfig int readConfig( const std::string& filename ) override; void emplace_back( const std::string& fileName, const std::string& url = std::string( "./" )); void setSchemaLocation( std::string path = std::string( "../../DDSchema" )); void setValidation( bool val ); void clear( void ); private: std::vector < std::string > fnames_; std::vector < std::string > urls_; std::string schemaLoc_; bool validate_; }; //-------------------------------------------------------------------------- // DDLTestDoc: Default constructor and destructor. //-------------------------------------------------------------------------- DDLTestDoc::~DDLTestDoc( void ) { } DDLTestDoc::DDLTestDoc( void ) : validate_(true) { schemaLoc_ = "http://www.cern.ch/cms/DDL ../../Schema/DDLSchema.xsd"; } const std::vector<std::string>& DDLTestDoc::getFileList( void ) const { return fnames_; } const std::vector<std::string>& DDLTestDoc::getURLList( void ) const { return urls_; } void DDLTestDoc::emplace_back( const std::string& fileName, const std::string& url ) { fnames_.emplace_back(fileName); urls_.emplace_back(url); } void DDLTestDoc::setValidation( bool val ) { validate_= val; } bool DDLTestDoc::doValidation( void ) const { return validate_; } void DDLTestDoc::setSchemaLocation( std::string path ) { schemaLoc_ = std::move(path); } std::string DDLTestDoc::getSchemaLocation( void ) const { std::cout << schemaLoc_ << std::endl; return schemaLoc_; } void DDLTestDoc::dumpFileList( void ) const { std::cout << "File List:" << std::endl; std::vector<std::string> vst = getFileList(); std::cout << " number of files=" << vst.size() << std::endl; for (std::vector<std::string>::const_iterator it = vst.begin(); it != vst.end(); ++it) std::cout << *it << std::endl; } void DDLTestDoc::clear( void ) { fnames_.clear(); urls_.clear(); } //----------------------------------------------------------------------- // Here the Xerces parser is used to process the content of the // configuration file. // FIX: Right now, each config file passed to this will simply increase the // size of the list of files. So if this default DDLDocumentProvider is // called repeatedly (i.e. the same instance of it) then the file list MAY // repeat files. It is the Parser which checks for maintains a list of real // files. //----------------------------------------------------------------------- int DDLTestDoc::readConfig( const std::string& filename ) { std::cout << "readConfig" << std::endl; // Set the parser to use the handler for the configuration file. // This makes sure the Parser is initialized and gets a handle to it. DDCompactView cpv; DDLParser parser(cpv); DDLSAX2Handler* errHandler; DDLSAX2ConfigHandler * sch; sch = new DDLSAX2ConfigHandler(cpv); errHandler = new DDLSAX2Handler; parser.getXMLParser()->setContentHandler(sch); parser.getXMLParser()->setErrorHandler(errHandler); try { parser.getXMLParser()->parse(filename.c_str()); } catch (const XERCES_CPP_NAMESPACE::XMLException& toCatch) { std::cout << "\nXMLException: parsing '" << filename << "'\n" << "Exception message is: \n" << cStr(toCatch.getMessage()).ptr() << "\n" ; return 1; } catch (...) { std::cout << "\nUnexpected exception during parsing: '" << filename << "'\n"; return 3; } fnames_ = sch->getFileNames(); urls_ = sch->getURLs(); std::cout << "there are " << fnames_.size() << " files." << std::endl; for (size_t i = 0; i < fnames_.size(); ++i) std::cout << "url=" << urls_[i] << " file=" << fnames_[i] << std::endl; return 0; } void testRotations( void ) { std::cout << "--------------- Parser testing Rotations --------------" << std::endl; std::cout << "z30 should be a rotation of 30 degrees around the z axis:" << std::endl; std::cout << DDRotation(DDName( "z30", "testRotations")) << std::endl; std::cout << std::endl; std::cout << "z30x20 should be a rotation 30 degrees around z, then 20 degrees around x:" << std::endl; std::cout << DDRotation(DDName( "z30x20", "testRotations")) << std::endl; std::cout << std::endl; std::cout << "x90y45 should be a rotation 90 degrees around x, then 45 degrees around y:" << std::endl; std::cout << DDRotation(DDName( "x90y45", "testRotations")) << std::endl; std::cout << std::endl; std::cout << "x90y90 should be a rotation 90 degrees around x, then 90 degrees around y:" << std::endl; std::cout << DDRotation(DDName( "x90y90", "testRotations")) << std::endl; std::cout << std::endl; std::cout << "x90y135 should be a rotation 90 degrees around x, then 135 degrees around y:" << std::endl; std::cout << DDRotation(DDName( "x90y135", "testRotations")) << std::endl; std::cout << std::endl; std::cout << "x90y180 should be a rotation 90 degrees around x, then 180 degrees around y:" << std::endl; std::cout << DDRotation(DDName( "x90y180", "testRotations")) << std::endl; std::cout << std::endl; std::cout << "x90 should be a rotation of 90 degrees around the x axis:" << std::endl; std::cout << DDRotation(DDName( "x90", "testRotations")) << std::endl; std::cout << std::endl; std::cout << "cmsimIdentity makes the identity rotation matrix using the cmsim method (phi and theta of each axis):" << std::endl; std::cout << DDRotation(DDName("cmsimIdentity", "testRotations")) << std::endl; std::cout << std::endl; std::cout << "newrotIdentity makes the identity rotation matrix by rotating 0 degrees around the z axis:" << std::endl; std::cout << DDRotation(DDName("newrotIdentity", "testRotations")) << std::endl; std::cout << std::endl; std::cout << "180R should be a REFLECTION rotation. It is defined using the cmsim way:" << std::endl; std::cout << DDRotation(DDName("180R", "testRotations")) << std::endl; std::cout << std::endl; } void testMaterials() { std::cout << "--------------- Parser testing Materials --------------" << std::endl; std::cout << "There should be 4 Elementary Materials: Nitrogen," << std::endl; std::cout << "Oxygen,Argon and Hydrogen. There should be one composite" << std::endl; std::cout << " material:Air, made up of those 4 components." << std::endl; std::cout << DDMaterial(DDName("Nitrogen", "testMaterials")) << std::endl; std::cout << std::endl; std::cout << DDMaterial(DDName("Oxygen", "testMaterials")) << std::endl; std::cout << std::endl; std::cout << DDMaterial(DDName("Argon", "testMaterials")) << std::endl; std::cout << std::endl; std::cout << DDMaterial(DDName("Hydrogen", "testMaterials")) << std::endl; std::cout << std::endl; std::cout << DDMaterial(DDName("Air", "testMaterials")) << std::endl; std::cout << std::endl; } void testSolids( void ) { std::cout << "--------------- Parser testing Solids --------------" << std::endl; std::cout << "trap1 is a trapezoid:" << std::endl; std::cout << DDSolid(DDName("trap1", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "trap2 is a trapezoid with more symmetry:" << std::endl; std::cout << DDSolid(DDName("trap2", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "ptrap1 is a pseudo Trapezoid with atMinusZ=false:" << std::endl; std::cout << DDSolid(DDName("ptrap1", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "ptrap2 is a psuedo Trapezoid with atMinusZ=true:" << std::endl; std::cout << DDSolid(DDName("ptrap2", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "box1 is a Box:" << std::endl; std::cout << DDSolid(DDName("box1", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "cone1 is a conical section (full 360 degree):" << std::endl; std::cout << DDSolid(DDName("cone1", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "cone2 is a conical section (full 360 degree) which is actually a tube:" << std::endl; std::cout << DDSolid(DDName("cone2", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "cone2hole is a conical section (20 degree):" << std::endl; std::cout << DDSolid(DDName("cone2hole", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "pczsect is a polycone defined using z-sections:" << std::endl; std::cout << DDSolid(DDName("pczsect", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "pcrz is a polycone defined using r & z points:" << std::endl; std::cout << DDSolid(DDName("pcrz", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "phzsect is a polyhedra defined using z-sections:" << std::endl; std::cout << DDSolid(DDName("phzsect", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "phrz is a polyhedra defined using r & z points:" << std::endl; std::cout << DDSolid(DDName("phrz", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "trd1 is a \"special\" trapezoid declaration with fewer" ; std::cout << " parameters (Trd1):" << std::endl; std::cout << DDSolid(DDName("trd1", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "trd2 is a \"special\" trapezoid declaration with fewer" ; std::cout << " parameters (Trd1):" << std::endl; std::cout << DDSolid(DDName("trd2", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "tube1 is a tube:" << std::endl; std::cout << DDSolid(DDName("tube1", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "tube2 is a tubs(Tube Section):" << std::endl; std::cout << DDSolid(DDName("tube2", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "trunctubs1 is a trunctubs(Cut or truncated Tube Section):" << std::endl; std::cout << DDSolid(DDName("trunctubs1", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "momma is a shapeless solid, a way of \"grouping\" things:" << std::endl; std::cout << DDSolid(DDName("momma", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "MotherOfAllBoxes is a box and is the root's solid:" << std::endl; std::cout << DDSolid(DDName("MotherOfAllBoxes", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "trd2mirror is a ReflectionSolid of trd2:" << std::endl; std::cout << DDSolid(DDName("trd2mirror", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "subsolid is a subtraction solid, cone2-cone2hole:" << std::endl; std::cout << DDSolid(DDName("subsolid", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "unionsolid is a union of pcrz and cone1:" << std::endl; std::cout << DDSolid(DDName("unionsolid", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "intsolid is an Intersection(Solid) of cone1 and cone2:" << std::endl; std::cout << DDSolid(DDName("intsolid", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "cuttubs is a Cut tubs solid:" << std::endl; std::cout << DDSolid(DDName("cuttubs", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "extrudedpgon is an Extruded Polygone solid:" << std::endl; std::cout << DDSolid(DDName("extrudedpgon", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "verify parameters interface\nx: "; DDExtrudedPolygon extrPgon(DDSolid(DDName("extrudedpgon", "testSolids"))); std::vector<double> x = extrPgon.xVec(); std::vector<double> y = extrPgon.yVec(); std::vector<double> z = extrPgon.zVec(); std::vector<double> zx = extrPgon.zxVec(); std::vector<double> zy = extrPgon.zyVec(); std::vector<double> zs = extrPgon.zscaleVec(); for( auto i : x ) std::cout << i << ", "; std::cout << "\ny: "; for( auto i : y ) std::cout << i << ", "; std::cout << "\nz: "; for( auto i : z ) std::cout << i << ", "; std::cout << "\nzx: "; for( auto i : zx ) std::cout << i << ", "; std::cout << "\nzy: "; for( auto i : zy ) std::cout << i << ", "; std::cout << "\nz scale: "; for( auto i : zs ) std::cout << i << ", "; std::cout << std::endl; std::cout << "multiunionsolid is a Multi Union solid:" << std::endl; std::cout << DDSolid(DDName("multiunionsolid", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "verify parameters interface\n"; DDMultiUnion multiUnion(DDSolid(DDName("multiunionsolid", "testSolids"))); std::cout << " Solids:\n"; for( auto s : multiUnion.solids()) std::cout << s << "\n"; for( auto t : multiUnion.translations()) std::cout << t << "\n"; for( auto r : multiUnion.rotations()) std::cout << r << "\n"; } void testLogicalParts( void ) { std::cout << "--------------- Parser testing LogicalParts --------------" << std::endl; std::cout << "LogicalPart trap1:" << std::endl; std::cout << DDLogicalPart(DDName("trap1", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart trap2:" << std::endl; std::cout << DDLogicalPart(DDName("trap2", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart ptrap1:" << std::endl; std::cout << DDLogicalPart(DDName("ptrap1", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart ptrap2:" << std::endl; std::cout << DDLogicalPart(DDName("ptrap2", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart box1:" << std::endl; std::cout << DDLogicalPart(DDName("box1", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart cone1:" << std::endl; std::cout << DDLogicalPart(DDName("cone1", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart cone2:" << std::endl; std::cout << DDLogicalPart(DDName("cone2", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart cone2hole:" << std::endl; std::cout << DDLogicalPart(DDName("cone2hole", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart pczsect:" << std::endl; std::cout << DDLogicalPart(DDName("pczsect", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart pcrz:" << std::endl; std::cout << DDLogicalPart(DDName("pcrz", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart phzsect:" << std::endl; std::cout << DDLogicalPart(DDName("phzsect", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart phrz:" << std::endl; std::cout << DDLogicalPart(DDName("phrz", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart trd1:" ; std::cout << DDLogicalPart(DDName("trd1", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart trd2:" << std::endl; std::cout << DDLogicalPart(DDName("trd2", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart tube1:" << std::endl; std::cout << DDLogicalPart(DDName("tube1", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart tube2:" << std::endl; std::cout << DDLogicalPart(DDName("tube2", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart trunctubs1:" << std::endl; std::cout << DDLogicalPart(DDName("trunctubs1", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart momma:" << std::endl; std::cout << DDLogicalPart(DDName("momma", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart MotherOfAllBoxes:" << std::endl; std::cout << DDLogicalPart(DDName("MotherOfAllBoxes", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart torus:" << std::endl; std::cout << DDLogicalPart(DDName("torus", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart trd2mirror:" << std::endl; std::cout << DDLogicalPart(DDName("trd2mirror", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart subsolid:" << std::endl; std::cout << DDLogicalPart(DDName("subsolid", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart unionsolid:" << std::endl; std::cout << DDLogicalPart(DDName("unionsolid", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart intsolid:" << std::endl; std::cout << DDLogicalPart(DDName("intsolid", "testLogicalParts")) << std::endl; std::cout << std::endl; } int main(int argc, char *argv[]) { std::string const kProgramName = argv[0]; int rc = 0; if (argc < 2 || argc > 2 ) { std::cout << "This is a polite exit so that scram b runtests' first run of this program does not give an error" << std::endl; exit(0); // SUCCESS; } try { edmplugin::PluginManager::configure(edmplugin::standard::config()); std::cout << "Initialize a DDL parser " << std::endl; DDCompactView cpv; DDLParser myP(cpv); if ( argc == 2 ) { DDLTestDoc dp; dp.readConfig(argv[1]); dp.dumpFileList(); std::cout << "About to start parsing..." << std::endl; myP.parse(dp); std::cout << "Completed Parser" << std::endl; std::cout << std::endl << std::endl << "Start checking!" << std::endl << std::endl; std::cout << "Call DDCheckMaterials and other DDChecks." << std::endl; DDCheckMaterials(std::cout); std::cout << "======== Navigate a little bit ======" << std::endl; try { if (!cpv.root().isDefined().second) { cpv.setRoot(DDRootDef::instance().root()); } DDExpandedView ev(cpv); while (ev.next()) { std::cout << ev.geoHistory() << std::endl; } } catch (cms::Exception& e) { std::cout << e.what() << std::endl; } std::cout << "--------------- Parser testing started --------------" << std::endl; std::cout << std::endl << "Run the XML tests." << std::endl; testMaterials(); testRotations(); testSolids(); testLogicalParts(); } else if (argc < 3) { // scram b runtests for now this should not work. // just to have something! DDRootDef::instance().set(DDName("LP1", "testNoSections")); std::string fname = std::string(argv[1]); DDLTestDoc dp; while (fname != "q") { std::cout << "about to try to process the file " << fname << std::endl; dp.emplace_back(fname); myP.parse(dp); std::cout << "next file name:" ; std::cin >> fname; dp.clear(); } } } catch (cms::Exception& e) { std::cout << "cms::Exception caught in " << kProgramName << "\n" << e.explainSelf(); rc = 1; } catch (std::exception& e) { std::cout << "Standard library exception caught in " << kProgramName << "\n" << e.what(); rc = 1; } return rc; }
21,189
7,406
//===- LowerUniformRealMath.cpp ------------------------------------------===// // // Copyright 2019 The MLIR Authors. // // 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 "UniformKernelUtils.h" #include "mlir/Dialect/FxpMathOps/FxpMathOps.h" #include "mlir/Dialect/FxpMathOps/Passes.h" #include "mlir/Dialect/StandardOps/Ops.h" #include "mlir/IR/Diagnostics.h" #include "mlir/IR/PatternMatch.h" #include "mlir/Pass/Pass.h" using namespace mlir; using namespace mlir::fxpmath; using namespace mlir::fxpmath::detail; using namespace mlir::quant; namespace { struct LowerUniformRealMathPass : public FunctionPass<LowerUniformRealMathPass> { void runOnFunction() override; }; struct LowerUniformCastsPass : public FunctionPass<LowerUniformCastsPass> { void runOnFunction() override; }; } // end anonymous namespace //===----------------------------------------------------------------------===// // Dequantize //===----------------------------------------------------------------------===// static ValuePtr emitUniformPerLayerDequantize(Location loc, ValuePtr input, UniformQuantizedType elementType, PatternRewriter &rewriter) { // Pre-conditions. if (!elementType.isSigned()) { // TODO: Support unsigned storage type. emitWarning(loc, "unimplemented: dequantize signed uniform"); return nullptr; } Type storageType = elementType.castToStorageType(input->getType()); Type realType = elementType.castToExpressedType(input->getType()); Type intermediateType = castElementType(storageType, IntegerType::get(32, rewriter.getContext())); assert(storageType && "cannot cast to storage type"); assert(realType && "cannot cast to expressed type"); // Cast to storage type. input = rewriter.create<StorageCastOp>(loc, storageType, input); // Promote to intermediate type. input = rewriter.create<ConvertISOp>(loc, intermediateType, input); // Apply zero-point offset. if (elementType.getZeroPoint() != 0) { ValuePtr negZeroPointConst = rewriter.create<ConstantOp>( loc, broadcastScalarConstIntValue(intermediateType, -elementType.getZeroPoint())); input = rewriter.create<AddIOp>(loc, input, negZeroPointConst); } // Convert to float. input = rewriter.create<ConvertISToFOp>(loc, realType, input); // Mul by scale. ValuePtr scaleConst = rewriter.create<ConstantOp>( loc, broadcastScalarConstFloatValue(realType, APFloat(elementType.getScale()))); return rewriter.create<MulFOp>(loc, input, scaleConst); } static ValuePtr emitUniformPerAxisDequantize(Location loc, ValuePtr input, UniformQuantizedPerAxisType elementType, PatternRewriter &rewriter) { // TODO: Support per-axis dequantize. rewriter.getContext()->getDiagEngine().emit(loc, DiagnosticSeverity::Warning) << "unimplemented: per-axis uniform dequantization"; return nullptr; } static ValuePtr emitDequantize(Location loc, ValuePtr input, PatternRewriter &rewriter) { Type inputType = input->getType(); QuantizedType qElementType = QuantizedType::getQuantizedElementType(inputType); if (auto uperLayerElementType = qElementType.dyn_cast_or_null<UniformQuantizedType>()) { return emitUniformPerLayerDequantize(loc, input, uperLayerElementType, rewriter); } else if (auto uperAxisElementType = qElementType.dyn_cast_or_null<UniformQuantizedPerAxisType>()) { return emitUniformPerAxisDequantize(loc, input, uperAxisElementType, rewriter); } else { return nullptr; } } namespace { struct UniformDequantizePattern : public OpRewritePattern<DequantizeCastOp> { using OpRewritePattern<DequantizeCastOp>::OpRewritePattern; PatternMatchResult matchAndRewrite(DequantizeCastOp op, PatternRewriter &rewriter) const override { Type inputType = op.arg()->getType(); Type outputType = op.getResult()->getType(); QuantizedType inputElementType = QuantizedType::getQuantizedElementType(inputType); Type expressedOutputType = inputElementType.castToExpressedType(inputType); if (expressedOutputType != outputType) { // Not a valid uniform cast. return matchFailure(); } ValuePtr dequantizedValue = emitDequantize(op.getLoc(), op.arg(), rewriter); if (!dequantizedValue) { return matchFailure(); } rewriter.replaceOp(op, dequantizedValue); return matchSuccess(); } }; } // end anonymous namespace //===----------------------------------------------------------------------===// // Elementwise add //===----------------------------------------------------------------------===// static LogicalResult tryRewriteAffineAddEwIsomorphicSigned(const UniformBinaryOpInfo &info, PatternRewriter &rewriter) { if (!info.resultType.isSigned() || info.lhsType != info.resultType || info.rhsType != info.resultType) { return failure(); } // Choose a byte aligned intermediate width big enough to perform the // calculation without overflow. // TODO: This should probably be made just big enough to avoid overflow and // leave the downstream tooling to decide how to align that to machine // word sizes. unsigned intermediateWidth = info.resultType.getStorageTypeIntegralWidth() <= 8 ? 16 : 32; IntegerType intermediateElementType = IntegerType::get(intermediateWidth, rewriter.getContext()); Type intermediateType = castElementType(info.resultStorageType, intermediateElementType); // Cast operands to storage type. ValuePtr lhsValue = rewriter .create<StorageCastOp>(info.op->getLoc(), info.lhsStorageType, info.lhs) .getResult(); ValuePtr rhsValue = rewriter .create<StorageCastOp>(info.op->getLoc(), info.rhsStorageType, info.rhs) .getResult(); // Cast to the intermediate sized type. lhsValue = rewriter.create<ConvertISOp>(info.op->getLoc(), intermediateType, lhsValue); rhsValue = rewriter.create<ConvertISOp>(info.op->getLoc(), intermediateType, rhsValue); // Add. ValuePtr resultValue = rewriter.create<AddIOp>(info.op->getLoc(), lhsValue, rhsValue); // Zero point offset adjustment. // result = (lhs - zp) + (rhs - zp) + zp // zpOffset = -zp int zpOffset = -1 * info.resultType.getZeroPoint(); if (zpOffset != 0) { ValuePtr zpOffsetConst = rewriter.create<ConstantOp>( info.op->getLoc(), broadcastScalarConstIntValue(intermediateType, zpOffset)); resultValue = rewriter.create<AddIOp>(info.op->getLoc(), resultValue, zpOffsetConst); } // Clamp. auto clampMinMax = info.getClampMinMax(intermediateElementType); resultValue = rewriter.create<ClampISOp>( info.op->getLoc(), resultValue, clampMinMax.first, clampMinMax.second); // Convert back to original type. resultValue = rewriter.create<ConvertISOp>( info.op->getLoc(), info.resultStorageType, resultValue); // Cast back for new result. rewriter.replaceOpWithNewOp<StorageCastOp>( info.op, info.getQuantizedResultType(), resultValue); return success(); } //===----------------------------------------------------------------------===// // Elementwise mul //===----------------------------------------------------------------------===// static LogicalResult tryRewriteAffineMulEwSigned(const UniformBinaryOpInfo &info, PatternRewriter &rewriter) { if (!info.resultType.isSigned()) { return failure(); } double outputMultiplierReal = info.lhsType.getScale() * info.rhsType.getScale() / info.resultType.getScale(); if (outputMultiplierReal > 1.0) { info.op->emitWarning( "unimplemented: cannot multiply with multiplier > 1.0"); return failure(); } // TODO: Choose an appropriate intermediate width for muls > 8 bits to // avoid overflow. unsigned intermediateWidth = 32; IntegerType intermediateElementType = IntegerType::get(intermediateWidth, rewriter.getContext()); Type intermediateType = castElementType(info.resultStorageType, intermediateElementType); // Cast operands to storage type. ValuePtr lhsValue = rewriter .create<StorageCastOp>(info.op->getLoc(), info.lhsStorageType, info.lhs) .getResult(); ValuePtr rhsValue = rewriter .create<StorageCastOp>(info.op->getLoc(), info.rhsStorageType, info.rhs) .getResult(); // Cast to the intermediate sized type. lhsValue = rewriter.create<ConvertISOp>(info.op->getLoc(), intermediateType, lhsValue); rhsValue = rewriter.create<ConvertISOp>(info.op->getLoc(), intermediateType, rhsValue); // Apply argument zeroPoints. if (info.lhsType.getZeroPoint() != 0) { ValuePtr zpOffsetConst = rewriter.create<ConstantOp>( info.op->getLoc(), broadcastScalarConstIntValue( intermediateType, -info.lhsType.getZeroPoint())); lhsValue = rewriter.create<AddIOp>(info.op->getLoc(), lhsValue, zpOffsetConst); } if (info.rhsType.getZeroPoint() != 0) { ValuePtr zpOffsetConst = rewriter.create<ConstantOp>( info.op->getLoc(), broadcastScalarConstIntValue( intermediateType, -info.rhsType.getZeroPoint())); rhsValue = rewriter.create<AddIOp>(info.op->getLoc(), rhsValue, zpOffsetConst); } // Mul. ValuePtr resultValue = rewriter.create<MulIOp>(info.op->getLoc(), lhsValue, rhsValue); // Scale output. QuantizedMultiplierSmallerThanOneExp outputMultiplier(outputMultiplierReal); resultValue = rewriter.create<VecScalarSaturatingRoundingDoublingHighMulISOp>( info.op->getLoc(), resultValue, IntegerAttr::get(intermediateElementType, outputMultiplier.multiplier)); resultValue = rewriter.create<RoundingDivideByPotISOp>( info.op->getLoc(), resultValue, IntegerAttr::get(intermediateElementType, -outputMultiplier.exponent)); // Zero point offset adjustment. if (info.resultType.getZeroPoint() != 0) { ValuePtr zpOffsetConst = rewriter.create<ConstantOp>( info.op->getLoc(), broadcastScalarConstIntValue(intermediateType, info.resultType.getZeroPoint())); resultValue = rewriter.create<AddIOp>(info.op->getLoc(), resultValue, zpOffsetConst); } // Clamp. auto clampMinMax = info.getClampMinMax(intermediateElementType); resultValue = rewriter.create<ClampISOp>( info.op->getLoc(), resultValue, clampMinMax.first, clampMinMax.second); // Convert back to original type. resultValue = rewriter.create<ConvertISOp>( info.op->getLoc(), info.resultStorageType, resultValue); // Cast back for new result. rewriter.replaceOpWithNewOp<StorageCastOp>( info.op, info.getQuantizedResultType(), resultValue); return success(); } namespace { struct UniformRealAddEwPattern : public OpRewritePattern<RealAddEwOp> { using OpRewritePattern<RealAddEwOp>::OpRewritePattern; PatternMatchResult matchAndRewrite(RealAddEwOp op, PatternRewriter &rewriter) const override { const UniformBinaryOpInfo info(op, op.lhs(), op.rhs(), op.clamp_min(), op.clamp_max()); if (!info.isValid()) { return matchFailure(); } // Try all of the permutations we support. if (succeeded(tryRewriteAffineAddEwIsomorphicSigned(info, rewriter))) { return matchSuccess(); } return matchFailure(); } }; struct UniformRealMulEwPattern : public OpRewritePattern<RealMulEwOp> { using OpRewritePattern<RealMulEwOp>::OpRewritePattern; PatternMatchResult matchAndRewrite(RealMulEwOp op, PatternRewriter &rewriter) const override { const UniformBinaryOpInfo info(op, op.lhs(), op.rhs(), op.clamp_min(), op.clamp_max()); if (!info.isValid()) { return matchFailure(); } // Try all of the permutations we support. if (succeeded(tryRewriteAffineMulEwSigned(info, rewriter))) { return matchSuccess(); } return matchFailure(); } }; } // end anonymous namespace //===----------------------------------------------------------------------===// // LowerUniformRealMath pass //===----------------------------------------------------------------------===// void LowerUniformRealMathPass::runOnFunction() { auto fn = getFunction(); OwningRewritePatternList patterns; auto *context = &getContext(); patterns.insert<UniformRealAddEwPattern, UniformRealMulEwPattern>(context); applyPatternsGreedily(fn, patterns); } OpPassBase<FuncOp> *mlir::fxpmath::createLowerUniformRealMathPass() { return new LowerUniformRealMathPass(); } static PassRegistration<LowerUniformRealMathPass> lowerUniformRealMathPass( "fxpmath-lower-uniform-real-math", "Lowers uniform-quantized real math ops to integer arithmetic."); //===----------------------------------------------------------------------===// // LowerUniformCasts pass //===----------------------------------------------------------------------===// void LowerUniformCastsPass::runOnFunction() { auto fn = getFunction(); OwningRewritePatternList patterns; auto *context = &getContext(); patterns.insert<UniformDequantizePattern>(context); applyPatternsGreedily(fn, patterns); } OpPassBase<FuncOp> *mlir::fxpmath::createLowerUniformCastsPass() { return new LowerUniformCastsPass(); } static PassRegistration<LowerUniformCastsPass> lowerUniformCastsPass("fxpmath-lower-uniform-casts", "Lowers uniform-quantized casts.");
15,051
4,243
/* ------------------------------------------------------------------ * Copyright (C) 1998-2009 PacketVideo * * 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. * ------------------------------------------------------------------- */ /**************************************************************************************** Portions of this file are derived from the following 3GPP standard: 3GPP TS 26.173 ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec Available from http://www.3gpp.org (C) 2007, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC) Permission to distribute, modify and use this file under the standard license terms listed above has been obtained from the copyright holder. ****************************************************************************************/ /* ------------------------------------------------------------------------------ Pathname: ./src/mime_io.cpp Date: 05/07/2007 ------------------------------------------------------------------------------ REVISION HISTORY Description: ------------------------------------------------------------------------------ INPUT AND OUTPUT DEFINITIONS Inputs: [input_variable_name] = [description of the input to module, its type definition, and length (when applicable)] Local Stores/Buffers/Pointers Needed: [local_store_name] = [description of the local store, its type definition, and length (when applicable)] [local_buffer_name] = [description of the local buffer, its type definition, and length (when applicable)] [local_ptr_name] = [description of the local pointer, its type definition, and length (when applicable)] Global Stores/Buffers/Pointers Needed: [global_store_name] = [description of the global store, its type definition, and length (when applicable)] [global_buffer_name] = [description of the global buffer, its type definition, and length (when applicable)] [global_ptr_name] = [description of the global pointer, its type definition, and length (when applicable)] Outputs: [return_variable_name] = [description of data/pointer returned by module, its type definition, and length (when applicable)] Pointers and Buffers Modified: [variable_bfr_ptr] points to the [describe where the variable_bfr_ptr points to, its type definition, and length (when applicable)] [variable_bfr] contents are [describe the new contents of variable_bfr] Local Stores Modified: [local_store_name] = [describe new contents, its type definition, and length (when applicable)] Global Stores Modified: [global_store_name] = [describe new contents, its type definition, and length (when applicable)] ------------------------------------------------------------------------------ FUNCTION DESCRIPTION [Describe what the module does by using the variable names listed in the Input and Output Definitions Section above.] ------------------------------------------------------------------------------ REQUIREMENTS [List requirements to be satisfied by this module.] ------------------------------------------------------------------------------ REFERENCES [List all references used in designing this module.] ------------------------------------------------------------------------------ PSEUDO-CODE ------------------------------------------------------------------------------ RESOURCES USED STACK USAGE: DATA MEMORY USED: x words PROGRAM MEMORY USED: x words CLOCK CYCLES: ------------------------------------------------------------------------------ */ /*---------------------------------------------------------------------------- ; INCLUDES ----------------------------------------------------------------------------*/ #include "pv_amr_wb_type_defs.h" #include "pvamrwbdecoder_api.h" #include "pvamrwbdecoder.h" #include "pvamrwbdecoder_mem_funcs.h" #include "pvamrwbdecoder_cnst.h" #include "dtx.h" #include "mime_io.h" /*---------------------------------------------------------------------------- ; MACROS ; Define module specific macros here ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; DEFINES ; Include all pre-processor statements here. Include conditional ; compile variables also. ----------------------------------------------------------------------------*/ #define MRSID 9 /*---------------------------------------------------------------------------- ; LOCAL FUNCTION DEFINITIONS ; Function Prototype declaration ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; LOCAL STORE/BUFFER/POINTER DEFINITIONS ; Variable declaration - defined here and used outside this module ----------------------------------------------------------------------------*/ const uint8 toc_byte[16] = {0x04, 0x0C, 0x14, 0x1C, 0x24, 0x2C, 0x34, 0x3C, 0x44, 0x4C, 0x54, 0x5C, 0x64, 0x6C, 0x74, 0x7C }; /* number of speech bits for all modes */ const int16 unpacked_size[16] = { 132, 177, 253, 285, 317, 365, 397, 461, 477, 35, 0, 0, 0, 0, 0, 0 }; /* size of packed frame for each mode, excluding TOC byte */ const int16 packed_size[16] = {17, 23, 32, 36, 40, 46, 50, 58, 60, 5, 0, 0, 0, 0, 0, 0 }; /* number of unused speech bits in packed format for each mode */ const int16 unused_size[16] = {4, 7, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0}; /* sorting tables for all modes */ const int16 sort_660[132] = { 0, 5, 6, 7, 61, 84, 107, 130, 62, 85, 8, 4, 37, 38, 39, 40, 58, 81, 104, 127, 60, 83, 106, 129, 108, 131, 128, 41, 42, 80, 126, 1, 3, 57, 103, 82, 105, 59, 2, 63, 109, 110, 86, 19, 22, 23, 64, 87, 18, 20, 21, 17, 13, 88, 43, 89, 65, 111, 14, 24, 25, 26, 27, 28, 15, 16, 44, 90, 66, 112, 9, 11, 10, 12, 67, 113, 29, 30, 31, 32, 34, 33, 35, 36, 45, 51, 68, 74, 91, 97, 114, 120, 46, 69, 92, 115, 52, 75, 98, 121, 47, 70, 93, 116, 53, 76, 99, 122, 48, 71, 94, 117, 54, 77, 100, 123, 49, 72, 95, 118, 55, 78, 101, 124, 50, 73, 96, 119, 56, 79, 102, 125 }; const int16 sort_885[177] = { 0, 4, 6, 7, 5, 3, 47, 48, 49, 112, 113, 114, 75, 106, 140, 171, 80, 111, 145, 176, 77, 108, 142, 173, 78, 109, 143, 174, 79, 110, 144, 175, 76, 107, 141, 172, 50, 115, 51, 2, 1, 81, 116, 146, 19, 21, 12, 17, 18, 20, 16, 25, 13, 10, 14, 24, 23, 22, 26, 8, 15, 52, 117, 31, 82, 147, 9, 33, 11, 83, 148, 53, 118, 28, 27, 84, 149, 34, 35, 29, 46, 32, 30, 54, 119, 37, 36, 39, 38, 40, 85, 150, 41, 42, 43, 44, 45, 55, 60, 65, 70, 86, 91, 96, 101, 120, 125, 130, 135, 151, 156, 161, 166, 56, 87, 121, 152, 61, 92, 126, 157, 66, 97, 131, 162, 71, 102, 136, 167, 57, 88, 122, 153, 62, 93, 127, 158, 67, 98, 132, 163, 72, 103, 137, 168, 58, 89, 123, 154, 63, 94, 128, 159, 68, 99, 133, 164, 73, 104, 138, 169, 59, 90, 124, 155, 64, 95, 129, 160, 69, 100, 134, 165, 74, 105, 139, 170 }; const int16 sort_1265[253] = { 0, 4, 6, 93, 143, 196, 246, 7, 5, 3, 47, 48, 49, 50, 51, 150, 151, 152, 153, 154, 94, 144, 197, 247, 99, 149, 202, 252, 96, 146, 199, 249, 97, 147, 200, 250, 100, 203, 98, 148, 201, 251, 95, 145, 198, 248, 52, 2, 1, 101, 204, 155, 19, 21, 12, 17, 18, 20, 16, 25, 13, 10, 14, 24, 23, 22, 26, 8, 15, 53, 156, 31, 102, 205, 9, 33, 11, 103, 206, 54, 157, 28, 27, 104, 207, 34, 35, 29, 46, 32, 30, 55, 158, 37, 36, 39, 38, 40, 105, 208, 41, 42, 43, 44, 45, 56, 106, 159, 209, 57, 66, 75, 84, 107, 116, 125, 134, 160, 169, 178, 187, 210, 219, 228, 237, 58, 108, 161, 211, 62, 112, 165, 215, 67, 117, 170, 220, 71, 121, 174, 224, 76, 126, 179, 229, 80, 130, 183, 233, 85, 135, 188, 238, 89, 139, 192, 242, 59, 109, 162, 212, 63, 113, 166, 216, 68, 118, 171, 221, 72, 122, 175, 225, 77, 127, 180, 230, 81, 131, 184, 234, 86, 136, 189, 239, 90, 140, 193, 243, 60, 110, 163, 213, 64, 114, 167, 217, 69, 119, 172, 222, 73, 123, 176, 226, 78, 128, 181, 231, 82, 132, 185, 235, 87, 137, 190, 240, 91, 141, 194, 244, 61, 111, 164, 214, 65, 115, 168, 218, 70, 120, 173, 223, 74, 124, 177, 227, 79, 129, 182, 232, 83, 133, 186, 236, 88, 138, 191, 241, 92, 142, 195, 245 }; const int16 sort_1425[285] = { 0, 4, 6, 101, 159, 220, 278, 7, 5, 3, 47, 48, 49, 50, 51, 166, 167, 168, 169, 170, 102, 160, 221, 279, 107, 165, 226, 284, 104, 162, 223, 281, 105, 163, 224, 282, 108, 227, 106, 164, 225, 283, 103, 161, 222, 280, 52, 2, 1, 109, 228, 171, 19, 21, 12, 17, 18, 20, 16, 25, 13, 10, 14, 24, 23, 22, 26, 8, 15, 53, 172, 31, 110, 229, 9, 33, 11, 111, 230, 54, 173, 28, 27, 112, 231, 34, 35, 29, 46, 32, 30, 55, 174, 37, 36, 39, 38, 40, 113, 232, 41, 42, 43, 44, 45, 56, 114, 175, 233, 62, 120, 181, 239, 75, 133, 194, 252, 57, 115, 176, 234, 63, 121, 182, 240, 70, 128, 189, 247, 76, 134, 195, 253, 83, 141, 202, 260, 92, 150, 211, 269, 84, 142, 203, 261, 93, 151, 212, 270, 85, 143, 204, 262, 94, 152, 213, 271, 86, 144, 205, 263, 95, 153, 214, 272, 64, 122, 183, 241, 77, 135, 196, 254, 65, 123, 184, 242, 78, 136, 197, 255, 87, 145, 206, 264, 96, 154, 215, 273, 58, 116, 177, 235, 66, 124, 185, 243, 71, 129, 190, 248, 79, 137, 198, 256, 88, 146, 207, 265, 97, 155, 216, 274, 59, 117, 178, 236, 67, 125, 186, 244, 72, 130, 191, 249, 80, 138, 199, 257, 89, 147, 208, 266, 98, 156, 217, 275, 60, 118, 179, 237, 68, 126, 187, 245, 73, 131, 192, 250, 81, 139, 200, 258, 90, 148, 209, 267, 99, 157, 218, 276, 61, 119, 180, 238, 69, 127, 188, 246, 74, 132, 193, 251, 82, 140, 201, 259, 91, 149, 210, 268, 100, 158, 219, 277 }; const int16 sort_1585[317] = { 0, 4, 6, 109, 175, 244, 310, 7, 5, 3, 47, 48, 49, 50, 51, 182, 183, 184, 185, 186, 110, 176, 245, 311, 115, 181, 250, 316, 112, 178, 247, 313, 113, 179, 248, 314, 116, 251, 114, 180, 249, 315, 111, 177, 246, 312, 52, 2, 1, 117, 252, 187, 19, 21, 12, 17, 18, 20, 16, 25, 13, 10, 14, 24, 23, 22, 26, 8, 15, 53, 188, 31, 118, 253, 9, 33, 11, 119, 254, 54, 189, 28, 27, 120, 255, 34, 35, 29, 46, 32, 30, 55, 190, 37, 36, 39, 38, 40, 121, 256, 41, 42, 43, 44, 45, 56, 122, 191, 257, 63, 129, 198, 264, 76, 142, 211, 277, 89, 155, 224, 290, 102, 168, 237, 303, 57, 123, 192, 258, 70, 136, 205, 271, 83, 149, 218, 284, 96, 162, 231, 297, 62, 128, 197, 263, 75, 141, 210, 276, 88, 154, 223, 289, 101, 167, 236, 302, 58, 124, 193, 259, 71, 137, 206, 272, 84, 150, 219, 285, 97, 163, 232, 298, 59, 125, 194, 260, 64, 130, 199, 265, 67, 133, 202, 268, 72, 138, 207, 273, 77, 143, 212, 278, 80, 146, 215, 281, 85, 151, 220, 286, 90, 156, 225, 291, 93, 159, 228, 294, 98, 164, 233, 299, 103, 169, 238, 304, 106, 172, 241, 307, 60, 126, 195, 261, 65, 131, 200, 266, 68, 134, 203, 269, 73, 139, 208, 274, 78, 144, 213, 279, 81, 147, 216, 282, 86, 152, 221, 287, 91, 157, 226, 292, 94, 160, 229, 295, 99, 165, 234, 300, 104, 170, 239, 305, 107, 173, 242, 308, 61, 127, 196, 262, 66, 132, 201, 267, 69, 135, 204, 270, 74, 140, 209, 275, 79, 145, 214, 280, 82, 148, 217, 283, 87, 153, 222, 288, 92, 158, 227, 293, 95, 161, 230, 296, 100, 166, 235, 301, 105, 171, 240, 306, 108, 174, 243, 309 }; const int16 sort_1825[365] = { 0, 4, 6, 121, 199, 280, 358, 7, 5, 3, 47, 48, 49, 50, 51, 206, 207, 208, 209, 210, 122, 200, 281, 359, 127, 205, 286, 364, 124, 202, 283, 361, 125, 203, 284, 362, 128, 287, 126, 204, 285, 363, 123, 201, 282, 360, 52, 2, 1, 129, 288, 211, 19, 21, 12, 17, 18, 20, 16, 25, 13, 10, 14, 24, 23, 22, 26, 8, 15, 53, 212, 31, 130, 289, 9, 33, 11, 131, 290, 54, 213, 28, 27, 132, 291, 34, 35, 29, 46, 32, 30, 55, 214, 37, 36, 39, 38, 40, 133, 292, 41, 42, 43, 44, 45, 56, 134, 215, 293, 198, 299, 136, 120, 138, 60, 279, 58, 62, 357, 139, 140, 295, 156, 57, 219, 297, 63, 217, 137, 170, 300, 222, 64, 106, 61, 78, 294, 92, 142, 141, 135, 221, 296, 301, 343, 59, 298, 184, 329, 315, 220, 216, 265, 251, 218, 237, 352, 223, 157, 86, 171, 87, 164, 351, 111, 302, 65, 178, 115, 323, 72, 192, 101, 179, 93, 73, 193, 151, 337, 309, 143, 274, 69, 324, 165, 150, 97, 338, 110, 310, 330, 273, 68, 107, 175, 245, 114, 79, 113, 189, 246, 259, 174, 71, 185, 96, 344, 100, 322, 83, 334, 316, 333, 252, 161, 348, 147, 82, 269, 232, 260, 308, 353, 347, 163, 231, 306, 320, 188, 270, 146, 177, 266, 350, 256, 85, 149, 116, 191, 160, 238, 258, 336, 305, 255, 88, 224, 99, 339, 230, 228, 227, 272, 242, 241, 319, 233, 311, 102, 74, 180, 275, 66, 194, 152, 325, 172, 247, 244, 261, 117, 158, 166, 354, 75, 144, 108, 312, 94, 186, 303, 80, 234, 89, 195, 112, 340, 181, 345, 317, 326, 276, 239, 167, 118, 313, 70, 355, 327, 253, 190, 176, 271, 104, 98, 153, 103, 90, 76, 267, 277, 248, 225, 262, 182, 84, 154, 235, 335, 168, 331, 196, 341, 249, 162, 307, 148, 349, 263, 321, 257, 243, 229, 356, 159, 119, 67, 187, 173, 145, 240, 77, 304, 332, 314, 342, 109, 254, 81, 278, 105, 91, 346, 318, 183, 250, 197, 328, 95, 155, 169, 268, 226, 236, 264 }; const int16 sort_1985[397] = { 0, 4, 6, 129, 215, 304, 390, 7, 5, 3, 47, 48, 49, 50, 51, 222, 223, 224, 225, 226, 130, 216, 305, 391, 135, 221, 310, 396, 132, 218, 307, 393, 133, 219, 308, 394, 136, 311, 134, 220, 309, 395, 131, 217, 306, 392, 52, 2, 1, 137, 312, 227, 19, 21, 12, 17, 18, 20, 16, 25, 13, 10, 14, 24, 23, 22, 26, 8, 15, 53, 228, 31, 138, 313, 9, 33, 11, 139, 314, 54, 229, 28, 27, 140, 315, 34, 35, 29, 46, 32, 30, 55, 230, 37, 36, 39, 38, 40, 141, 316, 41, 42, 43, 44, 45, 56, 142, 231, 317, 63, 73, 92, 340, 82, 324, 149, 353, 159, 334, 165, 338, 178, 163, 254, 77, 168, 257, 153, 343, 57, 248, 238, 79, 252, 166, 67, 80, 201, 101, 267, 143, 164, 341, 255, 339, 187, 376, 318, 78, 328, 362, 115, 232, 242, 253, 290, 276, 62, 58, 158, 68, 93, 179, 319, 148, 169, 154, 72, 385, 329, 333, 344, 102, 83, 144, 233, 323, 124, 243, 192, 354, 237, 64, 247, 202, 209, 150, 116, 335, 268, 239, 299, 188, 196, 298, 94, 195, 258, 123, 363, 384, 109, 325, 371, 170, 370, 84, 110, 295, 180, 74, 210, 191, 106, 291, 205, 367, 381, 377, 206, 355, 122, 119, 120, 383, 160, 105, 108, 277, 380, 294, 284, 285, 345, 208, 269, 249, 366, 386, 300, 297, 259, 125, 369, 197, 97, 194, 286, 211, 281, 280, 183, 372, 87, 155, 283, 59, 348, 327, 184, 76, 111, 330, 203, 349, 69, 98, 152, 145, 189, 66, 320, 337, 173, 358, 251, 198, 174, 263, 262, 126, 241, 193, 88, 388, 117, 95, 387, 112, 359, 287, 244, 103, 272, 301, 171, 162, 234, 273, 127, 373, 181, 292, 85, 378, 302, 121, 107, 364, 346, 356, 212, 278, 213, 65, 382, 288, 207, 113, 175, 99, 296, 374, 368, 199, 260, 185, 336, 331, 161, 270, 264, 250, 240, 75, 350, 151, 60, 89, 321, 156, 274, 360, 326, 70, 282, 167, 146, 352, 81, 91, 389, 266, 245, 177, 235, 190, 256, 204, 342, 128, 118, 303, 104, 379, 182, 114, 375, 200, 96, 293, 172, 214, 365, 279, 86, 289, 351, 347, 357, 261, 186, 176, 271, 90, 100, 147, 322, 275, 361, 71, 332, 61, 265, 157, 246, 236 }; const int16 sort_2305[461] = { 0, 4, 6, 145, 247, 352, 454, 7, 5, 3, 47, 48, 49, 50, 51, 254, 255, 256, 257, 258, 146, 248, 353, 455, 151, 253, 358, 460, 148, 250, 355, 457, 149, 251, 356, 458, 152, 359, 150, 252, 357, 459, 147, 249, 354, 456, 52, 2, 1, 153, 360, 259, 19, 21, 12, 17, 18, 20, 16, 25, 13, 10, 14, 24, 23, 22, 26, 8, 15, 53, 260, 31, 154, 361, 9, 33, 11, 155, 362, 54, 261, 28, 27, 156, 363, 34, 35, 29, 46, 32, 30, 55, 262, 37, 36, 39, 38, 40, 157, 364, 41, 42, 43, 44, 45, 56, 158, 263, 365, 181, 192, 170, 79, 57, 399, 90, 159, 297, 377, 366, 275, 68, 183, 388, 286, 194, 299, 92 , 70, 182, 401, 172, 59, 91, 58, 400, 368, 161, 81, 160, 264, 171, 80, 389, 390, 378, 379, 193, 298, 69, 266, 265, 367, 277, 288, 276, 287, 184, 60, 195, 82, 93, 71, 369, 402, 173, 162, 444, 300, 391, 98, 76, 278, 61, 267, 374, 135, 411, 167, 102, 380, 200, 87, 178, 65, 94, 204, 124, 72, 342, 189, 305, 381, 396, 433, 301, 226, 407, 289, 237, 113, 215, 185, 128, 309, 403, 116, 320, 196, 331, 370, 422, 174, 64, 392, 83, 425, 219, 134, 188, 432, 112, 427, 139, 279, 163, 436, 208, 447, 218, 236, 229, 97, 294, 385, 230, 166, 268, 177, 443, 225, 426, 101, 272, 138, 127, 290, 117, 347, 199, 414, 95, 140, 240, 410, 395, 209, 129, 283, 346, 105, 241, 437, 86, 308, 448, 203, 345, 186, 107, 220, 415, 334, 319, 106, 313, 118, 123, 73, 207, 421, 214, 384, 373, 438, 62, 371, 341, 75, 449, 168, 323, 164, 242, 416, 324, 304, 197, 335, 404, 271, 63, 191, 325, 96, 169, 231, 280, 312, 187, 406, 84, 201, 100, 67, 382, 175, 336, 202, 330, 269, 393, 376, 383, 293, 307, 409, 179, 285, 314, 302, 372, 398, 190, 180, 89, 99, 103, 232, 78, 88, 77, 136, 387, 165, 198, 394, 125, 176, 428, 74, 375, 238, 227, 66, 273, 282, 141, 306, 412, 114, 85, 130, 348, 119, 291, 296, 386, 233, 397, 303, 405, 284, 445, 423, 221, 210, 205, 450, 108, 274, 434, 216, 343, 337, 142, 243, 321, 408, 451, 310, 292, 120, 109, 281, 439, 270, 429, 332, 295, 418, 211, 315, 222, 326, 131, 430, 244, 327, 349, 417, 316, 143, 338, 440, 234, 110, 212, 452, 245, 121, 419, 350, 223, 132, 441, 328, 413, 317, 339, 126, 104, 137, 446, 344, 239, 435, 115, 333, 206, 322, 217, 228, 424, 453, 311, 351, 111, 442, 224, 213, 122, 431, 340, 235, 246, 133, 144, 420, 329, 318 }; const int16 sort_2385[477] = { 0, 4, 6, 145, 251, 360, 466, 7, 5, 3, 47, 48, 49, 50, 51, 262, 263, 264, 265, 266, 146, 252, 361, 467, 151, 257, 366, 472, 148, 254, 363, 469, 149, 255, 364, 470, 156, 371, 150, 256, 365, 471, 147, 253, 362, 468, 52, 2, 1, 157, 372, 267, 19, 21, 12, 17, 18, 20, 16, 25, 13, 10, 14, 24, 23, 22, 26, 8, 15, 53, 268, 31, 152, 153, 154, 155, 258, 259, 260, 261, 367, 368, 369, 370, 473, 474, 475, 476, 158, 373, 9, 33, 11, 159, 374, 54, 269, 28, 27, 160, 375, 34, 35, 29, 46, 32, 30, 55, 270, 37, 36, 39, 38, 40, 161, 376, 41, 42, 43, 44, 45, 56, 162, 271, 377, 185, 196, 174, 79, 57, 411, 90, 163, 305, 389, 378, 283, 68, 187, 400, 294, 198, 307, 92, 70, 186, 413, 176, 59, 91, 58, 412, 380, 165, 81, 164, 272, 175, 80, 401, 402, 390, 391, 197, 306, 69, 274, 273, 379, 285, 296, 284, 295, 188, 60, 199, 82, 93, 71, 381, 414, 177, 166, 456, 308, 403, 98, 76, 286, 61, 275, 386, 135, 423, 171, 102, 392, 204, 87, 182, 65, 94, 208, 124, 72, 350, 193, 313, 393, 408, 445, 309, 230, 419, 297, 241, 113, 219, 189, 128, 317, 415, 116, 328, 200, 339, 382, 434, 178, 64, 404, 83, 437, 223, 134, 192, 444, 112, 439, 139, 287, 167, 448, 212, 459, 222, 240, 233, 97, 302, 397, 234, 170, 276, 181, 455, 229, 438, 101, 280, 138, 127, 298, 117, 355, 203, 426, 95, 140, 244, 422, 407, 213, 129, 291, 354, 105, 245, 449, 86, 316, 460, 207, 353, 190, 107, 224, 427, 342, 327, 106, 321, 118, 123, 73, 211, 433, 218, 396, 385, 450, 62, 383, 349, 75, 461, 172, 331, 168, 246, 428, 332, 312, 201, 343, 416, 279, 63, 195, 333, 96, 173, 235, 288, 320, 191, 418, 84, 205, 100, 67, 394, 179, 344, 206, 338, 277, 405, 388, 395, 301, 315, 421, 183, 293, 322, 310, 384, 410, 194, 184, 89, 99, 103, 236, 78, 88, 77, 136, 399, 169, 202, 406, 125, 180, 440, 74, 387, 242, 231, 66, 281, 290, 141, 314, 424, 114, 85, 130, 356, 119, 299, 304, 398, 237, 409, 311, 417, 292, 457, 435, 225, 214, 209, 462, 108, 282, 446, 220, 351, 345, 142, 247, 329, 420, 463, 318, 300, 120, 109, 289, 451, 278, 441, 340, 303, 430, 215, 323, 226, 334, 131, 442, 248, 335, 357, 429, 324, 143, 346, 452, 238, 110, 216, 464, 249, 121, 431, 358, 227, 132, 453, 336, 425, 325, 347, 126, 104, 137, 458, 352, 243, 447, 115, 341, 210, 330, 221, 232, 436, 465, 319, 359, 111, 454, 228, 217, 122, 443, 348, 239, 250, 133, 144, 432, 337, 326 }; const int16 sort_SID[35] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34 }; /*---------------------------------------------------------------------------- ; EXTERNAL FUNCTION REFERENCES ; Declare functions defined elsewhere and referenced in this module ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES ; Declare variables used in this module but defined elsewhere ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; FUNCTION CODE ----------------------------------------------------------------------------*/ void mime_unsorting(uint8 unsorted_bits[], int16 sorted_bits_into_int16[], int16 * frame_type, int16 * mode, uint8 quality, RX_State_wb *st) { int16 i; int16 j; uint8 temp = 0; uint8 *unsorted_bits_ptr = (uint8*)unsorted_bits; /* pointer table for bit sorting tables */ const int16 *AmrWbSortingTables[16] = { sort_660, sort_885, sort_1265, sort_1425, sort_1585, sort_1825, sort_1985, sort_2305, sort_2385, sort_SID, NULL, NULL, NULL, NULL, NULL, NULL }; const int16 * pt_AmrWbSortingTables = AmrWbSortingTables[*mode]; /* clear compressed speech bit buffer */ pv_memset(sorted_bits_into_int16, 0, unpacked_size[*mode]*sizeof(*sorted_bits_into_int16)); /* unpack and unsort speech or SID bits */ for (i = unpacked_size[*mode] >> 3; i != 0; i--) { temp = *(unsorted_bits_ptr++); for (j = 2; j != 0; j--) { switch (temp & 0xf0) { case 0xf0: sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; break; case 0xe0: sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; pt_AmrWbSortingTables++; break; case 0xd0: sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; pt_AmrWbSortingTables++; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; break; case 0xc0: sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; pt_AmrWbSortingTables += 2; break; case 0xb0: sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; pt_AmrWbSortingTables++; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; break; case 0xa0: sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; pt_AmrWbSortingTables++; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; pt_AmrWbSortingTables++; break; case 0x90: sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; pt_AmrWbSortingTables += 2; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; break; case 0x80: sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; pt_AmrWbSortingTables += 3; break; case 0x70: pt_AmrWbSortingTables++; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; break; case 0x60: pt_AmrWbSortingTables++; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; pt_AmrWbSortingTables++; break; case 0x50: pt_AmrWbSortingTables++; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; pt_AmrWbSortingTables++; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; break; case 0x40: pt_AmrWbSortingTables++; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; pt_AmrWbSortingTables += 2; break; case 0x30: pt_AmrWbSortingTables += 2; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; break; case 0x20: pt_AmrWbSortingTables += 2; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; pt_AmrWbSortingTables++; break; case 0x10: pt_AmrWbSortingTables += 3; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; break; default: pt_AmrWbSortingTables += 4; break; } temp <<= 4; } } if (unpacked_size[*mode] % 4) { temp <<= 1; if (temp & 0x80) { sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; } } /* set frame type */ switch (*mode) { case MODE_7k: case MODE_9k: case MODE_12k: case MODE_14k: case MODE_16k: case MODE_18k: case MODE_20k: case MODE_23k: case MODE_24k: if (quality) { *frame_type = RX_SPEECH_GOOD; } else { *frame_type = RX_SPEECH_BAD; } break; case MRSID: if (quality) { if (temp & 0x80) { *frame_type = RX_SID_UPDATE; } else { *frame_type = RX_SID_FIRST; } } else { *frame_type = RX_SID_BAD; } /* set mode index */ *mode = st->prev_mode; break; case 14: /* SPEECH_LOST */ *frame_type = RX_SPEECH_LOST; *mode = st->prev_mode; break; case 15: /* NO_DATA */ *frame_type = RX_NO_DATA; *mode = st->prev_mode; break; default: /* replace frame with unused mode index by NO_DATA frame */ *frame_type = RX_NO_DATA; *mode = st->prev_mode; break; } st->prev_mode = *mode; }
30,144
18,286
#include <opengl/buffer.hpp> #include <fstream> #include <glad/glad.h> #include <opengl/check-error.hpp> constexpr int usageToGlUsage(Buffer::Usage usage) { switch(usage) { case Buffer::StreamDraw: return GL_STREAM_DRAW; case Buffer::StreamRead: return GL_STREAM_READ; case Buffer::StreamCopy: return GL_STREAM_COPY; case Buffer::StaticDraw: return GL_STATIC_DRAW; case Buffer::StaticRead: return GL_STATIC_READ; case Buffer::StaticCopy: return GL_STATIC_COPY; case Buffer::DynamicDraw: return GL_DYNAMIC_DRAW; case Buffer::DynamicRead: return GL_DYNAMIC_READ; case Buffer::DynamicCopy: return GL_DYNAMIC_COPY; default: return GL_STREAM_COPY; } } constexpr int typeToGlType(Buffer::Type type) { switch(type) { case Buffer::ArrayBuffer: return GL_ARRAY_BUFFER; case Buffer::ElementArrayBuffer: return GL_ELEMENT_ARRAY_BUFFER; case Buffer::ShaderStorageBuffer: return GL_SHADER_STORAGE_BUFFER; default: return GL_ARRAY_BUFFER; } } Buffer::~Buffer() { if(buffer) { glDeleteBuffers(1, &buffer); buffer = 0; } if(data) { free(data); data = nullptr; } } void Buffer::build() { auto type = typeToGlType(this->type); auto usage = usageToGlUsage(this->usage); checkGlError(glGenBuffers(1, &buffer)); checkGlError(glBindBuffer(type, buffer)); checkGlError(glBufferData(type, bufferSize, data, usage)); } void Buffer::bind() { if(!buffer) { build(); } checkGlError(glBindBuffer(typeToGlType(type), buffer)); } void Buffer::bindBase(uint32_t index) { if(!buffer) { build(); } checkGlError(glBindBufferBase(typeToGlType(type), index, buffer)); } void Buffer::setData(const void* data, size_t size) { if(bufferSize < size || !this->data) { this->data = realloc(this->data, size); } auto type = typeToGlType(this->type); auto usage = usageToGlUsage(this->usage); memcpy(this->data, data, size); bufferSize = size; checkGlError(glBufferData(type, bufferSize, data, usage)); } void Buffer::mapBuffer(const std::function<void(const void* const)>& func) { bind(); auto type = typeToGlType(this->type); GLvoid* p = glMapBuffer(type, GL_READ_ONLY); func(p); glUnmapBuffer(type); } void Buffer::mapWritableBuffer(const std::function<void(void*)>& func) { bind(); auto type = typeToGlType(this->type); GLvoid* p = glMapBuffer(type, GL_READ_WRITE); func(p); glUnmapBuffer(type); } void Buffer::_writeContentsToFile(const char* fileName) { mapBuffer([this, fileName] (const void* const ptr) { std::ofstream ff("yes.bin"); ff.write((const char*) ptr, this->bufferSize); ff.close(); }); }
2,821
975
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #include "CryLegacy_precompiled.h" #include <IRenderAuxGeom.h> #include "ModelMesh.h" #include "Model.h" #ifdef EDITOR_PCDEBUGCODE extern float g_YLine; //-------------------------------------------------------------------- //--- hex-dump of model --- //-------------------------------------------------------------------- void CModelMesh::ExportModel(IRenderMesh* pIRenderMesh) { #if 0 DynArray<Vec3> arrSrcPositions; DynArray<Quat> arrSrcQTangents; DynArray<Vec2> arrSrcUV; DynArray<BoneIndices8> arrSrcBoneIDs; DynArray<BoneWeights8> arrSrcVWeights; uint32 numExtIndices = pIRenderMesh->GetIndicesCount(); uint32 numExtVertices = pIRenderMesh->GetVerticesCount(); uint32 vsize = m_arrSrcPositions.size(); if (vsize < numExtVertices) { arrSrcPositions.resize(numExtVertices); arrSrcQTangents.resize(numExtVertices); arrSrcVWeights.resize(numExtVertices); arrSrcUV.resize(numExtVertices); } pIRenderMesh->LockForThreadAccess(); vtx_idx* pIndices = pIRenderMesh->GetIndexPtr(FSL_READ); int32 nPositionStride; uint8* pPositions = pIRenderMesh->GetPosPtr(nPositionStride, FSL_READ); if (pPositions == 0) { return; } int32 nQTangentStride; uint8* pQTangents = pIRenderMesh->GetQTangentPtr(nQTangentStride, FSL_READ); if (pQTangents == 0) { return; } int32 nUVStride; uint8* pUV = pIRenderMesh->GetUVPtr(nUVStride, FSL_READ); if (pUV == 0) { return; } int32 nSkinningStride; uint8* pSkinningInfo = pIRenderMesh->GetHWSkinPtr(nSkinningStride, FSL_READ); //pointer to weights and bone-id if (pSkinningInfo == 0) { return; } ++m_iThreadMeshAccessCounter; //convert hw-buffer into sw-buffer for (uint32 i = 0; i < numExtVertices; ++i) { Vec3 wpos = *((Vec3*) (pPositions + i * nPositionStride)); SPipQTangents QTangent = *(SPipQTangents*)(pQTangents + i * nQTangentStride); Vec2 uv = *((Vec2*) (pUV + i * nUVStride)); ColorB weights = *(ColorB*)&((SVF_W4B_I4B*)(pSkinningInfo + i * nSkinningStride))->weights; arrSrcPositions[i] = wpos; arrSrcQTangents[i] = QTangent.GetQ(); assert(m_arrSrcQTangents[i].IsUnit()); arrSrcVWeights[i].w0 = weights[0] / 255.0f; arrSrcVWeights[i].w1 = weights[1] / 255.0f; arrSrcVWeights[i].w2 = weights[2] / 255.0f; arrSrcVWeights[i].w3 = weights[3] / 255.0f; arrSrcUV[i].x = uv.x; arrSrcUV[i].y = uv.y; } //initialize bone indices if (m_arrSrcBoneIDs.size() != numExtVertices) { m_arrSrcBoneIDs.resize(numExtVertices); memset(&m_arrSrcBoneIDs[0], 0, numExtVertices * sizeof(BoneIndices8)); uint32 numSubsets = m_arrRenderChunks.size(); for (uint32 s = 0; s < numSubsets; s++) { uint32 startIndex = m_arrRenderChunks[s].m_nFirstIndexId; uint32 endIndex = m_arrRenderChunks[s].m_nFirstIndexId + m_arrRenderChunks[s].m_nNumIndices; for (uint32 idx = startIndex; idx < endIndex; ++idx) { uint32 e = pIndices[idx]; ColorB hwBoneIDs = *(ColorB*)&((SVF_W4B_I4B*)(pSkinningInfo + e * nSkinningStride))->indices; ColorB hwWeights = *(ColorB*)&((SVF_W4B_I4B*)(pSkinningInfo + e * nSkinningStride))->weights; uint32 _id0 = hwBoneIDs[0]; uint32 _id1 = hwBoneIDs[1]; uint32 _id2 = hwBoneIDs[2]; uint32 _id3 = hwBoneIDs[3]; if (hwWeights[0]) { arrSrcBoneIDs[e].idx0 = _id0; } if (hwWeights[1]) { arrSrcBoneIDs[e].idx1 = _id1; } if (hwWeights[2]) { arrSrcBoneIDs[e].idx2 = _id2; } if (hwWeights[3]) { arrSrcBoneIDs[e].idx3 = _id3; } } } } //-------------------------------------------------------------------------------- //-- dump all vertices //-------------------------------------------------------------------------------- FILE* vstream = nullptr; fopen_s(&vstream, "c:\\VBuffer.txt", "w+b"); for (uint32 v = 0; v < numExtVertices; v++) { fprintf(vstream, " {%15.10ff,%15.10ff,%15.10ff, %15.10ff,%15.10ff,%15.10ff,%15.10ff, %15.10ff,%15.10ff }, //%04x", arrSrcPositions[v].x, arrSrcPositions[v].y, arrSrcPositions[v].z, arrSrcQTangents[v].v.x, arrSrcQTangents[v].v.y, arrSrcQTangents[v].v.z, arrSrcQTangents[v].w, arrSrcUV[v].x, arrSrcUV[v].y, v); fprintf(vstream, "\r\n"); } fprintf(vstream, "\r\n\r\n"); fclose(vstream); //-------------------------------------------------------------------------------- //-- dump all indices //-------------------------------------------------------------------------------- FILE* istream = nullptr; fopen_s(&istream, "c:\\IBuffer.txt", "w+b"); for (uint32 f = 0; f < numExtIndices; f = f + 3) { fprintf(istream, "0x%04x,0x%04x,0x%04x, //0x%08x", pIndices[f + 0], pIndices[f + 1], pIndices[f + 2], f / 3); fprintf(istream, "\r\n"); } fprintf(istream, "\r\n\r\n"); fclose(istream); //-------------------------------------------------------------------------------- //-- dump all subsets //-------------------------------------------------------------------------------- /*uint32 numSubsets = m_arrSubsets.size(); FILE* sstream = nullptr; fopen_s(&sstream, "c:\\Subsets.txt", "w+b" ); for (uint32 s=0; s<numSubsets; s++) { fprintf(sstream, "0x%08x,0x%08x, 0x%08x,0x%08x, 0x%04x, //0x%08x", m_arrSubsets[s].nFirstVertId,m_arrSubsets[s].nNumVerts, m_arrSubsets[s].nFirstIndexId,m_arrSubsets[s].nNumIndices/3, m_arrSubsets[s].nMatID, s); fprintf(vstream, "\r\n"); } fprintf(sstream, "\r\n\r\n"); fclose(sstream);*/ pIRenderMesh->UnLockForThreadAccess(); --m_iThreadMeshAccessCounter; if (m_iThreadMeshAccessCounter == 0) { pIRenderMesh->UnlockStream(VSF_GENERAL); pIRenderMesh->UnlockStream(VSF_TANGENTS); pIRenderMesh->UnlockStream(VSF_HWSKIN_INFO); } #endif } void CModelMesh::DrawWireframeStatic(const Matrix34& rRenderMat34, uint32 color) { if (m_pIRenderMesh == 0) { return; } uint32 numExtIndices = m_pIRenderMesh->GetIndicesCount(); uint32 numExtVertices = m_pIRenderMesh->GetVerticesCount(); assert(numExtVertices); static std::vector<Vec3> arrExtSkinnedStream; uint32 vsize = arrExtSkinnedStream.size(); if (vsize < numExtVertices) { arrExtSkinnedStream.resize(numExtVertices); } m_pIRenderMesh->LockForThreadAccess(); uint32 numIndices = m_pIRenderMesh->GetIndicesCount(); vtx_idx* pIndices = m_pIRenderMesh->GetIndexPtr(FSL_READ); int32 nPositionStride; uint8* pPositions = m_pIRenderMesh->GetPosPtr(nPositionStride, FSL_READ); if (pPositions == 0) { return; } ++m_iThreadMeshAccessCounter; for (uint32 e = 0; e < numExtVertices; e++) { Vec3 v = *(Vec3*)(pPositions + e * nPositionStride); arrExtSkinnedStream[e] = rRenderMat34 * (v + m_vRenderMeshOffset); } m_pIRenderMesh->UnLockForThreadAccess(); --m_iThreadMeshAccessCounter; if (m_iThreadMeshAccessCounter == 0) { m_pIRenderMesh->UnlockStream(VSF_GENERAL); m_pIRenderMesh->UnlockStream(VSF_TANGENTS); m_pIRenderMesh->UnlockStream(VSF_HWSKIN_INFO); } SAuxGeomRenderFlags renderFlags(e_Def3DPublicRenderflags); renderFlags.SetFillMode(e_FillModeWireframe); renderFlags.SetDrawInFrontMode(e_DrawInFrontOn); renderFlags.SetAlphaBlendMode(e_AlphaAdditive); g_pAuxGeom->SetRenderFlags(renderFlags); g_pAuxGeom->DrawTriangles(&arrExtSkinnedStream[0], numExtVertices, pIndices, numExtIndices, color); } #endif void CModelMesh::DrawDebugInfo(CDefaultSkeleton* pCSkel, int nLOD, const Matrix34& rRenderMat34, int DebugMode, const _smart_ptr<IMaterial>& pMaterial, CRenderObject* pObj, const SRendParams& RendParams, bool isGeneralPass, IRenderNode* pRenderNode, const AABB& aabb) { if (m_pIRenderMesh == 0) { return; } bool bNoText = DebugMode < 0; int32 numLODs = 1; int index = 0; Vec3 trans = rRenderMat34.GetTranslation(); float color[4] = {1, 1, 1, 1}; int nTris = m_pIRenderMesh->GetVerticesCount(); int nMats = m_pIRenderMesh->GetChunks().size(); int nRenderMats = 0; string shortName = PathUtil::GetFile(pCSkel->GetModelFilePath()); IRenderAuxGeom* pAuxGeom = g_pIRenderer->GetIRenderAuxGeom(); if (nMats) { for (int i = 0; i < nMats; ++i) { CRenderChunk& rc = m_pIRenderMesh->GetChunks()[i]; if (rc.pRE && rc.nNumIndices && rc.nNumVerts && ((rc.m_nMatFlags & MTL_FLAG_NODRAW) == 0)) { ++nRenderMats; } } } switch (DebugMode) { case 1: g_pIRenderer->DrawLabelEx(trans, 1.3f, color, true, true, "%s\n%d LOD(%i\\%i)", shortName.c_str(), nTris, nLOD + 1, numLODs); pAuxGeom->DrawAABB(pCSkel->m_ModelAABB, rRenderMat34, false, ColorB(0, 255, 255, 128), eBBD_Faceted); break; case 2: { IMaterialManager* pMatMan = g_pI3DEngine->GetMaterialManager(); int fMult = 1; //int nTris = m_pDefaultSkeleton->GetRenderMesh(nLOD)->GetSysVertCount(); ColorB clr = ColorB(255, 255, 255, 255); if (nTris >= 20000 * fMult) { clr = ColorB(255, 0, 0, 255); } else if (nTris >= 10000 * fMult) { clr = ColorB(255, 255, 0, 255); } else if (nTris >= 5000 * fMult) { clr = ColorB(0, 255, 0, 255); } else if (nTris >= 2500 * fMult) { clr = ColorB(0, 255, 255, 255); } else if (nTris > 1250 * fMult) { clr = ColorB(0, 0, 255, 255); } else { clr = ColorB(nTris / 10, nTris / 10, nTris / 10, 255); } //if (pMaterial) // pMaterial = pMatMan->GetDefaultHelperMaterial(); //if (pObj) pObj->m_II.m_AmbColor = ColorF(clr.r /*/155.0f*/, clr.g /*/155.0f*/, clr.b /*/155.0f*/, 1); if (!bNoText) { g_pIRenderer->DrawLabelEx(trans, 1.3f, color, true, true, "%d", nTris); } } break; case 3: { ////////////////////////////////////////////////////////////////////////// // Show Lods ////////////////////////////////////////////////////////////////////////// ColorB clr; if (numLODs < 2) { if (nTris <= 30) { clr = ColorB(50, 50, 50, 255); } else { clr = ColorB(255, 0, 0, 255); float fAngle = gEnv->pTimer->GetFrameStartTime().GetPeriodicFraction(1.0f) * gf_PI2; clr.g = 127 + (int)(sin(fAngle) * 120); // flashing color } } else { if (nLOD == 1) { clr = ColorB(255, 0, 0, 255); } else if (nLOD == 2) { clr = ColorB(0, 255, 0, 255); } else if (nLOD == 3) { clr = ColorB(0, 0, 255, 255); } else if (nLOD == 4) { clr = ColorB(0, 255, 255, 255); } else { clr = ColorB(255, 255, 255, 255); } } //if (pMaterial) // pMaterial = GetMatMan()->GetDefaultHelperMaterial(); if (pObj) { pObj->m_II.m_AmbColor = ColorF(clr.r, clr.g, clr.b, 1); } if (numLODs > 1 && !bNoText) { g_pIRenderer->DrawLabelEx(trans, 1.3f, color, true, true, "%d/%d", nLOD + 1, numLODs); } } break; case 4: if (m_pIRenderMesh) { int nTexMemUsage = m_pIRenderMesh->GetTextureMemoryUsage(pMaterial); g_pIRenderer->DrawLabelEx(trans, 1.3f, color, true, true, "%d", nTexMemUsage / 1024); } break; case 5: { ColorB clr; if (nRenderMats == 1) { clr = ColorB(0, 0, 255, 255); } else if (nRenderMats == 2) { clr = ColorB(0, 255, 255, 255); } else if (nRenderMats == 3) { clr = ColorB(0, 255, 0, 255); } else if (nRenderMats == 4) { clr = ColorB(255, 0, 255, 255); } else if (nRenderMats == 5) { clr = ColorB(255, 255, 0, 255); } else if (nRenderMats >= 6) { clr = ColorB(255, 0, 0, 255); } else if (nRenderMats >= 11) { clr = ColorB(255, 255, 255, 255); } pObj->m_II.m_AmbColor = ColorF(clr.r, clr.g, clr.b, 1); if (!bNoText) { g_pIRenderer->DrawLabelEx(trans, 1.3f, color, true, true, "%d", nRenderMats); } } break; case 6: { g_pIRenderer->DrawLabelEx(trans, 1.3f, color, true, true, "%d,%d,%d,%d", (int)(RendParams.AmbientColor.r * 255.0f), (int)(RendParams.AmbientColor.g * 255.0f), (int)(RendParams.AmbientColor.b * 255.0f), (int)(RendParams.AmbientColor.a * 255.0f) ); } break; case 7: if (m_pIRenderMesh) { int nTexMemUsage = m_pIRenderMesh->GetTextureMemoryUsage(pMaterial); g_pIRenderer->DrawLabelEx(trans, 1.3f, color, true, true, "%d,%d,%d", nTris, nRenderMats, nTexMemUsage / 1024); } break; case 21: if (m_pIRenderMesh) { AABB bbox; m_pIRenderMesh->GetBBox(bbox.min, bbox.max); bbox.SetTransformedAABB(rRenderMat34, bbox); trans = (bbox.max + bbox.min) / 2; Vec3 pos = g_pI3DEngine->GetRenderingCamera().GetPosition(); float fEntDistance = sqrt_tpl(Distance::Point_AABBSq(pos, bbox)); // activate objects before they get really visible g_pIRenderer->DrawLabelEx(trans, 1.3f, color, true, true, "%.2f", fEntDistance); } break; case -21: if (m_pIRenderMesh) { AABB bbox; m_pIRenderMesh->GetBBox(bbox.min, bbox.max); bbox.SetTransformedAABB(rRenderMat34, bbox); trans = (bbox.max + bbox.min) / 2; Vec3 pos = g_pI3DEngine->GetRenderingCamera().GetPosition(); float fEntDistance = sqrt_tpl(Distance::Point_AABBSq(pos, bbox)); // activate objects before they get really visible g_pIRenderer->DrawLabelEx(trans, 1.3f, color, true, true, "%.2f (%s)", fEntDistance, m_pIRenderMesh->GetSourceName()); } break; case 10: if (m_pIRenderMesh) { SGeometryDebugDrawInfo dd; dd.tm = *RendParams.pMatrix; m_pIRenderMesh->DebugDraw(dd); } break; case 19: // Displays the triangle count of physic proxies. if (!bNoText) { int nPhysTrisCount = 0; #if ENABLE_CRY_PHYSICS const phys_geometry* pgeom; for (int i = pCSkel->GetJointCount() - 1; i >= 0; --i) { if (pgeom = pCSkel->GetJointPhysGeom((uint32)i)) { nPhysTrisCount += pgeom->pGeom->GetPrimitiveCount(); } } #endif // ENABLE_CRY_PHYSICS if (nPhysTrisCount == 0) { color[3] = 0.1f; } g_pIRenderer->DrawLabelEx(trans, 1.3f, color, true, true, "%d", nPhysTrisCount); } break; default: break; } #ifndef _RELEASE if (isGeneralPass && gEnv->p3DEngine->IsDebugDrawListEnabled()) { I3DEngine::SObjectInfoToAddToDebugDrawList objectInfo; objectInfo.pFileName = pCSkel->GetModelFilePath(); objectInfo.pName = pRenderNode ? pRenderNode->GetName() : ""; objectInfo.pClassName = pRenderNode ? pRenderNode->GetEntityClassName() : ""; objectInfo.texMemory = m_pIRenderMesh->GetTextureMemoryUsage(pMaterial); objectInfo.numTris = nTris; objectInfo.numVerts = nTris; objectInfo.meshMemory = m_pIRenderMesh->GetMemoryUsage(NULL, IRenderMesh::MEM_USAGE_COMBINED); objectInfo.pBox = &aabb; objectInfo.pMat = &rRenderMat34; objectInfo.type = I3DEngine::DLOT_CHARACTER; objectInfo.pRenderNode = pRenderNode; gEnv->p3DEngine->AddObjToDebugDrawList(objectInfo); } #endif }
17,910
6,841
/* ========================= eCAL LICENSE ================================= * * Copyright (C) 2016 - 2019 Continental Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ========================= eCAL LICENSE ================================= */ #include <ecal/ecal.h> #include <iostream> #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable: 4100 4127 4146 4505 4800 4189 4592) // disable proto warnings #endif #include "ecal/pb/ecal.pb.h" #ifdef _MSC_VER #pragma warning(pop) #endif void OnProcessRegistration(const char* sample_, int sample_size_) { eCAL::pb::Sample sample; if (sample.ParseFromArray(sample_, sample_size_)) { std::cout << std::endl; std::cout << "----------------------------------" << std::endl; std::cout << "Process Registration" << std::endl; std::cout << "----------------------------------" << std::endl; std::cout << sample.DebugString(); std::cout << std::endl; } } void OnServiceRegistration(const char* sample_, int sample_size_) { eCAL::pb::Sample sample; if (sample.ParseFromArray(sample_, sample_size_)) { std::cout << std::endl; std::cout << "----------------------------------" << std::endl; std::cout << "Service Registration" << std::endl; std::cout << "----------------------------------" << std::endl; std::cout << sample.DebugString(); std::cout << std::endl; } } void OnSubscriberRegistration(const char* sample_, int sample_size_) { eCAL::pb::Sample sample; if (sample.ParseFromArray(sample_, sample_size_)) { std::cout << std::endl; std::cout << "----------------------------------" << std::endl; std::cout << "Subscriber Registration" << std::endl; std::cout << "----------------------------------" << std::endl; std::cout << sample.DebugString(); std::cout << std::endl; } } void OnPublisherRegistration(const char* sample_, int sample_size_) { eCAL::pb::Sample sample; if (sample.ParseFromArray(sample_, sample_size_)) { std::cout << std::endl; std::cout << "----------------------------------" << std::endl; std::cout << "Publisher Registration" << std::endl; std::cout << "----------------------------------" << std::endl; std::cout << sample.DebugString(); std::cout << std::endl; } } int main(int argc, char **argv) { // initialize eCAL API eCAL::Initialize(argc, argv, "monitoring registrations", eCAL::Init::None); // set process state eCAL::Process::SetState(proc_sev_healthy, proc_sev_level1, "I feel good !"); // add process register callback function eCAL::Process::AddRegistrationCallback(reg_event_process, std::bind(OnProcessRegistration, std::placeholders::_1, std::placeholders::_2)); // add service register callback function eCAL::Process::AddRegistrationCallback(reg_event_service, std::bind(OnServiceRegistration, std::placeholders::_1, std::placeholders::_2)); // add subscriber register callback function eCAL::Process::AddRegistrationCallback(reg_event_subscriber, std::bind(OnSubscriberRegistration, std::placeholders::_1, std::placeholders::_2)); // add publisher register callback function eCAL::Process::AddRegistrationCallback(reg_event_publisher, std::bind(OnPublisherRegistration, std::placeholders::_1, std::placeholders::_2)); while(eCAL::Ok()) { // sleep 100 ms eCAL::Process::SleepMS(100); } // finalize eCAL API eCAL::Finalize(); return(0); }
4,168
1,295
//////////////////////////////////////////////////////////////////////////////////////////////////// // // Project: tiler // File: PrintUtils.cpp // Authors: Ofer Dekel // //////////////////////////////////////////////////////////////////////////////////////////////////// #include "PrintUtils.h" namespace tiler { int globalIndentLevel = 0; std::ostream& Indent(std::ostream& stream) { stream << std::string(4 * globalIndentLevel, ' '); return stream; } void IncreaseIndent() { globalIndentLevel++; } void DecreaseIndent() { globalIndentLevel--; } void PrintFormated(std::ostream& os, const char* format) { while (*format != '\0') { os << *format; ++format; } } }
826
235
//#ifdef _DEBUG //#include "../../../library/src/debug_template.hpp" //#define DMP(...) dump(#__VA_ARGS__, __VA_ARGS__) //#else //#define DMP(...) ((void)0) //#endif // //#include <cassert> //#include <cstdio> //#include <cmath> //#include <iostream> //#include <iomanip> //#include <vector> //#include <set> //#include <map> //#include <unordered_map> //#include <queue> //#include <numeric> //#include <algorithm> //#include <bitset> //#include <functional> // //using namespace std; //using lint = long long; //constexpr int MOD = 1000000007, INF = 1010101010; //constexpr lint LINF = 1LL << 60; // //struct init { // init() { // cin.tie(nullptr); ios::sync_with_stdio(false); // cout << fixed << setprecision(10); // } //} init_; // //template <typename T> //struct SegmentTree { // using F = function<T(T, T)>; // int n; // F f; // T ti; // vector<T> dat; // // SegmentTree(F f, T ti) :f(f), ti(ti) {} // // void init(int n_) { // n = 1; // while (n < n_) n <<= 1; // dat.assign(n << 1, ti); // } // // void build(const vector<T>& v) { // int n_ = v.size(); // init(n_); // for (int i = 0; i < n_; i++) dat[n + i] = v[i]; // for (int i = n - 1; i; i--) // dat[i] = f(dat[(i << 1) | 0], dat[(i << 1) | 1]); // } // // void set_val(int k, T x) { // dat[k += n] = x; // while (k >>= 1) // dat[k] = f(dat[(k << 1) | 0], dat[(k << 1) | 1]); // } // // T query(int a, int b) { // if (a >= b) return ti; // T vl = ti, vr = ti; // for (int l = a + n, r = b + n; l < r; l >>= 1, r >>= 1) { // if (l & 1) vl = f(vl, dat[l++]); // if (r & 1) vr = f(dat[--r], vr); // } // return f(vl, vr); // } // // template<typename C> // int find(int st, C& check, T& acc, int k, int l, int r) { // if (l + 1 == r) { // acc = f(acc, dat[k]); // return check(acc) ? k - n : -1; // } // int m = (l + r) >> 1; // if (m <= st) return find(st, check, acc, (k << 1) | 1, m, r); // if (st <= l and !check(f(acc, dat[k]))) { // acc = f(acc, dat[k]); // return -1; // } // int vl = find(st, check, acc, (k << 1) | 0, l, m); // if (~vl) return vl; // return find(st, check, acc, (k << 1) | 1, m, r); // } // // template<typename C> // int find(int st, C& check) { // T acc = ti; // return find(st, check, acc, 1, 0, n); // } //}; // //template<class T> //inline bool chmax(T& a, const T b) { return a < b && (a = b, true); } // //int main() { // // int N, K; // cin >> N >> K; // // vector<int> A(N); // for (int i = 0; i < N; i++) cin >> A[i]; // // constexpr int A_max = 333333; // auto f = [](int a, int b) { return max(a, b); }; // SegmentTree<int> sg(f, 0); // sg.init(A_max); // // int ans = 0; // for (int i = 0; i < N; i++) { // int L = max(A[i] - K, 0); // int R = min(A[i] + K + 1, A_max); // int now = sg.query(L, R) + 1; // sg.set_val(A[i], now); // chmax(ans, now); // } // // cout << ans << "\n"; // // return 0; //}
3,198
1,389
#include <bits/stdc++.h> using namespace std; using LL = long long; using Pii = pair<int, int>; using Pll = pair<LL, LL>; using VI = vector<int>; using VP = vector<pair<int, int>>; #define rep(i, a, b) for (auto i = (a); i < (b); ++i) #define rev(i, a, b) for (auto i = (b - 1); i >= (a); --i) #define grep(i, u) for (auto i = gh[u]; i != -1; i = gn[i]) #define mem(x, v) memset(x, v, sizeof(x)) #define cpy(x, y) memcpy(x, y, sizeof(x)) #define SZ(V) static_cast<int>(V.size()) #define pb push_back #define mp make_pair constexpr int maxn = 10400000; int fa[maxn], vis[maxn], sz[maxn]; int n, m, l, t; inline int get_id(int x, int y, int z) { return z * n * m + x * m + y; } int find_fa(int x) { return x == fa[x] ? x : fa[x] = find_fa(fa[x]); } bool is_union(int x, int y) { return find_fa(x) == find_fa(y); } void join(int u, int v) { u = find_fa(u); v = find_fa(v); if (u != v) { fa[v] = u; sz[u] += sz[v]; } } int main() { // freopen("input.in", "r", stdin); scanf("%d%d%d%d", &n, &m, &l, &t); rep(k, 0, l) rep(i, 0, n) rep(j, 0, m) { int id = get_id(i, j, k); scanf("%d", &sz[id]); fa[id] = id; } rep(k, 0, l) rep(i, 0, n) rep(j, 0, m) { int id = get_id(i, j, k), new_id; if (!sz[id]) continue; if (i + 1 < n) { new_id = get_id(i + 1, j, k); if (sz[new_id]) join(id, new_id); } if (j + 1 < m) { new_id = get_id(i, j + 1, k); if (sz[new_id]) join(id, new_id); } if (k + 1 < l) { new_id = get_id(i, j, k + 1); if (sz[new_id]) join(id, new_id); } } LL ans = 0; rep(k, 0, l) rep(i, 0, n) rep(j, 0, m) { int id = find_fa(get_id(i, j, k)); if (vis[id]) continue; vis[id] = true; if (sz[id] >= t) ans += sz[id]; } printf("%lld\n", ans); }
1,778
882
#include "fbx_lod_group_loader.hpp" #include <utils/f_typedefs.hpp> namespace fengine { float FbxLodGroupLoader::RetrieveThreshold(int index) const { FbxDistance threshold; auto result = this->GetThreshold(index, threshold); return result ? threshold.value() : FLT_MAX; } }
284
109
#include <QmlNet/types/NetReference.h> #include <QmlNet/types/NetTypeArrayFacade.h> #include <QmlNet/qml/NetVariant.h> #include <QmlNet/qml/NetValue.h> #include <QmlNet/qml/NetJsValue.h> #include <QmlNet/qml/NetQObject.h> #include <QmlNetUtilities.h> #include <QDateTime> #include <QDebug> #include <QJSEngine> #include <QmlNet/qml/QQmlApplicationEngine.h> namespace { struct NetReferenceQmlContainer { QSharedPointer<NetReference> netReference; }; struct NetJsValueQmlContainer { QSharedPointer<NetJSValue> jsValue; }; struct NetQObjectQmlContainer { QSharedPointer<NetQObject> netQObject; }; struct NetVariantListQmlContainer { QSharedPointer<NetVariantList> netVariantList; }; } Q_DECLARE_METATYPE(NetReferenceQmlContainer) Q_DECLARE_METATYPE(NetJsValueQmlContainer) Q_DECLARE_METATYPE(NetQObjectQmlContainer) Q_DECLARE_METATYPE(NetVariantListQmlContainer) namespace { const int NetReferenceQmlContainerTypeId = qMetaTypeId<NetReferenceQmlContainer>(); const int NetJsValueQmlContainerTypeId = qMetaTypeId<NetJsValueQmlContainer>(); const int NetQObjectQmlContainerTypeId = qMetaTypeId<NetQObjectQmlContainer>(); const int NetVariantListQmlContainerTypeId = qMetaTypeId<NetVariantListQmlContainer>(); } NetVariant::NetVariant() = default; NetVariant::~NetVariant() { clearNetReference(); } NetVariantTypeEnum NetVariant::getVariantType() const { const int type = _variant.userType(); switch(type) { case QMetaType::UnknownType: return NetVariantTypeEnum_Invalid; case QMetaType::Nullptr: return NetVariantTypeEnum_Null; case QMetaType::Bool: return NetVariantTypeEnum_Bool; case QMetaType::QChar: return NetVariantTypeEnum_Char; case qMetaTypeId<qint32>(): return NetVariantTypeEnum_Int; case qMetaTypeId<quint32>(): return NetVariantTypeEnum_UInt; case qMetaTypeId<qint64>(): return NetVariantTypeEnum_Long; case qMetaTypeId<quint64>(): return NetVariantTypeEnum_ULong; case QMetaType::Float: return NetVariantTypeEnum_Float; case QMetaType::Double: return NetVariantTypeEnum_Double; case QMetaType::QString: return NetVariantTypeEnum_String; case QMetaType::QDateTime: return NetVariantTypeEnum_DateTime; case QMetaType::QSize: return NetVariantTypeEnum_Size; case QMetaType::QSizeF: return NetVariantTypeEnum_SizeF; case QMetaType::QRect: return NetVariantTypeEnum_Rect; case QMetaType::QRectF: return NetVariantTypeEnum_RectF; case QMetaType::QPoint: return NetVariantTypeEnum_Point; case QMetaType::QPointF: return NetVariantTypeEnum_PointF; case QMetaType::QVector2D: return NetVariantTypeEnum_Vector2D; case QMetaType::QVector3D: return NetVariantTypeEnum_Vector3D; case QMetaType::QVector4D: return NetVariantTypeEnum_Vector4D; case QMetaType::QQuaternion: return NetVariantTypeEnum_Quaternion; case QMetaType::QMatrix4x4: return NetVariantTypeEnum_Matrix4x4; case QMetaType::QColor: return NetVariantTypeEnum_Color; case QMetaType::QByteArray: return NetVariantTypeEnum_ByteArray; default: if(type == NetReferenceQmlContainerTypeId) { return NetVariantTypeEnum_Object; } else if(type == NetJsValueQmlContainerTypeId) { return NetVariantTypeEnum_JSValue; } else if(type == NetQObjectQmlContainerTypeId) { return NetVariantTypeEnum_QObject; } else if(type == NetVariantListQmlContainerTypeId) { return NetVariantTypeEnum_NetVariantList; } else { qWarning() << "Unknown type for NetVariant: " << _variant.typeName(); return NetVariantTypeEnum_Invalid; } } } void NetVariant::setNull() { clearNetReference(); _variant.setValue(nullptr); } void NetVariant::setNetReference(QSharedPointer<NetReference> netReference) { clearNetReference(); _variant.setValue(NetReferenceQmlContainer{ std::move(netReference) }); } QSharedPointer<NetReference> NetVariant::getNetReference() const { return getValue<NetReferenceQmlContainer>().netReference; } void NetVariant::setBool(bool value) { setValue(value); } bool NetVariant::getBool() const { return getValue<bool>(); } void NetVariant::setChar(QChar value) { setValue(value); } QChar NetVariant::getChar() const { // Try to convert the internal QString into a Char if(_variant.userType() == QMetaType::QString) { QString str = _variant.value<QString>(); if(str.length() == 1) { return str.at(0); } qWarning() << "Can't convert '" << str << "' to QChar"; return QChar::Null; } return getValue<QChar>(); } void NetVariant::setInt(qint32 value) { setValue(value); } qint32 NetVariant::getInt() const { return getValue<qint32>(); } void NetVariant::setUInt(quint32 value) { setValue(value); } quint32 NetVariant::getUInt() const { return getValue<quint32>(); } void NetVariant::setLong(qint64 value) { setValue(value); } qint64 NetVariant::getLong() const { return getValue<qint64>(); } void NetVariant::setULong(quint64 value) { setValue(value); } quint64 NetVariant::getULong() const { return getValue<quint64>(); } void NetVariant::setFloat(float value) { setValue(value); } float NetVariant::getFloat() const { return getValue<float>(); } void NetVariant::setDouble(double value) { setValue(value); } double NetVariant::getDouble() const { return getValue<double>(); } QSize NetVariant::getSize() const { return getValue<QSize>(); } void NetVariant::setSize(const QSize &value) { setValue(value); } QSizeF NetVariant::getSizeF() const { return getValue<QSizeF>(); } void NetVariant::setSizeF(const QSizeF &value) { setValue(value); } QRect NetVariant::getRect() const { return getValue<QRect>(); } void NetVariant::setRect(const QRect &value) { setValue(value); } QRectF NetVariant::getRectF() const { return getValue<QRectF>(); } void NetVariant::setRectF(const QRectF &value) { setValue(value); } QPoint NetVariant::getPoint() const { return getValue<QPoint>(); } void NetVariant::setPoint(const QPoint &value) { setValue(value); } QPointF NetVariant::getPointF() const { return getValue<QPointF>(); } void NetVariant::setPointF(const QPointF &value) { setValue(value); } QVector2D NetVariant::getVector2D() const { return getValue<QVector2D>(); } void NetVariant::setVector2D(const QVector2D &value) { setValue(value); } QVector3D NetVariant::getVector3D() const { return getValue<QVector3D>(); } void NetVariant::setVector3D(const QVector3D &value) { setValue(value); } QVector4D NetVariant::getVector4D() const { return getValue<QVector4D>(); } void NetVariant::setVector4D(const QVector4D &value) { setValue(value); } QQuaternion NetVariant::getQuaternion() const { return getValue<QQuaternion>(); } void NetVariant::setQuaternion(const QQuaternion &value) { setValue(value); } QMatrix4x4 NetVariant::getMatrix4x4() const { return getValue<QMatrix4x4>(); } void NetVariant::setMatrix4x4(const QMatrix4x4 &value) { setValue(value); } void NetVariant::setColor(const QColor& value) { setValue(value); } QColor NetVariant::getColor() const { return getValue<QColor>(); } void NetVariant::setString(const QString* value) { setValuePtr(value); } void NetVariant::setString(const QString& value) { setValue(value); } QString NetVariant::getString() const { return _variant.toString(); } void NetVariant::setBytes(QByteArray values) { setValue(values); } QByteArray NetVariant::getBytes() const { return _variant.toByteArray(); } void NetVariant::setDateTime(const QDateTime& value) { setValue(value); } QDateTime NetVariant::getDateTime() const { return getValue<QDateTime>(); } void NetVariant::setJsValue(QSharedPointer<NetJSValue> jsValue) { setValue(NetJsValueQmlContainer{ std::move(jsValue) }); } QSharedPointer<NetJSValue> NetVariant::getJsValue() const { return getValue<NetJsValueQmlContainer>().jsValue; } void NetVariant::setQObject(QSharedPointer<NetQObject> netQObject) { setValue(NetQObjectQmlContainer{ std::move(netQObject) }); } QSharedPointer<NetQObject> NetVariant::getQObject() const { return getValue<NetQObjectQmlContainer>().netQObject; } void NetVariant::setNetVariantList(QSharedPointer<NetVariantList> netVariantList) { setValue(NetVariantListQmlContainer{ std::move(netVariantList) }); } QSharedPointer<NetVariantList> NetVariant::getNetVariantList() const { return getValue<NetVariantListQmlContainer>().netVariantList; } void NetVariant::clear() { clearNetReference(); _variant.clear(); } QVariantList NetVariant::toQVariantList() const { NetVariantTypeEnum variantType = getVariantType(); if(variantType == NetVariantTypeEnum_NetVariantList) { QVariantList list; QSharedPointer<NetVariantList> netVariantList = getValue<NetVariantListQmlContainer>().netVariantList; for(int x = 0; x < netVariantList->count(); x++) { QSharedPointer<NetVariant> variant = netVariantList->get(x); list.append(variant->toQVariant()); } return list; } if(variantType == NetVariantTypeEnum_Object) { // This may be a .NET list type. // If it is, try to enumerate it. QSharedPointer<NetReference> netReference = getNetReference(); QSharedPointer<NetTypeArrayFacade> facade = netReference->getTypeInfo()->getArrayFacade(); if(facade == nullptr) { qWarning() << "The given .NET type" << netReference->getTypeInfo()->getClassName() << "can't be converted to a QVariantList"; return QVariantList(); } QVariantList list; uint count = facade->getLength(netReference); for(uint x = 0; x < count; x++) { QSharedPointer<NetVariant> item = facade->getIndexed(netReference, x); list.append(item->toQVariant()); } return list; } qWarning() << "Can't convert value" << _variant << "from" << _variant.typeName() << "to QVariantList"; return QVariantList(); } QSharedPointer<NetVariant> NetVariant::fromQJSValue(const QJSValue& qJsValue) { QSharedPointer<NetVariant> result; if(qJsValue.isNull() || qJsValue.isUndefined()) { // Nothing! } else if(qJsValue.isQObject()) { result = QSharedPointer<NetVariant>(new NetVariant()); QObject* qObject = qJsValue.toQObject(); NetValueInterface* netValue = qobject_cast<NetValueInterface*>(qObject); if(!netValue) { result->setQObject(QSharedPointer<NetQObject>(new NetQObject(qObject))); } else { result->setNetReference(netValue->getNetReference()); } } else if(qJsValue.isObject()) { result = QSharedPointer<NetVariant>(new NetVariant()); result->setJsValue(QSharedPointer<NetJSValue>(new NetJSValue(qJsValue))); } else { result = QSharedPointer<NetVariant>(new NetVariant()); QVariant variant = qJsValue.toVariant(); result->_variant = variant; } return result; } QJSValue NetVariant::toQJSValue() const { switch(getVariantType()) { case NetVariantTypeEnum_Object: { NetValue* netValue = NetValue::forInstance(getNetReference()); return sharedQmlEngine()->newQObject(netValue); } case NetVariantTypeEnum_JSValue: { return getJsValue()->getJsValue(); } default: { return sharedQmlEngine()->toScriptValue<QVariant>(toQVariant()); } } } void NetVariant::fromQVariant(const QVariant* variant, const QSharedPointer<NetVariant>& destination) { const int type = variant->userType(); switch(type) { case QMetaType::UnknownType: destination->clear(); break; case QMetaType::Bool: case QMetaType::QChar: case qMetaTypeId<qint32>(): case qMetaTypeId<quint32>(): case qMetaTypeId<qint64>(): case qMetaTypeId<quint64>(): case QMetaType::Float: case QMetaType::Double: case QMetaType::QString: case QMetaType::QByteArray: case QMetaType::QDateTime: case QMetaType::QSize: case QMetaType::QSizeF: case QMetaType::QRect: case QMetaType::QRectF: case QMetaType::QPoint: case QMetaType::QPointF: case QMetaType::QVector2D: case QMetaType::QVector3D: case QMetaType::QVector4D: case QMetaType::QQuaternion: case QMetaType::QMatrix4x4: case QMetaType::QColor: destination->setValueVariant(*variant); break; // Generally, we can convert from QUrl to QString. // QML internally uses a string for the url basic type, // but we can still get a QUrl if someone passes through // a QUrl property found on a native QQuickItem (i.e. QQuickImage::source). case QMetaType::QUrl: destination->setValueVariant(variant->value<QUrl>().toString()); break; case QMetaType::ULong: destination->setULong(variant->value<quint64>()); break; case QMetaType::Long: destination->setLong(variant->value<qint64>()); break; case QMetaType::QObjectStar: { QObject* value = variant->value<QObject*>(); if(value == nullptr) { destination->clear(); return; } NetValueInterface* netValue = qobject_cast<NetValueInterface*>(value); if(netValue) { destination->setNetReference(netValue->getNetReference()); } else { destination->setQObject(QSharedPointer<NetQObject>(new NetQObject(value))); } break; } case QMetaType::QVariantList: { QSharedPointer<NetVariantList> netVariantList = QSharedPointer<NetVariantList>(new NetVariantList()); QVariantList list = variant->value<QVariantList>(); QVariantList::iterator i; for (i = list.begin(); i != list.end(); ++i) { QVariant item = *i; netVariantList->add(NetVariant::fromQVariant(&item)); } destination->setNetVariantList(netVariantList); break; } default: if(type == qMetaTypeId<QJSValue>()) { // TODO: Either serialize this type to a string, to be deserialized in .NET, or // pass raw value to .NET to be dynamically invoked (using dynamic). // See qtdeclarative\src\plugins\qmltooling\qmldbg_debugger\qqmlenginedebugservice.cpp:184 // for serialization methods. QSharedPointer<NetJSValue> netJsValue(new NetJSValue(variant->value<QJSValue>())); destination->setJsValue(netJsValue); break; } QMetaType::TypeFlags flags = QMetaType::typeFlags(type); if(flags & QMetaType::PointerToQObject) { QObject* value = variant->value<QObject*>(); if(value == nullptr) { destination->clear(); break; } destination->setQObject(QSharedPointer<NetQObject>(new NetQObject(value))); break; } qDebug() << "Unsupported variant type: " << variant->type() << variant->typeName(); break; } } QSharedPointer<NetVariant> NetVariant::fromQVariant(const QVariant* variant) { QSharedPointer<NetVariant> result(new NetVariant()); fromQVariant(variant, result); return result; } QVariant NetVariant::toQVariant() const { QVariant variant; toQVariant(&variant); return variant; } void NetVariant::toQVariant(QVariant* variant) const { switch(getVariantType()) { case NetVariantTypeEnum_JSValue: *variant = getJsValue()->getJsValue().toVariant(); break; case NetVariantTypeEnum_Object: *variant = QVariant::fromValue<QObject*>(NetValue::forInstance(getNetReference())); break; case NetVariantTypeEnum_QObject: *variant = QVariant::fromValue<QObject*>(this->getQObject()->getQObject()); break; case NetVariantTypeEnum_NetVariantList: *variant = QVariant::fromValue(toQVariantList()); break; default: *variant = _variant; break; } } QString NetVariant::getDisplayValue() const { switch(getVariantType()) { case NetVariantTypeEnum_JSValue: return getJsValue()->getJsValue().toString(); case NetVariantTypeEnum_Object: return getNetReference()->displayName(); case NetVariantTypeEnum_QObject: return getQObject()->getQObject()->objectName(); default: return _variant.toString(); } } void NetVariant::clearNetReference() { if(_variant.canConvert<NetReferenceQmlContainer>()) { _variant.value<NetReferenceQmlContainer>().netReference.clear(); _variant.clear(); } else if(_variant.canConvert<NetJsValueQmlContainer>()) { _variant.value<NetJsValueQmlContainer>().jsValue.clear(); _variant.clear(); } else if(_variant.canConvert<NetQObjectQmlContainer>()) { _variant.value<NetQObjectQmlContainer>().netQObject.clear(); _variant.clear(); } } template<typename T> void NetVariant::setValue(const T& value) { clearNetReference(); _variant.setValue(value); } void NetVariant::setValueVariant(const QVariant& value) { Q_ASSERT(value.userType() != QMetaType::QObjectStar); Q_ASSERT(value.userType() != qMetaTypeId<QJSValue>()); Q_ASSERT(value.userType() < QMetaType::User); clearNetReference(); _variant = value; } template<typename T> void NetVariant::setValuePtr(const T* value) { if(value) { setValue(*value); } else { clear(); } } template<typename T> T NetVariant::getValue() const { if(!_variant.canConvert(qMetaTypeId<T>())) { qDebug() << "Can't convert value" << _variant << "from" << _variant.typeName() << "to" << QMetaType::typeName(qMetaTypeId<T>()); } return _variant.value<T>(); } extern "C" { struct Q_DECL_EXPORT DateTimeContainer { uchar isNull; int month; int day; int year; int hour; int minute; int second; int msec; int offsetSeconds; }; struct ColorContainer { uchar isNull; quint8 r; quint8 g; quint8 b; quint8 a; }; Q_DECL_EXPORT NetVariantContainer* net_variant_create() { NetVariantContainer* result = new NetVariantContainer(); result->variant = QSharedPointer<NetVariant>(new NetVariant()); return result; } Q_DECL_EXPORT void net_variant_destroy(NetVariantContainer* container) { delete container; } Q_DECL_EXPORT NetVariantTypeEnum net_variant_getVariantType(NetVariantContainer* container) { return container->variant->getVariantType(); } Q_DECL_EXPORT void net_variant_setNull(NetVariantContainer* container) { container->variant->setNull(); } Q_DECL_EXPORT void net_variant_setNetReference(NetVariantContainer* container, NetReferenceContainer* instanceContainer) { if(instanceContainer == nullptr) { container->variant->setNetReference(nullptr); } else { container->variant->setNetReference(instanceContainer->instance); } } Q_DECL_EXPORT NetReferenceContainer* net_variant_getNetReference(NetVariantContainer* container) { QSharedPointer<NetReference> instance = container->variant->getNetReference(); if(instance == nullptr) { return nullptr; } NetReferenceContainer* result = new NetReferenceContainer(); result->instance = instance; return result; } Q_DECL_EXPORT void net_variant_setBool(NetVariantContainer* container, uchar value) { container->variant->setBool(value == 1 ? true : false); } Q_DECL_EXPORT uchar net_variant_getBool(NetVariantContainer* container) { if(container->variant->getBool()) { return 1; } else { return 0; } } Q_DECL_EXPORT void net_variant_setChar(NetVariantContainer* container, quint16 value) { container->variant->setChar(value); } Q_DECL_EXPORT quint16 net_variant_getChar(NetVariantContainer* container) { return quint16(container->variant->getChar().unicode()); } Q_DECL_EXPORT void net_variant_setInt(NetVariantContainer* container, qint32 value) { container->variant->setInt(value); } Q_DECL_EXPORT qint32 net_variant_getInt(NetVariantContainer* container) { return container->variant->getInt(); } Q_DECL_EXPORT void net_variant_setUInt(NetVariantContainer* container, quint32 value) { container->variant->setUInt(value); } Q_DECL_EXPORT quint32 net_variant_getUInt(NetVariantContainer* container) { return container->variant->getUInt(); } Q_DECL_EXPORT void net_variant_setLong(NetVariantContainer* container, qint64 value) { container->variant->setLong(value); } Q_DECL_EXPORT qint64 net_variant_getLong(NetVariantContainer* container) { return container->variant->getLong(); } Q_DECL_EXPORT void net_variant_setULong(NetVariantContainer* container, quint64 value) { container->variant->setULong(value); } Q_DECL_EXPORT quint64 net_variant_getULong(NetVariantContainer* container) { return container->variant->getULong(); } Q_DECL_EXPORT void net_variant_setFloat(NetVariantContainer* container, float value) { container->variant->setFloat(value); } Q_DECL_EXPORT float net_variant_getFloat(NetVariantContainer* container) { return container->variant->getFloat(); } Q_DECL_EXPORT void net_variant_setDouble(NetVariantContainer* container, double value) { container->variant->setDouble(value); } Q_DECL_EXPORT double net_variant_getDouble(NetVariantContainer* container) { return container->variant->getDouble(); } Q_DECL_EXPORT void net_variant_setSize(NetVariantContainer* container, int w, int h) { container->variant->setSize(QSize(w, h)); } Q_DECL_EXPORT void net_variant_getSize(NetVariantContainer* container, int *w, int *h) { auto qtValue = container->variant->getSize(); *w = qtValue.width(); *h = qtValue.height(); } Q_DECL_EXPORT void net_variant_setSizeF(NetVariantContainer* container, float w, float h) { container->variant->setSizeF(QSizeF(w, h)); } Q_DECL_EXPORT void net_variant_getSizeF(NetVariantContainer* container, float *w, float *h) { auto qtValue = container->variant->getSizeF(); // .NET type is always single precision *w = static_cast<float>(qtValue.width()); *h = static_cast<float>(qtValue.height()); } Q_DECL_EXPORT void net_variant_setRect(NetVariantContainer* container, int x, int y, int w, int h) { container->variant->setRect(QRect(x, y, w, h)); } Q_DECL_EXPORT void net_variant_getRect(NetVariantContainer* container, int *x, int *y, int *w, int *h) { auto qtValue = container->variant->getRect(); *x = qtValue.x(); *y = qtValue.y(); *w = qtValue.width(); *h = qtValue.height(); } Q_DECL_EXPORT void net_variant_setRectF(NetVariantContainer* container, float x, float y, float w, float h) { container->variant->setRectF(QRectF(x, y, w, h)); } Q_DECL_EXPORT void net_variant_getRectF(NetVariantContainer* container, float *x, float *y, float *w, float *h) { auto qtValue = container->variant->getRectF(); // .NET type is always single precision *x = static_cast<float>(qtValue.x()); *y = static_cast<float>(qtValue.y()); *w = static_cast<float>(qtValue.width()); *h = static_cast<float>(qtValue.height()); } Q_DECL_EXPORT void net_variant_setPoint(NetVariantContainer* container, int x, int y) { container->variant->setPoint(QPoint(x, y)); } Q_DECL_EXPORT void net_variant_getPoint(NetVariantContainer* container, int *x, int *y) { auto qtValue = container->variant->getPoint(); *x = qtValue.x(); *y = qtValue.y(); } Q_DECL_EXPORT void net_variant_setPointF(NetVariantContainer* container, float x, float y) { container->variant->setPointF(QPointF(x, y)); } Q_DECL_EXPORT void net_variant_getPointF(NetVariantContainer* container, float *x, float *y) { auto qtValue = container->variant->getPointF(); // .NET type is always single precision *x = static_cast<float>(qtValue.x()); *y = static_cast<float>(qtValue.y()); } Q_DECL_EXPORT void net_variant_setVector2D(NetVariantContainer* container, float x, float y) { container->variant->setVector2D(QVector2D(x, y)); } Q_DECL_EXPORT void net_variant_getVector2D(NetVariantContainer* container, float *x, float *y) { auto qtValue = container->variant->getVector2D(); *x = qtValue.x(); *y = qtValue.y(); } Q_DECL_EXPORT void net_variant_setVector3D(NetVariantContainer* container, float x, float y, float z) { container->variant->setVector3D(QVector3D(x, y, z)); } Q_DECL_EXPORT void net_variant_getVector3D(NetVariantContainer* container, float *x, float *y, float *z) { auto qtValue = container->variant->getVector3D(); *x = qtValue.x(); *y = qtValue.y(); *z = qtValue.z(); } Q_DECL_EXPORT void net_variant_setVector4D(NetVariantContainer* container, float x, float y, float z, float w) { container->variant->setVector4D(QVector4D(x, y, z, w)); } Q_DECL_EXPORT void net_variant_getVector4D(NetVariantContainer* container, float *x, float *y, float *z, float *w) { auto qtValue = container->variant->getVector4D(); *x = qtValue.x(); *y = qtValue.y(); *z = qtValue.z(); *w = qtValue.w(); } Q_DECL_EXPORT void net_variant_setQuaternion(NetVariantContainer* container, float w, float x, float y, float z) { container->variant->setQuaternion(QQuaternion(w, x, y, z)); } Q_DECL_EXPORT void net_variant_getQuaternion(NetVariantContainer* container, float *w, float *x, float *y, float *z) { auto qtValue = container->variant->getQuaternion(); *w = qtValue.scalar(); *x = qtValue.x(); *y = qtValue.y(); *z = qtValue.z(); } Q_DECL_EXPORT void net_variant_setMatrix4x4(NetVariantContainer* container, float m11, float m12, float m13, float m14, float m21, float m22, float m23, float m24, float m31, float m32, float m33, float m34, float m41, float m42, float m43, float m44) { container->variant->setMatrix4x4(QMatrix4x4(m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44)); } Q_DECL_EXPORT void net_variant_getMatrix4x4(NetVariantContainer* container, float* m11, float* m12, float* m13, float* m14, float* m21, float* m22, float* m23, float* m24, float* m31, float* m32, float* m33, float* m34, float* m41, float* m42, float* m43, float* m44) { auto qtValue = container->variant->getMatrix4x4(); *m11 = qtValue(0, 0); *m12 = qtValue(0, 1); *m13 = qtValue(0, 2); *m14 = qtValue(0, 3); *m21 = qtValue(1, 0); *m22 = qtValue(1, 1); *m23 = qtValue(1, 2); *m24 = qtValue(1, 3); *m31 = qtValue(2, 0); *m32 = qtValue(2, 1); *m33 = qtValue(2, 2); *m34 = qtValue(2, 3); *m41 = qtValue(3, 0); *m42 = qtValue(3, 1); *m43 = qtValue(3, 2); *m44 = qtValue(3, 3); } Q_DECL_EXPORT void net_variant_setColor(NetVariantContainer* container, const ColorContainer* value) { if(value == nullptr || value->isNull) { container->variant->setColor(QColor()); } else { container->variant->setColor(QColor(value->r, value->g, value->b, value->a)); } } Q_DECL_EXPORT void net_variant_getColor(NetVariantContainer* container, ColorContainer* value) { const QColor& c = container->variant->getColor(); if(!c.isValid()) { value->isNull = 1; return; } value->isNull = 0; value->r = c.red(); value->g = c.green(); value->b = c.blue(); value->a = c.alpha(); return; } Q_DECL_EXPORT void net_variant_setString(NetVariantContainer* container, QChar* value) { if(value == nullptr) { container->variant->setString(nullptr); } else { container->variant->setString(QString(value)); } } Q_DECL_EXPORT QmlNetStringContainer* net_variant_getString(NetVariantContainer* container) { const QString& string = container->variant->getString(); if(string.isNull()) { return nullptr; } return createString(string); } Q_DECL_EXPORT void net_variant_setBytes(NetVariantContainer* container, const char* value, int count) { if(value == nullptr) { container->variant->setBytes(nullptr); } else { container->variant->setBytes(QByteArray::fromRawData(value, count)); } } Q_DECL_EXPORT const char* net_variant_getBytes(NetVariantContainer* container, int &count) { const QByteArray byteArray = container->variant->getBytes(); if(byteArray.isNull()) { count = 0; return nullptr; } else { count = byteArray.count();; return byteArray.constData(); } } Q_DECL_EXPORT void net_variant_setDateTime(NetVariantContainer* container, const DateTimeContainer* value) { if(value == nullptr || value->isNull) { container->variant->setDateTime(QDateTime()); } else { container->variant->setDateTime(QDateTime(QDate(value->year, value->month, value->day), QTime(value->hour, value->minute, value->second, value->msec), Qt::OffsetFromUTC, value->offsetSeconds)); } } Q_DECL_EXPORT void net_variant_getDateTime(NetVariantContainer* container, DateTimeContainer* value) { const QDateTime& dt = container->variant->getDateTime(); if(dt.isNull()) { value->isNull = 1; return; } if(!dt.isValid()) { qWarning() << "QDateTime is invalid"; value->isNull = 1; return; } value->isNull = 0; const QDate& date = dt.date(); const QTime& time = dt.time(); value->year = date.year(); value->month = date.month(); value->day = date.day(); value->hour = time.hour(); value->minute = time.minute(); value->second = time.second(); value->msec = time.msec(); value->offsetSeconds = dt.offsetFromUtc(); } Q_DECL_EXPORT void net_variant_setJsValue(NetVariantContainer* container, NetJSValueContainer* jsValueContainer) { if(jsValueContainer == nullptr) { container->variant->setJsValue(nullptr); } else { container->variant->setJsValue(jsValueContainer->jsValue); } } Q_DECL_EXPORT NetJSValueContainer* net_variant_getJsValue(NetVariantContainer* container) { const QSharedPointer<NetJSValue>& instance = container->variant->getJsValue(); if(instance == nullptr) { return nullptr; } NetJSValueContainer* result = new NetJSValueContainer(); result->jsValue = instance; return result; } Q_DECL_EXPORT void net_variant_setQObject(NetVariantContainer* container, NetQObjectContainer* qObjectContainer) { if(qObjectContainer == nullptr) { container->variant->setQObject(nullptr); } else { container->variant->setQObject(qObjectContainer->qObject); } } Q_DECL_EXPORT NetQObjectContainer* net_variant_getQObject(NetVariantContainer* container) { const QSharedPointer<NetQObject>& instance = container->variant->getQObject(); if(instance == nullptr) { return nullptr; } NetQObjectContainer* result = new NetQObjectContainer(); result->qObject = instance; return result; } Q_DECL_EXPORT void net_variant_setNetVariantList(NetVariantContainer* container, NetVariantListContainer* netVariantListContainer) { if(netVariantListContainer == nullptr) { container->variant->setNetVariantList(nullptr); } else { container->variant->setNetVariantList(netVariantListContainer->list); } } Q_DECL_EXPORT NetVariantListContainer* net_variant_getNetVariantList(NetVariantContainer* container) { const QSharedPointer<NetVariantList>& netVariantList = container->variant->getNetVariantList(); if(netVariantList == nullptr) { return nullptr; } return new NetVariantListContainer { netVariantList }; } Q_DECL_EXPORT void net_variant_clear(NetVariantContainer* container) { container->variant->clear(); } }
32,104
10,715
/* Copyright (c) 2010 David Anderson. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * 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 the example 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 David Anderson ''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 David Anderson 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. */ // zero.cc is a trivial application which enables one to take // an arbitrary file (normally an object file used for testing DWARF) // and replace areas of the file with binary zeros. // // The point of the replacement is to remove irrelevant and possibly // proprietary instructions and data from the object files, leaving // the Elf headers and the file size unchanged. // // This app is used once, typically before committing a new test object, // to clean out the irrelevant .text and .data section contents. // This app assumes some other application was used to determine // what areas to zero out (the other app would usually be an object header // dumper like readelf -S). // Usage: // zero -s <startoffset> -l <length> ... filename #include <fcntl.h> // For open #include <iostream> #include <string> #include <string> #include <vector> #include <errno.h> #include <stdlib.h> // For exit() #include <unistd.h> // For lseek using std::string; using std::cout; using std::endl; using std::vector; int fd = -1; typedef unsigned long counter; #define ZEROSIZE 128000 char zerobuf[ZEROSIZE]; struct range { range(unsigned long o, unsigned long l) {offset = o;len = l; }; range() {offset = 0; len = 0;}; ~range() {}; counter offset; counter len; }; string filepath; vector<range> ranges; static void usage() { cout << "Usage: " << " zero -s <offset> -l <len> ... filepath " <<endl; cout << " where ... means repeat the -s <offset> -l <len> quads as often as needed." <<endl; cout << " Offset/length values may be decimal or with 0x prefix for hex" << endl; cout << " Example: ./zero -s 0x1 -l 2 testdata" << endl; } counter getval(const string s) { char *ep = 0; errno = 0; unsigned long long v = strtoull(s.c_str(),&ep,0); if (errno != 0) { cout << "The offset " << s << " is outside the representable value set. " <<endl; exit(1); } return v; } /* Args are: appname -s start -l len // the -s -l repeat as many times as wanted filepath */ static void validate_args(int argc, char **argv) { int nextarg = 1; while( nextarg < (argc-1)) { string a = argv[nextarg]; if( a != "-s") { cout << "Expected -s, got " << a <<endl; usage(); exit(1); } ++nextarg; if (nextarg >= (argc-1)) { cout << "Expected start offset, got no argument " <<endl; usage(); exit(1); } counter off = getval(argv[nextarg]); ++nextarg; if (nextarg >= (argc-1)) { cout << "Expected -l, got no argument" << endl; usage(); exit(1); } string l = argv[nextarg]; if( l != "-l") { cout << "Expected -l, got " << l <<endl; usage(); exit(1); } ++nextarg; if (nextarg >= (argc-1)) { cout << "Too few arguments." << endl; usage(); exit(1); } counter len = getval(argv[nextarg]); range r(off,len); ranges.push_back(r); ++nextarg; } if (nextarg != (argc-1)) { usage(); cout << "Expected file path , got no argument " <<endl; exit(1); } filepath = argv[nextarg]; }; static void write_some_zeros(counter o, counter len) { errno = 0; off_t res = lseek(fd,o,SEEK_SET); if(res == (off_t)-1) { cout << "lseek failed on " << filepath << " to offset " << o << endl; exit(1); } size_t remaining = len; cout << "Zeroing " << filepath << " offset " << o << " length " << len << endl; while( remaining) { size_t writesize = ZEROSIZE; if (writesize > remaining) { writesize = remaining; } errno = 0; ssize_t w = write(fd,zerobuf,writesize); if ( w < 0 ) { cout << "Write failed on " << filepath << " of " << writesize << " bytes, errno is " << errno << endl; exit(1); } if (w == 0) { cout << "Write produced no progress on " << filepath << " of " << writesize << " bytes, errno is " << errno << endl; exit(1); } remaining -= w; } } static void write_all_zeros() { for(unsigned i = 0; i < ranges.size(); ++i) { counter o = ranges[i].offset; counter l = ranges[i].len; if(l > 0) { write_some_zeros(o,l); } } }; int main(int argc, char **argv) { validate_args(argc,argv); errno = 0; fd = open(filepath.c_str(), O_RDWR); if(fd < 0) { cout << "Open failed on " << filepath << " errno is " << errno<< endl; exit(1); } write_all_zeros(); close(fd); return 0; }
6,420
2,107
// // Polynomial.cpp // cpp_Midterm2 // // Created by Nguyen Le Khanh Ngoc on 11/11/2020. // Copyright © 2020 Nguyen Le Khanh Ngoc. All rights reserved. // #include "Polynomial.h" #include <string> //string type #include <string.h> #include <vector> //vector #include <ctype.h> //isalpha #include <iostream> #include <algorithm> #include <cctype> using namespace std; //Constructor Polynomial::Polynomial (string num){ //Polynomial cout<<"p"<<num<<": "; string f; cin>>f; parsePoly(f); } //Constructor Polynomial::Polynomial(vector<Term> terms){ t.reserve(terms.size()); t.insert(t.end(), terms.begin(), terms.end()); } //Parse and set string to each term void Polynomial::parsePoly(const string str){ size_t position = 0; //point each char in string string temp, term; for (int i = 0; i < str.size(); i++){ //reach + or - => save to temp data on the left if (str[i] != '+' && str[i] != '-'){ temp += str[i]; } else{ temp += ";"; temp += str[i]; } } //add ; after an element temp += ";"; //error handling e.g. ;-4xy;+2 if (temp[0] == ';'){ temp.erase(0,1); } while ((position = temp.find(";")) != string::npos) { //reach ; => push back the left term && erase it term = temp.substr(0, position); t.push_back(Term(term)); temp.erase(0, position + 1); } } Polynomial Polynomial::operator* (const Polynomial& p){ vector<Term> new_terms; for (int i = 0; i < t.size(); i++){ for (int j = 0; j < p.t.size(); j++){ new_terms.push_back(t[i] * p.t[j]); } } return Polynomial(new_terms); } ostream& operator<< (ostream& output, const Polynomial& p){ cout<<"p1 * p2 = p3: "; for (int i = 0; i < p.t.size(); ++i){ for (int j = 0; j < p.t[i].getElement().size(); ++j){ //first element always contains coeff if (j == 0){ //if 1x => x if(p.t[i].getElement()[j+1].getCoeff() == 1){ //e.g. test: p1:-3x^2-1 result = 3x^2+3x^3y+1+xy // p2:-1-xy instead= 3x^2+3x^3y+1+1xy if(p.t[i].getElement()[j].getCoeff() == 1){ output<<""; } else if (p.t[i].getElement()[j].getCoeff() == -1){ output<<"-"; } else { output<<p.t[i].getElement()[j].getCoeff(); } } else { output<<p.t[i].getElement()[j].getCoeff(); } } else { //if 1x^1 => print only 1x else print e.g. x^2 if (p.t[i].getElement()[j].getExp() == 1){ output<<p.t[i].getElement()[j].getVar(); } else { output<<p.t[i].getElement()[j].getVar()<<"^"<< p.t[i].getElement()[j].getExp(); } } } if (i != p.t.size() -1){ //error handling: trailing plus otherwise -4x^2y+3+ //error handling: no add + before negative coeff e.g. -36x^2 instead +-36x^2 if (p.t[i+1].getElement()[0].getCoeff() < 0){ continue; } cout << "+"; } } return output << endl; } //evaluate void Polynomial::evaluate(){ vector<char> store_var; vector<double> store_value; double temp; long double sum{0.0}; for (int i = 0; i < t.size(); ++i){ for (int j = 0; j < t[i].getElement().size(); ++j){ if (isalpha (t[i].getElement()[j].getVar())){ //check if variable already print or not if (find(store_var.begin(), store_var.end(), t[i].getElement()[j].getVar()) != store_var.end()) { continue; } cout<<t[i].getElement()[j].getVar()<<": "; cin>>temp; store_value.push_back(temp); store_var.push_back(t[i].getElement()[j].getVar()); //sum of terms } } } for (int i = 0; i < t.size(); ++i){ sum += t[i].evaluateTerm(store_var, store_value); } cout<<"Result: "<<sum<<endl; }
4,385
1,499
#include "../common/d2.hpp" #include "../learn/wm3.hpp" #include <string> #include <sstream> #include <time.h> int main(int argc, char** argv) { using namespace d2; server::Init(argc, argv); size_t len = 864, size=400; Block<Elem<def::Histogram, 0> > data (size, len); std::string filename("data/orl/orl.d2s"); data.read(filename, size); size_t k = 40; Block<Elem<def::Histogram, 0> > wm3 (k, 864); for (size_t i=0; i<k; ++i) { std::string uniform_sample = "0 864 "; srand (i); for (size_t i=1; i<=864; ++i) { uniform_sample += std::to_string(rand()%100+1) + " "; } std::istringstream istr (uniform_sample); wm3.append(istr); } WM3_SA(wm3, data, 1000, .05, 2., 20); wm3.write("data/orl/mixture_" + std::to_string(k) + "n.txt"); std::ofstream f; f.open("data/orl/real.d2s"); for (size_t i=0; i<size; ++i) operator<<(f, data[i]); f.close(); server::Finalize(); return 0; }
958
454
#include <cassert> #include <sodium/randombytes.h> #include <libff/common/utils.hpp> namespace libiop { template<typename T> std::vector<T> all_subset_sums(const std::vector<T> &basis, const T& shift) { const size_t m = basis.size(); std::vector<T> result; /* as we are I/O-bound here, reserve + emplace_back is ~2x faster then pre-initializing with zero and then overwriting (as per benchmark_vector_op.cpp) */ result.reserve(1ull<<m); result.emplace_back(shift); for (size_t i = 0; i < m; ++i) { const size_t l = (1ull<<i); for (size_t j = 0; j < l; ++j) { result.emplace_back(result[j] + basis[i]); } } return result; } template<typename FieldT> std::vector<FieldT> batch_inverse(const std::vector<FieldT> &vec, const bool has_zeroes) { return batch_inverse_and_mul(vec, FieldT::one(), has_zeroes); } template<typename FieldT> std::vector<FieldT> batch_inverse_and_mul_internal(const std::vector<FieldT> &vec, const FieldT &k) { /** Montgomery batch inversion trick. * This assumes that all elements of the input are non-zero. * It also multiplies every element by k, which can be done with one multiplication. */ std::vector<FieldT> R; R.reserve(vec.size()); FieldT c = vec[0]; R.emplace_back(c); // Set R[i] to be the product of all vec[j], where j <= 0 <= i for (size_t i = 1; i < vec.size(); ++i) { c *= vec[i]; R.emplace_back(c); } FieldT c_inv = c.inverse() * k; for (size_t i = vec.size()-1; i > 0; --i) { R[i] = R[i-1] * c_inv; c_inv *= vec[i]; } R[0] = c_inv; return R; } template<typename FieldT> std::vector<FieldT> batch_inverse_and_mul(const std::vector<FieldT> &vec, const FieldT &k, const bool has_zeroes) { /** Montgomery batch inversion trick. * This wraps the internal batch inverse and mul to handle 0's. * If we need more efficiency, we can make an entirely separate codepath for the case with zeroes, * and get rid of the loop that searches for zeroes. * We omit this optimization, as has_zeroes=false in the verifiers code path. */ if (has_zeroes) { std::vector<FieldT> vec_copy(vec); std::vector<size_t> zero_locations; FieldT zero = FieldT::zero(); for (std::size_t i = 0; i < vec.size(); i++) { if (vec_copy[i] == zero) { zero_locations.emplace_back(i); vec_copy[i] = FieldT::one(); } } std::vector<FieldT> result = batch_inverse_and_mul_internal(vec_copy, k); for (std::size_t i = 0; i < zero_locations.size(); i++) { result[zero_locations[i]] = zero; } return result; } else { return batch_inverse_and_mul_internal(vec, k); } } template<typename FieldT> void mut_batch_inverse(std::vector<FieldT> &vec) { /** Montgomery batch inversion trick, which mutates vec. * This assumes that all elements of the input are non-zero. * * The primary advantage of mut_batch_inverse is that instead of * heap allocating a vector of size vec.size() internally, an array * can be stack allocated. This matters more as the size of vec grows. */ /* Not using std::vector in order to make this stack allocated. */ FieldT vec_copy[vec.size()]; FieldT c = vec[0]; vec_copy[0] = c; // Set R[i] to be the product of all vec[j], where j <= 0 <= i for (size_t i = 1; i < vec.size(); ++i) { vec_copy[i] = vec[i]; c *= vec[i]; vec[i] = c; } FieldT c_inv = c.inverse(); for (size_t i = vec.size()-1; i > 0; --i) { vec[i] = vec[i-1] * c_inv; c_inv *= vec_copy[i]; } vec[0] = c_inv; return; } template<typename T> void bitreverse_vector(std::vector<T> &a) { const size_t n = a.size(); const size_t logn = libff::log2(n); assert(n == 1ull<<logn); for (size_t k = 0; k < n; ++k) { const size_t rk = libff::bitreverse(k, logn); if (k < rk) { std::swap(a[k], a[rk]); } } } template<typename T> std::vector<T> random_vector(const std::size_t count) { std::vector<T> result(count); randombytes_buf(result.data(), count * sizeof(T)); return result; } template<typename FieldT> std::vector<FieldT> random_FieldT_vector(const std::size_t count) { std::vector<FieldT> result; result.reserve(count); for (std::size_t i = 0; i < count; i++) { result.emplace_back(FieldT::random_element()); } return result; } } // namespace libiop
4,730
1,711
#include "../.././Core/Container/Buffer/BfAcc2Iter.hh"
57
26
#pragma once #include <input/Input.hh> #include <input/common/iCade.hh> struct ICadeHelper { UIView *mainView, *dummyInputView; uint active, cycleResponder; void init(UIView *mainView) { if(!dummyInputView) { logMsg("init iCade helper"); dummyInputView = [[UIView alloc] initWithFrame:CGRectZero]; var_selfs(mainView); if(active) { [mainView becomeFirstResponder]; } } } void setActive(uint active) { var_selfs(active); logMsg("set iCade active %d", active); if(!mainView) return; if(active) { [mainView becomeFirstResponder]; } else { [mainView resignFirstResponder]; } } uint isActive() { return active; } void didEnterBackground() { if(active) [mainView resignFirstResponder]; } void didBecomeActive() { if(active) [mainView becomeFirstResponder]; } void insertText(NSString *text) { using namespace Input; //logMsg("got text %s", [text cStringUsingEncoding: NSUTF8StringEncoding]); char c = [text characterAtIndex:0]; Input::processICadeKey(c, PUSHED, *devList.first()); // iCade device is always added first on app init if (++cycleResponder > 20) { // necessary to clear a buffer that accumulates internally cycleResponder = 0; [mainView resignFirstResponder]; [mainView becomeFirstResponder]; } } };
1,329
540
// // JsonDocument.cpp // JSON // // Created by Iulian on 13.03.2013. // #include "JsonDocument.hpp" #define SHOW_LIST( list ) for (auto iteratorBeing=list.begin(); iteratorBeing != list.end(); iteratorBeing++) {\ std::cout<<(*iteratorBeing)<<std::endl;} #define SHOW_LIST_POINT( list ) for (auto iteratorBeing=list->begin(); iteratorBeing != list->end(); iteratorBeing++) {\ std::cout<<(*iteratorBeing)<<std::endl;} enum class TokenNext{ None, Start, End, }; JsonDocument::JsonDocument():lJsonRootObject(nullptr){ } JsonDocument::~JsonDocument(){ if (lJsonRootObject != nullptr) { delete lJsonRootObject; lJsonRootObject=nullptr; } } JsonDocument::JsonDocument(JsonDocument & ldoc){ lJsonRootObject=ldoc.lJsonRootObject; ldoc.lJsonRootObject=nullptr; } JsonDocument::JsonDocument(JsonDocument && ldoc){ lJsonRootObject=ldoc.lJsonRootObject; ldoc.lJsonRootObject=nullptr; } JsonObject * JsonDocument::getNodeRoot(){ if (lJsonRootObject == nullptr) { lJsonRootObject=new JsonObject(); } return lJsonRootObject; } JsonObject * JsonDocument::addObject(JsonObject * lObject,std::string &lProperty){ JsonObject *lReturn; lReturn=new JsonObject(); std::string s("\""+lProperty+"\""); lObject->addProperty(s, lReturn); return lReturn; } JsonArray * JsonDocument::addArray(JsonObject * lObject,std::string &lProperty){ JsonArray *lReturn; lReturn=new JsonArray(); std::string s("\""+lProperty+"\""); lObject->addProperty(s, lReturn); return lReturn; } void JsonDocument::addNumber(JsonObject * lObject,std::string &lProperty,double lValue){ std::string s("\""+lProperty+"\""); lObject->addProperty(s, new JsonNumber(lValue)); } void JsonDocument::addString(JsonObject * lObject,std::string &lProperty,std::string &lValue){ std::string s("\""+lProperty+"\""); lObject->addProperty(lProperty, new JsonString(s)); } void JsonDocument::addBoolean(JsonObject * lObject,std::string &lProperty,bool lValue){ std::string s("\""+lProperty+"\""); lObject->addProperty(s, new JsonBoolean(lValue)); } void JsonDocument::addNull(JsonObject * lObject,std::string &lProperty){ std::string s("\""+lProperty+"\""); lObject->addProperty(s, new JsonNull()); } JsonObject * JsonDocument::addObject(JsonArray * lArray){ JsonObject *lReturn; lReturn=new JsonObject(); lArray->additem(lReturn); return lReturn; } JsonArray * JsonDocument::addArray(JsonArray * lArray){ JsonArray *lReturn; lReturn=new JsonArray(); lArray->additem(lReturn); return lReturn; } void JsonDocument::addNumber(JsonArray * lArray,double lValue){ lArray->additem(new JsonNumber(lValue)); } void JsonDocument::addString(JsonArray * lArray,std::string &lValue){ std::string s("\""+lValue+"\""); lArray->additem(new JsonString(s)); } void JsonDocument::addBoolean(JsonArray * lArray,bool lValue){ lArray->additem(new JsonBoolean(lValue)); } void JsonDocument::addNull(JsonArray * lArray){ lArray->additem(new JsonNull()); } std::vector<char> JsonDocument::getVectorJson(JsonDocumentFormat lFormat){ std::vector<char> lReturn; switch (lFormat) { case JsonDocumentFormat::Inndenter:{ }break; case JsonDocumentFormat::Compact:{ }break; default: break; } return lReturn; } void JsonDocument::parseJson(const char* iBegin , const char* iEnd){ // BEGIN PARSS TOKEN const char *iSearch=iBegin; std::list<std::string_view> listToken; while (iSearch < iEnd) { if((*iSearch) == ':' || (*iSearch) == '{' || (*iSearch) == '}' || (*iSearch) == '[' || (*iSearch) == ']' || (*iSearch) == ','){ listToken.push_back(std::string_view(iSearch,1)); iSearch++; continue; }else if ((*iSearch) == '"'){ const char *iStart=iSearch; iSearch++; while (iSearch < iEnd) { if (std::strncmp(iSearch, "\\\"", 2) == 0){ iSearch+=2; continue; }else if((*iSearch) == '"'){ listToken.push_back(std::string_view(iStart,(iSearch-iStart)+1)); iSearch++; break; } iSearch++; } continue; }else if ((std::strncmp(iSearch, "null", 4) == 0) || (std::strncmp(iSearch, "true", 4) == 0)){ listToken.push_back(std::string_view(iSearch,4)); iSearch+=4; continue; }else if ( std::strncmp(iSearch, "false", 5) == 0){ listToken.push_back(std::string_view(iSearch,5)); iSearch+=5; continue; }else if (std::isdigit(*iSearch)){ const char *iStart=iSearch; int pointSize=0; while (iSearch < iEnd && ((std::isdigit(*iSearch)) || (*iSearch == '.' && ++pointSize)) ) { if (pointSize > 1) { throw std::string("Error Token Multi Point: File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__)); } iSearch++; } listToken.push_back(std::string_view(iStart,(iSearch-iStart))); continue; } iSearch++; } // END PARSS TOKEN // BEGIN SHOW PARSS TOKEN #ifdef SHOW_TOKEN_TERMINAL SHOW_LIST(listToken) #endif // END SHOW PARSS TOKEN // BEGIN CREATE THREE OBJECT if (listToken.size() > 1 && listToken.front() == "{" && listToken.back() == "}" ) { listToken.pop_back(); listToken.pop_front(); lJsonRootObject=new JsonObject(); parseObject(lJsonRootObject,&listToken); }else{ throw std::string("Error root "); } // END CREATE THREE OBJECT } void JsonDocument::parseObject(JsonObject *lObject,std::list<std::string_view> *listStringView){ TokenNext lNextItem=TokenNext::None; for (auto iBegin=listStringView->begin(); iBegin != listStringView->end(); iBegin++) { auto iSearch=&(*iBegin); if((*iSearch).length() > 1 && (*iSearch).back() == '"' && (*iSearch).front() == '"'){ iBegin++; if ( iBegin != listStringView->end()) { if ((*iBegin) == ":") { iBegin++; if(iBegin != listStringView->end()){ if ((*iBegin) == "{"){ std::list<std::string_view> sObjectList; int tNumber=1; for ( iBegin++; iBegin != listStringView->end(); iBegin++) { if ((*iBegin) == "{") { tNumber++; }else if ((*iBegin) == "}"){ tNumber--; if (tNumber == 0) { break; } } sObjectList.push_back(*iBegin); } if (tNumber == 0 ) { std::string s(*iSearch); JsonObject *tObject= new JsonObject(); lObject->addProperty(s, tObject); parseObject(tObject,&sObjectList); lNextItem=TokenNext::End; }else{ throw std::string("Error Token {}: File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__)); } }else if ((*iBegin) == "["){ std::list<std::string_view> sArrayList; int tNumber=1; for ( iBegin++; iBegin != listStringView->end(); iBegin++) { if ((*iBegin) == "[") { tNumber++; }else if ((*iBegin) == "]"){ tNumber--; if (tNumber == 0) { break; } } sArrayList.push_back(*iBegin); } if (tNumber == 0 ) { std::string s(*iSearch); JsonArray *tArray= new JsonArray(); lObject->addProperty(s, tArray); parseArray(tArray,&sArrayList); lNextItem=TokenNext::End; }else{ throw std::string("Error Token []: File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__)); } }else if ((*iBegin).length() > 1 && (*iBegin).front() == '"' && (*iBegin).back() == '"'){ std::string s(*iSearch); std::string v(*iBegin); lObject->addProperty(s, new JsonString(v)); lNextItem=TokenNext::End; }else if ((*iBegin) == "null"){ std::string s(*iSearch); lObject->addProperty(s, new JsonNull()); lNextItem=TokenNext::End; }else if((*iBegin) == "true" ){ std::string s(*iSearch); lObject->addProperty(s, new JsonBoolean(true)); lNextItem=TokenNext::End; }else if ((*iBegin) == "false"){ std::string s(*iSearch); lObject->addProperty(s, new JsonBoolean(false)); lNextItem=TokenNext::End; }else if ((*iBegin).length() > 0 && std::isdigit((*iBegin).front()) ){ std::string s(*iSearch); double d=std::atof(std::string(*iBegin).data()); lObject->addProperty(s, new JsonNumber(d)); lNextItem=TokenNext::End; }else if ((*iBegin) == ",") { throw std::string("Error Token (,): File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__)); } auto iteratorNextItem=iBegin; iteratorNextItem++; if (TokenNext::End == lNextItem && iteratorNextItem != listStringView->end() && (*iteratorNextItem) == ",") { iBegin=iteratorNextItem; lNextItem=TokenNext::Start; } }else{ throw std::string("Error Token : File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__)); } }else{ throw std::string("Error Token : File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__)); } }else{ throw std::string("Error Token : File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__)); } }else{ throw std::string("Error Token ("+std::string(*iSearch)+"): File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__)); } } if (lNextItem == TokenNext::Start) { throw std::string("Error Token (,): File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__)); } } void JsonDocument::parseArray(JsonArray *lArray,std::list<std::string_view> *listStringView){ TokenNext lNextItem=TokenNext::None; for (auto iBegin=listStringView->begin(); iBegin != listStringView->end(); iBegin++) { if ((*iBegin) == "{") { std::list<std::string_view> sObjectList; int tNumber=1; for ( iBegin++; iBegin != listStringView->end(); iBegin++) { if ((*iBegin) == "{") { tNumber++; }else if ((*iBegin) == "}"){ tNumber--; if (tNumber == 0) { break; } } sObjectList.push_back(*iBegin); } if (tNumber == 0) { JsonObject *tObject= new JsonObject(); lArray->additem(tObject); parseObject(tObject,&sObjectList); lNextItem=TokenNext::End; }else{ throw std::string("Error Token {}: File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__)); } }else if((*iBegin) == "["){ std::list<std::string_view> sArrayList; int tNumber=1; for ( iBegin++; iBegin != listStringView->end(); iBegin++) { if ((*iBegin) == "[") { tNumber++; }else if ((*iBegin) == "]"){ tNumber--; if (tNumber == 0) { break; } } sArrayList.push_back(*iBegin); } if (tNumber == 0) { JsonArray *tArray= new JsonArray(); lArray->additem( tArray); parseArray(tArray,&sArrayList); lNextItem=TokenNext::End; }else{ throw std::string("Error Token []: File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__)); } }else if ((*iBegin).length() > 1 && (*iBegin).front() == '"' && (*iBegin).back() == '"'){ std::string s(*iBegin); lArray->additem(new JsonString(s)); lNextItem=TokenNext::End; }else if (std::isdigit((*iBegin).front())){ double d=std::atof(std::string(*iBegin).data()); lArray->additem(new JsonNumber(d)); lNextItem=TokenNext::End; }else if ((*iBegin) == "true"){ lArray->additem(new JsonBoolean(true)); lNextItem=TokenNext::End; }else if ((*iBegin) == "false"){ lArray->additem(new JsonBoolean(false)); lNextItem=TokenNext::End; }else if ((*iBegin) == "null"){ lArray->additem(new JsonNull()); lNextItem=TokenNext::End; }else if ((*iBegin) == ","){ throw std::string("Error Token , : File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__)); } auto iteratorNextItem=iBegin; iteratorNextItem++; if (TokenNext::End == lNextItem && iteratorNextItem != listStringView->end() && (*iteratorNextItem) == ",") { iBegin=iteratorNextItem; lNextItem=TokenNext::Start; } } if (lNextItem == TokenNext::Start) { throw std::string("Error Token (,): File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__)); } } JsonDocument JsonDocument::fromVecotr(std::vector<char> & lArray){ JsonDocument lReturnDoc; if(lArray.empty() == false){ const char *iBegine=lArray.data(); const char *iEnd=iBegine+lArray.size(); lReturnDoc.parseJson(iBegine, iEnd); } return lReturnDoc; } // BEGIN OPERATOR << JsonStream & operator <<(JsonStream & lout, JsonDocument & lin){ if (lin.lJsonRootObject) { lout<<(*lin.lJsonRootObject); } return lout; } // END OPERATOR <<
15,878
4,538
#include "Client.h" #include <string> #include <ostream> using namespace std; Client::Client(string id, string nom, string prenom, int nbReservations){ _id = id; _nom = nom; _prenom = prenom; _nbReservations = nbReservations; } string Client::getId() const{ return _id; } string Client::getNom() const{ return _nom; } string Client::getPrenom() const{ return _prenom; } int Client::getNbReservations()const{ return _nbReservations; } void Client::setId(string id) { _id = id; } void Client::setNom(string nom) { _nom = nom; } void Client::Client::setPrenom(string prenom) { _prenom = prenom; } void Client::Client::setNbReservations(int nbReservations) { _nbReservations = nbReservations; } ostream& operator << (ostream& os, const Client& client){ os << "ID: " << client._id << endl; os << "Nom: " << client._nom << endl; os << "Prenom: " << client._prenom << endl; os << "Nombre de reservations: " << client._nbReservations << endl; os << "_______________" << endl; return os; }
1,063
396
/*///////////////////////////////////////////////////////////////////////////////// /// An /// ___ ____ ___ _____ ___ ____ /// / _ \ / ___|_ _|_ _/ _ \| _ \ /// | | | | | _ | | | || | | | |_) | /// | |_| | |_| || | | || |_| | _ < /// \___/ \____|___| |_| \___/|_| \_\ /// File /// /// Copyright (c) 2008-2011 Ismail TARIM <ismail@royalspor.com> and the Ogitor Team // /// The 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. ////////////////////////////////////////////////////////////////////////////////*/ #include <QtGui/QMenu> #include <QtGui/QMessageBox> #include <QtGui/QFileDialog> #include <QtGui/QPainter> #include <QtGui/QColorDialog> #include <QtCore/QEvent> #include <QtCore/QDirIterator> #include <QtGui/QDragEnterEvent> #include <QtCore/QUrl> #include "settingsdialog.hxx" #include "OgitorsRoot.h" #include "OgitorsSystem.h" #include "BaseEditor.h" #include "ViewGrid.h" using namespace Ogitors; const int RES_LOC_DIR = 1; const int RES_LOC_ZIP = 2; extern QString ConvertToQString(Ogre::UTFString& value); //---------------------------------------------------------------------------------- SettingsDialog::SettingsDialog(QWidget *parent, PROJECTOPTIONS *options) : QDialog(parent, Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint) { setupUi(this); connect(buttonBox, SIGNAL(accepted()), this, SLOT(onAccept())); connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); connect(mBrowseProjectDirButton, SIGNAL(clicked()), this, SLOT(browse())); mOptions = options; mProjectDirTextBox->setText(mOptions->ProjectDir.c_str()); mProjectNameTextBox->setText(mOptions->ProjectName.c_str()); mSceneMgrNameMenu->addItem("OctreeSceneManager"); mSceneMgrNameMenu->setCurrentIndex(0); mConfigFileTextBox->setText(mOptions->SceneManagerConfigFile.c_str()); mTerrainDirTextBox->setText(mOptions->TerrainDirectory.c_str()); if(!mOptions->IsNewProject) { mProjectNameTextBox->setText(QApplication::translate("QtOgitorSystem", "<Enter New Name>")); mProjectDirTextBox->setEnabled(false); mProjectNameTextBox->setEnabled(false); mSceneMgrNameMenu->setEnabled(false); mConfigFileTextBox->setEnabled(false); mTerrainDirTextBox->setEnabled(false); mBrowseProjectDirButton->setEnabled(false); } unsigned int i; QString value; for(i = 0;i < mOptions->ResourceDirectories.size();i++) { value = mOptions->ResourceDirectories[i].c_str(); value = value.right(value.length() - 3); if(mOptions->ResourceDirectories[i].find("FS:") == 0) { addResourceLocation(RES_LOC_DIR, value); } else if(mOptions->ResourceDirectories[i].find("ZP:") == 0) { addResourceLocation(RES_LOC_ZIP, value); } } mResourceListBox->installEventFilter(this); mSelRectColourWidget = new ColourPickerWidget(this, QColor(mOptions->SelectionRectColour.r * 255, mOptions->SelectionRectColour.g * 255, mOptions->SelectionRectColour.b * 255)); mSelColourWidget = new ColourPickerWidget(this, QColor(mOptions->SelectionBBColour.r * 255, mOptions->SelectionBBColour.g * 255, mOptions->SelectionBBColour.b * 255)); mHighlightColourWidget = new ColourPickerWidget(this, QColor(mOptions->HighlightBBColour.r * 255, mOptions->HighlightBBColour.g * 255, mOptions->HighlightBBColour.b * 255)); mSelectHighlightColourWidget = new ColourPickerWidget(this, QColor(mOptions->SelectHighlightBBColour.r * 255, mOptions->SelectHighlightBBColour.g * 255, mOptions->SelectHighlightBBColour.b * 255)); mSelectionGridLayout->addWidget(mSelRectColourWidget,0,1,1,1); mSelectionGridLayout->addWidget(mSelColourWidget,1,1,1,1); mSelectionGridLayout->addWidget(mHighlightColourWidget,2,1,1,1); mSelectionGridLayout->addWidget(mSelectHighlightColourWidget,3,1,1,1); mGridColourWidget = new ColourPickerWidget(this, QColor(mOptions->GridColour.r * 255, mOptions->GridColour.g * 255, mOptions->GridColour.b * 255)); mGridAppearanceLayout->addWidget(mGridColourWidget,1,1,1,1); mGridSpacingMenu->setValue(ViewportGrid::getGridSpacing()); mSnapAngleMenu->setValue(0); mSelectionDepthMenu->setValue(mOptions->VolumeSelectionDepth); mSelRectColourWidget->setMaximumSize(40,20); mSelRectColourWidget->setMinimumSize(40,20); mSelColourWidget->setMaximumSize(40,20); mSelColourWidget->setMinimumSize(40,20); mHighlightColourWidget->setMaximumSize(40,20); mHighlightColourWidget->setMinimumSize(40,20); mSelectHighlightColourWidget->setMaximumSize(40,20); mSelectHighlightColourWidget->setMinimumSize(40,20); mGridColourWidget->setMaximumSize(40,20); mGridColourWidget->setMinimumSize(40,20); tabWidget->setCurrentIndex(0); // Enable dropping on the widget setAcceptDrops(true); } //---------------------------------------------------------------------------------- SettingsDialog::~SettingsDialog() { } //---------------------------------------------------------------------------------- void SettingsDialog::browse() { QString path = QFileDialog::getExistingDirectory(QApplication::activeWindow(), "",QApplication::applicationDirPath() #if OGRE_PLATFORM == OGRE_PLATFORM_LINUX , QFileDialog::DontUseNativeDialog | QFileDialog::ShowDirsOnly); #else ); #endif if(!path.isEmpty()) mProjectDirTextBox->setText(path); } //---------------------------------------------------------------------------------- bool IsValidName(QString strName, QString strDisplayName, QString exkeys = "") { strName = strName.trimmed(); bool found = false; QString mask = "%\"<>#,?&;" + exkeys; for(int i = 0;i < mask.size();i++) { if(strName.contains(mask[i])) found = true; } if(found) { Ogre::UTFString msgTemp = OgitorsSystem::getSingletonPtr()->Translate("%1 can not contain (\"<>,\"#?&;%2\")"); QString msg = ConvertToQString(msgTemp).arg(strDisplayName).arg(exkeys); QMessageBox::warning(QApplication::activeWindow(),"qtOgitor", msg, QMessageBox::Ok); return false; } if(strName.isEmpty()) { Ogre::UTFString msgTemp = OgitorsSystem::getSingletonPtr()->Translate("%1 does not contain a valid value!"); QString msg = ConvertToQString(msgTemp).arg(strDisplayName); QMessageBox::warning(QApplication::activeWindow(),"qtOgitor", msg, QMessageBox::Ok); return false; } return true; } //---------------------------------------------------------------------------------- QString lastDirPath = ""; void SettingsDialog::addResourceLocation(int loctype, QString path) { bool found = false; for(int i = 0;i < mResourceListBox->count();i++) { if(mResourceListBox->item(i)->text() == path) { found = true; break; } } if(!found) { mResourceListBox->addItem(path); mResourceFileTypes.push_back(loctype); } } //---------------------------------------------------------------------------------- void SettingsDialog::onAddDirectory() { QString path; if(lastDirPath == "") path = QApplication::applicationDirPath(); else path = lastDirPath; path = QFileDialog::getExistingDirectory(QApplication::activeWindow(), "", path #if OGRE_PLATFORM == OGRE_PLATFORM_LINUX , QFileDialog::DontUseNativeDialog | QFileDialog::ShowDirsOnly); #else ); #endif if(!path.isEmpty()) { addResourceLocation(RES_LOC_DIR, path); lastDirPath = path; } } //---------------------------------------------------------------------------------- void SettingsDialog::onAddDirectoryRecursive() { QString path; if(lastDirPath == "") path = QApplication::applicationDirPath(); else path = lastDirPath; path = QFileDialog::getExistingDirectory(QApplication::activeWindow(), "", path #if OGRE_PLATFORM == OGRE_PLATFORM_LINUX , QFileDialog::DontUseNativeDialog | QFileDialog::ShowDirsOnly); #else ); #endif // DO NOT MAKE RELATIVE CONVERSION HERE, IT WILL BE DONE WHEN OK IS CLICKED, // THE PROJECT DIRECTORY MAY NOT BE DETERMINED AT THIS POINT if(!path.isEmpty()) { lastDirPath = path; addResourceLocation(RES_LOC_DIR, path); QDirIterator it(path, QDir::AllDirs, QDirIterator::Subdirectories); while (it.hasNext()) { QString dir = it.next(); QFileInfo inf(dir); if(!dir.endsWith(".")) { addResourceLocation(RES_LOC_DIR, dir); } } } } //---------------------------------------------------------------------------------- void SettingsDialog::onAddArchive() { QString path; if(lastDirPath == "") path = QApplication::applicationDirPath(); else path = lastDirPath; path = QFileDialog::getOpenFileName(QApplication::activeWindow(), tr("Archive Files"), path, QString(tr("Zip Files (*.zip)")), 0 #if OGRE_PLATFORM == OGRE_PLATFORM_LINUX , QFileDialog::DontUseNativeDialog); #else ); #endif if(!path.isEmpty()) { addResourceLocation(RES_LOC_ZIP, path); } } //---------------------------------------------------------------------------------- void SettingsDialog::onRemoveEntry() { if(mResourceListBox->currentIndex().isValid()) { int index = mResourceListBox->currentIndex().row(); if(index >= 0) { mResourceFileTypes.erase(mResourceFileTypes.begin() + index); mResourceListBox->takeItem(index); } } } //---------------------------------------------------------------------------------- bool SettingsDialog::eventFilter ( QObject * watched, QEvent * e ) { if(watched == mResourceListBox) { if(e->type() == QEvent::ContextMenu) { QMenu *menu = new QMenu(this); menu->addAction(tr("Add Directory"), this, SLOT(onAddDirectory())); menu->addAction(tr("Add Directories Recursively"), this, SLOT(onAddDirectoryRecursive())); menu->addAction(tr("Add Archive"), this, SLOT(onAddArchive())); QAction *removeAction = menu->addAction(tr("Remove Entry"), this, SLOT(onRemoveEntry())); removeAction->setEnabled(mResourceListBox->currentIndex().row() >= 0); menu->exec(QCursor::pos()); delete menu; e->ignore(); return true; } else if(e->type() == QEvent::KeyRelease) { QKeyEvent *evt = static_cast<QKeyEvent*>(e); if(evt->key() == Qt::Key_Delete) { onRemoveEntry(); return true; } } } return false; } //---------------------------------------------------------------------------------- void SettingsDialog::onAccept() { if(mOptions->IsNewProject) { QString ProjectDir = mProjectDirTextBox->text(); QString ProjectName = mProjectNameTextBox->text(); QString SceneManagerName = mSceneMgrNameMenu->itemText(mSceneMgrNameMenu->currentIndex()); QString SceneManagerConfigFile = mConfigFileTextBox->text(); QString TerrainDir = mTerrainDirTextBox->text(); if(!IsValidName(ProjectDir, qApp->translate("SettingsDialog", "Project Directory"))) return; if(!IsValidName(ProjectName, qApp->translate("SettingsDialog", "Project Name"), "\\/")) return; if(!IsValidName(TerrainDir, qApp->translate("SettingsDialog", "Terrain Directory"))) return; Ogre::String sProjectDir = OgitorsUtils::QualifyPath(QString(ProjectDir + QString("/") + ProjectName).toStdString()); OgitorsSystem::getSingletonPtr()->MakeDirectory(sProjectDir); mOptions->CreatedIn = ""; mOptions->ProjectDir = sProjectDir; mOptions->ProjectName = ProjectName.toStdString(); mOptions->SceneManagerName = SceneManagerName.toStdString(); mOptions->SceneManagerConfigFile = SceneManagerConfigFile.toStdString(); mOptions->TerrainDirectory = TerrainDir.toStdString(); } mOptions->ResourceDirectories.clear(); Ogre::String pathTo = mOptions->ProjectDir; HashMap<Ogre::String, int> resDirMap; unsigned int i; unsigned int itemcount = mResourceListBox->count(); for(i = 0;i < itemcount;i++) { Ogre::String strTemp = mResourceListBox->item(i)->text().toStdString(); int stype = mResourceFileTypes[i]; if(strTemp.substr(0,1) != ".") strTemp = OgitorsUtils::GetRelativePath(pathTo,strTemp); Ogre::String val; if(stype == RES_LOC_DIR) { val = Ogre::String("FS:") + strTemp; if(resDirMap.find(val) == resDirMap.end()) { resDirMap[val] = 0; } } else if(stype == RES_LOC_ZIP) { val = Ogre::String("ZP:") + strTemp; if(resDirMap.find(val) == resDirMap.end()) { resDirMap[val] = 0; } } } HashMap<Ogre::String, int>::const_iterator rit = resDirMap.begin(); while(rit != resDirMap.end()) { mOptions->ResourceDirectories.push_back(rit->first); rit++; } mOptions->SelectionRectColour = mSelRectColourWidget->getColour(); mOptions->SelectionBBColour = mSelColourWidget->getColour(); mOptions->HighlightBBColour = mHighlightColourWidget->getColour(); mOptions->SelectHighlightBBColour = mSelectHighlightColourWidget->getColour(); mOptions->GridColour = mGridColourWidget->getColour(); mOptions->GridSpacing = mGridSpacingMenu->value(); mOptions->SnapAngle = mSnapAngleMenu->value(); mOptions->VolumeSelectionDepth = mSelectionDepthMenu->value(); accept(); } //---------------------------------------------------------------------------------- void SettingsDialog::dragEnterEvent(QDragEnterEvent * e) { // Only accept drags on the resources tab if(tabWidget->currentIndex() != 1) { e->ignore(); return; } // Get the filenames QStringList filenames = getFilenames(e->mimeData()); // Don't accept empty drags if(filenames.empty()) { e->ignore(); return; } // Accept when only directories and zip-files are being dragged for(int i = 0; i < filenames.size(); ++i) { QFileInfo file(filenames.at(i)); QString extension = file.suffix().toLower(); if(!file.isDir() && extension != "zip") { e->ignore(); return; } } e->accept(); } //---------------------------------------------------------------------------------- void SettingsDialog::dropEvent(QDropEvent * e) { // This should only occur when the resource tab is active assert(tabWidget->currentIndex() == 1); // Get the dropped filenames QStringList filenames = getFilenames(e->mimeData()); if(filenames.empty()) e->ignore(); // Handle the dropped items for(int i = 0; i < filenames.size(); ++i) { // All dropped items should be directories QFileInfo file(filenames.at(i)); QString extension = file.suffix().toLower(); if(file.isDir()) { addResourceLocation(RES_LOC_DIR, filenames.at(i)); } else if(extension == "zip") { addResourceLocation(RES_LOC_ZIP, filenames.at(i)); } } } //---------------------------------------------------------------------------------- QStringList SettingsDialog::getFilenames(const QMimeData * data) { QStringList result; QList<QUrl> urls = data->urls(); for(int i = 0; i < urls.size(); ++i) result.push_back(urls.at(i).toLocalFile()); return result; } //----------------------------------------------------------------------------------
16,706
5,260
#include "common.h" HMENU hMenuMain; HMENU hMenuTray; HMENU hMenuPlayListPop; ConfigReference BP_ConfigReference; CurrentFileInfomation BP_CurrentInfomation; MainWindowInfomation BP_MainWindowInfomation; ClassInfoTrackbar BP_tris, BP_trie; SkinConfiguration SkinConfig; publicInfo BP_PublicInfo; HICON hIcon_Tray; HICON hIcon_Tray_V; HWND hButton_Play; HWND hButton_Stop; HWND hButton_Back; HWND hButton_Next; HWND hWndPlayList; HICON hIcon_False; HICON hIcon_True;
472
203
//@file update.cpp /** * Copyright (C) 2008 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * 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 * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "mongo/pch.h" #include "mongo/db/ops/update.h" #include <cstring> // for memcpy #include "mongo/bson/mutable/damage_vector.h" #include "mongo/bson/mutable/document.h" #include "mongo/client/dbclientinterface.h" #include "mongo/db/clientcursor.h" #include "mongo/db/index_set.h" #include "mongo/db/namespace_details.h" #include "mongo/db/ops/update_driver.h" #include "mongo/db/pagefault.h" #include "mongo/db/pdfile.h" #include "mongo/db/query_optimizer.h" #include "mongo/db/query_runner.h" #include "mongo/db/queryutil.h" #include "mongo/db/storage/record.h" #include "mongo/db/repl/oplog.h" #include "mongo/platform/unordered_set.h" namespace mongo { namespace { // TODO: Make this a function on NamespaceString, or make it cleaner. inline void validateUpdate( const char* ns , const BSONObj& updateobj, const BSONObj& patternOrig ) { uassert( 10155 , "cannot update reserved $ collection", strchr(ns, '$') == 0 ); if ( strstr(ns, ".system.") ) { /* dm: it's very important that system.indexes is never updated as IndexDetails has pointers into it */ uassert( 10156, str::stream() << "cannot update system collection: " << ns << " q: " << patternOrig << " u: " << updateobj, legalClientSystemNS( ns , true ) ); } } /** * return a BSONObj with the _id field of the doc passed in. If no _id and multi, error. */ BSONObj makeOplogEntryQuery(const BSONObj doc, bool multi) { BSONObjBuilder idPattern; BSONElement id; // NOTE: If the matching object lacks an id, we'll log // with the original pattern. This isn't replay-safe. // It might make sense to suppress the log instead // if there's no id. if ( doc.getObjectID( id ) ) { idPattern.append( id ); return idPattern.obj(); } else { uassert( 10157, "multi-update requires all modified objects to have an _id" , ! multi ); return doc; } } } // namespace UpdateResult update(const UpdateRequest& request, OpDebug* opDebug) { // Should the modifiers validate their embedded docs via okForStorage // Only user updates should be checked. Any system or replication stuff should pass through. // Config db docs shouldn't get checked for valid field names since the shard key can have // a dot (".") in it. bool shouldValidate = !(request.isFromReplication() || request.getNamespaceString().isConfigDB()); // TODO: Consider some sort of unification between the UpdateDriver, ModifierInterface // and UpdateRequest structures. UpdateDriver::Options opts; opts.multi = request.isMulti(); opts.upsert = request.isUpsert(); opts.logOp = request.shouldUpdateOpLog(); opts.modOptions = ModifierInterface::Options( request.isFromReplication(), shouldValidate ); UpdateDriver driver( opts ); Status status = driver.parse( request.getUpdates() ); if ( !status.isOK() ) { uasserted( 16840, status.reason() ); } return update(request, opDebug, &driver); } UpdateResult update(const UpdateRequest& request, OpDebug* opDebug, UpdateDriver* driver) { const NamespaceString& nsString = request.getNamespaceString(); validateUpdate( nsString.ns().c_str(), request.getUpdates(), request.getQuery() ); NamespaceDetails* nsDetails = nsdetails( nsString.ns() ); NamespaceDetailsTransient* nsDetailsTransient = &NamespaceDetailsTransient::get( nsString.ns().c_str() ); // TODO: This seems a bit circuitious. opDebug->updateobj = request.getUpdates(); driver->refreshIndexKeys( nsDetailsTransient->indexKeys() ); shared_ptr<Cursor> cursor = getOptimizedCursor( nsString.ns(), request.getQuery(), BSONObj(), request.getQueryPlanSelectionPolicy() ); // If the update was marked with '$isolated' (a.k.a '$atomic'), we are not allowed to // yield while evaluating the update loop below. // // TODO: Old code checks this repeatedly within the update loop. Is that necessary? It seems // that once atomic should be always atomic. const bool isolated = cursor->ok() && cursor->matcher() && cursor->matcher()->docMatcher().atomic(); // The 'cursor' the optimizer gave us may contain query plans that generate duplicate // diskloc's. We set up here the mechanims that will prevent us from processing those // twice if we see them. We also set up a 'ClientCursor' so that we can support // yielding. // // TODO: Is it valid to call this on a non-ok cursor? const bool dedupHere = cursor->autoDedup(); // // We'll start assuming we have one or more documents for this update. (Othwerwise, // we'll fallback to upserting.) // // We record that this will not be an upsert, in case a mod doesn't want to be applied // when in strict update mode. driver->setContext( ModifierInterface::ExecInfo::UPDATE_CONTEXT ); // Let's fetch each of them and pipe them through the update expression, making sure to // keep track of the necessary stats. Recall that we'll be pulling documents out of // cursors and some of them do not deduplicate the entries they generate. We have // deduping logic in here, too -- for now. unordered_set<DiskLoc, DiskLoc::Hasher> seenLocs; int numMatched = 0; opDebug->nscanned = 0; Client& client = cc(); mutablebson::Document doc; // If we are going to be yielding, we will need a ClientCursor scoped to this loop. We // only loop as long as the underlying cursor is OK. for ( auto_ptr<ClientCursor> clientCursor; cursor->ok(); ) { // If we haven't constructed a ClientCursor, and if the client allows us to throw // page faults, and if we are referring to a location that is likely not in // physical memory, then throw a PageFaultException. The entire operation will be // restarted. if ( clientCursor.get() == NULL && client.allowedToThrowPageFaultException() && !cursor->currLoc().isNull() && !cursor->currLoc().rec()->likelyInPhysicalMemory() ) { // We should never throw a PFE if we have already updated items. dassert((numMatched == 0) || (numMatched == opDebug->nupdateNoops)); throw PageFaultException( cursor->currLoc().rec() ); } if ( !isolated && opDebug->nscanned != 0 ) { // We are permitted to yield. To do so we need a ClientCursor, so create one // now if we have not yet done so. if ( !clientCursor.get() ) clientCursor.reset( new ClientCursor( QueryOption_NoCursorTimeout, cursor, nsString.ns() ) ); // Ask the client cursor to yield. We get two bits of state back: whether or not // we yielded, and whether or not we correctly recovered from yielding. bool yielded = false; const bool recovered = clientCursor->yieldSometimes( ClientCursor::WillNeed, &yielded ); if ( !recovered ) { // If we failed to recover from the yield, then the ClientCursor is already // gone. Release it so we don't destroy it a second time. clientCursor.release(); break; } if ( !cursor->ok() ) { // If the cursor died while we were yielded, just get out of the update loop. break; } if ( yielded ) { // We yielded and recovered OK, and our cursor is still good. Details about // our namespace may have changed while we were yielded, so we re-acquire // them here. If we can't do so, escape the update loop. Otherwise, refresh // the driver so that it knows about what is currently indexed. nsDetails = nsdetails( nsString.ns() ); if ( !nsDetails ) break; nsDetailsTransient = &NamespaceDetailsTransient::get( nsString.ns().c_str() ); // TODO: This copies the index keys, but it may not need to do so. driver->refreshIndexKeys( nsDetailsTransient->indexKeys() ); } } // Let's fetch the next candidate object for this update. Record* record = cursor->_current(); DiskLoc loc = cursor->currLoc(); const BSONObj oldObj = loc.obj(); // We count how many documents we scanned even though we may skip those that are // deemed duplicated. The final 'numUpdated' and 'nscanned' numbers may differ for // that reason. opDebug->nscanned++; // Skips this document if it: // a) doesn't match the query portion of the update // b) was deemed duplicate by the underlying cursor machinery // // Now, if we are going to update the document, // c) we don't want to do so while the cursor is at it, as that may invalidate // the cursor. So, we advance to next document, before issuing the update. MatchDetails matchDetails; matchDetails.requestElemMatchKey(); if ( !cursor->currentMatches( &matchDetails ) ) { // a) cursor->advance(); continue; } else if ( cursor->getsetdup( loc ) && dedupHere ) { // b) cursor->advance(); continue; } else if (!driver->isDocReplacement() && request.isMulti()) { // c) cursor->advance(); if ( dedupHere ) { if ( seenLocs.count( loc ) ) { continue; } } // There are certain kind of cursors that hold multiple pointers to data // underneath. $or cursors is one example. In a $or cursor, it may be the case // that when we did the last advance(), we finished consuming documents from // one of $or child and started consuming the next one. In that case, it is // possible that the last document of the previous child is the same as the // first document of the next (see SERVER-5198 and jstests/orp.js). // // So we advance the cursor here until we see a new diskloc. // // Note that we won't be yielding, and we may not do so for a while if we find // a particularly duplicated sequence of loc's. That is highly unlikely, // though. (See SERVER-5725, if curious, but "stage" based $or will make that // ticket moot). while( cursor->ok() && loc == cursor->currLoc() ) { cursor->advance(); } } // For some (unfortunate) historical reasons, not all cursors would be valid after // a write simply because we advanced them to a document not affected by the write. // To protect in those cases, not only we engaged in the advance() logic above, but // we also tell the cursor we're about to write a document that we've just seen. // prepareToTouchEarlierIterate() requires calling later // recoverFromTouchingEarlierIterate(), so we make a note here to do so. bool touchPreviousDoc = request.isMulti() && cursor->ok(); if ( touchPreviousDoc ) { if ( clientCursor.get() ) clientCursor->setDoingDeletes( true ); cursor->prepareToTouchEarlierIterate(); } // Found a matching document numMatched++; // Ask the driver to apply the mods. It may be that the driver can apply those "in // place", that is, some values of the old document just get adjusted without any // change to the binary layout on the bson layer. It may be that a whole new // document is needed to accomodate the new bson layout of the resulting document. doc.reset( oldObj, mutablebson::Document::kInPlaceEnabled ); BSONObj logObj; // If there was a matched field, obtain it. string matchedField; if (matchDetails.hasElemMatchKey()) matchedField = matchDetails.elemMatchKey(); Status status = driver->update( matchedField, &doc, &logObj ); if ( !status.isOK() ) { uasserted( 16837, status.reason() ); } // If the driver applied the mods in place, we can ask the mutable for what // changed. We call those changes "damages". :) We use the damages to inform the // journal what was changed, and then apply them to the original document // ourselves. If, however, the driver applied the mods out of place, we ask it to // generate a new, modified document for us. In that case, the file manager will // take care of the journaling details for us. // // This code flow is admittedly odd. But, right now, journaling is baked in the file // manager. And if we aren't using the file manager, we have to do jounaling // ourselves. bool objectWasChanged = false; BSONObj newObj; const char* source = NULL; mutablebson::DamageVector damages; bool inPlace = doc.getInPlaceUpdates(&damages, &source); if ( inPlace && !damages.empty() && !driver->modsAffectIndices() ) { nsDetails->paddingFits(); // All updates were in place. Apply them via durability and writing pointer. mutablebson::DamageVector::const_iterator where = damages.begin(); const mutablebson::DamageVector::const_iterator end = damages.end(); for( ; where != end; ++where ) { const char* sourcePtr = source + where->sourceOffset; void* targetPtr = getDur().writingPtr( const_cast<char*>(oldObj.objdata()) + where->targetOffset, where->size); std::memcpy(targetPtr, sourcePtr, where->size); } newObj = oldObj; opDebug->fastmod = true; objectWasChanged = true; } else { // The updates were not in place. Apply them through the file manager. newObj = doc.getObject(); DiskLoc newLoc = theDataFileMgr.updateRecord(nsString.ns().c_str(), nsDetails, nsDetailsTransient, record, loc, newObj.objdata(), newObj.objsize(), *opDebug); // If we've moved this object to a new location, make sure we don't apply // that update again if our traversal picks the objecta again. // // We also take note that the diskloc if the updates are affecting indices. // Chances are that we're traversing one of them and they may be multi key and // therefore duplicate disklocs. if ( newLoc != loc || driver->modsAffectIndices() ) { seenLocs.insert( newLoc ); } objectWasChanged = true; } // Log Obj if ( request.shouldUpdateOpLog() ) { if ( driver->isDocReplacement() || !logObj.isEmpty() ) { BSONObj idQuery = driver->makeOplogEntryQuery(newObj, request.isMulti()); logOp("u", nsString.ns().c_str(), logObj , &idQuery, NULL, request.isFromMigration(), &newObj); } } // If it was noop since the document didn't change, record that. if (!objectWasChanged) opDebug->nupdateNoops++; if (!request.isMulti()) { break; } // If we used the cursor mechanism that prepares an earlier seen document for a // write we need to tell such mechanisms that the write is over. if ( touchPreviousDoc ) { cursor->recoverFromTouchingEarlierIterate(); } getDur().commitIfNeeded(); } // TODO: Can this be simplified? if ((numMatched > 0) || (numMatched == 0 && !request.isUpsert()) ) { opDebug->nupdated = numMatched; return UpdateResult( numMatched > 0 /* updated existing object(s) */, !driver->isDocReplacement() /* $mod or obj replacement */, numMatched /* # of docments update, even no-ops */, BSONObj() ); } // // We haven't found any existing document so an insert is done // (upsert is true). // opDebug->upsert = true; // Since this is an insert (no docs found and upsert:true), we will be logging it // as an insert in the oplog. We don't need the driver's help to build the // oplog record, then. We also set the context of the update driver to the INSERT_CONTEXT. // Some mods may only work in that context (e.g. $setOnInsert). driver->setLogOp( false ); driver->setContext( ModifierInterface::ExecInfo::INSERT_CONTEXT ); BSONObj baseObj; // Reset the document we will be writing to doc.reset( baseObj, mutablebson::Document::kInPlaceDisabled ); if ( request.getQuery().hasElement("_id") ) { uassertStatusOK(doc.root().appendElement(request.getQuery().getField("_id"))); } // If this is a $mod base update, we need to generate a document by examining the // query and the mods. Otherwise, we can use the object replacement sent by the user // update command that was parsed by the driver before. // In the following block we handle the query part, and then do the regular mods after. if ( *request.getUpdates().firstElementFieldName() == '$' ) { uassertStatusOK(UpdateDriver::createFromQuery(request.getQuery(), doc)); opDebug->fastmodinsert = true; } // Apply the update modifications and then log the update as an insert manually. Status status = driver->update( StringData(), &doc, NULL /* no oplog record */); if ( !status.isOK() ) { uasserted( 16836, status.reason() ); } BSONObj newObj = doc.getObject(); theDataFileMgr.insertWithObjMod( nsString.ns().c_str(), newObj, false, request.isGod() ); if ( request.shouldUpdateOpLog() ) { logOp( "i", nsString.ns().c_str(), newObj, NULL, NULL, request.isFromMigration(), &newObj ); } opDebug->nupdated = 1; return UpdateResult( false /* updated a non existing document */, !driver->isDocReplacement() /* $mod or obj replacement? */, 1 /* count of updated documents */, newObj /* object that was upserted */ ); } BSONObj applyUpdateOperators( const BSONObj& from, const BSONObj& operators ) { UpdateDriver::Options opts; opts.multi = false; opts.upsert = false; UpdateDriver driver( opts ); Status status = driver.parse( operators ); if ( !status.isOK() ) { uasserted( 16838, status.reason() ); } mutablebson::Document doc( from, mutablebson::Document::kInPlaceDisabled ); status = driver.update( StringData(), &doc, NULL /* not oplogging */ ); if ( !status.isOK() ) { uasserted( 16839, status.reason() ); } return doc.getObject(); } } // namespace mongo
21,927
5,567
/**************************************************************************** * * Copyright 2018 Samsung Electronics 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. * ****************************************************************************/ //===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <algorithm> // template<class T, StrictWeakOrder<auto, T> Compare> // requires !SameType<T, Compare> && CopyConstructible<Compare> // pair<const T&, const T&> // minmax(const T& a, const T& b, Compare comp); #include <algorithm> #include <functional> #include <cassert> #include "test_macros.h" #include "libcxx_tc_common.h" template <class T, class C> static int test(const T& a, const T& b, C c, const T& x, const T& y) { std::pair<const T&, const T&> p = std::minmax(a, b, c); TC_ASSERT_EXPR(&p.first == &x); TC_ASSERT_EXPR(&p.second == &y); return 0; } int tc_libcxx_algorithms_alg_min_max_minmax_comp(void) { { int x = 0; int y = 0; TC_ASSERT_FUNC((test(x, y, std::greater<int>(), x, y))); TC_ASSERT_FUNC((test(y, x, std::greater<int>(), y, x))); } { int x = 0; int y = 1; TC_ASSERT_FUNC((test(x, y, std::greater<int>(), y, x))); TC_ASSERT_FUNC((test(y, x, std::greater<int>(), y, x))); } { int x = 1; int y = 0; TC_ASSERT_FUNC((test(x, y, std::greater<int>(), x, y))); TC_ASSERT_FUNC((test(y, x, std::greater<int>(), x, y))); } #if TEST_STD_VER >= 14 { // Note that you can't take a reference to a local var, since // its address is not a compile-time constant. constexpr static int x = 1; constexpr static int y = 0; constexpr auto p1 = std::minmax(x, y, std::greater<>()); static_assert(p1.first == x, ""); static_assert(p1.second == y, ""); constexpr auto p2 = std::minmax(y, x, std::greater<>()); static_assert(p2.first == x, ""); static_assert(p2.second == y, ""); } #endif TC_SUCCESS_RESULT(); return 0; }
2,806
987
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe // SPDX-License-Identifier: MIT #include <TestFramework.h> #include <Tests/General/IslandTest.h> #include <Physics/Collision/Shape/BoxShape.h> #include <Physics/Body/BodyCreationSettings.h> #include <Layers.h> JPH_IMPLEMENT_RTTI_VIRTUAL(IslandTest) { JPH_ADD_BASE_CLASS(IslandTest, Test) } void IslandTest::Initialize() { // Floor CreateFloor(); RefConst<Shape> box_shape = new BoxShape(Vec3(1.0f, 1.0f, 1.0f)); // Walls for (int i = 0; i < 10; ++i) for (int j = i / 2; j < 10 - (i + 1) / 2; ++j) for (int k = 0; k < 8; ++k) { Vec3 position(-10 + j * 2.0f + (i & 1? 1.0f : 0.0f), 1.0f + i * 2.0f, 8.0f * (k - 4)); Body &wall = *mBodyInterface->CreateBody(BodyCreationSettings(box_shape, position, Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING)); mBodyInterface->AddBody(wall.GetID(), EActivation::Activate); } }
904
434
#include <gtest/gtest.h> #include <defer.hpp> TEST(DEFER_TEST,BAST_TEST) { bool flag = false; { defer_scope [&flag] { flag = true; }; } EXPECT_TRUE(flag); flag = false; { defer_scope [&flag] { flag = true; }; } EXPECT_TRUE(flag); flag = false; { defer_lamda { flag = true; }; } EXPECT_TRUE(flag); }
465
176
#include <iostream> #include <vector> #include <stack> using namespace std; std::vector<vector<int>> vec; std::vector<bool> visited; void dfs_r(int s){ int i; visited[s] = true; cout << "\nVisited: "<< s; for(i=0; i < vec[s].size(); ++i ){ if (visited[vec[s][i]] == false ) dfs_r(vec[s][i]); } } void dfs(const std::vector<vector<int>> vec, int s){ int node, i; std::stack<int> stk; stk.push(s); visited[s] = true; while(!stk.empty()){ node = stk.top(); stk.pop(); cout << "\nVisited: "<< node; for(int i=0; i < vec[node].size(); ++i) { if(visited[vec[node][i]] == false) { stk.push(vec[node][i]); visited[vec[node][i]] = true; } } } } void init_visited(){ // Initialize visited vector for (int i=0; i<visited.size(); i++) { visited[i] = false; } } int main() { int nodes, edges; int x[] = {1,1,2,2,3,4,4,5,5,6,6,8}; int y[] = {2,4,3,4,6,5,6,7,9,7,8,10}; // setting default for simplicity nodes = 10; edges = 12; vec.resize(nodes+1); visited.resize(nodes+1); // Creating adjacency matrix for(int i=0; i<edges; ++i) { vec[x[i]].push_back(y[i]); vec[y[i]].push_back(x[i]); } int start; cout << "Enter starting node, [1,10] : "; cin >> start; if( start>0 && start <11) { cout << "\nDFS -->\n"; init_visited(); cout << "Recursive dfs\n"; dfs_r(start); init_visited(); cout<< "\n\niterative dfs\n"; dfs(vec, start); } else cout << "\nNo such node.\n"; return 0; }
1,748
706
#include "nn_acc/CombWrite.hh" #include "debug/CombWrite.hh" CombWrite::CombWrite(CombWriteParams *params) : CombBase(params), n_of_iterations(params->data.size()), _writeEvent([this]{ writeData(); }, name() + ".event") { for (int i = 0; i < params->data.size(); i++) { _writeDataVector.push_back(params->data[i]); } } CombWrite::~CombWrite() { } void CombWrite::startup() { if(!_writeEvent.scheduled() && n_of_iterations > 0) { schedule(_writeEvent, curTick()); } } CombWrite* CombWriteParams::create() { return new CombWrite(this); } void CombWrite::writeData(){ n_of_iterations--; DPRINTF(CombWrite, "Master %s writing %d\n", _master[0].name(), _writeDataVector[n_of_iterations]); _master[0].newData(_writeDataVector[n_of_iterations]); if(n_of_iterations > 0) { schedule(_writeEvent, curTick() + _latency[0]); } }
897
372
// Copyright (c) 2011 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/browser/browser_about_handler.h" #include <algorithm> #include <string> #include <vector> #include "base/callback.h" #include "base/command_line.h" #include "base/file_util.h" #include "base/i18n/number_formatting.h" #include "base/json/json_writer.h" #include "base/memory/singleton.h" #include "base/metrics/histogram.h" #include "base/metrics/stats_table.h" #include "base/path_service.h" #include "base/string_number_conversions.h" #include "base/string_piece.h" #include "base/string_util.h" #include "base/stringprintf.h" #include "base/threading/thread.h" #include "base/tracked_objects.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "chrome/browser/about_flags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/defaults.h" #include "chrome/browser/memory_details.h" #include "chrome/browser/metrics/histogram_synchronizer.h" #include "chrome/browser/net/predictor_api.h" #include "chrome/browser/platform_util.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/browser_dialogs.h" #include "chrome/browser/ui/webui/chrome_url_data_manager.h" #include "chrome/common/about_handler.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_version_info.h" #include "chrome/common/jstemplate_builder.h" #include "chrome/common/net/gaia/google_service_auth_error.h" #include "chrome/common/render_messages.h" #include "chrome/common/url_constants.h" #include "content/browser/browser_thread.h" #include "content/browser/gpu_process_host.h" #include "content/browser/renderer_host/render_process_host.h" #include "content/browser/renderer_host/render_view_host.h" #include "content/common/gpu_messages.h" #include "googleurl/src/gurl.h" #include "grit/browser_resources.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "grit/locale_settings.h" #include "net/base/escape.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "webkit/glue/webkit_glue.h" #include "webkit/glue/plugins/plugin_list.h" #include "webkit/plugins/npapi/webplugininfo.h" #ifdef CHROME_V8 #include "v8/include/v8.h" #endif #if defined(OS_WIN) #include "chrome/browser/enumerate_modules_model_win.h" #elif defined(OS_CHROMEOS) #include "chrome/browser/chromeos/cros/cros_library.h" #include "chrome/browser/chromeos/cros/network_library.h" #include "chrome/browser/chromeos/cros/syslogs_library.h" #include "chrome/browser/chromeos/login/wizard_controller.h" #include "chrome/browser/chromeos/version_loader.h" #include "content/browser/zygote_host_linux.h" #elif defined(OS_LINUX) #include "content/browser/zygote_host_linux.h" #endif #if defined(USE_TCMALLOC) #include "third_party/tcmalloc/chromium/src/google/malloc_extension.h" #endif using base::Time; using base::TimeDelta; #if defined(USE_TCMALLOC) // static AboutTcmallocOutputs* AboutTcmallocOutputs::GetInstance() { return Singleton<AboutTcmallocOutputs>::get(); } AboutTcmallocOutputs::AboutTcmallocOutputs() {} AboutTcmallocOutputs::~AboutTcmallocOutputs() {} // Glue between the callback task and the method in the singleton. void AboutTcmallocRendererCallback(base::ProcessId pid, const std::string& output) { AboutTcmallocOutputs::GetInstance()->RendererCallback(pid, output); } #endif namespace { // The (alphabetized) paths used for the about pages. // Note: Keep these in sync with url_constants.h const char kAppCacheInternalsPath[] = "appcache-internals"; const char kBlobInternalsPath[] = "blob-internals"; const char kCreditsPath[] = "credits"; const char kCachePath[] = "view-http-cache"; #if defined(OS_WIN) const char kConflictsPath[] = "conflicts"; #endif const char kDnsPath[] = "dns"; const char kFlagsPath[] = "flags"; const char kGpuPath[] = "gpu-internals"; const char kHistogramsPath[] = "histograms"; const char kMemoryRedirectPath[] = "memory-redirect"; const char kMemoryPath[] = "memory"; const char kStatsPath[] = "stats"; const char kTasksPath[] = "tasks"; const char kTcmallocPath[] = "tcmalloc"; const char kTermsPath[] = "terms"; const char kVersionPath[] = "version"; const char kAboutPath[] = "about"; // Not about:* pages, but included to make about:about look nicer const char kNetInternalsPath[] = "net-internals"; const char kPluginsPath[] = "plugins"; const char kSyncInternalsPath[] = "sync-internals"; #if defined(OS_LINUX) const char kLinuxProxyConfigPath[] = "linux-proxy-config"; const char kSandboxPath[] = "sandbox"; #endif #if defined(OS_CHROMEOS) const char kNetworkPath[] = "network"; const char kOSCreditsPath[] = "os-credits"; const char kEULAPathFormat[] = "/usr/share/chromeos-assets/eula/%s/eula.html"; #endif // Add path here to be included in about:about const char *kAllAboutPaths[] = { kAboutPath, kAppCacheInternalsPath, kBlobInternalsPath, kCachePath, kCreditsPath, #if defined(OS_WIN) kConflictsPath, #endif kDnsPath, kFlagsPath, kGpuPath, kHistogramsPath, kMemoryPath, kNetInternalsPath, kPluginsPath, kStatsPath, kSyncInternalsPath, #ifdef TRACK_ALL_TASK_OBJECTS kTasksPath, #endif // TRACK_ALL_TASK_OBJECTS kTcmallocPath, kTermsPath, kVersionPath, #if defined(OS_LINUX) kSandboxPath, #endif #if defined(OS_CHROMEOS) kNetworkPath, kOSCreditsPath, #endif }; // When you type about:memory, it actually loads an intermediate URL that // redirects you to the final page. This avoids the problem where typing // "about:memory" on the new tab page or any other page where a process // transition would occur to the about URL will cause some confusion. // // The problem is that during the processing of the memory page, there are two // processes active, the original and the destination one. This can create the // impression that we're using more resources than we actually are. This // redirect solves the problem by eliminating the process transition during the // time that about memory is being computed. std::string GetAboutMemoryRedirectResponse() { return "<meta http-equiv=\"refresh\" " "content=\"0;chrome://about/memory\">"; } class AboutSource : public ChromeURLDataManager::DataSource { public: // Creates our datasource. AboutSource(); // Called when the network layer has requested a resource underneath // the path we registered. virtual void StartDataRequest(const std::string& path, bool is_incognito, int request_id); virtual std::string GetMimeType(const std::string&) const { return "text/html"; } // Send the response data. void FinishDataRequest(const std::string& html, int request_id); private: virtual ~AboutSource(); DISALLOW_COPY_AND_ASSIGN(AboutSource); }; // Handling about:memory is complicated enough to encapsulate its related // methods into a single class. The user should create it (on the heap) and call // its |StartFetch()| method. class AboutMemoryHandler : public MemoryDetails { public: AboutMemoryHandler(AboutSource* source, int request_id) : source_(source), request_id_(request_id) {} virtual void OnDetailsAvailable(); private: ~AboutMemoryHandler() {} void BindProcessMetrics(DictionaryValue* data, ProcessMemoryInformation* info); void AppendProcess(ListValue* child_data, ProcessMemoryInformation* info); scoped_refptr<AboutSource> source_; int request_id_; DISALLOW_COPY_AND_ASSIGN(AboutMemoryHandler); }; #if defined(OS_CHROMEOS) // ChromeOSAboutVersionHandler is responsible for loading the Chrome OS // version. // ChromeOSAboutVersionHandler handles deleting itself once the version has // been obtained and AboutSource notified. class ChromeOSAboutVersionHandler { public: ChromeOSAboutVersionHandler(AboutSource* source, int request_id); // Callback from chromeos::VersionLoader giving the version. void OnVersion(chromeos::VersionLoader::Handle handle, std::string version); private: // Where the results are fed to. scoped_refptr<AboutSource> source_; // ID identifying the request. int request_id_; // Handles asynchronously loading the version. chromeos::VersionLoader loader_; // Used to request the version. CancelableRequestConsumer consumer_; DISALLOW_COPY_AND_ASSIGN(ChromeOSAboutVersionHandler); }; class ChromeOSTermsHandler : public base::RefCountedThreadSafe<ChromeOSTermsHandler> { public: static void Start(AboutSource* source, int request_id) { scoped_refptr<ChromeOSTermsHandler> handler( new ChromeOSTermsHandler(source, request_id)); handler->StartOnUIThread(); } private: ChromeOSTermsHandler(AboutSource* source, int request_id) : source_(source), request_id_(request_id), locale_(WizardController::GetInitialLocale()) { } void StartOnUIThread() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, NewRunnableMethod(this, &ChromeOSTermsHandler::LoadFileOnFileThread)); } void LoadFileOnFileThread() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); std::string path = StringPrintf(kEULAPathFormat, locale_.c_str()); if (!file_util::ReadFileToString(FilePath(path), &contents_)) { // No EULA for given language - try en-US as default. path = StringPrintf(kEULAPathFormat, "en-US"); if (!file_util::ReadFileToString(FilePath(path), &contents_)) { // File with EULA not found, ResponseOnUIThread will load EULA from // resources if contents_ is empty. contents_.clear(); } } BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &ChromeOSTermsHandler::ResponseOnUIThread)); } void ResponseOnUIThread() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (contents_.empty()) { contents_ = ResourceBundle::GetSharedInstance().GetRawDataResource( IDR_TERMS_HTML).as_string(); } source_->FinishDataRequest(contents_, request_id_); } // Where the results are fed to. scoped_refptr<AboutSource> source_; // ID identifying the request. int request_id_; std::string locale_; std::string contents_; DISALLOW_COPY_AND_ASSIGN(ChromeOSTermsHandler); }; #endif // Individual about handlers --------------------------------------------------- std::string AboutAbout() { std::string html("<html><head><title>About Pages</title></head>\n" "<body><h2>List of About pages</h2>\n<ul>"); std::vector<std::string> paths(AboutPaths()); for (std::vector<std::string>::const_iterator i = paths.begin(); i != paths.end(); ++i) { html += "<li><a href='chrome://"; if ((*i != kAppCacheInternalsPath) && (*i != kBlobInternalsPath) && (*i != kCachePath) && #if defined(OS_WIN) (*i != kConflictsPath) && #endif (*i != kFlagsPath) && (*i != kGpuPath) && (*i != kNetInternalsPath) && (*i != kPluginsPath)) { html += "about/"; } html += *i + "/'>about:" + *i + "</a></li>\n"; } const char *debug[] = { "crash", "kill", "hang", "shorthang", "gpucrash", "gpuhang" }; html += "</ul>\n<h2>For Debug</h2>\n" "<p>The following pages are for debugging purposes only. Because they " "crash or hang the renderer, they're not linked directly; you can type " "them into the address bar if you need them.</p>\n<ul>"; for (size_t i = 0; i < arraysize(debug); i++) html += "<li>about:" + std::string(debug[i]) + "</li>\n"; html += "</ul>\n</body></html>"; return html; } #if defined(OS_CHROMEOS) // Html output helper functions // TODO(stevenjb): L10N this. // Helper function to wrap Html with <th> tag. static std::string WrapWithTH(std::string text) { return "<th>" + text + "</th>"; } // Helper function to wrap Html with <td> tag. static std::string WrapWithTD(std::string text) { return "<td>" + text + "</td>"; } // Helper function to create an Html table header for a Network. static std::string ToHtmlTableHeader(const chromeos::Network* network) { std::string str = WrapWithTH("Name") + WrapWithTH("Active") + WrapWithTH("State"); if (network->type() == chromeos::TYPE_WIFI || network->type() == chromeos::TYPE_CELLULAR) { str += WrapWithTH("Auto-Connect"); str += WrapWithTH("Strength"); } if (network->type() == chromeos::TYPE_WIFI) { str += WrapWithTH("Encryption"); str += WrapWithTH("Passphrase"); str += WrapWithTH("Identity"); str += WrapWithTH("Certificate"); } if (network->type() == chromeos::TYPE_CELLULAR) { str += WrapWithTH("Technology"); str += WrapWithTH("Connectivity"); str += WrapWithTH("Activation"); str += WrapWithTH("Roaming"); } if (network->type() == chromeos::TYPE_VPN) { str += WrapWithTH("Host"); str += WrapWithTH("Provider Type"); str += WrapWithTH("PSK Passphrase"); str += WrapWithTH("Username"); str += WrapWithTH("User Passphrase"); } str += WrapWithTH("Error"); str += WrapWithTH("IP Address"); return str; } // Helper function to create an Html table row for a Network. static std::string ToHtmlTableRow(const chromeos::Network* network) { std::string str = WrapWithTD(network->name()) + WrapWithTD(base::IntToString(network->is_active())) + WrapWithTD(network->GetStateString()); if (network->type() == chromeos::TYPE_WIFI || network->type() == chromeos::TYPE_CELLULAR) { const chromeos::WirelessNetwork* wireless = static_cast<const chromeos::WirelessNetwork*>(network); str += WrapWithTD(base::IntToString(wireless->auto_connect())); str += WrapWithTD(base::IntToString(wireless->strength())); } if (network->type() == chromeos::TYPE_WIFI) { const chromeos::WifiNetwork* wifi = static_cast<const chromeos::WifiNetwork*>(network); str += WrapWithTD(wifi->GetEncryptionString()); str += WrapWithTD(std::string(wifi->passphrase().length(), '*')); str += WrapWithTD(wifi->identity()); str += WrapWithTD(wifi->cert_path()); } if (network->type() == chromeos::TYPE_CELLULAR) { const chromeos::CellularNetwork* cell = static_cast<const chromeos::CellularNetwork*>(network); str += WrapWithTH(cell->GetNetworkTechnologyString()); str += WrapWithTH(cell->GetConnectivityStateString()); str += WrapWithTH(cell->GetActivationStateString()); str += WrapWithTH(cell->GetRoamingStateString()); } if (network->type() == chromeos::TYPE_VPN) { const chromeos::VirtualNetwork* vpn = static_cast<const chromeos::VirtualNetwork*>(network); str += WrapWithTH(vpn->server_hostname()); str += WrapWithTH(vpn->GetProviderTypeString()); str += WrapWithTD(std::string(vpn->psk_passphrase().length(), '*')); str += WrapWithTH(vpn->username()); str += WrapWithTD(std::string(vpn->user_passphrase().length(), '*')); } str += WrapWithTD(network->failed() ? network->GetErrorString() : ""); str += WrapWithTD(network->ip_address()); return str; } std::string GetNetworkHtmlInfo(int refresh) { chromeos::NetworkLibrary* cros = chromeos::CrosLibrary::Get()->GetNetworkLibrary(); std::string output; output.append("<html><head><title>About Network</title>"); if (refresh > 0) output.append("<meta http-equiv=\"refresh\" content=\"" + base::IntToString(refresh) + "\"/>"); output.append("</head><body>"); if (refresh > 0) { output.append("(Auto-refreshing page every " + base::IntToString(refresh) + "s)"); } else { output.append("(To auto-refresh this page: about:network/&lt;secs&gt;)"); } if (cros->ethernet_enabled()) { output.append("<h3>Ethernet:</h3><table border=1>"); const chromeos::EthernetNetwork* ethernet = cros->ethernet_network(); if (ethernet) { output.append("<tr>" + ToHtmlTableHeader(ethernet) + "</tr>"); output.append("<tr>" + ToHtmlTableRow(ethernet) + "</tr>"); } } if (cros->wifi_enabled()) { output.append("</table><h3>Wifi Networks:</h3><table border=1>"); const chromeos::WifiNetworkVector& wifi_networks = cros->wifi_networks(); for (size_t i = 0; i < wifi_networks.size(); ++i) { if (i == 0) output.append("<tr>" + ToHtmlTableHeader(wifi_networks[i]) + "</tr>"); output.append("<tr>" + ToHtmlTableRow(wifi_networks[i]) + "</tr>"); } } if (cros->cellular_enabled()) { output.append("</table><h3>Cellular Networks:</h3><table border=1>"); const chromeos::CellularNetworkVector& cellular_networks = cros->cellular_networks(); for (size_t i = 0; i < cellular_networks.size(); ++i) { if (i == 0) output.append("<tr>" + ToHtmlTableHeader(cellular_networks[i]) + "</tr>"); output.append("<tr>" + ToHtmlTableRow(cellular_networks[i]) + "</tr>"); } } { output.append("</table><h3>Virtual Networks:</h3><table border=1>"); const chromeos::VirtualNetworkVector& virtual_networks = cros->virtual_networks(); for (size_t i = 0; i < virtual_networks.size(); ++i) { if (i == 0) output.append("<tr>" + ToHtmlTableHeader(virtual_networks[i]) + "</tr>"); output.append("<tr>" + ToHtmlTableRow(virtual_networks[i]) + "</tr>"); } } { output.append( "</table><h3>Remembered Wi-Fi Networks:</h3><table border=1>"); const chromeos::WifiNetworkVector& remembered_wifi_networks = cros->remembered_wifi_networks(); for (size_t i = 0; i < remembered_wifi_networks.size(); ++i) { if (i == 0) output.append("<tr>" + ToHtmlTableHeader(remembered_wifi_networks[i]) + "</tr>"); output.append("<tr>" + ToHtmlTableRow(remembered_wifi_networks[i]) + "</tr>"); } } output.append("</table></body></html>"); return output; } std::string AboutNetwork(const std::string& query) { int refresh; base::StringToInt(query, &refresh); return GetNetworkHtmlInfo(refresh); } #endif // AboutDnsHandler bounces the request back to the IO thread to collect // the DNS information. class AboutDnsHandler : public base::RefCountedThreadSafe<AboutDnsHandler> { public: static void Start(AboutSource* source, int request_id) { scoped_refptr<AboutDnsHandler> handler( new AboutDnsHandler(source, request_id)); handler->StartOnUIThread(); } private: AboutDnsHandler(AboutSource* source, int request_id) : source_(source), request_id_(request_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); } // Calls FinishOnUIThread() on completion. void StartOnUIThread() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, NewRunnableMethod(this, &AboutDnsHandler::StartOnIOThread)); } void StartOnIOThread() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); std::string data; chrome_browser_net::PredictorGetHtmlInfo(&data); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &AboutDnsHandler::FinishOnUIThread, data)); } void FinishOnUIThread(const std::string& data) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); source_->FinishDataRequest(data, request_id_); } // Where the results are fed to. scoped_refptr<AboutSource> source_; // ID identifying the request. int request_id_; DISALLOW_COPY_AND_ASSIGN(AboutDnsHandler); }; #if defined(USE_TCMALLOC) std::string AboutTcmalloc(const std::string& query) { std::string data; AboutTcmallocOutputsType* outputs = AboutTcmallocOutputs::GetInstance()->outputs(); // Display any stats for which we sent off requests the last time. data.append("<html><head><title>About tcmalloc</title></head><body>\n"); data.append("<p>Stats as of last page load;"); data.append("reload to get stats as of this page load.</p>\n"); data.append("<table width=\"100%\">\n"); for (AboutTcmallocOutputsType::const_iterator oit = outputs->begin(); oit != outputs->end(); oit++) { data.append("<tr><td bgcolor=\"yellow\">"); data.append(oit->first); data.append("</td></tr>\n"); data.append("<tr><td><pre>\n"); data.append(oit->second); data.append("</pre></td></tr>\n"); } data.append("</table>\n"); data.append("</body></html>\n"); // Reset our collector singleton. outputs->clear(); // Populate the collector with stats from the local browser process // and send off requests to all the renderer processes. char buffer[1024 * 32]; MallocExtension::instance()->GetStats(buffer, sizeof(buffer)); std::string browser("Browser"); AboutTcmallocOutputs::GetInstance()->SetOutput(browser, buffer); RenderProcessHost::iterator it(RenderProcessHost::AllHostsIterator()); while (!it.IsAtEnd()) { it.GetCurrentValue()->Send(new ViewMsg_GetRendererTcmalloc); it.Advance(); } return data; } #endif std::string AboutHistograms(const std::string& query) { TimeDelta wait_time = TimeDelta::FromMilliseconds(10000); HistogramSynchronizer* current_synchronizer = HistogramSynchronizer::CurrentSynchronizer(); DCHECK(current_synchronizer != NULL); current_synchronizer->FetchRendererHistogramsSynchronously(wait_time); std::string data; base::StatisticsRecorder::WriteHTMLGraph(query, &data); return data; } void AboutMemory(AboutSource* source, int request_id) { // The AboutMemoryHandler cleans itself up, but |StartFetch()| will want the // refcount to be greater than 0. scoped_refptr<AboutMemoryHandler> handler(new AboutMemoryHandler(source, request_id)); handler->StartFetch(); } #ifdef TRACK_ALL_TASK_OBJECTS static std::string AboutObjects(const std::string& query) { std::string data; tracked_objects::ThreadData::WriteHTML(query, &data); return data; } #endif // TRACK_ALL_TASK_OBJECTS // Handler for filling in the "about:stats" page, as called by the browser's // About handler processing. // |query| is roughly the query string of the about:stats URL. // Returns a string containing the HTML to render for the about:stats page. // Conditional Output: // if |query| is "json", returns a JSON format of all counters. // if |query| is "raw", returns plain text of counter deltas. // otherwise, returns HTML with pretty JS/HTML to display the data. std::string AboutStats(const std::string& query) { // We keep the DictionaryValue tree live so that we can do delta // stats computations across runs. static DictionaryValue root; static base::TimeTicks last_sample_time = base::TimeTicks::Now(); base::TimeTicks now = base::TimeTicks::Now(); base::TimeDelta time_since_last_sample = now - last_sample_time; last_sample_time = now; base::StatsTable* table = base::StatsTable::current(); if (!table) return std::string(); // We maintain two lists - one for counters and one for timers. // Timers actually get stored on both lists. ListValue* counters; if (!root.GetList("counters", &counters)) { counters = new ListValue(); root.Set("counters", counters); } ListValue* timers; if (!root.GetList("timers", &timers)) { timers = new ListValue(); root.Set("timers", timers); } // NOTE: Counters start at index 1. for (int index = 1; index <= table->GetMaxCounters(); index++) { // Get the counter's full name std::string full_name = table->GetRowName(index); if (full_name.length() == 0) break; DCHECK_EQ(':', full_name[1]); char counter_type = full_name[0]; std::string name = full_name.substr(2); // JSON doesn't allow '.' in names. size_t pos; while ((pos = name.find(".")) != std::string::npos) name.replace(pos, 1, ":"); // Try to see if this name already exists. DictionaryValue* counter = NULL; for (size_t scan_index = 0; scan_index < counters->GetSize(); scan_index++) { DictionaryValue* dictionary; if (counters->GetDictionary(scan_index, &dictionary)) { std::string scan_name; if (dictionary->GetString("name", &scan_name) && scan_name == name) { counter = dictionary; } } else { NOTREACHED(); // Should always be there } } if (counter == NULL) { counter = new DictionaryValue(); counter->SetString("name", name); counters->Append(counter); } switch (counter_type) { case 'c': { int new_value = table->GetRowValue(index); int prior_value = 0; int delta = 0; if (counter->GetInteger("value", &prior_value)) { delta = new_value - prior_value; } counter->SetInteger("value", new_value); counter->SetInteger("delta", delta); } break; case 'm': { // TODO(mbelshe): implement me. } break; case 't': { int time = table->GetRowValue(index); counter->SetInteger("time", time); // Store this on the timers list as well. timers->Append(counter); } break; default: NOTREACHED(); } } std::string data; if (query == "json") { base::JSONWriter::WriteWithOptionalEscape(&root, true, false, &data); } else if (query == "raw") { // Dump the raw counters which have changed in text format. data = "<pre>"; data.append(StringPrintf("Counter changes in the last %ldms\n", static_cast<long int>(time_since_last_sample.InMilliseconds()))); for (size_t i = 0; i < counters->GetSize(); ++i) { Value* entry = NULL; bool rv = counters->Get(i, &entry); if (!rv) continue; // None of these should fail. DictionaryValue* counter = static_cast<DictionaryValue*>(entry); int delta; rv = counter->GetInteger("delta", &delta); if (!rv) continue; if (delta > 0) { std::string name; rv = counter->GetString("name", &name); if (!rv) continue; int value; rv = counter->GetInteger("value", &value); if (!rv) continue; data.append(name); data.append(":"); data.append(base::IntToString(delta)); data.append("\n"); } } data.append("</pre>"); } else { // Get about_stats.html and process a pretty page. static const base::StringPiece stats_html( ResourceBundle::GetSharedInstance().GetRawDataResource( IDR_ABOUT_STATS_HTML)); // Create jstemplate and return. data = jstemplate_builder::GetTemplateHtml( stats_html, &root, "t" /* template root node id */); // Clear the timer list since we stored the data in the timers list as well. for (int index = static_cast<int>(timers->GetSize())-1; index >= 0; index--) { Value* value; timers->Remove(index, &value); // We don't care about the value pointer; it's still tracked // on the counters list. } } return data; } #if defined(OS_LINUX) std::string AboutLinuxProxyConfig() { std::string data; data.append("<!DOCTYPE HTML>\n"); data.append("<html><head><meta charset=\"utf-8\"><title>"); data.append(l10n_util::GetStringUTF8(IDS_ABOUT_LINUX_PROXY_CONFIG_TITLE)); data.append("</title>"); data.append("<style>body { max-width: 70ex; padding: 2ex 5ex; }</style>"); data.append("</head><body>\n"); FilePath binary = CommandLine::ForCurrentProcess()->GetProgram(); data.append(l10n_util::GetStringFUTF8( IDS_ABOUT_LINUX_PROXY_CONFIG_BODY, l10n_util::GetStringUTF16(IDS_PRODUCT_NAME), ASCIIToUTF16(binary.BaseName().value()))); data.append("</body></html>\n"); return data; } void AboutSandboxRow(std::string* data, const std::string& prefix, int name_id, bool good) { data->append("<tr><td>"); data->append(prefix); data->append(l10n_util::GetStringUTF8(name_id)); if (good) { data->append("</td><td style=\"color: green;\">"); data->append( l10n_util::GetStringUTF8(IDS_CONFIRM_MESSAGEBOX_YES_BUTTON_LABEL)); } else { data->append("</td><td style=\"color: red;\">"); data->append( l10n_util::GetStringUTF8(IDS_CONFIRM_MESSAGEBOX_NO_BUTTON_LABEL)); } data->append("</td></tr>"); } std::string AboutSandbox() { std::string data; data.append("<!DOCTYPE HTML>\n"); data.append("<html><head><meta charset=\"utf-8\"><title>"); data.append(l10n_util::GetStringUTF8(IDS_ABOUT_SANDBOX_TITLE)); data.append("</title>"); data.append("</head><body>\n"); data.append("<h1>"); data.append(l10n_util::GetStringUTF8(IDS_ABOUT_SANDBOX_TITLE)); data.append("</h1>"); const int status = ZygoteHost::GetInstance()->sandbox_status(); data.append("<table>"); AboutSandboxRow(&data, "", IDS_ABOUT_SANDBOX_SUID_SANDBOX, status & ZygoteHost::kSandboxSUID); if (status & ZygoteHost::kSandboxPIDNS) { AboutSandboxRow(&data, "&nbsp;&nbsp;", IDS_ABOUT_SANDBOX_PID_NAMESPACES, status & ZygoteHost::kSandboxPIDNS); AboutSandboxRow(&data, "&nbsp;&nbsp;", IDS_ABOUT_SANDBOX_NET_NAMESPACES, status & ZygoteHost::kSandboxNetNS); } AboutSandboxRow(&data, "", IDS_ABOUT_SANDBOX_SECCOMP_SANDBOX, status & ZygoteHost::kSandboxSeccomp); data.append("</table>"); bool good = ((status & ZygoteHost::kSandboxSUID) && (status & ZygoteHost::kSandboxPIDNS)) || (status & ZygoteHost::kSandboxSeccomp); if (good) { data.append("<p style=\"color: green\">"); data.append(l10n_util::GetStringUTF8(IDS_ABOUT_SANDBOX_OK)); } else { data.append("<p style=\"color: red\">"); data.append(l10n_util::GetStringUTF8(IDS_ABOUT_SANDBOX_BAD)); } data.append("</p>"); data.append("</body></html>\n"); return data; } #endif std::string AboutVersion(DictionaryValue* localized_strings) { localized_strings->SetString("title", l10n_util::GetStringUTF16(IDS_ABOUT_VERSION_TITLE)); chrome::VersionInfo version_info; std::string webkit_version = webkit_glue::GetWebKitVersion(); #ifdef CHROME_V8 std::string js_version(v8::V8::GetVersion()); std::string js_engine = "V8"; #else std::string js_version = webkit_version; std::string js_engine = "JavaScriptCore"; #endif localized_strings->SetString("name", l10n_util::GetStringUTF16(IDS_PRODUCT_NAME)); localized_strings->SetString("version", version_info.Version()); // Bug 79458: Need to evaluate the use of getting the version string on // this thread. base::ThreadRestrictions::ScopedAllowIO allow_io; localized_strings->SetString("version_modifier", platform_util::GetVersionStringModifier()); localized_strings->SetString("js_engine", js_engine); localized_strings->SetString("js_version", js_version); // Obtain the version of the first enabled Flash plugin. std::vector<webkit::npapi::WebPluginInfo> info_array; webkit::npapi::PluginList::Singleton()->GetPluginInfoArray( GURL(), "application/x-shockwave-flash", false, &info_array, NULL); string16 flash_version = l10n_util::GetStringUTF16(IDS_PLUGINS_DISABLED_PLUGIN); for (size_t i = 0; i < info_array.size(); ++i) { if (webkit::npapi::IsPluginEnabled(info_array[i])) { flash_version = info_array[i].version; break; } } localized_strings->SetString("flash_plugin", "Flash"); localized_strings->SetString("flash_version", flash_version); localized_strings->SetString("webkit_version", webkit_version); localized_strings->SetString("company", l10n_util::GetStringUTF16(IDS_ABOUT_VERSION_COMPANY_NAME)); localized_strings->SetString("copyright", l10n_util::GetStringUTF16(IDS_ABOUT_VERSION_COPYRIGHT)); localized_strings->SetString("cl", version_info.LastChange()); localized_strings->SetString("official", l10n_util::GetStringUTF16( version_info.IsOfficialBuild() ? IDS_ABOUT_VERSION_OFFICIAL : IDS_ABOUT_VERSION_UNOFFICIAL)); localized_strings->SetString("user_agent_name", l10n_util::GetStringUTF16(IDS_ABOUT_VERSION_USER_AGENT)); localized_strings->SetString("useragent", webkit_glue::GetUserAgent(GURL())); localized_strings->SetString("command_line_name", l10n_util::GetStringUTF16(IDS_ABOUT_VERSION_COMMAND_LINE)); #if defined(OS_WIN) localized_strings->SetString("command_line", WideToUTF16(CommandLine::ForCurrentProcess()->command_line_string())); #elif defined(OS_POSIX) std::string command_line = ""; typedef std::vector<std::string> ArgvList; const ArgvList& argv = CommandLine::ForCurrentProcess()->argv(); for (ArgvList::const_iterator iter = argv.begin(); iter != argv.end(); iter++) command_line += " " + *iter; // TODO(viettrungluu): |command_line| could really have any encoding, whereas // below we assumes it's UTF-8. localized_strings->SetString("command_line", command_line); #endif base::StringPiece version_html( ResourceBundle::GetSharedInstance().GetRawDataResource( IDR_ABOUT_VERSION_HTML)); return jstemplate_builder::GetTemplatesHtml( version_html, localized_strings, "t" /* template root node id */); } std::string VersionNumberToString(uint32 value) { int hi = (value >> 8) & 0xff; int low = value & 0xff; return base::IntToString(hi) + "." + base::IntToString(low); } // AboutSource ----------------------------------------------------------------- AboutSource::AboutSource() : DataSource(chrome::kAboutScheme, MessageLoop::current()) { } AboutSource::~AboutSource() { } void AboutSource::StartDataRequest(const std::string& path_raw, bool is_incognito, int request_id) { std::string path = path_raw; std::string info; if (path.find("/") != std::string::npos) { size_t pos = path.find("/"); info = path.substr(pos + 1, path.length() - (pos + 1)); path = path.substr(0, pos); } path = StringToLowerASCII(path); std::string response; if (path == kDnsPath) { AboutDnsHandler::Start(this, request_id); return; } else if (path == kHistogramsPath) { response = AboutHistograms(info); } else if (path == kMemoryPath) { AboutMemory(this, request_id); return; } else if (path == kMemoryRedirectPath) { response = GetAboutMemoryRedirectResponse(); #ifdef TRACK_ALL_TASK_OBJECTS } else if (path == kTasksPath) { response = AboutObjects(info); #endif } else if (path == kStatsPath) { response = AboutStats(info); #if defined(USE_TCMALLOC) } else if (path == kTcmallocPath) { response = AboutTcmalloc(info); #endif } else if (path == kVersionPath || path.empty()) { #if defined(OS_CHROMEOS) new ChromeOSAboutVersionHandler(this, request_id); return; #else DictionaryValue value; response = AboutVersion(&value); #endif } else if (path == kCreditsPath) { response = ResourceBundle::GetSharedInstance().GetRawDataResource( IDR_CREDITS_HTML).as_string(); } else if (path == kAboutPath) { response = AboutAbout(); #if defined(OS_CHROMEOS) } else if (path == kOSCreditsPath) { response = ResourceBundle::GetSharedInstance().GetRawDataResource( IDR_OS_CREDITS_HTML).as_string(); } else if (path == kNetworkPath) { response = AboutNetwork(info); #endif } else if (path == kTermsPath) { #if defined(OS_CHROMEOS) ChromeOSTermsHandler::Start(this, request_id); return; #else response = ResourceBundle::GetSharedInstance().GetRawDataResource( IDR_TERMS_HTML).as_string(); #endif #if defined(OS_LINUX) } else if (path == kLinuxProxyConfigPath) { response = AboutLinuxProxyConfig(); } else if (path == kSandboxPath) { response = AboutSandbox(); #endif } FinishDataRequest(response, request_id); } void AboutSource::FinishDataRequest(const std::string& response, int request_id) { scoped_refptr<RefCountedBytes> html_bytes(new RefCountedBytes); html_bytes->data.resize(response.size()); std::copy(response.begin(), response.end(), html_bytes->data.begin()); SendResponse(request_id, html_bytes); } // AboutMemoryHandler ---------------------------------------------------------- // Helper for AboutMemory to bind results from a ProcessMetrics object // to a DictionaryValue. Fills ws_usage and comm_usage so that the objects // can be used in caller's scope (e.g for appending to a net total). void AboutMemoryHandler::BindProcessMetrics(DictionaryValue* data, ProcessMemoryInformation* info) { DCHECK(data && info); // Bind metrics to dictionary. data->SetInteger("ws_priv", static_cast<int>(info->working_set.priv)); data->SetInteger("ws_shareable", static_cast<int>(info->working_set.shareable)); data->SetInteger("ws_shared", static_cast<int>(info->working_set.shared)); data->SetInteger("comm_priv", static_cast<int>(info->committed.priv)); data->SetInteger("comm_map", static_cast<int>(info->committed.mapped)); data->SetInteger("comm_image", static_cast<int>(info->committed.image)); data->SetInteger("pid", info->pid); data->SetString("version", info->version); data->SetInteger("processes", info->num_processes); } // Helper for AboutMemory to append memory usage information for all // sub-processes (i.e. renderers, plugins) used by Chrome. void AboutMemoryHandler::AppendProcess(ListValue* child_data, ProcessMemoryInformation* info) { DCHECK(child_data && info); // Append a new DictionaryValue for this renderer to our list. DictionaryValue* child = new DictionaryValue(); child_data->Append(child); BindProcessMetrics(child, info); std::string child_label( ChildProcessInfo::GetFullTypeNameInEnglish(info->type, info->renderer_type)); if (info->is_diagnostics) child_label.append(" (diagnostics)"); child->SetString("child_name", child_label); ListValue* titles = new ListValue(); child->Set("titles", titles); for (size_t i = 0; i < info->titles.size(); ++i) titles->Append(new StringValue(info->titles[i])); } void AboutMemoryHandler::OnDetailsAvailable() { // the root of the JSON hierarchy for about:memory jstemplate DictionaryValue root; ListValue* browsers = new ListValue(); root.Set("browsers", browsers); const std::vector<ProcessData>& browser_processes = processes(); // Aggregate per-process data into browser summary data. std::wstring log_string; for (size_t index = 0; index < browser_processes.size(); index++) { if (browser_processes[index].processes.empty()) continue; // Sum the information for the processes within this browser. ProcessMemoryInformation aggregate; ProcessMemoryInformationList::const_iterator iterator; iterator = browser_processes[index].processes.begin(); aggregate.pid = iterator->pid; aggregate.version = iterator->version; while (iterator != browser_processes[index].processes.end()) { if (!iterator->is_diagnostics || browser_processes[index].processes.size() == 1) { aggregate.working_set.priv += iterator->working_set.priv; aggregate.working_set.shared += iterator->working_set.shared; aggregate.working_set.shareable += iterator->working_set.shareable; aggregate.committed.priv += iterator->committed.priv; aggregate.committed.mapped += iterator->committed.mapped; aggregate.committed.image += iterator->committed.image; aggregate.num_processes++; } ++iterator; } DictionaryValue* browser_data = new DictionaryValue(); browsers->Append(browser_data); browser_data->SetString("name", browser_processes[index].name); BindProcessMetrics(browser_data, &aggregate); // We log memory info as we record it. if (log_string.length() > 0) log_string.append(L", "); log_string.append(UTF16ToWide(browser_processes[index].name)); log_string.append(L", "); log_string.append(UTF8ToWide( base::Int64ToString(aggregate.working_set.priv))); log_string.append(L", "); log_string.append(UTF8ToWide( base::Int64ToString(aggregate.working_set.shared))); log_string.append(L", "); log_string.append(UTF8ToWide( base::Int64ToString(aggregate.working_set.shareable))); } if (log_string.length() > 0) VLOG(1) << "memory: " << log_string; // Set the browser & renderer detailed process data. DictionaryValue* browser_data = new DictionaryValue(); root.Set("browzr_data", browser_data); ListValue* child_data = new ListValue(); root.Set("child_data", child_data); ProcessData process = browser_processes[0]; // Chrome is the first browser. root.SetString("current_browser_name", process.name); for (size_t index = 0; index < process.processes.size(); index++) { if (process.processes[index].type == ChildProcessInfo::BROWSER_PROCESS) BindProcessMetrics(browser_data, &process.processes[index]); else AppendProcess(child_data, &process.processes[index]); } root.SetBoolean("show_other_browsers", browser_defaults::kShowOtherBrowsersInAboutMemory); // Get about_memory.html static const base::StringPiece memory_html( ResourceBundle::GetSharedInstance().GetRawDataResource( IDR_ABOUT_MEMORY_HTML)); // Create jstemplate and return. std::string template_html = jstemplate_builder::GetTemplateHtml( memory_html, &root, "t" /* template root node id */); source_->FinishDataRequest(template_html, request_id_); } #if defined(OS_CHROMEOS) // ChromeOSAboutVersionHandler ----------------------------------------------- ChromeOSAboutVersionHandler::ChromeOSAboutVersionHandler(AboutSource* source, int request_id) : source_(source), request_id_(request_id) { loader_.EnablePlatformVersions(true); loader_.GetVersion(&consumer_, NewCallback(this, &ChromeOSAboutVersionHandler::OnVersion), chromeos::VersionLoader::VERSION_FULL); } void ChromeOSAboutVersionHandler::OnVersion( chromeos::VersionLoader::Handle handle, std::string version) { DictionaryValue localized_strings; localized_strings.SetString("os_name", l10n_util::GetStringUTF16(IDS_PRODUCT_OS_NAME)); localized_strings.SetString("os_version", version); localized_strings.SetBoolean("is_chrome_os", true); source_->FinishDataRequest(AboutVersion(&localized_strings), request_id_); // CancelableRequestProvider isn't happy when it's deleted and servicing a // task, so we delay the deletion. MessageLoop::current()->DeleteSoon(FROM_HERE, this); } #endif // Returns true if |url|'s spec starts with |about_specifier|, and is // terminated by the start of a path. bool StartsWithAboutSpecifier(const GURL& url, const char* about_specifier) { return StartsWithASCII(url.spec(), about_specifier, true) && (url.spec().size() == strlen(about_specifier) || url.spec()[strlen(about_specifier)] == '/'); } // Transforms a URL of the form "about:foo/XXX" to <url_prefix> + "XXX". GURL RemapAboutURL(const std::string& url_prefix, const GURL& url) { std::string path; size_t split = url.spec().find('/'); if (split != std::string::npos) path = url.spec().substr(split + 1); return GURL(url_prefix + path); } } // namespace // ----------------------------------------------------------------------------- bool WillHandleBrowserAboutURL(GURL* url, Profile* profile) { // We only handle about: schemes. if (!url->SchemeIs(chrome::kAboutScheme)) return false; // about:blank is special. Frames are allowed to access about:blank, // but they are not allowed to access other types of about pages. // Just ignore the about:blank and let the TAB_CONTENTS_WEB handle it. if (LowerCaseEqualsASCII(url->spec(), chrome::kAboutBlankURL)) return false; // Rewrite about:cache/* URLs to chrome://view-http-cache/* if (StartsWithAboutSpecifier(*url, chrome::kAboutCacheURL)) { *url = RemapAboutURL(chrome::kNetworkViewCacheURL, *url); return true; } #if defined(OS_WIN) // Rewrite about:conflicts/* URLs to chrome://conflicts/* if (StartsWithAboutSpecifier(*url, chrome::kAboutConflicts)) { *url = GURL(chrome::kChromeUIConflictsURL); return true; } #endif // Rewrite about:flags to chrome://flags/. if (LowerCaseEqualsASCII(url->spec(), chrome::kAboutFlagsURL)) { *url = GURL(chrome::kChromeUIFlagsURL); return true; } // Rewrite about:net-internals/* URLs to chrome://net-internals/* if (StartsWithAboutSpecifier(*url, chrome::kAboutNetInternalsURL)) { *url = RemapAboutURL(chrome::kNetworkViewInternalsURL, *url); return true; } // Rewrite about:gpu/* URLs to chrome://gpu-internals/* if (StartsWithAboutSpecifier(*url, chrome::kAboutGpuURL)) { *url = RemapAboutURL(chrome::kGpuInternalsURL, *url); return true; } // Rewrite about:appcache-internals/* URLs to chrome://appcache/* if (StartsWithAboutSpecifier(*url, chrome::kAboutAppCacheInternalsURL)) { *url = RemapAboutURL(chrome::kAppCacheViewInternalsURL, *url); return true; } // Rewrite about:sync-internals/* URLs (and about:sync, too, for // legacy reasons) to chrome://sync-internals/* if (StartsWithAboutSpecifier(*url, chrome::kAboutSyncInternalsURL) || StartsWithAboutSpecifier(*url, chrome::kAboutSyncURL)) { *url = RemapAboutURL(chrome::kSyncViewInternalsURL, *url); return true; } // Rewrite about:plugins to chrome://plugins/. if (LowerCaseEqualsASCII(url->spec(), chrome::kAboutPluginsURL)) { *url = GURL(chrome::kChromeUIPluginsURL); return true; } // Handle URL to crash the browser process. if (LowerCaseEqualsASCII(url->spec(), chrome::kAboutBrowserCrash)) { // Induce an intentional crash in the browser process. int* bad_pointer = NULL; *bad_pointer = 42; return true; } // Handle URLs to wreck the gpu process. if (LowerCaseEqualsASCII(url->spec(), chrome::kAboutGpuCrashURL)) { GpuProcessHost::SendOnIO( 0, content::CAUSE_FOR_GPU_LAUNCH_ABOUT_GPUCRASH, new GpuMsg_Crash()); } if (LowerCaseEqualsASCII(url->spec(), chrome::kAboutGpuHangURL)) { GpuProcessHost::SendOnIO( 0, content::CAUSE_FOR_GPU_LAUNCH_ABOUT_GPUHANG, new GpuMsg_Hang()); } // There are a few about: URLs that we hand over to the renderer. If the // renderer wants them, don't do any rewriting. if (chrome_about_handler::WillHandle(*url)) return false; // Anything else requires our special handler; make sure it's initialized. InitializeAboutDataSource(profile); // Special case about:memory to go through a redirect before ending up on // the final page. See GetAboutMemoryRedirectResponse above for why. if (LowerCaseEqualsASCII(url->path(), kMemoryPath)) { *url = GURL("chrome://about/memory-redirect"); return true; } // Rewrite the about URL to use chrome:. WebKit treats all about URLS the // same (blank page), so if we want to display content, we need another // scheme. std::string about_url = "chrome://about/"; about_url.append(url->path()); *url = GURL(about_url); return true; } void InitializeAboutDataSource(Profile* profile) { profile->GetChromeURLDataManager()->AddDataSource(new AboutSource()); } // This function gets called with the fixed-up chrome: URLs, so we have to // compare against those instead of "about:blah". bool HandleNonNavigationAboutURL(const GURL& url) { // about:ipc is currently buggy, so we disable it for official builds. #if !defined(OFFICIAL_BUILD) #if (defined(OS_MACOSX) || defined(OS_WIN)) && defined(IPC_MESSAGE_LOG_ENABLED) if (LowerCaseEqualsASCII(url.spec(), chrome::kChromeUIIPCURL)) { // Run the dialog. This will re-use the existing one if it's already up. browser::ShowAboutIPCDialog(); return true; } #endif #endif // OFFICIAL_BUILD return false; } std::vector<std::string> AboutPaths() { std::vector<std::string> paths; paths.reserve(arraysize(kAllAboutPaths)); for (size_t i = 0; i < arraysize(kAllAboutPaths); i++) paths.push_back(kAllAboutPaths[i]); return paths; }
48,770
15,857
/* * Copyright (C) 2007 Vitor Sessak <vitor1001@gmail.com> * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * Codebook Generator using the ELBG algorithm */ #include "XMFFmpeg/libavutil/lfg.h" #include "elbg.h" #include "internal.h" #define DELTA_ERR_MAX 0.1 ///< Precision of the ELBG algorithm (as percentual error) /** * In the ELBG jargon, a cell is the set of points that are closest to a * codebook entry. Not to be confused with a RoQ Video cell. */ typedef struct cell_s { int index; struct cell_s *next; } cell; /** * ELBG internal data */ typedef struct{ int error; int dim; int numCB; int *codebook; cell **cells; int *utility; int *utility_inc; int *nearest_cb; int *points; AVLFG *rand_state; int *scratchbuf; } elbg_data; static inline int distance_limited(int *a, int *b, int dim, int limit) { int i, dist=0; for (i=0; i<dim; i++) { dist += (a[i] - b[i])*(a[i] - b[i]); if (dist > limit) return INT_MAX; } return dist; } static inline void vect_division(int *res, int *vect, int div, int dim) { int i; if (div > 1) for (i=0; i<dim; i++) res[i] = ROUNDED_DIV(vect[i],div); else if (res != vect) memcpy(res, vect, dim*sizeof(int)); } static int eval_error_cell(elbg_data *elbg, int *centroid, cell *cells) { int error=0; for (; cells; cells=cells->next) error += distance_limited(centroid, elbg->points + cells->index*elbg->dim, elbg->dim, INT_MAX); return error; } static int get_closest_codebook(elbg_data *elbg, int index) { int i, pick=0, diff, diff_min = INT_MAX; for (i=0; i<elbg->numCB; i++) if (i != index) { diff = distance_limited(elbg->codebook + i*elbg->dim, elbg->codebook + index*elbg->dim, elbg->dim, diff_min); if (diff < diff_min) { pick = i; diff_min = diff; } } return pick; } static int get_high_utility_cell(elbg_data *elbg) { int i=0; /* Using linear search, do binary if it ever turns to be speed critical */ int r = av_lfg_get(elbg->rand_state)%elbg->utility_inc[elbg->numCB-1] + 1; while (elbg->utility_inc[i] < r) i++; assert(!elbg->cells[i]); return i; } /** * Implementation of the simple LBG algorithm for just two codebooks */ static int simple_lbg(elbg_data *elbg, int dim, int *centroid[3], int newutility[3], int *points, cell *cells) { int i, idx; int numpoints[2] = {0,0}; int *newcentroid[2] = { elbg->scratchbuf + 3*dim, elbg->scratchbuf + 4*dim }; cell *tempcell; memset(newcentroid[0], 0, 2 * dim * sizeof(*newcentroid[0])); newutility[0] = newutility[1] = 0; for (tempcell = cells; tempcell; tempcell=tempcell->next) { idx = distance_limited(centroid[0], points + tempcell->index*dim, dim, INT_MAX)>= distance_limited(centroid[1], points + tempcell->index*dim, dim, INT_MAX); numpoints[idx]++; for (i=0; i<dim; i++) newcentroid[idx][i] += points[tempcell->index*dim + i]; } vect_division(centroid[0], newcentroid[0], numpoints[0], dim); vect_division(centroid[1], newcentroid[1], numpoints[1], dim); for (tempcell = cells; tempcell; tempcell=tempcell->next) { int dist[2] = {distance_limited(centroid[0], points + tempcell->index*dim, dim, INT_MAX), distance_limited(centroid[1], points + tempcell->index*dim, dim, INT_MAX)}; int idx = dist[0] > dist[1]; newutility[idx] += dist[idx]; } return newutility[0] + newutility[1]; } static void get_new_centroids(elbg_data *elbg, int huc, int *newcentroid_i, int *newcentroid_p) { cell *tempcell; int *min = newcentroid_i; int *max = newcentroid_p; int i; for (i=0; i< elbg->dim; i++) { min[i]=INT_MAX; max[i]=0; } for (tempcell = elbg->cells[huc]; tempcell; tempcell = tempcell->next) for(i=0; i<elbg->dim; i++) { min[i]=FFMIN(min[i], elbg->points[tempcell->index*elbg->dim + i]); max[i]=FFMAX(max[i], elbg->points[tempcell->index*elbg->dim + i]); } for (i=0; i<elbg->dim; i++) { int ni = min[i] + (max[i] - min[i])/3; int np = min[i] + (2*(max[i] - min[i]))/3; newcentroid_i[i] = ni; newcentroid_p[i] = np; } } /** * Add the points in the low utility cell to its closest cell. Split the high * utility cell, putting the separed points in the (now empty) low utility * cell. * * @param elbg Internal elbg data * @param indexes {luc, huc, cluc} * @param newcentroid A vector with the position of the new centroids */ static void shift_codebook(elbg_data *elbg, int *indexes, int *newcentroid[3]) { cell *tempdata; cell **pp = &elbg->cells[indexes[2]]; while(*pp) pp= &(*pp)->next; *pp = elbg->cells[indexes[0]]; elbg->cells[indexes[0]] = NULL; tempdata = elbg->cells[indexes[1]]; elbg->cells[indexes[1]] = NULL; while(tempdata) { cell *tempcell2 = tempdata->next; int idx = distance_limited(elbg->points + tempdata->index*elbg->dim, newcentroid[0], elbg->dim, INT_MAX) > distance_limited(elbg->points + tempdata->index*elbg->dim, newcentroid[1], elbg->dim, INT_MAX); tempdata->next = elbg->cells[indexes[idx]]; elbg->cells[indexes[idx]] = tempdata; tempdata = tempcell2; } } static void evaluate_utility_inc(elbg_data *elbg) { int i, inc=0; for (i=0; i < elbg->numCB; i++) { if (elbg->numCB*elbg->utility[i] > elbg->error) inc += elbg->utility[i]; elbg->utility_inc[i] = inc; } } static void update_utility_and_n_cb(elbg_data *elbg, int idx, int newutility) { cell *tempcell; elbg->utility[idx] = newutility; for (tempcell=elbg->cells[idx]; tempcell; tempcell=tempcell->next) elbg->nearest_cb[tempcell->index] = idx; } /** * Evaluate if a shift lower the error. If it does, call shift_codebooks * and update elbg->error, elbg->utility and elbg->nearest_cb. * * @param elbg Internal elbg data * @param idx {luc (low utility cell, huc (high utility cell), cluc (closest cell to low utility cell)} */ static void try_shift_candidate(elbg_data *elbg, int idx[3]) { int j, k, olderror=0, newerror, cont=0; int newutility[3]; int *newcentroid[3] = { elbg->scratchbuf, elbg->scratchbuf + elbg->dim, elbg->scratchbuf + 2*elbg->dim }; cell *tempcell; for (j=0; j<3; j++) olderror += elbg->utility[idx[j]]; memset(newcentroid[2], 0, elbg->dim*sizeof(int)); for (k=0; k<2; k++) for (tempcell=elbg->cells[idx[2*k]]; tempcell; tempcell=tempcell->next) { cont++; for (j=0; j<elbg->dim; j++) newcentroid[2][j] += elbg->points[tempcell->index*elbg->dim + j]; } vect_division(newcentroid[2], newcentroid[2], cont, elbg->dim); get_new_centroids(elbg, idx[1], newcentroid[0], newcentroid[1]); newutility[2] = eval_error_cell(elbg, newcentroid[2], elbg->cells[idx[0]]); newutility[2] += eval_error_cell(elbg, newcentroid[2], elbg->cells[idx[2]]); newerror = newutility[2]; newerror += simple_lbg(elbg, elbg->dim, newcentroid, newutility, elbg->points, elbg->cells[idx[1]]); if (olderror > newerror) { shift_codebook(elbg, idx, newcentroid); elbg->error += newerror - olderror; for (j=0; j<3; j++) update_utility_and_n_cb(elbg, idx[j], newutility[j]); evaluate_utility_inc(elbg); } } /** * Implementation of the ELBG block */ static void do_shiftings(elbg_data *elbg) { int idx[3]; evaluate_utility_inc(elbg); for (idx[0]=0; idx[0] < elbg->numCB; idx[0]++) if (elbg->numCB*elbg->utility[idx[0]] < elbg->error) { if (elbg->utility_inc[elbg->numCB-1] == 0) return; idx[1] = get_high_utility_cell(elbg); idx[2] = get_closest_codebook(elbg, idx[0]); if (idx[1] != idx[0] && idx[1] != idx[2]) try_shift_candidate(elbg, idx); } } #define BIG_PRIME 433494437LL void ff_init_elbg(int *points, int dim, int numpoints, int *codebook, int numCB, int max_steps, int *closest_cb, AVLFG *rand_state) { int i, k; if (numpoints > 24*numCB) { /* ELBG is very costly for a big number of points. So if we have a lot of them, get a good initial codebook to save on iterations */ int *temp_points = (int *)av_malloc(dim*(numpoints/8)*sizeof(int)); for (i=0; i<numpoints/8; i++) { k = (i*BIG_PRIME) % numpoints; memcpy(temp_points + i*dim, points + k*dim, dim*sizeof(int)); } ff_init_elbg(temp_points, dim, numpoints/8, codebook, numCB, 2*max_steps, closest_cb, rand_state); ff_do_elbg(temp_points, dim, numpoints/8, codebook, numCB, 2*max_steps, closest_cb, rand_state); av_free(temp_points); } else // If not, initialize the codebook with random positions for (i=0; i < numCB; i++) memcpy(codebook + i*dim, points + ((i*BIG_PRIME)%numpoints)*dim, dim*sizeof(int)); } void ff_do_elbg(int *points, int dim, int numpoints, int *codebook, int numCB, int max_steps, int *closest_cb, AVLFG *rand_state) { int dist; elbg_data elbg_d; elbg_data *elbg = &elbg_d; int i, j, k, last_error, steps=0; int *dist_cb = (int *)av_malloc(numpoints*sizeof(int)); int *size_part = (int *)av_malloc(numCB*sizeof(int)); cell *list_buffer = (cell *)av_malloc(numpoints*sizeof(cell)); cell *free_cells; int best_dist, best_idx = 0; elbg->error = INT_MAX; elbg->dim = dim; elbg->numCB = numCB; elbg->codebook = codebook; elbg->cells = (cell **)av_malloc(numCB*sizeof(cell *)); elbg->utility = (int *)av_malloc(numCB*sizeof(int)); elbg->nearest_cb = closest_cb; elbg->points = points; elbg->utility_inc = (int *)av_malloc(numCB*sizeof(int)); elbg->scratchbuf = (int *)av_malloc(5*dim*sizeof(int)); elbg->rand_state = rand_state; do { free_cells = list_buffer; last_error = elbg->error; steps++; memset(elbg->utility, 0, numCB*sizeof(int)); memset(elbg->cells, 0, numCB*sizeof(cell *)); elbg->error = 0; /* This loop evaluate the actual Voronoi partition. It is the most costly part of the algorithm. */ for (i=0; i < numpoints; i++) { best_dist = distance_limited(elbg->points + i*elbg->dim, elbg->codebook + best_idx*elbg->dim, dim, INT_MAX); for (k=0; k < elbg->numCB; k++) { dist = distance_limited(elbg->points + i*elbg->dim, elbg->codebook + k*elbg->dim, dim, best_dist); if (dist < best_dist) { best_dist = dist; best_idx = k; } } elbg->nearest_cb[i] = best_idx; dist_cb[i] = best_dist; elbg->error += dist_cb[i]; elbg->utility[elbg->nearest_cb[i]] += dist_cb[i]; free_cells->index = i; free_cells->next = elbg->cells[elbg->nearest_cb[i]]; elbg->cells[elbg->nearest_cb[i]] = free_cells; free_cells++; } do_shiftings(elbg); memset(size_part, 0, numCB*sizeof(int)); memset(elbg->codebook, 0, elbg->numCB*dim*sizeof(int)); for (i=0; i < numpoints; i++) { size_part[elbg->nearest_cb[i]]++; for (j=0; j < elbg->dim; j++) elbg->codebook[elbg->nearest_cb[i]*elbg->dim + j] += elbg->points[i*elbg->dim + j]; } for (i=0; i < elbg->numCB; i++) vect_division(elbg->codebook + i*elbg->dim, elbg->codebook + i*elbg->dim, size_part[i], elbg->dim); } while(((last_error - elbg->error) > DELTA_ERR_MAX*elbg->error) && (steps < max_steps)); av_free(dist_cb); av_free(size_part); av_free(elbg->utility); av_free(list_buffer); av_free(elbg->cells); av_free(elbg->utility_inc); av_free(elbg->scratchbuf); }
13,359
4,932
#pragma once #include <vector> #include <string> // like `trait` struct MagicItem { virtual void has_enough_mana(const char* spellname) const noexcept = 0; /// \note same for all types // @gen(inject_to_all) //S interface_data; }; template<typename T1> struct ParentTemplated_1 { virtual void has_P1(T1 name1) const noexcept = 0; }; template<typename T1> struct ParentTemplated_2 { virtual void has_P2(T1 name1) const noexcept = 0; }; // like `trait` template<typename T1, typename T2> struct MagicTemplated { virtual void has_T(const T1& name1, const T2& name2) const noexcept = 0; /// \note same for all types // @gen(inject_to_all) //S interface_data; };
685
261
#include "sdlxx/core/blendmode.h" #include <SDL_blendmode.h> #include "sdlxx/utils/bitmask.h" using namespace sdlxx; #define ASSERT_BLENDMODE(x) \ static_assert(static_cast<SDL_BlendMode>(BlendMode::x) == SDL_BLENDMODE_##x); ASSERT_BLENDMODE(NONE); ASSERT_BLENDMODE(BLEND); ASSERT_BLENDMODE(ADD); ASSERT_BLENDMODE(MOD); ASSERT_BLENDMODE(MUL); ASSERT_BLENDMODE(INVALID); #define ASSERT_BLENDOPERATION(x) \ static_assert(static_cast<SDL_BlendOperation>(BlendOperation::x) == SDL_BLENDOPERATION_##x); ASSERT_BLENDOPERATION(ADD); ASSERT_BLENDOPERATION(SUBTRACT); ASSERT_BLENDOPERATION(REV_SUBTRACT); ASSERT_BLENDOPERATION(MINIMUM); ASSERT_BLENDOPERATION(MAXIMUM); #define ASSERT_BLENDFACTOR(x) \ static_assert(static_cast<SDL_BlendFactor>(BlendFactor::x) == SDL_BLENDFACTOR_##x); ASSERT_BLENDFACTOR(ZERO); ASSERT_BLENDFACTOR(ONE); ASSERT_BLENDFACTOR(SRC_COLOR); ASSERT_BLENDFACTOR(ONE_MINUS_SRC_COLOR); ASSERT_BLENDFACTOR(SRC_ALPHA); ASSERT_BLENDFACTOR(ONE_MINUS_SRC_ALPHA); ASSERT_BLENDFACTOR(DST_COLOR); ASSERT_BLENDFACTOR(ONE_MINUS_DST_COLOR); ASSERT_BLENDFACTOR(DST_ALPHA); ASSERT_BLENDFACTOR(ONE_MINUS_DST_ALPHA); BitMask<BlendMode> ComposeCustomBlendMode( BlendFactor src_color_factor, BlendFactor dst_color_factor, BlendOperation color_operation, BlendFactor src_alpha_factor, BlendFactor dst_alpha_factor, BlendOperation alpha_operation) { return BitMask<BlendMode>{ SDL_ComposeCustomBlendMode(static_cast<SDL_BlendFactor>(src_color_factor), static_cast<SDL_BlendFactor>(dst_color_factor), static_cast<SDL_BlendOperation>(color_operation), static_cast<SDL_BlendFactor>(src_alpha_factor), static_cast<SDL_BlendFactor>(dst_alpha_factor), static_cast<SDL_BlendOperation>(alpha_operation))}; }
1,891
774
#include "expression.hpp" #include "comparison.hpp" bool operator==(const Constant& c1, const Constant& c2) { return c1.name == c2.name; } bool operator==(const Value& v1, const Value& v2) { return v1.value == v2.value; } bool operator==(const Variable& v1, const Variable& v2) { return v1.name == v2.name; } bool operator==(const Sum& s1, const Sum& s2) { return std::equal(begin(s1.operands), end(s1.operands), begin(s2.operands), end(s2.operands)); } bool operator==(const Product& s1, const Product& s2) { return std::equal(begin(s1.operands), end(s1.operands), begin(s2.operands), end(s2.operands)); } bool operator==(const Cos& c1, const Cos& c2) { return areEqual(c1.expr, c2.expr); } bool operator==(const Sin& s1, const Sin& s2) { return areEqual(s1.expr, s2.expr); }
813
322
//@group Misc/impl #include "../DgBinaryReader.h" namespace Dg { BinaryReader::BinaryReader(EndianConverter const a_ec) : BinaryIO(a_ec) { } BinaryReader::BinaryReader(Stream * a_pStream, EndianConverter const a_ec) : BinaryIO(a_ec) { Open(a_pStream); } BinaryReader::~BinaryReader() { } BinaryReader::BinaryReader(BinaryReader && a_rhs) noexcept : BinaryIO(std::move(a_rhs)) { } BinaryReader & BinaryReader::operator=(BinaryReader && a_rhs) noexcept { if (this != &a_rhs) { BinaryIO::operator=(std::move(a_rhs)); } return *this; } ErrorCode BinaryReader::Open(Stream * a_pStream) { Close(); if (a_pStream == nullptr) return ErrorCode::InvalidInput; if (!a_pStream->IsReadable()) return ErrorCode::Disallowed; m_pStream = a_pStream; return ErrorCode::None; } IO::ReturnType BinaryReader::Read_string(std::string * a_out, IO::myInt const a_count) { if (a_count < 0 || a_out == nullptr) return IO::ReturnType{ErrorCode::InvalidInput, 0}; IO::myInt curSze = static_cast<IO::myInt>(a_out->size()); a_out->resize(curSze + a_count); return Read<char>(&(*a_out)[curSze], a_count); } IO::ReturnType BinaryReader::ReadRaw(void * a_buffer, IO::myInt const a_count) { if (m_pStream == nullptr) return IO::ReturnType{ErrorCode::NullObject, IO::INVALID_VALUE}; return m_pStream->Read(a_buffer, a_count); } }
1,465
551
#pragma once #ifndef DISH2_DEBUG_LOGSTACKFRAME_HPP_INCLUDE #define DISH2_DEBUG_LOGSTACKFRAME_HPP_INCLUDE #include <string> namespace dish2 { struct LogStackFrame { std::string name; std::string detail; LogStackFrame() = default; LogStackFrame( const std::string& name_, const std::string& detail_="" ) : name( name_ ), detail( detail_ ) {} }; } // namespace dish2 #endif // #ifndef DISH2_DEBUG_LOGSTACKFRAME_HPP_INCLUDE
441
178
#ifndef EXPRAST_H #define EXPRAST_H #include <memory> #include <string> #include <vector> #include "llvm/IR/Value.h" #include "../code_gen_context.hpp" /// ExprAST - Base class for all expression nodes. class ExprAST { public: virtual ~ExprAST() = default; virtual llvm::Value *codegen(CodeGenContext &) = 0; }; #endif
334
129
// -*- C++ -*- // // ====================================================================== // // Brad T. Aagaard, U.S. Geological Survey // Charles A. Williams, GNS Science // Matthew G. Knepley, University at Buffalo // // This code was developed as part of the Computational Infrastructure // for Geodynamics (http://geodynamics.org). // // Copyright (c) 2010-2021 University of California, Davis // // See LICENSE.md for license information. // // ====================================================================== // #include "FrictionModelData.hh" // ---------------------------------------------------------------------- // Constructor pylith::friction::FrictionModelData::FrictionModelData(void) : numLocs(0), numProperties(0), numStateVars(0), numDBProperties(0), numDBStateVars(0), numPropsVertex(0), numVarsVertex(0), numPropertyValues(0), numStateVarValues(0), dbPropertyValues(0), dbStateVarValues(0), dt(0.0), dbProperties(0), dbStateVars(0), properties(0), stateVars(0), propertiesNondim(0), stateVarsNondim(0), friction(0), frictionDeriv(0), slip(0), slipRate(0), normalTraction(0), stateVarsUpdated(0), setLengthScale(0), setTimeScale(0), setPressureScale(0), setDensityScale(0) { // constructor } // constructor // ---------------------------------------------------------------------- // Destructor pylith::friction::FrictionModelData::~FrictionModelData(void) { // destructor } // destructor // End of file
1,491
487
#include "airplane.h" #include "main.h" Airplane::Airplane(float xs, float ys, float zs, color_t color) { this->position = glm::vec3(xs, ys, 0); this->rotation_x = 0; this->rotation_z = 0; this->rotation_y = 0; this->fuel = 1000; this->orc[0][0] = 1; this->orc[0][1] = 0; this->orc[0][2] = 0; this->orc[1][0] = 0; this->orc[1][1] = 1; this->orc[1][2] = 0; this->orc[2][0] = 0; this->orc[2][1] = 0; this->orc[2][2] = 1; speed = 0.5; this->score = 0; this->health = 100; static GLfloat g_vertex_buffer_data[100000]; int n = 0; int ticker = 0; orc *= speed; float x1, y1, z, xy; // vertex position float radius = 2.9; // vertex normal float s, t; // vertex texCoord float px, py, pz; int i, j = 3, k = 3; float incO = 2 * M_PI / 20; float incA = M_PI / 20; float scale_x = 0.3; GLfloat x[30], y[30]; for(int i = 0; i < 30; ++i) { x[i] = scale_x*cos(2*3.14*i/10); y[i] = scale_x*sin(2*3.14*i/10); } for(int i = 0; i < 10; ++i) { int j = 0; g_vertex_buffer_data[18*i] = x[i+j]; g_vertex_buffer_data[18*i+1] = y[i+j]; g_vertex_buffer_data[18*i+2] = -2; g_vertex_buffer_data[18*i+3] = x[(i+j+1)%30]; g_vertex_buffer_data[18*i+4] = y[(i+j+1)%30]; g_vertex_buffer_data[18*i+5] = -2; g_vertex_buffer_data[18*i+6] = x[i+j]; g_vertex_buffer_data[18*i+7] = y[i+j]; g_vertex_buffer_data[18*i+8] = 3; g_vertex_buffer_data[18*i+9] = x[i+j]; g_vertex_buffer_data[18*i+10] = y[i+j]; g_vertex_buffer_data[18*i+11] = 3; g_vertex_buffer_data[18*i+12] = x[(i+j+1)%30]; g_vertex_buffer_data[18*i+13] = y[(i+j+1)%30]; g_vertex_buffer_data[18*i+14] = 3; g_vertex_buffer_data[18*i+15] = x[(i+j+1)%30]; g_vertex_buffer_data[18*i+16] = y[(i+j+1)%30]; g_vertex_buffer_data[18*i+17] = -2; } for(int j = 0; j < 5; ++j) { for(int i = 0; i < 10; ++i) { g_vertex_buffer_data[18*i + 180* (j+1)] = x[j] * x[i]/scale_x; g_vertex_buffer_data[18*i + 180* (j+1) + 1] = x[j] * y[i]/scale_x; g_vertex_buffer_data[18*i + 180* (j+1) + 2] = 3 + y[j]/scale_x; //back g_vertex_buffer_data[18*i + 180* (j+1) + 3] = x[j] *x[(i+1)%30]/scale_x; g_vertex_buffer_data[18*i + 180* (j+1) + 4] = x[j] *y[(i+1)%30]/scale_x; g_vertex_buffer_data[18*i + 180* (j+1) + 5] = 3 + y[j]/scale_x; //back g_vertex_buffer_data[18*i + 180* (j+1) + 6] = x[j+1] *x[i]/scale_x; g_vertex_buffer_data[18*i + 180* (j+1) + 7] = x[j+1] *y[i]/scale_x; g_vertex_buffer_data[18*i + 180* (j+1) + 8] = 3 + y[j+1]/scale_x;//front g_vertex_buffer_data[18*i + 180* (j+1) + 9] = x[j+1] * x[i]/scale_x; g_vertex_buffer_data[18*i + 180* (j+1) + 10] = x[j+1] * y[i]/scale_x; g_vertex_buffer_data[18*i + 180* (j+1) + 11] = 3 + y[j+1]/scale_x; //front g_vertex_buffer_data[18*i + 180* (j+1) + 12] = x[j+1] *x[(i+1)%30]/scale_x; g_vertex_buffer_data[18*i + 180* (j+1) + 13] = x[j+1] *y[(i+1)%30]/scale_x; g_vertex_buffer_data[18*i + 180* (j+1) + 14] = 3 + y[j+1]/scale_x;//front g_vertex_buffer_data[18*i + 180* (j+1) + 15] = x[j] *x[(i+1)%30]/scale_x; g_vertex_buffer_data[18*i + 180* (j+1) + 16] = x[j] *y[(i+1)%30]/scale_x; g_vertex_buffer_data[18*i + 180* (j+1) + 17] = 3 + y[j]/scale_x;//back } } for(int i = 0; i < 10; ++i) { int j = 0; g_vertex_buffer_data[18*i + 1080] = x[j] * x[i]/scale_x; g_vertex_buffer_data[18*i + 1080 + 1] = x[j] * y[i]/scale_x; g_vertex_buffer_data[18*i + 1080 + 2] = -2 - y[j]/scale_x; //back g_vertex_buffer_data[18*i + 1080 + 3] = x[j] *x[(i+1)%30]/scale_x; g_vertex_buffer_data[18*i + 1080 + 4] = x[j] *y[(i+1)%30]/scale_x; g_vertex_buffer_data[18*i + 1080 + 5] = -2 - y[j]/scale_x; //back g_vertex_buffer_data[18*i + 1080 + 6] = x[j+1] *x[i]/scale_x; g_vertex_buffer_data[18*i + 1080 + 7] = x[j+1] *y[i]/scale_x; g_vertex_buffer_data[18*i + 1080 + 8] = -2 - y[j+1]/scale_x;//front g_vertex_buffer_data[18*i + 1080 + 9] = x[j+1] * x[i]/scale_x; g_vertex_buffer_data[18*i + 1080 + 10] = x[j+1] * y[i]/scale_x; g_vertex_buffer_data[18*i + 1080 + 11] = -2 - y[j+1]/scale_x; //front g_vertex_buffer_data[18*i + 1080 + 12] = x[j+1] *x[(i+1)%30]/scale_x; g_vertex_buffer_data[18*i + 1080 + 13] = x[j+1] *y[(i+1)%30]/scale_x; g_vertex_buffer_data[18*i + 1080 + 14] = -2 - y[j+1]/scale_x;//front g_vertex_buffer_data[18*i + 1080 + 15] = x[j] *x[(i+1)%30]/scale_x; g_vertex_buffer_data[18*i + 1080 + 16] = x[j] *y[(i+1)%30]/scale_x; g_vertex_buffer_data[18*i + 1080 + 17] = -2 - y[j]/scale_x;//back } //tail 1 g_vertex_buffer_data[1260] = 0; g_vertex_buffer_data[1261] = scale_x; g_vertex_buffer_data[1262] = -1; g_vertex_buffer_data[1263] = 0; g_vertex_buffer_data[1264] = 1.3; g_vertex_buffer_data[1265] = -2.2; g_vertex_buffer_data[1266] = 0; g_vertex_buffer_data[1267] = scale_x; g_vertex_buffer_data[1268] = -2; //tail 2 g_vertex_buffer_data[1269] = 0; g_vertex_buffer_data[1270] = 1.3; g_vertex_buffer_data[1271] = -2.2; g_vertex_buffer_data[1272] = 0; g_vertex_buffer_data[1273] = scale_x; g_vertex_buffer_data[1274] = -2; g_vertex_buffer_data[1275] = 0; g_vertex_buffer_data[1276] = 1.3; g_vertex_buffer_data[1277] = -2.7; //fins g_vertex_buffer_data[1278] = 0; g_vertex_buffer_data[1279] = -0.15; g_vertex_buffer_data[1280] = -1; g_vertex_buffer_data[1281] = 1.5f; g_vertex_buffer_data[1282] = -0.15f; g_vertex_buffer_data[1283] = -2; g_vertex_buffer_data[1284] = -1.5; g_vertex_buffer_data[1285] = -0.15; g_vertex_buffer_data[1286] = -2; g_vertex_buffer_data[1287] = 1.5f; g_vertex_buffer_data[1288] = -0.15; g_vertex_buffer_data[1289] = -2; g_vertex_buffer_data[1290] = 1.5f; g_vertex_buffer_data[1291] = -0.15; g_vertex_buffer_data[1292] = -2.3; g_vertex_buffer_data[1293] = -0.3; g_vertex_buffer_data[1294] = -0.15; g_vertex_buffer_data[1295] = -2; g_vertex_buffer_data[1296] = -1.5f; g_vertex_buffer_data[1297] = -0.15; g_vertex_buffer_data[1298] = -2; g_vertex_buffer_data[1299] = -1.5f; g_vertex_buffer_data[1300] = -0.15; g_vertex_buffer_data[1301] = -2.3; g_vertex_buffer_data[1302] = 0.3; g_vertex_buffer_data[1303] = -0.15; g_vertex_buffer_data[1304] = -2; g_vertex_buffer_data[1305] = 0; g_vertex_buffer_data[1306] = -0.15; g_vertex_buffer_data[1307] = 1.5; g_vertex_buffer_data[1308] = 3.5; g_vertex_buffer_data[1309] = -0.15f; g_vertex_buffer_data[1310] = -0.5; g_vertex_buffer_data[1311] = 0; g_vertex_buffer_data[1312] = -0.15; g_vertex_buffer_data[1313] = 0.5; g_vertex_buffer_data[1314] = 0; g_vertex_buffer_data[1315] = -0.15; g_vertex_buffer_data[1316] = 1.5; g_vertex_buffer_data[1317] = -3.5; g_vertex_buffer_data[1318] = -0.15f; g_vertex_buffer_data[1319] = -0.5; g_vertex_buffer_data[1320] = 0; g_vertex_buffer_data[1321] = -0.15; g_vertex_buffer_data[1322] = 0.5; g_vertex_buffer_data[1323] = 0; g_vertex_buffer_data[1324] = -0.15; g_vertex_buffer_data[1325] = 1.5; g_vertex_buffer_data[1326] = 1.5f; g_vertex_buffer_data[1327] = -0.15f; g_vertex_buffer_data[1328] = 0.1; g_vertex_buffer_data[1329] = -1.5; g_vertex_buffer_data[1330] = -0.15; g_vertex_buffer_data[1331] = 0.1; for(int i = 2;i<1332;i+=3) { g_vertex_buffer_data[i]*=-1; } this->object = create3DObject(GL_TRIANGLES, 420 + 12 + 12, g_vertex_buffer_data, COLOR_GOLD, GL_FILL); } void Airplane::draw(glm::mat4 VP, glm::vec3& cam_position, glm::vec3& target_position) { Matrices.model = glm::mat4(1.0f); glm::mat4 temp = glm::mat4(1.0f); glm::mat4 translate = glm::translate (this->position); // glTranslatef // glm::mat4 pitch = glm::rotate((float) (this->rotation_x * M_PI / 180.0f), glm::vec3(1,0,0)); // glm::mat4 yaw = glm::rotate((float) (this->rotation_z * M_PI / 180.0f), glm::vec3(0,0,1)); // glm::mat4 roll = glm::rotate((float) (this->rotation_y * M_PI / 180.0f), glm::vec3(0,1,0)); glm::mat4 pitch = glm::rotate((float) (this->rotation_x * M_PI / 180.0f), glm::vec3(1,0,0)); glm::mat4 yaw = glm::rotate((float) (this->rotation_y * M_PI / 180.0f), glm::vec3(0,1,0)); glm::mat4 roll = glm::rotate((float) (this->rotation_z * M_PI / 180.0f), glm::vec3(0,0,1)); // No need as coords centered at 0, 0, 0 of cube arouund which we want to rotate // rotate = rotate * glm::translate(glm::vec3(0, -0.6, 0)); // Matrices.model *= initial; Matrices.model *= (translate * yaw*pitch*roll); glm::mat4 MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(this->object); } void Airplane::set_position(float x, float y, float z) { this->position = glm::vec3(x, y, z); } int Airplane::barrel_roll() { this->rotation_z += (5*1.0); this->position.z -= speed*cosf(this->rotation_y * M_PI/180.0); if(this->rotation_z >= 360) { this->rotation_z -= 360; return 1; } return 0; } void Airplane::tick(int move, glm::vec3& cam_position, glm::vec3& target_position) { // this->rotation += speed; ticker++; // std::cout<<ticker<<"\n"; // this->position.y -= speed; if(move == 1){ if(this->rotation_x < 30) this->rotation_x += (1*1.0); this->position.y+=speed*sinf(this->rotation_x * M_PI/180.0); // cam_position.y+=speed*sinf(this->rotation_x * M_PI/180.0); // target_position.y+=speed*sinf(this->rotation_x * M_PI/180.0); } else { if(this->rotation_x >- 30) this->rotation_x -= (1* 1.0); if(this->position.y >=1){ this->position.y+=speed*sinf(this->rotation_x * M_PI/180.0); if(this->position.y < 10) this->position.y = 10; if(this->position.x > 500 && this->position.y < 24) this->position.y = 24; // cam_position.y+=speed*sinf(this->rotation_x * M_PI/180.0); // target_position.y+=speed*sinf(this->rotation_x * M_PI/180.0); } } if(move == 2) { // std::cout<<"first "<<this->rotation_z<<"\n"; if(this->rotation_z < 30) { this->rotation_z += (1*1.0); } } else if(move == -2) { // std::cout<<"second "<<this->rotation_z<<"\n"; if(this->rotation_z >- 30) { this->rotation_z -= (1*1.0); } // this->position.x -= speed*sinf(this->rotation_z * M_PI/180.0); } if(move == 3) { this->rotation_y += (-1*1.0); orc *= glm::rotate((float) (this->rotation_y * M_PI / 180.0f), glm::vec3(0,1,0)); } else if(move == -3) { this->rotation_y -= (-1*1.0); orc *= glm::rotate((float) (this->rotation_y * M_PI / 180.0f), glm::vec3(0,1,0)); } // int i,j; // for(i = 0;i<3;++i) // { // for(j = 0;j<3;++j) // std::cout<<orc[i][j]<<" "; // std::cout<<orc[i][j]<<"\n\n\n"; // } // this->position.x += orc[0][0]; //this->position.y += orc[1][1]; // this->position.z += orc[2][2]; this->position.x -= speed*sinf(this->rotation_y * M_PI/180.0); this->position.x -= speed*sinf(this->rotation_z * M_PI/180.0); this->position.z -= speed*cosf(this->rotation_y * M_PI/180.0); // std::cout<<move<<" "<<this->position.y<<"\n"; // cam_position.x -= speed*sinf(this->rotation_y * M_PI/180.0); // cam_position.x -= speed*sinf(this->rotation_z * M_PI/180.0); // cam_position.z -= speed*cosf(this->rotation_y * M_PI/180.0); // // target_position.x -= speed*sinf(this->rotation_y * M_PI/180.0); // target_position.x -= speed*sinf(this->rotation_z * M_PI/180.0); // target_position.z -= speed*cosf(this->rotation_y * M_PI/180.0); }
12,719
6,391
#pragma once #include <concepts> #include <cstddef> #include <type_traits> #include <utility> namespace opt { // clang-format off template <class T, class U = T, class R = T> concept Addable = requires (T a, U b) { { a + b } -> std::same_as<R>; }; template <class T, class U = T, class R = T> concept Subtractible = requires (T a, U b) { { a - b } -> std::same_as<R>; }; template <class T, class U = T, class R = T> concept Multipliable = requires (T a, U b) { { a * b } -> std::same_as<R>; }; template <class T, class U = T, class R = T> concept Divisible = requires (T a, U b) { { a / b } -> std::same_as<R>; }; template <class T> concept Negatable = requires (T a) { { -a } -> std::same_as<T>; }; template <class T, class U = T> concept CompoundAddable = requires (T& a, U b) { { a += b } -> std::same_as<T&>; }; template <class T, class U = T> concept CompoundSubtractible = requires (T& a, U b) { { a -= b } -> std::same_as<T&>; }; template <class T, class U = T> concept CompoundMultipliable = requires (T& a, U b) { { a *= b } -> std::same_as<T&>; }; template <class T, class U = T> concept CompoundDivisible = requires (T& a, U b) { { a /= b } -> std::same_as<T&>; }; template <class T> concept Arithmetic = std::regular<T> && Addable<T> && Subtractible<T> && Multipliable<T> && Divisible<T> && Negatable<T> && CompoundAddable<T> && CompoundSubtractible<T> && CompoundMultipliable<T> && CompoundDivisible<T> && requires(T a) { T{0}; // additive identity T{1}; // multiplicative identity }; namespace detail { template <class T> concept is_lvalue_ref = std::is_lvalue_reference_v<T>; template <class T> concept is_const_lvalue_ref = std::is_lvalue_reference_v<T> && std::is_const_v<std::remove_reference_t<T>>; } // namespace detail template <class T, class U = std::size_t> concept Indexable = requires(T& a, const T& b, U n) { { a[n] } -> detail::is_lvalue_ref; { b[n] } -> detail::is_const_lvalue_ref; }; template <class T> concept TupleSizable = requires { { std::tuple_size<T>::value } -> std::same_as<const std::size_t&>; }; template <Indexable T> using scalar_t = std::remove_cvref_t<decltype(std::declval<T&>()[0])>; template <class T, class U = scalar_t<T>> concept Vector = Arithmetic<U> && std::regular<T> && TupleSizable<T> && Indexable<T> && Addable<T> && Subtractible<T> && Negatable<T> && Multipliable<U, const T&, T>; template <class T> concept Diffable = requires (T a, T b) { a - b; }; template <Diffable T> using distance_t = std::remove_cvref_t<decltype(std::declval<const T&>() - std::declval<const T&>())>; template <class T, class U = distance_t<T>> concept Point = Vector<U> && std::regular<T> && TupleSizable<T> && (std::tuple_size<T>::value == std::tuple_size<U>::value) && Indexable<T> && Addable<const T&, const U&, T> && Addable<const U&, const T&, T> && Subtractible<const T&, const T&, U> && Subtractible<const T&, const U&, T>; template <Arithmetic, std::size_t> struct point; namespace impl { template <Arithmetic> struct dual; } // TODO replace total ordering requirement with partial ordering template <class T, class P> concept Cost = Point<P> && std::regular_invocable<const T&, const P&> && std::regular_invocable<const T&, const opt::point<impl::dual<scalar_t<P>>, std::tuple_size<P>::value>&> && std::totally_ordered<std::invoke_result_t<const T&, const P&>>; // clang-format on } // namespace opt
3,524
1,394
/* * If not stated otherwise in this file or this component's LICENSE file the * following copyright and licenses apply: * * Copyright 2020 Metrological * * 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 "../../Module.h" #include "Dolby.h" namespace WPEFramework { namespace Plugin { class DolbyOutputImplementation : public Exchange::Dolby::IOutput { public: uint32_t Register(Exchange::Dolby::IOutput::INotification* notification) override { _adminLock.Lock(); // Make sure a sink is not registered multiple times. ASSERT(std::find(_observers.begin(), _observers.end(), notification) == _observers.end()); _observers.push_back(notification); notification->AddRef(); _adminLock.Unlock(); return (Core::ERROR_NONE); } uint32_t Unregister(Exchange::Dolby::IOutput::INotification* notification) override { _adminLock.Lock(); std::list<Exchange::Dolby::IOutput::INotification*>::iterator index(std::find(_observers.begin(), _observers.end(), notification)); // Make sure you do not unregister something you did not register !!! ASSERT(index != _observers.end()); if (index != _observers.end()) { (*index)->Release(); _observers.erase(index); } _adminLock.Unlock(); return (Core::ERROR_NONE); } uint32_t AtmosMetadata(bool& supported) const override { return (Core::ERROR_UNAVAILABLE); } uint32_t SoundMode(Exchange::Dolby::IOutput::SoundModes& mode) const override { return (Core::ERROR_UNAVAILABLE); } uint32_t EnableAtmosOutput(const bool& enable) override { return (Core::ERROR_UNAVAILABLE); } uint32_t Mode(const Exchange::Dolby::IOutput::Type& mode) override { return set_audio_output_type(mode); } uint32_t Mode(Exchange::Dolby::IOutput::Type& mode) const override { return get_audio_output_type(&mode); } BEGIN_INTERFACE_MAP(DolbyOutputImplementation) INTERFACE_ENTRY(Exchange::Dolby::IOutput) END_INTERFACE_MAP private: std::list<Exchange::Dolby::IOutput::INotification*> _observers; mutable Core::CriticalSection _adminLock; }; SERVICE_REGISTRATION(DolbyOutputImplementation, 1, 0); } // namespace Plugin } // namespace WPEFramework
3,316
923
/** * @Copyright 2015 seancode * * Reads the header of a world file, as well as the json that defines it. */ #include "./worldheader.h" #include <QFile> #include <QJsonDocument> #include <QJsonArray> #include <QJsonObject> #include <QDebug> #include <utility> WorldHeader::WorldHeader() = default; WorldHeader::~WorldHeader() = default; void WorldHeader::init() { QFile file(":/res/header.json"); if (!file.open(QIODevice::ReadOnly)) throw InitException("header.json is missing!"); QJsonDocument doc = QJsonDocument::fromJson(file.readAll()); file.close(); if (doc.isNull()) throw InitException("header.json is corrupt"); if (!doc.isArray()) throw InitException("header.json isn't an array"); for (auto const &field : doc.array()) { QJsonObject const &obj = field.toObject(); fields.append(Field(obj)); } } void WorldHeader::load(const QSharedPointer<Handle> &handle, int version) { data.clear(); int num; for (auto const &field : fields) { if (version >= field.minVersion && (field.maxVersion == 0 || version <= field.maxVersion)) { auto header = QSharedPointer<Header>(new Header()); switch (field.type) { case Field::Type::BOOLEAN: header->setData(handle->r8()); break; case Field::Type::BYTE: header->setData(handle->r8()); break; case Field::Type::INT16: header->setData(handle->r16()); break; case Field::Type::INT32: header->setData(handle->r32()); break; case Field::Type::INT64: header->setData(handle->r64()); break; case Field::Type::FLOAT32: header->setData(handle->rf()); break; case Field::Type::FLOAT64: header->setData(handle->rd()); break; case Field::Type::STRING: header->setData(handle->rs()); break; case Field::Type::ARRAY_BYTE: num = field.length; if (!field.dynamicLength.isEmpty()) num = data[field.dynamicLength]->toInt(); for (int i = 0; i < num; i++) header->append(handle->r8()); break; case Field::Type::ARRAY_INT32: num = field.length; if (!field.dynamicLength.isEmpty()) num = data[field.dynamicLength]->toInt(); for (int i = 0; i < num; i++) header->append(handle->r32()); break; case Field::Type::ARRAY_STRING: num = field.length; if (!field.dynamicLength.isEmpty()) num = data[field.dynamicLength]->toInt(); for (int i = 0; i < num; i++) header->append(handle->rs()); break; } data[field.name] = header; } } } QSharedPointer<WorldHeader::Header> WorldHeader::operator[]( QString const &key) const { if (!data.contains(key)) qDebug() << "Key not found: " << key; return data[key]; } bool WorldHeader::has(const QString &key) const { return data.contains(key); } bool WorldHeader::is(const QString &key) const { if (!data.contains(key)) return false; return data[key]->toInt(); } int WorldHeader::treeStyle(int x) const { auto xs = data["treeX"]; int i; for (i = 0; i < xs->length(); i++) { if (x <= xs->at(i)->toInt()) break; } int style = data["treeStyle"]->at(i)->toInt(); switch (style) { case 0: return 0; case 5: return 10; default: return style + 5; } } WorldHeader::Field::Field(QJsonObject const &data) { name = data["name"].toString(); QString t = data["type"].toString(); if (t.isNull() || t == "b") type = Type::BOOLEAN; else if (t == "s") type = (data.contains("num") || data.contains("relnum")) ? Type::ARRAY_STRING : Type::STRING; else if (t == "u8") type = (data.contains("num") || data.contains("relnum")) ? Type::ARRAY_BYTE : Type::BYTE; else if (t == "i16") type = Type::INT16; else if (t == "i32") type = (data.contains("num") || data.contains("relnum")) ? Type::ARRAY_INT32 : Type::INT32; else if (t == "i64") type = Type::INT64; else if (t == "f32") type = Type::FLOAT32; else if (t == "f64") type = Type::FLOAT64; else throw InitException(QString("Invalid header type: %1 on %2") .arg(t).arg(name)); length = data["num"].toInt(); dynamicLength = data["relnum"].toString(); minVersion = data.contains("min") ? data["min"].toInt() : 88; maxVersion = data.contains("max") ? data["max"].toInt() : 0; } static WorldHeader::Header Null; WorldHeader::Header::Header() { ddbl = 0.0; dint = 0; } WorldHeader::Header::~Header() = default; int WorldHeader::Header::length() const { return arr.count(); } QSharedPointer<WorldHeader::Header> WorldHeader::Header::at(int i) const { return arr[i]; } int WorldHeader::Header::toInt() const { return dint; } double WorldHeader::Header::toDouble() const { return ddbl; } void WorldHeader::Header::setData(quint64 v) { dint = v; ddbl = static_cast<double>(v); } void WorldHeader::Header::setData(QString s) { dstr = std::move(s); } void WorldHeader::Header::append(QString s) { auto h = QSharedPointer<Header>(new Header()); h->setData(std::move(s)); arr.append(h); } void WorldHeader::Header::append(quint64 v) { auto h = QSharedPointer<Header>(new Header()); h->setData(v); arr.append(h); }
5,732
1,825
#include "stdafx.h" #include "SoundComponent.h" bool SoundComponent::isSame(sf::SoundBuffer& buffer) { return &buffer == this->sound->getBuffer(); } bool SoundComponent::Loaded() { return this->sound != NULL; } #pragma region Play, Pause, Stop SoundComponent* SoundComponent::play() { if (this->sound == NULL) return this; this->sound->play(); return this; } SoundComponent* SoundComponent::pause() { if (this->sound == NULL) return this; this->sound->pause(); return this; } SoundComponent* SoundComponent::stop() { if (this->sound == NULL) return this; this->sound->stop(); return this; } #pragma endregion bool SoundComponent::isPlaying() { if (this->sound == NULL) return false; return this->sound->getStatus() == sf::Sound::Status::Playing; } #pragma region Volume SoundComponent* SoundComponent::setVolume(float volume) { if (this->sound == NULL) return this; this->sound->setVolume(volume); return this; } float SoundComponent::getVolume() { if (this->sound == NULL) return -1; return this->sound->getVolume(); } #pragma endregion #pragma region Offset SoundComponent* SoundComponent::setOffset(int msec) { if (this->sound == NULL) return this; this->sound->setPlayingOffset(sf::milliseconds(msec)); return this; } int SoundComponent::getOffset() { if (this->sound == NULL) return -1; return this->sound->getPlayingOffset().asMilliseconds(); } #pragma endregion #pragma region Loop SoundComponent* SoundComponent::setLoop(bool loop) { if (this->sound == NULL) return this; this->sound->setLoop(loop); return this; } bool SoundComponent::getLoop() { if (this->sound == NULL) return false; return this->sound->getLoop(); } #pragma endregion SoundComponent::SoundComponent(sf::SoundBuffer& buffer) { this->sound = new sf::Sound(buffer); } SoundComponent::~SoundComponent() { if (this->sound != NULL) { delete this->sound; this->sound = NULL; } } SoundComponent* SoundComponent::reset(sf::SoundBuffer& buffer) { if (this->sound == NULL) return this; this->sound->stop(); this->sound->setBuffer(buffer); this->sound->setPlayingOffset(sf::milliseconds(0)); return this; }
2,154
731
#pragma once #include "CreditsView.hpp" #include "GameScene.hpp" #include "MenuSceneView.hpp" namespace HiLo { class Game : public Observer<MenuSceneView> , public Observer<GameScene> , public Observer<CreditsView> { public: auto receiveEvent(MenuSceneView*, MenuSceneView::Event const&) noexcept -> void override; auto receiveEvent(GameScene*, GameScene::Event const&) noexcept -> void override; auto receiveEvent(CreditsView*, CreditsView::Event const&) noexcept -> void override; Game() noexcept; auto handleEvent(SDL_Event const&) noexcept -> void; auto draw() const noexcept -> void; private: enum class Scene { Menu, Game, Credits }; Scene mActiveScene{Scene::Menu}; MenuSceneView mMenuSceneView; GameScene mGameScene; CreditsView mCreditsView; }; } // namespace HiLo
877
270
#include "run_test_files.hpp" #include "log_pipe.hpp" #ifndef _WIN32 # include "posix/run_test_file.hpp" namespace platform = mettle::posix; #else # include "windows/run_test_file.hpp" namespace platform = mettle::windows; #endif namespace mettle { void run_test_files( const std::vector<test_command> &commands, log::file_logger &logger, const std::vector<std::string> &args ) { using namespace platform; logger.started_run(); detail::file_uid_maker uid; for(const auto &command : commands) { test_file file = {command, uid.make_file_uid()}; logger.started_file(file); std::vector<std::string> final_args = command.args(); final_args.insert(final_args.end(), args.begin(), args.end()); auto result = run_test_file(std::move(final_args), log::pipe(logger, file.id)); if(result.passed) logger.ended_file(file); else logger.failed_file(file, result.message); } logger.ended_run(); } } // namespace mettle
1,044
353
/* //@HEADER // ***************************************************************************** // // test_termination_action_callable.extended.cc // DARMA/vt => Virtual Transport // // Copyright 2019-2021 National Technology & Engineering Solutions of Sandia, LLC // (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. // Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * 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 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 OWNER 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. // // Questions? Contact darma@sandia.gov // // ***************************************************************************** //@HEADER */ #include "test_termination_action_common.h" #if !defined INCLUDED_VT_TERMINATION_ACTION_CALLABLE_H #define INCLUDED_VT_TERMINATION_ACTION_CALLABLE_H namespace vt { namespace tests { namespace unit { namespace channel { // set channel counting ranks vt::NodeType root = vt::uninitialized_destination; vt::NodeType node = vt::uninitialized_destination; vt::NodeType all = vt::uninitialized_destination; std::unordered_map<vt::EpochType,Data> data; bool ok = false; }}}} /* end namespace vt::tests::unit::channel */ namespace vt { namespace tests { namespace unit { static bool finished[2] = {false, false}; static int num = 0; // no need for a parameterized fixture struct TestTermCallable : action::SimpleFixture { void verify(int cur) { int const nxt = (cur + 1) % 2; EXPECT_FALSE(finished[cur]); EXPECT_TRUE(not finished[nxt] or num == 1); finished[cur] = true; num++; } }; TEST_F(TestTermCallable, test_add_action_unique) /*NOLINT*/{ finished[0] = finished[1] = false; num = 0; vt::theCollective()->barrier(); // create an epoch and a related termination flag auto epoch = ::vt::theTerm()->makeEpochCollective(); // assign an arbitrary action to be triggered at // the end of the epoch and toggle the previous flag. ::vt::theTerm()->addActionEpoch(epoch, [=]{ vt_debug_print( normal, term, "current epoch:{:x} finished\n", epoch ); verify(0); }); // assign a callable to be triggered after // the action submitted for the given epoch. ::vt::theTerm()->addActionUnique(epoch, [=]{ vt_debug_print( normal, term, "trigger callable for epoch:{:x}\n", epoch ); verify(1); }); if (channel::node == channel::root) { action::compute(epoch); } ::vt::theTerm()->finishedEpoch(epoch); } }}} // namespace vt::tests::unit::action #endif /*INCLUDED_VT_TERMINATION_ACTION_CALLABLE_H*/
3,989
1,334
#include "map.h" #include "utilities.h" void build_unique_pentamers(DNA_to_properties& pentamers){ std::string alphabet[4]={"A","T","G","C"}; pentamers.clear(); std::string t=""; for (int i=0;i<4;i++) for (int j=0;j<4;j++) for (int k=0;k<4;k++) for (int l=0;l<4;l++) for (int m=0;m<4;m++){ t=alphabet[i]+alphabet[j]+alphabet[k]+alphabet[l]+alphabet[m]; if ((!found_str_in_map(t,pentamers)) && (!found_str_in_map(opposite_strand(t),pentamers))){ properties p=properties(); pentamers[t]=p; } } } bool found_str_in_map(std::string str, DNA_to_properties &onemap){ DNA_to_properties::const_iterator end=onemap.end(); if (onemap.find(str)!=end) return true; else return false; }
745
331
/* KeyPad.cpp - Driver for a 4x4 keypad used for RPN calculator. Copyright (c) 2021 Igor Mikolic-Torreira 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 "KeyPad.h" #include "AVRTools/SystemClock.h" #include "PinAssignments.h" void configureKeyPad() { // Configure the keybad to accept inputs // Configure keypad column pins... // First set gpio pins PD4-PD7 (= columns), as output (PD0-PD3 unchanged) // This is the high nibble of register DDRD // Get current DDRD value, set high nibble to ones, write it back uint8_t ddrVal = getGpioDDR( pKeyPadCol1 ); ddrVal |= 0xF0; getGpioDDR( pKeyPadCol1 ) = ddrVal; // Then set these pins low (high nibble of register PORTD) // Get current PORTD value, set high nibble to zeros, write it back uint8_t portVal = getGpioPORT( pKeyPadCol1 ); portVal &= 0x0F; getGpioPORT( pKeyPadCol1 ) = portVal; // Configure keypad row pins... // First set gpio pins PB0-PB3 (= rows), as inputs (PB4-PB7 unchanged) // This is the low nibble of register DDRB // Get current DDRB value, set low nibble to zeros, write it back ddrVal = getGpioDDR( pKeyPadRow1 ); ddrVal &= 0xF0; getGpioDDR( pKeyPadRow1 ) = ddrVal; // Then enable pull-up resistors on column pins // This is the low nibble of register PORTB // Get current PORTB, set low nibble to ones, write it back portVal = getGpioPORT( pKeyPadRow1 ); portVal |= 0x0F; getGpioPORT( pKeyPadRow1 ) = portVal; // Allow time for the gpio circuits to settle delayMicroseconds( 200 ); } bool keyPressed() { // A key is pressed if any row goes low // Get the PINB register value uint8_t pinsVal = getGpioPIN( pKeyPadRow1 ); // Keep only the low nibble (corresponding to rows) pinsVal &= 0x0F; // If pinsVal != 0x0F, then not all row pins are high, ergo key press return ( pinsVal != 0x0F ); } uint8_t getKeyPressed() { // This function assumes a key is actually been pressed // If this assumption is wrong, function returns 255... // This will store the key number uint8_t keyNbr = 255; // First find the row of the key press (which row pin is low) if ( !readGpioPinDigital( pKeyPadRow1 ) ) { keyNbr = 0; } else if ( !readGpioPinDigital( pKeyPadRow2 ) ) { keyNbr = 4; } else if ( !readGpioPinDigital( pKeyPadRow3 ) ) { keyNbr = 8; } else if ( !readGpioPinDigital( pKeyPadRow4 ) ) { keyNbr = 12; } // To read the column value need to flip the configuration of rows & columns // Change rows (low nibble) to outputs (set high)... uint8_t ddrVal = getGpioDDR( pKeyPadRow1 ); ddrVal |= 0x0F; getGpioDDR( pKeyPadRow1 ) = ddrVal; // Set rows (low nibble) low uint8_t portVal = getGpioPORT( pKeyPadRow1 ); portVal &= 0xF0; getGpioPORT( pKeyPadRow1 ) = portVal; // Change columns (high nibble) to inputs (set low) ddrVal = getGpioDDR( pKeyPadCol1 ); ddrVal &= 0x0F; getGpioDDR( pKeyPadCol1 ) = ddrVal; // Set pull-up resistors on columns (high nibble) (set high) portVal = getGpioPORT( pKeyPadCol1 ); portVal |= 0xF0; getGpioPORT( pKeyPadCol1 ) = portVal; // Allow time for the gpio circuits to settle delayMicroseconds( 200 ); // Find the column of the key press (which row pin is low) if ( !readGpioPinDigital( pKeyPadCol1 ) ) { keyNbr += 0; } else if ( !readGpioPinDigital( pKeyPadCol2 ) ) { keyNbr += 1; } else if ( !readGpioPinDigital( pKeyPadCol3 ) ) { keyNbr += 2; } else if ( !readGpioPinDigital( pKeyPadCol4 ) ) { keyNbr += 3; } // restore keypad configuration configureKeyPad(); return keyNbr; }
4,863
1,767
// Copyright 2019 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 // // 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 "tink/aead/kms_envelope_aead.h" #include <memory> #include <string> #include <utility> #include "absl/base/internal/endian.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "tink/aead.h" #include "tink/registry.h" #include "tink/util/errors.h" #include "tink/util/status.h" #include "tink/util/statusor.h" #include "proto/tink.pb.h" namespace crypto { namespace tink { namespace { const int kEncryptedDekPrefixSize = 4; const char* kEmptyAssociatedData = ""; // Constructs a ciphertext of KMS envelope encryption. // The format of the ciphertext is the following: // 4-byte-prefix | encrypted_dek | encrypted_plaintext // where 4-byte-prefix is the length of encrypted_dek in big-endian format // (for compatibility with Java) std::string GetEnvelopeCiphertext(absl::string_view encrypted_dek, absl::string_view encrypted_plaintext) { uint8_t enc_dek_size[kEncryptedDekPrefixSize]; absl::big_endian::Store32(enc_dek_size, encrypted_dek.size()); return absl::StrCat(std::string(reinterpret_cast<const char*>(enc_dek_size), kEncryptedDekPrefixSize), encrypted_dek, encrypted_plaintext); } } // namespace // static util::StatusOr<std::unique_ptr<Aead>> KmsEnvelopeAead::New( const google::crypto::tink::KeyTemplate& dek_template, std::unique_ptr<Aead> remote_aead) { if (remote_aead == nullptr) { return util::Status(absl::StatusCode::kInvalidArgument, "remote_aead must be non-null"); } auto km_result = Registry::get_key_manager<Aead>(dek_template.type_url()); if (!km_result.ok()) return km_result.status(); std::unique_ptr<Aead> envelope_aead( new KmsEnvelopeAead(dek_template, std::move(remote_aead))); return std::move(envelope_aead); } util::StatusOr<std::string> KmsEnvelopeAead::Encrypt( absl::string_view plaintext, absl::string_view associated_data) const { // Generate DEK. auto dek_result = Registry::NewKeyData(dek_template_); if (!dek_result.ok()) return dek_result.status(); auto dek = std::move(dek_result.value()); // Wrap DEK key values with remote. auto dek_encrypt_result = remote_aead_->Encrypt(dek->value(), kEmptyAssociatedData); if (!dek_encrypt_result.ok()) return dek_encrypt_result.status(); // Encrypt plaintext using DEK. auto aead_result = Registry::GetPrimitive<Aead>(*dek); if (!aead_result.ok()) return aead_result.status(); auto aead = std::move(aead_result.value()); auto encrypt_result = aead->Encrypt(plaintext, associated_data); if (!encrypt_result.ok()) return encrypt_result.status(); // Build and return ciphertext. return GetEnvelopeCiphertext(dek_encrypt_result.value(), encrypt_result.value()); } util::StatusOr<std::string> KmsEnvelopeAead::Decrypt( absl::string_view ciphertext, absl::string_view associated_data) const { // Parse the ciphertext. if (ciphertext.size() < kEncryptedDekPrefixSize) { return util::Status(absl::StatusCode::kInvalidArgument, "ciphertext too short"); } auto enc_dek_size = absl::big_endian::Load32( reinterpret_cast<const uint8_t*>(ciphertext.data())); if (enc_dek_size > ciphertext.size() - kEncryptedDekPrefixSize || enc_dek_size < 0) { return util::Status(absl::StatusCode::kInvalidArgument, "invalid ciphertext"); } // Decrypt the DEK with remote. auto dek_decrypt_result = remote_aead_->Decrypt( ciphertext.substr(kEncryptedDekPrefixSize, enc_dek_size), kEmptyAssociatedData); if (!dek_decrypt_result.ok()) { return util::Status(absl::StatusCode::kInvalidArgument, absl::StrCat("invalid ciphertext: ", dek_decrypt_result.status().message())); } // Create AEAD from DEK. google::crypto::tink::KeyData dek; dek.set_type_url(dek_template_.type_url()); dek.set_value(dek_decrypt_result.value()); dek.set_key_material_type(google::crypto::tink::KeyData::SYMMETRIC); // Encrypt plaintext using DEK. auto aead_result = Registry::GetPrimitive<Aead>(dek); if (!aead_result.ok()) return aead_result.status(); auto aead = std::move(aead_result.value()); return aead->Decrypt( ciphertext.substr(kEncryptedDekPrefixSize + enc_dek_size), associated_data); } } // namespace tink } // namespace crypto
5,152
1,708
/*============================================================================= NiftyLink: A software library to facilitate communication over OpenIGTLink. Copyright (c) University College London (UCL). All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt in the top level directory for details. =============================================================================*/ #include "stdlib.h" #include <QDebug> #include <QSettings> #include <QDateTime> #include "TestStringMsg_General.h" #include <cmath> TestStringMsg_General::TestStringMsg_General(void) { m_TestCounter = 0; m_SuccessCounter = 0; } TestStringMsg_General::~TestStringMsg_General(void) { std::cerr << "Test class destructor"; } void TestStringMsg_General::SetupTest() { //Nothing to do right now } void TestStringMsg_General::PerformTest() { //Create image message and initialize with test data std::cout << ++m_TestCounter << ". Creating string message.."; NiftyLinkStringMessage::Pointer stringMsg; stringMsg.reset(); stringMsg = (NiftyLinkStringMessage::Pointer(new NiftyLinkStringMessage())); if (stringMsg.operator != (NULL)) { std::cout << " OK\n"; m_SuccessCounter++; } else { std::cout << " FAILED\n"; } //*********************************************** std::cout << ++m_TestCounter << ". Initializing with test data.."; stringMsg->InitializeWithTestData(); if (stringMsg->GetString() == QString("This is a test string")) { std::cout << " OK\n"; m_SuccessCounter++; } else { std::cout << " FAILED\n"; } //*********************************************** std::cout << ++m_TestCounter << ". Setting string.."; stringMsg->SetString("This is a random string which meant to crash the NiftyLink lib"); if (stringMsg->GetString() != QString("This is a random string which meant to crash the NiftyLink lib")) { std::cout << " FAILED\n"; } else { std::cout << " OK\n"; m_SuccessCounter++; } //*********************************************** std::cout << ++m_TestCounter << ". Setting encoding.."; stringMsg->SetEncoding(3); if (stringMsg->GetEncoding() != 3) { std::cout << " FAILED\n"; } else { std::cout << " OK\n"; m_SuccessCounter++; } //*********************************************** std::cout << ++m_TestCounter << ". Setting timestamp and sender ID.."; stringMsg->Update(GetLocalHostAddress()); if (stringMsg->GetHostName().isEmpty() || stringMsg->GetTimeCreated().IsNull()) { std::cout << " FAILED\n"; } else { std::cout << " OK\n"; m_SuccessCounter++; } //*********************************************** std::cout << ++m_TestCounter << ". Setting message type tag.."; stringMsg->ChangeMessageType("Something"); if (stringMsg->GetMessageType() != QString("Something")) { std::cout << " FAILED\n"; } else { std::cout << " OK\n"; m_SuccessCounter++; } //*********************************************** std::cout << ++m_TestCounter << ". Setting port number.."; stringMsg->SetPort(100); if (stringMsg->GetPort() != 100) { std::cout << " FAILED\n"; } else { std::cout << " OK\n"; m_SuccessCounter++; } //*********************************************** std::cout << ++m_TestCounter << ". Setting receive timestamp.."; igtl::TimeStamp::Pointer tsr = igtl::TimeStamp::New(); igtl::TimeStamp::Pointer tss = igtl::TimeStamp::New(); tsr->Update(); stringMsg->SetTimeReceived(tsr); tss = stringMsg->GetTimeReceived(); if (tsr->GetTimeInNanoSeconds() != tss->GetTimeInNanoSeconds()) { std::cout << " FAILED\n"; } else { std::cout << " OK\n"; m_SuccessCounter++; } //*********************************************** std::cout << ++m_TestCounter << ". Checking create timestamp and id.."; igtl::TimeStamp::Pointer tsc = igtl::TimeStamp::New(); igtlUint64 id = 0; tsc = stringMsg->GetTimeCreated(); id = stringMsg->GetId(); if (tsr->GetTimeInNanoSeconds() < tsc->GetTimeInNanoSeconds() || id <= 0) { std::cout << " FAILED\n"; } else { std::cout << " OK\n"; m_SuccessCounter++; } //*********************************************** std::cout << ++m_TestCounter << ". Checking Update function and hostname.."; stringMsg->Update("Something"); QString hname = stringMsg->GetHostName(); stringMsg->ChangeHostName("Anything"); QString hname2 = stringMsg->GetHostName(); if (hname2 != QString("Anything") || hname != QString("Something")) { std::cout << " FAILED\n"; } else { std::cout << " OK\n"; m_SuccessCounter++; } //*********************************************** std::cout << ++m_TestCounter << ". Checking message pointer get / set.."; igtl::MessageBase::Pointer mp = igtl::MessageBase::New(); igtl::MessageBase::Pointer mp3; stringMsg->SetMessagePointer(mp); stringMsg->GetMessagePointer(mp3); if (mp != mp3) { std::cout << " FAILED\n"; } else { std::cout << " OK\n"; m_SuccessCounter++; } //*********************************************** std::cout << ++m_TestCounter << ". Set resolution settings.."; NiftyLinkMessage::Pointer sttString; sttString.reset(); NiftyLinkStringMessage::Create_STT(sttString); sttString->SetResolution(100); igtlUint64 res = 0; sttString->GetResolution(res); if (res != 100) { std::cout << " FAILED\n"; } else { std::cout << " OK\n"; m_SuccessCounter++; } //*********************************************** std::cout << ++m_TestCounter << ". Deleting messages.."; stringMsg.reset(); stringMsg.operator = (NULL); sttString.reset(); sttString.operator = (NULL); if (sttString.operator != (NULL) || stringMsg.operator != (NULL)) { std::cout << " FAILED\n"; } else { std::cout << " OK\n"; m_SuccessCounter++; } //*********************************************** QuitTest(); } void TestStringMsg_General::QuitTest() { emit Done(); if (m_TestCounter > m_SuccessCounter) { std::cout << "\n\n\n"; std::cout << "****************************************************\n"; std::cout << "**************** TESTING FINISHED: *****************\n"; std::cout << "***************** " << (m_TestCounter - m_SuccessCounter) << " TEST(S) FAILED *****************\n"; std::cout << "****************************************************\n"; exit(-1); } else { std::cout << "\n\n\n"; std::cout << "****************************************************\n"; std::cout << "**************** TESTING FINISHED: *****************\n"; std::cout << "********* ALL TESTS COMPLETED SUCCESSFULLY *********\n"; std::cout << "****************************************************\n"; exit(0); } }
6,932
2,283
////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015, John Haddon. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * 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 John Haddon nor the names of // any other contributors to this software 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 OWNER 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 "Gaffer/Loop.h" #include "Gaffer/ContextAlgo.h" #include "Gaffer/MetadataAlgo.h" #include "boost/bind.hpp" namespace Gaffer { IE_CORE_DEFINERUNTIMETYPED( Loop ); Loop::Loop( const std::string &name ) : ComputeNode( name ), m_inPlugIndex( 0 ), m_outPlugIndex( 0 ), m_firstPlugIndex( 0 ) { // Connect to `childAddedSignal()` so we can set ourselves up later when the // appropriate plugs are added manually. /// \todo Remove this and do all the work in `setup()`. childAddedSignal().connect( boost::bind( &Loop::childAdded, this ) ); } Loop::~Loop() { } void Loop::setup( const ValuePlug *plug ) { if( inPlug() ) { throw IECore::Exception( "Loop already has an \"in\" plug." ); } if( outPlug() ) { throw IECore::Exception( "Loop already has an \"out\" plug." ); } PlugPtr in = plug->createCounterpart( "in", Plug::In ); MetadataAlgo::copyColors( plug , in.get() , /* overwrite = */ false ); in->setFlags( Plug::Serialisable, true ); addChild( in ); PlugPtr out = plug->createCounterpart( "out", Plug::Out ); MetadataAlgo::copyColors( plug , out.get() , /* overwrite = */ false ); addChild( out ); } ValuePlug *Loop::inPlug() { return m_inPlugIndex ? getChild<ValuePlug>( m_inPlugIndex ) : nullptr; } const ValuePlug *Loop::inPlug() const { return m_inPlugIndex ? getChild<ValuePlug>( m_inPlugIndex ) : nullptr; } ValuePlug *Loop::outPlug() { return m_outPlugIndex ? getChild<ValuePlug>( m_outPlugIndex ) : nullptr; } const ValuePlug *Loop::outPlug() const { return m_outPlugIndex ? getChild<ValuePlug>( m_outPlugIndex ) : nullptr; } ValuePlug *Loop::nextPlug() { return m_firstPlugIndex ? getChild<ValuePlug>( m_firstPlugIndex ) : nullptr; } const ValuePlug *Loop::nextPlug() const { return m_firstPlugIndex ? getChild<ValuePlug>( m_firstPlugIndex ) : nullptr; } ValuePlug *Loop::previousPlug() { return m_firstPlugIndex ? getChild<ValuePlug>( m_firstPlugIndex + 1 ) : nullptr; } const ValuePlug *Loop::previousPlug() const { return m_firstPlugIndex ? getChild<ValuePlug>( m_firstPlugIndex + 1 ) : nullptr; } IntPlug *Loop::iterationsPlug() { return m_firstPlugIndex ? getChild<IntPlug>( m_firstPlugIndex + 2 ) : nullptr; } const IntPlug *Loop::iterationsPlug() const { return m_firstPlugIndex ? getChild<IntPlug>( m_firstPlugIndex + 2 ) : nullptr; } StringPlug *Loop::indexVariablePlug() { return m_firstPlugIndex ? getChild<StringPlug>( m_firstPlugIndex + 3 ) : nullptr; } const StringPlug *Loop::indexVariablePlug() const { return m_firstPlugIndex ? getChild<StringPlug>( m_firstPlugIndex + 3 ) : nullptr; } Gaffer::BoolPlug *Loop::enabledPlug() { return m_firstPlugIndex ? getChild<BoolPlug>( m_firstPlugIndex + 4 ) : nullptr; } const Gaffer::BoolPlug *Loop::enabledPlug() const { return m_firstPlugIndex ? getChild<BoolPlug>( m_firstPlugIndex + 4 ) : nullptr; } Gaffer::Plug *Loop::correspondingInput( const Gaffer::Plug *output ) { return output == outPlug() ? inPlug() : nullptr; } const Gaffer::Plug *Loop::correspondingInput( const Gaffer::Plug *output ) const { return output == outPlug() ? inPlug() : nullptr; } void Loop::affects( const Plug *input, DependencyNode::AffectedPlugsContainer &outputs ) const { ComputeNode::affects( input, outputs ); if( input == iterationsPlug() ) { addAffectedPlug( outPlug(), outputs ); } else if( input == indexVariablePlug() || input == enabledPlug() ) { addAffectedPlug( outPlug(), outputs ); addAffectedPlug( previousPlug(), outputs ); } else if( const ValuePlug *inputValuePlug = IECore::runTimeCast<const ValuePlug>( input ) ) { std::vector<IECore::InternedString> relativeName; const ValuePlug *ancestor = ancestorPlug( inputValuePlug, relativeName ); if( ancestor == inPlug() || ancestor == nextPlug() ) { outputs.push_back( descendantPlug( outPlug(), relativeName ) ); outputs.push_back( descendantPlug( previousPlug(), relativeName ) ); } } } void Loop::hash( const ValuePlug *output, const Context *context, IECore::MurmurHash &h ) const { int index = -1; IECore::InternedString indexVariable; if( const ValuePlug *plug = sourcePlug( output, context, index, indexVariable ) ) { Context::EditableScope tmpContext( context ); if( index >= 0 ) { tmpContext.set<int>( indexVariable, index ); } else { tmpContext.remove( indexVariable ); } h = plug->hash(); return; } ComputeNode::hash( output, context, h ); } void Loop::compute( ValuePlug *output, const Context *context ) const { int index = -1; IECore::InternedString indexVariable; if( const ValuePlug *plug = sourcePlug( output, context, index, indexVariable ) ) { Context::EditableScope tmpContext( context ); if( index >= 0 ) { tmpContext.set<int>( indexVariable, index ); } else { tmpContext.remove( indexVariable ); } output->setFrom( plug ); return; } ComputeNode::compute( output, context ); } void Loop::childAdded() { setupPlugs(); } bool Loop::setupPlugs() { const ValuePlug *in = getChild<ValuePlug>( "in" ); const ValuePlug *out = getChild<ValuePlug>( "out" ); if( !in || !out ) { return false; } childAddedSignal().disconnect( boost::bind( &Loop::childAdded, this ) ); m_inPlugIndex = std::find( children().begin(), children().end(), in ) - children().begin(); m_outPlugIndex = std::find( children().begin(), children().end(), out ) - children().begin(); const size_t firstPlugIndex = children().size(); addChild( in->createCounterpart( "next", Plug::In ) ); addChild( out->createCounterpart( "previous", Plug::Out ) ); addChild( new IntPlug( "iterations", Gaffer::Plug::In, 10, 0 ) ); addChild( new StringPlug( "indexVariable", Gaffer::Plug::In, "loop:index" ) ); addChild( new BoolPlug( "enabled", Gaffer::Plug::In, true ) ); // Only assign after adding all plugs, because our plug accessors // use a non-zero value to indicate that all plugs are now available. m_firstPlugIndex = firstPlugIndex; // The in/out plugs might be dynamic in the case of // LoopComputeNode, but because we create the next/previous // plugs ourselves in response, they don't need to be dynamic. nextPlug()->setFlags( Plug::Dynamic, false ); previousPlug()->setFlags( Plug::Dynamic, false ); // Copy styling over from main plugs. /// \todo We shouldn't really need to do this, because plug colours are /// expected to be registered against plug type, so our plugs will get /// the right colour automatically (and `copyColors()` will do nothing /// because of the `overwrite = false` argument). We are keeping it for /// now to accommodate proprietary extensions which are using custom colours /// instead of introducing their own plug types, but some day we should /// just remove this entirely. Note that the same applies for the Dot, /// ContextProcessor, ArrayPlug and Switch nodes. See /// https://github.com/GafferHQ/gaffer/pull/2953 for further discussion. MetadataAlgo::copyColors( inPlug(), nextPlug() , /* overwrite = */ false ); MetadataAlgo::copyColors( inPlug(), previousPlug() , /* overwrite = */ false ); // Because we're a loop, our affects() implementation specifies a cycle // between nextPlug() and previousPlug(), so we must ask nicely for leniency // during dirty propagation. The cycles aren't an issue when it comes to // hash()/compute() because each iteration changes the context and we bottom // out after the specified number of iterations. previousPlug()->setFlags( Plug::AcceptsDependencyCycles, true ); for( Gaffer::RecursivePlugIterator it( previousPlug() ); !it.done(); ++it ) { (*it)->setFlags( Plug::AcceptsDependencyCycles, true ); } return true; } void Loop::addAffectedPlug( const ValuePlug *output, DependencyNode::AffectedPlugsContainer &outputs ) const { if( output->children().size() ) { for( RecursiveOutputPlugIterator it( output ); !it.done(); ++it ) { if( !(*it)->children().size() ) { outputs.push_back( it->get() ); } } } else { outputs.push_back( output ); } } const ValuePlug *Loop::ancestorPlug( const ValuePlug *plug, std::vector<IECore::InternedString> &relativeName ) const { while( plug ) { const GraphComponent *plugParent = plug->parent(); if( plugParent == this ) { return plug; } else { relativeName.push_back( plug->getName() ); plug = static_cast<const ValuePlug *>( plugParent ); } } return nullptr; } const ValuePlug *Loop::descendantPlug( const ValuePlug *plug, const std::vector<IECore::InternedString> &relativeName ) const { for( std::vector<IECore::InternedString>::const_reverse_iterator it = relativeName.rbegin(), eIt = relativeName.rend(); it != eIt; ++it ) { plug = plug->getChild<ValuePlug>( *it ); } return plug; } const ValuePlug *Loop::sourcePlug( const ValuePlug *output, const Context *context, int &sourceLoopIndex, IECore::InternedString &indexVariable ) const { sourceLoopIndex = -1; ContextAlgo::GlobalScope globalScope( context, inPlug() ); indexVariable = indexVariablePlug()->getValue(); std::vector<IECore::InternedString> relativeName; const ValuePlug *ancestor = ancestorPlug( output, relativeName ); if( ancestor == previousPlug() ) { const int index = context->get<int>( indexVariable, 0 ); if( index >= 1 && enabledPlug()->getValue() ) { sourceLoopIndex = index - 1; return descendantPlug( nextPlug(), relativeName ); } else { return descendantPlug( inPlug(), relativeName ); } } else if( ancestor == outPlug() ) { const int iterations = iterationsPlug()->getValue(); if( iterations > 0 && enabledPlug()->getValue() ) { sourceLoopIndex = iterations - 1; return descendantPlug( nextPlug(), relativeName ); } else { return descendantPlug( inPlug(), relativeName ); } } return nullptr; } } // namespace Gaffer
11,583
4,082
} } } #endif
18
16
/* $id$ */ #include <windows.h> #include <stdio.h> #include <iostream> using namespace std; #define Size 8192 LPVOID Address; volatile unsigned long counter; DWORD __stdcall threadFunc(void *) { fprintf(stderr, "Thread start \n"); getc(stdin); return 0; } LONG MemoryExceptionFilter(_EXCEPTION_POINTERS *ExceptionInfo) { // address of exception info DWORD OldProtection; EXCEPTION_RECORD *ExRec=ExceptionInfo->ExceptionRecord; if(ExRec->ExceptionCode!=EXCEPTION_ACCESS_VIOLATION) { return EXCEPTION_CONTINUE_SEARCH; } fprintf(stderr, "Counter == %d\n", counter); cerr << (ExRec->ExceptionInformation[0]?"Write":"Read")<<"-violation at "<<(void*)ExRec->ExceptionInformation[1]<<endl; if(ExRec->ExceptionInformation[1] == 0) return EXCEPTION_CONTINUE_SEARCH; if(++counter<100) return EXCEPTION_CONTINUE_EXECUTION; else { VirtualProtect((void*)ExRec->ExceptionInformation[1],4096,PAGE_READWRITE,&OldProtection); return EXCEPTION_CONTINUE_EXECUTION; } } int main() { volatile char a = '\0'; SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)MemoryExceptionFilter); counter=0; Address=VirtualAlloc(0,Size,MEM_COMMIT,PAGE_NOACCESS); if(!Address) { cerr<<"VirtualAllocFailed!!!\n"; return 0; } DWORD id; CreateThread(0, 0, threadFunc, 0, 0, &id); //__try { ((char*)Address)[4096]=0; counter=0; a = *((char*)Address); //} __except(MemoryExceptionFilter(GetExceptionInformation())){}; return 0; }
1,507
623
// Copyright (c) 2021 The Orbit 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 "MetricsUploader/CaptureMetric.h" #include <chrono> #include <cstdint> #include <filesystem> #include "OrbitBase/File.h" #include "OrbitBase/Logging.h" #include "orbit_log_event.pb.h" namespace orbit_metrics_uploader { CaptureMetric::CaptureMetric(MetricsUploader* uploader, const CaptureStartData& start_data) : uploader_(uploader), start_(std::chrono::steady_clock::now()) { CHECK(uploader_ != nullptr); capture_data_.set_number_of_instrumented_functions(start_data.number_of_instrumented_functions); capture_data_.set_number_of_frame_tracks(start_data.number_of_frame_tracks); capture_data_.set_thread_states(start_data.thread_states); capture_data_.set_memory_information_sampling_period_ms( start_data.memory_information_sampling_period_ms); capture_data_.set_lib_orbit_vulkan_layer(start_data.lib_orbit_vulkan_layer); capture_data_.set_local_marker_depth_per_command_buffer( start_data.local_marker_depth_per_command_buffer); capture_data_.set_max_local_marker_depth_per_command_buffer( start_data.max_local_marker_depth_per_command_buffer); } void CaptureMetric::SetCaptureCompleteData(const CaptureCompleteData& complete_data) { capture_data_.set_number_of_instrumented_function_timers( complete_data.number_of_instrumented_function_timers); capture_data_.set_number_of_gpu_activity_timers(complete_data.number_of_gpu_activity_timers); capture_data_.set_number_of_vulkan_layer_gpu_command_buffer_timers( complete_data.number_of_vulkan_layer_gpu_command_buffer_timers); capture_data_.set_number_of_vulkan_layer_gpu_debug_marker_timers( complete_data.number_of_vulkan_layer_gpu_debug_marker_timers); capture_data_.set_number_of_manual_start_timers(complete_data.number_of_manual_start_timers); capture_data_.set_number_of_manual_stop_timers(complete_data.number_of_manual_stop_timers); capture_data_.set_number_of_manual_start_async_timers( complete_data.number_of_manual_start_async_timers); capture_data_.set_number_of_manual_stop_async_timers( complete_data.number_of_manual_stop_async_timers); capture_data_.set_number_of_manual_tracked_value_timers( complete_data.number_of_manual_tracked_value_timers); file_path_ = complete_data.file_path; } bool CaptureMetric::SendCaptureFailed() { auto duration = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::steady_clock::now() - start_); capture_data_.set_duration_in_milliseconds(duration.count()); status_code_ = OrbitLogEvent_StatusCode_INTERNAL_ERROR; return uploader_->SendCaptureEvent(capture_data_, status_code_); } bool CaptureMetric::SendCaptureCancelled() { auto duration = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::steady_clock::now() - start_); capture_data_.set_duration_in_milliseconds(duration.count()); status_code_ = OrbitLogEvent_StatusCode_CANCELLED; return uploader_->SendCaptureEvent(capture_data_, status_code_); } bool CaptureMetric::SendCaptureSucceeded(std::chrono::milliseconds duration_in_milliseconds) { capture_data_.set_duration_in_milliseconds(duration_in_milliseconds.count()); status_code_ = OrbitLogEvent_StatusCode_SUCCESS; if (file_path_.empty()) { ERROR("Unable to determine capture file size for metrics. File path is empty"); } else { ErrorMessageOr<uint64_t> file_size = orbit_base::FileSize(file_path_); if (file_size.has_error()) { ERROR("Unable to determine capture file size for metrics. File: \"%s\"; error: %s", file_path_.string(), file_size.error().message()); } else { capture_data_.set_file_size(file_size.value()); } } return uploader_->SendCaptureEvent(capture_data_, status_code_); } } // namespace orbit_metrics_uploader
3,940
1,358
/** * @file /kobuki_core/include/kobuki_core/modules/sound.hpp * * @brief Flags and id's for commanding sound sequences. * * License: BSD * https://raw.githubusercontent.com/kobuki-base/kobuki_core/license/LICENSE **/ /***************************************************************************** ** Ifdefs *****************************************************************************/ #ifndef KOBUKI_CORE_SOUND_HPP_ #define KOBUKI_CORE_SOUND_HPP_ /***************************************************************************** ** Includes *****************************************************************************/ /***************************************************************************** ** Namespaces *****************************************************************************/ namespace kobuki { /***************************************************************************** ** Enums *****************************************************************************/ enum SoundSequences { On = 0x0, /**< Turn on **/ Off = 0x1, /**< Turn off **/ Recharge = 0x2, /**< Recharging starting **/ Button = 0x3, /**< Button pressed **/ Error = 0x4, /**< Error sound **/ CleaningStart = 0x5, /**< Cleaning started **/ CleaningEnd = 0x6, /**< Cleaning ended **/ }; } // namespace kobuki #endif /* KOBUKI_CORE_SOUND_HPP_ */
1,354
380
/*! \file grasp/run_trials.hh \brief Performs grasp trials Run full dynamic simulated grasp trials in Gazebo \author João Borrego : jsbruglie */ #ifndef _RUN_TRIALS_HH_ #define _RUN_TRIALS_HH_ // Gazebo #include <gazebo/gazebo_client.hh> #include <gazebo/gazebo_config.h> #include <gazebo/transport/transport.hh> #include <gazebo/msgs/msgs.hh> // I/O streams #include <iostream> // Threads #include <chrono> #include <condition_variable> #include <mutex> #include <thread> // Open YAML config files #include "yaml-cpp/yaml.h" // Custom messages #include "MessageTypes.hh" // Grasp representation #include "Grasp.hh" // Rest pose utils #include "RestPose.hh" // Interface for hand plugin #include "Interface.hh" // Tools #include "object_utils.hh" // Debug streams #include "debug.hh" // Randomiser class #include "Randomiser.hh" // GAP // Custom messages #include "dr_request.pb.h" // Domain randomization plugin interface #include "DRInterface.hh" /// Config dictionary typedef std::map<std::string,std::string> Config; // Topics /// Topic monitored by hand plugin for incoming requests #define HAND_REQ_TOPIC "~/hand" /// Topic for hand plugin responses #define HAND_RES_TOPIC "~/hand/response" /// Topic monitored by target plugin for incoming requests #define TARGET_REQ_TOPIC "~/grasp/target" /// Topic for target plugin responses #define TARGET_RES_TOPIC "~/grasp/target/response" /// Topic monitored by contacts plugin for incoming requests #define CONTACT_REQ_TOPIC "~/grasp/contact" /// Topic for contacts plugin responses #define CONTACT_RES_TOPIC "~/grasp/contact/response" /// Topic monitored by camera plugin for incoming requests #define CAMERA_REQ_TOPIC "~/grasp/rgbd" /// Topic for camera plugin responses #define CAMERA_RES_TOPIC "~/grasp/rgbd/response" /// Topic for Gazebo factory utility #define FACTORY_TOPIC "~/factory" /// Topic for generic Gazebo requests #define REQUEST_TOPIC "~/request" // Type enums // Target Plugin /// Get pose request #define REQ_GET_POSE grasp::msgs::TargetRequest::GET_POSE /// Set pose request #define REQ_SET_POSE grasp::msgs::TargetRequest::SET_POSE /// Update rest pose request #define REQ_REST_POSE grasp::msgs::TargetRequest::GET_REST_POSE /// Reset request #define REQ_RESET grasp::msgs::TargetRequest::RESET /// Current pose response #define RES_POSE grasp::msgs::TargetResponse::POSE /// Updated rest pose response #define RES_REST_POSE grasp::msgs::TargetResponse::REST_POSE // Camera plugin /// Request to capture frame #define REQ_CAPTURE grasp::msgs::CameraRequest::CAPTURE // Hand plugin /// Position control #define POSITION grasp::msgs::Target::POSITION /// Velocity control #define VELOCITY grasp::msgs::Target::VELOCITY /// Invalid grasp flag #define INVALID_GRASP -1.0 // Message type definitions /// Declaration for hand message type typedef grasp::msgs::Hand HandMsg; /// Shared pointer declaration for hand message type typedef const boost::shared_ptr<const grasp::msgs::Hand> HandMsgPtr; /// Declaration for request message type typedef grasp::msgs::TargetRequest TargetRequest; /// Shared pointer declaration for request message type typedef const boost::shared_ptr<const grasp::msgs::TargetRequest> TargetRequestPtr; /// Declaration for response message type typedef grasp::msgs::TargetResponse TargetResponse; /// Shared pointer declaration for response message type typedef const boost::shared_ptr<const grasp::msgs::TargetResponse> TargetResponsePtr; /// Declaration for request aux message type typedef grasp::msgs::CollisionRequest CollisionRequest; /// Declaration for request message type typedef grasp::msgs::ContactRequest ContactRequest; /// Shared pointer declaration for request message type typedef const boost::shared_ptr<const grasp::msgs::ContactRequest> ContactRequestPtr; /// Declaration for response message type typedef grasp::msgs::ContactResponse ContactResponse; /// Shared pointer declaration for response message type typedef const boost::shared_ptr<const grasp::msgs::ContactResponse> ContactResponsePtr; /// Declaration for request message type typedef grasp::msgs::CameraRequest CameraRequest; /// Shared pointer declaration for request message type typedef const boost::shared_ptr<const grasp::msgs::CameraRequest> CameraRequestPtr; /// Declaration for response message type typedef grasp::msgs::CameraResponse CameraResponse; /// Shared pointer declaration for response message type typedef const boost::shared_ptr<const grasp::msgs::CameraResponse> CameraResponsePtr; // // Argument parsing and setup // /// \brief Obtains usage string /// \param argv_0 Name of the executable /// \return String with command-line usage const std::string getUsage(const char* argv_0); /// \brief Parses command-line arguments /// \param argc Argument count /// \param argv Arguments /// \param config Configuration YAML node void parseArgs( int argc, char** argv, Config & config); /// \brief Sets up gazebo communication pubs/subs /// \param node Gazebo communication node pointer /// \param pubs Resulting map of publishers /// \param subs Resulting map of subscribers void setupCommunications( gazebo::transport::NodePtr & node, std::map<std::string, gazebo::transport::PublisherPtr> & pubs, std::map<std::string, gazebo::transport::SubscriberPtr> & subs); // // File I/O // /// \brief Obtain list of models' names in dataset yml /// \param targets Output list of model names /// \param file_name Input dataset config yml void obtainTargets(std::vector<std::string> & targets, const std::string & file_name); /// \brief Obtain list of grasps in yml files /// \param grasp_cfg_dir Directory for grasp files /// \param robot Target robot /// \param object_name Target object name /// \param grasps Output imported grasps /// \returns Whether import was successful bool importGrasps(const std::string & grasp_cfg_dir, const std::string & robot, const std::string & object_name, std::vector<Grasp> & grasps); /// \brief Export set of metrics to file /// \param trials_out_dir Output directory /// \param robot Target robot name /// \param object_name Target object name /// \param grasps Set of grasps to export to file void exportGraspMetrics(const std::string & trials_out_dir, const std::string & robot, const std::string & object_name, const std::vector<Grasp> & grasps); // // Gazebo plugin interaction // /// \brief Sets hand pose /// \param pub Publisher to hand's topic /// \param pose New hand pose void setPose(gazebo::transport::PublisherPtr pub, ignition::math::Pose3d pose, double timeout=-1); /// \brief Requests collisions in the world /// \param pub Publisher to contact topic /// \param target The target object name /// \param hand The hand model name void checkHandCollisions(gazebo::transport::PublisherPtr pub, const std::string & hand, std::vector<std::string> & targets); /// \brief Closes manipulator fingers /// \param pub Publisher to hand topic /// \param timeout Timeout in seconds /// \warning Applies force directly void closeFingers(gazebo::transport::PublisherPtr pub, double timeout=-1); /// \brief Lifts robotic manipulator along positive z axis /// \param pub Publisher to hand topic /// \param timeout Timeout in seconds void liftHand(gazebo::transport::PublisherPtr pub, double timeout=-1); /// \brief Resets target object to rest pose /// \param pub Publisher to target's topic void resetTarget(gazebo::transport::PublisherPtr pub); /// \brief Attempts to grasp object /// \param grasp The grasp configuration /// \param pubs Map of publishers /// \param model_name Target object model name /// \return Grasp outcome metric double tryGrasp( Grasp & grasp, Interface & interface, std::map<std::string, gazebo::transport::PublisherPtr> & pubs, const std::string & model_name); // Synchronisation /// \brief Waits for condition variable /// \param timeout Timeout value in milliseconds void waitForTrigger(int timeout=-1); // Callback functions /// TODO void onHandResponse(HandMsgPtr & _msg); /// TODO void onTargetResponse(TargetResponsePtr & _msg); /// TODO void onContactResponse(ContactResponsePtr & _msg); #endif
8,282
2,490
#include <libwidget/Application.h> #include <libwidget/Widgets.h> int main(int argc, char **argv) { if (argc == 1) return -1; if (application_initialize(argc, argv) != SUCCESS) return -1; Window *window = new Window(WINDOW_RESIZABLE); window->icon(Icon::get("image")); window->title("Image Viewer"); window->size(Vec2i(700, 500)); new Image(window->root(), Bitmap::load_from_or_placeholder(argv[1])); window->show(); return application_run(); }
504
183