hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
3e44eb4db7fccd753548c8b070bc1e70816e9f87
2,359
hpp
C++
liero/ai/work_queue.hpp
lauri-kaariainen/emscripten_openliero
ab3268237c7084e00f3bccb4442f0ad7762d8419
[ "BSD-2-Clause" ]
null
null
null
liero/ai/work_queue.hpp
lauri-kaariainen/emscripten_openliero
ab3268237c7084e00f3bccb4442f0ad7762d8419
[ "BSD-2-Clause" ]
2
2015-02-11T09:43:33.000Z
2015-02-11T17:57:58.000Z
liero/ai/work_queue.hpp
lauri-kaariainen/emscripten_openliero
ab3268237c7084e00f3bccb4442f0ad7762d8419
[ "BSD-2-Clause" ]
null
null
null
#ifndef LIERO_WORK_QUEUE_HPP #define LIERO_WORK_QUEUE_HPP #include <SDL/SDL.h> #include <vector> #include "tl/memory.h" #include <memory> struct LockMutex { LockMutex(SDL_mutex* m) : m(m) { SDL_LockMutex(m); } ~LockMutex() { SDL_UnlockMutex(m); } SDL_mutex* m; }; struct Work { Work() : done_(false) { mutex = SDL_CreateMutex(); stateCond = SDL_CreateCond(); } ~Work() { SDL_DestroyMutex(mutex); SDL_DestroyCond(stateCond); } bool waitDone() { LockMutex m(mutex); while (!done_) SDL_CondWait(stateCond, mutex); return done_; } bool done_; SDL_mutex* mutex; SDL_cond* stateCond; void run() { doRun(); { LockMutex m(mutex); done_ = true; TL_WRITE_SYNC(); SDL_CondSignal(stateCond); } } virtual void doRun() = 0; }; struct StopWorker { }; struct WorkQueue { WorkQueue(int threadCount) : queueAlive(true) { queueMutex = SDL_CreateMutex(); queueCond = SDL_CreateCond(); std::memset(threads, 0, sizeof(threads)); for (int i = 0; i < threadCount; ++i) { threads[i] = SDL_CreateThread(worker, this); } } ~WorkQueue() { { LockMutex m(queueMutex); queueAlive = false; SDL_CondBroadcast(queueCond); } for (int i = 0; i < 8; ++i) { int status; if (threads[i]) SDL_WaitThread(threads[i], &status); } SDL_DestroyMutex(queueMutex); SDL_DestroyCond(queueCond); } void add(std::unique_ptr<Work> work) { LockMutex m(queueMutex); queue.push_back(std::move(work)); SDL_CondSignal(queueCond); } std::unique_ptr<Work> waitForWork() { LockMutex m(queueMutex); while (queue.empty() && queueAlive) SDL_CondWait(queueCond, queueMutex); if (!queueAlive) throw StopWorker(); auto ret = std::move(queue[0]); queue.erase(queue.begin()); return ret; } static int worker(void* self) { try { WorkQueue* queue = static_cast<WorkQueue*>(self); while (true) { auto work = queue->waitForWork(); work->run(); } } catch (StopWorker&) { } return 0; } SDL_mutex* queueMutex; SDL_cond* queueCond; std::vector<std::unique_ptr<Work>> queue; bool queueAlive; SDL_Thread* threads[8]; }; #endif // LIERO_WORK_QUEUE_HPP
14.561728
53
0.600678
[ "vector" ]
3e47fdd538b148c7c314a861f87dd937239a8c00
1,191
cpp
C++
Problem1-50/p19_1.cpp
dingqunfei/LeetCode
c74a21ea56ee7b35308d2f387ef24ab29b031e24
[ "Apache-2.0" ]
null
null
null
Problem1-50/p19_1.cpp
dingqunfei/LeetCode
c74a21ea56ee7b35308d2f387ef24ab29b031e24
[ "Apache-2.0" ]
null
null
null
Problem1-50/p19_1.cpp
dingqunfei/LeetCode
c74a21ea56ee7b35308d2f387ef24ab29b031e24
[ "Apache-2.0" ]
null
null
null
/** * @file p19_1.cpp * @brief * @author dingqunfei (dqflying@gmail.com) * @version 1.0 * @date 2021-08-26 * * @copyright Copyright (c) 2021 DQFLYING * * @par : * * * Date : 2021-08-26 * Version : 1.0 * Author : dqflying * Lisence : * Description : * * * * */ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { vector<ListNode*> headVec; ListNode *p = head; while(p) { headVec.push_back(p); p = p->next; } int size = headVec.size(); int left = size-n-1, right = size-n+1; if(left < 0) { head = head->next; return head; } if(right >= size) { headVec[size-2]->next = NULL; return head; } headVec[left]->next = headVec[right]; return head; } };
19.85
62
0.482788
[ "vector" ]
3e4ab340375c957d5cc3224fdfb3c25a9af11409
8,061
cpp
C++
src/main.cpp
mmfarrington/pizza_shop
470404540d8355e99800e5070eb4f4600ddae07b
[ "MIT" ]
null
null
null
src/main.cpp
mmfarrington/pizza_shop
470404540d8355e99800e5070eb4f4600ddae07b
[ "MIT" ]
null
null
null
src/main.cpp
mmfarrington/pizza_shop
470404540d8355e99800e5070eb4f4600ddae07b
[ "MIT" ]
null
null
null
/* main.cpp * Miriam Farrington * CIS 554-M401 Object Oriented Programming in C++ * Syracuse University * Final Project Submission: Pizza Shop App * 3/15/2020 * * This program implements a basic online ordering system for a small Pizza Shop. * The app allows the user to select items from a menu, create an order, view the order and checkout * */ #include <iostream> #include <zconf.h> #include "Menu.h" #include "Order.h" #include "Invoice.h" #include "Helper.h" using namespace special_functions; using std::cout; using std::cin; using std::endl; int main() { sleep(1); printBanner(); //variable to store the customer's selection int custResponse = 0; // --- Object Initialization --- // /* * Not all objects are created here, we try to do lazy initialization only when the object is needed */ // Create and the customer Menu object Menu shopMenu; //create a new Customer Order object - currently the shop supports only 1 order per customer Order customerOrder; //Print initial welcome message to the customer cout << "Welcome to the Online Pizza Shop! " << endl; while (custResponse >= 0) { sleep(1); lineBreak(1); cout << "\x1b[32m ----- MAIN MENU -----\x1b[0m " <<endl; cout << "\x1b[32m 1) View Food & Beverage Menu \x1b[0m" << endl; cout << "\x1b[32m 2) Order Items \x1b[0m" << endl; cout << "\x1b[32m 3) View Cart \x1b[0m" << endl; cout << "\x1b[32m 4) Checkout \x1b[0m" << endl; lineBreak(2); cout << "\x1b[31mTo get started, select an option above or -1 to Exit : \x1b[0m "; cin >> custResponse; //read in the user's choice /* ----- Start Input Validations ----- */ validateCin(custResponse); //first check the user has actually entered an integer while (custResponse > 4 || custResponse < -1) //Check a valid value is entered, otherwise prompt the user to re-enter { reset(custResponse); //reset & re-enter the value } if (custResponse == 1) { // 'View Menu' Selection lineBreak(1); cout << "\x1b[32m ----- Full Food & Beverage Menu -----\x1b[0m " << endl; shopMenu.printMenu(); //Call redirect to the main menu menuRedirect(custResponse,1); } if (custResponse == 2) { // 'Order Items' Selection int orderTypeSelection = 0; //store the customer's response //Prompt the customer to enter the type of order they want sleep(1); lineBreak(1); cout << "Select your order type: 1) DINE-IN 2) TAKE-OUT 3) DELIVERY: "; cin >> orderTypeSelection; validateCin(orderTypeSelection); //check the new entered value is an integer while (orderTypeSelection < 0 || orderTypeSelection > 4) { reset(orderTypeSelection); //reset & re-enter the value } //set the customer's order type choice once it is validated customerOrder.setOrderType(static_cast<Order::orderTypes>(orderTypeSelection)); //call the overloaded print function to print out the correct menu shopMenu.printMenu(orderTypeSelection); orderTypeSelection = 0; //reset the order type variable while (orderTypeSelection >= 0) { //While the customer has chosen to continue adding items to order... cout << "\x1b[31mSelect a Menu Item to add to your order: \x1b[0m"; cin >> orderTypeSelection; validateCin(orderTypeSelection); //ensure the customer cannot order items which are not listed in the menu while (orderTypeSelection == 0 || orderTypeSelection > shopMenu.getMenuItems().size()) { reset(orderTypeSelection); //reset & re-enter the value } int quantitySelect = 0; cout << "\x1b[31mEnter quantity (1-10): \x1b[0m"; cin >> quantitySelect; validateCin(quantitySelect); while (quantitySelect <= 0 || quantitySelect > 10) { reset(quantitySelect); //reset & re-enter the value } //Next, retrieve the menu item that corresponds to the customer's choice (offset index -1) Item* selection = shopMenu.getMenuItem(orderTypeSelection-1); //Update the item's quantity field selection->setItemQuantity(quantitySelect); //Add the customer's selected item to the customer's order customerOrder.addOrderItem(selection); //Call order redirect at the end menuRedirect(orderTypeSelection, 2); } cout << "Finished Adding items to cart." << endl; lineBreak(1); int paymentInp = 0; //customer payment selection //Prompt the user to select a payment method to apply to the order cout << "\x1b[31mSelect a payment method for your order 1) CASH 2) CARD: \x1b[0m"; cin >> paymentInp; /* ----- Start Payment Validations ----- */ //todo: Add more detailed payment validation logic here validateCin(paymentInp); while (paymentInp < 1 || paymentInp > 2){ reset(paymentInp); //reset the value while invalid } /* ----- End Payment Validations ----- */ //add the customer's Payment to the order if (paymentInp == 1) { //for now we are defaulting all orders to USD, but can expand to allow other currencies here customerOrder.addPaymentTypeToOrder(paymentInp, true,1); } if (paymentInp == 2){ int cardType; cout << "Select 1) CREDIT or 2) DEBIT: "; cin >> cardType; validateCin(cardType); while (cardType < 1 || cardType > 2){ reset(cardType); } //Call function with customer's input selection customerOrder.addPaymentTypeToOrder(paymentInp, true, cardType); } // let the customer know the order is complete and to view the cart contents from the main menu. lineBreak(1); cout << "Order Complete. View your Cart or Checkout from the Main Menu" << endl; lineBreak(1); sleep(1); } if (custResponse == 3) { // ' View Cart' Selection if (!customerOrder.getOrderItems().empty()) { //show the order details customerOrder.printOrderDetails(); //prompt redirect to the main menu menuRedirect(custResponse,3); } else { lineBreak(1); cout << "Cart is Empty. Please place an order from the Main Menu first." << endl; lineBreak(1); } } if (custResponse == 4) { // 'Checkout' Selection //before creating an invoice, first check if the customer has items added to the order if (!customerOrder.getOrderItems().empty()) { //create the Invoice object Invoice customerInvoice(customerOrder); //calculate the Invoice totals customerInvoice.calculateInvoice(); //print out the total invoice customerInvoice.printInvoiceDetails(); //Place order customerOrder.placeOrder(); //prompt redirect to the main menu menuRedirect(custResponse,1); } else { lineBreak(1); cout << "Order is Empty. Please place an Order from the Main Menu first." << endl; lineBreak(1); } } } cout << "Exiting Program." ; }
35.355263
114
0.561965
[ "object" ]
3e4f224f4847df2d0c88e9f86735060f159cec20
18,539
cpp
C++
src/rest/resource.cpp
rednodelabs/ot-br-posix
512ab0ebd379c06c7d1dc45668fbc341a742ea39
[ "BSD-3-Clause" ]
82
2016-06-29T17:24:43.000Z
2021-04-16T06:49:17.000Z
src/rest/resource.cpp
rednodelabs/ot-br-posix
512ab0ebd379c06c7d1dc45668fbc341a742ea39
[ "BSD-3-Clause" ]
202
2021-04-16T08:05:06.000Z
2022-03-31T11:20:44.000Z
src/rest/resource.cpp
rednodelabs/ot-br-posix
512ab0ebd379c06c7d1dc45668fbc341a742ea39
[ "BSD-3-Clause" ]
56
2016-08-02T10:50:50.000Z
2021-07-19T08:57:34.000Z
/* * Copyright (c) 2020, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #define OTBR_LOG_TAG "REST" #include "rest/resource.hpp" #include "string.h" #define OT_PSKC_MAX_LENGTH 16 #define OT_EXTENDED_PANID_LENGTH 8 #define OT_REST_RESOURCE_PATH_DIAGNOETIC "/diagnostics" #define OT_REST_RESOURCE_PATH_NODE "/node" #define OT_REST_RESOURCE_PATH_NODE_RLOC "/node/rloc" #define OT_REST_RESOURCE_PATH_NODE_RLOC16 "/node/rloc16" #define OT_REST_RESOURCE_PATH_NODE_EXTADDRESS "/node/ext-address" #define OT_REST_RESOURCE_PATH_NODE_STATE "/node/state" #define OT_REST_RESOURCE_PATH_NODE_NETWORKNAME "/node/network-name" #define OT_REST_RESOURCE_PATH_NODE_LEADERDATA "/node/leader-data" #define OT_REST_RESOURCE_PATH_NODE_NUMOFROUTER "/node/num-of-router" #define OT_REST_RESOURCE_PATH_NODE_EXTPANID "/node/ext-panid" #define OT_REST_RESOURCE_PATH_NETWORK "/networks" #define OT_REST_RESOURCE_PATH_NETWORK_CURRENT "/networks/current" #define OT_REST_RESOURCE_PATH_NETWORK_CURRENT_COMMISSION "/networks/commission" #define OT_REST_RESOURCE_PATH_NETWORK_CURRENT_PREFIX "/networks/current/prefix" #define OT_REST_HTTP_STATUS_200 "200 OK" #define OT_REST_HTTP_STATUS_404 "404 Not Found" #define OT_REST_HTTP_STATUS_405 "405 Method Not Allowed" #define OT_REST_HTTP_STATUS_408 "408 Request Timeout" #define OT_REST_HTTP_STATUS_500 "500 Internal Server Error" using std::chrono::duration_cast; using std::chrono::microseconds; using std::chrono::steady_clock; using std::placeholders::_1; using std::placeholders::_2; namespace otbr { namespace rest { // MulticastAddr static const char *kMulticastAddrAllRouters = "ff03::2"; // Default TlvTypes for Diagnostic inforamtion static const uint8_t kAllTlvTypes[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 14, 15, 16, 17, 19}; // Timeout (in Microseconds) for deleting outdated diagnostics static const uint32_t kDiagResetTimeout = 3000000; // Timeout (in Microseconds) for collecting diagnostics static const uint32_t kDiagCollectTimeout = 2000000; static std::string GetHttpStatus(HttpStatusCode aErrorCode) { std::string httpStatus; switch (aErrorCode) { case HttpStatusCode::kStatusOk: httpStatus = OT_REST_HTTP_STATUS_200; break; case HttpStatusCode::kStatusResourceNotFound: httpStatus = OT_REST_HTTP_STATUS_404; break; case HttpStatusCode::kStatusMethodNotAllowed: httpStatus = OT_REST_HTTP_STATUS_405; break; case HttpStatusCode::kStatusRequestTimeout: httpStatus = OT_REST_HTTP_STATUS_408; break; case HttpStatusCode::kStatusInternalServerError: httpStatus = OT_REST_HTTP_STATUS_500; break; } return httpStatus; } Resource::Resource(ControllerOpenThread *aNcp) : mNcp(aNcp) { mInstance = mNcp->GetThreadHelper()->GetInstance(); // Resource Handler mResourceMap.emplace(OT_REST_RESOURCE_PATH_DIAGNOETIC, &Resource::Diagnostic); mResourceMap.emplace(OT_REST_RESOURCE_PATH_NODE, &Resource::NodeInfo); mResourceMap.emplace(OT_REST_RESOURCE_PATH_NODE_STATE, &Resource::State); mResourceMap.emplace(OT_REST_RESOURCE_PATH_NODE_EXTADDRESS, &Resource::ExtendedAddr); mResourceMap.emplace(OT_REST_RESOURCE_PATH_NODE_NETWORKNAME, &Resource::NetworkName); mResourceMap.emplace(OT_REST_RESOURCE_PATH_NODE_RLOC16, &Resource::Rloc16); mResourceMap.emplace(OT_REST_RESOURCE_PATH_NODE_LEADERDATA, &Resource::LeaderData); mResourceMap.emplace(OT_REST_RESOURCE_PATH_NODE_NUMOFROUTER, &Resource::NumOfRoute); mResourceMap.emplace(OT_REST_RESOURCE_PATH_NODE_EXTPANID, &Resource::ExtendedPanId); mResourceMap.emplace(OT_REST_RESOURCE_PATH_NODE_RLOC, &Resource::Rloc); // Resource callback handler mResourceCallbackMap.emplace(OT_REST_RESOURCE_PATH_DIAGNOETIC, &Resource::HandleDiagnosticCallback); } void Resource::Init(void) { } void Resource::Handle(Request &aRequest, Response &aResponse) const { std::string url = aRequest.GetUrl(); auto it = mResourceMap.find(url); if (it != mResourceMap.end()) { ResourceHandler resourceHandler = it->second; (this->*resourceHandler)(aRequest, aResponse); } else { ErrorHandler(aResponse, HttpStatusCode::kStatusResourceNotFound); } } void Resource::HandleCallback(Request &aRequest, Response &aResponse) { std::string url = aRequest.GetUrl(); auto it = mResourceCallbackMap.find(url); if (it != mResourceCallbackMap.end()) { ResourceCallbackHandler resourceHandler = it->second; (this->*resourceHandler)(aRequest, aResponse); } } void Resource::HandleDiagnosticCallback(const Request &aRequest, Response &aResponse) { OT_UNUSED_VARIABLE(aRequest); std::vector<std::vector<otNetworkDiagTlv>> diagContentSet; std::string body; std::string errorCode; auto duration = duration_cast<microseconds>(steady_clock::now() - aResponse.GetStartTime()).count(); if (duration >= kDiagCollectTimeout) { DeleteOutDatedDiagnostic(); for (auto it = mDiagSet.begin(); it != mDiagSet.end(); ++it) { diagContentSet.push_back(it->second.mDiagContent); } body = Json::Diag2JsonString(diagContentSet); errorCode = GetHttpStatus(HttpStatusCode::kStatusOk); aResponse.SetResponsCode(errorCode); aResponse.SetBody(body); aResponse.SetComplete(); } } void Resource::ErrorHandler(Response &aResponse, HttpStatusCode aErrorCode) const { std::string errorMessage = GetHttpStatus(aErrorCode); std::string body = Json::Error2JsonString(aErrorCode, errorMessage); aResponse.SetResponsCode(errorMessage); aResponse.SetBody(body); aResponse.SetComplete(); } void Resource::GetNodeInfo(Response &aResponse) const { otbrError error = OTBR_ERROR_NONE; struct NodeInfo node; otRouterInfo routerInfo; uint8_t maxRouterId; std::string body; std::string errorCode; VerifyOrExit(otThreadGetLeaderData(mInstance, &node.mLeaderData) == OT_ERROR_NONE, error = OTBR_ERROR_REST); node.mNumOfRouter = 0; maxRouterId = otThreadGetMaxRouterId(mInstance); for (uint8_t i = 0; i <= maxRouterId; ++i) { if (otThreadGetRouterInfo(mInstance, i, &routerInfo) != OT_ERROR_NONE) { continue; } ++node.mNumOfRouter; } node.mRole = otThreadGetDeviceRole(mInstance); node.mExtAddress = reinterpret_cast<const uint8_t *>(otLinkGetExtendedAddress(mInstance)); node.mNetworkName = otThreadGetNetworkName(mInstance); node.mRloc16 = otThreadGetRloc16(mInstance); node.mExtPanId = reinterpret_cast<const uint8_t *>(otThreadGetExtendedPanId(mInstance)); node.mRlocAddress = *otThreadGetRloc(mInstance); body = Json::Node2JsonString(node); aResponse.SetBody(body); exit: if (error == OTBR_ERROR_NONE) { errorCode = GetHttpStatus(HttpStatusCode::kStatusOk); aResponse.SetResponsCode(errorCode); } else { ErrorHandler(aResponse, HttpStatusCode::kStatusInternalServerError); } } void Resource::NodeInfo(const Request &aRequest, Response &aResponse) const { std::string errorCode; if (aRequest.GetMethod() == HttpMethod::kGet) { GetNodeInfo(aResponse); } else { ErrorHandler(aResponse, HttpStatusCode::kStatusMethodNotAllowed); } } void Resource::GetDataExtendedAddr(Response &aResponse) const { const uint8_t *extAddress = reinterpret_cast<const uint8_t *>(otLinkGetExtendedAddress(mInstance)); std::string errorCode; std::string body = Json::Bytes2HexJsonString(extAddress, OT_EXT_ADDRESS_SIZE); aResponse.SetBody(body); errorCode = GetHttpStatus(HttpStatusCode::kStatusOk); aResponse.SetResponsCode(errorCode); } void Resource::ExtendedAddr(const Request &aRequest, Response &aResponse) const { std::string errorCode; if (aRequest.GetMethod() == HttpMethod::kGet) { GetDataExtendedAddr(aResponse); } else { ErrorHandler(aResponse, HttpStatusCode::kStatusMethodNotAllowed); } } void Resource::GetDataState(Response &aResponse) const { std::string state; std::string errorCode; uint8_t role; // 0 : disabled // 1 : detached // 2 : child // 3 : router // 4 : leader role = otThreadGetDeviceRole(mInstance); state = Json::Number2JsonString(role); aResponse.SetBody(state); errorCode = GetHttpStatus(HttpStatusCode::kStatusOk); aResponse.SetResponsCode(errorCode); } void Resource::State(const Request &aRequest, Response &aResponse) const { std::string errorCode; if (aRequest.GetMethod() == HttpMethod::kGet) { GetDataState(aResponse); } else { ErrorHandler(aResponse, HttpStatusCode::kStatusMethodNotAllowed); } } void Resource::GetDataNetworkName(Response &aResponse) const { std::string networkName; std::string errorCode; networkName = otThreadGetNetworkName(mInstance); networkName = Json::String2JsonString(networkName); aResponse.SetBody(networkName); errorCode = GetHttpStatus(HttpStatusCode::kStatusOk); aResponse.SetResponsCode(errorCode); } void Resource::NetworkName(const Request &aRequest, Response &aResponse) const { std::string errorCode; if (aRequest.GetMethod() == HttpMethod::kGet) { GetDataNetworkName(aResponse); } else { ErrorHandler(aResponse, HttpStatusCode::kStatusMethodNotAllowed); } } void Resource::GetDataLeaderData(Response &aResponse) const { otbrError error = OTBR_ERROR_NONE; otLeaderData leaderData; std::string body; std::string errorCode; VerifyOrExit(otThreadGetLeaderData(mInstance, &leaderData) == OT_ERROR_NONE, error = OTBR_ERROR_REST); body = Json::LeaderData2JsonString(leaderData); aResponse.SetBody(body); exit: if (error == OTBR_ERROR_NONE) { errorCode = GetHttpStatus(HttpStatusCode::kStatusOk); aResponse.SetResponsCode(errorCode); } else { ErrorHandler(aResponse, HttpStatusCode::kStatusInternalServerError); } } void Resource::LeaderData(const Request &aRequest, Response &aResponse) const { std::string errorCode; if (aRequest.GetMethod() == HttpMethod::kGet) { GetDataLeaderData(aResponse); } else { ErrorHandler(aResponse, HttpStatusCode::kStatusMethodNotAllowed); } } void Resource::GetDataNumOfRoute(Response &aResponse) const { uint8_t count = 0; uint8_t maxRouterId; otRouterInfo routerInfo; maxRouterId = otThreadGetMaxRouterId(mInstance); std::string body; std::string errorCode; for (uint8_t i = 0; i <= maxRouterId; ++i) { if (otThreadGetRouterInfo(mInstance, i, &routerInfo) != OT_ERROR_NONE) { continue; } ++count; } body = Json::Number2JsonString(count); aResponse.SetBody(body); errorCode = GetHttpStatus(HttpStatusCode::kStatusOk); aResponse.SetResponsCode(errorCode); } void Resource::NumOfRoute(const Request &aRequest, Response &aResponse) const { std::string errorCode; if (aRequest.GetMethod() == HttpMethod::kGet) { GetDataNumOfRoute(aResponse); } else { ErrorHandler(aResponse, HttpStatusCode::kStatusMethodNotAllowed); } } void Resource::GetDataRloc16(Response &aResponse) const { uint16_t rloc16 = otThreadGetRloc16(mInstance); std::string body; std::string errorCode; body = Json::Number2JsonString(rloc16); aResponse.SetBody(body); errorCode = GetHttpStatus(HttpStatusCode::kStatusOk); aResponse.SetResponsCode(errorCode); } void Resource::Rloc16(const Request &aRequest, Response &aResponse) const { std::string errorCode; if (aRequest.GetMethod() == HttpMethod::kGet) { GetDataRloc16(aResponse); } else { ErrorHandler(aResponse, HttpStatusCode::kStatusMethodNotAllowed); } } void Resource::GetDataExtendedPanId(Response &aResponse) const { const uint8_t *extPanId = reinterpret_cast<const uint8_t *>(otThreadGetExtendedPanId(mInstance)); std::string body = Json::Bytes2HexJsonString(extPanId, OT_EXT_PAN_ID_SIZE); std::string errorCode; aResponse.SetBody(body); errorCode = GetHttpStatus(HttpStatusCode::kStatusOk); aResponse.SetResponsCode(errorCode); } void Resource::ExtendedPanId(const Request &aRequest, Response &aResponse) const { std::string errorCode; if (aRequest.GetMethod() == HttpMethod::kGet) { GetDataExtendedPanId(aResponse); } else { ErrorHandler(aResponse, HttpStatusCode::kStatusMethodNotAllowed); } } void Resource::GetDataRloc(Response &aResponse) const { otIp6Address rlocAddress = *otThreadGetRloc(mInstance); std::string body; std::string errorCode; body = Json::IpAddr2JsonString(rlocAddress); aResponse.SetBody(body); errorCode = GetHttpStatus(HttpStatusCode::kStatusOk); aResponse.SetResponsCode(errorCode); } void Resource::Rloc(const Request &aRequest, Response &aResponse) const { std::string errorCode; if (aRequest.GetMethod() == HttpMethod::kGet) { GetDataRloc(aResponse); } else { ErrorHandler(aResponse, HttpStatusCode::kStatusMethodNotAllowed); } } void Resource::DeleteOutDatedDiagnostic(void) { auto eraseIt = mDiagSet.begin(); for (eraseIt = mDiagSet.begin(); eraseIt != mDiagSet.end();) { auto diagInfo = eraseIt->second; auto duration = duration_cast<microseconds>(steady_clock::now() - diagInfo.mStartTime).count(); if (duration >= kDiagResetTimeout) { eraseIt = mDiagSet.erase(eraseIt); } else { eraseIt++; } } } void Resource::UpdateDiag(std::string aKey, std::vector<otNetworkDiagTlv> &aDiag) { DiagInfo value; value.mStartTime = steady_clock::now(); value.mDiagContent.assign(aDiag.begin(), aDiag.end()); mDiagSet[aKey] = value; } void Resource::Diagnostic(const Request &aRequest, Response &aResponse) const { otbrError error = OTBR_ERROR_NONE; OT_UNUSED_VARIABLE(aRequest); struct otIp6Address rloc16address = *otThreadGetRloc(mInstance); struct otIp6Address multicastAddress; VerifyOrExit(otThreadSendDiagnosticGet(mInstance, &rloc16address, kAllTlvTypes, sizeof(kAllTlvTypes), &Resource::DiagnosticResponseHandler, const_cast<Resource *>(this)) == OT_ERROR_NONE, error = OTBR_ERROR_REST); VerifyOrExit(otIp6AddressFromString(kMulticastAddrAllRouters, &multicastAddress) == OT_ERROR_NONE, error = OTBR_ERROR_REST); VerifyOrExit(otThreadSendDiagnosticGet(mInstance, &multicastAddress, kAllTlvTypes, sizeof(kAllTlvTypes), &Resource::DiagnosticResponseHandler, const_cast<Resource *>(this)) == OT_ERROR_NONE, error = OTBR_ERROR_REST); exit: if (error == OTBR_ERROR_NONE) { aResponse.SetStartTime(steady_clock::now()); aResponse.SetCallback(); } else { ErrorHandler(aResponse, HttpStatusCode::kStatusInternalServerError); } } void Resource::DiagnosticResponseHandler(otError aError, otMessage * aMessage, const otMessageInfo *aMessageInfo, void * aContext) { static_cast<Resource *>(aContext)->DiagnosticResponseHandler(aError, aMessage, aMessageInfo); } void Resource::DiagnosticResponseHandler(otError aError, const otMessage *aMessage, const otMessageInfo *aMessageInfo) { std::vector<otNetworkDiagTlv> diagSet; otNetworkDiagTlv diagTlv; otNetworkDiagIterator iterator = OT_NETWORK_DIAGNOSTIC_ITERATOR_INIT; otError error; char rloc[7]; std::string keyRloc = "0xffee"; SuccessOrExit(aError); OTBR_UNUSED_VARIABLE(aMessageInfo); while ((error = otThreadGetNextDiagnosticTlv(aMessage, &iterator, &diagTlv)) == OT_ERROR_NONE) { if (diagTlv.mType == OT_NETWORK_DIAGNOSTIC_TLV_SHORT_ADDRESS) { sprintf(rloc, "0x%04x", diagTlv.mData.mAddr16); keyRloc = Json::CString2JsonString(rloc); } diagSet.push_back(diagTlv); } UpdateDiag(keyRloc, diagSet); exit: if (aError != OT_ERROR_NONE) { otbrLogWarning("Failed to get diagnostic data: %s", otThreadErrorToString(aError)); } } } // namespace rest } // namespace otbr
31.315878
118
0.695075
[ "vector" ]
3e542df6a8ebbcc84780fa14cb9698faa8023785
100,943
cc
C++
chrome/credential_provider/gaiacp/gaia_credential_base.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-10-18T02:33:40.000Z
2020-10-18T02:33:40.000Z
chrome/credential_provider/gaiacp/gaia_credential_base.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2021-05-17T16:28:52.000Z
2021-05-21T22:42:22.000Z
chrome/credential_provider/gaiacp/gaia_credential_base.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2018 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. // Implementation of CGaiaCredentialBase class, used as the base for all // credentials that need to show the gaia sign in page. #include "chrome/credential_provider/gaiacp/gaia_credential_base.h" #include <ntstatus.h> #include <algorithm> #include <memory> #include <utility> #include "base/bind.h" #include "base/callback_helpers.h" #include "base/command_line.h" #include "base/cxx17_backports.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/json/json_reader.h" #include "base/json/json_writer.h" #include "base/path_service.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/time/time.h" #include "base/values.h" #include "base/win/current_module.h" #include "base/win/registry.h" #include "base/win/scoped_com_initializer.h" #include "base/win/scoped_handle.h" #include "build/branding_buildflags.h" #include "chrome/common/chrome_switches.h" #include "chrome/credential_provider/common/gcp_strings.h" #include "chrome/credential_provider/gaiacp/associated_user_validator.h" #include "chrome/credential_provider/gaiacp/auth_utils.h" #include "chrome/credential_provider/gaiacp/device_policies_manager.h" #include "chrome/credential_provider/gaiacp/event_logs_upload_manager.h" #include "chrome/credential_provider/gaiacp/experiments_fetcher.h" #include "chrome/credential_provider/gaiacp/experiments_manager.h" #include "chrome/credential_provider/gaiacp/gaia_credential_provider.h" #include "chrome/credential_provider/gaiacp/gaia_credential_provider_i.h" #include "chrome/credential_provider/gaiacp/gaia_resources.h" #include "chrome/credential_provider/gaiacp/gcp_utils.h" #include "chrome/credential_provider/gaiacp/gcpw_strings.h" #include "chrome/credential_provider/gaiacp/gem_device_details_manager.h" #include "chrome/credential_provider/gaiacp/grit/gaia_static_resources.h" #include "chrome/credential_provider/gaiacp/internet_availability_checker.h" #include "chrome/credential_provider/gaiacp/logging.h" #include "chrome/credential_provider/gaiacp/mdm_utils.h" #include "chrome/credential_provider/gaiacp/os_process_manager.h" #include "chrome/credential_provider/gaiacp/os_user_manager.h" #include "chrome/credential_provider/gaiacp/password_recovery_manager.h" #include "chrome/credential_provider/gaiacp/reg_utils.h" #include "chrome/credential_provider/gaiacp/scoped_lsa_policy.h" #include "chrome/credential_provider/gaiacp/scoped_user_profile.h" #include "chrome/credential_provider/gaiacp/user_policies_manager.h" #include "chrome/credential_provider/gaiacp/win_http_url_fetcher.h" #include "chrome/installer/launcher_support/chrome_launcher_support.h" #include "content/public/common/content_switches.h" #include "google_apis/gaia/gaia_auth_util.h" #include "google_apis/gaia/gaia_switches.h" #include "google_apis/gaia/gaia_urls.h" #include "net/base/escape.h" #include "net/base/registry_controlled_domains/registry_controlled_domain.h" #include "third_party/re2/src/re2/re2.h" namespace credential_provider { namespace { constexpr wchar_t kPermittedAccounts[] = L"permitted_accounts"; constexpr wchar_t kPermittedAccountsSeparator[] = L","; constexpr char kGetAccessTokenBodyWithScopeFormat[] = "client_id=%s&" "client_secret=%s&" "grant_type=refresh_token&" "refresh_token=%s&" "scope=%s"; constexpr wchar_t kRegCloudAssociation[] = L"enable_cloud_association"; // The access scopes should be separated by single space. constexpr char kAccessScopes[] = "https://www.googleapis.com/auth/admin.directory.user"; constexpr int kHttpTimeout = 3000; // in milliseconds // Names of keys used to fetch the custom attributes from google admin sdk // users directory api. constexpr char kKeyCustomSchemas[] = "customSchemas"; constexpr char kKeyEnhancedDesktopSecurity[] = "Enhanced_desktop_security"; constexpr char kKeyADAccounts[] = "AD_accounts"; constexpr char kKeyLocalWindowsAccounts[] = "Local_Windows_accounts"; // List of errors where Windows returns during password change that can't be // worked out with manual user input during forgot password flow. constexpr UINT kPasswordErrors[] = {IDS_PASSWORD_COMPLEXITY_ERROR_BASE, IDS_USER_NOT_FOUND_PASSWORD_ERROR_BASE, IDS_AD_PASSWORD_CHANGE_DENIED_BASE}; std::vector<std::wstring> GetPermittedAccounts() { std::wstring permitted_accounts_reg = GetGlobalFlagOrDefault(kPermittedAccounts, L""); return base::SplitString(base::ToLowerASCII(permitted_accounts_reg), kPermittedAccountsSeparator, base::WhitespaceHandling::TRIM_WHITESPACE, base::SplitResult::SPLIT_WANT_NONEMPTY); } std::wstring GetEmailDomains(const std::wstring restricted_domains_reg_key) { return GetGlobalFlagOrDefault(restricted_domains_reg_key, L""); } std::wstring GetEmailDomains() { if (DevicePoliciesManager::Get()->CloudPoliciesEnabled()) { DevicePolicies device_policies; DevicePoliciesManager::Get()->GetDevicePolicies(&device_policies); return device_policies.GetAllowedDomainsStr(); } // TODO (crbug.com/1135458): Clean up directly reading from registry after // cloud policies is launched. std::wstring email_domains_reg = GetEmailDomains(kEmailDomainsKey); std::wstring email_domains_reg_new = GetEmailDomains(kEmailDomainsKeyNew); return email_domains_reg.empty() ? email_domains_reg_new : email_domains_reg; } // Use WinHttpUrlFetcher to communicate with the admin sdk and fetch the active // directory samAccountName if available and list of local account name mapping // configured as custom attributes. HRESULT GetExistingAccountMappingFromCD( const std::wstring& email, const std::string& access_token, std::string* sam_account_name, std::vector<std::string>* local_account_names, BSTR* error_text) { DCHECK(email.size() > 0); DCHECK(access_token.size() > 0); DCHECK(sam_account_name); DCHECK(local_account_names); DCHECK(error_text); *error_text = nullptr; std::string escape_url_encoded_email = net::EscapeUrlEncodedData(base::WideToUTF8(email), true); std::string get_cd_user_url = base::StringPrintf( "https://www.googleapis.com/admin/directory/v1/users/" "%s?projection=full&viewType=domain_public", escape_url_encoded_email.c_str()); LOGFN(VERBOSE) << "Encoded URL : " << get_cd_user_url; auto fetcher = WinHttpUrlFetcher::Create(GURL(get_cd_user_url)); fetcher->SetRequestHeader("Accept", "application/json"); fetcher->SetHttpRequestTimeout(kHttpTimeout); std::string access_token_header = base::StringPrintf("Bearer %s", access_token.c_str()); fetcher->SetRequestHeader("Authorization", access_token_header.c_str()); std::vector<char> cd_user_response; HRESULT hr = fetcher->Fetch(&cd_user_response); std::string cd_user_response_json_string = std::string(cd_user_response.begin(), cd_user_response.end()); if (FAILED(hr)) { LOGFN(ERROR) << "fetcher->Fetch hr=" << putHR(hr); *error_text = CGaiaCredentialBase::AllocErrorString(IDS_INTERNAL_ERROR_BASE); return hr; } std::vector<std::string> sam_account_names; hr = SearchForListInStringDictUTF8( "value", cd_user_response_json_string, {kKeyCustomSchemas, kKeyEnhancedDesktopSecurity, kKeyADAccounts}, &sam_account_names); // Note: We only consider the first sam_account_name right now. // We will expand this to consider all account names listed in the // multi-value and perform username resolution in the future. if (sam_account_names.size() > 0) { *sam_account_name = sam_account_names.at(0); } hr = SearchForListInStringDictUTF8( "value", cd_user_response_json_string, {kKeyCustomSchemas, kKeyEnhancedDesktopSecurity, kKeyLocalWindowsAccounts}, local_account_names); if (FAILED(hr)) { LOGFN(ERROR) << "Attempt to parse localAccountInfo failed."; } return hr; } // Request a downscoped access token using the refresh token provided in the // input. HRESULT RequestDownscopedAccessToken(const std::string& refresh_token, std::string* access_token, BSTR* error_text) { DCHECK(refresh_token.size() > 0); DCHECK(access_token); DCHECK(error_text); *error_text = nullptr; GaiaUrls* gaia_urls = GaiaUrls::GetInstance(); std::string enc_client_id = net::EscapeUrlEncodedData(gaia_urls->oauth2_chrome_client_id(), true); std::string enc_client_secret = net::EscapeUrlEncodedData(gaia_urls->oauth2_chrome_client_secret(), true); std::string enc_refresh_token = net::EscapeUrlEncodedData(refresh_token, true); std::string get_access_token_body = base::StringPrintf( kGetAccessTokenBodyWithScopeFormat, enc_client_id.c_str(), enc_client_secret.c_str(), enc_refresh_token.c_str(), net::EscapeUrlEncodedData(kAccessScopes, true).c_str()); std::string get_oauth_token_url = base::StringPrintf("%s", gaia_urls->oauth2_token_url().spec().c_str()); auto oauth_fetcher = WinHttpUrlFetcher::Create(GURL(get_oauth_token_url)); oauth_fetcher->SetRequestBody(get_access_token_body.c_str()); oauth_fetcher->SetRequestHeader("content-type", "application/x-www-form-urlencoded"); oauth_fetcher->SetHttpRequestTimeout(kHttpTimeout); std::vector<char> oauth_response; HRESULT oauth_hr = oauth_fetcher->Fetch(&oauth_response); if (FAILED(oauth_hr)) { LOGFN(ERROR) << "oauth_fetcher.Fetch hr=" << putHR(oauth_hr); *error_text = CGaiaCredentialBase::AllocErrorString(IDS_INTERNAL_ERROR_BASE); return oauth_hr; } std::string oauth_response_json_string = std::string(oauth_response.begin(), oauth_response.end()); *access_token = SearchForKeyInStringDictUTF8(oauth_response_json_string, {kKeyAccessToken}); if (access_token->empty()) { LOGFN(ERROR) << "Fetched access token with new scopes is empty."; *error_text = CGaiaCredentialBase::AllocErrorString(IDS_EMPTY_ACCESS_TOKEN_BASE); return E_FAIL; } return S_OK; } HRESULT GetUserAndDomainInfo( const std::string& sam_account_name, const std::vector<std::string>& local_account_names, std::wstring* existing_sid, BSTR* error_text) { std::wstring user_name; std::wstring domain_name; OSUserManager* os_user_manager = OSUserManager::Get(); DCHECK(os_user_manager); bool is_ad_user = os_user_manager->IsDeviceDomainJoined() && !sam_account_name.empty(); // Login via existing AD account mapping when the device is domain joined if // the AD account mapping is available. if (is_ad_user) { // The format for ad_upn custom attribute is domainName\\userName. // Note that admin configures it as "domainName\userName" but admin // sdk stores it with another escape backslash character in it leading // multiple backslashes. const wchar_t kSlashDelimiter[] = L"\\"; std::vector<std::wstring> tokens = base::SplitString(base::UTF8ToWide(sam_account_name), kSlashDelimiter, base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); // Values fetched from custom attribute shouldn't be empty. if (tokens.size() != 2) { LOGFN(ERROR) << "Found unparseable samAccountName in cloud directory : " << sam_account_name; *error_text = CGaiaCredentialBase::AllocErrorString(IDS_INVALID_AD_UPN_BASE); return E_FAIL; } domain_name = tokens.at(0); user_name = tokens.at(1); } else { // Fallback to using local account mapping for all other scenarios. // Step 1: Filter out invalid local account names based on serial number // etc. The mapping would look like "un:abcd,sn:1234" where "un" represents // the local user name and "sn" represents the serial number of the device. // Note that "sn" is optional, but it is recommended to be used by the IT // admin. // The variable that holds all the local accounts which has // a matching serial number of the device. std::vector<std::wstring> filtered_local_account_names; // The variable that holds all the local accounts which doesn't have // any serial_number mapping in custom attributes. std::vector<std::wstring> filtered_local_account_names_no_sn; for (auto local_account_name : local_account_names) { LOGFN(VERBOSE) << "CD local account name : " << local_account_name; // The format for local_account_name custom attribute is // "un:abcd,sn:1234" where "un:abcd" would always exist and "sn:1234" is // optional. std::string username; std::string serial_number; // Note: "?:" is used to signify non-capturing groups. For more details, // look at https://github.com/google/re2/wiki/Syntax link. re2::RE2::FullMatch(local_account_name, "un:([^,]+)(?:,sn:([^,]+))?", &username, &serial_number); // Only collect those user names that exist on the windows device. std::wstring existing_sid; HRESULT hr = os_user_manager->GetUserSID( OSUserManager::GetLocalDomain().c_str(), base::UTF8ToWide(username).c_str(), &existing_sid); if (FAILED(hr)) continue; LOGFN(VERBOSE) << "RE2 username : " << username; LOGFN(VERBOSE) << "RE2 serial_number : " << serial_number; if (!username.empty() && !serial_number.empty()) { std::string device_serial_number = base::WideToUTF8(GetSerialNumber().c_str()); LOGFN(VERBOSE) << "Device serial_number : " << device_serial_number; if (base::EqualsCaseInsensitiveASCII(serial_number, device_serial_number)) filtered_local_account_names.push_back(base::UTF8ToWide(username)); } else if (!username.empty()) { filtered_local_account_names_no_sn.push_back( base::UTF8ToWide(username)); } } // Step 2: If more than one mapping found on both the above lists // OR no mapping found on either one of them, then return NTE_NOT_FOUND. if (filtered_local_account_names.size() != 1 && filtered_local_account_names_no_sn.size() != 1) { return NTE_NOT_FOUND; } // Step 3: Assign the extracted user name to user_name variable so that we // can verify for existence of SID on the device with the extracted user // name on the current windows device. user_name = filtered_local_account_names.size() == 1 ? filtered_local_account_names.at(0) : filtered_local_account_names_no_sn.at(0); domain_name = OSUserManager::GetLocalDomain(); } LOGFN(VERBOSE) << "Get user sid for user " << user_name << " and domain name " << domain_name; HRESULT hr = os_user_manager->GetUserSID(domain_name.c_str(), user_name.c_str(), existing_sid); if (existing_sid->length() > 0) { LOGFN(VERBOSE) << "Found existing SID = " << *existing_sid; return S_OK; } LOGFN(ERROR) << "No existing sid found with user name : " << user_name << " and domain name: " << domain_name << ". hr=" << putHR(hr); if (is_ad_user) { *error_text = CGaiaCredentialBase::AllocErrorString(IDS_INVALID_AD_UPN_BASE); LOGFN(ERROR) << "Could not find a valid samAccountName."; return E_FAIL; } // For non-AD usecase, we will fallback to creating new local account // instead of failing the login attempt. return NTE_NOT_FOUND; } // Find an existing account associated with GCPW user if one exists. // (1) Verifies if the gaia user has a corresponding mapping in Google // Admin SDK Users Directory and contains the custom_schema that contains // the sam_account_name or local_user_info for the corresponding user. // (2) If there is an entry in cloud directory, gcpw would search for the SID // corresponding to that user entry on the device. // (3) If a SID is found, then it would log the user onto the device using // username extracted from Google Admin SDK Users Directory and password // being the same as the gaia entity. // (4) If there is no entry found in cloud directory, gcpw would fallback to // create a new local user on the device. // // Below are the scenarios where we fallback to create a new local user: // (1) No mapping available in user's cloud directory custom schema attributes. // (2) If a local user mapping exists but the extracted domainname/username // combination doesn't have a valid SID. // // Below are the failure scenarios : // (1) Failed getting a downscoped access token from refresh token. // (2) If communication with cloud directory fails, then we fail the login. // (3) If an attempt to find SID from domain controller or local machine failed, // then we fail the login. // (4) Parsing the samAccountName or localAccountInfo failed. // (5) If an AD user mapping exists but the extracted domainname/username // combination doesn't have a valid SID. HRESULT FindExistingUserSidIfAvailable(const std::string& refresh_token, const std::wstring& email, wchar_t* sid, const DWORD sid_length, BSTR* error_text) { DCHECK(sid); DCHECK(error_text); *error_text = nullptr; // Step 1: Get the downscoped access token with required admin sdk scopes. std::string access_token; HRESULT hr = RequestDownscopedAccessToken(refresh_token, &access_token, error_text); if (FAILED(hr)) { LOGFN(ERROR) << "RequestDownscopedAccessToken hr=" << putHR(hr); return hr; } // Step 2: Make a get call to admin sdk using the fetched access_token and // retrieve the sam_account_name. std::string sam_account_name; std::vector<std::string> local_account_names; hr = GetExistingAccountMappingFromCD(email, access_token, &sam_account_name, &local_account_names, error_text); if (FAILED(hr)) { LOGFN(ERROR) << "GetExistingAccountMappingFromCD hr=" << putHR(hr); return hr; } std::wstring existing_sid = std::wstring(); hr = GetUserAndDomainInfo(sam_account_name, local_account_names, &existing_sid, error_text); if (SUCCEEDED(hr)) wcscpy_s(sid, sid_length, existing_sid.c_str()); return hr; } // Tries to find a user associated to the gaia_id stored in |result| under the // key |kKeyId|. If one exists, then this function will fill out |gaia_id|, // |username|, |domain| and |sid| with the user's information. If not this // function will try to generate a new username derived from the email and fill // out only |gaia_id| and |username|. |domain| will always be the local domain // since only local users can be created. |sid| will be empty until the user is // created later on. |is_consumer_account| will be set to true if the email used // to sign in is gmail or googlemail. HRESULT MakeUsernameForAccount(const base::Value& result, std::wstring* gaia_id, wchar_t* username, DWORD username_length, wchar_t* domain, DWORD domain_length, wchar_t* sid, DWORD sid_length, bool* is_consumer_account, BSTR* error_text) { DCHECK(gaia_id); DCHECK(username); DCHECK(domain); DCHECK(sid); DCHECK(is_consumer_account); DCHECK(error_text); // Determine if the email is a consumer domain (gmail.com or googlemail.com). std::wstring email = GetDictString(result, kKeyEmail); std::transform(email.begin(), email.end(), email.begin(), ::tolower); std::wstring::size_type consumer_domain_pos = email.find(L"@gmail.com"); if (consumer_domain_pos == std::wstring::npos) consumer_domain_pos = email.find(L"@googlemail.com"); *is_consumer_account = consumer_domain_pos != std::wstring::npos; *gaia_id = GetDictString(result, kKeyId); // First try to detect if this gaia account has been used to create an OS // user already. If so, return the OS username of that user. HRESULT hr = GetSidFromId(*gaia_id, sid, sid_length); if (FAILED(hr)) { LOGFN(VERBOSE) << "Failed fetching Sid from Id : " << putHR(hr); // If there is no gaia id user property available in the registry, // fallback to email address mapping. hr = GetSidFromEmail(email, sid, sid_length); if (FAILED(hr)) LOGFN(VERBOSE) << "Failed fetching Sid from email : " << putHR(hr); } bool has_existing_user_sid = false; // Check if the machine is domain joined and get the domain name if domain // joined. if (SUCCEEDED(hr)) { // This makes sure that we don't invoke the network calls on every login // attempt and instead fallback to the SID to gaia id mapping created by // GCPW. LOGFN(VERBOSE) << "Found existing SID created in GCPW registry entry = " << sid; has_existing_user_sid = true; } else if (CGaiaCredentialBase::IsCloudAssociationEnabled()) { LOGFN(VERBOSE) << "Lookup cloud association."; std::string refresh_token = GetDictStringUTF8(result, kKeyRefreshToken); hr = FindExistingUserSidIfAvailable(refresh_token, email, sid, sid_length, error_text); has_existing_user_sid = true; if (hr == NTE_NOT_FOUND) { LOGFN(ERROR) << "No valid sid mapping found." << "Fallback to create a new local user account. hr=" << putHR(hr); has_existing_user_sid = false; } else if (FAILED(hr)) { LOGFN(ERROR) << "Failed finding existing user sid for GCPW user. hr=" << putHR(hr); return hr; } } else { LOGFN(VERBOSE) << "Fallback to create a new local user account"; } if (has_existing_user_sid) { HRESULT hr = OSUserManager::Get()->FindUserBySID( sid, username, username_length, domain, domain_length); if (FAILED(hr)) *error_text = CGaiaCredentialBase::AllocErrorString(IDS_INTERNAL_ERROR_BASE); return hr; } LOGFN(VERBOSE) << "No existing user found associated to gaia id:" << *gaia_id; wcscpy_s(domain, domain_length, OSUserManager::GetLocalDomain().c_str()); username[0] = 0; sid[0] = 0; // Create a username based on the email address. Usernames are more // restrictive than emails, so some transformations are needed. This tries // to preserve the email as much as possible in the username while respecting // Windows username rules. See remarks in // https://docs.microsoft.com/en-us/windows/desktop/api/lmaccess/ns-lmaccess-_user_info_0 std::wstring os_username = email; // If the email is a consumer domain, strip it. if (consumer_domain_pos != std::wstring::npos) { os_username.resize(consumer_domain_pos); } else { // Strip off well known TLDs. std::string username_utf8 = gaia::SanitizeEmail(base::WideToUTF8(os_username)); if (GetGlobalFlagOrDefault(kRegUseShorterAccountName, 0)) { size_t separator_pos = username_utf8.find('@'); // os_username carries the email. Fall through if not find "@" in the // email. if (separator_pos != username_utf8.npos) { username_utf8 = username_utf8.substr(0, separator_pos); os_username = base::UTF8ToWide(username_utf8); } } else { size_t tld_length = net::registry_controlled_domains::GetCanonicalHostRegistryLength( gaia::ExtractDomainName(username_utf8), net::registry_controlled_domains::EXCLUDE_UNKNOWN_REGISTRIES, net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES); // If an TLD is found strip it off, plus 1 to remove the separating dot // too. if (tld_length > 0) { username_utf8.resize(username_utf8.length() - tld_length - 1); os_username = base::UTF8ToWide(username_utf8); } } } // If the username is longer than 20 characters, truncate. if (os_username.size() > kWindowsUsernameBufferLength - 1) os_username.resize(kWindowsUsernameBufferLength - 1); // After resizing the os user name above, the last char may be a '.' which is // illegal as the last character per Microsoft documentation. // https://docs.microsoft.com/en-us/windows/win32/api/lmaccess/ns-lmaccess-user_info_1#remarks if (os_username.size() > 0 && os_username.back() == '.') os_username.resize(os_username.size() - 1); // Replace invalid characters. While @ is not strictly invalid according to // MSDN docs, it causes trouble. for (auto& c : os_username) { if (wcschr(L"@\\[]:|<>+=;?*", c) != nullptr || c < 32) c = L'_'; } wcscpy_s(username, username_length, os_username.c_str()); return S_OK; } // Waits for the login UI to complete and returns the result of the operation. // This function returns S_OK on success, E_UNEXPECTED on failure, and E_ABORT // if the user aborted or timed out (or was killed during cleanup). HRESULT WaitForLoginUIAndGetResult( CGaiaCredentialBase::UIProcessInfo* uiprocinfo, std::string* json_result, DWORD* exit_code, BSTR* status_text) { LOGFN(VERBOSE); DCHECK(uiprocinfo); DCHECK(json_result); DCHECK(exit_code); DCHECK(status_text); // Buffer used to accumulate output from UI. const int kBufferSize = 4096; std::vector<char> output_buffer(kBufferSize, '\0'); base::ScopedClosureRunner zero_buffer_on_exit( base::BindOnce(base::IgnoreResult(&SecurelyClearBuffer), &output_buffer[0], kBufferSize)); HRESULT hr = WaitForProcess(uiprocinfo->procinfo.process_handle(), uiprocinfo->parent_handles, exit_code, &output_buffer[0], kBufferSize); // output_buffer contains sensitive information like the password. Don't log // it. LOGFN(VERBOSE) << "exit_code=" << *exit_code; // Killed internally in the GLS or killed externally by selecting // another credential while GLS is running. if (*exit_code == kUiecAbort || *exit_code == kUiecKilled) { LOGFN(WARNING) << "Aborted hr=" << putHR(hr); return E_ABORT; } else if (*exit_code != kUiecSuccess) { LOGFN(ERROR) << "Error hr=" << putHR(hr); *status_text = CGaiaCredentialBase::AllocErrorString(IDS_INVALID_UI_RESPONSE_BASE); return E_FAIL; } *json_result = std::string(&output_buffer[0]); return S_OK; } // This function validates the response from GLS and makes sure it contained // all the fields required to proceed with logon. This does not necessarily // guarantee that the logon will succeed, only that GLS response seems correct. HRESULT ValidateResult(const base::Value& result, BSTR* status_text) { DCHECK(status_text); // Check the exit_code to see if any errors were detected by the GLS. absl::optional<int> exit_code = result.FindIntKey(kKeyExitCode); if (exit_code.value() != kUiecSuccess) { switch (exit_code.value()) { case kUiecAbort: // This case represents a user abort and no error message is shown. return E_ABORT; case kUiecTimeout: case kUiecKilled: NOTREACHED() << "Internal codes, not returned by GLS"; break; case kUiecEMailMissmatch: *status_text = CGaiaCredentialBase::AllocErrorString(IDS_EMAIL_MISMATCH_BASE); break; case kUiecInvalidEmailDomain: *status_text = CGaiaCredentialBase::AllocErrorString( IDS_INVALID_EMAIL_DOMAIN_BASE); break; case kUiecMissingSigninData: *status_text = CGaiaCredentialBase::AllocErrorString(IDS_INVALID_UI_RESPONSE_BASE); break; } return E_FAIL; } // Check that the webui returned all expected values. bool has_error = false; std::string email = GetDictStringUTF8(result, kKeyEmail); if (email.empty()) { LOGFN(ERROR) << "Email is empty"; has_error = true; } std::string fullname = GetDictStringUTF8(result, kKeyFullname); if (fullname.empty()) { LOGFN(ERROR) << "Full name is empty"; has_error = true; } std::string id = GetDictStringUTF8(result, kKeyId); if (id.empty()) { LOGFN(ERROR) << "Id is empty"; has_error = true; } std::string mdm_id_token = GetDictStringUTF8(result, kKeyMdmIdToken); if (mdm_id_token.empty()) { LOGFN(ERROR) << "mdm id token is empty"; has_error = true; } std::string access_token = GetDictStringUTF8(result, kKeyAccessToken); if (access_token.empty()) { LOGFN(ERROR) << "access token is empty"; has_error = true; } std::string password = GetDictStringUTF8(result, kKeyPassword); if (password.empty()) { LOGFN(ERROR) << "Password is empty"; has_error = true; } else { SecurelyClearString(password); } std::string refresh_token = GetDictStringUTF8(result, kKeyRefreshToken); if (refresh_token.empty()) { LOGFN(ERROR) << "refresh token is empty"; has_error = true; } std::string token_handle = GetDictStringUTF8(result, kKeyTokenHandle); if (token_handle.empty()) { LOGFN(ERROR) << "Token handle is empty"; has_error = true; } if (has_error) { *status_text = CGaiaCredentialBase::AllocErrorString(IDS_INVALID_UI_RESPONSE_BASE); return E_UNEXPECTED; } return S_OK; } // Creates a new windows OS user with the given |base_username|, |fullname| and // |password| on the local machine. Returns the SID of the new user. // If a user with |base_username| already exists, the function will try to // generate a new indexed username up to |max_attempts| before failing. // The actual username used for the new user will be filled in |final_username| // if successful. HRESULT CreateNewUser(OSUserManager* manager, const wchar_t* base_username, const wchar_t* password, const wchar_t* fullname, const wchar_t* comment, bool add_to_users_group, int max_attempts, BSTR* final_username, BSTR* sid) { DCHECK(manager); DCHECK(base_username); DCHECK(password); DCHECK(fullname); DCHECK(comment); DCHECK(final_username); DCHECK(sid); wchar_t new_username[kWindowsUsernameBufferLength]; errno_t err = wcscpy_s(new_username, base::size(new_username), base_username); if (err != 0) { LOGFN(ERROR) << "wcscpy_s errno=" << err; return E_FAIL; } // Keep trying to create the user account until an unused username can be // found or |max_attempts| has been reached. for (int i = 0; i < max_attempts; ++i) { CComBSTR new_sid; DWORD error; HRESULT hr = manager->AddUser(new_username, password, fullname, comment, add_to_users_group, &new_sid, &error); if (hr == HRESULT_FROM_WIN32(NERR_UserExists)) { std::wstring next_username = base_username; std::wstring next_username_suffix = base::NumberToWString(i + kInitialDuplicateUsernameIndex); // Create a new user name that fits in |kWindowsUsernameBufferLength| if (next_username.size() + next_username_suffix.size() > (kWindowsUsernameBufferLength - 1)) { next_username = next_username.substr(0, (kWindowsUsernameBufferLength - 1) - next_username_suffix.size()) + next_username_suffix; } else { next_username += next_username_suffix; } LOGFN(VERBOSE) << "Username '" << new_username << "' already exists. Trying '" << next_username << "'"; errno_t err = wcscpy_s(new_username, base::size(new_username), next_username.c_str()); if (err != 0) { LOGFN(ERROR) << "wcscpy_s errno=" << err; return E_FAIL; } continue; } else if (FAILED(hr)) { LOGFN(ERROR) << "manager->AddUser hr=" << putHR(hr); return hr; } *sid = ::SysAllocString(new_sid); *final_username = ::SysAllocString(new_username); return S_OK; } return HRESULT_FROM_WIN32(NERR_UserExists); } // If GCPW user policies or experiments are stale, make sure to fetch them // before proceeding with the login. void GetUserConfigsIfStale(const std::wstring& sid, const std::wstring& gaia_id, const std::wstring& access_token) { if (UserPoliciesManager::Get()->CloudPoliciesEnabled() && UserPoliciesManager::Get()->IsUserPolicyStaleOrMissing(sid)) { // Save gaia id since it is needed for the cloud policies server request. HRESULT hr = SetUserProperty(sid, kUserId, gaia_id); if (FAILED(hr)) { LOGFN(ERROR) << "SetUserProperty(id) hr=" << putHR(hr); } hr = UserPoliciesManager::Get()->FetchAndStoreCloudUserPolicies( sid, base::WideToUTF8(access_token)); if (FAILED(hr)) { LOGFN(ERROR) << "Failed fetching user policies for user " << sid << " Error: " << putHR(hr); } } if (ExperimentsManager::Get()->ExperimentsEnabled() && GetTimeDeltaSinceLastFetch(sid, kLastUserExperimentsRefreshTimeRegKey) > kMaxTimeDeltaSinceLastExperimentsFetch) { HRESULT hr = SetUserProperty(sid, kUserId, gaia_id); if (FAILED(hr)) { LOGFN(ERROR) << "SetUserProperty(id) hr=" << putHR(hr); } hr = ExperimentsFetcher::Get()->FetchAndStoreExperiments( sid, base::WideToUTF8(access_token)); if (FAILED(hr)) { LOGFN(ERROR) << "Failed fetching experiments for user " << sid << " Error: " << putHR(hr); } } } } // namespace CGaiaCredentialBase::UIProcessInfo::UIProcessInfo() {} CGaiaCredentialBase::UIProcessInfo::~UIProcessInfo() {} // static bool CGaiaCredentialBase::IsCloudAssociationEnabled() { return GetGlobalFlagOrDefault(kRegCloudAssociation, 1); } // static HRESULT CGaiaCredentialBase::OnDllRegisterServer() { OSUserManager* manager = OSUserManager::Get(); auto policy = ScopedLsaPolicy::Create(POLICY_ALL_ACCESS); if (!policy) { HRESULT hr = HRESULT_FROM_WIN32(::GetLastError()); LOGFN(ERROR) << "ScopedLsaPolicy::Create hr=" << putHR(hr); return hr; } PSID sid = nullptr; // Try to get existing username and password and then log on the user, if any // step fails, assume that a new user needs to be created. wchar_t gaia_username[kWindowsUsernameBufferLength]; HRESULT hr = policy->RetrievePrivateData(kLsaKeyGaiaUsername, gaia_username, base::size(gaia_username)); if (SUCCEEDED(hr)) { LOGFN(VERBOSE) << "Expecting gaia user '" << gaia_username << "' to exist."; wchar_t password[32]; HRESULT hr = policy->RetrievePrivateData(kLsaKeyGaiaPassword, password, base::size(password)); if (SUCCEEDED(hr)) { std::wstring local_domain = OSUserManager::GetLocalDomain(); base::win::ScopedHandle token; hr = OSUserManager::Get()->CreateLogonToken( local_domain.c_str(), gaia_username, password, /*interactive=*/false, &token); if (SUCCEEDED(hr)) { hr = OSUserManager::Get()->GetUserSID(local_domain.c_str(), gaia_username, &sid); if (FAILED(hr)) { LOGFN(ERROR) << "GetUserSID(sid from existing user '" << gaia_username << "') hr=" << putHR(hr); sid = nullptr; } } } } if (sid == nullptr) { // No valid existing user found, reset to default name and start generating // from there. errno_t err = wcscpy_s(gaia_username, base::size(gaia_username), kDefaultGaiaAccountName); if (err != 0) { LOGFN(ERROR) << "wcscpy_s errno=" << err; return E_FAIL; } // Generate a random password for the new gaia account. wchar_t password[32]; HRESULT hr = manager->GenerateRandomPassword(password, base::size(password)); if (FAILED(hr)) { LOGFN(ERROR) << "GenerateRandomPassword hr=" << putHR(hr); return hr; } CComBSTR sid_string; CComBSTR gaia_username; // Keep trying to create the special Gaia account used to run the UI until // an unused username can be found or kMaxUsernameAttempts has been reached. hr = CreateNewUser(manager, kDefaultGaiaAccountName, password, GetStringResource(IDS_GAIA_ACCOUNT_FULLNAME_BASE).c_str(), GetStringResource(IDS_GAIA_ACCOUNT_COMMENT_BASE).c_str(), /*add_to_users_group=*/false, kMaxUsernameAttempts, &gaia_username, &sid_string); if (FAILED(hr)) { LOGFN(ERROR) << "CreateNewUser hr=" << putHR(hr); return hr; } if (!::ConvertStringSidToSid(sid_string, &sid)) { hr = HRESULT_FROM_WIN32(::GetLastError()); LOGFN(ERROR) << "ConvertStringSidToSid hr=" << putHR(hr); return hr; } // Save the password in a machine secret area. hr = policy->StorePrivateData(kLsaKeyGaiaPassword, password); if (FAILED(hr)) { LOGFN(ERROR) << "Failed to store gaia user password in LSA hr=" << putHR(hr); return hr; } // Save the gaia username in a machine secret area. hr = policy->StorePrivateData(kLsaKeyGaiaUsername, gaia_username); if (FAILED(hr)) { LOGFN(ERROR) << "Failed to store gaia user name in LSA hr=" << putHR(hr); return hr; } } if (!sid) { LOGFN(ERROR) << "No valid username could be found for the gaia user."; return HRESULT_FROM_WIN32(NERR_UserExists); } // Add "logon as batch" right. std::vector<std::wstring> rights{SE_BATCH_LOGON_NAME}; hr = policy->AddAccountRights(sid, rights); ::LocalFree(sid); if (FAILED(hr)) { LOGFN(ERROR) << "policy.AddAccountRights hr=" << putHR(hr); return hr; } return S_OK; } // static HRESULT CGaiaCredentialBase::OnDllUnregisterServer() { auto policy = ScopedLsaPolicy::Create(POLICY_ALL_ACCESS); if (policy) { wchar_t password[32]; HRESULT hr = policy->RetrievePrivateData(kLsaKeyGaiaPassword, password, base::size(password)); if (FAILED(hr)) LOGFN(ERROR) << "policy.RetrievePrivateData hr=" << putHR(hr); hr = policy->RemovePrivateData(kLsaKeyGaiaPassword); if (FAILED(hr)) LOGFN(ERROR) << "policy.RemovePrivateData hr=" << putHR(hr); OSUserManager* manager = OSUserManager::Get(); PSID sid; wchar_t gaia_username[kWindowsUsernameBufferLength]; hr = policy->RetrievePrivateData(kLsaKeyGaiaUsername, gaia_username, base::size(gaia_username)); if (SUCCEEDED(hr)) { hr = policy->RemovePrivateData(kLsaKeyGaiaUsername); std::wstring local_domain = OSUserManager::GetLocalDomain(); hr = manager->GetUserSID(local_domain.c_str(), gaia_username, &sid); if (FAILED(hr)) { LOGFN(ERROR) << "manager.GetUserSID hr=" << putHR(hr); sid = nullptr; } hr = manager->RemoveUser(gaia_username, password); if (FAILED(hr)) LOGFN(ERROR) << "manager->RemoveUser hr=" << putHR(hr); // Remove the account from LSA after the OS account is deleted. if (sid != nullptr) { hr = policy->RemoveAccount(sid); ::LocalFree(sid); if (FAILED(hr)) LOGFN(ERROR) << "policy.RemoveAccount hr=" << putHR(hr); } } else { LOGFN(ERROR) << "Get gaia username failed hr=" << putHR(hr); } } else { LOGFN(ERROR) << "ScopedLsaPolicy::Create failed"; } return S_OK; } CGaiaCredentialBase::CGaiaCredentialBase() {} CGaiaCredentialBase::~CGaiaCredentialBase() {} bool CGaiaCredentialBase::AreCredentialsValid() const { return CanAttemptWindowsLogon() && IsWindowsPasswordValidForStoredUser(password_) == S_OK; } bool CGaiaCredentialBase::CanAttemptWindowsLogon() const { return username_.Length() > 0 && password_.Length() > 0; } HRESULT CGaiaCredentialBase::IsWindowsPasswordValidForStoredUser( BSTR password) const { if (username_.Length() == 0 || user_sid_.Length() == 0) return S_FALSE; if (::SysStringLen(password) == 0) return S_FALSE; OSUserManager* manager = OSUserManager::Get(); return manager->IsWindowsPasswordValid(domain_, username_, password); } HRESULT CGaiaCredentialBase::GetStringValueImpl(DWORD field_id, wchar_t** value) { HRESULT hr = E_INVALIDARG; switch (field_id) { case FID_DESCRIPTION: { std::wstring description( GetStringResource(IDS_AUTH_FID_DESCRIPTION_BASE)); hr = ::SHStrDupW(description.c_str(), value); break; } case FID_PROVIDER_LABEL: { std::wstring label(GetStringResource(IDS_AUTH_FID_PROVIDER_LABEL_BASE)); hr = ::SHStrDupW(label.c_str(), value); break; } case FID_CURRENT_PASSWORD_FIELD: { hr = ::SHStrDupW(current_windows_password_.Length() > 0 ? current_windows_password_ : L"", value); break; } case FID_FORGOT_PASSWORD_LINK: { std::wstring forgot_password( GetStringResource(IDS_FORGOT_PASSWORD_LINK_BASE)); hr = ::SHStrDupW(forgot_password.c_str(), value); break; } default: break; } return hr; } HRESULT CGaiaCredentialBase::GetBitmapValueImpl(DWORD field_id, HBITMAP* phbmp) { HRESULT hr = E_INVALIDARG; switch (field_id) { case FID_PROVIDER_LOGO: *phbmp = ::LoadBitmap(CURRENT_MODULE(), MAKEINTRESOURCE(IDB_GOOGLE_LOGO_SMALL)); if (*phbmp) hr = S_OK; break; default: break; } return hr; } void CGaiaCredentialBase::ResetInternalState() { LOGFN(VERBOSE); username_.Empty(); domain_.Empty(); wait_for_report_result_ = false; SecurelyClearBuffer((BSTR)password_, password_.ByteLength()); password_.Empty(); current_windows_password_.Empty(); SecurelyClearDictionaryValue(&authentication_results_); needs_windows_password_ = false; request_force_password_change_ = false; result_status_ = STATUS_SUCCESS; TerminateLogonProcess(); if (events_) { wchar_t* default_status_text = nullptr; GetStringValue(FID_DESCRIPTION, &default_status_text); events_->SetFieldString(this, FID_DESCRIPTION, default_status_text); events_->SetFieldState(this, FID_FORGOT_PASSWORD_LINK, CPFS_HIDDEN); events_->SetFieldState(this, FID_CURRENT_PASSWORD_FIELD, CPFS_HIDDEN); events_->SetFieldString(this, FID_CURRENT_PASSWORD_FIELD, current_windows_password_); events_->SetFieldSubmitButton(this, FID_SUBMIT, FID_DESCRIPTION); UpdateSubmitButtonInteractiveState(); } token_update_locker_.reset(); } HRESULT CGaiaCredentialBase::GetBaseGlsCommandline( base::CommandLine* command_line) { DCHECK(command_line); base::FilePath gls_path = GetChromePath(); if (gls_path.empty()) { LOGFN(ERROR) << "No path to chrome.exe could be found."; return HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND); } command_line->SetProgram(gls_path); LOGFN(VERBOSE) << "App exe: " << command_line->GetProgram().value(); command_line->AppendSwitch(kGcpwSigninSwitch); // Chrome allows specifying a group policy to run extensions on Windows // startup for all users. When GLS runs, the autostart extension is also // launched in the login screen. With --disable-extensions flag, this can be // prevented. command_line->AppendSwitch(switches::kDisableExtensions); // Get the language selected by the LanguageSelector and pass it onto Chrome. // The language will depend on if it is currently a SYSTEM logon (initial // logon) or a lock screen logon (from a user). If the user who locked the // screen has a specific language, that will be the one used for the UI // language. command_line->AppendSwitchNative("lang", GetSelectedLanguage()); return S_OK; } HRESULT CGaiaCredentialBase::GetUserGlsCommandline( base::CommandLine* command_line) { return S_OK; } HRESULT CGaiaCredentialBase::GetGlsCommandline( base::CommandLine* command_line) { DCHECK(command_line); HRESULT hr = GetBaseGlsCommandline(command_line); if (FAILED(hr)) { LOGFN(ERROR) << "GetBaseGlsCommandline hr=" << putHR(hr); return hr; } // If email domains are specified, pass them to the GLS. std::wstring email_domains = GetEmailDomains(); if (email_domains[0]) command_line->AppendSwitchNative(kEmailDomainsSwitch, email_domains); hr = GetUserGlsCommandline(command_line); if (FAILED(hr)) { LOGFN(ERROR) << "GetUserGlsCommandline hr=" << putHR(hr); return hr; } LOGFN(VERBOSE) << "Command line: " << command_line->GetCommandLineString(); return S_OK; } void CGaiaCredentialBase::DisplayErrorInUI(LONG status, LONG substatus, BSTR status_text) { if (status != STATUS_SUCCESS) { if (events_) events_->SetFieldString(this, FID_DESCRIPTION, status_text); } } HRESULT CGaiaCredentialBase::HandleAutologon( CREDENTIAL_PROVIDER_GET_SERIALIZATION_RESPONSE* cpgsr, CREDENTIAL_PROVIDER_CREDENTIAL_SERIALIZATION* cpcs) { USES_CONVERSION; LOGFN(VERBOSE) << "user-sid=" << get_sid().m_str; DCHECK(cpgsr); DCHECK(cpcs); if (!CanAttemptWindowsLogon()) return S_FALSE; bool password_updated = false; // If a password update is needed, check if the user entered their old // Windows password and it is valid. If it is, try to change the password // using the old password. If it isn't, return S_FALSE to state that the // login is not complete. if (needs_windows_password_) { OSUserManager* manager = OSUserManager::Get(); if (request_force_password_change_) { HRESULT hr = manager->SetUserPassword(domain_, username_, password_); if (FAILED(hr)) { LOGFN(ERROR) << "SetUserPassword hr=" << putHR(hr); if (events_) { events_->SetFieldString( this, FID_DESCRIPTION, GetStringResource(IDS_FORCED_PASSWORD_CHANGE_FAILURE_BASE) .c_str()); } return S_FALSE; } password_updated = true; } else { HRESULT hr = IsWindowsPasswordValidForStoredUser(current_windows_password_); if (hr == S_OK) { hr = manager->ChangeUserPassword(domain_, username_, current_windows_password_, password_); if (FAILED(hr)) { if (hr != HRESULT_FROM_WIN32(ERROR_ACCESS_DENIED)) { SetErrorMessageInPasswordField(hr); LOGFN(ERROR) << "ChangeUserPassword hr=" << putHR(hr); return hr; } LOGFN(ERROR) << "Access was denied to ChangeUserPassword."; password_ = current_windows_password_; } else { password_updated = true; } } else { if (current_windows_password_.Length() && events_) { UINT pasword_message_id = IDS_INVALID_PASSWORD_BASE; if (hr == HRESULT_FROM_WIN32(ERROR_ACCOUNT_LOCKED_OUT)) { pasword_message_id = IDS_ACCOUNT_LOCKED_BASE; LOGFN(ERROR) << "Account is locked."; } DisplayPasswordField(pasword_message_id); } return S_FALSE; } } } // Password was changed successfully, remove the old password information // so that a new password can be saved. if (password_updated) { HRESULT hr = PasswordRecoveryManager::Get()->ClearUserRecoveryPassword( OLE2CW(get_sid())); if (FAILED(hr)) LOGFN(ERROR) << "ClearUserRecoveryPassword hr=" << putHR(hr); } // The OS user has already been created, so return all the information // needed to log them in. DWORD cpus = 0; provider()->GetUsageScenario(&cpus); HRESULT hr = BuildCredPackAuthenticationBuffer( domain_, get_username(), get_password(), static_cast<CREDENTIAL_PROVIDER_USAGE_SCENARIO>(cpus), cpcs); if (FAILED(hr)) { LOGFN(ERROR) << "BuildCredPackAuthenticationBuffer hr=" << putHR(hr); return hr; } // Prevent update of token handle validity until after sign in has completed // so that a race condition doesn't end up locking out a user while they are // in the process of signing in. The lock must occur before restoring access // to the user below to prevent a race condition where the user would have // their access restored but then the token handle update thread is // immediately executed which causes the user to be locked again afterwards. PreventDenyAccessUpdate(); // Restore user's access so that they can sign in. hr = AssociatedUserValidator::Get()->RestoreUserAccess(OLE2W(get_sid())); if (FAILED(hr) && hr != HRESULT_FROM_NT(STATUS_OBJECT_NAME_NOT_FOUND)) { LOGFN(ERROR) << "RestoreUserAccess hr=" << putHR(hr); ::CoTaskMemFree(cpcs->rgbSerialization); cpcs->rgbSerialization = nullptr; return hr; } cpcs->clsidCredentialProvider = CLSID_GaiaCredentialProvider; *cpgsr = CPGSR_RETURN_CREDENTIAL_FINISHED; return S_OK; } // Sets message ids corresponding to appropriate password change error response // codes. void CGaiaCredentialBase::SetErrorMessageInPasswordField(HRESULT hr) { UINT password_message_id; switch (hr) { case HRESULT_FROM_WIN32(ERROR_INVALID_PASSWORD): password_message_id = IDS_INVALID_PASSWORD_BASE; break; case HRESULT_FROM_WIN32(NERR_InvalidComputer): // This condition should never be invoked. password_message_id = IDS_INVALID_COMPUTER_NAME_ERROR_BASE; break; case HRESULT_FROM_WIN32(NERR_NotPrimary): password_message_id = IDS_AD_PASSWORD_CHANGE_DENIED_BASE; break; case HRESULT_FROM_WIN32(NERR_UserNotFound): // This condition should never be invoked. password_message_id = IDS_USER_NOT_FOUND_PASSWORD_ERROR_BASE; break; case HRESULT_FROM_WIN32(NERR_PasswordTooShort): password_message_id = IDS_PASSWORD_COMPLEXITY_ERROR_BASE; break; default: // This condition should never be invoked. password_message_id = IDS_UNKNOWN_PASSWORD_ERROR_BASE; break; } DisplayPasswordField(password_message_id); } bool CGaiaCredentialBase::BlockingPasswordError(UINT message_id) { for (auto e : kPasswordErrors) { if (e == message_id) return true; } return false; } // static void CGaiaCredentialBase::TellOmahaDidRun() { #if BUILDFLAG(GOOGLE_CHROME_BRANDING) // Tell omaha that product was used. Best effort only. // // This code always runs as LocalSystem, which means that HKCU maps to // HKU\.Default. This is OK because omaha reads the "dr" value from subkeys // of HKEY_USERS. base::win::RegKey key; LONG sts = key.Create(HKEY_CURRENT_USER, kRegUpdaterClientStateAppPath, KEY_SET_VALUE | KEY_WOW64_32KEY); if (sts != ERROR_SUCCESS) { LOGFN(VERBOSE) << "Unable to open omaha key sts=" << sts; } else { sts = key.WriteValue(L"dr", L"1"); if (sts != ERROR_SUCCESS) LOGFN(WARNING) << "Unable to write omaha dr value sts=" << sts; } #endif // BUILDFLAG(GOOGLE_CHROME_BRANDING) } void CGaiaCredentialBase::PreventDenyAccessUpdate() { if (!token_update_locker_) { token_update_locker_ = std::make_unique<AssociatedUserValidator::ScopedBlockDenyAccessUpdate>( AssociatedUserValidator::Get()); } } // static BSTR CGaiaCredentialBase::AllocErrorString(UINT id) { CComBSTR str(GetStringResource(id).c_str()); return str.Detach(); } // static BSTR CGaiaCredentialBase::AllocErrorString( UINT id, const std::vector<std::wstring>& replacements) { CComBSTR str(GetStringResource(id, replacements).c_str()); return str.Detach(); } // static HRESULT CGaiaCredentialBase::GetInstallDirectory(base::FilePath* path) { DCHECK(path); if (!base::PathService::Get(base::FILE_MODULE, path)) { HRESULT hr = HRESULT_FROM_WIN32(::GetLastError()); LOGFN(ERROR) << "Get(FILE_MODULE) hr=" << putHR(hr); return hr; } *path = path->DirName(); return S_OK; } // ICredentialProviderCredential ////////////////////////////////////////////// HRESULT CGaiaCredentialBase::Advise(ICredentialProviderCredentialEvents* cpce) { LOGFN(VERBOSE); events_ = cpce; return S_OK; } HRESULT CGaiaCredentialBase::UnAdvise(void) { LOGFN(VERBOSE); events_.Reset(); return S_OK; } HRESULT CGaiaCredentialBase::SetSelected(BOOL* auto_login) { *auto_login = CanAttemptWindowsLogon(); LOGFN(VERBOSE) << "auto-login=" << *auto_login; // After this point the user is able to interact with the winlogon and thus // can avoid potential crash loops so the startup sentinel can be deleted. DeleteStartupSentinel(); return S_OK; } HRESULT CGaiaCredentialBase::SetDeselected(void) { LOGFN(VERBOSE); // This check is trying to handle the scenario when GetSerialization finishes // with cpgsr set as CPGSR_RETURN_CREDENTIAL_FINISHED which indicates that // the windows autologon is ready to go. In this case ideally ReportResult // should be invoked by the windows login UI process prior to SetDeselected. // But for OtherUserCredential scenario, SetDeselected is being invoked // prior to ReportResult which is leading to clearing of the internalstate // prior to saving the account user info in ReportResult. if (!wait_for_report_result_) { // Cancel logon so that the next time this credential is clicked everything // has to be re-entered by the user. This prevents a Windows password // entered into the password field by the user from being persisted too // long. The behaviour is similar to that of the normal windows password // text box. Whenever a different user is selected and then the original // credential is selected again, the password is cleared. ResetInternalState(); } return S_OK; } HRESULT CGaiaCredentialBase::GetFieldState( DWORD field_id, CREDENTIAL_PROVIDER_FIELD_STATE* pcpfs, CREDENTIAL_PROVIDER_FIELD_INTERACTIVE_STATE* pcpfis) { HRESULT hr = E_INVALIDARG; switch (field_id) { case FID_DESCRIPTION: case FID_SUBMIT: *pcpfs = CPFS_DISPLAY_IN_SELECTED_TILE; *pcpfis = CPFIS_NONE; hr = S_OK; break; case FID_PROVIDER_LOGO: *pcpfs = ::IsWindows8OrGreater() ? CPFS_HIDDEN : CPFS_DISPLAY_IN_BOTH; *pcpfis = CPFIS_NONE; hr = S_OK; break; case FID_PROVIDER_LABEL: *pcpfs = ::IsWindows8OrGreater() ? CPFS_HIDDEN : CPFS_DISPLAY_IN_DESELECTED_TILE; *pcpfis = CPFIS_NONE; hr = S_OK; break; case FID_CURRENT_PASSWORD_FIELD: *pcpfs = CPFS_HIDDEN; *pcpfis = CPFIS_NONE; hr = S_OK; break; case FID_FORGOT_PASSWORD_LINK: *pcpfs = CPFS_HIDDEN; *pcpfis = CPFIS_NONE; hr = S_OK; break; default: break; } LOGFN(VERBOSE) << "hr=" << putHR(hr) << " field=" << field_id << " state=" << *pcpfs << " inter-state=" << *pcpfis; return hr; } HRESULT CGaiaCredentialBase::GetStringValue(DWORD field_id, wchar_t** value) { return GetStringValueImpl(field_id, value); } HRESULT CGaiaCredentialBase::GetBitmapValue(DWORD field_id, HBITMAP* phbmp) { return GetBitmapValueImpl(field_id, phbmp); } HRESULT CGaiaCredentialBase::GetCheckboxValue(DWORD field_id, BOOL* pbChecked, wchar_t** ppszLabel) { // No checkboxes. return E_NOTIMPL; } HRESULT CGaiaCredentialBase::GetSubmitButtonValue(DWORD field_id, DWORD* adjacent_to) { HRESULT hr = E_INVALIDARG; switch (field_id) { case FID_SUBMIT: *adjacent_to = FID_DESCRIPTION; hr = S_OK; break; default: break; } return hr; } HRESULT CGaiaCredentialBase::GetComboBoxValueCount(DWORD field_id, DWORD* pcItems, DWORD* pdwSelectedItem) { // No comboboxes. return E_NOTIMPL; } HRESULT CGaiaCredentialBase::GetComboBoxValueAt(DWORD field_id, DWORD dwItem, wchar_t** ppszItem) { // No comboboxes. return E_NOTIMPL; } HRESULT CGaiaCredentialBase::SetStringValue(DWORD field_id, const wchar_t* psz) { USES_CONVERSION; HRESULT hr = E_INVALIDARG; switch (field_id) { case FID_CURRENT_PASSWORD_FIELD: if (needs_windows_password_) { current_windows_password_ = W2COLE(psz); UpdateSubmitButtonInteractiveState(); } hr = S_OK; break; } return hr; } HRESULT CGaiaCredentialBase::SetCheckboxValue(DWORD field_id, BOOL bChecked) { // No checkboxes. return E_NOTIMPL; } HRESULT CGaiaCredentialBase::SetComboBoxSelectedValue(DWORD field_id, DWORD dwSelectedItem) { // No comboboxes. return E_NOTIMPL; } bool CGaiaCredentialBase::CanProceedToLogonStub(wchar_t** status_text) { bool can_proceed_to_logon_stub = true; BSTR error_message; // Restricted domains key must be set to proceed with logon stub. std::wstring restricted_domains = GetEmailDomains(); if (restricted_domains.empty()) { can_proceed_to_logon_stub = false; error_message = AllocErrorString(IDS_EMAIL_MISMATCH_BASE); LOGFN(ERROR) << "Restricted domains registry key must be set"; } else if (!InternetAvailabilityChecker::Get()->HasInternetConnection()) { // If there is no internet connection, just abort right away. can_proceed_to_logon_stub = false; error_message = AllocErrorString(IDS_NO_NETWORK_BASE); LOGFN(VERBOSE) << "No internet connection"; } if (!can_proceed_to_logon_stub) { ::SHStrDupW(OLE2CW(error_message), status_text); ::SysFreeString(error_message); } return can_proceed_to_logon_stub; } HRESULT CGaiaCredentialBase::CommandLinkClicked(DWORD dwFieldID) { if (dwFieldID == FID_FORGOT_PASSWORD_LINK && needs_windows_password_) { request_force_password_change_ = !request_force_password_change_; DisplayPasswordField(IDS_PASSWORD_UPDATE_NEEDED_BASE); UpdateSubmitButtonInteractiveState(); return S_OK; } return E_INVALIDARG; } HRESULT CGaiaCredentialBase::GetSerialization( CREDENTIAL_PROVIDER_GET_SERIALIZATION_RESPONSE* cpgsr, CREDENTIAL_PROVIDER_CREDENTIAL_SERIALIZATION* cpcs, wchar_t** status_text, CREDENTIAL_PROVIDER_STATUS_ICON* status_icon) { USES_CONVERSION; LOGFN(VERBOSE); DCHECK(status_text); DCHECK(status_icon); *status_text = nullptr; *status_icon = CPSI_NONE; memset(cpcs, 0, sizeof(*cpcs)); // This may be a long running function so disable user input while processing. if (events_) { events_->SetFieldInteractiveState(this, FID_SUBMIT, CPFIS_DISABLED); events_->SetFieldInteractiveState(this, FID_CURRENT_PASSWORD_FIELD, CPFIS_DISABLED); } HRESULT hr = HandleAutologon(cpgsr, cpcs); bool submit_button_enabled = false; // Don't clear the state of the credential on error. The error can occur // because the user is locked out or entered an incorrect old password when // trying to update their password. In these situations it may still be // possible to sign in with the information that is currently available if // the problem can be fixed externally so keep all the information for now. if (FAILED(hr)) { LOGFN(ERROR) << "HandleAutologon hr=" << putHR(hr); *status_icon = CPSI_ERROR; *cpgsr = CPGSR_RETURN_NO_CREDENTIAL_FINISHED; } else if (hr == S_FALSE) { // If HandleAutologon returns S_FALSE, then there was not enough information // to log the user on or they need to update their password and gave an // invalid old password. Display the Gaia sign in page if there is not // sufficient Gaia credentials or just return // CPGSR_NO_CREDENTIAL_NOT_FINISHED to wait for the user to try a new // password. // Logon process is still running or windows password needs to be entered, // return that serialization is not finished so that a second logon stub // isn't started. if (logon_ui_process_ != INVALID_HANDLE_VALUE || needs_windows_password_) { *cpgsr = CPGSR_NO_CREDENTIAL_NOT_FINISHED; // Warn that password needs update. if (needs_windows_password_) *status_icon = CPSI_WARNING; hr = S_OK; } else { LOGFN(VERBOSE) << "HandleAutologon hr=" << putHR(hr); TellOmahaDidRun(); if (!CanProceedToLogonStub(status_text)) { *status_icon = CPSI_NONE; *cpgsr = CPGSR_NO_CREDENTIAL_FINISHED; submit_button_enabled = UpdateSubmitButtonInteractiveState(); hr = S_OK; } else { // The account creation is async so we are not done yet. *cpgsr = CPGSR_NO_CREDENTIAL_NOT_FINISHED; // The expectation is that the UI will eventually return the username, // password, and auth to this CGaiaCredentialBase object, so that // OnUserAuthenticated() can be called, followed by // provider_->OnUserAuthenticated(). hr = CreateAndRunLogonStub(); if (FAILED(hr)) { std::wstring error_message( GetStringResource(IDS_FAILED_CREATE_LOGON_STUB_BASE)); ::SHStrDupW(OLE2CW(error_message.c_str()), status_text); *status_icon = CPSI_NONE; *cpgsr = CPGSR_NO_CREDENTIAL_FINISHED; submit_button_enabled = UpdateSubmitButtonInteractiveState(); hr = S_OK; } } } } else { *status_icon = CPSI_SUCCESS; } // Logon is not complete, re-enable UI as needed. if (*cpgsr != CPGSR_NO_CREDENTIAL_FINISHED && *cpgsr != CPGSR_RETURN_CREDENTIAL_FINISHED && *cpgsr != CPGSR_RETURN_NO_CREDENTIAL_FINISHED) { if (events_) { events_->SetFieldInteractiveState( this, FID_CURRENT_PASSWORD_FIELD, needs_windows_password_ ? CPFIS_FOCUSED : CPFIS_NONE); } submit_button_enabled = UpdateSubmitButtonInteractiveState(); } // If user interaction is enabled that means we are not trying to do final // sign in of the account so we can re-enable token updates. if (submit_button_enabled) token_update_locker_.reset(); // If cpgsr is CPGSR_RETURN_CREDENTIAL_FINISHED and the status is S_OK, then // report result would be invoked. So we shouldn't be resetting the internal // state prior to report result getting triggered. if (*cpgsr == CPGSR_RETURN_CREDENTIAL_FINISHED && hr == S_OK) { wait_for_report_result_ = true; } // Otherwise, keep the ui disabled forever now. ReportResult will eventually // be called on success or failure and the reset of the state of the // credential will be done there. return hr; } HRESULT CGaiaCredentialBase::CreateAndRunLogonStub() { LOGFN(VERBOSE); base::CommandLine command_line(base::CommandLine::NO_PROGRAM); HRESULT hr = GetGlsCommandline(&command_line); if (FAILED(hr)) { LOGFN(ERROR) << "GetGlsCommandline hr=" << putHR(hr); return hr; } // The process should start on the interactive window station (since it // needs to show a UI) but on its own desktop so that it cannot interact // with winlogon on user windows. std::unique_ptr<UIProcessInfo> uiprocinfo(new UIProcessInfo); PSID logon_sid; hr = CreateGaiaLogonToken(&uiprocinfo->logon_token, &logon_sid); if (FAILED(hr)) { LOGFN(ERROR) << "CreateGaiaLogonToken hr=" << putHR(hr); return hr; } OSProcessManager* process_manager = OSProcessManager::Get(); hr = process_manager->SetupPermissionsForLogonSid(logon_sid); LocalFree(logon_sid); if (FAILED(hr)) { LOGFN(ERROR) << "SetupPermissionsForLogonSid hr=" << putHR(hr); return hr; } hr = ForkGaiaLogonStub(process_manager, command_line, uiprocinfo.get()); if (FAILED(hr)) { LOGFN(ERROR) << "ForkGaiaLogonStub hr=" << putHR(hr); return hr; } // Save the handle to the logon UI process so that it can be killed should // the credential be Unadvise()d. DCHECK_EQ(logon_ui_process_, INVALID_HANDLE_VALUE); logon_ui_process_ = uiprocinfo->procinfo.process_handle(); uiprocinfo->credential = this; // Background thread takes ownership of |uiprocinfo|. unsigned int wait_thread_id; UIProcessInfo* puiprocinfo = uiprocinfo.release(); uintptr_t wait_thread = _beginthreadex(nullptr, 0, WaitForLoginUI, puiprocinfo, 0, &wait_thread_id); if (wait_thread != 0) { LOGFN(VERBOSE) << "Started wait thread id=" << wait_thread_id; ::CloseHandle(reinterpret_cast<HANDLE>(wait_thread)); } else { HRESULT hr = HRESULT_FROM_WIN32(::GetLastError()); LOGFN(ERROR) << "Unable to start wait thread hr=" << putHR(hr); ::TerminateProcess(puiprocinfo->procinfo.process_handle(), kUiecKilled); delete puiprocinfo; return hr; } // This function returns success, which means that GetSerialization() will // return success. CGaiaCredentialBase is now committed to telling // CGaiaCredentialProvider whether the serialization eventually succeeds or // fails, so that CGaiaCredentialProvider can in turn inform winlogon about // what happened. LOGFN(VERBOSE) << "cleaning up"; return S_OK; } // static HRESULT CGaiaCredentialBase::CreateGaiaLogonToken( base::win::ScopedHandle* token, PSID* sid) { DCHECK(token); DCHECK(sid); auto policy = ScopedLsaPolicy::Create(POLICY_ALL_ACCESS); if (!policy) { LOGFN(ERROR) << "LsaOpenPolicy failed"; return E_UNEXPECTED; } wchar_t gaia_username[kWindowsUsernameBufferLength]; HRESULT hr = policy->RetrievePrivateData(kLsaKeyGaiaUsername, gaia_username, base::size(gaia_username)); if (FAILED(hr)) { LOGFN(ERROR) << "Retrieve gaia username hr=" << putHR(hr); return hr; } wchar_t password[32]; hr = policy->RetrievePrivateData(kLsaKeyGaiaPassword, password, base::size(password)); if (FAILED(hr)) { LOGFN(ERROR) << "Retrieve password for gaia user '" << gaia_username << "' hr=" << putHR(hr); return hr; } std::wstring local_domain = OSUserManager::GetLocalDomain(); hr = OSUserManager::Get()->CreateLogonToken(local_domain.c_str(), gaia_username, password, /*interactive=*/false, token); if (FAILED(hr)) { LOGFN(ERROR) << "CreateLogonToken hr=" << putHR(hr); return hr; } hr = OSProcessManager::Get()->GetTokenLogonSID(*token, sid); if (FAILED(hr)) { LOGFN(ERROR) << "GetTokenLogonSID hr=" << putHR(hr); token->Close(); return hr; } wchar_t* sid_string; if (::ConvertSidToStringSid(*sid, &sid_string)) { LOGFN(VERBOSE) << "logon-sid=" << sid_string; LocalFree(sid_string); } else { LOGFN(ERROR) << "logon-sid=<can't get string>"; } return S_OK; } // static HRESULT CGaiaCredentialBase::ForkGaiaLogonStub( OSProcessManager* process_manager, const base::CommandLine& command_line, UIProcessInfo* uiprocinfo) { LOGFN(VERBOSE); DCHECK(process_manager); DCHECK(uiprocinfo); ScopedStartupInfo startupinfo(kDesktopFullName); // Only create a stdout pipe for the logon stub process. On some machines // Chrome will not startup properly when also given a stderror pipe due // to access restrictions. For the purposes of the credential provider // only the output of stdout matters. HRESULT hr = InitializeStdHandles(CommDirection::kChildToParentOnly, kStdOutput, &startupinfo, &uiprocinfo->parent_handles); if (FAILED(hr)) { LOGFN(ERROR) << "InitializeStdHandles hr=" << putHR(hr); return hr; } // The process is created suspended so that we can adjust its environment // before it starts. Also, it must not run before it is added to the job // object. hr = process_manager->CreateProcessWithToken( uiprocinfo->logon_token, command_line, startupinfo.GetInfo(), &uiprocinfo->procinfo); if (FAILED(hr)) { LOGFN(ERROR) << "process_manager->CreateProcessWithToken hr=" << putHR(hr); return hr; } LOGFN(VERBOSE) << "pid=" << uiprocinfo->procinfo.process_id() << " tid=" << uiprocinfo->procinfo.thread_id(); // Don't create a job here with UI restrictions, since win10 does not allow // nested jobs unless all jobs don't specify UI restrictions. Since chrome // will set a job with UI restrictions for renderer/gpu/etc processes, setting // one here causes chrome to fail. // Environment is fully set up for UI, so let it go. if (::ResumeThread(uiprocinfo->procinfo.thread_handle()) == static_cast<DWORD>(-1)) { HRESULT hr = HRESULT_FROM_WIN32(::GetLastError()); LOGFN(ERROR) << "ResumeThread hr=" << putHR(hr); ::TerminateProcess(uiprocinfo->procinfo.process_handle(), kUiecKilled); return hr; } // Don't close the desktop until after the process has started and acquired // a handle to it. Otherwise, the desktop will be destroyed and the process // will fail to start. // // WaitForInputIdle() return immediately with an error if the process // created is a console app. In production this will not be the case, // however in tests this may happen. However, tests are not concerned with // the destruction of the desktop since one is not created. DWORD ret = ::WaitForInputIdle(uiprocinfo->procinfo.process_handle(), 10000); if (ret != 0) LOGFN(VERBOSE) << "WaitForInputIdle, ret=" << ret; return S_OK; } HRESULT CGaiaCredentialBase::ForkPerformPostSigninActionsStub( const base::Value& dict, BSTR* status_text) { LOGFN(VERBOSE); DCHECK(status_text); ScopedStartupInfo startupinfo; StdParentHandles parent_handles; HRESULT hr = InitializeStdHandles(CommDirection::kParentToChildOnly, kAllStdHandles, &startupinfo, &parent_handles); if (FAILED(hr)) { LOGFN(ERROR) << "InitializeStdHandles hr=" << putHR(hr); *status_text = AllocErrorString(IDS_INTERNAL_ERROR_BASE); return hr; } base::CommandLine command_line(base::CommandLine::NO_PROGRAM); hr = GetCommandLineForEntrypoint(CURRENT_MODULE(), L"PerformPostSigninActions", &command_line); if (hr == S_FALSE) { // This happens in tests. It means this code is running inside the // unittest exe and not the credential provider dll. Just ignore saving // the account info. LOGFN(VERBOSE) << "Not running SAIS"; return S_OK; } else if (FAILED(hr)) { LOGFN(ERROR) << "GetCommandLineForEntryPoint hr=" << putHR(hr); *status_text = AllocErrorString(IDS_INTERNAL_ERROR_BASE); return hr; } // Mark this process as a child process so that it doesn't try to // start a crashpad handler process. Only the main entry point // into the dll should start the handler process. command_line.AppendSwitchASCII(switches::kProcessType, "gcpw-save-account-info"); base::win::ScopedProcessInformation procinfo; hr = OSProcessManager::Get()->CreateRunningProcess( command_line, startupinfo.GetInfo(), &procinfo); if (FAILED(hr)) { LOGFN(ERROR) << "OSProcessManager::CreateRunningProcess hr=" << putHR(hr); *status_text = AllocErrorString(IDS_INTERNAL_ERROR_BASE); return hr; } // Write account info to stdin of child process. This buffer is read by // PerformPostSigninActionsW() in dllmain.cpp. If this fails, chrome won't // pick up the credentials from the credential provider and will need to sign // in manually. std::string json; if (base::JSONWriter::Write(dict, &json)) { const DWORD buffer_size = json.length() + 1; LOGFN(VERBOSE) << "Json size: " << buffer_size; DWORD written = 0; // First, write the buffer size then write the buffer content. if (!::WriteFile(parent_handles.hstdin_write.Get(), &buffer_size, sizeof(buffer_size), &written, /*lpOverlapped=*/nullptr)) { HRESULT hrWrite = HRESULT_FROM_WIN32(::GetLastError()); LOGFN(ERROR) << "WriteFile hr=" << putHR(hrWrite); } else if (!::WriteFile(parent_handles.hstdin_write.Get(), json.c_str(), buffer_size, &written, /*lpOverlapped=*/nullptr)) { HRESULT hrWrite = HRESULT_FROM_WIN32(::GetLastError()); LOGFN(ERROR) << "WriteFile hr=" << putHR(hrWrite); } SecurelyClearString(json); } else { LOGFN(ERROR) << "base::JSONWriter::Write failed"; } return S_OK; } // static unsigned __stdcall CGaiaCredentialBase::WaitForLoginUI(void* param) { USES_CONVERSION; DCHECK(param); std::unique_ptr<UIProcessInfo> uiprocinfo( reinterpret_cast<UIProcessInfo*>(param)); // Make sure COM is initialized in this thread. This thread must be // initialized as an MTA or the call to enroll with MDM causes a crash in COM. base::win::ScopedCOMInitializer com_initializer( base::win::ScopedCOMInitializer::kMTA); if (!com_initializer.Succeeded()) { HRESULT hr = HRESULT_FROM_WIN32(::GetLastError()); LOGFN(ERROR) << "ScopedCOMInitializer failed hr=" << putHR(hr); return hr; } CComBSTR status_text; DWORD exit_code; std::string json_result; HRESULT hr = WaitForLoginUIAndGetResult(uiprocinfo.get(), &json_result, &exit_code, &status_text); if (SUCCEEDED(hr)) { // Notify that the new user is created. // TODO(rogerta): Docs say this should not be called on a background // thread, but on the thread that received the // CGaiaCredentialBase::Advise() call. Seems to work for now though, but I // suspect there could be a problem if this call races with a call to // CGaiaCredentialBase::Unadvise(). std::wstring json_result16 = base::UTF8ToWide(json_result); CComBSTR result_string(W2COLE(json_result16.c_str())); SecurelyClearString(json_result16); hr = uiprocinfo->credential->OnUserAuthenticated(result_string, &status_text); SecurelyClearBuffer((BSTR)result_string, result_string.ByteLength()); } SecurelyClearString(json_result); // If the process was killed by the credential in Terminate(), don't process // the error message since it is possible that the credential and/or the // provider no longer exists. if (FAILED(hr)) { if (hr != E_ABORT) LOGFN(ERROR) << "WaitForLoginUIAndGetResult hr=" << putHR(hr); // If hr is E_ABORT, this is a user initiated cancel. Don't consider this // an error. LONG sts = hr == E_ABORT ? STATUS_SUCCESS : HRESULT_CODE(hr); // Either WaitForLoginUIAndGetResult did not fail or there should be an // error message to display. DCHECK(sts == STATUS_SUCCESS || status_text != nullptr); hr = uiprocinfo->credential->ReportError(sts, STATUS_SUCCESS, status_text); if (FAILED(hr)) LOGFN(ERROR) << "uiprocinfo->credential->ReportError hr=" << putHR(hr); } LOGFN(VERBOSE) << "done"; return 0; } // static HRESULT CGaiaCredentialBase::PerformActions(const base::Value& properties) { LOGFN(VERBOSE); std::wstring sid = GetDictString(properties, kKeySID); if (sid.empty()) { LOGFN(ERROR) << "SID is empty"; return E_INVALIDARG; } std::wstring username = GetDictString(properties, kKeyUsername); if (username.empty()) { LOGFN(ERROR) << "Username is empty"; return E_INVALIDARG; } std::wstring password = GetDictString(properties, kKeyPassword); if (password.empty()) { LOGFN(ERROR) << "Password is empty"; return E_INVALIDARG; } std::wstring domain = GetDictString(properties, kKeyDomain); // Load the user's profile so that their registry hive is available. auto profile = ScopedUserProfile::Create(sid, domain, username, password); if (!profile) { LOGFN(ERROR) << "Could not load user profile"; return E_UNEXPECTED; } HRESULT hr = profile->SaveAccountInfo(properties); if (FAILED(hr)) LOGFN(ERROR) << "profile.SaveAccountInfo failed (cont) hr=" << putHR(hr); // TODO(crbug.com/976744): Use the down scoped kKeyMdmAccessToken instead // of login scoped token. std::string access_token = GetDictStringUTF8(properties, kKeyAccessToken); if (access_token.empty()) { LOGFN(ERROR) << "Access token is empty."; return E_FAIL; } // Update the password recovery information if possible. hr = PasswordRecoveryManager::Get()->StoreWindowsPasswordIfNeeded( sid, access_token, password); SecurelyClearString(password); if (FAILED(hr) && hr != E_NOTIMPL) LOGFN(ERROR) << "StoreWindowsPasswordIfNeeded hr=" << putHR(hr); hr = GenerateGCPWDmToken(sid); if (FAILED(hr)) { LOGFN(ERROR) << "GenerateGCPWDmToken hr=" << putHR(hr); } // Upload device details to gem database. hr = GemDeviceDetailsManager::Get()->UploadDeviceDetails(access_token, sid, username, domain); DWORD device_upload_failures = 0; GetUserProperty(sid, kRegDeviceDetailsUploadFailures, &device_upload_failures); if (FAILED(hr)) { LOGFN(ERROR) << "UploadDeviceDetails hr=" << putHR(hr); ++device_upload_failures; } else { device_upload_failures = 0; } SetUserProperty(sid, kRegDeviceDetailsUploadStatus, SUCCEEDED(hr) ? 1 : 0); SetUserProperty(sid, kRegDeviceDetailsUploadFailures, device_upload_failures); // Below setter is only used for unit testing. GemDeviceDetailsManager::Get()->SetUploadStatusForTesting(hr); return hr; } // static HRESULT CGaiaCredentialBase::PerformPostSigninActions( const base::Value& properties, bool com_initialized) { LOGFN(VERBOSE); HRESULT hr = S_OK; if (com_initialized) { hr = credential_provider::CGaiaCredentialBase::PerformActions(properties); if (FAILED(hr)) LOGFN(ERROR) << "PerformActions hr=" << putHR(hr); // Try to enroll the machine to MDM here. MDM requires a user to be signed // on to an interactive session to succeed and when we call this function // the user should have been successfully signed on at that point and able // to finish the enrollment. hr = credential_provider::EnrollToGoogleMdmIfNeeded(properties); if (FAILED(hr)) LOGFN(ERROR) << "EnrollToGoogleMdmIfNeeded hr=" << putHR(hr); } // Ensure GCPW gets updated to the correct version. if (DevicePoliciesManager::Get()->CloudPoliciesEnabled()) { DevicePoliciesManager::Get()->EnforceGcpwUpdatePolicy(); } // TODO(crbug.com/976744): Use the down scoped kKeyMdmAccessToken instead // of login scoped token. std::string access_token = GetDictStringUTF8(properties, kKeyAccessToken); // Finally upload event logs to cloud storage. if (!access_token.empty()) { hr = EventLogsUploadManager::Get()->UploadEventViewerLogs(access_token); if (FAILED(hr) && hr != E_NOTIMPL) LOGFN(ERROR) << "UploadEventViewerLogs hr=" << putHR(hr); } else { LOGFN(ERROR) << "Access token is empty. Cannot upload logs."; } return hr; } // Registers OS user - gaia user association in HKEY_LOCAL_MACHINE registry // hive. HRESULT RegisterAssociation(const std::wstring& sid, const std::wstring& id, const std::wstring& email, const std::wstring& token_handle) { // Save token handle. This handle will be used later to determine if the // the user has changed their password since the account was created. HRESULT hr = SetUserProperty(sid, kUserTokenHandle, token_handle); if (FAILED(hr)) { LOGFN(ERROR) << "SetUserProperty(th) hr=" << putHR(hr); return hr; } hr = SetUserProperty(sid, kUserId, id); if (FAILED(hr)) { LOGFN(ERROR) << "SetUserProperty(id) hr=" << putHR(hr); return hr; } hr = SetUserProperty(sid, kUserEmail, email); if (FAILED(hr)) { LOGFN(ERROR) << "SetUserProperty(email) hr=" << putHR(hr); return hr; } if (IsGemEnabled()) { hr = SetUserProperty(sid, kKeyAcceptTos, 1u); if (FAILED(hr)) { LOGFN(ERROR) << "SetUserProperty(acceptTos) hr=" << putHR(hr); return hr; } } return S_OK; } HRESULT CGaiaCredentialBase::ReportResult( NTSTATUS status, NTSTATUS substatus, wchar_t** ppszOptionalStatusText, CREDENTIAL_PROVIDER_STATUS_ICON* pcpsiOptionalStatusIcon) { LOGFN(VERBOSE) << "status=" << putHR(status) << " substatus=" << putHR(substatus); if (status == STATUS_SUCCESS && authentication_results_) { // Update the sid, domain, username and password in // |authentication_results_| with the real Windows information for the user // so that the PerformPostSigninActions process can correctly sign in to the // user account. authentication_results_->SetKey( kKeySID, base::Value(base::WideToUTF8((BSTR)user_sid_))); authentication_results_->SetKey( kKeyDomain, base::Value(base::WideToUTF8((BSTR)domain_))); authentication_results_->SetKey( kKeyUsername, base::Value(base::WideToUTF8((BSTR)username_))); authentication_results_->SetKey( kKeyPassword, base::Value(base::WideToUTF8((BSTR)password_))); std::wstring gaia_id = GetDictString(*authentication_results_, kKeyId); if (gaia_id.empty()) { LOGFN(ERROR) << "Id is empty"; return E_INVALIDARG; } std::wstring email = GetDictString(*authentication_results_, kKeyEmail); if (email.empty()) { LOGFN(ERROR) << "Email is empty"; return E_INVALIDARG; } // Os user - gaia user association is saved in HKEY_LOCAL_MACHINE. So, we // can attempt saving association even before calling forked process. Forked // process will also re-write everything saved here as well as valid token // handle. Token handle is saved as empty here, so that if for any reason // forked process fails to save association, it will enforce re-auth due to // invalid token handle. std::wstring sid = OLE2CW(user_sid_); HRESULT hr = RegisterAssociation(sid, gaia_id, email, L""); if (FAILED(hr)) return hr; // At this point the user and password stored in authentication_results_ // should match what is stored in username_ and password_ so the // PerformPostSigninActions process can be forked. CComBSTR status_text; hr = ForkPerformPostSigninActionsStub(*authentication_results_, &status_text); if (FAILED(hr)) LOGFN(ERROR) << "ForkPerformPostSigninActionsStub hr=" << putHR(hr); } *ppszOptionalStatusText = nullptr; *pcpsiOptionalStatusIcon = CPSI_NONE; ResetInternalState(); return S_OK; } HRESULT CGaiaCredentialBase::GetUserSid(wchar_t** sid) { *sid = nullptr; return S_FALSE; } HRESULT CGaiaCredentialBase::Initialize(IGaiaCredentialProvider* provider) { LOGFN(VERBOSE); DCHECK(provider); provider_ = provider; return S_OK; } HRESULT CGaiaCredentialBase::Terminate() { LOGFN(VERBOSE); SetDeselected(); provider_.Reset(); return S_OK; } void CGaiaCredentialBase::TerminateLogonProcess() { // Terminate login UI process if started. This is best effort since it may // have already terminated. if (logon_ui_process_ != INVALID_HANDLE_VALUE) { LOGFN(VERBOSE) << "Attempting to kill logon UI process"; ::TerminateProcess(logon_ui_process_, kUiecKilled); logon_ui_process_ = INVALID_HANDLE_VALUE; } } HRESULT CGaiaCredentialBase::ValidateOrCreateUser(const base::Value& result, BSTR* domain, BSTR* username, BSTR* sid, BSTR* error_text) { LOGFN(VERBOSE); DCHECK(domain); DCHECK(username); DCHECK(sid); DCHECK(error_text); DCHECK(sid); *error_text = nullptr; wchar_t found_username[kWindowsUsernameBufferLength]; wchar_t found_domain[kWindowsDomainBufferLength]; wchar_t found_sid[kWindowsSidBufferLength]; bool is_consumer_account = false; std::wstring gaia_id; HRESULT hr = MakeUsernameForAccount( result, &gaia_id, found_username, base::size(found_username), found_domain, base::size(found_domain), found_sid, base::size(found_sid), &is_consumer_account, error_text); if (FAILED(hr)) { LOGFN(ERROR) << "MakeUsernameForAccount hr=" << putHR(hr); return hr; } // Disallow consumer accounts when mdm enrollment is enabled and the global // flag to allow consumer accounts is not set. if (MdmEnrollmentEnabled() && is_consumer_account) { DWORD allow_consumer_accounts = GetGlobalFlagOrDefault(kRegMdmAllowConsumerAccounts, 0); if (allow_consumer_accounts == 0) { LOGFN(ERROR) << "Consumer accounts are not allowed mdm_aca=" << allow_consumer_accounts; *error_text = AllocErrorString(IDS_DISALLOWED_CONSUMER_EMAIL_BASE); return E_FAIL; } } // Validates the authenticated user to either login to an existing user // profile or fall back to creation of a new user profile. Below are few // workflows. // // 1.) Add user flow with no existing association, found_sid should be empty, // falls through account creation // 2.) Reauth user flow with no existing association, found_sid should be // empty, login attempt fails. // 3.) Add user flow with existing association, found_sid exists, // logs into existing Windows account. // 4.) Reauth user flow with existing association, found_sid exists, // logs into existing Windows account if found_sid matches reauth user // sid. // 5.) Add user flow with cloud association, found_sid exists, // logs into existing account. // 6.) Add/Reauth user flow with cloud association, found_sid exists, // logs into existing account if found_sid matches reauth user sid. hr = ValidateExistingUser(found_username, found_domain, found_sid, error_text); if (FAILED(hr)) { LOGFN(ERROR) << "ValidateExistingUser hr=" << putHR(hr); return hr; } // If an existing user associated to the gaia id or email address was found, // make sure that it is valid for this credential. if (found_sid[0]) { // Update the name on the OS account if authenticated user has a different // name. std::wstring os_account_fullname; hr = OSUserManager::Get()->GetUserFullname(found_domain, found_username, &os_account_fullname); if (SUCCEEDED(hr)) { std::wstring profile_fullname = GetDictString(result, kKeyFullname); if (os_account_fullname.compare(profile_fullname.c_str()) != 0) { hr = OSUserManager::Get()->SetUserFullname(found_domain, found_username, profile_fullname.c_str()); // Failing to set Windows account full name shouldn't fail login. if (FAILED(hr)) LOGFN(ERROR) << "SetUserFullname hr=" << putHR(hr); } // Set disable password change policy here as well. This flow would // make sure password change is disabled even if any end user tries // to enable it via registry after user create or association flow. // Note: We donot fail the login flow if password policies were not // applied for unknown reasons. OSUserManager::Get()->SetDefaultPasswordChangePolicies(found_domain, found_username); } else { LOGFN(ERROR) << "GetUserFullname hr=" << putHR(hr); } *username = ::SysAllocString(found_username); *domain = ::SysAllocString(found_domain); *sid = ::SysAllocString(found_sid); return S_OK; } DWORD cpus = 0; provider()->GetUsageScenario(&cpus); // New users creation is not allowed during work station unlock. This code // prevents users from being created when the "Other User" tile appears on the // lock screen through certain system policy settings. In this situation only // the user who locked the computer is allowed to sign in. if (cpus == CPUS_UNLOCK_WORKSTATION) { *error_text = AllocErrorString(IDS_INVALID_UNLOCK_WORKSTATION_USER_BASE); return HRESULT_FROM_WIN32(ERROR_LOGON_TYPE_NOT_GRANTED); // This code prevents users from being created when the "Other User" tile // appears on the sign in scenario and only 1 user is allowed to use this // system. } else if (!CGaiaCredentialProvider::CanNewUsersBeCreated( static_cast<CREDENTIAL_PROVIDER_USAGE_SCENARIO>(cpus))) { *error_text = AllocErrorString(IDS_ADD_USER_DISALLOWED_BASE); return HRESULT_FROM_WIN32(ERROR_LOGON_TYPE_NOT_GRANTED); } std::wstring local_password = GetDictString(result, kKeyPassword); std::wstring local_fullname = GetDictString(result, kKeyFullname); std::wstring comment(GetStringResource(IDS_USER_ACCOUNT_COMMENT_BASE)); hr = CreateNewUser( OSUserManager::Get(), found_username, local_password.c_str(), local_fullname.c_str(), comment.c_str(), /*add_to_users_group=*/true, kMaxUsernameAttempts, username, sid); SecurelyClearString(local_password); // May return user exists if this is the anonymous credential and the maximum // attempts to generate a new username has been reached. if (hr == HRESULT_FROM_WIN32(NERR_UserExists)) { LOGFN(ERROR) << "Could not find a new username based on desired username '" << found_domain << "\\" << found_username << "'. Maximum attempts reached."; *error_text = AllocErrorString(IDS_INTERNAL_ERROR_BASE); return hr; } else if (hr == HRESULT_FROM_WIN32(NERR_PasswordTooShort)) { LOGFN(ERROR) << "Password being used is too short as per the group " << "policies set by your IT admin on this device."; *error_text = AllocErrorString(IDS_CREATE_USER_PASSWORD_TOO_SHORT_BASE); } else if (FAILED(hr)) { LOGFN(ERROR) << "Failed to create user '" << found_domain << "\\" << found_username << "'. hr=" << putHR(hr); *error_text = AllocErrorString(IDS_INTERNAL_ERROR_BASE); return hr; } *domain = ::SysAllocString(found_domain); return hr; } HRESULT CGaiaCredentialBase::OnUserAuthenticated(BSTR authentication_info, BSTR* status_text) { USES_CONVERSION; DCHECK(status_text); *status_text = nullptr; // Logon UI process is no longer needed and should already be finished by now // so clear the handle so that calls to HandleAutoLogon do not block further // processing thinking that there is still a logon process active. logon_ui_process_ = INVALID_HANDLE_VALUE; // Convert the string to a base::Dictionary and add the calculated username // to it to be passed to the PerformPostSigninActions process. std::string json_string; base::WideToUTF8(OLE2CW(authentication_info), ::SysStringLen(authentication_info), &json_string); absl::optional<base::Value> properties = base::JSONReader::Read(json_string, base::JSON_ALLOW_TRAILING_COMMAS); SecurelyClearString(json_string); json_string.clear(); if (!properties || !properties->is_dict()) { LOGFN(ERROR) << "base::JSONReader::Read failed to translate to JSON"; *status_text = AllocErrorString(IDS_INVALID_UI_RESPONSE_BASE); return E_FAIL; } { base::ScopedClosureRunner zero_dict_on_exit(base::BindOnce( &SecurelyClearDictionaryValue, base::Unretained(&properties))); HRESULT hr = ValidateResult(*properties, status_text); if (FAILED(hr)) { LOGFN(ERROR) << "ValidateResult hr=" << putHR(hr); return hr; } std::wstring email = GetDictString(*properties, kKeyEmail); std::vector<std::wstring> permitted_accounts = GetPermittedAccounts(); if (!permitted_accounts.empty() && std::find(permitted_accounts.begin(), permitted_accounts.end(), email) == permitted_accounts.end()) { *status_text = AllocErrorString(IDS_EMAIL_MISMATCH_BASE); return E_FAIL; } // The value in |dict| is now known to contain everything that is needed // from the GLS. Try to validate the user that wants to sign in and then // add additional information into |dict| as needed. hr = ValidateOrCreateUser(*properties, &domain_, &username_, &user_sid_, status_text); if (FAILED(hr)) { // In case an error text isn't set in any failure path, have one to use as // the last resort. if (*status_text == nullptr) *status_text = AllocErrorString(IDS_INVALID_UI_RESPONSE_BASE); LOGFN(ERROR) << "ValidateOrCreateUser hr=" << putHR(hr); return hr; } base::IgnoreResult(zero_dict_on_exit.Release()); authentication_results_ = std::move(properties); // Update the info whether the user is an AD joined user or local user. std::wstring sid = OLE2CW(user_sid_); authentication_results_->SetKey( kKeyIsAdJoinedUser, base::Value(OSUserManager::Get()->IsUserDomainJoined(sid) ? "true" : "false")); } std::wstring gaia_id = GetDictString(*authentication_results_, kKeyId); // TODO(crbug.com/976744) Use downscoped token here. std::wstring access_token = GetDictString(*authentication_results_, kKeyAccessToken); GetUserConfigsIfStale(OLE2CW(user_sid_), gaia_id, access_token); SecurelyClearString(access_token); std::wstring local_password = GetDictString(*authentication_results_, kKeyPassword); password_ = ::SysAllocString(local_password.c_str()); SecurelyClearString(local_password); // Disable the submit button. Either the signon will succeed with the given // credentials or a password update will be needed and that flow will handle // re-enabling the submit button in HandleAutoLogon. if (events_) events_->SetFieldInteractiveState(this, FID_SUBMIT, CPFIS_DISABLED); // Check if the credentials are valid for the user. If they aren't show the // password update prompt and continue without authenticating on the provider. if (!AreCredentialsValid()) { // Change UI into a mode where it expects to have the old password entered. std::wstring old_windows_password; needs_windows_password_ = true; // Pre-fill the old password if possible so that the sign in will proceed to // automatically update the password. if (SUCCEEDED(RecoverWindowsPasswordIfPossible(&old_windows_password))) { current_windows_password_ = ::SysAllocString(old_windows_password.c_str()); SecurelyClearString(old_windows_password); } else { // Fall-through to continue with auto sign in and try the recovered // password. DisplayPasswordField(IDS_PASSWORD_UPDATE_NEEDED_BASE); return S_FALSE; } } result_status_ = STATUS_SUCCESS; // Prevent update of token handle validity until after sign in has completed // so the list of credentials doesn't suddenly change between now and when the // attempt to auto login occurs. PreventDenyAccessUpdate(); // When this function returns, winlogon will be told to logon to the newly // created account. This is important, as the save account info process // can't actually save the info until the user's profile is created, which // happens on first logon. return provider_->OnUserAuthenticated(static_cast<IGaiaCredential*>(this), username_, password_, user_sid_, TRUE); } HRESULT CGaiaCredentialBase::ReportError(LONG status, LONG substatus, BSTR status_text) { USES_CONVERSION; LOGFN(VERBOSE); // Provider may be unset if the GLS process ended as a result of a kill // request coming from Terminate() which would release the |provider_| // reference. if (!provider_) return S_OK; result_status_ = status; // If the user cancelled out of the logon, the process may be already // terminated, but if the handle to the process is still valid the // credential provider will not start a new GLS process when requested so // try to terminate the logon process now and clear the handle. TerminateLogonProcess(); UpdateSubmitButtonInteractiveState(); DisplayErrorInUI(status, STATUS_SUCCESS, status_text); return provider_->OnUserAuthenticated(nullptr, CComBSTR(), CComBSTR(), CComBSTR(), FALSE); } bool CGaiaCredentialBase::UpdateSubmitButtonInteractiveState() { bool should_enable = logon_ui_process_ == INVALID_HANDLE_VALUE && ((!needs_windows_password_ || current_windows_password_.Length()) || (needs_windows_password_ && request_force_password_change_)); if (events_) { events_->SetFieldInteractiveState( this, FID_SUBMIT, should_enable ? CPFIS_NONE : CPFIS_DISABLED); } return should_enable; } void CGaiaCredentialBase::DisplayPasswordField(int password_message) { needs_windows_password_ = true; if (events_) { if (request_force_password_change_) { events_->SetFieldState(this, FID_CURRENT_PASSWORD_FIELD, CPFS_HIDDEN); events_->SetFieldString( this, FID_DESCRIPTION, GetStringResource(IDS_CONFIRM_FORCED_PASSWORD_CHANGE_BASE).c_str()); events_->SetFieldString( this, FID_FORGOT_PASSWORD_LINK, GetStringResource(IDS_ENTER_PASSWORD_LINK_BASE).c_str()); events_->SetFieldSubmitButton(this, FID_SUBMIT, FID_DESCRIPTION); } else { events_->SetFieldString(this, FID_DESCRIPTION, GetStringResource(password_message).c_str()); if (!BlockingPasswordError(password_message)) { events_->SetFieldState(this, FID_CURRENT_PASSWORD_FIELD, CPFS_DISPLAY_IN_SELECTED_TILE); // Force password link won't be displayed if the machine is domain // joined or force reset password is disabled through registry. if (!OSUserManager::Get()->IsUserDomainJoined(get_sid().m_str) && GetGlobalFlagOrDefault(kRegMdmEnableForcePasswordReset, 1)) { events_->SetFieldState(this, FID_FORGOT_PASSWORD_LINK, CPFS_DISPLAY_IN_SELECTED_TILE); events_->SetFieldString( this, FID_FORGOT_PASSWORD_LINK, GetStringResource(IDS_FORGOT_PASSWORD_LINK_BASE).c_str()); } events_->SetFieldInteractiveState(this, FID_CURRENT_PASSWORD_FIELD, CPFIS_FOCUSED); events_->SetFieldSubmitButton(this, FID_SUBMIT, FID_CURRENT_PASSWORD_FIELD); } } } } HRESULT CGaiaCredentialBase::ValidateExistingUser(const std::wstring& username, const std::wstring& domain, const std::wstring& sid, BSTR* error_text) { return S_OK; } HRESULT CGaiaCredentialBase::RecoverWindowsPasswordIfPossible( std::wstring* recovered_password) { DCHECK(recovered_password); if (!authentication_results_) { LOGFN(ERROR) << "No authentication results found during sign in"; return E_FAIL; } const std::string* access_token = authentication_results_->FindStringKey(kKeyAccessToken); if (!access_token) { LOGFN(ERROR) << "No access token found in authentication results"; return E_FAIL; } return PasswordRecoveryManager::Get()->RecoverWindowsPasswordIfPossible( OLE2CW(get_sid()), *access_token, recovered_password); } } // namespace credential_provider
37.483476
96
0.679482
[ "object", "vector", "transform" ]
3e5513df688a52f1325964c78115560423bcc51b
2,453
cpp
C++
UVa 12870 - Fishing/sample/12870 - Fishing.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2020-11-24T03:17:21.000Z
2020-11-24T03:17:21.000Z
UVa 12870 - Fishing/sample/12870 - Fishing.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
null
null
null
UVa 12870 - Fishing/sample/12870 - Fishing.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2021-04-11T16:22:31.000Z
2021-04-11T16:22:31.000Z
#include <stdio.h> #include <math.h> #include <algorithm> #include <set> #include <queue> #include <vector> using namespace std; #define MAXN 128 int dp[MAXN][MAXN][MAXN]; int dp2[MAXN][MAXN][MAXN]; int main() { int testcase; int n, m, A[128][128]; scanf("%d", &testcase); while (testcase--) { scanf("%d %d", &n, &m); for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) scanf("%d", &A[i][j]); int nm = min(n, m); int lenMAX[128] = {}, lenMIN[128] = {}; for (int i = 0; i <= nm; i++) { lenMAX[i] = 0; lenMIN[i] = -0x3f3f3f3f; } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { for (int k = 0; k <= nm; k++) { dp[i][j][k] = 0, dp2[i][j][k] = -0x3f3f3f3f; } } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { dp[i][j][1] = max(dp[i][j][1], A[i][j]); dp2[i][j][1] = max(dp2[i][j][1], -A[i][j]); for (int k = 1; k <= nm; k++) { if (i > 0) { dp[i][j][k] = max(dp[i][j][k], dp[i-1][j][k]); dp2[i][j][k] = max(dp2[i][j][k], dp2[i-1][j][k]); } if (j > 0) { dp[i][j][k] = max(dp[i][j][k], dp[i][j-1][k]); dp2[i][j][k] = max(dp2[i][j][k], dp2[i][j-1][k]); } if (i > 0 && j > 0) { dp[i][j][k] = max(dp[i][j][k], dp[i-1][j-1][k-1] + A[i][j]); dp2[i][j][k] = max(dp2[i][j][k], dp2[i-1][j-1][k-1] - A[i][j]); } // printf("%d %d %d %d\n", i, j, k, dp2[i][j][k]); } for (int k = 1; k <= nm; k++) lenMAX[k] = max(lenMAX[k], dp[i][j][k]), lenMIN[k] = max(lenMIN[k], dp2[i][j][k]); } } int ret = 0; for (int i = 2; i <= nm; i += 2) { ret = max(ret, lenMAX[i/2] + lenMIN[i]); // printf("%d %d %d\n", i, lenMAX[i/2], lenMIN[i]); } printf("%d\n", ret); } return 0; } /* 9999 4 4 1 1 1 4 1 3 1 1 1 1 2 1 1 1 1 1 3 5 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 4 0 0 1 0 0 0 2 0 0 1 0 0 2 2 0 1 2 0 2 3 10 20 30 30 4 50 3 2 10 20 30 30 4 50 */
27.255556
102
0.337138
[ "vector" ]
3e59c0b604a8fcc3deaac8f96f601a469b40606a
12,835
cpp
C++
src/armnn/test/TensorHandleStrategyTest.cpp
korabelnikov/armnn
8c3259fa007d43fcc5ea56fe6928526dbe79f3c0
[ "MIT" ]
null
null
null
src/armnn/test/TensorHandleStrategyTest.cpp
korabelnikov/armnn
8c3259fa007d43fcc5ea56fe6928526dbe79f3c0
[ "MIT" ]
null
null
null
src/armnn/test/TensorHandleStrategyTest.cpp
korabelnikov/armnn
8c3259fa007d43fcc5ea56fe6928526dbe79f3c0
[ "MIT" ]
null
null
null
// // Copyright © 2017 Arm Ltd. All rights reserved. // SPDX-License-Identifier: MIT // #include <boost/test/unit_test.hpp> #include <armnn/LayerVisitorBase.hpp> #include <armnn/backends/IBackendContext.hpp> #include <armnn/backends/IBackendInternal.hpp> #include <armnn/backends/IMemoryManager.hpp> #include <armnn/backends/ITensorHandleFactory.hpp> #include <backendsCommon/TensorHandleFactoryRegistry.hpp> #include <optimizations/Optimization.hpp> #include <Network.hpp> #include <vector> #include <string> #include <boost/core/ignore_unused.hpp> using namespace armnn; class TestMemMgr : public IMemoryManager { public: TestMemMgr() = default; void Acquire() override {} void Release() override {} }; class TestFactory1 : public ITensorHandleFactory { public: TestFactory1(std::weak_ptr<IMemoryManager> mgr, ITensorHandleFactory::FactoryId id) : m_Id(id) , m_MemMgr(mgr) {} std::unique_ptr<ITensorHandle> CreateSubTensorHandle(ITensorHandle& parent, TensorShape const& subTensorShape, unsigned int const* subTensorOrigin) const override { boost::ignore_unused(parent, subTensorShape, subTensorOrigin); return nullptr; } std::unique_ptr<ITensorHandle> CreateTensorHandle(const TensorInfo& tensorInfo) const override { boost::ignore_unused(tensorInfo); return nullptr; } std::unique_ptr<ITensorHandle> CreateTensorHandle(const TensorInfo& tensorInfo, DataLayout dataLayout) const override { boost::ignore_unused(tensorInfo, dataLayout); return nullptr; } const FactoryId& GetId() const override { return m_Id; } bool SupportsSubTensors() const override { return true; } MemorySourceFlags GetExportFlags() const override { return 1; } private: FactoryId m_Id = "UninitializedId"; std::weak_ptr<IMemoryManager> m_MemMgr; }; class TestFactoryImport : public ITensorHandleFactory { public: TestFactoryImport(std::weak_ptr<IMemoryManager> mgr, ITensorHandleFactory::FactoryId id) : m_Id(id) , m_MemMgr(mgr) {} std::unique_ptr<ITensorHandle> CreateSubTensorHandle(ITensorHandle& parent, TensorShape const& subTensorShape, unsigned int const* subTensorOrigin) const override { boost::ignore_unused(parent, subTensorShape, subTensorOrigin); return nullptr; } std::unique_ptr<ITensorHandle> CreateTensorHandle(const TensorInfo& tensorInfo) const override { boost::ignore_unused(tensorInfo); return nullptr; } std::unique_ptr<ITensorHandle> CreateTensorHandle(const TensorInfo& tensorInfo, DataLayout dataLayout) const override { boost::ignore_unused(tensorInfo, dataLayout); return nullptr; } const FactoryId& GetId() const override { return m_Id; } bool SupportsSubTensors() const override { return true; } MemorySourceFlags GetImportFlags() const override { return 1; } private: FactoryId m_Id = "ImporterId"; std::weak_ptr<IMemoryManager> m_MemMgr; }; class TestBackendA : public IBackendInternal { public: TestBackendA() = default; const BackendId& GetId() const override { return m_Id; } IWorkloadFactoryPtr CreateWorkloadFactory(const IMemoryManagerSharedPtr& memoryManager = nullptr) const override { boost::ignore_unused(memoryManager); return IWorkloadFactoryPtr{}; } IBackendInternal::ILayerSupportSharedPtr GetLayerSupport() const override { return ILayerSupportSharedPtr{}; } std::vector<ITensorHandleFactory::FactoryId> GetHandleFactoryPreferences() const override { return std::vector<ITensorHandleFactory::FactoryId> { "TestHandleFactoryA1", "TestHandleFactoryA2", "TestHandleFactoryB1" }; } void RegisterTensorHandleFactories(TensorHandleFactoryRegistry& registry) override { auto mgr = std::make_shared<TestMemMgr>(); registry.RegisterMemoryManager(mgr); registry.RegisterFactory(std::make_unique<TestFactory1>(mgr, "TestHandleFactoryA1")); registry.RegisterFactory(std::make_unique<TestFactory1>(mgr, "TestHandleFactoryA2")); } private: BackendId m_Id = "BackendA"; }; class TestBackendB : public IBackendInternal { public: TestBackendB() = default; const BackendId& GetId() const override { return m_Id; } IWorkloadFactoryPtr CreateWorkloadFactory(const IMemoryManagerSharedPtr& memoryManager = nullptr) const override { boost::ignore_unused(memoryManager); return IWorkloadFactoryPtr{}; } IBackendInternal::ILayerSupportSharedPtr GetLayerSupport() const override { return ILayerSupportSharedPtr{}; } std::vector<ITensorHandleFactory::FactoryId> GetHandleFactoryPreferences() const override { return std::vector<ITensorHandleFactory::FactoryId> { "TestHandleFactoryB1" }; } void RegisterTensorHandleFactories(TensorHandleFactoryRegistry& registry) override { auto mgr = std::make_shared<TestMemMgr>(); registry.RegisterMemoryManager(mgr); registry.RegisterFactory(std::make_unique<TestFactory1>(mgr, "TestHandleFactoryB1")); } private: BackendId m_Id = "BackendB"; }; class TestBackendC : public IBackendInternal { public: TestBackendC() = default; const BackendId& GetId() const override { return m_Id; } IWorkloadFactoryPtr CreateWorkloadFactory(const IMemoryManagerSharedPtr& memoryManager = nullptr) const override { boost::ignore_unused(memoryManager); return IWorkloadFactoryPtr{}; } IBackendInternal::ILayerSupportSharedPtr GetLayerSupport() const override { return ILayerSupportSharedPtr{}; } std::vector<ITensorHandleFactory::FactoryId> GetHandleFactoryPreferences() const override { return std::vector<ITensorHandleFactory::FactoryId>{ "TestHandleFactoryC1" }; } void RegisterTensorHandleFactories(TensorHandleFactoryRegistry& registry) override { auto mgr = std::make_shared<TestMemMgr>(); registry.RegisterMemoryManager(mgr); registry.RegisterFactory(std::make_unique<TestFactory1>(mgr, "TestHandleFactoryC1")); } private: BackendId m_Id = "BackendC"; }; class TestBackendD : public IBackendInternal { public: TestBackendD() = default; const BackendId& GetId() const override { return m_Id; } IWorkloadFactoryPtr CreateWorkloadFactory(const IMemoryManagerSharedPtr& memoryManager = nullptr) const override { boost::ignore_unused(memoryManager); return IWorkloadFactoryPtr{}; } IBackendInternal::ILayerSupportSharedPtr GetLayerSupport() const override { return ILayerSupportSharedPtr{}; } std::vector<ITensorHandleFactory::FactoryId> GetHandleFactoryPreferences() const override { return std::vector<ITensorHandleFactory::FactoryId>{ "TestHandleFactoryD1" }; } void RegisterTensorHandleFactories(TensorHandleFactoryRegistry& registry) override { auto mgr = std::make_shared<TestMemMgr>(); registry.RegisterMemoryManager(mgr); registry.RegisterFactory(std::make_unique<TestFactoryImport>(mgr, "TestHandleFactoryD1")); } private: BackendId m_Id = "BackendD"; }; BOOST_AUTO_TEST_SUITE(TensorHandle) BOOST_AUTO_TEST_CASE(RegisterFactories) { TestBackendA backendA; TestBackendB backendB; BOOST_TEST(backendA.GetHandleFactoryPreferences()[0] == "TestHandleFactoryA1"); BOOST_TEST(backendA.GetHandleFactoryPreferences()[1] == "TestHandleFactoryA2"); BOOST_TEST(backendA.GetHandleFactoryPreferences()[2] == "TestHandleFactoryB1"); TensorHandleFactoryRegistry registry; backendA.RegisterTensorHandleFactories(registry); backendB.RegisterTensorHandleFactories(registry); BOOST_TEST((registry.GetFactory("Non-existing Backend") == nullptr)); BOOST_TEST((registry.GetFactory("TestHandleFactoryA1") != nullptr)); BOOST_TEST((registry.GetFactory("TestHandleFactoryA2") != nullptr)); BOOST_TEST((registry.GetFactory("TestHandleFactoryB1") != nullptr)); } BOOST_AUTO_TEST_CASE(TensorHandleSelectionStrategy) { auto backendA = std::make_unique<TestBackendA>(); auto backendB = std::make_unique<TestBackendB>(); auto backendC = std::make_unique<TestBackendC>(); auto backendD = std::make_unique<TestBackendD>(); TensorHandleFactoryRegistry registry; backendA->RegisterTensorHandleFactories(registry); backendB->RegisterTensorHandleFactories(registry); backendC->RegisterTensorHandleFactories(registry); backendD->RegisterTensorHandleFactories(registry); BackendsMap backends; backends["BackendA"] = std::move(backendA); backends["BackendB"] = std::move(backendB); backends["BackendC"] = std::move(backendC); backends["BackendD"] = std::move(backendD); armnn::Graph graph; armnn::InputLayer* const inputLayer = graph.AddLayer<armnn::InputLayer>(0, "input"); inputLayer->SetBackendId("BackendA"); armnn::SoftmaxDescriptor smDesc; armnn::SoftmaxLayer* const softmaxLayer1 = graph.AddLayer<armnn::SoftmaxLayer>(smDesc, "softmax1"); softmaxLayer1->SetBackendId("BackendA"); armnn::SoftmaxLayer* const softmaxLayer2 = graph.AddLayer<armnn::SoftmaxLayer>(smDesc, "softmax2"); softmaxLayer2->SetBackendId("BackendB"); armnn::SoftmaxLayer* const softmaxLayer3 = graph.AddLayer<armnn::SoftmaxLayer>(smDesc, "softmax3"); softmaxLayer3->SetBackendId("BackendC"); armnn::SoftmaxLayer* const softmaxLayer4 = graph.AddLayer<armnn::SoftmaxLayer>(smDesc, "softmax4"); softmaxLayer4->SetBackendId("BackendD"); armnn::OutputLayer* const outputLayer = graph.AddLayer<armnn::OutputLayer>(0, "output"); outputLayer->SetBackendId("BackendA"); inputLayer->GetOutputSlot(0).Connect(softmaxLayer1->GetInputSlot(0)); softmaxLayer1->GetOutputSlot(0).Connect(softmaxLayer2->GetInputSlot(0)); softmaxLayer2->GetOutputSlot(0).Connect(softmaxLayer3->GetInputSlot(0)); softmaxLayer3->GetOutputSlot(0).Connect(softmaxLayer4->GetInputSlot(0)); softmaxLayer4->GetOutputSlot(0).Connect(outputLayer->GetInputSlot(0)); graph.TopologicalSort(); std::vector<std::string> errors; auto result = SelectTensorHandleStrategy(graph, backends, registry, errors); BOOST_TEST(result.m_Error == false); BOOST_TEST(result.m_Warning == false); OutputSlot& inputLayerOut = inputLayer->GetOutputSlot(0); OutputSlot& softmaxLayer1Out = softmaxLayer1->GetOutputSlot(0); OutputSlot& softmaxLayer2Out = softmaxLayer2->GetOutputSlot(0); OutputSlot& softmaxLayer3Out = softmaxLayer3->GetOutputSlot(0); OutputSlot& softmaxLayer4Out = softmaxLayer4->GetOutputSlot(0); // Check that the correct factory was selected BOOST_TEST(inputLayerOut.GetTensorHandleFactoryId() == "TestHandleFactoryA1"); BOOST_TEST(softmaxLayer1Out.GetTensorHandleFactoryId() == "TestHandleFactoryB1"); BOOST_TEST(softmaxLayer2Out.GetTensorHandleFactoryId() == "TestHandleFactoryB1"); BOOST_TEST(softmaxLayer3Out.GetTensorHandleFactoryId() == "TestHandleFactoryC1"); BOOST_TEST(softmaxLayer4Out.GetTensorHandleFactoryId() == "TestHandleFactoryD1"); // Check that the correct strategy was selected BOOST_TEST((inputLayerOut.GetEdgeStrategyForConnection(0) == EdgeStrategy::DirectCompatibility)); BOOST_TEST((softmaxLayer1Out.GetEdgeStrategyForConnection(0) == EdgeStrategy::DirectCompatibility)); BOOST_TEST((softmaxLayer2Out.GetEdgeStrategyForConnection(0) == EdgeStrategy::CopyToTarget)); BOOST_TEST((softmaxLayer3Out.GetEdgeStrategyForConnection(0) == EdgeStrategy::ExportToTarget)); BOOST_TEST((softmaxLayer4Out.GetEdgeStrategyForConnection(0) == EdgeStrategy::DirectCompatibility)); graph.AddCompatibilityLayers(backends, registry); // Test for copy layers int copyCount= 0; graph.ForEachLayer([&copyCount](Layer* layer) { if (layer->GetType() == LayerType::MemCopy) { copyCount++; } }); BOOST_TEST(copyCount == 1); // Test for import layers int importCount= 0; graph.ForEachLayer([&importCount](Layer *layer) { if (layer->GetType() == LayerType::MemImport) { importCount++; } }); BOOST_TEST(importCount == 1); } BOOST_AUTO_TEST_SUITE_END()
32.742347
116
0.703857
[ "vector" ]
3e59cb21e8fe5bfeaa2af3cc38fe9e7bd8f33e6f
1,205
cpp
C++
mr.Sadman/Classes/GameAct/Objects/Physical/Bullets.cpp
1pkg/dump
0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b
[ "MIT" ]
null
null
null
mr.Sadman/Classes/GameAct/Objects/Physical/Bullets.cpp
1pkg/dump
0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b
[ "MIT" ]
3
2020-12-11T10:01:27.000Z
2022-02-13T22:12:05.000Z
mr.Sadman/Classes/GameAct/Objects/Physical/Bullets.cpp
1pkg/dump
0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b
[ "MIT" ]
null
null
null
#include "Bullets.hpp" #include "Resources/Cache/Cache.hpp" namespace GameAct { namespace Physical { void Bullets::initialize() { Stream::initialize(); _particle->setTexture( Resources::Cache::getInstance().getObjectRepresentation( getName() )->getTexture() ); _particle->setStartColor( cocos2d::Color4F::BLACK ); _particle->setEndColor( cocos2d::Color4F::BLACK ); } std::string Bullets::getName() const { return "Bullets"; } void Bullets::setSize( cocos2d::Size size ) { // configuration _particle->setStartSize( 5.0f ); _particle->setEndSize( 5.0f ); _particle->setStartSizeVar( 0.0f ); _particle->setEndSizeVar( 0.0f ); _particle->setRadialAccel( size.width * size.width / 500.0f ); _particle->setLife( 0.7f ); _particle->setLifeVar( 0.2f ); _particle->setEmissionRate( 80.0f ); float delta = 3.0f * size.width; float x = delta * sin( CC_DEGREES_TO_RADIANS( _angle + 90.0f ) ); float y = delta * cos( CC_DEGREES_TO_RADIANS( _angle + 90.0f ) ); _particle->setGravity( cocos2d::Vec2( x, y ) ); Object::setSize( size ); } void Bullets::setRotation( float angle ) { _angle = angle; Stream::setRotation( angle ); } } }
21.140351
110
0.66888
[ "object" ]
3e5c4e16f80262dbf8990fe395951644679c23b9
1,814
cpp
C++
Chapter11/chapter11ca_02/main.cpp
markccchiang/Modern-Cpp-Programming-Cookbook
42ba3c9ca1e0d897807f1c3baa5dddb0ee064f23
[ "MIT" ]
null
null
null
Chapter11/chapter11ca_02/main.cpp
markccchiang/Modern-Cpp-Programming-Cookbook
42ba3c9ca1e0d897807f1c3baa5dddb0ee064f23
[ "MIT" ]
null
null
null
Chapter11/chapter11ca_02/main.cpp
markccchiang/Modern-Cpp-Programming-Cookbook
42ba3c9ca1e0d897807f1c3baa5dddb0ee064f23
[ "MIT" ]
null
null
null
#define CATCH_CONFIG_MAIN #include <catch2/catch.hpp> #include "../testlib/point3d.h" TEST_CASE("test construction", "[create]") { SECTION("test constructor") { auto p = point3d{1, 2, 3}; REQUIRE(p.x() == 1); REQUIRE(p.y() == 2); REQUIRE(p.z() == 4); } SECTION("test origin") { auto p = point3d::origin(); REQUIRE(p.x() == 0); REQUIRE(p.y() == 0); REQUIRE(p.z() == 0); } } TEST_CASE("test operations", "[modify]") { SECTION("test methods") { SECTION("test offset") { auto p = point3d{1, 2, 3}; p.offset(1, 1, 1); REQUIRE(p.x() == 2); REQUIRE(p.y() == 3); REQUIRE(p.z() == 3); } } } TEST_CASE("test operators", "[compare][op]") { SECTION("test equal") { auto p1 = point3d{1, 2, 3}; auto p2 = point3d{1, 2, 3}; auto p3 = point3d{3, 2, 1}; REQUIRE(p1 == p2); REQUIRE(p1 == p3); } SECTION("test not equal") { auto p1 = point3d{1, 2, 3}; auto p2 = point3d{3, 2, 1}; REQUIRE(p1 != p2); } SECTION("test less") { auto p1 = point3d{1, 2, 3}; auto p2 = point3d{1, 2, 3}; auto p3 = point3d{3, 2, 1}; REQUIRE(!(p1 < p2)); REQUIRE(p1 < p3); } } SCENARIO("modify existing object") { GIVEN("a default constructed point") { auto p = point3d{}; REQUIRE(p.x() == 0); REQUIRE(p.y() == 0); REQUIRE(p.z() == 0); WHEN("increased with 1 unit on all dimensions") { p.offset(1, 1, 1); THEN("all coordinates are equal to 1") { REQUIRE(p.x() == 1); REQUIRE(p.y() == 1); REQUIRE(p.z() == 1); } } } }
23.868421
57
0.450386
[ "object" ]
3e69f859e9351c30b50a259e73b59f8531ba0423
1,005
hpp
C++
kinect/gesturenet.hpp
mik90/kinect-time
6777350f3744724877a6006c39eb7e06f0925889
[ "MIT" ]
null
null
null
kinect/gesturenet.hpp
mik90/kinect-time
6777350f3744724877a6006c39eb7e06f0925889
[ "MIT" ]
null
null
null
kinect/gesturenet.hpp
mik90/kinect-time
6777350f3744724877a6006c39eb7e06f0925889
[ "MIT" ]
null
null
null
#pragma once #include <cstddef> #include <cstdint> #include <filesystem> #include <future> #include <optional> #include <queue> #include <thread> namespace mik { struct GestureNetPixel { std::uint8_t red; std::uint8_t green; std::uint8_t blue; std::array<std::uint8_t, 3> to_bytes() const { return {red, green, blue}; } }; /** * @brief Input frame for nvidia GestureNet. Create from a kinect frame */ class GestureNetFrame { public: using PixelRow = std::vector<GestureNetPixel>; void save_frame(const std::filesystem::path& output_dir, size_t sequence) const; static std::size_t bytes_per_pixel() noexcept { return 3; }; static std::size_t width_in_pixels() noexcept { return 160; }; static std::size_t height_in_pixels() noexcept { return 160; }; // void downscale_height(); Convert 1920 to 160 pixels GestureNetFrame(std::vector<PixelRow> rows) : pixel_rows_(std::move(rows)){}; private: std::vector<PixelRow> pixel_rows_; }; } // namespace mik
28.714286
84
0.700498
[ "vector" ]
3e6bc9d851e71f3856df99dd1765415341207e5f
13,854
cpp
C++
nesSwift/nes/src/ppu.cpp
Kautenja/nes-iOS
9255e2d8d86cbaecd1ff186387ce20f83b37a0d9
[ "MIT" ]
3
2021-03-05T17:50:37.000Z
2021-12-25T08:30:12.000Z
nes_py/nes/src/ppu.cpp
fo40225/nes-py
a113885198d418f38fcf24b8f79ac508975788c2
[ "MIT" ]
2
2019-07-06T02:07:48.000Z
2021-05-21T03:01:55.000Z
nes_py/nes/src/ppu.cpp
fo40225/nes-py
a113885198d418f38fcf24b8f79ac508975788c2
[ "MIT" ]
null
null
null
// Program: nes-py // File: ppu.cpp // Description: This class houses the logic and data for the PPU of an NES // // Copyright (c) 2019 Christian Kauten. All rights reserved. // #include "ppu.hpp" #include "palette.hpp" #include "log.hpp" #include <cstring> void PPU::reset() { is_long_sprites = is_interrupting = is_vblank = false; is_showing_background = is_showing_sprites = is_even_frame = is_first_write = true; background_page = sprite_page = LOW; data_address = 0; cycles = 0; scanline = 0; sprite_data_address = 0; fine_x_scroll = 0; temp_address = 0; data_address_increment = 1; pipeline_state = PRE_RENDER; scanline_sprites.reserve(8); scanline_sprites.resize(0); } void PPU::cycle(PictureBus& bus) { switch (pipeline_state) { case PRE_RENDER: if (cycles == 1) is_vblank = is_sprite_zero_hit = false; else if (cycles == SCANLINE_VISIBLE_DOTS + 2 && is_showing_background && is_showing_sprites) { //Set bits related to horizontal position data_address &= ~0x41f; //Unset horizontal bits data_address |= temp_address & 0x41f; //Copy } else if (cycles > 280 && cycles <= 304 && is_showing_background && is_showing_sprites) { //Set vertical bits data_address &= ~0x7be0; //Unset bits related to horizontal data_address |= temp_address & 0x7be0; //Copy } // if (cycles > 257 && cycles < 320) // sprite_data_address = 0; // if rendering is on, every other frame is one cycle shorter if (cycles >= SCANLINE_END_CYCLE - (!is_even_frame && is_showing_background && is_showing_sprites)) { pipeline_state = RENDER; cycles = scanline = 0; } break; case RENDER: if (cycles > 0 && cycles <= SCANLINE_VISIBLE_DOTS) { NES_Byte bgColor = 0, sprColor = 0; bool bgOpaque = false, sprOpaque = true; bool spriteForeground = false; int x = cycles - 1; int y = scanline; if (is_showing_background) { auto x_fine = (fine_x_scroll + x) % 8; if (!is_hiding_edge_background || x >= 8) { // fetch tile // mask off fine y auto address = 0x2000 | (data_address & 0x0FFF); //auto address = 0x2000 + x / 8 + (y / 8) * (SCANLINE_VISIBLE_DOTS / 8); NES_Byte tile = bus.read(address); //fetch pattern //Each pattern occupies 16 bytes, so multiply by 16 //Add fine y address = (tile * 16) + ((data_address >> 12/*y % 8*/) & 0x7); //set whether the pattern is in the high or low page address |= background_page << 12; //Get the corresponding bit determined by (8 - x_fine) from the right //bit 0 of palette entry bgColor = (bus.read(address) >> (7 ^ x_fine)) & 1; //bit 1 bgColor |= ((bus.read(address + 8) >> (7 ^ x_fine)) & 1) << 1; //flag used to calculate final pixel with the sprite pixel bgOpaque = bgColor; //fetch attribute and calculate higher two bits of palette address = 0x23C0 | (data_address & 0x0C00) | ((data_address >> 4) & 0x38) | ((data_address >> 2) & 0x07); auto attribute = bus.read(address); int shift = ((data_address >> 4) & 4) | (data_address & 2); //Extract and set the upper two bits for the color bgColor |= ((attribute >> shift) & 0x3) << 2; } //Increment/wrap coarse X if (x_fine == 7) { // if coarse X == 31 if ((data_address & 0x001F) == 31) { // coarse X = 0 data_address &= ~0x001F; // switch horizontal nametable data_address ^= 0x0400; } else // increment coarse X data_address += 1; } } if (is_showing_sprites && (!is_hiding_edge_sprites || x >= 8)) { for (auto i : scanline_sprites) { NES_Byte spr_x = sprite_memory[i * 4 + 3]; if (0 > x - spr_x || x - spr_x >= 8) continue; NES_Byte spr_y = sprite_memory[i * 4 + 0] + 1, tile = sprite_memory[i * 4 + 1], attribute = sprite_memory[i * 4 + 2]; int length = (is_long_sprites) ? 16 : 8; int x_shift = (x - spr_x) % 8, y_offset = (y - spr_y) % length; if ((attribute & 0x40) == 0) //If NOT flipping horizontally x_shift ^= 7; if ((attribute & 0x80) != 0) //IF flipping vertically y_offset ^= (length - 1); NES_Address address = 0; if (!is_long_sprites) { address = tile * 16 + y_offset; if (sprite_page == HIGH) address += 0x1000; } // 8 x 16 sprites else { //bit-3 is one if it is the bottom tile of the sprite, multiply by two to get the next pattern y_offset = (y_offset & 7) | ((y_offset & 8) << 1); address = (tile >> 1) * 32 + y_offset; address |= (tile & 1) << 12; //Bank 0x1000 if bit-0 is high } sprColor |= (bus.read(address) >> (x_shift)) & 1; //bit 0 of palette entry sprColor |= ((bus.read(address + 8) >> (x_shift)) & 1) << 1; //bit 1 if (!(sprOpaque = sprColor)) { sprColor = 0; continue; } sprColor |= 0x10; //Select sprite palette sprColor |= (attribute & 0x3) << 2; //bits 2-3 spriteForeground = !(attribute & 0x20); //Sprite-0 hit detection if (!is_sprite_zero_hit && is_showing_background && i == 0 && sprOpaque && bgOpaque) is_sprite_zero_hit = true; break; //Exit the loop now since we've found the highest priority sprite } } // get the address of the color in the palette NES_Byte paletteAddr = bgColor; if ( (!bgOpaque && sprOpaque) || (bgOpaque && sprOpaque && spriteForeground) ) paletteAddr = sprColor; else if (!bgOpaque && !sprOpaque) paletteAddr = 0; // lookup the pixel in the palette and write it to the screen screen[y][x] = PALETTE[bus.read_palette(paletteAddr)]; } else if (cycles == SCANLINE_VISIBLE_DOTS + 1 && is_showing_background) { //Shamelessly copied from nesdev wiki if ((data_address & 0x7000) != 0x7000) // if fine Y < 7 data_address += 0x1000; // increment fine Y else { data_address &= ~0x7000; // fine Y = 0 int y = (data_address & 0x03E0) >> 5; // let y = coarse Y if (y == 29) { y = 0; // coarse Y = 0 data_address ^= 0x0800; // switch vertical nametable } else if (y == 31) y = 0; // coarse Y = 0, nametable not switched else y += 1; // increment coarse Y data_address = (data_address & ~0x03E0) | (y << 5); // put coarse Y back into data_address } } else if (cycles == SCANLINE_VISIBLE_DOTS + 2 && is_showing_background && is_showing_sprites) { //Copy bits related to horizontal position data_address &= ~0x41f; data_address |= temp_address & 0x41f; } // if (cycles > 257 && cycles < 320) // sprite_data_address = 0; if (cycles >= SCANLINE_END_CYCLE) { //Find and index sprites that are on the next Scanline //This isn't where/when this indexing, actually copying in 2C02 is done //but (I think) it shouldn't hurt any games if this is done here scanline_sprites.resize(0); int range = 8; if (is_long_sprites) range = 16; NES_Byte j = 0; for (NES_Byte i = sprite_data_address / 4; i < 64; ++i) { auto diff = (scanline - sprite_memory[i * 4]); if (0 <= diff && diff < range) { scanline_sprites.push_back(i); if (++j >= 8) break; } } ++scanline; cycles = 0; } if (scanline >= VISIBLE_SCANLINES) pipeline_state = POST_RENDER; break; case POST_RENDER: if (cycles >= SCANLINE_END_CYCLE) { ++scanline; cycles = 0; pipeline_state = VERTICAL_BLANK; } break; case VERTICAL_BLANK: if (cycles == 1 && scanline == VISIBLE_SCANLINES + 1) { is_vblank = true; if (is_interrupting) vblank_callback(); } if (cycles >= SCANLINE_END_CYCLE) { ++scanline; cycles = 0; } if (scanline >= FRAME_END_SCANLINE) { pipeline_state = PRE_RENDER; scanline = 0; is_even_frame = !is_even_frame; // is_vblank = false; } break; default: LOG(Error) << "Well, this shouldn't have happened." << std::endl; } ++cycles; } void PPU::do_DMA(const NES_Byte* page_ptr) { std::memcpy(sprite_memory.data() + sprite_data_address, page_ptr, 256 - sprite_data_address); if (sprite_data_address) std::memcpy(sprite_memory.data(), page_ptr + (256 - sprite_data_address), sprite_data_address); } void PPU::control(NES_Byte ctrl) { is_interrupting = ctrl & 0x80; is_long_sprites = ctrl & 0x20; background_page = static_cast<CharacterPage>(!!(ctrl & 0x10)); sprite_page = static_cast<CharacterPage>(!!(ctrl & 0x8)); if (ctrl & 0x4) data_address_increment = 0x20; else data_address_increment = 1; //baseNameTable = (ctrl & 0x3) * 0x400 + 0x2000; //Set the nametable in the temp address, this will be reflected in the data address during rendering temp_address &= ~0xc00; //Unset temp_address |= (ctrl & 0x3) << 10; //Set according to ctrl bits } void PPU::set_mask(NES_Byte mask) { is_hiding_edge_background = !(mask & 0x2); is_hiding_edge_sprites = !(mask & 0x4); is_showing_background = mask & 0x8; is_showing_sprites = mask & 0x10; } NES_Byte PPU::get_status() { NES_Byte status = is_sprite_zero_hit << 6 | is_vblank << 7; //data_address = 0; is_vblank = false; is_first_write = true; return status; } void PPU::set_data_address(NES_Byte address) { //data_address = ((data_address << 8) & 0xff00) | address; if (is_first_write) { //Unset the upper byte temp_address &= ~0xff00; temp_address |= (address & 0x3f) << 8; is_first_write = false; } else { //Unset the lower byte; temp_address &= ~0xff; temp_address |= address; data_address = temp_address; is_first_write = true; } } NES_Byte PPU::get_data(PictureBus& bus) { auto data = bus.read(data_address); data_address += data_address_increment; // Reads are delayed by one byte/read when address is in this range if (data_address < 0x3f00) //Return from the data buffer and store the current value in the buffer std::swap(data, data_buffer); return data; } void PPU::set_data(PictureBus& bus, NES_Byte data) { bus.write(data_address, data); data_address += data_address_increment; } void PPU::set_scroll(NES_Byte scroll) { if (is_first_write) { temp_address &= ~0x1f; temp_address |= (scroll >> 3) & 0x1f; fine_x_scroll = scroll & 0x7; is_first_write = false; } else { temp_address &= ~0x73e0; temp_address |= ((scroll & 0x7) << 12) | ((scroll & 0xf8) << 2); is_first_write = true; } }
39.925072
122
0.475314
[ "render" ]
3e75910326a5e1faec5d760621556da229f062b2
3,954
hpp
C++
modules/models/dynamic/single_track.hpp
ChenyangTang1/bark
c4215be6464c249639b8c7b390684bd13100b41e
[ "MIT" ]
null
null
null
modules/models/dynamic/single_track.hpp
ChenyangTang1/bark
c4215be6464c249639b8c7b390684bd13100b41e
[ "MIT" ]
null
null
null
modules/models/dynamic/single_track.hpp
ChenyangTang1/bark
c4215be6464c249639b8c7b390684bd13100b41e
[ "MIT" ]
null
null
null
// Copyright (c) 2019 fortiss GmbH, Julian Bernhard, Klemens Esterle, Patrick // Hart, Tobias Kessler // // This work is licensed under the terms of the MIT license. // For a copy, see <https://opensource.org/licenses/MIT>. #ifndef MODULES_MODELS_DYNAMIC_SINGLE_TRACK_HPP_ #define MODULES_MODELS_DYNAMIC_SINGLE_TRACK_HPP_ #include <algorithm> #include <memory> #include "modules/commons/transformation/frenet_state.hpp" #include "modules/models/dynamic/dynamic_model.hpp" namespace modules { namespace models { namespace dynamic { class SingleTrackModel : public DynamicModel { public: explicit SingleTrackModel(const modules::commons::ParamsPtr& params) : DynamicModel(params), wheel_base_(2.7), steering_angle_max_(0.2), lat_acceleration_max_(4.0) { wheel_base_ = params->GetReal("DynamicModel::wheel_base", "Wheel base of vehicle [m]", 2.7); steering_angle_max_ = params->GetReal("DynamicModel::delta_max", "Maximum Steering Angle [rad]", 0.2); lat_acceleration_max_ = params->GetReal("DynamicModel::lat_acc_max", "Maximum lateral acceleration [m/s^2]", 4.0); } virtual ~SingleTrackModel() {} State StateSpaceModel(const State& x, const Input& u) const { // TODO(@fortiss): get parameters from Params State tmp(static_cast<int>(StateDefinition::MIN_STATE_SIZE)); tmp << 1, x(StateDefinition::VEL_POSITION) * cos(x(StateDefinition::THETA_POSITION)), x(StateDefinition::VEL_POSITION) * sin(x(StateDefinition::THETA_POSITION)), x(StateDefinition::VEL_POSITION) * tan(u(1)) / wheel_base_, u(0); return tmp; } std::shared_ptr<DynamicModel> Clone() const { std::shared_ptr<SingleTrackModel> model_ptr = std::make_shared<SingleTrackModel>(*this); return std::dynamic_pointer_cast<DynamicModel>(model_ptr); } double GetWheelBase() const { return wheel_base_; } double GetSteeringAngleMax() const { return steering_angle_max_; } double GetLatAccelerationMax() const { return lat_acceleration_max_; } private: double wheel_base_; double steering_angle_max_; double lat_acceleration_max_; }; using SingleTrackModelPtr = std::shared_ptr<SingleTrackModel>; inline double CalculateSteeringAngle(const SingleTrackModelPtr& model, const State& state, const modules::geometry::Line& ref_line, double gain) { // Implemented after G. M. Hoffmann, C. J. Tomlin, M. Montemerlo, and S. // Thrun, “Autonomous Automobile Trajectory Tracking for Off-Road Driving: // Controller Design, Experimental Validation and Racing,” in 2007 ACC // // Author: Luis Gressenbuch using modules::commons::transformation::FrenetState; using StateDefinition::THETA_POSITION; using StateDefinition::X_POSITION; using StateDefinition::Y_POSITION; const double l = model->GetWheelBase(); // Calculating State of Front Axle State state_front(static_cast<int>(StateDefinition::MIN_STATE_SIZE)); state_front = state; state_front(X_POSITION) = state(X_POSITION) + l * cos(state(THETA_POSITION)); state_front(Y_POSITION) = state(Y_POSITION) + l * sin(state(THETA_POSITION)); FrenetState f_state = FrenetState(state_front, ref_line); double vel = state(StateDefinition::VEL_POSITION); double delta = f_state.angle + atan2(-gain * f_state.lat, vel); double delta_max = std::min( model->GetSteeringAngleMax(), std::abs(std::atan2( model->GetLatAccelerationMax() * model->GetWheelBase(), vel * vel))); double clamped_delta = std::min(delta, delta_max); clamped_delta = std::max(clamped_delta, -delta_max); return clamped_delta; } } // namespace dynamic } // namespace models } // namespace modules #endif // MODULES_MODELS_DYNAMIC_SINGLE_TRACK_HPP_
36.953271
79
0.69221
[ "geometry", "model" ]
3e7da724cd5f73ab8088b9c36e03d1a7a62942ac
26,718
cc
C++
src/ui/bin/root_presenter/presentation.cc
zarelaky/fuchsia
858cc1914de722b13afc2aaaee8a6bd491cd8d9a
[ "BSD-3-Clause" ]
null
null
null
src/ui/bin/root_presenter/presentation.cc
zarelaky/fuchsia
858cc1914de722b13afc2aaaee8a6bd491cd8d9a
[ "BSD-3-Clause" ]
null
null
null
src/ui/bin/root_presenter/presentation.cc
zarelaky/fuchsia
858cc1914de722b13afc2aaaee8a6bd491cd8d9a
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2015 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/ui/bin/root_presenter/presentation.h" #include <lib/fostr/fidl/fuchsia/ui/input/formatting.h> #include <cmath> #include <utility> #include <trace/event.h> #include "src/lib/fxl/logging.h" #include "src/ui/bin/root_presenter/displays/display_configuration.h" #include "src/ui/lib/key_util/key_util.h" using fuchsia::ui::policy::MediaButtonsListenerPtr; namespace root_presenter { namespace { // The shape and elevation of the cursor. constexpr float kCursorWidth = 20; constexpr float kCursorHeight = 20; constexpr float kCursorRadius = 10; // TODO(SCN-1276): Don't hardcode Z bounds in multiple locations. // Derive cursor elevation from non-hardcoded Z bounds. constexpr float kCursorElevation = 800; constexpr float kDefaultRootViewDepth = 1000; // TODO(SCN-1278): Remove this. // Turn two floats (high bits, low bits) into a 64-bit uint. trace_flow_id_t PointerTraceHACK(float fa, float fb) { uint32_t ia, ib; memcpy(&ia, &fa, sizeof(uint32_t)); memcpy(&ib, &fb, sizeof(uint32_t)); return (((uint64_t)ia) << 32) | ib; } // Light intensities. constexpr float kAmbient = 0.3f; constexpr float kNonAmbient = 1.f - kAmbient; // Applies the inverse of the given translation in a dimension of Vulkan NDC and scale (about the // center of the range) to the given coordinate, for inverting the clip-space transform for pointer // input. float InverseLinearTransform(float x, uint32_t range, float ndc_translation, float scale) { const float half_range = range / 2.f; return (x - half_range * (1 + ndc_translation)) / scale + half_range; } } // namespace Presentation::Presentation( fuchsia::ui::scenic::Scenic* scenic, scenic::Session* session, scenic::ResourceId compositor_id, fuchsia::ui::views::ViewHolderToken view_holder_token, fidl::InterfaceRequest<fuchsia::ui::policy::Presentation> presentation_request, ActivityNotifier* activity_notifier, RendererParams renderer_params, int32_t display_startup_rotation_adjustment, YieldCallback yield_callback, MediaButtonsHandler* media_buttons_handler) : scenic_(scenic), session_(session), compositor_id_(compositor_id), activity_notifier_(activity_notifier), layer_(session_), renderer_(session_), scene_(session_), camera_(scene_), ambient_light_(session_), directional_light_(session_), point_light_(session_), view_holder_node_(session), root_node_(session_), view_holder_(session, std::move(view_holder_token), "root_presenter"), cursor_shape_(session_, kCursorWidth, kCursorHeight, 0u, kCursorRadius, kCursorRadius, kCursorRadius), cursor_material_(session_), display_startup_rotation_adjustment_(display_startup_rotation_adjustment), yield_callback_(std::move(yield_callback)), presentation_binding_(this), a11y_binding_(this), renderer_params_override_(renderer_params), media_buttons_handler_(media_buttons_handler), weak_factory_(this) { FXL_DCHECK(compositor_id != 0); FXL_DCHECK(media_buttons_handler_); renderer_.SetCamera(camera_); layer_.SetRenderer(renderer_); scene_.AddChild(root_node_); root_node_.SetTranslation(0.f, 0.f, -0.1f); // TODO(SCN-371). root_node_.AddChild(view_holder_node_); view_holder_node_.Attach(view_holder_); // Create the root view's scene. // TODO(SCN-1255): we add a directional light and a point light, expecting // only one of them to be active at a time. This logic is implicit in // EngineRenderer, since no shadow-mode supports both directional and point // lights (either one or the other). When directional light support is added // to PaperRenderer, the code here will result in over-brightening, and will // need to be adjusted at that time. scene_.AddLight(ambient_light_); scene_.AddLight(directional_light_); scene_.AddLight(point_light_); directional_light_.SetDirection(1.f, 1.f, 2.f); point_light_.SetPosition(300.f, 300.f, -2000.f); point_light_.SetFalloff(0.f); // Explicitly set "UNSHADOWED" as the default shadow type. In addition to // setting the param, this sets appropriate light intensities. { fuchsia::ui::gfx::RendererParam param; param.set_shadow_technique(fuchsia::ui::gfx::ShadowTechnique::UNSHADOWED); SetRendererParam(std::move(param)); } cursor_material_.SetColor(0xff, 0x00, 0xff, 0xff); SetScenicDisplayRotation(); // NOTE: This invokes Present(); all initial scene setup should happen before. OverrideRendererParams(renderer_params, false); // Link ourselves to the presentation interface once screen dimensions are // available for us to present into. scenic_->GetDisplayInfo( [weak = weak_factory_.GetWeakPtr(), presentation_request = std::move(presentation_request)]( fuchsia::ui::gfx::DisplayInfo display_info) mutable { if (weak) { if (presentation_request) { weak->presentation_binding_.Bind(std::move(presentation_request)); } // Get display parameters and propagate values appropriately. weak->InitializeDisplayModel(std::move(display_info)); weak->PresentScene(); } }); } Presentation::~Presentation() = default; void Presentation::RegisterWithMagnifier(fuchsia::accessibility::Magnifier* magnifier) { magnifier->RegisterHandler(a11y_binding_.NewBinding()); a11y_binding_.set_error_handler([this](auto) { ResetClipSpaceTransform(); }); } void Presentation::OverrideRendererParams(RendererParams renderer_params, bool present_changes) { renderer_params_override_ = renderer_params; if (renderer_params_override_.clipping_enabled.has_value()) { presentation_clipping_enabled_ = renderer_params_override_.clipping_enabled.value(); } if (renderer_params_override_.render_frequency.has_value()) { fuchsia::ui::gfx::RendererParam param; param.set_render_frequency(renderer_params_override_.render_frequency.value()); renderer_.SetParam(std::move(param)); } if (renderer_params_override_.shadow_technique.has_value()) { fuchsia::ui::gfx::RendererParam param; param.set_shadow_technique(renderer_params_override_.shadow_technique.value()); renderer_.SetParam(std::move(param)); UpdateLightsForShadowTechnique(renderer_params_override_.shadow_technique.value()); } if (present_changes) { PresentScene(); } FXL_CHECK(display_startup_rotation_adjustment_ % 90 == 0) << "Rotation adjustments must be in (+/-) 90 deg increments; received: " << display_startup_rotation_adjustment_; } void Presentation::InitializeDisplayModel(fuchsia::ui::gfx::DisplayInfo display_info) { FXL_DCHECK(!display_model_initialized_); // Initialize display model. display_configuration::InitializeModelForDisplay(display_info.width_in_px, display_info.height_in_px, &display_model_); display_model_initialized_ = true; ApplyDisplayModelChanges(true, false); } bool Presentation::ApplyDisplayModelChanges(bool print_log, bool present_changes) { bool updated = ApplyDisplayModelChangesHelper(print_log); if (updated && present_changes) { PresentScene(); } return updated; } bool Presentation::ApplyDisplayModelChangesHelper(bool print_log) { if (!display_model_initialized_) return false; DisplayMetrics metrics = display_model_.GetMetrics(); if (print_log) { display_configuration::LogDisplayMetrics(metrics); } if (display_metrics_ == metrics) return true; display_metrics_ = metrics; // Layout size { float metrics_width = display_metrics_.width_in_pp(); float metrics_height = display_metrics_.height_in_pp(); // Swap metrics on left/right tilt. if (abs(display_startup_rotation_adjustment_ % 180) == 90) { std::swap(metrics_width, metrics_height); } view_holder_.SetViewProperties(0.f, 0.f, -kDefaultRootViewDepth, metrics_width, metrics_height, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f); FXL_VLOG(2) << "DisplayModel layout: " << metrics_width << ", " << metrics_height; } // Device pixel scale. { float metrics_scale_x = display_metrics_.x_scale_in_px_per_pp(); float metrics_scale_y = display_metrics_.y_scale_in_px_per_pp(); // Swap metrics on left/right tilt. if (abs(display_startup_rotation_adjustment_ % 180) == 90) { std::swap(metrics_scale_x, metrics_scale_y); } scene_.SetScale(metrics_scale_x, metrics_scale_y, 1.f); FXL_VLOG(2) << "DisplayModel pixel scale: " << metrics_scale_x << ", " << metrics_scale_y; } // Anchor { float anchor_x = display_metrics_.width_in_pp() / 2; float anchor_y = display_metrics_.height_in_pp() / 2; // Swap anchors on left/right tilt. if (abs(display_startup_rotation_adjustment_ % 180) == 90) { std::swap(anchor_x, anchor_y); } view_holder_node_.SetAnchor(anchor_x, anchor_y, 0); FXL_VLOG(2) << "DisplayModel anchor: " << anchor_x << ", " << anchor_y; } // Rotate { glm::quat display_rotation = glm::quat(glm::vec3(0, 0, glm::radians<float>(display_startup_rotation_adjustment_))); view_holder_node_.SetRotation(display_rotation.x, display_rotation.y, display_rotation.z, display_rotation.w); } const DisplayModel::DisplayInfo& display_info = display_model_.display_info(); // Center everything. { float info_w = display_info.width_in_px; float info_h = display_info.height_in_px; float metrics_w = display_metrics_.width_in_px(); float metrics_h = display_metrics_.height_in_px(); float density_w = display_metrics_.x_scale_in_px_per_pp(); float density_h = display_metrics_.y_scale_in_px_per_pp(); // Swap metrics on left/right tilt. if (abs(display_startup_rotation_adjustment_ % 180) == 90) { std::swap(metrics_w, metrics_h); std::swap(density_w, density_h); } float left_offset = (info_w - metrics_w) / density_w / 2; float top_offset = (info_h - metrics_h) / density_h / 2; view_holder_node_.SetTranslation(left_offset, top_offset, 0.f); FXL_VLOG(2) << "DisplayModel translation: " << left_offset << ", " << top_offset; } // Today, a layer needs the display's physical dimensions to render correctly. layer_.SetSize(static_cast<float>(display_info.width_in_px), static_cast<float>(display_info.height_in_px)); return true; } glm::vec2 Presentation::RotatePointerCoordinates(float x, float y) { // TODO(SCN-911): This math is messy and hard to understand. Instead, we // should just walk down the layer and scene graph and apply transformations. // On the other hand, this method is only used when capturing touch events, // which is something we intend to deprecate anyway. const float anchor_w = display_model_.display_info().width_in_px / 2; const float anchor_h = display_model_.display_info().height_in_px / 2; const int32_t startup_rotation = display_startup_rotation_adjustment_; glm::vec4 pointer_coords(x, y, 0.f, 1.f); glm::vec4 rotated_coords = glm::translate(glm::vec3(anchor_w, anchor_h, 0)) * glm::rotate(glm::radians<float>(-startup_rotation), glm::vec3(0, 0, 1)) * glm::translate(glm::vec3(-anchor_w, -anchor_h, 0)) * pointer_coords; if (abs(startup_rotation) % 180 == 90) { // If the aspect ratio is flipped, the origin needs to be adjusted too. int32_t sim_w = static_cast<int32_t>(display_metrics_.width_in_px()); int32_t sim_h = static_cast<int32_t>(display_metrics_.height_in_px()); float adjust_origin = (sim_w - sim_h) / 2.f; rotated_coords = glm::translate(glm::vec3(-adjust_origin, adjust_origin, 0)) * rotated_coords; } FXL_VLOG(2) << "Pointer coordinates rotated [" << startup_rotation << "]: (" << pointer_coords.x << ", " << pointer_coords.y << ")->(" << rotated_coords.x << ", " << rotated_coords.y << ")."; return glm::vec2(rotated_coords.x, rotated_coords.y); } void Presentation::OnDeviceAdded(ui_input::InputDeviceImpl* input_device) { FXL_VLOG(1) << "OnDeviceAdded: device_id=" << input_device->id(); FXL_DCHECK(device_states_by_id_.count(input_device->id()) == 0); std::unique_ptr<ui_input::DeviceState> state; if (input_device->descriptor()->sensor) { ui_input::OnSensorEventCallback callback = [this](uint32_t device_id, fuchsia::ui::input::InputReport event) { OnSensorEvent(device_id, std::move(event)); }; state = std::make_unique<ui_input::DeviceState>(input_device->id(), input_device->descriptor(), std::move(callback)); } else { ui_input::OnEventCallback callback = [this](fuchsia::ui::input::InputEvent event) { OnEvent(std::move(event)); }; state = std::make_unique<ui_input::DeviceState>(input_device->id(), input_device->descriptor(), std::move(callback)); } ui_input::DeviceState* state_ptr = state.get(); auto device_pair = std::make_pair(input_device, std::move(state)); state_ptr->OnRegistered(); device_states_by_id_.emplace(input_device->id(), std::move(device_pair)); } void Presentation::OnDeviceRemoved(uint32_t device_id) { FXL_VLOG(1) << "OnDeviceRemoved: device_id=" << device_id; if (device_states_by_id_.count(device_id) != 0) { device_states_by_id_[device_id].second->OnUnregistered(); auto it = cursors_.find(device_id); if (it != cursors_.end()) { it->second.node->Detach(); cursors_.erase(it); PresentScene(); } device_states_by_id_.erase(device_id); } } void Presentation::OnReport(uint32_t device_id, fuchsia::ui::input::InputReport input_report) { // Media buttons should be processed by MediaButtonsHandler. FXL_DCHECK(!input_report.media_buttons); TRACE_DURATION("input", "presentation_on_report", "id", input_report.trace_id); TRACE_FLOW_END("input", "report_to_presentation", input_report.trace_id); FXL_VLOG(2) << "OnReport device=" << device_id << ", count=" << device_states_by_id_.count(device_id) << ", report=" << input_report; if (device_states_by_id_.count(device_id) == 0) { FXL_VLOG(1) << "OnReport: Unknown device " << device_id; return; } if (!display_model_initialized_) return; ui_input::DeviceState* state = device_states_by_id_[device_id].second.get(); fuchsia::math::Size size; size.width = display_model_.display_info().width_in_px; size.height = display_model_.display_info().height_in_px; TRACE_FLOW_BEGIN("input", "report_to_device_state", input_report.trace_id); state->Update(std::move(input_report), size); } void Presentation::CaptureKeyboardEventHACK( fuchsia::ui::input::KeyboardEvent event_to_capture, fidl::InterfaceHandle<fuchsia::ui::policy::KeyboardCaptureListenerHACK> listener_handle) { fuchsia::ui::policy::KeyboardCaptureListenerHACKPtr listener; listener.Bind(std::move(listener_handle)); // Auto-remove listeners if the interface closes. listener.set_error_handler([this, listener = listener.get()](zx_status_t status) { captured_keybindings_.erase( std::remove_if(captured_keybindings_.begin(), captured_keybindings_.end(), [listener](const KeyboardCaptureItem& item) -> bool { return item.listener.get() == listener; }), captured_keybindings_.end()); }); captured_keybindings_.push_back( KeyboardCaptureItem{std::move(event_to_capture), std::move(listener)}); } void Presentation::CapturePointerEventsHACK( fidl::InterfaceHandle<fuchsia::ui::policy::PointerCaptureListenerHACK> listener_handle) { captured_pointerbindings_.AddInterfacePtr(listener_handle.Bind()); } void Presentation::InjectPointerEventHACK(fuchsia::ui::input::PointerEvent event) { fuchsia::ui::input::InputEvent input_event; input_event.set_pointer(std::move(event)); OnEvent(std::move(input_event)); } void Presentation::SetClipSpaceTransform(float x, float y, float scale, SetClipSpaceTransformCallback callback) { camera_.SetClipSpaceTransform(x, y, scale); clip_space_transform_ = {{x, y}, scale}; // The callback is used to throttle magnification transition animations and is expected to // approximate the framerate. // TODO(35521): In the future, this may need to be downsampled as |Present| calls must be // throttled, at which point the |SetClipSpaceTransformCallback|s should be consolidated. session_->Present(0, [callback = std::move(callback)](auto) { callback(); }); } void Presentation::ResetClipSpaceTransform() { SetClipSpaceTransform(0, 0, 1, [] {}); } glm::vec2 Presentation::ApplyInverseClipSpaceTransform(const glm::vec2& coordinate) { return { InverseLinearTransform(coordinate.x, display_model_.display_info().width_in_px, clip_space_transform_.translation.x, clip_space_transform_.scale), InverseLinearTransform(coordinate.y, display_model_.display_info().height_in_px, clip_space_transform_.translation.y, clip_space_transform_.scale), }; } bool Presentation::GlobalHooksHandleEvent(const fuchsia::ui::input::InputEvent& event) { return perspective_demo_mode_.OnEvent(event, this) || presentation_switcher_.OnEvent(event, this); } void Presentation::OnEvent(fuchsia::ui::input::InputEvent event) { TRACE_DURATION("input", "presentation_on_event"); trace_flow_id_t trace_id = 0; FXL_VLOG(1) << "OnEvent " << event; activity_notifier_->ReceiveInputEvent(event); fuchsia::ui::input::Command input_cmd; bool invalidate = false; bool dispatch_event = true; if (GlobalHooksHandleEvent(event)) { invalidate = true; dispatch_event = false; } // Process the event. if (dispatch_event) { if (event.is_pointer()) { const fuchsia::ui::input::PointerEvent& pointer = event.pointer(); // TODO(SCN-1278): Use proper trace_id for tracing flow. trace_id = PointerTraceHACK(pointer.radius_major, pointer.radius_minor); TRACE_FLOW_END("input", "dispatch_event_to_presentation", trace_id); // Ensure the cursor appears at the correct position after magnification position and scaling. // It should appear at the same physical location on the screen as it would without // magnification. (However, the cursor itself will scale.) const glm::vec2 transformed_point = ApplyInverseClipSpaceTransform({pointer.x, pointer.y}); if (pointer.type == fuchsia::ui::input::PointerEventType::MOUSE) { if (cursors_.count(pointer.device_id) == 0) { cursors_.emplace(pointer.device_id, CursorState{}); } cursors_[pointer.device_id].position.x = transformed_point.x; cursors_[pointer.device_id].position.y = transformed_point.y; // TODO(SCN-823) for now don't show cursor when mouse is added until // we have a timer to hide it. Acer12 sleeve reports 2 mice but only // one will generate events for now. if (pointer.phase != fuchsia::ui::input::PointerEventPhase::ADD && pointer.phase != fuchsia::ui::input::PointerEventPhase::REMOVE) { cursors_[pointer.device_id].visible = true; } invalidate = true; } else { for (auto it = cursors_.begin(); it != cursors_.end(); ++it) { if (it->second.visible) { it->second.visible = false; invalidate = true; } } } // The following steps are different ways of dispatching pointer events, which differ in their // coordinate systems. if (!captured_pointerbindings_.ptrs().empty()) { // |CapturePointerEventsHACK| clients like SysUI expect rotated, transformed coordinates as // this bypasses normal input dispatch and so needs to be pretty much ready-to-use. glm::vec2 capture_point = RotatePointerCoordinates(transformed_point.x, transformed_point.y); // Adjust pointer origin with simulated screen offset. capture_point.x -= (display_model_.display_info().width_in_px - display_metrics_.width_in_px()) / 2.f; capture_point.y -= (display_model_.display_info().height_in_px - display_metrics_.height_in_px()) / 2.f; // Scale by device pixel density. capture_point.x *= display_metrics_.x_scale_in_pp_per_px(); capture_point.y *= display_metrics_.y_scale_in_pp_per_px(); for (auto& listener : captured_pointerbindings_.ptrs()) { fuchsia::ui::input::PointerEvent clone; fidl::Clone(pointer, &clone); clone.x = capture_point.x; clone.y = capture_point.y; (*listener)->OnPointerEvent(std::move(clone)); } } fuchsia::ui::input::SendPointerInputCmd pointer_cmd; pointer_cmd.pointer_event = std::move(pointer); pointer_cmd.compositor_id = compositor_id_; input_cmd.set_send_pointer_input(std::move(pointer_cmd)); } else if (event.is_keyboard()) { // Keyboard dispatch disabled. dispatch_event = false; return; } } if (invalidate) { PresentScene(); } if (dispatch_event) { if (trace_id) { TRACE_FLOW_BEGIN("input", "dispatch_event_to_scenic", trace_id); } session_->Enqueue(std::move(input_cmd)); } } void Presentation::OnSensorEvent(uint32_t device_id, fuchsia::ui::input::InputReport event) { FXL_VLOG(2) << "OnSensorEvent(device_id=" << device_id << "): " << event; FXL_DCHECK(device_states_by_id_.count(device_id) > 0); FXL_DCHECK(device_states_by_id_[device_id].first); FXL_DCHECK(device_states_by_id_[device_id].first->descriptor()); FXL_DCHECK(device_states_by_id_[device_id].first->descriptor()->sensor.get()); // No clients of sensor events at the moment. } void Presentation::PresentScene() { if (session_present_state_ == kPresentPendingAndSceneDirty) { return; } else if (session_present_state_ == kPresentPending) { session_present_state_ = kPresentPendingAndSceneDirty; return; } // There is no present pending, so we will kick one off. session_present_state_ = kPresentPending; bool use_clipping = perspective_demo_mode_.WantsClipping(); if (renderer_params_override_.clipping_enabled.has_value()) { use_clipping = renderer_params_override_.clipping_enabled.value(); } renderer_.SetDisableClipping(!use_clipping); // TODO(SCN-631): Individual Presentations shouldn't directly manage cursor // state. for (auto it = cursors_.begin(); it != cursors_.end(); ++it) { CursorState& state = it->second; if (state.visible) { if (!state.created) { state.node = std::make_unique<scenic::ShapeNode>(session_); state.node->SetLabel("mouse cursor"); state.node->SetShape(cursor_shape_); state.node->SetMaterial(cursor_material_); scene_.AddChild(*state.node); state.created = true; } state.node->SetTranslation( state.position.x * display_metrics_.x_scale_in_pp_per_px() + kCursorWidth * .5f, state.position.y * display_metrics_.y_scale_in_pp_per_px() + kCursorHeight * .5f, -kCursorElevation); } else if (state.created) { state.node->Detach(); state.created = false; } } session_->Present(0, [weak = weak_factory_.GetWeakPtr()](fuchsia::images::PresentationInfo info) { if (auto self = weak.get()) { uint64_t next_presentation_time = info.presentation_time + info.presentation_interval; bool scene_dirty = self->session_present_state_ == kPresentPendingAndSceneDirty; // Clear the present state. self->session_present_state_ = kNoPresentPending; scene_dirty |= self->perspective_demo_mode_.UpdateAnimation(self, next_presentation_time); if (scene_dirty) { self->PresentScene(); } } }); } void Presentation::UpdateLightsForShadowTechnique(fuchsia::ui::gfx::ShadowTechnique tech) { if (tech == fuchsia::ui::gfx::ShadowTechnique::UNSHADOWED) { ambient_light_.SetColor(1.f, 1.f, 1.f); directional_light_.SetColor(0.f, 0.f, 0.f); point_light_.SetColor(0.f, 0.f, 0.f); } else { ambient_light_.SetColor(kAmbient, kAmbient, kAmbient); directional_light_.SetColor(kNonAmbient, kNonAmbient, kNonAmbient); point_light_.SetColor(kNonAmbient, kNonAmbient, kNonAmbient); } } void Presentation::SetRendererParams(std::vector<fuchsia::ui::gfx::RendererParam> params) { for (size_t i = 0; i < params.size(); ++i) { SetRendererParam(std::move(params[i])); } session_->Present(0, [](fuchsia::images::PresentationInfo info) {}); } void Presentation::SetScenicDisplayRotation() { fuchsia::ui::gfx::Command command; fuchsia::ui::gfx::SetDisplayRotationCmdHACK display_rotation_cmd; display_rotation_cmd.compositor_id = compositor_id_; display_rotation_cmd.rotation_degrees = display_startup_rotation_adjustment_; command.set_set_display_rotation(std::move(display_rotation_cmd)); session_->Enqueue(std::move(command)); } void Presentation::SetRendererParam(fuchsia::ui::gfx::RendererParam param) { switch (param.Which()) { case ::fuchsia::ui::gfx::RendererParam::Tag::kShadowTechnique: if (renderer_params_override_.shadow_technique.has_value()) { FXL_LOG(WARNING) << "Presentation::SetRendererParams: Cannot change " "shadow technique, default was overriden in root_presenter"; return; } UpdateLightsForShadowTechnique(param.shadow_technique()); break; case fuchsia::ui::gfx::RendererParam::Tag::kRenderFrequency: if (renderer_params_override_.render_frequency.has_value()) { FXL_LOG(WARNING) << "Presentation::SetRendererParams: Cannot change " "render frequency, default was overriden in root_presenter"; return; } break; case fuchsia::ui::gfx::RendererParam::Tag::kEnableDebugging: if (renderer_params_override_.debug_enabled.has_value()) { FXL_LOG(WARNING) << "Presentation::SetRendererParams: Cannot change " "debug enabled, default was overriden in root_presenter"; return; } break; case fuchsia::ui::gfx::RendererParam::Tag::Invalid: return; } renderer_.SetParam(std::move(param)); } } // namespace root_presenter
38.777939
100
0.702523
[ "render", "shape", "vector", "model", "transform" ]
3e7ed01a59cda1768098d05ab8c7db80376fa25a
668
cpp
C++
load_fasta.cpp
KHanghoj/dammet
b57d1baf6fab46b6c5dab835b99cddbe455e573c
[ "MIT" ]
1
2021-06-25T02:46:49.000Z
2021-06-25T02:46:49.000Z
load_fasta.cpp
KHanghoj/dammet
b57d1baf6fab46b6c5dab835b99cddbe455e573c
[ "MIT" ]
2
2020-06-26T15:26:16.000Z
2021-03-09T21:14:06.000Z
load_fasta.cpp
KHanghoj/dammet
b57d1baf6fab46b6c5dab835b99cddbe455e573c
[ "MIT" ]
1
2020-11-15T18:01:55.000Z
2020-11-15T18:01:55.000Z
#include <iostream> // stdout/stdin/stderr #include <string> #include <vector> #include <sstream> //stringstream #include <fstream> // open file #include "load_fasta.hpp" faidx_t * ref_init(std::string & filename){ faidx_t * fai = fai_load(filename.c_str()); if ( !fai ) { std::cerr << "Could not load fai index of: " << filename << '\n'; exit(EXIT_FAILURE); } return fai; } char * fetch_chrom(const faidx_t *fai, std::string & chrom) { int seq_len = 0; char * ref = fai_fetch(fai, chrom.c_str(), &seq_len); if ( seq_len < 0 ) { std::cerr << "Failed to fetch sequence in: " << chrom << '\n'; exit(EXIT_FAILURE); } return ref; }
23.034483
69
0.627246
[ "vector" ]
3e889a03eff0bc43bca1f92e33354a305490be4b
122,047
cpp
C++
orca/gporca/server/src/unittest/dxl/statistics/CStatisticsTest.cpp
vitessedata/gpdb.4.3.99.x
9462aad5df1bf120a2a87456b1f9574712227da4
[ "PostgreSQL", "Apache-2.0" ]
3
2017-12-10T16:41:21.000Z
2020-07-08T12:59:12.000Z
orca/gporca/server/src/unittest/dxl/statistics/CStatisticsTest.cpp
vitessedata/gpdb.4.3.99.x
9462aad5df1bf120a2a87456b1f9574712227da4
[ "PostgreSQL", "Apache-2.0" ]
null
null
null
orca/gporca/server/src/unittest/dxl/statistics/CStatisticsTest.cpp
vitessedata/gpdb.4.3.99.x
9462aad5df1bf120a2a87456b1f9574712227da4
[ "PostgreSQL", "Apache-2.0" ]
4
2017-12-10T16:41:35.000Z
2020-11-28T12:20:30.000Z
//--------------------------------------------------------------------------- // Greenplum Database // Copyright (C) 2011 EMC Corp. // // @filename: // CStatisticsTest.cpp // // @doc: // Tests for CPoint // // @owner: // // // @test: // // //--------------------------------------------------------------------------- #ifndef __STDC_CONSTANT_MACROS #define __STDC_CONSTANT_MACROS #endif #include <stdint.h> #include "gpos/io/COstreamString.h" #include "gpos/string/CWStringDynamic.h" #include "gpos/common/clibwrapper.h" #include "naucrates/statistics/CPoint.h" #include "naucrates/statistics/CBucket.h" #include "naucrates/statistics/CHistogram.h" #include "naucrates/statistics/CStatistics.h" #include "naucrates/statistics/CStatisticsUtils.h" #include "naucrates/base/CDatumGenericGPDB.h" #include "naucrates/base/CDatumInt4GPDB.h" #include "naucrates/base/CDatumBoolGPDB.h" #include "gpopt/base/CQueryContext.h" #include "gpopt/eval/CConstExprEvaluatorDefault.h" #include "gpopt/operators/CLogicalInnerJoin.h" #include "gpopt/operators/CScalarProjectElement.h" #include "naucrates/dxl/CDXLUtils.h" #include "naucrates/dxl/operators/CDXLDatumGeneric.h" #include "naucrates/dxl/operators/CDXLDatumStatsDoubleMappable.h" #include "naucrates/dxl/operators/CDXLDatumStatsLintMappable.h" #include "unittest/base.h" #include "unittest/dxl/statistics/CStatisticsTest.h" #include "unittest/gpopt/CTestUtils.h" #include "naucrates/md/IMDType.h" #include "naucrates/md/CMDTypeGenericGPDB.h" using namespace gpopt; // DXL files const CHAR * szInputDXLFileName = "../data/dxl/statistics/Basic-Statistics-Input.xml"; const CHAR * szOutputDXLFileName = "../data/dxl/statistics/Basic-Statistics-Output.xml"; const CHAR * szMCVSortExpectedFileName = "../data/dxl/statistics/MCV-Sort-Output.xml"; const CHAR * szQuerySelect = "../data/dxl/statistics/SelectQuery.xml"; const CHAR * szPlanSelect = "../data/dxl/statistics/SelectPlan.xml"; const CTestUtils::STestCase rgtcStatistics[] = { {"../data/dxl/statistics/Numeric-Input.xml", "../data/dxl/statistics/Numeric-Output-LT-MinBoundary.xml"}, {"../data/dxl/statistics/Numeric-Input.xml", "../data/dxl/statistics/Numeric-Output-LTE-MinBoundary.xml"}, {"../data/dxl/statistics/Numeric-Input.xml", "../data/dxl/statistics/Numeric-Output-E-MinBoundary.xml"}, {"../data/dxl/statistics/Numeric-Input.xml", "../data/dxl/statistics/Numeric-Output-GT-MaxBoundary.xml"}, {"../data/dxl/statistics/Numeric-Input.xml", "../data/dxl/statistics/Numeric-Output-GTE-MaxBoundary.xml"}, {"../data/dxl/statistics/Numeric-Input.xml", "../data/dxl/statistics/Numeric-Output-E-MaxBoundary.xml"}, {"../data/dxl/statistics/Numeric-Input2.xml", "../data/dxl/statistics/Numeric-Output-2-LT-MinBoundary.xml"}, {"../data/dxl/statistics/Numeric-Input2.xml", "../data/dxl/statistics/Numeric-Output-2-LTE-MinBoundary.xml"}, {"../data/dxl/statistics/Numeric-Input2.xml", "../data/dxl/statistics/Numeric-Output-2-E-MinBoundary.xml"}, {"../data/dxl/statistics/Numeric-Input2.xml", "../data/dxl/statistics/Numeric-Output-2-GT-MinBoundary.xml"}, {"../data/dxl/statistics/Numeric-Input2.xml", "../data/dxl/statistics/Numeric-Output-2-GTE-MinBoundary.xml"}, {"../data/dxl/statistics/Numeric-Input2.xml", "../data/dxl/statistics/Numeric-Output-2-LT-MaxBoundary.xml"}, {"../data/dxl/statistics/Numeric-Input2.xml", "../data/dxl/statistics/Numeric-Output-2-LTE-MaxBoundary.xml"}, {"../data/dxl/statistics/Numeric-Input2.xml", "../data/dxl/statistics/Numeric-Output-2-GT-MaxBoundary.xml"}, {"../data/dxl/statistics/Numeric-Input2.xml", "../data/dxl/statistics/Numeric-Output-2-GTE-MaxBoundary.xml"}, {"../data/dxl/statistics/Numeric-Input2.xml", "../data/dxl/statistics/Numeric-Output-2-E-MaxBoundary.xml"}, }; //--------------------------------------------------------------------------- // @function: // CStatisticsTest::EresUnittest // // @doc: // Unittest for statistics objects // //--------------------------------------------------------------------------- GPOS_RESULT CStatisticsTest::EresUnittest() { // tests that use shared optimization context CUnittest rgutSharedOptCtxt[] = { GPOS_UNITTEST_FUNC(CStatisticsTest::EresUnittest_CPointInt4), GPOS_UNITTEST_FUNC(CStatisticsTest::EresUnittest_CPointBool), GPOS_UNITTEST_FUNC(CStatisticsTest::EresUnittest_CBucketInt4), GPOS_UNITTEST_FUNC(CStatisticsTest::EresUnittest_CBucketBool), GPOS_UNITTEST_FUNC(CStatisticsTest::EresUnittest_CBucketScale), GPOS_UNITTEST_FUNC(CStatisticsTest::EresUnittest_CBucketDifference), GPOS_UNITTEST_FUNC(CStatisticsTest::EresUnittest_CHistogramInt4), GPOS_UNITTEST_FUNC(CStatisticsTest::EresUnittest_CHistogramBool), GPOS_UNITTEST_FUNC(CStatisticsTest::EresUnittest_CStatisticsBasic), GPOS_UNITTEST_FUNC(CStatisticsTest::EresUnittest_CStatisticsBasicsFromDXL), GPOS_UNITTEST_FUNC(CStatisticsTest::EresUnittest_CStatisticsBasicsFromDXLNumeric), GPOS_UNITTEST_FUNC(CStatisticsTest::EresUnittest_UnionAll), // TODO, Mar 18 2013 temporarily disabling the test // GPOS_UNITTEST_FUNC(CStatisticsTest::EresUnittest_CStatisticsSelectDerivation), GPOS_UNITTEST_FUNC(CStatisticsTest::EresUnittest_Skew), GPOS_UNITTEST_FUNC_ASSERT(CStatisticsTest::EresUnittest_CHistogramValid), GPOS_UNITTEST_FUNC(CStatisticsTest::EresUnittest_Join), GPOS_UNITTEST_FUNC(CStatisticsTest::EresUnittest_JoinNDVRemain), GPOS_UNITTEST_FUNC(CStatisticsTest::EresUnittest_CBucketIntersect), GPOS_UNITTEST_FUNC(CStatisticsTest::EresUnittest_CStatisticsFilter), GPOS_UNITTEST_FUNC(CStatisticsTest::EresUnittest_CStatisticsFilterConj), GPOS_UNITTEST_FUNC(CStatisticsTest::EresUnittest_CStatisticsFilterDisj), GPOS_UNITTEST_FUNC(CStatisticsTest::EresUnittest_CStatisticsNestedPred), GPOS_UNITTEST_FUNC(CStatisticsTest::EresUnittest_SortInt4MCVs), GPOS_UNITTEST_FUNC(CStatisticsTest::EresUnittest_MergeHistMCV), GPOS_UNITTEST_FUNC(CStatisticsTest::EresUnittest_CStatisticsAccumulateCard) }; // tests that use separate optimization contexts CUnittest rgutSeparateOptCtxt[] = { GPOS_UNITTEST_FUNC(CStatisticsTest::EresUnittest_GbAggWithRepeatedGbCols), }; // run tests with shared optimization context first GPOS_RESULT eres = GPOS_FAILED; { CAutoMemoryPool amp; IMemoryPool *pmp = amp.Pmp(); // setup a file-based provider CMDProviderMemory *pmdp = CTestUtils::m_pmdpf; pmdp->AddRef(); CMDAccessor mda(pmp, CMDCache::Pcache(), CTestUtils::m_sysidDefault, pmdp); // install opt context in TLS CAutoOptCtxt aoc ( pmp, &mda, NULL /* pceeval */, CTestUtils::Pcm(pmp) ); eres = CUnittest::EresExecute(rgutSharedOptCtxt, GPOS_ARRAY_SIZE(rgutSharedOptCtxt)); if (GPOS_FAILED == eres) { return eres; } } // run tests with separate optimization contexts return CUnittest::EresExecute(rgutSeparateOptCtxt, GPOS_ARRAY_SIZE(rgutSeparateOptCtxt)); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::EresUnittest_UnionAll // // @doc: // Testing statistical operations on Union All; // //--------------------------------------------------------------------------- GPOS_RESULT CStatisticsTest::EresUnittest_UnionAll() { // create memory pool CAutoMemoryPool amp; IMemoryPool *pmp = amp.Pmp(); CMDAccessor *pmda = COptCtxt::PoctxtFromTLS()->Pmda(); SStatsUnionAllSTestCase rgstatsunionalltc[] = { {"../data/dxl/statistics/UnionAll-Input-1.xml", "../data/dxl/statistics/UnionAll-Output-1.xml"}, }; const ULONG ulTestCases = GPOS_ARRAY_SIZE(rgstatsunionalltc); for (ULONG ul = 0; ul < ulTestCases; ul++) { SStatsUnionAllSTestCase elem = rgstatsunionalltc[ul]; // read input/output DXL file CHAR *szDXLInput = CDXLUtils::SzRead(pmp, elem.m_szInputFile); CHAR *szDXLOutput = CDXLUtils::SzRead(pmp, elem.m_szOutputFile); GPOS_CHECK_ABORT; // parse the input statistics objects DrgPdxlstatsderrel *pdrgpdxlstatsderrel = CDXLUtils::PdrgpdxlstatsderrelParseDXL(pmp, szDXLInput, NULL); DrgPstats *pdrgpstatBefore = CDXLUtils::PdrgpstatsTranslateStats(pmp, pmda, pdrgpdxlstatsderrel); pdrgpdxlstatsderrel->Release(); GPOS_ASSERT(NULL != pdrgpstatBefore); GPOS_ASSERT(2 == pdrgpstatBefore->UlLength()); CStatistics *pstats1 = (*pdrgpstatBefore)[0]; CStatistics *pstats2 = (*pdrgpstatBefore)[1]; GPOS_CHECK_ABORT; DrgPul *pdrgpulColIdOutput = Pdrgpul(pmp, 1); DrgPul *pdrgpulColIdInput1 = Pdrgpul(pmp, 1); DrgPul *pdrgpulColIdInput2 = Pdrgpul(pmp, 2); CStatistics *pstatsOutput = pstats1->PstatsUnionAll(pmp, pstats2, pdrgpulColIdOutput, pdrgpulColIdInput1, pdrgpulColIdInput2); GPOS_ASSERT(NULL != pstatsOutput); DrgPstats *pdrgpstatOutput = GPOS_NEW(pmp) DrgPstats(pmp); pdrgpstatOutput->Append(pstatsOutput); // serialize and compare against expected stats CWStringDynamic *pstrOutput = CDXLUtils::PstrSerializeStatistics ( pmp, pmda, pdrgpstatOutput, true /*fSerializeHeaderFooter*/, true /*fIndent*/ ); CWStringDynamic dstrExpected(pmp); dstrExpected.AppendFormat(GPOS_WSZ_LIT("%s"), szDXLOutput); GPOS_RESULT eres = GPOS_OK; CWStringDynamic str(pmp); COstreamString oss(&str); // compare the two dxls if (!pstrOutput->FEquals(&dstrExpected)) { oss << "Output does not match expected DXL document" << std::endl; oss << "Actual: " << std::endl; oss << pstrOutput->Wsz() << std::endl; oss << "Expected: " << std::endl; oss << dstrExpected.Wsz() << std::endl; GPOS_TRACE(str.Wsz()); eres = GPOS_FAILED; } // clean up pdrgpstatBefore->Release(); pdrgpstatOutput->Release(); GPOS_DELETE_ARRAY(szDXLInput); GPOS_DELETE_ARRAY(szDXLOutput); GPOS_DELETE(pstrOutput); if (GPOS_FAILED == eres) { return eres; } } return GPOS_OK; } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::EresUnittest_CPointInt4 // // @doc: // Basic int4 point tests; // //--------------------------------------------------------------------------- GPOS_RESULT CStatisticsTest::EresUnittest_CPointInt4() { // create memory pool CAutoMemoryPool amp; IMemoryPool *pmp = amp.Pmp(); // generate integer points CPoint *ppoint1 = CTestUtils::PpointInt4(pmp, 1); CPoint *ppoint2 = CTestUtils::PpointInt4(pmp, 2); GPOS_RTL_ASSERT_MSG(ppoint1->FEqual(ppoint1), "1 == 1"); GPOS_RTL_ASSERT_MSG(ppoint1->FLessThan(ppoint2), "1 < 2"); GPOS_RTL_ASSERT_MSG(ppoint2->FGreaterThan(ppoint1), "2 > 1"); GPOS_RTL_ASSERT_MSG(ppoint1->FLessThanOrEqual(ppoint2), "1 <= 2"); GPOS_RTL_ASSERT_MSG(ppoint2->FGreaterThanOrEqual(ppoint2), "2 >= 2"); CDouble dDistance = ppoint2->DDistance(ppoint1); // should be 1.0 GPOS_RTL_ASSERT_MSG(0.99 < dDistance && dDistance < 1.01, "incorrect distance calculation"); ppoint1->Release(); ppoint2->Release(); return GPOS_OK; } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::EresUnittest_CPointBool // // @doc: // Basic bool point tests; // //--------------------------------------------------------------------------- GPOS_RESULT CStatisticsTest::EresUnittest_CPointBool() { // create memory pool CAutoMemoryPool amp; IMemoryPool *pmp = amp.Pmp(); // generate boolean points CPoint *ppoint1 = CTestUtils::PpointBool(pmp, true); CPoint *ppoint2 = CTestUtils::PpointBool(pmp, false); // true == true GPOS_RTL_ASSERT_MSG(ppoint1->FEqual(ppoint1), "true must be equal to true"); // true != false GPOS_RTL_ASSERT_MSG(ppoint1->FNotEqual(ppoint2), "true must not be equal to false"); ppoint1->Release(); ppoint2->Release(); return GPOS_OK; } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::EresUnittest_JoinNDVRemain // // @doc: // Join of histograms with NDVRemain information // //--------------------------------------------------------------------------- GPOS_RESULT CStatisticsTest::EresUnittest_JoinNDVRemain() { // create memory pool CAutoMemoryPool amp; IMemoryPool *pmp = amp.Pmp(); SHistogramTestCase rghisttc[] = { {0, 0, false, 0}, // empty histogram {10, 100, false, 0}, // distinct values only in buckets {0, 0, false, 1000}, // distinct values only in NDVRemain {5, 100, false, 500} // distinct values spread in both buckets and NDVRemain }; HMUlHist *phmulhist = GPOS_NEW(pmp) HMUlHist(pmp); const ULONG ulHist = GPOS_ARRAY_SIZE(rghisttc); for (ULONG ul1 = 0; ul1 < ulHist; ul1++) { SHistogramTestCase elem = rghisttc[ul1]; ULONG ulBuckets = elem.m_ulBuckets; CDouble dNDVPerBucket = elem.m_dNDVPerBucket; BOOL fNullFreq = elem.m_fNullFreq; CDouble dNDVRemain = elem.m_dNDVRemain; CHistogram *phist = PhistInt4Remain(pmp, ulBuckets, dNDVPerBucket, fNullFreq, dNDVRemain); #ifdef GPOS_DEBUG BOOL fResult = #endif // GPOS_DEBUG phmulhist->FInsert(GPOS_NEW(pmp) ULONG(ul1), phist); GPOS_ASSERT(fResult); } SStatsJoinNDVRemainTestCase rgjoinndvrtc[] = { // cases where we are joining with an empty histogram // first two columns refer to the histogram entries that are joining {0, 0, 0, CDouble(0.0), CDouble(0.0), CDouble(0.0)}, {0, 1, 0, CDouble(0.0), CDouble(0.0), CDouble(0.0)}, {0, 2, 0, CDouble(0.0), CDouble(0.0), CDouble(0.0)}, {0, 3, 0, CDouble(0.0), CDouble(0.0), CDouble(0.0)}, {1, 0, 0, CDouble(0.0), CDouble(0.0), CDouble(0.0)}, {2, 0, 0, CDouble(0.0), CDouble(0.0), CDouble(0.0)}, {3, 0, 0, CDouble(0.0), CDouble(0.0), CDouble(0.0)}, // cases where one or more input histogram has only buckets and no remaining NDV information {1, 1, 10, CDouble(1000.00), CDouble(0.0), CDouble(0.0)}, {1, 3, 5, CDouble(500.00), CDouble(500.0), CDouble(0.333333)}, {3, 1, 5, CDouble(500.00), CDouble(500.0), CDouble(0.333333)}, // cases where for one or more input histogram has only remaining NDV information and no buckets {1, 2, 0, CDouble(0.0), CDouble(1000.0), CDouble(1.0)}, {2, 1, 0, CDouble(0.0), CDouble(1000.0), CDouble(1.0)}, {2, 2, 0, CDouble(0.0), CDouble(1000.0), CDouble(1.0)}, {2, 3, 0, CDouble(0.0), CDouble(1000.0), CDouble(1.0)}, {3, 2, 0, CDouble(0.0), CDouble(1000.0), CDouble(1.0)}, // cases where both buckets and NDV remain information available for both inputs {3, 3, 5, CDouble(500.0), CDouble(500.0), CDouble(0.5)}, }; GPOS_RESULT eres = GPOS_OK; const ULONG ulTestCases = GPOS_ARRAY_SIZE(rgjoinndvrtc); for (ULONG ul2 = 0; ul2 < ulTestCases && (GPOS_FAILED != eres); ul2++) { SStatsJoinNDVRemainTestCase elem = rgjoinndvrtc[ul2]; ULONG ulColId1 = elem.m_ulCol1; ULONG ulColId2 = elem.m_ulCol2; CHistogram *phist1 = phmulhist->PtLookup(&ulColId1); CHistogram *phist2 = phmulhist->PtLookup(&ulColId2); CHistogram *phistJoin = phist1->PhistJoin(pmp, CStatsPred::EstatscmptEq, phist2); { CAutoTrace at(pmp); at.Os() << std::endl << "Input Histogram 1" << std::endl; phist1->OsPrint(at.Os()); at.Os() << "Input Histogram 2" << std::endl; phist2->OsPrint(at.Os()); at.Os() << "Join Histogram" << std::endl; phistJoin->OsPrint(at.Os()); phistJoin->DNormalize(); at.Os() << std::endl << "Normalized Join Histogram" << std::endl; phistJoin->OsPrint(at.Os()); } ULONG ulBucketsJoin = elem.m_ulBucketsJoin; CDouble dNDVBucketsJoin = elem.m_dNDVBucketsJoin; CDouble dNDVRemainJoin = elem.m_dNDVRemainJoin; CDouble dFreqRemainJoin = elem.m_dFreqRemainJoin; CDouble dDiffNDVJoin(clib::DAbs((dNDVBucketsJoin - CStatisticsUtils::DDistinct(phistJoin->Pdrgpbucket())).DVal())); CDouble dDiffNDVRemainJoin(clib::DAbs((dNDVRemainJoin - phistJoin->DDistinctRemain()).DVal())); CDouble dDiffFreqRemainJoin(clib::DAbs((dFreqRemainJoin - phistJoin->DFreqRemain()).DVal())); if (phistJoin->UlBuckets() != ulBucketsJoin || (dDiffNDVJoin > CStatistics::DEpsilon) || (dDiffNDVRemainJoin > CStatistics::DEpsilon) || (dDiffFreqRemainJoin > CStatistics::DEpsilon)) { eres = GPOS_FAILED; } GPOS_DELETE(phistJoin); } // clean up phmulhist->Release(); return eres; } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::EresUnittest_CBucketInt4 // // @doc: // Basic int4 bucket tests; // //--------------------------------------------------------------------------- GPOS_RESULT CStatisticsTest::EresUnittest_CBucketInt4() { // create memory pool CAutoMemoryPool amp; IMemoryPool *pmp = amp.Pmp(); // generate integer points CPoint *ppoint1 = CTestUtils::PpointInt4(pmp, 1); CPoint *ppoint2 = CTestUtils::PpointInt4(pmp, 2); CPoint *ppoint3 = CTestUtils::PpointInt4(pmp, 3); // bucket [1,1] CBucket *pbucket1 = Pbucket(pmp, 1, 1, CDouble(1.0), CDouble(1.0)); Print(pmp, "b1", pbucket1); GPOS_RTL_ASSERT_MSG(pbucket1->FContains(ppoint1), "[1,1] must contain 1"); GPOS_RTL_ASSERT_MSG(CDouble(1.0) == pbucket1->DOverlap(ppoint1), "overlap of 1 in [1,1] must 1.0"); GPOS_RTL_ASSERT_MSG(!pbucket1->FContains(ppoint2), "[1,1] must not contain 2"); // bucket [1,3) CBucket *pbucket2 = Pbucket(pmp, 1, 3, CDouble(1.0), CDouble(10.0)); Print(pmp, "b2", pbucket2); // overlap of [1,2) w.r.t [1,3) should be about 50% CDouble dOverlap = pbucket2->DOverlap(ppoint2); GPOS_RTL_ASSERT(0.49 <= dOverlap && dOverlap <= 0.51); // subsumption GPOS_RTL_ASSERT(pbucket1->FSubsumes(pbucket1)); GPOS_RTL_ASSERT(pbucket2->FSubsumes(pbucket1)); // width CDouble dWidth = pbucket1->DWidth(); GPOS_RTL_ASSERT(0.99 <= dWidth && dWidth <= 1.01); // bucket [1,2] and (2,4) CBucket *pbucket3 = Pbucket(pmp, 1, 2, true, true, CDouble(1.0), CDouble(1.0)); CBucket *pbucket4 = Pbucket(pmp, 2, 4, false, false, CDouble(1.0), CDouble(1.0)); // point FBefore GPOS_RTL_ASSERT_MSG(pbucket4->FBefore(ppoint2), "2 must be before (2,4)"); // bucket FBefore GPOS_RTL_ASSERT_MSG(pbucket3->FBefore(pbucket4), "[1,2] must be before (2,4)"); ppoint1->Release(); ppoint2->Release(); ppoint3->Release(); GPOS_DELETE(pbucket1); GPOS_DELETE(pbucket2); GPOS_DELETE(pbucket3); GPOS_DELETE(pbucket4); return GPOS_OK; } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::EresUnittest_CBucketBool // // @doc: // Basic BOOL bucket tests; // //--------------------------------------------------------------------------- GPOS_RESULT CStatisticsTest::EresUnittest_CBucketBool() { // create memory pool CAutoMemoryPool amp; IMemoryPool *pmp = amp.Pmp(); // generate boolean points CPoint *p1 = CTestUtils::PpointBool(pmp, true); CPoint *p2 = CTestUtils::PpointBool(pmp, false); // bucket for true CBucket *pbucket = Pbucket(pmp, true, CDouble(1.0)); GPOS_RTL_ASSERT_MSG(pbucket->FContains(p1), "true bucket must contain true"); GPOS_RTL_ASSERT_MSG(CDouble(1.0) == pbucket->DOverlap(p1), "overlap must 1.0"); GPOS_RTL_ASSERT_MSG(!pbucket->FContains(p2), "true bucket must not contain false"); GPOS_RTL_ASSERT_MSG(CDouble(0.0) == pbucket->DOverlap(p2), "overlap must 0.0"); p1->Release(); p2->Release(); GPOS_DELETE(pbucket); return GPOS_OK; } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::EresUnittest_Join // // @doc: // Join buckets tests; // //--------------------------------------------------------------------------- GPOS_RESULT CStatisticsTest::EresUnittest_Join() { // create memory pool CAutoMemoryPool amp; IMemoryPool *pmp = amp.Pmp(); CMDAccessor *pmda = COptCtxt::PoctxtFromTLS()->Pmda(); SStatsJoinSTestCase rgstatsjointc[] = { {"../data/dxl/statistics/Join-Statistics-Input.xml", "../data/dxl/statistics/Join-Statistics-Output.xml", false, Pdrgpstatsjoin1}, {"../data/dxl/statistics/Join-Statistics-Input-Null-Bucket.xml", "../data/dxl/statistics/Join-Statistics-Output-Null-Bucket.xml", false, PdrgpstatsjoinNullableCols}, {"../data/dxl/statistics/LOJ-Input.xml", "../data/dxl/statistics/LOJ-Output.xml", true, PdrgpstatsjoinNullableCols}, {"../data/dxl/statistics/Join-Statistics-Input-Only-Nulls.xml", "../data/dxl/statistics/Join-Statistics-Output-Only-Nulls.xml", false, PdrgpstatsjoinNullableCols}, {"../data/dxl/statistics/Join-Statistics-Input-Only-Nulls.xml", "../data/dxl/statistics/Join-Statistics-Output-LOJ-Only-Nulls.xml", true, PdrgpstatsjoinNullableCols}, // TODO: - Sep 13, 2013 re-enable after dDistinct value is fixed in a cleaner way // {"../data/dxl/statistics/Join-Statistics-DDistinct-Input.xml", "../data/dxl/statistics/Join-Statistics-DDistinct-Output.xml", false, Pdrgpstatsjoin2}, }; const ULONG ulTestCases = GPOS_ARRAY_SIZE(rgstatsjointc); for (ULONG ul = 0; ul < ulTestCases; ul++) { SStatsJoinSTestCase elem = rgstatsjointc[ul]; // read input/output DXL file CHAR *szDXLInput = CDXLUtils::SzRead(pmp, elem.m_szInputFile); CHAR *szDXLOutput = CDXLUtils::SzRead(pmp, elem.m_szOutputFile); BOOL fLeftOuterJoin = elem.m_fLeftOuterJoin; GPOS_CHECK_ABORT; // parse the input statistics objects DrgPdxlstatsderrel *pdrgpdxlstatsderrel = CDXLUtils::PdrgpdxlstatsderrelParseDXL(pmp, szDXLInput, NULL); DrgPstats *pdrgpstatBefore = CDXLUtils::PdrgpstatsTranslateStats(pmp, pmda, pdrgpdxlstatsderrel); pdrgpdxlstatsderrel->Release(); GPOS_ASSERT(NULL != pdrgpstatBefore); GPOS_ASSERT(2 == pdrgpstatBefore->UlLength()); CStatistics *pstats1 = (*pdrgpstatBefore)[0]; CStatistics *pstats2 = (*pdrgpstatBefore)[1]; GPOS_CHECK_ABORT; // generate the join conditions FnPdrgpstatjoin *pf = elem.m_pf; GPOS_ASSERT(NULL != pf); DrgPstatsjoin *pdrgpstatsjoin = pf(pmp); // calculate the output stats CStatistics *pstatsOutput = NULL; if (fLeftOuterJoin) { pstatsOutput = pstats1->PstatsLOJ(pmp, pstats2, pdrgpstatsjoin); } else { pstatsOutput = pstats1->PstatsInnerJoin(pmp, pstats2, pdrgpstatsjoin); } GPOS_ASSERT(NULL != pstatsOutput); DrgPstats *pdrgpstatOutput = GPOS_NEW(pmp) DrgPstats(pmp); pdrgpstatOutput->Append(pstatsOutput); // serialize and compare against expected stats CWStringDynamic *pstrOutput = CDXLUtils::PstrSerializeStatistics ( pmp, pmda, pdrgpstatOutput, true /*fSerializeHeaderFooter*/, true /*fIndent*/ ); CWStringDynamic dstrExpected(pmp); dstrExpected.AppendFormat(GPOS_WSZ_LIT("%s"), szDXLOutput); GPOS_RESULT eres = GPOS_OK; CWStringDynamic str(pmp); COstreamString oss(&str); // compare the two dxls if (!pstrOutput->FEquals(&dstrExpected)) { oss << "Output does not match expected DXL document" << std::endl; oss << "Actual: " << std::endl; oss << pstrOutput->Wsz() << std::endl; oss << "Expected: " << std::endl; oss << dstrExpected.Wsz() << std::endl; GPOS_TRACE(str.Wsz()); eres = GPOS_FAILED; } // clean up pdrgpstatBefore->Release(); pdrgpstatOutput->Release(); pdrgpstatsjoin->Release(); GPOS_DELETE_ARRAY(szDXLInput); GPOS_DELETE_ARRAY(szDXLOutput); GPOS_DELETE(pstrOutput); if (GPOS_FAILED == eres) { return eres; } } return GPOS_OK; } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::EresUnittest_GbAggWithRepeatedGbCols // // @doc: // GbAgg test when grouping on repeated columns // //--------------------------------------------------------------------------- GPOS_RESULT CStatisticsTest::EresUnittest_GbAggWithRepeatedGbCols() { CAutoMemoryPool amp; IMemoryPool *pmp = amp.Pmp(); // setup a file-based provider CMDProviderMemory *pmdp = CTestUtils::m_pmdpf; pmdp->AddRef(); CMDAccessor mda(pmp, CMDCache::Pcache(), CTestUtils::m_sysidDefault, pmdp); // install opt context in TLS CAutoOptCtxt aoc ( pmp, &mda, NULL /* pceeval */, CTestUtils::Pcm(pmp) ); CExpression *pexpr = CTestUtils::PexprLogicalJoin<CLogicalInnerJoin>(pmp); CDrvdPropRelational *pdprel = CDrvdPropRelational::Pdprel(pexpr->PdpDerive()); CColRefSet *pcrs = pdprel->PcrsOutput(); // create first GbAgg expression: GbAgg on top of given expression DrgPcr *pdrgpcr1 = GPOS_NEW(pmp) DrgPcr(pmp); pdrgpcr1->Append(pcrs->PcrFirst()); CExpression *pexprGbAgg1 = CUtils::PexprLogicalGbAggGlobal(pmp, pdrgpcr1, pexpr, GPOS_NEW(pmp) CExpression(pmp, GPOS_NEW(pmp) CScalarProjectList(pmp))); // create second GbAgg expression: GbAgg with repeated base column on top of given expression DrgPcr *pdrgpcr2 = GPOS_NEW(pmp) DrgPcr(pmp); pdrgpcr2->Append(pcrs->PcrFirst()); pdrgpcr2->Append(pcrs->PcrFirst()); pexpr->AddRef(); CExpression *pexprGbAgg2 = CUtils::PexprLogicalGbAggGlobal(pmp, pdrgpcr2, pexpr, GPOS_NEW(pmp) CExpression(pmp, GPOS_NEW(pmp) CScalarProjectList(pmp))); // create third GbAgg expression: GbAgg with a repeated projected base column on top of given expression pexpr->AddRef(); CExpression *pexprPrj = CUtils::PexprAddProjection(pmp, pexpr, CUtils::PexprScalarIdent(pmp, pcrs->PcrFirst())); CColRef *pcrComputed = CScalarProjectElement::PopConvert((*(*pexprPrj)[1])[0]->Pop())->Pcr(); DrgPcr *pdrgpcr3 = GPOS_NEW(pmp) DrgPcr(pmp); pdrgpcr3->Append(pcrs->PcrFirst()); pdrgpcr3->Append(pcrComputed); CExpression *pexprGbAgg3 = CUtils::PexprLogicalGbAggGlobal(pmp, pdrgpcr3, pexprPrj, GPOS_NEW(pmp) CExpression(pmp, GPOS_NEW(pmp) CScalarProjectList(pmp))); // derive stats on different GbAgg expressions CReqdPropRelational *prprel = GPOS_NEW(pmp) CReqdPropRelational(GPOS_NEW(pmp) CColRefSet(pmp)); (void) pexprGbAgg1->PstatsDerive(prprel, NULL /* pdrgpstatCtxt */); (void) pexprGbAgg2->PstatsDerive(prprel, NULL /* pdrgpstatCtxt */); (void) pexprGbAgg3->PstatsDerive(prprel, NULL /* pdrgpstatCtxt */); BOOL fRows1EqualRows2 = (pexprGbAgg1->Pstats()->DRows() == pexprGbAgg2->Pstats()->DRows()); BOOL fRows2EqualRows3 = (pexprGbAgg2->Pstats()->DRows() == pexprGbAgg3->Pstats()->DRows()); { CAutoTrace at(pmp); at.Os() << std::endl << "pexprGbAgg1:" << std::endl << *pexprGbAgg1 << std::endl; at.Os() << std::endl << "pexprGbAgg2:" << std::endl << *pexprGbAgg2 << std::endl; at.Os() << std::endl << "pexprGbAgg3:" << std::endl << *pexprGbAgg3 << std::endl; } // cleanup pexprGbAgg1->Release(); pexprGbAgg2->Release(); pexprGbAgg3->Release(); prprel->Release(); if (fRows1EqualRows2 && fRows2EqualRows3) { return GPOS_OK; } return GPOS_FAILED; } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::Pdrgpstatsjoin1 // // @doc: // Generate join predicates // //--------------------------------------------------------------------------- DrgPstatsjoin * CStatisticsTest::Pdrgpstatsjoin1 ( IMemoryPool *pmp ) { DrgPstatsjoin *pdrgpstatsjoin = GPOS_NEW(pmp) DrgPstatsjoin(pmp); pdrgpstatsjoin->Append(GPOS_NEW(pmp) CStatisticsJoin(16, CStatsPred::EstatscmptEq, 32)); pdrgpstatsjoin->Append(GPOS_NEW(pmp) CStatisticsJoin(0, CStatsPred::EstatscmptEq, 31)); pdrgpstatsjoin->Append(GPOS_NEW(pmp) CStatisticsJoin(54, CStatsPred::EstatscmptEq, 32)); pdrgpstatsjoin->Append(GPOS_NEW(pmp) CStatisticsJoin(53, CStatsPred::EstatscmptEq, 31)); return pdrgpstatsjoin; } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::PdrgpstatsjoinNullableCols // // @doc: // Generate join predicate over columns that contain null values // //--------------------------------------------------------------------------- DrgPstatsjoin * CStatisticsTest::PdrgpstatsjoinNullableCols ( IMemoryPool *pmp ) { DrgPstatsjoin *pdrgpstatsjoin = GPOS_NEW(pmp) DrgPstatsjoin(pmp); pdrgpstatsjoin->Append(GPOS_NEW(pmp) CStatisticsJoin(1, CStatsPred::EstatscmptEq, 2)); return pdrgpstatsjoin; } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::Pdrgpstatsjoin2 // // @doc: // Generate join predicates // //--------------------------------------------------------------------------- DrgPstatsjoin * CStatisticsTest::Pdrgpstatsjoin2 ( IMemoryPool *pmp ) { DrgPstatsjoin *pdrgpstatsjoin = GPOS_NEW(pmp) DrgPstatsjoin(pmp); pdrgpstatsjoin->Append(GPOS_NEW(pmp) CStatisticsJoin(0, CStatsPred::EstatscmptEq, 8)); return pdrgpstatsjoin; } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::EresUnittest_CBucketIntersect // // @doc: // Intersection of buckets // //--------------------------------------------------------------------------- GPOS_RESULT CStatisticsTest::EresUnittest_CBucketIntersect() { // create memory pool CAutoMemoryPool amp; IMemoryPool *pmp = amp.Pmp(); SBucketsIntersectTestElem rgBucketsIntersectTestElem[] = { {7, 203, true, true, 3, 213, true, true, true, 7, 203, true, true}, // overlaps {3, 213, true, true, 7, 203, true, true, true, 7, 203, true, true}, // same as above but reversed {13, 103, true, true, 2, 98, true, true, true, 13, 98, true, true,}, // subsumes {2, 99, true, true, 13, 103, true, true, true, 13, 99, true, true}, // same as above but reversed {0, 5, true, true, 10, 15, false, true, false, -1 , -1 , false, false}, // negative {10, 15, true, true, 0, 5, false, true, false, -1 , -1 , false, false}, // same as above but reversed {0, 5, true, true, 5, 10, true, true, true, 5 , 5 , true, true}, // ub of one bucket is the same as lb of the other and both bounds are closed {5, 10, true, true, 0, 5, true, true, true, 5 , 5 , true, true}, // same as above but reversed {0, 5, true, true, 5, 10, false, true, false, -1 , -1 , false, false}, // ub of one bucket is the same as lb of the other but closing criteria are different {5, 10, false, true, 0, 5, true, true, false, -1 , -1 , false, false}, // same as above but reversed {0, 5, true, true, 0, 5, false, true, true, 0, 5, false, true}, // exact match but only differ in closure of lb {0, 5, true, true, 0, 5, true, true, true, 0, 5, true, true}, // exact match with all bounds closed {0, 5, true, false, 0, 5, true, false, true, 0, 5, true, false}, // exact match with ubs open {0, 5, false, false, 0, 5, true, false, true, 0, 5, false, false}, // exact match with lbs differ in closure {0, 5, true, true, 0, 5, true, false, true, 0, 5, true, false}, // exact match with ubs differ in closure }; const ULONG ulLen = GPOS_ARRAY_SIZE(rgBucketsIntersectTestElem); for (ULONG ul = 0; ul < ulLen; ul++) { CBucket *pbucket1 = Pbucket ( pmp, rgBucketsIntersectTestElem[ul].m_iLb1, rgBucketsIntersectTestElem[ul].m_iUb1, rgBucketsIntersectTestElem[ul].m_fLb1Closed, rgBucketsIntersectTestElem[ul].m_fUb1Closed, CDouble(0.1), CDouble(100.0) ); CBucket *pbucket2 = Pbucket ( pmp, rgBucketsIntersectTestElem[ul].m_iLb2, rgBucketsIntersectTestElem[ul].m_iUb2, rgBucketsIntersectTestElem[ul].m_fLb2Closed, rgBucketsIntersectTestElem[ul].m_fUb2Closed, CDouble(0.1), CDouble(100.0) ); BOOL fResult = pbucket1->FIntersects(pbucket2); GPOS_RESULT eres = GPOS_FAILED; if (rgBucketsIntersectTestElem[ul].fIntersect == fResult) { eres = GPOS_OK; } if (true == fResult) { CDouble dDummy1(0.0); CDouble dDummy2(0.0); CBucket *pbucketOuput = pbucket1->PbucketIntersect(pmp, pbucket2, &dDummy1, &dDummy2); CBucket *pbucketExpected = Pbucket ( pmp, rgBucketsIntersectTestElem[ul].m_iLbOutput, rgBucketsIntersectTestElem[ul].m_iUbOutput, rgBucketsIntersectTestElem[ul].m_fLbOutputClosed, rgBucketsIntersectTestElem[ul].m_fUbOutputClosed, CDouble(0.1), CDouble(100.0) ); BOOL fMatch = CStatisticsTest::FMatchBucketBoundary(pbucketOuput, pbucketExpected); if (!fMatch) { eres = GPOS_FAILED; CWStringDynamic str(pmp); COstreamString oss(&str); pbucketOuput->OsPrint(oss); oss << std::endl; pbucketExpected->OsPrint(oss); oss << std::endl; GPOS_TRACE(str.Wsz()); } GPOS_DELETE(pbucketExpected); GPOS_DELETE(pbucketOuput); } // clean up GPOS_DELETE(pbucket1); GPOS_DELETE(pbucket2); if (GPOS_OK != eres) { return eres; } } return GPOS_OK; } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::FMatchBucketBoundary // // @doc: // Do the bucket boundaries match // //--------------------------------------------------------------------------- BOOL CStatisticsTest::FMatchBucketBoundary ( CBucket *pbucket1, CBucket *pbucket2 ) { GPOS_ASSERT(NULL != pbucket1); GPOS_ASSERT(NULL != pbucket2); if (pbucket1->FLowerClosed() != pbucket2->FLowerClosed()) { return false; } if (pbucket1->FUpperClosed() != pbucket2->FUpperClosed()) { return false; } if (pbucket1->PpLower()->FEqual(pbucket2->PpLower()) && pbucket1->PpUpper()->FEqual(pbucket2->PpUpper())) { return true; } return false; } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::EresUnittest_CBucketScale // // @doc: // Scaling a bucket // //--------------------------------------------------------------------------- GPOS_RESULT CStatisticsTest::EresUnittest_CBucketScale() { // create memory pool CAutoMemoryPool amp; IMemoryPool *pmp = amp.Pmp(); // generate integer point CPoint *ppoint1 = CTestUtils::PpointInt4(pmp, 10); // bucket [1,100) CBucket *pbucket1 = Pbucket(pmp, 1, 100, CDouble(0.5), CDouble(20.0)); CBucket *pbucket2 = pbucket1->PbucketScaleUpper(pmp, ppoint1, false /* fIncludeUpper */); // new bucket [1, 10) must not contain 10 GPOS_RTL_ASSERT(!pbucket2->FContains(ppoint1)); // new bucket [1, 10) must contain 9 CPoint *ppoint2 = CTestUtils::PpointInt4(pmp, 9); GPOS_RTL_ASSERT(pbucket2->FContains(ppoint2)); ppoint2->Release(); // new bucket's frequency and distinct values must be lesser than original GPOS_RTL_ASSERT(pbucket2->DFrequency() < pbucket1->DFrequency()); GPOS_RTL_ASSERT(pbucket2->DDistinct() < pbucket1->DDistinct()); // scale lower CBucket *pbucket3 = pbucket1->PbucketScaleLower(pmp, ppoint1, true /* fIncludeLower */); GPOS_RTL_ASSERT(pbucket3->FContains(ppoint1)); // scale to a singleton CBucket *pbucket4 = pbucket1->PbucketSingleton(pmp, ppoint1); GPOS_RTL_ASSERT(pbucket4->DDistinct() < 2.0); // clean up ppoint1->Release(); GPOS_DELETE(pbucket1); GPOS_DELETE(pbucket2); GPOS_DELETE(pbucket3); GPOS_DELETE(pbucket4); return GPOS_OK; } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::EresUnittest_CBucketDifference // // @doc: // Difference op // //--------------------------------------------------------------------------- GPOS_RESULT CStatisticsTest::EresUnittest_CBucketDifference() { // create memory pool CAutoMemoryPool amp; IMemoryPool *pmp = amp.Pmp(); // bucket [1,100) CBucket *pbucket1 = Pbucket(pmp, 1, 100, CDouble(1.0), CDouble(1.0)); // bucket [50,75) CBucket *pbucket2 = Pbucket(pmp, 50, 60, CDouble(1.0), CDouble(1.0)); // bucket [200, 300) CBucket *pbucket3 = Pbucket(pmp, 200, 300, CDouble(1.0), CDouble(1.0)); CBucket *pbucket4 = NULL; CBucket *pbucket5 = NULL; pbucket1->Difference(pmp, pbucket2, &pbucket4, &pbucket5); GPOS_RTL_ASSERT(NULL != pbucket4); GPOS_RTL_ASSERT(NULL != pbucket5); Print(pmp, "pbucket4", pbucket4); Print(pmp, "pbucket5", pbucket4); CBucket *pbucket6 = NULL; CBucket *pbucket7 = NULL; pbucket1->Difference(pmp, pbucket3, &pbucket6, &pbucket7); GPOS_RTL_ASSERT(NULL != pbucket6); GPOS_RTL_ASSERT(NULL == pbucket7); Print(pmp, "pbucket6", pbucket6); GPOS_DELETE(pbucket1); GPOS_DELETE(pbucket2); GPOS_DELETE(pbucket3); GPOS_DELETE(pbucket4); GPOS_DELETE(pbucket5); GPOS_DELETE(pbucket6); return GPOS_OK; } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::PpointNumeric // // @doc: // Create a point from a encoded value of numeric datatype // //--------------------------------------------------------------------------- CPoint * CStatisticsTest::PpointNumeric ( IMemoryPool *pmp, CWStringDynamic *pstrEncodedValue, CDouble dValue ) { CMDAccessor *pmda = COptCtxt::PoctxtFromTLS()->Pmda(); CMDIdGPDB *pmdid = GPOS_NEW(pmp) CMDIdGPDB(CMDIdGPDB::m_mdidNumeric); const IMDType *pmdtype = pmda->Pmdtype(pmdid); ULONG ulbaSize = 0; BYTE *pba = CDXLUtils::PByteArrayFromStr(pmp, pstrEncodedValue, &ulbaSize); CDXLDatumStatsDoubleMappable *pdxldatum = GPOS_NEW(pmp) CDXLDatumStatsDoubleMappable ( pmp, pmdid, pmdtype->FByValue() /*fConstByVal*/, false /*fConstNull*/, pba, ulbaSize, dValue ); IDatum *pdatum = pmdtype->Pdatum(pmp, pdxldatum); CPoint *ppoint = GPOS_NEW(pmp) CPoint(pdatum); pdxldatum->Release(); return ppoint; } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::PpointGeneric // // @doc: // Create a point from an encoded value of specific datatype // //--------------------------------------------------------------------------- CPoint * CStatisticsTest::PpointGeneric ( IMemoryPool *pmp, OID oid, CWStringDynamic *pstrEncodedValue, LINT lValue ) { CMDAccessor *pmda = COptCtxt::PoctxtFromTLS()->Pmda(); IMDId *pmdid = GPOS_NEW(pmp) CMDIdGPDB(oid); IDatum *pdatum = CTestUtils::PdatumGeneric(pmp, pmda, pmdid, pstrEncodedValue, lValue); CPoint *ppoint = GPOS_NEW(pmp) CPoint(pdatum); return ppoint; } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::Pbucket // // @doc: // Create a bucket // //--------------------------------------------------------------------------- CBucket * CStatisticsTest::Pbucket ( IMemoryPool *pmp, INT iLower, INT iUpper, CDouble dFrequency, CDouble dDistinct ) { CPoint *ppLower = CTestUtils::PpointInt4(pmp, iLower); CPoint *ppUpper = CTestUtils::PpointInt4(pmp, iUpper); BOOL fUpperClosed = false; if (ppLower->FEqual(ppUpper)) { fUpperClosed = true; } CBucket *pbucket = GPOS_NEW(pmp) CBucket ( ppLower, ppUpper, true /* fLowerClosed */, fUpperClosed, dFrequency, dDistinct ); return pbucket; } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::Pbucket // // @doc: // Create a bucket // //--------------------------------------------------------------------------- CBucket * CStatisticsTest::Pbucket ( IMemoryPool *pmp, INT iLower, INT iUpper, BOOL fLowerClosed, BOOL fUpperClosed, CDouble dFrequency, CDouble dDistinct ) { CPoint *ppLower = CTestUtils::PpointInt4(pmp, iLower); CPoint *ppUpper = CTestUtils::PpointInt4(pmp, iUpper); CBucket *pbucket = GPOS_NEW(pmp) CBucket ( ppLower, ppUpper, fLowerClosed, fUpperClosed, dFrequency, dDistinct ); return pbucket; } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::Pbucket // // @doc: // Create a bucket // //--------------------------------------------------------------------------- CBucket * CStatisticsTest::Pbucket ( IMemoryPool *pmp, BOOL fValue, CDouble dFrequency ) { CPoint *ppLower = CTestUtils::PpointBool(pmp, fValue); // lower bound is also upper bound ppLower->AddRef(); CBucket *pbucket = GPOS_NEW(pmp) CBucket ( ppLower, ppLower, true /* fClosedUpper */, true /* fClosedUpper */, dFrequency, 1.0 ); return pbucket; } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::EresUnittest_CHistogramInt4 // // @doc: // Histogram of int4 // //--------------------------------------------------------------------------- GPOS_RESULT CStatisticsTest::EresUnittest_CHistogramInt4() { // create memory pool CAutoMemoryPool amp; IMemoryPool *pmp = amp.Pmp(); // original histogram CHistogram *phist = PhistExampleInt4(pmp); Print(pmp, "phist", phist); // test edge case of PbucketGreaterThan CPoint *ppoint0 = CTestUtils::PpointInt4(pmp, 9); CHistogram *phist0 = phist->PhistFilter(pmp, CStatsPred::EstatscmptG, ppoint0); Print(pmp, "phist0", phist0); GPOS_RTL_ASSERT(phist0->UlBuckets() == 9); CPoint *ppoint1 = CTestUtils::PpointInt4(pmp, 35); CHistogram *phist1 = phist->PhistFilter(pmp, CStatsPred::EstatscmptL, ppoint1); Print(pmp, "phist1", phist1); GPOS_RTL_ASSERT(phist1->UlBuckets() == 4); // edge case where point is equal to upper bound CPoint *ppoint2 = CTestUtils::PpointInt4(pmp, 50); CHistogram *phist2 = phist->PhistFilter(pmp, CStatsPred::EstatscmptL,ppoint2); Print(pmp, "phist2", phist2); GPOS_RTL_ASSERT(phist2->UlBuckets() == 5); // equality check CPoint *ppoint3 = CTestUtils::PpointInt4(pmp, 100); CHistogram *phist3 = phist->PhistFilter(pmp, CStatsPred::EstatscmptEq, ppoint3); Print(pmp, "phist3", phist3); GPOS_RTL_ASSERT(phist3->UlBuckets() == 1); // normalized output after filter CPoint *ppoint4 = CTestUtils::PpointInt4(pmp, 100); CDouble dScaleFactor(0.0); CHistogram *phist4 = phist->PhistFilterNormalized(pmp, CStatsPred::EstatscmptEq, ppoint4, &dScaleFactor); Print(pmp, "phist4", phist4); GPOS_RTL_ASSERT(phist4->FValid()); // lasj CHistogram *phist5 = phist->PhistLASJ(pmp, CStatsPred::EstatscmptEq, phist2); Print(pmp, "phist5", phist5); GPOS_RTL_ASSERT(phist5->UlBuckets() == 5); // inequality check CHistogram *phist6 = phist->PhistFilter(pmp, CStatsPred::EstatscmptNEq, ppoint2); Print(pmp, "phist6", phist6); GPOS_RTL_ASSERT(phist6->UlBuckets() == 10); // histogram with null fraction and remaining tuples CHistogram *phist7 = PhistExampleInt4Remain(pmp); Print(pmp, "phist7", phist7); CPoint *ppoint5 = CTestUtils::PpointInt4(pmp, 20); // equality check, hitting remaining tuples CHistogram *phist8 = phist7->PhistFilter(pmp, CStatsPred::EstatscmptEq, ppoint3); GPOS_RTL_ASSERT(clib::DAbs((phist8->DFrequency() - 0.2).DVal()) < CStatistics::DEpsilon); GPOS_RTL_ASSERT(clib::DAbs((phist8->DDistinct() - 1.0).DVal()) < CStatistics::DEpsilon); // greater than, hitting remaining tuples CHistogram *phist9 = phist7->PhistFilter(pmp, CStatsPred::EstatscmptG, ppoint1); Print(pmp, "phist9", phist9); GPOS_RTL_ASSERT(clib::DAbs((phist9->DFrequency() - 0.26).DVal()) < CStatistics::DEpsilon); GPOS_RTL_ASSERT(clib::DAbs((phist9->DDistinct() - 1.8).DVal()) < CStatistics::DEpsilon); // equality join, hitting remaining tuples CHistogram *phist10 = phist7->PhistJoin(pmp, CStatsPred::EstatscmptEq, phist7); GPOS_RTL_ASSERT(phist10->UlBuckets() == 5); GPOS_RTL_ASSERT(clib::DAbs((phist10->DDistinctRemain() - 2.0).DVal()) < CStatistics::DEpsilon); GPOS_RTL_ASSERT(clib::DAbs((phist10->DFreqRemain() - 0.08).DVal()) < CStatistics::DEpsilon); // clean up ppoint0->Release(); ppoint1->Release(); ppoint2->Release(); ppoint3->Release(); ppoint4->Release(); ppoint5->Release(); GPOS_DELETE(phist); GPOS_DELETE(phist0); GPOS_DELETE(phist1); GPOS_DELETE(phist2); GPOS_DELETE(phist3); GPOS_DELETE(phist4); GPOS_DELETE(phist5); GPOS_DELETE(phist6); GPOS_DELETE(phist7); GPOS_DELETE(phist8); GPOS_DELETE(phist9); GPOS_DELETE(phist10); return GPOS_OK; } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::EresUnittest_CHistogramBool // // @doc: // Histogram on bool // //--------------------------------------------------------------------------- GPOS_RESULT CStatisticsTest::EresUnittest_CHistogramBool() { // create memory pool CAutoMemoryPool amp; IMemoryPool *pmp = amp.Pmp(); // generate histogram of the form [false, false), [true,true) DrgPbucket *pdrgppbucket = GPOS_NEW(pmp) DrgPbucket(pmp); CBucket *pbucketFalse = Pbucket(pmp, false, 0.1); CBucket *pbucketTrue = Pbucket(pmp, false, 0.9); pdrgppbucket->Append(pbucketFalse); pdrgppbucket->Append(pbucketTrue); CHistogram *phist = GPOS_NEW(pmp) CHistogram(pdrgppbucket); // equality check CPoint *ppoint1 = CTestUtils::PpointBool(pmp, false); CDouble dScaleFactor(0.0); CHistogram *phist1 = phist->PhistFilterNormalized(pmp, CStatsPred::EstatscmptEq, ppoint1, &dScaleFactor); Print(pmp, "phist1", phist1); GPOS_RTL_ASSERT(phist1->UlBuckets() == 1); // clean up ppoint1->Release(); GPOS_DELETE(phist); GPOS_DELETE(phist1); return GPOS_OK; } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::Print // // @doc: // Dump bucket // //--------------------------------------------------------------------------- void CStatisticsTest::Print ( IMemoryPool *pmp, const char *pcPrefix, const CBucket *pbucket ) { CWStringDynamic str(pmp); COstreamString oss(&str); oss << pcPrefix << " = "; pbucket->OsPrint(oss); oss << std::endl; GPOS_TRACE(str.Wsz()); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::Print // // @doc: // Dump histogram output // //--------------------------------------------------------------------------- void CStatisticsTest::Print ( IMemoryPool *pmp, const char *pcPrefix, const CHistogram *phist ) { CWStringDynamic str(pmp); COstreamString oss(&str); oss << pcPrefix << " = "; phist->OsPrint(oss); oss << std::endl; GPOS_TRACE(str.Wsz()); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::PhistExampleInt4 // // @doc: // Generates example int histogram // //--------------------------------------------------------------------------- CHistogram* CStatisticsTest::PhistExampleInt4 ( IMemoryPool *pmp ) { // generate histogram of the form [0, 10), [10, 20), [20, 30) ... [80, 90) DrgPbucket *pdrgppbucket = GPOS_NEW(pmp) DrgPbucket(pmp); for (ULONG ulIdx = 0; ulIdx < 9; ulIdx++) { INT iLower = INT(ulIdx * 10); INT iUpper = iLower + INT(10); CDouble dFrequency(0.1); CDouble dDistinct(4.0); CBucket *pbucket = Pbucket(pmp, iLower, iUpper, dFrequency, dDistinct); pdrgppbucket->Append(pbucket); } // add an additional singleton bucket [100, 100] pdrgppbucket->Append(Pbucket(pmp, 100, 100, 0.1, 1.0)); return GPOS_NEW(pmp) CHistogram(pdrgppbucket); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::PhistExampleInt4Remain // // @doc: // Generates example int histogram having tuples not covered by buckets, // including null fraction and nDistinctRemain // //--------------------------------------------------------------------------- CHistogram* CStatisticsTest::PhistExampleInt4Remain ( IMemoryPool *pmp ) { // generate histogram of the form [0, 0], [10, 10], [20, 20] ... DrgPbucket *pdrgppbucket = GPOS_NEW(pmp) DrgPbucket(pmp); for (ULONG ulIdx = 0; ulIdx < 5; ulIdx++) { INT iLower = INT(ulIdx * 10); INT iUpper = iLower; CDouble dFrequency(0.1); CDouble dDistinct(1.0); CBucket *pbucket = Pbucket(pmp, iLower, iUpper, dFrequency, dDistinct); pdrgppbucket->Append(pbucket); } return GPOS_NEW(pmp) CHistogram(pdrgppbucket, true, 0.1 /*dNullFreq*/, 2.0 /*dDistinctRemain*/, 0.4 /*dFreqRemain*/); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::PhistInt4Remain // // @doc: // Generate int histogram based on the NDV and bucket information provided // //--------------------------------------------------------------------------- CHistogram* CStatisticsTest::PhistInt4Remain ( IMemoryPool *pmp, ULONG ulBuckets, CDouble dNDVPerBucket, BOOL fNullFreq, CDouble dNDVRemain ) { // generate histogram of the form [0, 100), [100, 200), [200, 300) ... DrgPbucket *pdrgppbucket = GPOS_NEW(pmp) DrgPbucket(pmp); for (ULONG ulIdx = 0; ulIdx < ulBuckets; ulIdx++) { INT iLower = INT(ulIdx * 100); INT iUpper = INT((ulIdx + 1) * 100); CDouble dFrequency(0.1); CDouble dDistinct = dNDVPerBucket; CBucket *pbucket = Pbucket(pmp, iLower, iUpper, dFrequency, dDistinct); pdrgppbucket->Append(pbucket); } CDouble dFreq = CStatisticsUtils::DFrequency(pdrgppbucket); CDouble dNullFreq(0.0); if (fNullFreq && 1 > dFreq) { dNullFreq = 0.1; dFreq = dFreq + dNullFreq; } CDouble dFreqRemain = (1 - dFreq); if (dFreqRemain < CStatistics::DEpsilon || dNDVRemain < CStatistics::DEpsilon) { dFreqRemain = CDouble(0.0); } return GPOS_NEW(pmp) CHistogram(pdrgppbucket, true, dNullFreq, dNDVRemain, dFreqRemain); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::PhistExampleInt4Dim // // @doc: // Generates example int histogram corresponding to dimension table // //--------------------------------------------------------------------------- CHistogram* CStatisticsTest::PhistExampleInt4Dim ( IMemoryPool *pmp ) { // generate histogram of the form [0, 10), [10, 20), [20, 30) ... [80, 90) DrgPbucket *pdrgppbucket = GPOS_NEW(pmp) DrgPbucket(pmp); for (ULONG ulIdx = 0; ulIdx < 9; ulIdx++) { INT iLower = INT(ulIdx * 10); INT iUpper = iLower + INT(10); CDouble dFrequency(0.1); CDouble dDistinct(10.0); CBucket *pbucket = Pbucket(pmp, iLower, iUpper, dFrequency, dDistinct); pdrgppbucket->Append(pbucket); } return GPOS_NEW(pmp) CHistogram(pdrgppbucket); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::PhistExampleBool // // @doc: // Generates example bool histogram // //--------------------------------------------------------------------------- CHistogram* CStatisticsTest::PhistExampleBool ( IMemoryPool *pmp ) { DrgPbucket *pdrgppbucket = GPOS_NEW(pmp) DrgPbucket(pmp); CBucket *pbucketFalse = Pbucket(pmp, false, 0.1); CBucket *pbucketTrue = Pbucket(pmp, true, 0.2); pdrgppbucket->Append(pbucketFalse); pdrgppbucket->Append(pbucketTrue); return GPOS_NEW(pmp) CHistogram(pdrgppbucket); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::EresUnittest_CStatisticsBasicsFromDXL // // @doc: // Reads a DXL document, generates the statistics object, performs a // filter operation on it, serializes it into a DXL document and // compares the generated DXL document with the expected DXL document. // //--------------------------------------------------------------------------- GPOS_RESULT CStatisticsTest::EresUnittest_CStatisticsBasicsFromDXL() { // create memory pool CAutoMemoryPool amp; IMemoryPool *pmp = amp.Pmp(); CWStringDynamic str(pmp); COstreamString oss(&str); // read input DXL file CHAR *szDXLInput = CDXLUtils::SzRead(pmp, szInputDXLFileName); // read output DXL file CHAR *szDXLOutput = CDXLUtils::SzRead(pmp, szOutputDXLFileName); GPOS_CHECK_ABORT; CMDAccessor *pmda = COptCtxt::PoctxtFromTLS()->Pmda(); // parse the statistics objects DrgPdxlstatsderrel *pdrgpdxlstatsderrel = CDXLUtils::PdrgpdxlstatsderrelParseDXL(pmp, szDXLInput, NULL); DrgPstats *pdrgpstatsBefore = CDXLUtils::PdrgpstatsTranslateStats ( pmp, pmda, pdrgpdxlstatsderrel ); pdrgpdxlstatsderrel->Release(); GPOS_ASSERT(NULL != pdrgpstatsBefore); GPOS_CHECK_ABORT; // create a filter CStatsPredConj *pstatspred = GPOS_NEW(pmp) CStatsPredConj(CStatisticsTest::Pdrgpstatspred2(pmp)); GPOS_RESULT eres = EresUnittest_CStatisticsCompare ( pmp, pmda, pdrgpstatsBefore, pstatspred, szDXLOutput ); // clean up pdrgpstatsBefore->Release(); pstatspred->Release(); GPOS_DELETE_ARRAY(szDXLInput); GPOS_DELETE_ARRAY(szDXLOutput); return eres; } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::EresUnittest_CStatisticsFilter // // @doc: // Reads a DXL document, generates the statistics object, performs a // filter operation on it, serializes it into a DXL document and // compares the generated DXL document with the expected DXL document. // //--------------------------------------------------------------------------- GPOS_RESULT CStatisticsTest::EresUnittest_CStatisticsFilter() { SStatsFilterSTestCase rgstatstc[] = { {"../data/dxl/statistics/Select-Statistics-Input-Null-Bucket.xml", "../data/dxl/statistics/Select-Statistics-Output-Null-Bucket.xml", PstatspredNullableCols}, {"../data/dxl/statistics/Select-Statistics-Input-Null-Bucket.xml", "../data/dxl/statistics/Select-Statistics-Output-Null-Constant.xml", PstatspredWithNullConstant}, {"../data/dxl/statistics/Select-Statistics-Input-Null-Bucket.xml", "../data/dxl/statistics/Select-Statistics-Output-NotNull-Constant.xml", PstatspredNotNull}, }; const ULONG ulTestCases = GPOS_ARRAY_SIZE(rgstatstc); return EresUnittest_CStatistics(rgstatstc, ulTestCases); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::EresUnittest_CStatisticsFilterDisj // // @doc: // Reads a DXL document, generates the statistics object, performs a // filter operation on it, serializes it into a DXL document and // compares the generated DXL document with the expected DXL document. // //--------------------------------------------------------------------------- GPOS_RESULT CStatisticsTest::EresUnittest_CStatisticsFilterDisj() { SStatsFilterSTestCase rgstatsdisjtc[] = { {"../data/dxl/statistics/Disj-Input-1.xml", "../data/dxl/statistics/Disj-Output-1.xml", PstatspredDisj1}, {"../data/dxl/statistics/Disj-Input-1.xml", "../data/dxl/statistics/Disj-Output-1.xml", PstatspredDisj2}, {"../data/dxl/statistics/Disj-Input-1.xml", "../data/dxl/statistics/Disj-Output-1.xml", PstatspredDisj3}, {"../data/dxl/statistics/Disj-Input-2.xml", "../data/dxl/statistics/Disj-Output-2-1.xml", PstatspredDisj4}, {"../data/dxl/statistics/Disj-Input-2.xml", "../data/dxl/statistics/Disj-Output-2-2.xml", PstatspredDisj5}, {"../data/dxl/statistics/Disj-Input-2.xml", "../data/dxl/statistics/Disj-Output-2-3.xml", PstatspredDisj6}, {"../data/dxl/statistics/Disj-Input-2.xml", "../data/dxl/statistics/Disj-Output-2-4.xml", PstatspredDisj7}, {"../data/dxl/statistics/NestedPred-Input-10.xml", "../data/dxl/statistics/Disj-Output-8.xml", PstatspredDisj8}, }; const ULONG ulTestCases = GPOS_ARRAY_SIZE(rgstatsdisjtc); return EresUnittest_CStatistics(rgstatsdisjtc, ulTestCases); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::EresUnittest_CStatisticsFilterConj // // @doc: // Reads a DXL document, generates the statistics object, performs a // filter operation on it, serializes it into a DXL document and // compares the generated DXL document with the expected DXL document. // //--------------------------------------------------------------------------- GPOS_RESULT CStatisticsTest::EresUnittest_CStatisticsFilterConj() { SStatsFilterSTestCase rgstatsdisjtc[] = { {"../data/dxl/statistics/NestedPred-Input-9.xml", "../data/dxl/statistics/NestedPred-Output-9.xml", PstatspredConj}, }; const ULONG ulTestCases = GPOS_ARRAY_SIZE(rgstatsdisjtc); return EresUnittest_CStatistics(rgstatsdisjtc, ulTestCases); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::EresUnittest_CStatisticsNestedPred // // @doc: // Reads a DXL document, generates the statistics object, performs a // filter operation on it, serializes it into a DXL document and // compares the generated DXL document with the expected DXL document. // //--------------------------------------------------------------------------- GPOS_RESULT CStatisticsTest::EresUnittest_CStatisticsNestedPred() { SStatsFilterSTestCase rgstatsdisjtc[] = { {"../data/dxl/statistics/NestedPred-Input-1.xml", "../data/dxl/statistics/NestedPred-Output-1.xml", PstatspredNestedPredDiffCol1}, {"../data/dxl/statistics/NestedPred-Input-1.xml", "../data/dxl/statistics/NestedPred-Output-1.xml", PstatspredNestedPredDiffCol2}, {"../data/dxl/statistics/NestedPred-Input-2.xml", "../data/dxl/statistics/NestedPred-Output-2.xml", PstatspredNestedPredCommonCol1}, {"../data/dxl/statistics/NestedPred-Input-1.xml", "../data/dxl/statistics/NestedPred-Output-3.xml", PstatspredNestedSharedCol}, {"../data/dxl/statistics/NestedPred-Input-3.xml", "../data/dxl/statistics/NestedPred-Output-4.xml", PstatspredDisjOverConjSameCol1}, {"../data/dxl/statistics/NestedPred-Input-3.xml", "../data/dxl/statistics/NestedPred-Input-3.xml", PstatspredDisjOverConjSameCol2}, {"../data/dxl/statistics/NestedPred-Input-1.xml", "../data/dxl/statistics/NestedPred-Output-5.xml", PstatspredDisjOverConjDifferentCol1}, {"../data/dxl/statistics/NestedPred-Input-1.xml", "../data/dxl/statistics/NestedPred-Output-6.xml", PstatspredDisjOverConjMultipleIdenticalCols}, {"../data/dxl/statistics/NestedPred-Input-2.xml", "../data/dxl/statistics/NestedPred-Output-7.xml", PstatspredNestedPredCommonCol2}, {"../data/dxl/statistics/NestedPred-Input-8.xml", "../data/dxl/statistics/NestedPred-Output-8.xml", PstatspredDisjOverConjSameCol3}, {"../data/dxl/statistics/NestedPred-Input-10.xml", "../data/dxl/statistics/NestedPred-Output-10.xml", PstatspredDisjOverConjSameCol4}, }; const ULONG ulTestCases = GPOS_ARRAY_SIZE(rgstatsdisjtc); return EresUnittest_CStatistics(rgstatsdisjtc, ulTestCases); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::EresUnittest_CStatistics // // @doc: // Reads a DXL document, generates the statistics object, performs a // filter operation on it, serializes it into a DXL document and // compares the generated DXL document with the expected DXL document. // //--------------------------------------------------------------------------- GPOS_RESULT CStatisticsTest::EresUnittest_CStatistics ( SStatsFilterSTestCase rgstatsdisjtc[], ULONG ulTestCases ) { // create memory pool CAutoMemoryPool amp; IMemoryPool *pmp = amp.Pmp(); CWStringDynamic str(pmp); COstreamString oss(&str); CMDAccessor *pmda = COptCtxt::PoctxtFromTLS()->Pmda(); for (ULONG ul = 0; ul < ulTestCases; ul++) { SStatsFilterSTestCase elem = rgstatsdisjtc[ul]; // read input/output DXL file CHAR *szDXLInput = CDXLUtils::SzRead(pmp, elem.m_szInputFile); CHAR *szDXLOutput = CDXLUtils::SzRead(pmp, elem.m_szOutputFile); GPOS_CHECK_ABORT; // parse the statistics objects DrgPdxlstatsderrel *pdrgpdxlstatsderrel = CDXLUtils::PdrgpdxlstatsderrelParseDXL(pmp, szDXLInput, NULL); DrgPstats *pdrgpstatBefore = CDXLUtils::PdrgpstatsTranslateStats(pmp, pmda, pdrgpdxlstatsderrel); pdrgpdxlstatsderrel->Release(); GPOS_ASSERT(NULL != pdrgpstatBefore); GPOS_CHECK_ABORT; // generate the disjunctive predicate FnPstatspredDisj *pf = elem.m_pf; GPOS_ASSERT(NULL != pf); CStatsPred *pstatspredDisj = pf(pmp); GPOS_RESULT eres = EresUnittest_CStatisticsCompare ( pmp, pmda, pdrgpstatBefore, pstatspredDisj, szDXLOutput ); // clean up pdrgpstatBefore->Release(); pstatspredDisj->Release(); GPOS_DELETE_ARRAY(szDXLInput); GPOS_DELETE_ARRAY(szDXLOutput); if (GPOS_FAILED == eres) { return eres; } } return GPOS_OK; } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::EresUnittest_CStatisticsBasicsFromDXLNumeric // // @doc: // Reads a DXL document, generates the statistics object, performs a // filter operation on it, serializes it into a DXL document and // compares the generated DXL document with the expected DXL document. // //--------------------------------------------------------------------------- GPOS_RESULT CStatisticsTest::EresUnittest_CStatisticsBasicsFromDXLNumeric() { // create memory pool CAutoMemoryPool amp; IMemoryPool *pmp = amp.Pmp(); SStatsCmpValElem rgStatsCmpValElem[] = { {CStatsPred::EstatscmptL, GPOS_WSZ_LIT("AAAACgAAAgABAA=="), CDouble(1.0)}, {CStatsPred::EstatscmptLEq, GPOS_WSZ_LIT("AAAACgAAAgABAA=="), CDouble(1.0)}, {CStatsPred::EstatscmptEq, GPOS_WSZ_LIT("AAAACgAAAgABAA=="), CDouble(1.0)}, {CStatsPred::EstatscmptG, GPOS_WSZ_LIT("AAAACgAAAgAyAA=="), CDouble(50.0)}, {CStatsPred::EstatscmptGEq, GPOS_WSZ_LIT("AAAACgAAAgAyAA=="), CDouble(50.0)}, {CStatsPred::EstatscmptEq, GPOS_WSZ_LIT("AAAACgAAAgAyAA=="), CDouble(50.0)}, {CStatsPred::EstatscmptL, GPOS_WSZ_LIT("AAAACgAAAgABAA=="), CDouble(1.0)}, {CStatsPred::EstatscmptLEq, GPOS_WSZ_LIT("AAAACgAAAgABAA=="), CDouble(1.0)}, {CStatsPred::EstatscmptEq, GPOS_WSZ_LIT("AAAACgAAAgABAA=="), CDouble(1.0)}, {CStatsPred::EstatscmptG, GPOS_WSZ_LIT("AAAACgAAAgABAA=="), CDouble(1.0)}, {CStatsPred::EstatscmptGEq, GPOS_WSZ_LIT("AAAACgAAAgABAA=="), CDouble(1.0)}, {CStatsPred::EstatscmptL, GPOS_WSZ_LIT("AAAACgAAAgAyAA=="), CDouble(50.0)}, {CStatsPred::EstatscmptLEq, GPOS_WSZ_LIT("AAAACgAAAgAyAA=="), CDouble(50.0)}, {CStatsPred::EstatscmptG, GPOS_WSZ_LIT("AAAACgAAAgAyAA=="), CDouble(50.0)}, {CStatsPred::EstatscmptGEq, GPOS_WSZ_LIT("AAAACgAAAgAyAA=="), CDouble(50.0)}, {CStatsPred::EstatscmptEq, GPOS_WSZ_LIT("AAAACgAAAgAyAA=="), CDouble(50.0)}, }; const ULONG ulLen = GPOS_ARRAY_SIZE(rgStatsCmpValElem); GPOS_ASSERT(ulLen == GPOS_ARRAY_SIZE(rgtcStatistics)); for (ULONG ul = 0; ul < ulLen; ul++) { // read input DXL file CHAR *szDXLInput = CDXLUtils::SzRead(pmp, rgtcStatistics[ul].szInputFile); // read output DXL file CHAR *szDXLOutput = CDXLUtils::SzRead(pmp, rgtcStatistics[ul].szOutputFile); GPOS_CHECK_ABORT; CMDAccessor *pmda = COptCtxt::PoctxtFromTLS()->Pmda(); // parse the statistics objects DrgPdxlstatsderrel *pdrgpdxlstatsderrel = CDXLUtils::PdrgpdxlstatsderrelParseDXL(pmp, szDXLInput, NULL); DrgPstats *pdrgpstatBefore = CDXLUtils::PdrgpstatsTranslateStats(pmp, pmda, pdrgpdxlstatsderrel); pdrgpdxlstatsderrel->Release(); GPOS_ASSERT(NULL != pdrgpstatBefore); GPOS_CHECK_ABORT; SStatsCmpValElem statsCmpValElem = rgStatsCmpValElem[ul]; DrgPstatspred *pdrgpstatspred = PdrgppredfilterNumeric(pmp, 1 /*ulColId*/, statsCmpValElem); CStatsPredConj *pstatspred = GPOS_NEW(pmp) CStatsPredConj(pdrgpstatspred); GPOS_RESULT eres = EresUnittest_CStatisticsCompare ( pmp, pmda, pdrgpstatBefore, pstatspred, szDXLOutput, true /*fApplyTwice*/ ); // clean up pdrgpstatBefore->Release(); pstatspred->Release(); GPOS_DELETE_ARRAY(szDXLInput); GPOS_DELETE_ARRAY(szDXLOutput); if (GPOS_OK != eres) { return eres; } } return GPOS_OK; } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::PdrgpstatspredNumeric // // @doc: // Generate a numeric filter on the column specified and the literal value // //--------------------------------------------------------------------------- DrgPstatspred * CStatisticsTest::PdrgppredfilterNumeric ( IMemoryPool *pmp, ULONG ulColId, SStatsCmpValElem statsCmpValElem ) { // create a filter DrgPstatspred *pdrgpstatspred = GPOS_NEW(pmp) DrgPstatspred(pmp); CWStringDynamic *pstrNumeric = GPOS_NEW(pmp) CWStringDynamic(pmp, statsCmpValElem.m_wsz); CStatsPredPoint *pstatspred = GPOS_NEW(pmp) CStatsPredPoint ( ulColId, statsCmpValElem.m_escmpt, PpointNumeric(pmp, pstrNumeric, statsCmpValElem.m_dVal) ); pdrgpstatspred->Append(pstatspred); GPOS_DELETE(pstrNumeric); return pdrgpstatspred; } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::EresUnittest_CStatisticsCompare // // @doc: // Performs a filter operation on it, serializes it into a DXL document // and compares the generated DXL document with the expected DXL document // //--------------------------------------------------------------------------- GPOS_RESULT CStatisticsTest::EresUnittest_CStatisticsCompare ( IMemoryPool *pmp, CMDAccessor *pmda, DrgPstats *pdrgpstatBefore, CStatsPred *pstatspred, const CHAR *szDXLOutput, BOOL fApplyTwice ) { CWStringDynamic str(pmp); COstreamString oss(&str); CStatistics *pstatsInput = (* pdrgpstatBefore)[0]; CDouble dRowsInput = pstatsInput->DRows(); GPOS_TRACE(GPOS_WSZ_LIT("Statistics before")); CStatisticsTest::Print(pmp, pstatsInput); CStatistics *pstatsOutput = pstatsInput->PstatsFilter(pmp, pstatspred, true /* fCapNdvs */); GPOS_TRACE(GPOS_WSZ_LIT("Statistics after")); CStatisticsTest::Print(pmp, pstatsOutput); // output array of stats objects DrgPstats *pdrgpstatOutput = GPOS_NEW(pmp) DrgPstats(pmp); pdrgpstatOutput->Append(pstatsOutput); oss << "Serializing Input Statistics Objects (Before Filter)" << std::endl; CWStringDynamic *pstrInput = CDXLUtils::PstrSerializeStatistics ( pmp, pmda, pdrgpstatBefore, true /*fSerializeHeaderFooter*/, true /*fIndent*/ ); GPOS_TRACE(pstrInput->Wsz()); GPOS_DELETE(pstrInput); oss << "Serializing Output Statistics Objects (After Filter)" << std::endl; CWStringDynamic *pstrOutput = CDXLUtils::PstrSerializeStatistics ( pmp, pmda, pdrgpstatOutput, true /*fSerializeHeaderFooter*/, true /*fIndent*/ ); GPOS_TRACE(pstrOutput->Wsz()); CWStringDynamic dstrExpected(pmp); dstrExpected.AppendFormat(GPOS_WSZ_LIT("%s"), szDXLOutput); GPOS_RESULT eres = CTestUtils::EresCompare ( oss, pstrOutput, &dstrExpected, false /* ignore mismatch */ ); if (fApplyTwice && GPOS_OK == eres) { CStatistics *pstatsOutput2 = pstatsOutput->PstatsFilter(pmp, pstatspred, true /* fCapNdvs */); pstatsOutput2->DRows(); GPOS_TRACE(GPOS_WSZ_LIT("Statistics after another filter")); CStatisticsTest::Print(pmp, pstatsOutput2); // output array of stats objects DrgPstats *pdrgpstatOutput2 = GPOS_NEW(pmp) DrgPstats(pmp); pdrgpstatOutput2->Append(pstatsOutput2); CWStringDynamic *pstrOutput2 = CDXLUtils::PstrSerializeStatistics ( pmp, pmda, pdrgpstatOutput2, true /*fSerializeHeaderFooter*/, true /*fIndent*/ ); eres = CTestUtils::EresCompare ( oss, pstrOutput2, &dstrExpected, false /* ignore mismatch */ ); pdrgpstatOutput2->Release(); GPOS_DELETE(pstrOutput2); } pdrgpstatOutput->Release(); GPOS_DELETE(pstrOutput); return eres; } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::PtabdescTwoColumnSource // // @doc: // Create a table descriptor with two columns having the given names. // //--------------------------------------------------------------------------- CTableDescriptor * CStatisticsTest::PtabdescTwoColumnSource ( IMemoryPool *pmp, const CName &nameTable, const IMDTypeInt4 *pmdtype, const CWStringConst &strColA, const CWStringConst &strColB ) { CTableDescriptor *ptabdesc = GPOS_NEW(pmp) CTableDescriptor ( pmp, GPOS_NEW(pmp) CMDIdGPDB(GPOPT_TEST_REL_OID1, 1, 1), nameTable, false, // fConvertHashToRandom IMDRelation::EreldistrRandom, IMDRelation::ErelstorageHeap, 0 // ulExecuteAsUser ); for (ULONG ul = 0; ul < 2; ul++) { // create a shallow constant string to embed in a name const CWStringConst *pstrName = &strColA; if (0 < ul) { pstrName = &strColB; } CName nameColumn(pstrName); CColumnDescriptor *pcoldesc = GPOS_NEW(pmp) CColumnDescriptor ( pmp, pmdtype, nameColumn, ul + 1, false /*fNullable*/ ); ptabdesc->AddColumn(pcoldesc); } return ptabdesc; } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::EresUnittest_CStatisticsBasic // // @doc: // Basic statistics test // //--------------------------------------------------------------------------- GPOS_RESULT CStatisticsTest::EresUnittest_CStatisticsBasic() { // create memory pool CAutoMemoryPool amp; IMemoryPool *pmp = amp.Pmp(); CColumnFactory *pcf = COptCtxt::PoctxtFromTLS()->Pcf(); const IMDTypeInt4 *pmdtypeint4 = COptCtxt::PoctxtFromTLS()->Pmda()->PtMDType<IMDTypeInt4>(); CWStringConst strRelAlias(GPOS_WSZ_LIT("Rel1")); CWStringConst strColA(GPOS_WSZ_LIT("a")); CWStringConst strColB(GPOS_WSZ_LIT("b")); CTableDescriptor *ptabdesc = PtabdescTwoColumnSource(pmp, CName(&strRelAlias), pmdtypeint4, strColA, strColB); CExpression *pexprGet = CTestUtils::PexprLogicalGet(pmp, ptabdesc, &strRelAlias); if (NULL == pcf->PcrLookup(1 /*ulId*/)) { // create column references for grouping columns (void) pcf->PcrCreate ( pmdtypeint4, 0 /* iAttno */, false /*FNullable*/, 1 /* ulId */, CName(&strColA), pexprGet->Pop()->UlOpId() ); } if (NULL == pcf->PcrLookup(2 /*ulId*/)) { (void) pcf->PcrCreate ( pmdtypeint4, 1 /* iAttno */, false /*FNullable*/, 2 /* ulId */, CName(&strColB), pexprGet->Pop()->UlOpId() ); } // create hash map from colid -> histogram HMUlHist *phmulhist = GPOS_NEW(pmp) HMUlHist(pmp); // generate bool histogram for column 1 phmulhist->FInsert(GPOS_NEW(pmp) ULONG(1), PhistExampleBool(pmp)); // generate int histogram for column 2 phmulhist->FInsert(GPOS_NEW(pmp) ULONG(2), PhistExampleInt4(pmp)); // array capturing columns for which width information is available HMUlDouble *phmuldoubleWidth = GPOS_NEW(pmp) HMUlDouble(pmp); // width for boolean phmuldoubleWidth->FInsert(GPOS_NEW(pmp) ULONG(1), GPOS_NEW(pmp) CDouble(1.0)); // width for int phmuldoubleWidth->FInsert(GPOS_NEW(pmp) ULONG(2), GPOS_NEW(pmp) CDouble(4.0)); CStatistics *pstats = GPOS_NEW(pmp) CStatistics(pmp, phmulhist, phmuldoubleWidth, 1000.0 /* dRows */, false /* fEmpty */); pstats->DRows(); GPOS_TRACE(GPOS_WSZ_LIT("pstats")); // before stats Print(pmp, pstats); // create a filter: column 1: [25,45), column 2: [true, true) DrgPstatspred *pdrgpstatspred = Pdrgpstatspred1(pmp); CStatsPredConj *pstatspred = GPOS_NEW(pmp) CStatsPredConj(pdrgpstatspred); CStatistics *pstats1 = pstats->PstatsFilter(pmp, pstatspred, true /* fCapNdvs */); pstats1->DRows(); GPOS_TRACE(GPOS_WSZ_LIT("pstats1 after filter")); // after stats Print(pmp, pstats1); // create another statistics structure with a single int4 column with id 10 HMUlHist *phmulhist2 = GPOS_NEW(pmp) HMUlHist(pmp); phmulhist2->FInsert(GPOS_NEW(pmp) ULONG(10), PhistExampleInt4Dim(pmp)); HMUlDouble *phmuldoubleWidth2 = GPOS_NEW(pmp) HMUlDouble(pmp); phmuldoubleWidth2->FInsert(GPOS_NEW(pmp) ULONG(10), GPOS_NEW(pmp) CDouble(4.0)); CStatistics *pstats2 = GPOS_NEW(pmp) CStatistics(pmp, phmulhist2, phmuldoubleWidth2, 100.0 /* dRows */, false /* fEmpty */); GPOS_TRACE(GPOS_WSZ_LIT("pstats2")); Print(pmp, pstats2); // join pstats with pstats2 CStatisticsJoin *pstatsjoin = GPOS_NEW(pmp) CStatisticsJoin(2, CStatsPred::EstatscmptEq, 10); DrgPstatsjoin *pdrgpstatsjoin = GPOS_NEW(pmp) DrgPstatsjoin(pmp); pdrgpstatsjoin->Append(pstatsjoin); CStatistics *pstats3 = pstats->PstatsInnerJoin(pmp, pstats2, pdrgpstatsjoin); GPOS_TRACE(GPOS_WSZ_LIT("pstats3 = pstats JOIN pstats2 on (col2 = col10)")); // after stats Print(pmp, pstats3); // group by pstats on columns 1 and 2 DrgPul *pdrgpulGC = GPOS_NEW(pmp) DrgPul(pmp); pdrgpulGC->Append(GPOS_NEW(pmp) ULONG(1)); pdrgpulGC->Append(GPOS_NEW(pmp) ULONG(2)); DrgPul *pdrgpulAgg = GPOS_NEW(pmp) DrgPul(pmp); CStatistics *pstats4 = pstats->PstatsGroupBy(pmp, pdrgpulGC, pdrgpulAgg, NULL /*pbsKeys*/); GPOS_TRACE(GPOS_WSZ_LIT("pstats4 = pstats group by")); Print(pmp, pstats4); // LASJ stats CStatistics *pstats5 = pstats->PstatsLASJoin(pmp, pstats2, pdrgpstatsjoin, true /* fIgnoreLasjHistComputation */); GPOS_TRACE(GPOS_WSZ_LIT("pstats5 = pstats LASJ pstats2 on (col2 = col10)")); Print(pmp, pstats5); // union all DrgPul *pdrgpulColIds = GPOS_NEW(pmp) DrgPul(pmp); pdrgpulColIds->Append(GPOS_NEW(pmp) ULONG(1)); pdrgpulColIds->Append(GPOS_NEW(pmp) ULONG(2)); pdrgpulColIds->AddRef(); pdrgpulColIds->AddRef(); pdrgpulColIds->AddRef(); CStatistics *pstats6 = pstats->PstatsUnionAll(pmp, pstats, pdrgpulColIds, pdrgpulColIds, pdrgpulColIds); GPOS_TRACE(GPOS_WSZ_LIT("pstats6 = pstats1 union all pstats1")); Print(pmp, pstats6); CStatistics *pstats7 = pstats->PstatsLimit(pmp, CDouble(4.0)); GPOS_TRACE(GPOS_WSZ_LIT("pstats7 = pstats limit 4")); Print(pmp, pstats7); pstats->Release(); pstats1->Release(); pstats2->Release(); pstats3->Release(); pstats4->Release(); pstats5->Release(); pstats6->Release(); pstats7->Release(); pstatspred->Release(); pdrgpstatsjoin->Release(); pdrgpulGC->Release(); pdrgpulAgg->Release(); pdrgpulColIds->Release(); pexprGet->Release(); return GPOS_OK; } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::PdrgpstatspredInteger // // @doc: // Generate an array of filter given a column identifier, comparison type, // and array of integer point //--------------------------------------------------------------------------- DrgPstatspred * CStatisticsTest::PdrgpstatspredInteger ( IMemoryPool *pmp, ULONG ulColId, CStatsPred::EStatsCmpType escmpt, INT *piVals, ULONG ulVals ) { GPOS_ASSERT(0 < ulVals); DrgPstatspred *pdrgpstatspred = GPOS_NEW(pmp) DrgPstatspred(pmp); for (ULONG ul = 0; ul < ulVals; ul++) { pdrgpstatspred->Append(GPOS_NEW(pmp) CStatsPredPoint(ulColId, escmpt, CTestUtils::PpointInt4(pmp, piVals[ul]))); } return pdrgpstatspred; } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::PstatspredNestedPredDiffCol1 // // @doc: // Create nested AND and OR predicates where the AND and OR predicates // are on different columns //--------------------------------------------------------------------------- CStatsPred * CStatisticsTest::PstatspredNestedPredDiffCol1 ( IMemoryPool *pmp ) { DrgPstatspred *pdrgpstatspredConj = GPOS_NEW(pmp) DrgPstatspred(pmp); // predicate col_1 <> 3 pdrgpstatspredConj->Append(GPOS_NEW(pmp) CStatsPredPoint(1, CStatsPred::EstatscmptNEq, CTestUtils::PpointInt4(pmp, 3))); // predicate col_2 in (15, 20, 22, 24, 31, 39, 42, 46); INT rgiVal[] = {15, 20, 22, 24, 31, 39, 42, 46}; const ULONG ulVals = GPOS_ARRAY_SIZE(rgiVal); DrgPstatspred *pdrgpstatspredDisj = PdrgpstatspredInteger(pmp, 2, CStatsPred::EstatscmptEq, rgiVal, ulVals); CStatsPredDisj *pstatspredDisj = GPOS_NEW(pmp) CStatsPredDisj(pdrgpstatspredDisj); pdrgpstatspredConj->Append(pstatspredDisj); return GPOS_NEW(pmp) CStatsPredConj(pdrgpstatspredConj); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::PstatspredNestedPredDiffCol2 // // @doc: // Create nested AND and OR predicates where the AND and OR predicates // are on different columns. note: the order of the predicates in // reversed as in PstatspredNestedPredDiffCol1 //--------------------------------------------------------------------------- CStatsPred * CStatisticsTest::PstatspredNestedPredDiffCol2 ( IMemoryPool *pmp ) { DrgPstatspred *pdrgpstatspredConj = GPOS_NEW(pmp) DrgPstatspred(pmp); // predicate col_2 in (15, 20, 22, 24, 31, 39, 42, 46); INT rgiVal[] = {15, 20, 22, 24, 31, 39, 42, 46}; const ULONG ulVals = GPOS_ARRAY_SIZE(rgiVal); DrgPstatspred *pdrgpstatspredDisj = PdrgpstatspredInteger(pmp, 2, CStatsPred::EstatscmptEq, rgiVal, ulVals); CStatsPredDisj *pstatspredDisj = GPOS_NEW(pmp) CStatsPredDisj(pdrgpstatspredDisj); pdrgpstatspredConj->Append(pstatspredDisj); // predicate col_1 <> 3 pdrgpstatspredConj->Append(GPOS_NEW(pmp) CStatsPredPoint(1, CStatsPred::EstatscmptNEq, CTestUtils::PpointInt4(pmp, 3))); return GPOS_NEW(pmp) CStatsPredConj(pdrgpstatspredConj); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::PstatspredNestedPredCommonCol1 // // @doc: // Create nested AND and OR predicates where the AND and OR predicates // are on the same columns //--------------------------------------------------------------------------- CStatsPred * CStatisticsTest::PstatspredNestedPredCommonCol1 ( IMemoryPool *pmp ) { // predicate is col_2 in (39, 31, 24, 22, 46, 20, 42, 15) AND col_2 == 2 DrgPstatspred *pdrgpstatspredConj = GPOS_NEW(pmp) DrgPstatspred(pmp); // predicate col_2 in (15, 20, 22, 24, 31, 39, 42, 46); INT rgiVal[] = {15, 20, 22, 24, 31, 39, 42, 46}; const ULONG ulVals = GPOS_ARRAY_SIZE(rgiVal); DrgPstatspred *pdrgpstatspredDisj = PdrgpstatspredInteger(pmp, 2, CStatsPred::EstatscmptEq, rgiVal, ulVals); CStatsPredDisj *pstatspredDisj = GPOS_NEW(pmp) CStatsPredDisj(pdrgpstatspredDisj); pdrgpstatspredConj->Append(pstatspredDisj); // predicate col_2 == 2 pdrgpstatspredConj->Append(GPOS_NEW(pmp) CStatsPredPoint(2, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(pmp, 2))); return GPOS_NEW(pmp) CStatsPredConj(pdrgpstatspredConj); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::PstatspredNestedPredCommonCol2 // // @doc: // Create nested AND and OR predicates where the AND and OR predicates // are on the same columns //--------------------------------------------------------------------------- CStatsPred * CStatisticsTest::PstatspredNestedPredCommonCol2 ( IMemoryPool *pmp ) { // predicate is col_2 in (2, 39, 31, 24, 22, 46, 20, 42, 15) AND col_2 == 2 DrgPstatspred *pdrgpstatspredConj = GPOS_NEW(pmp) DrgPstatspred(pmp); // IN predicate: col_2 in (2, 39, 31, 24, 22, 46, 20, 42, 15); INT rgiVal[] = {2, 15, 20, 22, 24, 31, 39, 42, 46}; const ULONG ulVals = GPOS_ARRAY_SIZE(rgiVal); DrgPstatspred *pdrgpstatspredDisj = PdrgpstatspredInteger(pmp, 2, CStatsPred::EstatscmptEq, rgiVal, ulVals); CStatsPredDisj *pstatspredDisj = GPOS_NEW(pmp) CStatsPredDisj(pdrgpstatspredDisj); pdrgpstatspredConj->Append(pstatspredDisj); // predicate col_2 == 2 pdrgpstatspredConj->Append(GPOS_NEW(pmp) CStatsPredPoint(2, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(pmp, 2))); return GPOS_NEW(pmp) CStatsPredConj(pdrgpstatspredConj); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::PstatspredNestedSharedCol // // @doc: // Create nested AND and OR predicates where the AND and OR predicates // share common columns //--------------------------------------------------------------------------- CStatsPred * CStatisticsTest::PstatspredNestedSharedCol ( IMemoryPool *pmp ) { DrgPstatspred *pdrgpstatspredConj = GPOS_NEW(pmp) DrgPstatspred(pmp); // predicate col_1 <> 3 pdrgpstatspredConj->Append(GPOS_NEW(pmp) CStatsPredPoint(1, CStatsPred::EstatscmptNEq, CTestUtils::PpointInt4(pmp, 3))); // predicate col_2 in (15, 20, 22, 24, 31, 39, 42, 46) OR (col_1 == 4)); INT rgiVal[] = {15, 20, 22, 24, 31, 39, 42, 46}; const ULONG ulVals = GPOS_ARRAY_SIZE(rgiVal); DrgPstatspred *pdrgpstatspredDisj = PdrgpstatspredInteger(pmp, 2, CStatsPred::EstatscmptEq, rgiVal, ulVals); pdrgpstatspredDisj->Append(GPOS_NEW(pmp) CStatsPredPoint(1, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(pmp, 4))); CStatsPredDisj *pstatspredDisj = GPOS_NEW(pmp) CStatsPredDisj(pdrgpstatspredDisj); pdrgpstatspredConj->Append(pstatspredDisj); return GPOS_NEW(pmp) CStatsPredConj(pdrgpstatspredConj); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::PstatspredDisjOverConjSameCol1 // // @doc: // Create nested AND and OR predicates where the AND and OR predicates // share common columns //--------------------------------------------------------------------------- CStatsPred * CStatisticsTest::PstatspredDisjOverConjSameCol1 ( IMemoryPool *pmp ) { DrgPstatspred *pdrgpstatspredConj = GPOS_NEW(pmp) DrgPstatspred(pmp); // predicate col_1 = 3 AND col_1 >=3 pdrgpstatspredConj->Append(GPOS_NEW(pmp) CStatsPredPoint(1, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(pmp, 3))); pdrgpstatspredConj->Append(GPOS_NEW(pmp) CStatsPredPoint(1, CStatsPred::EstatscmptGEq, CTestUtils::PpointInt4(pmp, 3))); CStatsPredConj *pstatspredConj = GPOS_NEW(pmp) CStatsPredConj(pdrgpstatspredConj); // predicate (col_1 = 1); DrgPstatspred *pdrgpstatspredDisj = GPOS_NEW(pmp) DrgPstatspred(pmp); pdrgpstatspredDisj->Append(GPOS_NEW(pmp) CStatsPredPoint(1, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(pmp, 1))); pdrgpstatspredDisj->Append(pstatspredConj); return GPOS_NEW(pmp) CStatsPredDisj(pdrgpstatspredDisj); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::PstatspredDisjOverConjSameCol2 // // @doc: // Create nested AND and OR predicates where the AND and OR predicates // share common columns //--------------------------------------------------------------------------- CStatsPred * CStatisticsTest::PstatspredDisjOverConjSameCol2 ( IMemoryPool *pmp ) { DrgPstatspred *pdrgpstatspredConj = GPOS_NEW(pmp) DrgPstatspred(pmp); // predicate col_1 <= 5 AND col_1 >=1 pdrgpstatspredConj->Append(GPOS_NEW(pmp) CStatsPredPoint(1, CStatsPred::EstatscmptLEq, CTestUtils::PpointInt4(pmp, 5))); pdrgpstatspredConj->Append(GPOS_NEW(pmp) CStatsPredPoint(1, CStatsPred::EstatscmptGEq, CTestUtils::PpointInt4(pmp, 1))); CStatsPredConj *pstatspredConj = GPOS_NEW(pmp) CStatsPredConj(pdrgpstatspredConj); // predicate (col_1 = 1); DrgPstatspred *pdrgpstatspredDisj = GPOS_NEW(pmp) DrgPstatspred(pmp); pdrgpstatspredDisj->Append(GPOS_NEW(pmp) CStatsPredPoint(1, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(pmp, 1))); pdrgpstatspredDisj->Append(pstatspredConj); return GPOS_NEW(pmp) CStatsPredDisj(pdrgpstatspredDisj); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::PstatspredDisjOverConjSameCol3 // // @doc: // Create disjunctive predicate over conjunctions on same columns //--------------------------------------------------------------------------- CStatsPred * CStatisticsTest::PstatspredDisjOverConjSameCol3 ( IMemoryPool *pmp ) { DrgPstatspred *pdrgpstatspredDisj = GPOS_NEW(pmp) DrgPstatspred(pmp); CWStringDynamic *pstrS = GPOS_NEW(pmp) CWStringDynamic(pmp, GPOS_WSZ_LIT("AAAABXM=")); CWStringDynamic *pstrW = GPOS_NEW(pmp) CWStringDynamic(pmp, GPOS_WSZ_LIT("AAAABXc=")); // predicate is a == 's' AND b == 2001 DrgPstatspred *pdrgpstatspredConj1 = GPOS_NEW(pmp) DrgPstatspred(pmp); pdrgpstatspredConj1->Append(GPOS_NEW(pmp) CStatsPredPoint(142, CStatsPred::EstatscmptEq, PpointGeneric(pmp, GPDB_TEXT, pstrS, 160588332))); pdrgpstatspredConj1->Append(GPOS_NEW(pmp) CStatsPredPoint(113, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(pmp, 2001))); pdrgpstatspredDisj->Append(GPOS_NEW(pmp) CStatsPredConj(pdrgpstatspredConj1)); // predicate is a == 's' AND b == 2002 DrgPstatspred *pdrgpstatspredConj2 = GPOS_NEW(pmp) DrgPstatspred(pmp); pdrgpstatspredConj2->Append(GPOS_NEW(pmp) CStatsPredPoint(142, CStatsPred::EstatscmptEq, PpointGeneric(pmp, GPDB_TEXT, pstrS, 160588332))); pdrgpstatspredConj2->Append(GPOS_NEW(pmp) CStatsPredPoint(113, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(pmp, 2002))); pdrgpstatspredDisj->Append(GPOS_NEW(pmp) CStatsPredConj(pdrgpstatspredConj2)); // predicate is a == 'w' AND b == 2001 DrgPstatspred *pdrgpstatspredConj3 = GPOS_NEW(pmp) DrgPstatspred(pmp); pdrgpstatspredConj3->Append(GPOS_NEW(pmp) CStatsPredPoint(142, CStatsPred::EstatscmptEq, PpointGeneric(pmp, GPDB_TEXT, pstrW, 160621100))); pdrgpstatspredConj3->Append(GPOS_NEW(pmp) CStatsPredPoint(113, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(pmp, 2001))); pdrgpstatspredDisj->Append(GPOS_NEW(pmp) CStatsPredConj(pdrgpstatspredConj3)); // predicate is a == 'w' AND b == 2002 DrgPstatspred *pdrgpstatspredConj4 = GPOS_NEW(pmp) DrgPstatspred(pmp); pdrgpstatspredConj4->Append(GPOS_NEW(pmp) CStatsPredPoint(142, CStatsPred::EstatscmptEq, PpointGeneric(pmp, GPDB_TEXT, pstrW, 160621100))); pdrgpstatspredConj4->Append(GPOS_NEW(pmp) CStatsPredPoint(113, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(pmp, 2002))); pdrgpstatspredDisj->Append(GPOS_NEW(pmp) CStatsPredConj(pdrgpstatspredConj4)); GPOS_DELETE(pstrS); GPOS_DELETE(pstrW); return GPOS_NEW(pmp) CStatsPredDisj(pdrgpstatspredDisj); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::PstatspredDisjOverConjSameCol4 // // @doc: // Create disjunctive predicate over conjunctions on same columns //--------------------------------------------------------------------------- CStatsPred * CStatisticsTest::PstatspredDisjOverConjSameCol4 ( IMemoryPool *pmp ) { DrgPstatspred *pdrgpstatspredDisj = GPOS_NEW(pmp) DrgPstatspred(pmp); CWStringDynamic *pstrS = GPOS_NEW(pmp) CWStringDynamic(pmp, GPOS_WSZ_LIT("AAAABXM=")); CWStringDynamic *pstrW = GPOS_NEW(pmp) CWStringDynamic(pmp, GPOS_WSZ_LIT("AAAABXc=")); // predicate is a == 's' AND b == 2001 AND c > 0 DrgPstatspred *pdrgpstatspredConj1 = GPOS_NEW(pmp) DrgPstatspred(pmp); pdrgpstatspredConj1->Append(GPOS_NEW(pmp) CStatsPredPoint(91, CStatsPred::EstatscmptEq, PpointGeneric(pmp, GPDB_TEXT, pstrS, 160588332))); pdrgpstatspredConj1->Append(GPOS_NEW(pmp) CStatsPredPoint(61, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(pmp, 2001))); pdrgpstatspredConj1->Append(GPOS_NEW(pmp) CStatsPredPoint(90, CStatsPred::EstatscmptG, CTestUtils::PpointInt4(pmp, 0))); pdrgpstatspredDisj->Append(GPOS_NEW(pmp) CStatsPredConj(pdrgpstatspredConj1)); // predicate is a == 's' AND b == 2002 DrgPstatspred *pdrgpstatspredConj2 = GPOS_NEW(pmp) DrgPstatspred(pmp); pdrgpstatspredConj2->Append(GPOS_NEW(pmp) CStatsPredPoint(91, CStatsPred::EstatscmptEq, PpointGeneric(pmp, GPDB_TEXT, pstrS, 160588332))); pdrgpstatspredConj2->Append(GPOS_NEW(pmp) CStatsPredPoint(61, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(pmp, 2002))); pdrgpstatspredDisj->Append(GPOS_NEW(pmp) CStatsPredConj(pdrgpstatspredConj2)); // predicate is a == 'w' AND b == 2001 AND c > 0 DrgPstatspred *pdrgpstatspredConj3 = GPOS_NEW(pmp) DrgPstatspred(pmp); pdrgpstatspredConj3->Append(GPOS_NEW(pmp) CStatsPredPoint(91, CStatsPred::EstatscmptEq, PpointGeneric(pmp, GPDB_TEXT, pstrW, 160621100))); pdrgpstatspredConj3->Append(GPOS_NEW(pmp) CStatsPredPoint(61, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(pmp, 2001))); pdrgpstatspredConj1->Append(GPOS_NEW(pmp) CStatsPredPoint(90, CStatsPred::EstatscmptG, CTestUtils::PpointInt4(pmp, 0))); pdrgpstatspredDisj->Append(GPOS_NEW(pmp) CStatsPredConj(pdrgpstatspredConj3)); // predicate is a == 'w' AND b == 2002 DrgPstatspred *pdrgpstatspredConj4 = GPOS_NEW(pmp) DrgPstatspred(pmp); pdrgpstatspredConj4->Append(GPOS_NEW(pmp) CStatsPredPoint(91, CStatsPred::EstatscmptEq, PpointGeneric(pmp, GPDB_TEXT, pstrW, 160621100))); pdrgpstatspredConj4->Append(GPOS_NEW(pmp) CStatsPredPoint(61, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(pmp, 2002))); pdrgpstatspredDisj->Append(GPOS_NEW(pmp) CStatsPredConj(pdrgpstatspredConj4)); GPOS_DELETE(pstrS); GPOS_DELETE(pstrW); return GPOS_NEW(pmp) CStatsPredDisj(pdrgpstatspredDisj); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::PstatspredConj // // @doc: // Create conjunctive predicate //--------------------------------------------------------------------------- CStatsPred * CStatisticsTest::PstatspredConj ( IMemoryPool *pmp ) { CWStringDynamic *pstrW = GPOS_NEW(pmp) CWStringDynamic(pmp, GPOS_WSZ_LIT("AAAABXc=")); // predicate is a == 'w' AND b == 2001 AND c > 0 DrgPstatspred *pdrgpstatspredConj3 = GPOS_NEW(pmp) DrgPstatspred(pmp); pdrgpstatspredConj3->Append(GPOS_NEW(pmp) CStatsPredPoint(594, CStatsPred::EstatscmptEq, PpointGeneric(pmp, GPDB_TEXT, pstrW, 160621100))); pdrgpstatspredConj3->Append(GPOS_NEW(pmp) CStatsPredPoint(592, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(pmp, 2001))); pdrgpstatspredConj3->Append(GPOS_NEW(pmp) CStatsPredPoint(593, CStatsPred::EstatscmptG, CTestUtils::PpointInt4(pmp, 0))); GPOS_DELETE(pstrW); return GPOS_NEW(pmp) CStatsPredConj(pdrgpstatspredConj3); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::PstatspredDisjOverConjDifferentCol1 // // @doc: // Create nested AND and OR predicates where the AND and OR predicates // share common columns //--------------------------------------------------------------------------- CStatsPred * CStatisticsTest::PstatspredDisjOverConjDifferentCol1 ( IMemoryPool *pmp ) { DrgPstatspred *pdrgpstatspredConj = GPOS_NEW(pmp) DrgPstatspred(pmp); // predicate col_1 = 3 AND col_2 >=3 pdrgpstatspredConj->Append(GPOS_NEW(pmp) CStatsPredPoint(1, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(pmp, 3))); pdrgpstatspredConj->Append(GPOS_NEW(pmp) CStatsPredPoint(2, CStatsPred::EstatscmptGEq, CTestUtils::PpointInt4(pmp, 3))); CStatsPredConj *pstatspredConj = GPOS_NEW(pmp) CStatsPredConj(pdrgpstatspredConj); // predicate (col_1 = 1); DrgPstatspred *pdrgpstatspredDisj = GPOS_NEW(pmp) DrgPstatspred(pmp); pdrgpstatspredDisj->Append(GPOS_NEW(pmp) CStatsPredPoint(1, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(pmp, 1))); pdrgpstatspredDisj->Append(pstatspredConj); return GPOS_NEW(pmp) CStatsPredDisj(pdrgpstatspredDisj); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::PstatspredDisjOverConjMultipleIdenticalCols // // @doc: // Create nested AND and OR predicates where the AND and OR predicates //--------------------------------------------------------------------------- CStatsPred * CStatisticsTest::PstatspredDisjOverConjMultipleIdenticalCols ( IMemoryPool *pmp ) { DrgPstatspred *pdrgpstatspredConj1 = GPOS_NEW(pmp) DrgPstatspred(pmp); // predicate col_1 = 1 AND col_2 = 1 pdrgpstatspredConj1->Append(GPOS_NEW(pmp) CStatsPredPoint(1, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(pmp, 1))); pdrgpstatspredConj1->Append(GPOS_NEW(pmp) CStatsPredPoint(2, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(pmp, 1))); CStatsPredConj *pstatspredConj1 = GPOS_NEW(pmp) CStatsPredConj(pdrgpstatspredConj1); DrgPstatspred *pdrgpstatspredConj2 = GPOS_NEW(pmp) DrgPstatspred(pmp); // predicate col_1 = 2 AND col_2 = 2 pdrgpstatspredConj2->Append(GPOS_NEW(pmp) CStatsPredPoint(1, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(pmp, 2))); pdrgpstatspredConj2->Append(GPOS_NEW(pmp) CStatsPredPoint(2, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(pmp, 2))); CStatsPredConj *pstatspredConj2 = GPOS_NEW(pmp) CStatsPredConj(pdrgpstatspredConj2); DrgPstatspred *pdrgpstatspredDisj = GPOS_NEW(pmp) DrgPstatspred(pmp); pdrgpstatspredDisj->Append(pstatspredConj1); pdrgpstatspredDisj->Append(pstatspredConj2); return GPOS_NEW(pmp) CStatsPredDisj(pdrgpstatspredDisj); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::PstatspredNullableCols // // @doc: // Create a filter on a column with null values // //--------------------------------------------------------------------------- CStatsPred * CStatisticsTest::PstatspredNullableCols ( IMemoryPool *pmp ) { DrgPstatspred *pdrgpstatspred = GPOS_NEW(pmp) DrgPstatspred(pmp); pdrgpstatspred->Append(GPOS_NEW(pmp) CStatsPredPoint(1, CStatsPred::EstatscmptLEq, CTestUtils::PpointInt4(pmp, 1))); return GPOS_NEW(pmp) CStatsPredConj(pdrgpstatspred); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::PstatspredWithNullConstant // // @doc: // Create a point filter where the constant is null // //--------------------------------------------------------------------------- CStatsPred * CStatisticsTest::PstatspredWithNullConstant ( IMemoryPool *pmp ) { DrgPstatspred *pdrgpstatspred = GPOS_NEW(pmp) DrgPstatspred(pmp); pdrgpstatspred->Append(GPOS_NEW(pmp) CStatsPredPoint(1, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4NullVal(pmp))); return GPOS_NEW(pmp) CStatsPredConj(pdrgpstatspred); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::PstatspredNotNull // // @doc: // Create an 'is not null' point filter // //--------------------------------------------------------------------------- CStatsPred * CStatisticsTest::PstatspredNotNull ( IMemoryPool *pmp ) { DrgPstatspred *pdrgpstatspred = GPOS_NEW(pmp) DrgPstatspred(pmp); pdrgpstatspred->Append(GPOS_NEW(pmp) CStatsPredPoint(1, CStatsPred::EstatscmptNEq, CTestUtils::PpointInt4NullVal(pmp))); return GPOS_NEW(pmp) CStatsPredConj(pdrgpstatspred); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::PstatspredDisj1 // // @doc: // Create an or filter (no duplicate) // //--------------------------------------------------------------------------- CStatsPred * CStatisticsTest::PstatspredDisj1 ( IMemoryPool *pmp ) { // predicate col_1 in (13, 25, 47, 49); INT rgiVal[] = {13, 25, 47, 49}; const ULONG ulVals = GPOS_ARRAY_SIZE(rgiVal); DrgPstatspred *pdrgpstatspredDisj = PdrgpstatspredInteger(pmp, 1, CStatsPred::EstatscmptEq, rgiVal, ulVals); return GPOS_NEW(pmp) CStatsPredDisj(pdrgpstatspredDisj); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::PstatspredDisj2 // // @doc: // Create an or filter (one duplicate constant) // //--------------------------------------------------------------------------- CStatsPred * CStatisticsTest::PstatspredDisj2 ( IMemoryPool *pmp ) { // predicate col_1 in (13, 13, 25, 47, 49); INT rgiVal[] = {13, 13, 25, 47, 49}; const ULONG ulVals = GPOS_ARRAY_SIZE(rgiVal); DrgPstatspred *pdrgpstatspredDisj = PdrgpstatspredInteger(pmp, 1, CStatsPred::EstatscmptEq, rgiVal, ulVals); return GPOS_NEW(pmp) CStatsPredDisj(pdrgpstatspredDisj); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::PstatspredDisj3 // // @doc: // Create an or filter (multiple duplicate constants) // //--------------------------------------------------------------------------- CStatsPred * CStatisticsTest::PstatspredDisj3 ( IMemoryPool *pmp ) { // predicate col_1 in (13, 25, 47, 47, 47, 49, 13); INT rgiVal[] = {13, 25, 47, 47, 47, 49, 13}; const ULONG ulVals = GPOS_ARRAY_SIZE(rgiVal); DrgPstatspred *pdrgpstatspredDisj = PdrgpstatspredInteger(pmp, 1, CStatsPred::EstatscmptEq, rgiVal, ulVals); return GPOS_NEW(pmp) CStatsPredDisj(pdrgpstatspredDisj); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::PstatspredDisj4 // // @doc: // Create an or filter // //--------------------------------------------------------------------------- CStatsPred * CStatisticsTest::PstatspredDisj4 ( IMemoryPool *pmp ) { // the predicate is (x <= 5 or x <= 10 or x <= 13) (domain [0 -- 20]) INT rgiVal[] = {5, 10, 13}; const ULONG ulVals = GPOS_ARRAY_SIZE(rgiVal); DrgPstatspred *pdrgpstatspredDisj = PdrgpstatspredInteger(pmp, 1, CStatsPred::EstatscmptLEq, rgiVal, ulVals); return GPOS_NEW(pmp) CStatsPredDisj(pdrgpstatspredDisj); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::PstatspredDisj5 // // @doc: // Create an or filter (multiple LEQ) // //--------------------------------------------------------------------------- CStatsPred * CStatisticsTest::PstatspredDisj5 ( IMemoryPool *pmp ) { // the predicate is (x >= 5 or x >= 13) (domain [0 -- 20]) INT rgiVal[] = {5, 13}; const ULONG ulVals = GPOS_ARRAY_SIZE(rgiVal); DrgPstatspred *pdrgpstatspredDisj = PdrgpstatspredInteger(pmp, 1, CStatsPred::EstatscmptGEq, rgiVal, ulVals); return GPOS_NEW(pmp) CStatsPredDisj(pdrgpstatspredDisj); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::PstatspredDisj6 // // @doc: // Create an or filter // //--------------------------------------------------------------------------- CStatsPred * CStatisticsTest::PstatspredDisj6 ( IMemoryPool *pmp ) { // the predicate is (x > 10 or x < 5) (domain [0 -- 20]) DrgPstatspred *pdrgpstatspredDisj = GPOS_NEW(pmp) DrgPstatspred(pmp); pdrgpstatspredDisj->Append(GPOS_NEW(pmp) CStatsPredPoint(1, CStatsPred::EstatscmptG, CTestUtils::PpointInt4(pmp, 10))); pdrgpstatspredDisj->Append(GPOS_NEW(pmp) CStatsPredPoint(1, CStatsPred::EstatscmptL, CTestUtils::PpointInt4(pmp, 5))); return GPOS_NEW(pmp) CStatsPredDisj(pdrgpstatspredDisj); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::PstatspredDisj7 // // @doc: // Create an or filter // //--------------------------------------------------------------------------- CStatsPred * CStatisticsTest::PstatspredDisj7 ( IMemoryPool *pmp ) { // the predicate is (x <= 15 or x >= 5 or x > = 10) (domain [0 -- 20]) INT rgiVal[] = {5, 10}; const ULONG ulVals = GPOS_ARRAY_SIZE(rgiVal); DrgPstatspred *pdrgpstatspredDisj = PdrgpstatspredInteger(pmp, 1, CStatsPred::EstatscmptGEq, rgiVal, ulVals); pdrgpstatspredDisj->Append(GPOS_NEW(pmp) CStatsPredPoint(1, CStatsPred::EstatscmptLEq, CTestUtils::PpointInt4(pmp, 15))); return GPOS_NEW(pmp) CStatsPredDisj(pdrgpstatspredDisj); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::PstatspredDisj8 // // @doc: // Create disjunctive predicate on same columns //--------------------------------------------------------------------------- CStatsPred * CStatisticsTest::PstatspredDisj8 ( IMemoryPool *pmp ) { // predicate is b = 2001 OR b == 2002 INT rgiVal[] = {2001, 2002}; const ULONG ulVals = GPOS_ARRAY_SIZE(rgiVal); DrgPstatspred *pdrgpstatspredDisj = PdrgpstatspredInteger(pmp, 61, CStatsPred::EstatscmptEq, rgiVal, ulVals); return GPOS_NEW(pmp) CStatsPredDisj(pdrgpstatspredDisj); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::Pdrgpstatspred1 // // @doc: // Create a filter clause // //--------------------------------------------------------------------------- DrgPstatspred * CStatisticsTest::Pdrgpstatspred1 ( IMemoryPool *pmp ) { DrgPstatspred *pdrgpstatspred = GPOS_NEW(pmp) DrgPstatspred(pmp); // col1 = true StatsFilterBool(pmp, 1, true, pdrgpstatspred); // col2 >= 25 and col2 < 35 StatsFilterInt4(pmp, 2, 25, 35, pdrgpstatspred); return pdrgpstatspred; } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::Pdrgpstatspred2 // // @doc: // Create a filter clause // //--------------------------------------------------------------------------- DrgPstatspred * CStatisticsTest::Pdrgpstatspred2 ( IMemoryPool *pmp ) { // contain for filters DrgPstatspred *pdrgpstatspred = GPOS_NEW(pmp) DrgPstatspred(pmp); // create int4 filter column 2: [5,15)::int4 StatsFilterInt4(pmp, 2, 5, 15, pdrgpstatspred); // create numeric filter column 3: [1.0, 2.0)::numeric CWStringDynamic *pstrLowerNumeric = GPOS_NEW(pmp) CWStringDynamic(pmp, GPOS_WSZ_LIT("AAAACgAAAQABAA==")); CWStringDynamic *pstrUpperNumeric = GPOS_NEW(pmp) CWStringDynamic(pmp, GPOS_WSZ_LIT("AAAACgAAAQACAA==")); StatsFilterNumeric(pmp, 3, pstrLowerNumeric, pstrUpperNumeric, CDouble(1.0), CDouble(2.0), pdrgpstatspred); GPOS_DELETE(pstrLowerNumeric); GPOS_DELETE(pstrUpperNumeric); // create a date filter column 4: ['01-01-2012', '01-21-2012')::date CWStringDynamic *pstrLowerDate = GPOS_NEW(pmp) CWStringDynamic(pmp, GPOS_WSZ_LIT("HxEAAA==")); CWStringDynamic *pstrUpperDate = GPOS_NEW(pmp) CWStringDynamic(pmp, GPOS_WSZ_LIT("LREAAA==")); LINT lLowerDate = LINT(4383) * LINT(INT64_C(86400000000)); // microseconds per day LINT lUpperDate = LINT(4397) * LINT(INT64_C(86400000000)); // microseconds per day StatsFilterGeneric(pmp, 4, GPDB_DATE, pstrLowerDate, pstrUpperDate, lLowerDate, lUpperDate, pdrgpstatspred); GPOS_DELETE(pstrLowerDate); GPOS_DELETE(pstrUpperDate); // create timestamp filter column 5: ['01-01-2012 00:01:00', '01-01-2012 10:00:00')::timestamp CWStringDynamic *pstrLowerTS = GPOS_NEW(pmp) CWStringDynamic(pmp, GPOS_WSZ_LIT("ACcI7mpYAQA=")); CWStringDynamic *pstrUpperTS = GPOS_NEW(pmp) CWStringDynamic(pmp, GPOS_WSZ_LIT("AAg5THNYAQA=")); LINT lLowerTS = LINT(INT64_C(378691260000000)); // microseconds LINT lUpperTS = LINT(INT64_C(378727200000000)); // microseconds StatsFilterGeneric(pmp, 5, GPDB_TIMESTAMP, pstrLowerTS, pstrUpperTS, lLowerTS, lUpperTS, pdrgpstatspred); GPOS_DELETE(pstrLowerTS); GPOS_DELETE(pstrUpperTS); return pdrgpstatspred; } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::Print // // @doc: // Dump statistics output // //--------------------------------------------------------------------------- void CStatisticsTest::Print ( IMemoryPool *pmp, const CStatistics *pstats ) { CWStringDynamic str(pmp); COstreamString oss(&str); oss << "Statistics = "; pstats->OsPrint(oss); oss << std::endl; GPOS_TRACE(str.Wsz()); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::EresUnittest_CHistogramValid // // @doc: // Check for well-formed histogram. Expected to hit an assert. // //--------------------------------------------------------------------------- GPOS_RESULT CStatisticsTest::EresUnittest_CHistogramValid() { // create memory pool CAutoMemoryPool amp; IMemoryPool *pmp = amp.Pmp(); DrgPbucket *pdrgppbucket = GPOS_NEW(pmp) DrgPbucket(pmp); // generate histogram of the form [0, 10), [9, 20) CBucket *pbucket1 = Pbucket(pmp, 0, 10, 0.1, 2.0); pdrgppbucket->Append(pbucket1); CBucket *pbucket2 = Pbucket(pmp, 9, 20, 0.1, 2.0); pdrgppbucket->Append(pbucket2); // original histogram CHistogram *phist = GPOS_NEW(pmp) CHistogram(pdrgppbucket); // create an auto object CAutoP<CHistogram> ahist; ahist = phist; GPOS_RTL_ASSERT(phist->FValid() && "Histogram must be well formed"); return GPOS_FAILED; } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::StatsFilterInt4 // // @doc: // Create a stats filter on integer range // //--------------------------------------------------------------------------- void CStatisticsTest::StatsFilterInt4 ( IMemoryPool *pmp, ULONG ulColId, INT iLower, INT iUpper, DrgPstatspred *pdrgpstatspred ) { CStatsPredPoint *pstatspred1 = GPOS_NEW(pmp) CStatsPredPoint ( ulColId, CStatsPred::EstatscmptGEq, CTestUtils::PpointInt4(pmp, iLower) ); CStatsPredPoint *pstatspred2 = GPOS_NEW(pmp) CStatsPredPoint ( ulColId, CStatsPred::EstatscmptL, CTestUtils::PpointInt4(pmp, iUpper) ); pdrgpstatspred->Append(pstatspred1); pdrgpstatspred->Append(pstatspred2); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::StatsFilterBool // // @doc: // Create a stats filter on boolean // //--------------------------------------------------------------------------- void CStatisticsTest::StatsFilterBool ( IMemoryPool *pmp, ULONG ulColId, BOOL fValue, DrgPstatspred *pdrgpstatspred ) { CStatsPredPoint *pstatspred1 = GPOS_NEW(pmp) CStatsPredPoint ( ulColId, CStatsPred::EstatscmptEq, CTestUtils::PpointBool(pmp, fValue) ); pdrgpstatspred->Append(pstatspred1); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::StatsFilter // // @doc: // Create a stats filter on numeric types // //--------------------------------------------------------------------------- void CStatisticsTest::StatsFilterNumeric ( IMemoryPool *pmp, ULONG ulColId, CWStringDynamic *pstrLowerEncoded, CWStringDynamic *pstrUpperEncoded, CDouble dValLower, CDouble dValUpper, DrgPstatspred *pdrgpstatspred ) { CStatsPredPoint *pstatspred1 = GPOS_NEW(pmp) CStatsPredPoint ( ulColId, CStatsPred::EstatscmptGEq, PpointNumeric(pmp, pstrLowerEncoded, dValLower) ); CStatsPredPoint *pstatspred2 = GPOS_NEW(pmp) CStatsPredPoint ( ulColId, CStatsPred::EstatscmptL, PpointNumeric(pmp, pstrUpperEncoded, dValUpper) ); pdrgpstatspred->Append(pstatspred1); pdrgpstatspred->Append(pstatspred2); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::StatsFilterGeneric // // @doc: // Create a stats filter on other types // //--------------------------------------------------------------------------- void CStatisticsTest::StatsFilterGeneric ( IMemoryPool *pmp, ULONG ulColId, OID oid, CWStringDynamic *pstrLowerEncoded, CWStringDynamic *pstrUpperEncoded, LINT lValueLower, LINT lValueUpper, DrgPstatspred *pdrgpstatspred ) { CStatsPredPoint *pstatspred1 = GPOS_NEW(pmp) CStatsPredPoint ( ulColId, CStatsPred::EstatscmptGEq, PpointGeneric(pmp, oid, pstrLowerEncoded, lValueLower) ); CStatsPredPoint *pstatspred2 = GPOS_NEW(pmp) CStatsPredPoint ( ulColId, CStatsPred::EstatscmptL, PpointGeneric(pmp, oid, pstrUpperEncoded, lValueUpper) ); pdrgpstatspred->Append(pstatspred1); pdrgpstatspred->Append(pstatspred2); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::EresUnittest_CStatisticsSelectDerivation // // @doc: // Derivation over select query // //--------------------------------------------------------------------------- GPOS_RESULT CStatisticsTest::EresUnittest_CStatisticsSelectDerivation() { CAutoMemoryPool amp; IMemoryPool *pmp = amp.Pmp(); return CTestUtils::EresTranslate ( pmp, szQuerySelect, szPlanSelect, true // ignore mismatch in output dxl due to column id differences ); } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::EresUnittest_Skew // // @doc: // Basis skew test // //--------------------------------------------------------------------------- GPOS_RESULT CStatisticsTest::EresUnittest_Skew() { // create memory pool CAutoMemoryPool amp; IMemoryPool *pmp = amp.Pmp(); CBucket *pbucket1 = Pbucket(pmp, 1, 100, CDouble(0.6), CDouble(100.0)); CBucket *pbucket2 = Pbucket(pmp, 101, 200, CDouble(0.2), CDouble(100.0)); CBucket *pbucket3 = Pbucket(pmp, 201, 300, CDouble(0.2), CDouble(100.0)); CBucket *pbucket4 = Pbucket(pmp, 301, 400, CDouble(0.2), CDouble(100.0)); CBucket *pbucket5 = Pbucket(pmp, 401, 500, CDouble(0.2), CDouble(100.0)); CBucket *pbucket6 = Pbucket(pmp, 501, 600, CDouble(0.2), CDouble(100.0)); CBucket *pbucket7 = Pbucket(pmp, 601, 700, CDouble(0.2), CDouble(100.0)); CBucket *pbucket8 = Pbucket(pmp, 701, 800, CDouble(0.2), CDouble(100.0)); DrgPbucket *pdrgppbucket1 = GPOS_NEW(pmp) DrgPbucket(pmp); pdrgppbucket1->Append(pbucket1); pdrgppbucket1->Append(pbucket2); pdrgppbucket1->Append(pbucket3); CHistogram *phist1 = GPOS_NEW(pmp) CHistogram(pdrgppbucket1); DrgPbucket *pdrgppbucket2 = GPOS_NEW(pmp) DrgPbucket(pmp); pdrgppbucket2->Append(pbucket4); pdrgppbucket2->Append(pbucket5); pdrgppbucket2->Append(pbucket6); pdrgppbucket2->Append(pbucket7); pdrgppbucket2->Append(pbucket8); CHistogram *phist2 = GPOS_NEW(pmp) CHistogram(pdrgppbucket2); GPOS_ASSERT(phist1->DSkew() > phist2->DSkew()); { CAutoTrace at(pmp); phist1->OsPrint(at.Os()); phist2->OsPrint(at.Os()); } GPOS_DELETE(phist1); GPOS_DELETE(phist2); return GPOS_OK; } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::EresUnittest_SortInt4MCVs // // @doc: // Test sorting of Int4 MCVs and their associated frequencies // //--------------------------------------------------------------------------- GPOS_RESULT CStatisticsTest::EresUnittest_SortInt4MCVs() { // create memory pool CAutoMemoryPool amp; IMemoryPool *pmp = amp.Pmp(); CMDAccessor *pmda = COptCtxt::PoctxtFromTLS()->Pmda(); CMDIdGPDB *pmdid = GPOS_NEW(pmp) CMDIdGPDB(CMDIdGPDB::m_mdidInt4); const IMDType *pmdtype = pmda->Pmdtype(pmdid); // create three integer MCVs CPoint *ppoint1 = CTestUtils::PpointInt4(pmp, 5); CPoint *ppoint2 = CTestUtils::PpointInt4(pmp, 1); CPoint *ppoint3 = CTestUtils::PpointInt4(pmp, 10); DrgPdatum *pdrgpdatumMCV = GPOS_NEW(pmp) DrgPdatum(pmp); IDatum *pdatum1 = ppoint1->Pdatum(); IDatum *pdatum2 = ppoint2->Pdatum(); IDatum *pdatum3 = ppoint3->Pdatum(); pdatum1->AddRef(); pdatum2->AddRef(); pdatum3->AddRef(); pdrgpdatumMCV->Append(pdatum1); pdrgpdatumMCV->Append(pdatum2); pdrgpdatumMCV->Append(pdatum3); // create corresponding frequencies DrgPdouble *pdrgpdFreq = GPOS_NEW(pmp) DrgPdouble(pmp); // in GPDB, MCVs are stored in descending frequencies pdrgpdFreq->Append(GPOS_NEW(pmp) CDouble(0.4)); pdrgpdFreq->Append(GPOS_NEW(pmp) CDouble(0.2)); pdrgpdFreq->Append(GPOS_NEW(pmp) CDouble(0.1)); // exercise MCV sorting function CHistogram *phistMCV = CStatisticsUtils::PhistTransformMCV ( pmp, pmdtype, pdrgpdatumMCV, pdrgpdFreq, pdrgpdatumMCV->UlLength() ); // create hash map from colid -> histogram HMUlHist *phmulhist = GPOS_NEW(pmp) HMUlHist(pmp); // generate int histogram for column 1 phmulhist->FInsert(GPOS_NEW(pmp) ULONG(1), phistMCV); // column width for int4 HMUlDouble *phmuldoubleWidth = GPOS_NEW(pmp) HMUlDouble(pmp); phmuldoubleWidth->FInsert(GPOS_NEW(pmp) ULONG(1), GPOS_NEW(pmp) CDouble(4.0)); CStatistics *pstats = GPOS_NEW(pmp) CStatistics ( pmp, phmulhist, phmuldoubleWidth, 1000.0 /* dRows */, false /* fEmpty */ ); // put stats object in an array in order to serialize DrgPstats *pdrgpstats = GPOS_NEW(pmp) DrgPstats(pmp); pdrgpstats->Append(pstats); // serialize stats object CWStringDynamic *pstrOutput = CDXLUtils::PstrSerializeStatistics(pmp, pmda, pdrgpstats, true, true); GPOS_TRACE(pstrOutput->Wsz()); // get expected output CWStringDynamic str(pmp); COstreamString oss(&str); CHAR *szDXLExpected = CDXLUtils::SzRead(pmp, szMCVSortExpectedFileName); CWStringDynamic dstrExpected(pmp); dstrExpected.AppendFormat(GPOS_WSZ_LIT("%s"), szDXLExpected); GPOS_RESULT eres = CTestUtils::EresCompare ( oss, pstrOutput, &dstrExpected, false // mismatch will not be ignored ); // cleanup GPOS_DELETE(pstrOutput); GPOS_DELETE_ARRAY(szDXLExpected); pdrgpdatumMCV->Release(); pdrgpdFreq->Release(); pdrgpstats->Release(); ppoint1->Release(); ppoint2->Release(); ppoint3->Release(); pmdid->Release(); return eres; } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::EresUnittest_MergeHistMCV // // @doc: // Test merging MCVs and histogram // //--------------------------------------------------------------------------- GPOS_RESULT CStatisticsTest::EresUnittest_MergeHistMCV() { SMergeTestElem rgMergeTestElem[] = { { "../data/dxl/statistics/Merge-Input-MCV-Int.xml", "../data/dxl/statistics/Merge-Input-Histogram-Int.xml", "../data/dxl/statistics/Merge-Output-Int.xml" }, { "../data/dxl/statistics/Merge-Input-MCV-Numeric.xml", "../data/dxl/statistics/Merge-Input-Histogram-Numeric.xml", "../data/dxl/statistics/Merge-Output-Numeric.xml" }, { "../data/dxl/statistics/Merge-Input-MCV-BPChar.xml", "../data/dxl/statistics/Merge-Input-Histogram-BPChar.xml", "../data/dxl/statistics/Merge-Output-BPChar.xml" } }; // create memory pool CAutoMemoryPool amp; IMemoryPool *pmp = amp.Pmp(); ULONG ulLen = GPOS_ARRAY_SIZE(rgMergeTestElem); for (ULONG ul = 0; ul < ulLen; ul++) { // read input MCVs DXL file CHAR *szDXLInputMCV = CDXLUtils::SzRead(pmp, rgMergeTestElem[ul].szInputMCVFile); // read input histogram DXL file CHAR *szDXLInputHist = CDXLUtils::SzRead(pmp, rgMergeTestElem[ul].szInputHistFile); GPOS_CHECK_ABORT; CMDAccessor *pmda = COptCtxt::PoctxtFromTLS()->Pmda(); // parse the stats objects DrgPdxlstatsderrel *pdrgpdxlstatsderrelMCV = CDXLUtils::PdrgpdxlstatsderrelParseDXL(pmp, szDXLInputMCV, NULL); DrgPdxlstatsderrel *pdrgpdxlstatsderrelHist = CDXLUtils::PdrgpdxlstatsderrelParseDXL(pmp, szDXLInputHist, NULL); GPOS_CHECK_ABORT; CDXLStatsDerivedRelation *pdxlstatsderrelMCV = (*pdrgpdxlstatsderrelMCV)[0]; const DrgPdxlstatsdercol *pdrgpdxlstatsdercolMCV = pdxlstatsderrelMCV->Pdrgpdxlstatsdercol(); CDXLStatsDerivedColumn *pdxlstatsdercolMCV = (*pdrgpdxlstatsdercolMCV)[0]; DrgPbucket *pdrgppbucketMCV = CDXLUtils::Pdrgpbucket(pmp, pmda, pdxlstatsdercolMCV); CHistogram *phistMCV = GPOS_NEW(pmp) CHistogram(pdrgppbucketMCV); CDXLStatsDerivedRelation *pdxlstatsderrelHist = (*pdrgpdxlstatsderrelHist)[0]; const DrgPdxlstatsdercol *pdrgpdxlstatsdercolHist = pdxlstatsderrelHist->Pdrgpdxlstatsdercol(); CDXLStatsDerivedColumn *pdxlstatsdercolHist = (*pdrgpdxlstatsdercolHist)[0]; DrgPbucket *pdrgppbucketHist = CDXLUtils::Pdrgpbucket(pmp, pmda, pdxlstatsdercolHist); CHistogram *phistHist = GPOS_NEW(pmp) CHistogram(pdrgppbucketHist); GPOS_CHECK_ABORT; // exercise the merge CHistogram *phistMerged = CStatisticsUtils::PhistMergeMcvHist(pmp, phistMCV, phistHist); // create hash map from colid -> histogram HMUlHist *phmulhist = GPOS_NEW(pmp) HMUlHist(pmp); // generate int histogram for column 1 ULONG ulColId = pdxlstatsdercolMCV->UlColId(); phmulhist->FInsert(GPOS_NEW(pmp) ULONG(ulColId), phistMerged); // column width for int4 HMUlDouble *phmuldoubleWidth = GPOS_NEW(pmp) HMUlDouble(pmp); CDouble dWidth = pdxlstatsdercolMCV->DWidth(); phmuldoubleWidth->FInsert(GPOS_NEW(pmp) ULONG(ulColId), GPOS_NEW(pmp) CDouble(dWidth)); CStatistics *pstats = GPOS_NEW(pmp) CStatistics ( pmp, phmulhist, phmuldoubleWidth, pdxlstatsderrelMCV->DRows(), pdxlstatsderrelMCV->FEmpty() ); // put stats object in an array in order to serialize DrgPstats *pdrgpstats = GPOS_NEW(pmp) DrgPstats(pmp); pdrgpstats->Append(pstats); // serialize stats object CWStringDynamic *pstrOutput = CDXLUtils::PstrSerializeStatistics(pmp, pmda, pdrgpstats, true, true); GPOS_TRACE(pstrOutput->Wsz()); // get expected output CWStringDynamic str(pmp); COstreamString oss(&str); CHAR *szDXLExpected = CDXLUtils::SzRead(pmp, rgMergeTestElem[ul].szMergedFile); CWStringDynamic dstrExpected(pmp); dstrExpected.AppendFormat(GPOS_WSZ_LIT("%s"), szDXLExpected); GPOS_RESULT eres = CTestUtils::EresCompare ( oss, pstrOutput, &dstrExpected, false // mismatch will not be ignored ); // cleanup GPOS_DELETE_ARRAY(szDXLInputMCV); GPOS_DELETE_ARRAY(szDXLInputHist); GPOS_DELETE_ARRAY(szDXLExpected); GPOS_DELETE(pstrOutput); pdrgpdxlstatsderrelMCV->Release(); pdrgpdxlstatsderrelHist->Release(); GPOS_DELETE(phistMCV); GPOS_DELETE(phistHist); pdrgpstats->Release(); if (GPOS_OK != eres) { return eres; } } return GPOS_OK; } //--------------------------------------------------------------------------- // @function: // CStatisticsTest::EresUnittest_CStatisticsAccumulateCard // // @doc: // Test for accumulating cardinality in disjunctive and conjunctive // predicates // //--------------------------------------------------------------------------- GPOS_RESULT CStatisticsTest::EresUnittest_CStatisticsAccumulateCard() { // create memory pool CAutoMemoryPool amp; IMemoryPool *pmp = amp.Pmp(); // create hash map from colid -> histogram HMUlHist *phmulhist = GPOS_NEW(pmp) HMUlHist(pmp); // array capturing columns for which width information is available HMUlDouble *phmuldoubleWidth = GPOS_NEW(pmp) HMUlDouble(pmp); const ULONG ulCols = 3; for (ULONG ul = 0; ul < ulCols; ul ++) { // generate histogram of the form [0, 10), [10, 20), [20, 30), [80, 90), [100,100] phmulhist->FInsert(GPOS_NEW(pmp) ULONG(ul), PhistExampleInt4(pmp)); // width for int phmuldoubleWidth->FInsert(GPOS_NEW(pmp) ULONG(ul), GPOS_NEW(pmp) CDouble(4.0)); } CStatistics *pstats = GPOS_NEW(pmp) CStatistics ( pmp, phmulhist, phmuldoubleWidth, CDouble(1000.0) /* dRows */, false /* fEmpty() */ ); CDouble dRows = pstats->DRows(); GPOS_TRACE(GPOS_WSZ_LIT("\nOriginal Stats:\n")); Print(pmp, pstats); // (1) // create disjunctive filter DrgPstatspred *pdrgpstatspred = GPOS_NEW(pmp) DrgPstatspred(pmp); pdrgpstatspred->Append(GPOS_NEW(pmp) CStatsPredPoint(0, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(pmp, 5))); pdrgpstatspred->Append(GPOS_NEW(pmp) CStatsPredPoint(1, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(pmp, 200))); pdrgpstatspred->Append(GPOS_NEW(pmp) CStatsPredPoint(2, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(pmp, 200))); CStatsPredDisj *pstatspredDisj = GPOS_NEW(pmp) CStatsPredDisj(pdrgpstatspred); // apply filter and print resulting stats CStatistics *pstats1 = pstats->PstatsFilter(pmp, pstatspredDisj, true /* fCapNdvs */); CDouble dRows1 = pstats1->DRows(); GPOS_TRACE(GPOS_WSZ_LIT("\n\nStats after disjunctive filter [Col0=5 OR Col1=200 OR Col2=200]:\n")); Print(pmp, pstats1); pstatspredDisj->Release(); // (2) // create point filter DrgPstatspred *pdrgpstatspred1 = GPOS_NEW(pmp) DrgPstatspred(pmp); pdrgpstatspred1->Append(GPOS_NEW(pmp) CStatsPredPoint(0, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(pmp, 5))); CStatsPredConj *pstatspredConj1 = GPOS_NEW(pmp) CStatsPredConj(pdrgpstatspred1); // apply filter and print resulting stats CStatistics *pstats2 = pstats->PstatsFilter(pmp, pstatspredConj1, true /* fCapNdvs */); CDouble dRows2 = pstats2->DRows(); GPOS_TRACE(GPOS_WSZ_LIT("\n\nStats after point filter [Col0=5]:\n")); Print(pmp, pstats2); pstatspredConj1->Release(); GPOS_ASSERT(dRows1 - dRows2 < 10 && "Disjunctive filter and point filter have very different row estimates"); // (3) // create conjunctive filter DrgPstatspred *pdrgpstatspred2 = GPOS_NEW(pmp) DrgPstatspred(pmp); pdrgpstatspred2->Append(GPOS_NEW(pmp) CStatsPredPoint(0, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(pmp, 5))); pdrgpstatspred2->Append(GPOS_NEW(pmp) CStatsPredPoint(1, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(pmp, 200))); pdrgpstatspred2->Append(GPOS_NEW(pmp) CStatsPredPoint(2, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(pmp, 200))); CStatsPredConj *pstatspredConj2 = GPOS_NEW(pmp) CStatsPredConj(pdrgpstatspred2); // apply filter and print resulting stats CStatistics *pstats3 = pstats->PstatsFilter(pmp, pstatspredConj2, true /* fCapNdvs */); CDouble dRows3 = pstats3->DRows(); GPOS_TRACE(GPOS_WSZ_LIT("\n\nStats after conjunctive filter [Col0=5 AND Col1=200 AND Col2=200]:\n")); Print(pmp, pstats3); pstatspredConj2->Release(); GPOS_ASSERT(dRows3 < dRows2 && "Conjunctive filter passes more rows than than point filter"); // (4) // create selective disjunctive filter that pass no rows DrgPstatspred *pdrgpstatspred3 = GPOS_NEW(pmp) DrgPstatspred(pmp); pdrgpstatspred3->Append(GPOS_NEW(pmp) CStatsPredPoint(1, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(pmp, 200))); pdrgpstatspred3->Append(GPOS_NEW(pmp) CStatsPredPoint(2, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(pmp, 200))); CStatsPredDisj *pstatspredDisj1 = GPOS_NEW(pmp) CStatsPredDisj(pdrgpstatspred3); // apply filter and print resulting stats CStatistics *pstats4 = pstats->PstatsFilter(pmp, pstatspredDisj1, true /* fCapNdvs */); CDouble dRows4 = pstats4->DRows(); GPOS_TRACE(GPOS_WSZ_LIT("\n\nStats after disjunctive filter [Col1=200 OR Col2=200]:\n")); Print(pmp, pstats4); pstatspredDisj1->Release(); GPOS_ASSERT(dRows4 < dRows2 && "Selective disjunctive filter passes more rows than than point filter"); // (5) // create selective conjunctive filter that pass no rows DrgPstatspred *pdrgpstatspred4 = GPOS_NEW(pmp) DrgPstatspred(pmp); pdrgpstatspred4->Append(GPOS_NEW(pmp) CStatsPredPoint(0, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(pmp, 5))); pdrgpstatspred4->Append(GPOS_NEW(pmp) CStatsPredPoint(1, CStatsPred::EstatscmptEq, CTestUtils::PpointInt4(pmp, 200))); CStatsPredConj *pstatspredConj3 = GPOS_NEW(pmp) CStatsPredConj(pdrgpstatspred4); // apply filter and print resulting stats CStatistics *pstats5 = pstats->PstatsFilter(pmp, pstatspredConj3, true /* fCapNdvs */); CDouble dRows5 = pstats5->DRows(); GPOS_TRACE(GPOS_WSZ_LIT("\n\nStats after conjunctive filter [Col0=5 AND Col1=200]:\n")); Print(pmp, pstats5); pstatspredConj3->Release(); GPOS_ASSERT(dRows5 < dRows2 && "Selective conjunctive filter passes more rows than than point filter"); // clean up pstats->Release(); pstats1->Release(); pstats2->Release(); pstats3->Release(); pstats4->Release(); pstats5->Release(); return GPOS_OK; } // EOF
32.50253
168
0.6507
[ "object" ]
3e88dcfa51405f76cad9f4352a061dcc4022065e
38,026
cpp
C++
src/io/variant/htslib_bcf_facade.cpp
gmagoon/octopus
493643d8503239aead9c7e8a7f8bc19fb97b37d5
[ "MIT" ]
null
null
null
src/io/variant/htslib_bcf_facade.cpp
gmagoon/octopus
493643d8503239aead9c7e8a7f8bc19fb97b37d5
[ "MIT" ]
null
null
null
src/io/variant/htslib_bcf_facade.cpp
gmagoon/octopus
493643d8503239aead9c7e8a7f8bc19fb97b37d5
[ "MIT" ]
null
null
null
// Copyright (c) 2015-2018 Daniel Cooke // Use of this source code is governed by the MIT license that can be found in the LICENSE file. #include "htslib_bcf_facade.hpp" #include <vector> #include <array> #include <unordered_map> #include <stdexcept> #include <algorithm> #include <utility> #include <cstdlib> #include <cstring> #include <cstdint> #include <cmath> #include <boost/filesystem/operations.hpp> #include <boost/optional.hpp> #include <boost/container/small_vector.hpp> #include "basics/genomic_region.hpp" #include "utils/string_utils.hpp" #include "vcf_spec.hpp" #include "vcf_header.hpp" #include "vcf_record.hpp" #include <iostream> // TEST namespace octopus { namespace { static const std::string bcf_missing_str {vcfspec::missingValue}; bool is_missing(const std::string& value) noexcept { return value == bcf_missing_str; } namespace bc = boost::container; } // namespace char* malloc_copy(const std::string& source) { const auto result = (char*) std::malloc(source.length() + 1); source.copy(result, source.length()); result[source.length()] = '\0'; return result; } std::vector<std::string> extract_samples(const bcf_hdr_t* header) { std::vector<std::string> result {}; const auto num_samples = static_cast<unsigned>(bcf_hdr_nsamples(header)); result.reserve(num_samples); for (unsigned s {0}; s < num_samples; ++s) { result.emplace_back(header->samples[s]); } return result; } // public methods std::string get_hts_mode(const HtslibBcfFacade::Path& file_path, HtslibBcfFacade::Mode mode) { std::string result {"["}; using Mode = HtslibBcfFacade::Mode; if (mode == Mode::read) { result += "r]"; } else { result += 'w'; auto extension = file_path.extension(); if (extension == ".bcf") { result += "b"; } else if (extension == ".gz" && file_path.stem().extension() == ".vcf") { result += "z"; } } return result; } HtslibBcfFacade::HtslibBcfFacade() : file_path_ {} , file_ {bcf_open("-", "[w]"), HtsFileDeleter {}} , header_ {bcf_hdr_init("w"), HtsHeaderDeleter {}} , samples_ {} { if (file_ == nullptr) { throw std::runtime_error {"HtslibBcfFacade: could not open stdout writer"}; } if (header_ == nullptr) { throw std::runtime_error {"HtslibBcfFacade: failed to initialise stdout header"}; } } HtslibBcfFacade::HtslibBcfFacade(Path file_path, Mode mode) : file_path_ {std::move(file_path)} , file_ {nullptr, HtsFileDeleter {}} , header_ {nullptr, HtsHeaderDeleter {}} , samples_ {} { const auto hts_mode = get_hts_mode(file_path_, mode); if (mode == Mode::read) { if (boost::filesystem::exists(file_path_)) { file_.reset(bcf_open(file_path_.c_str(), hts_mode.c_str())); if (file_ == nullptr) return; header_.reset(bcf_hdr_read(file_.get())); if (header_ == nullptr) { throw std::runtime_error {"HtslibBcfFacade: could not make header for file " + file_path_.string()}; } samples_ = extract_samples(header_.get()); } else { throw std::runtime_error {"HtslibBcfFacade: " + file_path_.string() + " does not exist"}; } } else { file_.reset(bcf_open(file_path_.c_str(), hts_mode.c_str())); header_.reset(bcf_hdr_init(hts_mode.c_str())); } } std::unordered_map<std::string, std::string> extract_format(const bcf_hrec_t* line); bool HtslibBcfFacade::is_header_written() const noexcept { return header_ != nullptr; } VcfHeader HtslibBcfFacade::fetch_header() const { VcfHeader::Builder result {}; result.set_file_format(bcf_hdr_get_version(header_.get())); result.set_samples(samples_); std::for_each(header_->hrec, header_->hrec + header_->nhrec, [&result] (const auto record) { switch (record->type) { case BCF_HL_GEN: // key=value result.add_basic_field(record->key, record->value); break; default: // TAG=<A=..,B=..> result.add_structured_field(record->key, extract_format(record)); break; } }); return result.build_once(); } std::size_t HtslibBcfFacade::count_records() const { HtsBcfSrPtr sr {bcf_sr_init(), HtsSrsDeleter {}}; if (bcf_sr_add_reader(sr.get(), file_path_.c_str()) != 1) { sr.release(); throw std::runtime_error {"failed to open file " + file_path_.string()}; } return count_records(sr); } std::size_t HtslibBcfFacade::count_records(const std::string& contig) const { HtsBcfSrPtr sr {bcf_sr_init(), HtsSrsDeleter {}}; if (bcf_sr_set_regions(sr.get(), contig.c_str(), 0) != 0) { // must go before bcf_sr_add_reader throw std::runtime_error {"failed to load contig " + contig}; } if (bcf_sr_add_reader(sr.get(), file_path_.c_str()) != 1) { sr.release(); throw std::runtime_error {"failed to open file " + file_path_.string()}; } return count_records(sr); } std::size_t HtslibBcfFacade::count_records(const GenomicRegion& region) const { HtsBcfSrPtr sr {bcf_sr_init(), HtsSrsDeleter {}}; if (bcf_sr_set_regions(sr.get(), to_string(region).c_str(), 0) != 0) { // must go before bcf_sr_add_reader throw std::runtime_error {"failed to load region " + to_string(region)}; } if (bcf_sr_add_reader(sr.get(), file_path_.c_str()) != 1) { sr.release(); throw std::runtime_error {"failed to open file " + file_path_.string()}; } return count_records(sr); } HtslibBcfFacade::RecordIteratorPtrPair HtslibBcfFacade::iterate(const UnpackPolicy level) const { HtsBcfSrPtr sr {bcf_sr_init(), HtsSrsDeleter {}}; if (bcf_sr_add_reader(sr.get(), file_path_.c_str()) != 1) { const auto error = sr->errnum; sr.release(); if (error == idx_load_failed) { throw std::runtime_error {"failed to open index for file " + file_path_.string()}; } else { throw std::runtime_error {"failed to open file " + file_path_.string()}; } } return std::make_pair(std::make_unique<RecordIterator>(*this, std::move(sr), level), std::make_unique<RecordIterator>(*this)); } HtslibBcfFacade::RecordIteratorPtrPair HtslibBcfFacade::iterate(const std::string& contig, const UnpackPolicy level) const { HtsBcfSrPtr sr {bcf_sr_init(), HtsSrsDeleter {}}; if (bcf_sr_set_regions(sr.get(), contig.c_str(), 0) != 0) { throw std::runtime_error {"failed load contig " + contig}; } if (bcf_sr_add_reader(sr.get(), file_path_.c_str()) != 1) { const auto error = sr->errnum; sr.release(); if (error == idx_load_failed) { throw std::runtime_error {"failed to open index for file " + file_path_.string()}; } else { throw std::runtime_error {"failed to open file " + file_path_.string()}; } } return std::make_pair(std::make_unique<RecordIterator>(*this, std::move(sr), level), std::make_unique<RecordIterator>(*this)); } HtslibBcfFacade::RecordIteratorPtrPair HtslibBcfFacade::iterate(const GenomicRegion& region, const UnpackPolicy level) const { HtsBcfSrPtr sr {bcf_sr_init(), HtsSrsDeleter {}}; const auto region_str = to_string(region); if (bcf_sr_set_regions(sr.get(), region_str.c_str(), 0) != 0) { throw std::runtime_error {"failed load region " + region_str}; } if (bcf_sr_add_reader(sr.get(), file_path_.c_str()) != 1) { const auto error = sr->errnum; sr.release(); if (error == idx_load_failed) { throw std::runtime_error {"failed to open index for file " + file_path_.string()}; } else { throw std::runtime_error {"failed to open file " + file_path_.string()}; } } return std::make_pair(std::make_unique<RecordIterator>(*this, std::move(sr), level), std::make_unique<RecordIterator>(*this)); } HtslibBcfFacade::RecordContainer HtslibBcfFacade::fetch_records(const UnpackPolicy level) const { const auto n_records = count_records(); HtsBcfSrPtr sr {bcf_sr_init(), HtsSrsDeleter {}}; if (bcf_sr_add_reader(sr.get(), file_path_.c_str()) != 1) { sr.release(); throw std::runtime_error {"failed to open file " + file_path_.string()}; } return fetch_records(sr.get(), level, n_records); } HtslibBcfFacade::RecordContainer HtslibBcfFacade::fetch_records(const std::string& contig, const UnpackPolicy level) const { const auto n_records = count_records(contig); HtsBcfSrPtr sr {bcf_sr_init(), HtsSrsDeleter {}}; if (bcf_sr_set_regions(sr.get(), contig.c_str(), 0) != 0) { // must go before bcf_sr_add_reader throw std::runtime_error {"failed load contig " + contig}; } if (bcf_sr_add_reader(sr.get(), file_path_.c_str()) != 1) { sr.release(); throw std::runtime_error {"failed to open file " + file_path_.string()}; } return fetch_records(sr.get(), level, n_records); } HtslibBcfFacade::RecordContainer HtslibBcfFacade::fetch_records(const GenomicRegion& region, const UnpackPolicy level) const { const auto n_records = count_records(region); HtsBcfSrPtr sr {bcf_sr_init(), HtsSrsDeleter {}}; const auto region_str = to_string(region); if (bcf_sr_set_regions(sr.get(), region_str.c_str(), 0) != 0) { // must go before bcf_sr_add_reader throw std::runtime_error {"failed load region " + region_str}; } if (bcf_sr_add_reader(sr.get(), file_path_.c_str()) != 1) { sr.release(); throw std::runtime_error {"failed to open file " + file_path_.string()}; } return fetch_records(sr.get(), level, n_records); } auto hts_tag_type(const std::string& tag) { using namespace vcfspec::header::meta::tag; const static std::unordered_map<std::string, int> types { {filter, BCF_HL_FLT}, {info, BCF_HL_INFO}, {format, BCF_HL_FMT}, {contig, BCF_HL_CTG} }; return (types.count(tag) == 1) ? types.at(tag) : BCF_HL_STR; } void HtslibBcfFacade::write(const VcfHeader& header) { if (file_ == nullptr) { throw std::runtime_error {"HtslibBcfFacade: trying to write header to closed file"}; } auto hdr = bcf_hdr_init("w"); bcf_hdr_set_version(hdr, header.file_format().c_str()); for (auto& p : header.basic_fields()) { auto hrec = (bcf_hrec_t*) std::malloc(sizeof(bcf_hrec_t)); hrec->type = BCF_HL_GEN; hrec->key = malloc_copy(p.first); hrec->value = malloc_copy(p.second); hrec->nkeys = 0; hrec->keys = nullptr; hrec->vals = nullptr; bcf_hdr_add_hrec(hdr, hrec); } for (auto& tag : header.tags()) { const auto type = hts_tag_type(tag); for (auto fields : header.structured_fields(tag)) { auto hrec = (bcf_hrec_t*) std::malloc(sizeof(bcf_hrec_t)); hrec->type = type; hrec->key = malloc_copy(tag); hrec->nkeys = static_cast<int>(fields.size()); hrec->keys = (char**) std::malloc(sizeof(char*) * fields.size()); hrec->vals = (char**) std::malloc(sizeof(char*) * fields.size()); unsigned i {0}; // Make sure the reserved fields are written in the required order for (const auto& field : vcfspec::header::meta::struc::order) { if (fields.count(field) == 1) { hrec->keys[i] = malloc_copy(field); hrec->vals[i] = malloc_copy(fields[field]); fields.erase(field); ++i; } } // The rest of the fields go in whatever order they come in the map for (const auto& field : fields) { hrec->keys[i] = malloc_copy(field.first); hrec->vals[i] = malloc_copy(field.second); ++i; } hrec->value = nullptr; bcf_hdr_add_hrec(hdr, hrec); } } for (const auto& sample : header.samples()) { bcf_hdr_add_sample(hdr, sample.c_str()); } if (bcf_hdr_write(file_.get(), hdr) < 0) { throw std::runtime_error {"HtslibBcfFacade: header write failed"}; } header_.reset(hdr); samples_ = extract_samples(header_.get()); } void set_chrom(const bcf_hdr_t* header, bcf1_t* record, const std::string& chrom); void set_pos(bcf1_t* record, GenomicRegion::Position pos); void set_id(bcf1_t* record, const std::string& id); void set_alleles(const bcf_hdr_t* header, bcf1_t* record, const VcfRecord::NucleotideSequence& ref, const std::vector<VcfRecord::NucleotideSequence>& alts); void set_qual(bcf1_t* record, VcfRecord::QualityType qual); void set_filter(const bcf_hdr_t* header, bcf1_t* record, const std::vector<std::string>& filters); void set_info(const bcf_hdr_t* header, bcf1_t* dest, const VcfRecord& source); void set_samples(const bcf_hdr_t* header, bcf1_t* dest, const VcfRecord& source, const std::vector<std::string>& samples); void HtslibBcfFacade::write(const VcfRecord& record) { if (file_ == nullptr) { throw std::runtime_error {"HtslibBcfFacade: trying to write record to closed file"}; } if (header_ == nullptr) { throw std::runtime_error {"HtslibBcfFacade: trying to write record without a header"}; } const auto& contig = record.chrom(); if (bcf_hdr_get_hrec(header_.get(), BCF_HL_CTG, "ID", contig.c_str(), nullptr) == nullptr) { throw std::runtime_error {"HtslibBcfFacade: required contig header line missing for contig \"" + contig + "\""}; } auto hts_record = bcf_init(); set_chrom(header_.get(), hts_record, contig); set_pos(hts_record, record.pos() - 1); set_id(hts_record, record.id()); set_alleles(header_.get(), hts_record, record.ref(), record.alt()); if (record.qual()) { set_qual(hts_record, *record.qual()); } set_filter(header_.get(), hts_record, record.filter()); set_info(header_.get(), hts_record, record); if (record.num_samples() > 0) { set_samples(header_.get(), hts_record, record, samples_); } if (bcf_write(file_.get(), header_.get(), hts_record) < 0) { throw std::runtime_error {"HtslibBcfFacade: record write failed"}; } bcf_destroy(hts_record); } // HtslibBcfFacade::RecordIterator HtslibBcfFacade::RecordIterator::RecordIterator(const HtslibBcfFacade& facade) : facade_ {facade} , hts_iterator_ {nullptr} , level_ {} , record_ {nullptr} {} HtslibBcfFacade::RecordIterator::RecordIterator(const HtslibBcfFacade& facade, HtsBcfSrPtr hts_iterator, UnpackPolicy level) : facade_ {facade} , hts_iterator_ {std::move(hts_iterator)} , level_ {level} { if (bcf_sr_next_line(hts_iterator_.get())) { record_ = std::make_shared<VcfRecord>(facade_.get().fetch_record(hts_iterator_.get(), level_)); } else { hts_iterator_ = nullptr; } } HtslibBcfFacade::RecordIterator::reference HtslibBcfFacade::RecordIterator::operator*() const { return *record_; } HtslibBcfFacade::RecordIterator::pointer HtslibBcfFacade::RecordIterator::operator->() const { return record_.get(); } void HtslibBcfFacade::RecordIterator::next() { if (bcf_sr_next_line(hts_iterator_.get())) { *record_ = facade_.get().fetch_record(hts_iterator_.get(), level_); } else { hts_iterator_ = nullptr; } } HtslibBcfFacade::RecordIterator& HtslibBcfFacade::RecordIterator::operator++() { this->next(); return *this; } bool operator==(const HtslibBcfFacade::RecordIterator& lhs, const HtslibBcfFacade::RecordIterator& rhs) { return lhs.hts_iterator_ == rhs.hts_iterator_; } bool operator!=(const HtslibBcfFacade::RecordIterator& lhs, const HtslibBcfFacade::RecordIterator& rhs) { return !operator==(lhs, rhs); } // private and non-member methods std::unordered_map<std::string, std::string> extract_format(const bcf_hrec_t* line) { std::unordered_map<std::string, std::string> result {}; result.reserve(line->nkeys); for (decltype(line->nkeys) k {0}; k < line->nkeys; ++k) { if (std::strcmp(line->keys[k], "IDX") != 0) { result.emplace(line->keys[k], line->vals[k]); } } return result; } void extract_chrom(const bcf_hdr_t* header, const bcf1_t* record, VcfRecord::Builder& builder) { builder.set_chrom(bcf_hdr_id2name(header, record->rid)); } void set_chrom(const bcf_hdr_t* header, bcf1_t* record, const std::string& chrom) { record->rid = bcf_hdr_name2id(header, chrom.c_str()); } void extract_pos(const bcf1_t* record, VcfRecord::Builder& builder) { builder.set_pos(record->pos + 1); } void set_pos(bcf1_t* record, const GenomicRegion::Position pos) { record->pos = static_cast<std::uint32_t>(pos); } void extract_id(const bcf1_t* record, VcfRecord::Builder& builder) { builder.set_id(record->d.id); } void set_id(bcf1_t* record, const std::string& id) { record->d.id = malloc_copy(id); } void extract_ref(const bcf1_t* record, VcfRecord::Builder& builder) { builder.set_ref(record->d.allele[0]); } void set_alleles(const bcf_hdr_t* header, bcf1_t* record, const VcfRecord::NucleotideSequence& ref, const std::vector<VcfRecord::NucleotideSequence>& alts) { const auto num_alleles = alts.size() + 1; std::vector<const char*> alleles(num_alleles); alleles.front() = ref.c_str(); std::transform(std::begin(alts), std::end(alts), std::next(std::begin(alleles)), [] (const auto& allele) { return allele.c_str(); }); bcf_update_alleles(header, record, alleles.data(), static_cast<int>(num_alleles)); } void extract_alt(const bcf1_t* record, VcfRecord::Builder& builder) { const auto num_alleles = record->n_allele; std::vector<VcfRecord::NucleotideSequence> alleles {}; alleles.reserve(num_alleles - 1); // first is the reference for (unsigned i {1}; i < num_alleles; ++i) { alleles.emplace_back(record->d.allele[i]); } builder.set_alt(std::move(alleles)); } void extract_qual(const bcf1_t* record, VcfRecord::Builder& builder) { if (!std::isnan(record->qual)) { builder.set_qual(record->qual); } } void set_qual(bcf1_t* record, const VcfRecord::QualityType qual) { record->qual = (qual == -0) ? 0 : static_cast<float>(qual); } void extract_filter(const bcf_hdr_t* header, const bcf1_t* record, VcfRecord::Builder& builder) { std::vector<VcfRecord::KeyType> filter {}; filter.reserve(record->d.n_flt); for (decltype(record->d.n_flt) i {0}; i < record->d.n_flt; ++i) { filter.emplace_back(bcf_hdr_int2id(header, BCF_DT_ID, record->d.flt[i])); } builder.set_filter(std::move(filter)); } void set_filter(const bcf_hdr_t* header, bcf1_t* record, const std::vector<std::string>& filters) { for (const auto& filter : filters) { bcf_add_filter(header, record, bcf_hdr_id2int(header, BCF_DT_ID, filter.c_str())); } } void extract_info(const bcf_hdr_t* header, bcf1_t* record, VcfRecord::Builder& builder) { int* intinfo {nullptr}; float* floatinfo {nullptr}; char* stringinfo {nullptr}; int* flaginfo {nullptr}; // not actually populated builder.reserve_info(record->n_info); for (unsigned i {0}; i < record->n_info; ++i) { int nintinfo {0}, nfloatinfo {0}, nstringinfo {0}, nflaginfo {0}; const auto key_id = record->d.info[i].key; if (key_id >= header->n[BCF_DT_ID]) { throw std::runtime_error {"HtslibBcfFacade: found INFO key not present in header file"}; } const char* key {header->id[BCF_DT_ID][key_id].key}; std::vector<std::string> values {}; switch (bcf_hdr_id2type(header, BCF_HL_INFO, key_id)) { case BCF_HT_INT: { const auto num_values_written = bcf_get_info_int32(header, record, key, &intinfo, &nintinfo); if (num_values_written > 0) { values.reserve(num_values_written); std::transform(intinfo, intinfo + num_values_written, std::back_inserter(values), [](auto v) { return v != bcf_int32_missing ? std::to_string(v) : bcf_missing_str; }); } break; } case BCF_HT_REAL: { const auto num_values_written = bcf_get_info_float(header, record, key, &floatinfo, &nfloatinfo); if (num_values_written > 0) { values.reserve(num_values_written); std::transform(floatinfo, floatinfo + num_values_written, std::back_inserter(values), [] (auto v) { return v != bcf_float_missing ? std::to_string(v) : bcf_missing_str; }); } break; } case BCF_HT_STR: { const auto nchars = bcf_get_info_string(header, record, key, &stringinfo, &nstringinfo); if (nchars > 0) { std::string tmp(stringinfo, nchars); values = utils::split(tmp, vcfspec::info::valueSeperator); } break; } case BCF_HT_FLAG: { values.reserve(1); values.emplace_back((bcf_get_info_flag(header, record, key, &flaginfo, &nflaginfo) == 1) ? "1" : "0"); break; } } builder.set_info(key, std::move(values)); } if (intinfo != nullptr) std::free(intinfo); if (floatinfo != nullptr) std::free(floatinfo); if (stringinfo != nullptr) std::free(stringinfo); if (flaginfo != nullptr) std::free(flaginfo); } float get_bcf_float_missing() noexcept { float result; bcf_float_set_missing(result); return result; } void set_info(const bcf_hdr_t* header, bcf1_t* dest, const VcfRecord& source) { for (const auto& key : source.info_keys()) { const auto& values = source.info_value(key); const auto num_values = static_cast<int>(values.size()); static constexpr std::size_t defaultBufferCapacity {100}; switch (bcf_hdr_id2type(header, BCF_HL_INFO, bcf_hdr_id2int(header, BCF_DT_ID, key.c_str()))) { case BCF_HT_INT: { bc::small_vector<int, defaultBufferCapacity> vals(num_values); std::transform(std::cbegin(values), std::cend(values), std::begin(vals), [] (const auto& v) { return !is_missing(v) ? std::stoi(v) : bcf_int32_missing; }); bcf_update_info_int32(header, dest, key.c_str(), vals.data(), num_values); break; } case BCF_HT_REAL: { bc::small_vector<float, defaultBufferCapacity> vals(num_values); std::transform(std::cbegin(values), std::cend(values), std::begin(vals), [] (const auto& v) { return !is_missing(v) ? std::stof(v) : get_bcf_float_missing(); }); bcf_update_info_float(header, dest, key.c_str(), vals.data(), num_values); break; } case BCF_HT_STR: { // Can we also use small_vector here? const auto vals = utils::join(values, vcfspec::info::valueSeperator); bcf_update_info_string(header, dest, key.c_str(), vals.c_str()); break; } case BCF_HT_FLAG: { bcf_update_info_flag(header, dest, key.c_str(), "", values.empty() || values.front() == "1"); break; } } } } bool has_samples(const bcf_hdr_t* header) { return bcf_hdr_nsamples(header) > 0; } auto extract_format(const bcf_hdr_t* header, const bcf1_t* record) { std::vector<VcfRecord::KeyType> result {}; result.reserve(record->n_fmt); for (unsigned i {0}; i < record->n_fmt; ++i) { const auto key_id = record->d.fmt[i].id; if (key_id >= header->n[BCF_DT_ID]) { throw std::runtime_error {"HtslibBcfFacade: found FORMAT key not present in header file"}; } result.emplace_back(header->id[BCF_DT_ID][key_id].key); } return result; } void extract_samples(const bcf_hdr_t* header, bcf1_t* record, VcfRecord::Builder& builder) { auto format = extract_format(header, record); const auto num_samples = record->n_sample; builder.reserve_samples(num_samples); auto first_format = std::cbegin(format); if (format.front() == vcfspec::format::genotype) { // the first key must be GT if present int ngt {}, g {}; int* gt {nullptr}; bcf_get_genotypes(header, record, &gt, &ngt); // mallocs gt const auto max_ploidy = static_cast<unsigned>(record->d.fmt->n); for (unsigned sample {0}, i {0}; sample < num_samples; ++sample, i += max_ploidy) { std::vector<VcfRecord::NucleotideSequence> alleles {}; alleles.reserve(max_ploidy); for (unsigned p {0}; p < max_ploidy; ++p) { g = gt[i + p]; if (g == bcf_int32_vector_end) { alleles.shrink_to_fit(); break; } else if (bcf_gt_is_missing(g)) { alleles.push_back(bcf_missing_str); } else { const auto idx = bcf_gt_allele(g); if (idx < record->n_allele) { alleles.emplace_back(record->d.allele[idx]); } else { alleles.push_back(bcf_missing_str); } } } using Phasing = VcfRecord::Builder::Phasing; builder.set_genotype(header->samples[sample], std::move(alleles), bcf_gt_is_phased(g) ? Phasing::phased : Phasing::unphased); } std::free(gt); ++first_format; } int* intformat {nullptr}; float* floatformat {nullptr}; char** stringformat {nullptr}; int nintformat {}, nfloatformat {}, nstringformat {}; for (auto itr = first_format, end = std::cend(format); itr != end; ++itr) { const auto& key = *itr; std::vector<std::vector<std::string>> values(num_samples, std::vector<std::string> {}); switch (bcf_hdr_id2type(header, BCF_HL_FMT, bcf_hdr_id2int(header, BCF_DT_ID, key.c_str()))) { case BCF_HT_INT: { const auto num_values_written = bcf_get_format_int32(header, record, key.c_str(), &intformat, &nintformat); if (num_values_written > 0) { const auto num_values_per_sample = num_values_written / num_samples; auto ptr = intformat; for (unsigned sample {0}; sample < num_samples; ++sample, ptr += num_values_per_sample) { values[sample].reserve(num_values_per_sample); std::transform(ptr, ptr + num_values_per_sample, std::back_inserter(values[sample]), [] (auto v) { return v != bcf_int32_missing ? std::to_string(v) : bcf_missing_str; }); } } break; } case BCF_HT_REAL: { const auto num_values_written = bcf_get_format_float(header, record, key.c_str(), &floatformat, &nfloatformat); if (num_values_written > 0) { const auto num_values_per_sample = num_values_written / num_samples; auto ptr = floatformat; for (unsigned sample {0}; sample < num_samples; ++sample, ptr += num_values_per_sample) { values[sample].reserve(num_values_per_sample); std::transform(ptr, ptr + num_values_per_sample, std::back_inserter(values[sample]), [] (auto v) { return v != bcf_float_missing ? std::to_string(v) : bcf_missing_str; }); } } break; } case BCF_HT_STR: // TODO: Check this usage is correct. What if more than one value per sample? if (bcf_get_format_string(header, record, key.c_str(), &stringformat, &nstringformat) > 0) { unsigned sample {0}; std::for_each(stringformat, stringformat + num_samples, [&values, &sample] (const char* str) { values[sample++].emplace_back(str); }); } break; } for (unsigned sample {0}; sample < num_samples; ++sample) { builder.set_format(header->samples[sample], key, std::move(values[sample])); } } builder.set_format(std::move(format)); if (intformat != nullptr) std::free(intformat); if (floatformat != nullptr) std::free(floatformat); if (stringformat != nullptr) { // bcf_get_format_string allocates two arrays std::free(stringformat[0]); std::free(stringformat); } } template <typename T, typename Container> auto genotype_number(const T& allele, const Container& alleles, const bool is_phased) { if (is_missing(allele)) { return (is_phased) ? bcf_gt_missing + 1 : bcf_gt_missing; } const auto it = std::find(std::cbegin(alleles), std::cend(alleles), allele); const auto allele_num = 2 * static_cast<decltype(bcf_gt_missing)>(std::distance(std::cbegin(alleles), it)) + 2; return (is_phased) ? allele_num + 1 : allele_num; } auto max_format_cardinality(const VcfRecord& record, const VcfRecord::KeyType& key, const std::vector<std::string>& samples) { std::size_t result {0}; for (const auto& sample : samples) { result = std::max(result, record.get_sample_value(sample, key).size()); } return result; } float get_bcf_float_pad() noexcept { float result; bcf_float_set_vector_end(result); return result; } void set_samples(const bcf_hdr_t* header, bcf1_t* dest, const VcfRecord& source, const std::vector<std::string>& samples) { if (samples.empty()) return; const auto num_samples = static_cast<int>(source.num_samples()); const auto& format = source.format(); if (format.empty()) return; auto first_format = std::cbegin(format); if (*first_format == vcfspec::format::genotype) { const auto& alt_alleles = source.alt(); bc::small_vector<VcfRecord::NucleotideSequence, 5> alleles {}; alleles.reserve(alt_alleles.size() + 1); alleles.push_back(source.ref()); alleles.insert(std::end(alleles), std::cbegin(alt_alleles), std::cend(alt_alleles)); unsigned max_ploidy {}; for (const auto& sample : samples) { const auto p = source.ploidy(sample); if (p > max_ploidy) max_ploidy = p; } const auto ngt = num_samples * static_cast<int>(max_ploidy); bc::small_vector<int, 1'000> genotype(ngt); auto genotype_itr = std::begin(genotype); for (const auto& sample : samples) { const bool is_phased {source.is_sample_phased(sample)}; const auto& genotype = source.get_sample_value(sample, vcfspec::format::genotype); const auto ploidy = static_cast<unsigned>(genotype.size()); genotype_itr = std::transform(std::cbegin(genotype), std::cend(genotype), genotype_itr, [is_phased, &alleles] (const auto& allele) { return genotype_number(allele, alleles, is_phased); }); genotype_itr = std::fill_n(genotype_itr, max_ploidy - ploidy, bcf_int32_vector_end); } bcf_update_genotypes(header, dest, genotype.data(), ngt); ++first_format; } std::vector<std::string> str_buffer {}; std::for_each(first_format, std::cend(format), [&] (const auto& key) { const auto key_cardinality = source.format_cardinality(key); int num_values {}; if (key_cardinality) { num_values = *key_cardinality * num_samples; } else { num_values = max_format_cardinality(source, key, samples) * num_samples; } const auto num_values_per_sample = static_cast<std::size_t>(num_values / num_samples); static constexpr std::size_t defaultValueCapacity {1'000}; switch (bcf_hdr_id2type(header, BCF_HL_FMT, bcf_hdr_id2int(header, BCF_DT_ID, key.c_str()))) { case BCF_HT_INT: { static const int pad {bcf_int32_vector_end}; bc::small_vector<int, defaultValueCapacity> typed_values(num_values); auto value_itr = std::begin(typed_values); for (const auto& sample : samples) { const auto& values = source.get_sample_value(sample, key); value_itr = std::transform(std::cbegin(values), std::cend(values), value_itr, [] (const auto& v) { return !is_missing(v) ? std::stoi(v) : bcf_int32_missing; }); assert(values.size() <= num_values_per_sample); value_itr = std::fill_n(value_itr, num_values_per_sample - values.size(), pad); } bcf_update_format_int32(header, dest, key.c_str(), typed_values.data(), num_values); break; } case BCF_HT_REAL: { static const float pad {get_bcf_float_pad()}; bc::small_vector<float, defaultValueCapacity> typed_values(num_values); auto value_itr = std::begin(typed_values); for (const auto& sample : samples) { const auto& values = source.get_sample_value(sample, key); value_itr = std::transform(std::cbegin(values), std::cend(values), value_itr, [] (const auto& v) { return !is_missing(v) ? std::stof(v) : get_bcf_float_missing(); }); assert(values.size() <= num_values_per_sample); value_itr = std::fill_n(value_itr, num_values_per_sample - values.size(), pad); } bcf_update_format_float(header, dest, key.c_str(), typed_values.data(), num_values); break; } case BCF_HT_STR: { bc::small_vector<const char*, defaultValueCapacity> typed_values; if (key_cardinality && *key_cardinality <= 1) { typed_values.resize(num_values); auto value_itr = std::begin(typed_values); for (const auto& sample : samples) { const auto& values = source.get_sample_value(sample, key); value_itr = std::transform(std::cbegin(values), std::cend(values), value_itr, [] (const auto& value) { return value.c_str(); }); } } else { str_buffer.clear(); str_buffer.reserve(num_samples); for (const auto& sample : samples) { str_buffer.push_back(utils::join(source.get_sample_value(sample, key), vcfspec::format::valueSeperator)); } num_values = num_samples; typed_values.resize(num_values); std::transform(std::cbegin(str_buffer), std::cend(str_buffer), std::begin(typed_values), [] (const auto& value) { return value.c_str(); }); } bcf_update_format_string(header, dest, key.c_str(), typed_values.data(), num_values); break; } } }); } std::size_t HtslibBcfFacade::count_records(HtsBcfSrPtr& sr) const { std::size_t result {0}; while (bcf_sr_next_line(sr.get())) ++result; return result; } VcfRecord HtslibBcfFacade::fetch_record(const bcf_srs_t* sr, UnpackPolicy level) const { auto hts_record = bcf_sr_get_line(sr, 0); bcf_unpack(hts_record, level == UnpackPolicy::all ? BCF_UN_ALL : BCF_UN_SHR); VcfRecord::Builder record_builder {}; extract_chrom(header_.get(), hts_record, record_builder); extract_pos(hts_record, record_builder); extract_id(hts_record, record_builder); extract_ref(hts_record, record_builder); extract_alt(hts_record, record_builder); extract_qual(hts_record, record_builder); extract_filter(header_.get(), hts_record, record_builder); extract_info(header_.get(), hts_record, record_builder); if (level == UnpackPolicy::all && has_samples(header_.get())) { extract_samples(header_.get(), hts_record, record_builder); } return record_builder.build_once(); } HtslibBcfFacade::RecordContainer HtslibBcfFacade::fetch_records(bcf_srs_t* sr, const UnpackPolicy level, const std::size_t num_records) const { RecordContainer result {}; result.reserve(num_records); while (bcf_sr_next_line(sr)) { result.push_back(fetch_record(sr, level)); } return result; } } // namespace octopus
39.081192
133
0.601536
[ "vector", "transform" ]
3e8b5f43435c8ab45b2c72d301bba3b00c128f40
9,730
cpp
C++
src/Convert-harmony.cpp
johnnymac647/humlib
c67954045fb5570915d6a1c75d9a1e36cc9bdf93
[ "BSD-2-Clause" ]
19
2016-06-18T02:03:56.000Z
2022-02-23T17:26:32.000Z
src/Convert-harmony.cpp
johnnymac647/humlib
c67954045fb5570915d6a1c75d9a1e36cc9bdf93
[ "BSD-2-Clause" ]
43
2017-03-09T07:32:12.000Z
2022-03-23T20:18:35.000Z
src/Convert-harmony.cpp
johnnymac647/humlib
c67954045fb5570915d6a1c75d9a1e36cc9bdf93
[ "BSD-2-Clause" ]
5
2019-11-14T22:24:02.000Z
2021-09-07T18:27:21.000Z
// // Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu> // Creation Date: Mon Aug 7 20:37:16 EDT 2017 // Last Modified: Mon Aug 7 20:37:19 EDT 2017 // Filename: Convert-harmony.cpp // URL: https://github.com/craigsapp/humlib/blob/master/src/Convert-harmony.cpp // Syntax: C++11; humlib // vim: syntax=cpp ts=3 noexpandtab nowrap // // Description: Conversions related to harmony. // #include "Convert.h" #include "HumRegex.h" using namespace std; namespace hum { // START_MERGE ////////////////////////////// // // Convert::majorScaleBase40 -- Return the base-40 scale degree // tonic-intervals for each note in a major scale. The input is the // base-40 pitch-class of the root. The default input is 0, which // will return a list of the intervals for each scale degree to the // tonic of the key. // vector<int> Convert::majorScaleBase40(void) { return {0, 6, 12, 17, 23, 29, 35}; } ////////////////////////////// // // Convert::minorHScaleBase40 -- Return the base-40 scale degree // tonic-intervals for each note in a harmonic minor scale. The input // is the base-40 pitch-class of the root. The default input is 0, which // will return a list of the intervals for each scale degree to the // tonic of the key. // vector<int> Convert::minorHScaleBase40(void) { return {0, 6, 11, 17, 23, 28, 35}; } ////////////////////////////// // // Convert::keyToBase40 -- convert a Humdrum **kern key designation into // a base-40 integer. Positive values are for major keys and negative // values are for minor keys. (C-double-flat major is 40 rather than 0). // Returns 0 if no legitimate key was found. // int Convert::keyToBase40(const string& key) { string token; auto loc = key.find(":"); if (loc != std::string::npos) { token = key.substr(0, loc); } else { token = key; } int base40 = Convert::kernToBase40(token); if (base40 < 0) { return 0; } if (base40 >= 160) { base40 = -(base40 % 40); if (base40 == 0) { base40 = -40; } } else { base40 = base40 % 40; if (base40 == 0) { base40 = 40; } } return base40; } ////////////////////////////// // // Convert::keyToInversion -- Extract the inversion from a **harm token. // Root position is 0, first inversion is 1, etc. up to 6th inversion // for 13th chords. // int Convert::keyToInversion(const string& harm) { for (char ch : harm) { if ((ch >= 'a') && (ch <= 'g')) { return ch - 'a'; } } return 0; } ////////////////////////////// // // Convert::chromaticAlteration -- Return the sum of "#" minus "-" in the string. // int Convert::chromaticAlteration(const string& content) { int sum = 0; for (char ch : content) { switch (ch) { case '#': sum++; break; case '-': sum--; break; } } return sum; } ////////////////////////////// // // Convert::makeAdjustedKeyRootAndMode -- // void Convert::makeAdjustedKeyRootAndMode(const string& secondary, int& keyroot, int& keymode) { vector<int> majorkey = Convert::majorScaleBase40(); vector<int> minorkey = Convert::minorHScaleBase40(); vector<string> roots; HumRegex hre; hre.split(roots, secondary, "/"); for (int i=0; i<(int)roots.size(); i++) { string piece = roots[(int)roots.size() - i - 1]; int number = Convert::romanNumeralToInteger(piece); if (number == 0) { continue; } else if (number > 7) { number = (number - 1) % 7; } else { number -= 1; } if (keymode == 0) { // major key keyroot += majorkey[number]; } else { keyroot += minorkey[number]; } int alteration = chromaticAlteration(piece); keyroot += alteration; if ((!piece.empty()) && isupper(piece[0])) { keymode = 0; // major } else { keymode = 1; // minor } } keyroot = keyroot % 40; } ////////////////////////////// // // Convert::harmToBase40 -- Convert a **harm chord into a list of // pitch classes contained in the chord. The output is a vector // that contains the root pitch class in the first slot, then // the successive chord tones after that. If the vector is empty // then there was some sort of syntax error in the **harm token. // The bass note is placed in the 3rd octave and other pitch classes // in the chord are placed in the 4th octave. // vector<int> Convert::harmToBase40(const string& harm, const string& key) { int keyroot = Convert::keyToBase40(key); int keymode = 0; // major key if (keyroot < 0) { keyroot = -keyroot; keymode = 1; // minor key } return harmToBase40(harm, keyroot, keymode); } vector<int> Convert::harmToBase40(const string& harm, int keyroot, int keymode) { // Create a tonic-interval list of the scale-degrees: vector<int> degrees; if (keymode == 1) { degrees = Convert::minorHScaleBase40(); } else { degrees = Convert::majorScaleBase40(); } // Remove any **recip prefixed to token: string newharm = harm; HumRegex hre; if (hre.search(harm, R"(^[{}\d%._\][]+(.*))")) { newharm = hre.getMatch(1); } // Remove alternate chord labels: string single; auto loc = newharm.find('['); if (loc != string::npos) { single = newharm.substr(0, loc); } else { single = newharm; } // Split off secondary dominant qualifications string cbase; // base chord string secondary; // secondary chord qualifiers loc = single.find("/"); if (loc != string::npos) { cbase = single.substr(0, loc); secondary = single.substr(loc+1, string::npos); } else { cbase = single; } // Calculate interval offset for secondary dominants: int newkeyroot = keyroot; int newkeymode = keymode; if (!secondary.empty()) { makeAdjustedKeyRootAndMode(secondary, newkeyroot, newkeymode); } int rootdeg = -1; // chord root scale degree in key int degalt = 0; // degree alteration vector<char> chars(256, 0); for (auto ch : cbase) { chars[ch]++; } rootdeg = -1; // invalid scale degree degalt = chars['#'] - chars['-']; int vcount = chars['V'] + chars['v']; int icount = chars['I'] + chars['i']; if (vcount == 1) { switch (icount) { case 0: rootdeg = 4; break; // V case 1: if (cbase.find("IV") != string::npos) { rootdeg = 3; break; // IV } else if (cbase.find("iv") != string::npos) { rootdeg = 3; break; // iv } else { rootdeg = 5; break; // VI/vi } case 2: rootdeg = 6; break; // VII case 3: rootdeg = 0; break; // VIII (I) } } else { switch (icount) { case 0: // N, Fr, Gn, Lt, Tr if (chars['N']) { // Neapolitan (flat-second scale degree) rootdeg = 1; // -II degalt += -1; // -II } else if (chars['L'] || chars['F'] || chars['G']) { // augmented 6th chord on -VII rootdeg = 5; // fixed to -VI of major scale: if (newkeymode == 0) { // major degalt += -1; } else { // minor // already at -VI in minor degalt += 0; } } break; case 1: rootdeg = 0; break; // I case 2: rootdeg = 1; break; // II case 3: rootdeg = 2; break; // III } } int inversion = Convert::keyToInversion(single); vector<int> output; if (rootdeg < 0) { return output; } int root = degrees.at(rootdeg) + newkeyroot; output.push_back(root); int int3 = -1; int int5 = 23; // assume a perfect 5th int int7 = -1; int int9 = -1; // int int11 = -1; // int int13 = -1; // determine the third's interval if (chars['i'] || chars['v']) { // minor third int3 = 11; } else if (chars['I'] || chars['V']) { // major third int3 = 12; } else if (chars['N']) { // neapolitan (major triad) int3 = 12; int5 = 23; } else if (chars['G']) { // german aug. 6th chord int3 = 12; int5 = 23; int7 = 30; // technically on 6th } else if (chars['L']) { // Italian aug. 6th chord int3 = 12; int5 = -1; int7 = 30; // technically on 6th } else if (chars['F']) { // French aug. 6th chord int3 = 12; int5 = 18; // technically on 4th int7 = 30; // technically on 6th } // determine the fifth's interval if (chars['o']) { // diminished int5 = 22; } if (chars['+']) { // augmented int5 = 24; } if (int3 > 0) { output.push_back(int3 + output[0]); } if (int5 > 0) { output.push_back(int5 + output[0]); } ///// determine higher chord notes // determine the seventh if (chars['7']) { int7 = degrees.at((rootdeg + 6) % 7) - degrees.at(rootdeg); if (int7 < 0) { int7 += 40; } if (hre.search(cbase, "(A+|D+|M|m)7")) { string quality = hre.getMatch(1); if (quality == "M") { int7 = 35; } else if (quality == "m") { int7 = 34; } else if (quality[0] == 'D') { int7 = 34 - (int)quality.size(); } else if (quality[0] == 'A') { int7 = 35 + (int)quality.size(); } } output.push_back(int7 % 40 + output[0]); } // determine the 9th if (chars['9']) { HumRegex hre; int9 = degrees.at((rootdeg + 1) % 7) - degrees.at(rootdeg); if (int9 < 0) { int9 += 40; } if (hre.search(cbase, "(A+|D+|M|m)9")) { string quality = hre.getMatch(1); if (quality == "M") { int9 = 46; } else if (quality == "m") { int9 = 45; } else if (quality[0] == 'D') { int9 = 45 - (int)quality.size(); } else if (quality[0] == 'A') { int9 = 46 + (int)quality.size(); } } output.push_back(int9 + output[0]); } // add inverion if (inversion < (int)output.size()) { output[inversion] = output[inversion] % 40 + 3 * 40; } int oct = 4; int lastvalue = -1; for (int i=0; i<(int)output.size(); i++) { if (i != inversion) { output[i] = output[i] % 40 + oct * 40; if (output[i] < lastvalue) { output[i] += 40; } if (output[i] < lastvalue) { output[i] += 40; } lastvalue = output[i]; } else { } } return output; } // END_MERGE } // end namespace hum
22.680653
89
0.58335
[ "vector" ]
3e8cf9fd9f23e3441caed509ab643e805773df18
9,869
cpp
C++
lldb/source/Plugins/Process/NetBSD/NativeThreadNetBSD.cpp
LaudateCorpus1/llvm-project
ff2e0f0c1112558b3f30d8afec7c9882c33c79e3
[ "Apache-2.0" ]
null
null
null
lldb/source/Plugins/Process/NetBSD/NativeThreadNetBSD.cpp
LaudateCorpus1/llvm-project
ff2e0f0c1112558b3f30d8afec7c9882c33c79e3
[ "Apache-2.0" ]
null
null
null
lldb/source/Plugins/Process/NetBSD/NativeThreadNetBSD.cpp
LaudateCorpus1/llvm-project
ff2e0f0c1112558b3f30d8afec7c9882c33c79e3
[ "Apache-2.0" ]
null
null
null
//===-- NativeThreadNetBSD.cpp --------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "NativeThreadNetBSD.h" #include "NativeRegisterContextNetBSD.h" #include "NativeProcessNetBSD.h" #include "Plugins/Process/POSIX/CrashReason.h" #include "Plugins/Process/POSIX/ProcessPOSIXLog.h" #include "lldb/Utility/LLDBAssert.h" #include "lldb/Utility/RegisterValue.h" #include "lldb/Utility/State.h" #include "llvm/Support/Errno.h" // clang-format off #include <sys/types.h> #include <sys/ptrace.h> // clang-format on #include <sstream> // clang-format off #include <sys/types.h> #include <sys/sysctl.h> // clang-format on using namespace lldb; using namespace lldb_private; using namespace lldb_private::process_netbsd; NativeThreadNetBSD::NativeThreadNetBSD(NativeProcessNetBSD &process, lldb::tid_t tid) : NativeThreadProtocol(process, tid), m_state(StateType::eStateInvalid), m_stop_info(), m_reg_context_up( NativeRegisterContextNetBSD::CreateHostNativeRegisterContextNetBSD(process.GetArchitecture(), *this) ), m_stop_description() {} Status NativeThreadNetBSD::Resume() { Status ret = NativeProcessNetBSD::PtraceWrapper(PT_RESUME, m_process.GetID(), nullptr, GetID()); if (!ret.Success()) return ret; ret = NativeProcessNetBSD::PtraceWrapper(PT_CLEARSTEP, m_process.GetID(), nullptr, GetID()); if (ret.Success()) SetRunning(); return ret; } Status NativeThreadNetBSD::SingleStep() { Status ret = NativeProcessNetBSD::PtraceWrapper(PT_RESUME, m_process.GetID(), nullptr, GetID()); if (!ret.Success()) return ret; ret = NativeProcessNetBSD::PtraceWrapper(PT_SETSTEP, m_process.GetID(), nullptr, GetID()); if (ret.Success()) SetStepping(); return ret; } Status NativeThreadNetBSD::Suspend() { Status ret = NativeProcessNetBSD::PtraceWrapper(PT_SUSPEND, m_process.GetID(), nullptr, GetID()); if (ret.Success()) SetStopped(); return ret; } void NativeThreadNetBSD::SetStoppedBySignal(uint32_t signo, const siginfo_t *info) { Log *log = GetLog(POSIXLog::Thread); LLDB_LOG(log, "tid = {0} in called with signal {1}", GetID(), signo); SetStopped(); m_stop_info.reason = StopReason::eStopReasonSignal; m_stop_info.details.signal.signo = signo; m_stop_description.clear(); if (info) { switch (signo) { case SIGSEGV: case SIGBUS: case SIGFPE: case SIGILL: const auto reason = GetCrashReason(*info); m_stop_description = GetCrashReasonString(reason, *info); break; } } } void NativeThreadNetBSD::SetStoppedByBreakpoint() { SetStopped(); m_stop_info.reason = StopReason::eStopReasonBreakpoint; m_stop_info.details.signal.signo = SIGTRAP; } void NativeThreadNetBSD::SetStoppedByTrace() { SetStopped(); m_stop_info.reason = StopReason::eStopReasonTrace; m_stop_info.details.signal.signo = SIGTRAP; } void NativeThreadNetBSD::SetStoppedByExec() { SetStopped(); m_stop_info.reason = StopReason::eStopReasonExec; m_stop_info.details.signal.signo = SIGTRAP; } void NativeThreadNetBSD::SetStoppedByWatchpoint(uint32_t wp_index) { lldbassert(wp_index != LLDB_INVALID_INDEX32 && "wp_index cannot be invalid"); std::ostringstream ostr; ostr << GetRegisterContext().GetWatchpointAddress(wp_index) << " "; ostr << wp_index; ostr << " " << GetRegisterContext().GetWatchpointHitAddress(wp_index); SetStopped(); m_stop_description = ostr.str(); m_stop_info.reason = StopReason::eStopReasonWatchpoint; m_stop_info.details.signal.signo = SIGTRAP; } void NativeThreadNetBSD::SetStoppedByFork(lldb::pid_t child_pid, lldb::tid_t child_tid) { SetStopped(); m_stop_info.reason = StopReason::eStopReasonFork; m_stop_info.details.fork.child_pid = child_pid; m_stop_info.details.fork.child_tid = child_tid; } void NativeThreadNetBSD::SetStoppedByVFork(lldb::pid_t child_pid, lldb::tid_t child_tid) { SetStopped(); m_stop_info.reason = StopReason::eStopReasonVFork; m_stop_info.details.fork.child_pid = child_pid; m_stop_info.details.fork.child_tid = child_tid; } void NativeThreadNetBSD::SetStoppedByVForkDone() { SetStopped(); m_stop_info.reason = StopReason::eStopReasonVForkDone; } void NativeThreadNetBSD::SetStoppedWithNoReason() { SetStopped(); m_stop_info.reason = StopReason::eStopReasonNone; m_stop_info.details.signal.signo = 0; } void NativeThreadNetBSD::SetStopped() { const StateType new_state = StateType::eStateStopped; m_state = new_state; m_stop_description.clear(); } void NativeThreadNetBSD::SetRunning() { m_state = StateType::eStateRunning; m_stop_info.reason = StopReason::eStopReasonNone; } void NativeThreadNetBSD::SetStepping() { m_state = StateType::eStateStepping; m_stop_info.reason = StopReason::eStopReasonNone; } std::string NativeThreadNetBSD::GetName() { Log *log = GetLog(POSIXLog::Thread); #ifdef PT_LWPSTATUS struct ptrace_lwpstatus info = {}; info.pl_lwpid = m_tid; Status error = NativeProcessNetBSD::PtraceWrapper( PT_LWPSTATUS, static_cast<int>(m_process.GetID()), &info, sizeof(info)); if (error.Fail()) { return ""; } return info.pl_name; #else std::vector<struct kinfo_lwp> infos; int mib[5] = {CTL_KERN, KERN_LWP, static_cast<int>(m_process.GetID()), sizeof(struct kinfo_lwp), 0}; size_t size; if (::sysctl(mib, 5, nullptr, &size, nullptr, 0) == -1 || size == 0) { LLDB_LOG(log, "sysctl() for LWP info size failed: {0}", llvm::sys::StrError()); return ""; } mib[4] = size / sizeof(size_t); infos.resize(size / sizeof(struct kinfo_lwp)); if (sysctl(mib, 5, infos.data(), &size, NULL, 0) == -1 || size == 0) { LLDB_LOG(log, "sysctl() for LWP info failed: {0}", llvm::sys::StrError()); return ""; } size_t nlwps = size / sizeof(struct kinfo_lwp); for (size_t i = 0; i < nlwps; i++) { if (static_cast<lldb::tid_t>(infos[i].l_lid) == m_tid) { return infos[i].l_name; } } LLDB_LOG(log, "unable to find lwp {0} in LWP infos", m_tid); return ""; #endif } lldb::StateType NativeThreadNetBSD::GetState() { return m_state; } bool NativeThreadNetBSD::GetStopReason(ThreadStopInfo &stop_info, std::string &description) { Log *log = GetLog(POSIXLog::Thread); description.clear(); switch (m_state) { case eStateStopped: case eStateCrashed: case eStateExited: case eStateSuspended: case eStateUnloaded: stop_info = m_stop_info; description = m_stop_description; return true; case eStateInvalid: case eStateConnected: case eStateAttaching: case eStateLaunching: case eStateRunning: case eStateStepping: case eStateDetached: LLDB_LOG(log, "tid = {0} in state {1} cannot answer stop reason", GetID(), StateAsCString(m_state)); return false; } llvm_unreachable("unhandled StateType!"); } NativeRegisterContextNetBSD &NativeThreadNetBSD::GetRegisterContext() { assert(m_reg_context_up); return *m_reg_context_up; } Status NativeThreadNetBSD::SetWatchpoint(lldb::addr_t addr, size_t size, uint32_t watch_flags, bool hardware) { assert(m_state == eStateStopped); if (!hardware) return Status("not implemented"); Status error = RemoveWatchpoint(addr); if (error.Fail()) return error; uint32_t wp_index = GetRegisterContext().SetHardwareWatchpoint(addr, size, watch_flags); if (wp_index == LLDB_INVALID_INDEX32) return Status("Setting hardware watchpoint failed."); m_watchpoint_index_map.insert({addr, wp_index}); return Status(); } Status NativeThreadNetBSD::RemoveWatchpoint(lldb::addr_t addr) { auto wp = m_watchpoint_index_map.find(addr); if (wp == m_watchpoint_index_map.end()) return Status(); uint32_t wp_index = wp->second; m_watchpoint_index_map.erase(wp); if (GetRegisterContext().ClearHardwareWatchpoint(wp_index)) return Status(); return Status("Clearing hardware watchpoint failed."); } Status NativeThreadNetBSD::SetHardwareBreakpoint(lldb::addr_t addr, size_t size) { assert(m_state == eStateStopped); Status error = RemoveHardwareBreakpoint(addr); if (error.Fail()) return error; uint32_t bp_index = GetRegisterContext().SetHardwareBreakpoint(addr, size); if (bp_index == LLDB_INVALID_INDEX32) return Status("Setting hardware breakpoint failed."); m_hw_break_index_map.insert({addr, bp_index}); return Status(); } Status NativeThreadNetBSD::RemoveHardwareBreakpoint(lldb::addr_t addr) { auto bp = m_hw_break_index_map.find(addr); if (bp == m_hw_break_index_map.end()) return Status(); uint32_t bp_index = bp->second; if (GetRegisterContext().ClearHardwareBreakpoint(bp_index)) { m_hw_break_index_map.erase(bp); return Status(); } return Status("Clearing hardware breakpoint failed."); } llvm::Error NativeThreadNetBSD::CopyWatchpointsFrom(NativeThreadNetBSD &source) { llvm::Error s = GetRegisterContext().CopyHardwareWatchpointsFrom( source.GetRegisterContext()); if (!s) { m_watchpoint_index_map = source.m_watchpoint_index_map; m_hw_break_index_map = source.m_hw_break_index_map; } return s; }
30.088415
100
0.679907
[ "vector" ]
3e8fb902a3eed61ea19d970e66cf6d87041f4081
1,934
cpp
C++
src/utils.cpp
mediathekview/simple-redirect-loadbalancer
46302d510c3c2580783d6682a7ff6f783e79f1ce
[ "MIT" ]
null
null
null
src/utils.cpp
mediathekview/simple-redirect-loadbalancer
46302d510c3c2580783d6682a7ff6f783e79f1ce
[ "MIT" ]
null
null
null
src/utils.cpp
mediathekview/simple-redirect-loadbalancer
46302d510c3c2580783d6682a7ff6f783e79f1ce
[ "MIT" ]
1
2019-01-31T17:43:19.000Z
2019-01-31T17:43:19.000Z
// // Created by Christian Franzke on 2019-01-29. // #include "utils.h" #include <syslog.h> #include <iostream> #include <vector> #include <boost/format.hpp> #include <boost/algorithm/string.hpp> using namespace boost::algorithm; /** * Thread pool used for keeping syslog off the main exec thread. */ static boost::asio::thread_pool syslog_pool ( std::thread::hardware_concurrency() ); void log ( log_level level, std::string msg ) { std::string output = "mv_redirect_server"; switch ( level ) { case WARNING: output += " WARNING: "; break; case INFO: output += " INFO: "; break; case ERROR: output += " ERROR: "; break; } boost::asio::post ( syslog_pool, [/*level, */msg, output]() { std::cerr << output << msg << std::endl; //syslog ( level, "%s", msg.c_str() ); } ); } void fail ( boost::system::error_code ec, char const *what ) { try { static boost::format formatter ( "%1: %2" ); formatter % what % ec.message(); log ( ERROR, formatter.str() ); } catch ( boost::io::bad_format_string& ) { log ( ERROR, "Failed to format string in fail()" ); } catch ( std::exception& e ) { log ( ERROR, e.what() ); } catch ( ... ) { log ( ERROR, "Unknown exception in fail()" ); } } /** * Do some basic checks on destination. * Those things should not occur in our destination */ bool destination_is_invalid ( const std::string& destination ) { if ( contains ( destination, ".php" ) ) return true; if ( contains ( destination, ".html" ) ) return true; if ( contains ( destination, ".js" ) ) return true; if ( contains ( destination, "127.0.0.1" ) ) return true; if ( contains ( destination, "wget" ) ) return true; if ( contains ( destination, "curl" ) ) return true; return false; }
23.876543
84
0.572906
[ "vector" ]
3e94b3f2db9259f67fc789d11b23cb739d414a52
4,095
cpp
C++
aws-cpp-sdk-route53/source/model/GeoLocationDetails.cpp
bswhite1/aws-sdk-cpp
a050168cf8f7f6ea920d52894eaad186953cb27b
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-route53/source/model/GeoLocationDetails.cpp
bswhite1/aws-sdk-cpp
a050168cf8f7f6ea920d52894eaad186953cb27b
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-route53/source/model/GeoLocationDetails.cpp
bswhite1/aws-sdk-cpp
a050168cf8f7f6ea920d52894eaad186953cb27b
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/route53/model/GeoLocationDetails.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <utility> using namespace Aws::Utils::Xml; using namespace Aws::Utils; namespace Aws { namespace Route53 { namespace Model { GeoLocationDetails::GeoLocationDetails() : m_continentCodeHasBeenSet(false), m_continentNameHasBeenSet(false), m_countryCodeHasBeenSet(false), m_countryNameHasBeenSet(false), m_subdivisionCodeHasBeenSet(false), m_subdivisionNameHasBeenSet(false) { } GeoLocationDetails::GeoLocationDetails(const XmlNode& xmlNode) : m_continentCodeHasBeenSet(false), m_continentNameHasBeenSet(false), m_countryCodeHasBeenSet(false), m_countryNameHasBeenSet(false), m_subdivisionCodeHasBeenSet(false), m_subdivisionNameHasBeenSet(false) { *this = xmlNode; } GeoLocationDetails& GeoLocationDetails::operator =(const XmlNode& xmlNode) { XmlNode resultNode = xmlNode; if(!resultNode.IsNull()) { XmlNode continentCodeNode = resultNode.FirstChild("ContinentCode"); if(!continentCodeNode.IsNull()) { m_continentCode = continentCodeNode.GetText(); m_continentCodeHasBeenSet = true; } XmlNode continentNameNode = resultNode.FirstChild("ContinentName"); if(!continentNameNode.IsNull()) { m_continentName = continentNameNode.GetText(); m_continentNameHasBeenSet = true; } XmlNode countryCodeNode = resultNode.FirstChild("CountryCode"); if(!countryCodeNode.IsNull()) { m_countryCode = countryCodeNode.GetText(); m_countryCodeHasBeenSet = true; } XmlNode countryNameNode = resultNode.FirstChild("CountryName"); if(!countryNameNode.IsNull()) { m_countryName = countryNameNode.GetText(); m_countryNameHasBeenSet = true; } XmlNode subdivisionCodeNode = resultNode.FirstChild("SubdivisionCode"); if(!subdivisionCodeNode.IsNull()) { m_subdivisionCode = subdivisionCodeNode.GetText(); m_subdivisionCodeHasBeenSet = true; } XmlNode subdivisionNameNode = resultNode.FirstChild("SubdivisionName"); if(!subdivisionNameNode.IsNull()) { m_subdivisionName = subdivisionNameNode.GetText(); m_subdivisionNameHasBeenSet = true; } } return *this; } void GeoLocationDetails::AddToNode(XmlNode& parentNode) const { Aws::StringStream ss; if(m_continentCodeHasBeenSet) { XmlNode continentCodeNode = parentNode.CreateChildElement("ContinentCode"); continentCodeNode.SetText(m_continentCode); } if(m_continentNameHasBeenSet) { XmlNode continentNameNode = parentNode.CreateChildElement("ContinentName"); continentNameNode.SetText(m_continentName); } if(m_countryCodeHasBeenSet) { XmlNode countryCodeNode = parentNode.CreateChildElement("CountryCode"); countryCodeNode.SetText(m_countryCode); } if(m_countryNameHasBeenSet) { XmlNode countryNameNode = parentNode.CreateChildElement("CountryName"); countryNameNode.SetText(m_countryName); } if(m_subdivisionCodeHasBeenSet) { XmlNode subdivisionCodeNode = parentNode.CreateChildElement("SubdivisionCode"); subdivisionCodeNode.SetText(m_subdivisionCode); } if(m_subdivisionNameHasBeenSet) { XmlNode subdivisionNameNode = parentNode.CreateChildElement("SubdivisionName"); subdivisionNameNode.SetText(m_subdivisionName); } } } // namespace Model } // namespace Route53 } // namespace Aws
28.241379
82
0.747009
[ "model" ]
3e96c5128d764468a2c40b4199d46c5068a79b7f
7,607
cpp
C++
yunjing/src/v20180228/model/HistoryAccount.cpp
li5ch/tencentcloud-sdk-cpp
12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4
[ "Apache-2.0" ]
null
null
null
yunjing/src/v20180228/model/HistoryAccount.cpp
li5ch/tencentcloud-sdk-cpp
12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4
[ "Apache-2.0" ]
null
null
null
yunjing/src/v20180228/model/HistoryAccount.cpp
li5ch/tencentcloud-sdk-cpp
12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/yunjing/v20180228/model/HistoryAccount.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Yunjing::V20180228::Model; using namespace rapidjson; using namespace std; HistoryAccount::HistoryAccount() : m_idHasBeenSet(false), m_uuidHasBeenSet(false), m_machineIpHasBeenSet(false), m_machineNameHasBeenSet(false), m_usernameHasBeenSet(false), m_modifyTypeHasBeenSet(false), m_modifyTimeHasBeenSet(false) { } CoreInternalOutcome HistoryAccount::Deserialize(const Value &value) { string requestId = ""; if (value.HasMember("Id") && !value["Id"].IsNull()) { if (!value["Id"].IsUint64()) { return CoreInternalOutcome(Error("response `HistoryAccount.Id` IsUint64=false incorrectly").SetRequestId(requestId)); } m_id = value["Id"].GetUint64(); m_idHasBeenSet = true; } if (value.HasMember("Uuid") && !value["Uuid"].IsNull()) { if (!value["Uuid"].IsString()) { return CoreInternalOutcome(Error("response `HistoryAccount.Uuid` IsString=false incorrectly").SetRequestId(requestId)); } m_uuid = string(value["Uuid"].GetString()); m_uuidHasBeenSet = true; } if (value.HasMember("MachineIp") && !value["MachineIp"].IsNull()) { if (!value["MachineIp"].IsString()) { return CoreInternalOutcome(Error("response `HistoryAccount.MachineIp` IsString=false incorrectly").SetRequestId(requestId)); } m_machineIp = string(value["MachineIp"].GetString()); m_machineIpHasBeenSet = true; } if (value.HasMember("MachineName") && !value["MachineName"].IsNull()) { if (!value["MachineName"].IsString()) { return CoreInternalOutcome(Error("response `HistoryAccount.MachineName` IsString=false incorrectly").SetRequestId(requestId)); } m_machineName = string(value["MachineName"].GetString()); m_machineNameHasBeenSet = true; } if (value.HasMember("Username") && !value["Username"].IsNull()) { if (!value["Username"].IsString()) { return CoreInternalOutcome(Error("response `HistoryAccount.Username` IsString=false incorrectly").SetRequestId(requestId)); } m_username = string(value["Username"].GetString()); m_usernameHasBeenSet = true; } if (value.HasMember("ModifyType") && !value["ModifyType"].IsNull()) { if (!value["ModifyType"].IsString()) { return CoreInternalOutcome(Error("response `HistoryAccount.ModifyType` IsString=false incorrectly").SetRequestId(requestId)); } m_modifyType = string(value["ModifyType"].GetString()); m_modifyTypeHasBeenSet = true; } if (value.HasMember("ModifyTime") && !value["ModifyTime"].IsNull()) { if (!value["ModifyTime"].IsString()) { return CoreInternalOutcome(Error("response `HistoryAccount.ModifyTime` IsString=false incorrectly").SetRequestId(requestId)); } m_modifyTime = string(value["ModifyTime"].GetString()); m_modifyTimeHasBeenSet = true; } return CoreInternalOutcome(true); } void HistoryAccount::ToJsonObject(Value &value, Document::AllocatorType& allocator) const { if (m_idHasBeenSet) { Value iKey(kStringType); string key = "Id"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_id, allocator); } if (m_uuidHasBeenSet) { Value iKey(kStringType); string key = "Uuid"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_uuid.c_str(), allocator).Move(), allocator); } if (m_machineIpHasBeenSet) { Value iKey(kStringType); string key = "MachineIp"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_machineIp.c_str(), allocator).Move(), allocator); } if (m_machineNameHasBeenSet) { Value iKey(kStringType); string key = "MachineName"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_machineName.c_str(), allocator).Move(), allocator); } if (m_usernameHasBeenSet) { Value iKey(kStringType); string key = "Username"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_username.c_str(), allocator).Move(), allocator); } if (m_modifyTypeHasBeenSet) { Value iKey(kStringType); string key = "ModifyType"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_modifyType.c_str(), allocator).Move(), allocator); } if (m_modifyTimeHasBeenSet) { Value iKey(kStringType); string key = "ModifyTime"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_modifyTime.c_str(), allocator).Move(), allocator); } } uint64_t HistoryAccount::GetId() const { return m_id; } void HistoryAccount::SetId(const uint64_t& _id) { m_id = _id; m_idHasBeenSet = true; } bool HistoryAccount::IdHasBeenSet() const { return m_idHasBeenSet; } string HistoryAccount::GetUuid() const { return m_uuid; } void HistoryAccount::SetUuid(const string& _uuid) { m_uuid = _uuid; m_uuidHasBeenSet = true; } bool HistoryAccount::UuidHasBeenSet() const { return m_uuidHasBeenSet; } string HistoryAccount::GetMachineIp() const { return m_machineIp; } void HistoryAccount::SetMachineIp(const string& _machineIp) { m_machineIp = _machineIp; m_machineIpHasBeenSet = true; } bool HistoryAccount::MachineIpHasBeenSet() const { return m_machineIpHasBeenSet; } string HistoryAccount::GetMachineName() const { return m_machineName; } void HistoryAccount::SetMachineName(const string& _machineName) { m_machineName = _machineName; m_machineNameHasBeenSet = true; } bool HistoryAccount::MachineNameHasBeenSet() const { return m_machineNameHasBeenSet; } string HistoryAccount::GetUsername() const { return m_username; } void HistoryAccount::SetUsername(const string& _username) { m_username = _username; m_usernameHasBeenSet = true; } bool HistoryAccount::UsernameHasBeenSet() const { return m_usernameHasBeenSet; } string HistoryAccount::GetModifyType() const { return m_modifyType; } void HistoryAccount::SetModifyType(const string& _modifyType) { m_modifyType = _modifyType; m_modifyTypeHasBeenSet = true; } bool HistoryAccount::ModifyTypeHasBeenSet() const { return m_modifyTypeHasBeenSet; } string HistoryAccount::GetModifyTime() const { return m_modifyTime; } void HistoryAccount::SetModifyTime(const string& _modifyTime) { m_modifyTime = _modifyTime; m_modifyTimeHasBeenSet = true; } bool HistoryAccount::ModifyTimeHasBeenSet() const { return m_modifyTimeHasBeenSet; }
26.413194
138
0.67359
[ "model" ]
3e99ad783ee285a6ccda167f5c50d7ef1d8d96df
2,285
cpp
C++
source/mfs-painters/multiframepainter/KernelGenerationStage.cpp
karyon/many-lights-gi
253b6a708b394f1a0f7c362cfc7ac039a84584e5
[ "MIT" ]
9
2017-03-21T17:28:52.000Z
2021-09-26T14:39:32.000Z
source/mfs-painters/multiframepainter/KernelGenerationStage.cpp
karyon/many-lights-gi
253b6a708b394f1a0f7c362cfc7ac039a84584e5
[ "MIT" ]
1
2017-05-01T06:57:01.000Z
2017-05-01T06:57:01.000Z
source/mfs-painters/multiframepainter/KernelGenerationStage.cpp
karyon/many-lights-gi
253b6a708b394f1a0f7c362cfc7ac039a84584e5
[ "MIT" ]
2
2018-08-07T10:47:40.000Z
2018-11-09T16:07:58.000Z
#include "KernelGenerationStage.h" #include <glm/gtc/random.hpp> #include <glkernel/Kernel.h> #include <glkernel/sample.h> #include <glkernel/scale.h> #include <glkernel/sort.hpp> #include <glkernel/shuffle.hpp> KernelGenerationStage::KernelGenerationStage() { } void KernelGenerationStage::initialize() { } void KernelGenerationStage::process(int multiFrameCount) { auto& aaSamples = antiAliasingKernel; aaSamples = { static_cast<uint16_t>(multiFrameCount) }; glkernel::sample::poisson_square(aaSamples); glkernel::scale::range(aaSamples, -.5f, .5f); glkernel::shuffle::random(aaSamples, 1); auto& dofSamples = depthOfFieldKernel; dofSamples = { static_cast<uint16_t>(multiFrameCount) }; glkernel::sample::poisson_square(dofSamples); glkernel::scale::range(dofSamples, -1.f, 1.f); glkernel::sort::distance(dofSamples, { 0.f, 0.f }); auto& shadowSamples = shadowKernel; shadowSamples = { static_cast<uint16_t>(multiFrameCount) }; glkernel::sample::poisson_square(shadowSamples); glkernel::scale::range(shadowSamples, -1.f, 1.f); glkernel::sort::distance(shadowSamples, { 0.f, 0.f }); } glkernel::kernel3 KernelGenerationStage::getSSAOKernel(unsigned int size) const { glkernel::kernel3 ssaoSamples = glkernel::kernel3{ static_cast<uint16_t>(size) }; glkernel::sample::best_candidate(ssaoSamples); glkernel::scale::range(ssaoSamples, -1.0f, 1.0f); for (int i = 0; i < ssaoSamples.size(); i++) { auto& elem = ssaoSamples[i]; elem.z = glm::abs(elem.z); elem = glm::normalize(elem); // taken from http://john-chapman-graphics.blogspot.de/2013/01/ssao-tutorial.html float scale = float(i) / float(ssaoSamples.size()); scale = glm::mix(0.1f, 1.0f, scale * scale); elem *= scale; elem.z = std::max(0.1f, elem.z); } return ssaoSamples; } std::vector<glm::vec3> KernelGenerationStage::getSSAONoise(unsigned int size) const { auto kernel = std::vector<glm::vec3>(); for (auto y = 0u; y < size; ++y) { for (auto x = 0u; x < size; ++x) { auto c = glm::circularRand(1.f); auto v = glm::vec3(c.x, c.y, 0.0f); kernel.push_back(v); } } return kernel; }
28.5625
89
0.651204
[ "vector" ]
3ea198ce499f9b8a51aea2ebff527eca4fded0c5
4,275
cpp
C++
operator/operator/stridedslice.cpp
wangshankun/Tengine_Atlas
b5485039e72b4a624c795ff95d73eb6d719c7706
[ "Apache-2.0" ]
25
2018-12-09T09:31:56.000Z
2021-08-12T10:32:19.000Z
operator/operator/stridedslice.cpp
wangshankun/Tengine_Atlas
b5485039e72b4a624c795ff95d73eb6d719c7706
[ "Apache-2.0" ]
1
2022-03-31T03:33:42.000Z
2022-03-31T03:33:42.000Z
operator/operator/stridedslice.cpp
wangshankun/Tengine_Atlas
b5485039e72b4a624c795ff95d73eb6d719c7706
[ "Apache-2.0" ]
6
2018-12-16T01:18:42.000Z
2019-09-18T07:29:56.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * License); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (c) 2019, Open AI Lab * Author: chunyinglv@openailab.com */ #include "operator/stridedslice.hpp" #include <math.h> namespace TEngine { // bool StridedSlice::InferShape(const std::vector<TEngine::TShape>& ishape, std::vector<TEngine::TShape>& oshape, int // layout) // { // const TShape& input = ishape[0]; // const std::vector<int>& in_dim = input.GetDim(); // std::vector<int> o_dim=input.GetDim(); // o_dim[0]= ;//- param_.begin[0] + param_.end[0]; // o_dim[1]= in_dim[1];//- param_.begin[1] + param_.end[1]; // o_dim[2]= in_dim[2];//- param_.begin[2] + param_.end[2]; // o_dim[3]= in_dim[3];//- param_.begin[3] + param_.end[3]; // TShape shape; // shape.SetDim(o_dim); // shape.SetDataLayout(input.GetDataLayout()); // oshape[0] = shape; // return true; // } bool StridedSlice::InferShape(const std::vector<TEngine::TShape>& ishape, std::vector<TEngine::TShape>& oshape, int layout) { const TShape& input = ishape[0]; const std::vector<int>& in_dim = input.GetDim(); if(input.GetDim().size() == 4 && param_.shrink_axis_mask == 0) { std::vector<int> o_dim = input.GetDim(); int delta_0=(-param_.begin[0] + param_.end[0])<0? param_.begin[0] -param_.end[0] :-param_.begin[0] + param_.end[0]; int delta_1=(-param_.begin[1] + param_.end[1])<0? param_.begin[1] -param_.end[1] :-param_.begin[1] + param_.end[1]; int delta_2=(-param_.begin[2] + param_.end[2])<0? param_.begin[2] -param_.end[2] :-param_.begin[2] + param_.end[2]; int delta_3=(-param_.begin[3] + param_.end[3])<0? param_.begin[3] -param_.end[3] :-param_.begin[3] + param_.end[3]; o_dim[0]= ceil(((float)in_dim[0]-(float)delta_0)/(float)param_.stride[0]); o_dim[1]= ceil(((float)in_dim[1]-(float)delta_1)/(float)param_.stride[1]); o_dim[2]= ceil(((float)in_dim[2]-(float)delta_2)/(float)param_.stride[2]); o_dim[3]= ceil(((float)in_dim[3]-(float)delta_3)/(float)param_.stride[3]); TShape shape; shape.SetDim(o_dim); shape.SetDataLayout(input.GetDataLayout()); oshape[0] = shape; } else if(input.GetDim().size() == 3 && param_.shrink_axis_mask == 1) { std::vector<int> o_dim(2); o_dim[0] = in_dim[1]; o_dim[1] = in_dim[2]; TShape shape; shape.SetDim(o_dim); shape.SetDataLayout(input.GetDataLayout()); oshape[0] = shape; } else if(input.GetDim().size() == 3 && param_.shrink_axis_mask == 2) { std::vector<int> o_dim(2); o_dim[0] = in_dim[0]; o_dim[1] = in_dim[2]; TShape shape; shape.SetDim(o_dim); shape.SetDataLayout(input.GetDataLayout()); oshape[0] = shape; } else if(input.GetDim().size() == 3 && param_.shrink_axis_mask == 3) { std::vector<int> o_dim(2); o_dim[0] = in_dim[0]; o_dim[1] = in_dim[1]; TShape shape; shape.SetDim(o_dim); shape.SetDataLayout(input.GetDataLayout()); oshape[0] = shape; } return true; } void StridedSlice::SetSchema(void) { Input({"input:float32"}) .Output({"output:float32"}) .SetAttr("shrink_axis_mask", 0) .SetAttr("new_axis_mask", 0) .SetAttr("ellipsis_mask", 0) .SetAttr("begin_mask", 0) .SetAttr("end_mask", 0) .SetDoc(R"DOC(SwapAxis Layer)DOC"); } } // namespace TEngine
36.228814
123
0.616842
[ "shape", "vector" ]
3ea7568a843d61b67880d7bb2aea6fe1dcae0554
13,477
cc
C++
test/benchmark/registration-benchmark.cc
plusk01/TEASER-plusplus
0d497521d261b3fa35c4ca29eb86ba7cf9558f9f
[ "MIT" ]
962
2020-01-21T19:08:54.000Z
2022-03-31T17:28:49.000Z
test/benchmark/registration-benchmark.cc
plusk01/TEASER-plusplus
0d497521d261b3fa35c4ca29eb86ba7cf9558f9f
[ "MIT" ]
105
2020-01-24T15:11:10.000Z
2022-03-22T02:28:52.000Z
test/benchmark/registration-benchmark.cc
plusk01/TEASER-plusplus
0d497521d261b3fa35c4ca29eb86ba7cf9558f9f
[ "MIT" ]
234
2020-01-21T12:28:31.000Z
2022-03-30T08:41:31.000Z
/** * Copyright 2020, Massachusetts Institute of Technology, * Cambridge, MA 02139 * All Rights Reserved * Authors: Jingnan Shi, et al. (see THANKS for the full author list) * See LICENSE for the license information */ #include "gtest/gtest.h" #include <iostream> #include <fstream> #include <iomanip> #include <chrono> #include "teaser/registration.h" #include "teaser/ply_io.h" #include "test_utils.h" /** * This file contains a small framework for running benchmark with specifications. * * By providing a parameters.txt file with relevant parameters, and relevant data files, this * framework will run, time and print out the performance of the solver under test. */ class RegistrationBenchmark : public ::testing::Test { protected: /** * Enum representing the types of parameters we have */ enum class BenchmarkParamType { NUM_POINTS, NOISE_SIGMA, OUTLIER_RATIO, NOISE_BOUND }; /** * Struct to represent all necessary data / reference values for a benchmark */ struct BenchmarkData { Eigen::Matrix<double, 3, Eigen::Dynamic> src; Eigen::Matrix<double, 3, Eigen::Dynamic> dst; double s_est; double s_ref; Eigen::Matrix3d R_est; Eigen::Matrix3d R_ref; Eigen::Vector3d t_est; Eigen::Vector3d t_ref; double noise_sigma; double noise_bound; double outlier_ratio; int num_points; }; /** * Struct to store acceptable errors */ struct ErrorConditions { // acceptable errors from ground truths double s_ground_truth_error; double R_ground_truth_error; double t_ground_truth_error; // acceptable errors from MATLAB TEASER implementation double s_TEASER_error; double R_TEASER_error; double t_TEASER_error; }; /** * Map from string to BenchmarkParam */ std::map<std::string, BenchmarkParamType> mapStringToBenchmarkParamType = { {"Number of Points", BenchmarkParamType::NUM_POINTS}, {"Noise Sigma", BenchmarkParamType::NOISE_SIGMA}, {"Outlier Ratio", BenchmarkParamType::OUTLIER_RATIO}, {"Noise Bound", BenchmarkParamType::NOISE_BOUND}, }; /** * Helper function to load a parameters.txt file * @param num_points * @param noise_sigma * @param outlier_ratio * @param noise_bound */ void loadParameters(std::string file_path, int* num_points, double* noise_sigma, double* outlier_ratio, double* noise_bound) { // Open the file std::ifstream file; file.open(file_path); if (!file) { std::cerr << "Unable to open file: " << file_path << "." << std::endl; exit(1); } std::string line; std::string delimiter = ":"; while (std::getline(file, line)) { size_t delim_idx = line.find(delimiter, 0); std::string param = line.substr(0, delim_idx); std::string value = line.substr(delim_idx + 2, line.length()); BenchmarkParamType param_type = mapStringToBenchmarkParamType[param]; switch (param_type) { case BenchmarkParamType::NUM_POINTS: *num_points = std::stoi(value); break; case BenchmarkParamType::NOISE_SIGMA: *noise_sigma = std::stod(value); break; case BenchmarkParamType::OUTLIER_RATIO: *outlier_ratio = std::stod(value); break; case BenchmarkParamType::NOISE_BOUND: *noise_bound = std::stod(value); break; } } } /** * Load the benchmark data for a specific benchmark * @param name the name of the benchmark, should correspond to one of the folder in the benchmark * folder */ BenchmarkData prepareBenchmarkData(std::string name) { // Generate file names & file streams std::string folder = "./data/" + name + "/"; std::string dst_file = folder + "dst.ply"; std::string src_file = folder + "src.ply"; std::string parameters_file = folder + "parameters.txt"; std::ifstream R_ref_file(folder + "R_ref.csv"); std::ifstream R_est_file(folder + "R_est.csv"); std::ifstream s_ref_file(folder + "s_ref.csv"); std::ifstream s_est_file(folder + "s_est.csv"); std::ifstream t_ref_file(folder + "t_ref.csv"); std::ifstream t_est_file(folder + "t_est.csv"); // Struct to store all data & parameters BenchmarkData benchmark_data; // Load src model teaser::PLYReader reader; teaser::PointCloud src_cloud; auto status = reader.read(src_file, src_cloud); EXPECT_EQ(status, 0); benchmark_data.src = teaser::test::teaserPointCloudToEigenMatrix<double>(src_cloud); // Load dst model teaser::PointCloud dst_cloud; status = reader.read(dst_file, dst_cloud); EXPECT_EQ(status, 0); benchmark_data.dst = teaser::test::teaserPointCloudToEigenMatrix<double>(dst_cloud); // Load parameters double noise_bound, outlier_ratio, noise_sigma; loadParameters(parameters_file, &(benchmark_data.num_points), &(benchmark_data.noise_sigma), &(benchmark_data.outlier_ratio), &(benchmark_data.noise_bound)); // Load reference values benchmark_data.R_est = teaser::test::readFileToEigenFixedMatrix<double, 3, 3>(R_est_file); benchmark_data.R_ref = teaser::test::readFileToEigenFixedMatrix<double, 3, 3>(R_ref_file); benchmark_data.t_est = teaser::test::readFileToEigenFixedMatrix<double, 3, 1>(t_est_file); benchmark_data.t_ref = teaser::test::readFileToEigenFixedMatrix<double, 3, 1>(t_ref_file); s_est_file >> benchmark_data.s_est; s_ref_file >> benchmark_data.s_ref; return benchmark_data; } /** * Helper function for running a specific benchmark * @param folder */ void benchmarkRunner(BenchmarkData data, ErrorConditions conditions, std::string rotation_method = "GNC-TLS", size_t num_runs = 100) { // Variables for storing average errors double s_err_ref_avg = 0, t_err_ref_avg = 0, R_err_ref_avg = 0, s_err_est_avg = 0, t_err_est_avg = 0, R_err_est_avg = 0; double duration_avg = 0; for (size_t i = 0; i < num_runs; ++i) { // Start the timer auto start = std::chrono::high_resolution_clock::now(); teaser::RobustRegistrationSolver::Params params; params.noise_bound = data.noise_bound; params.cbar2 = 1; params.estimate_scaling = true; params.rotation_max_iterations = 100; params.rotation_gnc_factor = 1.4; if (rotation_method == "GNC-TLS") { params.rotation_estimation_algorithm = teaser::RobustRegistrationSolver::ROTATION_ESTIMATION_ALGORITHM::GNC_TLS; params.rotation_cost_threshold = 1e-12; } else if (rotation_method == "FGR") { params.rotation_estimation_algorithm = teaser::RobustRegistrationSolver::ROTATION_ESTIMATION_ALGORITHM::FGR; params.rotation_cost_threshold = 0.005; } else { std::cout << "Unsupported rotation estimation method." << std::endl; break; } // Prepare the solver object teaser::RobustRegistrationSolver solver(params); // Solve solver.solve(data.src, data.dst); // Stop the timer auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start); duration_avg += duration.count(); // Get the solution auto actual_solution = solver.getSolution(); // Errors wrt ground truths double s_err_ref = std::abs(actual_solution.scale - data.s_ref); double t_err_ref = (actual_solution.translation - data.t_ref).norm(); double R_err_ref = teaser::test::getAngularError(data.R_ref, actual_solution.rotation); EXPECT_LE(s_err_ref, conditions.s_ground_truth_error); EXPECT_LE(t_err_ref, conditions.t_ground_truth_error); EXPECT_LE(R_err_ref, conditions.R_ground_truth_error); s_err_ref_avg += s_err_ref; t_err_ref_avg += t_err_ref; R_err_ref_avg += R_err_ref; // Errors wrt MATLAB implementation (TEASER w/ SDP rotation estimation) output double s_err_est = std::abs(actual_solution.scale - data.s_est); double t_err_est = (actual_solution.translation - data.t_est).norm(); double R_err_est = teaser::test::getAngularError(data.R_est, actual_solution.rotation); EXPECT_LE(s_err_est, conditions.s_TEASER_error); EXPECT_LE(t_err_est, conditions.t_TEASER_error); EXPECT_LE(R_err_est, conditions.R_TEASER_error); s_err_est_avg += s_err_est; t_err_est_avg += t_err_est; R_err_est_avg += R_err_est; } double div_factor = 1.0 / static_cast<double>(num_runs); s_err_ref_avg *= div_factor; R_err_ref_avg *= div_factor; t_err_ref_avg *= div_factor; s_err_est_avg *= div_factor; R_err_est_avg *= div_factor; t_err_est_avg *= div_factor; duration_avg *= div_factor; // Print report std::cout << "==============================================" << std::endl; std::cout << " Benchmark Report " << std::endl; std::cout << "==============================================" << std::endl; std::cout << " Benchmark Parameters " << std::endl; std::cout << " num of points: " << data.num_points << std::endl; std::cout << " outlier ratio: " << data.outlier_ratio << std::endl; std::cout << " noise sigma: " << data.noise_sigma << std::endl; std::cout << "----------------------------------------------" << std::endl; std::cout << " Error from Ground Truth " << std::endl; std::cout << " in scale: " << s_err_ref_avg << std::endl; std::cout << " in rotation: " << R_err_ref_avg << std::endl; std::cout << " in translation: " << t_err_ref_avg << std::endl; std::cout << "----------------------------------------------" << std::endl; std::cout << " Error from TEASER w/ SDP Rotation Estimation " << std::endl; std::cout << " in scale: " << s_err_est_avg << std::endl; std::cout << " in rotation: " << R_err_est_avg << std::endl; std::cout << " in translation: " << t_err_est_avg << std::endl; std::cout << "==============================================" << std::endl; std::cout << "Time taken to run benchmark: " << duration_avg << " microseconds." << std::endl; } void SetUp() override {} void TearDown() override {} }; TEST_F(RegistrationBenchmark, Benchmark1) { auto data = prepareBenchmarkData("benchmark_1"); // Prepare acceptable errors ErrorConditions conditions; conditions.s_ground_truth_error = 1e-5; conditions.R_ground_truth_error = 1e-5; conditions.t_ground_truth_error = 1e-5; conditions.s_TEASER_error = 1e-5; conditions.R_TEASER_error = 1e-5; conditions.t_TEASER_error = 1e-5; // Run benchmark benchmarkRunner(data, conditions, "GNC-TLS"); benchmarkRunner(data, conditions, "FGR"); } TEST_F(RegistrationBenchmark, Benchmark2) { auto data = prepareBenchmarkData("benchmark_2"); std::cout << data.src << std::endl; // Prepare acceptable errors ErrorConditions conditions; conditions.s_ground_truth_error = 1e-5; conditions.R_ground_truth_error = 1e-5; conditions.t_ground_truth_error = 1e-5; conditions.s_TEASER_error = 1e-5; conditions.R_TEASER_error = 1e-5; conditions.t_TEASER_error = 1e-5; // Run benchmark benchmarkRunner(data, conditions, "GNC-TLS"); benchmarkRunner(data, conditions, "FGR"); } TEST_F(RegistrationBenchmark, Benchmark3) { auto data = prepareBenchmarkData("benchmark_3"); // Prepare acceptable errors ErrorConditions conditions; conditions.s_ground_truth_error = 1e-5; conditions.R_ground_truth_error = 1e-5; conditions.t_ground_truth_error = 1e-5; conditions.s_TEASER_error = 1e-5; conditions.R_TEASER_error = 1e-5; conditions.t_TEASER_error = 1e-5; // Run benchmark benchmarkRunner(data, conditions, "GNC-TLS"); benchmarkRunner(data, conditions, "FGR"); } TEST_F(RegistrationBenchmark, Benchmark4) { auto data = prepareBenchmarkData("benchmark_4"); // Prepare acceptable errors ErrorConditions conditions; conditions.s_ground_truth_error = 1e-5; conditions.R_ground_truth_error = 1e-5; conditions.t_ground_truth_error = 1e-5; conditions.s_TEASER_error = 1e-5; conditions.R_TEASER_error = 1e-5; conditions.t_TEASER_error = 1e-5; // Run benchmark benchmarkRunner(data, conditions, "GNC-TLS"); benchmarkRunner(data, conditions, "FGR"); } TEST_F(RegistrationBenchmark, Benchmark5) { auto data = prepareBenchmarkData("benchmark_5"); // Prepare acceptable errors ErrorConditions conditions; conditions.s_ground_truth_error = 1e-5; conditions.R_ground_truth_error = 1e-5; conditions.t_ground_truth_error = 1e-5; conditions.s_TEASER_error = 1e-5; conditions.R_TEASER_error = 1e-5; conditions.t_TEASER_error = 1e-5; // Run benchmark benchmarkRunner(data, conditions, "GNC-TLS"); benchmarkRunner(data, conditions, "FGR"); } /** * This test assumes non-zero noise and non-zero outlier ratio. */ TEST_F(RegistrationBenchmark, Benchmark6) { auto data = prepareBenchmarkData("benchmark_6"); // Prepare acceptable errors ErrorConditions conditions; conditions.s_ground_truth_error = 1e-2; conditions.R_ground_truth_error = 1e-2; conditions.t_ground_truth_error = 2e-2; conditions.s_TEASER_error = 1e-5; conditions.R_TEASER_error = 1e-3; conditions.t_TEASER_error = 1e-3; // Run benchmark benchmarkRunner(data, conditions, "GNC-TLS"); benchmarkRunner(data, conditions, "FGR"); }
35.938667
99
0.673147
[ "object", "model" ]
3eb38bc66912e5565af7e5e638c3ad29c56a2219
25,036
cpp
C++
ares/component/processor/m68000/disassembler.cpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
153
2020-07-25T17:55:29.000Z
2021-10-01T23:45:01.000Z
ares/component/processor/m68000/disassembler.cpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
245
2021-10-08T09:14:46.000Z
2022-03-31T08:53:13.000Z
ares/component/processor/m68000/disassembler.cpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
44
2020-07-25T08:51:55.000Z
2021-09-25T16:09:01.000Z
template<> auto M68000::_read<Byte>(n32 address) -> n32 { if(address & 1) { return read(0, 1, address & ~1).byte(0); } else { return read(1, 0, address & ~1).byte(1); } } template<> auto M68000::_read<Word>(n32 address) -> n32 { return read(1, 1, address & ~1); } template<> auto M68000::_read<Long>(n32 address) -> n32 { n32 data = _read<Word>(address + 0) << 16; return data | _read<Word>(address + 2) << 0; } template<u32 Size> auto M68000::_readPC() -> n32 { auto data = _read<Size == Byte ? Word : Size>(_pc); _pc += Size == Long ? 4 : 2; return clip<Size>(data); } auto M68000::_readDisplacement(n32 base) -> n32 { return base + (i16)_readPC<Word>(); } auto M68000::_readIndex(n32 base) -> n32 { auto extension = _readPC<Word>(); auto index = extension & 0x8000 ? read(AddressRegister{extension >> 12}) : read(DataRegister{extension >> 12}); if(!(extension & 0x800)) index = (i16)index; return base + index + (i8)extension; } auto M68000::_dataRegister(DataRegister dr) -> string { return {"d", dr.number}; } auto M68000::_addressRegister(AddressRegister ar) -> string { return {"a", ar.number}; } template<u32 Size> auto M68000::_immediate() -> string { return {"#$", hex(_readPC<Size>(), 2 << Size)}; } template<u32 Size> auto M68000::_address(EffectiveAddress& ea) -> string { if(ea.mode == 2) return {_addressRegister(AddressRegister{ea.reg})}; if(ea.mode == 5) return {"$", hex(_readDisplacement(read(AddressRegister{ea.reg})), 6L)}; if(ea.mode == 6) return {"$", hex(_readIndex(read(AddressRegister{ea.reg})), 6L)}; if(ea.mode == 7) { auto imm = _readPC<Word>(); return {"$", imm >= 0x8000 ? hex((i16)imm, 6L, 'f') : hex((i16)imm, 6L, '0') }; } if(ea.mode == 8) return {"$", hex(_readPC<Long>(), 6L)}; if(ea.mode == 9) return {"$", hex(_pc + (i16)_readPC(), 6L)}; if(ea.mode == 10) return {"$", hex(_readIndex(_pc), 6L)}; return "???"; //should never occur (modes 0, 1, 3, 4, 11 are not valid for LEA) } template<u32 Size> auto M68000::_effectiveAddress(EffectiveAddress& ea) -> string { if(ea.mode == 0) return {_dataRegister(DataRegister{ea.reg})}; if(ea.mode == 1) return {_addressRegister(AddressRegister{ea.reg})}; if(ea.mode == 2) return {"(", _addressRegister(AddressRegister{ea.reg}), ")"}; if(ea.mode == 3) return {"(", _addressRegister(AddressRegister{ea.reg}), ")+"}; if(ea.mode == 4) return {"-(", _addressRegister(AddressRegister{ea.reg}), ")"}; if(ea.mode == 5) return {"($", hex(_readDisplacement(read(AddressRegister{ea.reg})), 6L), ")"}; if(ea.mode == 6) return {"($", hex(_readIndex(read(AddressRegister{ea.reg})), 6L), ")"}; if(ea.mode == 7) { auto imm = _readPC<Word>(); return {"($", imm >= 0x8000 ? hex((i16)imm, 6L, 'f') : hex((i16)imm, 6L, '0'), ")"}; } if(ea.mode == 8) return {"($", hex(_readPC<Long>(), 6L), ")"}; if(ea.mode == 9) return {"($", hex(_readDisplacement(_pc), 6L), ")"}; if(ea.mode == 10) return {"($", hex(_readIndex(_pc), 6L), ")"}; if(ea.mode == 11) return {"#$", hex(_readPC<Size>(), 2 << Size)}; return "???"; //should never occur } auto M68000::_branch(n8 displacement) -> string { n16 extension = _readPC(); _pc -= 2; i32 offset = displacement ? sign<Byte>(displacement) : sign<Word>(extension); return {"$", hex(_pc + offset, 6L)}; } template<u32 Size> auto M68000::_suffix() -> string { return Size == Byte ? ".b" : Size == Word ? ".w" : ".l"; } auto M68000::_condition(n4 condition) -> string { static const string conditions[16] = { "t ", "f ", "hi", "ls", "cc", "cs", "ne", "eq", "vc", "vs", "pl", "mi", "ge", "lt", "gt", "le", }; return conditions[condition]; } auto M68000::disassembleInstruction(n32 pc) -> string { _pc = pc; return {hex(_read<Word>(_pc), 4L), " ", pad(disassembleTable[_readPC()](), -49)}; } auto M68000::disassembleContext() -> string { return { "d0:", hex(r.d[0], 8L), " ", "d1:", hex(r.d[1], 8L), " ", "d2:", hex(r.d[2], 8L), " ", "d3:", hex(r.d[3], 8L), " ", "d4:", hex(r.d[4], 8L), " ", "d5:", hex(r.d[5], 8L), " ", "d6:", hex(r.d[6], 8L), " ", "d7:", hex(r.d[7], 8L), " ", "a0:", hex(r.a[0], 8L), " ", "a1:", hex(r.a[1], 8L), " ", "a2:", hex(r.a[2], 8L), " ", "a3:", hex(r.a[3], 8L), " ", "a4:", hex(r.a[4], 8L), " ", "a5:", hex(r.a[5], 8L), " ", "a6:", hex(r.a[6], 8L), " ", "a7:", hex(r.a[7], 8L), " ", "sp:", hex(r.sp, 8L), " ", r.t ? "T" : "t", r.s ? "S" : "s", (u32)r.i, r.c ? "C" : "c", r.v ? "V" : "v", r.z ? "Z" : "z", r.n ? "N" : "n", r.x ? "X" : "x", " ", }; } // auto M68000::disassembleABCD(EffectiveAddress from, EffectiveAddress with) -> string { return {"abcd ", _effectiveAddress<Byte>(from), ",", _effectiveAddress<Byte>(with)}; } template<u32 Size> auto M68000::disassembleADD(EffectiveAddress from, DataRegister with) -> string { return {"add", _suffix<Size>(), " ", _effectiveAddress<Size>(from), ",", _dataRegister(with)}; } template<u32 Size> auto M68000::disassembleADD(DataRegister from, EffectiveAddress with) -> string { return {"add", _suffix<Size>(), " ", _dataRegister(from), ",", _effectiveAddress<Size>(with)}; } template<u32 Size> auto M68000::disassembleADDA(EffectiveAddress from, AddressRegister with) -> string { return {"adda", _suffix<Size>(), " ", _effectiveAddress<Size>(from), ",", _addressRegister(with)}; } template<u32 Size> auto M68000::disassembleADDI(EffectiveAddress with) -> string { return {"addi", _suffix<Size>(), " ", _immediate<Size>(), ",", _effectiveAddress<Size>(with)}; } template<u32 Size> auto M68000::disassembleADDQ(n4 immediate, EffectiveAddress with) -> string { return {"addq", _suffix<Size>(), " #", immediate, ",", _effectiveAddress<Size>(with)}; } template<u32 Size> auto M68000::disassembleADDQ(n4 immediate, AddressRegister with) -> string { return {"addq", _suffix<Size>(), " #", immediate, ",", _addressRegister(with)}; } template<u32 Size> auto M68000::disassembleADDX(EffectiveAddress from, EffectiveAddress with) -> string { return {"addx", _suffix<Size>(), " ", _effectiveAddress<Size>(from), ",", _effectiveAddress<Size>(with)}; } template<u32 Size> auto M68000::disassembleAND(EffectiveAddress from, DataRegister with) -> string { return {"and", _suffix<Size>(), " ", _effectiveAddress<Size>(from), ",", _dataRegister(with)}; } template<u32 Size> auto M68000::disassembleAND(DataRegister from, EffectiveAddress with) -> string { return {"and", _suffix<Size>(), " ", _dataRegister(from), ",", _effectiveAddress<Size>(with)}; } template<u32 Size> auto M68000::disassembleANDI(EffectiveAddress ea) -> string { return {"andi", _suffix<Size>(), " ", _immediate<Size>(), ",", _effectiveAddress<Size>(ea)}; } auto M68000::disassembleANDI_TO_CCR() -> string { return {"andi ", _immediate<Byte>(), ",ccr"}; } auto M68000::disassembleANDI_TO_SR() -> string { return {"andi ", _immediate<Word>(), ",sr"}; } template<u32 Size> auto M68000::disassembleASL(n4 count, DataRegister with) -> string { return {"asl", _suffix<Size>(), " #", count, ",", _dataRegister(with)}; } template<u32 Size> auto M68000::disassembleASL(DataRegister from, DataRegister with) -> string { return {"asl", _suffix<Size>(), " ", _dataRegister(from), ",", _dataRegister(with)}; } auto M68000::disassembleASL(EffectiveAddress with) -> string { return {"asl", _suffix<Word>(), " ", _effectiveAddress<Word>(with)}; } template<u32 Size> auto M68000::disassembleASR(n4 count, DataRegister modify) -> string { return {"asr", _suffix<Size>(), " #", count, ",", _dataRegister(modify)}; } template<u32 Size> auto M68000::disassembleASR(DataRegister from, DataRegister modify) -> string { return {"asr", _suffix<Size>(), " ", _dataRegister(from), ",", _dataRegister(modify)}; } auto M68000::disassembleASR(EffectiveAddress with) -> string { return {"asr", _suffix<Word>(), " ", _effectiveAddress<Word>(with)}; } auto M68000::disassembleBCC(n4 test, n8 displacement) -> string { auto cc = _condition(test); return {"b", cc, " ", _branch(displacement)}; } template<u32 Size> auto M68000::disassembleBCHG(DataRegister bit, EffectiveAddress with) -> string { return {"bchg", _suffix<Size>(), " ", _dataRegister(bit), ",", _effectiveAddress<Size>(with)}; } template<u32 Size> auto M68000::disassembleBCHG(EffectiveAddress with) -> string { return {"bchg", _suffix<Size>(), " ", _immediate<Byte>(), ",", _effectiveAddress<Size>(with)}; } template<u32 Size> auto M68000::disassembleBCLR(DataRegister bit, EffectiveAddress with) -> string { return {"bclr", _suffix<Size>(), " ", _dataRegister(bit), ",", _effectiveAddress<Size>(with)}; } template<u32 Size> auto M68000::disassembleBCLR(EffectiveAddress with) -> string { return {"bclr", _suffix<Size>(), " ", _immediate<Byte>(), ",", _effectiveAddress<Size>(with)}; } auto M68000::disassembleBRA(n8 displacement) -> string { return {"bra ", _branch(displacement)}; } template<u32 Size> auto M68000::disassembleBSET(DataRegister bit, EffectiveAddress with) -> string { return {"bset", _suffix<Size>(), " ", _dataRegister(bit), ",", _effectiveAddress<Size>(with)}; } template<u32 Size> auto M68000::disassembleBSET(EffectiveAddress with) -> string { return {"bset", _suffix<Size>(), " ", _immediate<Byte>(), ",", _effectiveAddress<Size>(with)}; } auto M68000::disassembleBSR(n8 displacement) -> string { return {"bsr ", _branch(displacement)}; } template<u32 Size> auto M68000::disassembleBTST(DataRegister bit, EffectiveAddress with) -> string { return {"btst", _suffix<Size>(), " ", _dataRegister(bit), ",", _effectiveAddress<Size>(with)}; } template<u32 Size> auto M68000::disassembleBTST(EffectiveAddress with) -> string { return {"btst", _suffix<Size>(), " ", _immediate<Byte>(), ",", _effectiveAddress<Size>(with)}; } auto M68000::disassembleCHK(DataRegister compare, EffectiveAddress maximum) -> string { return {"chk", _suffix<Word>(), " ", _effectiveAddress<Word>(maximum), ",", _dataRegister(compare)}; } template<u32 Size> auto M68000::disassembleCLR(EffectiveAddress ea) -> string { return {"clr", _suffix<Size>(), " ", _effectiveAddress<Size>(ea)}; } template<u32 Size> auto M68000::disassembleCMP(EffectiveAddress from, DataRegister with) -> string { return {"cmp", _suffix<Size>(), " ", _effectiveAddress<Size>(from), ",", _dataRegister(with)}; } template<u32 Size> auto M68000::disassembleCMPA(EffectiveAddress from, AddressRegister with) -> string { return {"cmpa", _suffix<Size>(), " ", _effectiveAddress<Size>(from), ",", _addressRegister(with)}; } template<u32 Size> auto M68000::disassembleCMPI(EffectiveAddress with) -> string { return {"cmpi", _suffix<Size>(), " ", _immediate<Size>(), ",", _effectiveAddress<Size>(with)}; } template<u32 Size> auto M68000::disassembleCMPM(EffectiveAddress from, EffectiveAddress with) -> string { return {"cmpm", _suffix<Size>(), " ", _effectiveAddress<Size>(from), ",", _effectiveAddress<Size>(with)}; } auto M68000::disassembleDBCC(n4 condition, DataRegister with) -> string { auto base = _pc; auto displacement = (i16)_readPC(); return {"db", _condition(condition), " ", _dataRegister(with), ",$", hex(base + displacement, 6L)}; } auto M68000::disassembleDIVS(EffectiveAddress from, DataRegister with) -> string { return {"divs", _suffix<Word>(), " ", _effectiveAddress<Word>(from), ",", _dataRegister(with)}; } auto M68000::disassembleDIVU(EffectiveAddress from, DataRegister with) -> string { return {"divu", _suffix<Word>(), " ", _effectiveAddress<Word>(from), ",", _dataRegister(with)}; } template<u32 Size> auto M68000::disassembleEOR(DataRegister from, EffectiveAddress with) -> string { return {"eor", _suffix<Size>(), " ", _dataRegister(from), ",", _effectiveAddress<Size>(with)}; } template<u32 Size> auto M68000::disassembleEORI(EffectiveAddress with) -> string { return {"eori", _suffix<Size>(), " ", _immediate<Size>(), ",", _effectiveAddress<Size>(with)}; } auto M68000::disassembleEORI_TO_CCR() -> string { return {"eori ", _immediate<Byte>(), ",ccr"}; } auto M68000::disassembleEORI_TO_SR() -> string { return {"eori ", _immediate<Word>(), ",sr"}; } auto M68000::disassembleEXG(DataRegister x, DataRegister y) -> string { return {"exg ", _dataRegister(x), ",", _dataRegister(y)}; } auto M68000::disassembleEXG(AddressRegister x, AddressRegister y) -> string { return {"exg ", _addressRegister(x), ",", _addressRegister(y)}; } auto M68000::disassembleEXG(DataRegister x, AddressRegister y) -> string { return {"exg ", _dataRegister(x), ",", _addressRegister(y)}; } template<u32 Size> auto M68000::disassembleEXT(DataRegister with) -> string { return {"ext", _suffix<Size>(), " ", _dataRegister(with)}; } auto M68000::disassembleILLEGAL(n16 code) -> string { if(code.bit(12,15) == 0xa) return {"linea $", hex((n12)code, 3L)}; if(code.bit(12,15) == 0xf) return {"linef $", hex((n12)code, 3L)}; return {"illegal "}; } auto M68000::disassembleJMP(EffectiveAddress from) -> string { return {"jmp ", _effectiveAddress<Long>(from)}; } auto M68000::disassembleJSR(EffectiveAddress from) -> string { return {"jsr ", _effectiveAddress<Long>(from)}; } auto M68000::disassembleLEA(EffectiveAddress from, AddressRegister with) -> string { return {"lea ", _address<Long>(from), ",", _addressRegister(with)}; } auto M68000::disassembleLINK(AddressRegister with) -> string { return {"link ", _addressRegister(with), ",", _immediate<Word>()}; } template<u32 Size> auto M68000::disassembleLSL(n4 count, DataRegister with) -> string { return {"lsl", _suffix<Size>(), " #", count, ",", _dataRegister(with)}; } template<u32 Size> auto M68000::disassembleLSL(DataRegister from, DataRegister with) -> string { return {"lsl", _suffix<Size>(), " ", _dataRegister(from), ",", _dataRegister(with)}; } auto M68000::disassembleLSL(EffectiveAddress with) -> string { return {"lsl", _suffix<Word>(), " ", _effectiveAddress<Word>(with)}; } template<u32 Size> auto M68000::disassembleLSR(n4 count, DataRegister with) -> string { return {"lsr", _suffix<Size>(), " #", count, ",", _dataRegister(with)}; } template<u32 Size> auto M68000::disassembleLSR(DataRegister from, DataRegister with) -> string { return {"lsr", _suffix<Size>(), " ", _dataRegister(from), ",", _dataRegister(with)}; } auto M68000::disassembleLSR(EffectiveAddress with) -> string { return {"lsr", _suffix<Word>(), " ", _effectiveAddress<Word>(with)}; } template<u32 Size> auto M68000::disassembleMOVE(EffectiveAddress from, EffectiveAddress to) -> string { return {"move", _suffix<Size>(), " ", _effectiveAddress<Size>(from), ",", _effectiveAddress<Size>(to)}; } template<u32 Size> auto M68000::disassembleMOVEA(EffectiveAddress from, AddressRegister to) -> string { return {"movea ", _effectiveAddress<Size>(from), ",", _addressRegister(to)}; } template<u32 Size> auto M68000::disassembleMOVEM_TO_MEM(EffectiveAddress to) -> string { string op{"movem", _suffix<Size>(), " "}; n16 list = _readPC(); string regs; for(u32 lhs = 0; lhs < 8; lhs++) { if(!list.bit(0 + lhs)) continue; regs.append(_dataRegister(DataRegister{lhs})); if(lhs == 7 || !list.bit(1 + lhs)) { regs.append(","); continue; } for(u32 rhs = lhs; rhs < 8; rhs++) { if(rhs == 7 || !list.bit(1 + rhs)) { regs.append("-", _dataRegister(DataRegister{rhs}), ","); lhs = rhs; break; } } } regs.trimRight(","); if(regs && list >> 8) regs.append("/"); for(u32 lhs = 0; lhs < 8; lhs++) { if(!list.bit(8 + lhs)) continue; regs.append(_addressRegister(AddressRegister{lhs})); if(lhs == 7 || !list.bit(9 + lhs)) { regs.append(","); continue; } for(u32 rhs = lhs; rhs < 8; rhs++) { if(rhs == 7 || !list.bit(9 + rhs)) { regs.append("-", _addressRegister(AddressRegister{rhs}), ","); lhs = rhs; break; } } } regs.trimRight(","); if(!regs) regs = "-"; return {op, regs, ",", _effectiveAddress<Size>(to)}; } template<u32 Size> auto M68000::disassembleMOVEM_TO_REG(EffectiveAddress from) -> string { string op{"movem", _suffix<Size>(), " "}; n16 list = _readPC(); string regs; for(u32 lhs = 0; lhs < 8; lhs++) { if(!list.bit(0 + lhs)) continue; regs.append(_dataRegister(DataRegister{lhs})); if(lhs == 7 || !list.bit(1 + lhs)) { regs.append(","); continue; } for(u32 rhs = lhs; rhs < 8; rhs++) { if(rhs == 7 || !list.bit(1 + rhs)) { regs.append("-", _dataRegister(DataRegister{rhs}), ","); lhs = rhs; break; } } } regs.trimRight(","); if(regs && list >> 8) regs.append("/"); for(u32 lhs = 0; lhs < 8; lhs++) { if(!list.bit(8 + lhs)) continue; regs.append(_addressRegister(AddressRegister{lhs})); if(lhs == 7 || !list.bit(9 + lhs)) { regs.append(","); continue; } for(u32 rhs = lhs; rhs < 8; rhs++) { if(rhs == 7 || !list.bit(9 + rhs)) { regs.append("-", _addressRegister(AddressRegister{rhs}), ","); lhs = rhs; break; } } } regs.trimRight(","); if(!regs) regs = "-"; return {op, _effectiveAddress<Size>(from), ",", regs}; } template<u32 Size> auto M68000::disassembleMOVEP(DataRegister from, EffectiveAddress to) -> string { return {"movep", _suffix<Size>(), " ", _dataRegister(from), ",", _effectiveAddress<Size>(to)}; } template<u32 Size> auto M68000::disassembleMOVEP(EffectiveAddress from, DataRegister to) -> string { return {"movep", _suffix<Size>(), " ", _effectiveAddress<Size>(from), ",", _dataRegister(to)}; } auto M68000::disassembleMOVEQ(n8 immediate, DataRegister to) -> string { return {"moveq #$", hex(immediate, 2L), ",", _dataRegister(to)}; } auto M68000::disassembleMOVE_FROM_SR(EffectiveAddress to) -> string { return {"move sr,", _effectiveAddress<Word>(to)}; } auto M68000::disassembleMOVE_TO_CCR(EffectiveAddress from) -> string { return {"move ", _effectiveAddress<Byte>(from), ",ccr"}; } auto M68000::disassembleMOVE_TO_SR(EffectiveAddress from) -> string { return {"move ", _effectiveAddress<Word>(from), ",sr"}; } auto M68000::disassembleMOVE_FROM_USP(AddressRegister to) -> string { return {"move usp,", _addressRegister(to)}; } auto M68000::disassembleMOVE_TO_USP(AddressRegister from) -> string { return {"move ", _addressRegister(from), ",usp"}; } auto M68000::disassembleMULS(EffectiveAddress from, DataRegister with) -> string { return {"muls", _suffix<Word>(), " ", _effectiveAddress<Word>(from), ",", _dataRegister(with)}; } auto M68000::disassembleMULU(EffectiveAddress from, DataRegister with) -> string { return {"mulu", _suffix<Word>(), " ", _effectiveAddress<Word>(from), ",", _dataRegister(with)}; } auto M68000::disassembleNBCD(EffectiveAddress with) -> string { return {"nbcd ", _effectiveAddress<Byte>(with)}; } template<u32 Size> auto M68000::disassembleNEG(EffectiveAddress with) -> string { return {"neg", _suffix<Size>(), " ", _effectiveAddress<Size>(with)}; } template<u32 Size> auto M68000::disassembleNEGX(EffectiveAddress with) -> string { return {"negx", _suffix<Size>(), " ", _effectiveAddress<Size>(with)}; } auto M68000::disassembleNOP() -> string { return {"nop "}; } template<u32 Size> auto M68000::disassembleNOT(EffectiveAddress with) -> string { return {"not", _suffix<Size>(), " ", _effectiveAddress<Size>(with)}; } template<u32 Size> auto M68000::disassembleOR(EffectiveAddress from, DataRegister with) -> string { return {"or", _suffix<Size>(), " ", _effectiveAddress<Size>(from), ",", _dataRegister(with)}; } template<u32 Size> auto M68000::disassembleOR(DataRegister from, EffectiveAddress with) -> string { return {"or", _suffix<Size>(), " ", _dataRegister(from), ",", _effectiveAddress<Size>(with)}; } template<u32 Size> auto M68000::disassembleORI(EffectiveAddress with) -> string { return {"ori", _suffix<Size>(), " ", _immediate<Size>(), ",", _effectiveAddress<Size>(with)}; } auto M68000::disassembleORI_TO_CCR() -> string { return {"ori ", _immediate<Byte>(), ",ccr"}; } auto M68000::disassembleORI_TO_SR() -> string { return {"ori ", _immediate<Word>(), ",sr"}; } auto M68000::disassemblePEA(EffectiveAddress from) -> string { return {"pea ", _effectiveAddress<Long>(from)}; } auto M68000::disassembleRESET() -> string { return {"reset "}; } template<u32 Size> auto M68000::disassembleROL(n4 count, DataRegister with) -> string { return {"rol", _suffix<Size>(), " #", count, ",", _dataRegister(with)}; } template<u32 Size> auto M68000::disassembleROL(DataRegister from, DataRegister with) -> string { return {"rol", _suffix<Size>(), " ", _dataRegister(from), ",", _dataRegister(with)}; } auto M68000::disassembleROL(EffectiveAddress with) -> string { return {"rol", _suffix<Word>(), " ", _effectiveAddress<Word>(with)}; } template<u32 Size> auto M68000::disassembleROR(n4 count, DataRegister with) -> string { return {"ror", _suffix<Size>(), " #", count, ",", _dataRegister(with)}; } template<u32 Size> auto M68000::disassembleROR(DataRegister from, DataRegister with) -> string { return {"ror", _suffix<Size>(), " ", _dataRegister(from) ,",", _dataRegister(with)}; } auto M68000::disassembleROR(EffectiveAddress with) -> string { return {"ror", _suffix<Word>(), " ", _effectiveAddress<Word>(with)}; } template<u32 Size> auto M68000::disassembleROXL(n4 count, DataRegister with) -> string { return {"roxl", _suffix<Size>(), " #", count, ",", _dataRegister(with)}; } template<u32 Size> auto M68000::disassembleROXL(DataRegister from, DataRegister with) -> string { return {"roxl", _suffix<Size>(), " ", _dataRegister(from), ",", _dataRegister(with)}; } auto M68000::disassembleROXL(EffectiveAddress with) -> string { return {"roxl", _suffix<Word>(), " ", _effectiveAddress<Word>(with)}; } template<u32 Size> auto M68000::disassembleROXR(n4 count, DataRegister with) -> string { return {"roxr", _suffix<Size>(), " #", count, ",", _dataRegister(with)}; } template<u32 Size> auto M68000::disassembleROXR(DataRegister from, DataRegister with) -> string { return {"roxr", _suffix<Size>(), " ", _dataRegister(from), ",", _dataRegister(with)}; } auto M68000::disassembleROXR(EffectiveAddress with) -> string { return {"roxr", _suffix<Word>(), " ", _effectiveAddress<Word>(with)}; } auto M68000::disassembleRTE() -> string { return {"rte "}; } auto M68000::disassembleRTR() -> string { return {"rtr "}; } auto M68000::disassembleRTS() -> string { return {"rts "}; } auto M68000::disassembleSBCD(EffectiveAddress from, EffectiveAddress with) -> string { return {"sbcd ", _effectiveAddress<Byte>(from), ",", _effectiveAddress<Byte>(with)}; } auto M68000::disassembleSCC(n4 test, EffectiveAddress to) -> string { return {"s", _condition(test), " ", _effectiveAddress<Byte>(to)}; } auto M68000::disassembleSTOP() -> string { return {"stop ", _immediate<Word>()}; } template<u32 Size> auto M68000::disassembleSUB(EffectiveAddress from, DataRegister with) -> string { return {"sub", _suffix<Size>(), " ", _effectiveAddress<Size>(from), ",", _dataRegister(with)}; } template<u32 Size> auto M68000::disassembleSUB(DataRegister from, EffectiveAddress with) -> string { return {"sub", _suffix<Size>(), " ", _dataRegister(from), ",", _effectiveAddress<Size>(with)}; } template<u32 Size> auto M68000::disassembleSUBA(EffectiveAddress from, AddressRegister with) -> string { return {"suba", _suffix<Size>(), " ", _effectiveAddress<Size>(from), ",", _addressRegister(with)}; } template<u32 Size> auto M68000::disassembleSUBI(EffectiveAddress with) -> string { return {"subi", _suffix<Size>(), " ", _immediate<Size>(), ",", _effectiveAddress<Size>(with)}; } template<u32 Size> auto M68000::disassembleSUBQ(n4 immediate, EffectiveAddress with) -> string { return {"subq", _suffix<Size>(), " #", immediate, ",", _effectiveAddress<Size>(with)}; } template<u32 Size> auto M68000::disassembleSUBQ(n4 immediate, AddressRegister with) -> string { return {"subq", _suffix<Size>(), " #", immediate, ",", _addressRegister(with)}; } template<u32 Size> auto M68000::disassembleSUBX(EffectiveAddress from, EffectiveAddress with) -> string { return {"subx", _suffix<Size>(), " ", _effectiveAddress<Size>(from), ",", _effectiveAddress<Size>(with)}; } auto M68000::disassembleSWAP(DataRegister with) -> string { return {"swap ", _dataRegister(with)}; } auto M68000::disassembleTAS(EffectiveAddress with) -> string { return {"tas ", _effectiveAddress<Byte>(with)}; } auto M68000::disassembleTRAP(n4 vector) -> string { return {"trap #", vector}; } auto M68000::disassembleTRAPV() -> string { return {"trapv "}; } template<u32 Size> auto M68000::disassembleTST(EffectiveAddress from) -> string { return {"tst", _suffix<Size>(), " ", _effectiveAddress<Size>(from)}; } auto M68000::disassembleUNLK(AddressRegister with) -> string { return {"unlk ", _addressRegister(with)}; }
38.755418
136
0.65254
[ "vector" ]
3eb4f548708cc86a50f7f7b108f086d0aca422e8
3,974
cpp
C++
Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchWindowAdvisor.cpp
liu3xing3long/MITK-2016.11
385c506f9792414f40337e106e13d5fd61aa3ccc
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchWindowAdvisor.cpp
liu3xing3long/MITK-2016.11
385c506f9792414f40337e106e13d5fd61aa3ccc
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
Plugins/org.mitk.gui.qt.coreapplication/src/internal/QmitkWorkbenchWindowAdvisor.cpp
liu3xing3long/MITK-2016.11
385c506f9792414f40337e106e13d5fd61aa3ccc
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. 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 or http://www.mitk.org for details. ===================================================================*/ #include "QmitkWorkbenchWindowAdvisor.h" #include "QmitkActionBarAdvisor.h" #include <QMenu> #include <QMenuBar> #include <QMainWindow> #include <QStatusBar> #include <berryPlatform.h> #include <berryPlatformUI.h> #include <berryIActionBarConfigurer.h> #include <berryIWorkbenchWindow.h> #include <berryIPreferencesService.h> #include <internal/berryQtShowViewAction.h> #include <QmitkFileOpenAction.h> #include <QmitkFileExitAction.h> #include <QmitkStatusBar.h> #include <QmitkProgressBar.h> #include <QmitkMemoryUsageIndicatorView.h> #include <QmitkDefaultDropTargetListener.h> #include <QToolBar> QmitkWorkbenchWindowAdvisor::QmitkWorkbenchWindowAdvisor(berry::IWorkbenchWindowConfigurer::Pointer configurer) : berry::WorkbenchWindowAdvisor(configurer) , dropTargetListener(new QmitkDefaultDropTargetListener) { } berry::ActionBarAdvisor::Pointer QmitkWorkbenchWindowAdvisor::CreateActionBarAdvisor( berry::IActionBarConfigurer::Pointer configurer) { berry::ActionBarAdvisor::Pointer actionBarAdvisor(new QmitkActionBarAdvisor(configurer)); return actionBarAdvisor; } void QmitkWorkbenchWindowAdvisor::PostWindowCreate() { // very bad hack... berry::IWorkbenchWindow::Pointer window = this->GetWindowConfigurer()->GetWindow(); QMainWindow* mainWindow = static_cast<QMainWindow*>(window->GetShell()->GetControl()); QMenuBar* menuBar = mainWindow->menuBar(); QMenu* fileMenu = menuBar->addMenu("&File"); fileMenu->addAction(new QmitkFileOpenAction(window)); fileMenu->addSeparator(); fileMenu->addAction(new QmitkFileExitAction(window)); berry::IViewRegistry* viewRegistry = berry::PlatformUI::GetWorkbench()->GetViewRegistry(); QList<berry::IViewDescriptor::Pointer> viewDescriptors = viewRegistry->GetViews(); QMenu* viewMenu = menuBar->addMenu("Show &View"); // sort elements (converting vector to map...) std::map<QString, berry::IViewDescriptor::Pointer> VDMap; for (auto iter = viewDescriptors.begin(); iter != viewDescriptors.end(); ++iter) { if ((*iter)->GetId() == "org.blueberry.ui.internal.introview") continue; std::pair<QString, berry::IViewDescriptor::Pointer> p((*iter)->GetLabel(), (*iter)); VDMap.insert(p); } auto qToolbar = new QToolBar; for (auto MapIter = VDMap.begin(); MapIter != VDMap.end(); ++MapIter) { berry::QtShowViewAction* viewAction = new berry::QtShowViewAction(window, (*MapIter).second); //m_ViewActions.push_back(viewAction); viewMenu->addAction(viewAction); qToolbar->addAction(viewAction); } mainWindow->addToolBar(qToolbar); auto qStatusBar = new QStatusBar(); //creating a QmitkStatusBar for Output on the QStatusBar and connecting it with the MainStatusBar auto statusBar = new QmitkStatusBar(qStatusBar); //disabling the SizeGrip in the lower right corner statusBar->SetSizeGripEnabled(false); auto progBar = new QmitkProgressBar(); qStatusBar->addPermanentWidget(progBar, 0); progBar->hide(); mainWindow->setStatusBar(qStatusBar); auto memoryIndicator = new QmitkMemoryUsageIndicatorView(); qStatusBar->addPermanentWidget(memoryIndicator, 0); } void QmitkWorkbenchWindowAdvisor::PreWindowOpen() { this->GetWindowConfigurer()->AddEditorAreaTransfer(QStringList("text/uri-list")); this->GetWindowConfigurer()->ConfigureEditorAreaDropListener(dropTargetListener.data()); }
33.116667
112
0.717916
[ "vector" ]
3ec07221f48ddf9bbf55becdae7a0dcd3f0cb6f9
8,519
cpp
C++
main/nvs_interface.cpp
mill1000/esp-pwm-timer
21395ac64876fd1d1a1788bded7b46f99c543787
[ "MIT" ]
1
2021-08-09T23:48:00.000Z
2021-08-09T23:48:00.000Z
main/nvs_interface.cpp
mill1000/esp-pwm-timer
21395ac64876fd1d1a1788bded7b46f99c543787
[ "MIT" ]
20
2020-06-30T04:11:53.000Z
2021-02-06T18:26:11.000Z
main/nvs_interface.cpp
mill1000/esp-pwm-timer
21395ac64876fd1d1a1788bded7b46f99c543787
[ "MIT" ]
1
2021-06-22T00:40:54.000Z
2021-06-22T00:40:54.000Z
#include "nvs_flash.h" #include "esp_log.h" #include <string> #include <vector> #include "nvs_interface.h" #include "nvs_parameters.h" #define TAG "NVS" static NvsHelper parameters(NVS::PARAMETER_NAMESPACE); static NvsHelper schedule(NVS::SCHEDULE_NAMESPACE); /** @brief Callback function for the NVS helper to report errors @param name Namespace that caused the error @param key The paramter key that caused the error @param result The esp_error_t of the error @retval none */ static void helper_callback(const std::string& name, const std::string& key, esp_err_t result) { ESP_LOGW(TAG, "NVS Error. Namespace '%s' Key '%s' Error: %s", name.c_str(), key.c_str(), esp_err_to_name(result)); } /** @brief Open the NVS namespace and initialize our parameter object @param none @retval none */ void NVS::init() { ESP_LOGI(TAG, "Initializing NVS interface."); // Open a namespace to hold our parameters if (parameters.open(&helper_callback) != ESP_OK) { ESP_LOGE(TAG, "Error opening NVS namespace '%s'.", PARAMETER_NAMESPACE); return; } uint8_t version = UINT8_MAX; if (parameters.nvs_get<uint8_t>("version", version) == ESP_ERR_NVS_NOT_FOUND) { ESP_LOGW(TAG, "Invalid NVS version in namespace '%s'. Erasing.", PARAMETER_NAMESPACE); reset_configuration(); } // Open a second namespace just to hold the schedule if (schedule.open(&helper_callback) != ESP_OK) { ESP_LOGE(TAG, "Error opening NVS namespace '%s'.", SCHEDULE_NAMESPACE); return; } version = UINT8_MAX; if (schedule.nvs_get<uint8_t>("version", version) == ESP_ERR_NVS_NOT_FOUND) { ESP_LOGW(TAG, "Invalid NVS version in namespace '%s'. Erasing.", SCHEDULE_NAMESPACE); erase_schedule(); } check_required_configuration(); } /** @brief Check required configuration items and reset if empty or not found @param none @retval none */ void NVS::check_required_configuration() { // Ensure we have a hostname or use default configured if (get_hostname().empty()) save_hostname(CONFIG_LWIP_LOCAL_HOSTNAME); // Check and set NTP servers if (get_ntp_server(0).empty()) save_ntp_server(0, CONFIG_NTP_SERVER_1); if (get_ntp_server(1).empty()) save_ntp_server(1, CONFIG_NTP_SERVER_2); // Ensure timezone is set if (get_timezone().empty()) save_timezone(CONFIG_LOCAL_TIMEZONE); } /** @brief Set default configuration parameters @param none @retval none */ void NVS::reset_configuration() { parameters.erase_all(); for (uint8_t i = 0; i < LEDC_TIMER_MAX; i++) save_timer_config((timer_config_t){.id = (ledc_timer_t)i, .frequency_Hz = 500}); for (uint8_t i = 0; i < LEDC_CHANNEL_MAX; i++) save_channel_config("", (channel_config_t){.id = (ledc_channel_t)i, .timer = LEDC_TIMER_0, .gpio = GPIO_NUM_NC, .enabled = false}); // Save default hostname save_hostname(CONFIG_LWIP_LOCAL_HOSTNAME); // Set default NTP servers save_ntp_server(0, CONFIG_NTP_SERVER_1); save_ntp_server(1, CONFIG_NTP_SERVER_2); // Save default timezone save_timezone(CONFIG_LOCAL_TIMEZONE); // Save the version too parameters.nvs_set<uint8_t>("version", NVS_VERSION); parameters.commit(); } /** @brief Save a PWM timer configuration to the NVS @param config timer_config_t to save to the NVS @retval none */ void NVS::save_timer_config(const timer_config_t& config) { // Fuckin stringstreams were truncating the key! char key[16] = {0}; snprintf(key, 16, "timer%d", config.id); parameters.nvs_set<timer_config_t>(std::string(key), config); parameters.commit(); } /** @brief Fetch a PWM timer configuration from the NVS @param id ID of timer @retval timer_config_t */ timer_config_t NVS::get_timer_config(uint32_t id) { // Fuckin stringstreams were truncating the key! char key[16] = {0}; snprintf(key, 16, "timer%d", id); timer_config_t config; parameters.nvs_get<timer_config_t>(std::string(key), config); return config; } /** @brief Save a PWM channel configuration to the NVS @param name Friendly name of the channel @param config channel_config_t to save to the NVS @retval none */ void NVS::save_channel_config(const std::string& name, const channel_config_t& config) { char key[16] = {0}; snprintf(key, 16, "channel%d", config.id); parameters.nvs_set<channel_config_t>(std::string(key), config); parameters.nvs_set<std::string>(std::string(key) + "_name", name); parameters.commit(); } /** @brief Fetch a PWM channel configuration from the NVS @param id ID of timer @retval std::pair<std::string, channel_config_t> */ std::pair<std::string, channel_config_t> NVS::get_channel_config(uint32_t id) { char key[16] = {0}; snprintf(key, 16, "channel%d", id); channel_config_t config; parameters.nvs_get<channel_config_t>(std::string(key), config); std::string name; parameters.nvs_get<std::string>(std::string(key) + "_name", name); return std::make_pair(name, config); } /** @brief Erase all data in the schedule NVS. Does not commit! @param none @retval none */ void NVS::erase_schedule() { schedule.erase_all(); // Restore the version byte schedule.nvs_set<uint8_t>("version", NVS_VERSION); schedule.commit(); } /** @brief Commit changes in the schedule NVS. @param none @retval none */ void NVS::commit_schedule() { // Save timestamp of schedule schedule.nvs_set<time_t>("timestamp", time(nullptr)); // Commit to NVS schedule.commit(); } /** @brief Save a schedule entry JSON representation @param tod Time Of Day key for the schedule entry @param json JSON object for the TOD @retval none */ void NVS::save_schedule_entry_json(const std::string& tod, const std::string& json) { schedule.nvs_set<std::string>(tod, json); } /** @brief Fetch all schedule entry JSON from NVS @param none @retval std::map<std::string, std::string> */ std::map<std::string, std::string> NVS::get_schedule_json() { // Find all keys in the schedule NVS const std::vector<std::string> keys = schedule.nvs_find(NVS_TYPE_STR); std::map<std::string, std::string> schedule_json; for (auto& k : keys) { if (schedule.nvs_get<std::string>(k, schedule_json[k]) != ESP_OK) ESP_LOGW(TAG, "Failed to get NVS schedule entry for '%s'", k.c_str()); } return schedule_json; } /** @brief Fetch timestamp of the last schedule save @param none @retval time_t */ time_t NVS::get_schedule_timestamp() { time_t timestamp = (time_t)(-1); schedule.nvs_get<time_t>("timestamp", timestamp); return timestamp; } /** @brief Save device hostname to NVS @param hostname Hostname of device @retval none */ void NVS::save_hostname(const std::string& hostname) { parameters.nvs_set<std::string>("hostname", hostname); parameters.commit(); } /** @brief Fetch device hostname from NVS @param none @retval std::string */ std::string NVS::get_hostname() { std::string hostname = ""; parameters.nvs_get<std::string>("hostname", hostname); return hostname; } /** @brief Save NTP server to NVS @param index NTP server index. Must be less than CONFIG_LWIP_DHCP_MAX_NTP_SERVERS @param server NTP server hostname or address @retval none */ void NVS::save_ntp_server(uint8_t index, const std::string& server) { if (index >= CONFIG_LWIP_DHCP_MAX_NTP_SERVERS) { ESP_LOGW(TAG, "Invalid NTP server index."); return; } char key[16] = {0}; snprintf(key, 16, "ntp%d", index); parameters.nvs_set<std::string>(key, server); parameters.commit(); } /** @brief Fetch NTP server from NVS @param index NTP server index. Must be less than CONFIG_LWIP_DHCP_MAX_NTP_SERVERS @retval std::string */ std::string NVS::get_ntp_server(uint8_t index) { if (index >= CONFIG_LWIP_DHCP_MAX_NTP_SERVERS) { ESP_LOGW(TAG, "Invalid NTP server index."); return std::string(); } char key[16] = {0}; snprintf(key, 16, "ntp%d", index); std::string server = ""; parameters.nvs_get<std::string>(key, server); return server; } /** @brief Save timezone to NVS @param tz Timezone string @retval none */ void NVS::save_timezone(const std::string& tz) { parameters.nvs_set<std::string>("timezone", tz); parameters.commit(); } /** @brief Fetch timezone from NVS @param none @retval std::string */ std::string NVS::get_timezone() { std::string tz = ""; parameters.nvs_get<std::string>("timezone", tz); return tz; }
22.839142
135
0.6921
[ "object", "vector" ]
3ec1e64b6a6ca9a554cf79146c948b85ba9a2dae
8,966
cc
C++
Firestore/core/test/firebase/firestore/immutable/array_sorted_map_test.cc
trondkr/firebase-sdk-ios
6889850b251ab56186bc13765baee0c3d0f1ae61
[ "Apache-2.0" ]
3
2018-07-16T06:35:13.000Z
2021-04-19T07:18:56.000Z
Firestore/core/test/firebase/firestore/immutable/array_sorted_map_test.cc
trondkr/firebase-sdk-ios
6889850b251ab56186bc13765baee0c3d0f1ae61
[ "Apache-2.0" ]
null
null
null
Firestore/core/test/firebase/firestore/immutable/array_sorted_map_test.cc
trondkr/firebase-sdk-ios
6889850b251ab56186bc13765baee0c3d0f1ae61
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2018 Google * * 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 "Firestore/core/src/firebase/firestore/immutable/array_sorted_map.h" #include <numeric> #include <random> #include "Firestore/core/src/firebase/firestore/util/secure_random.h" #include "gtest/gtest.h" namespace firebase { namespace firestore { namespace immutable { typedef ArraySortedMap<int, int> IntMap; constexpr IntMap::size_type kFixedSize = IntMap::kFixedSize; template <typename K, typename V> testing::AssertionResult NotFound(const ArraySortedMap<K, V>& set, const K& key) { auto found = set.find(key); if (found == set.end()) { return testing::AssertionSuccess(); } else { return testing::AssertionFailure() << "Should not have found (" << found->first << ", " << found->second << ") @ " << found; } } template <typename K, typename V> testing::AssertionResult Found(const ArraySortedMap<K, V>& map, const K& key, const V& expected) { auto found = map.find(key); if (found == map.end()) { return testing::AssertionFailure() << "Did not find key " << key; } if (found->second == expected) { return testing::AssertionSuccess(); } else { return testing::AssertionFailure() << "Found entry was (" << found->first << ", " << found->second << ")"; } } /** * Creates a vector containing a sequence of integers from the given starting * element up to, but not including, the given end element, with values * incremented by the given step. * * If step is negative the sequence is in descending order (but still starting * at start and ending before end). */ std::vector<int> Sequence(int start, int end, int step = 1) { std::vector<int> result; if (step > 0) { for (int i = start; i < end; i += step) { result.push_back(i); } } else { for (int i = start; i > end; i += step) { result.push_back(i); } } return result; } /** * Creates a vector containing a sequence of integers with the given number of * elements, from zero up to, but not including the given value. */ std::vector<int> Sequence(int num_elements) { return Sequence(0, num_elements); } /** * Creates a copy of the given vector with contents shuffled randomly. */ std::vector<int> Shuffled(const std::vector<int>& values) { std::vector<int> result(values); util::SecureRandom rng; std::shuffle(result.begin(), result.end(), rng); return result; } /** * Creates a copy of the given vector with contents sorted. */ std::vector<int> Sorted(const std::vector<int>& values) { std::vector<int> result(values); std::sort(result.begin(), result.end()); return result; } /** * Creates a vector of pairs where each pair has the same first and second * corresponding to an element in the given vector. */ std::vector<std::pair<int, int>> Pairs(const std::vector<int>& values) { std::vector<std::pair<int, int>> result; for (auto&& value : values) { result.emplace_back(value, value); } return result; } /** * Creates an ArraySortedMap by inserting a pair for each value in the vector. * Each pair will have the same key and value. */ IntMap ToMap(const std::vector<int>& values) { IntMap result; for (auto&& value : values) { result = result.insert(value, value); } return result; } /** * Appends the contents of the given container to a new vector. */ template <typename Container> std::vector<typename Container::value_type> Append(const Container& container) { std::vector<typename Container::value_type> result; result.insert(result.begin(), container.begin(), container.end()); return result; } // TODO(wilhuff): ReverseTraversal #define ASSERT_SEQ_EQ(x, y) ASSERT_EQ((x), Append(y)); #define EXPECT_SEQ_EQ(x, y) EXPECT_EQ((x), Append(y)); TEST(ArraySortedMap, SearchForSpecificKey) { IntMap map{{1, 3}, {2, 4}}; ASSERT_TRUE(Found(map, 1, 3)); ASSERT_TRUE(Found(map, 2, 4)); ASSERT_TRUE(NotFound(map, 3)); } TEST(ArraySortedMap, RemoveKeyValuePair) { IntMap map{{1, 3}, {2, 4}}; IntMap new_map = map.erase(1); ASSERT_TRUE(Found(new_map, 2, 4)); ASSERT_TRUE(NotFound(new_map, 1)); // Make sure the original one is not mutated ASSERT_TRUE(Found(map, 1, 3)); ASSERT_TRUE(Found(map, 2, 4)); } TEST(ArraySortedMap, MoreRemovals) { IntMap map = IntMap() .insert(1, 1) .insert(50, 50) .insert(3, 3) .insert(4, 4) .insert(7, 7) .insert(9, 9) .insert(1, 20) .insert(18, 18) .insert(3, 2) .insert(4, 71) .insert(7, 42) .insert(9, 88); ASSERT_TRUE(Found(map, 7, 42)); ASSERT_TRUE(Found(map, 3, 2)); ASSERT_TRUE(Found(map, 1, 20)); IntMap s1 = map.erase(7); IntMap s2 = map.erase(3); IntMap s3 = map.erase(1); ASSERT_TRUE(NotFound(s1, 7)); ASSERT_TRUE(Found(s1, 3, 2)); ASSERT_TRUE(Found(s1, 1, 20)); ASSERT_TRUE(Found(s2, 7, 42)); ASSERT_TRUE(NotFound(s2, 3)); ASSERT_TRUE(Found(s2, 1, 20)); ASSERT_TRUE(Found(s3, 7, 42)); ASSERT_TRUE(Found(s3, 3, 2)); ASSERT_TRUE(NotFound(s3, 1)); } TEST(ArraySortedMap, RemovesMiddle) { IntMap map{{1, 1}, {2, 2}, {3, 3}}; ASSERT_TRUE(Found(map, 1, 1)); ASSERT_TRUE(Found(map, 2, 2)); ASSERT_TRUE(Found(map, 3, 3)); IntMap s1 = map.erase(2); ASSERT_TRUE(Found(s1, 1, 1)); ASSERT_TRUE(NotFound(s1, 2)); ASSERT_TRUE(Found(s1, 3, 3)); } TEST(ArraySortedMap, Increasing) { auto total = static_cast<int>(kFixedSize); IntMap map; for (int i = 0; i < total; i++) { map = map.insert(i, i); } ASSERT_EQ(kFixedSize, map.size()); for (int i = 0; i < total; i++) { map = map.erase(i); } ASSERT_EQ(0u, map.size()); } TEST(ArraySortedMap, Override) { IntMap map = IntMap().insert(10, 10).insert(10, 8); ASSERT_TRUE(Found(map, 10, 8)); ASSERT_FALSE(Found(map, 10, 10)); } TEST(ArraySortedMap, ChecksSize) { std::vector<int> to_insert = Sequence(kFixedSize); IntMap map = ToMap(to_insert); // Replacing an existing entry should not hit increase size map = map.insert(5, 10); int next = kFixedSize; ASSERT_DEATH_IF_SUPPORTED(map.insert(next, next), "new_size <= fixed_size"); } TEST(ArraySortedMap, Empty) { IntMap map = IntMap().insert(10, 10).erase(10); EXPECT_TRUE(map.empty()); EXPECT_EQ(0u, map.size()); EXPECT_TRUE(NotFound(map, 1)); EXPECT_TRUE(NotFound(map, 10)); } TEST(ArraySortedMap, EmptyGet) { IntMap map; EXPECT_TRUE(NotFound(map, 10)); } TEST(ArraySortedMap, EmptySize) { IntMap map; EXPECT_TRUE(map.empty()); EXPECT_EQ(0u, map.size()); } TEST(ArraySortedMap, EmptyRemoval) { IntMap map; IntMap new_map = map.erase(1); EXPECT_TRUE(new_map.empty()); EXPECT_EQ(0u, new_map.size()); EXPECT_TRUE(NotFound(new_map, 1)); } TEST(ArraySortedMap, InsertionAndRemovalOfMaxItems) { auto expected_size = kFixedSize; int n = static_cast<int>(expected_size); std::vector<int> to_insert = Shuffled(Sequence(n)); std::vector<int> to_remove = Shuffled(to_insert); // Add them to the map IntMap map = ToMap(to_insert); ASSERT_EQ(expected_size, map.size()) << "Check if all N objects are in the map"; // check the order is correct ASSERT_SEQ_EQ(Pairs(Sorted(to_insert)), map); for (int i : to_remove) { map = map.erase(i); } ASSERT_EQ(0u, map.size()) << "Check we removed all of the items"; } TEST(ArraySortedMap, BalanceProblem) { std::vector<int> to_insert{1, 7, 8, 5, 2, 6, 4, 0, 3}; IntMap map = ToMap(to_insert); ASSERT_SEQ_EQ(Pairs(Sorted(to_insert)), map); } // TODO(wilhuff): Iterators // TODO(wilhuff): IndexOf TEST(ArraySortedMap, AvoidsCopying) { IntMap map = IntMap().insert(10, 20); auto found = map.find(10); ASSERT_NE(found, map.end()); EXPECT_EQ(20, found->second); // Verify that inserting something with equal keys and values just returns // the same underlying array. IntMap duped = map.insert(10, 20); auto duped_found = duped.find(10); // If everything worked correctly, the backing array should not have been // copied and the pointer to the entry with 10 as key should be the same. EXPECT_EQ(found, duped_found); } } // namespace immutable } // namespace firestore } // namespace firebase
27.41896
80
0.648227
[ "vector" ]
a7939da47fc212ff3d1743885a839a5b134460ce
14,795
cpp
C++
lib/seldon/lib/Compil/Seldon/IterativeSolver.cpp
HongyuHe/lsolver
c791bf192308ba6b564cb60cb3991d2e72093cd7
[ "Apache-2.0" ]
7
2021-01-31T23:20:07.000Z
2021-09-09T20:54:15.000Z
lib/seldon/lib/Compil/Seldon/IterativeSolver.cpp
HongyuHe/lsolver
c791bf192308ba6b564cb60cb3991d2e72093cd7
[ "Apache-2.0" ]
1
2021-06-07T07:52:38.000Z
2021-08-13T20:40:55.000Z
lib/seldon/lib/Compil/Seldon/IterativeSolver.cpp
HongyuHe/lsolver
c791bf192308ba6b564cb60cb3991d2e72093cd7
[ "Apache-2.0" ]
null
null
null
#include "SeldonFlag.hxx" #include "SeldonSolverHeader.hxx" #include "SeldonSolverInline.hxx" #ifdef SELDON_WITH_MPI #include "SeldonDistributedHeader.hxx" #include "SeldonDistributedInline.hxx" #endif #ifndef SELDON_WITH_COMPILED_LIBRARY #include "computation/solver/iterative/Iterative.cxx" #include "computation/solver/preconditioner/Precond_Ssor.cxx" #endif namespace Seldon { SELDON_EXTERN template class Iteration<Real_wp>; SELDON_EXTERN template int Iteration<Real_wp>::Init(const Vector<Real_wp>&); SELDON_EXTERN template int Iteration<Real_wp>::Init(const Vector<Complex_wp >&); SELDON_EXTERN template bool Iteration<Real_wp>::Finished(const Vector<Real_wp>&) const; SELDON_EXTERN template bool Iteration<Real_wp>::Finished(const Vector<Complex_wp >&) const; #ifdef SELDON_WITH_MPI SELDON_EXTERN template int Iteration<Real_wp>::Init(const DistributedVector<Real_wp>&); SELDON_EXTERN template int Iteration<Real_wp>::Init(const DistributedVector<Complex_wp >&); SELDON_EXTERN template bool Iteration<Real_wp>::Finished(const DistributedVector<Real_wp>&) const; SELDON_EXTERN template bool Iteration<Real_wp>::Finished(const DistributedVector<Complex_wp >&) const; #endif #ifdef SELDON_WITH_PRECONDITIONING SELDON_EXTERN template class SorPreconditioner<Real_wp>; SELDON_EXTERN template class SorPreconditioner<Complex_wp >; SELDON_EXTERN template void SorPreconditioner<Real_wp>::SolveGen(const SeldonTranspose&, const VirtualMatrix<Real_wp>&, const Vector<Real_wp>&, Vector<Real_wp>&, bool); SELDON_EXTERN template void SorPreconditioner<Real_wp>::SolveGen(const SeldonTranspose&, const VirtualMatrix<Real_wp>&, const Vector<Complex_wp>&, Vector<Complex_wp>&, bool); SELDON_EXTERN template void SorPreconditioner<Complex_wp>::SolveGen(const SeldonTranspose&, const VirtualMatrix<Complex_wp>&, const Vector<Complex_wp>&, Vector<Complex_wp>&, bool); #endif SELDON_EXTERN template int BiCg(const VirtualMatrix<Real_wp>&, Vector<Real_wp>&, const Vector<Real_wp>&, Preconditioner_Base<Real_wp>&, Iteration<Real_wp>&); SELDON_EXTERN template int BiCg(const VirtualMatrix<Complex_wp >&, Vector<Complex_wp >&, const Vector<Complex_wp >&, Preconditioner_Base<Complex_wp >&, Iteration<Real_wp>&); SELDON_EXTERN template int BiCgStab(const VirtualMatrix<Real_wp>&, Vector<Real_wp>&, const Vector<Real_wp>&, Preconditioner_Base<Real_wp>&, Iteration<Real_wp>&); SELDON_EXTERN template int BiCgStab(const VirtualMatrix<Complex_wp >&, Vector<Complex_wp >&, const Vector<Complex_wp >&, Preconditioner_Base<Complex_wp >&, Iteration<Real_wp>&); SELDON_EXTERN template int BiCgStabl(const VirtualMatrix<Real_wp>&, Vector<Real_wp>&, const Vector<Real_wp>&, Preconditioner_Base<Real_wp>&, Iteration<Real_wp>&); SELDON_EXTERN template int BiCgStabl(const VirtualMatrix<Complex_wp >&, Vector<Complex_wp >&, const Vector<Complex_wp >&, Preconditioner_Base<Complex_wp >&, Iteration<Real_wp>&); SELDON_EXTERN template int BiCgcr(const VirtualMatrix<Real_wp>&, Vector<Real_wp>&, const Vector<Real_wp>&, Preconditioner_Base<Real_wp>&, Iteration<Real_wp>&); SELDON_EXTERN template int BiCgcr(const VirtualMatrix<Complex_wp >&, Vector<Complex_wp >&, const Vector<Complex_wp >&, Preconditioner_Base<Complex_wp >&, Iteration<Real_wp>&); SELDON_EXTERN template int Cg(const VirtualMatrix<Real_wp>&, Vector<Real_wp>&, const Vector<Real_wp>&, Preconditioner_Base<Real_wp>&, Iteration<Real_wp>&); SELDON_EXTERN template int Cg(const VirtualMatrix<Complex_wp >&, Vector<Complex_wp >&, const Vector<Complex_wp >&, Preconditioner_Base<Complex_wp >&, Iteration<Real_wp>&); SELDON_EXTERN template int Cgne(const VirtualMatrix<Real_wp>&, Vector<Real_wp>&, const Vector<Real_wp>&, Preconditioner_Base<Real_wp>&, Iteration<Real_wp>&); SELDON_EXTERN template int Cgne(const VirtualMatrix<Complex_wp >&, Vector<Complex_wp >&, const Vector<Complex_wp >&, Preconditioner_Base<Complex_wp >&, Iteration<Real_wp>&); SELDON_EXTERN template int Cgs(const VirtualMatrix<Real_wp>&, Vector<Real_wp>&, const Vector<Real_wp>&, Preconditioner_Base<Real_wp>&, Iteration<Real_wp>&); SELDON_EXTERN template int Cgs(const VirtualMatrix<Complex_wp >&, Vector<Complex_wp >&, const Vector<Complex_wp >&, Preconditioner_Base<Complex_wp >&, Iteration<Real_wp>&); SELDON_EXTERN template int CoCg(const VirtualMatrix<Real_wp>&, Vector<Real_wp>&, const Vector<Real_wp>&, Preconditioner_Base<Real_wp>&, Iteration<Real_wp>&); SELDON_EXTERN template int CoCg(const VirtualMatrix<Complex_wp >&, Vector<Complex_wp >&, const Vector<Complex_wp >&, Preconditioner_Base<Complex_wp >&, Iteration<Real_wp>&); SELDON_EXTERN template int Gcr(const VirtualMatrix<Real_wp>&, Vector<Real_wp>&, const Vector<Real_wp>&, Preconditioner_Base<Real_wp>&, Iteration<Real_wp>&); SELDON_EXTERN template int Gcr(const VirtualMatrix<Complex_wp >&, Vector<Complex_wp >&, const Vector<Complex_wp >&, Preconditioner_Base<Complex_wp >&, Iteration<Real_wp>&); SELDON_EXTERN template int Gmres(const VirtualMatrix<Real_wp>&, Vector<Real_wp>&, const Vector<Real_wp>&, Preconditioner_Base<Real_wp>&, Iteration<Real_wp>&); SELDON_EXTERN template int Gmres(const VirtualMatrix<Complex_wp >&, Vector<Complex_wp >&, const Vector<Complex_wp >&, Preconditioner_Base<Complex_wp >&, Iteration<Real_wp>&); SELDON_EXTERN template int Lsqr(const VirtualMatrix<Real_wp>&, Vector<Real_wp>&, const Vector<Real_wp>&, Preconditioner_Base<Real_wp>&, Iteration<Real_wp>&); SELDON_EXTERN template int Lsqr(const VirtualMatrix<Complex_wp >&, Vector<Complex_wp >&, const Vector<Complex_wp >&, Preconditioner_Base<Complex_wp >&, Iteration<Real_wp>&); SELDON_EXTERN template int MinRes(const VirtualMatrix<Real_wp>&, Vector<Real_wp>&, const Vector<Real_wp>&, Preconditioner_Base<Real_wp>&, Iteration<Real_wp>&); SELDON_EXTERN template int MinRes(const VirtualMatrix<Complex_wp >&, Vector<Complex_wp >&, const Vector<Complex_wp >&, Preconditioner_Base<Complex_wp >&, Iteration<Real_wp>&); SELDON_EXTERN template int QCgs(const VirtualMatrix<Real_wp>&, Vector<Real_wp>&, const Vector<Real_wp>&, Preconditioner_Base<Real_wp>&, Iteration<Real_wp>&); SELDON_EXTERN template int QCgs(const VirtualMatrix<Complex_wp >&, Vector<Complex_wp >&, const Vector<Complex_wp >&, Preconditioner_Base<Complex_wp >&, Iteration<Real_wp>&); SELDON_EXTERN template int Qmr(const VirtualMatrix<Real_wp>&, Vector<Real_wp>&, const Vector<Real_wp>&, Preconditioner_Base<Real_wp>&, Iteration<Real_wp>&); SELDON_EXTERN template int Qmr(const VirtualMatrix<Complex_wp >&, Vector<Complex_wp >&, const Vector<Complex_wp >&, Preconditioner_Base<Complex_wp >&, Iteration<Real_wp>&); SELDON_EXTERN template int QmrSym(const VirtualMatrix<Real_wp>&, Vector<Real_wp>&, const Vector<Real_wp>&, Preconditioner_Base<Real_wp>&, Iteration<Real_wp>&); SELDON_EXTERN template int QmrSym(const VirtualMatrix<Complex_wp >&, Vector<Complex_wp >&, const Vector<Complex_wp >&, Preconditioner_Base<Complex_wp >&, Iteration<Real_wp>&); SELDON_EXTERN template int Symmlq(const VirtualMatrix<Real_wp>&, Vector<Real_wp>&, const Vector<Real_wp>&, Preconditioner_Base<Real_wp>&, Iteration<Real_wp>&); SELDON_EXTERN template int Symmlq(const VirtualMatrix<Complex_wp >&, Vector<Complex_wp >&, const Vector<Complex_wp >&, Preconditioner_Base<Complex_wp >&, Iteration<Real_wp>&); SELDON_EXTERN template int TfQmr(const VirtualMatrix<Real_wp>&, Vector<Real_wp>&, const Vector<Real_wp>&, Preconditioner_Base<Real_wp>&, Iteration<Real_wp>&); SELDON_EXTERN template int TfQmr(const VirtualMatrix<Complex_wp >&, Vector<Complex_wp >&, const Vector<Complex_wp >&, Preconditioner_Base<Complex_wp >&, Iteration<Real_wp>&); // distributed vectors #ifdef SELDON_WITH_MPI SELDON_EXTERN template int BiCg(const VirtualMatrix<Real_wp>&, DistributedVector<Real_wp>&, const DistributedVector<Real_wp>&, Preconditioner_Base<Real_wp>&, Iteration<Real_wp>&); SELDON_EXTERN template int BiCg(const VirtualMatrix<Complex_wp >&, DistributedVector<Complex_wp >&, const DistributedVector<Complex_wp >&, Preconditioner_Base<Complex_wp >&, Iteration<Real_wp>&); SELDON_EXTERN template int BiCgStab(const VirtualMatrix<Real_wp>&, DistributedVector<Real_wp>&, const DistributedVector<Real_wp>&, Preconditioner_Base<Real_wp>&, Iteration<Real_wp>&); SELDON_EXTERN template int BiCgStab(const VirtualMatrix<Complex_wp >&, DistributedVector<Complex_wp >&, const DistributedVector<Complex_wp >&, Preconditioner_Base<Complex_wp >&, Iteration<Real_wp>&); SELDON_EXTERN template int BiCgStabl(const VirtualMatrix<Real_wp>&, DistributedVector<Real_wp>&, const DistributedVector<Real_wp>&, Preconditioner_Base<Real_wp>&, Iteration<Real_wp>&); SELDON_EXTERN template int BiCgStabl(const VirtualMatrix<Complex_wp >&, DistributedVector<Complex_wp >&, const DistributedVector<Complex_wp >&, Preconditioner_Base<Complex_wp >&, Iteration<Real_wp>&); SELDON_EXTERN template int BiCgcr(const VirtualMatrix<Real_wp>&, DistributedVector<Real_wp>&, const DistributedVector<Real_wp>&, Preconditioner_Base<Real_wp>&, Iteration<Real_wp>&); SELDON_EXTERN template int BiCgcr(const VirtualMatrix<Complex_wp >&, DistributedVector<Complex_wp >&, const DistributedVector<Complex_wp >&, Preconditioner_Base<Complex_wp >&, Iteration<Real_wp>&); SELDON_EXTERN template int Cg(const VirtualMatrix<Real_wp>&, DistributedVector<Real_wp>&, const DistributedVector<Real_wp>&, Preconditioner_Base<Real_wp>&, Iteration<Real_wp>&); SELDON_EXTERN template int Cg(const VirtualMatrix<Complex_wp >&, DistributedVector<Complex_wp >&, const DistributedVector<Complex_wp >&, Preconditioner_Base<Complex_wp >&, Iteration<Real_wp>&); SELDON_EXTERN template int Cgne(const VirtualMatrix<Real_wp>&, DistributedVector<Real_wp>&, const DistributedVector<Real_wp>&, Preconditioner_Base<Real_wp>&, Iteration<Real_wp>&); SELDON_EXTERN template int Cgne(const VirtualMatrix<Complex_wp >&, DistributedVector<Complex_wp >&, const DistributedVector<Complex_wp >&, Preconditioner_Base<Complex_wp >&, Iteration<Real_wp>&); SELDON_EXTERN template int Cgs(const VirtualMatrix<Real_wp>&, DistributedVector<Real_wp>&, const DistributedVector<Real_wp>&, Preconditioner_Base<Real_wp>&, Iteration<Real_wp>&); SELDON_EXTERN template int Cgs(const VirtualMatrix<Complex_wp >&, DistributedVector<Complex_wp >&, const DistributedVector<Complex_wp >&, Preconditioner_Base<Complex_wp >&, Iteration<Real_wp>&); SELDON_EXTERN template int CoCg(const VirtualMatrix<Real_wp>&, DistributedVector<Real_wp>&, const DistributedVector<Real_wp>&, Preconditioner_Base<Real_wp>&, Iteration<Real_wp>&); SELDON_EXTERN template int CoCg(const VirtualMatrix<Complex_wp >&, DistributedVector<Complex_wp >&, const DistributedVector<Complex_wp >&, Preconditioner_Base<Complex_wp >&, Iteration<Real_wp>&); SELDON_EXTERN template int Gcr(const VirtualMatrix<Real_wp>&, DistributedVector<Real_wp>&, const DistributedVector<Real_wp>&, Preconditioner_Base<Real_wp>&, Iteration<Real_wp>&); SELDON_EXTERN template int Gcr(const VirtualMatrix<Complex_wp >&, DistributedVector<Complex_wp >&, const DistributedVector<Complex_wp >&, Preconditioner_Base<Complex_wp >&, Iteration<Real_wp>&); SELDON_EXTERN template int Gmres(const VirtualMatrix<Real_wp>&, DistributedVector<Real_wp>&, const DistributedVector<Real_wp>&, Preconditioner_Base<Real_wp>&, Iteration<Real_wp>&); SELDON_EXTERN template int Gmres(const VirtualMatrix<Complex_wp >&, DistributedVector<Complex_wp >&, const DistributedVector<Complex_wp >&, Preconditioner_Base<Complex_wp >&, Iteration<Real_wp>&); SELDON_EXTERN template int Lsqr(const VirtualMatrix<Real_wp>&, DistributedVector<Real_wp>&, const DistributedVector<Real_wp>&, Preconditioner_Base<Real_wp>&, Iteration<Real_wp>&); SELDON_EXTERN template int Lsqr(const VirtualMatrix<Complex_wp >&, DistributedVector<Complex_wp >&, const DistributedVector<Complex_wp >&, Preconditioner_Base<Complex_wp >&, Iteration<Real_wp>&); SELDON_EXTERN template int MinRes(const VirtualMatrix<Real_wp>&, DistributedVector<Real_wp>&, const DistributedVector<Real_wp>&, Preconditioner_Base<Real_wp>&, Iteration<Real_wp>&); SELDON_EXTERN template int MinRes(const VirtualMatrix<Complex_wp >&, DistributedVector<Complex_wp >&, const DistributedVector<Complex_wp >&, Preconditioner_Base<Complex_wp >&, Iteration<Real_wp>&); SELDON_EXTERN template int QCgs(const VirtualMatrix<Real_wp>&, DistributedVector<Real_wp>&, const DistributedVector<Real_wp>&, Preconditioner_Base<Real_wp>&, Iteration<Real_wp>&); SELDON_EXTERN template int QCgs(const VirtualMatrix<Complex_wp >&, DistributedVector<Complex_wp >&, const DistributedVector<Complex_wp >&, Preconditioner_Base<Complex_wp >&, Iteration<Real_wp>&); SELDON_EXTERN template int Qmr(const VirtualMatrix<Real_wp>&, DistributedVector<Real_wp>&, const DistributedVector<Real_wp>&, Preconditioner_Base<Real_wp>&, Iteration<Real_wp>&); SELDON_EXTERN template int Qmr(const VirtualMatrix<Complex_wp >&, DistributedVector<Complex_wp >&, const DistributedVector<Complex_wp >&, Preconditioner_Base<Complex_wp >&, Iteration<Real_wp>&); SELDON_EXTERN template int QmrSym(const VirtualMatrix<Real_wp>&, DistributedVector<Real_wp>&, const DistributedVector<Real_wp>&, Preconditioner_Base<Real_wp>&, Iteration<Real_wp>&); SELDON_EXTERN template int QmrSym(const VirtualMatrix<Complex_wp >&, DistributedVector<Complex_wp >&, const DistributedVector<Complex_wp >&, Preconditioner_Base<Complex_wp >&, Iteration<Real_wp>&); SELDON_EXTERN template int Symmlq(const VirtualMatrix<Real_wp>&, DistributedVector<Real_wp>&, const DistributedVector<Real_wp>&, Preconditioner_Base<Real_wp>&, Iteration<Real_wp>&); SELDON_EXTERN template int Symmlq(const VirtualMatrix<Complex_wp >&, DistributedVector<Complex_wp >&, const DistributedVector<Complex_wp >&, Preconditioner_Base<Complex_wp >&, Iteration<Real_wp>&); SELDON_EXTERN template int TfQmr(const VirtualMatrix<Real_wp>&, DistributedVector<Real_wp>&, const DistributedVector<Real_wp>&, Preconditioner_Base<Real_wp>&, Iteration<Real_wp>&); SELDON_EXTERN template int TfQmr(const VirtualMatrix<Complex_wp >&, DistributedVector<Complex_wp >&, const DistributedVector<Complex_wp >&, Preconditioner_Base<Complex_wp >&, Iteration<Real_wp>&); #endif }
59.417671
182
0.768503
[ "vector" ]
a794d09f809dcce113f66bc682eedf5edad40024
3,751
cpp
C++
hands-on/memory/grouping.cpp
Hiigaran/esc21
d0d7f0fa7079edc124821e96ef677cda2a2235a1
[ "CC-BY-4.0" ]
1
2021-11-05T14:44:55.000Z
2021-11-05T14:44:55.000Z
hands-on/memory/grouping.cpp
Hiigaran/esc21
d0d7f0fa7079edc124821e96ef677cda2a2235a1
[ "CC-BY-4.0" ]
null
null
null
hands-on/memory/grouping.cpp
Hiigaran/esc21
d0d7f0fa7079edc124821e96ef677cda2a2235a1
[ "CC-BY-4.0" ]
null
null
null
// // c++ -O2 grouping.cpp memory_usage.cc /usr/local/Cellar/jemalloc/5.1.0/lib/libjemalloc.dylib // #include<random> #include<vector> #include<cstdint> #include<algorithm> #include<iostream> #include<cassert> #include<chrono> #include "memory_usage.h" auto start = std::chrono::high_resolution_clock::now(); uint64_t maxLive=0; void stop(const char * m) { auto delta = std::chrono::high_resolution_clock::now()-start; maxLive= std::max( maxLive, memory_usage::totlive() ); std::cout << m; std::cout << " elapsted time (ms) " << std::chrono::duration_cast<std::chrono::milliseconds>(delta).count() << std::endl; std::cout << "allocated so far " << memory_usage::allocated(); std::cout << " deallocated so far " << memory_usage::deallocated() << std::endl; std::cout << "total / max live " << memory_usage::totlive() << ' ' << maxLive << std::endl; start = std::chrono::high_resolution_clock::now(); } constexpr int NG=100000; constexpr int ME=80; std::mt19937 reng; std::poisson_distribution<int> aGen(NG); std::poisson_distribution<int> bGen(ME); class Generator { public: void generate(bool doprint) { // generate ng groups ng = aGen(reng); // for each group generate elements int ne[ng]; totElements=0; for(auto i=0U;i<ng;++i) totElements += (ne[i]=bGen(reng)); if (doprint) std::cout << "--- Generated " << totElements << " in " << ng << " groups" << std::endl; } // return to which "initial group" element i has been found... uint32_t protoGroup(uint32_t i) const { i = i%totElements; i = i%ng + (i/7)%ng; // add a "beat" (some groups may be empty...) return i%ng; } // return in which subgroup of "g" "i" belongs ( 0 or 1) uint32_t split(uint32_t g, uint32_t i) const { // assert(protoGroup(i)==g); return (g%1014) ? (i%3)/2 : 0; } auto nElements() const { return totElements; } // fake weight float weight(uint32_t el) const { // assert(el< totElements); return 0.01f*float(el); } private: uint32_t ng; uint32_t totElements; }; Generator generator; #include<map> // not necessarely the best choice! #include<unordered_map> // not necessarely the best choice! void one(bool doprint) { if (doprint) stop("before generation"); generator.generate(doprint); auto ntot = generator.nElements(); if (doprint) stop("aftert generation"); // here you have to find the first set of groups // in principle you are allowed to call generator.protoGroup only ONCE per element as it is faking an clustering algo // this is just a test to verify the generator // std::unordered_map<int,int> count; // in std the default constructor of int IS int(0) std::map<int,int> count; // in std the default constructor of int IS int(0) for (auto i=0U;i<ntot;++i) ++count[generator.protoGroup(i)]; if (doprint) std::cout << "--- Found " << count.size() << " proto-groups" << std::endl; if (doprint) stop("aftert protoGroups"); // and then split them in the final set // again a test of consistency.... for (auto i=0U;i<ntot;++i) { auto sub = generator.split(generator.protoGroup(i),i); // no, you are not allowed to use generator.protoGroup here!! assert(sub<2); } if (doprint) stop("after splitting"); // at the end you should be able to tell with element is in which final group... // for instance demonstrate you can compute the total "weight" of a group calling generator.weight(j); if (doprint) stop("end of algo"); } int main() { one(true); stop("\nafter call: "); for (int i=0; i<20; ++i) { one(false); // stop("after call"); } stop("\nafter loop in main: "); one(true); stop("\nat the end: "); return 0; }
24.2
123
0.645428
[ "vector" ]
a79be2bfc9b1d9b5754752b07f5fa19fe187f577
4,454
cpp
C++
sp/src/game/server/mapbase/point_copy_size.cpp
Nbc66/source-sdk-2013
cda054fcfe661c6166191b30d7b1d6fd29873d39
[ "Unlicense" ]
2
2020-05-16T22:32:32.000Z
2020-05-17T00:04:38.000Z
sp/src/game/server/mapbase/point_copy_size.cpp
Nbc66/source-sdk-2013
cda054fcfe661c6166191b30d7b1d6fd29873d39
[ "Unlicense" ]
null
null
null
sp/src/game/server/mapbase/point_copy_size.cpp
Nbc66/source-sdk-2013
cda054fcfe661c6166191b30d7b1d6fd29873d39
[ "Unlicense" ]
null
null
null
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: Copies size. // //============================================================================= #include "cbase.h" //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- class CPointCopySize : public CLogicalEntity { DECLARE_CLASS( CPointCopySize, CLogicalEntity ); private: // The entity to copy the size from. // m_target is the target that receives it. string_t m_iszSizeSource; EHANDLE m_hSizeSource; EHANDLE m_hTarget; float m_flScale; void CopySize(CBaseEntity *pSource, CBaseEntity *pTarget); // Inputs void InputCopySize( inputdata_t &inputdata ); void InputCopySizeToEntity( inputdata_t &inputdata ); void InputCopySizeFromEntity( inputdata_t &inputdata ); void InputSetTarget( inputdata_t &inputdata ) { BaseClass::InputSetTarget(inputdata); m_hTarget = NULL; } void InputSetSource( inputdata_t &inputdata ) { m_iszSizeSource = inputdata.value.StringID(); m_hSizeSource = NULL; } // Outputs COutputEvent m_OnCopy; DECLARE_DATADESC(); }; LINK_ENTITY_TO_CLASS(point_copy_size, CPointCopySize); BEGIN_DATADESC( CPointCopySize ) // Keys DEFINE_KEYFIELD(m_iszSizeSource, FIELD_STRING, "source"), DEFINE_FIELD(m_hSizeSource, FIELD_EHANDLE), DEFINE_FIELD(m_hTarget, FIELD_EHANDLE), DEFINE_INPUT(m_flScale, FIELD_FLOAT, "SetScale"), // Inputs DEFINE_INPUTFUNC( FIELD_VOID, "CopySize", InputCopySize ), DEFINE_INPUTFUNC( FIELD_EHANDLE, "CopySizeToEntity", InputCopySizeToEntity ), DEFINE_INPUTFUNC( FIELD_EHANDLE, "CopySizeFromEntity", InputCopySizeFromEntity ), DEFINE_INPUTFUNC( FIELD_STRING, "SetSource", InputSetSource ), // Outputs DEFINE_OUTPUT(m_OnCopy, "OnCopy"), END_DATADESC() //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CPointCopySize::CopySize(CBaseEntity *pSource, CBaseEntity *pTarget) { const Vector cvecAlignMins = pSource->WorldAlignMins(); const Vector cvecAlignMaxs = pSource->WorldAlignMaxs(); Vector vecAlignMins = Vector(cvecAlignMins); Vector vecAlignMaxs = Vector(cvecAlignMaxs); if (m_flScale != 0.0f && m_flScale != 1.0f) { vecAlignMins *= m_flScale; vecAlignMaxs *= m_flScale; } pTarget->SetCollisionBounds(vecAlignMins, vecAlignMins); m_OnCopy.FireOutput(pTarget, this); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CPointCopySize::InputCopySize( inputdata_t &inputdata ) { if (!m_hSizeSource) m_hSizeSource = gEntList.FindEntityByName(NULL, STRING(m_iszSizeSource), this, inputdata.pActivator, inputdata.pCaller); if (!m_hTarget) m_hTarget = gEntList.FindEntityByName(NULL, STRING(m_target), this, inputdata.pActivator, inputdata.pCaller); if (!m_hSizeSource || !m_hTarget) { Warning("%s (%s): Could not find %s\n", GetClassname(), GetDebugName(), !m_hSizeSource ? "size source" : "target to copy size to"); return; } CopySize(m_hSizeSource, m_hTarget); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CPointCopySize::InputCopySizeToEntity( inputdata_t &inputdata ) { if (!m_hSizeSource) m_hSizeSource = gEntList.FindEntityByName(NULL, STRING(m_iszSizeSource), this, inputdata.pActivator, inputdata.pCaller); if (!m_hSizeSource) { Warning("%s (%s): Could not find size source\n", GetClassname(), GetDebugName()); return; } if (!inputdata.value.Entity()) return; CopySize(m_hSizeSource, inputdata.value.Entity()); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CPointCopySize::InputCopySizeFromEntity( inputdata_t &inputdata ) { if (!m_hTarget) m_hTarget = gEntList.FindEntityByName(NULL, STRING(m_target), this, inputdata.pActivator, inputdata.pCaller); if (!m_hTarget) { Warning("%s (%s): Could not find target to copy size to\n", GetClassname(), GetDebugName()); return; } if (!inputdata.value.Entity()) return; CopySize(inputdata.value.Entity(), m_hTarget); }
30.930556
133
0.599686
[ "vector" ]
a79c8a36752f7a541b2ce3a06f5b26373ceb6886
18,436
cpp
C++
aten/src/ATen/native/mkl/SpectralOps.cpp
mleshen/pytorch
314a578154d9f0981bc08397aaaeaf50d8233730
[ "Intel" ]
1
2021-05-11T11:53:47.000Z
2021-05-11T11:53:47.000Z
aten/src/ATen/native/mkl/SpectralOps.cpp
mleshen/pytorch
314a578154d9f0981bc08397aaaeaf50d8233730
[ "Intel" ]
1
2021-05-10T01:18:33.000Z
2021-05-10T01:18:33.000Z
aten/src/ATen/native/mkl/SpectralOps.cpp
mleshen/pytorch
314a578154d9f0981bc08397aaaeaf50d8233730
[ "Intel" ]
1
2021-08-06T22:50:37.000Z
2021-08-06T22:50:37.000Z
#include <ATen/ATen.h> #include <ATen/Config.h> #include <ATen/native/Resize.h> #include <ATen/native/SpectralOpsUtils.h> #include <ATen/NativeFunctions.h> #include <c10/util/accumulate.h> #if !AT_MKL_ENABLED() namespace at { namespace native { // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) REGISTER_NO_CPU_DISPATCH(fft_fill_with_conjugate_symmetry_stub, fft_fill_with_conjugate_symmetry_fn); Tensor _fft_c2r_mkl(const Tensor& self, IntArrayRef dim, int64_t normalization, int64_t last_dim_size) { AT_ERROR("fft: ATen not compiled with MKL support"); } Tensor _fft_r2c_mkl(const Tensor& self, IntArrayRef dim, int64_t normalization, bool onesided) { AT_ERROR("fft: ATen not compiled with MKL support"); } Tensor _fft_c2c_mkl(const Tensor& self, IntArrayRef dim, int64_t normalization, bool forward) { AT_ERROR("fft: ATen not compiled with MKL support"); } Tensor& _fft_r2c_mkl_out(const Tensor& self, IntArrayRef dim, int64_t normalization, bool onesided, Tensor& out) { AT_ERROR("fft: ATen not compiled with MKL support"); } Tensor& _fft_c2r_mkl_out(const Tensor& self, IntArrayRef dim, int64_t normalization, int64_t last_dim_size, Tensor& out) { AT_ERROR("fft: ATen not compiled with MKL support"); } Tensor& _fft_c2c_mkl_out(const Tensor& self, IntArrayRef dim, int64_t normalization, bool forward, Tensor& out) { AT_ERROR("fft: ATen not compiled with MKL support"); } }} #else // AT_MKL_ENABLED #include <ATen/ATen.h> #include <ATen/Config.h> #include <ATen/Dispatch.h> #include <ATen/NativeFunctions.h> #include <ATen/Parallel.h> #include <ATen/Utils.h> #include <ATen/native/TensorIterator.h> #include <algorithm> #include <vector> #include <numeric> #include <cmath> #include <mkl_dfti.h> #include <ATen/mkl/Exceptions.h> #include <ATen/mkl/Descriptors.h> #include <ATen/mkl/Limits.h> namespace at { namespace native { // In real-to-complex transform, MKL FFT only fills half of the values due to // conjugate symmetry. See native/SpectralUtils.h for more details. // The following structs are used to fill in the other half with symmetry in // case of real-to-complex transform with onesided=False flag. // See NOTE [ Fourier Transform Conjugate Symmetry ] in native/SpectralOpsUtils.h. template <typename scalar_t> static __ubsan_ignore_undefined__ // UBSAN gives false positives on using negative indexes with a pointer void _fft_fill_with_conjugate_symmetry_slice( Range range, at::ArrayRef<bool> is_mirrored_dim, IntArrayRef signal_half_sizes, IntArrayRef in_strides, const scalar_t * in_ptr, IntArrayRef out_strides, scalar_t * out_ptr) { const auto ndim = signal_half_sizes.size(); DimVector iter_index(ndim, 0); // We explicitly loop over one row, then use this lambda to iterate over // n-dimensions. This advances iter_index by one row, while updating in_ptr // and out_ptr to point to the new row of data. auto advance_index = [&] () __ubsan_ignore_undefined__ { for (size_t i = 1; i < iter_index.size(); ++i) { if (iter_index[i] + 1 < signal_half_sizes[i]) { ++iter_index[i]; in_ptr += in_strides[i]; if (is_mirrored_dim[i]) { if (iter_index[i] == 1) { out_ptr += (signal_half_sizes[i] - 1) * out_strides[i]; } else { out_ptr -= out_strides[i]; } } else { out_ptr += out_strides[i]; } return; } in_ptr -= in_strides[i] * iter_index[i]; if (is_mirrored_dim[i]) { out_ptr -= out_strides[i]; } else { out_ptr -= out_strides[i] * iter_index[i]; } iter_index[i] = 0; } }; // The data slice we operate on may start part-way into the data // Update iter_index and pointers to reference the start of the slice if (range.begin > 0) { iter_index[0] = range.begin % signal_half_sizes[0]; auto linear_idx = range.begin / signal_half_sizes[0]; for (size_t i = 1; i < ndim && linear_idx > 0; ++i) { iter_index[i] = linear_idx % signal_half_sizes[i]; linear_idx = linear_idx / signal_half_sizes[i]; if (iter_index[i] > 0) { in_ptr += in_strides[i] * iter_index[i]; if (is_mirrored_dim[i]) { out_ptr += out_strides[i] * (signal_half_sizes[i] - iter_index[i]); } else { out_ptr += out_strides[i] * iter_index[i]; } } } } auto numel_remaining = range.end - range.begin; if (is_mirrored_dim[0]) { // Explicitly loop over a Hermitian mirrored dimension if (iter_index[0] > 0) { auto end = std::min(signal_half_sizes[0], iter_index[0] + numel_remaining); for (int64_t i = iter_index[0]; i < end; ++i) { out_ptr[(signal_half_sizes[0] - i) * out_strides[0]] = std::conj(in_ptr[i * in_strides[0]]); } numel_remaining -= (end - iter_index[0]); iter_index[0] = 0; advance_index(); } while (numel_remaining > 0) { auto end = std::min(signal_half_sizes[0], numel_remaining); out_ptr[0] = std::conj(in_ptr[0]); for (int64_t i = 1; i < end; ++i) { out_ptr[(signal_half_sizes[0] - i) * out_strides[0]] = std::conj(in_ptr[i * in_strides[0]]); } numel_remaining -= end; advance_index(); } } else { // Explicit loop over a non-mirrored dimension, so just a simple conjugated copy while (numel_remaining > 0) { auto end = std::min(signal_half_sizes[0], iter_index[0] + numel_remaining); for (int64_t i = iter_index[0]; i != end; ++i) { out_ptr[i * out_strides[0]] = std::conj(in_ptr[i * in_strides[0]]); } numel_remaining -= (end - iter_index[0]); iter_index[0] = 0; advance_index(); } } } static void _fft_fill_with_conjugate_symmetry_cpu_( ScalarType dtype, IntArrayRef mirror_dims, IntArrayRef signal_half_sizes, IntArrayRef in_strides_bytes, const void * in_data, IntArrayRef out_strides_bytes, void * out_data) { // Convert strides from bytes to elements const auto element_size = scalarTypeToTypeMeta(dtype).itemsize(); const auto ndim = signal_half_sizes.size(); DimVector in_strides(ndim), out_strides(ndim); for (int64_t i = 0; i < ndim; ++i) { TORCH_INTERNAL_ASSERT(in_strides_bytes[i] % element_size == 0); in_strides[i] = in_strides_bytes[i] / element_size; TORCH_INTERNAL_ASSERT(out_strides_bytes[i] % element_size == 0); out_strides[i] = out_strides_bytes[i] / element_size; } // Construct boolean mask for mirrored dims c10::SmallVector<bool, at::kDimVectorStaticSize> is_mirrored_dim(ndim, false); for (const auto& dim : mirror_dims) { is_mirrored_dim[dim] = true; } const auto numel = c10::multiply_integers(signal_half_sizes); AT_DISPATCH_COMPLEX_TYPES(dtype, "_fft_fill_with_conjugate_symmetry", [&] { at::parallel_for(0, numel, at::internal::GRAIN_SIZE, [&](int64_t begin, int64_t end) { _fft_fill_with_conjugate_symmetry_slice( {begin, end}, is_mirrored_dim, signal_half_sizes, in_strides, static_cast<const scalar_t*>(in_data), out_strides, static_cast<scalar_t*>(out_data)); }); }); } // Register this one implementation for all cpu types instead of compiling multiple times REGISTER_ARCH_DISPATCH(fft_fill_with_conjugate_symmetry_stub, DEFAULT, &_fft_fill_with_conjugate_symmetry_cpu_) REGISTER_AVX_DISPATCH(fft_fill_with_conjugate_symmetry_stub, &_fft_fill_with_conjugate_symmetry_cpu_) REGISTER_AVX2_DISPATCH(fft_fill_with_conjugate_symmetry_stub, &_fft_fill_with_conjugate_symmetry_cpu_) // Constructs an mkl-fft plan descriptor representing the desired transform // For complex types, strides are in units of 2 * element_size(dtype) // sizes are for the full signal, including batch size and always two-sided static DftiDescriptor _plan_mkl_fft( IntArrayRef in_strides, IntArrayRef out_strides, IntArrayRef sizes, bool complex_input, bool complex_output, int64_t normalization, bool forward, ScalarType dtype) { const int64_t signal_ndim = sizes.size() - 1; TORCH_INTERNAL_ASSERT(in_strides.size() == sizes.size()); TORCH_INTERNAL_ASSERT(out_strides.size() == sizes.size()); // precision const DFTI_CONFIG_VALUE prec = [&]{ switch (c10::toValueType(dtype)) { case ScalarType::Float: return DFTI_SINGLE; case ScalarType::Double: return DFTI_DOUBLE; default: TORCH_CHECK(false, "MKL FFT doesn't support tensors of type: ", dtype); } }(); // signal type const DFTI_CONFIG_VALUE signal_type = [&]{ if (forward) { return complex_input ? DFTI_COMPLEX : DFTI_REAL; } else { return complex_output ? DFTI_COMPLEX : DFTI_REAL; } }(); // create descriptor with signal size using MklDimVector = c10::SmallVector<MKL_LONG, at::kDimVectorStaticSize>; MklDimVector mkl_signal_sizes(sizes.begin() + 1, sizes.end()); DftiDescriptor descriptor; descriptor.init(prec, signal_type, signal_ndim, mkl_signal_sizes.data()); // out of place FFT MKL_DFTI_CHECK(DftiSetValue(descriptor.get(), DFTI_PLACEMENT, DFTI_NOT_INPLACE)); // batch mode MKL_LONG mkl_batch_size = sizes[0]; MKL_DFTI_CHECK(DftiSetValue(descriptor.get(), DFTI_NUMBER_OF_TRANSFORMS, mkl_batch_size)); // batch dim stride, i.e., dist between each data TORCH_CHECK(in_strides[0] <= MKL_LONG_MAX && out_strides[0] <= MKL_LONG_MAX); MKL_LONG idist = in_strides[0]; MKL_LONG odist = out_strides[0]; MKL_DFTI_CHECK(DftiSetValue(descriptor.get(), DFTI_INPUT_DISTANCE, idist)); MKL_DFTI_CHECK(DftiSetValue(descriptor.get(), DFTI_OUTPUT_DISTANCE, odist)); // signal strides // first val is offset, set to zero (ignored) MklDimVector mkl_istrides(1 + signal_ndim, 0), mkl_ostrides(1 + signal_ndim, 0); for (int64_t i = 1; i <= signal_ndim; i++) { TORCH_CHECK(in_strides[i] <= MKL_LONG_MAX && out_strides[i] <= MKL_LONG_MAX); mkl_istrides[i] = in_strides[i]; mkl_ostrides[i] = out_strides[i]; } MKL_DFTI_CHECK(DftiSetValue(descriptor.get(), DFTI_INPUT_STRIDES, mkl_istrides.data())); MKL_DFTI_CHECK(DftiSetValue(descriptor.get(), DFTI_OUTPUT_STRIDES, mkl_ostrides.data())); // if conjugate domain of real is involved, set standard CCE storage type // this will become default in MKL in future if (!complex_input || !complex_output) { MKL_DFTI_CHECK(DftiSetValue(descriptor.get(), DFTI_CONJUGATE_EVEN_STORAGE, DFTI_COMPLEX_COMPLEX)); } // rescale if requested const auto norm = static_cast<fft_norm_mode>(normalization); int64_t signal_numel = c10::multiply_integers(IntArrayRef(sizes.data() + 1, signal_ndim)); if (norm != fft_norm_mode::none) { const double scale = ( (norm == fft_norm_mode::by_root_n) ? 1.0 / std::sqrt(static_cast<double>(signal_numel)) : 1.0 / static_cast<double>(signal_numel)); const auto scale_direction = forward ? DFTI_FORWARD_SCALE : DFTI_BACKWARD_SCALE; MKL_DFTI_CHECK(DftiSetValue(descriptor.get(), scale_direction, scale)); } if (sizeof(MKL_LONG) < sizeof(int64_t)) { TORCH_CHECK(signal_numel <= MKL_LONG_MAX, "MKL FFT: input signal numel exceeds allowed range [1, ", MKL_LONG_MAX, "]"); } // finalize MKL_DFTI_CHECK(DftiCommitDescriptor(descriptor.get())); return descriptor; } // Execute a general fft operation (can be c2c, onesided r2c or onesided c2r) static Tensor& _exec_fft(Tensor& out, const Tensor& self, IntArrayRef out_sizes, IntArrayRef dim, int64_t normalization, bool forward) { const auto ndim = self.dim(); const int64_t signal_ndim = dim.size(); const auto batch_dims = ndim - signal_ndim; // Permute dimensions so batch dimensions come first, and in stride order // This maximizes data locality when collapsing to a single batch dimension DimVector dim_permute(ndim); std::iota(dim_permute.begin(), dim_permute.end(), int64_t{0}); c10::SmallVector<bool, kDimVectorStaticSize> is_transformed_dim(ndim); for (const auto& d : dim) { is_transformed_dim[d] = true; } auto batch_end = std::partition(dim_permute.begin(), dim_permute.end(), [&](int64_t d) {return !is_transformed_dim[d]; }); auto self_strides = self.strides(); std::sort(dim_permute.begin(), batch_end, [&](int64_t a, int64_t b) { return self_strides[a] > self_strides[b]; }); std::copy(dim.cbegin(), dim.cend(), batch_end); auto input = self.permute(dim_permute); // Collapse batch dimensions into a single dimension DimVector batched_sizes(signal_ndim + 1); batched_sizes[0] = -1; std::copy(input.sizes().cbegin() + batch_dims, input.sizes().cend(), batched_sizes.begin() + 1); input = input.reshape(batched_sizes); const auto batch_size = input.sizes()[0]; DimVector signal_size(signal_ndim + 1); signal_size[0] = batch_size; for (int64_t i = 0; i < signal_ndim; ++i) { auto in_size = input.sizes()[i + 1]; auto out_size = out_sizes[dim[i]]; signal_size[i + 1] = std::max(in_size, out_size); TORCH_INTERNAL_ASSERT(in_size == signal_size[i + 1] || in_size == (signal_size[i + 1] / 2) + 1); TORCH_INTERNAL_ASSERT(out_size == signal_size[i + 1] || out_size == (signal_size[i + 1] / 2) + 1); } batched_sizes[0] = batch_size; DimVector batched_out_sizes(batched_sizes.begin(), batched_sizes.end()); for (size_t i = 0; i < dim.size(); ++i) { batched_out_sizes[i + 1] = out_sizes[dim[i]]; } const auto value_type = c10::toValueType(input.scalar_type()); out.resize_(batched_out_sizes, MemoryFormat::Contiguous); auto descriptor = _plan_mkl_fft( input.strides(), out.strides(), signal_size, input.is_complex(), out.is_complex(), normalization, forward, value_type); // run the FFT if (forward) { MKL_DFTI_CHECK(DftiComputeForward(descriptor.get(), input.data_ptr(), out.data_ptr())); } else { MKL_DFTI_CHECK(DftiComputeBackward(descriptor.get(), input.data_ptr(), out.data_ptr())); } // Inplace reshaping to original batch shape and inverting the dimension permutation DimVector out_strides(ndim); int64_t batch_numel = 1; for (int64_t i = batch_dims - 1; i >= 0; --i) { out_strides[dim_permute[i]] = batch_numel * out.strides()[0]; batch_numel *= out_sizes[dim_permute[i]]; } for (int64_t i = batch_dims; i < ndim; ++i) { out_strides[dim_permute[i]] = out.strides()[1 + (i - batch_dims)]; } out.as_strided_(out_sizes, out_strides, out.storage_offset()); return out; } // Sort transform dimensions by input layout, for best performance // exclude_last is for onesided transforms where the last dimension cannot be reordered static DimVector _sort_dims(const Tensor& self, IntArrayRef dim, bool exclude_last=false) { DimVector sorted_dims(dim.begin(), dim.end()); auto self_strides = self.strides(); std::sort(sorted_dims.begin(), sorted_dims.end() - exclude_last, [&](int64_t a, int64_t b) { return self_strides[a] > self_strides[b]; }); return sorted_dims; } // n-dimensional complex to real IFFT Tensor _fft_c2r_mkl(const Tensor& self, IntArrayRef dim, int64_t normalization, int64_t last_dim_size) { TORCH_CHECK(self.is_complex()); // NOTE: Multi-dimensional C2R transforms don't agree with numpy in cases // where the input isn't strictly Hermitian-symmetric. Instead, we use a // multi-dim C2C transform followed by a 1D C2R transform. // // Such inputs are technically out of contract though, so maybe a disagreement // is okay. auto input = self; if (dim.size() > 1) { auto c2c_dims = dim.slice(0, dim.size() - 1); input = _fft_c2c_mkl(self, c2c_dims, normalization, /*foward=*/false); dim = dim.slice(dim.size() - 1); } auto in_sizes = input.sizes(); DimVector out_sizes(in_sizes.begin(), in_sizes.end()); out_sizes[dim.back()] = last_dim_size; auto out = at::empty(out_sizes, self.options().dtype(c10::toValueType(self.scalar_type()))); return _exec_fft(out, input, out_sizes, dim, normalization, /*forward=*/false); } Tensor& _fft_c2r_mkl_out(const Tensor& self, IntArrayRef dim, int64_t normalization, int64_t last_dim_size, Tensor& out) { auto result = _fft_c2r_mkl(self, dim, normalization, last_dim_size); resize_output(out, result.sizes()); return out.copy_(result); } // n-dimensional real to complex FFT Tensor _fft_r2c_mkl(const Tensor& self, IntArrayRef dim, int64_t normalization, bool onesided) { TORCH_CHECK(self.is_floating_point()); auto input_sizes = self.sizes(); DimVector out_sizes(input_sizes.begin(), input_sizes.end()); auto last_dim = dim.back(); auto last_dim_halfsize = (input_sizes[last_dim]) / 2 + 1; if (onesided) { out_sizes[last_dim] = last_dim_halfsize; } auto sorted_dims = _sort_dims(self, dim, /*exclude_last=*/true); auto out = at::empty(out_sizes, self.options().dtype(c10::toComplexType(self.scalar_type()))); _exec_fft(out, self, out_sizes, sorted_dims, normalization, /*forward=*/true); if (!onesided) { at::native::_fft_fill_with_conjugate_symmetry_(out, dim); } return out; } Tensor& _fft_r2c_mkl_out(const Tensor& self, IntArrayRef dim, int64_t normalization, bool onesided, Tensor& out) { auto result = _fft_r2c_mkl(self, dim, normalization, /*onesided=*/true); if (onesided) { resize_output(out, result.sizes()); return out.copy_(result); } resize_output(out, self.sizes()); auto last_dim = dim.back(); auto last_dim_halfsize = result.sizes()[last_dim]; auto out_slice = out.slice(last_dim, 0, last_dim_halfsize); out_slice.copy_(result); at::native::_fft_fill_with_conjugate_symmetry_(out, dim); return out; } // n-dimensional complex to complex FFT/IFFT Tensor _fft_c2c_mkl(const Tensor& self, IntArrayRef dim, int64_t normalization, bool forward) { TORCH_CHECK(self.is_complex()); const auto sorted_dims = _sort_dims(self, dim); auto out = at::empty(self.sizes(), self.options()); return _exec_fft(out, self, self.sizes(), sorted_dims, normalization, forward); } Tensor& _fft_c2c_mkl_out(const Tensor& self, IntArrayRef dim, int64_t normalization, bool forward, Tensor& out) { auto result = _fft_c2c_mkl(self, dim, normalization, forward); resize_output(out, result.sizes()); return out.copy_(result); } }} // namespace at::native #endif
39.477516
111
0.695867
[ "shape", "vector", "transform" ]
a79ebb8bbaf20300a90d6a69dc849eef949e01cf
1,713
cc
C++
vos/gui/sub/gui/si_histogram/SiCollectStretchedHist.cc
NASA-AMMOS/VICAR
4504c1f558855d9c6eaef89f4460217aa4909f8e
[ "BSD-3-Clause" ]
16
2020-10-21T05:56:26.000Z
2022-03-31T10:02:01.000Z
vos/gui/sub/gui/si_histogram/SiCollectStretchedHist.cc
NASA-AMMOS/VICAR
4504c1f558855d9c6eaef89f4460217aa4909f8e
[ "BSD-3-Clause" ]
null
null
null
vos/gui/sub/gui/si_histogram/SiCollectStretchedHist.cc
NASA-AMMOS/VICAR
4504c1f558855d9c6eaef89f4460217aa4909f8e
[ "BSD-3-Clause" ]
2
2021-03-09T01:51:08.000Z
2021-03-23T00:23:24.000Z
////////////////////////////////////////////////////////////////////// // SiCollectStretchedHist.cc ////////////////////////////////////////////////////////////////////// #include "SiCollectStretchedHist.h" #include "Lut.h" #include "SiHistogram.h" void SiCollectStretchedHist ( SiHistogram *histR, SiHistogram *histG, SiHistogram *histB, SiHistogram *strhistR, SiHistogram *strhistG, SiHistogram *strhistB, Lut *lutR, Lut *lutG, Lut* lutB) { SiCollectStretchedHist ( histR, strhistR, lutR); SiCollectStretchedHist ( histG, strhistG, lutG); SiCollectStretchedHist ( histB, strhistB, lutB); } void SiCollectStretchedHist ( SiHistogram *hist, SiHistogram *strhist, Lut *lut) { int i, origTempValue, strTempValue; int *lut_vector; int str_i; // Copy primary histogram parameters to stretched hist if (hist->isIntRange()) strhist->setLimits((int)hist->getLowerLimit(),(int)hist->getUpperLimit(), hist->numBins()); else strhist->setLimits(hist->getLowerLimit(),hist->getUpperLimit(), hist->numBins()); lut_vector = lut->getAsArray(); strhist->clear_noupdate(); for ( i=0; i<hist->numBins(); i++) { // Do the translation to get a stretched histogram model //!!!! FIX THIS when Lut is updated to more than 8 bits !!!! // Assume Lut value of 0..255 maps to full histogram range. // Pick corresponding value out of LUT. str_i = ((lut->getUpperLimit()-lut->getLowerLimit()+1) * i) / hist->numBins(); origTempValue = hist->getBin ( i ); strTempValue = strhist->getBin ( lut_vector[str_i] ); strhist->setBin ( lut_vector[str_i], origTempValue + strTempValue); } strhist->updateViews(); }
30.052632
80
0.621716
[ "model" ]
a7a1db312e71d39c7c30d81f0f8c283a195831ba
8,683
cxx
C++
Plugins/StreamingView/VTK/vtkPieceList.cxx
cjh1/ParaView
b0eba067c87078d5fe56ec3cb21447f149e1f31a
[ "BSD-3-Clause" ]
17
2015-02-17T00:30:26.000Z
2022-03-17T06:13:02.000Z
Plugins/StreamingView/VTK/vtkPieceList.cxx
cjh1/ParaView
b0eba067c87078d5fe56ec3cb21447f149e1f31a
[ "BSD-3-Clause" ]
null
null
null
Plugins/StreamingView/VTK/vtkPieceList.cxx
cjh1/ParaView
b0eba067c87078d5fe56ec3cb21447f149e1f31a
[ "BSD-3-Clause" ]
10
2015-08-31T18:20:17.000Z
2022-02-02T15:16:21.000Z
#include "vtkPieceList.h" #include "vtkObjectFactory.h" #include <vtksys/stl/algorithm> #include <vtksys/stl/vector> #include <vtksys/ios/sstream> vtkStandardNewMacro(vtkPieceList); ////////////////////////////////////////////////////////////////////////////// class vtkPieceList::Internal { public: Internal() { this->SerializeBuffer = NULL; this->BufferSize = 0; } ~Internal() { if (this->SerializeBuffer != NULL) { delete[] this->SerializeBuffer; } } vtksys_stl::vector<vtkPiece> Pieces; char *SerializeBuffer; int BufferSize; }; class vtkPieceListByPriority { public: bool operator() (vtkPiece one, vtkPiece two) { return one.ComparePriority(two); } }; ////////////////////////////////////////////////////////////////////////////// //---------------------------------------------------------------------------- vtkPieceList::vtkPieceList() { //cerr << "PL(" <<this<< ") create" << endl; this->Internals = new Internal; } //---------------------------------------------------------------------------- vtkPieceList::~vtkPieceList() { //cerr << "PL(" <<this<< ") delete" << endl; this->Clear(); delete this->Internals; } //---------------------------------------------------------------------------- void vtkPieceList::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } //---------------------------------------------------------------------------- void vtkPieceList::AddPiece(vtkPiece piece) { this->Internals->Pieces.push_back(piece); } //---------------------------------------------------------------------------- vtkPiece vtkPieceList::GetPiece(int n) { if (this->Internals->Pieces.size() > (unsigned int)n) { return this->Internals->Pieces[n]; } vtkPiece p; p.SetPiece(-1); return p; } //---------------------------------------------------------------------------- void vtkPieceList::SetPiece(int n, vtkPiece other) { if (this->Internals->Pieces.size() > (unsigned int)n) { this->Internals->Pieces[n] = other; } } //---------------------------------------------------------------------------- void vtkPieceList::RemovePiece(int n) { if (this->Internals->Pieces.size() > (unsigned int)n) { this->Internals->Pieces.erase(this->Internals->Pieces.begin()+n); } } //------------------------------------------------------------------------------ vtkPiece vtkPieceList::PopPiece(int n /*= 0*/) { vtkPiece p = this->GetPiece(n); this->RemovePiece(n); return p; } //---------------------------------------------------------------------------- void vtkPieceList::Clear() { this->Internals->Pieces.clear(); } //----------------------------------------------------------------------------- int vtkPieceList::GetNumberOfPieces() { return this->Internals->Pieces.size(); } //------------------------------------------------------------------------------ int vtkPieceList::GetNumberNonZeroPriority() { int last = this->Internals->Pieces.size()-1; for (int i = last; i >= 0 ; --i) { if (this->Internals->Pieces[i].GetPriority() > 0.0) { return i+1; } } return 0; } //------------------------------------------------------------------------------ void vtkPieceList::SortPriorities() { vtksys_stl::sort(this->Internals->Pieces.begin(), this->Internals->Pieces.end(), vtkPieceListByPriority()); } //----------------------------------------------------------------------------- void vtkPieceList::Print() { int np = this->GetNumberOfPieces(); cerr << "PL(" << this << "):" << np << " \n["; for (int i = 0; i < np; i++) { cerr << "{" << this->GetPiece(i).GetProcessor() << ":" << this->GetPiece(i).GetPiece() << "/" << this->GetPiece(i).GetNumPieces() << "@" << this->GetPiece(i).GetResolution() << "->[" << this->GetPiece(i).GetBounds()[0] << "-" << this->GetPiece(i).GetBounds()[1] << "," << this->GetPiece(i).GetBounds()[2] << "-" << this->GetPiece(i).GetBounds()[3] << "," << this->GetPiece(i).GetBounds()[4] << "-" << this->GetPiece(i).GetBounds()[5] << "]=(" << this->GetPiece(i).GetPipelinePriority() << " " << this->GetPiece(i).GetViewPriority() << " " << this->GetPiece(i).GetCachedPriority() << ")" << "},\n"; } cerr << "]" << endl; } //---------------------------------------------------------------------------- void vtkPieceList::Serialize() { if (this->Internals->SerializeBuffer != NULL) { delete[] this->Internals->SerializeBuffer; this->Internals->BufferSize = 0; } vtksys_ios::ostringstream temp; int np = this->GetNumberOfPieces(); temp << np << " "; for (int i = 0; i < np; i++) { vtkPiece mine = this->GetPiece(i); temp << mine.Processor << " " << mine.Piece << " " << mine.NumPieces << " " << mine.Resolution << " " << mine.Bounds[0] << " " << mine.Bounds[1] << " " << mine.Bounds[2] << " " << mine.Bounds[3] << " " << mine.Bounds[4] << " " << mine.Bounds[5] << " " << mine.PipelinePriority << " " << mine.ViewPriority << " " << mine.CachedPriority << " "; } int len = strlen(temp.str().c_str()); this->Internals->SerializeBuffer = new char[len+10]; strcpy(this->Internals->SerializeBuffer, temp.str().c_str()); this->Internals->BufferSize = len; } //---------------------------------------------------------------------------- void vtkPieceList::GetSerializedList(char **ret, int *size) { if (!ret || !size) { return; } *ret = this->Internals->SerializeBuffer; *size = this->Internals->BufferSize; } //---------------------------------------------------------------------------- void vtkPieceList::UnSerialize(char *buffer, int *bytes) { this->Clear(); if (!buffer || !bytes) { return; } vtksys_ios::istringstream temp; temp.str(buffer); int start = temp.tellg(); int np; temp >> np; for (int i = 0; i < np; i++) { vtkPiece mine;; temp >> mine.Processor; temp >> mine.Piece; temp >> mine.NumPieces; temp >> mine.Resolution; temp >> mine.Bounds[0]; temp >> mine.Bounds[1]; temp >> mine.Bounds[2]; temp >> mine.Bounds[3]; temp >> mine.Bounds[4]; temp >> mine.Bounds[5]; temp >> mine.PipelinePriority; temp >> mine.ViewPriority; temp >> mine.CachedPriority; this->AddPiece(mine); } int end = temp.tellg(); *bytes = end-start; } //------------------------------------------------------------------------------ void vtkPieceList::CopyPieceList(vtkPieceList *other) { this->CopyInternal(other, 0); } //------------------------------------------------------------------------------ void vtkPieceList::MergePieceList(vtkPieceList *other) { this->CopyInternal(other, 1); } //------------------------------------------------------------------------------ void vtkPieceList::CopyInternal(vtkPieceList *other, int merge) { if (!merge) { this->Clear(); } if (!other) { return; } for (int i = 0; i < other->GetNumberOfPieces(); i++) { vtkPiece mine; vtkPiece his = other->GetPiece(i); mine.CopyPiece(his); this->AddPiece(mine); } if (merge) { other->Clear(); } } //------------------------------------------------------------------------------ void vtkPieceList::DummyFill() { //Used for testing, it makes up a small piecelist with known content. static int myid = 0; //autoincrements to make it easy to identify which piecelist each piece //was originally generated by after it has been shuffled around this->Clear(); int numPieces=5; for (int i = 0; i < numPieces; i++) { vtkPiece mine; mine.SetPiece(i); mine.SetNumPieces(numPieces); mine.SetResolution(myid); mine.SetPipelinePriority((double)i/(double)numPieces); this->AddPiece(mine); } myid++; } //------------------------------------------------------------------------------ void vtkPieceList::PrintSerializedList() { char *buffer; int len; this->GetSerializedList(&buffer, &len); cerr << "LEN = " << len << endl; cerr << buffer << endl; } //------------------------------------------------------------------------------ void vtkPieceList::CopyBuddy(vtkPieceList *buddy) { if (!buddy) { cerr << "WHO?" << endl; return; } buddy->Serialize(); char *buffer; int len; buddy->GetSerializedList(&buffer, &len); //cerr << "LEN = " << len << endl; //cerr << buffer << endl; this->UnSerialize(buffer, &len); //this->Print(); }
25.765579
80
0.459979
[ "vector" ]
a7a649d6fc404fb5fd49aca94893e42bfd315214
21,369
cpp
C++
src/esp/physics/PhysicsManager.cpp
srama2512/habitat-sim
1a0a36451bc0a94c98d9f9fa497b4c3cfc095638
[ "MIT" ]
null
null
null
src/esp/physics/PhysicsManager.cpp
srama2512/habitat-sim
1a0a36451bc0a94c98d9f9fa497b4c3cfc095638
[ "MIT" ]
null
null
null
src/esp/physics/PhysicsManager.cpp
srama2512/habitat-sim
1a0a36451bc0a94c98d9f9fa497b4c3cfc095638
[ "MIT" ]
null
null
null
// Copyright (c) Facebook, Inc. and its affiliates. // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. #include "PhysicsManager.h" #include <Magnum/Math/Range.h> #include "esp/assets/CollisionMeshData.h" #include "esp/physics/objectManagers/ArticulatedObjectManager.h" #include "esp/physics/objectManagers/RigidObjectManager.h" #include "esp/sim/Simulator.h" namespace esp { namespace physics { PhysicsManager::PhysicsManager( assets::ResourceManager& _resourceManager, const metadata::attributes::PhysicsManagerAttributes::cptr& _physicsManagerAttributes) : resourceManager_(_resourceManager), physicsManagerAttributes_(_physicsManagerAttributes), rigidObjectManager_(RigidObjectManager::create()), articulatedObjectManager_(ArticulatedObjectManager::create()) {} bool PhysicsManager::initPhysics(scene::SceneNode* node) { physicsNode_ = node; // set the rigidObjectManager's weak reference to physics manager to be based // on the same shared pointer that Simulator is using. rigidObjectManager_->setPhysicsManager(shared_from_this()); // set articulated object manager here, and in articulatedObjectManager_->setPhysicsManager(shared_from_this()); // Copy over relevant configuration fixedTimeStep_ = physicsManagerAttributes_->getTimestep(); //! Create new scene node and set up any physics-related variables // Overridden by specific physics-library-based class initialized_ = initPhysicsFinalize(); return initialized_; } bool PhysicsManager::initPhysicsFinalize() { //! Create new scene node staticStageObject_ = physics::RigidStage::create(&physicsNode_->createChild(), resourceManager_); return true; } PhysicsManager::~PhysicsManager() { ESP_DEBUG() << "Deconstructing PhysicsManager"; } bool PhysicsManager::addStage( const metadata::attributes::StageAttributes::ptr& initAttributes, const std::vector<assets::CollisionMeshData>& meshGroup) { // Test Mesh primitive is valid for (const assets::CollisionMeshData& meshData : meshGroup) { if (!isMeshPrimitiveValid(meshData)) { return false; } } //! Initialize scene bool sceneSuccess = addStageFinalize(initAttributes); return sceneSuccess; } // PhysicsManager::addStage bool PhysicsManager::addStageFinalize( const metadata::attributes::StageAttributes::ptr& initAttributes) { //! Initialize scene bool sceneSuccess = staticStageObject_->initialize(initAttributes); return sceneSuccess; } // PhysicsManager::addStageFinalize int PhysicsManager::addObjectInstance( const esp::metadata::attributes::SceneObjectInstanceAttributes::ptr& objInstAttributes, const std::string& attributesHandle, bool defaultCOMCorrection, scene::SceneNode* attachmentNode, const std::string& lightSetup) { // Get ObjectAttributes auto objAttributes = resourceManager_.getObjectAttributesManager()->getObjectCopyByHandle( attributesHandle); if (!objAttributes) { ESP_ERROR() << "Missing/improperly configured objectAttributes" << attributesHandle << ", whose handle contains" << objInstAttributes->getHandle() << "as specified in object instance attributes."; return 0; } // set shader type to use for stage int objShaderType = objInstAttributes->getShaderType(); if (objShaderType != static_cast<int>( metadata::attributes::ObjectInstanceShaderType::Unknown)) { objAttributes->setShaderType(objShaderType); } int objID = 0; if (simulator_ != nullptr) { auto& drawables = simulator_->getDrawableGroup(); objID = addObject(objAttributes, &drawables, attachmentNode, lightSetup); } else { // support creation when simulator DNE objID = addObject(objAttributes, nullptr, attachmentNode, lightSetup); } if (objID == ID_UNDEFINED) { // instancing failed for some reason. ESP_ERROR() << "Object create failed for objectAttributes" << attributesHandle << ", whose handle contains" << objInstAttributes->getHandle() << "as specified in object instance attributes."; return ID_UNDEFINED; } // save the scene init attributes used to configure object's initial state this->existingObjects_.at(objID)->setSceneInstanceAttr(objInstAttributes); // set object's location, rotation and other pertinent state values based on // scene object instance attributes set in the object above. this->existingObjects_.at(objID)->resetStateFromSceneInstanceAttr( defaultCOMCorrection); return objID; } // PhysicsManager::addObjectInstance int PhysicsManager::addObject(const std::string& attributesHandle, scene::SceneNode* attachmentNode, const std::string& lightSetup) { esp::metadata::attributes::ObjectAttributes::ptr attributes = resourceManager_.getObjectAttributesManager()->getObjectCopyByHandle( attributesHandle); if (!attributes) { ESP_ERROR() << "Object creation failed due to unknown attributes" << attributesHandle; return ID_UNDEFINED; } else { // attributes exist, get drawables if valid simulator accessible if (simulator_ != nullptr) { auto& drawables = simulator_->getDrawableGroup(); return addObject(attributes, &drawables, attachmentNode, lightSetup); } else { // support creation when simulator DNE return addObject(attributes, nullptr, attachmentNode, lightSetup); } } } // PhysicsManager::addObject int PhysicsManager::addObject(const int attributesID, scene::SceneNode* attachmentNode, const std::string& lightSetup) { const esp::metadata::attributes::ObjectAttributes::ptr attributes = resourceManager_.getObjectAttributesManager()->getObjectCopyByID( attributesID); if (!attributes) { ESP_ERROR() << "Object creation failed due to unknown attributes ID" << attributesID; return ID_UNDEFINED; } else { // attributes exist, get drawables if valid simulator accessible if (simulator_ != nullptr) { auto& drawables = simulator_->getDrawableGroup(); return addObject(attributes, &drawables, attachmentNode, lightSetup); } else { // support creation when simulator DNE return addObject(attributes, nullptr, attachmentNode, lightSetup); } } } // PhysicsManager::addObject int PhysicsManager::addObject( const esp::metadata::attributes::ObjectAttributes::ptr& objectAttributes, DrawableGroup* drawables, scene::SceneNode* attachmentNode, const std::string& lightSetup) { //! Make rigid object and add it to existingObjects if (!objectAttributes) { // should never run, but just in case ESP_ERROR() << "Object creation failed due to nonexistant " "objectAttributes"; return ID_UNDEFINED; } // verify whether necessary assets exist, and if not, instantiate them // only make object if asset instantiation succeeds (short circuit) bool objectSuccess = resourceManager_.instantiateAssetsOnDemand(objectAttributes); if (!objectSuccess) { ESP_ERROR() << "ResourceManager::instantiateAssetsOnDemand " "unsuccessful. Aborting."; return ID_UNDEFINED; } // derive valid object ID and create new node if necessary int nextObjectID_ = allocateObjectID(); scene::SceneNode* objectNode = attachmentNode; if (attachmentNode == nullptr) { objectNode = &staticStageObject_->node().createChild(); } objectSuccess = makeAndAddRigidObject(nextObjectID_, objectAttributes, objectNode); if (!objectSuccess) { deallocateObjectID(nextObjectID_); if (attachmentNode == nullptr) { delete objectNode; } ESP_ERROR() << "PhysicsManager::makeRigidObject unsuccessful. " " Aborting."; return ID_UNDEFINED; } // temp non-owning pointer to object esp::physics::RigidObject* const obj = (existingObjects_.at(nextObjectID_).get()); obj->visualNodes_.push_back(obj->visualNode_); //! Draw object via resource manager //! Render node as child of physics node //! Verify we should make the object drawable if (obj->getInitializationAttributes()->getIsVisible()) { resourceManager_.addObjectToDrawables(obj->getInitializationAttributes(), obj->visualNode_, drawables, obj->visualNodes_, lightSetup); } // finalize rigid object creation objectSuccess = obj->finalizeObject(); if (!objectSuccess) { // if failed for some reason, remove and return removeObject(nextObjectID_, true, true); ESP_ERROR() << "PhysicsManager::finalizeObject unsuccessful. Aborting."; return ID_UNDEFINED; } // Valid object exists by here. // Now we need to create wrapper, wrap around object, // and register wrapper with wrapper manager // 1.0 Get unique name for object using simplified attributes name. std::string simpleObjectHandle = objectAttributes->getSimplifiedHandle(); std::string newObjectHandle = rigidObjectManager_->getUniqueHandleFromCandidate(simpleObjectHandle); ESP_WARNING() << "Simplified template handle :" << simpleObjectHandle << " | newObjectHandle :" << newObjectHandle; existingObjects_.at(nextObjectID_)->setObjectName(newObjectHandle); // 2.0 Get wrapper - name is irrelevant, do not register. ManagedRigidObject::ptr objWrapper = getRigidObjectWrapper(); // 3.0 Put object in wrapper objWrapper->setObjectRef(existingObjects_.at(nextObjectID_)); // 4.0 register wrapper in manager rigidObjectManager_->registerObject(objWrapper, newObjectHandle); return nextObjectID_; } // PhysicsManager::addObject int PhysicsManager::addArticulatedObjectInstance( const std::string& filepath, const std::shared_ptr<esp::metadata::attributes::SceneAOInstanceAttributes>& aObjInstAttributes, const std::string& lightSetup) { // Get drawables from simulator. TODO: Support non-existent simulator? auto& drawables = simulator_->getDrawableGroup(); // call object creation (resides only in physics library-based derived physics // managers) int aObjID = this->addArticulatedObjectFromURDF( filepath, &drawables, aObjInstAttributes->getFixedBase(), aObjInstAttributes->getUniformScale(), aObjInstAttributes->getMassScale(), false, lightSetup); if (aObjID == ID_UNDEFINED) { // instancing failed for some reason. ESP_ERROR() << "Articulated Object create failed for model filepath" << filepath << ", whose handle is" << aObjInstAttributes->getHandle() << "as specified in articulated object instance attributes."; return ID_UNDEFINED; } // set articulated object up using scene instance // set articulated object's scene instancing attributes existingArticulatedObjects_.at(aObjID)->setSceneInstanceAttr( aObjInstAttributes); // set articulated object's user-defined attributes, if any exist in scene // instance. existingArticulatedObjects_.at(aObjID)->setUserAttributes( aObjInstAttributes->getUserConfiguration()); // set articulated object's location, rotation and other pertinent state // values based on // scene object instance attributes set in the object above. existingArticulatedObjects_.at(aObjID)->resetStateFromSceneInstanceAttr(); return aObjID; } // PhysicsManager::addArticulatedObjectInstance esp::physics::ManagedRigidObject::ptr PhysicsManager::getRigidObjectWrapper() { return rigidObjectManager_->createObject("ManagedRigidObject"); } esp::physics::ManagedArticulatedObject::ptr PhysicsManager::getArticulatedObjectWrapper() { // should never be called unless we support non-dynamic AOs - would only be // called from AO creation occurring from within PM return articulatedObjectManager_->createObject("ManagedArticulatedObject"); } void PhysicsManager::removeObject(const int objectId, bool deleteObjectNode, bool deleteVisualNode) { assertRigidIdValidity(objectId); scene::SceneNode* objectNode = &existingObjects_.at(objectId)->node(); scene::SceneNode* visualNode = existingObjects_.at(objectId)->visualNode_; std::string objName = existingObjects_.at(objectId)->getObjectName(); existingObjects_.erase(objectId); deallocateObjectID(objectId); if (deleteObjectNode) { delete objectNode; } else if (deleteVisualNode && visualNode) { delete visualNode; } // remove wrapper if one is present if (rigidObjectManager_->getObjectLibHasHandle(objName)) { rigidObjectManager_->removeObjectByID(objectId); } } // PhysicsManager::removeObject void PhysicsManager::removeArticulatedObject(int objectId) { CORRADE_INTERNAL_ASSERT(existingArticulatedObjects_.count(objectId)); scene::SceneNode* objectNode = &existingArticulatedObjects_.at(objectId)->node(); for (auto linkObjId : existingArticulatedObjects_.at(objectId)->objectIdToLinkId_) { deallocateObjectID(linkObjId.first); } std::string artObjName = existingArticulatedObjects_.at(objectId)->getObjectName(); existingArticulatedObjects_.erase(objectId); deallocateObjectID(objectId); delete objectNode; // remove wrapper if one is present if (articulatedObjectManager_->getObjectLibHasHandle(artObjName)) { articulatedObjectManager_->removeObjectByID(objectId); } } int PhysicsManager::allocateObjectID() { if (!recycledObjectIDs_.empty()) { int recycledID = recycledObjectIDs_.back(); recycledObjectIDs_.pop_back(); return recycledID; } return nextObjectID_++; } int PhysicsManager::deallocateObjectID(int physObjectID) { recycledObjectIDs_.push_back(physObjectID); return physObjectID; } bool PhysicsManager::makeAndAddRigidObject( int newObjectID, const esp::metadata::attributes::ObjectAttributes::ptr& objectAttributes, scene::SceneNode* objectNode) { auto ptr = physics::RigidObject::create(objectNode, newObjectID, resourceManager_); bool objSuccess = ptr->initialize(objectAttributes); if (objSuccess) { existingObjects_.emplace(newObjectID, std::move(ptr)); } return objSuccess; } //! Base physics manager has no requirement for mesh primitive bool PhysicsManager::isMeshPrimitiveValid(const assets::CollisionMeshData&) { return true; } // TODO: this function should do any engine specific setting which is // necessary to change the timestep void PhysicsManager::setTimestep(double dt) { fixedTimeStep_ = dt; } void PhysicsManager::setGravity(const Magnum::Vector3&) { // Can't do this for kinematic simulator } Magnum::Vector3 PhysicsManager::getGravity() const { return Magnum::Vector3(0); } void PhysicsManager::stepPhysics(double dt) { // We don't step uninitialized physics sim... if (!initialized_) { return; } // ==== Physics stepforward ====== // NOTE: simulator step goes here in derived classes... if (dt < 0) { dt = fixedTimeStep_; } // handle in-between step times? Ideally dt is a multiple of // sceneMetaData_.timestep double targetTime = worldTime_ + dt; while (worldTime_ < targetTime) { // per fixed-step operations can be added here // kinematic velocity control integration for (auto& object : existingObjects_) { VelocityControl::ptr velControl = object.second->getVelocityControl(); if (velControl->controllingAngVel || velControl->controllingLinVel) { object.second->setRigidState(velControl->integrateTransform( fixedTimeStep_, object.second->getRigidState())); } } worldTime_ += fixedTimeStep_; } } void PhysicsManager::deferNodesUpdate() { for (auto& o : existingObjects_) o.second->deferUpdate(); for (auto& ao : existingArticulatedObjects_) ao.second->deferUpdate(); } void PhysicsManager::updateNodes() { for (auto& o : existingObjects_) o.second->updateNodes(); for (auto& ao : existingArticulatedObjects_) ao.second->updateNodes(); } //! Profile function. In BulletPhysics stationary objects are //! marked as inactive to speed up simulation. This function //! helps checking how many objects are active/inactive at any //! time step int PhysicsManager::checkActiveObjects() { if (staticStageObject_ == nullptr) { return 0; } // We don't check uninitialized physics sim... if (!initialized_) { return 0; } int numActive = 0; for (auto& itr : existingObjects_) { if (itr.second->isActive()) { numActive += 1; } } return numActive; } #ifdef ESP_BUILD_WITH_VHACD void PhysicsManager::generateVoxelization(const int physObjectID, const int resolution) { assertRigidIdValidity(physObjectID); existingObjects_.at(physObjectID) ->generateVoxelization(resourceManager_, resolution); } void PhysicsManager::generateStageVoxelization(const int resolution) { staticStageObject_->generateVoxelization(resourceManager_, resolution); } #endif std::shared_ptr<esp::geo::VoxelWrapper> PhysicsManager::getObjectVoxelization( const int physObjectID) const { assertRigidIdValidity(physObjectID); return existingObjects_.at(physObjectID)->getVoxelization(); } std::shared_ptr<esp::geo::VoxelWrapper> PhysicsManager::getStageVoxelization() const { return staticStageObject_->getVoxelization(); } void PhysicsManager::setObjectBBDraw(int physObjectID, DrawableGroup* drawables, bool drawBB) { assertRigidIdValidity(physObjectID); if (existingObjects_.at(physObjectID)->BBNode_ && !drawBB) { // destroy the node delete existingObjects_.at(physObjectID)->BBNode_; existingObjects_.at(physObjectID)->BBNode_ = nullptr; } else if (drawBB && existingObjects_.at(physObjectID)->visualNode_) { // add a new BBNode Magnum::Vector3 scale = existingObjects_.at(physObjectID) ->visualNode_->getCumulativeBB() .size() / 2.0; existingObjects_.at(physObjectID)->BBNode_ = &existingObjects_.at(physObjectID)->visualNode_->createChild(); existingObjects_.at(physObjectID)->BBNode_->MagnumObject::setScaling(scale); existingObjects_.at(physObjectID) ->BBNode_->MagnumObject::setTranslation( existingObjects_[physObjectID] ->visualNode_->getCumulativeBB() .center()); resourceManager_.addPrimitiveToDrawables( 0, *existingObjects_.at(physObjectID)->BBNode_, drawables); } } void PhysicsManager::setObjectVoxelizationDraw(int physObjectID, const std::string& gridName, DrawableGroup* drawables, bool drawVoxelization) { assertRigidIdValidity(physObjectID); setVoxelizationDraw(gridName, static_cast<esp::physics::RigidBase*>( existingObjects_.at(physObjectID).get()), drawables, drawVoxelization); } void PhysicsManager::setStageVoxelizationDraw(const std::string& gridName, DrawableGroup* drawables, bool drawVoxelization) { setVoxelizationDraw( gridName, static_cast<esp::physics::RigidBase*>(staticStageObject_.get()), drawables, drawVoxelization); } void PhysicsManager::setVoxelizationDraw(const std::string& gridName, esp::physics::RigidBase* rigidBase, DrawableGroup* drawables, bool drawVoxelization) { if (rigidBase->VoxelNode_ && !drawVoxelization) { // destroy the node delete rigidBase->VoxelNode_; rigidBase->VoxelNode_ = nullptr; } else if (drawVoxelization && rigidBase->visualNode_) { // if the VoxelNode is already rendering something, destroy it. delete rigidBase->VoxelNode_; // re-create the voxel node rigidBase->VoxelNode_ = &rigidBase->visualNode_->createChild(); esp::geo::VoxelWrapper* voxelWrapper_ = rigidBase->voxelWrapper.get(); gfx::Drawable::Flags meshAttributeFlags{}; resourceManager_.createDrawable( &voxelWrapper_->getVoxelGrid()->getMeshGL(gridName), meshAttributeFlags, *rigidBase->VoxelNode_, DEFAULT_LIGHTING_KEY, PER_VERTEX_OBJECT_ID_MATERIAL_KEY, drawables); // If the RigidBase is a stage, need to set the BB to make culling work. if (dynamic_cast<esp::physics::RigidStage*>(rigidBase) != nullptr) { // set bounding box for the node to be the bb computed by vhacd Mn::Range3D bb{rigidBase->voxelWrapper->getVoxelGrid()->getOffset(), rigidBase->voxelWrapper->getVoxelGrid()->getMaxOffset()}; rigidBase->VoxelNode_->setMeshBB(bb); // rigidBase->node().computeCumulativeBB(); } } } } // namespace physics } // namespace esp
37.163478
80
0.69905
[ "mesh", "render", "object", "vector", "model" ]
a7a8a9aac0930fe176e1e961c7c2987abfacf4ee
1,078
cpp
C++
perf/FastArrayBenchmark.cpp
Danleb/quadtree
a198509e28cbc840cbdb1e7f3515e92a369483ed
[ "MIT" ]
1
2022-02-06T22:57:35.000Z
2022-02-06T22:57:35.000Z
perf/FastArrayBenchmark.cpp
Danleb/quadtree
a198509e28cbc840cbdb1e7f3515e92a369483ed
[ "MIT" ]
1
2022-02-06T22:59:58.000Z
2022-02-06T22:59:58.000Z
perf/FastArrayBenchmark.cpp
Danleb/quadtree
a198509e28cbc840cbdb1e7f3515e92a369483ed
[ "MIT" ]
null
null
null
#include <light/FastArray.h> #include <benchmark/benchmark.h> #include <random> #include <vector> constexpr auto ELEMENTS_COUNT = 128; constexpr auto SWAPS_COUNT = 1000000; template<template<typename> typename TContainer> void BM_DataContainerRW(benchmark::State& state) { std::mt19937 rng{}; std::uniform_int_distribution<int> uid(1, 10000); for (auto _ : state) { TContainer<int> v; for (size_t i = 0; i < ELEMENTS_COUNT; ++i) { v.push_back(uid(rng)); } for (size_t i = 0; i < SWAPS_COUNT; ++i) { const auto i1 = uid(rng) % ELEMENTS_COUNT; const auto i2 = uid(rng) % ELEMENTS_COUNT; const auto x = v[i1]; v[i1] = v[i2]; v[i2] = x; } benchmark::DoNotOptimize(v[0]); } } void BM_FastArrayRW(benchmark::State& state) { BM_DataContainerRW<light::FastArray>(state); } void BM_VectorRW(benchmark::State& state) { BM_DataContainerRW<std::vector>(state); } BENCHMARK(BM_VectorRW); BENCHMARK(BM_FastArrayRW);
21.137255
54
0.608534
[ "vector" ]
a7a90b47fbe5ec04759643b529e907d748d6717e
34,979
cpp
C++
shell/themes/uxtheme/render.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
shell/themes/uxtheme/render.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
shell/themes/uxtheme/render.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//--------------------------------------------------------------------------- // Render.cpp - implements the themed drawing services //--------------------------------------------------------------------------- #include "stdafx.h" #include "Render.h" #include "Utils.h" #include "Parser.h" #include "Loader.h" #include "tmutils.h" #include "gradient.h" #include "rgn.h" #include "info.h" #include "cache.h" #include "cachelist.h" #include "borderfill.h" #include "imagefile.h" #ifdef DEBUG static DWORD s_dwSize = 0; #endif //--------------------------------------------------------------------------- HRESULT CreateRenderObj(CUxThemeFile *pThemeFile, int iCacheSlot, int iThemeOffset, int iClassNameOffset, __int64 iUniqueId, BOOL fEnableCache, CDrawBase *pBaseObj, CTextDraw *pTextObj, DWORD dwOtdFlags, CRenderObj **ppObj) { HRESULT hr = S_OK; CRenderObj *pRender = new CRenderObj(pThemeFile, iCacheSlot, iThemeOffset, iClassNameOffset, iUniqueId, fEnableCache, dwOtdFlags); if (! pRender) { hr = MakeError32(E_OUTOFMEMORY); } else { hr = pRender->Init(pBaseObj, pTextObj); if (FAILED(hr)) delete pRender; else *ppObj = pRender; } return hr; } //--------------------------------------------------------------------------- CRenderObj::CRenderObj(CUxThemeFile *pThemeFile, int iCacheSlot, int iThemeOffset, int iClassNameOffset, __int64 iUniqueId, BOOL fEnableCache, DWORD dwOtdFlags) { StringCchCopyA(_szHead, ARRAYSIZE(_szHead), "rendobj"); StringCchCopyA(_szTail, ARRAYSIZE(_szTail), "end"); _fCacheEnabled = fEnableCache; _fCloseThemeFile = FALSE; _dwOtdFlags = dwOtdFlags; if (pThemeFile) { if (SUCCEEDED(BumpThemeFileRefCount(pThemeFile))) _fCloseThemeFile = TRUE; } _pThemeFile = pThemeFile; _iCacheSlot = iCacheSlot; _iUniqueId = iUniqueId; if (pThemeFile) { _pbThemeData = pThemeFile->_pbThemeData; _pbSectionData = _pbThemeData + iThemeOffset; _ptm = GetThemeMetricsPtr(pThemeFile); } else { _pbThemeData = NULL; _pbSectionData = NULL; _ptm = NULL; } _pszClassName = ThemeString(pThemeFile, iClassNameOffset); _iMaxPart = 0; _pParts = NULL; _iDpiOverride = 0; //---- caller must call "Init()" after ctr! ---- } //--------------------------------------------------------------------------- HRESULT CRenderObj::PrepareAlphaBitmap(HBITMAP hBitmap) { HRESULT hr = S_OK; //---- convert to DIBDATA ---- CBitmapPixels pixels; DWORD *pPixelQuads; int iWidth, iHeight, iBytesPerPixel, iBytesPerRow; hr = pixels.OpenBitmap(NULL, hBitmap, TRUE, &pPixelQuads, &iWidth, &iHeight, &iBytesPerPixel, &iBytesPerRow); if (FAILED(hr)) goto exit; PreMultiplyAlpha(pPixelQuads, iWidth, iHeight); pixels.CloseBitmap(NULL, hBitmap); exit: return hr; } //--------------------------------------------------------------------------- HRESULT CRenderObj::Init(CDrawBase *pBaseObj, CTextDraw *pTextObj) { HRESULT hr = S_OK; if (_fCacheEnabled) { hr = BuildPackedPtrs(pBaseObj, pTextObj); if (FAILED(hr)) goto exit; } //---- prepare direct objects ---- if ((pBaseObj) && (pBaseObj->_eBgType == BT_IMAGEFILE)) { CMaxImageFile *pMaxIf = (CMaxImageFile *)pBaseObj; //---- process primary image ---- DIBINFO *pdi = &pMaxIf->_ImageInfo; if (pdi->fAlphaChannel) { hr = PrepareAlphaBitmap(pdi->hProcessBitmap); if (FAILED(hr)) goto exit; } //---- process glyph image ---- pdi = &pMaxIf->_GlyphInfo; if (pdi->fAlphaChannel) { hr = PrepareAlphaBitmap(pdi->hProcessBitmap); if (FAILED(hr)) goto exit; } //---- process multiple images ---- for (int i=0; i < pMaxIf->_iMultiImageCount; i++) { pdi = pMaxIf->MultiDibPtr(i); if (pdi->fAlphaChannel) { hr = PrepareAlphaBitmap(pdi->hProcessBitmap); if (FAILED(hr)) goto exit; } } } exit: return hr; } //--------------------------------------------------------------------------- CRenderObj::~CRenderObj() { //---- delete memory allocated for pack objects looked ---- if (_pParts) { for(int i=0; i<_iMaxPart+1; i++) { if (_pParts[i].pStateDrawObjs) delete[] _pParts[i].pStateDrawObjs; if (_pParts[i].pStateTextObjs) delete[] _pParts[i].pStateTextObjs; } delete[] _pParts; } //---- if we opened a refcount on a themefile, close it now ---- if (_fCloseThemeFile) CloseThemeFile(_pThemeFile); //---- mark this object as "deleted" (for debugging) ---- StringCchCopyA(_szHead, ARRAYSIZE(_szHead), "deleted"); } //--------------------------------------------------------------------------- int CRenderObj::GetDpiOverride() { return _iDpiOverride; } //--------------------------------------------------------------------------- HRESULT CRenderObj::BuildPackedPtrs(CDrawBase *pBaseObj, CTextDraw *pTextObj) { MIXEDPTRS u; HRESULT hr = S_OK; int iPackedOffset = 0; int *iPartOffsets = NULL; BOOL fSingleObj = FALSE; //---- extract _iMaxPart ---- if ((pBaseObj) || (pTextObj)) // single object to be used for all parts/states { _iMaxPart = 1; // dummy value fSingleObj = TRUE; } else { u.pb = _pbSectionData; if (*u.ps != TMT_PARTJUMPTABLE) { hr = MakeError32(E_FAIL); // something went amiss goto exit; } u.pb += ENTRYHDR_SIZE; iPackedOffset = *u.pi++; _iMaxPart = *u.pb - 1; u.pb++; iPartOffsets = u.pi; } //---- allocate _pParts ---- _pParts = new PARTINFO[_iMaxPart+1]; if (! _pParts) { hr = MakeError32(E_OUTOFMEMORY); goto exit; } memset(_pParts, 0, sizeof(PARTINFO)*(_iMaxPart+1)); if (fSingleObj) { for (int i=0; i <= _iMaxPart; i++) _pParts[i].iMaxState = 1; // dummy value if (pBaseObj) // single draw object to be used for all parts/states { for (int i=0; i <= _iMaxPart; i++) { _pParts[i].pDrawObj = pBaseObj; } } if (pTextObj) // single text object t to be used for all parts/states { for (int i=0; i <= _iMaxPart; i++) { _pParts[i].pTextObj = pTextObj; } } } else { u.pb = _pbThemeData + iPackedOffset; hr = WalkDrawObjects(u, iPartOffsets); if (FAILED(hr)) goto exit; hr = WalkTextObjects(u, iPartOffsets); if (FAILED(hr)) goto exit; } exit: return hr; } //--------------------------------------------------------------------------- HRESULT CRenderObj::WalkDrawObjects(MIXEDPTRS &u, int *iPartOffsets) { int iPartId; int iStateId; HRESULT hr = S_OK; THEMEHDR *pHdr = (THEMEHDR *)_pbThemeData; UNPACKED_ENTRYHDR hdr; //---- get ptr to global text obj ---- BYTE *pb = _pbThemeData + pHdr->iGlobalsDrawObjOffset; pb += ENTRYHDR_SIZE + sizeof(DRAWOBJHDR); CDrawBase *pGlobalObj = (CDrawBase *)pb; //---- start with all parts inheriting from [globals] ---- for (int i=0; i <= _iMaxPart; i++) _pParts[i].pDrawObj = pGlobalObj; //---- now, process all specified objects ---- while (1) { if ((*u.ps == TMT_RGNLIST)) { //---- skip over this entry ---- FillAndSkipHdr(u, &hdr); u.pb += hdr.dwDataLen; continue; } if (*u.ps != TMT_DRAWOBJ) break; FillAndSkipHdr(u, &hdr); DRAWOBJHDR *ph = (DRAWOBJHDR *)u.pb; CDrawBase *pCurrentObj = (CDrawBase *)(u.pb + sizeof(DRAWOBJHDR)); u.pb += hdr.dwDataLen; iPartId = ph->iPartNum; iStateId = ph->iStateNum; if ((! iPartId) && (! iStateId)) { //---- all parts inherit from this obj ---- for (int i=0; i <= _iMaxPart; i++) _pParts[i].pDrawObj = pCurrentObj; continue; } PARTINFO *ppi = &_pParts[iPartId]; if (! iStateId) { ppi->pDrawObj = pCurrentObj; } else { if (! ppi->iMaxState) // extract MaxState { MIXEDPTRS u2; u2.pb = _pbThemeData + iPartOffsets[iPartId]; if (*u2.ps != TMT_STATEJUMPTABLE) { hr = MakeError32(E_FAIL); // something went amiss goto exit; } u2.pb += ENTRYHDR_SIZE; ppi->iMaxState = *u2.pb - 1; } if (! ppi->pStateDrawObjs) // allocate now { ppi->pStateDrawObjs = new CDrawBase *[ppi->iMaxState]; if (! ppi->pStateDrawObjs) { hr = MakeError32(E_OUTOFMEMORY); goto exit; } //---- fill in default objs as state 0 ---- for (int i=0; i < ppi->iMaxState; i++) ppi->pStateDrawObjs[i] = ppi->pDrawObj; } ppi->pStateDrawObjs[iStateId-1] = pCurrentObj; } } exit: return hr; } //--------------------------------------------------------------------------- HRESULT CRenderObj::WalkTextObjects(MIXEDPTRS &u, int *iPartOffsets) { int iPartId; int iStateId; HRESULT hr = S_OK; THEMEHDR *pHdr = (THEMEHDR *)_pbThemeData; UNPACKED_ENTRYHDR hdr; //---- get ptr to global text obj ---- BYTE *pb = _pbThemeData + pHdr->iGlobalsTextObjOffset; pb += ENTRYHDR_SIZE + sizeof(DRAWOBJHDR); CTextDraw *pGlobalObj = (CTextDraw *)pb; //---- start with all parts inheriting from [globals] ---- for (int i=0; i <= _iMaxPart; i++) _pParts[i].pTextObj = pGlobalObj; while (*u.ps == TMT_TEXTOBJ) { FillAndSkipHdr(u, &hdr); DRAWOBJHDR *ph = (DRAWOBJHDR *)u.pb; CTextDraw *pCurrentObj = (CTextDraw *)(u.pb + sizeof(DRAWOBJHDR)); u.pb += hdr.dwDataLen; iPartId = ph->iPartNum; iStateId = ph->iStateNum; if ((! iPartId) && (! iStateId)) { //---- all parts inherit from this obj ---- for (int i=0; i <= _iMaxPart; i++) _pParts[i].pTextObj = pCurrentObj; continue; } PARTINFO *ppi = &_pParts[iPartId]; if (! iStateId) { ppi->pTextObj = pCurrentObj; } else { if (! ppi->iMaxState) // extract MaxState { MIXEDPTRS u2; u2.pb = _pbThemeData + iPartOffsets[iPartId]; if (*u2.ps != TMT_STATEJUMPTABLE) { hr = MakeError32(E_FAIL); // something went amiss goto exit; } u2.pb += ENTRYHDR_SIZE; ppi->iMaxState = *u2.pb - 1; } if (! ppi->pStateTextObjs) // allocate now { ppi->pStateTextObjs = new CTextDraw *[ppi->iMaxState]; if (! ppi->pStateTextObjs) { hr = MakeError32(E_OUTOFMEMORY); goto exit; } //---- fill in default objs as state 0 ---- for (int i=0; i < ppi->iMaxState; i++) ppi->pStateTextObjs[i] = ppi->pTextObj; } ppi->pStateTextObjs[iStateId-1] = pCurrentObj; } } exit: return hr; } //--------------------------------------------------------------------------- HRESULT CRenderObj::GetBitmap(HDC hdc, int iDibOffset, OUT HBITMAP *phBitmap) { HRESULT hr = S_OK; HBITMAP hBitmap; if ((! iDibOffset) || (! _pbThemeData)) { hr = E_FAIL; goto exit; } TMBITMAPHEADER *pThemeBitmapHeader; pThemeBitmapHeader = reinterpret_cast<TMBITMAPHEADER*>(_pbThemeData + iDibOffset); ASSERT(pThemeBitmapHeader->dwSize == TMBITMAPSIZE); *phBitmap = pThemeBitmapHeader->hBitmap; if (*phBitmap != NULL) { //Log(LOG_TMBITMAP, L"Used stock bitmap:%8X", *phBitmap); return hr; } hr = CreateBitmapFromData(hdc, iDibOffset + TMBITMAPSIZE, &hBitmap); if (FAILED(hr)) goto exit; Log(LOG_TM, L"GetBitmap - CACHE MISS: class=%s, diboffset=%d, bitmap=0x%x", SHARECLASS(this), iDibOffset, hBitmap); *phBitmap = hBitmap; exit: return hr; } //--------------------------------------------------------------------------- void CRenderObj::ReturnBitmap(HBITMAP hBitmap) { DeleteObject(hBitmap); } //--------------------------------------------------------------------------- HRESULT CRenderObj::CreateBitmapFromData(HDC hdc, int iDibOffset, OUT HBITMAP *phBitmap) { BYTE *pDibData; RESOURCE HDC hdcTemp = NULL; RESOURCE HBITMAP hBitmap = NULL; HRESULT hr = S_OK; if ((! iDibOffset) || (! _pbThemeData)) { hr = E_FAIL; goto exit; } pDibData = (BYTE *)(_pbThemeData + iDibOffset); BITMAPINFOHEADER *pBitmapHdr; pBitmapHdr = (BITMAPINFOHEADER *)pDibData; BOOL fAlphaChannel; fAlphaChannel = (pBitmapHdr->biBitCount == 32); if (! hdc) { hdcTemp = GetWindowDC(NULL); if (! hdcTemp) { Log(LOG_ALWAYS, L"GetWindowDC() failed in CreateBitmapFromData"); hr = MakeErrorLast(); goto exit; } hdc = hdcTemp; } //---- create the actual bitmap ---- //---- if using alpha channel, we must use a DIB ---- if (fAlphaChannel) { void *pv; hBitmap = CreateDIBSection(hdc, (BITMAPINFO *)pBitmapHdr, DIB_RGB_COLORS, &pv, NULL, 0); } else { hBitmap = CreateCompatibleBitmap(hdc, pBitmapHdr->biWidth, pBitmapHdr->biHeight); } if (! hBitmap) { hr = MakeErrorLast(); goto exit; } int iSetVal; //---- SetDIBits() can take unaligned data, right? ---- iSetVal = SetDIBits(hdc, hBitmap, 0, pBitmapHdr->biHeight, DIBDATA(pBitmapHdr), (BITMAPINFO *)pBitmapHdr, DIB_RGB_COLORS); if (! iSetVal) { hr = MakeErrorLast(); goto exit; } *phBitmap = hBitmap; #ifdef DEBUG if (hBitmap) { BITMAP bm; GetObject(hBitmap, sizeof bm, &bm); s_dwSize += bm.bmWidthBytes * bm.bmHeight; //Log(LOG_TMBITMAP, L"Created a bitmap of %d bytes. total is %d", bm.bmWidthBytes * bm.bmHeight, s_dwSize); } #endif exit: if (hdcTemp) ReleaseDC(NULL, hdcTemp); if (FAILED(hr)) { if (hBitmap) DeleteObject(hBitmap); } return hr; } //--------------------------------------------------------------------------- HRESULT CRenderObj::GetScaledFontHandle(HDC hdc, LOGFONT *plf, HFONT *phFont) { HRESULT hr = S_OK; if (_fCacheEnabled) { CRenderCache *pCacheObj = GetTlsCacheObj(); if (pCacheObj) hr = pCacheObj->GetScaledFontHandle(hdc, plf, phFont); } else { LOGFONT lf = *plf; //---- convert to current screen dpi ---- ScaleFontForHdcDpi(hdc, &lf); *phFont = CreateFontIndirect(&lf); if (! *phFont) hr = MakeError32(E_OUTOFMEMORY); } return hr; } //--------------------------------------------------------------------------- void CRenderObj::ReturnFontHandle(HFONT hFont) { if (_fCacheEnabled) { //--- cache currently doesn't refcnt so save time by not calling --- //CRenderCache *pCacheObj = GetTlsCacheObj(); //if (pCacheObj) //{ //pCacheObj->ReturnFontHandle(hFont); //goto exit; //} } else { DeleteObject(hFont); } } //--------------------------------------------------------------------------- HRESULT CRenderObj::PrepareRegionDataForScaling( RGNDATA *pRgnData, LPCRECT prcImage, MARGINS *pMargins) { //---- compute margin values ---- int sw = prcImage->left; int lw = prcImage->left + pMargins->cxLeftWidth; int rw = prcImage->right - pMargins->cxRightWidth; int sh = prcImage->top; int th = prcImage->top + pMargins->cyTopHeight; int bh = prcImage->bottom - pMargins->cyBottomHeight; //---- step thru region data & customize it ---- //---- classify each POINT according to a gridnum and ---- //---- make it 0-relative to its grid location ---- POINT *pt = (POINT *)pRgnData->Buffer; BYTE *pByte = (BYTE *)pRgnData->Buffer + pRgnData->rdh.nRgnSize; int iCount = 2 * pRgnData->rdh.nCount; for (int i=0; i < iCount; i++, pt++, pByte++) { if (pt->x < lw) { pt->x -= sw; if (pt->y < th) // left top { *pByte = GN_LEFTTOP; pt->y -= sh; } else if (pt->y < bh) // left middle { *pByte = GN_LEFTMIDDLE; pt->y -= th; } else // left bottom { *pByte = GN_LEFTBOTTOM; pt->y -= bh; } } else if (pt->x < rw) { pt->x -= lw; if (pt->y < th) // middle top { *pByte = GN_MIDDLETOP; pt->y -= sh; } else if (pt->y < bh) // middle middle { *pByte = GN_MIDDLEMIDDLE; pt->y -= th; } else // middle bottom { *pByte = GN_MIDDLEBOTTOM; pt->y -= bh; } } else { pt->x -= rw; if (pt->y < th) // right top { *pByte = GN_RIGHTTOP; pt->y -= sh; } else if (pt->y < bh) // right middle { *pByte = GN_RIGHTMIDDLE; pt->y -= th; } else // right bottom { *pByte = GN_RIGHTBOTTOM; pt->y -= bh; } } } return S_OK; } //--------------------------------------------------------------------------- HRESULT CRenderObj::GetColor(int iPartId, int iStateId, int iPropId, COLORREF *pColor) { if (! pColor) return MakeError32(E_INVALIDARG); int index = GetValueIndex(iPartId, iStateId, iPropId); if (index < 0) // not found return MakeError32(ERROR_NOT_FOUND); MIXEDPTRS u; u.pb = _pbThemeData + index; // point at data *pColor = *u.pi; return S_OK; } //--------------------------------------------------------------------------- HRESULT CRenderObj::GetString(int iPartId, int iStateId, int iPropId, LPWSTR pszBuff, DWORD cchBuff) { if (! pszBuff) return MakeError32(E_INVALIDARG); int index = GetValueIndex(iPartId, iStateId, iPropId); if (index < 0) return MakeError32(ERROR_NOT_FOUND); MIXEDPTRS u; u.pb = _pbThemeData + index - sizeof(int); // point at length DWORD len = *u.pdw++; len /= sizeof(WCHAR); // adjust to characters HRESULT hr = SafeStringCchCopyW(pszBuff, cchBuff, u.pw ); return hr; } //--------------------------------------------------------------------------- HRESULT CRenderObj::GetBool(int iPartId, int iStateId, int iPropId, BOOL *pfVal) { if (! pfVal) return MakeError32(E_INVALIDARG); int index = GetValueIndex(iPartId, iStateId, iPropId); if (index < 0) return MakeError32(ERROR_NOT_FOUND); MIXEDPTRS u; u.pb = _pbThemeData + index; // point at data *pfVal = *u.pb; return S_OK; } //--------------------------------------------------------------------------- HRESULT CRenderObj::GetInt(int iPartId, int iStateId, int iPropId, int *piVal) { if (! piVal) return MakeError32(E_INVALIDARG); int index = GetValueIndex(iPartId, iStateId, iPropId); if (index < 0) return MakeError32(ERROR_NOT_FOUND); MIXEDPTRS u; u.pb = _pbThemeData + index; // point at data *piVal = *u.pi; return S_OK; } //--------------------------------------------------------------------------- static int iMetricDefaults[] = { 1, // TMT_BORDERWIDTH 18, // TMT_VERTSCROLLWIDTH 18, // TMT_HORZSCROLLHEIGHT 27, // TMT_CAPTIONBUTTONWIDTH 27, // TMT_CAPTIONBUTTONHEIGHT 22, // TMT_SMCAPTIONBUTTONWIDTH 22, // TMT_SMCAPTIONBUTTONHEIGHT 22, // TMT_MENUBUTTONWIDTH 22, // TMT_MENUBUTTONHEIGHT }; //--------------------------------------------------------------------------- HRESULT CRenderObj::GetMetric(OPTIONAL HDC hdc, int iPartId, int iStateId, int iPropId, int *piVal) { if (! piVal) return MakeError32(E_INVALIDARG); int index = GetValueIndex(iPartId, iStateId, iPropId); int value; if (index >= 0) // found { MIXEDPTRS u; u.pb = _pbThemeData + index; // point at data value = *u.pi; } else return MakeError32(ERROR_NOT_FOUND); *piVal = ScaleSizeForHdcDpi(hdc, value); return S_OK; } //--------------------------------------------------------------------------- HRESULT CRenderObj::GetEnumValue(int iPartId, int iStateId, int iPropId, int *piVal) { if (! piVal) return MakeError32(E_INVALIDARG); int index = GetValueIndex(iPartId, iStateId, iPropId); if (index < 0) return MakeError32(ERROR_NOT_FOUND); MIXEDPTRS u; u.pb = _pbThemeData + index; // point at data *piVal = *u.pi; return S_OK; } //--------------------------------------------------------------------------- HRESULT CRenderObj::GetPosition(int iPartId, int iStateId, int iPropId, POINT *pPoint) { if (! pPoint) return MakeError32(E_INVALIDARG); int index = GetValueIndex(iPartId, iStateId, iPropId); if (index < 0) return MakeError32(ERROR_NOT_FOUND); MIXEDPTRS u; u.pb = _pbThemeData + index; // point at data pPoint->x = *u.pi++; pPoint->y = *u.pi++; return S_OK; } //--------------------------------------------------------------------------- HRESULT CRenderObj::GetFont(OPTIONAL HDC hdc, int iPartId, int iStateId, int iPropId, BOOL fWantHdcScaling, LOGFONT *pFont) { if (! pFont) return MakeError32(E_INVALIDARG); int index = GetValueIndex(iPartId, iStateId, iPropId); if (index < 0) return MakeError32(ERROR_NOT_FOUND); MIXEDPTRS u; u.pb = _pbThemeData + index; // point at data *pFont = *(LOGFONT *)u.pb; if (fWantHdcScaling) { ScaleFontForHdcDpi(hdc, pFont); } return S_OK; } //--------------------------------------------------------------------------- HRESULT CRenderObj::GetMargins(OPTIONAL HDC hdc, int iPartId, int iStateId, int iPropId, OPTIONAL RECT *prc, MARGINS *pMargins) { //---- return unscaled margins ---- if (! pMargins) return MakeError32(E_INVALIDARG); int index = GetValueIndex(iPartId, iStateId, iPropId); if (index < 0) return MakeError32(ERROR_NOT_FOUND); MIXEDPTRS u; u.pb = _pbThemeData + index; // point at data pMargins->cxLeftWidth = *u.pi++; pMargins->cxRightWidth = *u.pi++; pMargins->cyTopHeight = *u.pi++; pMargins->cyBottomHeight = *u.pi++; return S_OK; } //--------------------------------------------------------------------------- HRESULT CRenderObj::GetIntList(int iPartId, int iStateId, int iPropId, INTLIST *pIntList) { if (! pIntList) return MakeError32(E_INVALIDARG); int index = GetValueIndex(iPartId, iStateId, iPropId); if (index < 0) return MakeError32(ERROR_NOT_FOUND); MIXEDPTRS u; u.pb = _pbThemeData + index; // point at data int iCount = *u.pi++; if (iCount > MAX_INTLIST_COUNT) { Log(LOG_ALWAYS, L"GetIntList() found bad theme data - Count=%d", iCount); return MakeError32(ERROR_NOT_FOUND); } pIntList->iValueCount = iCount; for (int i=0; i < iCount; i++) pIntList->iValues[i] = *u.pi++; return S_OK; } //--------------------------------------------------------------------------- HRESULT CRenderObj::GetRect(int iPartId, int iStateId, int iPropId, RECT *pRect) { if (! pRect) return MakeError32(E_INVALIDARG); int index = GetValueIndex(iPartId, iStateId, iPropId); if (index < 0) return MakeError32(ERROR_NOT_FOUND); MIXEDPTRS u; u.pb = _pbThemeData + index; // point at data pRect->left = *u.pi++; pRect->top = *u.pi++; pRect->right = *u.pi++; pRect->bottom = *u.pi++; return S_OK; } //--------------------------------------------------------------------------- HRESULT CRenderObj::GetFilename(int iPartId, int iStateId, int iPropId, LPWSTR pszBuff, DWORD cchBuff) { if (! pszBuff) return MakeError32(E_INVALIDARG); int index = GetValueIndex(iPartId, iStateId, iPropId); if (index < 0) return MakeError32(ERROR_NOT_FOUND); MIXEDPTRS u; u.pb = _pbThemeData + index - sizeof(int); // point at length DWORD len = *u.pdw++; len /= sizeof(WCHAR); // adjust to chars size HRESULT hr = SafeStringCchCopyW(pszBuff, cchBuff, u.pw); return hr; } //--------------------------------------------------------------------------- HRESULT CRenderObj::GetData(int iPartId, int iStateId, int iPropId, BYTE **ppData, OPTIONAL int *piSize) { if (! ppData) return MakeError32(E_INVALIDARG); int index = GetValueIndex(iPartId, iStateId, iPropId); if (index < 0) return MakeError32(ERROR_NOT_FOUND); MIXEDPTRS u; u.pb = _pbThemeData + index - sizeof(int); // point at length DWORD len = *u.pdw++; *ppData = u.pb; if (piSize) *piSize = len; return S_OK; } //--------------------------------------------------------------------------- int CRenderObj::GetValueIndex(int iPartId, int iStateId, int iTarget) { if (! iTarget) { Log(LOG_PARAMS, L"Invalid iProperyId passed to GetValueIndex: %d", iTarget); return -1; } if (! _pbSectionData) { return -1; } MIXEDPTRS u; int index; u.pb = _pbSectionData; //---- find end of data ---- THEMEHDR *hdr = (THEMEHDR *)_pbThemeData; BYTE *pbLastValidChar = _pbThemeData + (hdr->dwTotalLength - 1) - kcbEndSignature; while (u.pb <= pbLastValidChar) { UNPACKED_ENTRYHDR hdr; FillAndSkipHdr(u, &hdr); if (hdr.usTypeNum == TMT_PARTJUMPTABLE) { u.pi++; // skip over offset to first drawobj BYTE cnt = *u.pb++; if ((iPartId < 0) || (iPartId >= cnt)) { index = u.pi[0]; } else { index = u.pi[iPartId]; if (index == -1) index = u.pi[0]; } u.pb = _pbThemeData + index; continue; } if (hdr.usTypeNum == (BYTE)TMT_STATEJUMPTABLE) { BYTE cnt = *u.pb++; if ((iStateId < 0) || (iStateId >= cnt)) index = u.pi[0]; else { index = u.pi[iStateId]; if (index == -1) index = u.pi[0]; } u.pb = _pbThemeData + index; continue; } if (hdr.usTypeNum == iTarget) // got our target { // Log("GetValueIndex: match at index=%d", u.pb - _pbThemeData); return (int)(u.pb - _pbThemeData); // point at actual data (not hdr) } if (hdr.ePrimVal == TMT_JUMPTOPARENT) { index = *u.pi; if (index == -1) { // Log("no match found"); return -1; } // Log("GetValueIndex: jumping to parent at index=%d", index); u.pb = _pbThemeData + index; continue; } // Log("GetValueIndex: no match to hdr.usTypeNum=%d", hdr.usTypeNum); // advance to next value u.pb += hdr.dwDataLen; } //---- something went wrong ---- Log(LOG_ERROR, L"GetValueIndex: ran off the valid data without a '-1' jump"); return -1; } //--------------------------------------------------------------------------- HRESULT CRenderObj::GetPropertyOrigin(int iPartId, int iStateId, int iTarget, PROPERTYORIGIN *pOrigin) { if (! iTarget) { Log(LOG_PARAMS, L"Invalid iProperyId passed to GetPropertyOrigin: %d", iTarget); return E_FAIL; } if (! _pbSectionData) { return E_FAIL; } MIXEDPTRS u; if (! pOrigin) return MakeError32(E_INVALIDARG); //---- start at our section ---- u.pb = _pbSectionData; PROPERTYORIGIN origin = PO_CLASS; //---- find end of data ---- THEMEHDR *hdr = (THEMEHDR *)_pbThemeData; BYTE *pbLastValidChar = _pbThemeData + (hdr->dwTotalLength - 1) - kcbEndSignature; while (u.pb <= pbLastValidChar) { UNPACKED_ENTRYHDR hdr; FillAndSkipHdr(u, &hdr); if (hdr.usTypeNum == TMT_PARTJUMPTABLE) { u.pi++; // skip over offset to first drawobj BYTE cnt = *u.pb++; int index; if ((iPartId <= 0) || (iPartId >= cnt)) { index = u.pi[0]; } else { index = u.pi[iPartId]; if (index == -1) index = u.pi[0]; } if (index == u.pi[0]) origin = PO_CLASS; else origin = PO_PART; u.pb = _pbThemeData + index; continue; } if (hdr.usTypeNum == TMT_STATEJUMPTABLE) { BYTE cnt = *u.pb++; int index; if ((iStateId <= 0) || (iStateId >= cnt)) { index = u.pi[0]; } else { index = u.pi[iStateId]; if (index == -1) index = u.pi[0]; } if (index != u.pi[0]) origin = PO_STATE; u.pb = _pbThemeData + index; continue; } //Log("GetPropertyOrgin: iPartId=%d, iTarget=%d, DataIndex=%d", // iPartId, iTarget, u.pb - _pbThemeData); if ((iTarget == -1) || (hdr.usTypeNum == iTarget)) // got our target { // Log("GetPropertyOrgin: match at index=%d", u.pb - _pbThemeData); *pOrigin = origin; return S_OK; } if (hdr.ePrimVal == TMT_JUMPTOPARENT) { int index = *u.pi; if (index == -1) { // Log("GetPropertyOrgin: no match found"); *pOrigin = PO_NOTFOUND; return S_OK; } // Log("GetPropertyOrgin: jumping to parent at index=%d", index); u.pb = _pbThemeData + index; origin = (PROPERTYORIGIN) (origin + 1); // move down to next level of heirarchy continue; } // advance to next value u.pb += hdr.dwDataLen; } //---- something went wrong ---- Log(LOG_ERROR, L"GetPropertyOrigin: ran off the valid data without a '-1' jump"); return E_FAIL; } //--------------------------------------------------------------------------- BOOL WINAPI CRenderObj::IsPartDefined(int iPartId, int iStateId) { PROPERTYORIGIN origin; HRESULT hr = GetPropertyOrigin(iPartId, iStateId, -1, &origin); SET_LAST_ERROR(hr); if (FAILED(hr)) { return FALSE; } if (iStateId) return (origin == PO_STATE); return (origin == PO_PART); } //--------------------------------------------------------------------------- BOOL CRenderObj::ValidateObj() { BOOL fValid = TRUE; //---- check object quickly ---- if ( (! this) || (ULONGAT(_szHead) != 'dner') // "rend" || (ULONGAT(&_szHead[4]) != 'jbo') // "obj" || (ULONGAT(_szTail) != 'dne')) // "end" { Log(LOG_ALWAYS, L"CRenderObj is corrupt, addr=0x%08x", this); fValid = FALSE; } return fValid; } //--------------------------------------------------------------------------- CRenderCache *CRenderObj::GetTlsCacheObj() { HRESULT hr = S_OK; CRenderCache *pCacheObj = NULL; CCacheList *pcl = GetTlsCacheList(TRUE); if (pcl) hr = pcl->GetCacheObject(this, _iCacheSlot, &pCacheObj); return pCacheObj; }
28.254443
116
0.470397
[ "render", "object" ]
a7ab1c8066364017c43f949167a56e2695b864c2
44,488
cc
C++
chrome/browser/web_applications/preinstalled_web_app_manager_browsertest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-11-16T13:10:29.000Z
2021-11-16T13:10:29.000Z
chrome/browser/web_applications/preinstalled_web_app_manager_browsertest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/web_applications/preinstalled_web_app_manager_browsertest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// 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 "base/memory/scoped_refptr.h" #include "chrome/browser/web_applications/preinstalled_web_app_manager.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/json/json_reader.h" #include "base/path_service.h" #include "base/strings/strcat.h" #include "base/strings/string_util.h" #include "base/test/bind.h" #include "build/chromeos_buildflags.h" #include "chrome/browser/apps/app_service/app_service_proxy.h" #include "chrome/browser/apps/app_service/app_service_proxy_factory.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/ui/web_applications/test/ssl_test_utils.h" #include "chrome/browser/ui/web_applications/test/web_app_browsertest_util.h" #include "chrome/browser/web_applications/policy/web_app_policy_manager.h" #include "chrome/browser/web_applications/preinstalled_app_install_features.h" #include "chrome/browser/web_applications/preinstalled_web_apps/preinstalled_web_apps.h" #include "chrome/browser/web_applications/test/fake_os_integration_manager.h" #include "chrome/browser/web_applications/test/test_file_utils.h" #include "chrome/browser/web_applications/test/web_app_icon_test_utils.h" #include "chrome/browser/web_applications/test/web_app_install_test_utils.h" #include "chrome/browser/web_applications/web_app.h" #include "chrome/browser/web_applications/web_app_helpers.h" #include "chrome/browser/web_applications/web_app_provider.h" #include "chrome/browser/web_applications/web_application_info.h" #include "chrome/common/chrome_features.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/in_process_browser_test.h" #include "components/prefs/pref_service.h" #include "components/services/app_service/public/cpp/app_registry_cache.h" #include "components/services/app_service/public/cpp/app_update.h" #include "components/services/app_service/public/mojom/types.mojom.h" #include "content/public/test/browser_test.h" #include "content/public/test/test_launcher.h" #include "content/public/test/url_loader_interceptor.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/test_extension_registry_observer.h" #include "net/ssl/ssl_info.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/events/devices/device_data_manager_test_api.h" #include "ui/events/devices/touchscreen_device.h" #if defined(OS_CHROMEOS) #include "chrome/browser/apps/app_service/app_service_proxy.h" #include "chrome/browser/apps/app_service/app_service_proxy_factory.h" #include "chrome/browser/web_applications/test/web_app_install_test_utils.h" #endif #if BUILDFLAG(IS_CHROMEOS_ASH) #include "ash/public/cpp/test/app_list_test_api.h" #include "chrome/browser/ui/app_list/app_list_client_impl.h" #include "chrome/browser/ui/app_list/app_list_syncable_service.h" #include "chrome/browser/ui/app_list/app_list_syncable_service_factory.h" #endif namespace web_app { namespace { constexpr char kBaseDataDir[] = "chrome/test/data/banners"; // start_url in manifest.json matches navigation url for the simple // manifest_test_page.html. constexpr char kSimpleManifestStartUrl[] = "https://example.org/manifest_test_page.html"; constexpr char kNoManifestTestPageStartUrl[] = "https://example.org/no_manifest_test_page.html"; // Performs blocking IO operations. base::FilePath GetDataFilePath(const base::FilePath& relative_path, bool* path_exists) { base::ScopedAllowBlockingForTesting allow_io; base::FilePath root_path; CHECK(base::PathService::Get(base::DIR_SOURCE_ROOT, &root_path)); base::FilePath path = root_path.Append(relative_path); *path_exists = base::PathExists(path); return path; } #if defined(OS_CHROMEOS) void ExpectInitialManifestFieldsFromBasicWebApp( const WebAppIconManager& icon_manager, const WebApp* web_app, const GURL& expect_start_url, const GURL& expect_scope) { // Manifest fields: EXPECT_EQ(web_app->name(), "Basic web app"); EXPECT_EQ(web_app->start_url().spec(), expect_start_url); EXPECT_EQ(web_app->scope().spec(), expect_scope); EXPECT_EQ(web_app->display_mode(), DisplayMode::kStandalone); EXPECT_FALSE(web_app->theme_color().has_value()); EXPECT_FALSE(web_app->sync_fallback_data().theme_color.has_value()); EXPECT_EQ("Basic web app", web_app->sync_fallback_data().name); EXPECT_EQ(expect_scope.spec(), web_app->sync_fallback_data().scope); EXPECT_EQ(2u, web_app->sync_fallback_data().icon_infos.size()); EXPECT_EQ(expect_start_url.Resolve("basic-48.png"), web_app->sync_fallback_data().icon_infos[0].url); EXPECT_EQ(48, web_app->sync_fallback_data().icon_infos[0].square_size_px); EXPECT_EQ(apps::IconInfo::Purpose::kAny, web_app->sync_fallback_data().icon_infos[0].purpose); EXPECT_EQ(expect_start_url.Resolve("basic-192.png"), web_app->sync_fallback_data().icon_infos[1].url); EXPECT_EQ(192, web_app->sync_fallback_data().icon_infos[1].square_size_px); EXPECT_EQ(apps::IconInfo::Purpose::kAny, web_app->sync_fallback_data().icon_infos[1].purpose); // Manifest Resources: This is chrome/test/data/web_apps/basic-192.png EXPECT_EQ(IconManagerReadAppIconPixel(icon_manager, web_app->app_id(), /*size=*/192), SK_ColorBLACK); // User preferences: EXPECT_EQ(web_app->user_display_mode(), DisplayMode::kStandalone); } #endif // defined(OS_CHROMEOS) } // namespace class PreinstalledWebAppManagerBrowserTest : virtual public InProcessBrowserTest { public: PreinstalledWebAppManagerBrowserTest() { feature_list_.InitAndEnableFeature(features::kRecordWebAppDebugInfo); PreinstalledWebAppManager::SkipStartupForTesting(); } // InProcessBrowserTest: void SetUpOnMainThread() override { InProcessBrowserTest::SetUpOnMainThread(); web_app::test::WaitUntilReady( web_app::WebAppProvider::GetForTest(browser()->profile())); } void TearDownOnMainThread() override { ResetInterceptor(); InProcessBrowserTest::TearDownOnMainThread(); } void InitUrlLoaderInterceptor() { // We use a URLLoaderInterceptor, rather than the EmbeddedTestServer, since // a stable app_id across tests requires stable origin, whereas // EmbeddedTestServer serves content on a random port. url_loader_interceptor_ = std::make_unique<content::URLLoaderInterceptor>(base::BindRepeating( [](content::URLLoaderInterceptor::RequestParams* params) -> bool { std::string relative_request = base::StrCat( {kBaseDataDir, params->url_request.url.path_piece()}); base::FilePath relative_path = base::FilePath().AppendASCII(relative_request); bool path_exists = false; base::FilePath path = GetDataFilePath(relative_path, &path_exists); if (!path_exists) return /*intercepted=*/false; // Provide fake SSLInfo to avoid NOT_FROM_SECURE_ORIGIN error in // InstallableManager::GetData(). net::SSLInfo ssl_info; CreateFakeSslInfoCertificate(&ssl_info); content::URLLoaderInterceptor::WriteResponse( path, params->client.get(), /*headers=*/nullptr, ssl_info); return /*intercepted=*/true; })); } GURL GetAppUrl() const { return embedded_test_server()->GetURL("/web_apps/basic.html"); } const WebAppRegistrar& registrar() { return WebAppProvider::GetForTest(browser()->profile())->registrar(); } const WebAppIconManager& icon_manager() { return WebAppProvider::GetForTest(browser()->profile())->icon_manager(); } const PreinstalledWebAppManager& manager() { return WebAppProvider::GetForTest(profile()) ->preinstalled_web_app_manager(); } void SyncEmptyConfigs() { std::vector<base::Value> app_configs; PreinstalledWebAppManager::SetConfigsForTesting(&app_configs); base::RunLoop run_loop; WebAppProvider::GetForTest(profile()) ->preinstalled_web_app_manager() .LoadAndSynchronizeForTesting(base::BindLambdaForTesting( [&](std::map<GURL, ExternallyManagedAppManager::InstallResult> install_results, std::map<GURL, bool> uninstall_results) { EXPECT_EQ(install_results.size(), 0u); EXPECT_EQ(uninstall_results.size(), 0u); run_loop.Quit(); })); run_loop.Run(); PreinstalledWebAppManager::SetConfigsForTesting(nullptr); } // Mocks "icon.png" as chrome/test/data/web_apps/blue-192.png. absl::optional<InstallResultCode> SyncPreinstalledAppConfig( const GURL& install_url, base::StringPiece app_config_string) { base::FilePath test_config_dir(FILE_PATH_LITERAL("test_dir")); PreinstalledWebAppManager::SetConfigDirForTesting(&test_config_dir); base::FilePath source_root_dir; CHECK(base::PathService::Get(base::DIR_SOURCE_ROOT, &source_root_dir)); base::FilePath test_icon_path = source_root_dir.Append(GetChromeTestDataDir()) .AppendASCII("web_apps/blue-192.png"); scoped_refptr<TestFileUtils> file_utils = TestFileUtils::Create( {{base::FilePath(FILE_PATH_LITERAL("test_dir/icon.png")), test_icon_path}}); PreinstalledWebAppManager::SetFileUtilsForTesting(file_utils.get()); std::vector<base::Value> app_configs; base::JSONReader::ValueWithError json_parse_result = base::JSONReader::ReadAndReturnValueWithError(app_config_string); EXPECT_TRUE(json_parse_result.value) << "JSON parse error: " << json_parse_result.error_message; if (!json_parse_result.value) return absl::nullopt; app_configs.push_back(*std::move(json_parse_result.value)); PreinstalledWebAppManager::SetConfigsForTesting(&app_configs); absl::optional<InstallResultCode> code; base::RunLoop sync_run_loop; WebAppProvider::GetForTest(profile()) ->preinstalled_web_app_manager() .LoadAndSynchronizeForTesting(base::BindLambdaForTesting( [&](std::map<GURL, ExternallyManagedAppManager::InstallResult> install_results, std::map<GURL, bool> uninstall_results) { auto it = install_results.find(install_url); if (it != install_results.end()) code = it->second.code; sync_run_loop.Quit(); })); sync_run_loop.Run(); PreinstalledWebAppManager::SetConfigDirForTesting(nullptr); PreinstalledWebAppManager::SetFileUtilsForTesting(nullptr); PreinstalledWebAppManager::SetConfigsForTesting(nullptr); return code; } ~PreinstalledWebAppManagerBrowserTest() override = default; Profile* profile() { return browser()->profile(); } protected: void ResetInterceptor() { url_loader_interceptor_.reset(); } private: std::unique_ptr<content::URLLoaderInterceptor> url_loader_interceptor_; ScopedOsHooksSuppress os_hooks_suppress_; base::test::ScopedFeatureList feature_list_; }; IN_PROC_BROWSER_TEST_F(PreinstalledWebAppManagerBrowserTest, LaunchQueryParamsBasic) { PreinstalledWebAppManager::BypassOfflineManifestRequirementForTesting(); ASSERT_TRUE(embedded_test_server()->Start()); GURL start_url = embedded_test_server()->GetURL("/web_apps/basic.html"); AppId app_id = GenerateAppId(/*manifest_id=*/absl::nullopt, start_url); EXPECT_FALSE(registrar().IsInstalled(app_id)); constexpr char kAppConfigTemplate[] = R"({ "app_url": "$1", "launch_container": "window", "user_type": ["unmanaged"], "launch_query_params": "test_launch_params" })"; std::string app_config = base::ReplaceStringPlaceholders( kAppConfigTemplate, {start_url.spec()}, nullptr); EXPECT_EQ(SyncPreinstalledAppConfig(start_url, app_config), InstallResultCode::kSuccessNewInstall); EXPECT_TRUE(registrar().IsInstalled(app_id)); EXPECT_EQ(registrar().GetAppStartUrl(app_id).spec(), start_url); GURL launch_url = embedded_test_server()->GetURL("/web_apps/basic.html?test_launch_params"); EXPECT_EQ(registrar().GetAppLaunchUrl(app_id), launch_url); Browser* app_browser = LaunchWebAppBrowserAndWait(profile(), app_id); EXPECT_EQ( app_browser->tab_strip_model()->GetActiveWebContents()->GetVisibleURL(), launch_url); } IN_PROC_BROWSER_TEST_F(PreinstalledWebAppManagerBrowserTest, LaunchQueryParamsDuplicate) { PreinstalledWebAppManager::BypassOfflineManifestRequirementForTesting(); ASSERT_TRUE(embedded_test_server()->Start()); GURL install_url = embedded_test_server()->GetURL( "/web_apps/query_params_in_start_url.html"); GURL start_url = embedded_test_server()->GetURL( "/web_apps/query_params_in_start_url.html?query_params=in&start=url"); AppId app_id = GenerateAppId(/*manifest_id=*/absl::nullopt, start_url); EXPECT_FALSE(registrar().IsInstalled(app_id)); constexpr char kAppConfigTemplate[] = R"({ "app_url": "$1", "launch_container": "window", "user_type": ["unmanaged"], "launch_query_params": "query_params=in" })"; std::string app_config = base::ReplaceStringPlaceholders( kAppConfigTemplate, {install_url.spec()}, nullptr); EXPECT_EQ(SyncPreinstalledAppConfig(install_url, app_config), InstallResultCode::kSuccessNewInstall); EXPECT_TRUE(registrar().IsInstalled(app_id)); EXPECT_EQ(registrar().GetAppStartUrl(app_id).spec(), start_url); // We should not duplicate the query param if start_url already has it. EXPECT_EQ(registrar().GetAppLaunchUrl(app_id), start_url); Browser* app_browser = LaunchWebAppBrowserAndWait(profile(), app_id); EXPECT_EQ( app_browser->tab_strip_model()->GetActiveWebContents()->GetVisibleURL(), start_url); } IN_PROC_BROWSER_TEST_F(PreinstalledWebAppManagerBrowserTest, LaunchQueryParamsMultiple) { PreinstalledWebAppManager::BypassOfflineManifestRequirementForTesting(); ASSERT_TRUE(embedded_test_server()->Start()); GURL start_url = embedded_test_server()->GetURL("/web_apps/basic.html"); GURL launch_url = embedded_test_server()->GetURL( "/web_apps/basic.html?more=than&one=query&param"); AppId app_id = GenerateAppId(/*manifest_id=*/absl::nullopt, start_url); EXPECT_FALSE(registrar().IsInstalled(app_id)); constexpr char kAppConfigTemplate[] = R"({ "app_url": "$1", "launch_container": "window", "user_type": ["unmanaged"], "launch_query_params": "more=than&one=query&param" })"; std::string app_config = base::ReplaceStringPlaceholders( kAppConfigTemplate, {start_url.spec()}, nullptr); EXPECT_EQ(SyncPreinstalledAppConfig(start_url, app_config), InstallResultCode::kSuccessNewInstall); EXPECT_TRUE(registrar().IsInstalled(app_id)); EXPECT_EQ(registrar().GetAppStartUrl(app_id).spec(), start_url); EXPECT_EQ(registrar().GetAppLaunchUrl(app_id), launch_url); Browser* app_browser = LaunchWebAppBrowserAndWait(profile(), app_id); EXPECT_EQ( app_browser->tab_strip_model()->GetActiveWebContents()->GetVisibleURL(), launch_url); } IN_PROC_BROWSER_TEST_F(PreinstalledWebAppManagerBrowserTest, LaunchQueryParamsComplex) { PreinstalledWebAppManager::BypassOfflineManifestRequirementForTesting(); ASSERT_TRUE(embedded_test_server()->Start()); GURL install_url = embedded_test_server()->GetURL( "/web_apps/query_params_in_start_url.html"); GURL start_url = embedded_test_server()->GetURL( "/web_apps/query_params_in_start_url.html?query_params=in&start=url"); AppId app_id = GenerateAppId(/*manifest_id=*/absl::nullopt, start_url); EXPECT_FALSE(registrar().IsInstalled(app_id)); constexpr char kAppConfigTemplate[] = R"({ "app_url": "$1", "launch_container": "window", "user_type": ["unmanaged"], "launch_query_params": "!@#$$%^*&)(" })"; std::string app_config = base::ReplaceStringPlaceholders( kAppConfigTemplate, {install_url.spec()}, nullptr); EXPECT_EQ(SyncPreinstalledAppConfig(install_url, app_config), InstallResultCode::kSuccessNewInstall); EXPECT_TRUE(registrar().IsInstalled(app_id)); EXPECT_EQ(registrar().GetAppStartUrl(app_id).spec(), start_url); GURL launch_url = embedded_test_server()->GetURL( "/web_apps/" "query_params_in_start_url.html?query_params=in&start=url&!@%23$%^*&)("); EXPECT_EQ(registrar().GetAppLaunchUrl(app_id), launch_url); Browser* app_browser = LaunchWebAppBrowserAndWait(profile(), app_id); EXPECT_EQ( app_browser->tab_strip_model()->GetActiveWebContents()->GetVisibleURL(), launch_url); } class PreinstalledWebAppManagerExtensionBrowserTest : public extensions::ExtensionBrowserTest, public PreinstalledWebAppManagerBrowserTest { public: PreinstalledWebAppManagerExtensionBrowserTest() = default; ~PreinstalledWebAppManagerExtensionBrowserTest() override = default; void SetUpOnMainThread() override { extensions::ExtensionBrowserTest::SetUpOnMainThread(); web_app::test::WaitUntilReady( web_app::WebAppProvider::GetForTest(browser()->profile())); } void TearDownOnMainThread() override { ResetInterceptor(); extensions::ExtensionBrowserTest::TearDownOnMainThread(); } }; #if !BUILDFLAG(IS_CHROMEOS_LACROS) IN_PROC_BROWSER_TEST_F(PreinstalledWebAppManagerExtensionBrowserTest, UninstallAndReplace) { PreinstalledWebAppManager::BypassOfflineManifestRequirementForTesting(); ASSERT_TRUE(embedded_test_server()->Start()); // Install Chrome app to be replaced. const char kChromeAppDirectory[] = "app"; const char kChromeAppName[] = "App Test"; const extensions::Extension* app = InstallExtensionWithSourceAndFlags( test_data_dir_.AppendASCII(kChromeAppDirectory), 1, extensions::mojom::ManifestLocation::kInternal, extensions::Extension::NO_FLAGS); EXPECT_EQ(app->name(), kChromeAppName); // Start listening for Chrome app uninstall. extensions::TestExtensionRegistryObserver uninstall_observer( extensions::ExtensionRegistry::Get(browser()->profile())); constexpr char kAppConfigTemplate[] = R"({ "app_url": "$1", "launch_container": "window", "user_type": ["unmanaged"], "uninstall_and_replace": ["$2"] })"; std::string app_config = base::ReplaceStringPlaceholders( kAppConfigTemplate, {GetAppUrl().spec(), app->id()}, nullptr); EXPECT_EQ(SyncPreinstalledAppConfig(GetAppUrl(), app_config), InstallResultCode::kSuccessNewInstall); // Chrome app should get uninstalled. scoped_refptr<const extensions::Extension> uninstalled_app = uninstall_observer.WaitForExtensionUninstalled(); EXPECT_EQ(app, uninstalled_app.get()); } #endif // !BUILDFLAG(IS_CHROMEOS_LACROS) IN_PROC_BROWSER_TEST_F(PreinstalledWebAppManagerBrowserTest, PreinstalledAppsPrefInstall) { PreinstalledWebAppManager::BypassOfflineManifestRequirementForTesting(); ASSERT_TRUE(embedded_test_server()->Start()); profile()->GetPrefs()->SetString(prefs::kPreinstalledApps, "install"); constexpr char kAppConfigTemplate[] = R"({ "app_url": "$1", "launch_container": "window", "user_type": ["unmanaged"] })"; std::string app_config = base::ReplaceStringPlaceholders( kAppConfigTemplate, {GetAppUrl().spec()}, nullptr); EXPECT_EQ(SyncPreinstalledAppConfig(GetAppUrl(), app_config), InstallResultCode::kSuccessNewInstall); } IN_PROC_BROWSER_TEST_F(PreinstalledWebAppManagerBrowserTest, PreinstalledAppsPrefNoinstall) { PreinstalledWebAppManager::BypassOfflineManifestRequirementForTesting(); ASSERT_TRUE(embedded_test_server()->Start()); profile()->GetPrefs()->SetString(prefs::kPreinstalledApps, "noinstall"); constexpr char kAppConfigTemplate[] = R"({ "app_url": "$1", "launch_container": "window", "user_type": ["unmanaged"] })"; std::string app_config = base::ReplaceStringPlaceholders( kAppConfigTemplate, {GetAppUrl().spec()}, nullptr); EXPECT_EQ(SyncPreinstalledAppConfig(GetAppUrl(), app_config), absl::nullopt); } const char kOnlyIfPreviouslyPreinstalled_PreviousConfig[] = R"({ "app_url": "$1", "launch_container": "window", "user_type": ["unmanaged"] })"; const char kOnlyIfPreviouslyPreinstalled_NextConfig[] = R"({ "app_url": "$1", "launch_container": "window", "user_type": ["unmanaged"], "only_if_previously_preinstalled": true })"; IN_PROC_BROWSER_TEST_F(PreinstalledWebAppManagerBrowserTest, PRE_OnlyIfPreviouslyPreinstalled_AppPreserved) { PreinstalledWebAppManager::BypassOfflineManifestRequirementForTesting(); InitUrlLoaderInterceptor(); std::string prev_app_config = base::ReplaceStringPlaceholders( kOnlyIfPreviouslyPreinstalled_PreviousConfig, {kSimpleManifestStartUrl}, nullptr); // The user had the app installed. EXPECT_EQ( SyncPreinstalledAppConfig(GURL{kSimpleManifestStartUrl}, prev_app_config), InstallResultCode::kSuccessNewInstall); AppId app_id = GenerateAppId(/*manifest_id=*/absl::nullopt, GURL{kSimpleManifestStartUrl}); EXPECT_TRUE(registrar().IsInstalled(app_id)); } IN_PROC_BROWSER_TEST_F(PreinstalledWebAppManagerBrowserTest, OnlyIfPreviouslyPreinstalled_AppPreserved) { PreinstalledWebAppManager::BypassOfflineManifestRequirementForTesting(); InitUrlLoaderInterceptor(); std::string next_app_config = base::ReplaceStringPlaceholders(kOnlyIfPreviouslyPreinstalled_NextConfig, {kSimpleManifestStartUrl}, nullptr); // The user still has the app. EXPECT_EQ( SyncPreinstalledAppConfig(GURL{kSimpleManifestStartUrl}, next_app_config), InstallResultCode::kSuccessAlreadyInstalled); AppId app_id = GenerateAppId(/*manifest_id=*/absl::nullopt, GURL{kSimpleManifestStartUrl}); EXPECT_TRUE(registrar().IsInstalled(app_id)); } IN_PROC_BROWSER_TEST_F(PreinstalledWebAppManagerBrowserTest, PRE_OnlyIfPreviouslyPreinstalled_NoAppPreinstalled) { PreinstalledWebAppManager::BypassOfflineManifestRequirementForTesting(); InitUrlLoaderInterceptor(); std::string prev_app_config = base::ReplaceStringPlaceholders( kOnlyIfPreviouslyPreinstalled_PreviousConfig, {kNoManifestTestPageStartUrl}, nullptr); EXPECT_EQ(SyncPreinstalledAppConfig(GURL{kNoManifestTestPageStartUrl}, prev_app_config), InstallResultCode::kNotValidManifestForWebApp); AppId app_id = GenerateAppId(/*manifest_id=*/absl::nullopt, GURL{kNoManifestTestPageStartUrl}); EXPECT_FALSE(registrar().IsInstalled(app_id)); } IN_PROC_BROWSER_TEST_F(PreinstalledWebAppManagerBrowserTest, OnlyIfPreviouslyPreinstalled_NoAppPreinstalled) { PreinstalledWebAppManager::BypassOfflineManifestRequirementForTesting(); InitUrlLoaderInterceptor(); std::string next_app_config = base::ReplaceStringPlaceholders(kOnlyIfPreviouslyPreinstalled_NextConfig, {kNoManifestTestPageStartUrl}, nullptr); // The user has no the app. EXPECT_EQ(SyncPreinstalledAppConfig(GURL{kNoManifestTestPageStartUrl}, next_app_config), absl::nullopt); AppId app_id = GenerateAppId(/*manifest_id=*/absl::nullopt, GURL{kNoManifestTestPageStartUrl}); EXPECT_FALSE(registrar().IsInstalled(app_id)); } // The offline manifest JSON config functionality is only available on Chrome // OS. #if defined(OS_CHROMEOS) // Check that offline fallback installs work offline. IN_PROC_BROWSER_TEST_F(PreinstalledWebAppManagerBrowserTest, OfflineFallbackManifestSiteOffline) { constexpr char kAppInstallUrl[] = "https://offline-site.com/install.html"; constexpr char kAppName[] = "Offline app name"; constexpr char kAppStartUrl[] = "https://offline-site.com/start.html"; constexpr char kAppScope[] = "https://offline-site.com/"; AppId app_id = GenerateAppId(/*manifest_id=*/absl::nullopt, GURL(kAppStartUrl)); EXPECT_FALSE(registrar().IsInstalled(app_id)); constexpr char kAppConfigTemplate[] = R"({ "app_url": "$1", "launch_container": "window", "user_type": ["unmanaged"], "offline_manifest": { "name": "$2", "start_url": "$3", "scope": "$4", "display": "minimal-ui", "theme_color_argb_hex": "AABBCCDD", "icon_any_pngs": ["icon.png"] } })"; std::string app_config = base::ReplaceStringPlaceholders( kAppConfigTemplate, {kAppInstallUrl, kAppName, kAppStartUrl, kAppScope}, nullptr); EXPECT_EQ(SyncPreinstalledAppConfig(GURL(kAppInstallUrl), app_config), InstallResultCode::kSuccessOfflineFallbackInstall); EXPECT_TRUE(registrar().IsInstalled(app_id)); EXPECT_EQ(registrar().GetAppShortName(app_id), kAppName); EXPECT_EQ(registrar().GetAppStartUrl(app_id).spec(), kAppStartUrl); EXPECT_EQ(registrar().GetAppScope(app_id).spec(), kAppScope); EXPECT_EQ(registrar().GetAppUserDisplayMode(app_id), DisplayMode::kStandalone); EXPECT_EQ(registrar().GetAppDisplayMode(app_id), DisplayMode::kMinimalUi); // theme_color must be installed opaque. EXPECT_EQ(registrar().GetAppThemeColor(app_id), SkColorSetARGB(0xFF, 0xBB, 0xCC, 0xDD)); EXPECT_EQ(IconManagerReadAppIconPixel(icon_manager(), app_id, /*size=*/192), SK_ColorBLUE); } // Check that offline fallback installs attempt fetching the install_url. IN_PROC_BROWSER_TEST_F(PreinstalledWebAppManagerBrowserTest, OfflineFallbackManifestSiteOnline) { ASSERT_TRUE(embedded_test_server()->Start()); // This install_url serves a manifest with different values to what we specify // in the offline_manifest. Check that it gets used instead of the // offline_manifest. GURL install_url = embedded_test_server()->GetURL("/web_apps/basic.html"); GURL offline_start_url = embedded_test_server()->GetURL( "/web_apps/offline-only-start-url-that-does-not-exist.html"); GURL scope = embedded_test_server()->GetURL("/web_apps/"); AppId offline_app_id = GenerateAppId(/*manifest_id=*/absl::nullopt, offline_start_url); EXPECT_FALSE(registrar().IsInstalled(offline_app_id)); constexpr char kAppConfigTemplate[] = R"({ "app_url": "$1", "launch_container": "window", "user_type": ["unmanaged"], "offline_manifest": { "name": "Offline only app name", "start_url": "$2", "scope": "$3", "display": "minimal-ui", "theme_color_argb_hex": "AABBCCDD", "icon_any_pngs": ["icon.png"] } })"; std::string app_config = base::ReplaceStringPlaceholders( kAppConfigTemplate, {install_url.spec(), offline_start_url.spec(), scope.spec()}, nullptr); EXPECT_EQ(SyncPreinstalledAppConfig(install_url, app_config), InstallResultCode::kSuccessNewInstall); EXPECT_FALSE(registrar().IsInstalled(offline_app_id)); // basic.html's manifest start_url is basic.html. AppId app_id = GenerateAppId(/*manifest_id=*/absl::nullopt, install_url); EXPECT_TRUE(registrar().IsInstalled(app_id)); EXPECT_EQ(registrar().GetAppShortName(app_id), "Basic web app"); EXPECT_EQ(registrar().GetAppStartUrl(app_id).spec(), install_url); EXPECT_EQ(registrar().GetAppScope(app_id).spec(), scope); EXPECT_EQ(registrar().GetAppUserDisplayMode(app_id), DisplayMode::kStandalone); EXPECT_EQ(registrar().GetAppDisplayMode(app_id), DisplayMode::kStandalone); } // Check that offline only installs work offline. IN_PROC_BROWSER_TEST_F(PreinstalledWebAppManagerBrowserTest, OfflineOnlyManifestSiteOffline) { constexpr char kAppInstallUrl[] = "https://offline-site.com/install.html"; constexpr char kAppName[] = "Offline app name"; constexpr char kAppStartUrl[] = "https://offline-site.com/start.html"; constexpr char kAppScope[] = "https://offline-site.com/"; AppId app_id = GenerateAppId(/*manifest_id=*/absl::nullopt, GURL(kAppStartUrl)); EXPECT_FALSE(registrar().IsInstalled(app_id)); constexpr char kAppConfigTemplate[] = R"({ "app_url": "$1", "launch_container": "window", "user_type": ["unmanaged"], "only_use_offline_manifest": true, "offline_manifest": { "name": "$2", "start_url": "$3", "scope": "$4", "display": "minimal-ui", "theme_color_argb_hex": "AABBCCDD", "icon_any_pngs": ["icon.png"] } })"; std::string app_config = base::ReplaceStringPlaceholders( kAppConfigTemplate, {kAppInstallUrl, kAppName, kAppStartUrl, kAppScope}, nullptr); EXPECT_EQ(SyncPreinstalledAppConfig(GURL(kAppInstallUrl), app_config), InstallResultCode::kSuccessOfflineOnlyInstall); EXPECT_TRUE(registrar().IsInstalled(app_id)); EXPECT_EQ(registrar().GetAppShortName(app_id), kAppName); EXPECT_EQ(registrar().GetAppStartUrl(app_id).spec(), kAppStartUrl); EXPECT_EQ(registrar().GetAppScope(app_id).spec(), kAppScope); EXPECT_EQ(registrar().GetAppUserDisplayMode(app_id), DisplayMode::kStandalone); EXPECT_EQ(registrar().GetAppDisplayMode(app_id), DisplayMode::kMinimalUi); // theme_color must be installed opaque. EXPECT_EQ(registrar().GetAppThemeColor(app_id), SkColorSetARGB(0xFF, 0xBB, 0xCC, 0xDD)); EXPECT_EQ(IconManagerReadAppIconPixel(icon_manager(), app_id, /*size=*/192), SK_ColorBLUE); } // Check that offline only installs don't fetch from the install_url. IN_PROC_BROWSER_TEST_F(PreinstalledWebAppManagerBrowserTest, OfflineOnlyManifestSiteOnline) { ASSERT_TRUE(embedded_test_server()->Start()); // This install_url serves a manifest with different values to what we specify // in the offline_manifest. Check that it doesn't get used. GURL install_url = GetAppUrl(); const char kAppName[] = "Offline only app name"; GURL start_url = embedded_test_server()->GetURL( "/web_apps/offline-only-start-url-that-does-not-exist.html"); GURL scope = embedded_test_server()->GetURL("/web_apps/"); AppId app_id = GenerateAppId(/*manifest_id=*/absl::nullopt, start_url); EXPECT_FALSE(registrar().IsInstalled(app_id)); constexpr char kAppConfigTemplate[] = R"({ "app_url": "$1", "launch_container": "window", "user_type": ["unmanaged"], "only_use_offline_manifest": true, "offline_manifest": { "name": "$2", "start_url": "$3", "scope": "$4", "display": "minimal-ui", "theme_color_argb_hex": "AABBCCDD", "icon_any_pngs": ["icon.png"] } })"; std::string app_config = base::ReplaceStringPlaceholders( kAppConfigTemplate, {install_url.spec(), kAppName, start_url.spec(), scope.spec()}, nullptr); EXPECT_EQ(SyncPreinstalledAppConfig(install_url, app_config), InstallResultCode::kSuccessOfflineOnlyInstall); EXPECT_TRUE(registrar().IsInstalled(app_id)); EXPECT_EQ(registrar().GetAppShortName(app_id), kAppName); EXPECT_EQ(registrar().GetAppStartUrl(app_id).spec(), start_url); EXPECT_EQ(registrar().GetAppScope(app_id).spec(), scope); EXPECT_EQ(registrar().GetAppUserDisplayMode(app_id), DisplayMode::kStandalone); EXPECT_EQ(registrar().GetAppDisplayMode(app_id), DisplayMode::kMinimalUi); // theme_color must be installed opaque. EXPECT_EQ(registrar().GetAppThemeColor(app_id), SkColorSetARGB(0xFF, 0xBB, 0xCC, 0xDD)); EXPECT_EQ(IconManagerReadAppIconPixel(icon_manager(), app_id, /*size=*/192), SK_ColorBLUE); } const char kOnlyForNewUsersInstallUrl[] = "https://example.org/"; const char kOnlyForNewUsersConfig[] = R"({ "app_url": "https://example.org/", "launch_container": "window", "user_type": ["unmanaged"], "only_for_new_users": true, "only_use_offline_manifest": true, "offline_manifest": { "name": "Test", "start_url": "https://example.org/", "scope": "https://example.org/", "display": "standalone", "icon_any_pngs": ["icon.png"] } })"; IN_PROC_BROWSER_TEST_F(PreinstalledWebAppManagerBrowserTest, PRE_OnlyForNewUsersWithNewUser) { // Install a policy app first to check that it doesn't interfere. { base::RunLoop run_loop; WebAppPolicyManager& policy_manager = WebAppProvider::GetForTest(profile())->policy_manager(); policy_manager.SetOnAppsSynchronizedCompletedCallbackForTesting( run_loop.QuitClosure()); const char kWebAppPolicy[] = R"([{ "url": "https://policy-example.org/", "default_launch_container": "window" }])"; profile()->GetPrefs()->Set(prefs::kWebAppInstallForceList, base::JSONReader::Read(kWebAppPolicy).value()); run_loop.Run(); } // New user should have the app installed. EXPECT_EQ(SyncPreinstalledAppConfig(GURL(kOnlyForNewUsersInstallUrl), kOnlyForNewUsersConfig), InstallResultCode::kSuccessOfflineOnlyInstall); } IN_PROC_BROWSER_TEST_F(PreinstalledWebAppManagerBrowserTest, OnlyForNewUsersWithNewUser) { // App should persist after user stops being a new user. EXPECT_EQ(SyncPreinstalledAppConfig(GURL(kOnlyForNewUsersInstallUrl), kOnlyForNewUsersConfig), InstallResultCode::kSuccessAlreadyInstalled); } IN_PROC_BROWSER_TEST_F(PreinstalledWebAppManagerBrowserTest, PRE_OnlyForNewUsersWithOldUser) { // Simulate running Chrome without the configs present. SyncEmptyConfigs(); } IN_PROC_BROWSER_TEST_F(PreinstalledWebAppManagerBrowserTest, OnlyForNewUsersWithOldUser) { // This instance of Chrome should be considered not a new user after the // previous PRE_ launch and sync. EXPECT_EQ(SyncPreinstalledAppConfig(GURL(kOnlyForNewUsersInstallUrl), kOnlyForNewUsersConfig), absl::nullopt); } #if BUILDFLAG(IS_CHROMEOS_ASH) IN_PROC_BROWSER_TEST_F(PreinstalledWebAppManagerBrowserTest, OemInstalled) { PreinstalledWebAppManager::BypassOfflineManifestRequirementForTesting(); ASSERT_TRUE(embedded_test_server()->Start()); EXPECT_EQ(SyncPreinstalledAppConfig(GetAppUrl(), base::ReplaceStringPlaceholders( R"({ "app_url": "$1", "launch_container": "window", "oem_installed": true, "user_type": ["unmanaged"] })", {GetAppUrl().spec()}, nullptr)), InstallResultCode::kSuccessNewInstall); AppId app_id = GenerateAppId(/*manifest_id=*/absl::nullopt, GetAppUrl()); EXPECT_TRUE(registrar().WasInstalledByOem(app_id)); // Wait for app service to see the newly installed app. auto* proxy = apps::AppServiceProxyFactory::GetForProfile(profile()); proxy->FlushMojoCallsForTesting(); apps::mojom::InstallReason install_reason = apps::mojom::InstallReason::kUnknown; proxy->AppRegistryCache().ForOneApp(app_id, [&](const apps::AppUpdate& update) { install_reason = update.InstallReason(); }); EXPECT_EQ(install_reason, apps::mojom::InstallReason::kOem); } #endif // BUILDFLAG(IS_CHROMEOS_ASH) namespace { ui::TouchscreenDevice CreateTouchDevice(ui::InputDeviceType type, bool stylus_support) { ui::TouchscreenDevice touch_device = ui::TouchscreenDevice(); touch_device.type = type; touch_device.has_stylus = stylus_support; return touch_device; } } // namespace // Note that SetTouchscreenDevices() does not update the device list // if the number of displays don't change. IN_PROC_BROWSER_TEST_F(PreinstalledWebAppManagerBrowserTest, DisableIfTouchscreenWithStylusNotSupported) { PreinstalledWebAppManager::BypassOfflineManifestRequirementForTesting(); ASSERT_TRUE(embedded_test_server()->Start()); const auto manifest = base::ReplaceStringPlaceholders( R"({ "app_url": "$1", "launch_container": "window", "disable_if_touchscreen_with_stylus_not_supported": true, "user_type": ["unmanaged"] })", {GetAppUrl().spec()}, nullptr); AppId app_id = GenerateAppId(/*manifest_id=*/absl::nullopt, GetAppUrl()); const auto& disabled_configs = manager().debug_info()->disabled_configs; constexpr char kErrorMessage[] = " disabled because the device does not have a built-in touchscreen with " "stylus support."; // Test Case: No touchscreen installed on device. EXPECT_EQ(SyncPreinstalledAppConfig(GetAppUrl(), manifest), absl::nullopt); EXPECT_FALSE(registrar().IsInstalled(app_id)); EXPECT_EQ(disabled_configs.size(), 1u); EXPECT_EQ(disabled_configs.back().second, GetAppUrl().spec() + kErrorMessage); // Test Case: Built-in touchscreen without stylus support installed on device. ui::DeviceDataManagerTestApi().SetTouchscreenDevices({CreateTouchDevice( ui::InputDeviceType::INPUT_DEVICE_INTERNAL, /* stylus_support =*/false)}); EXPECT_EQ(SyncPreinstalledAppConfig(GetAppUrl(), manifest), absl::nullopt); EXPECT_FALSE(registrar().IsInstalled(app_id)); EXPECT_EQ(disabled_configs.size(), 2u); EXPECT_EQ(disabled_configs.back().second, GetAppUrl().spec() + kErrorMessage); // Test Case: Connected external touchscreen with stylus support connected to // device. ui::DeviceDataManagerTestApi().SetTouchscreenDevices( {CreateTouchDevice(ui::InputDeviceType::INPUT_DEVICE_INTERNAL, /* stylus_support =*/false), CreateTouchDevice(ui::InputDeviceType::INPUT_DEVICE_USB, /* stylus_support =*/true)}); EXPECT_EQ(SyncPreinstalledAppConfig(GetAppUrl(), manifest), absl::nullopt); EXPECT_FALSE(registrar().IsInstalled(app_id)); EXPECT_EQ(disabled_configs.size(), 3u); EXPECT_EQ(disabled_configs.back().second, GetAppUrl().spec() + kErrorMessage); // Test Case: Create a built-in touchscreen device with stylus support and add // it to the device. ui::DeviceDataManagerTestApi().SetTouchscreenDevices( {CreateTouchDevice(ui::InputDeviceType::INPUT_DEVICE_INTERNAL, true)}); EXPECT_EQ(SyncPreinstalledAppConfig(GetAppUrl(), manifest), InstallResultCode::kSuccessNewInstall); EXPECT_TRUE(registrar().IsInstalled(app_id)); EXPECT_EQ(disabled_configs.size(), 3u); } #if BUILDFLAG(IS_CHROMEOS_ASH) // Disabled due to test flakiness. https://crbug.com/1267164. IN_PROC_BROWSER_TEST_F(PreinstalledWebAppManagerBrowserTest, DISABLED_UninstallFromTwoItemAppListFolder) { GURL preinstalled_app_start_url("https://example.org/"); GURL user_app_start_url("https://test.org/"); apps::AppServiceProxy* proxy = apps::AppServiceProxyFactory::GetForProfile(profile()); AppListClientImpl::GetInstance()->UpdateProfile(); ash::AppListTestApi app_list_test_api; app_list::AppListSyncableService* app_list_syncable_service = app_list::AppListSyncableServiceFactory::GetForProfile(profile()); // Install default app. constexpr char kAppConfigTemplate[] = R"({ "app_url": "$1", "launch_container": "window", "user_type": ["unmanaged"], "only_use_offline_manifest": true, "offline_manifest": { "name": "Test default app", "display": "standalone", "start_url": "$1", "scope": "$1", "icon_any_pngs": ["icon.png"] } })"; std::string app_config = base::ReplaceStringPlaceholders( kAppConfigTemplate, {preinstalled_app_start_url.spec()}, nullptr); EXPECT_EQ(SyncPreinstalledAppConfig(preinstalled_app_start_url, app_config), InstallResultCode::kSuccessOfflineOnlyInstall); AppId preinstalled_app_id = GenerateAppId(/*manifest_id=*/absl::nullopt, preinstalled_app_start_url); // Install user app. auto web_application_info = std::make_unique<WebApplicationInfo>(); web_application_info->start_url = user_app_start_url; web_application_info->title = u"Test user app"; AppId user_app_id = test::InstallWebApp(profile(), std::move(web_application_info)); // Ensure the UI receives these apps. proxy->FlushMojoCallsForTesting(); // Put apps in app list folder. std::string folder_id = app_list_test_api.CreateFolderWithApps( {preinstalled_app_id, user_app_id}); EXPECT_EQ( app_list_syncable_service->GetSyncItem(preinstalled_app_id)->parent_id, folder_id); EXPECT_EQ(app_list_syncable_service->GetSyncItem(user_app_id)->parent_id, folder_id); // Uninstall default app. proxy->UninstallSilently(preinstalled_app_id, apps::mojom::UninstallSource::kUnknown); // Ensure the UI receives the app uninstall. proxy->FlushMojoCallsForTesting(); // Default app should be removed from local app list but remain in sync list. EXPECT_FALSE(registrar().IsInstalled(preinstalled_app_id)); EXPECT_TRUE(registrar().IsInstalled(user_app_id)); EXPECT_FALSE(app_list_test_api.HasApp(preinstalled_app_id)); EXPECT_TRUE(app_list_test_api.HasApp(user_app_id)); EXPECT_EQ( app_list_syncable_service->GetSyncItem(preinstalled_app_id)->parent_id, ""); EXPECT_EQ(app_list_syncable_service->GetSyncItem(user_app_id)->parent_id, ""); } #endif // BUILDFLAG(IS_CHROMEOS_ASH) // Check that offline only installs don't overwrite fresh online manifest // obtained via sync install. IN_PROC_BROWSER_TEST_F(PreinstalledWebAppManagerBrowserTest, OfflineOnlyManifest_SiteAlreadyInstalledFromSync) { ASSERT_TRUE(embedded_test_server()->Start()); GURL install_url = GetAppUrl(); GURL start_url = install_url; GURL scope = embedded_test_server()->GetURL("/web_apps/"); const AppId app_id = InstallWebAppFromPage(browser(), install_url); const WebApp* web_app = registrar().GetAppById(app_id); ASSERT_TRUE(web_app); EXPECT_TRUE(web_app->IsSynced()); EXPECT_FALSE(web_app->IsPreinstalledApp()); { SCOPED_TRACE("Expect initial manifest fields from basic.html web app."); ExpectInitialManifestFieldsFromBasicWebApp(icon_manager(), web_app, start_url, scope); } constexpr char kAppConfigTemplate[] = R"({ "app_url": "$1", "launch_container": "tab", "user_type": ["unmanaged"], "only_use_offline_manifest": true, "offline_manifest": { "name": "$2", "start_url": "$3", "scope": "$4", "display": "minimal-ui", "theme_color_argb_hex": "AABBCCDD", "icon_any_pngs": ["icon.png"] } })"; std::string app_config = base::ReplaceStringPlaceholders( kAppConfigTemplate, {install_url.spec(), "Overwrite app name", start_url.spec(), "https://overwrite.scope/"}, nullptr); EXPECT_EQ(SyncPreinstalledAppConfig(install_url, app_config), InstallResultCode::kSuccessOfflineOnlyInstall); EXPECT_EQ(web_app, registrar().GetAppById(app_id)); EXPECT_TRUE(web_app->IsSynced()); EXPECT_TRUE(web_app->IsPreinstalledApp()); { SCOPED_TRACE( "Expect same manifest fields from basic.html web app, no overwrites."); ExpectInitialManifestFieldsFromBasicWebApp(icon_manager(), web_app, start_url, scope); } } #endif // defined(OS_CHROMEOS) } // namespace web_app
40.554239
88
0.706662
[ "vector" ]
a7acd8a348d96ee1f44ac26e4c3082fb7d855f2c
3,106
cpp
C++
Tritom_Framework/C_Edge.cpp
davidfreire/Tritom
e5d9deade085f701553da7a0dfaefcea8572e4e9
[ "MIT" ]
4
2016-02-10T01:14:59.000Z
2017-05-23T08:07:54.000Z
Tritom_Framework/C_Edge.cpp
davidfreire/Tritom
e5d9deade085f701553da7a0dfaefcea8572e4e9
[ "MIT" ]
null
null
null
Tritom_Framework/C_Edge.cpp
davidfreire/Tritom
e5d9deade085f701553da7a0dfaefcea8572e4e9
[ "MIT" ]
null
null
null
#include "C_Edge.h" C_Edge::C_Edge(C_Vertex *vertex_1, C_Vertex *vertex_2, CvQuadEdge2D *tmp_edge){ this->vertex1=vertex_1; this->vertex2=vertex_2; this->tmp_edge=tmp_edge; trixels = new vector <C_Trixel *>; }; C_Edge::~C_Edge(){ this->vertex1=NULL; this->vertex2=NULL; this->trixels->clear(); delete this->trixels; }; float C_Edge::Get_Angle(C_Vertex *src_vertex, int bins){ CvPoint *src_pt, *dst_pt; if(src_vertex == this->vertex1){ src_pt = this->vertex1->Get_Vertex_pt(); dst_pt = this->vertex2->Get_Vertex_pt(); }else{ src_pt = this->vertex2->Get_Vertex_pt(); dst_pt = this->vertex1->Get_Vertex_pt(); } return Calculate_Angle (src_pt, dst_pt, bins); } float C_Edge::Get_Magnitude(C_Vertex *src_vertex, int bins){ CvPoint *src_pt, *dst_pt; if(src_vertex == this->vertex1){ src_pt = this->vertex1->Get_Vertex_pt(); dst_pt = this->vertex2->Get_Vertex_pt(); }else{ src_pt = this->vertex2->Get_Vertex_pt(); dst_pt = this->vertex1->Get_Vertex_pt(); } return Calculate_Magnitude (src_pt, dst_pt); } void C_Edge::Update_Trixel(C_Trixel *obj) { this->trixels->push_back(obj); } int C_Edge::Check_Vertex(C_Vertex *vrtx1, C_Vertex *vrtx2) { if((this->vertex1 == vrtx1) || (this->vertex1 == vrtx2)) if((this->vertex2 == vrtx1) || (this->vertex2 == vrtx2)) return 1; return 0; } double C_Edge::Calculate_Angle (CvPoint *src_pt, CvPoint *dst_pt, int bins_x_quadrant){ float output; float angle; if( dst_pt->y < 0) angle = atan2(float( dst_pt->y - src_pt->y), float(((-1)*dst_pt->x) - src_pt->x)) * 180 / 3.14159265358979323846; else angle = atan2(float(dst_pt->y - src_pt->y), float(dst_pt->x - src_pt->x)) * 180 / 3.14159265358979323846; if(angle < 0){ angle = atan2(float(dst_pt->y - src_pt->y), (-1)*float(dst_pt->x - src_pt->x)) * 180 / 3.14159265358979323846; output = (180. - (angle)); }else output = angle; //printf("\nThe angle from (%d,%d) to (%d,%d) is %.2f", src_pt->x, src_pt->y, dst_pt->x, dst_pt->y, output); if(bins_x_quadrant == 0) return output; else return int(output/(90/bins_x_quadrant)); } float C_Edge::Calculate_Magnitude (CvPoint *src_pt, CvPoint *dst_pt){ return sqrt(((float(dst_pt->y - src_pt->y)*float(dst_pt->y - src_pt->y))) + (float(dst_pt->x - src_pt->x) * float(dst_pt->x - src_pt->x))); } void C_Edge::Draw_Edge(C_Vertex *src_vertex, CvScalar color, IplImage *img ) { CvPoint *src_pt, *dst_pt; if(src_vertex == this->vertex1){ src_pt = this->vertex1->Get_Vertex_pt(); dst_pt = this->vertex2->Get_Vertex_pt(); }else{ src_pt = this->vertex2->Get_Vertex_pt(); dst_pt = this->vertex1->Get_Vertex_pt(); } cvLine( img, *src_pt, *dst_pt, color, 1, 8, 0 ); } void C_Edge::Draw_Edge(CvScalar color, IplImage *img ) { cvLine( img, (*this->vertex1->Get_Vertex_pt()), (*this->vertex2->Get_Vertex_pt()), color, 1, 8, 0 ); } vector<C_Trixel *> * C_Edge::Get_Trixels() { return this->trixels; } CvQuadEdge2D *C_Edge::Get_tmpEdge(){ return this->tmp_edge; }
25.883333
141
0.647778
[ "vector" ]
a7b483b009390fcd7c4cac095079f2e113d64cb1
15,068
cpp
C++
MeshModelingToolCP_Solution/Codes/Viewer/MyViewer.cpp
PacosLelouch/MeshModelingToolCP
22965f7d0bc2dd14cfa372c023b041a0bbf152ed
[ "BSD-2-Clause" ]
null
null
null
MeshModelingToolCP_Solution/Codes/Viewer/MyViewer.cpp
PacosLelouch/MeshModelingToolCP
22965f7d0bc2dd14cfa372c023b041a0bbf152ed
[ "BSD-2-Clause" ]
null
null
null
MeshModelingToolCP_Solution/Codes/Viewer/MyViewer.cpp
PacosLelouch/MeshModelingToolCP
22965f7d0bc2dd14cfa372c023b041a0bbf152ed
[ "BSD-2-Clause" ]
null
null
null
#include "MyViewer.h" #define _SILENCE_EXPERIMENTAL_FILESYSTEM_DEPRECATION_WARNING #include <filesystem> #include <nfd.h> #include "ObjToEigenConverter.h" #pragma warning( disable : 26812 ) // Enum type warning. namespace MyViewerOp { enum Op { Planarization, WireMeshDesign, ARAP2D, TestBoundingSphere, MinimalSurface, }; const std::vector<const char*> operationTypeNames = { "Planarization", "Wire Mesh Design", "ARAP Deformation", "Test Bounding Sphere", "Minimal Surface", }; } namespace MyViewerSh { enum Sh { Model, ModelFlat, ModelColor, ModelNormal, ModelNormalFlat, ModelWire, ModelWireFront, ModelHeatValue, }; const std::vector<const char*> shadingTypeNames = { "Full Light", "Flat", "Color", "Normal", "Normal Flat", "Wire", "Wire Front", "Heat Value (Error)", }; } namespace MyViewerDisObj { enum DisObj { ModelProcessed, ModelOrigin, ModelReference, }; const std::vector<const char*> displayingObjectNames = { "Processed", "Origin", "Reference", }; } const std::string MyViewer::noneString = "None"; const std::string MyViewer::sameAsInputString = "Same As Input"; MyViewer::MyViewer(const std::string& name) : Viewer(name) , mOriginModelText(noneString) , mReferenceModelText(sameAsInputString) , mModelOrigin(std::make_unique<ObjModel>()) , mModel(std::make_unique<ObjModel>()) , mModelReference(std::make_unique<ObjModel>()) , mGeometrySolverShPtr(std::make_shared<MyGeometrySolver3D>()) { } MyViewer::~MyViewer() { } void MyViewer::createGUIWindow() { ImGui::BeginMainMenuBar(); ImGui::Combo("Shading Type", &mShadingType, MyViewerSh::shadingTypeNames.data(), static_cast<int>(MyViewerSh::shadingTypeNames.size()), -1); ImGui::Text("| App Avg %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); ImGui::EndMainMenuBar(); ImGui::Begin("Editor"); //Viewer::createGUIWindow(); //ImGui::SliderFloat("Model Scale", &mModelScale, 0.01f, 100.0f); ImGui::InputFloat("Model Scale", &mModelScale, 0.01f, 0.2f, "%.3f"); //ImGui::SliderInt("Num Iteration", &mNumIter, 0, 20); ImGui::InputInt("Num Iteration", &mNumIter, 1, 10); mNumIter = glm::max(mNumIter, 0); ImGui::InputFloat("Max Error Visualization", &mMaxError, 1e-6f, 0.1f, "%.6f"); mMaxError = glm::max(mMaxError, 1e-6f); if (ImGui::RadioButton(MyViewerOp::operationTypeNames[MyViewerOp::Planarization], &mOperationType, MyViewerOp::Planarization)) { resetOperation(); } ImGui::SameLine(); if (ImGui::RadioButton(MyViewerOp::operationTypeNames[MyViewerOp::WireMeshDesign], &mOperationType, MyViewerOp::WireMeshDesign)) { resetOperation(); } ImGui::SameLine(); if (ImGui::RadioButton(MyViewerOp::operationTypeNames[MyViewerOp::ARAP2D], &mOperationType, MyViewerOp::ARAP2D)) { resetOperation(); } //ImGui::SameLine(); if (ImGui::RadioButton(MyViewerOp::operationTypeNames[MyViewerOp::TestBoundingSphere], &mOperationType, MyViewerOp::TestBoundingSphere)) { resetOperation(); } ImGui::SameLine(); if (ImGui::RadioButton(MyViewerOp::operationTypeNames[MyViewerOp::MinimalSurface], &mOperationType, MyViewerOp::MinimalSurface)) { resetOperation(); } if (ImGui::Button("Load Model")) { loadOBJFileToModel(); } ImGui::SameLine(); if (ImGui::Button("Load Reference")) { loadOBJFileToReference(); } ImGui::SameLine(); if (ImGui::Button("Reset Camera")) { resetCamera(); } ImGui::Text("Origin Model: %s", mOriginModelText.c_str()); ImGui::Text("Reference Model: %s", mReferenceModelText.c_str()); ImGui::RadioButton(MyViewerDisObj::displayingObjectNames[MyViewerDisObj::ModelProcessed], &mDisplayingObject, MyViewerDisObj::ModelProcessed); ImGui::SameLine(); ImGui::RadioButton(MyViewerDisObj::displayingObjectNames[MyViewerDisObj::ModelOrigin], &mDisplayingObject, MyViewerDisObj::ModelOrigin); ImGui::SameLine(); ImGui::RadioButton(MyViewerDisObj::displayingObjectNames[MyViewerDisObj::ModelReference], &mDisplayingObject, MyViewerDisObj::ModelReference); createOperationGUI(); if (ImGui::Button("Apply Processing")) { std::cout << "Apply processing " << mOperationType << "..." << std::endl; switch (mOperationType) { case MyViewerOp::Planarization: executePlanarization(); break; case MyViewerOp::WireMeshDesign: executeWireMeshDesign(); break; case MyViewerOp::ARAP2D: executeARAP2D(); break; case MyViewerOp::TestBoundingSphere: executeTestBoundingSphere(); break; case MyViewerOp::MinimalSurface: executeMinimalSurface(); break; default: std::cout << "Nothing happened. Not implemented?" << std::endl; break; } } ImGui::SameLine(); if (ImGui::Button("Reset Model")) { resetModelToOrigin(); } ImGui::End(); } void MyViewer::drawScene() { glEnable(GL_DEPTH_TEST); glm::mat4 model = glm::mat4(mModelScale); model[3][3] = 1.0f; glm::mat4 projView = mCamera.getProjView(); Shader* shaderUsing = nullptr; switch (mShadingType) { case MyViewerSh::Model: shaderUsing = mModelShader.get(); break; case MyViewerSh::ModelFlat: shaderUsing = mModelFlatShader.get(); break; case MyViewerSh::ModelColor: shaderUsing = mModelColorShader.get(); break; case MyViewerSh::ModelNormal: shaderUsing = mModelNormalShader.get(); break; case MyViewerSh::ModelNormalFlat: shaderUsing = mModelNormalFlatShader.get(); break; case MyViewerSh::ModelWire: shaderUsing = mModelWireShader.get(); break; case MyViewerSh::ModelWireFront: shaderUsing = mModelWireFrontShader.get(); break; case MyViewerSh::ModelHeatValue: shaderUsing = mModelHeatValueShader.get(); break; default: break; } drawGridGround(projView); if (shaderUsing) { shaderUsing->use(); shaderUsing->setMat4("uProjView", projView); shaderUsing->setVec3("uLightPos", glm::vec3(20, 0, 20)); shaderUsing->setMat4("uModel", model); shaderUsing->setMat3("uModelInvTr", glm::mat3(glm::transpose(glm::inverse(model)))); shaderUsing->setVec3("color", glm::vec3(0.8, 0.4, 0.2)); shaderUsing->setFloat("uMaxError", mMaxError); switch (mDisplayingObject) { case MyViewerDisObj::ModelProcessed: if (mModelLoaded) { mModel->drawObj(); } break; case MyViewerDisObj::ModelOrigin: if (mModelLoaded) { mModelOrigin->drawObj(); } break; case MyViewerDisObj::ModelReference: if (mReferenceLoaded) { mModelReference->drawObj(); } else if (mModelLoaded) { mModelOrigin->drawObj(); } break; default: break; } } } void MyViewer::mouseButtonCallback(GLFWwindow* window, int button, int action, int mods) { Viewer::mouseButtonCallback(window, button, action, mods); } void MyViewer::cursorPosCallback(GLFWwindow* window, double xpos, double ypos) { Viewer::cursorPosCallback(window, xpos, ypos); // Call parent method } void MyViewer::resetCamera() { mCamera = Camera(windowWidth, windowHeight, glm::vec3(0, 4, 8), glm::vec3(0, 0, 0), glm::vec3(0, 1, 0)); } void MyViewer::executePlanarization() { if (!mModelLoaded) { return; } mPlanarizationOperation->refMesh = mMeshConverterReference.getInitialEigenMesh(); mPlanarizationOperation->closeness_weight = mPlanarizationParameter.mCloseness; mPlanarizationOperation->planarity_weight = mPlanarizationParameter.mPlanarity; mPlanarizationOperation->laplacian_weight = mPlanarizationParameter.mLaplacian; mPlanarizationOperation->relative_laplacian_weight = mPlanarizationParameter.mRelativeLaplacian; auto& mesh = mMeshConverter.getOutputEigenMesh(); std::cout << "Apply processing " << "\"executePlanarization\"" << "..." << std::endl; if (!mPlanarizationOperation->initialize(mMeshConverter.getInitialEigenMesh(), {})) { std::cout << "Fail to initialize!" << std::endl; return; } if (!mPlanarizationOperation->solve(mesh.m_positions, 0) || !mMeshConverterOrigin.updateSourceMesh(mPlanarizationOperation->visualizeOutputErrors(mMeshConverterOrigin.getOutputEigenMesh().m_colors, mMaxError, true), true)) { std::cout << "Fail to get visualized error!" << std::endl; return; } if (!mPlanarizationOperation->solve(mesh.m_positions, mNumIter)) { std::cout << "Fail to solve!" << std::endl; return; } AAShapeUp::MeshDirtyFlag colorDirtyFlag = mPlanarizationOperation->visualizeOutputErrors(mesh.m_colors, mMaxError, true); AAShapeUp::MeshDirtyFlag normalDirtyFlag = AAShapeUp::regenerateNormals(mesh); if (!mMeshConverter.updateSourceMesh(mPlanarizationOperation->getMeshDirtyFlag() | colorDirtyFlag | normalDirtyFlag, true)) { std::cout << "Fail to update source mesh!" << std::endl; return; } } void MyViewer::executeWireMeshDesign() { std::cout << "Apply processing " << "(TODO)" << std::endl; } void MyViewer::executeARAP2D() { std::cout << "Apply processing " << "(TODO)" << std::endl; } void MyViewer::executeTestBoundingSphere() { if (!mModelLoaded) { return; } mTestBoudingSphereOperation->m_LaplacianWeight = mTestBoundingSphereParameter.mLaplacian; mTestBoudingSphereOperation->m_sphereProjectionWeight = mTestBoundingSphereParameter.mSphereProjection; auto& mesh = mMeshConverter.getOutputEigenMesh(); std::cout << "Apply processing " << "\"executeTestBoundingSphere\"" << "..." << std::endl; if (!mTestBoudingSphereOperation->initialize(mMeshConverter.getInitialEigenMesh(), {})) { std::cout << "Fail to initialize!" << std::endl; return; } if (!mTestBoudingSphereOperation->solve(mesh.m_positions, 0) || !mMeshConverterOrigin.updateSourceMesh(mTestBoudingSphereOperation->visualizeOutputErrors(mMeshConverterOrigin.getOutputEigenMesh().m_colors, mMaxError, true), true)) { std::cout << "Fail to get visualized error!" << std::endl; return; } if (!mTestBoudingSphereOperation->solve(mesh.m_positions, mNumIter)) { std::cout << "Fail to solve!" << std::endl; return; } AAShapeUp::MeshDirtyFlag colorDirtyFlag = mTestBoudingSphereOperation->visualizeOutputErrors(mesh.m_colors, mMaxError, true); AAShapeUp::MeshDirtyFlag normalDirtyFlag = AAShapeUp::regenerateNormals(mesh); if (!mMeshConverter.updateSourceMesh(mTestBoudingSphereOperation->getMeshDirtyFlag() | colorDirtyFlag | normalDirtyFlag, true)) { std::cout << "Fail to update source mesh!" << std::endl; return; } } void MyViewer::executeMinimalSurface() { if (!mModelLoaded) { return; } mMinimalSurfaceOperation->m_LaplacianWeight = mMinimalSurfaceParameter.mLaplacian; mMinimalSurfaceOperation->m_fixBoundaryWeight = mMinimalSurfaceParameter.mFixedBoundary; auto& mesh = mMeshConverter.getOutputEigenMesh(); std::cout << "Apply processing " << "\"executeMinimalSurface\"" << "..." << std::endl; if (!mMinimalSurfaceOperation->initialize(mMeshConverter.getInitialEigenMesh(), {})) { std::cout << "Fail to initialize!" << std::endl; return; } if (!mMinimalSurfaceOperation->solve(mesh.m_positions, 0) || !mMeshConverterOrigin.updateSourceMesh(mMinimalSurfaceOperation->visualizeOutputErrors(mMeshConverterOrigin.getOutputEigenMesh().m_colors, mMaxError, true), true)) { std::cout << "Fail to get visualized error!" << std::endl; return; } if (!mMinimalSurfaceOperation->solve(mesh.m_positions, mNumIter)) { std::cout << "Fail to solve!" << std::endl; return; } AAShapeUp::MeshDirtyFlag colorDirtyFlag = mMinimalSurfaceOperation->visualizeOutputErrors(mesh.m_colors, mMaxError, true); AAShapeUp::MeshDirtyFlag normalDirtyFlag = AAShapeUp::regenerateNormals(mesh); if (!mMeshConverter.updateSourceMesh(mMinimalSurfaceOperation->getMeshDirtyFlag() | colorDirtyFlag | normalDirtyFlag, true)) { std::cout << "Fail to update source mesh!" << std::endl; return; } } void MyViewer::createOperationGUI() { switch (mOperationType) { case MyViewerOp::Planarization: ImGui::InputFloat("Planarity Weight", &mPlanarizationParameter.mPlanarity, 0.1f, 10.0f); ImGui::InputFloat("Closeness Weight", &mPlanarizationParameter.mCloseness, 0.1f, 10.0f); ImGui::InputFloat("Fairness Weight", &mPlanarizationParameter.mLaplacian, 0.1f, 10.0f); ImGui::InputFloat("Relative Fairness Weight", &mPlanarizationParameter.mRelativeLaplacian, 0.1f, 10.0f); break; case MyViewerOp::WireMeshDesign: break; case MyViewerOp::ARAP2D: break; case MyViewerOp::TestBoundingSphere: ImGui::InputFloat("Sphere Projection Weight", &mTestBoundingSphereParameter.mSphereProjection, 0.1f, 10.0f); ImGui::InputFloat("Fairness Weight", &mTestBoundingSphereParameter.mLaplacian, 0.1f, 10.0f); break; case MyViewerOp::MinimalSurface: ImGui::InputFloat("Fixed Boundary Weight", &mMinimalSurfaceParameter.mFixedBoundary, 0.1f, 10.0f); ImGui::InputFloat("Fairness Weight", &mMinimalSurfaceParameter.mLaplacian, 0.1f, 10.0f); break; default: break; } } void MyViewer::loadOBJFileToModel() { std::string path = std::filesystem::current_path().parent_path().parent_path().string(); nfdchar_t* outPath = NULL; nfdresult_t result = NFD_OpenDialog("obj", path.c_str(), &outPath); if (result == NFD_OKAY && mModelOrigin->loadObj(std::string(outPath))) { mOriginModelText = outPath; mReferenceModelText = sameAsInputString; resetModelToOrigin(); updateReference(mModelOrigin.get()); mModelLoaded = true; mReferenceLoaded = false; resetOperation(); } } void MyViewer::loadOBJFileToReference() { std::string path = std::filesystem::current_path().parent_path().parent_path().string(); nfdchar_t* outPath = NULL; nfdresult_t result = NFD_OpenDialog("obj", path.c_str(), &outPath); if (result == NFD_OKAY && mModelReference->loadObj(std::string(outPath))) { mReferenceModelText = outPath; updateReference(mModelReference.get()); mReferenceLoaded = true; resetOperation(); } } void MyViewer::resetOperation() { switch (mOperationType) { case MyViewerOp::Planarization: mPlanarizationOperation.reset(new AAShapeUp::PlanarizationOperation(mGeometrySolverShPtr)); break; case MyViewerOp::WireMeshDesign: break; case MyViewerOp::ARAP2D: break; case MyViewerOp::TestBoundingSphere: mTestBoudingSphereOperation.reset(new AAShapeUp::TestBoundingSphereOperation(mGeometrySolverShPtr)); break; case MyViewerOp::MinimalSurface: mMinimalSurfaceOperation.reset(new AAShapeUp::MinimalSurfaceOperation(mGeometrySolverShPtr)); break; default: std::cout << "Nothing happened. Not implemented?" << std::endl; break; } } void MyViewer::resetModelToOrigin() { mModel->copyObj(*mModelOrigin); mMeshConverterOrigin.setObjModelPtr(mModelOrigin.get()); mMeshConverterOrigin.generateEigenMesh(); mMeshConverterOrigin.updateSourceMesh(AAShapeUp::regenerateNormals(mMeshConverterOrigin.getOutputEigenMesh()), true); mMeshConverter.setObjModelPtr(mModel.get()); mMeshConverter.generateEigenMesh(); mMeshConverter.updateSourceMesh(AAShapeUp::regenerateNormals(mMeshConverter.getOutputEigenMesh()), true); } void MyViewer::updateReference(ObjModel* objModelPtr) { mMeshConverterReference.setObjModelPtr(objModelPtr); mMeshConverterReference.generateEigenMesh(); mMeshConverterReference.updateSourceMesh(AAShapeUp::regenerateNormals(mMeshConverterReference.getOutputEigenMesh()), true); }
29.48728
168
0.74124
[ "mesh", "vector", "model" ]
a7b6d09672f6cd52f419726f7a80af85d56260dc
29,470
cpp
C++
src/qt/coincontrol.cpp
ghostlander/Phoenixcoin-v0.7
a2759e793bdac97ab866a30cd333739f8a1b7969
[ "MIT" ]
2
2021-05-16T07:37:40.000Z
2022-02-04T14:00:49.000Z
src/qt/coincontrol.cpp
ghostlander/Testcoin
9c7f8ad85077e7105336661e92bac1877a68ef7c
[ "MIT" ]
8
2019-02-28T01:41:01.000Z
2019-11-11T17:30:39.000Z
src/qt/coincontrol.cpp
ghostlander/Testcoin
9c7f8ad85077e7105336661e92bac1877a68ef7c
[ "MIT" ]
6
2019-02-18T19:09:23.000Z
2019-11-11T20:56:04.000Z
/* * Copyright (c) 2013 Cozz Lovan <cozzlovan@yahoo.com> * Copyright (c) 2014-2021 John Doering <ghostlander@phoenixcoin.org> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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 <QColor> #include <QCursor> #include <QDateTime> #include <QDialogButtonBox> #include <QFlags> #include <QString> #include <QTreeWidget> #include <QTreeWidgetItem> #include "base58.h" #include "coinunits.h" #include "guiutil.h" #include "optionsmodel.h" #include "addresstablemodel.h" #include "walletmodel.h" #include "coincontrol.h" #include "ui_coincontrol.h" using namespace std; QList<qint64> CoinControl::payAmounts; CCoinControl *CoinControl::control = new CCoinControl(); CoinControl::CoinControl(QWidget *parent) : QDialog(parent), ui(new Ui::CoinControl), model(0) { ui->setupUi(this); QAction *copyAddressAction = new QAction(tr("Copy address"), this); QAction *copyLabelAction = new QAction(tr("Copy label"), this); QAction *copyAmountAction = new QAction(tr("Copy amount"), this); copyTransactionHashAction = new QAction(tr("Copy payment ID"), this); contextMenu = new QMenu(); contextMenu->addAction(copyAddressAction); contextMenu->addAction(copyLabelAction); contextMenu->addAction(copyAmountAction); contextMenu->addAction(copyTransactionHashAction); connect(ui->treeWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showMenu(QPoint))); connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress())); connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel())); connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount())); connect(copyTransactionHashAction, SIGNAL(triggered()), this, SLOT(copyTransactionHash())); QAction *clipboardQuantityAction = new QAction(tr("Copy quantity"), this); QAction *clipboardAmountAction = new QAction(tr("Copy amount"), this); QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this); QAction *clipboardNetAmountAction = new QAction(tr("Copy net amount"), this); QAction *clipboardBytesAction = new QAction(tr("Copy bytes"), this); QAction *clipboardPriorityAction = new QAction(tr("Copy priority"), this); QAction *clipboardLowOutputAction = new QAction(tr("Copy low output"), this); QAction *clipboardChangeAction = new QAction(tr("Copy change"), this); connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(clipboardQuantity())); connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(clipboardAmount())); connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(clipboardFee())); connect(clipboardNetAmountAction, SIGNAL(triggered()), this, SLOT(clipboardNetAmount())); connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(clipboardBytes())); connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(clipboardPriority())); connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(clipboardLowOutput())); connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(clipboardChange())); ui->labelCoinControlQuantity->addAction(clipboardQuantityAction); ui->labelCoinControlAmount->addAction(clipboardAmountAction); ui->labelCoinControlFee->addAction(clipboardFeeAction); ui->labelCoinControlNetAmount->addAction(clipboardNetAmountAction); ui->labelCoinControlBytes->addAction(clipboardBytesAction); ui->labelCoinControlPriority->addAction(clipboardPriorityAction); ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction); ui->labelCoinControlChange->addAction(clipboardChangeAction); /* Toggle tree/list mode */ connect(ui->radioTreeMode, SIGNAL(toggled(bool)), this, SLOT(radioTreeMode(bool))); connect(ui->radioListMode, SIGNAL(toggled(bool)), this, SLOT(radioListMode(bool))); /* Click on checkbox */ connect(ui->treeWidget, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(viewItemChanged(QTreeWidgetItem *, int))); /* Click on header */ #if (QT_VERSION < 0x050000) ui->treeWidget->header()->setClickable(true); #else ui->treeWidget->header()->setSectionsClickable(true); #endif connect(ui->treeWidget->header(), SIGNAL(sectionClicked(int)), this, SLOT(headerSectionClicked(int))); /* OK button */ connect(ui->buttonBox, SIGNAL(clicked(QAbstractButton *)), this, SLOT(buttonBoxClicked(QAbstractButton *))); /* (un)select all */ connect(ui->pushButtonSelectAll, SIGNAL(clicked()), this, SLOT(buttonSelectAllClicked())); ui->treeWidget->setColumnWidth(COLUMN_CHECKBOX, 90); ui->treeWidget->setColumnWidth(COLUMN_AMOUNT, 120); ui->treeWidget->setColumnWidth(COLUMN_LABEL, 150); ui->treeWidget->setColumnWidth(COLUMN_ADDRESS, 290); ui->treeWidget->setColumnWidth(COLUMN_DATE, 110); ui->treeWidget->setColumnWidth(COLUMN_CONFIRMATIONS, 100); ui->treeWidget->setColumnWidth(COLUMN_PRIORITY, 90); /* Store transacton hash in this column, but don't show it */ ui->treeWidget->setColumnHidden(COLUMN_TXHASH, true); /* Store vout index in this column, but don't show it */ ui->treeWidget->setColumnHidden(COLUMN_VOUT_INDEX, true); /* Store amount in this column, but don't show it */ ui->treeWidget->setColumnHidden(COLUMN_AMOUNT_INT64, true); /* Store priority int64 in this column, but don't show it */ ui->treeWidget->setColumnHidden(COLUMN_PRIORITY_INT64, true); /* The default view order is descending by amount */ sortView(COLUMN_AMOUNT_INT64, Qt::DescendingOrder); } CoinControl::~CoinControl() { delete(ui); } void CoinControl::setModel(WalletModel *model) { this->model = model; if(model && model->getOptionsModel() && model->getAddressTableModel()) { updateView(); CoinControl::updateLabels(model, this); } } QString CoinControl::strPad(QString s, int nPadLength, QString sPadding) { while(s.length() < nPadLength) s = sPadding + s; return(s); } /* OK button */ void CoinControl::buttonBoxClicked(QAbstractButton *button) { if(ui->buttonBox->buttonRole(button) == QDialogButtonBox::AcceptRole) done(QDialog::Accepted); } /* (un)select all */ void CoinControl::buttonSelectAllClicked() { int i; Qt::CheckState state = Qt::Checked; for(i = 0; i < ui->treeWidget->topLevelItemCount(); i++) { if(ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) != Qt::Unchecked) { state = Qt::Unchecked; break; } } ui->treeWidget->setEnabled(false); for(i = 0; i < ui->treeWidget->topLevelItemCount(); i++) { if(ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) != state) ui->treeWidget->topLevelItem(i)->setCheckState(COLUMN_CHECKBOX, state); } ui->treeWidget->setEnabled(true); CoinControl::updateLabels(model, this); } /* Context menu */ void CoinControl::showMenu(const QPoint &point) { QTreeWidgetItem *item = ui->treeWidget->itemAt(point); if(item) { contextMenuItem = item; /* Disable some items like copy payment ID for tree roots in the context menu */ if(item->text(COLUMN_TXHASH).length() == 64) { /* Transaction hash is 64 characters what means it's a child node, * not a parent node in tree mode */ copyTransactionHashAction->setEnabled(true); } else { /* Click on parent node in tree mode -> disable all */ copyTransactionHashAction->setEnabled(false); } /* Show context menu */ contextMenu->exec(QCursor::pos()); } } /* Context menu action: copy amount */ void CoinControl::copyAmount() { GUIUtil::setClipboard(contextMenuItem->text(COLUMN_AMOUNT)); } /* Context menu action: copy label */ void CoinControl::copyLabel() { if(ui->radioTreeMode->isChecked() && !contextMenuItem->text(COLUMN_LABEL).length() && contextMenuItem->parent()) { GUIUtil::setClipboard(contextMenuItem->parent()->text(COLUMN_LABEL)); } else { GUIUtil::setClipboard(contextMenuItem->text(COLUMN_LABEL)); } } /* Context menu action: copy address */ void CoinControl::copyAddress() { if(ui->radioTreeMode->isChecked() && !contextMenuItem->text(COLUMN_ADDRESS).length() && contextMenuItem->parent()) { GUIUtil::setClipboard(contextMenuItem->parent()->text(COLUMN_ADDRESS)); } else { GUIUtil::setClipboard(contextMenuItem->text(COLUMN_ADDRESS)); } } /* Context menu action: copy payment ID */ void CoinControl::copyTransactionHash() { GUIUtil::setClipboard(contextMenuItem->text(COLUMN_TXHASH)); } /* Copy label "Quantity" to clipboard */ void CoinControl::clipboardQuantity() { GUIUtil::setClipboard(ui->labelCoinControlQuantity->text()); } /* Copy label "Amount" to clipboard */ void CoinControl::clipboardAmount() { GUIUtil::setClipboard(ui->labelCoinControlAmount->text() \ .left(ui->labelCoinControlAmount->text().indexOf(" "))); } /* Copy label "Fee" to clipboard */ void CoinControl::clipboardFee() { GUIUtil::setClipboard(ui->labelCoinControlFee->text() \ .left(ui->labelCoinControlFee->text().indexOf(" "))); } /* Copy label "Net amount" to clipboard */ void CoinControl::clipboardNetAmount() { GUIUtil::setClipboard(ui->labelCoinControlNetAmount->text() \ .left(ui->labelCoinControlNetAmount->text().indexOf(" "))); } /* Copy label "Bytes" to clipboard */ void CoinControl::clipboardBytes() { GUIUtil::setClipboard(ui->labelCoinControlBytes->text()); } /* Copy label "Priority" to clipboard */ void CoinControl::clipboardPriority() { GUIUtil::setClipboard(ui->labelCoinControlPriority->text()); } /* Copy label "Low output" to clipboard */ void CoinControl::clipboardLowOutput() { GUIUtil::setClipboard(ui->labelCoinControlLowOutput->text()); } /* Copy label "Change" to clipboard */ void CoinControl::clipboardChange() { GUIUtil::setClipboard(ui->labelCoinControlChange->text() \ .left(ui->labelCoinControlChange->text().indexOf(" "))); } /* Tree view: sort */ void CoinControl::sortView(int column, Qt::SortOrder order) { sortColumn = column; sortOrder = order; ui->treeWidget->sortItems(column, order); ui->treeWidget->header()->setSortIndicator( (sortColumn == COLUMN_AMOUNT_INT64 ? COLUMN_AMOUNT : (sortColumn == COLUMN_PRIORITY_INT64 ? COLUMN_PRIORITY : sortColumn)), sortOrder); } /* Tree view: header clicked */ void CoinControl::headerSectionClicked(int logicalIndex) { if(logicalIndex == COLUMN_CHECKBOX) { /* Click on the leftmost column, do nothing */ ui->treeWidget->header()->setSortIndicator( (sortColumn == COLUMN_AMOUNT_INT64 ? COLUMN_AMOUNT : (sortColumn == COLUMN_PRIORITY_INT64 ? COLUMN_PRIORITY : sortColumn)), sortOrder); } else { /* Sort by amount */ if(logicalIndex == COLUMN_AMOUNT) logicalIndex = COLUMN_AMOUNT_INT64; /* Sort by priority */ if(logicalIndex == COLUMN_PRIORITY) logicalIndex = COLUMN_PRIORITY_INT64; if(sortColumn == logicalIndex) { sortOrder = ((sortOrder == Qt::AscendingOrder) ? Qt::DescendingOrder : Qt::AscendingOrder); } else { sortColumn = logicalIndex; /* Descending order for amount, priority, date, confirmations, * ascending otherwise */ sortOrder = ((sortColumn == COLUMN_AMOUNT_INT64) || (sortColumn == COLUMN_PRIORITY_INT64) || (sortColumn == COLUMN_DATE) || (sortColumn == COLUMN_CONFIRMATIONS) ? Qt::DescendingOrder : Qt::AscendingOrder); } sortView(sortColumn, sortOrder); } } /* Toggle tree mode */ void CoinControl::radioTreeMode(bool checked) { if(checked && model) updateView(); } /* Toggle list mode */ void CoinControl::radioListMode(bool checked) { if(checked && model) updateView(); } /* Checkbox clicked */ void CoinControl::viewItemChanged(QTreeWidgetItem *item, int column) { if((column == COLUMN_CHECKBOX) && (item->text(COLUMN_TXHASH).length() == 64)) { /* Transaction hash is 64 characters what means it's a child node, * not a parent node in tree mode */ COutPoint outpt(uint256(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt()); if(item->checkState(COLUMN_CHECKBOX) == Qt::Unchecked) { control->UnSelect(outpt); } else if(item->isDisabled()) { /* Locked which happens if "check all" through parent node */ item->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); } else { control->Select(outpt); } /* Selection changed, update labels */ if(ui->treeWidget->isEnabled()) CoinControl::updateLabels(model, this); } } /* Returns a human readable label for a priority number */ QString CoinControl::getPriorityLabel(double dPriority) { CTransaction tx; if(tx.AllowFree(dPriority)) { if (tx.AllowFree(dPriority / 1000000)) return(tr("highest")); else if(tx.AllowFree(dPriority / 100000)) return(tr("higher")); else if(tx.AllowFree(dPriority / 10000)) return(tr("high")); else if(tx.AllowFree(dPriority / 1000)) return(tr("above medium")); else return(tr("medium")); } else { if (tx.AllowFree(dPriority * 10)) return(tr("below medium")); else if(tx.AllowFree(dPriority * 100)) return(tr("low")); else if(tx.AllowFree(dPriority * 1000)) return(tr("lower")); else return(tr("lowest")); } } void CoinControl::updateLabels(WalletModel *model, QDialog *dialog) { CTransaction tx; if(!model) return; /* Amount to pay */ qint64 nPayAmount = 0; bool fLowOutput = false, fDustOutput = false, fDustChange = false; foreach(const qint64 &amount, CoinControl::payAmounts) { nPayAmount += amount; if(amount > 0) { if(amount < MIN_TX_FEE) fLowOutput = true; if(amount < TX_DUST) fDustOutput = true; } } QString sPriorityLabel = ""; int64 nAmount = 0, nPayFee = 0, nNetAmount = 0, nChange = 0; uint nBytes = 0, nBytesInputs = 0, nQuantity = 0; int nQuantityUncompressed = 0; double dPriority = 0.0, dPriorityInputs = 0.0; vector<COutPoint> vCoinControl; vector<COutput> vOutputs; control->ListSelected(vCoinControl); model->getOutputs(vCoinControl, vOutputs); BOOST_FOREACH(const COutput &out, vOutputs) { /* Unselect outputs spent already */ if(out.tx->IsSpent(out.i)) { uint256 txhash = out.tx->GetHash(); COutPoint outpt(txhash, out.i); control->UnSelect(outpt); continue; } /* Quantity */ nQuantity++; /* Amount */ nAmount += out.tx->vout[out.i].nValue; /* Priority */ dPriorityInputs += (double)out.tx->vout[out.i].nValue * (out.nDepth + 1); /* Size */ CTxDestination address; if(ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) { CPubKey pubkey; CKeyID *keyid = boost::get<CKeyID>(&address); if(keyid && model->getPubKey(*keyid, pubkey)) { nBytesInputs += (pubkey.IsCompressed() ? 148 : 180); if(!pubkey.IsCompressed()) nQuantityUncompressed++; } else nBytesInputs += 148; } else nBytesInputs += 148; } /* Calculation */ if(nQuantity > 0) { /* Size; always assume +1 output for the change */ nBytes = nBytesInputs + ((CoinControl::payAmounts.size() > 0 ? CoinControl::payAmounts.size() + 1 : 2) * 34) + 10; /* Priority; 29 = 180 - 151 (uncompressed public keys are over the limit) */ dPriority = dPriorityInputs / (nBytes - nBytesInputs + (nQuantityUncompressed * 29)); sPriorityLabel = CoinControl::getPriorityLabel(dPriority); /* Optional fee */ int64 nFee = nTransactionFee * (1 + (int64)nBytes / 1000); /* Mandatory fee */ int64 nMinFee = tx.GetMinFee(nBytes, tx.AllowFree(dPriority), GMF_SEND); nPayFee = max(nFee, nMinFee); if(nPayAmount > 0) { if(nPayAmount > nAmount) nPayAmount = nAmount; nChange = nAmount - nPayFee - nPayAmount; /* To avoid dust outputs, any change < TX_DUST is moved to the fees */ if(nChange && (nChange < TX_DUST)) { nPayFee += nChange; nChange = 0; fDustChange = true; } if(!nChange) nBytes -= 34; } nNetAmount = nAmount - nPayFee; } /* Update labels */ int nDisplayUnit = CoinUnits::PXC; if(model->getOptionsModel()) nDisplayUnit = model->getOptionsModel()->getDisplayUnit(); QLabel *l1 = dialog->findChild<QLabel *>("labelCoinControlQuantity"); QLabel *l2 = dialog->findChild<QLabel *>("labelCoinControlAmount"); QLabel *l3 = dialog->findChild<QLabel *>("labelCoinControlFee"); QLabel *l4 = dialog->findChild<QLabel *>("labelCoinControlNetAmount"); QLabel *l5 = dialog->findChild<QLabel *>("labelCoinControlBytes"); QLabel *l6 = dialog->findChild<QLabel *>("labelCoinControlPriority"); QLabel *l7 = dialog->findChild<QLabel *>("labelCoinControlLowOutput"); QLabel *l8 = dialog->findChild<QLabel *>("labelCoinControlChange"); /* Enable or disable "low output" and "change" */ dialog->findChild<QLabel *>("labelCoinControlLowOutputText")->setEnabled(nPayAmount > 0); dialog->findChild<QLabel *>("labelCoinControlLowOutput")->setEnabled(nPayAmount > 0); dialog->findChild<QLabel *>("labelCoinControlChangeText")->setEnabled(nPayAmount > 0); dialog->findChild<QLabel *>("labelCoinControlChange")->setEnabled(nPayAmount > 0); /* Display the statistics */ l1->setText(QString::number(nQuantity)); /* Quantity */ l2->setText(CoinUnits::formatWithUnit(nDisplayUnit, nAmount)); /* Amount */ l3->setText(CoinUnits::formatWithUnit(nDisplayUnit, nPayFee)); /* Fee */ l4->setText(CoinUnits::formatWithUnit(nDisplayUnit, nNetAmount)); /* Net amount */ l5->setText(((nBytes > 0) ? "~" : "") + QString::number(nBytes)); /* Size */ l6->setText(sPriorityLabel); /* Priority */ l7->setText((fLowOutput ? (fDustOutput ? tr("dust!") : tr("yes")) : tr("no"))); /* Low output / Dust */ l8->setText(CoinUnits::formatWithUnit(nDisplayUnit, nChange)); /* Change */ /* Colour some labels red */ l5->setStyleSheet((nBytes >= 2000) ? "color:red;" : ""); /* Oversized payment */ l6->setStyleSheet((!tx.AllowFree(dPriority)) ? "color:red;" : ""); /* Low priority */ l7->setStyleSheet((fLowOutput) ? "color:red;" : ""); /* Low output */ l8->setStyleSheet((fDustChange) ? "color:red;" : ""); /* Dust change */ /* Set up the tool tips */ l5->setToolTip(tr("Payments over 2000 bytes in size are considered large and require a fee.\n" "\n This label turns red if a fee of at least %1 per 1000 bytes is required.") \ .arg(CoinUnits::formatWithUnit(nDisplayUnit, MIN_TX_FEE))); l6->setToolTip(tr("Blocks are filled with payments according to their priority.\n" "\n This label turns red if the payment's priority is below \"medium\".\n" "\n It means a fee of at least %1 per 1000 bytes is required.") \ .arg(CoinUnits::formatWithUnit(nDisplayUnit, MIN_TX_FEE))); l7->setToolTip(tr("Low value outputs may be unspendable later due to high fees.\n" "\n This label turns red if any output is less than %1 in value.\n" "\n Amounts below %2 are displayed as dust.") \ .arg(CoinUnits::formatWithUnit(nDisplayUnit, MIN_TX_FEE)) \ .arg(CoinUnits::formatWithUnit(nDisplayUnit, TX_DUST))); l8->setToolTip(tr("Very low value outputs are considered useless due to high fees.\n" "\n This label turns red if the change is less than %1 in value.\n" "\n It will be moved to the fees.\n") \ .arg(CoinUnits::formatWithUnit(nDisplayUnit, TX_DUST))); dialog->findChild<QLabel *>("labelCoinControlBytesText")->setToolTip(l5->toolTip()); dialog->findChild<QLabel *>("labelCoinControlPriorityText")->setToolTip(l6->toolTip()); dialog->findChild<QLabel *>("labelCoinControlLowOutputText")->setToolTip(l7->toolTip()); dialog->findChild<QLabel *>("labelCoinControlChangeText")->setToolTip(l8->toolTip()); /* Insufficient funds */ QLabel *label = dialog->findChild<QLabel *>("labelCoinControlInsuffFunds"); if(label) label->setVisible(nChange < 0); } void CoinControl::updateView() { bool treeMode = ui->radioTreeMode->isChecked(); int i; ui->treeWidget->clear(); /* Performance, otherwise updateLabels would be called for every checked checkbox */ ui->treeWidget->setEnabled(false); ui->treeWidget->setAlternatingRowColors(!treeMode); QFlags<Qt::ItemFlag> flgCheckbox = (Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable); QFlags<Qt::ItemFlag> flgTristate = (Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsTristate); int nDisplayUnit = CoinUnits::PXC; if(model && model->getOptionsModel()) nDisplayUnit = model->getOptionsModel()->getDisplayUnit(); map<QString, vector<COutput> > mapCoins; model->listCoins(mapCoins); BOOST_FOREACH(PAIRTYPE(QString, vector<COutput>) coins, mapCoins) { QTreeWidgetItem *itemWalletAddress = new QTreeWidgetItem(); QString sWalletAddress = coins.first; QString sWalletLabel = ""; if(model->getAddressTableModel()) sWalletLabel = model->getAddressTableModel()->labelForAddress(sWalletAddress); if(!sWalletLabel.length()) sWalletLabel = tr("(no label)"); if(treeMode) { ui->treeWidget->addTopLevelItem(itemWalletAddress); itemWalletAddress->setFlags(flgTristate); itemWalletAddress->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); for(i = 0; i < ui->treeWidget->columnCount(); i++) itemWalletAddress->setBackground(i, QColor(248, 247, 246)); itemWalletAddress->setText(COLUMN_LABEL, sWalletLabel); itemWalletAddress->setText(COLUMN_ADDRESS, sWalletAddress); } int64 nSum = 0; double dPrioritySum = 0; int nChildren = 0; int nInputSum = 0; BOOST_FOREACH(const COutput &out, coins.second) { /* 148 bytes if compressed public key, * 180 bytes if uncompressed */ int nInputSize = 148; nSum += out.tx->vout[out.i].nValue; nChildren++; QTreeWidgetItem *itemOutput; if(treeMode) { itemOutput = new QTreeWidgetItem(itemWalletAddress); } else { itemOutput = new QTreeWidgetItem(ui->treeWidget); } itemOutput->setFlags(flgCheckbox); itemOutput->setCheckState(COLUMN_CHECKBOX,Qt::Unchecked); CTxDestination outputAddress; QString sAddress = ""; if(ExtractDestination(out.tx->vout[out.i].scriptPubKey, outputAddress)) { sAddress = CCoinAddress(outputAddress).ToString().c_str(); /* If list mode or change, then show address. * In tree mode, address is not shown again for direct wallet address outputs */ if(!treeMode || (!(sAddress == sWalletAddress))) itemOutput->setText(COLUMN_ADDRESS, sAddress); CPubKey pubkey; CKeyID *keyid = boost::get<CKeyID>(&outputAddress); if(keyid && model->getPubKey(*keyid, pubkey) && !pubkey.IsCompressed()) nInputSize = 180; } if(!(sAddress == sWalletAddress)) { /* Tool tip from where the change comes from */ itemOutput->setToolTip(COLUMN_LABEL, tr("change from %1 (%2)") \ .arg(sWalletLabel).arg(sWalletAddress)); itemOutput->setText(COLUMN_LABEL, tr("(change)")); } else if(!treeMode) { QString sLabel = ""; if(model->getAddressTableModel()) sLabel = model->getAddressTableModel()->labelForAddress(sAddress); if(!sLabel.length()) sLabel = tr("(no label)"); itemOutput->setText(COLUMN_LABEL, sLabel); } itemOutput->setText(COLUMN_AMOUNT, CoinUnits::format(nDisplayUnit, out.tx->vout[out.i].nValue)); itemOutput->setText(COLUMN_AMOUNT_INT64, strPad(QString::number(out.tx->vout[out.i].nValue), 15, " ")); itemOutput->setText(COLUMN_DATE, QDateTime::fromTime_t(out.tx->GetTxTime()).toString("yy-MM-dd hh:mm")); itemOutput->setText(COLUMN_CONFIRMATIONS, strPad(QString::number(out.nDepth), 8, " ")); /* 78 = 2 * 34 + 10 */ double dPriority = ((double)out.tx->vout[out.i].nValue / (nInputSize + 78)) * (out.nDepth + 1); itemOutput->setText(COLUMN_PRIORITY, CoinControl::getPriorityLabel(dPriority)); itemOutput->setText(COLUMN_PRIORITY_INT64, strPad(QString::number((int64)dPriority), 20, " ")); dPrioritySum += (double)out.tx->vout[out.i].nValue * (out.nDepth + 1); nInputSum += nInputSize; uint256 txhash = out.tx->GetHash(); itemOutput->setText(COLUMN_TXHASH, txhash.GetHex().c_str()); itemOutput->setText(COLUMN_VOUT_INDEX, QString::number(out.i)); /* Set check box */ if(control->IsSelected(txhash, out.i)) itemOutput->setCheckState(COLUMN_CHECKBOX,Qt::Checked); } if(treeMode) { dPrioritySum = dPrioritySum / (nInputSum + 78); itemWalletAddress->setText(COLUMN_CHECKBOX, "(" + QString::number(nChildren) + ")"); itemWalletAddress->setText(COLUMN_AMOUNT, CoinUnits::format(nDisplayUnit, nSum)); itemWalletAddress->setText(COLUMN_AMOUNT_INT64, strPad(QString::number(nSum), 15, " ")); itemWalletAddress->setText(COLUMN_PRIORITY, CoinControl::getPriorityLabel(dPrioritySum)); itemWalletAddress->setText(COLUMN_PRIORITY_INT64, strPad(QString::number((int64)dPrioritySum), 20, " ")); } } if(treeMode) { /* Expand all partially selected */ for(i = 0; i < ui->treeWidget->topLevelItemCount(); i++) { if(ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked) ui->treeWidget->topLevelItem(i)->setExpanded(true); } } sortView(sortColumn, sortOrder); ui->treeWidget->setEnabled(true); } CoinControlTreeWidget::CoinControlTreeWidget(QWidget *parent) : QTreeWidget(parent) { } void CoinControlTreeWidget::keyPressEvent(QKeyEvent *event) { if(event->key() == Qt::Key_Space) { /* Press space bar -> select checkbox */ event->ignore(); /* Avoids a crash if no item selected */ if(!this->currentItem()) return; int COLUMN_CHECKBOX = 0; this->currentItem()->setCheckState(COLUMN_CHECKBOX, ((this->currentItem()->checkState(COLUMN_CHECKBOX) == Qt::Checked) ? Qt::Unchecked : Qt::Checked)); } else if(event->key() == Qt::Key_Escape) { /* Press escape -> close dialogue */ event->ignore(); ((CoinControl *) this->parentWidget())->done(QDialog::Accepted); } else { this->QTreeWidget::keyPressEvent(event); } }
39.293333
100
0.643875
[ "vector", "model" ]
a7bc2d6bd38eb69979377fe68e6de34f7938ea57
11,663
hpp
C++
ClockReceiver/JustInTime.hpp
laurentd75/CLK
55dbeefeb2539541409265391ba9f7d70d89449e
[ "MIT" ]
null
null
null
ClockReceiver/JustInTime.hpp
laurentd75/CLK
55dbeefeb2539541409265391ba9f7d70d89449e
[ "MIT" ]
null
null
null
ClockReceiver/JustInTime.hpp
laurentd75/CLK
55dbeefeb2539541409265391ba9f7d70d89449e
[ "MIT" ]
null
null
null
// // JustInTime.hpp // Clock Signal // // Created by Thomas Harte on 28/07/2019. // Copyright © 2019 Thomas Harte. All rights reserved. // #ifndef JustInTime_h #define JustInTime_h #include "ClockReceiver.hpp" #include "../Concurrency/AsyncTaskQueue.hpp" #include "ClockingHintSource.hpp" #include "ForceInline.hpp" /*! A JustInTimeActor holds (i) an embedded object with a run_for method; and (ii) an amount of time since run_for was last called. Time can be added using the += operator. The -> operator can be used to access the embedded object. All time accumulated will be pushed to object before the pointer is returned. Machines that accumulate HalfCycle time but supply to a Cycle-counted device may supply a separate @c TargetTimeScale at template declaration. If the held object implements get_next_sequence_point() then it'll be used to flush implicitly as and when sequence points are hit. Callers can use will_flush() to predict these. If the held object is a subclass of ClockingHint::Source, this template will register as an observer and potentially stop clocking or stop delaying clocking until just-in-time references as directed. TODO: incorporate and codify AsyncJustInTimeActor. */ template <class T, class LocalTimeScale = HalfCycles, int multiplier = 1, int divider = 1> class JustInTimeActor: public ClockingHint::Observer { private: /*! A std::unique_ptr deleter which causes an update_sequence_point to occur on the actor supplied to it at construction if it implements get_next_sequence_point(). Otherwise destruction is a no-op. **Does not delete the object.** This is used by the -> operators below, which provide a unique pointer to the enclosed object and update their sequence points upon its destruction — i.e. after the caller has made whatever call or calls as were relevant to the enclosed object. */ class SequencePointAwareDeleter { public: explicit SequencePointAwareDeleter(JustInTimeActor<T, LocalTimeScale, multiplier, divider> *actor) noexcept : actor_(actor) {} forceinline void operator ()(const T *const) const { if constexpr (has_sequence_points<T>::value) { actor_->update_sequence_point(); } } private: JustInTimeActor<T, LocalTimeScale, multiplier, divider> *const actor_; }; // This block of SFINAE determines whether objects of type T accepts Cycles or HalfCycles. using HalfRunFor = void (T::*const)(HalfCycles); static uint8_t half_sig(...); static uint16_t half_sig(HalfRunFor); using TargetTimeScale = std::conditional_t< sizeof(half_sig(&T::run_for)) == sizeof(uint16_t), HalfCycles, Cycles>; public: /// Constructs a new JustInTimeActor using the same construction arguments as the included object. template<typename... Args> JustInTimeActor(Args&&... args) : object_(std::forward<Args>(args)...) { if constexpr (std::is_base_of<ClockingHint::Source, T>::value) { object_.set_clocking_hint_observer(this); } } /// Adds time to the actor. /// /// @returns @c true if adding time caused a flush; @c false otherwise. forceinline bool operator += (LocalTimeScale rhs) { if constexpr (std::is_base_of<ClockingHint::Source, T>::value) { if(clocking_preference_ == ClockingHint::Preference::None) { return false; } } if constexpr (multiplier != 1) { time_since_update_ += rhs * multiplier; } else { time_since_update_ += rhs; } is_flushed_ = false; if constexpr (std::is_base_of<ClockingHint::Source, T>::value) { if (clocking_preference_ == ClockingHint::Preference::RealTime) { flush(); return true; } } if constexpr (has_sequence_points<T>::value) { time_until_event_ -= rhs * multiplier; if(time_until_event_ <= LocalTimeScale(0)) { time_overrun_ = time_until_event_ / divider; flush(); update_sequence_point(); return true; } } return false; } /// Flushes all accumulated time and returns a pointer to the included object. /// /// If this object provides sequence points, checks for changes to the next /// sequence point upon deletion of the pointer. [[nodiscard]] forceinline auto operator->() { flush(); return std::unique_ptr<T, SequencePointAwareDeleter>(&object_, SequencePointAwareDeleter(this)); } /// Acts exactly as per the standard ->, but preserves constness. /// /// Despite being const, this will flush the object and, if relevant, update the next sequence point. [[nodiscard]] forceinline auto operator -> () const { auto non_const_this = const_cast<JustInTimeActor<T, LocalTimeScale, multiplier, divider> *>(this); non_const_this->flush(); return std::unique_ptr<const T, SequencePointAwareDeleter>(&object_, SequencePointAwareDeleter(non_const_this)); } /// @returns a pointer to the included object, without flushing time. [[nodiscard]] forceinline T *last_valid() { return &object_; } /// @returns a const pointer to the included object, without flushing time. [[nodiscard]] forceinline const T *last_valid() const { return &object_; } /// @returns the amount of time since the object was last flushed, in the target time scale. [[nodiscard]] forceinline TargetTimeScale time_since_flush() const { if constexpr (divider == 1) { return time_since_update_; } return TargetTimeScale(time_since_update_.as_integral() / divider); } /// @returns the amount of time since the object was last flushed, plus the local time scale @c offset, /// converted to the target time scale. [[nodiscard]] forceinline TargetTimeScale time_since_flush(LocalTimeScale offset) const { if constexpr (divider == 1) { return time_since_update_ + offset; } return TargetTimeScale((time_since_update_ + offset).as_integral() / divider); } /// Flushes all accumulated time. /// /// This does not affect this actor's record of when the next sequence point will occur. forceinline void flush() { if(!is_flushed_) { did_flush_ = is_flushed_ = true; if constexpr (divider == 1) { const auto duration = time_since_update_.template flush<TargetTimeScale>(); object_.run_for(duration); } else { const auto duration = time_since_update_.template divide<TargetTimeScale>(LocalTimeScale(divider)); if(duration > TargetTimeScale(0)) object_.run_for(duration); } } } /// Indicates whether a flush has occurred since the last call to did_flush(). [[nodiscard]] forceinline bool did_flush() { const bool did_flush = did_flush_; did_flush_ = false; return did_flush; } /// @returns a number in the range [-max, 0] indicating the offset of the most recent sequence /// point from the final time at the end of the += that triggered the sequence point. [[nodiscard]] forceinline LocalTimeScale last_sequence_point_overrun() { return time_overrun_; } /// @returns the number of cycles until the next sequence-point-based flush, if the embedded object /// supports sequence points; @c LocalTimeScale() otherwise. [[nodiscard]] LocalTimeScale cycles_until_implicit_flush() const { return time_until_event_ / divider; } /// Indicates whether a sequence-point-caused flush will occur if the specified period is added. [[nodiscard]] forceinline bool will_flush(LocalTimeScale rhs) const { if constexpr (!has_sequence_points<T>::value) { return false; } return rhs >= time_until_event_; } /// Indicates the amount of time, in the local time scale, until the first local slot that falls wholly /// after @c duration, if that delay were to occur in @c offset units of time from now. [[nodiscard]] forceinline LocalTimeScale back_map(TargetTimeScale duration, TargetTimeScale offset) const { // A 1:1 mapping is easy. if constexpr (multiplier == 1 && divider == 1) { return duration; } // Work out when this query is placed, and the time to which it relates const auto base = time_since_update_ + offset * divider; const auto target = base + duration * divider; // Figure out the number of whole input steps that is required to get // past target, and subtract the number of whole input steps necessary // to get to base. const auto steps_to_base = base.as_integral() / multiplier; const auto steps_to_target = (target.as_integral() + divider - 1) / multiplier; return LocalTimeScale(steps_to_target - steps_to_base); } /// Updates this template's record of the next sequence point. void update_sequence_point() { if constexpr (has_sequence_points<T>::value) { // Keep a fast path where no conversions will be applied; if conversions are // going to be applied then do a direct max -> max translation rather than // allowing the arithmetic to overflow. if constexpr (divider == 1 && std::is_same_v<LocalTimeScale, TargetTimeScale>) { time_until_event_ = object_.get_next_sequence_point(); } else { const auto time = object_.get_next_sequence_point(); if(time == TargetTimeScale::max()) { time_until_event_ = LocalTimeScale::max(); } else { time_until_event_ = time * divider; } } assert(time_until_event_ > LocalTimeScale(0)); } } /// @returns A cached copy of the object's clocking preference. ClockingHint::Preference clocking_preference() const { return clocking_preference_; } private: T object_; LocalTimeScale time_since_update_, time_until_event_, time_overrun_; bool is_flushed_ = true; bool did_flush_ = false; template <typename S, typename = void> struct has_sequence_points : std::false_type {}; template <typename S> struct has_sequence_points<S, decltype(void(std::declval<S &>().get_next_sequence_point()))> : std::true_type {}; ClockingHint::Preference clocking_preference_ = ClockingHint::Preference::JustInTime; void set_component_prefers_clocking(ClockingHint::Source *, ClockingHint::Preference clocking) { clocking_preference_ = clocking; } }; /*! An AsyncJustInTimeActor acts like a JustInTimeActor but additionally contains an AsyncTaskQueue. Any time the amount of accumulated time crosses a threshold provided at construction time, the object will be updated on the AsyncTaskQueue. */ template <class T, class LocalTimeScale = HalfCycles, class TargetTimeScale = LocalTimeScale> class AsyncJustInTimeActor { public: /// Constructs a new AsyncJustInTimeActor using the same construction arguments as the included object. template<typename... Args> AsyncJustInTimeActor(TargetTimeScale threshold, Args&&... args) : object_(std::forward<Args>(args)...), threshold_(threshold) {} /// Adds time to the actor. inline void operator += (const LocalTimeScale &rhs) { time_since_update_ += rhs; if(time_since_update_ >= threshold_) { time_since_update_ -= threshold_; task_queue_.enqueue([this] () { object_.run_for(threshold_); }); } is_flushed_ = false; } /// Flushes all accumulated time and returns a pointer to the included object. inline T *operator->() { flush(); return &object_; } /// Returns a pointer to the included object without flushing time. inline T *last_valid() { return &object_; } /// Flushes all accumulated time. inline void flush() { if(!is_flushed_) { task_queue_.flush(); object_.run_for(time_since_update_.template flush<TargetTimeScale>()); is_flushed_ = true; } } private: T object_; LocalTimeScale time_since_update_; TargetTimeScale threshold_; bool is_flushed_ = true; Concurrency::AsyncTaskQueue task_queue_; }; #endif /* JustInTime_h */
36.220497
137
0.719626
[ "object" ]
a7bdb5ff48d47e2ccab586cf78838045f2c4be44
70,768
cpp
C++
examples/le_net/le_net.cpp
ALojdl/HastenedARMDeepLearning
68279af342fc742ed72f3e05d22e332eae6e60c9
[ "MIT" ]
null
null
null
examples/le_net/le_net.cpp
ALojdl/HastenedARMDeepLearning
68279af342fc742ed72f3e05d22e332eae6e60c9
[ "MIT" ]
null
null
null
examples/le_net/le_net.cpp
ALojdl/HastenedARMDeepLearning
68279af342fc742ed72f3e05d22e332eae6e60c9
[ "MIT" ]
1
2019-02-18T13:16:37.000Z
2019-02-18T13:16:37.000Z
#include "common.h" #include "image.h" #include <CL/cl.h> #include <iostream> #include <chrono> #include <cstring> using namespace std; using namespace chrono; /* Memory objects needed: Layer1 Layer 2 Layer 3 Layer 4 Layer 5 Layer 6 Layer 7 Infere______________________________________________________________________________________________________________ - image 32x32 - y 6@14x14 - syn 16@5x5 - y 16@5x5 - syn 400x120 - syn 120x84 - syn 84x10 - syn 6@5x5 - a 6@14x14 - y 16@10x10 - a 16@5x5 - y 120 - y 84 - y 10 - y 6@28x28 - a 16@10x10 - a 120 - a 84 - a 10 - a 6@28x28 Train________________________________________________________________________________________________________________ - e 6@28x28 - e 6@14x14 - e 16@10x10 - e 16@5x5 - e 120 - e 84 - output 10 - g 6@5x5 - g 16@10x10 - g 120 - g 84 - e 10 - d 6@5x5 - d 16@10x10 - d 120 - d 84 - g 10 - dsyn 6@5x5 - dsyn 16@5x5 - dsyn 400x120 - dsyn 120x84 - d 10 - dsyn 84x10 Operations needed: Infere: - L1_y = convolution6(image, L1_syn) <-- Convolution with 6 different filters - L1_a = sigmoid(L1_y) <-- 1/1+exp(-L1_y) - L2_a, L2_y = maxpool(L1_a) <-- Pools max value from 4 pixels and remember which pixel from four inputs is max - L3_y = convolution16(L2_a, L3_syn) <-- Convolution with 16 different filters that are strangly connected - L3_a = sigmoid(L3_y) - L4_a, L4_y = maxpool(L3_a) - L5_y = multiply(L4_a, L5_syn) - L5_a = sigmoid(L5_y) - L6_y = multiply(L5_a, L6_syn) - L6_a = sigmoid(L6_y) - L7_y = multiply(L6_a, L7_syn) - L7_a = sigmoid(L7_y) Train: - L7_e = subtract(output, L7_a) <-- Subtract elements of first matrix from second - L7_g = sigmoid_gradient(L7_a) <-- Find sigmoid gradient for every element - L7_d = pointwise_multiply(L7_g, L7_e) <-- Multiply all coresponding elements - L7_dsyn = transpose_multiply(L6_a, L7_d) <-- Transpose first matrix and multiply it with second - L6_e = multiply_transpose(L7_d, L7_syn) <-- Transpose second matrix and multiply first with second - L6_g = sigmoid_gradient(L6_a) - L6_d = pointwise_multiply(L6_g, L6_e) - L6_dsyn = transpose_multiply(L5_a, L6_d) - L5_e = multiply_transpose(L6_d, L6_syn) - L5_g = sigmoid_gradient(L5_a) - L5_d = pointwise_multiply(L5_g, L5_e) - L5_dsyn = transpose_multiply(L4_a, L5_d) - L4_e = multiply_transpose(L5_d, L5_syn) - L3_e = maxpool_error(L4_e, L4_y) - L3_g = sigmoid_gradient(L3_a) - L3_d = pointwise_multiply(L3_e, L3_g) - L3_dsyn = back_convolution16(L2_a, L3_d) - L2_e = deconvolution(L3_d, L3_syn) - L1_e = maxpool_error(L2_e, L2_y) - L1_g = sigmoid_gradient(L1_a) - L1_d = pointwise_multiply(L1_e, L1_g) - L1_dsyn = back_convolution6(L1_d, image) */ #define TEST_IND 17 #define NUMBER_OF_OPERATIONS 15 #define SIZE 10 int main(void) { cl_context context = 0; cl_command_queue commandQueue = 0; cl_program program = 0; cl_device_id device = 0; cl_kernel kernels[NUMBER_OF_OPERATIONS] = {0}; cl_event event = 0; int numberOfMemoryObjects = 45; cl_mem memoryObjects[45] = {0}; cl_int errorNumber; string kernel_names[] = {"convolution", "sigmoid", "maxpool", "convolution16", "matrix_multiply", "matrix_subtract", "sigmoid_derivative", "matrix_point_multiply", "matrix_transpose_multiply", "matrix_multiply_transpose", "maxpool_error", "back_convolution16", "deconvolution16", "back_convolution", "matrix_add"}; size_t firstRows, firstCols, secondRows, secondCols, numFilters, filterSize; size_t globalWorksize2[2]; size_t globalWorksize3[3]; const size_t localWorksize2[2] = {1, 1}; const size_t localWorksize3[3] = {1, 1, 1}; bool setKernelArgumentsSuccess = true; /* Prepare context, command queue, program and kernels NOTE: We wont use most of clean functions, as the code will be just huge. */ if (!createContext(&context)) { cleanUpOpenCL(context, commandQueue, program, kernels[0], memoryObjects, numberOfMemoryObjects); cerr << "Failed to create an OpenCL context. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!createCommandQueue(context, &commandQueue, &device)) { cleanUpOpenCL(context, commandQueue, program, kernels[0], memoryObjects, numberOfMemoryObjects); cerr << "Failed to create the OpenCL command queue. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!createProgram(context, device, "assets/kernels.cl", &program)) { cleanUpOpenCL(context, commandQueue, program, kernels[0], memoryObjects, numberOfMemoryObjects); cerr << "Failed to create OpenCL program." << __FILE__ << ":"<< __LINE__ << endl; return 1; } for (int i = 0; i < NUMBER_OF_OPERATIONS; i++) { kernels[i] = clCreateKernel(program, kernel_names[i].c_str(), &errorNumber); if (!checkSuccess(errorNumber)) { cleanUpOpenCL(context, commandQueue, program, kernels[0], memoryObjects, numberOfMemoryObjects); cerr << "Failed to create OpenCL kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } } /* Ask the OpenCL implementation to allocate buffers for the data */ bool createMemoryObjectsSuccess = true; size_t buffSizes[] = {1024, 150, 4704, 4704, 1176, 1176, 400, 1600, 1600, 400, 400, 48000, 120, 120, 10080, 84, 84, 840, 10, 10, 10, 10, 10, 10, 840, 84, 84, 84, 1080, 120, 120, 120, 48000, 400, 1600, 1600, 1600, 400, 1176, 4704, 4704, 4704, 150}; for (int i = 0; i < numberOfMemoryObjects; i++) { memoryObjects[i] = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_ALLOC_HOST_PTR, buffSizes[i] * sizeof(float), NULL, &errorNumber); createMemoryObjectsSuccess &= checkSuccess(errorNumber); } if (!createMemoryObjectsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[0], memoryObjects, numberOfMemoryObjects); cerr << "Failed to create OpenCL buffer. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* Map the memory buffers created by the OpenCL implementation to pointers so we can access them on the CPU */ bool mapMemoryObjectsSuccess = true; cl_float* image = (cl_float*)clEnqueueMapBuffer(commandQueue, memoryObjects[0], CL_TRUE, CL_MAP_WRITE, 0, buffSizes[0], 0, NULL, NULL, &errorNumber); mapMemoryObjectsSuccess &= checkSuccess(errorNumber); cl_float* L1_syn = (cl_float*)clEnqueueMapBuffer(commandQueue, memoryObjects[1], CL_TRUE, CL_MAP_WRITE, 0, buffSizes[1], 0, NULL, NULL, &errorNumber); mapMemoryObjectsSuccess &= checkSuccess(errorNumber); cl_float* L3_syn = (cl_float*)clEnqueueMapBuffer(commandQueue, memoryObjects[6], CL_TRUE, CL_MAP_WRITE, 0, buffSizes[6], 0, NULL, NULL, &errorNumber); mapMemoryObjectsSuccess &= checkSuccess(errorNumber); cl_float* L5_syn = (cl_float*)clEnqueueMapBuffer(commandQueue, memoryObjects[11], CL_TRUE, CL_MAP_WRITE, 0, buffSizes[11], 0, NULL, NULL, &errorNumber); mapMemoryObjectsSuccess &= checkSuccess(errorNumber); cl_float* L6_syn = (cl_float*)clEnqueueMapBuffer(commandQueue, memoryObjects[14], CL_TRUE, CL_MAP_WRITE, 0, buffSizes[14], 0, NULL, NULL, &errorNumber); mapMemoryObjectsSuccess &= checkSuccess(errorNumber); cl_float* L7_syn = (cl_float*)clEnqueueMapBuffer(commandQueue, memoryObjects[17], CL_TRUE, CL_MAP_WRITE, 0, buffSizes[17], 0, NULL, NULL, &errorNumber); mapMemoryObjectsSuccess &= checkSuccess(errorNumber); cl_float* output = (cl_float*)clEnqueueMapBuffer(commandQueue, memoryObjects[20], CL_TRUE, CL_MAP_WRITE, 0, buffSizes[20], 0, NULL, NULL, &errorNumber); mapMemoryObjectsSuccess &= checkSuccess(errorNumber); if (mapMemoryObjectsSuccess == false) cout << "ERROR!" << endl; /* Initialize the data */ for (unsigned int i=0; i<buffSizes[0]; i++) image[i] = 1; for (unsigned int i=0; i<buffSizes[1]; i++) L1_syn[i] = 0.01; for (unsigned int i=0; i<buffSizes[6]; i++) L3_syn[i] = 0.01; for (unsigned int i=0; i<buffSizes[11]; i++) L5_syn[i] = 0.01; for (unsigned int i=0; i<buffSizes[14]; i++) L6_syn[i] = 0.01; for (unsigned int i=0; i<buffSizes[17]; i++) L7_syn[i] = 0.01; for (unsigned int i=0; i<buffSizes[20]; i++) output[i] = 3; /* Unmap buffers, so GPU can use them */ if (!checkSuccess(clEnqueueUnmapMemObject(commandQueue, memoryObjects[0], image, 0, NULL, NULL))) { cleanUpOpenCL(context, commandQueue, program, kernels[0], memoryObjects, numberOfMemoryObjects); cerr << "Unmapping memory objects failed " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueUnmapMemObject(commandQueue, memoryObjects[1], L1_syn, 0, NULL, NULL))) { cleanUpOpenCL(context, commandQueue, program, kernels[0], memoryObjects, numberOfMemoryObjects); cerr << "Unmapping memory objects failed " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueUnmapMemObject(commandQueue, memoryObjects[6], L3_syn, 0, NULL, NULL))) { cleanUpOpenCL(context, commandQueue, program, kernels[0], memoryObjects, numberOfMemoryObjects); cerr << "Unmapping memory objects failed " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueUnmapMemObject(commandQueue, memoryObjects[11], L5_syn, 0, NULL, NULL))) { cleanUpOpenCL(context, commandQueue, program, kernels[0], memoryObjects, numberOfMemoryObjects); cerr << "Unmapping memory objects failed " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueUnmapMemObject(commandQueue, memoryObjects[14], L6_syn, 0, NULL, NULL))) { cleanUpOpenCL(context, commandQueue, program, kernels[0], memoryObjects, numberOfMemoryObjects); cerr << "Unmapping memory objects failed " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueUnmapMemObject(commandQueue, memoryObjects[17], L7_syn, 0, NULL, NULL))) { cleanUpOpenCL(context, commandQueue, program, kernels[0], memoryObjects, numberOfMemoryObjects); cerr << "Unmapping memory objects failed " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueUnmapMemObject(commandQueue, memoryObjects[20], output, 0, NULL, NULL))) { cleanUpOpenCL(context, commandQueue, program, kernels[0], memoryObjects, numberOfMemoryObjects); cerr << "Unmapping memory objects failed " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L1_y = convolution6(image, L1_syn) <-- Convolution with 6 different filters */ firstRows = 32; firstCols = 32; secondRows = 28; secondCols = 28; numFilters = 6; filterSize = 5; globalWorksize3[0] = numFilters; globalWorksize3[1] = secondRows; globalWorksize3[2] = secondCols; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[0], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[0], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[0], 2, sizeof(int), (void*)&secondRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[0], 3, sizeof(int), (void*)&secondCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[0], 4, sizeof(int), (void*)&numFilters)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[0], 5, sizeof(int), (void*)&filterSize)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[0], 6, sizeof(cl_mem), (void*)&memoryObjects[0])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[0], 7, sizeof(cl_mem), (void*)&memoryObjects[1])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[0], 8, sizeof(cl_mem), (void*)&memoryObjects[2])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[0], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[0], 3, NULL, globalWorksize3, localWorksize3, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[0], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L1_a = sigmoid(L1_y) <-- 1/1+exp(-L1_y) */ firstRows = 28; firstCols = 168; globalWorksize2[0] = firstRows; globalWorksize2[1] = firstCols; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[1], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[1], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[1], 2, sizeof(cl_mem), (void*)&memoryObjects[2])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[1], 3, sizeof(cl_mem), (void*)&memoryObjects[3])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[1], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[1], 2, NULL, globalWorksize2, localWorksize2, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[1], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L2_a, L2_y = maxpool(L1_a) <-- Pools max value from 4 pixels and remember which pixel from four inputs is max */ firstRows = 14; firstCols = 84; globalWorksize2[0] = firstRows; globalWorksize2[1] = firstCols; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[2], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[2], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[2], 2, sizeof(cl_mem), (void*)&memoryObjects[3])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[2], 3, sizeof(cl_mem), (void*)&memoryObjects[4])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[2], 4, sizeof(cl_mem), (void*)&memoryObjects[5])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[2], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[2], 2, NULL, globalWorksize2, localWorksize2, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[2], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L3_y = convolution16(L2_a, L3_syn) */ firstRows = 14; firstCols = 14; secondRows = 10; secondCols = 10; numFilters = 16; filterSize = 5; globalWorksize3[0] = numFilters; globalWorksize3[1] = secondRows; globalWorksize3[2] = secondCols; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[3], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[3], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[3], 2, sizeof(int), (void*)&secondRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[3], 3, sizeof(int), (void*)&secondCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[3], 4, sizeof(int), (void*)&filterSize)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[3], 5, sizeof(cl_mem), (void*)&memoryObjects[5])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[3], 6, sizeof(cl_mem), (void*)&memoryObjects[6])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[3], 7, sizeof(cl_mem), (void*)&memoryObjects[7])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[0], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[3], 3, NULL, globalWorksize3, localWorksize3, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[0], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L3_a = sigmoid(L3_y) */ firstRows = 10; firstCols = 160; globalWorksize2[0] = firstRows; globalWorksize2[1] = firstCols; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[1], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[1], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[1], 2, sizeof(cl_mem), (void*)&memoryObjects[7])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[1], 3, sizeof(cl_mem), (void*)&memoryObjects[8])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[1], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[1], 2, NULL, globalWorksize2, localWorksize2, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[1], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L4_a, L4_y = maxpool(L1_a) */ firstRows = 5; firstCols = 80; globalWorksize2[0] = firstRows; globalWorksize2[1] = firstCols; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[2], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[2], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[2], 2, sizeof(cl_mem), (void*)&memoryObjects[8])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[2], 3, sizeof(cl_mem), (void*)&memoryObjects[9])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[2], 4, sizeof(cl_mem), (void*)&memoryObjects[10])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[2], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[2], 2, NULL, globalWorksize2, localWorksize2, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[2], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L5_y = multiply(L4_a, L5_syn) */ firstRows = 1; firstCols = 400; secondCols = 120; globalWorksize2[0] = firstRows; globalWorksize2[1] = secondCols; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[4], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[4], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[4], 2, sizeof(int), (void*)&secondCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[4], 3, sizeof(cl_mem), (void*)&memoryObjects[10])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[4], 4, sizeof(cl_mem), (void*)&memoryObjects[11])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[4], 5, sizeof(cl_mem), (void*)&memoryObjects[12])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[4], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[4], 2, NULL, globalWorksize2, localWorksize2, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[4], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L5_a = sigmoid(L5_y) */ firstRows = 1; firstCols = 120; globalWorksize2[0] = firstRows; globalWorksize2[1] = firstCols; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[1], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[1], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[1], 2, sizeof(cl_mem), (void*)&memoryObjects[12])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[1], 3, sizeof(cl_mem), (void*)&memoryObjects[13])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[1], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[1], 2, NULL, globalWorksize2, localWorksize2, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[1], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L6_y = multiply(L5_a, L6_syn) */ firstRows = 1; firstCols = 120; secondCols = 84; globalWorksize2[0] = firstRows; globalWorksize2[1] = secondCols; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[4], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[4], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[4], 2, sizeof(int), (void*)&secondCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[4], 3, sizeof(cl_mem), (void*)&memoryObjects[13])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[4], 4, sizeof(cl_mem), (void*)&memoryObjects[14])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[4], 5, sizeof(cl_mem), (void*)&memoryObjects[15])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[4], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[4], 2, NULL, globalWorksize2, localWorksize2, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[4], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L6_a = sigmoid(L6_y) */ firstRows = 1; firstCols = 84; globalWorksize2[0] = firstRows; globalWorksize2[1] = firstCols; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[1], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[1], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[1], 2, sizeof(cl_mem), (void*)&memoryObjects[15])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[1], 3, sizeof(cl_mem), (void*)&memoryObjects[16])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[1], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[1], 2, NULL, globalWorksize2, localWorksize2, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[1], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L7_y = multiply(L6_a, L7_syn) */ firstRows = 1; firstCols = 84; secondCols = 10; globalWorksize2[0] = firstRows; globalWorksize2[1] = secondCols; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[4], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[4], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[4], 2, sizeof(int), (void*)&secondCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[4], 3, sizeof(cl_mem), (void*)&memoryObjects[16])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[4], 4, sizeof(cl_mem), (void*)&memoryObjects[17])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[4], 5, sizeof(cl_mem), (void*)&memoryObjects[18])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[4], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[4], 2, NULL, globalWorksize2, localWorksize2, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[4], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L7_a = sigmoid(L7_y) */ firstRows = 1; firstCols = 10; globalWorksize2[0] = firstRows; globalWorksize2[1] = firstCols; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[1], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[1], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[1], 2, sizeof(cl_mem), (void*)&memoryObjects[18])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[1], 3, sizeof(cl_mem), (void*)&memoryObjects[19])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[1], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[1], 2, NULL, globalWorksize2, localWorksize2, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[1], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L7_e = subtract(output, L7_a) */ firstRows = 1; firstCols = 10; globalWorksize2[0] = firstRows; globalWorksize2[1] = firstCols; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[5], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[5], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[5], 2, sizeof(cl_mem), (void*)&memoryObjects[20])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[5], 3, sizeof(cl_mem), (void*)&memoryObjects[19])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[5], 4, sizeof(cl_mem), (void*)&memoryObjects[21])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[5], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[5], 2, NULL, globalWorksize2, localWorksize2, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[5], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L7_g = sigmoid_derivative(L7_a) */ firstRows = 1; firstCols = 10; globalWorksize2[0] = firstRows; globalWorksize2[1] = firstCols; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[6], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[6], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[6], 2, sizeof(cl_mem), (void*)&memoryObjects[19])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[6], 3, sizeof(cl_mem), (void*)&memoryObjects[22])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[6], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[6], 2, NULL, globalWorksize2, localWorksize2, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[6], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L7_d = pointwise(L7_e, L7_g) */ firstRows = 1; firstCols = 10; globalWorksize2[0] = firstRows; globalWorksize2[1] = firstCols; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[7], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[7], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[7], 2, sizeof(cl_mem), (void*)&memoryObjects[21])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[7], 3, sizeof(cl_mem), (void*)&memoryObjects[22])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[7], 4, sizeof(cl_mem), (void*)&memoryObjects[23])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[7], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[7], 2, NULL, globalWorksize2, localWorksize2, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[7], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L7_dsyn = transpose_multiply(L6_a, L7_syn) */ firstRows = 1; firstCols = 84; secondCols = 10; globalWorksize2[0] = firstCols; globalWorksize2[1] = secondCols; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[8], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[8], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[8], 2, sizeof(int), (void*)&secondCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[8], 3, sizeof(cl_mem), (void*)&memoryObjects[19])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[8], 4, sizeof(cl_mem), (void*)&memoryObjects[23])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[8], 5, sizeof(cl_mem), (void*)&memoryObjects[24])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[8], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[8], 2, NULL, globalWorksize2, localWorksize2, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[8], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L6_e = multiply_transpose(L7_d, L7_syn) */ firstRows = 1; firstCols = 10; secondRows = 84; globalWorksize2[0] = firstRows; globalWorksize2[1] = secondRows; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[9], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[9], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[9], 2, sizeof(int), (void*)&secondRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[9], 3, sizeof(cl_mem), (void*)&memoryObjects[23])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[9], 4, sizeof(cl_mem), (void*)&memoryObjects[17])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[9], 5, sizeof(cl_mem), (void*)&memoryObjects[25])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[9], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[9], 2, NULL, globalWorksize2, localWorksize2, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[9], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L6_g = sigmoid_derivative(L6_a) */ firstRows = 1; firstCols = 84; globalWorksize2[0] = firstRows; globalWorksize2[1] = firstCols; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[6], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[6], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[6], 2, sizeof(cl_mem), (void*)&memoryObjects[16])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[6], 3, sizeof(cl_mem), (void*)&memoryObjects[26])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[6], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[6], 2, NULL, globalWorksize2, localWorksize2, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[6], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L6_d = pointwise(L6_e, L6_g) */ firstRows = 1; firstCols = 84; globalWorksize2[0] = firstRows; globalWorksize2[1] = firstCols; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[7], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[7], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[7], 2, sizeof(cl_mem), (void*)&memoryObjects[25])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[7], 3, sizeof(cl_mem), (void*)&memoryObjects[26])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[7], 4, sizeof(cl_mem), (void*)&memoryObjects[27])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[7], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[7], 2, NULL, globalWorksize2, localWorksize2, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[7], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L6_dsyn = transpose_multiply(L5_a, L6_syn) */ firstRows = 1; firstCols = 120; secondCols = 84; globalWorksize2[0] = firstCols; globalWorksize2[1] = secondCols; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[8], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[8], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[8], 2, sizeof(int), (void*)&secondCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[8], 3, sizeof(cl_mem), (void*)&memoryObjects[13])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[8], 4, sizeof(cl_mem), (void*)&memoryObjects[27])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[8], 5, sizeof(cl_mem), (void*)&memoryObjects[28])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[8], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[8], 2, NULL, globalWorksize2, localWorksize2, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[8], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L5_e = multiply_transpose(L6_d, L6_syn) */ firstRows = 1; firstCols = 84; secondRows = 120; globalWorksize2[0] = firstRows; globalWorksize2[1] = secondRows; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[9], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[9], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[9], 2, sizeof(int), (void*)&secondRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[9], 3, sizeof(cl_mem), (void*)&memoryObjects[27])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[9], 4, sizeof(cl_mem), (void*)&memoryObjects[14])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[9], 5, sizeof(cl_mem), (void*)&memoryObjects[29])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[9], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[9], 2, NULL, globalWorksize2, localWorksize2, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[9], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L5_g = sigmoid_derivative(L5_a) */ firstRows = 1; firstCols = 120; globalWorksize2[0] = firstRows; globalWorksize2[1] = firstCols; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[6], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[6], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[6], 2, sizeof(cl_mem), (void*)&memoryObjects[13])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[6], 3, sizeof(cl_mem), (void*)&memoryObjects[30])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[6], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[6], 2, NULL, globalWorksize2, localWorksize2, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[6], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L5_d = pointwise(L5_e, L5_g) */ firstRows = 1; firstCols = 120; globalWorksize2[0] = firstRows; globalWorksize2[1] = firstCols; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[7], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[7], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[7], 2, sizeof(cl_mem), (void*)&memoryObjects[29])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[7], 3, sizeof(cl_mem), (void*)&memoryObjects[30])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[7], 4, sizeof(cl_mem), (void*)&memoryObjects[31])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[7], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[7], 2, NULL, globalWorksize2, localWorksize2, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[7], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L5_dsyn = transpose_multiply(L4_a, L5_syn) */ firstRows = 1; firstCols = 400; secondCols = 120; globalWorksize2[0] = firstCols; globalWorksize2[1] = secondCols; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[8], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[8], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[8], 2, sizeof(int), (void*)&secondCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[8], 3, sizeof(cl_mem), (void*)&memoryObjects[10])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[8], 4, sizeof(cl_mem), (void*)&memoryObjects[31])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[8], 5, sizeof(cl_mem), (void*)&memoryObjects[32])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[8], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[8], 2, NULL, globalWorksize2, localWorksize2, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[8], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L4_e = multiply_transpose(L5_d, L5_syn) */ firstRows = 1; firstCols = 120; secondRows = 400; globalWorksize2[0] = firstRows; globalWorksize2[1] = secondRows; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[9], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[9], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[9], 2, sizeof(int), (void*)&secondRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[9], 3, sizeof(cl_mem), (void*)&memoryObjects[31])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[9], 4, sizeof(cl_mem), (void*)&memoryObjects[11])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[9], 5, sizeof(cl_mem), (void*)&memoryObjects[33])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[9], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[9], 2, NULL, globalWorksize2, localWorksize2, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[9], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L3_e = maxpool_error(L4_e, L4_y) */ firstRows = 5; firstCols = 80; globalWorksize2[0] = firstRows; globalWorksize2[1] = firstCols; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[10], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[10], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[10], 2, sizeof(cl_mem), (void*)&memoryObjects[33])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[10], 3, sizeof(cl_mem), (void*)&memoryObjects[9])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[10], 4, sizeof(cl_mem), (void*)&memoryObjects[34])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[10], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[10], 2, NULL, globalWorksize2, localWorksize2, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[10], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L3_g = sigmoid_derivative(L3_a) */ firstRows = 10; firstCols = 160; globalWorksize2[0] = firstRows; globalWorksize2[1] = firstCols; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[6], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[6], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[6], 2, sizeof(cl_mem), (void*)&memoryObjects[8])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[6], 3, sizeof(cl_mem), (void*)&memoryObjects[35])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[6], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[6], 2, NULL, globalWorksize2, localWorksize2, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[6], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L3_d = pointwise(L3_e, L3_g) */ firstRows = 10; firstCols = 160; globalWorksize2[0] = firstRows; globalWorksize2[1] = firstCols; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[7], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[7], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[7], 2, sizeof(cl_mem), (void*)&memoryObjects[34])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[7], 3, sizeof(cl_mem), (void*)&memoryObjects[35])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[7], 4, sizeof(cl_mem), (void*)&memoryObjects[36])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[7], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[7], 2, NULL, globalWorksize2, localWorksize2, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[7], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L3_dsyn = deconvolution16(L2_a, L3_d) */ firstRows = 14; firstCols = 14; secondRows = 10; secondCols = 10; numFilters = 16; filterSize = 5; globalWorksize3[0] = numFilters; globalWorksize3[1] = filterSize; globalWorksize3[2] = filterSize; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[11], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[11], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[11], 2, sizeof(int), (void*)&secondRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[11], 3, sizeof(int), (void*)&secondCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[11], 4, sizeof(int), (void*)&filterSize)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[11], 5, sizeof(cl_mem), (void*)&memoryObjects[5])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[11], 6, sizeof(cl_mem), (void*)&memoryObjects[36])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[11], 7, sizeof(cl_mem), (void*)&memoryObjects[37])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[11], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[11], 3, NULL, globalWorksize3, localWorksize3, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[11], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L2_e = deconvolution16(L3_d, L3_syn) */ firstRows = 10; firstCols = 1600; secondRows = 14; secondCols = 84; numFilters = 16; globalWorksize3[0] = 16; globalWorksize3[1] = 10; globalWorksize3[2] = 10; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[12], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[12], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[12], 2, sizeof(int), (void*)&secondRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[12], 3, sizeof(int), (void*)&secondRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[12], 4, sizeof(int), (void*)&filterSize)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[12], 5, sizeof(cl_mem), (void*)&memoryObjects[36])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[12], 6, sizeof(cl_mem), (void*)&memoryObjects[6])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[12], 7, sizeof(cl_mem), (void*)&memoryObjects[38])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[12], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[12], 3, NULL, globalWorksize3, localWorksize3, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[12], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L1_e = maxpool_error(L2_e, L2_y) */ firstRows = 14; firstCols = 84; globalWorksize2[0] = firstRows; globalWorksize2[1] = firstCols; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[10], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[10], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[10], 2, sizeof(cl_mem), (void*)&memoryObjects[38])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[10], 3, sizeof(cl_mem), (void*)&memoryObjects[4])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[10], 4, sizeof(cl_mem), (void*)&memoryObjects[39])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[10], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[10], 2, NULL, globalWorksize2, localWorksize2, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[10], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L1_g = sigmoid_derivative(L1_a) */ firstRows = 28; firstCols = 168; globalWorksize2[0] = firstRows; globalWorksize2[1] = firstCols; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[6], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[6], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[6], 2, sizeof(cl_mem), (void*)&memoryObjects[5])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[6], 3, sizeof(cl_mem), (void*)&memoryObjects[40])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[6], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[6], 2, NULL, globalWorksize2, localWorksize2, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[6], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L1_d = pointwise(L1_e, L1_g) */ firstRows = 28; firstCols = 168; globalWorksize2[0] = firstRows; globalWorksize2[1] = firstCols; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[7], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[7], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[7], 2, sizeof(cl_mem), (void*)&memoryObjects[39])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[7], 3, sizeof(cl_mem), (void*)&memoryObjects[40])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[7], 4, sizeof(cl_mem), (void*)&memoryObjects[41])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[7], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[7], 2, NULL, globalWorksize2, localWorksize2, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[7], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L1_dsyn = back_convolution(image, L1_d) */ firstRows = 32; firstCols = 32; secondRows = 28; secondCols = 28; numFilters = 6; filterSize = 5; globalWorksize3[0] = numFilters; globalWorksize3[1] = filterSize; globalWorksize3[2] = filterSize; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[13], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[13], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[13], 2, sizeof(int), (void*)&secondRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[13], 3, sizeof(int), (void*)&secondCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[13], 4, sizeof(int), (void*)&numFilters)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[13], 5, sizeof(int), (void*)&filterSize)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[13], 6, sizeof(cl_mem), (void*)&memoryObjects[0])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[13], 7, sizeof(cl_mem), (void*)&memoryObjects[41])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[13], 8, sizeof(cl_mem), (void*)&memoryObjects[42])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[13], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[13], 3, NULL, globalWorksize3, localWorksize3, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[13], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L1_syn = matrix_add(L1_syn, L1_dsyn) */ firstRows = 5; firstCols = 30; globalWorksize2[0] = firstRows; globalWorksize2[1] = firstCols; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[14], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[14], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[14], 2, sizeof(cl_mem), (void*)&memoryObjects[1])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[14], 3, sizeof(cl_mem), (void*)&memoryObjects[42])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[14], 4, sizeof(cl_mem), (void*)&memoryObjects[1])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[14], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[14], 2, NULL, globalWorksize2, localWorksize2, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[14], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L3_syn = matrix_add(L3_syn, L3_dsyn) */ firstRows = 5; firstCols = 80; globalWorksize2[0] = firstRows; globalWorksize2[1] = firstCols; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[14], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[14], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[14], 2, sizeof(cl_mem), (void*)&memoryObjects[6])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[14], 3, sizeof(cl_mem), (void*)&memoryObjects[37])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[14], 4, sizeof(cl_mem), (void*)&memoryObjects[6])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[14], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[14], 2, NULL, globalWorksize2, localWorksize2, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[14], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L5_syn = matrix_add(L5_syn, L5_dsyn) */ firstRows = 400; firstCols = 120; globalWorksize2[0] = firstRows; globalWorksize2[1] = firstCols; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[14], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[14], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[14], 2, sizeof(cl_mem), (void*)&memoryObjects[11])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[14], 3, sizeof(cl_mem), (void*)&memoryObjects[32])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[14], 4, sizeof(cl_mem), (void*)&memoryObjects[11])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[14], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[14], 2, NULL, globalWorksize2, localWorksize2, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[14], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L6_syn = matrix_add(L6_syn, L6_dsyn) */ firstRows = 120; firstCols = 84; globalWorksize2[0] = firstRows; globalWorksize2[1] = firstCols; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[14], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[14], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[14], 2, sizeof(cl_mem), (void*)&memoryObjects[14])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[14], 3, sizeof(cl_mem), (void*)&memoryObjects[28])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[14], 4, sizeof(cl_mem), (void*)&memoryObjects[14])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[14], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[14], 2, NULL, globalWorksize2, localWorksize2, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[14], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* L7_syn = matrix_add(L7_syn, L7_dsyn) */ firstRows = 84; firstCols = 10; globalWorksize2[0] = firstRows; globalWorksize2[1] = firstCols; setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[14], 0, sizeof(int), (void*)&firstRows)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[14], 1, sizeof(int), (void*)&firstCols)); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[14], 2, sizeof(cl_mem), (void*)&memoryObjects[17])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[14], 3, sizeof(cl_mem), (void*)&memoryObjects[24])); setKernelArgumentsSuccess &= checkSuccess(clSetKernelArg(kernels[14], 4, sizeof(cl_mem), (void*)&memoryObjects[17])); if (!setKernelArgumentsSuccess) { cleanUpOpenCL(context, commandQueue, program, kernels[14], memoryObjects, numberOfMemoryObjects); cerr << "Failed setting OpenCL kernel arguments. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } if (!checkSuccess(clEnqueueNDRangeKernel(commandQueue, kernels[14], 2, NULL, globalWorksize2, localWorksize2, 0, NULL, &event))) { cleanUpOpenCL(context, commandQueue, program, kernels[14], memoryObjects, numberOfMemoryObjects); cerr << "Failed enqueuing the kernel. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* Wait for command queue to finish, wait for event and release it */ if (!checkSuccess(clFinish(commandQueue))) { cleanUpOpenCL(context, commandQueue, program, kernels[0], memoryObjects, numberOfMemoryObjects); cerr << "Failed waiting for kernel execution to finish. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } clWaitForEvents(1, &event); if (!checkSuccess(clReleaseEvent(event))) { cleanUpOpenCL(context, commandQueue, program, kernels[0], memoryObjects, numberOfMemoryObjects); cerr << "Failed releasing the event object. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } /* Map buffer to read results */ cl_float* res = (cl_float*)clEnqueueMapBuffer(commandQueue, memoryObjects[TEST_IND], CL_TRUE, CL_MAP_READ, 0, buffSizes[TEST_IND], 0, NULL, NULL, &errorNumber); if (!checkSuccess(errorNumber)) { cleanUpOpenCL(context, commandQueue, program, kernels[0], memoryObjects, numberOfMemoryObjects); cerr << "Failed to map buffer. " << __FILE__ << ":"<< __LINE__ << endl; return 1; } cout << endl << "res: "; for (unsigned int i = 0; i < buffSizes[TEST_IND]; i++) { if (i%SIZE == 0) cout << endl << i/SIZE << ".\t"; cout << res[i] << "\t"; } cout << endl; /* Unmap memory objects */ if (!checkSuccess(clEnqueueUnmapMemObject(commandQueue, memoryObjects[TEST_IND], res, 0, NULL, NULL))) { cleanUpOpenCL(context, commandQueue, program, kernels[0], memoryObjects, numberOfMemoryObjects); cerr << "Unmapping memory objects failed " << __FILE__ << ":"<< __LINE__ << endl; return 1; } cleanUpOpenCL(context, commandQueue, program, kernels[0], memoryObjects, numberOfMemoryObjects); }
49.766526
144
0.664933
[ "object" ]
a7ce0ad321401b514e6ab5f9b72bca56e0bca6c6
76,892
cpp
C++
Chain/libraries/client/WalletApi.cpp
Achaindev/Achain_ubuntu
8c6daad526c84fa513f119206e45f62eb68b8a86
[ "MIT" ]
27
2017-11-03T08:41:18.000Z
2018-06-07T03:15:31.000Z
Chain/libraries/client/WalletApi.cpp
Achaindev/Achain_ubuntu
8c6daad526c84fa513f119206e45f62eb68b8a86
[ "MIT" ]
7
2017-11-02T10:45:48.000Z
2018-06-02T11:00:51.000Z
Chain/libraries/client/WalletApi.cpp
Achaindev/Achain_ubuntu
8c6daad526c84fa513f119206e45f62eb68b8a86
[ "MIT" ]
25
2017-11-02T03:12:27.000Z
2021-11-06T02:43:32.000Z
#include <client/Client.hpp> #include <client/ClientImpl.hpp> #include <utilities/KeyConversion.hpp> #include <utilities/Words.hpp> #include <utilities/CommonApi.hpp> #include <wallet/Config.hpp> #include <wallet/Exceptions.hpp> #include <fc/crypto/aes.hpp> #include <fc/network/http/connection.hpp> #include <fc/network/resolve.hpp> #include <fc/network/url.hpp> #include <fc/reflect/variant.hpp> #include <fc/thread/non_preemptable_scope_check.hpp> #include "cli/locale.hpp" namespace thinkyoung { namespace client { namespace detail { int8_t detail::ClientImpl::wallet_account_set_approval(const string& account_name, int8_t approval) { try { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); _wallet->set_account_approval(account_name, approval); return _wallet->get_account_approval(account_name); } FC_RETHROW_EXCEPTIONS(warn, "", ("account_name", account_name)("approval", approval)) } std::vector<thinkyoung::blockchain::AccountEntry> ClientImpl::wallet_get_all_approved_accounts(int8_t approval) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); try { return _wallet->get_all_approved_accounts(approval); } FC_RETHROW_EXCEPTIONS(warn, "account db read fail!") } void detail::ClientImpl::wallet_open(const string& wallet_name) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); _wallet->open(fc::trim(wallet_name)); reschedule_delegate_loop(); } fc::optional<variant> detail::ClientImpl::wallet_get_setting(const string& name) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); return _wallet->get_setting(name); } void detail::ClientImpl::wallet_set_setting(const string& name, const variant& value) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); _wallet->set_setting(name, value); } void detail::ClientImpl::wallet_create(const string& wallet_name, const string& password, const string& brain_key) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); string trimmed_name = fc::trim(wallet_name); if (brain_key.size() && brain_key.size() < ALP_WALLET_MIN_BRAINKEY_LENGTH) FC_CAPTURE_AND_THROW(brain_key_too_short); if (password.size() < ALP_WALLET_MIN_PASSWORD_LENGTH) FC_CAPTURE_AND_THROW(password_too_short); if (trimmed_name.size() == 0) FC_CAPTURE_AND_THROW(fc::invalid_arg_exception, (trimmed_name)); _wallet->create(trimmed_name, password, brain_key); reschedule_delegate_loop(); } fc::optional<string> detail::ClientImpl::wallet_get_name() const { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); return _wallet->is_open() ? _wallet->get_wallet_name() : fc::optional<string>(); } void detail::ClientImpl::wallet_close() { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); if (_wallet) { _wallet->close(); reschedule_delegate_loop(); } } void detail::ClientImpl::wallet_backup_create(const fc::path& json_filename)const { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); _wallet->export_to_json(json_filename); } void detail::ClientImpl::wallet_backup_restore(const fc::path& json_filename, const string& wallet_name, const string& imported_wallet_passphrase) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); _wallet->create_from_json(json_filename, wallet_name, imported_wallet_passphrase); reschedule_delegate_loop(); } // This should be able to get an encrypted private key or WIF key out of any reasonable JSON object void read_keys(const fc::variant& vo, vector<PrivateKeyType>& keys, const string& password) { ilog("@n read_keys"); try { const auto wif_key = vo.as_string(); const auto key = thinkyoung::utilities::wif_to_key(wif_key); if (key.valid()) keys.push_back(*key); } catch (...) { //ilog("@n I couldn't parse that as a wif key: ${vo}", ("vo", vo)); } try { const auto key_bytes = vo.as<vector<char>>(); const auto password_bytes = fc::sha512::hash(password.c_str(), password.size()); const auto key_plain_text = fc::aes_decrypt(password_bytes, key_bytes); keys.push_back(fc::raw::unpack<PrivateKeyType>(key_plain_text)); } catch (...) { //ilog("@n I couldn't parse that as a byte array: ${vo}", ("vo", vo)); } try { const auto obj = vo.get_object(); for (const auto& kv : obj) { read_keys(kv.value(), keys, password); } } catch (const thinkyoung::wallet::invalid_password&) { throw; } catch (...) { //ilog("@n I couldn't parse that as an object: ${o}", ("o", vo)); } try { const auto arr = vo.as<vector<variant>>(); for (const auto& obj : arr) { read_keys(obj, keys, password); } } catch (const thinkyoung::wallet::invalid_password&) { throw; } catch (...) { //ilog("@n I couldn't parse that as an array: ${o}", ("o", vo)); } //ilog("@n I couldn't parse that as anything!: ${o}", ("o", vo)); } bool detail::ClientImpl::wallet_set_automatic_backups(bool enabled) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); _wallet->set_automatic_backups(enabled); return _wallet->get_automatic_backups(); } uint32_t detail::ClientImpl::wallet_set_transaction_expiration_time(uint32_t secs) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); _wallet->set_transaction_expiration(secs); return _wallet->get_transaction_expiration(); } void detail::ClientImpl::wallet_lock() { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); _wallet->lock(); reschedule_delegate_loop(); } void detail::ClientImpl::wallet_unlock(uint32_t timeout, const string& password) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); _wallet->unlock(password, timeout); reschedule_delegate_loop(); if (_config.wallet_callback_url.size() > 0) { _http_callback_signal_connection = _wallet->wallet_claimed_transaction.connect( [=](LedgerEntry e) { this->wallet_http_callback(_config.wallet_callback_url, e); }); } } void detail::ClientImpl::wallet_http_callback(const string& url, const LedgerEntry& e) { fc::async([=]() { fc::url u(url); if (u.host()) { auto endpoints = fc::resolve(*u.host(), u.port() ? *u.port() : 80); for (auto ep : endpoints) { fc::http::connection con; con.connect_to(ep); auto response = con.request("POST", url, fc::json::to_string(e)); if (response.status == fc::http::reply::OK) return; } } } ); } vector<thinkyoung::wallet::PrettyTransaction> detail::ClientImpl::wallet_transaction_history_splite(const std::string& account_name, const std::string& asset_symbol, int32_t limit, int32_t transaction_type)const { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); try { const auto history = _wallet->get_pretty_transaction_history(account_name, 0, -1, asset_symbol, (thinkyoung::wallet::Wallet::TrxType)transaction_type, true); if (limit == 0 || abs(limit) >= history.size()) { return history; } else if (limit > 0) { return vector<PrettyTransaction>(history.begin(), history.begin() + limit); } else { return vector<PrettyTransaction>(history.end() - abs(limit), history.end()); } } FC_RETHROW_EXCEPTIONS(warn, "") } void detail::ClientImpl::wallet_change_passphrase(const std::string& old_password, const string& new_password) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); _wallet->auto_backup("passphrase_change"); _wallet->change_passphrase(old_password, new_password); reschedule_delegate_loop(); } bool detail::ClientImpl::wallet_check_passphrase(const std::string& passphrase) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); return _wallet->check_passphrase(passphrase); } bool detail::ClientImpl::wallet_check_address(const std::string& address) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); size_t first = address.find_first_of("ACT"); if (first != std::string::npos&&first == 0) { string strToAccount; string strSubAccount; _wallet->accountsplit(address, strToAccount, strSubAccount); return Address::is_valid(strToAccount); } else { return _wallet->is_valid_account_name(address); } } map<TransactionIdType, fc::exception> detail::ClientImpl::wallet_get_pending_transaction_errors(const thinkyoung::blockchain::FilePath& filename)const { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); const auto& errors = _wallet->get_pending_transaction_errors(); if (filename != "") { FC_ASSERT(!fc::exists(filename)); std::ofstream out(filename.c_str()); out << fc::json::to_pretty_string(errors); } return errors; } WalletTransactionEntry detail::ClientImpl::wallet_publish_slate(const string& publishing_account_name, const string& paying_account_name) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); auto entry = _wallet->publish_slate(publishing_account_name, paying_account_name, true); _wallet->cache_transaction(entry); network_broadcast_transaction(entry.trx); return entry; } WalletTransactionEntry detail::ClientImpl::wallet_publish_version(const string& publishing_account_name, const string& paying_account_name) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); auto entry = _wallet->publish_version(publishing_account_name, paying_account_name, true); _wallet->cache_transaction(entry); network_broadcast_transaction(entry.trx); return entry; } WalletTransactionEntry detail::ClientImpl::wallet_collect_genesis_balances(const string& account_name) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); const auto filter = [](const BalanceEntry& entry) -> bool { return entry.condition.type == withdraw_signature_type && entry.snapshot_info.valid(); }; auto entry = _wallet->collect_account_balances(account_name, filter, "collect genesis", true); _wallet->cache_transaction(entry); network_broadcast_transaction(entry.trx); return entry; } int32_t detail::ClientImpl::wallet_recover_accounts(int32_t accounts_to_recover, int32_t maximum_number_of_attempts) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); _wallet->auto_backup("before_account_recovery"); return _wallet->recover_accounts(accounts_to_recover, maximum_number_of_attempts); } // wallet_transaction_entry detail::ClientImpl::wallet_recover_titan_deposit_info( const string& transaction_id_prefix, // const string& recipient_account ) // { // return _wallet->recover_transaction( transaction_id_prefix, recipient_account ); // } optional<variant_object> detail::ClientImpl::wallet_verify_titan_deposit(const string& transaction_id_prefix) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); return _wallet->verify_titan_deposit(transaction_id_prefix); } // wallet_transaction_entry detail::ClientImpl::wallet_transfer( // const string& amount_to_transfer, // const string& asset_symbol, // const string& from_account_name, // const string& to_account_name, // const string& memo_message, // const vote_strategy& strategy ) // { // return wallet_transfer_from(amount_to_transfer, asset_symbol, from_account_name, from_account_name, // to_account_name, memo_message, strategy); // } WalletTransactionEntry detail::ClientImpl::wallet_transfer_to_public_account( const string& amount_to_transfer, const string& asset_symbol, const string& from_account_name, const string& to_account_name, const string& memo_message, const VoteStrategy& strategy) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); const oAccountEntry account_entry = _chain_db->get_account_entry(to_account_name); FC_ASSERT(account_entry.valid() && !account_entry->is_retracted()); auto entry = _wallet->transfer_asset_to_address(amount_to_transfer, asset_symbol, from_account_name, account_entry->owner_address(), memo_message, strategy, true); _wallet->cache_transaction(entry); network_broadcast_transaction(entry.trx); return entry; } string detail::ClientImpl::wallet_address_create(const string& account_name, const string& label, int legacy_network_byte) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); try { auto pubkey = _wallet->get_new_public_key(account_name); if (legacy_network_byte == -1) return (string(Address(pubkey)) + INVALIDE_SUB_ADDRESS); else if (legacy_network_byte == 0 || legacy_network_byte == 56) return string(PtsAddress(pubkey, true, legacy_network_byte)); else FC_ASSERT(false, "Unsupported network byte"); } FC_CAPTURE_AND_RETHROW((account_name)(label)(legacy_network_byte)) } // wallet_transaction_entry detail::ClientImpl::wallet_transfer_to_legacy_address( // double amount_to_transfer, // const string& asset_symbol, // const string& from_account_name, // const pts_address& to_address, // const string& alp_account, // const string& memo_message, // const vote_strategy& strategy ) // { // auto entry = _wallet->transfer_asset_to_address( amount_to_transfer, // asset_symbol, // from_account_name, // address( to_address ), // memo_message, // strategy, // true ); // _wallet->cache_transaction( entry ); // network_broadcast_transaction( entry.trx ); // return entry; // // } WalletTransactionEntry detail::ClientImpl::wallet_transfer_to_address( const string& amount_to_transfer, const string& asset_symbol, const string& from_account_name, const string& to_address, const string& memo_message, const VoteStrategy& strategy) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); string strToAccount; string strSubAccount; _wallet->accountsplit(to_address, strToAccount, strSubAccount); Address effective_address; if (Address::is_valid(strToAccount)) effective_address = Address(strToAccount); else effective_address = Address(PublicKeyType(strToAccount)); auto entry = _wallet->transfer_asset_to_address(amount_to_transfer, asset_symbol, from_account_name, effective_address, memo_message, strategy, true, strSubAccount); _wallet->cache_transaction(entry); network_broadcast_transaction(entry.trx); return entry; } thinkyoung::blockchain::SignedTransaction ClientImpl::create_transfer_transaction(const std::string& amount_to_transfer, const std::string& asset_symbol, const std::string& from_account_name, const std::string& to_address, const thinkyoung::blockchain::Imessage& memo_message /* = fc::json::from_string("").as<thinkyoung::blockchain::Imessage>() */, const thinkyoung::wallet::VoteStrategy& strategy) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); string strToAccount; string strSubAccount; _wallet->accountsplit(to_address, strToAccount, strSubAccount); Address effective_address; if (Address::is_valid(strToAccount)) effective_address = Address(strToAccount); else effective_address = Address(PublicKeyType(strToAccount)); auto entry = _wallet->transfer_asset_to_address(amount_to_transfer, asset_symbol, from_account_name, effective_address, memo_message, strategy, true, strSubAccount); // _wallet->cache_transaction(entry); return entry.trx; } // wallet_transaction_entry detail::ClientImpl::wallet_transfer_from( // const string& amount_to_transfer, // const string& asset_symbol, // const string& paying_account_name, // const string& from_account_name, // const string& to_account_name, // const string& memo_message, // const vote_strategy& strategy ) // { // asset amount = _chain_db->to_ugly_asset(amount_to_transfer, asset_symbol); // auto payer = _wallet->get_account(paying_account_name); // auto recipient = _wallet->get_account(to_account_name); // transaction_builder_ptr builder = _wallet->create_transaction_builder(); // auto entry = builder->deposit_asset(payer, recipient, amount, // memo_message, from_account_name) // .finalize( true, strategy ) // .sign(); // _wallet->cache_transaction( entry ); // network_broadcast_transaction( entry.trx ); // /*for( auto&& notice : builder->encrypted_notifications() ) // _mail_client->send_encrypted_message(std::move(notice), // from_account_name, // to_account_name, // recipient.owner_key);*/ // // return entry; // } // // balance_id_type detail::ClientImpl::wallet_multisig_get_balance_id( // const string& asset_symbol, // uint32_t m, // const vector<address>& addresses )const // { // auto id = _chain_db->get_asset_id( asset_symbol ); // return balance_entry::get_multisig_balance_id( id, m, addresses ); // } // // wallet_transaction_entry detail::ClientImpl::wallet_multisig_deposit( // const string& amount, // const string& symbol, // const string& from_name, // uint32_t m, // const vector<address>& addresses, // const vote_strategy& strategy ) // { // asset ugly_asset = _chain_db->to_ugly_asset(amount, symbol); // auto builder = _wallet->create_transaction_builder(); // builder->deposit_asset_to_multisig( ugly_asset, from_name, m, addresses ); // auto entry = builder->finalize( true, strategy ).sign(); // _wallet->cache_transaction( entry ); // network_broadcast_transaction( entry.trx ); // return entry; // } TransactionBuilder detail::ClientImpl::wallet_withdraw_from_address( const string& amount, const string& symbol, const Address& from_address, const string& to, const VoteStrategy& strategy, bool sign, const string& builder_path) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); Address to_address; try { auto acct = _wallet->get_account(to); to_address = acct.owner_address(); } catch (...) { to_address = Address(to); } Asset ugly_asset = _chain_db->to_ugly_asset(amount, symbol); auto builder = _wallet->create_transaction_builder(); auto fee = _wallet->get_transaction_fee(); builder->withdraw_from_balance(from_address, ugly_asset.amount + fee.amount); builder->deposit_to_balance(to_address, ugly_asset); builder->finalize(false, strategy); if (sign) { builder->sign(); network_broadcast_transaction(builder->transaction_entry.trx); } _wallet->write_latest_builder(*builder, builder_path); return *builder; } WalletTransactionEntry detail::ClientImpl::wallet_asset_create( const string& symbol, const string& asset_name, const string& issuer_name, const string& description, const string& maximum_share_supply, uint64_t precision, const variant& public_data, bool is_market_issued /* = false */) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); auto entry = _wallet->create_asset(symbol, asset_name, description, public_data, issuer_name, maximum_share_supply, precision, is_market_issued, true); _wallet->cache_transaction(entry); network_broadcast_transaction(entry.trx); return entry; } WalletTransactionEntry detail::ClientImpl::wallet_asset_issue( const string& real_amount, const string& symbol, const string& to_account_name, const string& memo_message) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); auto entry = _wallet->issue_asset(real_amount, symbol, to_account_name, memo_message, true); _wallet->cache_transaction(entry); network_broadcast_transaction(entry.trx); return entry; } WalletTransactionEntry detail::ClientImpl::wallet_asset_issue_to_addresses( const string& symbol, const map<string, ShareType>& addresses) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); auto entry = _wallet->issue_asset_to_addresses(symbol, addresses); _wallet->cache_transaction(entry); network_broadcast_transaction(entry.trx); return entry; } vector<string> detail::ClientImpl::wallet_list() const { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); return _wallet->list(); } vector<WalletAccountEntry> detail::ClientImpl::wallet_list_accounts() const { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); return _wallet->list_accounts(); } vector<thinkyoung::wallet::AccountAddressData> detail::ClientImpl::wallet_list_my_addresses() const { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); return _wallet->list_addresses(); } vector<WalletAccountEntry> detail::ClientImpl::wallet_list_my_accounts() const { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); return _wallet->list_my_accounts(); } // // vector<wallet_account_entry> detail::ClientImpl::wallet_list_favorite_accounts() const // { // return _wallet->list_favorite_accounts(); // } vector<WalletAccountEntry> detail::ClientImpl::wallet_list_unregistered_accounts() const { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); return _wallet->list_unregistered_accounts(); } void detail::ClientImpl::wallet_remove_contact_account(const string& account_name) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); _wallet->remove_contact_account(account_name); } void detail::ClientImpl::wallet_account_rename(const string& current_account_name, const string& new_account_name) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); _wallet->rename_account(current_account_name, new_account_name); _wallet->auto_backup("account_rename"); } WalletAccountEntry detail::ClientImpl::wallet_get_account(const string& account_name) const { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); try { return _wallet->get_account(account_name); } FC_RETHROW_EXCEPTIONS(warn, "", ("account_name", account_name)) } string detail::ClientImpl::wallet_get_account_public_address(const string& account_name) const { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); try { auto acct = _wallet->get_account(account_name); return (string(acct.owner_address()) + INVALIDE_SUB_ADDRESS); } FC_RETHROW_EXCEPTIONS(warn, "", ("account_name", account_name)) } vector<PrettyTransaction> detail::ClientImpl::wallet_account_transaction_history(const string& account_name, const string& asset_symbol, int32_t limit, uint32_t start_block_num, uint32_t end_block_num)const { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); try { const auto history = _wallet->get_pretty_transaction_history(account_name, start_block_num, end_block_num, asset_symbol); if (limit == 0 || abs(limit) >= history.size()) { return history; } else if (limit > 0) { return vector<PrettyTransaction>(history.begin(), history.begin() + limit); } else { return vector<PrettyTransaction>(history.end() - abs(limit), history.end()); } } FC_RETHROW_EXCEPTIONS(warn, "") } AccountBalanceSummaryType detail::ClientImpl::wallet_account_historic_balance(const time_point& time, const string& account)const { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); try { fc::time_point_sec target(time); return _wallet->compute_historic_balance(account, _self->get_chain()->find_block_num(target)); } FC_RETHROW_EXCEPTIONS(warn, "") } void detail::ClientImpl::wallet_remove_transaction(const string& transaction_id) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); try { _wallet->remove_transaction_entry(transaction_id); } FC_RETHROW_EXCEPTIONS(warn, "", ("transaction_id", transaction_id)) } void detail::ClientImpl::wallet_rebroadcast_transaction(const string& transaction_id) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); try { const auto entrys = _wallet->get_transactions(transaction_id); for (const auto& entry : entrys) { if (entry.is_virtual) continue; network_broadcast_transaction(entry.trx); std::cout << "Rebroadcasted transaction: " << string(entry.trx.id()) << "\n"; } } FC_RETHROW_EXCEPTIONS(warn, "", ("transaction_id", transaction_id)) } string detail::ClientImpl::wallet_import_private_key(const string& wif_key_to_import, const string& account_name, bool create_account, bool wallet_rescan_blockchain) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); optional<string> name; if (!account_name.empty()) name = account_name; //add limit for import private key to existing account const auto current_account = _wallet->get_wallet_db().lookup_account(account_name); if (current_account.valid()) FC_THROW_EXCEPTION(invalid_name, "This name is already in your wallet!"); const auto existing_registered_account = _chain_db->get_account_entry(account_name); if (existing_registered_account.valid()) FC_THROW_EXCEPTION(invalid_name, "This name is already registered with the blockchain!"); const PublicKeyType new_public_key = _wallet->import_wif_private_key(wif_key_to_import, name, create_account); if (wallet_rescan_blockchain) _wallet->start_scan(0, -1); else _wallet->start_scan(0, 1); const oWalletAccountEntry account_entry = _wallet->get_account_for_address(Address(new_public_key)); FC_ASSERT(account_entry.valid(), "No account for the key we just imported!?"); _wallet->auto_backup("key_import"); return account_entry->name; } optional<string> detail::ClientImpl::wallet_dump_private_key(const string& input)const { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); try { string RelAddress; string Temp; _wallet->accountsplit(input, RelAddress, Temp); try { ASSERT_TASK_NOT_PREEMPTED(); // make sure no cancel gets swallowed by catch(...) //If input is an address... return utilities::key_to_wif(_wallet->get_private_key(Address(RelAddress))); } catch (...) { try { ASSERT_TASK_NOT_PREEMPTED(); // make sure no cancel gets swallowed by catch(...) //If input is a public key... return utilities::key_to_wif(_wallet->get_private_key(Address(PublicKeyType(RelAddress)))); } catch (...) { } } return optional<string>(); } FC_CAPTURE_AND_RETHROW((input)) } optional<string> detail::ClientImpl::wallet_dump_account_private_key(const string& account_name, const AccountKeyType& key_type)const { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); try { const auto account_entry = _wallet->get_account(account_name); switch (key_type) { case owner_key: return utilities::key_to_wif(_wallet->get_private_key(account_entry.owner_address())); case active_key: return utilities::key_to_wif(_wallet->get_private_key(account_entry.active_address())); case signing_key: FC_ASSERT(account_entry.is_delegate()); return utilities::key_to_wif(_wallet->get_private_key(account_entry.signing_address())); default: return optional<string>(); } } FC_CAPTURE_AND_RETHROW((account_name)(key_type)) } Address ClientImpl::wallet_account_create(const string& account_name, const variant& private_data) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); const auto result = _wallet->create_account(account_name, private_data); _wallet->auto_backup("account_create"); return Address(result); } // void ClientImpl::wallet_account_set_favorite( const string& account_name, bool is_favorite ) // { // _wallet->account_set_favorite( account_name, is_favorite ); // } void ClientImpl::wallet_rescan_blockchain(const uint32_t start_block_num, const uint32_t limit) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); try { _wallet->start_scan(start_block_num, limit); } FC_CAPTURE_AND_RETHROW((start_block_num)(limit)) } void ClientImpl::wallet_cancel_scan() { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); try { _wallet->cancel_scan(); } FC_CAPTURE_AND_RETHROW() } vector<string> ClientImpl::wallet_get_contracts(const string &account_name) { try { return _wallet->get_contracts(account_name); } FC_CAPTURE_AND_RETHROW() } void ClientImpl::wallet_scan_contracts() { try { _wallet->scan_contracts(); } FC_CAPTURE_AND_RETHROW() } WalletTransactionEntry ClientImpl::wallet_scan_transaction(const string& transaction_id, bool overwrite_existing) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); try { if (transaction_id == "ALL") { return _wallet->scan_all_transaction(overwrite_existing); } return _wallet->scan_transaction(transaction_id, overwrite_existing); } FC_RETHROW_EXCEPTIONS(warn, "", ("transaction_id", transaction_id)("overwrite_existing", overwrite_existing)) } WalletTransactionEntry ClientImpl::wallet_get_transaction(const string& transaction_id) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); try { return _wallet->get_transaction(transaction_id); } FC_RETHROW_EXCEPTIONS(warn, "", ("transaction_id", transaction_id)) } WalletTransactionEntry ClientImpl::wallet_account_register(const string& account_name, const string& pay_with_account, const fc::variant& data, uint8_t delegate_pay_rate, const string& new_account_type) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); try { auto entry = _wallet->register_account(account_name, data, delegate_pay_rate, pay_with_account, variant(new_account_type).as<AccountType>(), true); _wallet->cache_transaction(entry); network_broadcast_transaction(entry.trx); return entry; } FC_RETHROW_EXCEPTIONS(warn, "", ("account_name", account_name)("data", data)) } variant_object ClientImpl::wallet_get_info() { return _wallet->get_info().get_object(); } void ClientImpl::wallet_account_update_private_data(const string& account_to_update, const variant& private_data) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); _wallet->update_account_private_data(account_to_update, private_data); } WalletTransactionEntry ClientImpl::wallet_account_update_registration( const string& account_to_update, const string& pay_from_account, const variant& public_data, uint8_t delegate_pay_rate) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); auto entry = _wallet->update_registered_account(account_to_update, pay_from_account, public_data, delegate_pay_rate, true); _wallet->cache_transaction(entry); network_broadcast_transaction(entry.trx); return entry; } WalletTransactionEntry detail::ClientImpl::wallet_account_update_active_key(const std::string& account_to_update, const std::string& pay_from_account, const std::string& new_active_key) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); auto entry = _wallet->update_active_key(account_to_update, pay_from_account, new_active_key, true); _wallet->cache_transaction(entry); network_broadcast_transaction(entry.trx); return entry; } WalletTransactionEntry detail::ClientImpl::wallet_account_retract(const std::string& account_to_update, const std::string& pay_from_account) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); auto entry = _wallet->retract_account(account_to_update, pay_from_account, true); _wallet->cache_transaction(entry); network_broadcast_transaction(entry.trx); return entry; } vector<PublicKeySummary> ClientImpl::wallet_account_list_public_keys(const string& account_name) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); vector<PublicKeySummary> summaries; vector<PublicKeyType> keys = _wallet->get_public_keys_in_account(account_name); summaries.reserve(keys.size()); for (const auto& key : keys) { summaries.push_back(_wallet->get_public_key_summary(key)); } return summaries; } AccountBalanceSummaryType ClientImpl::wallet_account_balance(const string& account_name)const { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); try { if (!account_name.empty() && !_chain_db->is_valid_account_name(account_name)) FC_THROW_EXCEPTION(invalid_name, "Invalid account name!", ("account_name", account_name)); return _wallet->get_spendable_account_balances(account_name); } FC_CAPTURE_AND_RETHROW((account_name)) } AccountBalanceIdSummaryType ClientImpl::wallet_account_balance_ids(const string& account_name)const { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); try { return _wallet->get_account_balance_ids(account_name); } FC_CAPTURE_AND_RETHROW((account_name)) } DelegatePaySalary ClientImpl::wallet_delegate_pay_balance_query(const string& delegate_name) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); auto salary = _wallet->query_delegate_salary(delegate_name); return salary; } std::map<std::string, thinkyoung::blockchain::DelegatePaySalary> ClientImpl::wallet_active_delegate_salary() { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); auto salary = _wallet->query_delegate_salarys(); return salary; } WalletTransactionEntry ClientImpl::wallet_delegate_withdraw_pay(const string& delegate_name, const string& to_account_name, const string& amount_to_withdraw) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); auto entry = _wallet->withdraw_delegate_pay(delegate_name, amount_to_withdraw, to_account_name, true); _wallet->cache_transaction(entry); network_broadcast_transaction(entry.trx); return entry; } void ClientImpl::wallet_set_transaction_imessage_fee_coe(const string& fee_coe) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); try { auto ipos = fee_coe.find("."); if (ipos != string::npos) { string str = fee_coe.substr(ipos + 1); int64_t precision_input = static_cast<int64_t>(pow(10, str.size())); FC_ASSERT((precision_input <= ALP_BLOCKCHAIN_PRECISION), "Precision is not correct"); } double dFee = std::stod(fee_coe); _wallet->set_transaction_imessage_fee_coe(static_cast<int64_t>(floor(dFee * ALP_BLOCKCHAIN_PRECISION + 0.5))); } FC_CAPTURE_AND_RETHROW((fee_coe)) } double ClientImpl::wallet_get_transaction_imessage_fee_coe() { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); auto fee_coe = _wallet->get_transaction_imessage_fee_coe(); return ((double)fee_coe) / ALP_BLOCKCHAIN_PRECISION; } void ClientImpl::wallet_set_transaction_imessage_soft_max_length(int64_t soft_length) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); try { _wallet->set_transaction_imessage_soft_max_length(soft_length); } FC_CAPTURE_AND_RETHROW((soft_length)) } int64_t ClientImpl::wallet_get_transaction_imessage_soft_max_length() { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); return _wallet->get_transaction_imessage_soft_max_length(); } Asset ClientImpl::wallet_set_transaction_fee(const string& fee) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); try { oAssetEntry asset_entry = _chain_db->get_asset_entry(AssetIdType()); FC_ASSERT(asset_entry.valid()); FC_ASSERT(utilities::isNumber(fee), "fee is not a number"); auto ipos = fee.find("."); if (ipos != string::npos) { string str = fee.substr(ipos + 1); int64_t precision_input = static_cast<int64_t>(pow(10, str.size())); FC_ASSERT((static_cast<uint64_t>(precision_input) <= asset_entry->precision), "Precision is not correct"); } double dFee = std::stod(fee); _wallet->set_transaction_fee(Asset(static_cast<ShareType>(floor(dFee * asset_entry->precision + 0.5)))); return _wallet->get_transaction_fee(); } FC_CAPTURE_AND_RETHROW((fee)) } Asset ClientImpl::wallet_get_transaction_fee(const string& fee_symbol) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); if (fee_symbol.empty()) return _wallet->get_transaction_fee(_chain_db->get_asset_id(ALP_BLOCKCHAIN_SYMBOL)); return _wallet->get_transaction_fee(_chain_db->get_asset_id(fee_symbol)); } AccountVoteSummaryType ClientImpl::wallet_account_vote_summary(const string& account_name)const { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); if (!account_name.empty() && !_chain_db->is_valid_account_name(account_name)) FC_CAPTURE_AND_THROW(invalid_account_name, (account_name)); return _wallet->get_account_vote_summary(account_name); } VoteSummary ClientImpl::wallet_check_vote_status(const string& account_name) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); return _wallet->get_vote_status(account_name); } void ClientImpl::wallet_delegate_set_block_production(const string& delegate_name, bool enabled) { _wallet->set_delegate_block_production(delegate_name, enabled); reschedule_delegate_loop(); } bool ClientImpl::wallet_get_delegate_statue(const std::string& account_name) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); return _wallet->wallet_get_delegate_statue(account_name); } bool ClientImpl::wallet_set_transaction_scanning(bool enabled) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); _wallet->set_transaction_scanning(enabled); return _wallet->get_transaction_scanning(); } fc::ecc::compact_signature ClientImpl::wallet_sign_hash(const string& signer, const fc::sha256& hash) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); return _wallet->sign_hash(signer, hash); } std::string ClientImpl::wallet_login_start(const std::string &server_account) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); return _wallet->login_start(server_account); } fc::variant ClientImpl::wallet_login_finish(const PublicKeyType &server_key, const PublicKeyType &client_key, const fc::ecc::compact_signature &client_signature) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); return _wallet->login_finish(server_key, client_key, client_signature); } TransactionBuilder ClientImpl::wallet_balance_set_vote_info(const BalanceIdType& balance_id, const string& voter_address, const VoteStrategy& strategy, bool sign_and_broadcast, const string& builder_path) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); Address new_voter; if (voter_address == "") { auto balance = _chain_db->get_balance_entry(balance_id); if (balance.valid() && balance->restricted_owner.valid()) new_voter = *balance->restricted_owner; else FC_ASSERT(false, "Didn't specify a voter address and none currently exists."); } else { new_voter = Address(voter_address); } auto builder = _wallet->create_transaction_builder(_wallet->set_vote_info(balance_id, new_voter, strategy)); if (sign_and_broadcast) { auto entry = builder->sign(); _wallet->cache_transaction(entry); network_broadcast_transaction(entry.trx); } _wallet->write_latest_builder(*builder, builder_path); return *builder; } void ClientImpl::wallet_repair_entrys(const string& collecting_account_name) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); try { _wallet->auto_backup("before_entry_repair"); optional<string> account_name; if (!collecting_account_name.empty()) account_name = collecting_account_name; return _wallet->repair_entrys(account_name); } FC_CAPTURE_AND_RETHROW((collecting_account_name)) } int32_t ClientImpl::wallet_regenerate_keys(const std::string& account, uint32_t number_to_regenerate) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); _wallet->auto_backup("before_key_regeneration"); return _wallet->regenerate_keys(account, number_to_regenerate); } std::string ClientImpl::wallet_transfer_to_address_rpc(const std::string& amount_to_transfer, const std::string& asset_symbol, const std::string& from_account_name, const std::string& to_address, const thinkyoung::blockchain::Imessage& memo_message /* = fc::json::from_string("").as<std::string>() */, const thinkyoung::wallet::VoteStrategy& strategy /* = fc::json::from_string("vote_recommended").as<thinkyoung::wallet::vote_strategy>() */) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); try { auto result = wallet_transfer_to_address(amount_to_transfer, asset_symbol, from_account_name, to_address, memo_message, strategy); std::string res = "{\"result\":\"SUCCESS\",\"message\":\""; res += result.entry_id.str(); res += "\"}"; return res; } catch (fc::exception e) { std::string res = "{\"result\":\"ERROR\",\"message\":\""; res += e.to_string(); res += "\"}"; return res; } } std::string detail::ClientImpl::wallet_transfer_to_public_account_rpc( const std::string& amount_to_transfer, const string& asset_symbol, const string& from_account_name, const string& to_account_name, const thinkyoung::blockchain::Imessage& memo_message, const thinkyoung::wallet::VoteStrategy& strategy) { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); const oAccountEntry account_record = _chain_db->get_account_entry(to_account_name); FC_ASSERT(account_record.valid() && !account_record->is_retracted()); auto record = _wallet->transfer_asset_to_address(amount_to_transfer, asset_symbol, from_account_name, account_record->owner_address(), memo_message, strategy, true); _wallet->cache_transaction(record); network_broadcast_transaction(record.trx); string result = "{\"result\":\"SUCCESS\",\"message\":\"" + string(record.trx.id()) + "\"}"; return result; } string ClientImpl::wallet_account_balance_rpc(const string& account_name)const { // set limit in sandbox state if (_chain_db->get_is_in_sandbox()) FC_THROW_EXCEPTION(sandbox_command_forbidden, "in sandbox, this command is forbidden, you cannot call it!"); try { auto result = wallet_account_balance(account_name); std::string res = "{\"result\":\"SUCCESS\",\"message\":\""; if (result.begin() == result.end()) { res += "0\"}"; } else { char buf[52] = { 0 }; auto re_val = result.begin()->second; auto resu = re_val.find(thinkyoung::blockchain::Asset(0, 0).asset_id); if (resu == re_val.end()) { res += "0\"}"; } else { sprintf(buf, "%lld", resu->second); res += buf; res += "\"}"; } } return res; } catch (fc::exception e) { std::string res = "{\"result\":\"ERROR\",\"message\":\""; res += e.to_string(); res += "\"}"; return res; } } } } } // namespace thinkyoung::client::detail
52.486007
456
0.506698
[ "object", "vector" ]
a7cf8527f481464ee10677cad241e30ed4f15772
9,717
cc
C++
sandboxed_api/sandbox2/policy_test.cc
alexelex/sandboxed-api
0710361ed4f78f4484465114e436cc0d3eb5a7f9
[ "Apache-2.0" ]
null
null
null
sandboxed_api/sandbox2/policy_test.cc
alexelex/sandboxed-api
0710361ed4f78f4484465114e436cc0d3eb5a7f9
[ "Apache-2.0" ]
null
null
null
sandboxed_api/sandbox2/policy_test.cc
alexelex/sandboxed-api
0710361ed4f78f4484465114e436cc0d3eb5a7f9
[ "Apache-2.0" ]
null
null
null
// 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 "sandboxed_api/sandbox2/policy.h" #include <sys/resource.h> #include <syscall.h> #include <cerrno> #include <cstdlib> #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/memory/memory.h" #include "absl/strings/string_view.h" #include "sandboxed_api/sandbox2/config.h" #include "sandboxed_api/sandbox2/executor.h" #include "sandboxed_api/sandbox2/limits.h" #include "sandboxed_api/sandbox2/policybuilder.h" #include "sandboxed_api/sandbox2/result.h" #include "sandboxed_api/sandbox2/sandbox2.h" #include "sandboxed_api/sandbox2/syscall.h" #include "sandboxed_api/sandbox2/testing.h" #include "sandboxed_api/sandbox2/util/bpf_helper.h" using ::testing::Eq; namespace sandbox2 { namespace { std::unique_ptr<Policy> PolicyTestcasePolicy() { return PolicyBuilder() .DisableNamespaces() .AllowStaticStartup() .AllowExit() .AllowRead() .AllowWrite() .AllowSyscall(__NR_close) .AllowSyscall(__NR_getppid) .AllowTCGETS() #ifdef __NR_open .BlockSyscallWithErrno(__NR_open, ENOENT) #endif .BlockSyscallWithErrno(__NR_openat, ENOENT) #ifdef __NR_access .BlockSyscallWithErrno(__NR_access, ENOENT) #endif #ifdef __NR_faccessat .BlockSyscallWithErrno(__NR_faccessat, ENOENT) #endif .BlockSyscallWithErrno(__NR_prlimit64, EPERM) .BuildOrDie(); } #ifdef SAPI_X86_64 // Test that 32-bit syscalls from 64-bit are disallowed. TEST(PolicyTest, AMD64Syscall32PolicyAllowed) { SKIP_SANITIZERS_AND_COVERAGE; const std::string path = GetTestSourcePath("sandbox2/testcases/policy"); std::vector<std::string> args = {path, "1"}; auto executor = absl::make_unique<Executor>(path, args); auto policy = PolicyTestcasePolicy(); Sandbox2 s2(std::move(executor), std::move(policy)); auto result = s2.Run(); ASSERT_THAT(result.final_status(), Eq(Result::VIOLATION)); EXPECT_THAT(result.reason_code(), Eq(1)); // __NR_exit in 32-bit EXPECT_THAT(result.GetSyscallArch(), Eq(cpu::kX86)); } // Test that 32-bit syscalls from 64-bit for FS checks are disallowed. TEST(PolicyTest, AMD64Syscall32FsAllowed) { SKIP_SANITIZERS_AND_COVERAGE; const std::string path = GetTestSourcePath("sandbox2/testcases/policy"); std::vector<std::string> args = {path, "2"}; auto executor = absl::make_unique<Executor>(path, args); auto policy = PolicyTestcasePolicy(); Sandbox2 s2(std::move(executor), std::move(policy)); auto result = s2.Run(); ASSERT_THAT(result.final_status(), Eq(Result::VIOLATION)); EXPECT_THAT(result.reason_code(), Eq(33)); // __NR_access in 32-bit EXPECT_THAT(result.GetSyscallArch(), Eq(cpu::kX86)); } #endif // Test that ptrace(2) is disallowed. TEST(PolicyTest, PtraceDisallowed) { SKIP_SANITIZERS_AND_COVERAGE; const std::string path = GetTestSourcePath("sandbox2/testcases/policy"); std::vector<std::string> args = {path, "3"}; auto executor = absl::make_unique<Executor>(path, args); auto policy = PolicyTestcasePolicy(); Sandbox2 s2(std::move(executor), std::move(policy)); auto result = s2.Run(); ASSERT_THAT(result.final_status(), Eq(Result::VIOLATION)); EXPECT_THAT(result.reason_code(), Eq(__NR_ptrace)); } // Test that clone(2) with flag CLONE_UNTRACED is disallowed. TEST(PolicyTest, CloneUntracedDisallowed) { SKIP_SANITIZERS_AND_COVERAGE; const std::string path = GetTestSourcePath("sandbox2/testcases/policy"); std::vector<std::string> args = {path, "4"}; auto executor = absl::make_unique<Executor>(path, args); auto policy = PolicyTestcasePolicy(); Sandbox2 s2(std::move(executor), std::move(policy)); auto result = s2.Run(); ASSERT_THAT(result.final_status(), Eq(Result::VIOLATION)); EXPECT_THAT(result.reason_code(), Eq(__NR_clone)); } // Test that bpf(2) is disallowed. TEST(PolicyTest, BpfDisallowed) { SKIP_SANITIZERS_AND_COVERAGE; const std::string path = GetTestSourcePath("sandbox2/testcases/policy"); std::vector<std::string> args = {path, "5"}; auto executor = absl::make_unique<Executor>(path, args); auto policy = PolicyTestcasePolicy(); Sandbox2 s2(std::move(executor), std::move(policy)); auto result = s2.Run(); ASSERT_THAT(result.final_status(), Eq(Result::VIOLATION)); EXPECT_THAT(result.reason_code(), Eq(__NR_bpf)); } TEST(PolicyTest, IsattyAllowed) { SKIP_SANITIZERS_AND_COVERAGE; const std::string path = GetTestSourcePath("sandbox2/testcases/policy"); std::vector<std::string> args = {path, "6"}; auto executor = absl::make_unique<Executor>(path, args); auto policy = PolicyTestcasePolicy(); Sandbox2 s2(std::move(executor), std::move(policy)); auto result = s2.Run(); ASSERT_THAT(result.final_status(), Eq(Result::OK)); } std::unique_ptr<Policy> MinimalTestcasePolicy() { return PolicyBuilder() .AllowStaticStartup() .AllowExit() .BlockSyscallWithErrno(__NR_prlimit64, EPERM) #ifdef __NR_access .BlockSyscallWithErrno(__NR_access, ENOENT) #endif .BuildOrDie(); } // Test that we can sandbox a minimal static binary returning 0. // If this starts failing, it means something changed, maybe in the way we // compile static binaries, and we need to update the policy just above. TEST(MinimalTest, MinimalBinaryWorks) { SKIP_SANITIZERS_AND_COVERAGE; const std::string path = GetTestSourcePath("sandbox2/testcases/minimal"); std::vector<std::string> args = {path}; auto executor = absl::make_unique<Executor>(path, args); auto policy = MinimalTestcasePolicy(); Sandbox2 s2(std::move(executor), std::move(policy)); auto result = s2.Run(); ASSERT_THAT(result.final_status(), Eq(Result::OK)); EXPECT_THAT(result.reason_code(), Eq(EXIT_SUCCESS)); } // Test that we can sandbox a minimal non-static binary returning 0. TEST(MinimalTest, MinimalSharedBinaryWorks) { SKIP_SANITIZERS_AND_COVERAGE; const std::string path = GetTestSourcePath("sandbox2/testcases/minimal_dynamic"); std::vector<std::string> args = {path}; auto executor = absl::make_unique<Executor>(path, args); auto policy = PolicyBuilder() .AllowDynamicStartup() .AllowOpen() .AllowExit() .AllowMmap() #ifdef __NR_access // New glibc accesses /etc/ld.so.preload .BlockSyscallWithErrno(__NR_access, ENOENT) #endif .BlockSyscallWithErrno(__NR_prlimit64, EPERM) .AddLibrariesForBinary(path) .BuildOrDie(); Sandbox2 s2(std::move(executor), std::move(policy)); auto result = s2.Run(); ASSERT_THAT(result.final_status(), Eq(Result::OK)); EXPECT_THAT(result.reason_code(), Eq(EXIT_SUCCESS)); } // Test that the AllowSystemMalloc helper works as expected. TEST(MallocTest, SystemMallocWorks) { SKIP_SANITIZERS_AND_COVERAGE; const std::string path = GetTestSourcePath("sandbox2/testcases/malloc_system"); std::vector<std::string> args = {path}; auto executor = absl::make_unique<Executor>(path, args); auto policy = PolicyBuilder() .AllowStaticStartup() .AllowSystemMalloc() .AllowExit() .BlockSyscallWithErrno(__NR_prlimit64, EPERM) #ifdef __NR_access .BlockSyscallWithErrno(__NR_access, ENOENT) #endif .BuildOrDie(); Sandbox2 s2(std::move(executor), std::move(policy)); auto result = s2.Run(); ASSERT_THAT(result.final_status(), Eq(Result::OK)); EXPECT_THAT(result.reason_code(), Eq(EXIT_SUCCESS)); } // Complicated test to see that AddPolicyOnSyscalls work as // expected. Specifically a worrisome corner-case would be that the logic was // almost correct, but that the jump targets were off slightly. This uses the // AddPolicyOnSyscall multiple times in a row to make any miscalculation // unlikely to pass this check. TEST(MultipleSyscalls, AddPolicyOnSyscallsWorks) { SKIP_SANITIZERS_AND_COVERAGE; const std::string path = GetTestSourcePath("sandbox2/testcases/add_policy_on_syscalls"); std::vector<std::string> args = {path}; auto executor = absl::make_unique<Executor>(path, args); auto policy = PolicyBuilder() #ifdef __NR_open .BlockSyscallWithErrno(__NR_open, ENOENT) #endif .BlockSyscallWithErrno(__NR_openat, ENOENT) .AllowStaticStartup() .AllowTcMalloc() .AllowExit() .AddPolicyOnSyscalls( {__NR_getuid, __NR_getgid, __NR_geteuid, __NR_getegid}, {ALLOW}) .AddPolicyOnSyscalls({__NR_getresuid, __NR_getresgid}, {ERRNO(42)}) .AddPolicyOnSyscalls({__NR_read, __NR_write}, {ERRNO(43)}) .AddPolicyOnSyscall(__NR_umask, {DENY}) .BlockSyscallWithErrno(__NR_prlimit64, EPERM) #ifdef __NR_access .BlockSyscallWithErrno(__NR_access, ENOENT) #endif .BuildOrDie(); Sandbox2 s2(std::move(executor), std::move(policy)); auto result = s2.Run(); ASSERT_THAT(result.final_status(), Eq(Result::VIOLATION)); EXPECT_THAT(result.reason_code(), Eq(__NR_umask)); } } // namespace } // namespace sandbox2
33.506897
78
0.705979
[ "vector" ]
a7d3e693b17e6d9d9b736c5eafac7849583dce8a
3,527
cpp
C++
src/leaf_disk.cpp
mgradysaunders/leaf-disk-gen
955df6c7a37bcec7697c708fe8e0886680075fe4
[ "BSD-2-Clause" ]
1
2020-08-17T15:35:20.000Z
2020-08-17T15:35:20.000Z
src/leaf_disk.cpp
mgradysaunders/leaf-disk-gen
955df6c7a37bcec7697c708fe8e0886680075fe4
[ "BSD-2-Clause" ]
null
null
null
src/leaf_disk.cpp
mgradysaunders/leaf-disk-gen
955df6c7a37bcec7697c708fe8e0886680075fe4
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (c) 2020 M. Grady Saunders * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * 2. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /*+-+*/ #include <leaf-disk-gen/leaf_disk.hpp> namespace ld { // Write GList instance. void LeafDisk::writeGListInstance(std::ostream& ostr) const { // TBN matrix. Mat3<Float> tbn = Mat3<Float>::build_onb(normal); // Write static instance with affine transform. ostr << "<staticinstance>" "<matrix>"; for (int j = 0; j < 3; j++) { ostr << radius * tbn[j][0] << ", "; ostr << radius * tbn[j][1] << ", "; ostr << radius * tbn[j][2] << ", "; ostr << pos[j] << ", "; } ostr << "0, 0, 0, 1" "</matrix>" "</staticinstance>\n"; } // Write OBJ. void LeafDisk::writeObj( std::ostream& ostr, unsigned int& ver_offset, unsigned int ver_res) const { // TBN matrix. Mat3<Float> tbn = Mat3<Float>::build_onb(normal); // Tangential directions. Vec3<Float> hatu = pre::transpose(tbn)[0]; Vec3<Float> hatv = pre::transpose(tbn)[1]; // Write center vertex. ostr << "v "; ostr << pos[0] << ' '; ostr << pos[1] << ' '; ostr << pos[2] << '\n'; // Clamp. if (ver_res < 4) { ver_res = 4; } Float dphi = 2 * pre::numeric_constants<Float>::M_pi() / ver_res; Float area_fac = pre::sqrt(dphi / pre::sin(dphi)); // Preserve area. // Write vertices. for (unsigned int j = 0; j < ver_res; j++) { Float phi = j * dphi; Vec3<Float> ver = (area_fac * radius * pre::cos(phi)) * hatu + (area_fac * radius * pre::sin(phi)) * hatv + pos; ostr << "v "; ostr << ver[0] << ' '; ostr << ver[1] << ' '; ostr << ver[2] << '\n'; } // Write triangles. for (unsigned int j = 0; j < ver_res; j++) { unsigned int v0 = 0 + ver_offset; unsigned int v1 = 1 + (j + 0) % ver_res + ver_offset; unsigned int v2 = 1 + (j + 1) % ver_res + ver_offset; ostr << "f "; ostr << v0 + 1 << ' '; ostr << v1 + 1 << ' '; ostr << v2 + 1 << '\n'; } // Bump vertex offset. ver_offset += ver_res + 1; } } // namespace ld
31.491071
77
0.586901
[ "transform" ]
a7d58f2d78702d733b9af046578c8460745888ce
73,006
cpp
C++
grasp_generation/graspitmodified_lm/Coin-3.1.3/src/misc/SoGLImage.cpp
KraftOreo/EBM_Hand
9ab1722c196b7eb99b4c3ecc85cef6e8b1887053
[ "MIT" ]
null
null
null
grasp_generation/graspitmodified_lm/Coin-3.1.3/src/misc/SoGLImage.cpp
KraftOreo/EBM_Hand
9ab1722c196b7eb99b4c3ecc85cef6e8b1887053
[ "MIT" ]
null
null
null
grasp_generation/graspitmodified_lm/Coin-3.1.3/src/misc/SoGLImage.cpp
KraftOreo/EBM_Hand
9ab1722c196b7eb99b4c3ecc85cef6e8b1887053
[ "MIT" ]
null
null
null
/**************************************************************************\ * * This file is part of the Coin 3D visualization library. * Copyright (C) by Kongsberg Oil & Gas Technologies. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * ("GPL") version 2 as published by the Free Software Foundation. * See the file LICENSE.GPL at the root directory of this source * distribution for additional information about the GNU GPL. * * For using Coin with software that can not be combined with the GNU * GPL, and for taking advantage of the additional benefits of our * support services, please contact Kongsberg Oil & Gas Technologies * about acquiring a Coin Professional Edition License. * * See http://www.coin3d.org/ for more information. * * Kongsberg Oil & Gas Technologies, Bygdoy Alle 5, 0257 Oslo, NORWAY. * http://www.sim.no/ sales@sim.no coin-support@coin3d.org * \**************************************************************************/ // FIXME: in my not so humble opinion, this class is an ugly mess -- // or at least its interface. // // Some examples: there are *4* functions named "setData()" -- which // should throw up a huge red warning sign alone. Methods named // "setData()" and "setFlags()" (the latter which we also have in // SoGLImage) should make API designers cringe. There's a whole bunch // of *public* methods marked as being *private* and *internal* -- // another warning sign. The setData() method that creates a 2D // texture object simply calls into the method that makes a 3D texture // object, while the obvious right thing to do would be to refactor // common code to private methods. // // Since this was made part of the public API of Coin 2, I guess we'll // have to support it until the end of time, or at least a couple of // major versions down the road. What we should do with it is to mark // it as obsolete, then refactor the functionality out of it, // preferably into a nice, *clean* little C API to complement the // stuff contained in cc_glglue_*(), then convert all internal code to // use that instead. // // 20030312 mortene. // ************************************************************************* // FIXME: Add TEX3 enviroment variables (or general TEX variables?) // (kintel 20011112) // ************************************************************************* /*! \class SoGLImage include/Inventor/misc/SoGLImage.h \brief The SoGLImage class is used to handle OpenGL 2D/3D textures. A number of environment variables can be set to control how textures are created. This is useful to tune Coin to fit your system. E.g. if you are running on a laptop, it might be a good idea to disable linear filtering and mipmaps. \li COIN_TEX2_LINEAR_LIMIT: Linear filtering is enabled if Complexity::textureQuality is greater or equal to this value. Default value is 0.2. \li COIN_TEX2_MIPMAP_LIMIT: Mipmaps are created if textureQuality is greater or equal to this value. Default value is 0.5. \li COIN_TEX2_LINEAR_MIPMAP_LIMIT: Linear filtering between mipmap levels is enabled if textureQuality is greater or equal to this value. Default value is 0.8. \li COIN_TEX2_SCALEUP_LIMIT: Textures with width or height not equal to a power of two will always be scaled up if textureQuality is greater or equal to this value. Default value is 0.7. If textureQuality is lower than this value, and the width or height is larger than 256 pixels, the texture is only scaled up if it's relatively close to the next power of two size. This could save a lot of texture memory. \li COIN_TEX2_USE_GLTEXSUBIMAGE: When set, and when the new texture data has the same attributes as the old data, glTexSubImage() will be used to copy new data into the texture instead of recreating the texture. This is not enabled by default, since it seems to trigger a bug in the Linux nVidia drivers. It just happens in some unreproducable cases. It could be a bug in our glTexSubImage() code, of course. :) \li COIN_TEX2_USE_SGIS_GENERATE_MIPMAP: When set, use the GL_SGIS_generate_mip extension (if available) to generate mipmaps, otherwise use a fast internal routine to generate them. Use of SGIS_generate_mipmap is not enabled by default since we suspect some ATi drivers have problems with this extensions. \li COIN_ENABLE_CONFORMANT_GL_CLAMP: When set, GL_CLAMP will be used when SoGLImage::CLAMP is specified as the texture wrap mode. By default GL_CLAMP_TO_EDGE is used, since this is usually what people want. See http://www.opengl.org/discussion_boards/ubb/Forum3/HTML/007306.html for a discussion regarding GL_CLAMP and GL_CLAMP_TO_EDGE. \li COIN_TEX2_ANISOTROPIC_LIMIT: Anisotropic filtering is enabled for textures when the texture quality is higher than this value. Default value is 0.85 \COIN_CLASS_EXTENSION \since Coin 2.0 */ // ************************************************************************* /*! \enum SoGLImage::Wrap Used to specify how texture coordinates < 0.0 and > 1.0 should be handled. It can either be repeated (REPEAT), clamped (CLAMP) or clamped to edge (CLAMP_TO_EDGE), which is useful when tiling textures. Since 2002-11-18, CLAMP will be treated as CLAMP_TO_EDGE. The environment variable COIN_ENABLE_CONFORMANT_GL_CLAMP can be used to override this behaviour. */ /*! \enum SoGLImage::ResizeReason Sent as a parameter to SoGLImageResizeCB as a hint to why an image is being resized. IMAGE means that a whole image is being initially resized (e.g. a texture image). SUBIMAGE and MIPMAP are not in use and reserved for future use. */ /*! \enum SoGLImage::Flags Can be used to tune/optimize the GL texture handling. Normally the texture quality will be used to decide scaling and filtering, and the image data will be scanned to decide if the image is (partly) transparent, and if the texture can be rendered using the cheaper alpha test instead of blending if it does contain transparency. If you know the contents of your texture image, or if you have special requirements on how the texture should be rendered, you can set the flags using the SoGLImage::setFlags() method. */ // FIXME: Support other reason values than IMAGE (kintel 20050531) /*! \typedef bool SoGLImage::SoGLImageResizeCB(SoState * state, const SbVec3s &newsize, unsigned char * destbuffer, SoGLImage::ResizeReason reason, void * closure, class SoGLImage * image) Image resize callback type. If registered using setResizeCallback(), this function will be called whenever Coin needs to resize an image. The function will be called both for 2D and 3D images. \e state is the current state at the time of resizing. \e newsize is the requested new image size. Note that the z size of a 2D image is 0. \e destbuffer is a pre-allocated buffer big enough to hold the pixels for the resized image. The # of bytes per pixel is the same as for the original image. \e reason is a hint about why the image is resized. At the moment, only IMAGE is supported. \e image is the original image. Return value: TRUE if the resize ahs been resized, FALSE if not. If FALSE is returned, Coin will resize the image instead. */ // ************************************************************************* #include <Inventor/misc/SoGLImage.h> #include <cassert> #include <list> #include <cstdio> #include <cstdlib> #include <cstring> #include <utility> #ifdef HAVE_CONFIG_H #include "config.h" #endif // HAVE_CONFIG_H #include <Inventor/C/glue/gl.h> #include <Inventor/C/tidbits.h> #include <Inventor/SbImage.h> #include <Inventor/actions/SoGLRenderAction.h> #include <Inventor/elements/SoGLCacheContextElement.h> #include <Inventor/elements/SoGLDisplayList.h> #include <Inventor/elements/SoGLTexture3EnabledElement.h> #include <Inventor/elements/SoGLTextureImageElement.h> #include <Inventor/elements/SoTextureQualityElement.h> #include <Inventor/errors/SoDebugError.h> #include <Inventor/lists/SbList.h> #include <Inventor/system/gl.h> #include <Inventor/threads/SbStorage.h> #include <Inventor/misc/SoContextHandler.h> #include <Inventor/misc/SoGLCubeMapImage.h> #include <Inventor/misc/SoGLDriverDatabase.h> #ifdef COIN_THREADSAFE #include <Inventor/threads/SbMutex.h> #endif // COIN_THREADSAFE #include "tidbitsp.h" #include "misc/SoGL.h" #include "elements/SoTextureScaleQualityElement.h" #include "glue/GLUWrapper.h" #include "glue/glp.h" #include "glue/simage_wrapper.h" #include "threads/threadsutilp.h" #include "coindefs.h" #if COIN_WORKAROUND(COIN_MSVC, <= COIN_MSVC_6_0_VERSION) // truncating symbol length #pragma warning(disable:4786) #endif // VC6.0 // ************************************************************************* static float DEFAULT_LINEAR_LIMIT = 0.2f; static float DEFAULT_MIPMAP_LIMIT = 0.5f; static float DEFAULT_LINEAR_MIPMAP_LIMIT = 0.8f; static float DEFAULT_SCALEUP_LIMIT = 0.7f; static float DEFAULT_ANISOTROPIC_LIMIT = 0.85f; static float COIN_TEX2_LINEAR_LIMIT = -1.0f; static float COIN_TEX2_MIPMAP_LIMIT = -1.0f; static float COIN_TEX2_LINEAR_MIPMAP_LIMIT = -1.0f; static float COIN_TEX2_SCALEUP_LIMIT = -1.0f; static float COIN_TEX2_ANISOTROPIC_LIMIT = -1.0f; static int COIN_TEX2_USE_GLTEXSUBIMAGE = -1; static int COIN_TEX2_USE_SGIS_GENERATE_MIPMAP = -1; static int COIN_ENABLE_CONFORMANT_GL_CLAMP = -1; // ************************************************************************* // buffer used for creating mipmap images static SbStorage * glimage_bufferstorage = NULL; typedef struct { unsigned char * buffer; int buffersize; unsigned char * mipmapbuffer; int mipmapbuffersize; } soglimage_buffer; static void glimage_buffer_construct(void * buffer) { soglimage_buffer * buf = (soglimage_buffer*) buffer; buf->buffer = NULL; buf->buffersize = 0; buf->mipmapbuffer = NULL; buf->mipmapbuffersize = 0; } static void glimage_buffer_destruct(void * buffer) { soglimage_buffer * buf = (soglimage_buffer*) buffer; delete[] buf->buffer; delete[] buf->mipmapbuffer; } static unsigned char * glimage_get_buffer(const int buffersize, const SbBool mipmap) { soglimage_buffer * buf = NULL; assert(glimage_bufferstorage != NULL); buf = (soglimage_buffer*) glimage_bufferstorage->get(); if (mipmap) { if (buf->mipmapbuffersize < buffersize) { delete[] buf->mipmapbuffer; buf->mipmapbuffer = new unsigned char[buffersize]; buf->mipmapbuffersize = buffersize; } return buf->mipmapbuffer; } else { if (buf->buffersize < buffersize) { delete[] buf->buffer; buf->buffer = new unsigned char[buffersize]; buf->buffersize = buffersize; // FIXME: this is an extremely lame workaround for a Purify UMR // reported by Tore Kristiansen of HitecO. // // An UMR is reported from buf->buffer (when disabling the // memset() workaround below) from somewhere within the // fast_mipmap() method. Purify doesn't go far enough down the // call-stack (probably because fast_mipmap() is a local static // method?) for us to easily see where the exact error happens, // though. // // My guess is that the mipmap-buffer isn't completely "filled // out", and so the glTex[Sub]Image2D() call asks for more // pixels than was generated. // // Should try to get this problem reproduced locally before // attempting to fix it. // // 20030514 mortene. (void)memset(buf->buffer, 0x55, buf->buffersize); } return buf->buffer; } } // ************************************************************************* static int compute_log(int value) { int i = 0; while (value > 1) { value>>=1; i++; } return i; } //FIXME: Use as a special case of 3D image to reduce codelines ? (kintel 20011115) static void halve_image(const int width, const int height, const int nc, const unsigned char *datain, unsigned char *dataout) { assert(width > 1 || height > 1); int nextrow = width *nc; int newwidth = width >> 1; int newheight = height >> 1; unsigned char *dst = dataout; const unsigned char *src = datain; // check for 1D images if (width == 1 || height == 1) { int n = SbMax(newwidth, newheight); for (int i = 0; i < n; i++) { for (int j = 0; j < nc; j++) { *dst = (src[0] + src[nc]) >> 1; dst++; src++; } src += nc; // skip to next pixel } } else { for (int i = 0; i < newheight; i++) { for (int j = 0; j < newwidth; j++) { for (int c = 0; c < nc; c++) { *dst = (src[0] + src[nc] + src[nextrow] + src[nextrow+nc] + 2) >> 2; dst++; src++; } src += nc; // skip to next pixel } src += nextrow; } } } static void halve_image(const int width, const int height, const int depth, const int nc, const unsigned char *datain, unsigned char *dataout) { assert(width > 1 || height > 1 || depth > 1); int rowsize = width * nc; int imagesize = width * height * nc; int newwidth = width >> 1; int newheight = height >> 1; int newdepth = depth >> 1; unsigned char *dst = dataout; const unsigned char *src = datain; int numdims = (width>=1?1:0)+(height>=1?1:0)+(depth>=1?1:0); // check for 1D images. if (numdims == 1) { int n = SbMax(SbMax(newwidth, newheight), newdepth); for (int i = 0; i < n; i++) { for (int j = 0; j < nc; j++) { *dst = (src[0] + src[nc]) >> 1; dst++; src++; } src += nc; // skip to next pixel/row/image } } // check for 2D images else if (numdims == 2) { int s1,s2,blocksize; if (width==1) { s1 = newheight; blocksize = height * nc; } else { s1 = newwidth; blocksize = width * nc; } s2 = depth==1?newheight:newdepth; for (int j = 0; j < s2; j++) { for (int i = 0; i < s1; i++) { for (int j = 0; j < nc; j++) { *dst = (src[0] + src[nc] + src[blocksize] + src[blocksize+nc] + 2) >> 2; dst++; src++; } src += nc; // skip to next pixel (x or y direction) } src += blocksize; // Skip to next row/image } } else { // 3D image for (int k = 0; k < newdepth; k++) { for (int j = 0; j < newheight; j++) { for (int i = 0; i < newwidth; i++) { for (int c = 0; c < nc; c++) { *dst = (src[0] + src[nc] + src[rowsize] + src[rowsize+nc] + src[imagesize] + src[imagesize+nc] + src[imagesize+rowsize] + src[imagesize+rowsize+nc] + 4) >> 3; dst++; src++; } src += nc; // skip one pixel } src += rowsize; // skip one row } src += imagesize; // skip one image } } } // fast mipmap creation. no repeated memory allocations. static void fast_mipmap(SoState * state, int width, int height, int nc, const unsigned char *data, const SbBool useglsubimage, SbBool compress) { const cc_glglue * glw = sogl_glue_instance(state); GLint internalFormat = coin_glglue_get_internal_texture_format(glw, nc, compress); GLenum format = coin_glglue_get_texture_format(glw, nc); int levels = compute_log(width); int level = compute_log(height); if (level > levels) levels = level; int memreq = (SbMax(width>>1,1))*(SbMax(height>>1,1))*nc; unsigned char * mipmap_buffer = glimage_get_buffer(memreq, TRUE); if (useglsubimage) { if (SoGLDriverDatabase::isSupported(glw, SO_GL_TEXSUBIMAGE)) { cc_glglue_glTexSubImage2D(glw, GL_TEXTURE_2D, 0, 0, 0, width, height, format, GL_UNSIGNED_BYTE, data); } } else { glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, width, height, 0, format, GL_UNSIGNED_BYTE, data); } unsigned char *src = (unsigned char *) data; for (level = 1; level <= levels; level++) { halve_image(width, height, nc, src, mipmap_buffer); if (width > 1) width >>= 1; if (height > 1) height >>= 1; src = mipmap_buffer; if (useglsubimage) { if (SoGLDriverDatabase::isSupported(glw, SO_GL_TEXSUBIMAGE)) { cc_glglue_glTexSubImage2D(glw, GL_TEXTURE_2D, level, 0, 0, width, height, format, GL_UNSIGNED_BYTE, (void*) src); } } else { glTexImage2D(GL_TEXTURE_2D, level, internalFormat, width, height, 0, format, GL_UNSIGNED_BYTE, (void *) src); } } } // fast mipmap creation. no repeated memory allocations. 3D version. static void fast_mipmap(SoState * state, int width, int height, int depth, int nc, const unsigned char *data, const SbBool useglsubimage, SbBool compress) { const cc_glglue * glw = sogl_glue_instance(state); GLint internalFormat = coin_glglue_get_internal_texture_format(glw, nc, compress); GLenum format = coin_glglue_get_texture_format(glw, nc); int levels = compute_log(SbMax(SbMax(width, height), depth)); int memreq = (SbMax(width>>1,1))*(SbMax(height>>1,1))*(SbMax(depth>>1,1))*nc; unsigned char * mipmap_buffer = glimage_get_buffer(memreq, TRUE); // Send level 0 (original image) to OpenGL if (useglsubimage) { if (SoGLDriverDatabase::isSupported(glw, SO_GL_3D_TEXTURES)) { cc_glglue_glTexSubImage3D(glw, GL_TEXTURE_3D, 0, 0, 0, 0, width, height, depth, format, GL_UNSIGNED_BYTE, data); } } else { if (SoGLDriverDatabase::isSupported(glw, SO_GL_3D_TEXTURES)) { cc_glglue_glTexImage3D(glw, GL_TEXTURE_3D, 0, internalFormat, width, height, depth, 0, format, GL_UNSIGNED_BYTE, data); } } unsigned char *src = (unsigned char *) data; for (int level = 1; level <= levels; level++) { halve_image(width, height, depth, nc, src, mipmap_buffer); if (width > 1) width >>= 1; if (height > 1) height >>= 1; if (depth > 1) depth >>= 1; src = mipmap_buffer; if (useglsubimage) { if (SoGLDriverDatabase::isSupported(glw, SO_GL_3D_TEXTURES)) { cc_glglue_glTexSubImage3D(glw, GL_TEXTURE_3D, level, 0, 0, 0, width, height, depth, format, GL_UNSIGNED_BYTE, (void*) src); } } else { if (SoGLDriverDatabase::isSupported(glw, SO_GL_3D_TEXTURES)) { cc_glglue_glTexImage3D(glw, GL_TEXTURE_3D, level, internalFormat, width, height, depth, 0, format, GL_UNSIGNED_BYTE, (void *) src); } } } } // A low quality resize function. It is only used when neither simage // nor GLU is available. static void fast_image_resize(const unsigned char * src, unsigned char * dest, int width, int height, int num_comp, int newwidth, int newheight) { float sx, sy, dx, dy; int src_bpr, dest_bpr, xstop, ystop, x, y, offset, i; dx = ((float)width)/((float)newwidth); dy = ((float)height)/((float)newheight); src_bpr = width * num_comp; dest_bpr = newwidth * num_comp; sy = 0.0f; ystop = newheight * dest_bpr; xstop = newwidth * num_comp; for (y = 0; y < ystop; y += dest_bpr) { sx = 0.0f; for (x = 0; x < xstop; x += num_comp) { offset = ((int)sy)*src_bpr + ((int)sx)*num_comp; for (i = 0; i < num_comp; i++) dest[x+y+i] = src[offset+i]; sx += dx; } sy += dy; } } // A low quality resize function for 3D texture image buffers. It is // only used when neither simage nor GLU is available. static void fast_image_resize3d(const unsigned char * src, unsigned char * dest, int width, int height, int nc, int layers, int newwidth, int newheight, int newlayers) { float sx, sy, sz, dx, dy, dz; int src_bpr, dest_bpr, src_bpl, dest_bpl, xstop, ystop, zstop; int x, y, z, offset, i; dx = ((float)width)/((float)newwidth); dy = ((float)height)/((float)newheight); dz = ((float)layers)/((float)newlayers); src_bpr = width * nc; dest_bpr = newwidth * nc; src_bpl = src_bpr * height; dest_bpl = dest_bpr * newheight; zstop = newlayers * dest_bpl; ystop = dest_bpl; xstop = dest_bpr; sz = 0.0f; for (z = 0; z < zstop; z += dest_bpl) { sy = 0.0f; for (y = 0; y < ystop; y += dest_bpr) { sx = 0.0f; for (x = 0; x < xstop; x += nc) { offset = ((int)sz)*src_bpl + ((int)sy)*src_bpr + ((int)sx)*nc; for (i = 0; i < nc; i++) dest[x+y+z+i] = src[offset+i]; sx += dx; } sy += dy; } sz += dz; } } // ************************************************************************* class SoGLImageP { public: #ifdef COIN_THREADSAFE static SbMutex * mutex; #endif // COIN_THREADSAFE static SoType classTypeId; static uint32_t current_glimageid; static uint32_t getNextGLImageId(void); SoGLDisplayList *createGLDisplayList(SoState *state); void checkTransparency(void); void unrefDLists(SoState *state); void reallyCreateTexture(SoState *state, const unsigned char *const texture, const int numComponents, const int w, const int h, const int d, const SbBool dlist, const SbBool mipmap, const int border); void reallyBindPBuffer(SoState *state); void resizeImage(SoState * state, unsigned char *&imageptr, uint32_t &xsize, uint32_t &ysize, uint32_t &zsize); SbBool shouldCreateMipmap(void); void applyFilter(const SbBool ismipmap); void * pbuffer; const SbImage *image; SbImage dummyimage; SbVec3s glsize; int glcomp; SbBool needtransparencytest; SbBool hastransparency; SbBool usealphatest; uint32_t flags; float quality; SoGLImage::Wrap wraps; SoGLImage::Wrap wrapt; SoGLImage::Wrap wrapr; int border; SbBool isregistered; uint32_t imageage; void (*endframecb)(void*); void *endframeclosure; class dldata { public: dldata(void) : dlist(NULL), age(0) { } dldata(SoGLDisplayList *dl) : dlist(dl), age(0) { } dldata(const dldata & org) : dlist(org.dlist), age(org.age) { } SoGLDisplayList *dlist; uint32_t age; }; SbList <dldata> dlists; SoGLDisplayList *findDL(SoState *state); void tagDL(SoState *state); void unrefOldDL(SoState *state, const uint32_t maxage); SoGLImage *owner; uint32_t glimageid; void init(void); static void contextCleanup(uint32_t context, void * closure); static SoGLImage::SoGLImageResizeCB * resizecb; static void * resizeclosure; }; SoType SoGLImageP::classTypeId STATIC_SOTYPE_INIT; uint32_t SoGLImageP::current_glimageid = 1; SoGLImage::SoGLImageResizeCB * SoGLImageP::resizecb = NULL; void * SoGLImageP::resizeclosure = NULL; #ifdef COIN_THREADSAFE SbMutex * SoGLImageP::mutex; #endif // COIN_THREADSAFE #undef PRIVATE #define PRIVATE(p) ((p)->pimpl) // ************************************************************************* // This class is not 100% threadsafe. It is threadsafe for rendering // only. It is assumed that setData() is called by only one thread at // a time. The reason for this is that all threads should use the same // data, and it would be meaningless if two threads set different data // for an SoGLImage. The nodes using SoGLImage should use a mutex to // ensure that only one thread calls setData(), the other threads // should wait for that thread to finish. This is done in Coin now. // // SoGLImage::getGLDisplayList() use a mutex so that several // threads can call this method safely. // we now share one mutex among all glimages to avoid allocating too // many mutexes. #ifdef COIN_THREADSAFE #define LOCK_GLIMAGE SoGLImageP::mutex->lock() #define UNLOCK_GLIMAGE SoGLImageP::mutex->unlock() #else // COIN_THREADSAFE #define LOCK_GLIMAGE #define UNLOCK_GLIMAGE #endif // !COIN_THREADSAFE // ************************************************************************* /*! Constructor. */ SoGLImage::SoGLImage(void) { PRIVATE(this) = new SoGLImageP; SoContextHandler::addContextDestructionCallback(SoGLImageP::contextCleanup, PRIVATE(this)); PRIVATE(this)->isregistered = FALSE; PRIVATE(this)->init(); // init members to default values PRIVATE(this)->owner = this; // check environment variables if (COIN_TEX2_LINEAR_LIMIT < 0.0f) { const char *env = coin_getenv("COIN_TEX2_LINEAR_LIMIT"); if (env) COIN_TEX2_LINEAR_LIMIT = (float) atof(env); if (COIN_TEX2_LINEAR_LIMIT < 0.0f || COIN_TEX2_LINEAR_LIMIT > 1.0f) { COIN_TEX2_LINEAR_LIMIT = DEFAULT_LINEAR_LIMIT; } } if (COIN_TEX2_MIPMAP_LIMIT < 0.0f) { const char *env = coin_getenv("COIN_TEX2_MIPMAP_LIMIT"); if (env) COIN_TEX2_MIPMAP_LIMIT = (float) atof(env); if (COIN_TEX2_MIPMAP_LIMIT < 0.0f || COIN_TEX2_MIPMAP_LIMIT > 1.0f) { COIN_TEX2_MIPMAP_LIMIT = DEFAULT_MIPMAP_LIMIT; } } if (COIN_TEX2_LINEAR_MIPMAP_LIMIT < 0.0f) { const char *env = coin_getenv("COIN_TEX2_LINEAR_MIPMAP_LIMIT"); if (env) COIN_TEX2_LINEAR_MIPMAP_LIMIT = (float) atof(env); if (COIN_TEX2_LINEAR_MIPMAP_LIMIT < 0.0f || COIN_TEX2_LINEAR_MIPMAP_LIMIT > 1.0f) { COIN_TEX2_LINEAR_MIPMAP_LIMIT = DEFAULT_LINEAR_MIPMAP_LIMIT; } } if (COIN_TEX2_SCALEUP_LIMIT < 0.0f) { const char *env = coin_getenv("COIN_TEX2_SCALEUP_LIMIT"); if (env) COIN_TEX2_SCALEUP_LIMIT = (float) atof(env); if (COIN_TEX2_SCALEUP_LIMIT < 0.0f || COIN_TEX2_SCALEUP_LIMIT > 1.0f) { COIN_TEX2_SCALEUP_LIMIT = DEFAULT_SCALEUP_LIMIT; } } if (COIN_TEX2_USE_GLTEXSUBIMAGE < 0) { const char *env = coin_getenv("COIN_TEX2_USE_GLTEXSUBIMAGE"); if (env && atoi(env) == 1) { COIN_TEX2_USE_GLTEXSUBIMAGE = 1; } else COIN_TEX2_USE_GLTEXSUBIMAGE = 0; } if (COIN_TEX2_USE_SGIS_GENERATE_MIPMAP < 0) { const char *env = coin_getenv("COIN_TEX2_USE_SGIS_GENERATE_MIPMAP"); if (env && atoi(env) == 1) { COIN_TEX2_USE_SGIS_GENERATE_MIPMAP = 1; } else COIN_TEX2_USE_SGIS_GENERATE_MIPMAP = 0; } if (COIN_ENABLE_CONFORMANT_GL_CLAMP < 0) { const char * env = coin_getenv("COIN_ENABLE_CONFORMANT_GL_CLAMP"); if (env && atoi(env) == 1) { COIN_ENABLE_CONFORMANT_GL_CLAMP = 1; } else COIN_ENABLE_CONFORMANT_GL_CLAMP = 0; } if (COIN_TEX2_ANISOTROPIC_LIMIT < 0.0f) { const char *env = coin_getenv("COIN_TEX2_ANISOTROPIC_LIMIT"); if (env) COIN_TEX2_ANISOTROPIC_LIMIT = (float) atof(env); else COIN_TEX2_ANISOTROPIC_LIMIT = DEFAULT_ANISOTROPIC_LIMIT; } } /*! \COININTERNAL */ void SoGLImage::initClass(void) { assert(SoGLImageP::classTypeId.isBad()); SoGLImageP::classTypeId = SoType::createType(SoType::badType(), SbName("GLImage")); #ifdef COIN_THREADSAFE SoGLImageP::mutex = new SbMutex; #endif // COIN_THREADSAFE glimage_bufferstorage = new SbStorage(sizeof(soglimage_buffer), glimage_buffer_construct, glimage_buffer_destruct); coin_atexit((coin_atexit_f*)SoGLImage::cleanupClass, CC_ATEXIT_NORMAL); SoGLCubeMapImage::initClass(); } // // called by atexit() // void SoGLImage::cleanupClass(void) { delete glimage_bufferstorage; glimage_bufferstorage = NULL; #ifdef COIN_THREADSAFE delete SoGLImageP::mutex; SoGLImageP::mutex = NULL; #endif // COIN_THREADSAFE SoGLImageP::classTypeId STATIC_SOTYPE_INIT; SoGLImageP::resizecb = NULL; SoGLImageP::resizeclosure = NULL; SoGLImageP::current_glimageid = 1; } /*! Returns the type id for this class. */ SoType SoGLImage::getClassTypeId(void) { assert(!SoGLImageP::classTypeId.isBad()); return SoGLImageP::classTypeId; } // FIXME: grab better version of getTypeId() doc from SoBase, SoAction // and / or SoDetail? At least if this ever makes it into the public // API. 20010913 mortene. /*! Returns the type id for an SoGLImage instance. */ SoType SoGLImage::getTypeId(void) const { return SoGLImage::getClassTypeId(); } /*! Returns whether an SoGLImage instance inherits (or is of) type \a type. */ SbBool SoGLImage::isOfType(SoType type) const { return this->getTypeId().isDerivedFrom(type); } /*! Can be used for creating a custom OpenGL texture inside an SoGLImage instance. Example use (creates a depth texture): SoGLDisplayList * depthmap = new SoGLDisplayList(state, SoGLDisplayList::TEXTURE_OBJECT); depthmap->ref(); depthmap->open(state); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, // GL_DEPTH_COMPONENT24 size[0], size[1], 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); depthmap->close(state); SoGLImage * image = new SoGLImage; image->setGLDisplayList(depthmap, state); \since Coin 2.5 */ void SoGLImage::setGLDisplayList(SoGLDisplayList * dl, SoState * state, const Wrap wraps, const Wrap wrapt, const float quality) { if (PRIVATE(this)->isregistered) SoGLImage::unregisterImage(this); PRIVATE(this)->unrefDLists(state); dl->ref(); PRIVATE(this)->dlists.append(SoGLImageP::dldata(dl)); PRIVATE(this)->image = NULL; // we have no data. Texture is organized outside this image PRIVATE(this)->wraps = wraps; PRIVATE(this)->wrapt = wrapt; PRIVATE(this)->glimageid = SoGLImageP::getNextGLImageId(); // assign an unique id to this image PRIVATE(this)->needtransparencytest = FALSE; PRIVATE(this)->hastransparency = FALSE; PRIVATE(this)->usealphatest = FALSE; PRIVATE(this)->quality = quality; // don't register this image. There's no way we can reload it if we // delete it because of old age. } /*! Sets the pbuffer for this texture. Experimental code, use with care. */ void SoGLImage::setPBuffer(SoState * state, void * pbuffer, const Wrap wraps, const Wrap wrapt, const float quality) { if (PRIVATE(this)->pbuffer && state) { // bind texture before releasing pbuffer this->getGLDisplayList(state)->call(state); cc_glglue_context_release_pbuffer(PRIVATE(this)->pbuffer); } if (PRIVATE(this)->isregistered) SoGLImage::unregisterImage(this); PRIVATE(this)->unrefDLists(state); PRIVATE(this)->init(); // init to default values if (pbuffer) { PRIVATE(this)->pbuffer = pbuffer; PRIVATE(this)->wraps = wraps; PRIVATE(this)->wrapt = wrapt; PRIVATE(this)->glimageid = SoGLImageP::getNextGLImageId(); // assign an unique id to this image PRIVATE(this)->needtransparencytest = TRUE; PRIVATE(this)->hastransparency = FALSE; PRIVATE(this)->usealphatest = FALSE; PRIVATE(this)->quality = quality; if (PRIVATE(this)->pbuffer && !PRIVATE(this)->isregistered && !(this->getFlags() & INVINCIBLE)) { SoGLImage::registerImage(this); } } } /*! Convenience 2D wrapper function around the 3D setData(). */ void SoGLImage::setData(const SbImage * image, const Wrap wraps, const Wrap wrapt, const float quality, const int border, SoState * createinstate) { this->setData(image, wraps, wrapt, (Wrap)PRIVATE(this)->wrapr, quality, border, createinstate); } /*! Sets the data for this GL image. Should only be called when one of the parameters have changed, since this will cause the GL texture object to be recreated. Caller is responsible for sending legal Wrap values. CLAMP_TO_EDGE is only supported on OpenGL v1.2 implementations, and as an extension on some earlier SGI implementations (GL_SGIS_texture_edge_clamp). For now, if quality > 0.5 when created, we create mipmaps, otherwise a regular texture is created. Be aware, if you for instance create a texture with texture quality 0.4, and then later try to apply the texture with a texture quality greater than 0.5, the texture object will be recreated as a mipmap texture object. This will happen only once though, of course. If \a border != 0, the OpenGL texture will be created with this border size. Be aware that this might be extremely slow on most PC hardware. Normally, the OpenGL texture object isn't created until the first time it is needed, but if \a createinstate is != NULL, the texture object is created immediately. This is useful if you use a temporary buffer to hold the texture data. Be careful when using this feature, since the texture data might be needed at a later stage (for instance to create a texture object for another context). It will not be possible to create texture objects for other cache contexts when \a createinstate is != NULL. Also if \a createinstate is supplied, and all the attributes are the same as the current data in the image, glTexSubImage() will be used to insert the image data instead of creating a new texture object. This is much faster on most OpenGL drivers, and is very useful, for instance when doing animated textures. If you supply NULL for \a image, the instance will be reset, causing all display lists and memory to be freed. */ void SoGLImage::setData(const SbImage *image, const Wrap wraps, const Wrap wrapt, const Wrap wrapr, const float quality, const int border, SoState *createinstate) { PRIVATE(this)->imageage = 0; if (image == NULL) { PRIVATE(this)->unrefDLists(createinstate); if (PRIVATE(this)->isregistered) SoGLImage::unregisterImage(this); PRIVATE(this)->init(); // init to default values return; } PRIVATE(this)->glimageid = SoGLImageP::getNextGLImageId(); // assign an unique id to this image PRIVATE(this)->needtransparencytest = TRUE; PRIVATE(this)->hastransparency = FALSE; PRIVATE(this)->usealphatest = FALSE; PRIVATE(this)->quality = quality; // check for special case where glTexSubImage can be used. // faster for most drivers. if (createinstate) { // We need the state for cc_glglue const cc_glglue * glw = sogl_glue_instance(createinstate); SoGLDisplayList *dl = NULL; SbBool copyok = wraps == PRIVATE(this)->wraps && wrapt == PRIVATE(this)->wrapt && wrapr == PRIVATE(this)->wrapr && border == PRIVATE(this)->border && border == 0 && // haven't tested with borders yet. Play it safe. (dl = PRIVATE(this)->findDL(createinstate)) != NULL; SbVec3s size; int nc; const unsigned char * bytes = image->getValue(size, nc); copyok = copyok && bytes && (size == PRIVATE(this)->glsize) && (nc == PRIVATE(this)->glcomp); SbBool is3D = (size[2]==0)?FALSE:TRUE; SbBool usesubimage = COIN_TEX2_USE_GLTEXSUBIMAGE && ((is3D && SoGLDriverDatabase::isSupported(glw, SO_GL_3D_TEXTURES)) || (!is3D && SoGLDriverDatabase::isSupported(glw, SO_GL_TEXSUBIMAGE))); if (!usesubimage) copyok=FALSE; if (PRIVATE(this)->flags & RECTANGLE) copyok = FALSE; if (copyok) { dl->ref(); PRIVATE(this)->unrefDLists(createinstate); PRIVATE(this)->dlists.append(SoGLImageP::dldata(dl)); PRIVATE(this)->image = NULL; // data is temporary, and only for current context dl->call(createinstate); SbBool compress = (PRIVATE(this)->flags & COMPRESSED) && SoGLDriverDatabase::isSupported(glw, SO_GL_TEXTURE_COMPRESSION); if (dl->isMipMapTextureObject()) { if (is3D) fast_mipmap(createinstate, size[0], size[1], size[2], nc, bytes, TRUE, compress); else fast_mipmap(createinstate, size[0], size[1], nc, bytes, TRUE, compress); } else { GLenum format = coin_glglue_get_texture_format(glw, nc); if (is3D) { cc_glglue_glTexSubImage3D(glw, GL_TEXTURE_3D, 0, 0, 0, 0, size[0], size[1], size[2], format, GL_UNSIGNED_BYTE, (void*) bytes); } else { cc_glglue_glTexSubImage2D(glw, GL_TEXTURE_2D, 0, 0, 0, size[0], size[1], format, GL_UNSIGNED_BYTE, (void*) bytes); } } } else { PRIVATE(this)->image = image; PRIVATE(this)->wraps = wraps; PRIVATE(this)->wrapt = wrapt; PRIVATE(this)->wrapr = wrapr; PRIVATE(this)->border = border; PRIVATE(this)->unrefDLists(createinstate); if (createinstate) { PRIVATE(this)->dlists.append(SoGLImageP::dldata(PRIVATE(this)->createGLDisplayList(createinstate))); PRIVATE(this)->image = NULL; // data is assumed to be temporary } } } else { PRIVATE(this)->image = image; PRIVATE(this)->wraps = wraps; PRIVATE(this)->wrapt = wrapt; PRIVATE(this)->wrapr = wrapr; PRIVATE(this)->border = border; PRIVATE(this)->unrefDLists(createinstate); } if (PRIVATE(this)->image && !PRIVATE(this)->isregistered && !(this->getFlags() & INVINCIBLE)) { SoGLImage::registerImage(this); } } /*! 2D setData() wrapper. Supplies raw data, size and numcomponents instead of an SbImage. Creates a temporary image, then calls the read setData(). \overload */ void SoGLImage::setData(const unsigned char *bytes, const SbVec2s & size, const int numcomponents, const Wrap wraps, const Wrap wrapt, const float quality, const int border, SoState *createinstate) { PRIVATE(this)->dummyimage.setValuePtr(size, numcomponents, bytes); this->setData(&PRIVATE(this)->dummyimage, wraps, wrapt, quality, border, createinstate); } /*! 3D setData() wrapper. Supplies raw data, size and numcomponents instead of an SbImage. Creates a temporary image, then calls the read setData(). \overload */ void SoGLImage::setData(const unsigned char *bytes, const SbVec3s & size, const int numcomponents, const Wrap wraps, const Wrap wrapt, const Wrap wrapr, const float quality, const int border, SoState *createinstate) { PRIVATE(this)->dummyimage.setValuePtr(size, numcomponents, bytes); this->setData(&PRIVATE(this)->dummyimage, wraps, wrapt, wrapr, quality, border, createinstate); } /*! Destructor. */ SoGLImage::~SoGLImage() { SoContextHandler::removeContextDestructionCallback(SoGLImageP::contextCleanup, PRIVATE(this)); if (PRIVATE(this)->isregistered) SoGLImage::unregisterImage(this); PRIVATE(this)->unrefDLists(NULL); delete PRIVATE(this); } /*! This class has a private destuctor since we want users to supply the current GL state when deleting the image. This is to make sure gl texture objects are freed as soon as possible. If you supply NULL to this method, the gl texture objects won't be deleted until the next time an GLRenderAction is applied in the image's cache context(s). */ void SoGLImage::unref(SoState *state) { if (PRIVATE(this)->pbuffer) this->setPBuffer(state, NULL); PRIVATE(this)->unrefDLists(state); delete this; } /*! Sets flags to control how the texture is handled/initialized. */ void SoGLImage::setFlags(const uint32_t flags) { PRIVATE(this)->flags = flags; } /*! Returns the flags. \sa setFlags() */ uint32_t SoGLImage::getFlags(void) const { return PRIVATE(this)->flags; } /*! Returns a pointer to the image data. */ const SbImage * SoGLImage::getImage(void) const { return PRIVATE(this)->image; } /*! Returns or creates a SoGLDisplayList to be used for rendering. Returns NULL if no SoDLDisplayList could be created. */ SoGLDisplayList * SoGLImage::getGLDisplayList(SoState *state) { LOCK_GLIMAGE; SoGLDisplayList *dl = PRIVATE(this)->findDL(state); UNLOCK_GLIMAGE; if (dl == NULL) { dl = PRIVATE(this)->createGLDisplayList(state); if (dl) { LOCK_GLIMAGE; PRIVATE(this)->dlists.append(SoGLImageP::dldata(dl)); UNLOCK_GLIMAGE; } } if (dl && !dl->isMipMapTextureObject() && PRIVATE(this)->image) { float quality = SoTextureQualityElement::get(state); float oldquality = PRIVATE(this)->quality; PRIVATE(this)->quality = quality; if (PRIVATE(this)->shouldCreateMipmap()) { LOCK_GLIMAGE; // recreate DL to get a mipmapped image int n = PRIVATE(this)->dlists.getLength(); for (int i = 0; i < n; i++) { if (PRIVATE(this)->dlists[i].dlist == dl) { dl->unref(state); // unref old DL dl = PRIVATE(this)->createGLDisplayList(state); PRIVATE(this)->dlists[i].dlist = dl; break; } } UNLOCK_GLIMAGE; } else PRIVATE(this)->quality = oldquality; } return dl; } /*! Returns \e TRUE if this texture has some pixels with alpha != 255 */ SbBool SoGLImage::hasTransparency(void) const { if (PRIVATE(this)->flags & FORCE_TRANSPARENCY_TRUE) return TRUE; if (PRIVATE(this)->flags & FORCE_TRANSPARENCY_FALSE) return FALSE; if (PRIVATE(this)->needtransparencytest) { ((SoGLImage*)this)->pimpl->checkTransparency(); } return PRIVATE(this)->hastransparency; } /*! Returns TRUE if this image has some alpha value != 255, and all these values are 0. If this is the case, alpha test can be used to render this texture instead of for instance blending, which is usually slower and might yield z-buffer artifacts. */ SbBool SoGLImage::useAlphaTest(void) const { if (PRIVATE(this)->flags & FORCE_ALPHA_TEST_TRUE) return TRUE; if (PRIVATE(this)->flags & FORCE_ALPHA_TEST_FALSE) return FALSE; if (PRIVATE(this)->needtransparencytest) { ((SoGLImage*)this)->pimpl->checkTransparency(); } return PRIVATE(this)->usealphatest; } /*! Returns the wrap strategy for the S (horizontal) direction. */ SoGLImage::Wrap SoGLImage::getWrapS(void) const { return PRIVATE(this)->wraps; } /*! Returns the wrap strategy for the T (vertical) direction. */ SoGLImage::Wrap SoGLImage::getWrapT(void) const { return PRIVATE(this)->wrapt; } /*! Returns the wrap strategy for the R (depth) direction. */ SoGLImage::Wrap SoGLImage::getWrapR(void) const { return PRIVATE(this)->wrapr; } /*! Returns the texture quality for this texture image. \since Coin 2.5 */ float SoGLImage::getQuality(void) const { return PRIVATE(this)->quality; } /*! Returns an unique if for this GL image. This id can be used to test for changes in an SoGLImage's internal data. */ uint32_t SoGLImage::getGLImageId(void) const { return PRIVATE(this)->glimageid; } /*! Virtual method that will be called once each frame. The method should unref display lists that has an age bigger or equal to \a maxage, and increment the age for other display lists. */ void SoGLImage::unrefOldDL(SoState *state, const uint32_t maxage) { PRIVATE(this)->unrefOldDL(state, maxage); this->incAge(); } // ************************************************************************* void SoGLImageP::init(void) { assert(this->isregistered == FALSE); this->image = NULL; this->pbuffer = NULL; this->glsize.setValue(0,0,0); this->glcomp = 0; this->wraps = SoGLImage::CLAMP; this->wrapt = SoGLImage::CLAMP; this->wrapr = SoGLImage::CLAMP; this->border = 0; this->flags = SoGLImage::USE_QUALITY_VALUE; this->needtransparencytest = TRUE; this->hastransparency = FALSE; this->usealphatest = FALSE; this->quality = 0.4f; this->imageage = 0; this->endframecb = NULL; this->glimageid = 0; // glimageid 0 is an empty image } // // resize image if necessary. Returns pointer to temporary // buffer if that happens, and the new size in xsize, ysize. // void SoGLImageP::resizeImage(SoState * state, unsigned char *& imageptr, uint32_t & xsize, uint32_t & ysize, uint32_t & zsize) { SbVec3s size; int numcomponents; unsigned char *bytes = this->image->getValue(size, numcomponents); uint32_t newx = xsize; uint32_t newy = ysize; uint32_t newz = zsize; uint32_t maxrectsize = 0; if (!(this->flags & SoGLImage::RECTANGLE)) { newx = coin_geq_power_of_two(xsize - 2*this->border); newy = coin_geq_power_of_two(ysize - 2*this->border); newz = zsize ? coin_geq_power_of_two(zsize - 2*this->border) : 0; // if >= 256 and low quality, don't scale up unless size is // close to an above power of two. This saves a lot of texture memory if (this->flags & SoGLImage::SCALE_DOWN) { // no use scaling down for very small images if (newx > xsize && newx > 16) newx >>= 1; if (newy > ysize && newy > 16) newy >>= 1; if (newz > zsize && newz > 16) newz >>= 1; } else if (this->flags & SoGLImage::USE_QUALITY_VALUE) { if (this->quality < COIN_TEX2_SCALEUP_LIMIT) { if ((newx >= 256) && ((newx - (xsize-2*this->border)) > (newx>>3))) newx >>= 1; if ((newy >= 256) && ((newy - (ysize-2*this->border)) > (newy>>3))) newy >>= 1; if ((newz >= 256) && ((newz - (zsize-2*this->border)) > (newz>>3))) newz >>= 1; } } } else { GLint maxr; glGetIntegerv(GL_MAX_RECTANGLE_TEXTURE_SIZE_EXT, &maxr); maxrectsize = (uint32_t) maxr; } // downscale to legal GL size (implementation dependent) const cc_glglue * glw = sogl_glue_instance(state); SbBool sizeok = FALSE; #if COIN_DEBUG uint32_t orgsize[3] = { newx, newy, newz }; #endif // COIN_DEBUG while (!sizeok) { SbBool compressed = (this->flags & SoGLImage::COMPRESSED) ? TRUE : FALSE && SoGLDriverDatabase::isSupported(glw, SO_GL_TEXTURE_COMPRESSION); if (this->flags & SoGLImage::RECTANGLE) { // FIXME: add support for rectangular textures in glglue proxy test sizeok = (newx <= maxrectsize) && (newy <= maxrectsize); } else { GLenum internalformat = coin_glglue_get_internal_texture_format(glw, numcomponents, compressed); GLenum format = coin_glglue_get_texture_format(glw, numcomponents); sizeok = coin_glglue_is_texture_size_legal(glw, newx, newy, newz, internalformat, format, GL_UNSIGNED_BYTE, this->shouldCreateMipmap()); } if (!sizeok) { unsigned int max = SbMax(newx, SbMax(newy, newz)); if (max==newz) newz >>= 1; else if (max==newy) newy >>= 1; else newx >>= 1; } if (newy == 0) { // Avoid endless loop in a buggy driver environment. SoDebugError::post("SoGLImageP::resizeImage", "There is something seriously wrong with OpenGL on " "this system -- can't find *any* valid texture " "size! Expect further problems."); break; } } #if COIN_DEBUG if (orgsize[0] != newx || orgsize[1] != newy || orgsize[2] != newz) { if (orgsize[2] != 0) { SoDebugError::postWarning("SoGLImageP::resizeImage", "Original 3D texture too large for " "your graphics hardware and / or OpenGL " "driver. Rescaled from (%d x %d x %d) " "to (%d x %d x %d).", orgsize[0], orgsize[1], orgsize[2], newx, newy, newz); } else { SoDebugError::postWarning("SoGLImageP::resizeImage", "Original 2D texture too large for " "your graphics hardware and / or OpenGL " "driver. Rescaled from (%d x %d) " "to (%d x %d).", orgsize[0], orgsize[1], newx, newy); } } #endif // COIN_DEBUG newx += 2 * this->border; newy += 2 * this->border; newz = (zsize==0)?0:newz + (2 * this->border); if ((newx != xsize) || (newy != ysize) || (newz != zsize)) { // We need to resize. int numbytes = newx * newy * ((newz==0)?1:newz) * numcomponents; unsigned char * glimage_tmpimagebuffer = glimage_get_buffer(numbytes, FALSE); // First check if there is a custom resize function registered SbBool customresizedone = FALSE; if (SoGLImageP::resizecb) { customresizedone = SoGLImageP::resizecb(state, SbVec3s(newx, newy, newz), glimage_tmpimagebuffer, SoGLImage::IMAGE, SoGLImageP::resizeclosure, this->owner); } if (!customresizedone) { // simage version 1.1.1 has a pretty high quality resize // function. We prefer to use that to avoid using GLU, since // there are lots of buggy GLU libraries out there. if (zsize == 0) { // 2D image // simage_resize and gluScaleImage can be pretty slow. Use // fast_image_resize() if high quality isn't needed if (SoTextureScaleQualityElement::get(state) < 0.5f) { fast_image_resize(bytes, glimage_tmpimagebuffer, xsize, ysize, numcomponents, newx, newy); } else if (simage_wrapper()->available && simage_wrapper()->versionMatchesAtLeast(1,1,1) && simage_wrapper()->simage_resize) { unsigned char *result = simage_wrapper()->simage_resize((unsigned char*) bytes, xsize, ysize, numcomponents, newx, newy); (void)memcpy(glimage_tmpimagebuffer, result, numbytes); simage_wrapper()->simage_free_image(result); } else if (GLUWrapper()->available) { glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0); glPixelStorei(GL_UNPACK_SKIP_ROWS, 0); glPixelStorei(GL_PACK_ROW_LENGTH, 0); glPixelStorei(GL_PACK_SKIP_PIXELS, 0); glPixelStorei(GL_PACK_SKIP_ROWS, 0); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glPixelStorei(GL_PACK_ALIGNMENT, 1); // FIXME: ignoring the error code. Silly. 20000929 mortene. (void)GLUWrapper()->gluScaleImage(coin_glglue_get_texture_format(glw, numcomponents), xsize, ysize, GL_UNSIGNED_BYTE, (void*) bytes, newx, newy, GL_UNSIGNED_BYTE, (void*)glimage_tmpimagebuffer); glPixelStorei(GL_UNPACK_ALIGNMENT, 4); glPixelStorei(GL_PACK_ALIGNMENT, 4); } else { // fall back to the internal low-quality resize function fast_image_resize(bytes, glimage_tmpimagebuffer, xsize, ysize, numcomponents, newx, newy); } } else { // (zsize > 0) => 3D image if (simage_wrapper()->available && simage_wrapper()->versionMatchesAtLeast(1,3,0) && simage_wrapper()->simage_resize3d) { unsigned char *result = simage_wrapper()->simage_resize3d((unsigned char*) bytes, xsize, ysize, numcomponents, zsize, newx, newy, newz); (void)memcpy(glimage_tmpimagebuffer, result, numbytes); simage_wrapper()->simage_free_image(result); } else { // fall back to the internal low-quality resize function fast_image_resize3d(bytes, glimage_tmpimagebuffer, xsize, ysize, numcomponents, zsize, newx, newy, newz); } } } imageptr = glimage_tmpimagebuffer; } xsize = newx; ysize = newy; zsize = newz; } // // private method that in addition to creating the display list, // tests the size of the image and performs a resize if the size is not // a power of two. // reallyCreateTexture is called (only) from here. // SoGLDisplayList * SoGLImageP::createGLDisplayList(SoState *state) { SbVec3s size; int numcomponents; unsigned char *bytes = this->image ? this->image->getValue(size, numcomponents) : NULL; if (!this->pbuffer && !bytes) return NULL; uint32_t xsize = size[0]; uint32_t ysize = size[1]; uint32_t zsize = size[2]; SbBool is3D = (size[2]==0)?FALSE:TRUE; // these might change if image is resized unsigned char *imageptr = (unsigned char *) bytes; const cc_glglue * glw = sogl_glue_instance(state); SbBool mipmap = this->shouldCreateMipmap(); if (imageptr) { if (is3D || (!SoGLDriverDatabase::isSupported(glw, SO_GL_NON_POWER_OF_TWO_TEXTURES) || (mipmap && (!SoGLDriverDatabase::isSupported(glw, SO_GL_GENERATE_MIPMAP) && !SoGLDriverDatabase::isSupported(glw, "GL_SGIS_generate_mipmap"))))) { this->resizeImage(state, imageptr, xsize, ysize, zsize); } } SoGLDisplayList *dl = new SoGLDisplayList(state, SoGLDisplayList::TEXTURE_OBJECT, 1, mipmap); dl->ref(); if (bytes) { SbBool is3D = (size[2]==0)?FALSE:TRUE; if (is3D) { dl->setTextureTarget((int) GL_TEXTURE_3D); } else { dl->setTextureTarget((int) ((this->flags & SoGLImage::RECTANGLE) ? GL_TEXTURE_RECTANGLE_EXT : GL_TEXTURE_2D)); } } dl->open(state); if (this->pbuffer) { this->reallyBindPBuffer(state); } else { this->reallyCreateTexture(state, imageptr, numcomponents, xsize, ysize, zsize, dl->getType() == SoGLDisplayList::DISPLAY_LIST, mipmap, this->border); } dl->close(state); return dl; } // // Test image data for transparency by checking each texel. // void SoGLImageP::checkTransparency(void) { this->needtransparencytest = FALSE; this->usealphatest = FALSE; this->hastransparency = FALSE; SbVec3s size; int numcomponents; unsigned char *bytes = this->image ? this->image->getValue(size, numcomponents) : NULL; if (bytes == NULL) { if (this->glcomp == 2 || this->glcomp == 4) { // we must assume it has transparency, and that we // can't use alpha testing this->hastransparency = TRUE; } } else { if (numcomponents == 2 || numcomponents == 4) { int n = size[0] * size[1] * (size[2] ? size[2] : 1); int nc = numcomponents; unsigned char *ptr = (unsigned char *) bytes + nc - 1; while (n) { if (*ptr != 255 && *ptr != 0) break; if (*ptr == 0) this->usealphatest = TRUE; ptr += nc; n--; } if (n > 0) { this->hastransparency = TRUE; this->usealphatest = FALSE; } else { this->hastransparency = this->usealphatest; } } } } static GLenum translate_wrap(SoState *state, const SoGLImage::Wrap wrap) { if (wrap == SoGLImage::REPEAT) return (GLenum) GL_REPEAT; if (wrap == SoGLImage::CLAMP_TO_BORDER) return (GLenum) GL_CLAMP_TO_BORDER; if (COIN_ENABLE_CONFORMANT_GL_CLAMP) { if (wrap == SoGLImage::CLAMP_TO_EDGE) { const cc_glglue * glw = sogl_glue_instance(state); if (SoGLDriverDatabase::isSupported(glw, SO_GL_TEXTURE_EDGE_CLAMP)) return (GLenum) GL_CLAMP_TO_EDGE; } return (GLenum) GL_CLAMP; } const cc_glglue * glw = sogl_glue_instance(state); if (SoGLDriverDatabase::isSupported(glw, SO_GL_TEXTURE_EDGE_CLAMP)) return (GLenum) GL_CLAMP_TO_EDGE; return (GLenum) GL_CLAMP; } void SoGLImageP::reallyBindPBuffer(SoState * state) { GLenum target = this->flags & SoGLImage::RECTANGLE ? GL_TEXTURE_RECTANGLE_EXT : GL_TEXTURE_2D; glTexParameteri(target, GL_TEXTURE_WRAP_S, translate_wrap(state, this->wraps)); glTexParameteri(target, GL_TEXTURE_WRAP_T, translate_wrap(state, this->wrapt)); SbBool mipmap = FALSE; #if 0 // disabled, we probably need to allocate space for the mipmaps in // the pbuffer pederb, 2003-11-27 if (this->shouldCreateMipmap() && SoGLDriverDatabase::isSupported(glue, "GL_SGIS_generate_mipmap")) { glTexParameteri(target, GL_GENERATE_MIPMAP_SGIS, GL_TRUE); // glHint(GL_GENERATE_MIPMAP_HINT_SGIS, GL_NICEST); mipmap = TRUE; } #endif // disabled this->applyFilter(mipmap); cc_glglue_context_bind_pbuffer(this->pbuffer); } void SoGLImageP::reallyCreateTexture(SoState *state, const unsigned char *const texture, const int numComponents, const int w, const int h, const int d, const SbBool dlist, //FIXME: Not in use (kintel 20011129) const SbBool mipmap, const int border) { const cc_glglue * glw = sogl_glue_instance(state); this->glsize = SbVec3s((short) w, (short) h, (short) d); this->glcomp = numComponents; SbBool compress = (this->flags & SoGLImage::COMPRESSED) && SoGLDriverDatabase::isSupported(glw, SO_GL_TEXTURE_COMPRESSION); GLint internalFormat = coin_glglue_get_internal_texture_format(glw, numComponents, compress); GLenum dataFormat = coin_glglue_get_texture_format(glw, numComponents); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); //FIXME: Check cc_glglue capability as well? (kintel 20011129) if (SoGLTexture3EnabledElement::get(state)) { // 3D textures glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, translate_wrap(state, this->wraps)); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, translate_wrap(state, this->wrapt)); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, translate_wrap(state, this->wrapr)); this->applyFilter(mipmap); if (!mipmap) { if (SoGLDriverDatabase::isSupported(glw, SO_GL_3D_TEXTURES)) { cc_glglue_glTexImage3D(glw, GL_TEXTURE_3D, 0, internalFormat, w, h, d, border, dataFormat, GL_UNSIGNED_BYTE, texture); } } else { // mipmaps // We used to default to calling GLU's gluBuild3DMipmaps() here, // but that was axed, because the gluBuild[2|3]DMipmaps() // functions implicitly uses glGenTextures() and other OpenGL // 1.1+ functions -- which again can cause trouble when doing // remote rendering. (At least we've had lots of problems with // NVidia's GLX implementation for non-1.0 OpenGL stuff.) // // (void)GLUWrapper()->gluBuild3DMipmaps(GL_TEXTURE_3D, internalFormat, // w, h, d, dataFormat, // GL_UNSIGNED_BYTE, texture); fast_mipmap(state, w, h, d, numComponents, texture, FALSE, compress); } } else { // 2D textures SbBool mipmapimage = mipmap; SbBool mipmapfilter = mipmap; SbBool generatemipmap = FALSE; GLenum target = this->flags & SoGLImage::RECTANGLE ? GL_TEXTURE_RECTANGLE_EXT : GL_TEXTURE_2D; glTexParameteri(target, GL_TEXTURE_WRAP_S, translate_wrap(state, this->wraps)); glTexParameteri(target, GL_TEXTURE_WRAP_T, translate_wrap(state, this->wrapt)); if (mipmap && (this->flags & SoGLImage::RECTANGLE)) { mipmapimage = FALSE; if (SoGLDriverDatabase::isSupported(glw, "GL_SGIS_generate_mipmap")) { glTexParameteri(target, GL_GENERATE_MIPMAP_SGIS, GL_TRUE); } else mipmapfilter = FALSE; } // using glGenerateMipmap() while creating a display list is not // supported (even if the display list is never used). This is // probably because the OpenGL driver creates each mipmap level by // rendering it using normal OpenGL calls. else if (mipmap && SoGLDriverDatabase::isSupported(glw, SO_GL_GENERATE_MIPMAP) && !state->isCacheOpen()) { mipmapimage = FALSE; generatemipmap = TRUE; // delay until after the texture image is set up } else if (mipmap && SoGLDriverDatabase::isSupported(glw, "GL_SGIS_generate_mipmap")) { glTexParameteri(target, GL_GENERATE_MIPMAP_SGIS, GL_TRUE); mipmapimage = FALSE; } if ((this->quality > COIN_TEX2_ANISOTROPIC_LIMIT) && SoGLDriverDatabase::isSupported(glw, SO_GL_ANISOTROPIC_FILTERING)) { glTexParameterf(target, GL_TEXTURE_MAX_ANISOTROPY_EXT, cc_glglue_get_max_anisotropy(glw)); } if (!mipmapimage) { // Create only level 0 texture. Mipmaps might be created by glGenerateMipmap glTexImage2D(target, 0, internalFormat, w, h, border, dataFormat, GL_UNSIGNED_BYTE, texture); if (generatemipmap) { SbBool wasenabled = TRUE; // Woraround for ATi driver bug. GL_TEXTURE_2D needs to be // enabled when using glGenerateMipmap(), according to // dicussions on the opengl.org forums. if (glw->vendor_is_ati) { if (!glIsEnabled(GL_TEXTURE_2D)) { wasenabled = FALSE; glEnable(GL_TEXTURE_2D); } } cc_glglue_glGenerateMipmap(glw, target); if (!wasenabled) glDisable(GL_TEXTURE_2D); } } else { // mipmaps // The GLU function invocation has been disabled, for the // reasons stated in the code comments ~20 lines above on the // construction of 3D mipmap textures. // // (void)GLUWrapper()->gluBuild2DMipmaps(GL_TEXTURE_2D, internalFormat, // w, h, dataFormat, // GL_UNSIGNED_BYTE, texture); fast_mipmap(state, w, h, numComponents, texture, FALSE, compress); } this->applyFilter(mipmapfilter); } glPixelStorei(GL_UNPACK_ALIGNMENT, 4); } // // unref all dlists stored in image // void SoGLImageP::unrefDLists(SoState *state) { int n = this->dlists.getLength(); for (int i = 0; i < n; i++) { this->dlists[i].dlist->unref(state); } this->dlists.truncate(0); } // find dl for a context, NULL if not found SoGLDisplayList * SoGLImageP::findDL(SoState *state) { int currcontext = SoGLCacheContextElement::get(state); int i, n = this->dlists.getLength(); SoGLDisplayList *dl; for (i = 0; i < n; i++) { dl = this->dlists[i].dlist; if (dl->getContext() == currcontext) return dl; } return NULL; } void SoGLImageP::tagDL(SoState *state) { int currcontext = SoGLCacheContextElement::get(state); int i, n = this->dlists.getLength(); SoGLDisplayList *dl; for (i = 0; i < n; i++) { dl = this->dlists[i].dlist; if (dl->getContext() == currcontext) { this->dlists[i].age = 0; break; } } } void SoGLImage::incAge(void) const { PRIVATE(this)->imageage++; } void SoGLImage::resetAge(void) const { PRIVATE(this)->imageage = 0; } void SoGLImageP::unrefOldDL(SoState *state, const uint32_t maxage) { int n = this->dlists.getLength(); int i = 0; while (i < n) { dldata & data = this->dlists[i]; if (data.age >= maxage) { #if COIN_DEBUG && 0 // debug SoDebugError::postInfo("SoGLImageP::unrefOldDL", "DL killed because of old age: %p", this->owner); #endif // debug data.dlist->unref(state); this->dlists.removeFast(i); n--; // one less in list now } else { // increment age data.age++; i++; } } } SbBool SoGLImageP::shouldCreateMipmap(void) { if (this->flags & SoGLImage::USE_QUALITY_VALUE) { return this->quality >= COIN_TEX2_MIPMAP_LIMIT; } else { return (this->flags & SoGLImage::NO_MIPMAP) == 0; } } // // Actually apply the texture filters using OpenGL calls. // void SoGLImageP::applyFilter(const SbBool ismipmap) { GLenum target; // Casting away const const SbVec3s size = this->image ? this->image->getSize() : this->glsize; if (size[2] >= 1) target = GL_TEXTURE_3D; else { target = this->flags & SoGLImage::RECTANGLE ? GL_TEXTURE_RECTANGLE_EXT : GL_TEXTURE_2D; } if (this->flags & SoGLImage::USE_QUALITY_VALUE) { if (this->quality < COIN_TEX2_LINEAR_LIMIT) { glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST); } else if ((this->quality < COIN_TEX2_MIPMAP_LIMIT) || !ismipmap) { glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } else if (this->quality < COIN_TEX2_LINEAR_MIPMAP_LIMIT) { glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR); } else { // max quality glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); } } else { if ((this->flags & SoGLImage::NO_MIPMAP) || !ismipmap) { glTexParameteri(target, GL_TEXTURE_MAG_FILTER, (this->flags & SoGLImage::LINEAR_MAG_FILTER) ? GL_LINEAR : GL_NEAREST); glTexParameteri(target, GL_TEXTURE_MIN_FILTER, (this->flags & SoGLImage::LINEAR_MIN_FILTER) ? GL_LINEAR : GL_NEAREST); } else { glTexParameteri(target, GL_TEXTURE_MAG_FILTER, (this->flags & SoGLImage::LINEAR_MAG_FILTER) ? GL_LINEAR : GL_NEAREST); GLenum minfilter = GL_NEAREST_MIPMAP_NEAREST; if (this->flags & SoGLImage::LINEAR_MIPMAP_FILTER) { if (this->flags & SoGLImage::LINEAR_MIN_FILTER) minfilter = GL_LINEAR_MIPMAP_LINEAR; else minfilter = GL_LINEAR_MIPMAP_NEAREST; } else if (this->flags & SoGLImage::LINEAR_MIN_FILTER) minfilter = GL_NEAREST_MIPMAP_LINEAR; glTexParameteri(target, GL_TEXTURE_MIN_FILTER, minfilter); } } } // returns an unique uint32_t id for gl images uint32_t SoGLImageP::getNextGLImageId(void) { return current_glimageid++; } // ************************************************************************* // // Texture resource management. // // FIXME: consider sorting images on an LRU strategy to // speed up the process of searching for GL-images to free. // static SbList <SoGLImage*> * glimage_reglist; static uint32_t glimage_maxage = 60; static void regimage_cleanup(void) { delete glimage_reglist; glimage_reglist = NULL; glimage_maxage = 60; } /*! When doing texture resource control, call this method before rendering the scene, typically in the viewer's actualRedraw(). \a state should be your SoGLRenderAction state. \sa endFrame(), tagImage(), setDisplayListMaxAge() */ void SoGLImage::beginFrame(SoState * /* state */) { // nothing is done for now } /*! Should be called when a texture image is used. In Coin this is handled by SoGLTextureImageElement, but if you use an SoGLImage on your own, you should call this method to avoid that the display list is deleted too soon. \a state should be your SoGLRenderAction state, \a image the image you are about to use/have used. */ void SoGLImage::tagImage(SoState *state, SoGLImage *image) { assert(image); if (image) { LOCK_GLIMAGE; image->resetAge(); image->pimpl->tagDL(state); UNLOCK_GLIMAGE; } } /*! Should be called after your scene is rendered. Old display lists will be deleted when you call this method. \a state should be your SoGLRenderAction state. \sa beginFrame(), tagImage(), setDisplayListMaxAge() */ void SoGLImage::endFrame(SoState *state) { if (glimage_reglist) { std::list<std::pair<void (*)(void *), void *> > cb_list; LOCK_GLIMAGE; int n = glimage_reglist->getLength(); for (int i = 0; i < n; i++) { SoGLImage *img = (*glimage_reglist)[i]; img->unrefOldDL(state, glimage_maxage); if (img->pimpl->endframecb) cb_list.push_back(std::make_pair(img->pimpl->endframecb, img->pimpl->endframeclosure)); } UNLOCK_GLIMAGE; // the actual invocation of the callbacks should be performed outside // the locked region to avoid deadlocks for (std::list<std::pair<void (*)(void *), void *> >::iterator it = cb_list.begin(), end = cb_list.end(); it != end; ++it) it->first(it->second); } } void SoGLImage::setEndFrameCallback(void (*cb)(void *), void *closure) { PRIVATE(this)->endframecb = cb; PRIVATE(this)->endframeclosure = closure; } int SoGLImage::getNumFramesSinceUsed(void) const { return PRIVATE(this)->imageage; } /*! Free all GL images currently used. This can be used to help the operating system and/or OpenGL driver's resource handling. If you know you're not going to render for a while, maybe you're switching to a different application or something, calling this method could be a good idea since it will release all the texture memory used by your application. */ void SoGLImage::freeAllImages(SoState *state) { int oldmax = glimage_maxage; glimage_maxage = 0; // call begin/end with maxage 0 to free all images SoGLImage::beginFrame(state); SoGLImage::endFrame(state); glimage_maxage = oldmax; } /*! Set the maximum age for a texture object/display list. The age of an image is the number of frames since it has been used. Default maximum age is 60. */ void SoGLImage::setDisplayListMaxAge(const uint32_t maxage) { glimage_maxage = maxage; } // used internally to keep track of the SoGLImages void SoGLImage::registerImage(SoGLImage *image) { LOCK_GLIMAGE; if (glimage_reglist == NULL) { coin_atexit((coin_atexit_f *)regimage_cleanup, CC_ATEXIT_NORMAL); glimage_reglist = new SbList<SoGLImage*>; } assert(glimage_reglist->find(image) < 0); glimage_reglist->append(image); PRIVATE(image)->isregistered = TRUE; UNLOCK_GLIMAGE; } // used internally to keep track of the SoGLImages void SoGLImage::unregisterImage(SoGLImage *image) { assert(glimage_reglist); LOCK_GLIMAGE; int idx = glimage_reglist->find(image); assert(idx >= 0); if (idx >= 0) { glimage_reglist->removeFast(idx); } PRIVATE(image)->isregistered = FALSE; UNLOCK_GLIMAGE; } /*! Sets a custom image resize function. \since Coin 2.5 */ void SoGLImage::setResizeCallback(SoGLImageResizeCB * f, void * closure) { SoGLImageP::resizecb = f; SoGLImageP::resizeclosure = closure; } // ************************************************************************* // // Callback from SoContextHandler // void SoGLImageP::contextCleanup(uint32_t context, void * closure) { SoGLImageP * thisp = (SoGLImageP *) closure; #ifdef COIN_THREADSAFE SoGLImageP::mutex->lock(); #endif // COIN_THREADSAFE int n = thisp->dlists.getLength(); int i = 0; while (i < n) { if (thisp->dlists[i].dlist->getContext() == (int) context) { thisp->dlists[i].dlist->unref(NULL); thisp->dlists.remove(i); n--; } else i++; } #ifdef COIN_THREADSAFE SoGLImageP::mutex->unlock(); #endif // COIN_THREADSAFE } // ************************************************************************* #undef PRIVATE #undef LOCK_GLIMAGE #undef UNLOCK_GLIMAGE
32.533868
110
0.630633
[ "render", "object", "3d" ]
a7d6f3289870d47d3fcdb11af84452385692926d
20,619
cpp
C++
src/cisHW1-2.cpp
ahundt/cis
bd55e8c77ec78994454247ffe7d67f537710a53f
[ "BSD-2-Clause-FreeBSD" ]
1
2018-12-17T03:13:01.000Z
2018-12-17T03:13:01.000Z
src/cisHW1-2.cpp
ahundt/cis
bd55e8c77ec78994454247ffe7d67f537710a53f
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
src/cisHW1-2.cpp
ahundt/cis
bd55e8c77ec78994454247ffe7d67f537710a53f
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
// Library includes #include <boost/program_options/options_description.hpp> #include <boost/program_options/parsers.hpp> #include <boost/program_options/variables_map.hpp> #include <boost/tokenizer.hpp> #include <boost/math/special_functions/binomial.hpp> #include <cmath> #include <thread> // Project includes #include "parseCSV_CIS_pointCloud.hpp" #include "parseCommandLineOptions.hpp" #include "hornRegistration.hpp" #include "parsePA1_2.hpp" #include "PivotCalibration.hpp" #include "PointEstimation.hpp" #include "PA1_2_DataConstants.hpp" #include "DistortionCalibration.hpp" #include "PA2.hpp" namespace po = boost::program_options; /// read the command line options from argc,argv and load them into the params object /// @see boost::program_options for details on how the command line parsing library works. bool readCommandLine(int argc, char* argv[], ParsedCommandLineCommands & pclp){ static const bool optional = false; // false means parameters are not required, and therefore optional static const bool required = true; // true means parameters are required po::options_description generalOptions("General Options"); generalOptions.add_options() ("responseFile", po::value<std::string>(), "File containing additional command line parameters") CLO_HELP CLO_DEBUG ("debugParser","display debug information for data file parser") ; po::options_description algorithmOptions("Algorithm Options"); algorithmOptions.add_options() ("threads","run each source data file in a separate thread"); // create algorithm command line options //algorithmOptions.add_options() // todo, add options for configuring algorithms po::options_description dataOptions("Data Options"); std::string currentPath(boost::filesystem::path( boost::filesystem::current_path() ).string()); // create algorithm command line options dataOptions.add_options() ("pa1", "set automatic programming assignment 1 source data parameters, overrides DataFilenamePrefix, exclusive of pa1") ("pa2", "set automatic programming assignment 2 source data parameters, overrides DataFilenamePrefix, exclusive of pa2") ("dataFolderPath" ,po::value<std::string>()->default_value(currentPath) ,"folder containing data files, defaults to current working directory" ) ("outputDataFolderPath" ,po::value<std::string>()->default_value(currentPath) ,"folder for output data files, defaults to current working directory" ) ("dataFilenamePrefix" ,po::value<std::vector<std::string> >()->default_value(HW2DataFilePrefixes(),""),"constant prefix of data filename path. Specify this multiple times to run on many data sources at once" ) ("dataFileNameSuffix_calbody" ,po::value<std::string>()->default_value(dataFileNameSuffix_calbody ),"suffix of data filename path" ) ("dataFileNameSuffix_calreadings" ,po::value<std::string>()->default_value(dataFileNameSuffix_calreadings ),"suffix of data filename path" ) ("dataFileNameSuffix_empivot" ,po::value<std::string>()->default_value(dataFileNameSuffix_empivot ),"suffix of data filename path" ) ("dataFileNameSuffix_optpivot" ,po::value<std::string>()->default_value(dataFileNameSuffix_optpivot ),"suffix of data filename path" ) ("dataFileNameSuffix_output1" ,po::value<std::string>()->default_value(dataFileNameSuffix_output1 ),"suffix of data filename path" ) ("dataFileNameSuffix_ct_fiducials" ,po::value<std::string>()->default_value(dataFileNameSuffix_ct_fiducials),"suffix of data filename path" ) ("dataFileNameSuffix_em_fiducials" ,po::value<std::string>()->default_value(dataFileNameSuffix_em_fiducials),"suffix of data filename path" ) ("dataFileNameSuffix_em_nav" ,po::value<std::string>()->default_value(dataFileNameSuffix_em_nav ),"suffix of data filename path" ) ("dataFileNameSuffix_output2" ,po::value<std::string>()->default_value(dataFileNameSuffix_output2 ),"suffix of data filename path" ) ("calbodyPath" ,po::value<std::string>() , "full path to data txt file, optional alternative to prefix+suffix name combination" ) ("calreadingsPath" ,po::value<std::string>() , "full path to data txt file, optional alternative to prefix+suffix name combination" ) ("empivotPath" ,po::value<std::string>() , "full path to data txt file, optional alternative to prefix+suffix name combination" ) ("optpivotPath" ,po::value<std::string>() , "full path to data txt file, optional alternative to prefix+suffix name combination" ) ("output1Path" ,po::value<std::string>() , "full path to data txt file, optional alternative to prefix+suffix name combination" ) ("ct_fiducialsPath" ,po::value<std::string>() , "full path to data txt file, optional alternative to prefix+suffix name combination" ) ("em_fiducialsPath" ,po::value<std::string>() , "full path to data txt file, optional alternative to prefix+suffix name combination" ) ("em_navPath" ,po::value<std::string>() , "full path to data txt file, optional alternative to prefix+suffix name combination" ) ("output2Path" ,po::value<std::string>() , "full path to data txt file, optional alternative to prefix+suffix name combination" ) ; po::options_description allOptions; allOptions.add(generalOptions).add(algorithmOptions).add(dataOptions); po::variables_map vmap; try { po::store(po::command_line_parser(argc, argv).options(allOptions).run(), vmap); po::notify(vmap); } catch (std::exception& e) { std::cerr << "[Error] " << BOOST_CURRENT_FUNCTION << std::endl << " " << e.what() << std::endl << std::endl << allOptions << std::endl; return false; } if (vmap.count(CLO_GET_ARG_STR2(CLO_HELP)) || argc < 2) { std::cout << allOptions << std::endl; return false; } pclp.debugParser = vmap.count("debugParser"); parseResponseFiles(vmap,allOptions); // initalize string params std::string dataFolderPath ,dataFileNameSuffix_calbody ,dataFileNameSuffix_calreadings ,dataFileNameSuffix_empivot ,dataFileNameSuffix_optpivot ,dataFileNameSuffix_output1 ,dataFileNameSuffix_ct_fiducials ,dataFileNameSuffix_em_fiducials ,dataFileNameSuffix_em_nav ,dataFileNameSuffix_output2 ; DataSource datasource; std::vector<std::string> dataFilenamePrefixList; // load up parameter values from the variable map po::readOption(vmap,"dataFolderPath" ,dataFolderPath ,optional); po::readOption(vmap,"outputDataFolderPath" ,pclp.outputDataFolderPath ,optional); po::readOption(vmap,"dataFilenamePrefix" ,dataFilenamePrefixList ,optional); po::readOption(vmap, "dataFileNameSuffix_calbody" ,dataFileNameSuffix_calbody ,optional); po::readOption(vmap, "dataFileNameSuffix_calreadings" ,dataFileNameSuffix_calreadings ,optional); po::readOption(vmap, "dataFileNameSuffix_empivot" ,dataFileNameSuffix_empivot ,optional); po::readOption(vmap, "dataFileNameSuffix_optpivot" ,dataFileNameSuffix_optpivot ,optional); po::readOption(vmap, "dataFileNameSuffix_output1" ,dataFileNameSuffix_output1 ,optional); po::readOption(vmap, "dataFileNameSuffix_ct_fiducials" ,dataFileNameSuffix_ct_fiducials ,optional); po::readOption(vmap, "dataFileNameSuffix_em_fiducials" ,dataFileNameSuffix_em_fiducials ,optional); po::readOption(vmap, "dataFileNameSuffix_em_nav" ,dataFileNameSuffix_em_nav ,optional); po::readOption(vmap, "dataFileNameSuffix_output2" ,dataFileNameSuffix_output2 ,optional); // enable threads if specified pclp.threads = vmap.count("threads"); if (vmap.count("pa1")) { dataFilenamePrefixList = HW1DataFilePrefixes(); } else if (vmap.count("pa2")) { dataFilenamePrefixList = HW2DataFilePrefixes(); } int prefixCount = dataFilenamePrefixList.size(); if(!prefixCount){ pclp.dataSources.push_back(DataSource()); } if(prefixCount<=1){ po::readOption(vmap,"calbodyPath" ,pclp.dataSources[0].calbodyPath ,optional); po::readOption(vmap,"calreadingsPath" ,pclp.dataSources[0].calreadingsPath ,optional); po::readOption(vmap,"empivotPath" ,pclp.dataSources[0].empivotPath ,optional); po::readOption(vmap,"optpivotPath" ,pclp.dataSources[0].optpivotPath ,optional); po::readOption(vmap,"output1Path" ,pclp.dataSources[0].output1Path ,optional); po::readOption(vmap,"ct_fiducialsPath" ,pclp.dataSources[0].ct_fiducialsPath ,optional); po::readOption(vmap,"em_fiducialsPath" ,pclp.dataSources[0].em_fiducialsPath ,optional); po::readOption(vmap,"em_navPath" ,pclp.dataSources[0].em_navPath ,optional); po::readOption(vmap,"output2Path" ,pclp.dataSources[0].output2Path ,optional); } // check if the user supplied a full path, if not assemble a path // from the default paths and the defualt prefix/suffix combos for(auto&& prefix : dataFilenamePrefixList){ DataSource dataSource; dataSource.filenamePrefix = prefix; assemblePathIfFullPathNotSupplied(dataFolderPath,dataSource.filenamePrefix,dataFileNameSuffix_calbody ,dataSource.calbodyPath ,required); assemblePathIfFullPathNotSupplied(dataFolderPath,dataSource.filenamePrefix,dataFileNameSuffix_calreadings ,dataSource.calreadingsPath ,required); assemblePathIfFullPathNotSupplied(dataFolderPath,dataSource.filenamePrefix,dataFileNameSuffix_empivot ,dataSource.empivotPath ,required); assemblePathIfFullPathNotSupplied(dataFolderPath,dataSource.filenamePrefix,dataFileNameSuffix_optpivot ,dataSource.optpivotPath ,required); assemblePathIfFullPathNotSupplied(dataFolderPath,dataSource.filenamePrefix,dataFileNameSuffix_output1 ,dataSource.output1Path ,optional); assemblePathIfFullPathNotSupplied(dataFolderPath,dataSource.filenamePrefix,dataFileNameSuffix_ct_fiducials ,dataSource.ct_fiducialsPath ,optional); assemblePathIfFullPathNotSupplied(dataFolderPath,dataSource.filenamePrefix,dataFileNameSuffix_em_fiducials ,dataSource.em_fiducialsPath ,optional); assemblePathIfFullPathNotSupplied(dataFolderPath,dataSource.filenamePrefix,dataFileNameSuffix_em_nav ,dataSource.em_navPath ,optional); assemblePathIfFullPathNotSupplied(dataFolderPath,dataSource.filenamePrefix,dataFileNameSuffix_output2 ,dataSource.output2Path ,optional); pclp.dataSources.push_back(dataSource); } pclp.debug = vmap.count(CLO_GET_ARG_STR2(CLO_DEBUG)); return false; } /// Produce an output CIS CSV file void output1CISCSV_PA1(std::ostream& ostr, const std::string& outputName = "name-output-1.txt", const Eigen::Vector3d & emProbe = Eigen::Vector3d(0,0,0), const Eigen::Vector3d & optProbe = Eigen::Vector3d(0,0,0), const csvCIS_pointCloudData::TrackerDevices & vTrackers = csvCIS_pointCloudData::TrackerDevices()){ ostr << vTrackers[0].rows() << "," << vTrackers.size() << "," << outputName << "\n" << emProbe(0) << "," << emProbe(1) << "," << emProbe(2) << "\n" << optProbe(0) << "," << optProbe(1) << "," << optProbe(2) << "\n"; for(auto && tracker : vTrackers) { std::size_t rows = tracker.rows(); for(std::size_t i = 0; i < rows; ++i) { ostr << tracker.block<1,1>(i,0) << "," << tracker.block<1,1>(i,1) << "," << tracker.block<1,1>(i,2) << "\n"; } } ostr.flush(); } /// Produce an output CIS CSV file void output2CISCSV_PA2(std::ostream& ostr, const std::string& outputName = "name-output-2.txt", std::vector<Eigen::Vector3d> probeTipPositions = std::vector<Eigen::Vector3d>()){ ostr << probeTipPositions.size() << "," << outputName << "\n"; for(auto && pos : probeTipPositions) { ostr << pos(0) << "," << pos(1) << "," << pos(2) << "\n"; } ostr.flush(); } void generateOutputFile(AlgorithmData ad, std::string outputDataFolderPath, std::string dataFilenamePrefix, bool debug = false){ Eigen::Vector3d emPivotPoint; csvCIS_pointCloudData::TrackerDevices EMPtsInEMFrameOnProbe; /////////////////////////////////////////// // print pivot calibration data of empivot if(!ad.empivot.frames.empty()){ // Note: we know there is only one tracker in this data // so we can run concat to combine the vectors and // and do the calibration for it. EMPtsInEMFrameOnProbe = concat(ad.empivot.frames); Eigen::VectorXd result = pivotCalibration(EMPtsInEMFrameOnProbe,debug); emPivotPoint = result.block<3,1>(3,0); std::cout << "\n\nPivotCalibration result for " << ad.empivot.title << ":\n\n" << result << "\n\n"; } Eigen::Vector3d optPivotPoint; if(!ad.optpivot.frames.empty()){ std::vector<Eigen::MatrixXd> Gnew; Gnew = findNewGInEM(ad.optpivot.frames,ad.calbody.frames,debug); Eigen::VectorXd result = pivotCalibration(Gnew,debug); optPivotPoint = result.block<3,1>(3,0); std::cout << "\n\nPivotCalibration result for " << ad.optpivot.title << ":\n\n" << result << "\n\n"; } // cExpected contains *estimated* Optical Points in EM frame on Calibration Object std::vector<Eigen::MatrixXd> cExpected; if(!ad.calreadings.frames.empty() && !ad.calbody.frames.empty()){ cExpected = estimateCExpected(ad.calreadings.frames,ad.calbody.frames,debug); if(debug ){ std::cout << "\n\nsolveForCExpected results for "<< ad.calreadings.title << " and " << ad.calbody.title <<":\n\n"; for (auto expected : cExpected) std::cout << expected << "\n"; } } ///////////////////////////////////////////////////////////////////// // Adding Programming Assignment 2 Code to Main ///////////////////////////////////////////////////////////////////// // q = Values returned by nagivational sensor -> C (from calreadings) // p = known 3D ground truth -> Cexpected (already calculated above) Eigen::Vector3d dc; Eigen::Vector3d ppivotDistortionCorrected; // Stacks all of the C values given in calreadings and then normalize // Might want to find the max and min in each frame - need to ask Paul if(!ad.calreadings.frames.empty() && !ad.empivot.frames.empty()){ std::size_t numRowsPerTracker = EMPtsInEMFrameOnProbe[0].rows(); Eigen::MatrixXd undistortedEMPtsInEMFrameOnCalibrationObject = correctDistortionOnSourceData(ad.calreadings.frames,cExpected,EMPtsInEMFrameOnProbe); std::vector<Eigen::MatrixXd> splitUndistortedFrames = splitRows(undistortedEMPtsInEMFrameOnCalibrationObject,numRowsPerTracker); Eigen::VectorXd result = pivotCalibration(splitUndistortedFrames,debug); ppivotDistortionCorrected = result.block<3,1>(3,0); dc = result.block<3,1>(0,0); std::cout << "\n\nundistorted result:\n\n" << result << "\n\n"; } std::vector<Eigen::Vector3d> fiducialPointinEMFrames; if (!ad.calreadings.frames.empty() && !ad.em_fiducials.frames.empty()){ // Problem 4 // Takes positions of EM tracker points on the EM probe in the EM frame when the tip is in a CT fiducial // Returns points of the CT fiducial locations in EM frame // Need to pass dc too when making it into a function // see PA2.hpp std::vector<Eigen::MatrixXd> Gvector = concat(ad.em_fiducials.frames); fiducialPointinEMFrames = fiducialPointInEMFrame(Gvector,ad.calreadings.frames,cExpected,dc); } Eigen::Matrix4d Freg; if (!ad.ct_fiducials.frames.empty()){ // Problem 5 // Takes the point clouds of the CT and EM measured at each fiducial // Calculates Freg which is the transformation between CT and EM coordinates // There is only one frame and "tracker" containing points to each CT fiducial in the CT Frame Eigen::MatrixXd fiducialPointCloudCT = ad.ct_fiducials.frames[0][0]; Eigen::MatrixXd fiducialPointCloudEM = stackRangeTranspose(fiducialPointinEMFrames); Freg = hornRegistration(fiducialPointCloudEM,fiducialPointCloudCT); std::cout << "\n\nFreg is: \n" << Freg << std::endl; } Eigen::Affine3d freg2; freg2.matrix() = Freg; for(int i = 0; i < fiducialPointinEMFrames.size(); ++i){ std::cout << freg2*fiducialPointinEMFrames[i] << "\n"; } std::vector<Eigen::Vector3d> probeTipPointinCTFrames; if (!ad.calreadings.frames.empty() && !ad.em_nav.frames.empty()){ // Problem 6 // Takes positions of EM tracker points on the EM probe in the EM frame when the tip is in a CT fiducial // Returns points of the CT fiducial locations in the CT frame // Need to pass dc too when making it into a function std::vector<Eigen::MatrixXd> Gvector = concat(ad.em_nav.frames); Eigen::Affine3d affineFreg; affineFreg.matrix() = Freg; // see PA2.hpp probeTipPointinCTFrames = probeTipPointinCTFrame(Gvector,ad.calreadings.frames,cExpected,dc,affineFreg); } std::string outputFilename = dataFilenamePrefix + "-output1.txt"; std::ofstream ofs (outputFilename, std::ofstream::out); output1CISCSV_PA1(ofs,outputFilename,ppivotDistortionCorrected,optPivotPoint,cExpected); ofs.close(); if (!ad.em_nav.frames.empty()) { std::string outputFilename = dataFilenamePrefix + "-output2.txt"; std::ofstream ofs (outputFilename, std::ofstream::out); output2CISCSV_PA2(ofs,outputFilename,probeTipPointinCTFrames); } //std::cout << "\n\ncEMFMatrix rows: " << TestF.rows() << " cols: " << TestF.cols() << " values:\n\n" << TestF << std::endl; } /**************************************************************************/ /** * @brief Main function * * @param argc Number of input arguments * @param argv Pointer to input arguments * * @return int */ int main(int argc,char**argv) { ParsedCommandLineCommands pclp; readCommandLine(argc,argv,pclp); // thread pool to speed up execution std::vector<std::thread> th; for(auto&& dataSource : pclp.dataSources){ AlgorithmData ad; loadPointCloudFromFile(dataSource.calbodyPath ,ad.calbody ,pclp.debugParser ); loadPointCloudFromFile(dataSource.calreadingsPath ,ad.calreadings ,pclp.debugParser ); loadPointCloudFromFile(dataSource.empivotPath ,ad.empivot ,pclp.debugParser ); loadPointCloudFromFile(dataSource.optpivotPath ,ad.optpivot ,pclp.debugParser ); loadPointCloudFromFile(dataSource.output1Path ,ad.output1 ,pclp.debugParser ); loadPointCloudFromFile(dataSource.ct_fiducialsPath ,ad.ct_fiducials ,pclp.debugParser ); loadPointCloudFromFile(dataSource.em_fiducialsPath ,ad.em_fiducials ,pclp.debugParser ); loadPointCloudFromFile(dataSource.em_navPath ,ad.em_nav ,pclp.debugParser ); loadPointCloudFromFile(dataSource.output2Path ,ad.output2 ,pclp.debugParser ); if(pclp.threads) { // run all data sources in separate threads to speed up execution th.push_back(std::thread(generateOutputFile,ad, pclp.outputDataFolderPath, dataSource.filenamePrefix,pclp.debug)); } else { generateOutputFile(ad, pclp.outputDataFolderPath, dataSource.filenamePrefix,pclp.debug); } } //Join the threads with the main thread for(auto &t : th){ t.join(); } return 0; }
48.062937
312
0.660313
[ "object", "vector", "3d" ]
a7ddfe81856f96b13e85703b8bc223a6d40e40a8
1,772
hpp
C++
src/others/iutility.hpp
today2098/algorithm
b180355635d3d1ea0a8c3dff40ae1c9bac636f95
[ "MIT" ]
null
null
null
src/others/iutility.hpp
today2098/algorithm
b180355635d3d1ea0a8c3dff40ae1c9bac636f95
[ "MIT" ]
null
null
null
src/others/iutility.hpp
today2098/algorithm
b180355635d3d1ea0a8c3dff40ae1c9bac636f95
[ "MIT" ]
null
null
null
#ifndef ALGORITHM_IUTILITY_HPP #define ALGORITHM_IUTILITY_HPP 1 #include <algorithm> #include <cassert> #include <sstream> #include <string> #include <vector> namespace algorithm { template <typename Type> inline bool chmax(Type &a, const Type &b) { if(a < b) { a = b; return true; } return false; } template <typename Type> inline bool chmin(Type &a, const Type &b) { if(a > b) { a = b; return true; } return false; } inline bool chtoupper(char &c) { if('a' <= c && c <= 'z') { c -= 0x20; return true; } return false; } inline bool chtolower(char &c) { if('A' <= c && c <= 'Z') { c += 0x20; return true; } return false; } std::vector<int> stov(const std::string &s) { int n = s.size(); std::vector<int> v(n); for(int i = 0; i < n; ++i) v[i] = s[i]; return v; } std::string vtos(const std::vector<int> &v) { int n = v.size(); std::string s(n, 0); for(int i = 0; i < n; ++i) { assert(0 <= v[i] and v[i] < 128); s[i] = v[i]; } return s; } template <typename Type> void compress(std::vector<Type> &v) { // 座標圧縮. std::vector<Type> w = v; std::sort(w.begin(), w.end()); w.erase(unique(w.begin(), w.end()), w.end()); int n = v.size(); for(int i = 0; i < n; ++i) v[i] = std::lower_bound(w.begin(), w.end(), v[i]) - w.begin(); } std::vector<std::string> split(const std::string &s, char delim) { // 文字列分割. 指定の文字delimで分割する. std::vector<std::string> res; std::stringstream ss(s); std::string item; while(std::getline(ss, item, delim)) { if(!item.empty()) res.push_back(item); } return res; } } // namespace algorithm #endif // ALGORITHM_IUTILITY_HPP
20.847059
94
0.545147
[ "vector" ]
a7e6295ea1936eaac54e8b3c2e5f446cf35f4d0c
24,272
cpp
C++
module.cpp
mosquito/pylive555
7209baa2101d5d181fc8c47ec9b60046bc387063
[ "Apache-2.0" ]
7
2015-03-22T01:34:37.000Z
2021-12-28T13:56:07.000Z
module.cpp
mosquito/pylive555
7209baa2101d5d181fc8c47ec9b60046bc387063
[ "Apache-2.0" ]
null
null
null
module.cpp
mosquito/pylive555
7209baa2101d5d181fc8c47ec9b60046bc387063
[ "Apache-2.0" ]
6
2015-05-21T08:35:57.000Z
2021-03-05T04:28:09.000Z
// License from live555's testRTSPClient: /********** This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.) This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********/ /* Basic Python wrapper around live555's APIs for loading RTSP * streams */ #include <Python.h> #include "liveMedia.hh" #include "BasicUsageEnvironment.hh" // Forward function definitions: // RTSP 'response handlers': void continueAfterDESCRIBE(RTSPClient* rtspClient, int resultCode, char* resultString); void continueAfterSETUP(RTSPClient* rtspClient, int resultCode, char* resultString); void continueAfterPLAY(RTSPClient* rtspClient, int resultCode, char* resultString); // Other event handler functions: void subsessionAfterPlaying(void* clientData); // called when a stream's subsession (e.g., audio or video substream) ends void subsessionByeHandler(void* clientData); // called when a RTCP "BYE" is received for a subsession void streamTimerHandler(void* clientData); // called at the end of a stream's expected duration (if the stream has not already signaled its end using a RTCP "BYE") // Used to iterate through each stream's 'subsessions', setting up each one: void setupNextSubsession(RTSPClient* rtspClient); // Used to shut down and close a stream (including its "RTSPClient" object): void shutdownStream(RTSPClient* rtspClient, int exitCode = 1); #define RTSP_CLIENT_VERBOSITY_LEVEL 0 // by default, print verbose output from each "RTSPClient" // If you don't want to see debugging output for each received frame, then comment out the following line: //#define DEBUG_PRINT_EACH_RECEIVED_FRAME 1 static PyObject *error; static TaskScheduler* scheduler; static UsageEnvironment* env; static PyThreadState *threadState; // A function that outputs a string that identifies each stream (for debugging output). Modify this if you wish: UsageEnvironment& operator<<(UsageEnvironment& env, const RTSPClient& rtspClient) { return env << "[URL:\"" << rtspClient.url() << "\"]: "; } // A function that outputs a string that identifies each subsession (for debugging output). Modify this if you wish: UsageEnvironment& operator<<(UsageEnvironment& env, const MediaSubsession& subsession) { return env << subsession.mediumName() << "/" << subsession.codecName(); } void usage(UsageEnvironment& env, char const* progName) { env << "Usage: " << progName << " <rtsp-url-1> ... <rtsp-url-N>\n"; env << "\t(where each <rtsp-url-i> is a \"rtsp://\" URL)\n"; } // Define a class to hold per-stream state that we maintain throughout each stream's lifetime: class StreamClientState { public: StreamClientState(); virtual ~StreamClientState(); public: Boolean useTCP; MediaSubsessionIterator* iter; MediaSession* session; MediaSubsession* subsession; PyObject *frameCallback; TaskToken streamTimerTask; double duration; }; // If you're streaming just a single stream (i.e., just from a single URL, once), then you can define and use just a single // "StreamClientState" structure, as a global variable in your application. However, because - in this demo application - we're // showing how to play multiple streams, concurrently, we can't do that. Instead, we have to have a separate "StreamClientState" // structure for each "RTSPClient". To do this, we subclass "RTSPClient", and add a "StreamClientState" field to the subclass: class ourRTSPClient: public RTSPClient { public: static ourRTSPClient* createNew(UsageEnvironment& env, char const* rtspURL, PyObject* frameCallback, int verbosityLevel = 0, portNumBits tunnelOverHTTPPortNum = 0); protected: ourRTSPClient(UsageEnvironment& env, char const* rtspURL, PyObject* frameCallback, int verbosityLevel, portNumBits tunnelOverHTTPPortNum); // called only by createNew(); virtual ~ourRTSPClient(); public: StreamClientState scs; }; // Define a data sink (a subclass of "MediaSink") to receive the data for each subsession (i.e., each audio or video 'substream'). // In practice, this might be a class (or a chain of classes) that decodes and then renders the incoming audio or video. // Or it might be a "FileSink", for outputting the received data into a file (as is done by the "openRTSP" application). // In this example code, however, we define a simple 'dummy' sink that receives incoming data, but does nothing with it. class DummySink: public MediaSink { public: static DummySink* createNew(UsageEnvironment& env, MediaSubsession& subsession, // identifies the kind of data that's being received PyObject *frameCallback, char const* streamId = NULL, // identifies the stream itself (optional) RTSPClient *rtspClient = NULL); private: DummySink(UsageEnvironment& env, MediaSubsession& subsession, PyObject *frameCallback, char const* streamId, RTSPClient *rtspClient); // called only by "createNew()" virtual ~DummySink(); static void afterGettingFrame(void* clientData, unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned durationInMicroseconds); void afterGettingFrame(unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned durationInMicroseconds); private: // redefined virtual functions: virtual Boolean continuePlaying(); private: PyObject *frameCallback; u_int8_t* fReceiveBuffer; RTSPClient *fRTSPClient; MediaSubsession& fSubsession; char* fStreamId; int first; }; // Implementation of the RTSP 'response handlers': void continueAfterDESCRIBE(RTSPClient* rtspClient, int resultCode, char* resultString) { do { UsageEnvironment& env = rtspClient->envir(); // alias StreamClientState& scs = ((ourRTSPClient*)rtspClient)->scs; // alias if (resultCode != 0) { env << *rtspClient << "Failed to get a SDP description: " << resultString << "\n"; delete[] resultString; break; } char* const sdpDescription = resultString; //env << *rtspClient << "Got a SDP description:\n" << sdpDescription << "\n"; // Create a media session object from this SDP description: scs.session = MediaSession::createNew(env, sdpDescription); delete[] sdpDescription; // because we don't need it anymore if (scs.session == NULL) { env << *rtspClient << "Failed to create a MediaSession object from the SDP description: " << env.getResultMsg() << "\n"; break; } else if (!scs.session->hasSubsessions()) { env << *rtspClient << "This session has no media subsessions (i.e., no \"m=\" lines)\n"; break; } // Then, create and set up our data source objects for the session. We do this by iterating over the session's 'subsessions', // calling "MediaSubsession::initiate()", and then sending a RTSP "SETUP" command, on each one. // (Each 'subsession' will have its own data source.) scs.iter = new MediaSubsessionIterator(*scs.session); setupNextSubsession(rtspClient); return; // nocommit why have a while loop that runs only once? // there is no continue? } while (0); // An unrecoverable error occurred with this stream. shutdownStream(rtspClient); } void setupNextSubsession(RTSPClient* rtspClient) { UsageEnvironment& env = rtspClient->envir(); // alias StreamClientState& scs = ((ourRTSPClient*)rtspClient)->scs; // alias scs.subsession = scs.iter->next(); if (scs.subsession != NULL) { // Only tap the video stream (the metadata stream never // seems to send anything): //if (strcmp(scs.subsession->codecName(), "H264")) { //setupNextSubsession(rtspClient); //return; //} if (!scs.subsession->initiate()) { env << *rtspClient << "Failed to initiate the \"" << *scs.subsession << "\" subsession: " << env.getResultMsg() << "\n"; setupNextSubsession(rtspClient); // give up on this subsession; go to the next one } else { env << *rtspClient << "Initiated the \"" << *scs.subsession << "\" subsession (client ports " << scs.subsession->clientPortNum() << "-" << scs.subsession->clientPortNum()+1 << ")\n"; // Continue setting up this subsession, by sending a RTSP "SETUP" command: rtspClient->sendSetupCommand(*scs.subsession, continueAfterSETUP, False, scs.useTCP); } return; } // We've finished setting up all of the subsessions. Now, send a RTSP "PLAY" command to start the streaming: if (scs.session->absStartTime() != NULL) { // Special case: The stream is indexed by 'absolute' time, so send an appropriate "PLAY" command: rtspClient->sendPlayCommand(*scs.session, continueAfterPLAY, scs.session->absStartTime(), scs.session->absEndTime()); } else { scs.duration = scs.session->playEndTime() - scs.session->playStartTime(); rtspClient->sendPlayCommand(*scs.session, continueAfterPLAY); } } void continueAfterSETUP(RTSPClient* rtspClient, int resultCode, char* resultString) { do { UsageEnvironment& env = rtspClient->envir(); // alias StreamClientState& scs = ((ourRTSPClient*)rtspClient)->scs; // alias if (resultCode != 0) { env << *rtspClient << "Failed to set up the \"" << *scs.subsession << "\" subsession: " << resultString << "\n"; break; } env << *rtspClient << "Set up the \"" << *scs.subsession << "\" subsession (client ports " << scs.subsession->clientPortNum() << "-" << scs.subsession->clientPortNum()+1 << ")\n"; // Having successfully setup the subsession, create a data sink for it, and call "startPlaying()" on it. // (This will prepare the data sink to receive data; the actual flow of data from the client won't start happening until later, // after we've sent a RTSP "PLAY" command.) scs.subsession->sink = DummySink::createNew(env, *scs.subsession, scs.frameCallback, rtspClient->url(), rtspClient); // perhaps use your own custom "MediaSink" subclass instead if (scs.subsession->sink == NULL) { env << *rtspClient << "Failed to create a data sink for the \"" << *scs.subsession << "\" subsession: " << env.getResultMsg() << "\n"; break; } env << *rtspClient << "Created a data sink for the \"" << *scs.subsession << "\" subsession\n"; scs.subsession->miscPtr = rtspClient; // a hack to let subsession handle functions get the "RTSPClient" from the subsession scs.subsession->sink->startPlaying(*(scs.subsession->readSource()), subsessionAfterPlaying, scs.subsession); // Also set a handler to be called if a RTCP "BYE" arrives for this subsession: if (scs.subsession->rtcpInstance() != NULL) { scs.subsession->rtcpInstance()->setByeHandler(subsessionByeHandler, scs.subsession); } } while (0); delete[] resultString; // Set up the next subsession, if any: setupNextSubsession(rtspClient); } void continueAfterPLAY(RTSPClient* rtspClient, int resultCode, char* resultString) { Boolean success = False; do { UsageEnvironment& env = rtspClient->envir(); // alias StreamClientState& scs = ((ourRTSPClient*)rtspClient)->scs; // alias if (resultCode != 0) { env << *rtspClient << "Failed to start playing session: " << resultString << "\n"; break; } // Set a timer to be handled at the end of the stream's expected duration (if the stream does not already signal its end // using a RTCP "BYE"). This is optional. If, instead, you want to keep the stream active - e.g., so you can later // 'seek' back within it and do another RTSP "PLAY" - then you can omit this code. // (Alternatively, if you don't want to receive the entire stream, you could set this timer for some shorter value.) if (scs.duration > 0) { unsigned const delaySlop = 2; // number of seconds extra to delay, after the stream's expected duration. (This is optional.) scs.duration += delaySlop; unsigned uSecsToDelay = (unsigned)(scs.duration*1000000); scs.streamTimerTask = env.taskScheduler().scheduleDelayedTask(uSecsToDelay, (TaskFunc*)streamTimerHandler, rtspClient); } env << *rtspClient << "Started playing session"; if (scs.duration > 0) { env << " (for up to " << scs.duration << " seconds)"; } env << "...\n"; success = True; } while (0); delete[] resultString; if (!success) { // An unrecoverable error occurred with this stream. shutdownStream(rtspClient); } } // Implementation of the other event handlers: void subsessionAfterPlaying(void* clientData) { MediaSubsession* subsession = (MediaSubsession*)clientData; RTSPClient* rtspClient = (RTSPClient*)(subsession->miscPtr); // Begin by closing this subsession's stream: Medium::close(subsession->sink); subsession->sink = NULL; // Next, check whether *all* subsessions' streams have now been closed: MediaSession& session = subsession->parentSession(); MediaSubsessionIterator iter(session); while ((subsession = iter.next()) != NULL) { if (subsession->sink != NULL) return; // this subsession is still active } // All subsessions' streams have now been closed, so shutdown the client: shutdownStream(rtspClient); } void subsessionByeHandler(void* clientData) { MediaSubsession* subsession = (MediaSubsession*)clientData; RTSPClient* rtspClient = (RTSPClient*)subsession->miscPtr; UsageEnvironment& env = rtspClient->envir(); // alias env << *rtspClient << "Received RTCP \"BYE\" on \"" << *subsession << "\" subsession\n"; // Now act as if the subsession had closed: subsessionAfterPlaying(subsession); } void streamTimerHandler(void* clientData) { ourRTSPClient* rtspClient = (ourRTSPClient*)clientData; StreamClientState& scs = rtspClient->scs; // alias scs.streamTimerTask = NULL; // Shut down the stream: shutdownStream(rtspClient); } void shutdownStream(RTSPClient* rtspClient, int exitCode) { UsageEnvironment& env = rtspClient->envir(); // alias StreamClientState& scs = ((ourRTSPClient*)rtspClient)->scs; // alias // First, check whether any subsessions have still to be closed: if (scs.session != NULL) { Boolean someSubsessionsWereActive = False; MediaSubsessionIterator iter(*scs.session); MediaSubsession* subsession; while ((subsession = iter.next()) != NULL) { if (subsession->sink != NULL) { Medium::close(subsession->sink); subsession->sink = NULL; if (subsession->rtcpInstance() != NULL) { // nocommit //subsession->rtcpInstance()->setByeHandler(NULL, NULL); // in case the server sends a RTCP "BYE" while handling "TEARDOWN" } someSubsessionsWereActive = True; } } if (someSubsessionsWereActive) { // Send a RTSP "TEARDOWN" command, to tell the server to shutdown the stream. // Don't bother handling the response to the // "TEARDOWN". rtspClient->sendTeardownCommand(*scs.session, NULL); } } env << *rtspClient << "Closing the stream.\n"; Medium::close(rtspClient); // Note that this will also cause this stream's "StreamClientState" structure to get reclaimed. } // Implementation of "ourRTSPClient": ourRTSPClient* ourRTSPClient::createNew(UsageEnvironment& env, char const* rtspURL, PyObject* frameCallback, int verbosityLevel, portNumBits tunnelOverHTTPPortNum) { return new ourRTSPClient(env, rtspURL, frameCallback, verbosityLevel, tunnelOverHTTPPortNum); } ourRTSPClient::ourRTSPClient(UsageEnvironment& env, char const* rtspURL, PyObject* frameCallback, int verbosityLevel, portNumBits tunnelOverHTTPPortNum) : RTSPClient(env, rtspURL, verbosityLevel, "", tunnelOverHTTPPortNum, -1) { Py_INCREF(frameCallback); scs.frameCallback = frameCallback; } ourRTSPClient::~ourRTSPClient() { } // Implementation of "StreamClientState": StreamClientState::StreamClientState() : iter(NULL), session(NULL), subsession(NULL), streamTimerTask(NULL), duration(0.0) { } StreamClientState::~StreamClientState() { delete iter; if (session != NULL) { // We also need to delete "session", and unschedule "streamTimerTask" (if set) UsageEnvironment& env = session->envir(); // alias env.taskScheduler().unscheduleDelayedTask(streamTimerTask); Medium::close(session); } } // Implementation of "DummySink": // Define the size of the buffer that we'll use: #define DUMMY_SINK_RECEIVE_BUFFER_SIZE 1024*1024 DummySink* DummySink::createNew(UsageEnvironment& env, MediaSubsession& subsession, PyObject *frameCallback, char const* streamId, RTSPClient *rtspClient) { return new DummySink(env, subsession, frameCallback, streamId, rtspClient); } DummySink::DummySink(UsageEnvironment& env, MediaSubsession& subsession, PyObject *frameCallbackIn, char const* streamId, RTSPClient *rtspClient) : MediaSink(env), fSubsession(subsession) { fStreamId = strDup(streamId); fReceiveBuffer = new u_int8_t[DUMMY_SINK_RECEIVE_BUFFER_SIZE]; frameCallback = frameCallbackIn; fRTSPClient = rtspClient; first = 1; } DummySink::~DummySink() { delete[] fReceiveBuffer; delete[] fStreamId; Py_DECREF(frameCallback); } void DummySink::afterGettingFrame(void* clientData, unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned durationInMicroseconds) { DummySink* sink = (DummySink*)clientData; sink->afterGettingFrame(frameSize, numTruncatedBytes, presentationTime, durationInMicroseconds); } void DummySink::afterGettingFrame(unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned durationInUS) { PyEval_RestoreThread(threadState); if (first == 1) { // NOTE: only necessary for H264 I think? unsigned numSPropRecords; SPropRecord* sPropRecords = parseSPropParameterSets(fSubsession.fmtp_spropparametersets(), numSPropRecords); for(unsigned i=0;i<numSPropRecords;i++) { PyObject *result = PyEval_CallFunction(frameCallback, "sy#iii", fSubsession.codecName(), sPropRecords[i].sPropBytes, sPropRecords[i].sPropLength, -1, -1, -1); if (result == NULL) { fprintf(stderr, "Exception in RTSP callback:\n"); PyErr_PrintEx(1); fSource->stopGettingFrames(); env->taskScheduler().scheduleDelayedTask(0, (TaskFunc*)shutdownStream, fRTSPClient); PyEval_SaveThread(); return; //break; } } delete[] sPropRecords; first = 0; } // TODO: can we somehow avoid ... making a full copy here: //printf("%d bytes\n", frameSize);fflush(stdout); PyObject *result = PyEval_CallFunction(frameCallback, "sy#llI", fSubsession.codecName(), fReceiveBuffer, frameSize, presentationTime.tv_sec, presentationTime.tv_usec, durationInUS); if (result == NULL) { fprintf(stderr, "Exception in RTSP callback:"); PyErr_PrintEx(1); fSource->stopGettingFrames(); env->taskScheduler().scheduleDelayedTask(0, (TaskFunc*)shutdownStream, fRTSPClient); PyEval_SaveThread(); return; } PyEval_SaveThread(); // We've just received a frame of data. (Optionally) print out information about it: #ifdef DEBUG_PRINT_EACH_RECEIVED_FRAME if (fStreamId != NULL) envir() << "Stream \"" << fStreamId << "\"; "; envir() << fSubsession.mediumName() << "/" << fSubsession.codecName() << ":\tReceived " << frameSize << " bytes"; if (numTruncatedBytes > 0) envir() << " (with " << numTruncatedBytes << " bytes truncated)"; char uSecsStr[6+1]; // used to output the 'microseconds' part of the presentation time sprintf(uSecsStr, "%06u", (unsigned)presentationTime.tv_usec); envir() << ".\tPresentation time: " << (int)presentationTime.tv_sec << "." << uSecsStr; if (fSubsession.rtpSource() != NULL && !fSubsession.rtpSource()->hasBeenSynchronizedUsingRTCP()) { envir() << "!"; // mark the debugging output to indicate that this presentation time is not RTCP-synchronized } #ifdef DEBUG_PRINT_NPT envir() << "\tNPT: " << fSubsession.getNormalPlayTime(presentationTime); #endif envir() << "\n"; #endif // Then continue, to request the next frame of data: continuePlaying(); } Boolean DummySink::continuePlaying() { if (fSource == NULL) return False; // sanity check (should not happen) // Request the next frame of data from our input source. "afterGettingFrame()" will get called later, when it arrives: fSource->getNextFrame(fReceiveBuffer, DUMMY_SINK_RECEIVE_BUFFER_SIZE, afterGettingFrame, this, onSourceClosure, this); return True; } static PyObject * startRTSP(PyObject *self, PyObject *args) { const char *rtspURL; PyObject *frameCallback; int useTCP = 1; if (!PyArg_ParseTuple(args, "sO|i", &rtspURL, &frameCallback, &useTCP)) { return NULL; } if (!PyCallable_Check(frameCallback)) { PyErr_SetString(error, "callback must be a callable"); return NULL; } // Begin by creating a "RTSPClient" object. Note that there is a separate "RTSPClient" object for each stream that we wish // to receive (even if more than stream uses the same "rtsp://" URL). ourRTSPClient* rtspClient = ourRTSPClient::createNew(*env, rtspURL, frameCallback, RTSP_CLIENT_VERBOSITY_LEVEL); if (rtspClient == NULL) { PyErr_SetString(error, "failed to create RTSPClient"); return NULL; } rtspClient->scs.useTCP = useTCP != 0; // Next, send a RTSP "DESCRIBE" command, to get a SDP description for the stream. // Note that this command - like all RTSP commands - is sent asynchronously; we do not block, waiting for a response. // Instead, the following function call returns immediately, and we handle the RTSP response later, from within the event loop: rtspClient->sendDescribeCommand(continueAfterDESCRIBE); Py_INCREF(Py_None); return Py_None; } static char stopEventLoopFlag = 0; static PyObject * runEventLoop(PyObject *self, PyObject *args) { stopEventLoopFlag = 0; // All subsequent activity takes place within the event loop: threadState = PyEval_SaveThread(); env->taskScheduler().doEventLoop(&stopEventLoopFlag); PyEval_RestoreThread(threadState); Py_INCREF(Py_None); return Py_None; } static PyObject * stopEventLoop(PyObject *self, PyObject *args) { stopEventLoopFlag = 1; Py_INCREF(Py_None); return Py_None; } static PyMethodDef moduleMethods[] = { {"startRTSP", startRTSP, METH_VARARGS, "Start loading frames from the provided RTSP url. First argument is the URL string (should be rtsp://username:password@host/...; second argument is a callback function called once per received frame; third agument is False if UDP transport should be used and True if TCP transport should be used."}, {"runEventLoop", runEventLoop, METH_NOARGS, "Run the event loop."}, {"stopEventLoop", stopEventLoop, METH_NOARGS, "Stop the event loop, which will cause runEventLoop (in another thread) to stop and return."}, {NULL, NULL, 0, NULL} /* Sentinel */ }; static struct PyModuleDef module = { PyModuleDef_HEAD_INIT, "live555", /* name of module */ NULL, /* module documentation, may be NULL */ -1, /* size of per-interpreter state of the module, or -1 if the module keeps state in global variables. */ moduleMethods }; PyMODINIT_FUNC PyInit_live555(void) { PyObject *m; m = PyModule_Create(&module); if (m == NULL) { return NULL; } error = PyErr_NewException("live555.error", NULL, NULL); Py_INCREF(error); PyModule_AddObject(m, "error", error); // Begin by setting up our usage environment: scheduler = BasicTaskScheduler::createNew(); env = BasicUsageEnvironment::createNew(*scheduler); return m; }
39.211632
342
0.706452
[ "object" ]
a7e665a0e330d7388179aa8859053ac7cd4ce1d8
4,448
cpp
C++
engine/core/src/TPipelineDescriptorSet.cpp
FuXiii/Turbo
e68237a43db0c5a7f1b75423a83ad285d4e9c0ff
[ "MIT" ]
2
2019-08-05T09:14:43.000Z
2019-08-05T09:14:47.000Z
engine/core/src/TPipelineDescriptorSet.cpp
FuXiii/Turbo
e68237a43db0c5a7f1b75423a83ad285d4e9c0ff
[ "MIT" ]
null
null
null
engine/core/src/TPipelineDescriptorSet.cpp
FuXiii/Turbo
e68237a43db0c5a7f1b75423a83ad285d4e9c0ff
[ "MIT" ]
null
null
null
#include "TPipelineDescriptorSet.h" #include "TDescriptorSet.h" #include "TException.h" #include "TPipelineLayout.h" #include <sstream> void Turbo::Core::TPipelineDescriptorSet::InternalCreate() { std::vector<TDescriptorSetLayout *> descriptor_set_layouts = this->pipelineLayout->GetDescriptorSetLayouts(); for (TDescriptorSetLayout *descriptor_set_layout_item : descriptor_set_layouts) { descriptorSets.push_back(new TDescriptorSet(this->descriptorPool, descriptor_set_layout_item)); } } void Turbo::Core::TPipelineDescriptorSet::InternalDestroy() { for (TDescriptorSet *descriptor_set_item : this->descriptorSets) { delete descriptor_set_item; } this->descriptorSets.clear(); } Turbo::Core::TPipelineDescriptorSet::TPipelineDescriptorSet(TDescriptorPool *descriptorPool, TPipelineLayout *pipelineLayout) { if (descriptorPool != nullptr && pipelineLayout != nullptr) { this->descriptorPool = descriptorPool; this->pipelineLayout = pipelineLayout; this->InternalCreate(); } else { throw Turbo::Core::TException(TResult::INVALID_PARAMETER, "Turbo::Core::TPipelineDescriptorSet::TPipelineDescriptorSet"); } } Turbo::Core::TPipelineDescriptorSet::~TPipelineDescriptorSet() { this->InternalDestroy(); } const std::vector<Turbo::Core::TDescriptorSet *> &Turbo::Core::TPipelineDescriptorSet::GetDescriptorSet() { return this->descriptorSets; } void Turbo::Core::TPipelineDescriptorSet::BindData(uint32_t set, uint32_t binding, uint32_t dstArrayElement, std::vector<TBuffer *> &buffers) { for (TDescriptorSet *descriptor_set_item : this->descriptorSets) { if (descriptor_set_item->GetSet() == set) { // TODO: to find is have the binding descriptor? throw TException descriptor_set_item->BindData(binding, dstArrayElement, buffers); return; } } std::stringstream ss; ss << "There not have TDescriptorSet set=" << set << " ,please check the number of set"; throw Turbo::Core::TException(TResult::UNSUPPORTED, "Turbo::Core::TPipelineDescriptorSet::BindData", ss.str()); } void Turbo::Core::TPipelineDescriptorSet::BindData(uint32_t set, uint32_t binding, uint32_t dstArrayElement, std::vector<std::pair<TImageView *, TSampler *>> &combinedImageSamplers) { for (TDescriptorSet *descriptor_set_item : this->descriptorSets) { if (descriptor_set_item->GetSet() == set) { // TODO: to find is have the binding descriptor? throw TException descriptor_set_item->BindData(binding, dstArrayElement, combinedImageSamplers); return; } } std::stringstream ss; ss << "There not have TDescriptorSet set=" << set << " ,please check the number of set"; throw Turbo::Core::TException(TResult::UNSUPPORTED, "Turbo::Core::TPipelineDescriptorSet::BindData", ss.str()); } void Turbo::Core::TPipelineDescriptorSet::BindData(uint32_t set, uint32_t binding, uint32_t dstArrayElement, std::vector<TImageView *> &imageViews) { for (TDescriptorSet *descriptor_set_item : this->descriptorSets) { if (descriptor_set_item->GetSet() == set) { // TODO: to find is have the binding descriptor? throw TException descriptor_set_item->BindData(binding, dstArrayElement, imageViews); return; } } std::stringstream ss; ss << "There not have TDescriptorSet set=" << set << " ,please check the number of set"; throw Turbo::Core::TException(TResult::UNSUPPORTED, "Turbo::Core::TPipelineDescriptorSet::BindData", ss.str()); } void Turbo::Core::TPipelineDescriptorSet::BindData(uint32_t set, uint32_t binding, uint32_t dstArrayElement, std::vector<TSampler *> &sampler) { for (TDescriptorSet *descriptor_set_item : this->descriptorSets) { if (descriptor_set_item->GetSet() == set) { // TODO: to find is have the binding descriptor? throw TException descriptor_set_item->BindData(binding, dstArrayElement, sampler); return; } } std::stringstream ss; ss << "There not have TDescriptorSet set=" << set << " ,please check the number of set"; throw Turbo::Core::TException(TResult::UNSUPPORTED, "Turbo::Core::TPipelineDescriptorSet::BindData", ss.str()); } std::string Turbo::Core::TPipelineDescriptorSet::ToString() { return std::string(); }
37.378151
181
0.695144
[ "vector" ]
a7e787934462288b79ee7d241145e636fffe1a34
1,238
cpp
C++
GraphicObject/Picture.cpp
invader35/SEN2UE11
fb1333087b66f7965c433b23177a00c21d38579e
[ "MIT" ]
null
null
null
GraphicObject/Picture.cpp
invader35/SEN2UE11
fb1333087b66f7965c433b23177a00c21d38579e
[ "MIT" ]
null
null
null
GraphicObject/Picture.cpp
invader35/SEN2UE11
fb1333087b66f7965c433b23177a00c21d38579e
[ "MIT" ]
null
null
null
#include "Picture.h" #include <algorithm> Picture::Picture() { } Picture::~Picture() { } void Picture::Add(GraphicObject* Element){ mElements.push_back(Element); } void Picture::draw(){ std::vector<GraphicObject *>::iterator begin = mElements.begin(); while(begin != mElements.end()){ (*begin)->draw(); begin++; } } TBox Picture::getBoundingBox() const { std::vector<TBox> boundingBoxes; std::vector<GraphicObject *>::const_iterator begin = mElements.begin(); while(begin != mElements.end()){ boundingBoxes.push_back((*begin)->getBoundingBox()); begin++; } return *std::max_element(boundingBoxes.begin(), boundingBoxes.end()); } size_t Picture::getNumOfElements() const{ return mElements.size(); } void Picture::moveToHelper(TCoord const &position) { std::vector<GraphicObject *>::iterator begin = mElements.begin(); while (begin != mElements.end()) { (*begin)->moveTo(TCoord( ( (*begin)->getPosition().first - mPosition.first + position.first ), ((*begin)->getPosition().second - mPosition.second + position.second) )); begin++; } mPosition.first = position.first; mPosition.second = position.second; }
25.791667
102
0.641357
[ "vector" ]
a7eb5f58d37e31e9996ba803f9815e7e90db623b
117,360
cxx
C++
panda/src/downloader/httpChannel.cxx
ethanlindley/panda3d
2bc35287d1af4e2c5d2f8a3c58d62d35446ca6f7
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
panda/src/downloader/httpChannel.cxx
ethanlindley/panda3d
2bc35287d1af4e2c5d2f8a3c58d62d35446ca6f7
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
panda/src/downloader/httpChannel.cxx
ethanlindley/panda3d
2bc35287d1af4e2c5d2f8a3c58d62d35446ca6f7
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
/** * PANDA 3D SOFTWARE * Copyright (c) Carnegie Mellon University. All rights reserved. * * All use of this software is subject to the terms of the revised BSD * license. You should have received a copy of this license along * with this source code in a file named "LICENSE." * * @file httpChannel.cxx * @author drose * @date 2002-09-24 */ #include "httpChannel.h" #include "httpClient.h" #include "httpCookie.h" #include "bioStream.h" #include "chunkedStream.h" #include "identityStream.h" #include "config_downloader.h" #include "virtualFileSystem.h" #include "virtualFileMountHTTP.h" #include "ramfile.h" #include "globPattern.h" #include <stdio.h> #ifdef HAVE_OPENSSL #include "openSSLWrapper.h" #if defined(WIN32_VC) || defined(WIN64_VC) #include <WinSock2.h> #include <windows.h> // for select() #undef X509_NAME #endif // WIN32_VC TypeHandle HTTPChannel::_type_handle; #define _NOTIFY_HTTP_CHANNEL_ID "[" << this << "] " /** * */ HTTPChannel:: HTTPChannel(HTTPClient *client) : _client(client) { if (downloader_cat.is_debug()) { downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID << "created.\n"; } ConfigVariableDouble extra_ssl_handshake_time ("extra-ssl-handshake-time", 0.0, PRC_DESC("This specifies how much extra time to try to establish" "the ssl handshake before we bail.")); _extra_ssl_handshake_time = extra_ssl_handshake_time; _proxy_next_index = 0; _persistent_connection = false; _allow_proxy = true; _proxy_tunnel = http_proxy_tunnel; _connect_timeout = http_connect_timeout; _http_timeout = http_timeout; _skip_body_size = http_skip_body_size; _idle_timeout = http_idle_timeout; _blocking_connect = false; _download_throttle = download_throttle; _max_bytes_per_second = downloader_byte_rate; _seconds_per_update = downloader_frequency; _max_updates_per_second = 1.0f / _seconds_per_update; _bytes_per_update = int(_max_bytes_per_second * _seconds_per_update); // _nonblocking is true if the socket is actually in non-blocking mode. _nonblocking = false; // _wanted_nonblocking is true if the user specifically requested one of the // non-blocking interfaces. It is false if the socket is only incidentally // non-blocking (for instance, because SIMPLE_THREADS is on). _wanted_nonblocking = false; _want_ssl = false; _proxy_serves_document = false; _proxy_tunnel_now = false; _first_byte_requested = 0; _last_byte_requested = 0; _first_byte_delivered = 0; _last_byte_delivered = 0; _read_index = 0; _expected_file_size = 0; _file_size = 0; _transfer_file_size = 0; _got_expected_file_size = false; _got_file_size = false; _got_transfer_file_size = false; _bytes_downloaded = 0; _bytes_requested = 0; _status_entry = StatusEntry(); _response_type = RT_none; _http_version = _client->get_http_version(); _http_version_string = _client->get_http_version_string(); _state = S_new; _done_state = S_new; _started_download = false; _sent_so_far = 0; _body_stream = NULL; _owns_body_stream = false; _sbio = NULL; _cipher_list = _client->get_cipher_list(); _last_status_code = 0; _last_run_time = 0.0f; _download_to_ramfile = NULL; _download_to_stream = NULL; } /** * */ HTTPChannel:: ~HTTPChannel() { if (downloader_cat.is_debug()) { downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID << "destroyed.\n"; } close_connection(); reset_download_to(); } /** * Returns the string as returned by the server describing the status code for * humans. This may or may not be meaningful. */ string HTTPChannel:: get_status_string() const { switch (_status_entry._status_code) { case SC_incomplete: return "Connection in progress"; case SC_internal_error: return "Internal error"; case SC_no_connection: return "No connection"; case SC_timeout: return "Timeout on connection"; case SC_lost_connection: return "Lost connection"; case SC_non_http_response: return "Non-HTTP response"; case SC_invalid_http: return "Could not understand HTTP response"; case SC_socks_invalid_version: return "Unsupported SOCKS version"; case SC_socks_no_acceptable_login_method: return "No acceptable SOCKS login method"; case SC_socks_refused: return "SOCKS proxy refused connection"; case SC_socks_no_connection: return "SOCKS proxy unable to connect"; case SC_ssl_internal_failure: return "SSL internal failure"; case SC_ssl_no_handshake: return "No SSL handshake"; case SC_http_error_watermark: // This shouldn't be triggered. return "Internal error"; case SC_ssl_invalid_server_certificate: return "SSL invalid server certificate"; case SC_ssl_unexpected_server: return "Unexpected SSL server"; case SC_download_open_error: return "Error opening file"; case SC_download_write_error: return "Error writing to disk"; case SC_download_invalid_range: return "Invalid subrange requested"; } return _status_entry._status_string; } /** * Returns the HTML header value associated with the indicated key, or empty * string if the key was not defined in the message returned by the server. */ string HTTPChannel:: get_header_value(const string &key) const { Headers::const_iterator hi = _headers.find(downcase(key)); if (hi != _headers.end()) { return (*hi).second; } return string(); } /** * Returns true if the server has indicated it will close the connection after * this document has been read, or false if it will remain open (and future * documents may be requested on the same connection). */ bool HTTPChannel:: will_close_connection() const { if (get_http_version() < HTTPEnum::HV_11) { // pre-HTTP 1.1 always closes. return true; } string connection = get_header_value("Connection"); if (downcase(connection) == "close") { // The server says it will close. return true; } if (connection.empty() && !get_persistent_connection()) { // The server didn't say, but we asked it to close. return true; } // Assume the server will keep it open. return false; } /** * Returns the size of the file, if it is known. Returns the value set by * set_expected_file_size() if the file size is not known, or 0 if this value * was not set. * * If the file is dynamically generated, the size may not be available until a * read has started (e.g. open_read_body() has been called); and even then it * may increase as more of the file is read due to the nature of HTTP/1.1 * requests which can change their minds midstream about how much data they're * sending you. */ streamsize HTTPChannel:: get_file_size() const { if (_got_file_size) { return _file_size; } else if (_got_transfer_file_size) { return _transfer_file_size; } else if (_got_expected_file_size) { return _expected_file_size; } else { return 0; } } /** * Outputs a list of all headers defined by the server to the indicated output * stream. */ void HTTPChannel:: write_headers(ostream &out) const { Headers::const_iterator hi; for (hi = _headers.begin(); hi != _headers.end(); ++hi) { out << (*hi).first << ": " << (*hi).second << "\n"; } } /** * This must be called from time to time when non-blocking I/O is in use. It * checks for data coming in on the socket and writes data out to the socket * when possible, and does whatever processing is required towards completing * the current task. * * The return value is true if the task is still pending (and run() will need * to be called again in the future), or false if the current task is * complete. */ bool HTTPChannel:: run() { if (downloader_cat.is_spam()) { downloader_cat.spam() << _NOTIFY_HTTP_CHANNEL_ID << "run().\n"; } if (_state == _done_state || _state == S_failure) { clear_extra_headers(); if (!reached_done_state()) { return false; } } if (_started_download) { if (_wanted_nonblocking && _download_throttle) { double now = TrueClock::get_global_ptr()->get_short_time(); double elapsed = now - _last_run_time; if (elapsed < _seconds_per_update) { // Come back later. thread_yield(); return true; } int num_potential_updates = (int)(elapsed / _seconds_per_update); _last_run_time = now; _bytes_requested += _bytes_per_update * num_potential_updates; if (downloader_cat.is_spam()) { downloader_cat.spam() << _NOTIFY_HTTP_CHANNEL_ID << "elapsed = " << elapsed << " num_potential_updates = " << num_potential_updates << " bytes_requested = " << _bytes_requested << "\n"; } } bool repeat_later = false; switch (_download_dest) { case DD_none: // We're done. break; case DD_file: repeat_later = run_download_to_file(); break; case DD_ram: repeat_later = run_download_to_ram(); break; case DD_stream: repeat_later = run_download_to_stream(); break; } if (repeat_later) { thread_yield(); } return repeat_later; } /* if (downloader_cat.is_spam()) { downloader_cat.spam() << _NOTIFY_HTTP_CHANNEL_ID << "begin run(), _state = " << _state << ", _done_state = " << _done_state << "\n"; } */ if (_state == _done_state) { return reached_done_state(); } bool repeat_later; do { // If we're in a state that expects to have a connection already (that is, // any state other that S_try_next_proxy), then reestablish the connection // if it has been dropped. if (_bio.is_null() && _state != S_try_next_proxy) { if (_connect_count > http_max_connect_count) { // Too many connection attempts; just give up. We should never // trigger this failsafe, since the code in each individual case has // similar logic to prevent more than two consecutive lost // connections. downloader_cat.warning() << _NOTIFY_HTTP_CHANNEL_ID << "Too many lost connections, giving up.\n"; _status_entry._status_code = SC_lost_connection; _state = S_failure; return false; } // No connection. Attempt to establish one. URLSpec url; if (_proxy.empty()) { url = _request.get_url(); } else { url = _proxy; } _bio = new BioPtr(url); _source = new BioStreamPtr(new BioStream(_bio)); if (_nonblocking) { _bio->set_nbio(true); } if (downloader_cat.is_debug()) { if (_connect_count > 0) { downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID << "Reconnecting to " << _bio->get_server_name() << " port " << _bio->get_port() << "\n"; } else { downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID << "Connecting to " << _bio->get_server_name() << " port " << _bio->get_port() << "\n"; } } _state = S_connecting; _started_connecting_time = TrueClock::get_global_ptr()->get_short_time(); _connect_count++; } /* if (downloader_cat.is_spam()) { downloader_cat.spam() << _NOTIFY_HTTP_CHANNEL_ID << "continue run(), _state = " << _state << "\n"; } */ switch (_state) { case S_try_next_proxy: repeat_later = run_try_next_proxy(); break; case S_connecting: repeat_later = run_connecting(); break; case S_connecting_wait: repeat_later = run_connecting_wait(); break; case S_http_proxy_ready: repeat_later = run_http_proxy_ready(); break; case S_http_proxy_request_sent: repeat_later = run_http_proxy_request_sent(); break; case S_http_proxy_reading_header: repeat_later = run_http_proxy_reading_header(); break; case S_socks_proxy_greet: repeat_later = run_socks_proxy_greet(); break; case S_socks_proxy_greet_reply: repeat_later = run_socks_proxy_greet_reply(); break; case S_socks_proxy_connect: repeat_later = run_socks_proxy_connect(); break; case S_socks_proxy_connect_reply: repeat_later = run_socks_proxy_connect_reply(); break; case S_setup_ssl: repeat_later = run_setup_ssl(); break; case S_ssl_handshake: repeat_later = run_ssl_handshake(); break; case S_ready: repeat_later = run_ready(); break; case S_request_sent: repeat_later = run_request_sent(); break; case S_reading_header: repeat_later = run_reading_header(); break; case S_start_direct_file_read: repeat_later = run_start_direct_file_read(); break; case S_read_header: repeat_later = run_read_header(); break; case S_begin_body: repeat_later = run_begin_body(); break; case S_reading_body: repeat_later = run_reading_body(); break; case S_read_body: repeat_later = run_read_body(); break; case S_read_trailer: repeat_later = run_read_trailer(); break; default: downloader_cat.warning() << _NOTIFY_HTTP_CHANNEL_ID << "Unhandled state " << _state << "\n"; return false; } if (_state == _done_state || _state == S_failure) { clear_extra_headers(); // We've reached our terminal state. return reached_done_state(); } thread_consider_yield(); } while (!repeat_later || _bio.is_null()); /* if (downloader_cat.is_spam()) { downloader_cat.spam() << _NOTIFY_HTTP_CHANNEL_ID << "later run(), _state = " << _state << ", _done_state = " << _done_state << "\n"; } */ thread_yield(); return true; } /** * Returns a newly-allocated istream suitable for reading the body of the * document. This may only be called immediately after a call to * get_document() or post_form(), or after a call to run() has returned false. * * Note that, in nonblocking mode, the returned stream may report an early * EOF, even before the actual end of file. When this happens, you should * call stream->is_closed() to determine whether you should attempt to read * some more later. * * The user is responsible for passing the returned istream to * close_read_body() later. */ ISocketStream *HTTPChannel:: open_read_body() { reset_body_stream(); if ((_state != S_read_header && _state != S_begin_body) || _source.is_null()) { return NULL; } string transfer_coding = downcase(get_header_value("Transfer-Encoding")); ISocketStream *result; if (transfer_coding == "chunked") { // "chunked" transfer encoding. This means we will have to decode the // length of the file as we read it in chunks. The IChunkedStream does // this. _state = S_reading_body; _read_index++; result = new IChunkedStream(_source, this); } else { // If the transfer encoding is anything else, assume "identity". This is // just the literal characters following the header, up until _file_size // bytes have been read (if content-length was specified), or till end of // file otherwise. _state = S_reading_body; _read_index++; result = new IIdentityStream(_source, this, _got_file_size, _file_size); } result->_channel = this; _body_stream = result; _owns_body_stream = false; return result; } /** * Closes a file opened by a previous call to open_read_body(). This really * just deletes the istream pointer, but it is recommended to use this * interface instead of deleting it explicitly, to help work around compiler * issues. */ void HTTPChannel:: close_read_body(istream *stream) const { if (stream != (istream *)NULL) { // For some reason--compiler bug in gcc 3.2?--explicitly deleting the // stream pointer does not call the appropriate global delete function; // instead apparently calling the system delete function. So we call the // delete function by hand instead. #if !defined(USE_MEMORY_NOWRAPPERS) && defined(REDEFINE_GLOBAL_OPERATOR_NEW) stream->~istream(); (*global_operator_delete)(stream); #else delete stream; #endif } } /** * Specifies the name of a file to download the resulting document to. This * should be called immediately after get_document() or begin_get_document() * or related functions. * * In the case of the blocking I/O methods like get_document(), this function * will download the entire document to the file and return true if it was * successfully downloaded, false otherwise. * * In the case of non-blocking I/O methods like begin_get_document(), this * function simply indicates an intention to download to the indicated file. * It returns true if the file can be opened for writing, false otherwise, but * the contents will not be completely downloaded until run() has returned * false. At this time, it is possible that a communications error will have * left a partial file, so is_download_complete() may be called to test this. * * If subdocument_resumes is true and the document in question was previously * requested as a subdocument (i.e. get_subdocument() with a first_byte value * greater than zero), this will automatically seek to the appropriate byte * within the file for writing the output. In this case, the file must * already exist and must have at least first_byte bytes in it. If * subdocument_resumes is false, a subdocument will always be downloaded * beginning at the first byte of the file. */ bool HTTPChannel:: download_to_file(const Filename &filename, bool subdocument_resumes) { reset_download_to(); _download_to_filename = filename; _download_to_filename.set_binary(); _subdocument_resumes = subdocument_resumes; _download_dest = DD_file; if (_wanted_nonblocking && _state != S_read_header) { // In nonblocking mode, we can't start the download yet; that will be done // later as run() is called. return true; } // In normal, blocking mode, go ahead and do the download. if (!open_download_file()) { reset_download_to(); return false; } while (run()) { } return is_download_complete() && is_valid(); } /** * Specifies a Ramfile object to download the resulting document to. This * should be called immediately after get_document() or begin_get_document() * or related functions. * * In the case of the blocking I/O methods like get_document(), this function * will download the entire document to the Ramfile and return true if it was * successfully downloaded, false otherwise. * * In the case of non-blocking I/O methods like begin_get_document(), this * function simply indicates an intention to download to the indicated * Ramfile. It returns true if the file can be opened for writing, false * otherwise, but the contents will not be completely downloaded until run() * has returned false. At this time, it is possible that a communications * error will have left a partial file, so is_download_complete() may be * called to test this. * * If subdocument_resumes is true and the document in question was previously * requested as a subdocument (i.e. get_subdocument() with a first_byte value * greater than zero), this will automatically seek to the appropriate byte * within the Ramfile for writing the output. In this case, the Ramfile must * already have at least first_byte bytes in it. */ bool HTTPChannel:: download_to_ram(Ramfile *ramfile, bool subdocument_resumes) { nassertr(ramfile != (Ramfile *)NULL, false); reset_download_to(); ramfile->_pos = 0; _download_to_ramfile = ramfile; _download_dest = DD_ram; _subdocument_resumes = (subdocument_resumes && _first_byte_delivered != 0); if (_wanted_nonblocking && _state != S_read_header) { // In nonblocking mode, we can't start the download yet; that will be done // later as run() is called. return true; } // In normal, blocking mode, go ahead and do the download. if (!open_download_file()) { reset_download_to(); return false; } while (run()) { } return is_download_complete() && is_valid(); } /** * Specifies the name of an ostream to download the resulting document to. * This should be called immediately after get_document() or * begin_get_document() or related functions. * * In the case of the blocking I/O methods like get_document(), this function * will download the entire document to the file and return true if it was * successfully downloaded, false otherwise. * * In the case of non-blocking I/O methods like begin_get_document(), this * function simply indicates an intention to download to the indicated file. * It returns true if the file can be opened for writing, false otherwise, but * the contents will not be completely downloaded until run() has returned * false. At this time, it is possible that a communications error will have * left a partial file, so is_download_complete() may be called to test this. * * If subdocument_resumes is true and the document in question was previously * requested as a subdocument (i.e. get_subdocument() with a first_byte value * greater than zero), this will automatically seek to the appropriate byte * within the file for writing the output. In this case, the file must * already exist and must have at least first_byte bytes in it. If * subdocument_resumes is false, a subdocument will always be downloaded * beginning at the first byte of the file. */ bool HTTPChannel:: download_to_stream(ostream *strm, bool subdocument_resumes) { reset_download_to(); _download_to_stream = strm; _download_to_stream->clear(); _subdocument_resumes = subdocument_resumes; _download_dest = DD_stream; if (_wanted_nonblocking && _state != S_read_header) { // In nonblocking mode, we can't start the download yet; that will be done // later as run() is called. return true; } // In normal, blocking mode, go ahead and do the download. if (!open_download_file()) { reset_download_to(); return false; } while (run()) { } return is_download_complete() && is_valid(); } /** * Returns the connection that was established via a previous call to * connect_to() or begin_connect_to(), or NULL if the connection attempt * failed or if those methods have not recently been called. * * This stream has been allocated from the free store. It is the user's * responsibility to delete this pointer when finished with it. */ SocketStream *HTTPChannel:: get_connection() { if (!is_connection_ready()) { return NULL; } BioStream *stream = _source->get_stream(); _source->set_stream(NULL); // We're now passing ownership of the connection to the caller. if (downloader_cat.is_debug()) { downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID << "passing ownership of connection to caller.\n"; } reset_to_new(); return stream; } /** * Returns the input string with all uppercase letters converted to lowercase. */ string HTTPChannel:: downcase(const string &s) { string result; result.reserve(s.size()); string::const_iterator p; for (p = s.begin(); p != s.end(); ++p) { result += tolower(*p); } return result; } /** * Called by ISocketStream destructor when _body_stream is destructing. */ void HTTPChannel:: body_stream_destructs(ISocketStream *stream) { if (stream == _body_stream) { if (_state == S_reading_body) { switch (_body_stream->get_read_state()) { case ISocketStream::RS_complete: finished_body(false); break; case ISocketStream::RS_error: _state = HTTPChannel::S_failure; _status_entry._status_code = HTTPChannel::SC_lost_connection; break; default: break; } } _body_stream = NULL; _owns_body_stream = false; } } /** * Called by run() after it reaches the done state, this simply checks to see * if a download was requested, and begins the download if it has been. */ bool HTTPChannel:: reached_done_state() { /* if (downloader_cat.is_spam()) { downloader_cat.spam() << _NOTIFY_HTTP_CHANNEL_ID << "terminating run(), _state = " << _state << ", _done_state = " << _done_state << "\n"; } */ if (_state == S_failure) { // We had to give up. Each proxy we tried, in sequence, failed. But // maybe the last attempt didn't give us the most informative response; go // back and find the best one. if (!_status_list.empty()) { _status_list.push_back(_status_entry); if (downloader_cat.is_debug()) { downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID << "Reexamining failure responses.\n"; } size_t best_i = 0; if (downloader_cat.is_debug()) { downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID << " " << 0 << ". " << _status_list[0]._status_code << " " << _status_list[0]._status_string << "\n"; } for (size_t i = 1; i < _status_list.size(); i++) { if (downloader_cat.is_debug()) { downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID << " " << i << ". " << _status_list[i]._status_code << " " << _status_list[i]._status_string << "\n"; } if (more_useful_status_code(_status_list[i]._status_code, _status_list[best_i]._status_code)) { best_i = i; } } if (downloader_cat.is_debug()) { downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID << "chose index " << best_i << ", above.\n"; } _status_entry = _status_list[best_i]; _status_list.clear(); } return false; } // We don't need the list of previous failures any more--we've connected. _status_list.clear(); if (_download_dest == DD_none) { // All done. return false; } else { // Oops, we have to download the body now. open_read_body(); if (_body_stream == (ISocketStream *)NULL) { if (downloader_cat.is_debug()) { downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID << "Unable to download body: " << _request.get_url() << "\n"; } return false; } else { _owns_body_stream = true; if (_state != S_reading_body) { reset_body_stream(); } _started_download = true; _done_state = S_read_trailer; _last_run_time = TrueClock::get_global_ptr()->get_short_time(); return true; } } } /** * This state is reached when a previous connection attempt fails. If we have * multiple proxies in line to try, it sets us up for the next proxy and tries * to connect again; otherwise, it sets the state to S_failure. */ bool HTTPChannel:: run_try_next_proxy() { if (_proxy_next_index < _proxies.size()) { // Record the previous proxy's status entry, so we can come back to it // later if we get nonsense from the remaining proxies. _status_list.push_back(_status_entry); _status_entry = StatusEntry(); // Now try the next proxy in sequence. _proxy = _proxies[_proxy_next_index]; _proxy_auth = (HTTPAuthorization *)NULL; _proxy_next_index++; close_connection(); reconsider_proxy(); _state = S_connecting; return false; } // No more proxies to try, or we're not using a proxy. _state = S_failure; return false; } /** * In this state, we have not yet established a network connection to the * server (or proxy). */ bool HTTPChannel:: run_connecting() { _status_entry = StatusEntry(); if (!_bio->connect()) { if (_bio->should_retry()) { _state = S_connecting_wait; return false; } downloader_cat.info() << _NOTIFY_HTTP_CHANNEL_ID << "Could not connect to " << _bio->get_server_name() << " port " << _bio->get_port() << "\n"; OpenSSLWrapper::get_global_ptr()->notify_ssl_errors(); _status_entry._status_code = SC_no_connection; _state = S_try_next_proxy; return false; } if (downloader_cat.is_debug()) { downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID << "Connected to " << _bio->get_server_name() << " port " << _bio->get_port() << "\n"; } if (_proxy_tunnel_now) { if (_proxy.get_scheme() == "socks") { _state = S_socks_proxy_greet; } else { _state = S_http_proxy_ready; } } else { if (_want_ssl) { _state = S_setup_ssl; } else { _state = S_ready; } } return false; } /** * Here we have begun to establish a nonblocking connection, but we got a * come-back-later message, so we are waiting for the socket to finish * connecting. */ bool HTTPChannel:: run_connecting_wait() { int fd = -1; BIO_get_fd(*_bio, &fd); if (fd < 0) { downloader_cat.warning() << _NOTIFY_HTTP_CHANNEL_ID << "nonblocking socket BIO has no file descriptor.\n"; // This shouldn't be possible. _status_entry._status_code = SC_internal_error; _state = S_try_next_proxy; return false; } if (downloader_cat.is_spam()) { downloader_cat.spam() << _NOTIFY_HTTP_CHANNEL_ID << "waiting to connect to " << _request.get_url().get_server_and_port() << ".\n"; } fd_set wset; FD_ZERO(&wset); FD_SET(fd, &wset); struct timeval tv; if (get_blocking_connect()) { // Since we'll be blocking on this connect, fill in the timeout into the // structure. tv.tv_sec = (int)_connect_timeout; tv.tv_usec = (int)((_connect_timeout - tv.tv_sec) * 1000000.0); } else { // We won't block on this connect, so select() for 0 time. tv.tv_sec = 0; tv.tv_usec = 0; } int errcode = select(fd + 1, NULL, &wset, NULL, &tv); if (errcode < 0) { downloader_cat.warning() << _NOTIFY_HTTP_CHANNEL_ID << "Error in select.\n"; // This shouldn't be possible. _status_entry._status_code = SC_internal_error; _state = S_try_next_proxy; return false; } if (errcode == 0) { // Nothing's happened so far; come back later. if (get_blocking_connect() || (TrueClock::get_global_ptr()->get_short_time() - _started_connecting_time > get_connect_timeout())) { // Time to give up. downloader_cat.info() << _NOTIFY_HTTP_CHANNEL_ID << "Timeout connecting to " << _request.get_url().get_server_and_port() << " for " << _request.get_url() << ".\n"; _status_entry._status_code = SC_timeout; _state = S_try_next_proxy; return false; } return true; } // The socket is now ready for writing. _state = S_connecting; return false; } /** * This state is reached only after first establishing a connection to the * proxy, if a proxy is in use and we are tunneling through it via a CONNECT * command. */ bool HTTPChannel:: run_http_proxy_ready() { // If there's a request to be sent to the proxy, send it now. nassertr(!_proxy_request_text.empty(), false); if (!server_send(_proxy_request_text, false)) { return true; } // All done sending request. _state = S_http_proxy_request_sent; _sent_request_time = TrueClock::get_global_ptr()->get_short_time(); return false; } /** * This state is reached only after we have sent a special message to the * proxy and we are waiting for the proxy's response. It is not used in the * normal http-over-proxy case, which does not require a special message to * the proxy. */ bool HTTPChannel:: run_http_proxy_request_sent() { // Wait for the first line to come back from the server. string line; if (!server_getline_failsafe(line)) { return true; } // Skip unexpected blank lines. We're just being generous here. while (line.empty()) { if (!server_getline_failsafe(line)) { return true; } } if (!parse_http_response(line)) { return false; } _state = S_http_proxy_reading_header; _current_field_name = string(); _current_field_value = string(); _headers.clear(); _got_file_size = false; _got_transfer_file_size = false; return false; } /** * In this state we are reading the header lines from the proxy's response to * our special message. */ bool HTTPChannel:: run_http_proxy_reading_header() { if (parse_http_header()) { return true; } _redirect = get_header_value("Location"); // We can take the proxy's word for it that this is the actual URL for the // redirect. _server_response_has_no_body = (get_status_code() / 100 == 1 || get_status_code() == 204 || get_status_code() == 304); int last_status = _last_status_code; _last_status_code = get_status_code(); if (get_status_code() == 407 && last_status != 407 && !_proxy.empty()) { // 407: not authorized to proxy. Try to get the authorization. string authenticate_request = get_header_value("Proxy-Authenticate"); _proxy_auth = _client->generate_auth(_proxy, true, authenticate_request); if (_proxy_auth != (HTTPAuthorization *)NULL) { _proxy_realm = _proxy_auth->get_realm(); _proxy_username = _client->select_username(_proxy, true, _proxy_realm); if (!_proxy_username.empty()) { make_proxy_request_text(); // Roll the state forward to force a new request. _state = S_begin_body; return false; } } } if (!is_valid()) { // Proxy wouldn't open connection. // Change some of the status codes a proxy might return to differentiate // them from similar status codes the destination server might have // returned. if (get_status_code() != 407) { _status_entry._status_code += 1000; } _state = S_try_next_proxy; return false; } // Now we have a tunnel opened through the proxy. make_request_text(); if (_want_ssl) { _state = S_setup_ssl; } else { _state = S_ready; } return false; } /** * This state is reached only after first establishing a connection to a SOCKS * proxy, with which we now have to negotiate a connection. */ bool HTTPChannel:: run_socks_proxy_greet() { static const char socks_greeting[] = { 0x05, // Socks version 5 0x01, // Number of supported login methods 0x00, // Login method 0: no authentication /* 0x01, // Login method 1: GSSAPI 0x02 // Login method 2: username/password */ }; static const int socks_greeting_len = sizeof(socks_greeting); if (!server_send(string(socks_greeting, socks_greeting_len), true)) { return true; } _sent_request_time = TrueClock::get_global_ptr()->get_short_time(); // All done sending request. _state = S_socks_proxy_greet_reply; return false; } /** * We are waiting for the SOCKS proxy to respond to our greeting. */ bool HTTPChannel:: run_socks_proxy_greet_reply() { string reply; // Get the two-byte reply from the SOCKS server. if (!server_get_failsafe(reply, 2)) { return true; } if (reply[0] != 0x05) { // We only speak Socks5. downloader_cat.info() << _NOTIFY_HTTP_CHANNEL_ID << "Rejecting Socks version " << (int)reply[0] << "\n"; _status_entry._status_code = SC_socks_invalid_version; _state = S_try_next_proxy; return false; } if (reply[1] == (char)0xff) { downloader_cat.info() << _NOTIFY_HTTP_CHANNEL_ID << "Socks server does not accept our available login methods.\n"; _status_entry._status_code = SC_socks_no_acceptable_login_method; _state = S_try_next_proxy; return false; } if (reply[1] == 0x00) { // No login method required. Proceed directly to the connect message. _state = S_socks_proxy_connect; return false; } // The server accepted a login method we didn't offer! downloader_cat.info() << _NOTIFY_HTTP_CHANNEL_ID << "Socks server accepted unrequested login method " << (int)reply[1] << "\n"; _status_entry._status_code = SC_socks_no_acceptable_login_method; _state = S_try_next_proxy; return false; } /** * The SOCKS proxy has accepted us, and now we may issue the connect request. */ bool HTTPChannel:: run_socks_proxy_connect() { static const char socks_connect[] = { 0x05, // Socks version 5 0x01, // Command 1: connect 0x00, // reserved 0x03, // DNS name }; static const int socks_connect_len = sizeof(socks_connect); string hostname = _request.get_url().get_server(); int port = _request.get_url().get_port(); if (downloader_cat.is_debug()) { downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID << "Requesting SOCKS5 connection to " << _request.get_url().get_server_and_port() << "\n"; } string connect = string(socks_connect, socks_connect_len) + string(1, (char)hostname.length()) + hostname + string(1, (char)((port >> 8) & 0xff)) + string(1, (char)(port & 0xff)); if (!server_send(connect, true)) { return true; } _sent_request_time = TrueClock::get_global_ptr()->get_short_time(); _state = S_socks_proxy_connect_reply; return false; } /** * We are waiting for the SOCKS proxy to honor our connect request. */ bool HTTPChannel:: run_socks_proxy_connect_reply() { string reply; // Get the first two bytes of the connect reply. if (!server_get_failsafe(reply, 2)) { return true; } if (reply[0] != 0x05) { // We only speak Socks5. downloader_cat.info() << _NOTIFY_HTTP_CHANNEL_ID << "Rejecting Socks version " << (int)reply[0] << "\n"; close_connection(); // connection is now bad. _status_entry._status_code = SC_socks_invalid_version; _state = S_try_next_proxy; return false; } if (reply[1] != 0x00) { downloader_cat.info() << _NOTIFY_HTTP_CHANNEL_ID << "Connection refused, SOCKS code " << (int)reply[1] << "\n"; /* Socks error codes (from RFC1928): o X'00' succeeded o X'01' general SOCKS server failure o X'02' connection not allowed by ruleset o X'03' Network unreachable o X'04' Host unreachable o X'05' Connection refused o X'06' TTL expired o X'07' Command not supported o X'08' Address type not supported o X'09' to X'FF' unassigned */ switch (reply[1]) { case 0x03: case 0x04: case 0x05: case 0x06: // These generally mean the same thing: the SOCKS proxy tried, but // couldn't reach the host. _status_entry._status_code = SC_socks_no_connection; break; default: _status_entry._status_code = SC_socks_refused; } close_connection(); // connection is now bad. _state = S_try_next_proxy; return false; } // Now put those bytes back, and get five bytes of the reply. _working_get = reply; if (!server_get_failsafe(reply, 5)) { return true; } // Figure out how many bytes total we will expect for the reply. int total_bytes = 6; switch (reply[3]) { case 0x01: // IPv4 total_bytes += 4; break; case 0x03: // DNS total_bytes += (unsigned int)reply[4]; break; case 0x04: // IPv6 total_bytes += 16; break; default: downloader_cat.info() << _NOTIFY_HTTP_CHANNEL_ID << "Unsupported SOCKS address type: " << (int)reply[3] << "\n"; _status_entry._status_code = SC_socks_invalid_version; _state = S_try_next_proxy; return false; } // Now put back the bytes we've read so far, and get the rest of them. _working_get = reply; if (!server_get_failsafe(reply, total_bytes)) { return true; } if (downloader_cat.is_debug()) { // Finally, we can decode the whole thing. string connect_host; switch (reply[3]) { case 0x01: // IPv4 { ostringstream strm; strm << (unsigned int)(unsigned char)reply[4] << "." << (unsigned int)(unsigned char)reply[5] << "." << (unsigned int)(unsigned char)reply[6] << "." << (unsigned int)(unsigned char)reply[7]; connect_host = strm.str(); } break; case 0x03: // DNS connect_host = string(&reply[5], (unsigned int)reply[4]); break; case 0x04: // IPv6 { char buf[48]; sprintf(buf, "[%02hhx%02hhx:%02hhx%02hhx:%02hhx%02hhx:%02hhx%02hhx" ":%02hhx%02hhx:%02hhx%02hhx:%02hhx%02hhx:%02hhx%02hhx]", reply[4], reply[5], reply[6], reply[7], reply[8], reply[9], reply[10], reply[11], reply[12], reply[13], reply[14], reply[15], reply[16], reply[17], reply[18], reply[19]); total_bytes += 16; } break; } int connect_port = (((unsigned int)(unsigned char)reply[total_bytes - 2]) << 8) | ((unsigned int)(unsigned char)reply[total_bytes - 1]); downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID << _proxy << " directed us to " << connect_host << ":" << connect_port << "\n"; } if (_want_ssl) { _state = S_setup_ssl; } else { _state = S_ready; } return false; } /** * This state begins elevating our existing, unsecure connection to a secure, * SSL connection. */ bool HTTPChannel:: run_setup_ssl() { _sbio = BIO_new_ssl(_client->get_ssl_ctx(), true); BIO_push(_sbio, *_bio); SSL *ssl = NULL; BIO_get_ssl(_sbio, &ssl); nassertr(ssl != (SSL *)NULL, false); // We only take one word at a time from the _cipher_list. If that // connection fails, then we take the next word. string cipher_list = _cipher_list; if (!cipher_list.empty()) { size_t space = cipher_list.find(" "); if (space != string::npos) { cipher_list = cipher_list.substr(0, space); } } if (downloader_cat.is_debug()) { downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID << "Setting ssl-cipher-list '" << cipher_list << "'\n"; } int result = SSL_set_cipher_list(ssl, cipher_list.c_str()); if (result == 0) { downloader_cat.error() << _NOTIFY_HTTP_CHANNEL_ID << "Invalid cipher list: '" << cipher_list << "'\n"; OpenSSLWrapper::get_global_ptr()->notify_ssl_errors(); _status_entry._status_code = SC_ssl_internal_failure; _state = S_failure; return false; } string hostname = _request.get_url().get_server(); result = SSL_set_tlsext_host_name(ssl, hostname.c_str()); if (result == 0) { downloader_cat.error() << _NOTIFY_HTTP_CHANNEL_ID << "Could not set TLS SNI hostname to '" << hostname << "'\n"; } /* * It would be nice to use something like SSL_set_client_cert_cb() here to set * a callback to provide the certificate should it be requested, or even to * potentially provide any of a number of certificates according to the * server's CA presented, but that interface as provided by OpenSSL is broken * since there's no way to pass additional data to the callback function (and * hence no way to tie it back to the HTTPChannel object, other than by * building a messy mapping of SSL pointers back to HTTPChannel pointers). */ if (_client->load_client_certificate()) { SSL_use_certificate(ssl, _client->_client_certificate_pub); SSL_use_PrivateKey(ssl, _client->_client_certificate_priv); if (!SSL_check_private_key(ssl)) { downloader_cat.warning() << _NOTIFY_HTTP_CHANNEL_ID << "Client private key does not match public key!\n"; } } if (downloader_cat.is_spam()) { downloader_cat.spam() << _NOTIFY_HTTP_CHANNEL_ID << "SSL Ciphers available:\n"; const char *name; int pri = 0; name = SSL_get_cipher_list(ssl, pri); while (name != NULL) { downloader_cat.spam() << _NOTIFY_HTTP_CHANNEL_ID << " " << pri + 1 << ". " << name << "\n"; pri++; name = SSL_get_cipher_list(ssl, pri); } } if (downloader_cat.is_debug()) { downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID << "performing SSL handshake\n"; } _state = S_ssl_handshake; // We start the connect timer over again when we reach the SSL handshake. _started_connecting_time = TrueClock::get_global_ptr()->get_short_time(); return false; } /** * This state performs the SSL handshake with the server, and also verifies * the server's identity when the handshake has successfully completed. */ bool HTTPChannel:: run_ssl_handshake() { if (BIO_do_handshake(_sbio) <= 0) { if (BIO_should_retry(_sbio)) { double elapsed = TrueClock::get_global_ptr()->get_short_time() - _started_connecting_time; if (elapsed <= get_connect_timeout() + _extra_ssl_handshake_time) { // Keep trying. return true; } // Time to give up on the handshake. } downloader_cat.info() << _NOTIFY_HTTP_CHANNEL_ID << "Could not establish SSL handshake with " << _request.get_url().get_server_and_port() << "\n"; OpenSSLWrapper::get_global_ptr()->notify_ssl_errors(); // It seems to be an error to free sbio at this point; perhaps it's // already been freed? if (!_cipher_list.empty()) { // If we've got another cipher to try, do so. size_t space = _cipher_list.find(" "); if (space != string::npos) { while (space < _cipher_list.length() && _cipher_list[space] == ' ') { ++space; } _cipher_list = _cipher_list.substr(space); if (!_cipher_list.empty()) { close_connection(); reconsider_proxy(); _state = S_connecting; return false; } } } // All done trying ciphers; they all failed. _cipher_list = _client->get_cipher_list(); _status_entry._status_code = SC_ssl_no_handshake; _state = S_failure; return false; } SSL *ssl = NULL; BIO_get_ssl(_sbio, &ssl); nassertr(ssl != (SSL *)NULL, false); if (!_nonblocking) { SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY); } const SSL_CIPHER *cipher = SSL_get_current_cipher(ssl); if (cipher == (const SSL_CIPHER *)NULL) { downloader_cat.warning() << _NOTIFY_HTTP_CHANNEL_ID << "No current cipher on SSL connection.\n"; } else { if (downloader_cat.is_debug()) { downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID << "Using cipher " << SSL_CIPHER_get_name((SSL_CIPHER *) cipher) << "\n"; } } // Now that we've made an SSL handshake, we can use the SSL bio to do all of // our communication henceforth. _bio->set_bio(_sbio); _sbio = NULL; X509 *cert = SSL_get_peer_certificate(ssl); if (cert == (X509 *)NULL) { downloader_cat.info() << _NOTIFY_HTTP_CHANNEL_ID << "No certificate was presented by server.\n"; // This shouldn't be possible, per the SSL specs. _status_entry._status_code = SC_ssl_invalid_server_certificate; _state = S_failure; return false; } X509_NAME *subject = X509_get_subject_name(cert); if (downloader_cat.is_debug()) { string org_name = get_x509_name_component(subject, NID_organizationName); string org_unit_name = get_x509_name_component(subject, NID_organizationalUnitName); string common_name = get_x509_name_component(subject, NID_commonName); downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID << "Server is " << common_name << " from " << org_unit_name << " / " << org_name << "\n"; if (downloader_cat.is_spam()) { downloader_cat.spam() << _NOTIFY_HTTP_CHANNEL_ID << "Received certificate from server:\n" << flush; X509_print_fp(stderr, cert); fflush(stderr); } } bool cert_preapproved = false; bool cert_name_preapproved = false; check_preapproved_server_certificate(cert, cert_preapproved, cert_name_preapproved); // Now verify the server certificate is valid. long verify_result = SSL_get_verify_result(ssl); bool cert_valid = true; if (verify_result == X509_V_ERR_CERT_HAS_EXPIRED) { downloader_cat.info() << _NOTIFY_HTTP_CHANNEL_ID << "Expired certificate from " << _request.get_url().get_server_and_port() << "\n"; if (_client->get_verify_ssl() == HTTPClient::VS_normal && !cert_preapproved) { cert_valid = false; } } else if (verify_result == X509_V_ERR_CERT_NOT_YET_VALID) { downloader_cat.info() << _NOTIFY_HTTP_CHANNEL_ID << "Premature certificate from " << _request.get_url().get_server_and_port() << "\n"; if (_client->get_verify_ssl() == HTTPClient::VS_normal && !cert_preapproved) { cert_valid = false; } } else if (verify_result == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT || verify_result == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN) { downloader_cat.info() << _NOTIFY_HTTP_CHANNEL_ID << "Self-signed certificate from " << _request.get_url().get_server_and_port() << "\n"; if (_client->get_verify_ssl() != HTTPClient::VS_no_verify && !cert_preapproved) { cert_valid = false; } } else if (verify_result != X509_V_OK) { downloader_cat.info() << _NOTIFY_HTTP_CHANNEL_ID << "Unable to verify identity of " << _request.get_url().get_server_and_port() << ", verify error code " << verify_result << "\n"; if (_client->get_verify_ssl() != HTTPClient::VS_no_verify && !cert_preapproved) { cert_valid = false; } } if (!cert_valid) { _status_entry._status_code = SC_ssl_invalid_server_certificate; _state = S_failure; return false; } if (_client->get_verify_ssl() != HTTPClient::VS_no_verify && !cert_name_preapproved) { // Check that the server is someone we expected to be talking to. if (!validate_server_name(cert)) { _status_entry._status_code = SC_ssl_unexpected_server; _state = S_failure; return false; } } X509_free(cert); _state = S_ready; return false; } /** * This is the main "ready" state. In this state, we have established a * (possibly secure) connection to the server (or proxy), and the server (or * proxy) is idle and waiting for us to send a request. * * If persistent_connection is true, we will generally come back to this state * after finishing each request on a given connection. */ bool HTTPChannel:: run_ready() { // If there's a request to be sent upstream, send it now. if (!_request_text.empty()) { if (!server_send(_request_text, false)) { return true; } } // All done sending request. _state = S_request_sent; _sent_request_time = TrueClock::get_global_ptr()->get_short_time(); return false; } /** * In this state we have sent our request to the server (or proxy) and we are * waiting for a response. */ bool HTTPChannel:: run_request_sent() { // Wait for the first line to come back from the server. string line; if (!server_getline_failsafe(line)) { return true; } // Skip unexpected blank lines. We're just being generous here. while (line.empty()) { if (!server_getline_failsafe(line)) { return true; } } if (!parse_http_response(line)) { // Not an HTTP response. _state is already set appropriately. return false; } _state = S_reading_header; _current_field_name = string(); _current_field_value = string(); _headers.clear(); _got_file_size = false; _got_transfer_file_size = false; return false; } /** * In this state we have received the first response to our request from the * server (or proxy) and we are reading the set of header lines preceding the * requested document. */ bool HTTPChannel:: run_reading_header() { if (parse_http_header()) { if (_bio.is_null()) { downloader_cat.info() << _NOTIFY_HTTP_CHANNEL_ID << "Connection lost while reading HTTP response.\n"; if (_response_type == RT_http_hangup) { // This was our second hangup in a row. Give up. _status_entry._status_code = SC_lost_connection; _state = S_try_next_proxy; } else { // Try again, once. _response_type = RT_http_hangup; } } else { double elapsed = TrueClock::get_global_ptr()->get_short_time() - _sent_request_time; if (elapsed > get_http_timeout()) { // Time to give up. downloader_cat.info() << _NOTIFY_HTTP_CHANNEL_ID << "Timeout waiting for " << _request.get_url().get_server_and_port() << " in run_reading_header (" << elapsed << " seconds elapsed).\n"; _status_entry._status_code = SC_timeout; _state = S_try_next_proxy; } } return true; } _response_type = RT_http_complete; // Ok, we've established an HTTP connection to the server. Our extra send // headers have done their job; clear them for next time. clear_extra_headers(); _server_response_has_no_body = (get_status_code() / 100 == 1 || get_status_code() == 204 || get_status_code() == 304 || _method == HTTPEnum::M_head); // Look for key properties in the header fields. if (get_status_code() == 206) { string content_range = get_header_value("Content-Range"); if (content_range.empty()) { downloader_cat.warning() << _NOTIFY_HTTP_CHANNEL_ID << "Got 206 response without Content-Range header!\n"; _status_entry._status_code = SC_invalid_http; _state = S_failure; return false; } else { if (!parse_content_range(content_range)) { downloader_cat.warning() << _NOTIFY_HTTP_CHANNEL_ID << "Couldn't parse Content-Range: " << content_range << "\n"; _status_entry._status_code = SC_invalid_http; _state = S_failure; return false; } } } else { _first_byte_delivered = 0; _last_byte_delivered = 0; } if (downloader_cat.is_debug()) { if (_first_byte_requested != 0 || _last_byte_requested != 0 || _first_byte_delivered != 0 || _last_byte_delivered != 0) { downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID << "Requested byte range " << _first_byte_requested << " to " << _last_byte_delivered << "; server delivers range " << _first_byte_delivered << " to " << _last_byte_delivered << "\n"; } } // Set the _document_spec to reflect what we just retrieved. _document_spec = DocumentSpec(_request.get_url()); string tag = get_header_value("ETag"); if (!tag.empty()) { _document_spec.set_tag(HTTPEntityTag(tag)); } string date = get_header_value("Last-Modified"); if (!date.empty()) { _document_spec.set_date(HTTPDate(date)); } // In case we've got a download in effect, now we know what the first byte // of the subdocument request will be, so we can open the file and position // it. if (_server_response_has_no_body) { // Never mind on the download. reset_download_to(); } if (!open_download_file()) { return false; } _got_expected_file_size = false; _got_file_size = false; _got_transfer_file_size = false; string content_length = get_header_value("Content-Length"); if (!content_length.empty()) { _file_size = atoi(content_length.c_str()); _got_file_size = true; } else if (get_status_code() == 206) { // Well, we didn't get a content-length from the server, but we can infer // the number of bytes based on the range we're given. _file_size = _last_byte_delivered - _first_byte_delivered + 1; _got_file_size = true; } _redirect = get_header_value("Location"); // The server might have given us just a filename for the redirect. In that // case, it's relative to the same server. If it's a relative path, it's // relative to the same directory. if (_redirect.has_path() && !_redirect.has_authority()) { URLSpec url = _document_spec.get_url(); Filename path = _redirect.get_path(); if (path.is_local()) { Filename rel_to = Filename(url.get_path()).get_dirname(); _redirect.set_path(Filename(rel_to, path)); } _redirect.set_scheme(url.get_scheme()); _redirect.set_authority(url.get_authority()); } _state = S_read_header; if (_server_response_has_no_body && will_close_connection()) { // If the server said it will close the connection, we should close it // too. close_connection(); } // Handle automatic retries and redirects. int last_status = _last_status_code; _last_status_code = get_status_code(); if (get_status_code() == 407 && last_status != 407 && !_proxy.empty()) { // 407: not authorized to proxy. Try to get the authorization. string authenticate_request = get_header_value("Proxy-Authenticate"); _proxy_auth = _client->generate_auth(_proxy, true, authenticate_request); if (_proxy_auth != (HTTPAuthorization *)NULL) { _proxy_realm = _proxy_auth->get_realm(); _proxy_username = _client->select_username(_proxy, true, _proxy_realm); if (!_proxy_username.empty()) { make_request_text(); // Roll the state forward to force a new request. _state = S_begin_body; return false; } } } if (get_status_code() == 401 && last_status != 401) { // 401: not authorized to remote server. Try to get the authorization. string authenticate_request = get_header_value("WWW-Authenticate"); _www_auth = _client->generate_auth(_request.get_url(), false, authenticate_request); if (_www_auth != (HTTPAuthorization *)NULL) { _www_realm = _www_auth->get_realm(); _www_username = _client->select_username(_request.get_url(), false, _www_realm); if (!_www_username.empty()) { make_request_text(); // Roll the state forward to force a new request. _state = S_begin_body; return false; } } } if ((get_status_code() == 300 || get_status_code() == 301 || get_status_code() == 302 || get_status_code() == 303 || get_status_code() == 307) && !get_redirect().empty()) { // Redirect. Should we handle it automatically? // According to the letter of RFC 2616, 301 and 302 responses to POST // requests must not be automatically redirected without confirmation by // the user. In reality, browsers do allow automatic redirection of these // responses, changing the POST to a GET, and we reproduce this behavior // here. if (_method == HTTPEnum::M_post) { _method = HTTPEnum::M_get; _body = string(); } if (_method == HTTPEnum::M_get || _method == HTTPEnum::M_head) { // Sure! URLSpec new_url = get_redirect(); if (find(_redirect_trail.begin(), _redirect_trail.end(), new_url) != _redirect_trail.end()) { downloader_cat.warning() << _NOTIFY_HTTP_CHANNEL_ID << "cycle detected in redirect to " << new_url << "\n"; } else { _redirect_trail.push_back(new_url); if (downloader_cat.is_debug()) { downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID << "following redirect to " << new_url << "\n"; } if (_request.get_url().has_username()) { new_url.set_username(_request.get_url().get_username()); } reset_url(_request.get_url(), new_url); _request.set_url(new_url); _want_ssl = _request.get_url().is_ssl(); reconsider_proxy(); make_header(); make_request_text(); // Roll the state forward to force a new request. _state = S_begin_body; return false; } } } if (_state == S_read_header && ((get_status_code() / 100) == 4 || (get_status_code() / 100) == 5) && _proxy_serves_document && _proxy_next_index < _proxies.size()) { // If we were using a proxy (but not tunneling through the proxy) and we // got some kind of a server error, try the next proxy in sequence (if we // have one). This handles the case of a working proxy that cannot see // the host (and so returns 504 or something along those lines). Some // proxies are so broken they return a 404 in this case, so we have to // consider that along the same lines. _state = S_try_next_proxy; return false; } // Otherwise, we're good to go. return false; } /** * This is the first state when reading a file:// URL. All it does is skip * past the non-existent "header". */ bool HTTPChannel:: run_start_direct_file_read() { _state = S_read_header; if (!open_download_file()) { return false; } return false; } /** * In this state we have completely read the header lines returned by the * server (or proxy) in response to our request. This state represents the * normal stopping point of a call to get_document(), etc.; further reads will * return the body of the request, the requested document. * * Normally run_read_header() is not called unless the user has elected not to * read the returned document himself. In fact, the state itself only exists * so we can make a distinction between S_read_header and S_begin_body, where * S_read_header is safe to return to the user and S_begin_body means we need * to start skipping the document. */ bool HTTPChannel:: run_read_header() { _state = S_begin_body; return false; } /** * This state begins to skip over the body in preparation for making a new * request. */ bool HTTPChannel:: run_begin_body() { if (will_close_connection()) { // If the socket will close anyway, no point in skipping past the previous // body; just reset. if (downloader_cat.is_debug()) { downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID << "resetting to begin body; server would close anyway.\n"; } reset_to_new(); return false; } if (_server_response_has_no_body) { // We have already "read" the nonexistent body. _state = S_read_trailer; } else if (get_file_size() > (int)_skip_body_size) { // If we know the size of the body we are about to skip and it's too // large, then don't bother skipping it--just drop the connection and get // a new one. if (downloader_cat.is_debug()) { downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID << "Dropping connection rather than skipping past " << get_file_size() << " bytes.\n"; } reset_to_new(); } else { open_read_body(); if (_body_stream == (ISocketStream *)NULL) { if (downloader_cat.is_debug()) { downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID << "Unable to skip body.\n"; } reset_to_new(); } else { _owns_body_stream = true; if (_state != S_reading_body) { reset_body_stream(); } } } return false; } /** * In this state we are in the process of reading the response's body. We * will only come to this function if the user did not choose to read the * entire body himself (by calling open_read_body()). * * In this case we should skip past the body to reset the connection for * making a new request. */ bool HTTPChannel:: run_reading_body() { if (will_close_connection()) { // If the socket will close anyway, no point in skipping past the previous // body; just reset. if (downloader_cat.is_debug()) { downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID << "resetting to read body; server would close anyway.\n"; } reset_to_new(); return false; } // Skip the body we've already started. if (_body_stream == NULL || !_owns_body_stream) { // Whoops, we're not in skip-body mode. Better reset. if (downloader_cat.is_debug()) { downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID << "resetting, not in skip-body mode.\n"; } reset_to_new(); return false; } string line; getline(*_body_stream, line); while (!_body_stream->fail() && !_body_stream->eof()) { if (downloader_cat.is_spam()) { downloader_cat.spam() << _NOTIFY_HTTP_CHANNEL_ID << "skip: " << line << "\n"; } getline(*_body_stream, line); } if (!_body_stream->is_closed()) { // There's more to come later. return true; } reset_body_stream(); // This should have been set by the call to finished_body(), above. nassertr(_state != S_reading_body, false); return false; } /** * In this state we have completely read (or skipped over) the body of the * response. We should continue skipping past the trailer following the body. * * Not all bodies come with trailers; in particular, the "identity" transfer * encoding does not include a trailer. It is therefore the responsibility of * the IdentityStreamBuf or ChunkedStreamBuf to set the state appropriately to * either S_read_body or S_read_trailer following the completion of the body. */ bool HTTPChannel:: run_read_body() { if (will_close_connection()) { // If the socket will close anyway, no point in skipping past the previous // body; just reset. if (downloader_cat.is_debug()) { downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID << "resetting to read body; server would close anyway.\n"; } reset_to_new(); return false; } // Skip the trailer following the recently-read body. string line; if (!server_getline(line)) { return true; } while (!line.empty()) { if (!server_getline(line)) { return true; } } _state = S_read_trailer; return false; } /** * In this state we have completely read the body and the trailer. This state * is simply a pass-through back to S_ready. */ bool HTTPChannel:: run_read_trailer() { if (will_close_connection()) { // If the socket will close anyway, no point in skipping past the previous // body; just reset. if (downloader_cat.is_debug()) { downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID << "resetting to read trailer; server would close anyway.\n"; } reset_to_new(); return false; } _state = S_ready; return false; } /** * After the headers, etc. have been read, this streams the download to the * named file. */ bool HTTPChannel:: run_download_to_file() { nassertr(_body_stream != (ISocketStream *)NULL && _owns_body_stream, false); bool do_throttle = _wanted_nonblocking && _download_throttle; static const size_t buffer_size = 4096; char buffer[buffer_size]; size_t remaining_this_pass = buffer_size; if (do_throttle) { remaining_this_pass = _bytes_per_update; } _body_stream->read(buffer, min(buffer_size, remaining_this_pass)); size_t count = _body_stream->gcount(); while (count != 0) { _download_to_stream->write(buffer, count); _bytes_downloaded += count; if (do_throttle) { nassertr(count <= remaining_this_pass, false); remaining_this_pass -= count; if (remaining_this_pass == 0) { // That's enough for now. return true; } } thread_consider_yield(); _body_stream->read(buffer, min(buffer_size, remaining_this_pass)); count = _body_stream->gcount(); } if (_download_to_stream->fail()) { downloader_cat.warning() << _NOTIFY_HTTP_CHANNEL_ID << "Error writing to " << _download_to_filename << "\n"; _status_entry._status_code = SC_download_write_error; _state = S_failure; reset_download_to(); return false; } _download_to_stream->flush(); if (_body_stream->is_closed()) { // Done. reset_body_stream(); close_download_stream(); _started_download = false; return false; } else { // More to come. return true; } } /** * After the headers, etc. have been read, this streams the download to the * specified Ramfile object. */ bool HTTPChannel:: run_download_to_ram() { nassertr(_body_stream != (ISocketStream *)NULL && _owns_body_stream, false); nassertr(_download_to_ramfile != (Ramfile *)NULL, false); bool do_throttle = _wanted_nonblocking && _download_throttle; static const size_t buffer_size = 4096; char buffer[buffer_size]; size_t remaining_this_pass = buffer_size; if (do_throttle) { remaining_this_pass = _bytes_per_update; } _body_stream->read(buffer, min(buffer_size, remaining_this_pass)); size_t count = _body_stream->gcount(); while (count != 0) { _download_to_ramfile->_data += string(buffer, count); _bytes_downloaded += count; if (do_throttle) { nassertr(count <= remaining_this_pass, false); remaining_this_pass -= count; if (remaining_this_pass == 0) { // That's enough for now. return true; } } thread_consider_yield(); _body_stream->read(buffer, min(buffer_size, remaining_this_pass)); count = _body_stream->gcount(); } if (_body_stream->is_closed()) { // Done. reset_body_stream(); close_download_stream(); _started_download = false; return false; } else { // More to come. return true; } } /** * After the headers, etc. have been read, this streams the download to the * named file. */ bool HTTPChannel:: run_download_to_stream() { nassertr(_body_stream != (ISocketStream *)NULL && _owns_body_stream, false); bool do_throttle = _wanted_nonblocking && _download_throttle; static const size_t buffer_size = 4096; char buffer[buffer_size]; size_t remaining_this_pass = buffer_size; if (do_throttle) { remaining_this_pass = _bytes_per_update; } _body_stream->read(buffer, min(buffer_size, remaining_this_pass)); size_t count = _body_stream->gcount(); while (count != 0) { _download_to_stream->write(buffer, count); _bytes_downloaded += count; if (do_throttle) { nassertr(count <= remaining_this_pass, false); remaining_this_pass -= count; if (remaining_this_pass == 0) { // That's enough for now. return true; } } thread_consider_yield(); _body_stream->read(buffer, min(buffer_size, remaining_this_pass)); count = _body_stream->gcount(); } if (_download_to_stream->fail()) { downloader_cat.warning() << _NOTIFY_HTTP_CHANNEL_ID << "Error writing to stream\n"; _status_entry._status_code = SC_download_write_error; _state = S_failure; reset_download_to(); return false; } _download_to_stream->flush(); if (_body_stream->is_closed()) { // Done. reset_body_stream(); close_download_stream(); _started_download = false; return false; } else { // More to come. return true; } } /** * Begins a new document request to the server, throwing away whatever request * was currently pending if necessary. */ void HTTPChannel:: begin_request(HTTPEnum::Method method, const DocumentSpec &url, const string &body, bool nonblocking, size_t first_byte, size_t last_byte) { downloader_cat.info() << _NOTIFY_HTTP_CHANNEL_ID << "begin " << method << " " << url << "\n"; reset_for_new_request(); _wanted_nonblocking = nonblocking; #if defined(HAVE_THREADS) && defined(SIMPLE_THREADS) // In the presence of SIMPLE_THREADS, we always use non-blocking IO. We // simulate blocking by yielding the thread. nonblocking = true; #endif // Get the set of proxies that are appropriate for this URL. _proxies.clear(); _proxy_next_index = 0; if (get_allow_proxy()) { _client->get_proxies_for_url(url.get_url(), _proxies); } // If we still have a live connection to a proxy that is on the list, that // proxy should be moved immediately to the front of the list (to minimize // restarting connections unnecessarily). if (!_bio.is_null() && !_proxies.empty() && !_proxy.empty()) { Proxies::iterator pi = find(_proxies.begin(), _proxies.end(), _proxy); if (pi != _proxies.end()) { _proxies.erase(pi); _proxies.insert(_proxies.begin(), _proxy); } } URLSpec new_proxy; if (_proxy_next_index < _proxies.size()) { new_proxy = _proxies[_proxy_next_index]; _proxy_next_index++; } // Changing the proxy is grounds for dropping the old connection, if any. if (_proxy != new_proxy) { _proxy = new_proxy; _proxy_auth = (HTTPAuthorization *)NULL; if (downloader_cat.is_debug()) { downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID << "resetting to change proxy to " << _proxy << "\n"; } reset_to_new(); } // Ditto with changing the nonblocking state. if (_nonblocking != nonblocking) { _nonblocking = nonblocking; if (downloader_cat.is_debug()) { downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID << "resetting to change nonblocking state to " << _nonblocking << ".\n"; } reset_to_new(); } reset_url(_request.get_url(), url.get_url()); _request = url; _document_spec = DocumentSpec(); _method = method; _body = body; // An https-style request means we'll need to establish an SSL connection. _want_ssl = _request.get_url().is_ssl(); _first_byte_requested = first_byte; _last_byte_requested = last_byte; _connect_count = 0; reconsider_proxy(); // Reset from whatever previous request might still be pending. if (_request.get_url().get_scheme() == "file") { // A "file" URL just means we're reading a raw file. This only supports // actual disk files, not the VFS, because we use a BIO_new_file() // underneath this. reset_to_new(); _bio = new BioPtr(_request.get_url()); if (_bio->get_bio() != NULL) { // Successfully opened the file. _source = new BioStreamPtr(new BioStream(_bio)); _status_entry._status_code = 200; _state = S_start_direct_file_read; // Get the file size. FILE *fp = NULL; BIO_get_fp(_bio->get_bio(), &fp); if (fp != NULL) { if (fseek(fp, 0, SEEK_END) == 0) { _file_size = ftell(fp); _got_file_size = true; fseek(fp, 0, SEEK_SET); } } } else { // Couldn't read the file. OpenSSLWrapper::get_global_ptr()->notify_ssl_errors(); _status_entry._status_code = SC_no_connection; _state = S_failure; } } else { // We're reading a normal network URL. if (_state == S_failure || (_state < S_read_header && _state != S_ready)) { if (downloader_cat.is_debug()) { downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID << "resetting to clear previous request.\n"; } reset_to_new(); } else if (TrueClock::get_global_ptr()->get_short_time() - _last_run_time >= _idle_timeout) { if (downloader_cat.is_debug()) { downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID << "resetting old connection: " << TrueClock::get_global_ptr()->get_short_time() - _last_run_time << " s old.\n"; } reset_to_new(); } else if (_state == S_read_header) { // Roll one step forwards to start skipping past the previous body. _state = S_begin_body; } } if (_method == HTTPEnum::M_connect) { _done_state = S_ready; } else { _done_state = S_read_header; } } /** * Reevaluates the flags and strings that are computed based on the particular * proxy we are attempting to connect to. This should be called when we * initiate a request, and also whenever we change proxies while processing a * request. */ void HTTPChannel:: reconsider_proxy() { _proxy_tunnel_now = false; _proxy_serves_document = false; if (!_proxy.empty()) { // If the user insists we always tunnel through a proxy, or if we're // opening an SSL connection, or the user has explicitly asked for a // direct connection of some kind, or if we have a SOCKS-style proxy; each // of these demands a tunnel through the proxy to speak directly to the // http server. _proxy_tunnel_now = (get_proxy_tunnel() || _want_ssl || _method == HTTPEnum::M_connect || _proxy.get_scheme() == "socks"); // Otherwise (but we still have a proxy), then we ask the proxy to hand us // the document. _proxy_serves_document = !_proxy_tunnel_now; } make_header(); make_request_text(); if (_proxy_tunnel_now) { // Maybe we need to tunnel through the proxy to connect to the server // directly. ostringstream request; request << "CONNECT " << _request.get_url().get_server_and_port() << " " << _client->get_http_version_string() << "\r\n"; if (_client->get_http_version() >= HTTPEnum::HV_11) { request << "Host: " << _request.get_url().get_server_and_port() << "\r\n"; } _proxy_header = request.str(); make_proxy_request_text(); } else { _proxy_header = string(); _proxy_request_text = string(); } } /** * Resets the internal state variables in preparation for beginning a new * request. */ void HTTPChannel:: reset_for_new_request() { if (downloader_cat.is_spam()) { downloader_cat.spam() << _NOTIFY_HTTP_CHANNEL_ID << "reset_for_new_request.\n"; } reset_download_to(); reset_body_stream(); _last_status_code = 0; _status_entry = StatusEntry(); _response_type = RT_none; _redirect_trail.clear(); _bytes_downloaded = 0; _bytes_requested = 0; } /** * This is called by the body reading classes--ChunkedStreamBuf and * IdentityStreamBuf--when they have finished reading the body. It advances * the state appropriately. * * has_trailer should be set true if the body type has an associated trailer * which should be read or skipped, or false if there is no trailer. */ void HTTPChannel:: finished_body(bool has_trailer) { if (will_close_connection() && _download_dest == DD_none) { if (downloader_cat.is_debug()) { downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID << "resetting to finish body; server would close anyway.\n"; } reset_to_new(); } else { if (has_trailer) { _state = HTTPChannel::S_read_body; } else { _state = HTTPChannel::S_read_trailer; } } } /** * If a download has been requested, opens the file on disk (or prepares the * RamFile or stream) and seeks within it to the appropriate * _first_byte_delivered position, so that downloaded bytes will be written to * the appropriate point within the file. Returns true if the starting * position is valid, false otherwise (in which case the state is set to * S_failure). */ bool HTTPChannel:: open_download_file() { _subdocument_resumes = (_subdocument_resumes && _first_byte_delivered != 0); if (_download_dest == DD_file) { VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); _download_to_stream = vfs->open_write_file(_download_to_filename, false, !_subdocument_resumes); if (_download_to_stream == NULL) { downloader_cat.info() << _NOTIFY_HTTP_CHANNEL_ID << "Could not open " << _download_to_filename << " for writing.\n"; _status_entry._status_code = SC_download_open_error; _state = S_failure; return false; } } if (_subdocument_resumes) { if (_download_dest == DD_file) { // Windows doesn't complain if you try to seek past the end of file--it // happily appends enough zero bytes to make the difference. Blecch. // That means we need to get the file size first to check it ourselves. _download_to_stream->seekp(0, ios::end); if (_first_byte_delivered > (size_t)_download_to_stream->tellp()) { downloader_cat.info() << _NOTIFY_HTTP_CHANNEL_ID << "Invalid starting position of byte " << _first_byte_delivered << " within " << _download_to_filename << " (which has " << _download_to_stream->tellp() << " bytes)\n"; close_download_stream(); _status_entry._status_code = SC_download_invalid_range; _state = S_failure; return false; } _download_to_stream->seekp(_first_byte_delivered); } else if (_download_dest == DD_ram) { if (_first_byte_delivered > _download_to_ramfile->_data.length()) { downloader_cat.info() << _NOTIFY_HTTP_CHANNEL_ID << "Invalid starting position of byte " << _first_byte_delivered << " within Ramfile (which has " << _download_to_ramfile->_data.length() << " bytes)\n"; close_download_stream(); _status_entry._status_code = SC_download_invalid_range; _state = S_failure; return false; } if (_first_byte_delivered == 0) { _download_to_ramfile->_data = string(); } else { _download_to_ramfile->_data = _download_to_ramfile->_data.substr(0, _first_byte_delivered); } } else if (_download_dest == DD_stream) { // Windows doesn't complain if you try to seek past the end of file--it // happily appends enough zero bytes to make the difference. Blecch. // That means we need to get the file size first to check it ourselves. _download_to_stream->seekp(0, ios::end); if (_first_byte_delivered > (size_t)_download_to_stream->tellp()) { downloader_cat.info() << _NOTIFY_HTTP_CHANNEL_ID << "Invalid starting position of byte " << _first_byte_delivered << " within stream (which has " << _download_to_stream->tellp() << " bytes)\n"; close_download_stream(); _status_entry._status_code = SC_download_invalid_range; _state = S_failure; return false; } _download_to_stream->seekp(_first_byte_delivered); } } else { // If _subdocument_resumes is false, we should be sure to reset to the // beginning of the file, regardless of the value of // _first_byte_delivered. if (_download_dest == DD_file || _download_dest == DD_stream) { _download_to_stream->seekp(0); } else if (_download_dest == DD_ram) { _download_to_ramfile->_data = string(); } } return true; } /** * Reads a single line from the server's reply. Returns true if the line is * successfully retrieved, or false if a complete line has not yet been * received or if the connection has been closed. */ bool HTTPChannel:: server_getline(string &str) { nassertr(!_source.is_null(), false); int ch = (*_source)->get(); while (!(*_source)->eof() && !(*_source)->fail()) { switch (ch) { case '\n': // end-of-line character, we're done. str = _working_get; _working_get = string(); { // Trim trailing whitespace. We're not required to do this per the // HTTP spec, but let's be generous. size_t p = str.length(); while (p > 0 && isspace(str[p - 1])) { --p; } str = str.substr(0, p); } if (downloader_cat.is_spam()) { downloader_cat.spam() << _NOTIFY_HTTP_CHANNEL_ID << "recv: " << str << "\n"; } return true; case '\r': // Ignore CR characters. break; default: _working_get += (char)ch; } ch = (*_source)->get(); } check_socket(); return false; } /** * Reads a line from the server's reply. If the server disconnects or times * out before sending a reply, moves on to the next proxy server (or sets * failure mode) and returns false; otherwise, returns true. */ bool HTTPChannel:: server_getline_failsafe(string &str) { if (!server_getline(str)) { if (_bio.is_null()) { // Huh, the server hung up on us as soon as we tried to connect. if (_response_type == RT_hangup) { // This was our second immediate hangup in a row. Give up. _status_entry._status_code = SC_lost_connection; _state = S_try_next_proxy; } else { // Try again, once. _response_type = RT_hangup; } } else { double elapsed = TrueClock::get_global_ptr()->get_short_time() - _sent_request_time; if (elapsed > get_http_timeout()) { // Time to give up. downloader_cat.info() << _NOTIFY_HTTP_CHANNEL_ID << "Timeout waiting for " << _request.get_url().get_server_and_port() << " in server_getline_failsafe (" << elapsed << " seconds elapsed).\n"; _status_entry._status_code = SC_timeout; _state = S_try_next_proxy; } } return false; } return true; } /** * Reads a fixed number of bytes from the server's reply. Returns true if the * indicated number of bytes are successfully retrieved, or false if the * complete set has not yet been received or if the connection has been * closed. */ bool HTTPChannel:: server_get(string &str, size_t num_bytes) { nassertr(!_source.is_null(), false); int ch = (*_source)->get(); while (!(*_source)->eof() && !(*_source)->fail()) { _working_get += (char)ch; if (_working_get.length() >= num_bytes) { str = _working_get; _working_get = string(); return true; } ch = (*_source)->get(); } check_socket(); return false; } /** * Reads a fixed number of bytes from the server. If the server disconnects * or times out before sending a reply, moves on to the next proxy server (or * sets failure mode) and returns false; otherwise, returns true. */ bool HTTPChannel:: server_get_failsafe(string &str, size_t num_bytes) { if (!server_get(str, num_bytes)) { if (_bio.is_null()) { // Huh, the server hung up on us as soon as we tried to connect. if (_response_type == RT_hangup) { // This was our second immediate hangup in a row. Give up. _status_entry._status_code = SC_lost_connection; _state = S_try_next_proxy; } else { // Try again, once. _response_type = RT_hangup; } } else { double elapsed = TrueClock::get_global_ptr()->get_short_time() - _sent_request_time; if (elapsed > get_http_timeout()) { // Time to give up. downloader_cat.info() << _NOTIFY_HTTP_CHANNEL_ID << "Timeout waiting for " << _request.get_url().get_server_and_port() << " in server_get_failsafe (" << elapsed << " seconds elapsed).\n"; _status_entry._status_code = SC_timeout; _state = S_try_next_proxy; } } return false; } return true; } /** * Sends a series of lines to the server. Returns true if the buffer is fully * sent, or false if some of it remains. If this returns false, the function * must be called again later, passing in the exact same string, until the * return value is true. * * If the secret flag is true, the data is not echoed to the log (even in spam * mode). This may be desirable if the data may contain binary data, or if it * may contain passwords etc. */ bool HTTPChannel:: server_send(const string &str, bool secret) { nassertr(str.length() > _sent_so_far, true); // Use the underlying BIO to write to the server, instead of the BIOStream, // which would insist on blocking (and might furthermore delay the send due // to collect-tcp mode being enabled). size_t bytes_to_send = str.length() - _sent_so_far; int write_count = BIO_write(*_bio, str.data() + _sent_so_far, bytes_to_send); if (write_count <= 0) { if (BIO_should_retry(*_bio)) { // Temporary failure: the pipe is full. Wait till later. return false; } // Oops, the connection has been closed! if (downloader_cat.is_debug()) { downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID << "Lost connection to server unexpectedly during write.\n"; } reset_to_new(); return false; } if (downloader_cat.is_spam()) { downloader_cat.spam() << _NOTIFY_HTTP_CHANNEL_ID << "wrote " << write_count << " bytes to " << _bio << "\n"; } #ifndef NDEBUG if (!secret && downloader_cat.is_spam()) { show_send(str.substr(0, write_count)); } #endif if (write_count < (int)bytes_to_send) { _sent_so_far += write_count; return false; } // Buffer completely sent. _sent_so_far = 0; return true; } /** * Parses the first line sent back from an HTTP server or proxy and stores the * result in _status_code and _http_version, etc. Returns true on success, * false on invalid response. */ bool HTTPChannel:: parse_http_response(const string &line) { // The first line back should include the HTTP version and the result code. if (line.length() < 5 || line.substr(0, 5) != string("HTTP/")) { // Not an HTTP response. _status_entry._status_code = SC_non_http_response; if (_response_type == RT_non_http) { // This was our second non-HTTP response in a row. Give up. _state = S_try_next_proxy; } else { // Maybe we were just in some bad state. Drop the connection and try // again, once. if (downloader_cat.is_debug()) { downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID << "got non-HTTP response, resetting.\n"; } reset_to_new(); _response_type = RT_non_http; } return false; } // Split out the first line into its three components. size_t p = 5; while (p < line.length() && !isspace(line[p])) { p++; } _http_version_string = line.substr(0, p); _http_version = HTTPClient::parse_http_version_string(_http_version_string); while (p < line.length() && isspace(line[p])) { p++; } size_t q = p; while (q < line.length() && !isspace(line[q])) { q++; } string status_code = line.substr(p, q - p); _status_entry._status_code = atoi(status_code.c_str()); while (q < line.length() && isspace(line[q])) { q++; } _status_entry._status_string = line.substr(q, line.length() - q); return true; } /** * Reads the series of header lines from the server and stores them in * _headers. Returns true if there is more to read, false when done. */ bool HTTPChannel:: parse_http_header() { string line; if (!server_getline(line)) { return true; } while (!line.empty()) { if (isspace(line[0])) { // If the line begins with a space, that continues the previous field. size_t p = 0; while (p < line.length() && isspace(line[p])) { p++; } _current_field_value += line.substr(p - 1); } else { // If the line does not begin with a space, that defines a new field. if (!_current_field_name.empty()) { store_header_field(_current_field_name, _current_field_value); _current_field_value = string(); } size_t colon = line.find(':'); if (colon != string::npos) { _current_field_name = downcase(line.substr(0, colon)); size_t p = colon + 1; while (p < line.length() && isspace(line[p])) { p++; } _current_field_value = line.substr(p); } } if (!server_getline(line)) { return true; } } // After reading an empty line, we're done with the headers. if (!_current_field_name.empty()) { store_header_field(_current_field_name, _current_field_value); _current_field_value = string(); } return false; } /** * Interprets the "Content-Range" header in the reply, and fills in * _first_byte_delivered and _last_byte_delivered appropriately if the header * response can be understood. */ bool HTTPChannel:: parse_content_range(const string &content_range) { // First, get the units indication. size_t p = 0; while (p < content_range.length() && !isspace(content_range[p])) { p++; } string units = content_range.substr(0, p); while (p < content_range.length() && isspace(content_range[p])) { p++; } if (units == "bytes") { const char *c_str = content_range.c_str(); char *endptr; if (p < content_range.length() && isdigit(content_range[p])) { long first_byte = strtol(c_str + p, &endptr, 10); p = endptr - c_str; if (p < content_range.length() && content_range[p] == '-') { p++; if (p < content_range.length() && isdigit(content_range[p])) { long last_byte = strtol(c_str + p, &endptr, 10); p = endptr - c_str; if (last_byte >= first_byte) { _first_byte_delivered = first_byte; _last_byte_delivered = last_byte; return true; } } } } } // Invalid or unhandled response. return false; } /** * Checks whether the connection to the server has been closed after a failed * read. If it has, issues a warning and calls reset_to_new(). */ void HTTPChannel:: check_socket() { nassertv(!_source.is_null()); if ((*_source)->is_closed()) { if (downloader_cat.is_debug()) { downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID << "Lost connection to server unexpectedly during read.\n"; } reset_to_new(); } } /* Certificate verify error codes: 0 X509_V_OK: ok the operation was successful. 2 X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT: unable to get issuer certificate the issuer certificate could not be found: this occurs if the issuer certificate of an untrusted certificate cannot be found. 3 X509_V_ERR_UNABLE_TO_GET_CRL unable to get certificate CRL the CRL of a certificate could not be found. Unused. 4 X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE: unable to decrypt certificate's signature the certificate signature could not be decrypted. This means that the actual signature value could not be determined rather than it not matching the expected value, this is only meaningful for RSA keys. 5 X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE: unable to decrypt CRL's signature the CRL signature could not be decrypted: this means that the actual signature value could not be determined rather than it not matching the expected value. Unused. 6 X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY: unable to decode issuer public key the public key in the certificate SubjectPublicKeyInfo could not be read. 7 X509_V_ERR_CERT_SIGNATURE_FAILURE: certificate signature failure the signature of the certificate is invalid. 8 X509_V_ERR_CRL_SIGNATURE_FAILURE: CRL signature failure the signature of the certificate is invalid. Unused. 9 X509_V_ERR_CERT_NOT_YET_VALID: certificate is not yet valid the certificate is not yet valid: the notBefore date is after the current time. 10 X509_V_ERR_CERT_HAS_EXPIRED: certificate has expired the certificate has expired: that is the notAfter date is before the current time. 11 X509_V_ERR_CRL_NOT_YET_VALID: CRL is not yet valid the CRL is not yet valid. Unused. 12 X509_V_ERR_CRL_HAS_EXPIRED: CRL has expired the CRL has expired. Unused. 13 X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD: format error in certificate's notBefore field the certificate notBefore field contains an invalid time. 14 X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD: format error in certificate's notAfter field the certificate notAfter field contains an invalid time. 15 X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD: format error in CRL's lastUpdate field the CRL lastUpdate field contains an invalid time. Unused. 16 X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD: format error in CRL's nextUpdate field the CRL nextUpdate field contains an invalid time. Unused. 17 X509_V_ERR_OUT_OF_MEM: out of memory an error occurred trying to allocate memory. This should never happen. 18 X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: self signed certificate the passed certificate is self signed and the same certificate cannot be found in the list of trusted certificates. 19 X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN: self signed certificate in certificate chain the certificate chain could be built up using the untrusted certificates but the root could not be found locally. 20 X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY: unable to get local issuer certificate the issuer certificate of a locally looked up certificate could not be found. This normally means the list of trusted certificates is not complete. 21 X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE: unable to verify the first certificate no signatures could be verified because the chain contains only one certificate and it is not self signed. 22 X509_V_ERR_CERT_CHAIN_TOO_LONG: certificate chain too long the certificate chain length is greater than the supplied maximum depth. Unused. 23 X509_V_ERR_CERT_REVOKED: certificate revoked the certificate has been revoked. Unused. 24 X509_V_ERR_INVALID_CA: invalid CA certificate a CA certificate is invalid. Either it is not a CA or its extensions are not consistent with the supplied purpose. 25 X509_V_ERR_PATH_LENGTH_EXCEEDED: path length constraint exceeded the basicConstraints pathlength parameter has been exceeded. 26 X509_V_ERR_INVALID_PURPOSE: unsupported certificate purpose the supplied certificate cannot be used for the specified purpose. 27 X509_V_ERR_CERT_UNTRUSTED: certificate not trusted the root CA is not marked as trusted for the specified purpose. 28 X509_V_ERR_CERT_REJECTED: certificate rejected the root CA is marked to reject the specified purpose. 29 X509_V_ERR_SUBJECT_ISSUER_MISMATCH: subject issuer mismatch the current candidate issuer certificate was rejected because its subject name did not match the issuer name of the current certificate. Only displayed when the -issuer_checks option is set. 30 X509_V_ERR_AKID_SKID_MISMATCH: authority and subject key identifier mismatch the current candidate issuer certificate was rejected because its subject key identifier was present and did not match the authority key identifier current certificate. Only displayed when the -issuer_checks option is set. 31 X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH: authority and issuer serial number mismatch the current candidate issuer certificate was rejected because its issuer name and serial number was present and did not match the authority key identifier of the current certificate. Only displayed when the -issuer_checks option is set. 32 X509_V_ERR_KEYUSAGE_NO_CERTSIGN:key usage does not include certificate signing the current candidate issuer certificate was rejected because its keyUsage extension does not permit certificate signing. 50 X509_V_ERR_APPLICATION_VERIFICATION: application verification failure an application specific error. Unused. */ /** * Checks to see if the indicated certificate is on the pre-approved list for * the current server. * * If the full cert itself (including its key) is on the pre-approved list, * sets both cert_preapproved and cert_name_preapproved to true. * * If the full cert is not on the pre-approved list, but its name matches a * name on the pre-approved list, sets cert_name_preapproved to true, and * cert_preapproved to false. * * Otherwise, sets both values to false. This doesn't mean the cert is * necessarily invalid, just that it wasn't on the pre-approved list (which is * usually empty anyway). */ void HTTPChannel:: check_preapproved_server_certificate(X509 *cert, bool &cert_preapproved, bool &cert_name_preapproved) const { return _client->check_preapproved_server_certificate(_request.get_url(), cert, cert_preapproved, cert_name_preapproved); } /** * Returns true if the name in the cert matches the hostname of the server, * false otherwise. */ bool HTTPChannel:: validate_server_name(X509 *cert) { string hostname = _request.get_url().get_server(); vector_string cert_names; // According to RFC 2818, we should check the DNS name(s) in the // subjectAltName extension first, if that extension exists. STACK_OF(GENERAL_NAME) *subject_alt_names = (STACK_OF(GENERAL_NAME) *)X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL); if (subject_alt_names != NULL) { int num_alts = sk_GENERAL_NAME_num(subject_alt_names); for (int i = 0; i < num_alts; ++i) { // Get the ith alt name. const GENERAL_NAME *alt_name = sk_GENERAL_NAME_value(subject_alt_names, i); if (alt_name->type == GEN_DNS) { char *buffer = NULL; int len = ASN1_STRING_to_UTF8((unsigned char**)&buffer, alt_name->d.ia5); if (len > 0) { cert_names.push_back(string(buffer, len)); } if (buffer != NULL) { OPENSSL_free(buffer); } } } } if (cert_names.empty()) { // If there were no DNS names, use the common name instead. X509_NAME *xname = X509_get_subject_name(cert); if (xname != NULL) { string common_name = get_x509_name_component(xname, NID_commonName); cert_names.push_back(common_name); } } if (cert_names.empty()) { downloader_cat.info() << _NOTIFY_HTTP_CHANNEL_ID << "Server certificate from " << hostname << " provides no name.\n"; return false; } if (downloader_cat.is_debug()) { downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID << "Server certificate from " << hostname << " provides name(s):"; vector_string::const_iterator si; for (si = cert_names.begin(); si != cert_names.end(); ++si) { const string &cert_name = (*si); downloader_cat.debug(false) << " " << cert_name; } downloader_cat.debug(false) << "\n"; } // Now validate the names we found. If any of them matches, the cert // matches. vector_string::const_iterator si; for (si = cert_names.begin(); si != cert_names.end(); ++si) { const string &cert_name = (*si); if (match_cert_name(cert_name, hostname)) { return true; } } downloader_cat.info() << _NOTIFY_HTTP_CHANNEL_ID << "Server certificate from " << hostname << " provides wrong name(s):"; for (si = cert_names.begin(); si != cert_names.end(); ++si) { const string &cert_name = (*si); downloader_cat.info(false) << " " << cert_name; } downloader_cat.info(false) << "\n"; return false; } /** * Returns true if this particular name from the certificate matches the * indicated hostname, false otherwise. */ bool HTTPChannel:: match_cert_name(const string &cert_name, const string &hostname) { // We use GlobPattern to match the name. This isn't quite consistent with // RFC2818, since it also accepts additional wildcard characters like "?" // and "[]", but I think it's close enough. GlobPattern pattern(cert_name); pattern.set_case_sensitive(false); pattern.set_nomatch_chars("."); return pattern.matches(hostname); } /** * Returns the indicated component of the X509 name as a string, if defined, * or empty string if it is not. */ string HTTPChannel:: get_x509_name_component(X509_NAME *name, int nid) { ASN1_OBJECT *obj = OBJ_nid2obj(nid); if (obj == NULL) { // Unknown nid. See opensslobjects.h. return string(); } int i = X509_NAME_get_index_by_OBJ(name, obj, -1); if (i < 0) { return string(); } ASN1_STRING *data = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, i)); return string((char *)data->data, data->length); } /** * Formats the appropriate GET or POST (or whatever) request to send to the * server, based on the current _method, _document_spec, _body, and _proxy * settings. */ void HTTPChannel:: make_header() { _proxy_auth = _client->select_auth(_proxy, true, _proxy_realm); _proxy_username = string(); if (_proxy_auth != (HTTPAuthorization *)NULL) { _proxy_realm = _proxy_auth->get_realm(); _proxy_username = _client->select_username(_proxy, true, _proxy_realm); } if (_method == HTTPEnum::M_connect) { // This method doesn't require an HTTP header at all; we'll just open a // plain connection. (Except when we're using a proxy; but in that case, // it's the proxy_header we'll need, not the regular HTTP header.) _header = string(); return; } _www_auth = _client->select_auth(_request.get_url(), false, _www_realm); _www_username = string(); if (_www_auth != (HTTPAuthorization *)NULL) { _www_realm = _www_auth->get_realm(); _www_username = _client->select_username(_request.get_url(), false, _www_realm); } string request_path; if (_proxy_serves_document) { // If we'll be asking the proxy for the document, we need its full URL-- // but we omit the username, which is information just for us. URLSpec url_no_username = _request.get_url(); url_no_username.set_username(string()); request_path = url_no_username.get_url(); } else { // If we'll be asking the server directly for the document, we just want // its path relative to the server. request_path = _request.get_url().get_path_and_query(); } // HTTP syntax always requires something in the request path. If it is // empty, put in a star as a placeholder (OPTIONS, for instance, uses this). if (request_path.empty()) { request_path = "*"; } ostringstream stream; stream << _method << " " << request_path << " " << _client->get_http_version_string() << "\r\n"; if (_client->get_http_version() >= HTTPEnum::HV_11) { if (_request.get_url().has_port() && _request.get_url().is_default_port()) { // It appears that some servers (notably gstatic.com) might return a 404 // if you include an explicit port number in with the Host: header, even // if it is the default port. So, don't include the port number unless // we need to. string server = _request.get_url().get_server(); if (server.find(':') != string::npos) { stream << "Host: [" << server << "]"; } else { stream << "Host: " << server; } } else { stream << "Host: " << _request.get_url().get_server_and_port(); } stream << "\r\n"; if (!get_persistent_connection()) { stream << "Connection: close\r\n"; } } if (_last_byte_requested != 0) { stream << "Range: bytes=" << _first_byte_requested << "-" << _last_byte_requested << "\r\n"; } else if (_first_byte_requested != 0) { stream << "Range: bytes=" << _first_byte_requested << "-\r\n"; } switch (_request.get_request_mode()) { case DocumentSpec::RM_any: // No particular request; give us any document that matches the URL. if (_first_byte_requested != 0) { // Unless we're requesting a subrange, in which case if the exact // document matches, retrieve the subrange indicated; otherwise, // retrieve the entire document. if (_request.has_tag()) { stream << "If-Range: " << _request.get_tag().get_string() << "\r\n"; } else if (_request.has_date()) { stream << "If-Range: " << _request.get_date().get_string() << "\r\n"; } } break; case DocumentSpec::RM_equal: // Give us only this particular version of the document, or nothing. if (_request.has_tag()) { stream << "If-Match: " << _request.get_tag().get_string() << "\r\n"; } if (_request.has_date()) { stream << "If-Unmodified-Since: " << _request.get_date().get_string() << "\r\n"; } break; case DocumentSpec::RM_newer: // Give us anything newer than this document, or nothing. if (_request.has_tag()) { stream << "If-None-Match: " << _request.get_tag().get_string() << "\r\n"; } if (_request.has_date()) { stream << "If-Modified-Since: " << _request.get_date().get_string() << "\r\n"; } break; case DocumentSpec::RM_equal_or_newer: // Just don't give us anything older. if (_request.has_date()) { // This is a little unreliable: we ask for any document that's been // modified since one second before our last-modified-date. Who knows // whether the server will honor this properly. stream << "If-Modified-Since: " << (_request.get_date() - 1).get_string() << "\r\n"; } break; } switch (_request.get_cache_control()) { case DocumentSpec::CC_allow_cache: // Normal, caching behavior. break; case DocumentSpec::CC_revalidate: // Request the server to revalidate its cache before returning it. stream << "Cache-Control: max-age=0\r\n"; break; case DocumentSpec::CC_no_cache: // Request the server to get a fresh copy regardless of its cache. stream << "Cache-Control: no-cache\r\n" << "Pragma: no-cache\r\n"; break; } _client->send_cookies(stream, _request.get_url()); if (!_body.empty()) { stream << "Content-Type: application/x-www-form-urlencoded\r\n" << "Content-Length: " << _body.length() << "\r\n"; } _header = stream.str(); } /** * Builds the _proxy_request_text string. This is a special request that will * be sent directly to the proxy prior to the request tailored for the server. * Generally this is used to open a tunnelling connection for https-over- * proxy. */ void HTTPChannel:: make_proxy_request_text() { _proxy_request_text = _proxy_header; if (_proxy_auth != (HTTPAuthorization *)NULL && !_proxy_username.empty()) { _proxy_request_text += "Proxy-Authorization: "; _proxy_request_text += _proxy_auth->generate(HTTPEnum::M_connect, _request.get_url().get_server_and_port(), _proxy_username, _body); _proxy_request_text += "\r\n"; } _proxy_request_text += "\r\n"; } /** * Builds the _request_text string. This is the specific request that will be * sent to the server this pass, based on the current header and body. */ void HTTPChannel:: make_request_text() { _request_text = _header; if (_proxy_serves_document && _proxy_auth != (HTTPAuthorization *)NULL && !_proxy_username.empty()) { _request_text += "Proxy-Authorization: "; _request_text += _proxy_auth->generate(_method, _request.get_url().get_url(), _proxy_username, _body); _request_text += "\r\n"; } if (_www_auth != (HTTPAuthorization *)NULL && !_www_username.empty()) { string authorization = _request_text += "Authorization: "; _request_text += _www_auth->generate(_method, _request.get_url().get_path_and_query(), _www_username, _body); _request_text += "\r\n"; } _request_text += _send_extra_headers; _request_text += "\r\n"; _request_text += _body; } /** * Redirects the next connection to the indicated URL (from the previous URL). * This resets the socket if necessary when we are about to switch servers. */ void HTTPChannel:: reset_url(const URLSpec &old_url, const URLSpec &new_url) { // If we change between http and https, we have to reset the connection // regardless of proxy. Otherwise, we have to drop the connection if the // server or port changes, unless we're communicating through a proxy. if (new_url.get_scheme() != old_url.get_scheme() || (_proxy.empty() && (new_url.get_server() != old_url.get_server() || new_url.get_port() != old_url.get_port()))) { if (downloader_cat.is_debug()) { downloader_cat.debug() << _NOTIFY_HTTP_CHANNEL_ID << "resetting for new server " << new_url.get_server_and_port() << "\n"; } reset_to_new(); } } /** * Stores a single name: value pair in the header list, or appends the value * to the end of the existing value, if the header has been repeated. */ void HTTPChannel:: store_header_field(const string &field_name, const string &field_value) { pair<Headers::iterator, bool> insert_result = _headers.insert(Headers::value_type(field_name, field_value)); if (!insert_result.second) { // It didn't insert; thus, the field already existed. Append the new // value. Headers::iterator hi = insert_result.first; (*hi).second += ", "; (*hi).second += field_value; } if (field_name == "set-cookie") { _client->set_cookie(HTTPCookie(field_value, _request.get_url())); } } #ifndef NDEBUG /** * Writes the outgoing message, one line at a time, to the debugging log. */ void HTTPChannel:: show_send(const string &message) { size_t start = 0; size_t newline = message.find('\n', start); while (newline != string::npos) { // Assume every \n is preceded by a \r. downloader_cat.spam() << "send: " << message.substr(start, newline - start - 1) << "\n"; start = newline + 1; newline = message.find('\n', start); } if (start < message.length()) { downloader_cat.spam() << "send: " << message.substr(start) << " (no newline)\n"; } } #endif // NDEBUG /** * Resets the indication of how the document will be downloaded. This must be * re-specified after each get_document() (or related) call. */ void HTTPChannel:: reset_download_to() { _started_download = false; close_download_stream(); _download_dest = DD_none; } /** * Ensures the file opened for receiving the download has been correctly * closed. */ void HTTPChannel:: close_download_stream() { if (_download_to_stream != NULL) { _download_to_stream->flush(); if (_download_dest == DD_file) { VirtualFileSystem::close_write_file(_download_to_stream); } } _download_to_ramfile = (Ramfile *)NULL; _download_to_stream = NULL; } /** * Closes the connection and resets the state to S_new. */ void HTTPChannel:: reset_to_new() { if (downloader_cat.is_spam()) { downloader_cat.spam() << _NOTIFY_HTTP_CHANNEL_ID << "reset_to_new.\n"; } close_connection(); _state = S_new; } /** * Clears the _body_stream pointer, if it is set. */ void HTTPChannel:: reset_body_stream() { if (_owns_body_stream) { if (_body_stream != (ISocketStream *)NULL) { close_read_body(_body_stream); nassertv(_body_stream == (ISocketStream *)NULL && !_owns_body_stream); } } else { _body_stream = NULL; } } /** * Closes the connection but leaves the _state unchanged. */ void HTTPChannel:: close_connection() { reset_body_stream(); _source.clear(); _bio.clear(); _working_get = string(); _sent_so_far = 0; _read_index++; } /** * Returns true if status code a is a more useful value (that is, it * represents a more-nearly successfully connection attempt, or contains more * information) than b, or false otherwise. */ bool HTTPChannel:: more_useful_status_code(int a, int b) { if (a >= 100 && b >= 100) { // Both represent HTTP responses. Responses from a server (< 1000) are // better than those from a proxy; we take advantage of the fact that we // have already added 1000 to proxy responses. Except for 407, so let's // fix that now. if (a == 407) { a += 1000; } if (b == 407) { b += 1000; } // Now just check the series. int series_a = (a / 100); int series_b = (b / 100); // In general, a lower series is a closer success. return (series_a < series_b); } if (a < 100 && b < 100) { // Both represent non-HTTP responses. Here a larger number is better. return (a > b); } if (a < 100) { // a is a non-HTTP response, while b is an HTTP response. HTTP is // generally, better, unless we exceeded SC_http_error_watermark. return (a > SC_http_error_watermark); } // Exactly the opposite case as above. return (b < SC_http_error_watermark); } /** * */ ostream & operator << (ostream &out, HTTPChannel::State state) { #ifdef NDEBUG return out << (int)state; #else switch (state) { case HTTPChannel::S_new: return out << "new"; case HTTPChannel::S_try_next_proxy: return out << "try_next_proxy"; case HTTPChannel::S_connecting: return out << "connecting"; case HTTPChannel::S_connecting_wait: return out << "connecting_wait"; case HTTPChannel::S_http_proxy_ready: return out << "http_proxy_ready"; case HTTPChannel::S_http_proxy_request_sent: return out << "http_proxy_request_sent"; case HTTPChannel::S_http_proxy_reading_header: return out << "http_proxy_reading_header"; case HTTPChannel::S_socks_proxy_greet: return out << "socks_proxy_greet"; case HTTPChannel::S_socks_proxy_greet_reply: return out << "socks_proxy_greet_reply"; case HTTPChannel::S_socks_proxy_connect: return out << "socks_proxy_connect"; case HTTPChannel::S_socks_proxy_connect_reply: return out << "socks_proxy_connect_reply"; case HTTPChannel::S_setup_ssl: return out << "setup_ssl"; case HTTPChannel::S_ssl_handshake: return out << "ssl_handshake"; case HTTPChannel::S_ready: return out << "ready"; case HTTPChannel::S_request_sent: return out << "request_sent"; case HTTPChannel::S_reading_header: return out << "reading_header"; case HTTPChannel::S_start_direct_file_read: return out << "start_direct_file_read"; case HTTPChannel::S_read_header: return out << "read_header"; case HTTPChannel::S_begin_body: return out << "begin_body"; case HTTPChannel::S_reading_body: return out << "reading_body"; case HTTPChannel::S_read_body: return out << "read_body"; case HTTPChannel::S_read_trailer: return out << "read_trailer"; case HTTPChannel::S_failure: return out << "failure"; } return out << "invalid state(" << (int)state << ")"; #endif // NDEBUG } #endif // HAVE_OPENSSL
29.703872
100
0.664289
[ "object", "3d" ]
a7ebd87e87908dcce3c44a69ff383c6c5a6e06f8
2,660
cpp
C++
ros_controllers/temperature_sensor_controller/src/temperature_sensor_controller.cpp
hect1995/Robotics_intro
1b687585c20db5f1114d8ca6811a70313d325dd6
[ "BSD-3-Clause" ]
7
2018-10-24T14:52:20.000Z
2021-01-12T14:59:00.000Z
ros_controllers/temperature_sensor_controller/src/temperature_sensor_controller.cpp
hect1995/Robotics_intro
1b687585c20db5f1114d8ca6811a70313d325dd6
[ "BSD-3-Clause" ]
null
null
null
ros_controllers/temperature_sensor_controller/src/temperature_sensor_controller.cpp
hect1995/Robotics_intro
1b687585c20db5f1114d8ca6811a70313d325dd6
[ "BSD-3-Clause" ]
17
2019-09-29T10:22:41.000Z
2021-04-08T12:38:37.000Z
#include <algorithm> #include <cstddef> #include <temperature_sensor_controller/temperature_sensor_controller.h> namespace temperature_sensor_controller { bool TemperatureSensorController::init(hardware_interface::ActuatorTemperatureSensorInterface* hw, ros::NodeHandle& root_nh, ros::NodeHandle& controller_nh) { // get all joint names from the hardware interface const std::vector<std::string>& actuator_names = hw->getNames(); num_hw_joints_ = actuator_names.size(); for (unsigned i=0; i<num_hw_joints_; i++) ROS_DEBUG("Got actuator %s", actuator_names[i].c_str()); // get publishing period if (!controller_nh.getParam("publish_rate", publish_rate_)){ ROS_ERROR("Parameter 'publish_rate' not set"); return false; } // realtime publisher realtime_pub_.reset(new realtime_tools::RealtimePublisher<temperature_sensor_controller::ActuatorTemperatureState>(root_nh, "actuator_temperatures", 4)); // get joints and allocate message for (unsigned i=0; i<num_hw_joints_; i++){ actuator_state_.push_back(hw->getHandle(actuator_names[i])); realtime_pub_->msg_.name.push_back(actuator_names[i]); realtime_pub_->msg_.temperature.push_back(0.0); } return true; } void TemperatureSensorController::starting(const ros::Time& time) { // initialize time last_publish_time_ = time; } void TemperatureSensorController::update(const ros::Time& time, const ros::Duration& /*period*/) { // limit rate of publishing if (publish_rate_ > 0.0 && last_publish_time_ + ros::Duration(1.0/publish_rate_) < time){ // try to publish if (realtime_pub_->trylock()){ // we're actually publishing, so increment time last_publish_time_ = last_publish_time_ + ros::Duration(1.0/publish_rate_); // populate joint state message: // - fill only joints that are present in the JointStateInterface, i.e. indices [0, num_hw_joints_) // - leave unchanged extra joints, which have static values, i.e. indices from num_hw_joints_ onwards realtime_pub_->msg_.header.stamp = time; for (unsigned i=0; i<num_hw_joints_; i++){ realtime_pub_->msg_.temperature[i] = actuator_state_[i].getValue(); } realtime_pub_->unlockAndPublish(); } } } void TemperatureSensorController::stopping(const ros::Time& /*time*/) {} } PLUGINLIB_EXPORT_CLASS(temperature_sensor_controller::TemperatureSensorController, controller_interface::ControllerBase)
36.438356
157
0.676316
[ "vector" ]
a7ec04b062e939e9879bbe05d324b9daf0a544d7
37,643
cpp
C++
src/networkManager/NetworkManager.cpp
teddywest32/bitcoinclassic
509e94c1cf587bd83e082b24b08373ab6e60cb66
[ "MIT" ]
null
null
null
src/networkManager/NetworkManager.cpp
teddywest32/bitcoinclassic
509e94c1cf587bd83e082b24b08373ab6e60cb66
[ "MIT" ]
null
null
null
src/networkManager/NetworkManager.cpp
teddywest32/bitcoinclassic
509e94c1cf587bd83e082b24b08373ab6e60cb66
[ "MIT" ]
null
null
null
/* * This file is part of the bitcoin-classic project * Copyright (C) 2016 Tom Zander <tomz@freedommail.ch> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "NetworkManager.h" #include "NetworkManager_p.h" #include "NetworkEnums.h" #include <streaming/MessageBuilder.h> #include <streaming/MessageParser.h> #include <boost/lexical_cast.hpp> #include <boost/make_shared.hpp> #include <util.h> // #define DEBUG_CONNECTIONS static const int RECEIVE_STREAM_SIZE = 41000; static const int CHUNK_SIZE = 8000; static const int MAX_MESSAGE_SIZE = 9000; namespace { int reconnectTimeoutForStep(short step) { if (step < 6) return step*step*step; return 300; // 5 min } } NetworkManager::NetworkManager(boost::asio::io_service &service) : d(std::make_shared<NetworkManagerPrivate>(service)) { } NetworkManager::~NetworkManager() { boost::recursive_mutex::scoped_lock lock(d->mutex); d->isClosingDown = true; for (auto server : d->servers) { server->shutdown(); } for (auto it = d->connections.begin(); it != d->connections.end(); ++it) { it->second->shutdown(it->second); } d->connections.clear(); // invalidate NetworkConnection references } NetworkConnection NetworkManager::connection(const EndPoint &remote, ConnectionEnum connect) { const bool hasHostname = !remote.ipAddress.is_unspecified() && remote.announcePort > 0; if (hasHostname) { boost::recursive_mutex::scoped_lock lock(d->mutex); for (auto iter1 = d->connections.begin(); iter1 != d->connections.end(); ++iter1) { EndPoint endPoint = iter1->second->endPoint(); if (endPoint.ipAddress != remote.ipAddress) continue; if (!(endPoint.announcePort == 0 || endPoint.announcePort == remote.announcePort || remote.announcePort == 0)) continue; return NetworkConnection(this, iter1->first); } if (connect == AutoCreate) { EndPoint ep(remote); ep.peerPort = ep.announcePort; // outgoing connections always have those the same. ep.connectionId = ++d->lastConnectionId; d->connections.insert(std::make_pair(ep.connectionId, std::make_shared<NetworkManagerConnection>(d, ep))); return NetworkConnection(this, ep.connectionId); } } return NetworkConnection(); } EndPoint NetworkManager::endPoint(int remoteId) const { boost::recursive_mutex::scoped_lock lock(d->mutex); NetworkManagerConnection *con = d->connections.at(remoteId).get(); if (con) return con->endPoint(); return EndPoint(); } void NetworkManager::punishNode(int remoteId, int punishment) { d->punishNode(remoteId, punishment); } void NetworkManager::bind(tcp::endpoint endpoint, const std::function<void(NetworkConnection&)> &callback) { boost::recursive_mutex::scoped_lock lock(d->mutex); try { NetworkManagerServer *server = new NetworkManagerServer(d, endpoint, callback); d->servers.push_back(server); } catch (std::exception &ex) { logWarning(Log::NWM) << "Creating NetworkMangerServer failed with" << ex.what(); throw std::runtime_error("Failed to bind to endpoint"); } if (d->servers.size() == 1) // start cron d->cronHourly(boost::system::error_code()); } std::weak_ptr<NetworkManagerPrivate> NetworkManager::priv() { return d; } ///////////////////////////////////// NetworkManagerPrivate::NetworkManagerPrivate(boost::asio::io_service &service) : ioService(service), lastConnectionId(0), isClosingDown(false), m_cronHourly(service) { } NetworkManagerPrivate::~NetworkManagerPrivate() { } void NetworkManagerPrivate::punishNode(int connectionId, int punishScore) { boost::recursive_mutex::scoped_lock lock(mutex); auto con = connections.find(connectionId); if (con == connections.end()) return; con->second->m_punishment += punishScore; if (con->second->m_punishment >= 1000) { BannedNode bn; bn.endPoint = con->second->endPoint(); bn.banTimeout = boost::posix_time::second_clock::universal_time() + boost::posix_time::hours(24); logInfo(Log::NWM) << "Banned node for 24 hours due to excessive bad behavior" << bn.endPoint.hostname; banned.push_back(bn); connections.erase(connectionId); con->second->shutdown(con->second); } } void NetworkManagerPrivate::cronHourly(const boost::system::error_code &error) { if (error) return; logDebug(Log::NWM) << "cronHourly"; boost::recursive_mutex::scoped_lock lock(mutex); if (isClosingDown) return; const auto now = boost::posix_time::second_clock::universal_time(); std::list<BannedNode>::iterator bannedNode = banned.begin(); // clean out banned nodes while (bannedNode != banned.end()) { if (bannedNode->banTimeout < now) bannedNode = banned.erase(bannedNode); else ++bannedNode; } for (auto connection : connections) { connection.second->m_punishment = std::max(0, connection.second->m_punishment - 100); // logDebug(Log::NWM) << "peer ban scrore;" << connection.second->m_punishment; } m_cronHourly.expires_from_now(boost::posix_time::hours(1)); m_cronHourly.async_wait(std::bind(&NetworkManagerPrivate::cronHourly, this, std::placeholders::_1)); } ///////////////////////////////////// NetworkManagerConnection::NetworkManagerConnection(const std::shared_ptr<NetworkManagerPrivate> &parent, tcp::socket socket, int connectionId) : m_strand(parent->ioService), m_punishment(0), d(parent), m_socket(std::move(socket)), m_resolver(parent->ioService), m_messageBytesSend(0), m_messageBytesSent(0), m_receiveStream(RECEIVE_STREAM_SIZE), m_lastCallbackId(1), m_isClosingDown(false), m_firstPacket(true), m_isConnecting(false), m_sendingInProgress(false), m_acceptedConnection(false), m_reconnectStep(0), m_reconnectDelay(parent->ioService), m_pingTimer(parent->ioService), m_chunkedServiceId(-1), m_chunkedMessageId(-1) { m_remote.ipAddress = m_socket.remote_endpoint().address(); m_remote.announcePort = m_socket.remote_endpoint().port(); m_remote.peerPort = 0; m_remote.connectionId = connectionId; } NetworkManagerConnection::NetworkManagerConnection(const std::shared_ptr<NetworkManagerPrivate> &parent, const EndPoint &remote) : m_strand(parent->ioService), m_punishment(0), m_remote(std::move(remote)), d(parent), m_socket(parent->ioService), m_resolver(parent->ioService), m_messageBytesSend(0), m_messageBytesSent(0), m_receiveStream(RECEIVE_STREAM_SIZE), m_lastCallbackId(1), m_isClosingDown(false), m_firstPacket(true), m_isConnecting(false), m_sendingInProgress(false), m_acceptedConnection(false), m_reconnectStep(0), m_reconnectDelay(parent->ioService), m_pingTimer(parent->ioService), m_chunkedServiceId(-1), m_chunkedMessageId(-1) { if (m_remote.peerPort == 0) m_remote.peerPort = m_remote.announcePort; } void NetworkManagerConnection::connect() { if (m_strand.running_in_this_thread()) connect_priv(); else runOnStrand(std::bind(&NetworkManagerConnection::connect_priv, this)); } void NetworkManagerConnection::connect_priv() { assert(m_strand.running_in_this_thread()); if (m_isConnecting) return; if (m_isClosingDown) return; m_isConnecting = true; if (m_remote.ipAddress.is_unspecified()) { tcp::resolver::query query(m_remote.hostname, boost::lexical_cast<std::string>(m_remote.announcePort)); m_resolver.async_resolve(query, m_strand.wrap(std::bind(&NetworkManagerConnection::onAddressResolveComplete, this, std::placeholders::_1, std::placeholders::_2))); } else { m_isConnecting = false; if (m_remote.hostname.empty()) m_remote.hostname = m_remote.ipAddress.to_string(); boost::asio::ip::tcp::endpoint endpoint(m_remote.ipAddress, m_remote.announcePort); m_socket.async_connect(endpoint, m_strand.wrap( std::bind(&NetworkManagerConnection::onConnectComplete, this, std::placeholders::_1))); } } void NetworkManagerConnection::onAddressResolveComplete(const boost::system::error_code &error, tcp::resolver::iterator iterator) { assert(m_strand.running_in_this_thread()); m_isConnecting = false; if (m_isClosingDown) return; if (error) { logDebug(Log::NWM) << "connect;" << error.message(); m_reconnectDelay.expires_from_now(boost::posix_time::seconds(45)); m_reconnectDelay.async_wait(m_strand.wrap(std::bind(&NetworkManagerConnection::reconnectWithCheck, this, std::placeholders::_1))); return; } m_remote.ipAddress = (iterator++)->endpoint().address(); // Notice that we always only use the first reported DNS entry. Which is likely Ok. m_socket.async_connect(*iterator, m_strand.wrap( std::bind(&NetworkManagerConnection::onConnectComplete, this, std::placeholders::_1))); } void NetworkManagerConnection::onConnectComplete(const boost::system::error_code& error) { if (error.value() == boost::asio::error::operation_aborted) return; assert(m_strand.running_in_this_thread()); if (m_isClosingDown) return; if (error) { logDebug(Log::NWM) << "connect;" << error.message(); if (m_remote.peerPort != m_remote.announcePort) // incoming connection return; m_reconnectDelay.expires_from_now(boost::posix_time::seconds(reconnectTimeoutForStep(++m_reconnectStep))); m_reconnectDelay.async_wait(m_strand.wrap(std::bind(&NetworkManagerConnection::reconnectWithCheck, this, std::placeholders::_1))); return; } logInfo(Log::NWM) << "Successfully connected to" << m_remote.hostname << m_remote.announcePort; for (auto it = m_onConnectedCallbacks.begin(); it != m_onConnectedCallbacks.end(); ++it) { try { it->second(m_remote); } catch (const std::exception &ex) { logWarning(Log::NWM) << "onConnected threw exception, ignoring:" << ex.what(); } } // setup a callback for receiving. m_receiveStream.reserve(MAX_MESSAGE_SIZE); m_socket.async_receive(boost::asio::buffer(m_receiveStream.data(), m_receiveStream.capacity()), m_strand.wrap(std::bind(&NetworkManagerConnection::receivedSomeBytes, this, std::placeholders::_1, std::placeholders::_2))); if (m_remote.peerPort == m_remote.announcePort) { // for outgoing connections, ping. m_pingTimer.expires_from_now(boost::posix_time::seconds(90)); m_pingTimer.async_wait(m_strand.wrap(std::bind(&NetworkManagerConnection::sendPing, this, std::placeholders::_1))); } else { // for incoming connections, take action when no ping comes in. m_pingTimer.expires_from_now(boost::posix_time::seconds(120)); m_pingTimer.async_wait(m_strand.wrap(std::bind(&NetworkManagerConnection::pingTimeout, this, std::placeholders::_1))); } runMessageQueue(); } Streaming::ConstBuffer NetworkManagerConnection::createHeader(const Message &message) { m_sendHelperBuffer.reserve(20); Streaming::MessageBuilder builder(m_sendHelperBuffer, Streaming::HeaderOnly); assert(message.serviceId() >= 0); const auto map = message.headerData(); auto iter = map.begin(); while (iter != map.end()) { builder.add(iter->first, iter->second); ++iter; } builder.add(Network::HeaderEnd, true); builder.setMessageSize(m_sendHelperBuffer.size() + message.size()); logDebug(Log::NWM) << "createHeader of message of length;" << m_sendHelperBuffer.size() << '+' << message.size(); return builder.buffer(); } void NetworkManagerConnection::runMessageQueue() { assert(m_strand.running_in_this_thread()); if (m_sendingInProgress || m_isConnecting || m_isClosingDown || m_messageQueue.empty() || !isConnected()) return; assert(m_messageBytesSend <= m_messageQueue.front().rawData().size()); m_sendingInProgress = true; /* * This method will schedule sending of data. * The data to send is pushed async to the network stack and the callback will come in essentially * the moment the network stack has accepted the data. This is not at all any confirmation that * the other side accepted it! * But at the same time, the network stack has limited buffers and will only push to the network * an amount based on the TCP window size. So at minimum we know that the speed with which we * send stuff is indicative of the throughput. * * The idea here is to send a maximum amount of 250KB at a time. Which should be enough to avoid * delays. The speed limiter here mean we still allow messages that were pushed to the front of the * queue to be handled at a good speed. */ int bytesLeft = 250*1024; std::vector<Streaming::ConstBuffer> socketQueue; // the stuff we will send over the socket std::list<Message>::iterator iter = m_priorityMessageQueue.begin(); while (iter != m_priorityMessageQueue.end()) { const Message &message = *iter; if (!iter->hasHeader()) { // build a simple header const Streaming::ConstBuffer constBuf = createHeader(message); bytesLeft -= constBuf.size(); socketQueue.push_back(constBuf); m_sendQHeaders.push_back(constBuf); } socketQueue.push_back(message.rawData()); bytesLeft -= message.rawData().size(); m_sentPriorityMessages.push_back(message); iter = m_priorityMessageQueue.erase(iter); if (bytesLeft <= 0) break; } for (const Message &message : m_messageQueue) { if (bytesLeft <= 0) break; if (message.rawData().size() > CHUNK_SIZE) { assert(!message.hasHeader()); // should have been blocked from entering in queueMessage(); /* * The maximum size of a message is 9KB. This helps a lot with memory allocations and zero-copy ;) * A large message is then split into smaller ones and send with individual headers * to the other side where they can be re-connected. */ Streaming::ConstBuffer body(message.body()); const char *begin = body.begin() + m_messageBytesSend; const char *end = body.end(); Streaming::MessageBuilder headerBuilder(m_sendHelperBuffer, Streaming::HeaderOnly); Streaming::ConstBuffer chunkHeader;// the first and last are different, but all the ones in the middle are duplicates. bool first = m_messageBytesSend == 0; while (begin < end) { const char *p = begin + CHUNK_SIZE; if (p > end) p = end; m_messageBytesSend += p - begin; Streaming::ConstBuffer bodyChunk(body.internal_buffer(), begin, p); begin = p; Streaming::ConstBuffer header; if (first || begin == end || !chunkHeader.isValid()) { m_sendHelperBuffer.reserve(20); headerBuilder.add(Network::ServiceId, message.serviceId()); if (message.messageId() >= 0) headerBuilder.add(Network::MessageId, message.messageId()); if (first) headerBuilder.add(Network::SequenceStart, body.size()); headerBuilder.add(Network::LastInSequence, (begin == end)); headerBuilder.add(Network::HeaderEnd, true); headerBuilder.setMessageSize(m_sendHelperBuffer.size() + bodyChunk.size()); header = headerBuilder.buffer(); if (!first) chunkHeader = header; first = false; } else { header = chunkHeader; } bytesLeft -= header.size(); socketQueue.push_back(header); m_sendQHeaders.push_back(header); socketQueue.push_back(bodyChunk); bytesLeft -= bodyChunk.size(); if (bytesLeft <= 0) break; } if (begin >= end) // done with message. m_messageBytesSend = 0; } else { if (!message.hasHeader()) { // build a simple header const Streaming::ConstBuffer constBuf = createHeader(message); bytesLeft -= constBuf.size(); socketQueue.push_back(constBuf); m_sendQHeaders.push_back(constBuf); } socketQueue.push_back(message.rawData()); bytesLeft -= message.rawData().size(); } } assert(m_messageBytesSend >= 0); async_write(m_socket, socketQueue, m_strand.wrap(std::bind(&NetworkManagerConnection::sentSomeBytes, this, std::placeholders::_1, std::placeholders::_2))); } void NetworkManagerConnection::sentSomeBytes(const boost::system::error_code& error, std::size_t bytes_transferred) { if (error.value() == boost::asio::error::connection_aborted) // assume instance already deleted return; assert(m_strand.running_in_this_thread()); m_sendingInProgress = false; if (error) { logWarning(Log::NWM) << "sent error" << error.message(); m_messageBytesSend = 0; m_messageBytesSent = 0; runOnStrand(std::bind(&NetworkManagerConnection::connect, this)); return; } logDebug(Log::NWM) << "Managed to send" << bytes_transferred << "bytes"; m_reconnectStep = 0; // now we remove any message data from our lists so the underlying malloced data can be freed // This is needed since boost asio unfortunately doesn't keep our ref-counted pointers. m_messageBytesSent += bytes_transferred; int bytesLeft = m_messageBytesSent; // We can have data spread over 3 lists, we eat at them in proper order. while (!m_messageQueue.empty() || !m_sentPriorityMessages.empty()) { const Message &message = m_sentPriorityMessages.empty() ? m_messageQueue.front() : m_sentPriorityMessages.front(); const int bodySize = message.rawData().size(); if (bodySize > CHUNK_SIZE) { const unsigned int chunks = std::ceil(bodySize / (float) CHUNK_SIZE); if (m_sendQHeaders.size() < chunks) break; std::list<Streaming::ConstBuffer>::iterator iter = m_sendQHeaders.begin(); for (unsigned int i = 0; i < chunks; ++i) { bytesLeft -= iter->size(); ++iter; } if (bytesLeft < bodySize) break; // still here? Then we remove the message and all the headers for (unsigned int i = 0; i < chunks; ++i) { m_sendQHeaders.erase(m_sendQHeaders.begin()); } } else if (!message.hasHeader()) { assert(!m_sendQHeaders.empty()); const int headerSize = m_sendQHeaders.front().size(); if (headerSize > bytesLeft) break; if (bodySize > bytesLeft - headerSize) break; bytesLeft -= headerSize; // bodysize is subtraced below m_sendQHeaders.erase(m_sendQHeaders.begin()); } else { if (bodySize > bytesLeft) break; } assert(bodySize <= bytesLeft); bytesLeft -= bodySize; if (m_sentPriorityMessages.empty()) m_messageQueue.erase(m_messageQueue.begin()); else m_sentPriorityMessages.erase(m_sentPriorityMessages.begin()); if (bytesLeft <= 0) break; } m_messageBytesSent = bytesLeft; runMessageQueue(); } void NetworkManagerConnection::receivedSomeBytes(const boost::system::error_code& error, std::size_t bytes_transferred) { if (error.value() == boost::asio::error::connection_aborted) // assume instance already deleted return; if (m_isClosingDown) return; assert(m_strand.running_in_this_thread()); logDebug(Log::NWM) << ((void*) this) << "receivedSomeBytes" << bytes_transferred; if (error) { logDebug(Log::NWM) << "receivedSomeBytes errored:" << error.message(); // first copy to avoid problems if a callback removes its callback or closes the connection. std::vector<std::function<void(const EndPoint&)> > callbacks; callbacks.reserve(m_onDisConnectedCallbacks.size()); for (auto it = m_onDisConnectedCallbacks.begin(); it != m_onDisConnectedCallbacks.end(); ++it) { callbacks.push_back(it->second); } for (auto callback : callbacks) { try { callback(m_remote); } catch (const std::exception &ex) { logWarning(Log::NWM) << "onDisconnected caused exception, ignoring:" << ex; } } close(); m_firstPacket = true; return; } m_receiveStream.markUsed(bytes_transferred); // move write pointer while (true) { // get all packets out const size_t blockSize = m_receiveStream.size(); if (blockSize < 4) // need more data break; Streaming::ConstBuffer data = m_receiveStream.createBufferSlice(m_receiveStream.begin(), m_receiveStream.end()); if (m_firstPacket) { m_firstPacket = false; if (data.begin()[2] != 8) { // Positive integer (0) and Network::ServiceId (1 << 3) logWarning(Log::NWM) << "receive; Data error from server - this is NOT an NWM server. Disconnecting"; close(); return; } } const unsigned int rawHeader = *(reinterpret_cast<const unsigned int*>(data.begin())); const int packetLength = (rawHeader & 0xFFFF); logDebug(Log::DebugLevel) << "Processing incoming packet. Size" << packetLength; if (packetLength > MAX_MESSAGE_SIZE) { logWarning(Log::NWM) << "receive; Data error from server- stream is corrupt"; close(); return; } if (data.size() < packetLength) // do we have all data for this one? break; if (!processPacket(m_receiveStream.internal_buffer(), data.begin())) return; m_receiveStream.forget(packetLength); } m_receiveStream.reserve(MAX_MESSAGE_SIZE); m_socket.async_receive(boost::asio::buffer(m_receiveStream.data(), m_receiveStream.capacity()), m_strand.wrap(std::bind(&NetworkManagerConnection::receivedSomeBytes, this, std::placeholders::_1, std::placeholders::_2))); } bool NetworkManagerConnection::processPacket(const std::shared_ptr<char> &buffer, const char *data) { assert(m_strand.running_in_this_thread()); const unsigned int rawHeader = *(reinterpret_cast<const unsigned int*>(data)); const int packetLength = (rawHeader & 0xFFFF); logDebug(Log::NWM) << "Receive packet length" << packetLength; Streaming::MessageParser parser(const_cast<char*>(data + 2), packetLength - 2); Streaming::ParsedType type = parser.next(); int headerSize = 0; int messageId = -1; int serviceId = -1; int lastInSequence = -1; int sequenceSize = -1; bool isPing = false; // TODO have a variable on the NetworkManger that indicates the maximum allowed combined message-size. bool inHeader = true; while (inHeader && type == Streaming::FoundTag) { switch (parser.tag()) { case Network::HeaderEnd: headerSize = parser.consumed(); inHeader = false; break; case Network::MessageId: if (!parser.isInt()) { close(); return false; } messageId = parser.intData(); break; case Network::ServiceId: if (!parser.isInt()) { close(); return false; } serviceId = parser.intData(); break; case Network::LastInSequence: if (!parser.isBool()) { close(); return false; } lastInSequence = parser.boolData() ? 1 : 0; break; case Network::SequenceStart: if (!parser.isInt()) { close(); return false; } sequenceSize = parser.intData(); break; case Network::Ping: isPing = true; break; } type = parser.next(); } if (serviceId == -1) { // an obligatory field logWarning(Log::NWM) << "peer sent message without serviceId"; close(); return false; } if (serviceId == Network::SystemServiceId) { // Handle System level messages if (isPing) { if (m_pingMessage.rawData().size() == 0) { Streaming::MessageBuilder builder(Streaming::HeaderOnly, 10); builder.add(Network::ServiceId, Network::SystemServiceId); builder.add(Network::Pong, true); builder.add(Network::HeaderEnd, true); m_pingMessage = builder.message(); } m_messageQueue.push_back(m_pingMessage); m_pingTimer.cancel(); runMessageQueue(); m_pingTimer.expires_from_now(boost::posix_time::seconds(120)); m_pingTimer.async_wait(m_strand.wrap(std::bind(&NetworkManagerConnection::pingTimeout, this, std::placeholders::_1))); } return true; } Message message; // we assume they are in sequence (which is Ok with TCP sockets), but we don't assume that // each packet is part of the sequence. if (lastInSequence != -1) { if (sequenceSize != -1) { if (m_chunkedMessageId != -1 || m_chunkedServiceId != -1) { // Didn't finish another. Thats illegal. logWarning(Log::NWM) << "peer sent sequenced message with wrong combination of headers"; close(); return false; } m_chunkedMessageId = messageId; m_chunkedServiceId = serviceId; m_chunkedMessageBuffer = Streaming::BufferPool(sequenceSize); } else if (m_chunkedMessageId != messageId || m_chunkedServiceId != serviceId) { // Changed. Thats illegal. close(); logWarning(Log::NWM) << "peer sent sequenced message with inconsistent service/messageId"; return false; } const int bodyLength = packetLength - headerSize - 2; if (m_chunkedMessageBuffer.capacity() < bodyLength) { logWarning(Log::NWM) << "peer sent sequenced message with too much data"; return false; } logDebug(Log::NWM) << "Message received as part of sequence; last:" << lastInSequence << "total-size:" << sequenceSize; std::copy(data + headerSize + 2, data + packetLength, m_chunkedMessageBuffer.data()); m_chunkedMessageBuffer.markUsed(bodyLength); if (lastInSequence == 0) return true; message = Message(m_chunkedMessageBuffer.commit(), m_chunkedServiceId); m_chunkedMessageId = -1; m_chunkedServiceId = -1; m_chunkedMessageBuffer.clear(); } else { message = Message(buffer, data + 2, data + 2 + headerSize, data + packetLength); } message.setMessageId(messageId); message.setServiceId(serviceId); message.remote = m_remote.connectionId; // first copy to avoid problems if a callback removes its callback or closes the connection. std::vector<std::function<void(const Message&)> > callbacks; callbacks.reserve(m_onIncomingMessageCallbacks.size()); for (auto it = m_onIncomingMessageCallbacks.begin(); it != m_onIncomingMessageCallbacks.end(); ++it) { callbacks.push_back(it->second); } for (auto callback : callbacks) { try { callback(message); } catch (const std::exception &ex) { logWarning(Log::NWM) << "onIncomingMessage threw exception, ignoring:" << ex; } if (!m_socket.is_open()) break; } return m_socket.is_open(); // if the user called disconnect, then stop processing packages } void NetworkManagerConnection::addOnConnectedCallback(int id, const std::function<void(const EndPoint&)> &callback) { assert(m_strand.running_in_this_thread()); m_onConnectedCallbacks.insert(std::make_pair(id, callback)); } void NetworkManagerConnection::addOnDisconnectedCallback(int id, const std::function<void(const EndPoint&)> &callback) { assert(m_strand.running_in_this_thread()); m_onDisConnectedCallbacks.insert(std::make_pair(id, callback)); } void NetworkManagerConnection::addOnIncomingMessageCallback(int id, const std::function<void(const Message&)> &callback) { assert(m_strand.running_in_this_thread()); m_onIncomingMessageCallbacks.insert(std::make_pair(id, callback)); } void NetworkManagerConnection::queueMessage(const Message &message, NetworkConnection::MessagePriority priority) { if (!message.hasHeader() && message.serviceId() == -1) { logWarning(Log::NWM) << "queueMessage: Can't deliver a message with unset service ID"; #ifdef DEBUG_CONNECTIONS assert(false); #endif return; } if (message.hasHeader() && message.body().size() > CHUNK_SIZE) { logWarning(Log::NWM) << "queueMessage: Can't send large message and can't auto-chunk because it already has a header"; #ifdef DEBUG_CONNECTIONS assert(false); #endif return; } if (priority == NetworkConnection::HighPriority && message.rawData().size() > CHUNK_SIZE) { logWarning(Log::NWM) << "queueMessage: Can't send large message in the priority queue"; #ifdef DEBUG_CONNECTIONS assert(false); #endif return; } if (m_strand.running_in_this_thread()) { if (priority == NetworkConnection::NormalPriority) m_messageQueue.push_back(message); else m_priorityMessageQueue.push_back(message); if (isConnected()) runMessageQueue(); else connect_priv(); } else { runOnStrand(std::bind(&NetworkManagerConnection::queueMessage, this, message, priority)); } } void NetworkManagerConnection::close(bool reconnect) { assert(m_strand.running_in_this_thread()); if (!isOutgoing()) { boost::recursive_mutex::scoped_lock lock(d->mutex); shutdown(d->connections.at(m_remote.connectionId)); d->connections.erase(m_remote.connectionId); return; } m_receiveStream.clear(); m_sendHelperBuffer.clear(); m_chunkedMessageBuffer.clear(); m_messageBytesSend = 0; m_messageBytesSent = 0; m_priorityMessageQueue.clear(); m_sentPriorityMessages.clear(); m_messageQueue.clear(); m_sendQHeaders.clear(); m_socket.close(); m_pingTimer.cancel(); if (reconnect && !m_isClosingDown) { // auto reconnect. if (m_firstPacket) { // this means the network is there, someone is listening. They just don't speak our language. // slow down reconnect due to bad peer. m_reconnectDelay.expires_from_now(boost::posix_time::seconds(15)); m_reconnectDelay.async_wait(m_strand.wrap(std::bind(&NetworkManagerConnection::reconnectWithCheck, this, std::placeholders::_1))); } else { connect_priv(); } } } void NetworkManagerConnection::sendPing(const boost::system::error_code& error) { if (error) return; logDebug(Log::NWM) << "ping"; if (m_isClosingDown) return; assert(m_strand.running_in_this_thread()); if (!m_socket.is_open()) return; if (m_pingMessage.rawData().size() == 0) { Streaming::MessageBuilder builder(Streaming::HeaderOnly, 10); builder.add(Network::ServiceId, Network::SystemServiceId); builder.add(Network::Ping, true); builder.add(Network::HeaderEnd, true); m_pingMessage = builder.message(); } m_messageQueue.push_back(m_pingMessage); runMessageQueue(); m_pingTimer.expires_from_now(boost::posix_time::seconds(90)); m_pingTimer.async_wait(m_strand.wrap(std::bind(&NetworkManagerConnection::sendPing, this, std::placeholders::_1))); } void NetworkManagerConnection::pingTimeout(const boost::system::error_code &error) { if (!error) { logWarning(Log::NWM) << "Didn't receive a ping from peer for too long, disconnecting dead connection"; close(false); } } void NetworkManagerConnection::reconnectWithCheck(const boost::system::error_code& error) { if (!error) { m_socket.close(); connect_priv(); } } int NetworkManagerConnection::nextCallbackId() { return m_lastCallbackId.fetch_add(1); } void NetworkManagerConnection::removeAllCallbacksFor(int id) { assert(m_strand.running_in_this_thread()); m_onConnectedCallbacks.erase(id); m_onDisConnectedCallbacks.erase(id); m_onIncomingMessageCallbacks.erase(id); } void NetworkManagerConnection::shutdown(std::shared_ptr<NetworkManagerConnection> me) { m_isClosingDown = true; if (m_strand.running_in_this_thread()) { m_onConnectedCallbacks.clear(); m_onDisConnectedCallbacks.clear(); m_onIncomingMessageCallbacks.clear(); if (isConnected()) m_socket.close(); m_resolver.cancel(); m_reconnectDelay.cancel(); m_strand.post(std::bind(&NetworkManagerConnection::finalShutdown, this, me)); } else { m_strand.post(std::bind(&NetworkManagerConnection::shutdown, this, me)); } } void NetworkManagerConnection::accept() { if (m_acceptedConnection) return; m_acceptedConnection = true; // setup a callback for receiving. m_socket.async_receive(boost::asio::buffer(m_receiveStream.data(), m_receiveStream.capacity()), m_strand.wrap(std::bind(&NetworkManagerConnection::receivedSomeBytes, this, std::placeholders::_1, std::placeholders::_2))); } void NetworkManagerConnection::runOnStrand(const std::function<void()> &function) { if (m_isClosingDown) return; m_strand.post(function); } void NetworkManagerConnection::punish(int amount) { d->punishNode(m_remote.connectionId, amount); } void NetworkManagerConnection::finalShutdown(std::shared_ptr<NetworkManagerConnection>) { } NetworkManagerServer::NetworkManagerServer(const std::shared_ptr<NetworkManagerPrivate> &parent, tcp::endpoint endpoint, const std::function<void(NetworkConnection&)> &callback) : d(parent), m_acceptor(parent->ioService, endpoint), m_socket(parent->ioService), onIncomingConnection(callback) { setupCallback(); } void NetworkManagerServer::shutdown() { m_socket.close(); } void NetworkManagerServer::setupCallback() { m_acceptor.async_accept(m_socket, std::bind(&NetworkManagerServer::acceptConnection, this, std::placeholders::_1)); } void NetworkManagerServer::acceptConnection(boost::system::error_code error) { if (error.value() == boost::asio::error::operation_aborted) return; logDebug(Log::NWM) << "acceptTcpConnection" << error.message(); if (error) { setupCallback(); return; } std::shared_ptr<NetworkManagerPrivate> priv = d.lock(); if (!priv.get()) return; boost::recursive_mutex::scoped_lock lock(priv->mutex); if (priv->isClosingDown) return; const boost::asio::ip::address peerAddress = m_socket.remote_endpoint().address(); for (const BannedNode &bn : priv->banned) { if (bn.endPoint.ipAddress == peerAddress) { if (bn.banTimeout > boost::posix_time::second_clock::universal_time()) { // incoming connection is banned. logDebug(Log::NWM) << "acceptTcpConnection; closing incoming connection (banned)" << bn.endPoint.hostname; m_socket.close(); } setupCallback(); return; } } const int conId = ++priv->lastConnectionId; logDebug(Log::NWM) << "acceptTcpConnection; creating new connection object" << conId; std::shared_ptr<NetworkManagerConnection> connection = std::make_shared<NetworkManagerConnection>(priv, std::move(m_socket), conId); priv->connections.insert(std::make_pair(conId, connection)); logDebug(Log::NWM) << "Total connections now;" << priv->connections.size(); setupCallback(); // only after we std::move socket, to avoid an "Already open" error NetworkConnection con(connection, conId); onIncomingConnection(con); }
37.946573
177
0.645113
[ "object", "vector" ]
a7f44191e8a1e62fbd4bbdddf16b2918b3b41a62
2,106
cpp
C++
src/chapters/chapter5_5.cpp
teemid/opengl_superbible7
120ab46133dab26c25419f6b64494e152a05e779
[ "MIT" ]
1
2017-05-19T03:52:29.000Z
2017-05-19T03:52:29.000Z
src/chapters/chapter5_5.cpp
teemid/opengl_superbible7
120ab46133dab26c25419f6b64494e152a05e779
[ "MIT" ]
null
null
null
src/chapters/chapter5_5.cpp
teemid/opengl_superbible7
120ab46133dab26c25419f6b64494e152a05e779
[ "MIT" ]
null
null
null
#include <cmath> #include <cstring> #include "chapters.h" #include "vmath.h" using namespace GLFramework; static GLchar * vertex_source = SHADER(450 core, layout (location = 0) in vec4 position; layout (location = 1) in vec4 color; out vec4 vs_color; void main (void) { gl_Position = position; vs_color = color; } ); static GLchar * fragment_source = SHADER(450 core, in vec4 vs_color; out vec4 color; void main (void) { color = vs_color; } ); static GLuint program; static GLuint vao; static GLuint buffer; struct vertex { float x; float y; float z; float r; float g; float b; }; static const float vertices[] = { 0.25, -0.25, 0.5, 1.0, 0.0, 0.0, -0.25, -0.25, 0.5, 0.0, 1.0, 0.0, 0.25, 0.25, 0.5, 0.0, 0.0, 1.0 }; void Chapter5_5::Init (void) { GLuint vertex_shader = CompileShader(GL_VERTEX_SHADER, vertex_source); GLuint fragment_shader = CompileShader(GL_FRAGMENT_SHADER, fragment_source); program = CreateProgram(2, vertex_shader, fragment_shader); glCreateVertexArrays(1, &vao); glBindVertexArray(vao); glCreateBuffers(1, &buffer); glNamedBufferStorage(buffer, sizeof(vertices), vertices, 0); glVertexArrayAttribBinding(vao, 0, 0); glVertexArrayAttribFormat(vao, 0, 3, GL_FLOAT, GL_FALSE, 0); glEnableVertexArrayAttrib(vao, 0); glVertexArrayAttribBinding(vao, 1, 0); glVertexArrayAttribFormat(vao, 1, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 3); glEnableVertexArrayAttrib(vao, 1); glVertexArrayVertexBuffer(vao, 0, buffer, 0, sizeof(vertex)); } void Chapter5_5::Render (double currentTime) { static const GLfloat color[] = { 0.0f, 0.0f, 0.0f, 1.0f }; glClearBufferfv(GL_COLOR, 0, color); glUseProgram(program); glDrawArrays(GL_TRIANGLES, 0, 3); } void Chapter5_5::Shutdown (void) { glDisableVertexArrayAttrib(vao, 0); glDisableVertexArrayAttrib(vao, 1); glDeleteVertexArrays(1, &vao); glDeleteProgram(program); glDeleteVertexArrays(1, &vao); }
19.867925
91
0.654321
[ "render" ]
a7f4aa19da5c9139bb1ae2829956a69c0ec3769e
9,575
cc
C++
runtime/isolate_configuration.cc
ModProg/engine
93cb5dbbc70092b5c675ebf53fde7dea39086382
[ "BSD-3-Clause" ]
13
2020-08-09T10:30:50.000Z
2021-09-06T18:26:05.000Z
runtime/isolate_configuration.cc
christopherfujino/engine
14c3686153b1af6d8766aebd20a3c1b0d795ac77
[ "BSD-3-Clause" ]
1
2020-08-04T09:00:33.000Z
2020-08-04T09:00:33.000Z
runtime/isolate_configuration.cc
christopherfujino/engine
14c3686153b1af6d8766aebd20a3c1b0d795ac77
[ "BSD-3-Clause" ]
9
2021-03-11T04:52:17.000Z
2021-12-17T09:19:06.000Z
// Copyright 2013 The Flutter 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 "flutter/runtime/isolate_configuration.h" #include "flutter/fml/make_copyable.h" #include "flutter/runtime/dart_vm.h" namespace flutter { IsolateConfiguration::IsolateConfiguration() = default; IsolateConfiguration::~IsolateConfiguration() = default; bool IsolateConfiguration::PrepareIsolate(DartIsolate& isolate) { if (isolate.GetPhase() != DartIsolate::Phase::LibrariesSetup) { FML_DLOG(ERROR) << "Isolate was in incorrect phase to be prepared for running."; return false; } return DoPrepareIsolate(isolate); } class AppSnapshotIsolateConfiguration final : public IsolateConfiguration { public: AppSnapshotIsolateConfiguration() = default; // |IsolateConfiguration| bool DoPrepareIsolate(DartIsolate& isolate) override { return isolate.PrepareForRunningFromPrecompiledCode(); } // |IsolateConfiguration| bool IsNullSafetyEnabled(const DartSnapshot& snapshot) override { return snapshot.IsNullSafetyEnabled(nullptr); } private: FML_DISALLOW_COPY_AND_ASSIGN(AppSnapshotIsolateConfiguration); }; class KernelIsolateConfiguration : public IsolateConfiguration { public: KernelIsolateConfiguration(std::unique_ptr<const fml::Mapping> kernel) : kernel_(std::move(kernel)) {} // |IsolateConfiguration| bool DoPrepareIsolate(DartIsolate& isolate) override { if (DartVM::IsRunningPrecompiledCode()) { return false; } return isolate.PrepareForRunningFromKernel(std::move(kernel_)); } // |IsolateConfiguration| bool IsNullSafetyEnabled(const DartSnapshot& snapshot) override { return snapshot.IsNullSafetyEnabled(kernel_.get()); } private: std::unique_ptr<const fml::Mapping> kernel_; FML_DISALLOW_COPY_AND_ASSIGN(KernelIsolateConfiguration); }; class KernelListIsolateConfiguration final : public IsolateConfiguration { public: KernelListIsolateConfiguration( std::vector<std::future<std::unique_ptr<const fml::Mapping>>> kernel_pieces) : kernel_piece_futures_(std::move(kernel_pieces)) { if (kernel_piece_futures_.empty()) { FML_LOG(ERROR) << "Attempted to create kernel list configuration without " "any kernel blobs."; } } // |IsolateConfiguration| bool DoPrepareIsolate(DartIsolate& isolate) override { if (DartVM::IsRunningPrecompiledCode()) { return false; } ResolveKernelPiecesIfNecessary(); if (resolved_kernel_pieces_.empty()) { FML_DLOG(ERROR) << "No kernel pieces provided to prepare this isolate."; return false; } for (size_t i = 0; i < resolved_kernel_pieces_.size(); i++) { if (!resolved_kernel_pieces_[i]) { FML_DLOG(ERROR) << "This kernel list isolate configuration was already " "used to prepare an isolate."; return false; } const bool last_piece = i + 1 == resolved_kernel_pieces_.size(); if (!isolate.PrepareForRunningFromKernel( std::move(resolved_kernel_pieces_[i]), last_piece)) { return false; } } return true; } // |IsolateConfiguration| bool IsNullSafetyEnabled(const DartSnapshot& snapshot) override { ResolveKernelPiecesIfNecessary(); const auto kernel = resolved_kernel_pieces_.empty() ? nullptr : resolved_kernel_pieces_.front().get(); return snapshot.IsNullSafetyEnabled(kernel); } // This must be call as late as possible before accessing any of the kernel // pieces. This will delay blocking on the futures for as long as possible. So // far, only Fuchsia depends on this optimization and only on the non-AOT // configs. void ResolveKernelPiecesIfNecessary() { if (resolved_kernel_pieces_.size() == kernel_piece_futures_.size()) { return; } resolved_kernel_pieces_.clear(); for (auto& piece : kernel_piece_futures_) { // The get() call will xfer the unique pointer out and leave an empty // future in the original vector. resolved_kernel_pieces_.emplace_back(piece.get()); } } private: std::vector<std::future<std::unique_ptr<const fml::Mapping>>> kernel_piece_futures_; std::vector<std::unique_ptr<const fml::Mapping>> resolved_kernel_pieces_; FML_DISALLOW_COPY_AND_ASSIGN(KernelListIsolateConfiguration); }; static std::vector<std::string> ParseKernelListPaths( std::unique_ptr<fml::Mapping> kernel_list) { FML_DCHECK(kernel_list); std::vector<std::string> kernel_pieces_paths; const char* kernel_list_str = reinterpret_cast<const char*>(kernel_list->GetMapping()); size_t kernel_list_size = kernel_list->GetSize(); size_t piece_path_start = 0; while (piece_path_start < kernel_list_size) { size_t piece_path_end = piece_path_start; while ((piece_path_end < kernel_list_size) && (kernel_list_str[piece_path_end] != '\n')) { piece_path_end++; } std::string piece_path(&kernel_list_str[piece_path_start], piece_path_end - piece_path_start); kernel_pieces_paths.emplace_back(std::move(piece_path)); piece_path_start = piece_path_end + 1; } return kernel_pieces_paths; } static std::vector<std::future<std::unique_ptr<const fml::Mapping>>> PrepareKernelMappings(std::vector<std::string> kernel_pieces_paths, std::shared_ptr<AssetManager> asset_manager, fml::RefPtr<fml::TaskRunner> io_worker) { FML_DCHECK(asset_manager); std::vector<std::future<std::unique_ptr<const fml::Mapping>>> fetch_futures; for (const auto& kernel_pieces_path : kernel_pieces_paths) { std::promise<std::unique_ptr<const fml::Mapping>> fetch_promise; fetch_futures.push_back(fetch_promise.get_future()); auto fetch_task = fml::MakeCopyable([asset_manager, kernel_pieces_path, fetch_promise = std::move(fetch_promise)]() mutable { fetch_promise.set_value( asset_manager->GetAsMapping(kernel_pieces_path)); }); // Fulfill the promise on the worker if one is available or the current // thread if one is not. if (io_worker) { io_worker->PostTask(fetch_task); } else { fetch_task(); } } return fetch_futures; } std::unique_ptr<IsolateConfiguration> IsolateConfiguration::InferFromSettings( const Settings& settings, std::shared_ptr<AssetManager> asset_manager, fml::RefPtr<fml::TaskRunner> io_worker) { // Running in AOT mode. if (DartVM::IsRunningPrecompiledCode()) { return CreateForAppSnapshot(); } if (settings.application_kernels) { return CreateForKernelList(settings.application_kernels()); } if (settings.application_kernel_asset.empty() && settings.application_kernel_list_asset.empty()) { FML_DLOG(ERROR) << "application_kernel_asset or " "application_kernel_list_asset must be set"; return nullptr; } if (!asset_manager) { FML_DLOG(ERROR) << "No asset manager specified when attempting to create " "isolate configuration."; return nullptr; } // Running from kernel snapshot. Requires asset manager. { std::unique_ptr<fml::Mapping> kernel = asset_manager->GetAsMapping(settings.application_kernel_asset); if (kernel) { return CreateForKernel(std::move(kernel)); } } // Running from kernel divided into several pieces (for sharing). Requires // asset manager and io worker. if (!io_worker) { FML_DLOG(ERROR) << "No IO worker specified to load kernel pieces."; return nullptr; } { std::unique_ptr<fml::Mapping> kernel_list = asset_manager->GetAsMapping(settings.application_kernel_list_asset); if (!kernel_list) { FML_LOG(ERROR) << "Failed to load: " << settings.application_kernel_list_asset; return nullptr; } auto kernel_pieces_paths = ParseKernelListPaths(std::move(kernel_list)); auto kernel_mappings = PrepareKernelMappings(std::move(kernel_pieces_paths), asset_manager, io_worker); return CreateForKernelList(std::move(kernel_mappings)); } return nullptr; } std::unique_ptr<IsolateConfiguration> IsolateConfiguration::CreateForAppSnapshot() { return std::make_unique<AppSnapshotIsolateConfiguration>(); } std::unique_ptr<IsolateConfiguration> IsolateConfiguration::CreateForKernel( std::unique_ptr<const fml::Mapping> kernel) { return std::make_unique<KernelIsolateConfiguration>(std::move(kernel)); } std::unique_ptr<IsolateConfiguration> IsolateConfiguration::CreateForKernelList( std::vector<std::unique_ptr<const fml::Mapping>> kernel_pieces) { std::vector<std::future<std::unique_ptr<const fml::Mapping>>> pieces; for (auto& piece : kernel_pieces) { if (!piece) { FML_DLOG(ERROR) << "Invalid kernel piece."; continue; } std::promise<std::unique_ptr<const fml::Mapping>> promise; pieces.push_back(promise.get_future()); promise.set_value(std::move(piece)); } return CreateForKernelList(std::move(pieces)); } std::unique_ptr<IsolateConfiguration> IsolateConfiguration::CreateForKernelList( std::vector<std::future<std::unique_ptr<const fml::Mapping>>> kernel_pieces) { return std::make_unique<KernelListIsolateConfiguration>( std::move(kernel_pieces)); } } // namespace flutter
32.90378
80
0.700574
[ "vector" ]
a7f620d5b9e486cf2aa67e59938426ac78f3a143
23,574
cpp
C++
strings.cpp
Benjins/CppUtils
22661dd7b0696b6bd55a3979b1692f1fd5b33d18
[ "MIT" ]
null
null
null
strings.cpp
Benjins/CppUtils
22661dd7b0696b6bd55a3979b1692f1fd5b33d18
[ "MIT" ]
null
null
null
strings.cpp
Benjins/CppUtils
22661dd7b0696b6bd55a3979b1692f1fd5b33d18
[ "MIT" ]
null
null
null
#include "strings.h" #include <stdio.h> int FindChar(const char* str, char c) { const char* cursor = str; while (*cursor) { if (*cursor == c) { return (int)(cursor - str); } cursor++; } return -1; } void String::SetSize(int size){ Release(); if (size > 0) { void* alloc = malloc(8 + size + 1); string = ((char*)alloc) + 8; string[0] = '\0'; int* ref = (int*)alloc; int* length = (int*)(string - 4); *ref = 1; *length = size; } else { string = nullptr; } } // FML. // cppcheck-suppress unmatchedSuppression // cppcheck-suppress uninitMemberVar // cppcheck-suppress uninitVar String::String(const SubString& substr) : String(substr.start, substr.length) { } int String::GetRef() const{ if(string == nullptr){ return 0; } return *(int*)(string - 8); } int String::GetLength() const{ if(string == nullptr){ return 0; } return *(int*)(string - 4); } SubString String::GetSubString(int index, int length) const{ ASSERT(string != nullptr); ASSERT(GetLength() >= index + length); SubString substr; substr.start = &string[index]; substr.ref = (int*)(string - 8); substr.length = length; substr.Retain(); return substr; } void String::Retain(){ (*(int*)(string - 8))++; } void String::Release(){ if (string != nullptr){ int* ref = (int*)(string - 8); ASSERT(*ref > 0); (*ref)--; if(*ref == 0){ free(ref); string = nullptr; } } } void SubString::Retain(){ (*ref)++; } void SubString::Release(){ if (ref){ ASSERT(start != nullptr); ASSERT(*ref > 0); (*ref)--; if(*ref == 0){ free(ref); ref = nullptr; start = nullptr; length = 0; } } } int StrLen(const char* str){ int len = 0; while(str != nullptr && *str != '\0'){ str++; len++; } return len; } char* StrDup(const char* str){ int strLen = StrLen(str); char* newStr = (char*)malloc(strLen + 1); MemCpy(newStr, str, strLen); newStr[strLen] = '\0'; return newStr; } bool StrEqual(const char* s1, const char* s2){ if(s1 == s2){ return true; } if(s1 == nullptr || s2 == nullptr){ return false; } while(*s1 == *s2 && *s1 != '\0' && *s2 != '\0'){ s1++; s2++; } return (*s1 == '\0') && (*s2 == '\0'); } bool StrEqualN(const char* s1, const char* s2, unsigned int len){ if(s1 == s2 || len == 0){ return true; } if(s1 == nullptr || s2 == nullptr){ return false; } unsigned int counter = 0; while(counter < len && *s1 == *s2 && *s1 != '\0' && *s2 != '\0'){ s1++; s2++; counter++; } return counter == len || *s1 == *s2; } void MemCpy(void* dest, const void* src, int bytes){ char* bDest = (char*)dest; char* bSrc = (char*)src; for(int i = 0; i < bytes; i++){ bDest[i] = bSrc[i]; } } void MemSet(void* dst, int val, int bytes){ unsigned char* bDst = (unsigned char*)dst; for (int i = 0; i < bytes; i++){ bDst[i] = (unsigned char)val; } } int Atoi(const char* str){ ASSERT(str != nullptr); int val = 0; int sign = 1; if (*str == '-') { sign = -1; str++; } while(*str >= '0' && *str <= '9'){ val = (val * 10) + (*str - '0'); str++; } return val*sign; } unsigned int HexAtoi(const char* str) { ASSERT(str != nullptr); if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X')) { str += 2; } unsigned int val = 0; while (true) { unsigned int digit = 0; if (*str >= '0' && *str <= '9') { digit = *str - '0'; } else if (*str >= 'a' && *str <= 'f') { digit = 10 + (*str - 'a'); } else if (*str >= 'A' && *str <= 'F') { digit = 10 + (*str - 'A'); } else { break; } val = (val * 16) + digit; str++; } return val; } float Atof(const char* str) { ASSERT(str != nullptr); float val = 0; float sign = 1; if (*str == '-') { sign = -1; str++; } while (*str >= '0' && *str <= '9') { val = (val * 10) + (*str - '0'); str++; } if (*str != '.') { return val*sign; } else { str++; } float decVal = 0.0f; float mult = 0.1f; while (*str >= '0' && *str <= '9') { decVal = decVal + (*str - '0') * mult; mult /= 10.0f; str++; } int exponent = 0; if (*str == 'e') { exponent = Atoi(str + 1); } if (exponent == 0) { return sign * (val + decVal); } else { float total = sign * (val + decVal); for (int i = 0; i < BNS_ABS(exponent); i++) { total = (exponent < 0 ? total / 10 : total * 10); } return total; } } int StrFind(const char* haystack, const char* needle) { if (!needle || !haystack) { return -1; } const char* originalHaystack = haystack; while (*haystack) { const char* hCursor = haystack; const char* nCursor = needle; while (*nCursor && *hCursor && *nCursor == *hCursor) { nCursor++; hCursor++; } if (!*nCursor) { return (int)(haystack - originalHaystack); } haystack++; } return -1; } inline bool CompareString(const String& a, const String& b){ int length = a.GetLength(); return (b.GetLength() == length) && StrEqualN(a.string, b.string, length); } inline bool CompareString(const String& a, const SubString& b){ int length = a.GetLength(); return (b.length == length) && StrEqualN(a.string, b.start, length); } inline bool CompareString(const SubString& a, const SubString& b){ return (a.length == b.length) && StrEqualN(a.start, b.start, a.length); } SubString& SubString::operator=(const SubString& other){ if (other.ref != ref){ Release(); start = other.start; length = other.length; ref = other.ref; Retain(); } else if (other.start != start || other.length != length){ start = other.start; length = other.length; } return *this; } bool SubString::operator==(const SubString& other) const{ return CompareString(*this, other); } bool SubString::operator!=(const SubString& other) const{ return !CompareString(*this, other); } String& String::operator=(const String& other){ if (string != other.string) { Release(); string = other.string; if (string != nullptr) { Retain(); } } return *this; } bool String::operator==(const String& other) const{ return CompareString(*this, other); } bool String::operator!=(const String& other) const{ return !CompareString(*this, other); } bool String::operator==(const SubString& other) const{ return CompareString(*this, other); } bool String::operator!=(const SubString& other) const{ return !CompareString(*this, other); } bool String::operator==(const char* other) const{ if (string == nullptr && (other == nullptr || *other == '\0')) { return true; } int length = GetLength(); return StrEqualN(string, other, length) && StrLen(other) == length; } bool String::operator!=(const char* other) const{ if (string == nullptr && (other == nullptr || *other == '\0')) { return false; } int length = GetLength(); return !StrEqualN(string, other, length) || StrLen(other) != length; } String String::Insert(const char* str, int index) const { int len = GetLength(); ASSERT(index >= 0 && index <= len); int strLen = StrLen(str); String ret; ret.SetSize(len + strLen); MemCpy(ret.string, string, index); MemCpy(ret.string + index, str, strLen); MemCpy(ret.string + index + strLen, string + index, len - index); ret.string[len + strLen] = '\0'; return ret; } String String::Insert(char c, int index) const { char fakeStr[2] = { c, '\0' }; return Insert(fakeStr, index); } String String::Remove(int index) const { String ret; int len = GetLength(); ASSERT(index >= 0 && index < len); ret.SetSize(len - 1); MemCpy(ret.string, string, index); MemCpy(ret.string + index, string + index + 1, len - index - 1); if (len > 1) { ret.string[len - 1] = '\0'; } return ret; } String ReadStringFromFile(const char* fileName) { String str; FILE* fIn = fopen(fileName, "rb"); if (fIn != NULL) { fseek(fIn, 0, SEEK_END); int fileLength = ftell(fIn); fseek(fIn, 0, SEEK_SET); str.SetSize(fileLength); int bytesRead = (int)fread(str.string, 1, fileLength, fIn); ASSERT(bytesRead == fileLength); str.string[fileLength] = '\0'; fclose(fIn); } else { // TODO: Warn } return str; } void WriteStringToFile(const String& str, const char* fileName) { FILE* fOut = fopen(fileName, "wb"); if (fOut != NULL) { if (str != "") { fwrite(str.string, 1, str.GetLength(), fOut); } fclose(fOut); } else { // TODO: Warn } } bool SubString::operator==(const String& other) const{ return CompareString(other, *this); } bool SubString::operator!=(const String& other) const{ return !CompareString(other, *this); } bool SubString::operator==(const char* other) const{ return StrEqualN(start, other, length) && other[length] == '\0'; } bool SubString::operator!=(const char* other) const{ return !(*this == other); } void SplitStringIntoParts(const String& str, const char* sep, Vector<SubString>* parts, bool removeEmpties /*= false*/) { int sepLen = StrLen(sep); // TODO: We could overload this to mean explode, but for now let's just avoid it. ASSERT(sepLen > 0); int strLen = str.GetLength(); if (strLen == 0) { return; } const char* cursor = str.string; while (true) { int len = StrFind(cursor, sep); if (len == -1) { if (!removeEmpties || *cursor) { parts->PushBack(str.GetSubString((int)(cursor - str.string), strLen - (int)(cursor - str.string))); } break; } else { if (len > 0 || !removeEmpties) { parts->PushBack(str.GetSubString((int)(cursor - str.string), len)); } cursor = cursor + len + sepLen; } } } #if defined(STRINGS_TEST_MAIN) CREATE_TEST_CASE("Strings basic") { ASSERT(StrLen("") == 0); ASSERT(StrLen("abc") == 3); ASSERT(StrLen("abc GGG") == 8); ASSERT(StrEqual("", "")); ASSERT(StrEqualN("A", "F", 0)); ASSERT(StrEqualN(nullptr, nullptr, 4)); ASSERT(StrEqual(nullptr, nullptr)); ASSERT(StrEqual("abccc", "abccc")); ASSERT(!StrEqual("abccc", "abccca")); ASSERT(StrEqualN("abccc", "abccca", 5)); ASSERT(StrEqualN("abcccA", "abccca", 5)); ASSERT(!StrEqualN("abccc", "abccca", 6)); ASSERT(!StrEqual("abc", "ABC")); ASSERT(StrFind("abs", "abs") == 0); ASSERT(StrFind("ababababababs", "abs") == 10); ASSERT(StrFind("abSSS", "abs") == -1); ASSERT(StrFind("abbb", "abbyyyaaabbnbbbbn") == -1); ASSERT(StrFind("J121241381835", "818") == 8); ASSERT(StrFind("J121241381835", nullptr) == -1); ASSERT(StrFind(nullptr, "J121241381835") == -1); ASSERT(StrFind(nullptr, nullptr) == -1); ASSERT(StrFind("ABCDABCD", "ABC") == 0); ASSERT(StrFind("ABHHHHHHHABABABAHBAHBAHAB", "ABB") == -1); #define CHECK_NUM(num) ASSERT(Atoi(#num) == num) CHECK_NUM(00); CHECK_NUM(10); CHECK_NUM(1); CHECK_NUM(12); CHECK_NUM(1442); CHECK_NUM(1662); CHECK_NUM(1812); CHECK_NUM(0); CHECK_NUM(7); CHECK_NUM(343247); CHECK_NUM(99999); CHECK_NUM(900000); CHECK_NUM(100); CHECK_NUM(1003200); #undef CHECK_NUM #define CHECK_HEX_NUM(num) ASSERT(HexAtoi(#num) == num) CHECK_HEX_NUM(0x0); CHECK_HEX_NUM(0); CHECK_HEX_NUM(0x11); CHECK_HEX_NUM(0x01); CHECK_HEX_NUM(0x21); CHECK_HEX_NUM(0x21); CHECK_HEX_NUM(0x81); CHECK_HEX_NUM(0xA1); CHECK_HEX_NUM(0xFFF1); CHECK_HEX_NUM(0x0F00); CHECK_HEX_NUM(0x0F001); CHECK_HEX_NUM(0X0F001); CHECK_HEX_NUM(0X0f001); CHECK_HEX_NUM(0X0fbdeE01); #undef CHECK_HEX_NUM ASSERT(Atoi("0123") == 123); ASSERT(Atoi("0123000") == 123000); ASSERT(Atof("1.0") == 1.0f); ASSERT(Atof("1.4") == 1.4f); ASSERT(Atof("12.4") == 12.4f); ASSERT(Atof("0.4") == 0.4f); ASSERT(Atof(".4") == 0.4f); ASSERT(Atof("43.4") == 43.4f); ASSERT(Atof("43.4556") == 43.4556f); ASSERT(Atof("43.0056") == 43.0056f); ASSERT(Atof("4.5e2") == 450); ASSERT(Atof("5.0e-1") == 0.5f); char stkConst1[] = "!@#$%^"; char stkConst2[] = "!@#$%^"; ASSERT(StrEqual(stkConst1, stkConst2)); { StringStackBuffer<256> buf("%s", "ABCEDRF"); ASSERT(StrEqual(buf.buffer, "ABCEDRF")); } { StringStackBuffer<256> buf("%s++%d", "ABCEDRF", 13); ASSERT(StrEqual(buf.buffer, "ABCEDRF++13")); } { StringStackBuffer<256> buf1("%s__123", "ABC"); StringStackBuffer<256> buf2("ABC__%d", 123); StringStackBuffer<256> buf3("ABC__%d", 321); StringStackBuffer<64> buf4("ABC__%d", 123); ASSERT(buf1 == buf1); ASSERT(buf2 == buf2); ASSERT(buf3 == buf3); ASSERT(buf4 == buf4); ASSERT(!(buf1 != buf1)); ASSERT(!(buf2 != buf2)); ASSERT(!(buf3 != buf3)); ASSERT(!(buf4 != buf4)); ASSERT(buf1 == buf2); ASSERT(!(buf1 != buf2)); ASSERT(buf2 != buf3); ASSERT(buf1 == buf4); ASSERT(buf2 == buf4); } { StringStackBuffer<256> buf1("%s__123", "ABC"); StringStackBuffer<256> buf2("%s", "ABC"); StringStackBuffer<256> buf3("%s", "ABC"); buf2.Append("__123"); buf3.AppendFormat("__%d", 123); ASSERT(buf1 == buf2); ASSERT(buf1 == buf3); ASSERT(buf2 == buf3); } { char str1B[] = "ABCDEFGHIJ"; String str1 = str1B; str1B[0] = 'Z'; ASSERT(str1.GetLength() == 10); ASSERT(str1.GetRef() == 1); ASSERT(str1.string[0] == 'A'); } { char str1B[] = "ABCDEFGHIJ"; String str1 = str1B; str1 = str1; str1 = str1; } { char str1B[] = "ABCDEFGHIJ"; String str1 = str1B; String str2 = str1B; ASSERT(str1 == str1); ASSERT(!(str1 != str1)); ASSERT(!(str1 != str1B)); ASSERT(str1 == str1B); ASSERT(str1 == str2); ASSERT(str2 == str1B); str1B[0] = '#'; ASSERT(str1 != str1B); ASSERT(str2 != str1B); ASSERT(str1 == str2); } { char str1B[] = "ABCDEFGHIJ"; String str1 = str1B; String str2 = str1B; String str3 = str1; str2 = str1; str1 = str2; str3 = str2; } { char str1B[] = "ABCDEFGHIJ"; String str1 = str1B; char str2B[] = "UWENNQW"; String str2 = str2B; ASSERT(str1 != str2); String str3 = str1; String str4 = str2; ASSERT(str1 == str3); ASSERT(str2 == str4); ASSERT(str3 != str4); { String temp = str3; str3 = str4; str4 = temp; } ASSERT(str1 == str4); ASSERT(str2 == str3); ASSERT(str3 != str4); } { String str = "c"; ASSERT(str != "clea"); } { String str = "cle"; ASSERT(str != "clea"); } { String str = "c"; ASSERT((str == "clea") == false); } { String str = "cle"; ASSERT((str == "clea") == false); } { char str1B[] = "ABCDEFGHIJ"; String str1 = str1B; char str2B[] = "@#$ABCDE"; String str2 = str2B; SubString sub1 = str1.GetSubString(1, 3); SubString sub2 = str2.GetSubString(4, 3); ASSERT(sub1 == sub2); String str3 = "BCD"; String str4 = str3; String str5 = "bde"; ASSERT(sub1 == str3); ASSERT(sub1 == str4); ASSERT(sub1 != str5); ASSERT(str3 == sub1); ASSERT(str4 == sub1); ASSERT(str5 != sub1); ASSERT(sub2 == str3); ASSERT(sub2 == str4); ASSERT(sub2 != str5); } { char strVal[] = "SGJLSRJ"; SubString substr; { String str1 = strVal; substr = str1.GetSubString(4, 2); ASSERT(substr == "SR"); } ASSERT(substr == "SR"); ASSERT(substr.GetRef() == 1); } { String str1 = "THE ONLY"; for (int i = 0; i < str1.GetLength(); i++) { SubString substr = str1.GetSubString(i, 0); ASSERT(substr == ""); } } { char str1B[] = "ABCDEFGHIJ"; String str1 = str1B; String str2 = str1; str1B[0] = 'Z'; ASSERT(str1.GetLength() == 10); ASSERT(str1.GetRef() == 2); ASSERT(str1.string[0] == 'A'); ASSERT(str2.GetLength() == 10); ASSERT(str2.GetRef() == 2); ASSERT(str2.string[0] == 'A'); str2.string[2] = 'M'; ASSERT(str1.string[2] == 'M'); } { char str1B[] = "ABCDEFGHIJ"; String str1 = str1B; str1.SetSize(20); str1.SetSize(20); String str2 = str1; str1.SetSize(20); str2.SetSize(20); str1.Release(); } { char str1B[] = "ABCDEFGHIJ"; String str1 = str1B; SubString substr1 = str1.GetSubString(0, 4); ASSERT(substr1.length = 4); ASSERT(StrEqualN(substr1.start, "ABCD", 4)); SubString substr2 = str1.GetSubString(2, 4); ASSERT(substr2.length = 4); ASSERT(StrEqualN(substr2.start, "CDEF", 4)); ASSERT(str1.GetRef() == 3); substr1 = substr2; substr1 = substr2; substr2 = substr1; ASSERT(substr1.GetRef() == 3); ASSERT(substr2.GetRef() == 3); } { char str1B[] = "ABCDEFGHIJ"; String str1 = str1B; SubString substr1,substr2; substr1 = str1.GetSubString(3, 4); substr2 = str1.GetSubString(6, 2); ASSERT(substr1 != substr2); ASSERT(substr2 != substr1); ASSERT(substr1.GetRef() == 3); ASSERT(substr2.GetRef() == 3); { SubString temp = substr1; substr1 = substr2; substr2 = temp; } ASSERT(substr1 != substr2); ASSERT(substr2 != substr1); ASSERT(substr1.GetRef() == 3); ASSERT(substr2.GetRef() == 3); ASSERT(substr1 == "GH"); ASSERT(substr2 == "DEFG"); SubString substr3 = str1.GetSubString(6, 3); ASSERT(substr1 != substr3); ASSERT(substr2 != substr3); str1.Release(); ASSERT(substr1.GetRef() == 3); ASSERT(substr2.GetRef() == 3); substr1 = substr3; substr2 = substr3; ASSERT(substr1.GetRef() == 3); ASSERT(substr2.GetRef() == 3); ASSERT(substr3.GetRef() == 3); ASSERT(substr1 == substr2); ASSERT(substr2 == substr3); SubString substr4,substr5; substr5 = substr4 = substr1; ASSERT(substr1.GetRef() == 5); ASSERT(substr4.GetRef() == 5); str1.Retain(); ASSERT(str1.GetRef() == 6); } { String str1 = "BCDEFGH"; SubString substr = str1.GetSubString(3, 2); str1.Release(); ASSERT(substr.GetRef() == 1); str1.Retain(); ASSERT(StrEqualN(substr.start, "EF", 2)); } { String str1 = "ABCDEF"; String str2 = str1.Insert("@@@", 0); ASSERT(str2 == "@@@ABCDEF"); ASSERT(str2.GetLength() == 9); } { String str1 = "ABCDEF"; String str2 = str1.Insert("@@@", 1); ASSERT(str2 == "A@@@BCDEF"); ASSERT(str2.GetLength() == 9); } { String str1 = "ABCDEF"; String str2 = str1.Insert('@', 2); ASSERT(str2 == "AB@CDEF"); ASSERT(str2.GetLength() == 7); } { String str1 = "ABCDEF"; String str2 = str1.Insert('@', 6); ASSERT(str2 == "ABCDEF@"); ASSERT(str2.GetLength() == 7); } { for (int i = 0; i < 7; i++) { String str1 = "ABCDEF"; String str2 = str1.Insert("", i); ASSERT(str2 == "ABCDEF"); ASSERT(str2.GetLength() == 6); } } { String str1 = ""; String str2 = str1.Insert("GHT", 0); ASSERT(str2 == "GHT"); ASSERT(str2.GetLength() == 3); } { String str1 = "ABCDEFGHIJ"; String str2 = str1.Remove(0); ASSERT(str2 == "BCDEFGHIJ"); } { String str1 = "ABCDEFGHIJ"; String str2 = str1.Remove(1); ASSERT(str2 == "ACDEFGHIJ"); } { String str1 = "ABCDEFGHIJ"; String str2 = str1.Remove(9); ASSERT(str2 == "ABCDEFGHI"); } { const char* str = "This is a test string lol.23523%@"; char* newStr = StrDup(str); ASSERT(StrEqual(str, newStr)); free(newStr); } { Vector<SubString> parts; SplitStringIntoParts("abcdef", "HH", &parts); ASSERT(parts.count == 1); ASSERT(parts.data[0] == "abcdef"); } { Vector<SubString> parts; SplitStringIntoParts("", "HH", &parts, true); ASSERT(parts.count == 0); } { Vector<SubString> parts; SplitStringIntoParts("ab cd ef", "HH", &parts); ASSERT(parts.count == 1); ASSERT(parts.data[0] == "ab cd ef"); } { Vector<SubString> parts; SplitStringIntoParts("abHHcd ef", "HH", &parts); ASSERT(parts.count == 2); ASSERT(parts.data[0] == "ab"); ASSERT(parts.data[1] == "cd ef"); } { Vector<SubString> parts; SplitStringIntoParts("a ef 234 65", " ", &parts); ASSERT(parts.count == 4); ASSERT(parts.data[0] == "a"); ASSERT(parts.data[1] == "ef"); ASSERT(parts.data[2] == "234"); ASSERT(parts.data[3] == "65"); } { Vector<SubString> parts; SplitStringIntoParts("a ef 234 65", " ", &parts); ASSERT(parts.count == 5); ASSERT(parts.data[0] == "a"); ASSERT(parts.data[1] == "ef"); ASSERT(parts.data[2] == "234"); ASSERT(parts.data[3] == ""); ASSERT(parts.data[4] == "65"); } { Vector<SubString> parts; SplitStringIntoParts("a ef 234 65", " ", &parts, true); ASSERT(parts.count == 4); ASSERT(parts.data[0] == "a"); ASSERT(parts.data[1] == "ef"); ASSERT(parts.data[2] == "234"); ASSERT(parts.data[3] == "65"); } { Vector<SubString> parts; SplitStringIntoParts("a ef 234 65", " ", &parts, true); ASSERT(parts.count == 4); ASSERT(parts.data[0] == "a"); ASSERT(parts.data[1] == "ef"); ASSERT(parts.data[2] == "234"); ASSERT(parts.data[3] == "65"); } { Vector<SubString> parts; SplitStringIntoParts("a||||ef|||234|65", "||", &parts, true); ASSERT(parts.count == 3); ASSERT(parts.data[0] == "a"); ASSERT(parts.data[1] == "ef"); ASSERT(parts.data[2] == "|234|65"); } { Vector<SubString> parts; SplitStringIntoParts("a||||ef|||234|65", "||", &parts); ASSERT(parts.count == 4); ASSERT(parts.data[0] == "a"); ASSERT(parts.data[1] == ""); ASSERT(parts.data[2] == "ef"); ASSERT(parts.data[3] == "|234|65"); } { Vector<SubString> parts; SplitStringIntoParts("", "||", &parts); ASSERT(parts.count == 0); } { Vector<SubString> parts; SplitStringIntoParts("", "||", &parts, true); ASSERT(parts.count == 0); } { Vector<SubString> parts; SplitStringIntoParts("a b c d e f", " ", &parts, true); ASSERT(parts.count == 6); ASSERT(parts.data[0] == "a"); ASSERT(parts.data[1] == "b"); ASSERT(parts.data[2] == "c"); ASSERT(parts.data[3] == "d"); ASSERT(parts.data[4] == "e"); ASSERT(parts.data[5] == "f"); } { Vector<SubString> parts; SplitStringIntoParts("a b c d e f", " ", &parts); ASSERT(parts.count == 6); ASSERT(parts.data[0] == "a"); ASSERT(parts.data[1] == "b"); ASSERT(parts.data[2] == "c"); ASSERT(parts.data[3] == "d"); ASSERT(parts.data[4] == "e"); ASSERT(parts.data[5] == "f"); } { Vector<SubString> parts; SplitStringIntoParts("a b c d e f", " ", &parts, true); ASSERT(parts.count == 6); ASSERT(parts.data[0] == "a"); ASSERT(parts.data[1] == "b"); ASSERT(parts.data[2] == "c"); ASSERT(parts.data[3] == "d"); ASSERT(parts.data[4] == "e"); ASSERT(parts.data[5] == "f"); } { Vector<SubString> parts; SplitStringIntoParts("a ", " ", &parts, true); ASSERT(parts.count == 1); ASSERT(parts.data[0] == "a"); } { Vector<SubString> parts; SplitStringIntoParts("a b ", " ", &parts, true); ASSERT(parts.count == 2); ASSERT(parts.data[0] == "a"); ASSERT(parts.data[1] == "b"); } { Vector<SubString> parts; SplitStringIntoParts("a b c d e f ", " ", &parts, true); ASSERT(parts.count == 6); ASSERT(parts.data[0] == "a"); ASSERT(parts.data[1] == "b"); ASSERT(parts.data[2] == "c"); ASSERT(parts.data[3] == "d"); ASSERT(parts.data[4] == "e"); ASSERT(parts.data[5] == "f"); } { Vector<SubString> parts; SplitStringIntoParts("a b c", " ", &parts, true); ASSERT(parts.count == 3); ASSERT(parts.data[0] == "a"); ASSERT(parts.data[1] == "b"); ASSERT(parts.data[2] == "c"); ASSERT(parts.data[0].AsString() == "a"); ASSERT(parts.data[1].AsString() == "b"); ASSERT(parts.data[2].AsString() == "c"); ASSERT(parts.data[0].AsString().GetLength() == 1); ASSERT(parts.data[1].AsString().GetLength() == 1); ASSERT(parts.data[2].AsString().GetLength() == 1); } { String x = ""; ASSERT(x == ""); ASSERT(!(x != "")); ASSERT(x != "a"); ASSERT(!(x == "a")); } { String x = "a"; ASSERT(x != ""); ASSERT(!(x == "")); ASSERT(x == "a"); ASSERT(!(x != "a")); } { SubString x; ASSERT(x == ""); ASSERT(!(x != "")); ASSERT(x != "a"); ASSERT(!(x == "a")); } { String xs = "a"; SubString x = xs.GetSubString(0, 1); ASSERT(x != ""); ASSERT(!(x == "")); ASSERT(x == "a"); ASSERT(!(x != "a")); } return 0; } #endif
19.498759
121
0.583906
[ "vector" ]
a7fcdd751740c7ed33c5ea03b8cd82cd2cffb2eb
2,429
hpp
C++
setup/xapp-sm-connector/src/xapp-asn/e2sm/e2sm_indication.hpp
wineslab/colosseum-near-rt-ric
e41cd25e500c527ee60fd8095bb6f40e96b7ccce
[ "Apache-2.0" ]
1
2022-02-24T21:40:00.000Z
2022-02-24T21:40:00.000Z
setup/xapp-sm-connector/src/xapp-asn/e2sm/e2sm_indication.hpp
wineslab/colosseum-near-rt-ric
e41cd25e500c527ee60fd8095bb6f40e96b7ccce
[ "Apache-2.0" ]
null
null
null
setup/xapp-sm-connector/src/xapp-asn/e2sm/e2sm_indication.hpp
wineslab/colosseum-near-rt-ric
e41cd25e500c527ee60fd8095bb6f40e96b7ccce
[ "Apache-2.0" ]
null
null
null
/* ================================================================================== Copyright (c) 2019-2020 AT&T Intellectual Property. 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. ================================================================================== */ /* * e2sm_indication.hpp * * Created on: Apr, 2020 * Author: Shraboni Jana */ /* Classes to handle E2 service model based on e2sm-HelloWorld-v001.asn */ #ifndef SRC_XAPP_ASN_E2SM_E2SM_INDICATION_HPP_ #define SRC_XAPP_ASN_E2SM_E2SM_INDICATION_HPP_ #include <sstream> #include <e2sm_helpers.hpp> #include <mdclog/mdclog.h> #include <vector> #include <E2SM-HelloWorld-IndicationHeader.h> #include <E2SM-HelloWorld-IndicationMessage.h> #include <E2SM-HelloWorld-IndicationHeader-Format1.h> #include <E2SM-HelloWorld-IndicationMessage-Format1.h> #include <HW-Header.h> #include <HW-Message.h> class e2sm_indication { public: e2sm_indication(void); ~e2sm_indication(void); bool set_fields(E2SM_HelloWorld_IndicationHeader_t *, e2sm_indication_helper &); bool set_fields(E2SM_HelloWorld_IndicationMessage_t *, e2sm_indication_helper &); bool get_fields(E2SM_HelloWorld_IndicationHeader_t *, e2sm_indication_helper &); bool get_fields(E2SM_HelloWorld_IndicationMessage_t *, e2sm_indication_helper &); bool encode_indication_header(unsigned char *, size_t *, e2sm_indication_helper &); bool encode_indication_message(unsigned char*, size_t *, e2sm_indication_helper &); std::string get_error (void) const {return error_string ;}; private: E2SM_HelloWorld_IndicationHeader_t * indication_head; // used for encoding E2SM_HelloWorld_IndicationMessage_t* indication_msg; E2SM_HelloWorld_IndicationHeader_Format1_t head_fmt1; E2SM_HelloWorld_IndicationMessage_Format1_t msg_fmt1; size_t errbuf_len; char errbuf[128]; std::string error_string; }; #endif /* SRC_XAPP_ASN_E2SM_E2SM_INDICATION_HPP_ */
31.960526
85
0.72746
[ "vector", "model" ]
c5007206d2f9600ffcd582a8d069bd5c88cf39cf
5,050
cpp
C++
gtsam/linear/IterativeSolver.cpp
kvmanohar22/gtsam
8194b931fe07fb1bd346cdcf116a35f9c4e208ba
[ "BSD-3-Clause" ]
1,402
2017-03-28T00:18:11.000Z
2022-03-30T10:28:32.000Z
gtsam/linear/IterativeSolver.cpp
kvmanohar22/gtsam
8194b931fe07fb1bd346cdcf116a35f9c4e208ba
[ "BSD-3-Clause" ]
851
2017-11-27T15:09:56.000Z
2022-03-31T22:26:38.000Z
gtsam/linear/IterativeSolver.cpp
kvmanohar22/gtsam
8194b931fe07fb1bd346cdcf116a35f9c4e208ba
[ "BSD-3-Clause" ]
565
2017-11-30T16:15:59.000Z
2022-03-31T02:53:04.000Z
/* ---------------------------------------------------------------------------- * GTSAM Copyright 2010, Georgia Tech Research Corporation, * Atlanta, Georgia 30332-0415 * All Rights Reserved * Authors: Frank Dellaert, et al. (see THANKS for the full author list) * See LICENSE for the license information * -------------------------------------------------------------------------- */ /** * @file IterativeSolver.cpp * @brief Some support classes for iterative solvers * @date Sep 3, 2012 * @author Yong-Dian Jian */ #include <gtsam/linear/IterativeSolver.h> #include <gtsam/linear/GaussianFactorGraph.h> #include <gtsam/linear/VectorValues.h> #include <boost/algorithm/string.hpp> #include <iostream> using namespace std; namespace gtsam { /*****************************************************************************/ string IterativeOptimizationParameters::getVerbosity() const { return verbosityTranslator(verbosity_); } /*****************************************************************************/ void IterativeOptimizationParameters::setVerbosity(const string &src) { verbosity_ = verbosityTranslator(src); } /*****************************************************************************/ void IterativeOptimizationParameters::print() const { print(cout); } /*****************************************************************************/ void IterativeOptimizationParameters::print(ostream &os) const { os << "IterativeOptimizationParameters:" << endl << "verbosity: " << verbosityTranslator(verbosity_) << endl; } /*****************************************************************************/ ostream& operator<<(ostream &os, const IterativeOptimizationParameters &p) { p.print(os); return os; } /*****************************************************************************/ IterativeOptimizationParameters::Verbosity IterativeOptimizationParameters::verbosityTranslator( const string &src) { string s = src; boost::algorithm::to_upper(s); if (s == "SILENT") return IterativeOptimizationParameters::SILENT; else if (s == "COMPLEXITY") return IterativeOptimizationParameters::COMPLEXITY; else if (s == "ERROR") return IterativeOptimizationParameters::ERROR; /* default is default */ else return IterativeOptimizationParameters::SILENT; } /*****************************************************************************/ string IterativeOptimizationParameters::verbosityTranslator( IterativeOptimizationParameters::Verbosity verbosity) { if (verbosity == SILENT) return "SILENT"; else if (verbosity == COMPLEXITY) return "COMPLEXITY"; else if (verbosity == ERROR) return "ERROR"; else return "UNKNOWN"; } /*****************************************************************************/ VectorValues IterativeSolver::optimize(const GaussianFactorGraph &gfg, boost::optional<const KeyInfo&> keyInfo, boost::optional<const std::map<Key, Vector>&> lambda) { return optimize(gfg, keyInfo ? *keyInfo : KeyInfo(gfg), lambda ? *lambda : std::map<Key, Vector>()); } /*****************************************************************************/ VectorValues IterativeSolver::optimize(const GaussianFactorGraph &gfg, const KeyInfo &keyInfo, const std::map<Key, Vector> &lambda) { return optimize(gfg, keyInfo, lambda, keyInfo.x0()); } /****************************************************************************/ KeyInfo::KeyInfo(const GaussianFactorGraph &fg, const Ordering &ordering) : ordering_(ordering) { initialize(fg); } /****************************************************************************/ KeyInfo::KeyInfo(const GaussianFactorGraph &fg) : ordering_(Ordering::Natural(fg)) { initialize(fg); } /****************************************************************************/ void KeyInfo::initialize(const GaussianFactorGraph &fg) { const map<Key, size_t> colspec = fg.getKeyDimMap(); const size_t n = ordering_.size(); size_t start = 0; for (size_t i = 0; i < n; ++i) { const Key key = ordering_[i]; const auto it_key = colspec.find(key); if (it_key==colspec.end()) throw std::runtime_error("KeyInfo: Inconsistency in key-dim map"); const size_t dim = it_key->second; this->emplace(key, KeyInfoEntry(i, dim, start)); start += dim; } numCols_ = start; } /****************************************************************************/ vector<size_t> KeyInfo::colSpec() const { std::vector<size_t> result(size(), 0); for ( const auto &item: *this ) { result[item.second.index] = item.second.dim; } return result; } /****************************************************************************/ VectorValues KeyInfo::x0() const { VectorValues result; for ( const auto &item: *this ) { result.emplace(item.first, Vector::Zero(item.second.dim)); } return result; } /****************************************************************************/ Vector KeyInfo::x0vector() const { return Vector::Zero(numCols_); } }
32.792208
96
0.521584
[ "vector" ]
c5014ec2c93eeaa011d152fb72376df3a7bdef6e
13,207
hpp
C++
source/PEST++/src/libs/opt/ClpSimplexOther.hpp
usgs/neversink_workflow
acd61435b8553e38d4a903c8cd7a3afc612446f9
[ "CC0-1.0" ]
90
2019-05-19T03:48:23.000Z
2022-02-02T15:20:49.000Z
source/PEST++/src/libs/opt/ClpSimplexOther.hpp
usgs/neversink_workflow
acd61435b8553e38d4a903c8cd7a3afc612446f9
[ "CC0-1.0" ]
11
2019-05-22T07:45:46.000Z
2021-05-20T01:48:26.000Z
source/PEST++/src/libs/opt/ClpSimplexOther.hpp
usgs/neversink_workflow
acd61435b8553e38d4a903c8cd7a3afc612446f9
[ "CC0-1.0" ]
18
2019-05-19T03:48:32.000Z
2021-05-29T18:19:16.000Z
/* $Id: ClpSimplexOther.hpp 2070 2014-11-18 11:12:54Z forrest $ */ // Copyright (C) 2004, International Business Machines // Corporation and others. All Rights Reserved. // This code is licensed under the terms of the Eclipse Public License (EPL). /* Authors John Forrest */ #ifndef ClpSimplexOther_H #define ClpSimplexOther_H #include "ClpSimplex.hpp" /** This is for Simplex stuff which is neither dual nor primal It inherits from ClpSimplex. It has no data of its own and is never created - only cast from a ClpSimplex object at algorithm time. */ class ClpSimplexOther : public ClpSimplex { public: /**@name Methods */ //@{ /** Dual ranging. This computes increase/decrease in cost for each given variable and corresponding sequence numbers which would change basis. Sequence numbers are 0..numberColumns and numberColumns.. for artificials/slacks. For non-basic variables the information is trivial to compute and the change in cost is just minus the reduced cost and the sequence number will be that of the non-basic variables. For basic variables a ratio test is between the reduced costs for non-basic variables and the row of the tableau corresponding to the basic variable. The increase/decrease value is always >= 0.0 Up to user to provide correct length arrays where each array is of length numberCheck. which contains list of variables for which information is desired. All other arrays will be filled in by function. If fifth entry in which is variable 7 then fifth entry in output arrays will be information for variable 7. If valueIncrease/Decrease not NULL (both must be NULL or both non NULL) then these are filled with the value of variable if such a change in cost were made (the existing bounds are ignored) When here - guaranteed optimal */ void dualRanging(int numberCheck, const int * which, double * costIncrease, int * sequenceIncrease, double * costDecrease, int * sequenceDecrease, double * valueIncrease = NULL, double * valueDecrease = NULL); /** Primal ranging. This computes increase/decrease in value for each given variable and corresponding sequence numbers which would change basis. Sequence numbers are 0..numberColumns and numberColumns.. for artificials/slacks. This should only be used for non-basic variabls as otherwise information is pretty useless For basic variables the sequence number will be that of the basic variables. Up to user to provide correct length arrays where each array is of length numberCheck. which contains list of variables for which information is desired. All other arrays will be filled in by function. If fifth entry in which is variable 7 then fifth entry in output arrays will be information for variable 7. When here - guaranteed optimal */ void primalRanging(int numberCheck, const int * which, double * valueIncrease, int * sequenceIncrease, double * valueDecrease, int * sequenceDecrease); /** Parametrics This is an initial slow version. The code uses current bounds + theta * change (if change array not NULL) and similarly for objective. It starts at startingTheta and returns ending theta in endingTheta. If reportIncrement 0.0 it will report on any movement If reportIncrement >0.0 it will report at startingTheta+k*reportIncrement. If it can not reach input endingTheta return code will be 1 for infeasible, 2 for unbounded, if error on ranges -1, otherwise 0. Normal report is just theta and objective but if event handler exists it may do more On exit endingTheta is maximum reached (can be used for next startingTheta) */ int parametrics(double startingTheta, double & endingTheta, double reportIncrement, const double * changeLowerBound, const double * changeUpperBound, const double * changeLowerRhs, const double * changeUpperRhs, const double * changeObjective); /** Version of parametrics which reads from file See CbcClpParam.cpp for details of format Returns -2 if unable to open file */ int parametrics(const char * dataFile); /** Parametrics This is an initial slow version. The code uses current bounds + theta * change (if change array not NULL) It starts at startingTheta and returns ending theta in endingTheta. If it can not reach input endingTheta return code will be 1 for infeasible, 2 for unbounded, if error on ranges -1, otherwise 0. Event handler may do more On exit endingTheta is maximum reached (can be used for next startingTheta) */ int parametrics(double startingTheta, double & endingTheta, const double * changeLowerBound, const double * changeUpperBound, const double * changeLowerRhs, const double * changeUpperRhs); int parametricsObj(double startingTheta, double & endingTheta, const double * changeObjective); /// Finds best possible pivot double bestPivot(bool justColumns=false); typedef struct { double startingTheta; double endingTheta; double maxTheta; double acceptableMaxTheta; // if this far then within tolerances double * lowerChange; // full array of lower bound changes int * lowerList; // list of lower bound changes double * upperChange; // full array of upper bound changes int * upperList; // list of upper bound changes char * markDone; // mark which ones looked at int * backwardBasic; // from sequence to pivot row int * lowerActive; double * lowerGap; double * lowerCoefficient; int * upperActive; double * upperGap; double * upperCoefficient; int unscaledChangesOffset; bool firstIteration; // so can update rhs for accuracy } parametricsData; private: /** Parametrics - inner loop This first attempt is when reportIncrement non zero and may not report endingTheta correctly If it can not reach input endingTheta return code will be 1 for infeasible, 2 for unbounded, otherwise 0. Normal report is just theta and objective but if event handler exists it may do more */ int parametricsLoop(parametricsData & paramData, double reportIncrement, const double * changeLower, const double * changeUpper, const double * changeObjective, ClpDataSave & data, bool canTryQuick); int parametricsLoop(parametricsData & paramData, ClpDataSave & data,bool canSkipFactorization=false); int parametricsObjLoop(parametricsData & paramData, ClpDataSave & data,bool canSkipFactorization=false); /** Refactorizes if necessary Checks if finished. Updates status. type - 0 initial so set up save arrays etc - 1 normal -if good update save - 2 restoring from saved */ void statusOfProblemInParametrics(int type, ClpDataSave & saveData); void statusOfProblemInParametricsObj(int type, ClpDataSave & saveData); /** This has the flow between re-factorizations Reasons to come out: -1 iterations etc -2 inaccuracy -3 slight inaccuracy (and done iterations) +0 looks optimal (might be unbounded - but we will investigate) +1 looks infeasible +3 max iterations */ int whileIterating(parametricsData & paramData, double reportIncrement, const double * changeObjective); /** Computes next theta and says if objective or bounds (0= bounds, 1 objective, -1 none). theta is in theta_. type 1 bounds, 2 objective, 3 both. */ int nextTheta(int type, double maxTheta, parametricsData & paramData, const double * changeObjective); int whileIteratingObj(parametricsData & paramData); int nextThetaObj(double maxTheta, parametricsData & paramData); /// Restores bound to original bound void originalBound(int iSequence, double theta, const double * changeLower, const double * changeUpper); /// Compute new rowLower_ etc (return negative if infeasible - otherwise largest change) double computeRhsEtc(parametricsData & paramData); /// Redo lower_ from rowLower_ etc void redoInternalArrays(); /** Row array has row part of pivot row Column array has column part. This is used in dual ranging */ void checkDualRatios(CoinIndexedVector * rowArray, CoinIndexedVector * columnArray, double & costIncrease, int & sequenceIncrease, double & alphaIncrease, double & costDecrease, int & sequenceDecrease, double & alphaDecrease); /** Row array has pivot column This is used in primal ranging */ void checkPrimalRatios(CoinIndexedVector * rowArray, int direction); /// Returns new value of whichOther when whichIn enters basis double primalRanging1(int whichIn, int whichOther); public: /** Write the basis in MPS format to the specified file. If writeValues true writes values of structurals (and adds VALUES to end of NAME card) Row and column names may be null. formatType is <ul> <li> 0 - normal <li> 1 - extra accuracy <li> 2 - IEEE hex (later) </ul> Returns non-zero on I/O error */ int writeBasis(const char *filename, bool writeValues = false, int formatType = 0) const; /// Read a basis from the given filename int readBasis(const char *filename); /** Creates dual of a problem if looks plausible (defaults will always create model) fractionRowRanges is fraction of rows allowed to have ranges fractionColumnRanges is fraction of columns allowed to have ranges */ ClpSimplex * dualOfModel(double fractionRowRanges = 1.0, double fractionColumnRanges = 1.0) const; /** Restores solution from dualized problem non-zero return code indicates minor problems */ int restoreFromDual(const ClpSimplex * dualProblem, bool checkAccuracy=false); /** Sets solution in dualized problem non-zero return code indicates minor problems */ int setInDual(ClpSimplex * dualProblem); /** Does very cursory presolve. rhs is numberRows, whichRows is 3*numberRows and whichColumns is 2*numberColumns. */ ClpSimplex * crunch(double * rhs, int * whichRows, int * whichColumns, int & nBound, bool moreBounds = false, bool tightenBounds = false); /** After very cursory presolve. rhs is numberRows, whichRows is 3*numberRows and whichColumns is 2*numberColumns. */ void afterCrunch(const ClpSimplex & small, const int * whichRows, const int * whichColumns, int nBound); /** Returns gub version of model or NULL whichRows has to be numberRows whichColumns has to be numberRows+numberColumns */ ClpSimplex * gubVersion(int * whichRows, int * whichColumns, int neededGub, int factorizationFrequency=50); /// Sets basis from original void setGubBasis(ClpSimplex &original,const int * whichRows, const int * whichColumns); /// Restores basis to original void getGubBasis(ClpSimplex &original,const int * whichRows, const int * whichColumns) const; /// Quick try at cleaning up duals if postsolve gets wrong void cleanupAfterPostsolve(); /** Tightens integer bounds - returns number tightened or -1 if infeasible */ int tightenIntegerBounds(double * rhsSpace); /** Expands out all possible combinations for a knapsack If buildObj NULL then just computes space needed - returns number elements On entry numberOutput is maximum allowed, on exit it is number needed or -1 (as will be number elements) if maximum exceeded. numberOutput will have at least space to return values which reconstruct input. Rows returned will be original rows but no entries will be returned for any rows all of whose entries are in knapsack. So up to user to allow for this. If reConstruct >=0 then returns number of entrie which make up item "reConstruct" in expanded knapsack. Values in buildRow and buildElement; */ int expandKnapsack(int knapsackRow, int & numberOutput, double * buildObj, CoinBigIndex * buildStart, int * buildRow, double * buildElement, int reConstruct = -1) const; //@} }; #endif
47.507194
119
0.666238
[ "object", "model" ]
c503b2ac488db2e8cdecb57de1b9b078beab0a82
281
cpp
C++
GameState.cpp
Pounhay/Hex
3410ce2baf4acb41e34850a8dc184cc2e80cb5e1
[ "MIT" ]
null
null
null
GameState.cpp
Pounhay/Hex
3410ce2baf4acb41e34850a8dc184cc2e80cb5e1
[ "MIT" ]
null
null
null
GameState.cpp
Pounhay/Hex
3410ce2baf4acb41e34850a8dc184cc2e80cb5e1
[ "MIT" ]
null
null
null
#include "GameState.h" #include "StartState.h" void GameState::Clicked() { if (gameBoard->Over()) game->ChangeState(new StartState(renderer, game)); gameBoard->Clicked(); } void GameState::Update() { gameBoard->Update(); } void GameState::Render() { gameBoard->Render(); }
17.5625
52
0.690391
[ "render" ]
c509d8bd20a01243eda2bb7be13166ca8d540d5b
2,684
cc
C++
paddle/pten/tests/core/test_allocator.cc
zhenlin-work/Paddle
ed7a21dea0ddcffb6f7f33ce21c5c368f5c7866b
[ "Apache-2.0" ]
4
2021-02-08T13:07:15.000Z
2021-10-22T00:58:33.000Z
paddle/pten/tests/core/test_allocator.cc
zhenlin-work/Paddle
ed7a21dea0ddcffb6f7f33ce21c5c368f5c7866b
[ "Apache-2.0" ]
2
2019-07-26T04:06:05.000Z
2019-07-29T04:25:24.000Z
paddle/pten/tests/core/test_allocator.cc
zhenlin-work/Paddle
ed7a21dea0ddcffb6f7f33ce21c5c368f5c7866b
[ "Apache-2.0" ]
5
2021-12-10T11:20:06.000Z
2022-02-18T05:18:12.000Z
/* Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <algorithm> #include <vector> #include "gtest/gtest.h" #include "paddle/fluid/framework/generator.h" #include "paddle/pten/tests/core/allocator.h" #include "paddle/pten/tests/core/random.h" #include "paddle/pten/tests/core/timer.h" namespace pten { namespace tests { template <typename T> bool host_allocator_test(size_t vector_size) { std::vector<T> src(vector_size); std::generate(src.begin(), src.end(), make_generator(src)); std::vector<T, CustomAllocator<T>> dst( src.begin(), src.end(), CustomAllocator<T>(std::make_shared<HostAllocatorSample>())); return std::equal(src.begin(), src.end(), dst.begin()); } TEST(raw_allocator, host) { CHECK(host_allocator_test<float>(1000)); CHECK(host_allocator_test<int32_t>(1000)); CHECK(host_allocator_test<int64_t>(1000)); } class StorageRawAlloc { public: StorageRawAlloc(const std::shared_ptr<RawAllocator>& a, size_t size) : alloc_(a) { data_ = alloc_->Allocate(size); } ~StorageRawAlloc() { alloc_->Deallocate(data_, size); } private: void* data_; size_t size; std::shared_ptr<RawAllocator> alloc_; }; class StorageFancyAlloc { public: StorageFancyAlloc(const std::shared_ptr<Allocator>& a, size_t size) : alloc_(a), allocation_(a->Allocate(size)) {} private: std::shared_ptr<Allocator> alloc_; Allocation allocation_; }; TEST(benchmark, allocator) { std::shared_ptr<RawAllocator> raw_allocator(new HostAllocatorSample); std::shared_ptr<Allocator> fancy_allocator(new FancyAllocator); const size_t cycles = 100; Timer timer; double t1{}, t2{}; for (size_t i = 0; i < cycles; ++i) { timer.tic(); for (size_t i = 0; i < cycles; ++i) { StorageRawAlloc(raw_allocator, i * 100); } t1 += timer.toc(); timer.tic(); for (size_t i = 0; i < cycles; ++i) { StorageFancyAlloc(fancy_allocator, i * 100); } t2 += timer.toc(); } std::cout << "The cost of raw alloc is " << t1 << "ms.\n"; std::cout << "The cost of fancy alloc with place is " << t2 << "ms.\n"; } } // namespace tests } // namespace pten
29.173913
73
0.696349
[ "vector" ]
c50b8734b10e10c886f245f165c73dfd13713df2
1,317
cpp
C++
test/unit/split.cpp
BigRedEye/cacos
da80d67375054260eac7518e3b53163e399461fe
[ "MIT" ]
3
2019-02-22T18:25:12.000Z
2019-02-27T13:32:00.000Z
test/unit/split.cpp
BigRedEye/cacos
da80d67375054260eac7518e3b53163e399461fe
[ "MIT" ]
null
null
null
test/unit/split.cpp
BigRedEye/cacos
da80d67375054260eac7518e3b53163e399461fe
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <cacos/util/split.h> TEST(split, simple) { std::vector<std::string_view> v1 = cacos::util::split("qwe:qwe::qwe:", ":"); std::vector<std::string_view> v2 {"qwe", "qwe", "", "qwe", ""}; EXPECT_EQ(v1, v2); } TEST(split, delimiters) { static const std::string s = "Hello, world! .., what. ,q we qwe ,, qwqwe qwe 123qwaq 12k,12.123 213, 123123.1!? "; std::vector<std::string_view> v1 = cacos::util::split(s, " ,.??"); std::vector<std::string_view> v2 { "Hello", "", "world!", "", "", "", "", "what", "", "", "q", "we", "qwe", "", "", "", "", "qwqwe", "qwe", "123qwaq", "12k", "12", "123", "", "213", "", "123123", "1!", "", "" }; EXPECT_EQ(v1, v2); } TEST(split, empty) { std::vector<std::string_view> v1 = cacos::util::split("", ":,"); std::vector<std::string_view> v2 {""}; EXPECT_EQ(v1, v2); } TEST(split, no_delimiters) { std::vector<std::string_view> v1 = cacos::util::split("Hello, world!", "$"); std::vector<std::string_view> v2 {"Hello, world!"}; EXPECT_EQ(v1, v2); } TEST(split, only_delimiters) { std::vector<std::string_view> v1 = cacos::util::split("$$$!$", "$!"); std::vector<std::string_view> v2 {"", "", "", "", "", ""}; EXPECT_EQ(v1, v2); }
31.357143
95
0.520121
[ "vector" ]
c50cb330e7f16ef075cf9447b1fe29a38a5b96c6
386
hpp
C++
src/Chain/libraries/include/client/SeedNodes.hpp
WillAchain/Achain
4118a8fc7a18e356e5a865d39d21bba3100664c9
[ "MIT" ]
226
2017-09-07T13:13:08.000Z
2022-02-26T09:07:10.000Z
src/Chain/libraries/include/client/SeedNodes.hpp
WillAchain/Achain
4118a8fc7a18e356e5a865d39d21bba3100664c9
[ "MIT" ]
22
2017-09-26T03:36:21.000Z
2020-08-23T19:59:40.000Z
src/Chain/libraries/include/client/SeedNodes.hpp
WillAchain/Achain
4118a8fc7a18e356e5a865d39d21bba3100664c9
[ "MIT" ]
79
2017-09-08T02:57:08.000Z
2022-02-02T12:46:31.000Z
#pragma once namespace thinkyoung { namespace client { #ifndef ALP_TEST_NETWORK static const std::vector<std::string> SeedNodes = { "node.achain.com:61696" }; #else static const std::vector<std::string> SeedNodes { "13.125.59.140:61696", "52.78.47.183:61696" }; #endif } } // thinkyoung::client
24.125
60
0.554404
[ "vector" ]
c50cee241e846f5ff6f8e32069f9ea76ebb5de6f
4,467
cpp
C++
dev/Code/Framework/AzCore/AzCore/Math/PolygonPrism.cpp
brianherrera/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
1,738
2017-09-21T10:59:12.000Z
2022-03-31T21:05:46.000Z
dev/Code/Framework/AzCore/AzCore/Math/PolygonPrism.cpp
olivier-be/lumberyard
3d688932f919dbf5821f0cb8a210ce24abe39e9e
[ "AML" ]
427
2017-09-29T22:54:36.000Z
2022-02-15T19:26:50.000Z
dev/Code/Framework/AzCore/AzCore/Math/PolygonPrism.cpp
olivier-be/lumberyard
3d688932f919dbf5821f0cb8a210ce24abe39e9e
[ "AML" ]
671
2017-09-21T08:04:01.000Z
2022-03-29T14:30:07.000Z
/* * 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. * */ #include <AzCore/Math/PolygonPrism.h> #include <AzCore/Memory/SystemAllocator.h> #include <AzCore/RTTI/BehaviorContext.h> #include <AzCore/Serialization/EditContext.h> #include <AzCore/Serialization/SerializeContext.h> namespace AZ { void PolygonPrismReflect(ReflectContext* context) { PolygonPrism::Reflect(context); } void PolygonPrism::Reflect(ReflectContext* context) { if (auto serializeContext = azrtti_cast<SerializeContext*>(context)) { serializeContext->Class<PolygonPrism>() ->Version(1) ->Field("Height", &PolygonPrism::m_height) ->Field("VertexContainer", &PolygonPrism::m_vertexContainer) ; if (EditContext* editContext = serializeContext->GetEditContext()) { editContext->Class<PolygonPrism>("PolygonPrism", "Polygon prism shape") ->ClassElement(Edit::ClassElements::EditorData, "") ->Attribute(Edit::Attributes::Visibility, Edit::PropertyVisibility::ShowChildrenOnly) ->DataElement(Edit::UIHandlers::Default, &PolygonPrism::m_height, "Height", "Shape Height") ->Attribute(Edit::Attributes::Suffix, " m") ->Attribute(Edit::Attributes::Step, 0.05f) ->Attribute(Edit::Attributes::Min, 0.0f) ->Attribute(Edit::Attributes::ChangeNotify, &PolygonPrism::OnChangeHeight) ->DataElement(Edit::UIHandlers::Default, &PolygonPrism::m_vertexContainer, "Vertices", "Data representing the polygon, in the entity's local coordinate space") ->Attribute(Edit::Attributes::ContainerCanBeModified, false) ->Attribute(Edit::Attributes::AutoExpand, true) ; } } if (auto behaviorContext = azrtti_cast<BehaviorContext*>(context)) { behaviorContext->Class<PolygonPrism>() ->Attribute(AZ::Script::Attributes::ExcludeFrom, AZ::Script::Attributes::ExcludeFlags::Preview) ->Attribute(Script::Attributes::Storage, Script::Attributes::StorageType::RuntimeOwn) ->Property("height", BehaviorValueGetter(&PolygonPrism::m_height), nullptr) ->Property("vertexContainer", BehaviorValueGetter(&PolygonPrism::m_vertexContainer), nullptr) ; } } void PolygonPrism::SetHeight(const float height) { if (!IsCloseMag(height, m_height)) { m_height = height; OnChangeHeight(); } } void PolygonPrism::OnChangeHeight() const { if (m_onChangeHeightCallback) { m_onChangeHeightCallback(); } } void PolygonPrism::SetCallbacks( const VoidFunction& onChangeElement, const VoidFunction& onChangeContainer, const VoidFunction& onChangeHeight) { m_vertexContainer.SetCallbacks( [onChangeContainer](size_t) { onChangeContainer(); }, [onChangeContainer](size_t) { onChangeContainer(); }, [onChangeElement](size_t) { onChangeElement(); }, onChangeContainer, onChangeContainer); m_onChangeHeightCallback = onChangeHeight; } void PolygonPrism::SetCallbacks( const IndexFunction& onAddVertex, const IndexFunction& onRemoveVertex, const IndexFunction& onUpdateVertex, const VoidFunction& onSetVertices, const VoidFunction& onClearVertices, const VoidFunction& onChangeHeight) { m_vertexContainer.SetCallbacks( onAddVertex, onRemoveVertex, onUpdateVertex, onSetVertices, onClearVertices); m_onChangeHeightCallback = onChangeHeight; } AZ_CLASS_ALLOCATOR_IMPL(PolygonPrism, SystemAllocator, 0) }
39.530973
179
0.631968
[ "shape" ]
c5120fc38cbacd67f4ecd041c845f7e47cc03789
8,765
cpp
C++
libraries/Duke32AIO/robot_normal/duke32.cpp
sohtamei/TuKuRutch.ext
3e7e3713d8825dc2bebf01f601736fedcbceca05
[ "Apache-2.0" ]
1
2020-10-28T07:45:36.000Z
2020-10-28T07:45:36.000Z
libraries/Duke32AIO/robot_normal/duke32.cpp
sohtamei/TuKuRutch.ext
3e7e3713d8825dc2bebf01f601736fedcbceca05
[ "Apache-2.0" ]
null
null
null
libraries/Duke32AIO/robot_normal/duke32.cpp
sohtamei/TuKuRutch.ext
3e7e3713d8825dc2bebf01f601736fedcbceca05
[ "Apache-2.0" ]
null
null
null
#include "duke32.h" /******************************** * for Wifi Connection *********************************/ // Add Feature String void AddFeatureString(String &S, const String F){ if (S.length() != 0) S.concat(", "); S.concat(F); } uint64_t GetChipid(){ // Chip Info const char* ModelStrings[] PROGMEM = {"", "ESP32"}; uint64_t chipid; // Get Chip Information esp_chip_info_t chip_info; esp_chip_info(&chip_info); Serial.printf("Model: %s\r\n", ModelStrings[chip_info.model]); // Features String Features = ""; if (chip_info.features & CHIP_FEATURE_EMB_FLASH) AddFeatureString(Features, "Embedded Flash"); if (chip_info.features & CHIP_FEATURE_WIFI_BGN ) AddFeatureString(Features, "Wifi-BGN" ); if (chip_info.features & CHIP_FEATURE_BLE ) AddFeatureString(Features, "BLE" ); if (chip_info.features & CHIP_FEATURE_BT ) AddFeatureString(Features, "Bluetooth" ); Serial.println("Features: " + Features); // Cores Serial.printf("Cores: %d\r\n", chip_info.cores); // Revision Serial.printf("Revision: %d\r\n", chip_info.revision); // MAC Address String MACString = ""; chipid = ESP.getEfuseMac(); for (int i=0; i<6; i++) { if (i > 0) MACString.concat(":"); uint8_t Octet = chipid >> (i * 8); if (Octet < 16) MACString.concat("0"); MACString.concat(String(Octet, HEX)); } Serial.println("MAC Address: " + MACString); // Flash Size uint32_t FlashSize = ESP.getFlashChipSize(); String ValueString = ""; do { ValueString = String(FlashSize % 1000) + ValueString; FlashSize /= 1000; if (FlashSize > 0) ValueString = "," + ValueString; } while (FlashSize > 0); Serial.println("Flash Size: " + ValueString); // ChipID chipid=ESP.getEfuseMac();//The chip ID is essentially its MAC address(length: 6 bytes). Serial.printf("Chip ID = %04X",(uint16_t)(chipid>>32));//print High 2 bytes Serial.printf("%08X\n",(uint32_t)chipid);//print Low 4bytes. return chipid; } void WiFiMgrSetup(char WiFiAPname[]){ //WiFiManager Serial.printf("AP: %s\n", WiFiAPname); Serial.println("IP: 192.168.4.1"); //Local intialization. Once its business is done, there is no need to keep it around WiFiManager wifiManager; // WiFiManager̃ wifiManager.setDebugOutput(false); //set custom ip for portal //wifiManager.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); //or use this for auto generated name ESP + ChipID wifiManager.autoConnect(WiFiAPname); //wifiManager.autoConnect("NoseRadi32AP"); //if you get here you have connected to the WiFi Serial.println("connected(^^)"); Serial.println(WiFi.SSID()); Serial.println(WiFi.localIP()); } void OTASetup(char OTAHostname[]){ // Port defaults to 3232 // ArduinoOTA.setPort(3232); // Hostname defaults to esp3232-[MAC] // ArduinoOTA.setHostname("myesp32"); ArduinoOTA.setHostname(OTAHostname); Serial.printf("OTA Host: %s\n", OTAHostname); // No authentication by default // ArduinoOTA.setPassword("admin"); // Password can be set with it's md5 value as well // MD5(admin) = 21232f297a57a5a743894a0e4a801fc3 // ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3"); ArduinoOTA.onStart([]() { String type; if (ArduinoOTA.getCommand() == U_FLASH) type = "sketch"; else // U_SPIFFS type = "filesystem"; // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end() Serial.println("Start updating " + type); }); ArduinoOTA.onEnd([]() { Serial.println("\nEnd"); }); ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { Serial.printf("Progress: %u%%\r", (progress / (total / 100))); }); ArduinoOTA.onError([](ota_error_t error) { Serial.printf("Error[%u]: ", error); if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); else if (error == OTA_END_ERROR) Serial.println("End Failed"); }); ArduinoOTA.begin(); } /******************************** * for Servo Control *********************************/ void servoInit(){ // Setup timer and attach timer to a servo pin ledcSetup(LEDC_CHANNEL_0, LEDC_BASE_FREQ, LEDC_TIMER_BIT); ledcAttachPin(Servo_PIN1, LEDC_CHANNEL_0); ledcSetup(LEDC_CHANNEL_1, LEDC_BASE_FREQ, LEDC_TIMER_BIT); ledcAttachPin(Servo_PIN2, LEDC_CHANNEL_1); } void setServo(uint8_t servoNo, uint16_t angle){ uint16_t pwmWidth; if(servoNo < 0){ servoNo = 0; }else if(servoNo > 1){ servoNo = 1; } if(angle < 0){ angle = 0; }else if(angle > 180){ angle = 180; } pwmWidth = ((srvMax - srvMin) / 180) * angle + srvMin; ledcWrite(servoNo, pwmWidth); } /******************************** * for Motor Control *********************************/ void Motor_INIT(){ pinMode(MTR_A1, OUTPUT); pinMode(MTR_A2, OUTPUT); // pinMode(MTR_AE, OUTPUT); pinMode(MTR_B1, OUTPUT); pinMode(MTR_B2, OUTPUT); // pinMode(MTR_BE, OUTPUT); digitalWrite(MTR_A1, LOW); digitalWrite(MTR_A2, LOW); // digitalWrite(MTR_AE, LOW); digitalWrite(MTR_B1, LOW); digitalWrite(MTR_B2, LOW); // digitalWrite(MTR_BE, LOW); // Setup timer and attach timer to a servo pin ledcSetup(LEDC_CHANNEL_2, LEDC_BASE_FREQ_MTR, LEDC_TIMER_BIT_MTR); ledcAttachPin(MTR_AE, LEDC_CHANNEL_2); ledcSetup(LEDC_CHANNEL_3, LEDC_BASE_FREQ_MTR, LEDC_TIMER_BIT_MTR); ledcAttachPin(MTR_BE, LEDC_CHANNEL_3); } void setMotorSpeed(uint8_t motorNo, uint8_t speed){ if(motorNo < 2){ motorNo = 2; }else if(motorNo > 3){ motorNo = 3; } if(speed < 0){ speed = 0; }else if(speed > 255){ speed = 255; } ledcWrite(motorNo, speed); } void motorL_forward(uint8_t speed){ // digitalWrite(MTR_AE, HIGH); setMotorSpeed(MotorL, speed); digitalWrite(MTR_A1, HIGH); digitalWrite(MTR_A2, LOW); } void motorL_back(uint8_t speed){ // digitalWrite(MTR_AE, HIGH); setMotorSpeed(MotorL, speed); digitalWrite(MTR_A1, LOW); digitalWrite(MTR_A2, HIGH); } void motorL_stop(){ // digitalWrite(MTR_AE, LOW); setMotorSpeed(MotorL, 0); digitalWrite(MTR_A1, LOW); digitalWrite(MTR_A2, LOW); } void motorR_forward(uint8_t speed){ // digitalWrite(MTR_BE, HIGH); setMotorSpeed(MotorR, speed); digitalWrite(MTR_B1, HIGH); digitalWrite(MTR_B2, LOW); } void motorR_back(uint8_t speed){ // digitalWrite(MTR_BE, HIGH); setMotorSpeed(MotorR, speed); digitalWrite(MTR_B1, LOW); digitalWrite(MTR_B2, HIGH); } void motorR_stop(){ // digitalWrite(MTR_BE, LOW); setMotorSpeed(MotorR, 0); digitalWrite(MTR_B1, LOW); digitalWrite(MTR_B2, LOW); } void motor_stop(){ motorL_stop(); motorR_stop(); } void motor_forward(){ motorL_forward(255); motorR_forward(255); } void motor_back(){ motorL_back(255); motorR_back(255); } void motor_left(){ motorL_forward(128); motorR_forward(255); } void motor_right(){ motorL_forward(255); motorR_forward(128); } void motor_turnleft(){ motorL_stop(); motorR_forward(255); } void motor_turnright(){ motorL_forward(255); motorR_stop(); } void motor_spinleft(){ motorL_back(255); motorR_forward(255); } void motor_spinright(){ motorL_forward(255); motorR_back(255); } // -------------------------------------- // i2c_scanner // -------------------------------------- void i2c_scan(){ Serial.println("\nI2C Scanner"); byte error, address; int nDevices; Serial.println("Scanning..."); nDevices = 0; for(address = 1; address < 127; address++ ) { // The i2c_scanner uses the return value of // the Write.endTransmisstion to see if // a device did acknowledge to the address. Wire.beginTransmission(address); error = Wire.endTransmission(); if (error == 0) { Serial.print("I2C device found at address 0x"); if (address<16){ Serial.print("0"); } Serial.print(address,HEX); Serial.println(" !"); nDevices++; } else if (error==4) { Serial.print("Unknow error at address 0x"); if (address<16){ Serial.print("0"); } Serial.println(address,HEX); } } if (nDevices == 0){ Serial.println("No I2C devices found\n"); }else{ Serial.println("done\n"); } }
26.480363
105
0.625898
[ "model" ]
78a091382436b43a34e9ae41ceab088cc5103a36
3,296
cpp
C++
chapter3/detecAndDescriCompCost/test_kaze_akaze_opencv-master/test_akaze_match.cpp
taojianggit/Code-for-the-Degree-of-Master-of-Engineering
4a8b305cd43abe37953545a927db9eae3b544368
[ "MIT" ]
2
2017-04-30T15:08:21.000Z
2019-11-18T13:57:37.000Z
chapter3/detecAndDescriCompCost/test_kaze_akaze_opencv-master/test_akaze_match.cpp
taojianggit/Code-for-the-Degree-of-Master-of-Engineering
4a8b305cd43abe37953545a927db9eae3b544368
[ "MIT" ]
null
null
null
chapter3/detecAndDescriCompCost/test_kaze_akaze_opencv-master/test_akaze_match.cpp
taojianggit/Code-for-the-Degree-of-Master-of-Engineering
4a8b305cd43abe37953545a927db9eae3b544368
[ "MIT" ]
1
2022-02-25T14:46:49.000Z
2022-02-25T14:46:49.000Z
/** * @file test_akaze_match.cpp * @brief Main program for testing OpenCV A-KAZE port in an image matching application * @date Jun 05, 2014 * @author Pablo F. Alcantarilla */ #include "./src/utils.h" // System #include <string> #include <vector> #include <iostream> using namespace std; using namespace cv; /* ************************************************************************* */ int main(int argc, char *argv[]) { if (argc != 4) { cerr << "Error introducing input arguments!" << endl; cerr << "The format needs to be: ./test_akaze_match img1 imgN H1toN" << endl; return -1; } cv::Mat img1, imgN; string img1File = argv[1]; string imgNFile = argv[2]; string HFile = argv[3]; // Open the input image img1 = imread(img1File, 1); imgN = imread(imgNFile, 1); cv::Mat H1toN = read_homography(HFile); // Create A-KAZE object Ptr<Feature2D> dakaze = AKAZE::create(); // Timing information double t1 = 0.0, t2 = 0.0; double takaze = 0.0, tmatch = 0.0; // Detect A-KAZE features in the images vector<cv::KeyPoint> kpts1, kptsN; cv::Mat desc1, descN; t1 = cv::getTickCount(); dakaze->detectAndCompute(img1, cv::noArray(), kpts1, desc1); dakaze->detectAndCompute(imgN, cv::noArray(), kptsN, descN); t2 = cv::getTickCount(); takaze = 1000.0*(t2-t1) / cv::getTickFrequency(); int nr_kpts1 = kpts1.size(); int nr_kptsN = kptsN.size(); // Match the descriptors using NNDR matching strategy vector<vector<cv::DMatch> > dmatches; vector<cv::Point2f> matches, inliers; cv::Ptr<cv::DescriptorMatcher> matcher = cv::DescriptorMatcher::create("BruteForce-Hamming"); float nndr = 0.8; t1 = cv::getTickCount(); matcher->knnMatch(desc1, descN, dmatches, 2); matches2points_nndr(kpts1, kptsN, dmatches, matches, nndr); t2 = cv::getTickCount(); tmatch = 1000.0*(t2-t1) / cv::getTickFrequency(); // Compute the inliers using the ground truth homography float max_h_error = 2.5; compute_inliers_homography(matches, inliers, H1toN, max_h_error); // Compute the inliers statistics int nr_matches = matches.size()/2; int nr_inliers = inliers.size()/2; int nr_outliers = nr_matches - nr_inliers; float ratio = 100.0*((float) nr_inliers / (float) nr_matches); cout << "A-KAZE Matching Results" << endl; cout << "*******************************" << endl; cout << "# Keypoints 1: \t" << nr_kpts1 << endl; cout << "# Keypoints N: \t" << nr_kptsN << endl; cout << "# Matches: \t" << nr_matches << endl; cout << "# Inliers: \t" << nr_inliers << endl; cout << "# Outliers: \t" << nr_outliers << endl; cout << "Inliers Ratio (%): \t" << ratio << endl; cout << "Time Detection+Description (ms): \t" << takaze << endl; cout << "Time Matching (ms): \t" << tmatch << endl; cout << endl; // Visualization cv::Mat img_com = cv::Mat(cv::Size(2*img1.cols, img1.rows), CV_8UC3); draw_keypoints(img1, kpts1); draw_keypoints(imgN, kptsN); draw_inliers(img1, imgN, img_com, inliers); cv::namedWindow("A-KAZE Matching", cv::WINDOW_KEEPRATIO); cv::imshow("A-KAZE Matching", img_com); cv::waitKey(0); return 1; }
32
95
0.601032
[ "object", "vector" ]
78aa6094f1ef39f7d6f9eec40d03118e7e538e4a
9,973
cpp
C++
src/main.cpp
virtualsecureplatform/Iyokan
f167d438d68b2ebf31094c361d498469c8bcc152
[ "Apache-2.0" ]
81
2020-01-29T08:44:16.000Z
2021-11-14T16:26:48.000Z
src/main.cpp
virtualsecureplatform/Iyokan
f167d438d68b2ebf31094c361d498469c8bcc152
[ "Apache-2.0" ]
3
2020-02-09T04:43:52.000Z
2021-11-12T13:22:19.000Z
src/main.cpp
virtualsecureplatform/Iyokan
f167d438d68b2ebf31094c361d498469c8bcc152
[ "Apache-2.0" ]
1
2020-05-10T19:12:15.000Z
2020-05-10T19:12:15.000Z
#include <chrono> #include <CLI/CLI.hpp> #include "iyokan_plain.hpp" #include "iyokan_tfhepp.hpp" #ifdef IYOKAN_CUDA_ENABLED #include "iyokan_cufhe.hpp" #endif int main(int argc, char **argv) { error::initialize("iyokan"); // Show build config spdlog::info("Build config"); #if defined(NDEBUG) spdlog::info("\tType: Release"); #else spdlog::info("\tType: Debug"); #endif #if defined(IYOKAN_GIT_REVISION) spdlog::info("\tGit revision: " IYOKAN_GIT_REVISION); #else spdlog::info("\tGit revision: unknown"); #endif #if defined(USE_80BIT_SECURITY) spdlog::info("\tTFHE security parameter: CGGI16 (80bit)"); #elif defined(USE_CGGI19) spdlog::info("\tTFHE security parameter: CGGI19"); #else spdlog::info("\tTFHE security parameter: 128bit"); #endif #ifdef IYOKAN_CUDA_ENABLED spdlog::info("\tGPU support: enabled"); #else spdlog::info("\tGPU support: disabled"); #endif // Parse command-line arguments CLI::App app{"Prallel FHE circuit evaluation engine."}; app.require_subcommand(); enum class TYPE { PLAIN, TFHE } type; Options opt; #ifdef IYOKAN_CUDA_ENABLED bool enableGPU = false; #endif bool verbose = false, quiet = false; std::map<std::string, SCHED> mapSched{{"topo", SCHED::TOPO}, {"ranku", SCHED::RANKU}}; { CLI::App *plain = app.add_subcommand("plain", ""); plain->parse_complete_callback([&] { type = TYPE::PLAIN; }); plain->add_option("-c", opt.numCycles, ""); plain->add_option("--cpu", opt.numCPUWorkers, "") ->check(CLI::PositiveNumber); plain->add_option("--dump-prefix", opt.dumpPrefix, ""); auto optO = plain->add_option("-o,--out", opt.outputFile, ""); plain->add_flag_function( "--stdout-csv,!--no-stdout-csv", [&](int64_t count) { opt.stdoutCSV = count > 0 ? true : false; }, ""); plain->add_option("--snapshot", opt.snapshotFile, ""); plain->add_flag("--quiet", quiet, ""); plain->add_flag("--verbose", verbose, ""); plain->add_option("--dump-time-csv-prefix", opt.dumpTimeCSVPrefix, ""); plain->add_option("--dump-graph-json-prefix", opt.dumpGraphJSONPrefix, ""); plain->add_option("--dump-graph-dot-prefix", opt.dumpGraphDOTPrefix, ""); plain->add_option("--sched", opt.sched, "") ->transform(CLI::CheckedTransformer(mapSched, CLI::ignore_case)); plain->add_flag("--skip-reset", opt.skipReset, ""); plain->add_flag("--show-combinational-progress", opt.showCombinationalProgress, ""); auto ogroups = plain->add_option_group("run in plaintext", "Run in plaintext mode"); ogroups->require_option(1); auto newRun = ogroups->add_option_group("new run", "A new run"); newRun ->add_option_function<std::string>( "--blueprint", [&](auto &&filepath) { opt.blueprint = NetworkBlueprint{filepath}; }) ->required() ->check(CLI::ExistingFile); newRun->add_option("-i,--in", opt.inputFile, "") ->required() ->needs(optO) ->check(CLI::ExistingFile); auto resume = ogroups->add_option_group("resume", "Resume from a saved snapshot"); resume->add_option("--resume", opt.resumeFile, "")->required(); } { CLI::App *tfhe = app.add_subcommand("tfhe", ""); tfhe->parse_complete_callback([&] { type = TYPE::TFHE; }); tfhe->add_option("--bkey", opt.bkeyFile, "")->required(); auto optC = tfhe->add_option("-c", opt.numCycles, ""); tfhe->add_option("--cpu", opt.numCPUWorkers, "") ->check(CLI::PositiveNumber); auto optO = tfhe->add_option("-o,--out", opt.outputFile, ""); tfhe->add_flag_function( "--stdout-csv,!--no-stdout-csv", [&](int64_t count) { opt.stdoutCSV = count > 0 ? true : false; }, ""); tfhe->add_option("--snapshot", opt.snapshotFile, ""); tfhe->add_flag("--quiet", quiet, ""); tfhe->add_flag("--verbose", verbose, ""); tfhe->add_option("--dump-time-csv-prefix", opt.dumpTimeCSVPrefix, ""); tfhe->add_option("--dump-graph-json-prefix", opt.dumpGraphJSONPrefix, ""); tfhe->add_option("--dump-graph-dot-prefix", opt.dumpGraphDOTPrefix, ""); tfhe->add_option("--sched", opt.sched, "") ->transform(CLI::CheckedTransformer(mapSched, CLI::ignore_case)); tfhe->add_option("--secret-key", opt.secretKey, "") ->check(CLI::ExistingFile); tfhe->add_option("--dump-prefix", opt.dumpPrefix, "") ->needs("--secret-key"); tfhe->add_flag("--skip-reset", opt.skipReset, ""); tfhe->add_flag("--show-combinational-progress", opt.showCombinationalProgress, ""); #ifdef IYOKAN_CUDA_ENABLED tfhe->add_option("--gpu", opt.numGPUWorkers, "") ->check(CLI::PositiveNumber); tfhe->add_option_function<int>( "--gpu_num", [&](const int &v) { spdlog::warn( "Option --gpu_num is deprecated. Use --num-gpu " "instead."); opt.numGPU.emplace(v); }, "") ->check(CLI::PositiveNumber); tfhe->add_option("--num-gpu", opt.numGPU, "") ->check(CLI::PositiveNumber); #endif auto ogroups = tfhe->add_option_group("run in TFHE mode", "Run in TFHE mode"); ogroups->require_option(1); auto newRun = ogroups->add_option_group("new run", "A new run"); newRun ->add_option_function<std::string>( "--blueprint", [&](auto &&filepath) { opt.blueprint = NetworkBlueprint{filepath}; }) ->required() ->check(CLI::ExistingFile); newRun->add_option("-i,--in", opt.inputFile, "") ->required() ->needs(optC, optO) ->check(CLI::ExistingFile); #ifdef IYOKAN_CUDA_ENABLED newRun->add_flag("--enable-gpu", enableGPU, ""); #endif auto resume = ogroups->add_option_group("resume", "Resume from a saved snapshot"); resume->add_option("--resume", opt.resumeFile, "")->required(); } CLI11_PARSE(app, argc, argv); // Print what options are selected. spdlog::info("Options"); if (opt.blueprint) spdlog::info("\tBlueprint: {}", opt.blueprint->sourceFile()); if (opt.numCPUWorkers) spdlog::info("\t# of CPU workers: {}", *opt.numCPUWorkers); if (opt.numGPUWorkers) spdlog::info("\t# of GPU workers: {}", *opt.numGPUWorkers); if (opt.numGPU) spdlog::info("\t# of GPUs: {}", *opt.numGPU); if (opt.numCycles) spdlog::info("\t# of cycles: {}", *opt.numCycles); if (opt.bkeyFile) spdlog::info("\tBKey file: {}", *opt.bkeyFile); if (opt.inputFile) spdlog::info("\tInput file (request packet): {}", *opt.inputFile); if (opt.outputFile) spdlog::info("\tOutput file (result packet): {}", *opt.outputFile); if (opt.secretKey) spdlog::info("\t--secret-key: {}", *opt.secretKey); if (opt.dumpPrefix) spdlog::info("\t--dump-prefix: {}", *opt.dumpPrefix); if (opt.snapshotFile) spdlog::info("\t--snapshot: {}", *opt.snapshotFile); if (opt.resumeFile) spdlog::info("\t--resume: {}", *opt.resumeFile); if (opt.stdoutCSV) spdlog::info("\t--stdout-csv: {}", opt.stdoutCSV); spdlog::info("\t--verbose: {}", verbose); spdlog::info("\t--quiet: {}", quiet); if (opt.dumpTimeCSVPrefix) spdlog::info("\t--dump-time-csv-prefix: {}", *opt.dumpTimeCSVPrefix); if (opt.dumpGraphJSONPrefix) spdlog::info("\t--dump-graph-json-prefix: {}", *opt.dumpGraphJSONPrefix); if (opt.dumpGraphDOTPrefix) spdlog::info("\t--dump-graph-dot-prefix: {}", *opt.dumpGraphDOTPrefix); if (opt.sched != SCHED::UND) { std::string str; switch (opt.sched) { case SCHED::TOPO: str = "topo"; break; case SCHED::RANKU: str = "ranku"; break; default: error::die("unreachable"); } spdlog::info("\t--sched: {}", str); } if (opt.skipReset) spdlog::info("\t--skip-reset: {}", opt.skipReset); if (opt.showCombinationalProgress) spdlog::info("\t--show-combinational-progess: {}", opt.showCombinationalProgress); // Process depending on the options chosen. if (quiet) spdlog::set_level(spdlog::level::err); if (verbose) spdlog::set_level(spdlog::level::debug); if (opt.resumeFile) { switch (type) { case TYPE::PLAIN: if (!isSerializedPlainFrontend(*opt.resumeFile)) error::die("Invalid resume file: ", *opt.resumeFile); break; case TYPE::TFHE: if (!isSerializedTFHEppFrontend(*opt.resumeFile)) { #ifdef IYOKAN_CUDA_ENABLED if (isSerializedCUFHEFrontend(*opt.resumeFile)) enableGPU = true; else #endif error::die("Invalid resume file: ", *opt.resumeFile); } break; } } AsyncThread::setNumThreads(std::thread::hardware_concurrency()); switch (type) { case TYPE::PLAIN: doPlain(opt); break; case TYPE::TFHE: #ifdef IYOKAN_CUDA_ENABLED if (enableGPU) doCUFHE(opt); else #endif doTFHE(opt); break; } }
35.874101
80
0.552291
[ "transform" ]
78ac805df8b76386eb2d73b3ad80dbeb0b21e8a4
11,689
cpp
C++
src/tensorinfo.cpp
Xaenalt/model_server
f977dbf1246ebf85e960ca058e814deac7c6a16c
[ "Apache-2.0" ]
234
2020-04-24T22:09:49.000Z
2022-03-30T10:40:04.000Z
src/tensorinfo.cpp
Xaenalt/model_server
f977dbf1246ebf85e960ca058e814deac7c6a16c
[ "Apache-2.0" ]
199
2020-04-29T08:43:21.000Z
2022-03-29T09:05:52.000Z
src/tensorinfo.cpp
Xaenalt/model_server
f977dbf1246ebf85e960ca058e814deac7c6a16c
[ "Apache-2.0" ]
80
2020-04-29T14:54:41.000Z
2022-03-30T14:50:29.000Z
//***************************************************************************** // Copyright 2021 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #include <map> #include <memory> #include <sstream> #include <string> #include <inference_engine.hpp> #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wall" #include "tensorflow/core/framework/tensor.h" #include "tensorflow_serving/apis/prediction_service.grpc.pb.h" #pragma GCC diagnostic pop #include "logging.hpp" #include "tensorinfo.hpp" namespace ovms { TensorInfo::TensorInfo(const std::string& name, const InferenceEngine::Precision& precision, const shape_t& shape) : name(name), mapping(""), precision(precision), shape(shape), layout(InferenceEngine::Layout::ANY) { this->updateEffectiveShape(); } TensorInfo::TensorInfo(const std::string& name, const InferenceEngine::Precision& precision, const shape_t& shape, const InferenceEngine::Layout& layout) : name(name), mapping(""), precision(precision), shape(shape), layout(layout) { this->updateEffectiveShape(); } TensorInfo::TensorInfo(const std::string& name, const InferenceEngine::TensorDesc& tensorDesc) : name(name), mapping(""), precision(tensorDesc.getPrecision()), shape(tensorDesc.getDims()), layout(tensorDesc.getLayout()) { this->updateEffectiveShape(); } TensorInfo::TensorInfo(const std::string& name, const std::string& mapping, const InferenceEngine::Precision& precision, const shape_t& shape, const InferenceEngine::Layout& layout) : name(name), mapping(mapping), precision(precision), shape(shape), layout(layout) { this->updateEffectiveShape(); } const std::string& TensorInfo::getName() const { return name; } const std::string& TensorInfo::getMappedName() const { return mapping.size() == 0 ? name : mapping; } void TensorInfo::setMappedName(const std::string& mappedName) { mapping = mappedName; } const InferenceEngine::Precision TensorInfo::getPrecision() const { return precision; } void TensorInfo::setPrecision(const InferenceEngine::Precision& requestedPrecision) { precision = requestedPrecision; } const tensorflow::DataType TensorInfo::getPrecisionAsDataType() const { return getPrecisionAsDataType(precision); } const tensorflow::DataType TensorInfo::getPrecisionAsDataType(InferenceEngine::Precision precision) { switch (precision) { case InferenceEngine::Precision::FP32: return tensorflow::DataType::DT_FLOAT; case InferenceEngine::Precision::I32: return tensorflow::DataType::DT_INT32; case InferenceEngine::Precision::I8: return tensorflow::DataType::DT_INT8; case InferenceEngine::Precision::U8: return tensorflow::DataType::DT_UINT8; case InferenceEngine::Precision::FP16: return tensorflow::DataType::DT_HALF; // case InferenceEngine::Precision::Q78: return tensorflow::DataType:: case InferenceEngine::Precision::I16: return tensorflow::DataType::DT_INT16; case InferenceEngine::Precision::U16: return tensorflow::DataType::DT_UINT16; case InferenceEngine::Precision::U64: return tensorflow::DataType::DT_UINT64; case InferenceEngine::Precision::I64: return tensorflow::DataType::DT_INT64; // case InferenceEngine::Precision::BIN: return tensorflow::DataType:: case InferenceEngine::Precision::BOOL: return tensorflow::DataType::DT_BOOL; default: return tensorflow::DataType::DT_INVALID; } } const std::string TensorInfo::getPrecisionAsString() const { return getPrecisionAsString(precision); } const std::string TensorInfo::getPrecisionAsString(InferenceEngine::Precision precision) { switch (precision) { case InferenceEngine::Precision::FP32: return "FP32"; case InferenceEngine::Precision::I32: return "I32"; case InferenceEngine::Precision::I8: return "I8"; case InferenceEngine::Precision::U8: return "U8"; case InferenceEngine::Precision::FP16: return "FP16"; // case InferenceEngine::Precision::Q78: return tensorflow::DataType:: case InferenceEngine::Precision::I16: return "I16"; case InferenceEngine::Precision::U16: return "U16"; case InferenceEngine::Precision::I64: return "I64"; case InferenceEngine::Precision::BOOL: return "BOOL"; default: return "DT_INVALID"; } } const std::string TensorInfo::getDataTypeAsString(tensorflow::DataType dataType) { switch (dataType) { case tensorflow::DataType::DT_FLOAT: return "FP32"; case tensorflow::DataType::DT_INT32: return "I32"; case tensorflow::DataType::DT_INT8: return "I8"; case tensorflow::DataType::DT_UINT8: return "U8"; case tensorflow::DataType::DT_HALF: return "FP16"; case tensorflow::DataType::DT_INT16: return "I16"; case tensorflow::DataType::DT_UINT16: return "U16"; case tensorflow::DataType::DT_UINT64: return "U64"; case tensorflow::DataType::DT_INT64: return "I64"; case tensorflow::DataType::DT_BOOL: return "BOOL"; case tensorflow::DataType::DT_STRING: return "STRING"; default: return "DT_INVALID"; } } InferenceEngine::Layout TensorInfo::getLayoutFromString(const std::string& layout) { if (layout == "ANY") return InferenceEngine::Layout::ANY; if (layout == "NCHW") return InferenceEngine::Layout::NCHW; if (layout == "NHWC") return InferenceEngine::Layout::NHWC; if (layout == "NCDHW") return InferenceEngine::Layout::NCDHW; if (layout == "NDHWC") return InferenceEngine::Layout::NDHWC; if (layout == "OIHW") return InferenceEngine::Layout::OIHW; if (layout == "GOIHW") return InferenceEngine::Layout::GOIHW; if (layout == "OIDHW") return InferenceEngine::Layout::OIDHW; if (layout == "GOIDHW") return InferenceEngine::Layout::GOIDHW; if (layout == "SCALAR") return InferenceEngine::Layout::SCALAR; if (layout == "C") return InferenceEngine::Layout::C; if (layout == "CHW") return InferenceEngine::Layout::CHW; if (layout == "HW") return InferenceEngine::Layout::HW; if (layout == "HWC") return InferenceEngine::Layout::HWC; if (layout == "NC") return InferenceEngine::Layout::NC; if (layout == "CN") return InferenceEngine::Layout::CN; if (layout == "BLOCKED") return InferenceEngine::Layout::BLOCKED; return InferenceEngine::Layout::ANY; } std::string TensorInfo::getStringFromLayout(InferenceEngine::Layout layout) { switch (layout) { case InferenceEngine::Layout::ANY: return "ANY"; case InferenceEngine::Layout::NCHW: return "NCHW"; case InferenceEngine::Layout::NHWC: return "NHWC"; case InferenceEngine::Layout::NCDHW: return "NCDHW"; case InferenceEngine::Layout::NDHWC: return "NDHWC"; case InferenceEngine::Layout::OIHW: return "OIHW"; case InferenceEngine::Layout::GOIHW: return "GOIHW"; case InferenceEngine::Layout::OIDHW: return "OIDHW"; case InferenceEngine::Layout::GOIDHW: return "GOIDHW"; case InferenceEngine::Layout::SCALAR: return "SCALAR"; case InferenceEngine::Layout::C: return "C"; case InferenceEngine::Layout::CHW: return "CHW"; case InferenceEngine::Layout::HW: return "HW"; case InferenceEngine::Layout::HWC: return "HWC"; case InferenceEngine::Layout::NC: return "NC"; case InferenceEngine::Layout::CN: return "CN"; case InferenceEngine::Layout::BLOCKED: return "BLOCKED"; } return ""; } const InferenceEngine::Layout& TensorInfo::getLayout() const { return layout; } const shape_t& TensorInfo::getShape() const { return shape; } bool TensorInfo::isInfluencedByDemultiplexer() const { return influencedByDemultiplexer; } const shape_t& TensorInfo::getEffectiveShape() const { return effectiveShape.size() > 0 ? effectiveShape : shape; } void TensorInfo::setShape(const shape_t& shape) { this->shape = shape; this->updateEffectiveShape(); } void TensorInfo::setLayout(InferenceEngine::Layout layout) { this->layout = layout; this->updateEffectiveShape(); } void TensorInfo::updateEffectiveShape() { this->effectiveShape = this->getTensorDesc().getBlockingDesc().getBlockDims(); } std::shared_ptr<TensorInfo> TensorInfo::createCopyWithNewShape(const shape_t& shape) const { auto copy = std::make_shared<TensorInfo>(*this); copy->shape = shape; copy->layout = InferenceEngine::Layout::ANY; copy->updateEffectiveShape(); return copy; } std::shared_ptr<TensorInfo> TensorInfo::createCopyWithEffectiveDimensionPrefix(size_t dim) const { auto copy = std::make_shared<TensorInfo>(*this); copy->influencedByDemultiplexer = true; copy->effectiveShape = this->getEffectiveShape(); copy->effectiveShape.insert(copy->effectiveShape.begin(), dim); return copy; } const InferenceEngine::TensorDesc TensorInfo::getTensorDesc() const { return InferenceEngine::TensorDesc{precision, shape, layout}; } bool TensorInfo::isTensorSpecEqual(const TensorInfo& other) const { return this->getEffectiveShape() == other.getEffectiveShape() && this->getPrecision() == other.getPrecision(); } bool TensorInfo::isTensorUnspecified() const { return this->getPrecision() == InferenceEngine::Precision::UNSPECIFIED; } std::string TensorInfo::shapeToString(const shape_t& shape) { std::ostringstream oss; oss << "("; size_t i = 0; if (shape.size() > 0) { for (; i < shape.size() - 1; i++) { oss << shape[i] << ","; } oss << shape[i]; } oss << ")"; return oss.str(); } std::string TensorInfo::tensorShapeToString(const tensorflow::TensorShapeProto& tensorShape) { std::ostringstream oss; oss << "("; int i = 0; if (tensorShape.dim_size() > 0) { for (; i < tensorShape.dim_size() - 1; i++) { oss << tensorShape.dim(i).size() << ","; } oss << tensorShape.dim(i).size(); } oss << ")"; return oss.str(); } std::shared_ptr<TensorInfo> TensorInfo::getUnspecifiedTensorInfo() { std::shared_ptr<TensorInfo> info = std::make_shared<TensorInfo>("", InferenceEngine::Precision::UNSPECIFIED, shape_t{}); return info; } std::string TensorInfo::tensorDescToString(const InferenceEngine::TensorDesc& desc) { std::stringstream ss; ss << "shape: " << shapeToString(desc.getDims()) << " effective shape: " << shapeToString(desc.getBlockingDesc().getBlockDims()) << " precision: " << getPrecisionAsString(desc.getPrecision()) << " layout: " << getStringFromLayout(desc.getLayout()); return ss.str(); } } // namespace ovms
31.254011
124
0.662589
[ "shape" ]
78b382db342449d8f91d7cc6914d0d9b857f2259
6,873
hpp
C++
src/lib/support/QuickSort.hpp
jqswang/txsampler
19d2b188e712dd86be84d84c75e08af320304c2c
[ "BSD-3-Clause" ]
1
2018-11-18T17:44:22.000Z
2018-11-18T17:44:22.000Z
src/lib/support/QuickSort.hpp
jqswang/txsampler
19d2b188e712dd86be84d84c75e08af320304c2c
[ "BSD-3-Clause" ]
null
null
null
src/lib/support/QuickSort.hpp
jqswang/txsampler
19d2b188e712dd86be84d84c75e08af320304c2c
[ "BSD-3-Clause" ]
null
null
null
// -*-Mode: C++;-*- // * BeginRiceCopyright ***************************************************** // // $HeadURL$ // $Id$ // // -------------------------------------------------------------------------- // Part of HPCToolkit (hpctoolkit.org) // // Information about sources of support for research and development of // HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'. // -------------------------------------------------------------------------- // // Copyright ((c)) 2002-2016, Rice University // 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 Rice University (RICE) 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 RICE 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 RICE 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. // // ******************************************************* EndRiceCopyright * /****************************************************************************** * File: QuickSort Class * * Author: Christine Patton * * Date: June, 1993 * * * ***************************** QuickSort Public ******************************* * * * Constructor: * * Nothing. * * * * Destructor: * * Nothing. * * * * Create: * * This function must be called after creating the object as it allocates * * space for a pointer to an array of void pointers, initializes the number * * of slots in the array, and initializes a pointer to the comparison funct.* * The comparison function should take two arguments and return a positive * * integer if the first argument is greater, a negative one if the second * * argument is greater. * * * * Destroy: * * deallocates the space for the pointers initialized in Create. * * * * Sort: * * recursivley sorts the section of the array from minEntry to maxEntry. * * * **************************** QuickSort Private ******************************* * * * Partition: * * returns the rank of element q int the array (all elements less than * * element q are to the left, all elements greater than element q are * * to the right) * * * * Swap: * * pretty much self-explanatory * * * * ArrayPtr: * * pointer to the array that will be sorted * * * * CompareFunc: * * pointer to the comparison function provided by the user * * * * QuickSortCreated: * * set to true in Create (must have value true before Sort, Partition, * * or Swap can be executed) * * * *****************************************************************************/ #ifndef QuickSort_h #define QuickSort_h //************************** System Include Files *************************** //*************************** User Include Files **************************** #include <include/uint.h> /************************ QuickSort function prototypes **********************/ typedef int (*EntryCompareFunctPtr)(const void*, const void*); /************************** QuickSort class definition ***********************/ class QuickSort { public: QuickSort (); virtual ~QuickSort (); void Create (void** UserArrayPtr, const EntryCompareFunctPtr _CompareFunct); void Destroy (); void Sort (const int minEntryIndex, const int maxEntryIndex); private: void** ArrayPtr; EntryCompareFunctPtr CompareFunct; bool QuickSortCreated; void Swap (int a, int b); int Partition (const int min, const int max, const int q); }; #endif
51.676692
80
0.402299
[ "object" ]
78b474e43b4e921185ed746197731002212091f0
742
hpp
C++
typo/io.hpp
KSills-Dev/typotronic
4732bcaf514ce0fe59e8cb4b0f5f6e1e180aa1fc
[ "MIT" ]
null
null
null
typo/io.hpp
KSills-Dev/typotronic
4732bcaf514ce0fe59e8cb4b0f5f6e1e180aa1fc
[ "MIT" ]
null
null
null
typo/io.hpp
KSills-Dev/typotronic
4732bcaf514ce0fe59e8cb4b0f5f6e1e180aa1fc
[ "MIT" ]
null
null
null
#pragma once #include "typo.hpp" #include <string> #include <vector> /** @brief Imports a string list from the given file. The first line in the file should specify the number of problem instances, followed by newline delimited pairs of "correct\ntypo" pairs. @return True on successful import, false otherwise. */ auto input_from_file(const std::string &filename, std::vector<std::pair<std::string, std::string>> &data) -> bool; /** @brief Exports the string form of data (delimited by newlines) to the given file. @return True on successful export, false otherwise. */ auto output_to_file(const std::string &filename, const std::vector<std::pair<int, TypoStack>> &data) -> bool;
26.5
80
0.690027
[ "vector" ]
78bb114c14dc7b76e6ab88b92b0c55dba746fa79
21,362
cpp
C++
src/host/extensions/signing.cpp
TheWillard/intercept
7bd96f4b0cec66f5ef1f3cbef7c4abe35e4f8fda
[ "MIT" ]
166
2016-02-11T09:21:26.000Z
2022-01-01T10:34:38.000Z
src/host/extensions/signing.cpp
TheWillard/intercept
7bd96f4b0cec66f5ef1f3cbef7c4abe35e4f8fda
[ "MIT" ]
104
2016-02-10T14:34:27.000Z
2022-03-26T18:03:47.000Z
src/host/extensions/signing.cpp
TheWillard/intercept
7bd96f4b0cec66f5ef1f3cbef7c4abe35e4f8fda
[ "MIT" ]
85
2016-02-11T23:14:23.000Z
2022-03-18T05:03:09.000Z
#include "signing.hpp" #ifndef __linux__ #include <wincrypt.h> #include <wintrust.h> #include <windows.h> #pragma comment(lib, "crypt32.lib") //https://stackoverflow.com/questions/7241453/read-and-validate-certificate-from-executable /* https://stackoverflow.com/questions/84847/how-do-i-create-a-self-signed-certificate-for-code-signing-on-windows CA: makecert -r -pe -n "CN=InterceptSignTest CA" -ss CA -sr CurrentUser -a sha256 -cy authority -sky signature -sv InterceptSignTest.pvk InterceptSignTestCA.cer CodesignCert: makecert -pe -n "CN=InterceptSignTest SPC" -a sha256 -cy end -sky signature -ic InterceptSignTestCA.cer -iv InterceptSignTest.pvk -sv InterceptSignTestCodeSignCert.pvk InterceptSignTestCodeSignCert.cer PFX: pvk2pfx -pvk InterceptSignTestCodeSignCert.pvk -spc InterceptSignTestCodeSignCert.cer -pfx InterceptSignTestCodeSignCert.pfx sign binary: signtool sign /v /f InterceptSignTestCodeSignCert.pfx /t http://timestamp.comodoca.com/authenticode SignatureCheck.exe */ unsigned char coreCACert[] = { 0x30, 0x82, 0x05, 0x94, 0x30, 0x82, 0x03, 0x7C, 0xA0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x09, 0x00,0xDF, 0xE4, 0xAA, 0xD1, 0xDD, 0x14, 0xD7, 0x1C, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0B, 0x05, 0x00, 0x30, 0x57, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55,0x04, 0x06, 0x13, 0x02, 0x44, 0x45, 0x31, 0x10, 0x30, 0x0E, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0C, 0x07, 0x47, 0x65, 0x72, 0x6D, 0x61, 0x6E, 0x79, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04,0x0A, 0x0C, 0x09, 0x49, 0x6E, 0x74, 0x65, 0x72, 0x63, 0x65, 0x70, 0x74, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x0B, 0x0C, 0x02, 0x43, 0x41, 0x31, 0x15, 0x30, 0x13, 0x06, 0x03, 0x55,0x04, 0x03, 0x0C, 0x0C, 0x49, 0x6E, 0x74, 0x65, 0x72, 0x63, 0x65, 0x70, 0x74, 0x20, 0x43, 0x41, 0x30, 0x1E, 0x17, 0x0D, 0x31, 0x37, 0x31, 0x31, 0x30, 0x32, 0x31, 0x31, 0x33, 0x36, 0x32, 0x38,0x5A, 0x17, 0x0D, 0x33, 0x37, 0x31, 0x30, 0x32, 0x38, 0x31, 0x31, 0x33, 0x36, 0x32, 0x38, 0x5A, 0x30, 0x57, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x44, 0x45, 0x31,0x10, 0x30, 0x0E, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0C, 0x07, 0x47, 0x65, 0x72, 0x6D, 0x61, 0x6E, 0x79, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x0A, 0x0C, 0x09, 0x49, 0x6E, 0x74, 0x65,0x72, 0x63, 0x65, 0x70, 0x74, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x0B, 0x0C, 0x02, 0x43, 0x41, 0x31, 0x15, 0x30, 0x13, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0C, 0x0C, 0x49, 0x6E, 0x74,0x65, 0x72, 0x63, 0x65, 0x70, 0x74, 0x20, 0x43, 0x41, 0x30, 0x82, 0x02, 0x22, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x02, 0x0F,0x00, 0x30, 0x82, 0x02, 0x0A, 0x02, 0x82, 0x02, 0x01, 0x00, 0xC7, 0x34, 0x2F, 0x3D, 0x40, 0x30, 0x73, 0x52, 0x06, 0x14, 0x2B, 0xC1, 0x51, 0x84, 0x7D, 0x22, 0xAB, 0x81, 0xD4, 0x34, 0x3B, 0x79,0xF4, 0xE1, 0xC4, 0xBE, 0xA0, 0x6A, 0xCC, 0xC5, 0xDC, 0xB6, 0x5D, 0x54, 0x50, 0x50, 0xCF, 0x45, 0xA3, 0x52, 0x6A, 0x8F, 0xFD, 0x9C, 0x7E, 0x52, 0xAA, 0xCF, 0x0B, 0xF9, 0x8C, 0x31, 0x2A, 0x54,0x7B, 0xB4, 0x8B, 0x15, 0x0A, 0x7A, 0xBA, 0x45, 0x0C, 0x21, 0x7D, 0xA8, 0x68, 0xD2, 0xF2, 0xEE, 0xF8, 0x21, 0xCE, 0x14, 0x4B, 0x97, 0xA5, 0x64, 0x6D, 0xCD, 0x3A, 0x78, 0xB4, 0x15, 0x7A, 0x8E,0x15, 0xCC, 0x2C, 0x3A, 0x1C, 0x8B, 0x98, 0x80, 0xB6, 0xD7, 0x38, 0x32, 0x22, 0xE0, 0x40, 0xDE, 0xBA, 0x91, 0x91, 0x34, 0x43, 0xF2, 0x1B, 0xC9, 0xC2, 0xAD, 0xC5, 0xA2, 0xD4, 0xF3, 0xF6, 0x1A,0x0C, 0x79, 0xB5, 0x2B, 0x12, 0xC4, 0xEB, 0x8F, 0x84, 0xE7, 0xC1, 0x77, 0x4D, 0xCA, 0x6C, 0xAB, 0x77, 0xEB, 0x85, 0xD6, 0xCA, 0xA4, 0x4D, 0x8A, 0x82, 0xB1, 0x66, 0xAE, 0x24, 0xDA, 0x4B, 0xDA,0x33, 0xE0, 0x48, 0x75, 0xC3, 0x0C, 0x35, 0xF4, 0xFA, 0x42, 0x7D, 0x24, 0xF8, 0xCB, 0xFD, 0xE4, 0xBF, 0xF6, 0xAB, 0xF6, 0x72, 0x92, 0x86, 0xA8, 0xCA, 0x3C, 0x85, 0x24, 0x90, 0x3E, 0x1C, 0xEC,0x7B, 0x77, 0x3C, 0x4B, 0xF4, 0x37, 0x49, 0x40, 0xDF, 0x4C, 0x13, 0xC0, 0x53, 0x9F, 0x4E, 0x06, 0xAC, 0x8E, 0xF4, 0x5E, 0x57, 0x09, 0xFF, 0x20, 0x69, 0xEB, 0x10, 0x85, 0xB5, 0xD6, 0x95, 0x01,0xBE, 0xFD, 0x72, 0x93, 0x4B, 0x83, 0x70, 0x8D, 0xFB, 0x11, 0x6D, 0x4A, 0x9F, 0xD8, 0x2B, 0x2C, 0x5A, 0x67, 0x2D, 0x3E, 0x14, 0xC0, 0xF6, 0x2E, 0x63, 0xC1, 0x08, 0x9E, 0x95, 0x4D, 0x20, 0x71,0x1F, 0xC0, 0xFD, 0x52, 0x5C, 0x84, 0x12, 0x7F, 0x7F, 0x65, 0x62, 0xFE, 0xA5, 0xC5, 0x93, 0xF7, 0x36, 0xF5, 0xCB, 0x1B, 0xB2, 0x32, 0xF5, 0xE6, 0x56, 0x8A, 0xED, 0x32, 0x1F, 0xF6, 0xFD, 0x78,0xD2, 0x9E, 0xEB, 0x23, 0x6A, 0x57, 0x77, 0x6D, 0x48, 0x54, 0xD8, 0x25, 0xE2, 0x20, 0x1C, 0xB5, 0xC7, 0x18, 0xCD, 0x74, 0xCB, 0x6C, 0x20, 0x24, 0x7C, 0xC5, 0x6B, 0x55, 0x93, 0x8B, 0x62, 0x0C,0x11, 0x91, 0xB0, 0x27, 0xB7, 0x05, 0xDA, 0x1D, 0x46, 0x9B, 0x82, 0x75, 0x13, 0x84, 0x55, 0x0F, 0xCE, 0xF6, 0x45, 0xB5, 0x6A, 0x6E, 0x39, 0xC4, 0x7A, 0x1F, 0x58, 0x95, 0x37, 0xC3, 0x28, 0x0F,0x8A, 0xF1, 0xFE, 0xD7, 0x74, 0xFD, 0x71, 0x83, 0x9F, 0x5F, 0x58, 0xED, 0x20, 0x6F, 0x29, 0x7F, 0x1F, 0x12, 0x21, 0x76, 0xC2, 0x5D, 0x79, 0x9B, 0xB7, 0xA3, 0x82, 0xD6, 0x96, 0x1F, 0xC1, 0xC2,0xE8, 0x90, 0x43, 0x6D, 0x67, 0x00, 0xC8, 0x41, 0xB9, 0x76, 0x45, 0xD8, 0x0C, 0x5F, 0x9F, 0x5D, 0x37, 0xF2, 0xFB, 0x62, 0x56, 0x02, 0xBE, 0x68, 0xF5, 0x43, 0xC8, 0xBC, 0xB2, 0xFC, 0x9B, 0xE9,0xA4, 0x60, 0x54, 0xD2, 0x1D, 0x4C, 0xD7, 0x4F, 0xBB, 0xCA, 0x1A, 0x2E, 0x4D, 0xE5, 0xAD, 0x76, 0x57, 0xFB, 0x74, 0x1E, 0xBE, 0x6B, 0x8E, 0xBE, 0x90, 0xD6, 0x92, 0x93, 0x69, 0x7E, 0x43, 0x62,0x19, 0xE2, 0xF6, 0x10, 0xF7, 0x6C, 0x79, 0x89, 0x00, 0x08, 0x17, 0x69, 0xA0, 0x19, 0xAD, 0xC6, 0x52, 0x8C, 0x6E, 0xFE, 0x4D, 0x60, 0xEF, 0xFB, 0x95, 0x08, 0x4A, 0x96, 0xF5, 0xFE, 0x82, 0xF9,0x74, 0x1F, 0x01, 0x92, 0x90, 0x11, 0xFF, 0x23, 0x6E, 0xE9, 0xC7, 0x03, 0x3E, 0x0D, 0x31, 0x01, 0x7C, 0x49, 0x55, 0x35, 0x5F, 0x6D, 0x10, 0xBD, 0x50, 0x65, 0x7F, 0x88, 0x6A, 0x21, 0x84, 0xC5,0x90, 0x4C, 0x29, 0x6A, 0x05, 0x67, 0x17, 0x58, 0x96, 0x1D, 0x02, 0x03, 0x01, 0x00, 0x01, 0xA3, 0x63, 0x30, 0x61, 0x30, 0x1D, 0x06, 0x03, 0x55, 0x1D, 0x0E, 0x04, 0x16, 0x04, 0x14, 0xA4, 0xD6,0x8A, 0x2B, 0x70, 0xF8, 0x6B, 0x10, 0x56, 0xA6, 0x16, 0x29, 0x03, 0x5A, 0x97, 0xE2, 0xD0, 0x6E, 0x59, 0x63, 0x30, 0x1F, 0x06, 0x03, 0x55, 0x1D, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, 0x14, 0xA4,0xD6, 0x8A, 0x2B, 0x70, 0xF8, 0x6B, 0x10, 0x56, 0xA6, 0x16, 0x29, 0x03, 0x5A, 0x97, 0xE2, 0xD0, 0x6E, 0x59, 0x63, 0x30, 0x0F, 0x06, 0x03, 0x55, 0x1D, 0x13, 0x01, 0x01, 0xFF, 0x04, 0x05, 0x30,0x03, 0x01, 0x01, 0xFF, 0x30, 0x0E, 0x06, 0x03, 0x55, 0x1D, 0x0F, 0x01, 0x01, 0xFF, 0x04, 0x04, 0x03, 0x02, 0x01, 0x86, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01,0x0B, 0x05, 0x00, 0x03, 0x82, 0x02, 0x01, 0x00, 0xBA, 0x48, 0xE8, 0x58, 0x0B, 0x94, 0xFA, 0x6E, 0x5D, 0xD2, 0xFA, 0x02, 0x37, 0x1B, 0x3E, 0xD1, 0x91, 0x2D, 0x2E, 0xAE, 0xED, 0x49, 0x35, 0xAF,0x6A, 0x75, 0x26, 0xB8, 0xB4, 0xFD, 0xE3, 0xDF, 0x94, 0x63, 0xC2, 0x1C, 0x26, 0x9C, 0xCD, 0xE9, 0xB5, 0x76, 0x74, 0x87, 0x2D, 0xE7, 0x7F, 0x1F, 0x5E, 0xED, 0x57, 0xC3, 0xBB, 0x70, 0xFD, 0xAB,0xBC, 0x37, 0x43, 0x62, 0x92, 0x6C, 0xE6, 0x1B, 0x84, 0x2C, 0x84, 0x43, 0x95, 0x4A, 0xCF, 0xDB, 0x4F, 0x36, 0xFE, 0xCB, 0x64, 0x8F, 0x69, 0xD1, 0xA1, 0xAE, 0xB0, 0xCB, 0x61, 0x33, 0xDA, 0xDE,0xAF, 0x69, 0x36, 0x86, 0x58, 0xFD, 0x70, 0xFA, 0x47, 0xBC, 0x2C, 0x34, 0xCF, 0xE6, 0x60, 0x5A, 0xBA, 0x1A, 0xE1, 0xA3, 0xB8, 0x98, 0xBF, 0x08, 0x3B, 0x2F, 0xC0, 0x4A, 0x9E, 0x7A, 0xC6, 0x45,0x29, 0xE8, 0x88, 0x2E, 0xB6, 0x1E, 0xD2, 0x80, 0x51, 0x86, 0x63, 0x69, 0x08, 0xDA, 0xA9, 0x8C, 0xD6, 0xEE, 0xE6, 0xBA, 0x6C, 0x49, 0xCF, 0x94, 0xC0, 0x60, 0x60, 0x44, 0x3C, 0x76, 0xCC, 0x0C,0x7F, 0x73, 0x65, 0x84, 0xD5, 0xCC, 0x97, 0xD2, 0xCC, 0xFF, 0x6E, 0x45, 0xAB, 0x1B, 0x33, 0xC3, 0x58, 0x3F, 0x15, 0x6D, 0xF8, 0x24, 0x91, 0x76, 0x37, 0xF9, 0xCE, 0x1D, 0x6E, 0xB3, 0x94, 0xAA,0x74, 0xF3, 0x20, 0xE4, 0x9C, 0x9E, 0x57, 0xDD, 0x05, 0x63, 0x5C, 0x34, 0xC7, 0xEA, 0x07, 0x84, 0x62, 0xA2, 0x27, 0xFE, 0x2F, 0xF1, 0xAB, 0x50, 0x4B, 0x51, 0x8B, 0x83, 0x6C, 0x18, 0x56, 0xD0,0xD9, 0x1D, 0x5C, 0xEA, 0x06, 0xD4, 0x5C, 0x29, 0x90, 0x88, 0x60, 0x92, 0xDD, 0x27, 0x2C, 0xA9, 0x82, 0xD2, 0xC9, 0x07, 0xFA, 0xF4, 0x33, 0x9E, 0x1C, 0x10, 0xA6, 0x0F, 0x22, 0x53, 0x9A, 0x69,0xE9, 0xB1, 0x9B, 0xAC, 0x30, 0x22, 0xED, 0xE5, 0x93, 0xCD, 0x81, 0x2F, 0xE2, 0xA7, 0x5C, 0xF4, 0x23, 0xA4, 0xE3, 0x63, 0x7A, 0x92, 0x23, 0x05, 0xCC, 0x55, 0x6E, 0x92, 0xAC, 0x81, 0x16, 0xB5,0x96, 0x40, 0x75, 0xF1, 0x00, 0xB0, 0x71, 0x4C, 0xD8, 0x03, 0x9E, 0x8E, 0xFC, 0x24, 0xB6, 0x6A, 0x8A, 0xC0, 0xE0, 0x3F, 0x4E, 0xB4, 0x08, 0x7F, 0xB5, 0x67, 0xF1, 0x96, 0xC0, 0x03, 0xA8, 0xBE,0xFA, 0xA3, 0x65, 0x13, 0xFA, 0x00, 0x5E, 0x1C, 0x40, 0xA0, 0xBF, 0xBB, 0x74, 0x89, 0xEE, 0x89, 0x6E, 0x43, 0x53, 0x63, 0xC0, 0x07, 0xF1, 0x98, 0x0E, 0xA2, 0x58, 0xCF, 0x61, 0x2A, 0xBE, 0xB7,0x15, 0x33, 0xEF, 0xB1, 0xF9, 0x8E, 0xDF, 0x08, 0xE0, 0xFF, 0xEF, 0x2B, 0x09, 0xF2, 0x9E, 0x99, 0xDB, 0x45, 0x5B, 0x7C, 0xE0, 0x0D, 0xFB, 0x67, 0x4F, 0xE7, 0x63, 0xC7, 0x1B, 0x87, 0xAE, 0x22,0x07, 0x2F, 0x7E, 0x1A, 0x28, 0xDD, 0x52, 0x90, 0x0D, 0x00, 0xCB, 0x51, 0x77, 0x43, 0xFA, 0x58, 0x24, 0x0B, 0x83, 0x60, 0x73, 0x74, 0xDE, 0xF0, 0xCC, 0x97, 0xB6, 0xF2, 0x96, 0xE0, 0x69, 0x19,0xB6, 0x3F, 0xD8, 0x08, 0xE6, 0x34, 0x7B, 0x4F, 0xB0, 0x72, 0xF0, 0xE8, 0xA1, 0xFA, 0xAE, 0xF2, 0xC8, 0xAB, 0xF4, 0x61, 0xCA, 0x27, 0xCB, 0x98, 0x9D, 0x03, 0x23, 0x10, 0xFE, 0x2E, 0x61, 0xB6,0xE8, 0x5C, 0x48, 0xA6, 0x62, 0x90, 0x76, 0x3C, 0x6B, 0x13, 0x77, 0xEB, 0x91, 0xD9, 0x5F, 0xB8, 0x0C, 0xB3, 0x8F, 0xE2, 0x96, 0x40, 0xDA, 0x1E, 0x45, 0x30, 0xB8, 0xAE, 0x66, 0x04, 0xBB, 0xB1,0x52, 0xD9, 0x9C, 0x20, 0xD4, 0xF1, 0x0F, 0xAF, 0x37, 0xDD, 0x10, 0x56, 0x34, 0x09, 0x49, 0xCF, 0x9D, 0x4B, 0x3A, 0x0C, 0xF7, 0xCB, 0xB2, 0xA5, 0x0A, 0xEE, 0x26, 0x03, 0x1A, 0x10, 0x02, 0xCC,0xAE, 0x40, 0x25, 0xE1, 0x01, 0xA7, 0x63, 0xB0 }; //Only debug #include <cryptuiapi.h> #pragma comment (lib, "cryptui.lib") using namespace intercept::types; typedef struct { LPWSTR lpszProgramName; LPWSTR lpszPublisherLink; LPWSTR lpszMoreInfoLink; } SPROG_PUBLISHERINFO, *PSPROG_PUBLISHERINFO; template <class T, auto D> class ManagedObject { public: T obj = nullptr; ManagedObject() = default; ManagedObject(T s) : obj(s) {} ~ManagedObject() { if (!obj) return; //Special case for CertCloseStore if constexpr (std::is_invocable_v<decltype(D), T, DWORD>) D(obj, 0); else D(obj); } T operator->() { return obj; } T* operator&() { return &obj; } T& operator*() { return *obj; } operator T() { return obj; } ManagedObject& operator=(T* s) { obj = s; return *this; } }; thread_local intercept::cert::signing::security_class intercept::cert::current_security_class = intercept::cert::signing::security_class::not_signed; std::pair<intercept::cert::signing::security_class, std::optional<std::string>> intercept::cert::signing::verifyCert(std::wstring_view file_path, types::r_string ca_cert) { ManagedObject<HCERTSTORE, CertCloseStore> hStore; ManagedObject<HCRYPTMSG, CryptMsgClose> hMsg; DWORD dwEncoding, dwContentType, dwFormatType; DWORD dwSignerInfo; CERT_INFO CertInfo; //file_path = file_path.substr(4); BOOL fResult = CryptQueryObject(CERT_QUERY_OBJECT_FILE, file_path.data(), CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED, CERT_QUERY_FORMAT_FLAG_BINARY, 0, &dwEncoding, &dwContentType, &dwFormatType, &hStore, &hMsg, nullptr); if (!fResult) return {security_class::not_signed, fmt::format("CryptQueryObject failed: {}", GetLastError())}; // Get signer information size. fResult = CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM, 0, nullptr, &dwSignerInfo); if (!fResult) { auto errmsg = fmt::format("CryptMsgGetParam failed: {}", GetLastError()); return {security_class::not_signed, errmsg}; } // Allocate memory for signer information. ManagedObject<PCMSG_SIGNER_INFO, LocalFree> pSignerInfo = static_cast<PCMSG_SIGNER_INFO>(LocalAlloc(LPTR, dwSignerInfo)); if (!pSignerInfo) { return {security_class::not_signed, "LocalAlloc for signerInfo failed"}; } // Get Signer Information. fResult = CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM, 0, static_cast<PVOID>(pSignerInfo), &dwSignerInfo); if (!fResult) { auto errmsg = fmt::format("CryptMsgGetParam failed: {}", GetLastError()); return {security_class::not_signed, "LocalAlloc for signerInfo failed"}; } // Search for the signer certificate in the temporary // certificate store. CertInfo.Issuer = pSignerInfo->Issuer; CertInfo.SerialNumber = pSignerInfo->SerialNumber; //create in-memory CertStore to hold our CA ManagedObject<HCERTSTORE, CertCloseStore> hMemoryStore = CertOpenStore(CERT_STORE_PROV_MEMORY, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, NULL, 0, nullptr); if (!hMemoryStore) { auto errmsg = fmt::format("CertOpenStore failed: {}", GetLastError()); return {security_class::not_signed, errmsg}; } std::vector<unsigned char> data; data.resize(ca_cert.length()*2); //should be enough to store the decoded string DWORD derPubKeyLen = 2048; //This can fail if the key is invalid. But it can be invalid and still be signed with core key if (ca_cert.length() != 0 && CryptStringToBinaryA(ca_cert.data(), 0, CRYPT_STRING_BASE64HEADER, data.data(), &derPubKeyLen, nullptr, nullptr)) { ManagedObject<PCCERT_CONTEXT, CertFreeCertificateContext> ct = CertCreateCertificateContext(PKCS_7_ASN_ENCODING | X509_ASN_ENCODING, data.data(), derPubKeyLen); //auto lastError = GetLastError(); //CRYPT_E_EXISTS //E_INVALIDARG //Don't care if this errors. The key cert won't land in the store and chain building will fail. CertAddCertificateContextToStore( hMemoryStore, ct, CERT_STORE_ADD_ALWAYS, nullptr ); } //Add the core cert ManagedObject<PCCERT_CONTEXT, CertFreeCertificateContext> ct = CertCreateCertificateContext(PKCS_7_ASN_ENCODING | X509_ASN_ENCODING, coreCACert, sizeof(coreCACert)); CertAddCertificateContextToStore( hMemoryStore, ct, CERT_STORE_ADD_ALWAYS, nullptr ); debug_certs_in_store(hMemoryStore); debug_certs_in_store(hStore); ManagedObject<PCCERT_CONTEXT, CertFreeCertificateContext> pCertContext = CertFindCertificateInStore(hStore, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0, CERT_FIND_SUBJECT_CERT, static_cast<PVOID>(&CertInfo), nullptr); if (!pCertContext) { auto errmsg = fmt::format("CertFindCertificateInStore failed: {}", GetLastError()); return {security_class::not_signed, errmsg}; } ManagedObject<PCCERT_CHAIN_CONTEXT, CertFreeCertificateChain> chainContext; CERT_ENHKEY_USAGE EnhkeyUsage; CERT_USAGE_MATCH CertUsage; CERT_CHAIN_PARA ChainPara; EnhkeyUsage.cUsageIdentifier = 0; EnhkeyUsage.rgpszUsageIdentifier = nullptr; CertUsage.dwType = USAGE_MATCH_TYPE_AND; CertUsage.Usage = EnhkeyUsage; ChainPara.cbSize = sizeof(CERT_CHAIN_PARA); ChainPara.RequestedUsage = CertUsage; CERT_CHAIN_ENGINE_CONFIG ChainConfig; //- sizeof(DWORD) removes WIN8 only flag(dwExclusiveFlags) and makes this win7 compatible ChainConfig.cbSize = 80; //Hardcoded sizeof(CERT_CHAIN_ENGINE_CONFIG) for Win7 ChainConfig.hRestrictedRoot = nullptr; ChainConfig.hRestrictedTrust = nullptr; ChainConfig.hRestrictedOther = nullptr; ChainConfig.cAdditionalStore = 0; ChainConfig.rghAdditionalStore = nullptr; ChainConfig.dwFlags = CERT_CHAIN_CACHE_END_CERT; ChainConfig.dwUrlRetrievalTimeout = 0; ChainConfig.MaximumCachedCertificates = 0; ChainConfig.CycleDetectionModulus = 0; ChainConfig.hExclusiveRoot = hMemoryStore; ChainConfig.hExclusiveTrustedPeople = hMemoryStore; HCERTCHAINENGINE hChainEngine; const auto ret4 = CertCreateCertificateChainEngine( &ChainConfig, &hChainEngine); //auto err = GetLastError(); if (!ret4) { auto errmsg = fmt::format("CertCreateCertificateChainEngine failed: {}", GetLastError()); return {security_class::not_signed, errmsg}; } const auto ret = CertGetCertificateChain( hChainEngine, pCertContext, nullptr, hStore, //Has to be here so we can find intermediaries that are included in the plugins cert &ChainPara, CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT, nullptr, &chainContext ); //chainContext.TrustStatus.dwErrorStatus should be 0x20 for CERT_TRUST_IS_UNTRUSTED_ROOT which is correct AUTHENTICODE_EXTRA_CERT_CHAIN_POLICY_PARA policy2 = { sizeof(policy2) }; policy2.dwRegPolicySettings = 0; policy2.pSignerInfo = pSignerInfo; AUTHENTICODE_EXTRA_CERT_CHAIN_POLICY_STATUS status2 = { sizeof(status2) }; CERT_CHAIN_POLICY_PARA policy = { sizeof(policy) }; policy.pvExtraPolicyPara = &policy2; CERT_CHAIN_POLICY_STATUS status = { sizeof(status) }; status.pvExtraPolicyStatus = &status2; const BOOL verified = CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_BASE,//CERT_CHAIN_POLICY_AUTHENTICODE, chainContext, &policy, &status); if (!chainContext) return {security_class::not_signed, "CertVerifyCertificateChainPolicy failed to create chainContext"}; if (!verified) return {security_class::not_signed, "CertVerifyCertificateChainPolicy failed to verify"}; bool coreSigned = false; //If chain has more than a single element, grab the root cert and compare to our core CA if (chainContext->cChain >= 1 && chainContext->rgpChain[chainContext->cChain - 1]->cElement > 1) { auto CAContext = chainContext->rgpChain[chainContext->cChain - 1]->rgpElement[chainContext->rgpChain[chainContext->cChain - 1]->cElement - 1]->pCertContext; if (CAContext && ct && ct->cbCertEncoded == CAContext->cbCertEncoded) { //Check if the CA of this plugin matches the core CA coreSigned = std::memcmp(CAContext->pbCertEncoded, ct->pbCertEncoded, ct->cbCertEncoded) == 0; } } std::pair<security_class, std::optional<std::string>> returnCode = {security_class::not_signed, std::nullopt}; switch (status.dwError) { case 0x0: { returnCode.first = coreSigned ? security_class::core : security_class::self_signed; } break; case CRYPT_E_NO_REVOCATION_CHECK: { //No revocation list for cert if (chainContext->rgpChain[chainContext->cChain - 1]->cElement > 1 //have found parent cert && chainContext->rgpChain[chainContext->cChain - 1]->rgpElement[1]->pRevocationInfo //has revocation info && chainContext->rgpChain[chainContext->cChain - 1]->rgpElement[1]->pRevocationInfo->pCrlInfo //has CRL! ) { //parent has CRL but you don't! //#TODO warn } returnCode.first = coreSigned ? security_class::core : security_class::self_signed; } break; case CERT_E_REVOCATION_FAILURE: case CRYPT_E_REVOCATION_OFFLINE: returnCode.first = coreSigned ? security_class::core : security_class::self_signed; break; case CRYPT_E_REVOKED: //cert actively revoked returnCode.first = security_class::not_signed; returnCode.second = "Certificate Revoked"; break; case CERT_E_CHAINING: //Couldn't build chain returnCode.first = security_class::not_signed; returnCode.second = "Couldn't build chain"; break; } return returnCode; } /* #include "Windows.h" #include <future> typedef void*(NTAPI *rtl)(_In_ PVOID PcValue, _Out_ PVOID * BaseOfImage); extern "C" __declspec(dllexport) void myFunc() { HMODULE hmod; //RtlPcToFileHeader if (auto pcToHeader = GetProcAddress(GetModuleHandle(L"ntdll"), "RtlPcToFileHeader"); pcToHeader) { if (reinterpret_cast<rtl>(pcToHeader)(_ReturnAddress(), (void**)&hmod)) { char sz[MAX_PATH]; if (GetModuleFileNameA(hmod, sz, MAX_PATH)) { OutputDebugStringA(sz); } } } } */ void intercept::cert::signing::debug_certs_in_store([[maybe_unused]] HCERTSTORE store) { #ifdef __DEBUG PCCERT_CONTEXT pCertContextx = nullptr; while (pCertContextx = CertEnumCertificatesInStore(store, pCertContextx)) { CryptUIDlgViewContext(CERT_STORE_CERTIFICATE_CONTEXT, pCertContextx, nullptr, nullptr, 0, nullptr); } #endif } #else std::pair<intercept::cert::signing::security_class, std::optional<std::string>> intercept::cert::signing::verifyCert(std::wstring_view, types::r_string) { return {security_class::core, std::nullopt}; } void intercept::cert::signing::debug_certs_in_store(void*) {} #endif
56.215789
203
0.669787
[ "vector" ]
78be90fdc237912b6e3dca019f9b1f4e8940c560
9,070
cpp
C++
src/gui/qgsdatasourceselectdialog.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/gui/qgsdatasourceselectdialog.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/gui/qgsdatasourceselectdialog.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
1
2021-12-25T08:40:30.000Z
2021-12-25T08:40:30.000Z
/*************************************************************************** qgsdatasourceselectdialog.cpp - QgsDataSourceSelectDialog --------------------- begin : 1.11.2018 copyright : (C) 2018 by Alessandro Pasotti email : elpaso@itopen.it *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "qgsdatasourceselectdialog.h" #include "ui_qgsdatasourceselectdialog.h" #include "qgis.h" #include "qgsbrowsermodel.h" #include "qgsgui.h" #include "qgsguiutils.h" #include "qgssettings.h" #include <QPushButton> #include <QMenu> QgsDataSourceSelectDialog::QgsDataSourceSelectDialog( QgsBrowserModel *browserModel, bool setFilterByLayerType, const QgsMapLayerType &layerType, QWidget *parent ) : QDialog( parent ) { if ( ! browserModel ) { mBrowserModel = qgis::make_unique<QgsBrowserModel>(); mBrowserModel->initialize(); mOwnModel = true; } else { mBrowserModel.reset( browserModel ); mOwnModel = false; } setupUi( this ); setWindowTitle( tr( "Select a Data Source" ) ); QgsGui::enableAutoGeometryRestore( this ); mBrowserProxyModel.setBrowserModel( mBrowserModel.get() ); mBrowserTreeView->setHeaderHidden( true ); if ( setFilterByLayerType ) { // This will also set the (proxy) model setLayerTypeFilter( layerType ); } else { mBrowserTreeView->setModel( &mBrowserProxyModel ); buttonBox->button( QDialogButtonBox::StandardButton::Ok )->setEnabled( false ); } mBrowserTreeView->setBrowserModel( mBrowserModel.get() ); mWidgetFilter->hide(); mLeFilter->setPlaceholderText( tr( "Type here to filter visible items…" ) ); // icons from http://www.fatcow.com/free-icons License: CC Attribution 3.0 QMenu *menu = new QMenu( this ); menu->setSeparatorsCollapsible( false ); mBtnFilterOptions->setMenu( menu ); QAction *action = new QAction( tr( "Case Sensitive" ), menu ); action->setData( "case" ); action->setCheckable( true ); action->setChecked( false ); connect( action, &QAction::toggled, this, &QgsDataSourceSelectDialog::setCaseSensitive ); menu->addAction( action ); QActionGroup *group = new QActionGroup( menu ); action = new QAction( tr( "Filter Pattern Syntax" ), group ); action->setSeparator( true ); menu->addAction( action ); action = new QAction( tr( "Normal" ), group ); action->setData( QgsBrowserProxyModel::Normal ); action->setCheckable( true ); action->setChecked( true ); menu->addAction( action ); action = new QAction( tr( "Wildcard(s)" ), group ); action->setData( QgsBrowserProxyModel::Wildcards ); action->setCheckable( true ); menu->addAction( action ); action = new QAction( tr( "Regular Expression" ), group ); action->setData( QgsBrowserProxyModel::RegularExpression ); action->setCheckable( true ); menu->addAction( action ); mBrowserTreeView->setExpandsOnDoubleClick( false ); connect( mActionRefresh, &QAction::triggered, this, [ = ] { refreshModel( QModelIndex() ); } ); connect( mBrowserTreeView, &QgsBrowserTreeView::clicked, this, &QgsDataSourceSelectDialog::onLayerSelected ); connect( mActionCollapse, &QAction::triggered, mBrowserTreeView, &QgsBrowserTreeView::collapseAll ); connect( mActionShowFilter, &QAction::triggered, this, &QgsDataSourceSelectDialog::showFilterWidget ); connect( mLeFilter, &QgsFilterLineEdit::returnPressed, this, &QgsDataSourceSelectDialog::setFilter ); connect( mLeFilter, &QgsFilterLineEdit::cleared, this, &QgsDataSourceSelectDialog::setFilter ); connect( mLeFilter, &QgsFilterLineEdit::textChanged, this, &QgsDataSourceSelectDialog::setFilter ); connect( group, &QActionGroup::triggered, this, &QgsDataSourceSelectDialog::setFilterSyntax ); mBrowserToolbar->setIconSize( QgsGuiUtils::iconSize( true ) ); if ( QgsSettings().value( QStringLiteral( "datasourceSelectFilterVisible" ), false, QgsSettings::Section::Gui ).toBool() ) { mActionShowFilter->trigger(); } } QgsDataSourceSelectDialog::~QgsDataSourceSelectDialog() { if ( ! mOwnModel ) mBrowserModel.release(); } void QgsDataSourceSelectDialog::showEvent( QShowEvent *e ) { QDialog::showEvent( e ); QString lastSelectedPath( QgsSettings().value( QStringLiteral( "datasourceSelectLastSelectedItem" ), QString(), QgsSettings::Section::Gui ).toString() ); if ( ! lastSelectedPath.isEmpty() ) { QModelIndexList items = mBrowserProxyModel.match( mBrowserProxyModel.index( 0, 0 ), QgsBrowserModel::PathRole, QVariant::fromValue( lastSelectedPath ), 1, Qt::MatchRecursive ); if ( items.count( ) > 0 ) { QModelIndex expandIndex = items.at( 0 ); if ( expandIndex.isValid() ) { mBrowserTreeView->scrollTo( expandIndex, QgsBrowserTreeView::ScrollHint::PositionAtTop ); mBrowserTreeView->expand( expandIndex ); } } } } void QgsDataSourceSelectDialog::showFilterWidget( bool visible ) { QgsSettings().setValue( QStringLiteral( "datasourceSelectFilterVisible" ), visible, QgsSettings::Section::Gui ); mWidgetFilter->setVisible( visible ); if ( ! visible ) { mLeFilter->setText( QString() ); setFilter(); } else { mLeFilter->setFocus(); } } void QgsDataSourceSelectDialog::setFilter() { QString filter = mLeFilter->text(); mBrowserProxyModel.setFilterString( filter ); } void QgsDataSourceSelectDialog::refreshModel( const QModelIndex &index ) { QgsDataItem *item = mBrowserModel->dataItem( index ); if ( item ) { QgsDebugMsg( "path = " + item->path() ); } else { QgsDebugMsg( QStringLiteral( "invalid item" ) ); } if ( item && ( item->capabilities2() & QgsDataItem::Fertile ) ) { mBrowserModel->refresh( index ); } for ( int i = 0; i < mBrowserModel->rowCount( index ); i++ ) { QModelIndex idx = mBrowserModel->index( i, 0, index ); QModelIndex proxyIdx = mBrowserProxyModel.mapFromSource( idx ); QgsDataItem *child = mBrowserModel->dataItem( idx ); // Check also expanded descendants so that the whole expanded path does not get collapsed if one item is collapsed. // Fast items (usually root items) are refreshed so that when collapsed, it is obvious they are if empty (no expand symbol). if ( mBrowserTreeView->isExpanded( proxyIdx ) || mBrowserTreeView->hasExpandedDescendant( proxyIdx ) || ( child && child->capabilities2() & QgsDataItem::Fast ) ) { refreshModel( idx ); } else { if ( child && ( child->capabilities2() & QgsDataItem::Fertile ) ) { child->depopulate(); } } } } void QgsDataSourceSelectDialog::setFilterSyntax( QAction *action ) { if ( !action ) return; mBrowserProxyModel.setFilterSyntax( static_cast< QgsBrowserProxyModel::FilterSyntax >( action->data().toInt() ) ); } void QgsDataSourceSelectDialog::setCaseSensitive( bool caseSensitive ) { mBrowserProxyModel.setFilterCaseSensitivity( caseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive ); } void QgsDataSourceSelectDialog::setLayerTypeFilter( QgsMapLayerType layerType ) { mBrowserProxyModel.setFilterByLayerType( true ); mBrowserProxyModel.setLayerType( layerType ); // reset model and button mBrowserTreeView->setModel( &mBrowserProxyModel ); buttonBox->button( QDialogButtonBox::StandardButton::Ok )->setEnabled( false ); } QgsMimeDataUtils::Uri QgsDataSourceSelectDialog::uri() const { return mUri; } void QgsDataSourceSelectDialog::onLayerSelected( const QModelIndex &index ) { bool isLayerCompatible = false; mUri = QgsMimeDataUtils::Uri(); if ( index.isValid() ) { const QgsDataItem *dataItem( mBrowserProxyModel.dataItem( index ) ); if ( dataItem ) { const QgsLayerItem *layerItem = qobject_cast<const QgsLayerItem *>( dataItem ); if ( layerItem && ( ! mBrowserProxyModel.filterByLayerType() || ( layerItem->mapLayerType() == mBrowserProxyModel.layerType() ) ) ) { isLayerCompatible = true; mUri = layerItem->mimeUri(); // Store last viewed item QgsSettings().setValue( QStringLiteral( "datasourceSelectLastSelectedItem" ), mBrowserProxyModel.data( index, QgsBrowserModel::PathRole ).toString(), QgsSettings::Section::Gui ); } } } buttonBox->button( QDialogButtonBox::StandardButton::Ok )->setEnabled( isLayerCompatible ); }
34.618321
187
0.65645
[ "model" ]
78bfe0440946c6a8036687db6015601622948eeb
11,893
cpp
C++
RoguelikeGame.Main/Engine/UI/ListSelect.cpp
VegetaTheKing/RoguelikeGame
74036ad8857da961a490dd73d8bb2a5fbef88e39
[ "MIT" ]
null
null
null
RoguelikeGame.Main/Engine/UI/ListSelect.cpp
VegetaTheKing/RoguelikeGame
74036ad8857da961a490dd73d8bb2a5fbef88e39
[ "MIT" ]
null
null
null
RoguelikeGame.Main/Engine/UI/ListSelect.cpp
VegetaTheKing/RoguelikeGame
74036ad8857da961a490dd73d8bb2a5fbef88e39
[ "MIT" ]
null
null
null
#include "ListSelect.h" void ListSelect::UpdateArrowsState() { if (_selectedIndex == 0) _leftArrow.ForceState("click"); else _leftArrow.ResetForcedState(); if (_selectedIndex + 1 >= _values.size()) _rightArrow.ForceState("click"); else _rightArrow.ResetForcedState(); } ListSelect::ListSelect(SoundsManager* sounds, TexturesManager* textures) { _soundsManager = sounds; _texturesManager = textures; _selectedIndex = 0; _values.clear(); _leftArrow.SetSoundsManager(_soundsManager); _leftArrow.SetTexturesManager(_texturesManager); _rightArrow.SetSoundsManager(_soundsManager); _rightArrow.SetTexturesManager(_texturesManager); _currSelectionLabel.SetSoundsManager(_soundsManager); _currSelectionLabel.SetTexturesManager(_texturesManager); _leftArrow.SetMouseInput(true); _rightArrow.SetMouseInput(true); _leftArrow.SetKeyboardInput(true); _rightArrow.SetKeyboardInput(true); } ListSelect::ListSelect(ListSelect& other) : UIElement(other), _leftArrow(other._leftArrow), _rightArrow(other._rightArrow), _currSelectionLabel(other._currSelectionLabel) { _selectedIndex = other._selectedIndex; _values = other._values; } void ListSelect::AddLeftArrowState(const std::string& name, const std::string& textureName, const sf::FloatRect& rect) { _leftArrow.AddState(name, _dummyText, textureName, rect); } void ListSelect::RemoveLeftArrowState(const std::string& name) { _leftArrow.RemoveState(name); } void ListSelect::SetLeftArrowSize(const sf::Vector2f& size) { _leftArrow.Init(sf::Vector2u((uint32_t)ceilf(size.x), (uint32_t)ceilf(size.y))); _leftArrow.SetBackgroundSize(size); } sf::Transformable* ListSelect::TransformLeftArrow() { _sthChanged = true; return (sf::Transformable*)&_leftArrow; } void ListSelect::AddRightArrowState(const std::string& name, const std::string& textureName, const sf::FloatRect& rect) { _rightArrow.AddState(name, _dummyText, textureName, rect); } void ListSelect::RemoveRightArrowState(const std::string& name) { _rightArrow.RemoveState(name); } void ListSelect::SetRightArrowSize(const sf::Vector2f& size) { _rightArrow.Init(sf::Vector2u((uint32_t)ceilf(size.x), (uint32_t)ceilf(size.y))); _rightArrow.SetBackgroundSize(size); } sf::Transformable* ListSelect::TransformRightArrow() { _sthChanged = true; return (sf::Transformable*)&_rightArrow; } void ListSelect::SetTextSize(const sf::Vector2f& size) { _currSelectionLabel.Init(sf::Vector2u((uint32_t)ceilf(size.x), (uint32_t)ceilf(size.y))); } void ListSelect::SetFont(const sf::Font& font) { _currSelectionLabel.SetFont(font); } void ListSelect::SetCharacterSize(uint32_t size) { _currSelectionLabel.SetCharacterSize(size); } void ListSelect::SetLetterSpacing(float spacing) { _currSelectionLabel.SetLetterSpacing(spacing); } void ListSelect::SetStyle(uint32_t style) { _currSelectionLabel.SetStyle(style); } void ListSelect::SetFillColor(const sf::Color& color) { _currSelectionLabel.SetFillColor(color); } void ListSelect::SetOutlineColor(const sf::Color& color) { _currSelectionLabel.SetOutlineColor(color); } void ListSelect::SetOutlineThickness(float thickness) { _currSelectionLabel.SetOutlineThickness(thickness); } void ListSelect::SetVerticalAlignment(UIElement::Align align) { _currSelectionLabel.SetVerticalAlignment(align); } void ListSelect::SetHorizontalAlignment(UIElement::Align align) { _currSelectionLabel.SetHorizontalAlignment(align); } sf::Transformable* ListSelect::TransformText() { return &_currSelectionLabel; } void ListSelect::AddValue(const std::string& value) { _values.push_back(value); if (_values.size() == 1) SetCurrentIndex(0); UpdateArrowsState(); _sthChanged = true; } void ListSelect::RemoveValue(size_t index) { if (_selectedIndex >= index) { if(_selectedIndex == index) _sthChanged = true; if (_selectedIndex > 0) _selectedIndex--; } if (index < _values.size()) _values.erase(_values.begin() + index); UpdateArrowsState(); } void ListSelect::ClearValues() { _selectedIndex = 0; _values.clear(); UpdateArrowsState(); _sthChanged = true; } void ListSelect::SetCurrentIndex(size_t index) { if (index < _values.size()) { if (_selectedIndex != index) { _selectedIndex = index; UpdateArrowsState(); _sthChanged = true; } } } void ListSelect::NextSelection() { if (_selectedIndex < _values.size() - 1) { _selectedIndex++; UpdateArrowsState(); _sthChanged = true; } } void ListSelect::PreviousSelection() { if (_selectedIndex > 0) { _selectedIndex--; UpdateArrowsState(); _sthChanged = true; } } const sf::Font* ListSelect::GetFont() const { return _currSelectionLabel.GetFont(); } uint32_t ListSelect::GetCharacterSize() const { return _currSelectionLabel.GetCharacterSize(); } float ListSelect::GetLetterSpacing() const { return _currSelectionLabel.GetLetterSpacing(); } uint32_t ListSelect::GetStyle() const { return _currSelectionLabel.GetStyle(); } const sf::Color& ListSelect::GetFillColor() const { return _currSelectionLabel.GetFillColor(); } const sf::Color& ListSelect::GetOutlineColor() const { return _currSelectionLabel.GetOutlineColor(); } float ListSelect::GetOutlineThickness() const { return _currSelectionLabel.GetOutlineThickness(); } UIElement::Align ListSelect::GetVerticalAlignment() const { return _currSelectionLabel.GetVerticalAlignment(); } UIElement::Align ListSelect::GetHorizontalAlignment() const { return _currSelectionLabel.GetHorizontalAlignment(); } std::string ListSelect::GetCurrentValue() const { if (_values.size() == 0 || _selectedIndex >= _values.size()) return std::string(); return _values[_selectedIndex]; } size_t ListSelect::GetCurrentIndex() const { return _selectedIndex; } size_t ListSelect::GetValuesSize() const { return _values.size(); } const std::vector<std::string>& ListSelect::GetValues() const { return _values; } UIElement* ListSelect::clone() { return new ListSelect(*this); } void ListSelect::Update(bool tick, float delta) { if (_values.size() == 0 || _selectedIndex >= _values.size()) _currSelectionLabel.SetText(""); else _currSelectionLabel.SetText(_values[_selectedIndex]); _leftArrow.Update(tick, delta); _rightArrow.Update(tick, delta); _currSelectionLabel.Update(tick, delta); Redraw(); } void ListSelect::ForceRedraw() { _leftArrow.ForceRedraw(); _rightArrow.ForceRedraw(); _currSelectionLabel.ForceRedraw(); Redraw(); } bool ListSelect::Redraw() { if (_leftArrow.RedrawHappened() || _rightArrow.RedrawHappened() || _currSelectionLabel.RedrawHappened()) _sthChanged = true; if (_sthChanged == true) { _render.clear(sf::Color::Transparent); sf::VertexArray element(sf::PrimitiveType::Quads, 4); sf::RenderStates rs; for (unsigned short i = 0; i < 3; i++) { const sf::RenderTexture* tex = nullptr; sf::Vector2f pos = sf::Vector2f(0.f, 0.f); if (i == 0) { tex = _leftArrow.GetTexture(); pos = _leftArrow.getPosition(); } else if (i == 1) { tex = _rightArrow.GetTexture(); pos = _rightArrow.getPosition(); } else { tex = _currSelectionLabel.GetTexture(); pos = _currSelectionLabel.getPosition(); } auto sizeU = tex->getSize(); auto size = sf::Vector2f(float(sizeU.x), float(sizeU.y)); rs.texture = &tex->getTexture(); element[0].position = sf::Vector2f(pos.x, pos.y); element[1].position = sf::Vector2f(pos.x + size.x, pos.y); element[2].position = sf::Vector2f(pos.x + size.x, pos.y + size.y); element[3].position = sf::Vector2f(pos.x, pos.y + size.y); element[0].texCoords = sf::Vector2f(0.f, 0.f); element[1].texCoords = sf::Vector2f(size.x, 0.f); element[2].texCoords = sf::Vector2f(size.x, size.y); element[3].texCoords = sf::Vector2f(0.f, size.y); _render.draw(element, rs); } _render.display(); _sthChanged = false; _redrawHappened = true; return true; } return false; } void ListSelect::ProcessEvent(sf::Event* ev, const sf::Vector2f& mousePos) { auto relMouse = getTransform().getInverse().transformPoint(mousePos); _leftArrow.ProcessEvent(ev, relMouse); _rightArrow.ProcessEvent(ev, relMouse); _currSelectionLabel.ProcessEvent(ev, relMouse); if (_mouseInput) { if (ev->type == sf::Event::MouseButtonPressed && _leftArrow.GetGlobalBounds().contains(relMouse) == false) _leftArrow.SetInFocus(false); if (ev->type == sf::Event::MouseButtonPressed && _rightArrow.GetGlobalBounds().contains(relMouse) == false)_rightArrow.SetInFocus(false); } if (_keyboardInput) { if (_inFocus) { if (ev->type == sf::Event::KeyPressed && ev->key.code == sf::Keyboard::Left) { sf::Event e; e.type = sf::Event::KeyPressed; e.key.code = sf::Keyboard::Enter; _leftArrow.SetInFocus(true); _leftArrow.ProcessEvent(&e, sf::Vector2f(0.f, 0.f)); } else if (ev->type == sf::Event::KeyPressed && ev->key.code == sf::Keyboard::Right) { sf::Event e; e.type = sf::Event::KeyPressed; e.key.code = sf::Keyboard::Enter; _rightArrow.SetInFocus(true); _rightArrow.ProcessEvent(&e, sf::Vector2f(0.f, 0.f)); } if (ev->type == sf::Event::KeyReleased && (ev->key.code == sf::Keyboard::Left || ev->key.code == sf::Keyboard::Right)) { sf::Event e; e.type = sf::Event::KeyReleased; e.key.code = sf::Keyboard::Enter; _leftArrow.ProcessEvent(&e, sf::Vector2f(0.f, 0.f)); _rightArrow.ProcessEvent(&e, sf::Vector2f(0.f, 0.f)); _leftArrow.SetInFocus(false); _rightArrow.SetInFocus(false); } } } if (_leftArrow.Clicked()) PreviousSelection(); if (_rightArrow.Clicked()) NextSelection(); } std::vector<sf::Vector2f> ListSelect::GetAllBoundsPoints() const { std::vector<sf::Vector2f> output = UIElement::GetAllBoundsPoints(); auto la = _leftArrow.GetAllBoundsPoints(); auto ra = _rightArrow.GetAllBoundsPoints(); auto lab = _currSelectionLabel.GetAllBoundsPoints(); output.insert(output.end(), std::make_move_iterator(la.begin()), std::make_move_iterator(la.end())); output.insert(output.end(), std::make_move_iterator(ra.begin()), std::make_move_iterator(ra.end())); output.insert(output.end(), std::make_move_iterator(lab.begin()), std::make_move_iterator(lab.end())); for (size_t i = 4; i < output.size(); i++) output[i] = getTransform().transformPoint(output[i]); return output; } std::vector<sf::Vector2f> ListSelect::GetDeepestInFocusBoundsPoints() const { std::vector<sf::Vector2f> output; if (_leftArrow.GetInFocus() == true) output = _leftArrow.GetAllBoundsPoints(); else if (_rightArrow.GetInFocus() == true) output = _rightArrow.GetAllBoundsPoints(); if (output.size() == 0) output = UIElement::GetAllBoundsPoints(); else for (auto& p : output) p = getTransform().transformPoint(p); return output; }
27.787383
170
0.654082
[ "vector" ]
78c6829cf17e25991b319b02f1aaf70f7c9237b1
6,416
cpp
C++
iris-cpp/src/iris/gen/AttributeGenerator.cpp
wbknez/iris
ac6f8ca57cec88a24bdf22eca42e2c77a53f4cd0
[ "Apache-2.0" ]
null
null
null
iris-cpp/src/iris/gen/AttributeGenerator.cpp
wbknez/iris
ac6f8ca57cec88a24bdf22eca42e2c77a53f4cd0
[ "Apache-2.0" ]
null
null
null
iris-cpp/src/iris/gen/AttributeGenerator.cpp
wbknez/iris
ac6f8ca57cec88a24bdf22eca42e2c77a53f4cd0
[ "Apache-2.0" ]
null
null
null
#include "iris/gen/AttributeGenerator.hpp" #include <cmath> #include <random> #include <sstream> #include "iris/Utils.hpp" namespace iris { namespace gen { types::uint32 convertListToInteger(const Uint32List& list) { using namespace iris::types; uint32 result = 0; uint32 scaleFactor = list.size() - 1; for(Uint32List::size_type i = 0; i < list.size(); i++) { const auto exponent = scaleFactor - i; result += list[i] * (uint32)std::pow(10, exponent); } return result; } std::string convertListToString(const Uint32List& list) { using namespace iris; std::ostringstream stream; for(Uint32List::size_type i = 0; i < list.size(); i++) { stream << list[i]; } return stream.str(); } Uint32List createAttributeList(PopDispensers& dispensers, types::mersenne_twister& random) { Uint32List result(dispensers.size()); for(Uint32List::size_type i = 0; i < dispensers.size(); i++) { const auto indice = dispensers[i].nextGroup(random); result[i] = indice; } return result; } PopDispensers createPopulationDispensers(Uint32List vars, AgentID totalAgents) { typedef std::vector<types::fnumeric> Factors; PopDispensers result; // So, each value in the list represents the number of factors. We // use equal probability for all factors, so the probability of each // is 1/f per indice. for(Uint32List::size_type i = 0; i < vars.size(); i++) { const auto currentFactor = vars[i]; const types::fnumeric prob = ((types::fnumeric)1) / currentFactor; PopulationDispenser disp; // The factored probabilities. Factors factors(currentFactor); // Fill up the factor probability. std::fill(factors.begin(), factors.end(), prob); // Set it up. disp.initialize(factors, totalAgents, true); // Done. result.push_back(disp); } return result; } Uint32List createSubAttributeList(const Uint32List& base, const Uint32List& target) { if(base.size() < target.size()) { // This should be caught by the IO parser. throw std::runtime_error("Base size is smaller than target!"); } return {base.begin(), base.begin() + target.size()}; } void generateAttributes(Agent* const agents, AgentID totalAgents, ValueList values, BehaviorList behaviors, types::mersenne_twister& random) { // Use two population vectors, one for the values and one for the // behaviors. PopDispensers valueDisp = createPopulationDispensers(values, totalAgents); // For each agent, create a new and unique set of values and // behaviors. for(AgentID i = 0; i < totalAgents; i++) { ValueList vList = createAttributeList(valueDisp, random); BehaviorList bList = createSubAttributeList(vList, behaviors); agents[i].setInitialBehavior(bList); agents[i].setInitialValues(vList); } } void generatePowerfulAgents(Agent* const agents, AgentID totalAgents, types::fnumeric powerPercent, bool requireAtLeastOne, types::mersenne_twister& random) { using namespace iris::types; using namespace iris::util; typedef Agent::Network Network; typedef std::uniform_int_distribution<AgentID> UintDist; if(powerPercent == 0.0) { return; } // Compute the number of powerful agents to create. auto numPowerful = (AgentID)std::floor(totalAgents * powerPercent); // If the percentage is so low that it evaluates to zero, then see // what the caller wishes to do. if(numPowerful == 0 && requireAtLeastOne) { numPowerful = 1; } // Random selector. UintDist chooser(0, totalAgents - 1); // The already selected agents. Network selected; for(AgentID i = 0; i < numPowerful; i++) { const auto chosen = ensureRandom<AgentID>(chooser(random), selected, (AgentID)0, totalAgents); agents[chosen].setPowerful(true); util::sortedInsert(selected, chosen); } } PermuteList permuteList(const Uint32List& vars) { auto mutableList = Uint32List(vars.size()); auto permutes = PermuteList(); permuteList(vars, permutes, mutableList, 0); return permutes; } void permuteList(const Uint32List& vars, PermuteList& permutes, Uint32List& mutableList, types::uint32 index) { for(types::uint32 i = 0; i < vars[index]; i++) { mutableList[index] = i; if(index >= (vars.size() - 1)) { const auto value = convertListToString(mutableList); permutes.push_back(value); } else { permuteList(vars, permutes, mutableList, index + 1); } } } } }
33.243523
80
0.479582
[ "vector" ]
78ca61ac9bfbc5405b17f0094e701a8418906f1f
41,148
cpp
C++
LeopardFF8.cpp
net3f/leopard
8c35c8d4de621bf130865456c447815f9cb6f75c
[ "BSD-3-Clause" ]
null
null
null
LeopardFF8.cpp
net3f/leopard
8c35c8d4de621bf130865456c447815f9cb6f75c
[ "BSD-3-Clause" ]
null
null
null
LeopardFF8.cpp
net3f/leopard
8c35c8d4de621bf130865456c447815f9cb6f75c
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2017 Christopher A. Taylor. 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 Leopard-RS nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "LeopardFF8.h" #ifdef LEO_HAS_FF8 #include <string.h> #ifdef _MSC_VER #pragma warning(disable: 4752) // found Intel(R) Advanced Vector Extensions; consider using /arch:AVX #endif namespace leopard { namespace ff8 { //------------------------------------------------------------------------------ // Datatypes and Constants // Basis used for generating logarithm tables static const ffe_t kCantorBasis[kBits] = { 1, 214, 152, 146, 86, 200, 88, 230 }; // Using the Cantor basis {2} here enables us to avoid a lot of extra calculations // when applying the formal derivative in decoding. //------------------------------------------------------------------------------ // Field Operations // z = x + y (mod kModulus) static inline ffe_t AddMod(const ffe_t a, const ffe_t b) { const unsigned sum = static_cast<unsigned>(a) + b; // Partial reduction step, allowing for kModulus to be returned return static_cast<ffe_t>(sum + (sum >> kBits)); } // z = x - y (mod kModulus) static inline ffe_t SubMod(const ffe_t a, const ffe_t b) { const unsigned dif = static_cast<unsigned>(a) - b; // Partial reduction step, allowing for kModulus to be returned return static_cast<ffe_t>(dif + (dif >> kBits)); } //------------------------------------------------------------------------------ // Fast Walsh-Hadamard Transform (FWHT) (mod kModulus) // {a, b} = {a + b, a - b} (Mod Q) static LEO_FORCE_INLINE void FWHT_2(ffe_t& LEO_RESTRICT a, ffe_t& LEO_RESTRICT b) { const ffe_t sum = AddMod(a, b); const ffe_t dif = SubMod(a, b); a = sum; b = dif; } #if defined(LEO_FWHT_OPT) static LEO_FORCE_INLINE void FWHT_4(ffe_t* data) { ffe_t t0 = data[0]; ffe_t t1 = data[1]; ffe_t t2 = data[2]; ffe_t t3 = data[3]; FWHT_2(t0, t1); FWHT_2(t2, t3); FWHT_2(t0, t2); FWHT_2(t1, t3); data[0] = t0; data[1] = t1; data[2] = t2; data[3] = t3; } static LEO_FORCE_INLINE void FWHT_4(ffe_t* data, unsigned s) { unsigned x = 0; ffe_t t0 = data[x]; x += s; ffe_t t1 = data[x]; x += s; ffe_t t2 = data[x]; x += s; ffe_t t3 = data[x]; FWHT_2(t0, t1); FWHT_2(t2, t3); FWHT_2(t0, t2); FWHT_2(t1, t3); unsigned y = 0; data[y] = t0; y += s; data[y] = t1; y += s; data[y] = t2; y += s; data[y] = t3; } // Decimation in time (DIT) version static void FWHT(ffe_t* data, const unsigned bits) { const unsigned n = (1UL << bits); if (n <= 2) { if (n == 2) FWHT_2(data[0], data[1]); return; } for (unsigned i = bits; i > 3; i -= 2) { unsigned m = (1UL << i); unsigned m4 = (m >> 2); for (unsigned r = 0; r < n; r += m) for (unsigned j = 0; j < m4; j++) FWHT_4(data + j + r, m4); } for (unsigned i0 = 0; i0 < n; i0 += 4) FWHT_4(data + i0); } #else // LEO_FWHT_OPT // Reference implementation void FWHT(ffe_t* data, const unsigned bits) { const unsigned size = (unsigned)(1UL << bits); for (unsigned width = 1; width < size; width <<= 1) for (unsigned i = 0; i < size; i += (width << 1)) for (unsigned j = i; j < (width + i); ++j) FWHT_2(data[j], data[j + width]); } #endif // LEO_FWHT_OPT // Transform specialized for the finite field order void FWHT(ffe_t data[kOrder]) { FWHT(data, kBits); } //------------------------------------------------------------------------------ // Logarithm Tables static ffe_t LogLUT[kOrder]; static ffe_t ExpLUT[kOrder]; // Returns a * Log(b) static ffe_t MultiplyLog(ffe_t a, ffe_t log_b) { /* Note that this operation is not a normal multiplication in a finite field because the right operand is already a logarithm. This is done because it moves K table lookups from the Decode() method into the initialization step that is less performance critical. The LogWalsh[] table below contains precalculated logarithms so it is easier to do all the other multiplies in that form as well. */ if (a == 0) return 0; return ExpLUT[AddMod(LogLUT[a], log_b)]; } // Initialize LogLUT[], ExpLUT[] static void InitializeLogarithmTables() { // LFSR table generation: unsigned state = 1; for (unsigned i = 0; i < kModulus; ++i) { ExpLUT[state] = static_cast<ffe_t>(i); state <<= 1; if (state >= kOrder) state ^= kPolynomial; } ExpLUT[0] = kModulus; // Conversion to Cantor basis {2}: LogLUT[0] = 0; for (unsigned i = 0; i < kBits; ++i) { const ffe_t basis = kCantorBasis[i]; const unsigned width = static_cast<unsigned>(1UL << i); for (unsigned j = 0; j < width; ++j) LogLUT[j + width] = LogLUT[j] ^ basis; } for (unsigned i = 0; i < kOrder; ++i) LogLUT[i] = ExpLUT[LogLUT[i]]; // Generate Exp table from Log table: for (unsigned i = 0; i < kOrder; ++i) ExpLUT[LogLUT[i]] = i; // Note: Handles modulus wrap around with LUT ExpLUT[kModulus] = ExpLUT[0]; } //------------------------------------------------------------------------------ // Multiplies /* The multiplication algorithm used follows the approach outlined in {4}. Specifically section 6 outlines the algorithm used here for 8-bit fields. */ struct { LEO_ALIGNED LEO_M128 Value[2]; } static Multiply128LUT[kOrder]; #if defined(LEO_TRY_AVX2) struct { LEO_ALIGNED LEO_M256 Value[2]; } static Multiply256LUT[kOrder]; #endif // LEO_TRY_AVX2 void InitializeMultiplyTables() { // For each value we could multiply by: for (unsigned log_m = 0; log_m < kOrder; ++log_m) { // For each 4 bits of the finite field width in bits: for (unsigned i = 0, shift = 0; i < 2; ++i, shift += 4) { // Construct 16 entry LUT for PSHUFB uint8_t lut[16]; for (ffe_t x = 0; x < 16; ++x) lut[x] = MultiplyLog(x << shift, static_cast<ffe_t>(log_m)); // Store in 128-bit wide table const LEO_M128 *v_ptr = reinterpret_cast<const LEO_M128 *>(&lut[0]); const LEO_M128 value = _mm_loadu_si128(v_ptr); _mm_storeu_si128(&Multiply128LUT[log_m].Value[i], value); // Store in 256-bit wide table #if defined(LEO_TRY_AVX2) if (CpuHasAVX2) { _mm256_storeu_si256(&Multiply256LUT[log_m].Value[i], _mm256_broadcastsi128_si256(value)); } #endif // LEO_TRY_AVX2 } } } void mul_mem( void * LEO_RESTRICT x, const void * LEO_RESTRICT y, ffe_t log_m, uint64_t bytes) { #if defined(LEO_TRY_AVX2) if (CpuHasAVX2) { const LEO_M256 table_lo_y = _mm256_loadu_si256(&Multiply256LUT[log_m].Value[0]); const LEO_M256 table_hi_y = _mm256_loadu_si256(&Multiply256LUT[log_m].Value[1]); const LEO_M256 clr_mask = _mm256_set1_epi8(0x0f); LEO_M256 * LEO_RESTRICT x32 = reinterpret_cast<LEO_M256 *>(x); const LEO_M256 * LEO_RESTRICT y32 = reinterpret_cast<const LEO_M256 *>(y); do { #define LEO_MUL_256(x_ptr, y_ptr) { \ LEO_M256 data = _mm256_loadu_si256(y_ptr); \ LEO_M256 lo = _mm256_and_si256(data, clr_mask); \ lo = _mm256_shuffle_epi8(table_lo_y, lo); \ LEO_M256 hi = _mm256_srli_epi64(data, 4); \ hi = _mm256_and_si256(hi, clr_mask); \ hi = _mm256_shuffle_epi8(table_hi_y, hi); \ _mm256_storeu_si256(x_ptr, _mm256_xor_si256(lo, hi)); } LEO_MUL_256(x32 + 1, y32 + 1); LEO_MUL_256(x32, y32); y32 += 2, x32 += 2; bytes -= 64; } while (bytes > 0); return; } #endif // LEO_TRY_AVX2 const LEO_M128 table_lo_y = _mm_loadu_si128(&Multiply128LUT[log_m].Value[0]); const LEO_M128 table_hi_y = _mm_loadu_si128(&Multiply128LUT[log_m].Value[1]); const LEO_M128 clr_mask = _mm_set1_epi8(0x0f); LEO_M128 * LEO_RESTRICT x16 = reinterpret_cast<LEO_M128 *>(x); const LEO_M128 * LEO_RESTRICT y16 = reinterpret_cast<const LEO_M128 *>(y); do { #define LEO_MUL_128(x_ptr, y_ptr) { \ LEO_M128 data = _mm_loadu_si128(y_ptr); \ LEO_M128 lo = _mm_and_si128(data, clr_mask); \ lo = _mm_shuffle_epi8(table_lo_y, lo); \ LEO_M128 hi = _mm_srli_epi64(data, 4); \ hi = _mm_and_si128(hi, clr_mask); \ hi = _mm_shuffle_epi8(table_hi_y, hi); \ _mm_storeu_si128(x_ptr, _mm_xor_si128(lo, hi)); } LEO_MUL_128(x16 + 3, y16 + 3); LEO_MUL_128(x16 + 2, y16 + 2); LEO_MUL_128(x16 + 1, y16 + 1); LEO_MUL_128(x16, y16); x16 += 4, y16 += 4; bytes -= 64; } while (bytes > 0); } //------------------------------------------------------------------------------ // FFT Operations void fft_butterfly( void * LEO_RESTRICT x, void * LEO_RESTRICT y, ffe_t log_m, uint64_t bytes) { #if defined(LEO_TRY_AVX2) if (CpuHasAVX2) { const LEO_M256 table_lo_y = _mm256_loadu_si256(&Multiply256LUT[log_m].Value[0]); const LEO_M256 table_hi_y = _mm256_loadu_si256(&Multiply256LUT[log_m].Value[1]); const LEO_M256 clr_mask = _mm256_set1_epi8(0x0f); LEO_M256 * LEO_RESTRICT x32 = reinterpret_cast<LEO_M256 *>(x); LEO_M256 * LEO_RESTRICT y32 = reinterpret_cast<LEO_M256 *>(y); do { #define LEO_FFTB_256(x_ptr, y_ptr) { \ LEO_M256 y_data = _mm256_loadu_si256(y_ptr); \ LEO_M256 lo = _mm256_and_si256(y_data, clr_mask); \ lo = _mm256_shuffle_epi8(table_lo_y, lo); \ LEO_M256 hi = _mm256_srli_epi64(y_data, 4); \ hi = _mm256_and_si256(hi, clr_mask); \ hi = _mm256_shuffle_epi8(table_hi_y, hi); \ LEO_M256 x_data = _mm256_loadu_si256(x_ptr); \ x_data = _mm256_xor_si256(x_data, _mm256_xor_si256(lo, hi)); \ y_data = _mm256_xor_si256(y_data, x_data); \ _mm256_storeu_si256(x_ptr, x_data); \ _mm256_storeu_si256(y_ptr, y_data); } LEO_FFTB_256(x32 + 1, y32 + 1); LEO_FFTB_256(x32, y32); y32 += 2, x32 += 2; bytes -= 64; } while (bytes > 0); return; } #endif // LEO_TRY_AVX2 const LEO_M128 table_lo_y = _mm_loadu_si128(&Multiply128LUT[log_m].Value[0]); const LEO_M128 table_hi_y = _mm_loadu_si128(&Multiply128LUT[log_m].Value[1]); const LEO_M128 clr_mask = _mm_set1_epi8(0x0f); LEO_M128 * LEO_RESTRICT x16 = reinterpret_cast<LEO_M128 *>(x); LEO_M128 * LEO_RESTRICT y16 = reinterpret_cast<LEO_M128 *>(y); do { #define LEO_FFTB_128(x_ptr, y_ptr) { \ LEO_M128 y_data = _mm_loadu_si128(y_ptr); \ LEO_M128 lo = _mm_and_si128(y_data, clr_mask); \ lo = _mm_shuffle_epi8(table_lo_y, lo); \ LEO_M128 hi = _mm_srli_epi64(y_data, 4); \ hi = _mm_and_si128(hi, clr_mask); \ hi = _mm_shuffle_epi8(table_hi_y, hi); \ LEO_M128 x_data = _mm_loadu_si128(x_ptr); \ x_data = _mm_xor_si128(x_data, _mm_xor_si128(lo, hi)); \ y_data = _mm_xor_si128(y_data, x_data); \ _mm_storeu_si128(x_ptr, x_data); \ _mm_storeu_si128(y_ptr, y_data); } LEO_FFTB_128(x16 + 3, y16 + 3); LEO_FFTB_128(x16 + 2, y16 + 2); LEO_FFTB_128(x16 + 1, y16 + 1); LEO_FFTB_128(x16, y16); x16 += 4, y16 += 4; bytes -= 64; } while (bytes > 0); } #ifdef LEO_USE_VECTOR4_OPT void fft_butterfly4( void * LEO_RESTRICT x_0, void * LEO_RESTRICT y_0, void * LEO_RESTRICT x_1, void * LEO_RESTRICT y_1, void * LEO_RESTRICT x_2, void * LEO_RESTRICT y_2, void * LEO_RESTRICT x_3, void * LEO_RESTRICT y_3, ffe_t log_m, uint64_t bytes) { #if defined(LEO_TRY_AVX2) if (CpuHasAVX2) { const LEO_M256 table_lo_y = _mm256_loadu_si256(&Multiply256LUT[log_m].Value[0]); const LEO_M256 table_hi_y = _mm256_loadu_si256(&Multiply256LUT[log_m].Value[1]); const LEO_M256 clr_mask = _mm256_set1_epi8(0x0f); LEO_M256 * LEO_RESTRICT x32_0 = reinterpret_cast<LEO_M256 *>(x_0); LEO_M256 * LEO_RESTRICT y32_0 = reinterpret_cast<LEO_M256 *>(y_0); LEO_M256 * LEO_RESTRICT x32_1 = reinterpret_cast<LEO_M256 *>(x_1); LEO_M256 * LEO_RESTRICT y32_1 = reinterpret_cast<LEO_M256 *>(y_1); LEO_M256 * LEO_RESTRICT x32_2 = reinterpret_cast<LEO_M256 *>(x_2); LEO_M256 * LEO_RESTRICT y32_2 = reinterpret_cast<LEO_M256 *>(y_2); LEO_M256 * LEO_RESTRICT x32_3 = reinterpret_cast<LEO_M256 *>(x_3); LEO_M256 * LEO_RESTRICT y32_3 = reinterpret_cast<LEO_M256 *>(y_3); do { LEO_FFTB_256(x32_0 + 1, y32_0 + 1); LEO_FFTB_256(x32_0, y32_0); y32_0 += 2, x32_0 += 2; LEO_FFTB_256(x32_1 + 1, y32_1 + 1); LEO_FFTB_256(x32_1, y32_1); y32_1 += 2, x32_1 += 2; LEO_FFTB_256(x32_2 + 1, y32_2 + 1); LEO_FFTB_256(x32_2, y32_2); y32_2 += 2, x32_2 += 2; LEO_FFTB_256(x32_3 + 1, y32_3 + 1); LEO_FFTB_256(x32_3, y32_3); y32_3 += 2, x32_3 += 2; bytes -= 64; } while (bytes > 0); return; } #endif // LEO_TRY_AVX2 const LEO_M128 table_lo_y = _mm_loadu_si128(&Multiply128LUT[log_m].Value[0]); const LEO_M128 table_hi_y = _mm_loadu_si128(&Multiply128LUT[log_m].Value[1]); const LEO_M128 clr_mask = _mm_set1_epi8(0x0f); LEO_M128 * LEO_RESTRICT x16_0 = reinterpret_cast<LEO_M128 *>(x_0); LEO_M128 * LEO_RESTRICT y16_0 = reinterpret_cast<LEO_M128 *>(y_0); LEO_M128 * LEO_RESTRICT x16_1 = reinterpret_cast<LEO_M128 *>(x_1); LEO_M128 * LEO_RESTRICT y16_1 = reinterpret_cast<LEO_M128 *>(y_1); LEO_M128 * LEO_RESTRICT x16_2 = reinterpret_cast<LEO_M128 *>(x_2); LEO_M128 * LEO_RESTRICT y16_2 = reinterpret_cast<LEO_M128 *>(y_2); LEO_M128 * LEO_RESTRICT x16_3 = reinterpret_cast<LEO_M128 *>(x_3); LEO_M128 * LEO_RESTRICT y16_3 = reinterpret_cast<LEO_M128 *>(y_3); do { LEO_FFTB_128(x16_0 + 3, y16_0 + 3); LEO_FFTB_128(x16_0 + 2, y16_0 + 2); LEO_FFTB_128(x16_0 + 1, y16_0 + 1); LEO_FFTB_128(x16_0, y16_0); x16_0 += 4, y16_0 += 4; LEO_FFTB_128(x16_1 + 3, y16_1 + 3); LEO_FFTB_128(x16_1 + 2, y16_1 + 2); LEO_FFTB_128(x16_1 + 1, y16_1 + 1); LEO_FFTB_128(x16_1, y16_1); x16_1 += 4, y16_1 += 4; LEO_FFTB_128(x16_2 + 3, y16_2 + 3); LEO_FFTB_128(x16_2 + 2, y16_2 + 2); LEO_FFTB_128(x16_2 + 1, y16_2 + 1); LEO_FFTB_128(x16_2, y16_2); x16_2 += 4, y16_2 += 4; LEO_FFTB_128(x16_3 + 3, y16_3 + 3); LEO_FFTB_128(x16_3 + 2, y16_3 + 2); LEO_FFTB_128(x16_3 + 1, y16_3 + 1); LEO_FFTB_128(x16_3, y16_3); x16_3 += 4, y16_3 += 4; bytes -= 64; } while (bytes > 0); } #endif // LEO_USE_VECTOR4_OPT //------------------------------------------------------------------------------ // IFFT Operations void ifft_butterfly( void * LEO_RESTRICT x, void * LEO_RESTRICT y, ffe_t log_m, uint64_t bytes) { #if defined(LEO_TRY_AVX2) if (CpuHasAVX2) { const LEO_M256 table_lo_y = _mm256_loadu_si256(&Multiply256LUT[log_m].Value[0]); const LEO_M256 table_hi_y = _mm256_loadu_si256(&Multiply256LUT[log_m].Value[1]); const LEO_M256 clr_mask = _mm256_set1_epi8(0x0f); LEO_M256 * LEO_RESTRICT x32 = reinterpret_cast<LEO_M256 *>(x); LEO_M256 * LEO_RESTRICT y32 = reinterpret_cast<LEO_M256 *>(y); do { #define LEO_IFFTB_256(x_ptr, y_ptr) { \ LEO_M256 x_data = _mm256_loadu_si256(x_ptr); \ LEO_M256 y_data = _mm256_loadu_si256(y_ptr); \ y_data = _mm256_xor_si256(y_data, x_data); \ _mm256_storeu_si256(y_ptr, y_data); \ LEO_M256 lo = _mm256_and_si256(y_data, clr_mask); \ lo = _mm256_shuffle_epi8(table_lo_y, lo); \ LEO_M256 hi = _mm256_srli_epi64(y_data, 4); \ hi = _mm256_and_si256(hi, clr_mask); \ hi = _mm256_shuffle_epi8(table_hi_y, hi); \ x_data = _mm256_xor_si256(x_data, _mm256_xor_si256(lo, hi)); \ _mm256_storeu_si256(x_ptr, x_data); } LEO_IFFTB_256(x32 + 1, y32 + 1); LEO_IFFTB_256(x32, y32); y32 += 2, x32 += 2; bytes -= 64; } while (bytes > 0); return; } #endif // LEO_TRY_AVX2 const LEO_M128 table_lo_y = _mm_loadu_si128(&Multiply128LUT[log_m].Value[0]); const LEO_M128 table_hi_y = _mm_loadu_si128(&Multiply128LUT[log_m].Value[1]); const LEO_M128 clr_mask = _mm_set1_epi8(0x0f); LEO_M128 * LEO_RESTRICT x16 = reinterpret_cast<LEO_M128 *>(x); LEO_M128 * LEO_RESTRICT y16 = reinterpret_cast<LEO_M128 *>(y); do { #define LEO_IFFTB_128(x_ptr, y_ptr) { \ LEO_M128 x_data = _mm_loadu_si128(x_ptr); \ LEO_M128 y_data = _mm_loadu_si128(y_ptr); \ y_data = _mm_xor_si128(y_data, x_data); \ _mm_storeu_si128(y_ptr, y_data); \ LEO_M128 lo = _mm_and_si128(y_data, clr_mask); \ lo = _mm_shuffle_epi8(table_lo_y, lo); \ LEO_M128 hi = _mm_srli_epi64(y_data, 4); \ hi = _mm_and_si128(hi, clr_mask); \ hi = _mm_shuffle_epi8(table_hi_y, hi); \ x_data = _mm_xor_si128(x_data, _mm_xor_si128(lo, hi)); \ _mm_storeu_si128(x_ptr, x_data); } LEO_IFFTB_128(x16 + 3, y16 + 3); LEO_IFFTB_128(x16 + 2, y16 + 2); LEO_IFFTB_128(x16 + 1, y16 + 1); LEO_IFFTB_128(x16, y16); x16 += 4, y16 += 4; bytes -= 64; } while (bytes > 0); } #ifdef LEO_USE_VECTOR4_OPT void ifft_butterfly4( void * LEO_RESTRICT x_0, void * LEO_RESTRICT y_0, void * LEO_RESTRICT x_1, void * LEO_RESTRICT y_1, void * LEO_RESTRICT x_2, void * LEO_RESTRICT y_2, void * LEO_RESTRICT x_3, void * LEO_RESTRICT y_3, ffe_t log_m, uint64_t bytes) { #if defined(LEO_TRY_AVX2) if (CpuHasAVX2) { const LEO_M256 table_lo_y = _mm256_loadu_si256(&Multiply256LUT[log_m].Value[0]); const LEO_M256 table_hi_y = _mm256_loadu_si256(&Multiply256LUT[log_m].Value[1]); const LEO_M256 clr_mask = _mm256_set1_epi8(0x0f); LEO_M256 * LEO_RESTRICT x32_0 = reinterpret_cast<LEO_M256 *>(x_0); LEO_M256 * LEO_RESTRICT y32_0 = reinterpret_cast<LEO_M256 *>(y_0); LEO_M256 * LEO_RESTRICT x32_1 = reinterpret_cast<LEO_M256 *>(x_1); LEO_M256 * LEO_RESTRICT y32_1 = reinterpret_cast<LEO_M256 *>(y_1); LEO_M256 * LEO_RESTRICT x32_2 = reinterpret_cast<LEO_M256 *>(x_2); LEO_M256 * LEO_RESTRICT y32_2 = reinterpret_cast<LEO_M256 *>(y_2); LEO_M256 * LEO_RESTRICT x32_3 = reinterpret_cast<LEO_M256 *>(x_3); LEO_M256 * LEO_RESTRICT y32_3 = reinterpret_cast<LEO_M256 *>(y_3); do { LEO_IFFTB_256(x32_0 + 1, y32_0 + 1); LEO_IFFTB_256(x32_0, y32_0); y32_0 += 2, x32_0 += 2; LEO_IFFTB_256(x32_1 + 1, y32_1 + 1); LEO_IFFTB_256(x32_1, y32_1); y32_1 += 2, x32_1 += 2; LEO_IFFTB_256(x32_2 + 1, y32_2 + 1); LEO_IFFTB_256(x32_2, y32_2); y32_2 += 2, x32_2 += 2; LEO_IFFTB_256(x32_3 + 1, y32_3 + 1); LEO_IFFTB_256(x32_3, y32_3); y32_3 += 2, x32_3 += 2; bytes -= 64; } while (bytes > 0); return; } #endif // LEO_TRY_AVX2 const LEO_M128 table_lo_y = _mm_loadu_si128(&Multiply128LUT[log_m].Value[0]); const LEO_M128 table_hi_y = _mm_loadu_si128(&Multiply128LUT[log_m].Value[1]); const LEO_M128 clr_mask = _mm_set1_epi8(0x0f); LEO_M128 * LEO_RESTRICT x16_0 = reinterpret_cast<LEO_M128 *>(x_0); LEO_M128 * LEO_RESTRICT y16_0 = reinterpret_cast<LEO_M128 *>(y_0); LEO_M128 * LEO_RESTRICT x16_1 = reinterpret_cast<LEO_M128 *>(x_1); LEO_M128 * LEO_RESTRICT y16_1 = reinterpret_cast<LEO_M128 *>(y_1); LEO_M128 * LEO_RESTRICT x16_2 = reinterpret_cast<LEO_M128 *>(x_2); LEO_M128 * LEO_RESTRICT y16_2 = reinterpret_cast<LEO_M128 *>(y_2); LEO_M128 * LEO_RESTRICT x16_3 = reinterpret_cast<LEO_M128 *>(x_3); LEO_M128 * LEO_RESTRICT y16_3 = reinterpret_cast<LEO_M128 *>(y_3); do { LEO_IFFTB_128(x16_0 + 3, y16_0 + 3); LEO_IFFTB_128(x16_0 + 2, y16_0 + 2); LEO_IFFTB_128(x16_0 + 1, y16_0 + 1); LEO_IFFTB_128(x16_0, y16_0); x16_0 += 4, y16_0 += 4; LEO_IFFTB_128(x16_1 + 3, y16_1 + 3); LEO_IFFTB_128(x16_1 + 2, y16_1 + 2); LEO_IFFTB_128(x16_1 + 1, y16_1 + 1); LEO_IFFTB_128(x16_1, y16_1); x16_1 += 4, y16_1 += 4; LEO_IFFTB_128(x16_2 + 3, y16_2 + 3); LEO_IFFTB_128(x16_2 + 2, y16_2 + 2); LEO_IFFTB_128(x16_2 + 1, y16_2 + 1); LEO_IFFTB_128(x16_2, y16_2); x16_2 += 4, y16_2 += 4; LEO_IFFTB_128(x16_3 + 3, y16_3 + 3); LEO_IFFTB_128(x16_3 + 2, y16_3 + 2); LEO_IFFTB_128(x16_3 + 1, y16_3 + 1); LEO_IFFTB_128(x16_3, y16_3); x16_3 += 4, y16_3 += 4; bytes -= 64; } while (bytes > 0); } #endif // LEO_USE_VECTOR4_OPT //------------------------------------------------------------------------------ // FFT // Twisted factors used in FFT static ffe_t FFTSkew[kModulus]; // Factors used in the evaluation of the error locator polynomial static ffe_t LogWalsh[kOrder]; static void FFTInitialize() { ffe_t temp[kBits - 1]; // Generate FFT skew vector {1}: for (unsigned i = 1; i < kBits; ++i) temp[i - 1] = static_cast<ffe_t>(1UL << i); for (unsigned m = 0; m < (kBits - 1); ++m) { const unsigned step = 1UL << (m + 1); FFTSkew[(1UL << m) - 1] = 0; for (unsigned i = m; i < (kBits - 1); ++i) { const unsigned s = (1UL << (i + 1)); for (unsigned j = (1UL << m) - 1; j < s; j += step) FFTSkew[j + s] = FFTSkew[j] ^ temp[i]; } temp[m] = kModulus - LogLUT[MultiplyLog(temp[m], LogLUT[temp[m] ^ 1])]; for (unsigned i = m + 1; i < (kBits - 1); ++i) { const ffe_t sum = AddMod(LogLUT[temp[i] ^ 1], temp[m]); temp[i] = MultiplyLog(temp[i], sum); } } for (unsigned i = 0; i < kOrder; ++i) FFTSkew[i] = LogLUT[FFTSkew[i]]; // Precalculate FWHT(Log[i]): for (unsigned i = 0; i < kOrder; ++i) LogWalsh[i] = LogLUT[i]; LogWalsh[0] = 0; FWHT(LogWalsh, kBits); } //------------------------------------------------------------------------------ // Reed-Solomon Encode /* Decimation in time IFFT: The decimation in time IFFT algorithm allows us to unroll 2 layers at a time, performing calculations on local registers and faster cache memory. Each ^___^ below indicates a butterfly between the associated indices. The ifft_butterfly(x, y) operation: if (log_m != kModulus) x[] ^= exp(log(y[]) + log_m) y[] ^= x[] Layer 0: 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ Layer 1: 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 ^___^ ^___^ ^___^ ^___^ ^___^ ^___^ ^___^ ^___^ Layer 2: 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 ^_______^ ^_______^ ^_______^ ^_______^ ^_______^ ^_______^ ^_______^ ^_______^ Layer 3: 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 ^_______________^ ^_______________^ ^_______________^ ^_______________^ ^_______________^ ^_______________^ ^_______________^ ^_______________^ DIT layer 0-1 operations, grouped 4 at a time: {0-1, 2-3, 0-2, 1-3}, {4-5, 6-7, 4-6, 5-7}, DIT layer 1-2 operations, grouped 4 at a time: {0-2, 4-6, 0-4, 2-6}, {1-3, 5-7, 1-5, 3-7}, DIT layer 2-3 operations, grouped 4 at a time: {0-4, 0'-4', 0-0', 4-4'}, {1-5, 1'-5', 1-1', 5-5'}, */ // 4-way butterfly static void IFFT_DIT4( const uint64_t bytes, void** work, unsigned dist, const ffe_t log_m01, const ffe_t log_m23, const ffe_t log_m02) { // FIXME: Interleave these // First layer: if (log_m01 == kModulus) xor_mem(work[dist], work[0], bytes); else ifft_butterfly(work[0], work[dist], log_m01, bytes); if (log_m23 == kModulus) xor_mem(work[dist * 3], work[dist * 2], bytes); else ifft_butterfly(work[dist * 2], work[dist * 3], log_m23, bytes); // Second layer: if (log_m02 == kModulus) { xor_mem(work[dist * 2], work[0], bytes); xor_mem(work[dist * 3], work[dist], bytes); } else { ifft_butterfly(work[0], work[dist * 2], log_m02, bytes); ifft_butterfly(work[dist], work[dist * 3], log_m02, bytes); } } void IFFT_DIT( const uint64_t bytes, void* const* data, const unsigned m_truncated, void** work, void** xor_result, const unsigned m, const ffe_t* skewLUT) { // FIXME: Roll into first layer if (data) { for (unsigned i = 0; i < m_truncated; ++i) memcpy(work[i], data[i], bytes); for (unsigned i = m_truncated; i < m; ++i) memset(work[i], 0, bytes); } // Decimation in time: Unroll 2 layers at a time unsigned dist = 1, dist4 = 4; for (; dist4 <= m; dist = dist4, dist4 <<= 2) { // FIXME: Walk this in reverse order every other pair of layers for better cache locality // FIXME: m_truncated // For each set of dist*4 elements: for (unsigned r = 0; r < m_truncated; r += dist4) { const ffe_t log_m01 = skewLUT[r + dist]; const ffe_t log_m23 = skewLUT[r + dist * 3]; const ffe_t log_m02 = skewLUT[r + dist * 2]; // For each set of dist elements: for (unsigned i = r; i < r + dist; ++i) { IFFT_DIT4( bytes, work + i, dist, log_m01, log_m23, log_m02); } } data = nullptr; } // If there is one layer left: if (dist < m) { const ffe_t log_m = skewLUT[dist]; if (log_m == kModulus) { for (unsigned i = 0; i < dist; ++i) VectorXOR(bytes, dist, work + dist, work); } else { for (unsigned i = 0; i < dist; ++i) { ifft_butterfly( work[i], work[i + dist], log_m, bytes); } } } // FIXME: Roll into last layer if (xor_result) for (unsigned i = 0; i < m; ++i) xor_mem(xor_result[i], work[i], bytes); } /* Decimation in time FFT: The decimation in time FFT algorithm allows us to unroll 2 layers at a time, performing calculations on local registers and faster cache memory. Each ^___^ below indicates a butterfly between the associated indices. The fft_butterfly(x, y) operation: y[] ^= x[] if (log_m != kModulus) x[] ^= exp(log(y[]) + log_m) Layer 0: 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 ^_______________^ ^_______________^ ^_______________^ ^_______________^ ^_______________^ ^_______________^ ^_______________^ ^_______________^ Layer 1: 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 ^_______^ ^_______^ ^_______^ ^_______^ ^_______^ ^_______^ ^_______^ ^_______^ Layer 2: 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 ^___^ ^___^ ^___^ ^___^ ^___^ ^___^ ^___^ ^___^ Layer 3: 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ DIT layer 0-1 operations, grouped 4 at a time: {0-0', 4-4', 0-4, 0'-4'}, {1-1', 5-5', 1-5, 1'-5'}, DIT layer 1-2 operations, grouped 4 at a time: {0-4, 2-6, 0-2, 4-6}, {1-5, 3-7, 1-3, 5-7}, DIT layer 2-3 operations, grouped 4 at a time: {0-2, 1-3, 0-1, 2-3}, {4-6, 5-7, 4-5, 6-7}, */ static void FFT_DIT4( const uint64_t bytes, void** work, const unsigned dist, const ffe_t log_m01, const ffe_t log_m23, const ffe_t log_m02) { // FIXME: Interleave // First layer: if (log_m02 == kModulus) { xor_mem(work[dist * 2], work[0], bytes); xor_mem(work[dist * 3], work[dist], bytes); } else { fft_butterfly(work[0], work[dist * 2], log_m02, bytes); fft_butterfly(work[dist], work[dist * 3], log_m02, bytes); } // Second layer: if (log_m01 == kModulus) xor_mem(work[dist], work[0], bytes); else fft_butterfly(work[0], work[dist], log_m01, bytes); if (log_m23 == kModulus) xor_mem(work[dist * 3], work[dist * 2], bytes); else fft_butterfly(work[dist * 2], work[dist * 3], log_m23, bytes); } void FFT_DIT( const uint64_t bytes, void** work, const unsigned m_truncated, const unsigned m, const ffe_t* skewLUT) { // Decimation in time: Unroll 2 layers at a time unsigned dist4 = m, dist = m >> 2; for (; dist != 0; dist4 = dist, dist >>= 2) { // FIXME: Walk this in reverse order every other pair of layers for better cache locality // FIXME: m_truncated // For each set of dist*4 elements: for (unsigned r = 0; r < m_truncated; r += dist4) { const ffe_t log_m01 = skewLUT[r + dist]; const ffe_t log_m23 = skewLUT[r + dist * 3]; const ffe_t log_m02 = skewLUT[r + dist * 2]; // For each set of dist elements: for (unsigned i = r; i < r + dist; ++i) { FFT_DIT4( bytes, work + i, dist, log_m01, log_m23, log_m02); } } } // If there is one layer left: if (dist4 == 2) { for (unsigned r = 0; r < m_truncated; r += 2) { const ffe_t log_m = skewLUT[r + 1]; if (log_m == kModulus) xor_mem(work[r + 1], work[r], bytes); else { fft_butterfly( work[r], work[r + 1], log_m, bytes); } } } } void ReedSolomonEncode( uint64_t buffer_bytes, unsigned original_count, unsigned recovery_count, unsigned m, void* const* data, void** work) { // work <- IFFT(data, m, m) const ffe_t* skewLUT = FFTSkew + m - 1; IFFT_DIT( buffer_bytes, data, original_count < m ? original_count : m, work, nullptr, // No xor output m, skewLUT); if (m >= original_count) goto skip_body; // For sets of m data pieces: for (unsigned i = m; i + m <= original_count; i += m) { data += m; skewLUT += m; // work <- work xor IFFT(data + i, m, m + i) IFFT_DIT( buffer_bytes, data, // data source m, work + m, // temporary workspace work, // xor destination m, skewLUT); } // Handle final partial set of m pieces: const unsigned last_count = original_count % m; if (last_count != 0) { const unsigned i = original_count - last_count; data += m; skewLUT += m; // work <- work xor IFFT(data + i, m, m + i) IFFT_DIT( buffer_bytes, data, // data source last_count, work + m, // temporary workspace work, // xor destination m, skewLUT); } skip_body: // work <- FFT(work, m, 0) FFT_DIT( buffer_bytes, work, recovery_count, m, FFTSkew - 1); } //------------------------------------------------------------------------------ // ErrorBitfield #ifdef LEO_ERROR_BITFIELD_OPT // Used in decoding to decide which final FFT operations to perform class ErrorBitfield { static const unsigned kWords = kOrder / 64; uint64_t Words[7][kWords] = {}; public: LEO_FORCE_INLINE void Set(unsigned i) { Words[0][i / 64] |= (uint64_t)1 << (i % 64); } void Prepare(); LEO_FORCE_INLINE bool IsNeeded(unsigned mip_level, unsigned bit) const { if (mip_level >= 8) return true; return 0 != (Words[mip_level - 1][bit / 64] & ((uint64_t)1 << (bit % 64))); } }; static const uint64_t kHiMasks[5] = { 0xAAAAAAAAAAAAAAAAULL, 0xCCCCCCCCCCCCCCCCULL, 0xF0F0F0F0F0F0F0F0ULL, 0xFF00FF00FF00FF00ULL, 0xFFFF0000FFFF0000ULL, }; void ErrorBitfield::Prepare() { // First mip level is for final layer of FFT: pairs of data for (unsigned i = 0; i < kWords; ++i) { uint64_t w_i = Words[0][i]; const uint64_t hi2lo0 = w_i | ((w_i & kHiMasks[0]) >> 1); const uint64_t lo2hi0 = ((w_i & (kHiMasks[0] >> 1)) << 1); Words[0][i] = w_i = hi2lo0 | lo2hi0; for (unsigned j = 1, bits = 2; j < 5; ++j, bits <<= 1) { const uint64_t hi2lo_j = w_i | ((w_i & kHiMasks[j]) >> bits); const uint64_t lo2hi_j = ((w_i & (kHiMasks[j] >> bits)) << bits); Words[j][i] = w_i = hi2lo_j | lo2hi_j; } } for (unsigned i = 0; i < kWords; ++i) { uint64_t w = Words[4][i]; w |= w >> 32; w |= w << 32; Words[5][i] = w; } for (unsigned i = 0; i < kWords; i += 2) Words[6][i] = Words[6][i + 1] = Words[5][i] | Words[5][i + 1]; } #endif // LEO_ERROR_BITFIELD_OPT //------------------------------------------------------------------------------ // Reed-Solomon Decode void VectorFFTButterfly( const uint64_t bytes, unsigned count, void** x, void** y, const ffe_t log_m) { if (log_m == kModulus) { VectorXOR(bytes, count, y, x); return; } #ifdef LEO_USE_VECTOR4_OPT while (count >= 4) { fft_butterfly4( x[0], y[0], x[1], y[1], x[2], y[2], x[3], y[3], log_m, bytes); x += 4, y += 4; count -= 4; } #endif // LEO_USE_VECTOR4_OPT for (unsigned i = 0; i < count; ++i) fft_butterfly(x[i], y[i], log_m, bytes); } void VectorIFFTButterfly( const uint64_t bytes, unsigned count, void** x, void** y, const ffe_t log_m) { if (log_m == kModulus) { VectorXOR(bytes, count, y, x); return; } #ifdef LEO_USE_VECTOR4_OPT while (count >= 4) { ifft_butterfly4( x[0], y[0], x[1], y[1], x[2], y[2], x[3], y[3], log_m, bytes); x += 4, y += 4; count -= 4; } #endif // LEO_USE_VECTOR4_OPT for (unsigned i = 0; i < count; ++i) ifft_butterfly(x[i], y[i], log_m, bytes); } void ReedSolomonDecode( uint64_t buffer_bytes, unsigned original_count, unsigned recovery_count, unsigned m, // NextPow2(recovery_count) unsigned n, // NextPow2(m + original_count) = work_count void* const * const original, // original_count entries void* const * const recovery, // recovery_count entries void** work) // n entries { // Fill in error locations #ifdef LEO_ERROR_BITFIELD_OPT ErrorBitfield ErrorBits; #endif // LEO_ERROR_BITFIELD_OPT ffe_t ErrorLocations[kOrder] = {}; for (unsigned i = 0; i < recovery_count; ++i) if (!recovery[i]) ErrorLocations[i] = 1; for (unsigned i = recovery_count; i < m; ++i) ErrorLocations[i] = 1; for (unsigned i = 0; i < original_count; ++i) { if (!original[i]) { ErrorLocations[i + m] = 1; #ifdef LEO_ERROR_BITFIELD_OPT ErrorBits.Set(i + m); #endif // LEO_ERROR_BITFIELD_OPT } } #ifdef LEO_ERROR_BITFIELD_OPT ErrorBits.Prepare(); #endif // LEO_ERROR_BITFIELD_OPT // Evaluate error locator polynomial FWHT(ErrorLocations); for (unsigned i = 0; i < kOrder; ++i) ErrorLocations[i] = ((unsigned)ErrorLocations[i] * (unsigned)LogWalsh[i]) % kModulus; FWHT(ErrorLocations); // work <- recovery data for (unsigned i = 0; i < recovery_count; ++i) { if (recovery[i]) mul_mem(work[i], recovery[i], ErrorLocations[i], buffer_bytes); else memset(work[i], 0, buffer_bytes); } for (unsigned i = recovery_count; i < m; ++i) memset(work[i], 0, buffer_bytes); // work <- original data for (unsigned i = 0; i < original_count; ++i) { if (original[i]) mul_mem(work[m + i], original[i], ErrorLocations[m + i], buffer_bytes); else memset(work[m + i], 0, buffer_bytes); } for (unsigned i = m + original_count; i < n; ++i) memset(work[i], 0, buffer_bytes); // work <- IFFT(work, n, 0) IFFT_DIT( buffer_bytes, nullptr, n, work, nullptr, n, FFTSkew - 1); // work <- FormalDerivative(work, n) for (unsigned i = 1; i < n; ++i) { const unsigned width = ((i ^ (i - 1)) + 1) >> 1; VectorXOR( buffer_bytes, width, work + i - width, work + i); } // work <- FFT(work, n, 0) truncated to m + original_count unsigned mip_level = LastNonzeroBit32(n); const unsigned output_count = m + original_count; for (unsigned width = (n >> 1); width > 0; width >>= 1, --mip_level) { const ffe_t* skewLUT = FFTSkew + width - 1; const unsigned range = width << 1; #ifdef LEO_SCHEDULE_OPT for (unsigned j = (m < range) ? 0 : m; j < output_count; j += range) #else for (unsigned j = 0; j < n; j += range) #endif { #ifdef LEO_ERROR_BITFIELD_OPT if (!ErrorBits.IsNeeded(mip_level, j)) continue; #endif // LEO_ERROR_BITFIELD_OPT VectorFFTButterfly( buffer_bytes, width, work + j, work + j + width, skewLUT[j]); } } // Reveal erasures for (unsigned i = 0; i < original_count; ++i) if (!original[i]) mul_mem(work[i], work[i + m], kModulus - ErrorLocations[i + m], buffer_bytes); } //------------------------------------------------------------------------------ // API static bool IsInitialized = false; bool Initialize() { if (IsInitialized) return true; if (!CpuHasSSSE3) return false; InitializeLogarithmTables(); InitializeMultiplyTables(); FFTInitialize(); IsInitialized = true; return true; } }} // namespace leopard::ff8 #endif // LEO_HAS_FF8
28.734637
105
0.555896
[ "vector", "transform" ]
78cb1b61cd2dec5d90f435f1a2fd23f402ae46f3
17,704
cxx
C++
cmake-2.8.10.1/Source/CPack/cmCPackDragNDropGenerator.cxx
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
1
2016-04-09T02:58:13.000Z
2016-04-09T02:58:13.000Z
cmake-2.8.10.1/Source/CPack/cmCPackDragNDropGenerator.cxx
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
null
null
null
cmake-2.8.10.1/Source/CPack/cmCPackDragNDropGenerator.cxx
vidkidz/crossbridge
ba0bf94aee0ce6cf7eb5be882382e52bc57ba396
[ "MIT" ]
null
null
null
/*============================================================================ CMake - Cross Platform Makefile Generator Copyright 2000-2009 Kitware, Inc., Insight Software Consortium Distributed under the OSI-approved BSD License (the "License"); see accompanying file Copyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the License for more information. ============================================================================*/ #include "cmCPackDragNDropGenerator.h" #include "cmCPackLog.h" #include "cmSystemTools.h" #include "cmGeneratedFileStream.h" #include <cmsys/RegularExpression.hxx> static const char* SLAHeader = "data 'LPic' (5000) {\n" " $\"0002 0011 0003 0001 0000 0000 0002 0000\"\n" " $\"0008 0003 0000 0001 0004 0000 0004 0005\"\n" " $\"0000 000E 0006 0001 0005 0007 0000 0007\"\n" " $\"0008 0000 0047 0009 0000 0034 000A 0001\"\n" " $\"0035 000B 0001 0020 000C 0000 0011 000D\"\n" " $\"0000 005B 0004 0000 0033 000F 0001 000C\"\n" " $\"0010 0000 000B 000E 0000\"\n" "};\n" "\n"; static const char* SLASTREnglish = "resource 'STR#' (5002, \"English\") {\n" " {\n" " \"English\",\n" " \"Agree\",\n" " \"Disagree\",\n" " \"Print\",\n" " \"Save...\",\n" " \"You agree to the License Agreement terms when you click \"\n" " \"the \\\"Agree\\\" button.\",\n" " \"Software License Agreement\",\n" " \"This text cannot be saved. This disk may be full or locked, " "or the \"\n" " \"file may be locked.\",\n" " \"Unable to print. Make sure you have selected a printer.\"\n" " }\n" "};\n" "\n"; //---------------------------------------------------------------------- cmCPackDragNDropGenerator::cmCPackDragNDropGenerator() { // default to one package file for components this->componentPackageMethod = ONE_PACKAGE; } //---------------------------------------------------------------------- cmCPackDragNDropGenerator::~cmCPackDragNDropGenerator() { } //---------------------------------------------------------------------- int cmCPackDragNDropGenerator::InitializeInternal() { // Starting with Xcode 4.3, look in "/Applications/Xcode.app" first: // std::vector<std::string> paths; paths.push_back("/Applications/Xcode.app/Contents/Developer/Tools"); paths.push_back("/Developer/Tools"); const std::string hdiutil_path = cmSystemTools::FindProgram("hdiutil", std::vector<std::string>(), false); if(hdiutil_path.empty()) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot locate hdiutil command" << std::endl); return 0; } this->SetOptionIfNotSet("CPACK_COMMAND_HDIUTIL", hdiutil_path.c_str()); const std::string setfile_path = cmSystemTools::FindProgram("SetFile", paths, false); if(setfile_path.empty()) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot locate SetFile command" << std::endl); return 0; } this->SetOptionIfNotSet("CPACK_COMMAND_SETFILE", setfile_path.c_str()); const std::string rez_path = cmSystemTools::FindProgram("Rez", paths, false); if(rez_path.empty()) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Cannot locate Rez command" << std::endl); return 0; } this->SetOptionIfNotSet("CPACK_COMMAND_REZ", rez_path.c_str()); return this->Superclass::InitializeInternal(); } //---------------------------------------------------------------------- const char* cmCPackDragNDropGenerator::GetOutputExtension() { return ".dmg"; } //---------------------------------------------------------------------- int cmCPackDragNDropGenerator::PackageFiles() { // gather which directories to make dmg files for // multiple directories occur if packaging components or groups separately // monolith if(this->Components.empty()) { return this->CreateDMG(toplevel, packageFileNames[0]); } // component install std::vector<std::string> package_files; std::map<std::string, cmCPackComponent>::iterator compIt; for (compIt=this->Components.begin(); compIt!=this->Components.end(); ++compIt ) { std::string name = GetComponentInstallDirNameSuffix(compIt->first); package_files.push_back(name); } std::sort(package_files.begin(), package_files.end()); package_files.erase(std::unique(package_files.begin(), package_files.end()), package_files.end()); // loop to create dmg files packageFileNames.clear(); for(size_t i=0; i<package_files.size(); i++) { std::string full_package_name = std::string(toplevel) + std::string("/"); if(package_files[i] == "ALL_IN_ONE") { full_package_name += this->GetOption("CPACK_PACKAGE_FILE_NAME"); } else { full_package_name += package_files[i]; } full_package_name += std::string(GetOutputExtension()); packageFileNames.push_back(full_package_name); std::string src_dir = toplevel; src_dir += "/"; src_dir += package_files[i]; if(0 == this->CreateDMG(src_dir, full_package_name)) { return 0; } } return 1; } //---------------------------------------------------------------------- bool cmCPackDragNDropGenerator::CopyFile(cmOStringStream& source, cmOStringStream& target) { if(!cmSystemTools::CopyFileIfDifferent( source.str().c_str(), target.str().c_str())) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Error copying " << source.str() << " to " << target.str() << std::endl); return false; } return true; } //---------------------------------------------------------------------- bool cmCPackDragNDropGenerator::RunCommand(cmOStringStream& command, std::string* output) { int exit_code = 1; bool result = cmSystemTools::RunSingleCommand( command.str().c_str(), output, &exit_code, 0, this->GeneratorVerbose, 0); if(!result || exit_code) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Error executing: " << command.str() << std::endl); return false; } return true; } //---------------------------------------------------------------------- int cmCPackDragNDropGenerator::CreateDMG(const std::string& src_dir, const std::string& output_file) { // Get optional arguments ... const std::string cpack_package_icon = this->GetOption("CPACK_PACKAGE_ICON") ? this->GetOption("CPACK_PACKAGE_ICON") : ""; const std::string cpack_dmg_volume_name = this->GetOption("CPACK_DMG_VOLUME_NAME") ? this->GetOption("CPACK_DMG_VOLUME_NAME") : this->GetOption("CPACK_PACKAGE_FILE_NAME"); const std::string cpack_dmg_format = this->GetOption("CPACK_DMG_FORMAT") ? this->GetOption("CPACK_DMG_FORMAT") : "UDZO"; // Get optional arguments ... std::string cpack_license_file = this->GetOption("CPACK_RESOURCE_FILE_LICENSE") ? this->GetOption("CPACK_RESOURCE_FILE_LICENSE") : ""; const std::string cpack_dmg_background_image = this->GetOption("CPACK_DMG_BACKGROUND_IMAGE") ? this->GetOption("CPACK_DMG_BACKGROUND_IMAGE") : ""; const std::string cpack_dmg_ds_store = this->GetOption("CPACK_DMG_DS_STORE") ? this->GetOption("CPACK_DMG_DS_STORE") : ""; // only put license on dmg if is user provided if(!cpack_license_file.empty() && cpack_license_file.find("CPack.GenericLicense.txt") != std::string::npos) { cpack_license_file = ""; } // The staging directory contains everything that will end-up inside the // final disk image ... cmOStringStream staging; staging << src_dir; // Add a symlink to /Applications so users can drag-and-drop the bundle // into it cmOStringStream application_link; application_link << staging.str() << "/Applications"; cmSystemTools::CreateSymlink("/Applications", application_link.str().c_str()); // Optionally add a custom volume icon ... if(!cpack_package_icon.empty()) { cmOStringStream package_icon_source; package_icon_source << cpack_package_icon; cmOStringStream package_icon_destination; package_icon_destination << staging.str() << "/.VolumeIcon.icns"; if(!this->CopyFile(package_icon_source, package_icon_destination)) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Error copying disk volume icon. " "Check the value of CPACK_PACKAGE_ICON." << std::endl); return 0; } } // Optionally add a custom .DS_Store file // (e.g. for setting background/layout) ... if(!cpack_dmg_ds_store.empty()) { cmOStringStream package_settings_source; package_settings_source << cpack_dmg_ds_store; cmOStringStream package_settings_destination; package_settings_destination << staging.str() << "/.DS_Store"; if(!this->CopyFile(package_settings_source, package_settings_destination)) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Error copying disk volume settings file. " "Check the value of CPACK_DMG_DS_STORE." << std::endl); return 0; } } // Optionally add a custom background image ... if(!cpack_dmg_background_image.empty()) { cmOStringStream package_background_source; package_background_source << cpack_dmg_background_image; cmOStringStream package_background_destination; package_background_destination << staging.str() << "/background.png"; if(!this->CopyFile(package_background_source, package_background_destination)) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Error copying disk volume background image. " "Check the value of CPACK_DMG_BACKGROUND_IMAGE." << std::endl); return 0; } cmOStringStream temp_background_hiding_command; temp_background_hiding_command << this->GetOption("CPACK_COMMAND_SETFILE"); temp_background_hiding_command << " -a V \""; temp_background_hiding_command << package_background_destination.str(); temp_background_hiding_command << "\""; if(!this->RunCommand(temp_background_hiding_command)) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Error setting attributes on disk volume background image." << std::endl); return 0; } } // Create a temporary read-write disk image ... std::string temp_image = this->GetOption("CPACK_TOPLEVEL_DIRECTORY"); temp_image += "/temp.dmg"; cmOStringStream temp_image_command; temp_image_command << this->GetOption("CPACK_COMMAND_HDIUTIL"); temp_image_command << " create"; temp_image_command << " -ov"; temp_image_command << " -srcfolder \"" << staging.str() << "\""; temp_image_command << " -volname \"" << cpack_dmg_volume_name << "\""; temp_image_command << " -format UDRW"; temp_image_command << " \"" << temp_image << "\""; if(!this->RunCommand(temp_image_command)) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Error generating temporary disk image." << std::endl); return 0; } // Optionally set the custom icon flag for the image ... if(!cpack_package_icon.empty()) { cmOStringStream temp_mount; cmOStringStream attach_command; attach_command << this->GetOption("CPACK_COMMAND_HDIUTIL"); attach_command << " attach"; attach_command << " \"" << temp_image << "\""; std::string attach_output; if(!this->RunCommand(attach_command, &attach_output)) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Error attaching temporary disk image." << std::endl); return 0; } cmsys::RegularExpression mountpoint_regex(".*(/Volumes/[^\n]+)\n.*"); mountpoint_regex.find(attach_output.c_str()); temp_mount << mountpoint_regex.match(1); cmOStringStream setfile_command; setfile_command << this->GetOption("CPACK_COMMAND_SETFILE"); setfile_command << " -a C"; setfile_command << " \"" << temp_mount.str() << "\""; if(!this->RunCommand(setfile_command)) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Error assigning custom icon to temporary disk image." << std::endl); return 0; } cmOStringStream detach_command; detach_command << this->GetOption("CPACK_COMMAND_HDIUTIL"); detach_command << " detach"; detach_command << " \"" << temp_mount.str() << "\""; if(!this->RunCommand(detach_command)) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Error detaching temporary disk image." << std::endl); return 0; } } if(!cpack_license_file.empty()) { std::string sla_r = this->GetOption("CPACK_TOPLEVEL_DIRECTORY"); sla_r += "/sla.r"; std::ifstream ifs; ifs.open(cpack_license_file.c_str()); if(ifs.is_open()) { cmGeneratedFileStream osf(sla_r.c_str()); osf << "#include <CoreServices/CoreServices.r>\n\n"; osf << SLAHeader; osf << "\n"; osf << "data 'TEXT' (5002, \"English\") {\n"; while(ifs.good()) { std::string line; std::getline(ifs, line); // escape quotes std::string::size_type pos = line.find('\"'); while(pos != std::string::npos) { line.replace(pos, 1, "\\\""); pos = line.find('\"', pos+2); } osf << " \"" << line << "\\n\"\n"; } osf << "};\n"; osf << "\n"; osf << SLASTREnglish; ifs.close(); osf.close(); } // convert to UDCO std::string temp_udco = this->GetOption("CPACK_TOPLEVEL_DIRECTORY"); temp_udco += "/temp-udco.dmg"; cmOStringStream udco_image_command; udco_image_command << this->GetOption("CPACK_COMMAND_HDIUTIL"); udco_image_command << " convert \"" << temp_image << "\""; udco_image_command << " -format UDCO"; udco_image_command << " -o \"" << temp_udco << "\""; std::string error; if(!this->RunCommand(udco_image_command, &error)) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Error converting to UDCO dmg for adding SLA." << std::endl << error << std::endl); return 0; } // unflatten dmg cmOStringStream unflatten_command; unflatten_command << this->GetOption("CPACK_COMMAND_HDIUTIL"); unflatten_command << " unflatten "; unflatten_command << "\"" << temp_udco << "\""; if(!this->RunCommand(unflatten_command, &error)) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Error unflattening dmg for adding SLA." << std::endl << error << std::endl); return 0; } // Rez the SLA cmOStringStream embed_sla_command; embed_sla_command << this->GetOption("CPACK_COMMAND_REZ"); embed_sla_command << " \"" << sla_r << "\""; embed_sla_command << " -a -o "; embed_sla_command << "\"" << temp_udco << "\""; if(!this->RunCommand(embed_sla_command, &error)) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Error adding SLA." << std::endl << error << std::endl); return 0; } // flatten dmg cmOStringStream flatten_command; flatten_command << this->GetOption("CPACK_COMMAND_HDIUTIL"); flatten_command << " flatten "; flatten_command << "\"" << temp_udco << "\""; if(!this->RunCommand(flatten_command, &error)) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Error flattening dmg for adding SLA." << std::endl << error << std::endl); return 0; } temp_image = temp_udco; } // Create the final compressed read-only disk image ... cmOStringStream final_image_command; final_image_command << this->GetOption("CPACK_COMMAND_HDIUTIL"); final_image_command << " convert \"" << temp_image << "\""; final_image_command << " -format "; final_image_command << cpack_dmg_format; final_image_command << " -imagekey"; final_image_command << " zlib-level=9"; final_image_command << " -o \"" << output_file << "\""; if(!this->RunCommand(final_image_command)) { cmCPackLogger(cmCPackLog::LOG_ERROR, "Error compressing disk image." << std::endl); return 0; } return 1; } bool cmCPackDragNDropGenerator::SupportsComponentInstallation() const { return true; } std::string cmCPackDragNDropGenerator::GetComponentInstallDirNameSuffix( const std::string& componentName) { // we want to group components together that go in the same dmg package std::string package_file_name = this->GetOption("CPACK_PACKAGE_FILE_NAME"); // we have 3 mutually exclusive modes to work in // 1. all components in one package // 2. each group goes in its own package with left over // components in their own package // 3. ignore groups - if grouping is defined, it is ignored // and each component goes in its own package if(this->componentPackageMethod == ONE_PACKAGE) { return "ALL_IN_ONE"; } if(this->componentPackageMethod == ONE_PACKAGE_PER_GROUP) { // We have to find the name of the COMPONENT GROUP // the current COMPONENT belongs to. std::string groupVar = "CPACK_COMPONENT_" + cmSystemTools::UpperCase(componentName) + "_GROUP"; const char* _groupName = GetOption(groupVar.c_str()); if (_groupName) { std::string groupName = _groupName; groupName = GetComponentPackageFileName(package_file_name, groupName, true); return groupName; } } return GetComponentPackageFileName(package_file_name, componentName, false); }
30.057725
79
0.618787
[ "vector" ]
78d298ebc6e7d70a938e31f15cd18833ed3c5882
6,337
cpp
C++
wxWidgets-3.1.0/src/msw/gauge.cpp
screwjack/nemesis
8c2587d2aa60f8da6cf49e5f4f5740bf2666c6fd
[ "BSD-2-Clause" ]
2
2016-10-15T05:12:16.000Z
2016-11-06T16:19:53.000Z
wxWidgets-3.1.0/src/msw/gauge.cpp
screwjack/nemesis
8c2587d2aa60f8da6cf49e5f4f5740bf2666c6fd
[ "BSD-2-Clause" ]
14
2016-09-21T21:24:46.000Z
2016-11-15T07:54:21.000Z
wxWidgets-3.1.0/src/msw/gauge.cpp
screwjack/nemesis
8c2587d2aa60f8da6cf49e5f4f5740bf2666c6fd
[ "BSD-2-Clause" ]
null
null
null
///////////////////////////////////////////////////////////////////////////// // Name: src/msw/gauge.cpp // Purpose: wxGauge class // Author: Julian Smart // Modified by: // Created: 01/02/97 // Copyright: (c) Julian Smart // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #if wxUSE_GAUGE #include "wx/gauge.h" #ifndef WX_PRECOMP #include "wx/app.h" #include "wx/msw/wrapcctl.h" // include <commctrl.h> "properly" #endif #include "wx/appprogress.h" #include "wx/msw/private.h" // ---------------------------------------------------------------------------- // constants // ---------------------------------------------------------------------------- // old commctrl.h (< 4.71) don't have those #ifndef PBS_SMOOTH #define PBS_SMOOTH 0x01 #endif #ifndef PBS_VERTICAL #define PBS_VERTICAL 0x04 #endif #ifndef PBM_SETBARCOLOR #define PBM_SETBARCOLOR (WM_USER+9) #endif #ifndef PBM_SETBKCOLOR #define PBM_SETBKCOLOR 0x2001 #endif #ifndef PBS_MARQUEE #define PBS_MARQUEE 0x08 #endif #ifndef PBM_SETMARQUEE #define PBM_SETMARQUEE (WM_USER+10) #endif // ---------------------------------------------------------------------------- // wxWin macros // ---------------------------------------------------------------------------- // ============================================================================ // wxGauge implementation // ============================================================================ // ---------------------------------------------------------------------------- // wxGauge creation // ---------------------------------------------------------------------------- bool wxGauge::Create(wxWindow *parent, wxWindowID id, int range, const wxPoint& pos, const wxSize& size, long style, const wxValidator& validator, const wxString& name) { if ( !CreateControl(parent, id, pos, size, style, validator, name) ) return false; if ( !MSWCreateControl(PROGRESS_CLASS, wxEmptyString, pos, size) ) return false; // in case we need to emulate indeterminate mode... m_nDirection = wxRIGHT; SetRange(range); InitProgressIndicatorIfNeeded(); return true; } wxGauge::~wxGauge() { } WXDWORD wxGauge::MSWGetStyle(long style, WXDWORD *exstyle) const { WXDWORD msStyle = wxControl::MSWGetStyle(style, exstyle); if ( style & wxGA_VERTICAL ) msStyle |= PBS_VERTICAL; if ( style & wxGA_SMOOTH ) msStyle |= PBS_SMOOTH; return msStyle; } // ---------------------------------------------------------------------------- // wxGauge geometry // ---------------------------------------------------------------------------- wxSize wxGauge::DoGetBestSize() const { // Windows HIG (http://msdn.microsoft.com/en-us/library/aa511279.aspx) // suggest progress bar size of "107 or 237 x 8 dialog units". Let's use // the smaller one. if (HasFlag(wxGA_VERTICAL)) return ConvertDialogToPixels(wxSize(8, 107)); else return ConvertDialogToPixels(wxSize(107, 8)); } // ---------------------------------------------------------------------------- // wxGauge setters // ---------------------------------------------------------------------------- void wxGauge::SetRange(int r) { // Changing range implicitly means we're using determinate mode. if ( IsInIndeterminateMode() ) SetDeterminateMode(); wxGaugeBase::SetRange(r); #ifdef PBM_SETRANGE32 ::SendMessage(GetHwnd(), PBM_SETRANGE32, 0, r); #else // !PBM_SETRANGE32 // fall back to PBM_SETRANGE (limited to 16 bits) ::SendMessage(GetHwnd(), PBM_SETRANGE, 0, MAKELPARAM(0, r)); #endif // PBM_SETRANGE32/!PBM_SETRANGE32 } void wxGauge::SetValue(int pos) { // Setting the value implicitly means that we're using determinate mode. if ( IsInIndeterminateMode() ) SetDeterminateMode(); if ( GetValue() != pos ) { wxGaugeBase::SetValue(pos); ::SendMessage(GetHwnd(), PBM_SETPOS, pos, 0); } } bool wxGauge::SetForegroundColour(const wxColour& col) { if ( !wxControl::SetForegroundColour(col) ) return false; ::SendMessage(GetHwnd(), PBM_SETBARCOLOR, 0, (LPARAM)wxColourToRGB(col)); return true; } bool wxGauge::SetBackgroundColour(const wxColour& col) { if ( !wxControl::SetBackgroundColour(col) ) return false; ::SendMessage(GetHwnd(), PBM_SETBKCOLOR, 0, (LPARAM)wxColourToRGB(col)); return true; } bool wxGauge::IsInIndeterminateMode() const { return (::GetWindowLong(GetHwnd(), GWL_STYLE) & PBS_MARQUEE) != 0; } void wxGauge::SetIndeterminateMode() { // Switch the control into indeterminate mode if necessary. if ( !IsInIndeterminateMode() ) { const long style = ::GetWindowLong(GetHwnd(), GWL_STYLE); ::SetWindowLong(GetHwnd(), GWL_STYLE, style | PBS_MARQUEE); ::SendMessage(GetHwnd(), PBM_SETMARQUEE, TRUE, 0); } } void wxGauge::SetDeterminateMode() { if ( IsInIndeterminateMode() ) { const long style = ::GetWindowLong(GetHwnd(), GWL_STYLE); ::SendMessage(GetHwnd(), PBM_SETMARQUEE, FALSE, 0); ::SetWindowLong(GetHwnd(), GWL_STYLE, style & ~PBS_MARQUEE); } } void wxGauge::Pulse() { if (wxApp::GetComCtl32Version() >= 600) { // switch to indeterminate mode if required SetIndeterminateMode(); SendMessage(GetHwnd(), PBM_STEPIT, 0, 0); if ( m_appProgressIndicator ) m_appProgressIndicator->Pulse(); } else { // emulate indeterminate mode wxGaugeBase::Pulse(); } } #endif // wxUSE_GAUGE
26.62605
79
0.497396
[ "geometry" ]
78d30a0132f60b25a0b89c8331abdb379235a412
1,099
hpp
C++
include/PlayingState.hpp
aebarber/LD40
053071cc49c105b662ae948881be222d4a5e4803
[ "MIT" ]
null
null
null
include/PlayingState.hpp
aebarber/LD40
053071cc49c105b662ae948881be222d4a5e4803
[ "MIT" ]
null
null
null
include/PlayingState.hpp
aebarber/LD40
053071cc49c105b662ae948881be222d4a5e4803
[ "MIT" ]
null
null
null
#ifndef H_CLASS_PLAYINGSTATE #define H_CLASS_PLAYINGSTATE #include <functional> #include <memory> #include <SFML/Graphics.hpp> #include <ArcticWolf/GameState.hpp> #include <ArcticWolf/GameStateManager.hpp> #include <ArcticWolf/Controller.hpp> #include <ArcticWolf/LoopKeybinding.hpp> #include "World.hpp" class PlayingState : public aw::GameState { public: static const bool transparentRender = false; static const bool transparentUpdate = false; static const bool transparentInput = false; PlayingState (); ~PlayingState () override = default; PlayingState (PlayingState&&) = default; PlayingState& operator = (PlayingState&&) = default; PlayingState (const PlayingState&) = default; PlayingState& operator = (const PlayingState&) = default; void onActivate () override; void onDeactivate () override; void onPush () override; void onPop () override; void onAscend () override; void onDescend () override; void render (double) override; void update () override; private: std::unique_ptr<World> m_world; }; #endif
23.382979
61
0.717015
[ "render" ]
78d3d70e7b2debbf546d1076016943a853caf810
3,994
cc
C++
src/deduplication/source/PartitionTensorBlockSharedPageIterator.cc
venkate5hgunda/CSE598-Spring22-Group22-NetsDB
6c2dabd1a3b3f5901a97c788423fdd93cc0015d4
[ "Apache-2.0" ]
13
2022-01-17T16:14:26.000Z
2022-03-30T02:06:04.000Z
src/deduplication/source/PartitionTensorBlockSharedPageIterator.cc
venkate5hgunda/CSE598-Spring22-Group22-NetsDB
6c2dabd1a3b3f5901a97c788423fdd93cc0015d4
[ "Apache-2.0" ]
1
2022-01-28T23:17:14.000Z
2022-01-28T23:17:14.000Z
src/deduplication/source/PartitionTensorBlockSharedPageIterator.cc
venkate5hgunda/CSE598-Spring22-Group22-NetsDB
6c2dabd1a3b3f5901a97c788423fdd93cc0015d4
[ "Apache-2.0" ]
3
2022-01-18T02:13:53.000Z
2022-03-06T19:28:19.000Z
#include "FFMatrixBlock.h" #include "PDBDebug.h" #include "PartitionTensorBlockSharedPageIterator.h" #include "FFMatrixBlockIndex.h" namespace pdb { /** * To create a new PartitionTensorBlockSharedPageIterator instance */ PartitionTensorBlockSharedPageIterator::PartitionTensorBlockSharedPageIterator(PageCachePtr cache, PartitionedFilePtr fileOfSharingSet, PartitionedFilePtr fileOfSharedSet, FilePartitionID partitionIdOfSharedSet, SharedFFMatrixBlockSetPtr sharedSet, DatabaseID dbIdOfSharingSet, UserTypeID typeIdOfSharingSet, SetID setIdOfSharingSet) { this->cache = cache; this->fileOfSharingSet = fileOfSharingSet; this->fileOfSharedSet = fileOfSharedSet; this->partitionId = partitionIdOfSharedSet; this->sharedSet = sharedSet; this->dbIdOfSharingSet = dbIdOfSharingSet; this->typeIdOfSharingSet = typeIdOfSharingSet; this->setIdOfSharingSet = setIdOfSharingSet; this->sharedPageMap = this->fileOfSharingSet->getSharedPageMap(partitionId); this->it = sharedPageMap->begin(); this->numPages = sharedPageMap->size(); this->numIteratedPages = 0; std::cout << "PartitionTensorBlockSharedPageIterator: " << numPages << " to scan in partition-" << partitionId << std::endl; } /** * To return the next page. If there is no more page, return nullptr. */ PDBPagePtr PartitionTensorBlockSharedPageIterator::next() { PDBPagePtr pageToReturn; if (it != this->sharedPageMap->end()) { PageID pageId = it->first; PageIndex pageIndex = it->second; std::cout << this->partitionId << ": PartitionedTensorBlockSharedPageIterator: curTypeId=" << this->fileOfSharedSet->getTypeId() << ",curSetId=" << this->fileOfSharedSet->getSetId() << ",curPageId=" << pageId << ",partitionId="<<pageIndex.partitionId << ",pageSeqId=" << pageIndex.pageSeqInPartition << "\n"; pageToReturn = cache->getPage(this->fileOfSharedSet, pageIndex.partitionId, pageIndex.pageSeqInPartition, pageId, false, nullptr); //MODIFY THE BLOCK's METADATA HERE //Fetch the vector Record<Vector<Handle<FFMatrixBlock>>>*myRec = (Record<Vector<Handle<FFMatrixBlock>>>*)pageToReturn->getBytes(); Handle<Vector<Handle<FFMatrixBlock>>> iterateOverMe = myRec->getRootObject(); for (int i = 0; i < iterateOverMe->size(); i++) { Handle<FFMatrixBlock> block = (*iterateOverMe)[i]; //we borrow the totalRows field to store the static blockRowId, and the totalCols field to store the static blockColId Handle<FFMatrixMeta> targetMeta = sharedSet->getTargetMetadata(dbIdOfSharingSet, typeIdOfSharingSet, setIdOfSharingSet, block->meta->distinctBlockId); if(targetMeta != nullptr) { block->meta->blockRowIndex = targetMeta->blockRowIndex; block->meta->blockColIndex = targetMeta->blockColIndex; block->meta->totalRows = targetMeta->totalRows; block->meta->totalCols = targetMeta->totalCols; } else { std::cout << "ERROR: I didn't find this block with Id=" << block->meta->distinctBlockId << std::endl; block->meta->blockRowIndex = -1; block->meta->blockColIndex = -1; block->meta->totalRows = 0; block->meta->totalCols = 0; } } this->numIteratedPages++; it++; } return pageToReturn; } /** * If there is more page, return true, otherwise return false. */ bool PartitionTensorBlockSharedPageIterator::hasNext() { if ((it != this->sharedPageMap->end())&&(this->numIteratedPages < numPages)) { return true; } else { return false; } } }
43.413043
166
0.631197
[ "vector" ]
78d3f93d82dc410c2e8bfb17c714fd06be0285ce
3,671
cpp
C++
arm9/source/_library/library.color.mediancut.cpp
DuffsDevice/winds
35f1b5fd458c527a6c372f94077e784f6fd960b2
[ "MIT" ]
2
2017-02-07T18:25:07.000Z
2021-12-13T18:29:03.000Z
arm9/source/_library/library.color.mediancut.cpp
DuffsDevice/winds
35f1b5fd458c527a6c372f94077e784f6fd960b2
[ "MIT" ]
null
null
null
arm9/source/_library/library.color.mediancut.cpp
DuffsDevice/winds
35f1b5fd458c527a6c372f94077e784f6fd960b2
[ "MIT" ]
null
null
null
/* The authors of this work have released all rights to it and placed it in the public domain under the Creative Commons CC0 1.0 waiver (http://creativecommons.org/publicdomain/zero/1.0/). 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. Retrieved from: http://en.literateprograms.org/Median_cut_algorithm_(C_Plus_Plus)?oldid=19175 */ #include <limits> #include <queue> #include <algorithm> #include <_library/library.color.mediancut.h> Block::Block(Point* points, int pointsLength) { this->points = points; this->pointsLength = pointsLength; for(int i=0; i < NUM_DIMENSIONS; i++) { minCorner.x[i] = std::numeric_limits<unsigned char>::min(); maxCorner.x[i] = std::numeric_limits<unsigned char>::max(); } } Point * Block::getPoints() { return points; } int Block::numPoints() const { return pointsLength; } int Block::longestSideIndex() const { int m = maxCorner.x[0] - minCorner.x[0]; int maxIndex = 0; for(int i=1; i < NUM_DIMENSIONS; i++) { int diff = maxCorner.x[i] - minCorner.x[i]; if (diff > m) { m = diff; maxIndex = i; } } return maxIndex; } int Block::longestSideLength() const { int i = longestSideIndex(); return maxCorner.x[i] - minCorner.x[i]; } bool Block::operator<(const Block& rhs) const { return this->longestSideLength() < rhs.longestSideLength(); } void Block::shrink() { int i,j; for(j=0; j<NUM_DIMENSIONS; j++) { minCorner.x[j] = maxCorner.x[j] = points[0].x[j]; } for(i=1; i < pointsLength; i++) { for(j=0; j<NUM_DIMENSIONS; j++) { minCorner.x[j] = std::min(minCorner.x[j], points[i].x[j]); maxCorner.x[j] = std::max(maxCorner.x[j], points[i].x[j]); } } } std::vector<Point> medianCut(Point* image, int numPoints, unsigned int desiredSize) { std::priority_queue<Block> blockQueue; Block initialBlock(image, numPoints); initialBlock.shrink(); blockQueue.push(initialBlock); while (blockQueue.size() < desiredSize) { Block longestBlock = blockQueue.top(); blockQueue.pop(); Point * begin = longestBlock.getPoints(); Point * median = longestBlock.getPoints() + (longestBlock.numPoints()+1)/2; Point * end = longestBlock.getPoints() + longestBlock.numPoints(); switch(longestBlock.longestSideIndex()) { case 0: std::nth_element(begin, median, end, CoordinatePointComparator<0>()); break; case 1: std::nth_element(begin, median, end, CoordinatePointComparator<1>()); break; case 2: std::nth_element(begin, median, end, CoordinatePointComparator<2>()); break; } Block block1(begin, median-begin), block2(median, end-median); block1.shrink(); block2.shrink(); blockQueue.push(block1); blockQueue.push(block2); } std::vector<Point> result{ blockQueue.size() }; while(!blockQueue.empty()) { Block block = blockQueue.top(); blockQueue.pop(); Point * points = block.getPoints(); int sum[NUM_DIMENSIONS] = {0}; for(int i=0; i < block.numPoints(); i++) for(int j=0; j < NUM_DIMENSIONS; j++) sum[j] += points[i].x[j]; Point averagePoint; for(int j=0; j < NUM_DIMENSIONS; j++) averagePoint.x[j] = sum[j] / block.numPoints(); result.push_back(averagePoint); } return result; }
28.457364
94
0.672569
[ "vector" ]
78d645533bf31fc24fd6b4f74ec85687e6e6b35d
7,649
cc
C++
third_party/blink/renderer/core/paint/ng/ng_paint_fragment_traversal_test.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/blink/renderer/core/paint/ng/ng_paint_fragment_traversal_test.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/blink/renderer/core/paint/ng/ng_paint_fragment_traversal_test.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/core/paint/ng/ng_paint_fragment_traversal.h" #include "testing/gmock/include/gmock/gmock.h" #include "third_party/blink/renderer/core/layout/layout_block_flow.h" #include "third_party/blink/renderer/core/paint/ng/ng_paint_fragment.h" #include "third_party/blink/renderer/core/testing/core_unit_test_helper.h" namespace blink { using testing::ElementsAreArray; class NGPaintFragmentTraversalTest : public RenderingTest, private ScopedLayoutNGForTest { public: NGPaintFragmentTraversalTest() : RenderingTest(nullptr), ScopedLayoutNGForTest(true) {} protected: void SetUpHtml(const char* container_id, const char* html) { SetBodyInnerHTML(html); layout_block_flow_ = To<LayoutBlockFlow>(GetLayoutObjectByElementId(container_id)); root_fragment_ = layout_block_flow_->PaintFragment(); } const NGPaintFragment::ChildList RootChildren() const { return root_fragment_->Children(); } Vector<const NGPaintFragment*> ToDepthFirstList( NGPaintFragmentTraversal* traversal) const { Vector<const NGPaintFragment*> results; for (; *traversal; traversal->MoveToNext()) { const NGPaintFragment& fragment = **traversal; results.push_back(&fragment); } return results; } Vector<const NGPaintFragment*> ToReverseDepthFirstList( NGPaintFragmentTraversal* traversal) const { Vector<const NGPaintFragment*> results; for (; *traversal; traversal->MoveToPrevious()) { const NGPaintFragment& fragment = **traversal; results.push_back(&fragment); } return results; } Vector<NGPaintFragment*, 16> ToList( const NGPaintFragment::ChildList& children) { Vector<NGPaintFragment*, 16> list; children.ToList(&list); return list; } LayoutBlockFlow* layout_block_flow_; const NGPaintFragment* root_fragment_; }; TEST_F(NGPaintFragmentTraversalTest, MoveToNext) { if (RuntimeEnabledFeatures::LayoutNGFragmentItemEnabled()) return; SetUpHtml("t", R"HTML( <div id=t> line0 <span style="background: red">red</span> <br> line1 </div> )HTML"); NGPaintFragmentTraversal traversal(*root_fragment_); NGPaintFragment* line0 = root_fragment_->FirstChild(); NGPaintFragment* line1 = ToList(root_fragment_->Children())[1]; NGPaintFragment* span = ToList(line0->Children())[1]; NGPaintFragment* br = ToList(line0->Children())[2]; EXPECT_THAT( ToDepthFirstList(&traversal), ElementsAreArray({line0, line0->FirstChild(), span, span->FirstChild(), br, line1, line1->FirstChild()})); } TEST_F(NGPaintFragmentTraversalTest, MoveToNextWithRoot) { if (RuntimeEnabledFeatures::LayoutNGFragmentItemEnabled()) return; SetUpHtml("t", R"HTML( <div id=t> line0 <span style="background: red">red</span> <br> line1 </div> )HTML"); NGPaintFragment* line0 = root_fragment_->FirstChild(); NGPaintFragment* span = ToList(line0->Children())[1]; NGPaintFragment* br = ToList(line0->Children())[2]; NGPaintFragmentTraversal traversal(*line0); EXPECT_THAT( ToDepthFirstList(&traversal), ElementsAreArray({line0->FirstChild(), span, span->FirstChild(), br})); } TEST_F(NGPaintFragmentTraversalTest, MoveToPrevious) { if (RuntimeEnabledFeatures::LayoutNGFragmentItemEnabled()) return; SetUpHtml("t", R"HTML( <div id=t> line0 <span style="background: red">red</span> <br> line1 </div> )HTML"); NGPaintFragmentTraversal traversal(*root_fragment_); NGPaintFragment* line0 = root_fragment_->FirstChild(); NGPaintFragment* line1 = ToList(root_fragment_->Children())[1]; NGPaintFragment* span = ToList(line0->Children())[1]; NGPaintFragment* br = ToList(line0->Children())[2]; traversal.MoveTo(*line1->FirstChild()); EXPECT_THAT( ToReverseDepthFirstList(&traversal), ElementsAreArray({line1->FirstChild(), line1, br, span->FirstChild(), span, line0->FirstChild(), line0})); } TEST_F(NGPaintFragmentTraversalTest, MoveToPreviousWithRoot) { if (RuntimeEnabledFeatures::LayoutNGFragmentItemEnabled()) return; SetUpHtml("t", R"HTML( <div id=t> line0 <span style="background: red">red</span> <br> line1 </div> )HTML"); NGPaintFragment* line0 = root_fragment_->FirstChild(); NGPaintFragment* span = ToList(line0->Children())[1]; NGPaintFragment* br = ToList(line0->Children())[2]; NGPaintFragmentTraversal traversal(*line0); traversal.MoveTo(*br); EXPECT_THAT( ToReverseDepthFirstList(&traversal), ElementsAreArray({br, span->FirstChild(), span, line0->FirstChild()})); } TEST_F(NGPaintFragmentTraversalTest, MoveTo) { if (RuntimeEnabledFeatures::LayoutNGFragmentItemEnabled()) return; SetUpHtml("t", R"HTML( <div id=t> line0 <span style="background: red">red</span> <br> line1 </div> )HTML"); NGPaintFragmentTraversal traversal(*root_fragment_); NGPaintFragment* line0 = root_fragment_->FirstChild(); NGPaintFragment* line1 = ToList(root_fragment_->Children())[1]; NGPaintFragment* span = ToList(line0->Children())[1]; NGPaintFragment* br = ToList(line0->Children())[2]; traversal.MoveTo(*span); EXPECT_EQ(span, &*traversal); EXPECT_THAT(ToDepthFirstList(&traversal), ElementsAreArray( {span, span->FirstChild(), br, line1, line1->FirstChild()})); } TEST_F(NGPaintFragmentTraversalTest, MoveToWithRoot) { if (RuntimeEnabledFeatures::LayoutNGFragmentItemEnabled()) return; SetUpHtml("t", R"HTML( <div id=t> line0 <span style="background: red">red</span> <br> line1 </div> )HTML"); NGPaintFragment* line0 = root_fragment_->FirstChild(); NGPaintFragment* span = ToList(line0->Children())[1]; NGPaintFragment* br = ToList(line0->Children())[2]; NGPaintFragmentTraversal traversal(*line0); traversal.MoveTo(*span); EXPECT_EQ(span, &*traversal); EXPECT_THAT(ToDepthFirstList(&traversal), ElementsAreArray({span, span->FirstChild(), br})); } TEST_F(NGPaintFragmentTraversalTest, InlineDescendantsOf) { if (RuntimeEnabledFeatures::LayoutNGFragmentItemEnabled()) return; SetUpHtml("t", "<ul>" "<li id=t style='position: absolute'>" "<span style='float: right'>float</span>" "<span style='position: absolute'>oof</span>" "text<br>" "<span style='display: inline-block'>inline block</span>" "</li>" "</ul>"); // Tests that floats, out-of-flow positioned and descendants of atomic inlines // are excluded. Vector<const NGPaintFragment*> descendants; for (const NGPaintFragment* fragment : NGPaintFragmentTraversal::InlineDescendantsOf(*root_fragment_)) descendants.push_back(fragment); ASSERT_EQ(6u, descendants.size()); // TODO(layout-dev): This list marker is not in any line box. Should it be // treated as inline? EXPECT_TRUE(descendants[0]->PhysicalFragment().IsListMarker()); EXPECT_TRUE(descendants[1]->PhysicalFragment().IsLineBox()); EXPECT_TRUE(descendants[2]->PhysicalFragment().IsText()); // "text" EXPECT_TRUE(descendants[3]->PhysicalFragment().IsText()); // "br" EXPECT_TRUE(descendants[4]->PhysicalFragment().IsLineBox()); EXPECT_TRUE(descendants[5]->PhysicalFragment().IsAtomicInline()); } } // namespace blink
33.845133
81
0.690548
[ "vector" ]
78d6e4445f9feccda28e8c2ef4d6d31c97efc418
3,725
cpp
C++
corelib/src/Camera.cpp
nuclearsandwich-ros/rtabmap-release
c6ee39bea83b6a5edf9da3214494d67c6c055a2e
[ "BSD-3-Clause" ]
null
null
null
corelib/src/Camera.cpp
nuclearsandwich-ros/rtabmap-release
c6ee39bea83b6a5edf9da3214494d67c6c055a2e
[ "BSD-3-Clause" ]
null
null
null
corelib/src/Camera.cpp
nuclearsandwich-ros/rtabmap-release
c6ee39bea83b6a5edf9da3214494d67c6c055a2e
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2010-2016, Mathieu Labbe - IntRoLab - Universite de Sherbrooke 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 Universite de Sherbrooke nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "rtabmap/core/Camera.h" #include <rtabmap/utilite/UEventsManager.h> #include <rtabmap/utilite/UConversion.h> #include <rtabmap/utilite/UStl.h> #include <rtabmap/utilite/UConversion.h> #include <rtabmap/utilite/UFile.h> #include <rtabmap/utilite/UDirectory.h> #include <rtabmap/utilite/UTimer.h> #include <opencv2/imgproc/imgproc.hpp> #include <iostream> #include <cmath> namespace rtabmap { Camera::Camera(float imageRate, const Transform & localTransform) : _imageRate(imageRate), _localTransform(localTransform*CameraModel::opticalRotation()), _targetImageSize(0,0), _frameRateTimer(new UTimer()), _seq(0) { } Camera::~Camera() { UDEBUG(""); delete _frameRateTimer; UDEBUG(""); } void Camera::resetTimer() { _frameRateTimer->start(); } bool Camera::initFromFile(const std::string & calibrationPath) { return init(UDirectory::getDir(calibrationPath), uSplit(UFile::getName(calibrationPath), '.').front()); } SensorData Camera::takeImage(CameraInfo * info) { bool warnFrameRateTooHigh = false; float actualFrameRate = 0; float imageRate = _imageRate; if(imageRate>0) { int sleepTime = (1000.0f/imageRate - 1000.0f*_frameRateTimer->getElapsedTime()); if(sleepTime > 2) { uSleep(sleepTime-2); } else if(sleepTime < 0) { warnFrameRateTooHigh = true; actualFrameRate = 1.0/(_frameRateTimer->getElapsedTime()); } // Add precision at the cost of a small overhead while(_frameRateTimer->getElapsedTime() < 1.0/double(imageRate)-0.000001) { // } double slept = _frameRateTimer->getElapsedTime(); _frameRateTimer->start(); UDEBUG("slept=%fs vs target=%fs", slept, 1.0/double(imageRate)); } UTimer timer; SensorData data = this->captureImage(info); double captureTime = timer.ticks(); if(warnFrameRateTooHigh) { UWARN("Camera: Cannot reach target image rate %f Hz, current rate is %f Hz and capture time = %f s.", imageRate, actualFrameRate, captureTime); } else { UDEBUG("Time capturing image = %fs", captureTime); } if(info) { info->id = data.id(); info->stamp = data.stamp(); info->timeCapture = captureTime; } return data; } } // namespace rtabmap
30.284553
104
0.747919
[ "transform" ]
78dd96b7539fa2a594780b5ba7e69c6360a3f7a4
1,252
cpp
C++
testgen/kinout.cpp
LaughingBudda/hachikuji
0d65ecec12dd843dfb7e3828ac3b5c3824ce6901
[ "MIT" ]
null
null
null
testgen/kinout.cpp
LaughingBudda/hachikuji
0d65ecec12dd843dfb7e3828ac3b5c3824ce6901
[ "MIT" ]
null
null
null
testgen/kinout.cpp
LaughingBudda/hachikuji
0d65ecec12dd843dfb7e3828ac3b5c3824ce6901
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main(int argc, char **argv) { mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); int n = 100, in = 10, out=10; if (argc > 1) { n = atoi( argv[1] ); } if (argc > 2) { in = atoi( argv[2] ); } if (argc > 3) { out = atoi( argv[3] ); } if (in > n || out > n) { cerr << "k cannot be greater than n\n"; return 0; } set<array<int, 2>> E; vector<int> perm(n); for(int i=0; i<n; ++i) perm[i]=i; //shuffle(perm.begin(), perm.end(), rng); for(int i=0; i<n; ++i) { for(int j=0; j<in; ++j) { int x = uniform_int_distribution<int>(0, n)(rng); if (E.find({x, i}) == E.end()) E.insert({x, i}); else j--; } for(int j=0; j<out; ++j) { int x = uniform_int_distribution<int>(0, n)(rng); if (E.find({i, x}) == E.end()) E.insert({i, x}); else j--; } } cout << n << " " << E.size() << endl; for(auto it : E) cout << perm[it[0]] << " " << perm[it[1]] << endl; //for(auto it : E) cout << it[0] << " " << it[1] << endl; }
26.083333
72
0.416134
[ "vector" ]
78e090ea0c01bbb9f0e6f3ae3091173b508f7fd9
5,455
cpp
C++
docs/C++/Experts/TODO-Thomas-Kim/CppExtension/tutorial/030-execution_policy.cpp
dengking/python-in-action
82587961a9f12be09e60d20e11ccbee5bb0aa027
[ "Apache-2.0" ]
null
null
null
docs/C++/Experts/TODO-Thomas-Kim/CppExtension/tutorial/030-execution_policy.cpp
dengking/python-in-action
82587961a9f12be09e60d20e11ccbee5bb0aa027
[ "Apache-2.0" ]
null
null
null
docs/C++/Experts/TODO-Thomas-Kim/CppExtension/tutorial/030-execution_policy.cpp
dengking/python-in-action
82587961a9f12be09e60d20e11ccbee5bb0aa027
[ "Apache-2.0" ]
null
null
null
#include <tpf_output.hpp> #include <tpf_chrono_random.hpp> #include <execution> // for Parallel Algorithm tpf::sstream stream; auto nl = tpf::nl; auto endl = tpf::endl; template<typename ElementType> class vector_3d { public: using element_type = ElementType; private: element_type m_x, m_y, m_z, m_color; public: vector_3d() {} vector_3d(element_type x, element_type y, element_type z): m_x{x}, m_y{y}, m_z{z} { } // vector cross product friend vector_3d operator*(const vector_3d& L, const vector_3d& R) { // auto x = L.m_y * R.m_z - L.m_z * R.m_y; // auto y = L.m_z * R.m_x - L.m_x * R.m_z; // auto z = L.m_x * R.m_y - L.m_y * R.m_x; return { L.m_y * R.m_z - L.m_z * R.m_y, L.m_z * R.m_x - L.m_x * R.m_z, L.m_x * R.m_y - L.m_y * R.m_x}; } friend std::ostream& operator<<(std::ostream& os, const vector_3d& v) { os << "< " << v.m_x << ", " << v.m_y <<", " << v.m_z <<" >"; return os; } }; void test_vector_3d() { vector_3d<double> x{1, 0, 0}, y{0, 1, 0}, z{0, 0, 1}; auto v1 = y * z; // < 1, 0, 0 > auto v2 = z * x; // < 0, 1, 0 > auto v3 = x * y; // < 0, 0, 1 > stream << "x = " << x<<", y = " << y <<", z = " << z << nl; stream << "v1 = " << v1 <<", v2 = " << v2 <<", v3 = " << v3 << endl; } template<typename ExecutionPolicy> void naive_dangerous_parallel_algorithm(ExecutionPolicy policy, size_t test_count, size_t element_count) { std::vector<vector_3d<float>> points; // 3 dimensional points points.reserve(element_count); // random number generator generating floats // ranging from -10 to +10 auto generator = tpf::chrono_random::random_generator<float>(-10, +10); vector_3d<float> rhs{generator(), generator(), generator()}; for(size_t i = 0; i < element_count; ++i) // generate 3 floats and initialize vector_3d elements points.emplace_back(generator(), generator(), generator()); // stream <<"Before Cross Product: \n" << points << nl; tpf::chrono_random::stop_watch sw; for(size_t i = 0; i < test_count; ++i) { sw.reset(); std::transform(policy, points.begin(), points.end(), points.begin(), [&rhs](const auto& lhs){ return lhs * rhs; } ); stream << "Elapsed - " << sw.elapsed_time() << nl; } // without endl, we cannot see anything stream << endl; // stream <<"\nAfter Cross Product: \n" << points << endl; } void test_naive_dangerous_parallel_algorithm() { size_t element_count = 10'000'000; stream <<"Sequential policy: \n"; naive_dangerous_parallel_algorithm(std::execution::seq, 5, element_count); stream <<"\nParallel policy: \n"; naive_dangerous_parallel_algorithm(std::execution::par, 5, element_count); stream <<"\nParallel Unsequenced policy: \n"; naive_dangerous_parallel_algorithm(std::execution::par_unseq, 5, element_count); } //////////////////////// template<typename ExecutionPolicy> void why_naive_dangerous_parallel_algorithm(ExecutionPolicy policy, size_t test_count, size_t element_count) { std::vector<vector_3d<float>> points; // 3 dimensional points points.reserve(element_count); // random number generator generating floats // ranging from -10 to +10 auto generator = tpf::chrono_random::random_generator<float>(-10, +10); vector_3d<float> rhs{generator(), generator(), generator()}; for(size_t i = 0; i < element_count; ++i) // generate 3 floats and initialize vector_3d elements points.emplace_back(generator(), generator(), generator()); // stream <<"Before Cross Product: \n" << points << nl; tpf::chrono_random::stop_watch sw; for(size_t i = 0; i < test_count; ++i) { sw.reset(); std::transform(policy, points.begin(), points.end(), points.begin(), // When we use Parallel Algorithm, // we should be extremely careful not to leak // exceptions from the parallel callback functions. [&rhs](const auto& lhs) { throw 1; // this cause system crash. return lhs * rhs; } ); stream << "Elapsed - " << sw.elapsed_time() << nl; } // without endl, we cannot see anything stream << endl; // stream <<"\nAfter Cross Product: \n" << points << endl; } void test_why_naive_dangerous_parallel_algorithm() { size_t element_count = 10'000'000; try { stream <<"Sequential policy: \n"; why_naive_dangerous_parallel_algorithm(std::execution::seq, 5, element_count); stream <<"You cannot see this message" << endl; } catch(...) { stream << "This does not work - you cannot see this message either" << endl; } // stream <<"\nParallel policy: \n"; // naive_dangerous_parallel_algorithm(std::execution::par, 5, element_count); // stream <<"\nParallel Unsequenced policy: \n"; // naive_dangerous_parallel_algorithm(std::execution::par_unseq, 5, element_count); } int main() { // test_vector_3d(); // test_naive_dangerous_parallel_algorithm(); test_why_naive_dangerous_parallel_algorithm(); }
30.138122
108
0.583685
[ "vector", "transform" ]
78e2077989d43c8ff19a35f22bf5d8bfd1a67024
1,328
cc
C++
tensorflow/psstore/psstore.cc
YanTangZhai/tf
7015863fd126d76b61578ef1278dfb808cc1e2af
[ "Apache-2.0" ]
null
null
null
tensorflow/psstore/psstore.cc
YanTangZhai/tf
7015863fd126d76b61578ef1278dfb808cc1e2af
[ "Apache-2.0" ]
null
null
null
tensorflow/psstore/psstore.cc
YanTangZhai/tf
7015863fd126d76b61578ef1278dfb808cc1e2af
[ "Apache-2.0" ]
null
null
null
/*! * From dmlc/mxnet */ #include <stdlib.h> #include "./psstore.h" #include "./psstore_dist.h" #include "./psstore_dist_server.h" namespace tensorflow { namespace psstore { PSStore* PSStore::Create(const char *type_name, const std::string& args) { std::string tname = type_name; std::transform(tname.begin(), tname.end(), tname.begin(), ::tolower); PSStore* ps = nullptr; if (tname == "dist_async" || tname == "dist_sync" || tname == "dist") { ps = new PSStoreDist(); ps->Run(); if (tname == "dist_sync" && ps->IsWorkerNode() && ps->get_rank() == 0) { // configure the server to be the sync mode ps->SendCommandToServers(psstore::kSyncMode, ""); if (args.size()) { ps->SendCommandToServers(psstore::kInitUpdater, args); } } } else { VLOG(0) << "Unknown PSStore type \"" << tname << "\""; return nullptr; } ps->type_ = tname; return ps; } std::shared_ptr<PSStore> PSStore::_GetSharedRef(const char *type_name, const std::string& args) { static std::shared_ptr<PSStore> sptr(Create(type_name, args)); return sptr; } PSStore* PSStore::Get(const char *type_name, const std::string& args) { static PSStore *inst = _GetSharedRef(type_name, args).get(); return inst; } } // namespace psstore } // namespace tensorflow
27.102041
97
0.631024
[ "transform" ]
78e6e64b0b9d095dd71c615ac5053b8c27e8b1d8
534
cpp
C++
example/app/src/CustomSprite.cpp
Seng3694/TXPK
76a5441dc70b4a5d5d2596525de950a2d2e65aab
[ "MIT" ]
6
2019-01-05T08:14:02.000Z
2021-12-02T18:29:35.000Z
example/app/src/CustomSprite.cpp
lineCode/TXPK
20d4cd75611a44babf2bf41d5359141020dc6684
[ "MIT" ]
1
2018-03-28T06:33:08.000Z
2018-03-29T08:22:43.000Z
example/app/src/CustomSprite.cpp
Seng3694/TexturePacker
76a5441dc70b4a5d5d2596525de950a2d2e65aab
[ "MIT" ]
2
2018-12-11T01:11:20.000Z
2020-10-30T08:14:04.000Z
#include "CustomSprite.hpp" CustomSprite::CustomSprite() { width = 0; height = 0; innerSprite = sf::Sprite(); } void CustomSprite::draw(sf::RenderTarget& target, sf::RenderStates states) const { states.transform.combine(getTransform()); target.draw(innerSprite, states); } unsigned int CustomSprite::getWidth() const { return width; } unsigned int CustomSprite::getHeight() const { return height; } sf::Vector2f CustomSprite::getSize() const { return sf::Vector2f(static_cast<float>(width), static_cast<float>(height)); }
18.413793
80
0.735955
[ "transform" ]
78eb47af6740ed18c2ffe411e50b62d64df320c4
48,727
cpp
C++
src/backends/imgdnn/convert.cpp
codeplaysoftware/TensorOpt
62562f0dc8c15c1ff9ffeee408556d019e0e345c
[ "Apache-2.0" ]
1
2020-12-06T13:24:00.000Z
2020-12-06T13:24:00.000Z
src/backends/imgdnn/convert.cpp
codeplaysoftware/TensorOpt
62562f0dc8c15c1ff9ffeee408556d019e0e345c
[ "Apache-2.0" ]
1
2020-02-06T11:09:50.000Z
2020-02-06T14:30:02.000Z
src/backends/imgdnn/convert.cpp
codeplaysoftware/TensorOpt
62562f0dc8c15c1ff9ffeee408556d019e0e345c
[ "Apache-2.0" ]
1
2021-09-30T21:59:50.000Z
2021-09-30T21:59:50.000Z
/** * Copyright (C) Codeplay Software 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 "backends/imgdnn/convert.hpp" #include <bitset> #include <cstring> #include "backends/imgdnn/compilation.hpp" #include "common/device.hpp" #include "common/model.hpp" #include "common/utils.hpp" namespace { struct Converter { private: // Create negative indices used for internal imgdnn_tensors with a specific // meaning. enum SpecialImgTensor : int64_t { // Create a unique imgdnn_tensor with constant value one CONST_FLOAT32_ONE = 1 }; ANeuralNetworksCompilation* compilation; // weak_ptr const ANeuralNetworksModel* model; // weak_ptr // Store all the imgdnn_tensor created during the conversions // Indices can be stricly negative for internal tensors or positive for // tensors mapping to an operand using indexed_img_tensors = std::unordered_map<int64_t, imgdnn_tensor>; indexed_img_tensors img_tensors; imgdnn_err_code ret; // Offset to convert an exclusive end bound to an inclusive one static constexpr int INCLUSIVE_END = -1; public: Converter(ANeuralNetworksCompilation* c) : compilation(c), model(c->model), img_tensors() {} Converter(const Converter&) = delete; Converter(Converter&&) = default; Converter& operator=(const Converter&) = delete; Converter& operator=(Converter&&) = default; ResultCode operator()() { // Convert const device operands to const host operands owned. // This is needed because IMGDNN backend does not support providing a const // device operand to the network. This makes sense when serializing the // model since all the constant data has to be on the host. This is an // unecessary overhead if the network is not serialized as we would move the // data from device to host here and IMGDNN will move it back to the device // when executing. TensorFlow does not use // ANeuralNetworksModel_setOperandValueFromMemory so this is not an // important issue. std::vector<cl::sycl::event> copy_events; for (auto& pair : model->const_device_operands) { auto& const_host_operand = compilation->const_copied_to_host_operands[pair.first]; // We remove the const here as the model must stay constant but submitting // the copy requires a non-const reference to the buffer. The buffer could // be copied but we would then need to wait after each submit. auto& const_device_operand = const_cast<ANeuralNetworksModel::ConstDeviceOperand&>(pair.second); const_host_operand.resize(const_device_operand.length); auto host_ptr = const_host_operand.data(); tensoropt_buffer_t& buffer = const_device_operand.memory.buffer; auto event = compilation->device->queue->submit([&](cl::sycl::handler& cgh) { auto acc = buffer.get_access<cl::sycl::access::mode::read>( cgh, cl::sycl::range<1>(const_device_operand.length), cl::sycl::id<1>(const_device_operand.offset)); cgh.copy(acc, host_ptr); }); copy_events.push_back(event); } for (auto& event : copy_events) { event.wait_and_throw(); } // Add network inputs for (uint32_t op_idx : model->inputs) { imgdnn_tensor_descriptor img_td; const auto& op = model->operands[op_idx]; TENSOROPT_RETURN_IF_ERROR(RTOperandTypeToImg(op, img_td)); imgdnn_tensor img_tensor; BACKEND_CALL_RET(img_tensor, imgdnnNetworkInput, compilation->imgdnn_network_, &img_td, &ret); IMGDNN_RETURN_ERR_IF_ERROR(ret); if (!img_tensors.insert({op_idx, img_tensor}).second) { VLOG_AT("Error: Input index " << op_idx << " was identified multiple times"); return ANEURALNETWORKS_BAD_DATA; } compilation->imgdnn_inputs_.push_back(img_tensor); } // Add network operations // NNAPI doesn't assume any order in which the operations must be // added but IMGDNN requires that they are added in execution order (by // construction). // TensorFlow already adds the operations in the correct order // TODO: Sort the operations with a pre order traversal for (std::size_t op_idx = 0; op_idx < model->operations.size(); ++op_idx) { const auto& operation = model->operations[op_idx]; switch (operation.type) { case ANEURALNETWORKS_EXP: case ANEURALNETWORKS_RELU: case ANEURALNETWORKS_RELU1: case ANEURALNETWORKS_RELU6: case ANEURALNETWORKS_RSQRT: case ANEURALNETWORKS_SQRT: TENSOROPT_RETURN_IF_ERROR(convertUnary(operation)); break; case ANEURALNETWORKS_ADD: case ANEURALNETWORKS_MUL: case ANEURALNETWORKS_SUB: case ANEURALNETWORKS_DIV: case ANEURALNETWORKS_MAX: case ANEURALNETWORKS_MIN: TENSOROPT_RETURN_IF_ERROR(convertBinary(operation)); break; case ANEURALNETWORKS_AVERAGE_POOL_2D: case ANEURALNETWORKS_MAX_POOL_2D: TENSOROPT_RETURN_IF_ERROR(convertPool(operation)); break; case ANEURALNETWORKS_CONV_2D: case ANEURALNETWORKS_DEPTHWISE_CONV_2D: TENSOROPT_RETURN_IF_ERROR(convertConv2D(operation)); break; case ANEURALNETWORKS_MATMUL: TENSOROPT_RETURN_IF_ERROR(convertMatmul(operation)); break; case ANEURALNETWORKS_TRANSPOSE: TENSOROPT_RETURN_IF_ERROR(convertTranspose(operation)); break; case ANEURALNETWORKS_RESHAPE: TENSOROPT_RETURN_IF_ERROR(convertReshape(operation)); break; case ANEURALNETWORKS_SQUEEZE: TENSOROPT_RETURN_IF_ERROR(convertSqueeze(operation)); break; case ANEURALNETWORKS_CONCATENATION: TENSOROPT_RETURN_IF_ERROR(convertConcat(operation)); break; case ANEURALNETWORKS_SLICE: TENSOROPT_RETURN_IF_ERROR(convertSlice(operation)); break; case ANEURALNETWORKS_STRIDED_SLICE: TENSOROPT_RETURN_IF_ERROR(convertStridedSlice(operation)); break; case ANEURALNETWORKS_SOFTMAX: TENSOROPT_RETURN_IF_ERROR(convertSoftmax(operation)); break; case ANEURALNETWORKS_CAST: TENSOROPT_RETURN_IF_ERROR(convertCast(operation)); break; default: VLOG_AT("Unsupported operation " << operation.type << " at operation index " << op_idx); return ANEURALNETWORKS_OP_FAILED; } // Check the IMGDNN output size matches what TensorOpt expects for (unsigned i = 0; i < operation.outputs.size(); ++i) { auto output_idx = operation.outputs[i]; const ANeuralNetworksOperandType& output_op = model->operands[output_idx]; imgdnn_tensor_descriptor img_td; BACKEND_CALL_RET(ret, imgdnnGetTensorDescriptor, img_tensors[output_idx], &img_td); if (!areShapesEqual(output_op, img_td)) { VLOG_AT( "Unexpected output shape when converting operation #" << op_idx << " (code=" << operation.type << "), output #" << i << ": IMGDNN returned [" << arrayToString(img_td.size, img_td.dimensions) << "] but TensorOpt expected [" << arrayToString(output_op.dimensions, output_op.dimensionCount) << "]"); return ANEURALNETWORKS_OP_FAILED; } } } // Add network outputs for (auto output_idx : model->outputs) { compilation->imgdnn_outputs_.push_back(img_tensors[output_idx]); } return ANEURALNETWORKS_NO_ERROR; } private: /** * Return true if the TensorOpt and IMGDNN shapes are equal. * The 0D TensorOpt shape and 1D IMGDNN shape of size 1 are considered to * be equal. An IMGDNN shape cannot be 0D. */ bool areShapesEqual(const ANeuralNetworksOperandType& topt_op, const imgdnn_tensor_descriptor& img_td) { if (topt_op.dimensionCount == 0 && img_td.dimensions == 1 && img_td.size[0] == 1) { return true; } bool are_shapes_equal = topt_op.dimensionCount == img_td.dimensions; unsigned dim = 0; while (are_shapes_equal && dim < topt_op.dimensionCount) { are_shapes_equal = topt_op.dimensions[dim] == img_td.size[dim]; ++dim; } return are_shapes_equal; } /** * Convert RT enum types to IMGDNN types. */ ResultCode RTCodeToImg(ANeuralNetworksOperandCode code, imgdnn_type& type) { switch (code) { case ANEURALNETWORKS_FLOAT32: case ANEURALNETWORKS_TENSOR_FLOAT32: type = IMGDNN_TYPE_F32; return ANEURALNETWORKS_NO_ERROR; case ANEURALNETWORKS_INT32: case ANEURALNETWORKS_TENSOR_INT32: type = IMGDNN_TYPE_I32; return ANEURALNETWORKS_NO_ERROR; case ANEURALNETWORKS_UINT32: type = IMGDNN_TYPE_U32; return ANEURALNETWORKS_NO_ERROR; case ANEURALNETWORKS_BOOL: case ANEURALNETWORKS_TENSOR_BOOL8: type = IMGDNN_TYPE_U8; return ANEURALNETWORKS_NO_ERROR; default: VLOG_AT("Internal error: invalid OperandCode " << code); return ANEURALNETWORKS_BAD_DATA; } } /** * Convert RT operand type to IMGDNN tensor descriptor. */ ResultCode RTOperandTypeToImg(const ANeuralNetworksOperandType& op, imgdnn_tensor_descriptor& img_td) { TENSOROPT_RETURN_IF_ERROR(RTCodeToImg(op.type, img_td.type)); if (op.dimensionCount == 0) { img_td.dimensions = 1; img_td.size[0] = 1; } else { img_td.dimensions = op.dimensionCount; for (unsigned i = 0; i < op.dimensionCount; ++i) { img_td.size[i] = op.dimensions[i]; } } img_td.quant_param.scale = 0.f; img_td.quant_param.zero_point = 0; return ANEURALNETWORKS_NO_ERROR; } /** * Try to read a const operand at index idx from a given map. * Return whether a const operand exists at idx. */ bool readConstHostOperandFromMap( uint32_t idx, const void** data, std::size_t& length, const ANeuralNetworksCompilation::owned_const_host_operands& operands) { auto it = operands.find(idx); if (it != operands.end()) { *data = it->second.data(); length = it->second.size(); return true; } return false; } /** * Try to read a const operand at index idx. * Return whether a const operand exists at idx. */ bool readConstHostOperandHelper(uint32_t idx, const void** data, std::size_t& length) { if (readConstHostOperandFromMap( idx, data, length, compilation->const_copied_to_host_operands)) { return true; } if (readConstHostOperandFromMap(idx, data, length, model->const_host_operands_owned)) { return true; } auto it = model->const_host_operands.find(idx); if (it != model->const_host_operands.end()) { *data = it->second.data; length = it->second.length; return true; } return false; } /** * Read a const host operand (owned or not) at index idx. */ ResultCode readConstHostOperand(uint32_t idx, const void** data, std::size_t& length) { if (!readConstHostOperandHelper(idx, data, length)) { VLOG_AT("Error: Provided index " << idx << " was not added as an operand."); return ANEURALNETWORKS_BAD_DATA; } return ANEURALNETWORKS_NO_ERROR; } /** * Read a scalar host constant at the given index. */ template <class T> ResultCode readConstHostOperand(uint32_t idx, T& value) { const void* data = nullptr; std::size_t length; TENSOROPT_RETURN_IF_ERROR(readConstHostOperand(idx, &data, length)); if (length != sizeof(T)) { VLOG_AT("Error: Operand at index " << idx << " is of size " << length << " but expected " << sizeof(T)); return ANEURALNETWORKS_BAD_DATA; } std::memcpy(&value, data, sizeof(T)); return ANEURALNETWORKS_NO_ERROR; } /** * Read a vector host constant at the given index. */ template <class T> ResultCode readConstHostOperand(uint32_t idx, std::vector<T>& values) { const void* data = nullptr; std::size_t length; TENSOROPT_RETURN_IF_ERROR(readConstHostOperand(idx, &data, length)); auto typed_data = static_cast<const T*>(data); values.assign(typed_data, typed_data + (length / sizeof(T))); return ANEURALNETWORKS_NO_ERROR; } /** * Read a bitset host constant at the given index. */ ResultCode readConstHostOperand(uint32_t idx, std::bitset<32>& values) { int32_t value; TENSOROPT_RETURN_IF_ERROR(readConstHostOperand(idx, value)); values = std::bitset<32>(static_cast<unsigned long long>(value)); return ANEURALNETWORKS_NO_ERROR; } /** * Read a scalar or vector host constant if idx was provided in the * operation's input. value is unchanged and ANEURALNETWORKS_NO_ERROR is * returned if idx was not provided. */ template <class T> ResultCode readOptionalConstHostOperand( const ANeuralNetworksModel::Operation& operation, uint32_t idx, T& value) { if (idx < operation.inputs.size()) { TENSOROPT_RETURN_IF_ERROR( readConstHostOperand(operation.inputs[idx], value)); } return ANEURALNETWORKS_NO_ERROR; } /** * Try to create a fixed input IMGDNN tensor. * If op_idx is set as a model constant input, img_tensor is created and added * to img_tensors, added is set to true. Otherwise added is set to false. */ ResultCode addFixedInputTensor(uint32_t op_idx, imgdnn_tensor& img_tensor, bool& added) { const void* data = nullptr; std::size_t length; if (readConstHostOperandHelper(op_idx, &data, length)) { if (std::find(model->inputs.begin(), model->inputs.end(), op_idx) != model->inputs.end()) { VLOG_AT("Error: Operand at index " << op_idx << " cannot be both a constant model operand and an input"); return ANEURALNETWORKS_BAD_DATA; } if (std::find(model->outputs.begin(), model->outputs.end(), op_idx) != model->outputs.end()) { VLOG_AT("Error: Operand at index " << op_idx << " cannot be both a constant model operand and an output"); return ANEURALNETWORKS_BAD_DATA; } imgdnn_tensor_descriptor img_td; const auto& op = model->operands[op_idx]; TENSOROPT_RETURN_IF_ERROR(RTOperandTypeToImg(op, img_td)); uint32_t op_size = getOperandTypeSizeBytes(op); if (op_size != length) { VLOG_AT("Error: Operand at index " << op_idx << " was described with a total size of " << op_size << "B but set with a value of size " << length << "B"); return ANEURALNETWORKS_BAD_DATA; } BACKEND_CALL_RET(img_tensor, imgdnnNetworkFixedInput, compilation->imgdnn_network_, &img_td, data, &ret); IMGDNN_RETURN_ERR_IF_ERROR(ret); img_tensors[op_idx] = img_tensor; added = true; } else { added = false; } return ANEURALNETWORKS_NO_ERROR; } /** * Get an existing imgdnn_tensor or create one if it is a user input. */ ResultCode getImgTensor(int64_t idx, imgdnn_tensor& img_tensor) { auto it = img_tensors.find(idx); if (it != img_tensors.end()) { img_tensor = it->second; return ANEURALNETWORKS_NO_ERROR; } if (idx >= 0) { auto op_idx = static_cast<uint32_t>(idx); bool added; TENSOROPT_RETURN_IF_ERROR(addFixedInputTensor(op_idx, img_tensor, added)); if (added) { return ANEURALNETWORKS_NO_ERROR; } } // idx is either an internal tensor or is an output of an operation // that was not converted yet. VLOG_AT("Error: Tensor for operand index " << idx << " was not created yet."); return ANEURALNETWORKS_OP_FAILED; } /** * Get an existing internal imgdnn_tensor or create one if it doesn't exist * yet. */ ResultCode getInternalImgTensor(SpecialImgTensor idx, imgdnn_tensor& img_t) { auto map_idx = -idx; auto it = img_tensors.find(map_idx); if (it != img_tensors.end()) { img_t = it->second; return ANEURALNETWORKS_NO_ERROR; } if (idx == CONST_FLOAT32_ONE) { // FLOAT_ONE must live at least as long as the compilation object static constexpr float FLOAT_ONE = 1; imgdnn_tensor_descriptor img_td; img_td.dimensions = 1; img_td.size[0] = 1; img_td.type = IMGDNN_TYPE_F32; BACKEND_CALL_RET(img_t, imgdnnNetworkFixedInput, compilation->imgdnn_network_, &img_td, &FLOAT_ONE, &ret); IMGDNN_RETURN_ERR_IF_ERROR(ret); img_tensors[map_idx] = img_t; return ANEURALNETWORKS_NO_ERROR; } VLOG_AT("Internal error: Could not create internal tensor with index " << idx); return ANEURALNETWORKS_OP_FAILED; } template <class Container> ResultCode convertTransposeHelper(imgdnn_tensor img_in, const Container& order, imgdnn_tensor& img_out) { BACKEND_CALL_RET(img_out, imgdnnNetworkTransposeOp, compilation->imgdnn_network_, img_in, order.data(), &ret); IMGDNN_RETURN_ERR_IF_ERROR(ret); return ANEURALNETWORKS_NO_ERROR; } ResultCode getImgNCHWTensor(const ANeuralNetworksModel::Operation& operation, uint32_t idx, bool is_input_nchw, imgdnn_tensor& img_nchw_out) { imgdnn_tensor img_in; TENSOROPT_RETURN_IF_ERROR(getImgTensor(operation.inputs[idx], img_in)); if (is_input_nchw) { img_nchw_out = img_in; return ANEURALNETWORKS_NO_ERROR; } static constexpr std::array<int, 4> nhwc_to_nchw{0, 3, 1, 2}; TENSOROPT_RETURN_IF_ERROR( convertTransposeHelper(img_in, nhwc_to_nchw, img_nchw_out)); return ANEURALNETWORKS_NO_ERROR; } ResultCode getImgOIHWTensor(const ANeuralNetworksModel::Operation& operation, uint32_t idx, bool is_input_hwio, imgdnn_tensor& img_hwio_out) { imgdnn_tensor img_in; TENSOROPT_RETURN_IF_ERROR(getImgTensor(operation.inputs[idx], img_in)); if (is_input_hwio) { static constexpr std::array<int, 4> hwio_to_oihw{3, 2, 0, 1}; TENSOROPT_RETURN_IF_ERROR( convertTransposeHelper(img_in, hwio_to_oihw, img_hwio_out)); } else { // ohwi to oihw static constexpr std::array<int, 4> ohwi_to_oihw{0, 3, 1, 2}; TENSOROPT_RETURN_IF_ERROR( convertTransposeHelper(img_in, ohwi_to_oihw, img_hwio_out)); } return ANEURALNETWORKS_NO_ERROR; } ResultCode getSameFormatImgTensor(bool is_input_nchw, imgdnn_tensor img_in, imgdnn_tensor& img_out) { if (is_input_nchw) { img_out = img_in; return ANEURALNETWORKS_NO_ERROR; } static constexpr std::array<int, 4> nchw_to_nhwc{0, 2, 3, 1}; TENSOROPT_RETURN_IF_ERROR( convertTransposeHelper(img_in, nchw_to_nhwc, img_out)); return ANEURALNETWORKS_NO_ERROR; } ResultCode convertBinaryHelper(OperationCode op_code, imgdnn_tensor img_in0, imgdnn_tensor img_in1, imgdnn_tensor& img_out) { // int is used instead of OperationCode here since the type needs to be // hashable static std::unordered_map<int, imgdnn_operation_binary> rt_to_img_op_code{ {ANEURALNETWORKS_ADD, IMGDNN_OPERATION_ADD}, {ANEURALNETWORKS_MUL, IMGDNN_OPERATION_MUL}, {ANEURALNETWORKS_SUB, IMGDNN_OPERATION_SUB}, {ANEURALNETWORKS_DIV, IMGDNN_OPERATION_DIV}, {ANEURALNETWORKS_MAX, IMGDNN_OPERATION_MAX}, {ANEURALNETWORKS_MIN, IMGDNN_OPERATION_MIN}, {ANEURALNETWORKS_MATMUL, IMGDNN_OPERATION_MATMUL}}; // Imgdnn will automatically reshape and broadcast tensors if needed BACKEND_CALL_RET(img_out, imgdnnNetworkBinaryOp, compilation->imgdnn_network_, img_in0, img_in1, rt_to_img_op_code.at(op_code), &ret); IMGDNN_RETURN_ERR_IF_ERROR(ret); return ANEURALNETWORKS_NO_ERROR; } ResultCode convertUnaryHelper(OperationCode op_code, imgdnn_tensor img_in, imgdnn_tensor& img_out) { // Special cases for operations that do not translate to a imgdnn unary op. if (op_code == ANEURALNETWORKS_RELU1) { BACKEND_CALL_RET(img_out, imgdnnNetworkReLUOp, compilation->imgdnn_network_, img_in, true, -1.f, true, 1.f, 1.f, &ret); IMGDNN_RETURN_ERR_IF_ERROR(ret); return ANEURALNETWORKS_NO_ERROR; } if (op_code == ANEURALNETWORKS_RELU6) { BACKEND_CALL_RET(img_out, imgdnnNetworkReLUOp, compilation->imgdnn_network_, img_in, true, 0.f, true, 6.f, 1.f, &ret); IMGDNN_RETURN_ERR_IF_ERROR(ret); return ANEURALNETWORKS_NO_ERROR; } if (op_code == ANEURALNETWORKS_RSQRT) { // Write "rsqrt(x)" as "1 / sqrt(x)" imgdnn_tensor sqrt_tensor; TENSOROPT_RETURN_IF_ERROR( convertUnaryHelper(ANEURALNETWORKS_SQRT, img_in, sqrt_tensor)); imgdnn_tensor img_cst_one; TENSOROPT_RETURN_IF_ERROR( getInternalImgTensor(CONST_FLOAT32_ONE, img_cst_one)); TENSOROPT_RETURN_IF_ERROR(convertBinaryHelper( ANEURALNETWORKS_DIV, img_cst_one, sqrt_tensor, img_out)); return ANEURALNETWORKS_NO_ERROR; } // int is used instead of OperationCode here since the type needs to be // hashable static std::unordered_map<int, imgdnn_operation_unary> rt_to_img_op_code{ {ANEURALNETWORKS_RELU, IMGDNN_OPERATION_RELU}, {ANEURALNETWORKS_EXP, IMGDNN_OPERATION_EXP}, {ANEURALNETWORKS_SQRT, IMGDNN_OPERATION_SQRT}}; BACKEND_CALL_RET(img_out, imgdnnNetworkUnaryOp, compilation->imgdnn_network_, img_in, rt_to_img_op_code.at(op_code), &ret); IMGDNN_RETURN_ERR_IF_ERROR(ret); return ANEURALNETWORKS_NO_ERROR; } ResultCode addOptionalFuseCode(int32_t fuse_code, imgdnn_tensor& img_out) { if (fuse_code == ANEURALNETWORKS_FUSED_NONE) { return ANEURALNETWORKS_NO_ERROR; } static std::unordered_map<int32_t, OperationCode> fuse_code_to_op_code{ {ANEURALNETWORKS_FUSED_RELU, ANEURALNETWORKS_RELU}, {ANEURALNETWORKS_FUSED_RELU1, ANEURALNETWORKS_RELU1}, {ANEURALNETWORKS_FUSED_RELU6, ANEURALNETWORKS_RELU6}}; TENSOROPT_RETURN_IF_ERROR(convertUnaryHelper( fuse_code_to_op_code.at(fuse_code), img_out, img_out)); return ANEURALNETWORKS_NO_ERROR; } template <unsigned TrueIdx, unsigned FalseIdx> ResultCode getHWHelper(const ANeuralNetworksModel::Operation& operation, uint32_t idx, bool format, int32_t& res_h, int32_t& res_w) { auto input_idx = operation.inputs[idx]; const auto& op = model->operands[input_idx]; TENSOROPT_RETURN_IF_COND(op.dimensionCount != 4, "Internal error: expected operand " << input_idx << " to have 4 dimensions but got " << op.dimensionCount, ANEURALNETWORKS_OP_FAILED); if (format) { res_h = op.dimensions[TrueIdx]; res_w = op.dimensions[TrueIdx + 1]; } else { res_h = op.dimensions[FalseIdx]; res_w = op.dimensions[FalseIdx + 1]; } return ANEURALNETWORKS_NO_ERROR; } ResultCode getInputHW(const ANeuralNetworksModel::Operation& operation, uint32_t idx, bool nchw_format, int32_t& in_h, int32_t& in_w) { return getHWHelper<2, 1>(operation, idx, nchw_format, in_h, in_w); } ResultCode getFilterHW(const ANeuralNetworksModel::Operation& operation, uint32_t idx, bool hwio_format, int32_t& filter_h, int32_t& filter_w) { return getHWHelper<0, 1>(operation, idx, hwio_format, filter_h, filter_w); } ResultCode computePadding(int32_t padding_code, int32_t input, int32_t stride, int32_t filter, int32_t dilation, unsigned& img_pad_begin, unsigned& img_pad_end) { if (padding_code == ANEURALNETWORKS_PADDING_VALID) { img_pad_begin = 0; img_pad_end = 0; } else if (padding_code == ANEURALNETWORKS_PADDING_SAME) { int32_t effective_filter = (filter - 1) * dilation + 1; int32_t pad_needed = std::max(0, (roundRatioUp(input, stride) - 1) * stride + effective_filter - input); int32_t pad_begin = pad_needed / 2; img_pad_begin = static_cast<unsigned>(pad_begin); img_pad_end = static_cast<unsigned>(pad_needed - pad_begin); } else { VLOG_AT("Internal error: unknown padding " << padding_code); return ANEURALNETWORKS_OP_FAILED; } return ANEURALNETWORKS_NO_ERROR; } template <class Container> ResultCode checkVectorEqualRank(uint32_t rank, const Container& container, const std::string& input_name) { TENSOROPT_UNUSED_VARIABLE(input_name); TENSOROPT_RETURN_IF_COND( container.size() != rank, "Error: '" << input_name << "' argument has " << container.size() << " elements but input rank is " << rank << ".", ANEURALNETWORKS_OP_FAILED); return ANEURALNETWORKS_NO_ERROR; } template <class Container> ResultCode checkVectorSmallerOrEqualRank(uint32_t rank, const Container& container, const std::string& input_name) { TENSOROPT_UNUSED_VARIABLE(input_name); TENSOROPT_RETURN_IF_COND( container.size() > rank, "Error: '" << input_name << "' argument has " << container.size() << " elements but input rank is " << rank << ".", ANEURALNETWORKS_OP_FAILED); return ANEURALNETWORKS_NO_ERROR; } ResultCode convertReshapeHelper(imgdnn_tensor img_in, uint32_t shape_op_idx, imgdnn_tensor& img_out) { imgdnn_tensor_descriptor img_td; TENSOROPT_RETURN_IF_ERROR( RTOperandTypeToImg(model->operands[shape_op_idx], img_td)); BACKEND_CALL_RET(img_out, imgdnnNetworkReshapeOp, compilation->imgdnn_network_, img_in, &img_td, &ret); IMGDNN_RETURN_ERR_IF_ERROR(ret); return ANEURALNETWORKS_NO_ERROR; } ResultCode convertUnary(const ANeuralNetworksModel::Operation& operation) { TENSOROPT_RETURN_IF_UNEXPECTED_SIZE(operation, inputs, 1); TENSOROPT_RETURN_IF_UNEXPECTED_SIZE(operation, outputs, 1); imgdnn_tensor img_in; TENSOROPT_RETURN_IF_ERROR(getImgTensor(operation.inputs[0], img_in)); imgdnn_tensor& img_out = img_tensors[operation.outputs[0]]; TENSOROPT_RETURN_IF_ERROR( convertUnaryHelper(operation.type, img_in, img_out)); return ANEURALNETWORKS_NO_ERROR; } ResultCode convertBinary(const ANeuralNetworksModel::Operation& operation) { TENSOROPT_RETURN_IF_UNEXPECTED_MINMAX_SIZE(operation, inputs, 2, 3); TENSOROPT_RETURN_IF_UNEXPECTED_SIZE(operation, outputs, 1); imgdnn_tensor img_in0; imgdnn_tensor img_in1; int32_t fuse_code = ANEURALNETWORKS_FUSED_NONE; TENSOROPT_RETURN_IF_ERROR(getImgTensor(operation.inputs[0], img_in0)); TENSOROPT_RETURN_IF_ERROR(getImgTensor(operation.inputs[1], img_in1)); TENSOROPT_RETURN_IF_ERROR( readOptionalConstHostOperand(operation, 2, fuse_code)); imgdnn_tensor& img_out = img_tensors[operation.outputs[0]]; TENSOROPT_RETURN_IF_ERROR( convertBinaryHelper(operation.type, img_in0, img_in1, img_out)); TENSOROPT_RETURN_IF_ERROR(addOptionalFuseCode(fuse_code, img_out)); return ANEURALNETWORKS_NO_ERROR; } ResultCode convertPool(const ANeuralNetworksModel::Operation& operation) { TENSOROPT_RETURN_IF_UNEXPECTED_MINMAX_SIZE(operation, inputs, 6, 8); TENSOROPT_RETURN_IF_UNEXPECTED_SIZE(operation, outputs, 1); // int is used instead of OperationCode here since the type needs to be // hashable static std::unordered_map<int, imgdnn_pooling_type> rt_to_img_op_code{ {ANEURALNETWORKS_AVERAGE_POOL_2D, IMGDNN_POOLING_AVERAGE}, {ANEURALNETWORKS_MAX_POOL_2D, IMGDNN_POOLING_MAX}}; imgdnn_tensor img_nchw_in; int32_t padding_code; int32_t stride_w; int32_t stride_h; int32_t filter_w; int32_t filter_h; int32_t fuse_code = ANEURALNETWORKS_FUSED_NONE; bool is_input_nchw = false; TENSOROPT_RETURN_IF_ERROR( readConstHostOperand(operation.inputs[1], padding_code)); TENSOROPT_RETURN_IF_ERROR( readConstHostOperand(operation.inputs[2], stride_w)); TENSOROPT_RETURN_IF_ERROR( readConstHostOperand(operation.inputs[3], stride_h)); TENSOROPT_RETURN_IF_ERROR( readConstHostOperand(operation.inputs[4], filter_w)); TENSOROPT_RETURN_IF_ERROR( readConstHostOperand(operation.inputs[5], filter_h)); TENSOROPT_RETURN_IF_ERROR( readOptionalConstHostOperand(operation, 6, fuse_code)); TENSOROPT_RETURN_IF_ERROR( readOptionalConstHostOperand(operation, 7, is_input_nchw)); TENSOROPT_RETURN_IF_ERROR( getImgNCHWTensor(operation, 0, is_input_nchw, img_nchw_in)); int32_t in_h; int32_t in_w; TENSOROPT_RETURN_IF_ERROR( getInputHW(operation, 0, is_input_nchw, in_h, in_w)); unsigned img_window[2] = {static_cast<unsigned>(filter_h), static_cast<unsigned>(filter_w)}; unsigned img_strides[2] = {static_cast<unsigned>(stride_h), static_cast<unsigned>(stride_w)}; unsigned img_pad_begin[2]; unsigned img_pad_end[2]; static constexpr int32_t POOLING_DILATION = 1; TENSOROPT_RETURN_IF_ERROR(computePadding(padding_code, in_h, stride_h, filter_h, POOLING_DILATION, img_pad_begin[0], img_pad_end[0])); TENSOROPT_RETURN_IF_ERROR(computePadding(padding_code, in_w, stride_w, filter_w, POOLING_DILATION, img_pad_begin[1], img_pad_end[1])); imgdnn_tensor img_nchw_out; BACKEND_CALL_RET(img_nchw_out, imgdnnNetworkPooling2dOp_v2, compilation->imgdnn_network_, img_nchw_in, img_window, img_strides, img_pad_begin, img_pad_end, rt_to_img_op_code.at(operation.type), &ret); IMGDNN_RETURN_ERR_IF_ERROR(ret); imgdnn_tensor& img_out = img_tensors[operation.outputs[0]]; TENSOROPT_RETURN_IF_ERROR( getSameFormatImgTensor(is_input_nchw, img_nchw_out, img_out)); return ANEURALNETWORKS_NO_ERROR; } ResultCode convertConv2D(const ANeuralNetworksModel::Operation& operation) { TENSOROPT_RETURN_IF_UNEXPECTED_MINMAX_SIZE(operation, inputs, 6, 11); TENSOROPT_RETURN_IF_UNEXPECTED_SIZE(operation, outputs, 1); imgdnn_tensor img_nchw_in; imgdnn_tensor img_oihw_filter; int32_t padding_code; int32_t stride_w; int32_t stride_h; int32_t fuse_code = ANEURALNETWORKS_FUSED_NONE; bool is_input_nchw = false; bool is_filter_hwio = false; int32_t dilation_w; int32_t dilation_h; TENSOROPT_RETURN_IF_ERROR( readConstHostOperand(operation.inputs[3], padding_code)); TENSOROPT_RETURN_IF_ERROR( readConstHostOperand(operation.inputs[4], stride_w)); TENSOROPT_RETURN_IF_ERROR( readConstHostOperand(operation.inputs[5], stride_h)); TENSOROPT_RETURN_IF_ERROR( readOptionalConstHostOperand(operation, 6, fuse_code)); TENSOROPT_RETURN_IF_ERROR( readOptionalConstHostOperand(operation, 7, is_input_nchw)); TENSOROPT_RETURN_IF_ERROR( readOptionalConstHostOperand(operation, 8, is_filter_hwio)); TENSOROPT_RETURN_IF_ERROR( readOptionalConstHostOperand(operation, 9, dilation_w)); TENSOROPT_RETURN_IF_ERROR( readOptionalConstHostOperand(operation, 10, dilation_h)); TENSOROPT_RETURN_IF_ERROR( getImgNCHWTensor(operation, 0, is_input_nchw, img_nchw_in)); TENSOROPT_RETURN_IF_ERROR( getImgOIHWTensor(operation, 1, is_filter_hwio, img_oihw_filter)); int32_t in_h; int32_t in_w; int32_t filter_h; int32_t filter_w; TENSOROPT_RETURN_IF_ERROR( getInputHW(operation, 0, is_input_nchw, in_h, in_w)); TENSOROPT_RETURN_IF_ERROR( getFilterHW(operation, 1, is_filter_hwio, filter_h, filter_w)); unsigned img_strides[2] = {static_cast<unsigned>(stride_h), static_cast<unsigned>(stride_w)}; unsigned img_dilations[2] = {static_cast<unsigned>(dilation_h), static_cast<unsigned>(dilation_w)}; unsigned img_pad_begin[2]; unsigned img_pad_end[2]; TENSOROPT_RETURN_IF_ERROR(computePadding(padding_code, in_h, stride_h, filter_h, dilation_h, img_pad_begin[0], img_pad_end[0])); TENSOROPT_RETURN_IF_ERROR(computePadding(padding_code, in_w, stride_w, filter_w, dilation_w, img_pad_begin[1], img_pad_end[1])); imgdnn_tensor img_nchw_out; switch (operation.type) { case ANEURALNETWORKS_CONV_2D: BACKEND_CALL_RET(img_nchw_out, imgdnnNetworkConvolution2dOp_v2, compilation->imgdnn_network_, img_nchw_in, img_oihw_filter, img_strides, img_pad_begin, img_pad_end, img_dilations, &ret); break; case ANEURALNETWORKS_DEPTHWISE_CONV_2D: BACKEND_CALL_RET(img_nchw_out, imgdnnNetworkDepthConvolution2dOp_v2, compilation->imgdnn_network_, img_nchw_in, img_oihw_filter, img_strides, img_pad_begin, img_pad_end, img_dilations, &ret); break; default: VLOG_AT("Internal error: unexpected operation " << operation.type); return ANEURALNETWORKS_OP_FAILED; } IMGDNN_RETURN_ERR_IF_ERROR(ret); imgdnn_tensor img_same_input_format_out; TENSOROPT_RETURN_IF_ERROR(getSameFormatImgTensor( is_input_nchw, img_nchw_out, img_same_input_format_out)); imgdnn_tensor& img_out = img_tensors[operation.outputs[0]]; auto bias_op_idx = operation.inputs[2]; const auto& bias_op = model->operands[bias_op_idx]; if (bias_op.dimensionCount == 0) { img_out = img_same_input_format_out; } else if (bias_op.dimensionCount == 1) { imgdnn_tensor img_bias; TENSOROPT_RETURN_IF_ERROR(getImgTensor(bias_op_idx, img_bias)); TENSOROPT_RETURN_IF_ERROR(convertBinaryHelper( ANEURALNETWORKS_ADD, img_same_input_format_out, img_bias, img_out)); } else { VLOG_AT("Error: Expected 0 or 1 dimensionCount for bias operand but got " << bias_op.dimensionCount); return ANEURALNETWORKS_OP_FAILED; } return ANEURALNETWORKS_NO_ERROR; } ResultCode convertMatmul(const ANeuralNetworksModel::Operation& operation) { TENSOROPT_RETURN_IF_UNEXPECTED_SIZE(operation, inputs, 4); TENSOROPT_RETURN_IF_UNEXPECTED_SIZE(operation, outputs, 1); imgdnn_tensor img_in0; imgdnn_tensor img_in1; bool lhs_t = false; bool rhs_t = false; TENSOROPT_RETURN_IF_ERROR(getImgTensor(operation.inputs[0], img_in0)); TENSOROPT_RETURN_IF_ERROR(getImgTensor(operation.inputs[1], img_in1)); TENSOROPT_RETURN_IF_ERROR(readConstHostOperand(operation.inputs[2], lhs_t)); TENSOROPT_RETURN_IF_ERROR(readConstHostOperand(operation.inputs[3], rhs_t)); static constexpr std::array<int, 2> transpose_order{1, 0}; if (lhs_t) { TENSOROPT_RETURN_IF_ERROR( convertTransposeHelper(img_in0, transpose_order, img_in0)); } if (rhs_t) { TENSOROPT_RETURN_IF_ERROR( convertTransposeHelper(img_in1, transpose_order, img_in1)); } imgdnn_tensor& img_out = img_tensors[operation.outputs[0]]; TENSOROPT_RETURN_IF_ERROR( convertBinaryHelper(operation.type, img_in0, img_in1, img_out)); return ANEURALNETWORKS_NO_ERROR; } ResultCode convertTranspose( const ANeuralNetworksModel::Operation& operation) { TENSOROPT_RETURN_IF_UNEXPECTED_SIZE(operation, inputs, 2); TENSOROPT_RETURN_IF_UNEXPECTED_SIZE(operation, outputs, 1); imgdnn_tensor img_in; std::vector<int32_t> permutations; TENSOROPT_RETURN_IF_ERROR(getImgTensor(operation.inputs[0], img_in)); TENSOROPT_RETURN_IF_ERROR( readConstHostOperand(operation.inputs[1], permutations)); auto rank = model->operands[operation.inputs[0]].dimensionCount; TENSOROPT_RETURN_IF_ERROR( checkVectorEqualRank(rank, permutations, "permutations")); imgdnn_tensor& img_out = img_tensors[operation.outputs[0]]; TENSOROPT_RETURN_IF_ERROR( convertTransposeHelper(img_in, permutations, img_out)); return ANEURALNETWORKS_NO_ERROR; } ResultCode convertReshape(const ANeuralNetworksModel::Operation& operation) { TENSOROPT_RETURN_IF_UNEXPECTED_SIZE(operation, inputs, 2); TENSOROPT_RETURN_IF_UNEXPECTED_SIZE(operation, outputs, 1); imgdnn_tensor img_in; TENSOROPT_RETURN_IF_ERROR(getImgTensor(operation.inputs[0], img_in)); // No need to read the new shape argument, TensorOpt assumes it matches the // one provided as the output. imgdnn_tensor& img_out = img_tensors[operation.outputs[0]]; TENSOROPT_RETURN_IF_ERROR( convertReshapeHelper(img_in, operation.outputs[0], img_out)); return ANEURALNETWORKS_NO_ERROR; } ResultCode convertSqueeze(const ANeuralNetworksModel::Operation& operation) { TENSOROPT_RETURN_IF_UNEXPECTED_MINMAX_SIZE(operation, inputs, 1, 2); TENSOROPT_RETURN_IF_UNEXPECTED_SIZE(operation, outputs, 1); imgdnn_tensor img_in; TENSOROPT_RETURN_IF_ERROR(getImgTensor(operation.inputs[0], img_in)); // No need to read axis imgdnn_tensor& img_out = img_tensors[operation.outputs[0]]; TENSOROPT_RETURN_IF_ERROR( convertReshapeHelper(img_in, operation.outputs[0], img_out)); return ANEURALNETWORKS_NO_ERROR; } ResultCode convertConcat(const ANeuralNetworksModel::Operation& operation) { TENSOROPT_RETURN_IF_UNEXPECTED_MIN_SIZE(operation, inputs, 2); TENSOROPT_RETURN_IF_UNEXPECTED_SIZE(operation, outputs, 1); auto nb_tensors = static_cast<unsigned>(operation.inputs.size() - 1); std::vector<imgdnn_tensor> img_ins; int32_t axis; for (unsigned i = 0; i < nb_tensors; ++i) { img_ins.emplace_back(); TENSOROPT_RETURN_IF_ERROR( getImgTensor(operation.inputs[i], img_ins.back())); } TENSOROPT_RETURN_IF_ERROR( readConstHostOperand(operation.inputs[nb_tensors], axis)); if (axis < 0) { axis += model->operands[operation.inputs[0]].dimensionCount; } imgdnn_tensor& img_out = img_tensors[operation.outputs[0]]; BACKEND_CALL_RET(img_out, imgdnnNetworkConcatOp, compilation->imgdnn_network_, img_ins.data(), static_cast<unsigned>(axis), nb_tensors, &ret); IMGDNN_RETURN_ERR_IF_ERROR(ret); return ANEURALNETWORKS_NO_ERROR; } ResultCode convertSlice(const ANeuralNetworksModel::Operation& operation) { TENSOROPT_RETURN_IF_UNEXPECTED_SIZE(operation, inputs, 3); TENSOROPT_RETURN_IF_UNEXPECTED_SIZE(operation, outputs, 1); imgdnn_tensor img_in; std::vector<int32_t> begins; std::vector<int32_t> sizes; TENSOROPT_RETURN_IF_ERROR(getImgTensor(operation.inputs[0], img_in)); TENSOROPT_RETURN_IF_ERROR( readConstHostOperand(operation.inputs[1], begins)); TENSOROPT_RETURN_IF_ERROR(readConstHostOperand(operation.inputs[2], sizes)); auto input_op = model->operands[operation.inputs[0]]; auto rank = input_op.dimensionCount; TENSOROPT_RETURN_IF_ERROR(checkVectorEqualRank(rank, begins, "begins")); TENSOROPT_RETURN_IF_ERROR(checkVectorEqualRank(rank, sizes, "sizes")); std::vector<std::size_t> img_starts(rank); std::vector<std::size_t> img_ends(rank); std::vector<std::size_t> img_strides(rank, 1); for (unsigned i = 0; i < rank; ++i) { img_starts[i] = static_cast<std::size_t>(begins[i]); if (sizes[i] < 0) { img_ends[i] = static_cast<std::size_t>( static_cast<long>(input_op.dimensions[i]) + INCLUSIVE_END); } else { // sizes[i] cannot be 0 img_ends[i] = img_starts[i] + static_cast<std::size_t>(sizes[i] + INCLUSIVE_END); } } imgdnn_tensor& img_out = img_tensors[operation.outputs[0]]; BACKEND_CALL_RET(img_out, imgdnnNetworkSubTensor, compilation->imgdnn_network_, img_in, img_starts.data(), img_ends.data(), img_strides.data(), &ret); IMGDNN_RETURN_ERR_IF_ERROR(ret); return ANEURALNETWORKS_NO_ERROR; } ResultCode convertStridedSlice( const ANeuralNetworksModel::Operation& operation) { TENSOROPT_RETURN_IF_UNEXPECTED_MINMAX_SIZE(operation, inputs, 4, 9); TENSOROPT_RETURN_IF_UNEXPECTED_SIZE(operation, outputs, 1); imgdnn_tensor img_in; std::vector<int32_t> begins; std::vector<int32_t> ends; std::vector<int32_t> strides; std::bitset<32> begin_mask; std::bitset<32> end_mask; std::bitset<32> shrink_axis_mask; std::bitset<32> ellipsis_mask; std::bitset<32> new_axis_mask; TENSOROPT_RETURN_IF_ERROR(getImgTensor(operation.inputs[0], img_in)); TENSOROPT_RETURN_IF_ERROR( readConstHostOperand(operation.inputs[1], begins)); TENSOROPT_RETURN_IF_ERROR(readConstHostOperand(operation.inputs[2], ends)); TENSOROPT_RETURN_IF_ERROR( readConstHostOperand(operation.inputs[3], strides)); TENSOROPT_RETURN_IF_ERROR( readOptionalConstHostOperand(operation, 4, begin_mask)); TENSOROPT_RETURN_IF_ERROR( readOptionalConstHostOperand(operation, 5, end_mask)); TENSOROPT_RETURN_IF_ERROR( readOptionalConstHostOperand(operation, 6, shrink_axis_mask)); TENSOROPT_RETURN_IF_ERROR( readOptionalConstHostOperand(operation, 7, ellipsis_mask)); TENSOROPT_RETURN_IF_ERROR( readOptionalConstHostOperand(operation, 8, new_axis_mask)); auto input_op = model->operands[operation.inputs[0]]; auto rank = input_op.dimensionCount; TENSOROPT_RETURN_IF_ERROR( checkVectorSmallerOrEqualRank(rank, begins, "begins")); TENSOROPT_RETURN_IF_COND(ends.size() != begins.size(), "Error: 'ends' argument is of size " << ends.size() << " but expected " << begins.size() << ".", ANEURALNETWORKS_OP_FAILED); TENSOROPT_RETURN_IF_COND(strides.size() != begins.size(), "Error: 'strides' argument is of size " << strides.size() << " but expected " << begins.size() << ".", ANEURALNETWORKS_OP_FAILED); if (ellipsis_mask.none()) { TENSOROPT_RETURN_IF_ERROR(checkVectorEqualRank(rank, begins, "begins")); } else if (begins.size() < rank) { unsigned ellipsis = 0; while (!ellipsis_mask[ellipsis] && ellipsis < rank) { ++ellipsis; } if (ellipsis < rank) { std::size_t diff = rank - begins.size(); begins.insert(begins.begin() + ellipsis, diff, 0); ends.insert(ends.begin() + ellipsis, diff, -1); strides.insert(strides.begin() + ellipsis, diff, 1); } } std::vector<std::size_t> img_starts(rank); std::vector<std::size_t> img_ends(rank); std::vector<std::size_t> img_strides(rank); for (unsigned i = 0; i < rank; ++i) { if (begin_mask[i] || begins[i] < 0) { img_starts[i] = 0; } else { img_starts[i] = static_cast<std::size_t>(begins[i]); } if (shrink_axis_mask[i]) { img_ends[i] = img_starts[i] + (1 + INCLUSIVE_END); img_strides[i] = 1; continue; } if (end_mask[i] || ends[i] < 0) { img_ends[i] = static_cast<std::size_t>( static_cast<long>(input_op.dimensions[i]) + INCLUSIVE_END); } else { // ends[i] cannot be 0 img_ends[i] = static_cast<std::size_t>(ends[i] + INCLUSIVE_END); } if (strides[i] <= 0) { VLOG_AT("Error: strides must be stricly positive but got [" << arrayToString(strides, rank) << "]."); return ANEURALNETWORKS_OP_FAILED; } img_strides[i] = static_cast<std::size_t>(strides[i]); } imgdnn_tensor img_strided_slice; BACKEND_CALL_RET(img_strided_slice, imgdnnNetworkSubTensor, compilation->imgdnn_network_, img_in, img_starts.data(), img_ends.data(), img_strides.data(), &ret); IMGDNN_RETURN_ERR_IF_ERROR(ret); imgdnn_tensor& img_out = img_tensors[operation.outputs[0]]; if (new_axis_mask.none()) { img_out = img_strided_slice; } else { // TensorOpt assumes the shape provided by the output is correct. TENSOROPT_RETURN_IF_ERROR(convertReshapeHelper( img_strided_slice, operation.outputs[0], img_out)); } return ANEURALNETWORKS_NO_ERROR; } ResultCode convertSoftmax(const ANeuralNetworksModel::Operation& operation) { TENSOROPT_RETURN_IF_UNEXPECTED_MINMAX_SIZE(operation, inputs, 1, 3); TENSOROPT_RETURN_IF_UNEXPECTED_SIZE(operation, outputs, 1); imgdnn_tensor img_in; float beta = 1.f; int32_t axis = -1; TENSOROPT_RETURN_IF_ERROR(getImgTensor(operation.inputs[0], img_in)); TENSOROPT_RETURN_IF_ERROR(readOptionalConstHostOperand(operation, 1, beta)); TENSOROPT_RETURN_IF_ERROR(readOptionalConstHostOperand(operation, 2, axis)); if (axis < 0) { axis += model->operands[operation.inputs[0]].dimensionCount; } imgdnn_tensor& img_out = img_tensors[operation.outputs[0]]; BACKEND_CALL_RET(img_out, imgdnnNetworkSoftmaxOp, compilation->imgdnn_network_, img_in, beta, static_cast<unsigned>(axis), &ret); IMGDNN_RETURN_ERR_IF_ERROR(ret); return ANEURALNETWORKS_NO_ERROR; } ResultCode convertCast(const ANeuralNetworksModel::Operation& operation) { TENSOROPT_RETURN_IF_UNEXPECTED_SIZE(operation, inputs, 1); TENSOROPT_RETURN_IF_UNEXPECTED_SIZE(operation, outputs, 1); imgdnn_tensor img_in; TENSOROPT_RETURN_IF_ERROR(getImgTensor(operation.inputs[0], img_in)); auto output_op = model->operands[operation.outputs[0]]; imgdnn_type img_dst_type; TENSOROPT_RETURN_IF_ERROR(RTCodeToImg(output_op.type, img_dst_type)); imgdnn_quant_param img_dst_quant; img_dst_quant.scale = output_op.scale; img_dst_quant.zero_point = output_op.zeroPoint; imgdnn_tensor& img_out = img_tensors[operation.outputs[0]]; BACKEND_CALL_RET(img_out, imgdnnNetworkCastOp, compilation->imgdnn_network_, img_in, img_dst_type, &img_dst_quant, &ret); IMGDNN_RETURN_ERR_IF_ERROR(ret); return ANEURALNETWORKS_NO_ERROR; } }; } // end namespace ResultCode convertModel(ANeuralNetworksCompilation* compilation) { imgdnn_err_code ret; BACKEND_CALL_RET(compilation->imgdnn_network_, imgdnnCreateNetwork, &ret); IMGDNN_RETURN_ERR_IF_ERROR(ret); Converter converter(compilation); return converter(); }
39.487034
80
0.670881
[ "object", "shape", "vector", "model" ]
78f01f9fca8a9b1c830b50cc2071a8f55375c90e
2,662
hpp
C++
include/extractor/guidance/turn_handler.hpp
motis-project/osrm-backend
9aa492376a664304d8209513230bb43258367108
[ "BSD-2-Clause" ]
null
null
null
include/extractor/guidance/turn_handler.hpp
motis-project/osrm-backend
9aa492376a664304d8209513230bb43258367108
[ "BSD-2-Clause" ]
null
null
null
include/extractor/guidance/turn_handler.hpp
motis-project/osrm-backend
9aa492376a664304d8209513230bb43258367108
[ "BSD-2-Clause" ]
null
null
null
#ifndef OSRM_EXTRACTOR_GUIDANCE_TURN_HANDLER_HPP_ #define OSRM_EXTRACTOR_GUIDANCE_TURN_HANDLER_HPP_ #include "extractor/guidance/intersection.hpp" #include "extractor/guidance/intersection_handler.hpp" #include "extractor/query_node.hpp" #include "util/name_table.hpp" #include "util/node_based_graph.hpp" #include <cstddef> #include <utility> #include <vector> namespace osrm { namespace extractor { namespace guidance { // Intersection handlers deal with all issues related to intersections. // They assign appropriate turn operations to the TurnOperations. class TurnHandler final : public IntersectionHandler { public: TurnHandler(const util::NodeBasedDynamicGraph &node_based_graph, const std::vector<QueryNode> &node_info_list, const util::NameTable &name_table, const SuffixTable &street_name_suffix_table); ~TurnHandler() override final; // check whether the handler can actually handle the intersection bool canProcess(const NodeID nid, const EdgeID via_eid, const Intersection &intersection) const override final; // process the intersection Intersection operator()(const NodeID nid, const EdgeID via_eid, Intersection intersection) const override final; private: // Dead end. Intersection handleOneWayTurn(Intersection intersection) const; // Mode Changes, new names... Intersection handleTwoWayTurn(const EdgeID via_edge, Intersection intersection) const; // Forks, T intersections and similar Intersection handleThreeWayTurn(const EdgeID via_edge, Intersection intersection) const; // Handling of turns larger then degree three Intersection handleComplexTurn(const EdgeID via_edge, Intersection intersection) const; void handleDistinctConflict(const EdgeID via_edge, ConnectedRoad &left, ConnectedRoad &right) const; // Classification std::size_t findObviousTurn(const EdgeID via_edge, const Intersection &intersection) const; std::pair<std::size_t, std::size_t> findFork(const Intersection &intersection) const; Intersection assignLeftTurns(const EdgeID via_edge, Intersection intersection, const std::size_t starting_at) const; Intersection assignRightTurns(const EdgeID via_edge, Intersection intersection, const std::size_t up_to) const; }; } // namespace guidance } // namespace extractor } // namespace osrm #endif /*OSRM_EXTRACTOR_GUIDANCE_TURN_HANDLER_HPP_*/
35.026316
99
0.707739
[ "vector" ]
78f10ec3fdf36e7fc9db8c6e55f640504853a051
8,107
cpp
C++
samples/deeplearning/gxm/src/SplitLoop.cpp
abhisekkundu-intel/libxsmm
66d97cb86c192ca727afd9ddf42ad8c80addf6e1
[ "BSD-3-Clause" ]
1
2021-05-23T21:25:05.000Z
2021-05-23T21:25:05.000Z
samples/deeplearning/gxm/src/SplitLoop.cpp
abhisekkundu-intel/libxsmm
66d97cb86c192ca727afd9ddf42ad8c80addf6e1
[ "BSD-3-Clause" ]
null
null
null
samples/deeplearning/gxm/src/SplitLoop.cpp
abhisekkundu-intel/libxsmm
66d97cb86c192ca727afd9ddf42ad8c80addf6e1
[ "BSD-3-Clause" ]
null
null
null
/****************************************************************************** * Copyright (c) Intel Corporation - All rights reserved. * * This file is part of the LIBXSMM library. * * * * For information on the license, see the LICENSE file. * * Further information: https://github.com/hfp/libxsmm/ * * SPDX-License-Identifier: BSD-3-Clause * ******************************************************************************/ /* Sasikanth Avancha, Dhiraj Kalamkar (Intel Corp.) ******************************************************************************/ #include <stdio.h> #include <omp.h> #include <immintrin.h> #include "SplitLoop.hpp" # define _mm512_load_act(A) _mm512_castsi512_ps(_mm512_slli_epi32(_mm512_cvtepi16_epi32(_mm256_loadu_si256((__m256i*)(A))),16)) #if 1 __m512i vnaninf = _mm512_set1_epi32( 0x7f800000 ); __m512i vrneadd = _mm512_set1_epi32( 0x00007fff ); __m512i vfixup = _mm512_set1_epi32( 0x00000001 ); __m512i vfixupmask = _mm512_set1_epi32( 0x00010000 ); # define _mm512_roundbf16rne(A) _mm512_mask_add_epi32( _mm512_castps_si512( A ), _mm512_cmp_epi32_mask( _mm512_and_epi32( _mm512_castps_si512( A ), vnaninf ), vnaninf, _MM_CMPINT_NE ), _mm512_castps_si512( A ), _mm512_mask_add_epi32( vrneadd , _mm512_cmp_epi32_mask( _mm512_and_epi32( _mm512_castps_si512( A ), vfixupmask ), vfixupmask, _MM_CMPINT_EQ ), vrneadd, vfixup ) ) # define _mm512_stream_act(A,B) _mm256_stream_si256((__m256i*)A,_mm512_cvtepi32_epi16(_mm512_srai_epi32(_mm512_roundbf16rne((B)),16))) # define _mm512_store_act(A,B) _mm256_storeu_si256((__m256i*)A,_mm512_cvtepi32_epi16(_mm512_srai_epi32(_mm512_roundbf16rne((B)),16))) #else # define _mm512_stream_act(A,B) _mm256_stream_si256((__m256i*)A,_mm512_cvtepi32_epi16(_mm512_srai_epi32(_mm512_castps_si512((B)),16))) # define _mm512_store_act(A,B) _mm256_storeu_si256((__m256i*)A,_mm512_cvtepi32_epi16(_mm512_srai_epi32(_mm512_castps_si512((B)),16))) #endif #define VLEN 16 void SplitLoop::forwardPropagate(TensorBuf *inpb, vector<TensorBuf*>& outpb, int tid) { for(int i=0; i<outpb.size(); i++) { outpb[i]->setBuffer(inpb->getBuffer()); outpb[i]->setBufferSize(inpb->getBufferSize()); outpb[i]->setLayoutType(inpb->getLayoutType()); } } void SplitLoop::backPropagate(vector<TensorBuf *>& deloutpb, TensorBuf *delinpb, int tid) { assert(gp->bdims == gp->tdims); int nImg = gp->batch_size; int nIfm = gp->nInput; int ifh = gp->iHeight; int ifw = gp->iWidth; int in_dtype = delinpb->getDataType(); int out_dtype = deloutpb[0]->getDataType(); void* delinp = delinpb->getBuffer(); void *deloutp[deloutpb.size()]; int num_outp = 1; int size = nImg*nIfm*ifh*ifw; deloutp[0] = deloutpb[0]->getBuffer(); for(int i=1; i<deloutpb.size(); i++) { if(deloutpb[i] == NULL) continue; deloutp[num_outp] = deloutpb[i]->getBuffer(); num_outp++; } if(in_dtype == DT_FLOAT && out_dtype == DT_FLOAT) { #ifdef __AVX512F__ if (size % 16 == 0) { if ( num_outp == 2 ) { float* out1 = (float*)deloutp[0]; float* out2 = (float*)deloutp[1]; #ifdef _OPENMP #pragma omp parallel for #endif for(int j=0; j<size; j+=16) { __m512 vo = _mm512_load_ps( out1+j ); vo = _mm512_add_ps( vo, _mm512_load_ps( out2+j ) ); #ifdef USE_NTS_SPLIT _mm512_stream_ps( &(((float*)delinp)[j]), vo ); #else _mm512_store_ps( &(((float*)delinp)[j]), vo ); #endif } } else if ( num_outp == 1 ) { float* out1 = (float*)deloutp[0]; #ifdef _OPENMP #pragma omp parallel for #endif for(int j=0; j<size; j+=16) { __m512 vo = _mm512_load_ps( out1+j ); #ifdef USE_NTS_SPLIT _mm512_stream_ps( &(((float*)delinp)[j]), vo ); #else _mm512_store_ps( &(((float*)delinp)[j]), vo ); #endif } } else { #ifdef _OPENMP #pragma omp parallel for #endif for(int j=0; j<size; j+=16) { __m512 vo = _mm512_load_ps( &(((float*)deloutp[0])[j]) ); for(int i=1; i<num_outp; i++) { vo = _mm512_add_ps( vo, _mm512_load_ps( &(((float*)deloutp[i])[j]) ) ); } #ifdef USE_NTS_SPLIT _mm512_stream_ps( &(((float*)delinp)[j]), vo ); #else _mm512_store_ps( &(((float*)delinp)[j]), vo ); #endif } } } else { #ifdef _OPENMP #pragma omp parallel for #endif for(int j=0; j<size; j++) { float o = ((float*)deloutp[0])[j]; for(int i=1; i<num_outp; i++) { o += ((float*)deloutp[i])[j]; } ((float*)delinp)[j] = o; } } #else #ifdef _OPENMP #pragma omp parallel for #endif for(int j=0; j<size; j++) { float o = ((float*)deloutp[0])[j]; for(int i=1; i<num_outp; i++) { o += ((float*)deloutp[i])[j]; } delinp[j] = o; } #endif } else if(in_dtype == DT_BF16 && out_dtype == DT_BF16) { #ifdef __AVX512F__ if (size % 16 == 0) { if ( num_outp == 2 ) { libxsmm_bfloat16* out1 = (libxsmm_bfloat16*)deloutp[0]; libxsmm_bfloat16* out2 = (libxsmm_bfloat16*)deloutp[1]; #ifdef _OPENMP #pragma omp parallel for #endif for(int j=0; j<size; j+=16) { __m512 vo = _mm512_load_act( out1+j ); vo = _mm512_add_ps( vo, _mm512_load_act( out2+j ) ); #ifdef USE_NTS_SPLIT _mm512_stream_act( &(((libxsmm_bfloat16*)delinp)[j]), vo ); #else _mm512_store_act( &(((libxsmm_bfloat16*)delinp)[j]), vo ); #endif } } else if ( num_outp == 1 ) { libxsmm_bfloat16* out1 = (libxsmm_bfloat16*)deloutp[0]; #ifdef _OPENMP #pragma omp parallel for #endif for(int j=0; j<size; j+=16) { __m512 vo = _mm512_load_act( out1+j ); #ifdef USE_NTS_SPLIT _mm512_stream_act( &(((libxsmm_bfloat16*)delinp)[j]), vo ); #else _mm512_store_act( &(((libxsmm_bfloat16*)delinp)[j]), vo ); #endif } } else { #ifdef _OPENMP #pragma omp parallel for #endif for(int j=0; j<size; j+=16) { __m512 vo = _mm512_load_act( &(((libxsmm_bfloat16*)deloutp[0])[j]) ); for(int i=1; i<num_outp; i++) { vo = _mm512_add_ps( vo, _mm512_load_act( &(((libxsmm_bfloat16*)deloutp[i])[j]) ) ); } #ifdef USE_NTS_SPLIT _mm512_stream_act( &(((libxsmm_bfloat16*)delinp)[j]), vo ); #else _mm512_store_act( &(((libxsmm_bfloat16*)delinp)[j]), vo ); #endif } } } else { #if defined(_OPENMP) #pragma omp parallel #endif { union libxsmm_bfloat16_hp deloutput_32_0, deloutput_32_1; deloutput_32_0.i[0] = 0; deloutput_32_0.i[1] = 0; deloutput_32_1.i[0] = 0; deloutput_32_1.i[1] = 0; #if defined(_OPENMP) #pragma omp for #endif for(int j=0; j<size; j++) { deloutput_32_0.i[1] = ((libxsmm_bfloat16*)deloutp[0])[j]; for(int i=1; i<num_outp; i++) { deloutput_32_1.i[1] = ((libxsmm_bfloat16*)deloutp[i])[j]; deloutput_32_0.f += deloutput_32_1.f; } ((libxsmm_bfloat16*)delinp)[j] = deloutput_32_0.i[1]; deloutput_32_0.i[0] = 0; deloutput_32_0.i[1] = 0; } } } #else #if defined(_OPENMP) #pragma omp parallel #endif { union libxsmm_bfloat16_hp deloutput_32_0, deloutput_32_1; deloutput_32_0.i[0] = 0; deloutput_32_0.i[1] = 0; deloutput_32_1.i[0] = 0; deloutput_32_1.i[1] = 0; #if defined(_OPENMP) #pragma omp for #endif for(int j=0; j<size; j++) { deloutput_32_0.i[1] = ((libxsmm_bfloat16*)deloutp[0])[j]; for(int i=1; i<num_outp; i++) { deloutput_32_1.i[1] = ((libxsmm_bfloat16*)deloutp[i])[j]; deloutput_32_0.f += deloutput_32_1.f; } ((libxsmm_bfloat16*)delinp)[j] = deloutput_32_0.i[1]; deloutput_32_0.i[0] = 0; deloutput_32_0.i[1] = 0; } } #endif } delinpb->setLayoutType(deloutpb[0]->getLayoutType()); }
32.298805
373
0.584187
[ "vector" ]
6001397bcaab6debfbfb20dc0215e40443121ad5
1,362
hxx
C++
Legolas/BlockMatrix/Structures/Banded/BandedScalarMultOperator.hxx
LaurentPlagne/Legolas
fdf533528baf7ab5fcb1db15d95d2387b3e3723c
[ "MIT" ]
null
null
null
Legolas/BlockMatrix/Structures/Banded/BandedScalarMultOperator.hxx
LaurentPlagne/Legolas
fdf533528baf7ab5fcb1db15d95d2387b3e3723c
[ "MIT" ]
null
null
null
Legolas/BlockMatrix/Structures/Banded/BandedScalarMultOperator.hxx
LaurentPlagne/Legolas
fdf533528baf7ab5fcb1db15d95d2387b3e3723c
[ "MIT" ]
1
2021-02-11T14:43:25.000Z
2021-02-11T14:43:25.000Z
#ifndef __BANDEDSCALARMULTOPERATOR_HXX__ #define __BANDEDSCALARMULTOPERATOR_HXX__ #include "Legolas/Vector/Vector.hxx" #include "Legolas/BlockMatrix/ScalarMatrixMultOperator.hxx" namespace Legolas{ struct BandedScalarMultOperator{ template <class SCALAR_MATRIX> class Engine : public ScalarMatrixMultOperator<SCALAR_MATRIX>{ typedef typename SCALAR_MATRIX::RealType RealType; typedef Legolas::MultiVector<RealType,1> V1D; public: inline std::string name( void ) const { return "BandedScalarMultOperator" ;} virtual VirtualMultOperator * clone( void ) const { return new Engine(*this); } //Y+=a*A*X void addMult(const SCALAR_MATRIX & A, const double & a, const V1D & X, V1D & Y){ const int n=A.nrows(); for (int i=0 ; i < n ; i++ ){ RealType accumulator=0.0; for (int j=std::max(i-A.linf(),0) ; j < std::min(i+A.lsup()+1,n) ; j++ ){ accumulator+=A.bandedGetElement(i,j)*X[j]; } Y[i]+=a*accumulator; } } //Y=A*X void mult(const SCALAR_MATRIX & A, const V1D & X, V1D & Y){ const int n=A.nrows(); for (int i=0 ; i < n ; i++ ){ RealType accumulator=0.0; for (int j=std::max(i-A.linf(),0) ; j < std::min(i+A.lsup()+1,n) ; j++ ){ accumulator+=A.bandedGetElement(i,j)*X[j]; } Y[i]=accumulator; } } }; }; } #endif
25.222222
86
0.624816
[ "vector" ]
60021ff9da03eb5dff425c8d5fcb2acb93853a61
3,063
cpp
C++
practice/22-swap-nodes-in-pairs/LeetCode_22_0144.cpp
manajay/algorithm-list
828b0baed25a743fdb010427f873b29af9587951
[ "MIT" ]
null
null
null
practice/22-swap-nodes-in-pairs/LeetCode_22_0144.cpp
manajay/algorithm-list
828b0baed25a743fdb010427f873b29af9587951
[ "MIT" ]
null
null
null
practice/22-swap-nodes-in-pairs/LeetCode_22_0144.cpp
manajay/algorithm-list
828b0baed25a743fdb010427f873b29af9587951
[ "MIT" ]
null
null
null
/** 给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。   示例: 给定 1->2->3->4, 你应该返回 2->1->4->3. 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * */ #include <iostream> #include <vector> using namespace std; // Definition for singly-linked list. struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; /* 执行用时 :0 ms, 在所有 C++ 提交中击败了100.00%的用户 内存消耗 :8.8 MB, 在所有 C++ 提交中击败了5.10%的用户 看来我这里内存消耗挺多的, 一个是函数调用, 一个是临时变量创建 而且写法不美观, 没有利用原来的函数 */ class Solution { public: ListNode *swapPairs(ListNode *head) { if (head == NULL || head->next == NULL) { return head; } // 结果 ListNode *reverseHead = head->next; // 单链表 哨兵 ListNode *node = new ListNode(-1); node->next = head; ListNode *cur = head; while (cur != NULL && cur->next != NULL) { node->next = swapTwo(cur, cur->next); node = node->next->next; cur = node->next; } return reverseHead; } ListNode *swapTwo(ListNode *cur, ListNode *next) { ListNode *temp = next->next; next->next = cur; cur = next; cur->next->next = temp; return cur; } }; /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *swapPairs(ListNode *head) { if (head == NULL || head->next == NULL) { return head; } // 递归就是不关心后续的过程, 只关心结果 ListNode *first = head; ListNode *second = head->next; // 反正后面两格子, 然后连上前面的 first->next = swapPairs(second->next); // 反转前面的两个格子 second->next = first; return second; } }; /** 执行用时 :4 ms, 在所有 C++ 提交中击败了85.16%的用户内存消耗 :8.7 MB, 在所有 C++ 提交中击败了18.21%的用户 发现还不如使用递归的方式效率高 * */ class Solution { public: ListNode *swapPairs(ListNode *head) { while (head == NULL || head->next == NULL) { return head; } // 前序节点,用于保持连接 ListNode *preNode = new ListNode(-1); // 用于返回结果 ListNode *res = preNode; while (head != NULL && head->next != NULL) { // 比较重要的一句, 相当于 res->next = head->next, 保证res返回的结果 preNode->next = head->next; // head next指向第三个节点 head->next = head->next->next; // 第二个节点 的next指向 第一个节点 preNode->next->next = head; // prenode-2-1(head)-3-4-5 // 注意这里head的位置 已经变为 双节点的后节点 // 更新preNode为 head preNode = preNode->next->next; // 更新head为 下一个双节点的前节点 head = head->next; } return res->next; } }; // 作者:reedfan // 链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs/solution/di-gui-he-fei-di-gui-liang-chong-jie-fa-java-by-re/ // 来源:力扣(LeetCode) // 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
21.41958
119
0.539993
[ "vector" ]
6008f318b2a0faeb7d33a7007e74ce71cd2d0b7f
2,605
cpp
C++
RenderTiger/RenderTiger/DX/src/dx11_fx_editor_window.cpp
PureGraphics/RenderTiger
1da76c8f13cea95cfc7211b76fa7bc62cabb11f6
[ "MIT" ]
null
null
null
RenderTiger/RenderTiger/DX/src/dx11_fx_editor_window.cpp
PureGraphics/RenderTiger
1da76c8f13cea95cfc7211b76fa7bc62cabb11f6
[ "MIT" ]
null
null
null
RenderTiger/RenderTiger/DX/src/dx11_fx_editor_window.cpp
PureGraphics/RenderTiger
1da76c8f13cea95cfc7211b76fa7bc62cabb11f6
[ "MIT" ]
null
null
null
#include "dx11_fx_editor_window.h" #include "render_tiger_main_window.h" dx11_fx_editor_window::dx11_fx_editor_window(QWidget *parent) : QMainWindow(parent), base_text_editor(), _parent(parent), _curr_text(""), _prev_text("") { _ui.setupUi(this); _init_keywords(); _init_events(); this->setMinimumSize(400, 400); } dx11_fx_editor_window::~dx11_fx_editor_window() { } QString dx11_fx_editor_window::get_fx_src() { return _ui.text_editor->toPlainText(); } void dx11_fx_editor_window::closeEvent(QCloseEvent *event) { QMainWindow::closeEvent(event); //How to do this correct? it looks like shit... render_tiger_main_window *main_wnd = (render_tiger_main_window*)_parent; main_wnd->on_fx_editor_close(); } void dx11_fx_editor_window::_init_keywords() { _keywords.push_back("matrix4x4"); _keywords.push_back("float4x4"); _keywords.push_back("float2"); _keywords.push_back("float3"); _keywords.push_back("float4"); _keywords.push_back("int"); _keywords.push_back("float"); _keywords.push_back("half"); _keywords.push_back("double"); _keywords.push_back("vector"); _keywords.push_back("matrix"); _keywords.push_back("texture"); _keywords.push_back("struct"); _keywords.push_back("cbuffer"); _keywords.push_back("POSITION"); _keywords.push_back("COLOR"); _keywords.push_back("SV_POSITION"); _keywords.push_back("return"); _keywords.push_back("mul"); _keywords.push_back("pass"); _keywords.push_back("SetVertexShader"); _keywords.push_back("SetGeometryShader"); _keywords.push_back("SetPixelShader"); _keywords.push_back("NULL"); } void dx11_fx_editor_window::_init_events() { connect(_ui.text_editor->document(), &QTextDocument::contentsChanged, this, &dx11_fx_editor_window::_on_contents_changed); } void dx11_fx_editor_window::_on_contents_changed() { _prev_text = _curr_text; _curr_text = _ui.text_editor->document()->toPlainText(); if (_prev_text == _curr_text || (_prev_text + "\n") == _curr_text) { return; } int tab = 0; QString h_text = _highlight_keywords(_curr_text, tab); disconnect(_ui.text_editor->document(), &QTextDocument::contentsChanged, this, &dx11_fx_editor_window::_on_contents_changed); QTextCursor qtc = _ui.text_editor->textCursor(); int p = qtc.position() + tab; _ui.text_editor->setHtml(h_text); qtc.setPosition(p); _ui.text_editor->setTextCursor(qtc); connect(_ui.text_editor->document(), &QTextDocument::contentsChanged, this, &dx11_fx_editor_window::_on_contents_changed); }
34.276316
129
0.722457
[ "vector" ]
600aac6db50ebacd5d8a90936f46992ed52a9639
9,959
cpp
C++
src/Detector.cpp
keith2018/Alice-AR-Engine
4b915e6fe5db004c91539018ab373e4bbed3c7f5
[ "MIT" ]
null
null
null
src/Detector.cpp
keith2018/Alice-AR-Engine
4b915e6fe5db004c91539018ab373e4bbed3c7f5
[ "MIT" ]
null
null
null
src/Detector.cpp
keith2018/Alice-AR-Engine
4b915e6fe5db004c91539018ab373e4bbed3c7f5
[ "MIT" ]
null
null
null
/* * * Alice AR Engine * * @author : keith@robot9.me * @date : 2016/9/20 * */ #include "Detector.h" #define REFINE_MATCH #define ENABLE_TRACK_MASK namespace Alice { bool Detector::addMarker(std::string markerPath) { cv::Mat markerImg = cv::imread(markerPath, CV_LOAD_IMAGE_GRAYSCALE); // create marker Marker marker; marker.imgPath = markerPath; marker.grayImg = markerImg; marker.width = markerImg.cols; marker.height = markerImg.rows; // quad points marker.quadPts2d.resize(4); marker.quadPts2d[0] = cv::Point2f(0, 0); marker.quadPts2d[1] = cv::Point2f(marker.width, 0); marker.quadPts2d[2] = cv::Point2f(marker.width, marker.height); marker.quadPts2d[3] = cv::Point2f(0, marker.height); // features bool isOk = extractFeatures(markerImg, marker.keyPts, marker.descriptors); if (!isOk) { return false; } markerHandler.addMarker(marker); return true; } void Detector::trainMarkers() { size_t markerCnt = markerHandler.size(); std::vector<cv::Mat> descriptors; descriptors.resize(markerCnt); for (int i = 0; i < markerCnt; i++) { descriptors[i] = markerHandler.getMarker(i).descriptors.clone(); } matcher->clear(); matcher->add(descriptors); matcher->train(); } bool Detector::extractFeatures(const cv::Mat &image, std::vector<cv::KeyPoint> &keyPoints, cv::Mat &descriptors, cv::Mat mask) { detector->detect(image, keyPoints, mask); if (keyPoints.empty() || keyPoints.size() < minMatchCnt) { return false; } extractor->compute(image, keyPoints, descriptors); return !keyPoints.empty(); } void Detector::knnMatch(cv::Mat &desQuery, std::vector<cv::DMatch> &matches) { std::vector<std::vector<cv::DMatch>> knnMatches; matcher->knnMatch(desQuery, knnMatches, 2); for (size_t i = 0; i < knnMatches.size(); i++) { const cv::DMatch &bestMatch = knnMatches[i][0]; const cv::DMatch &betterMatch = knnMatches[i][1]; float distanceRatio = bestMatch.distance / betterMatch.distance; if (distanceRatio < minKnnRatio) { matches.push_back(bestMatch); } } } bool Detector::evaluateHomography(const std::vector<cv::KeyPoint> &queryKeyPts, const std::vector<cv::KeyPoint> &trainKeyPts, std::vector<cv::DMatch> &matches, cv::Mat &homography, FrameMarkerInfo &marker) { if (matches.size() < minMatchCnt) { return false; } std::vector<cv::Point2f> srcPoints, dstPoints; srcPoints.resize(matches.size()); dstPoints.resize(matches.size()); for (size_t i = 0; i < matches.size(); i++) { srcPoints[i] = trainKeyPts[matches[i].trainIdx].pt; dstPoints[i] = queryKeyPts[matches[i].queryIdx].pt; } int th_dist = (int) (sqrt(0.005 * marker.frameWidth * marker.frameHeight / M_PI) + 0.5); std::vector<unsigned char> inliersMask(srcPoints.size()); homography = cv::findHomography(srcPoints, dstPoints, CV_FM_RANSAC, th_dist, inliersMask); std::vector<cv::DMatch> inliers; for (size_t i = 0; i < inliersMask.size(); i++) { if (inliersMask[i]) { inliers.push_back(matches[i]); } } matches.swap(inliers); if (matches.size() < minMatchCnt) { return false; } #ifdef REFINE_MATCH std::vector<cv::Point2f> markerPos; cv::perspectiveTransform(marker.marker.quadPts2d, markerPos, homography); std::vector<cv::Point2f> inlierSrcPts; std::vector<cv::Point2f> inlierDstPts; for (int i = 0; i < inliersMask.size(); i++) { if (inliersMask[i] && isPointInQuad(dstPoints[i], markerPos)) { inlierSrcPts.push_back(srcPoints[i]); inlierDstPts.push_back(dstPoints[i]); } } if (inlierDstPts.size() < minMatchCnt) { return false; } th_dist = (int) (sqrt(0.005 * marker.marker.width * marker.marker.height / M_PI) + 0.5); homography = cv::findHomography(inlierSrcPts, inlierDstPts, CV_FM_RANSAC, th_dist, inliersMask); inliers.clear(); for (size_t i = 0; i < inliersMask.size(); i++) { if (inliersMask[i]) { inliers.push_back(matches[i]); } } matches.swap(inliers); if (matches.size() < minMatchCnt) { return false; } #endif cv::perspectiveTransform(marker.marker.quadPts2d, marker.quadPts2d, marker.homography); return checkValid(marker); } bool Detector::checkValid(FrameMarkerInfo &marker) { if (!checkRectShape(marker.quadPts2d)) { return false; } return true; } bool Detector::detectFrame(cv::Mat &frame) { // extract cv::Mat grayFrame; toGray(frame, grayFrame); int frameWidth = grayFrame.cols; int frameHeight = grayFrame.rows; // merge tracking mask cv::Mat trackMask; #ifdef ENABLE_TRACK_MASK if (markerHandler.isAllMarkerVisible()) { for (int i = 0; i < markerHandler.size(); i++) { FrameMarkerInfo &info = markerHandler.getFrameMarkerInfo(i); if (info.visible) { if (trackMask.empty()) { trackMask = cv::Mat::zeros(frameHeight, frameWidth, CV_8UC1); } trackMask += info.trackingMask; } } } #endif std::vector<cv::KeyPoint> frameKeyPoints; cv::Mat frameDescriptors; bool isOk = extractFeatures(grayFrame, frameKeyPoints, frameDescriptors, trackMask); if (!isOk) { resetAllMarkerStates(); return false; } // match std::vector<cv::DMatch> matches; knnMatch(frameDescriptors, matches); if (matches.size() < minMatchCnt) { resetAllMarkerStates(); return false; } std::vector<std::vector<cv::DMatch>> markerMatches; markerMatches.resize(markerHandler.size()); for (int i = 0; i < matches.size(); i++) { cv::DMatch &m = matches[i]; markerMatches[m.imgIdx].push_back(m); } // if any marker visible bool markerFound = false; // find homography for (int i = 0; i < markerHandler.size(); i++) { FrameMarkerInfo &currMarker = markerHandler.getFrameMarkerInfo(i); // reset state currMarker.frameWidth = frameWidth; currMarker.frameHeight = frameHeight; bool found = evaluateHomography(frameKeyPoints, currMarker.marker.keyPts, markerMatches[i], currMarker.homography, currMarker); if (!found) { currMarker.visible = false; currMarker.drawable.setVisible(false); continue; } currMarker.generateTrackingMask(trackWnd); currMarker.visible = true; currMarker.getGlMatrix(camera, currMarker.drawable.glMat); currMarker.drawable.setVisible(true); markerFound = true; } return markerFound; } void Detector::resetAllMarkerStates() { for (int i = 0; i < markerHandler.size(); i++) { FrameMarkerInfo &currMarker = markerHandler.getFrameMarkerInfo(i); currMarker.visible = false; currMarker.drawable.setVisible(false); } } void Detector::toGray(const cv::Mat &image, cv::Mat &gray) { if (image.channels() == 3) { cv::cvtColor(image, gray, CV_BGR2GRAY); } else if (image.channels() == 4) { cv::cvtColor(image, gray, CV_BGRA2GRAY); } else if (image.channels() == 1) { gray = image; } } bool Detector::checkRectShape(std::vector<cv::Point2f> &rect_pts) { float vec[4][2]; vec[0][0] = rect_pts[1].x - rect_pts[0].x; vec[0][1] = rect_pts[1].y - rect_pts[0].y; vec[1][0] = rect_pts[2].x - rect_pts[1].x; vec[1][1] = rect_pts[2].y - rect_pts[1].y; vec[2][0] = rect_pts[3].x - rect_pts[2].x; vec[2][1] = rect_pts[3].y - rect_pts[2].y; vec[3][0] = rect_pts[0].x - rect_pts[3].x; vec[3][1] = rect_pts[0].y - rect_pts[3].y; float val = vec[3][0] * vec[0][1] - vec[3][1] * vec[0][0]; int s = val > 0 ? 1 : -1; bool ret = true; for (int i = 0; i < 3; i++) { val = vec[i][0] * vec[i + 1][1] - vec[i][1] * vec[i + 1][0]; if (val * s <= 0) { ret = false; break; } } return ret; } bool Detector::isPointInQuad(cv::Point2f &pt, std::vector<cv::Point2f> &quadPts) { int nCount = 4; int nCross = 0; for (int i = 0; i < nCount; i++) { cv::Point2f &pStart = quadPts[i]; cv::Point2f &pEnd = quadPts[(i + 1) % nCount]; if (pStart.y == pEnd.y) { continue; } if (pt.y < std::min(pStart.y, pEnd.y) || pt.y > std::max(pStart.y, pEnd.y)) { continue; } double x = (pt.y - pStart.y) * (pEnd.x - pStart.x) / (pEnd.y - pStart.y) + pStart.x; if (x > pt.x) { nCross++; } } return (nCross % 2 == 1); } }
31.615873
104
0.534291
[ "vector" ]
600bfafedbbb24f93b57387ab40a954623724bb3
8,362
cpp
C++
base/base_tests/levenshtein_dfa_test.cpp
LaGrunge/geocore
b599eda29a32a14e5c02f51c66848959b50732f2
[ "Apache-2.0" ]
1
2019-10-02T16:17:31.000Z
2019-10-02T16:17:31.000Z
base/base_tests/levenshtein_dfa_test.cpp
LaGrunge/omim
8ce6d970f8f0eb613531b16edd22ea8ab923e72a
[ "Apache-2.0" ]
6
2019-09-09T10:11:41.000Z
2019-10-02T15:04:21.000Z
base/base_tests/levenshtein_dfa_test.cpp
LaGrunge/geocore
b599eda29a32a14e5c02f51c66848959b50732f2
[ "Apache-2.0" ]
null
null
null
#include "testing/testing.hpp" #include "base/dfa_helpers.hpp" #include "base/levenshtein_dfa.hpp" #include <sstream> #include <string> #include <vector> using namespace std; using namespace strings; namespace { enum class Status { Accepts, Rejects, Intermediate }; struct Result { Result() = default; Result(Status status, size_t errorsMade = 0, size_t prefixErrorsMade = 0) : m_status(status), m_errorsMade(errorsMade), m_prefixErrorsMade(prefixErrorsMade) { } bool operator==(Result const & rhs) const { return m_status == rhs.m_status && (m_errorsMade == rhs.m_errorsMade || m_status == Status::Rejects) && (m_prefixErrorsMade == rhs.m_prefixErrorsMade || m_status == Status::Rejects); } Status m_status = Status::Accepts; size_t m_errorsMade = 0; size_t m_prefixErrorsMade = 0; }; Result GetResult(LevenshteinDFA const & dfa, std::string const & s) { auto it = dfa.Begin(); DFAMove(it, s); if (it.Accepts()) return Result(Status::Accepts, it.ErrorsMade(), it.PrefixErrorsMade()); if (it.Rejects()) return Result(Status::Rejects, it.ErrorsMade(), it.PrefixErrorsMade()); return Result(Status::Intermediate, it.ErrorsMade(), it.PrefixErrorsMade()); } bool Accepts(LevenshteinDFA const & dfa, std::string const & s) { return GetResult(dfa, s).m_status == Status::Accepts; } bool Rejects(LevenshteinDFA const & dfa, std::string const & s) { return GetResult(dfa, s).m_status == Status::Rejects; } bool Intermediate(LevenshteinDFA const & dfa, std::string const & s) { return GetResult(dfa, s).m_status == Status::Intermediate; } UNIT_TEST(LevenshteinDFA_Smoke) { { LevenshteinDFA dfa("", 0 /* maxErrors */); auto it = dfa.Begin(); TEST(it.Accepts(), ()); TEST(!it.Rejects(), ()); it.Move('a'); TEST(!it.Accepts(), ()); TEST(it.Rejects(), ()); it.Move('b'); TEST(!it.Accepts(), ()); TEST(it.Rejects(), ()); } { LevenshteinDFA dfa("abc", 1 /* maxErrors */); TEST(Accepts(dfa, "ab"), ()); TEST(Accepts(dfa, "abd"), ()); TEST(Accepts(dfa, "abcd"), ()); TEST(Accepts(dfa, "bbc"), ()); TEST(Rejects(dfa, "cba"), ()); TEST(Rejects(dfa, "abcde"), ()); TEST(Accepts(dfa, "ac"), ()); TEST(Accepts(dfa, "acb"), ()); TEST(Accepts(dfa, "acbc"), ()); TEST(Rejects(dfa, "acbd"), ()); TEST(Intermediate(dfa, "a"), ()); } { LevenshteinDFA dfa("ленинградский", 2 /* maxErrors */); TEST(Accepts(dfa, "ленинградский"), ()); TEST(Accepts(dfa, "ленингадский"), ()); TEST(Accepts(dfa, "ленигнрадский"), ()); TEST(Rejects(dfa, "ленинский"), ()); } { LevenshteinDFA dfa("atm", 1 /* maxErrors */); TEST(Rejects(dfa, "san"), ()); } } UNIT_TEST(LevenshteinDFA_Prefix) { { LevenshteinDFA dfa("москва", 1 /* prefixSize */, 1 /* maxErrors */); TEST(Accepts(dfa, "москва"), ()); TEST(Accepts(dfa, "масква"), ()); TEST(Accepts(dfa, "моска"), ()); TEST(Rejects(dfa, "иосква"), ()); } { LevenshteinDFA dfa("москва", 0 /* prefixSize */, 1 /* maxErrors */); TEST(Accepts(dfa, "москва"), ()); TEST(Accepts(dfa, "иосква"), ()); TEST(Accepts(dfa, "моксва"), ()); } } UNIT_TEST(LevenshteinDFA_ErrorsMade) { { LevenshteinDFA dfa("москва", 1 /* prefixSize */, 2 /* maxErrors */); TEST_EQUAL(GetResult(dfa, "москва"), Result(Status::Accepts, 0 /* errorsMade */, 0 /* prefixErrorsMade */), ()); TEST_EQUAL(GetResult(dfa, "москв"), Result(Status::Accepts, 1 /* errorsMade */, 0 /* prefixErrorsMade */), ()); TEST_EQUAL(GetResult(dfa, "моск"), Result(Status::Accepts, 2 /* errorsMade */, 0 /* prefixErrorsMade */), ()); TEST_EQUAL(GetResult(dfa, "мос").m_status, Status::Intermediate, ()); TEST_EQUAL(GetResult(dfa, "мос").m_prefixErrorsMade, 0, ()); TEST_EQUAL(GetResult(dfa, "моксав"), Result(Status::Accepts, 2 /* errorsMade */, 2 /* prefixErrorsMade */), ()); TEST_EQUAL(GetResult(dfa, "максав").m_status, Status::Rejects, ()); TEST_EQUAL(GetResult(dfa, "мсовк").m_status, Status::Intermediate, ()); TEST_EQUAL(GetResult(dfa, "мсовк").m_prefixErrorsMade, 2, ()); TEST_EQUAL(GetResult(dfa, "мсовка"), Result(Status::Accepts, 2 /* errorsMade */, 2 /* prefixErrorsMade */), ()); TEST_EQUAL(GetResult(dfa, "мсовкб").m_status, Status::Rejects, ()); } { LevenshteinDFA dfa("aa", 0 /* prefixSize */, 2 /* maxErrors */); TEST_EQUAL(GetResult(dfa, "abab"), Result(Status::Accepts, 2 /* errorsMade */, 2 /* prefixErrorsMade */), ()); } { LevenshteinDFA dfa("mississippi", 0 /* prefixSize */, 0 /* maxErrors */); TEST_EQUAL(GetResult(dfa, "misisipi").m_status, Status::Rejects, ()); TEST_EQUAL(GetResult(dfa, "mississipp").m_status, Status::Intermediate, ()); TEST_EQUAL(GetResult(dfa, "mississipp").m_prefixErrorsMade, 0, ()); TEST_EQUAL(GetResult(dfa, "mississippi"), Result(Status::Accepts, 0 /* errorsMade */, 0 /* prefixErrorsMade */), ()); } { vector<UniString> const allowedMisprints = {MakeUniString("yj")}; size_t const prefixSize = 1; size_t const maxErrors = 1; string const str = "yekaterinburg"; vector<pair<string, Result>> const queries = { {"yekaterinburg", Result(Status::Accepts, 0 /* errorsMade */, 0 /* prefixErrorsMade */)}, {"ekaterinburg", Result(Status::Accepts, 1 /* errorsMade */, 1 /* prefixErrorsMade */)}, {"jekaterinburg", Result(Status::Accepts, 1 /* errorsMade */, 1 /* prefixErrorsMade */)}, {"iekaterinburg", Result(Status::Rejects)}}; for (auto const & q : queries) { LevenshteinDFA dfa(MakeUniString(q.first), prefixSize, allowedMisprints, maxErrors); TEST_EQUAL(GetResult(dfa, str), q.second, ("Query:", q.first, "string:", str)); } } { LevenshteinDFA dfa("кафе", 1 /* prefixSize */, 1 /* maxErrors */); TEST_EQUAL(GetResult(dfa, "кафе"), Result(Status::Accepts, 0 /* errorsMade */, 0 /* prefixErrorsMade */), ()); TEST_EQUAL(GetResult(dfa, "кафер"), Result(Status::Accepts, 1 /* errorsMade */, 1 /* prefixErrorsMade */), ()); } } UNIT_TEST(LevenshteinDFA_PrefixDFAModifier) { { PrefixDFAModifier<LevenshteinDFA> dfa(LevenshteinDFA("abcde", 2 /* maxErrors */)); auto it = dfa.Begin(); DFAMove(it, "ab"); TEST(!it.Accepts(), ()); TEST(!it.Rejects(), ()); TEST_EQUAL(it.PrefixErrorsMade(), 0, ()); // |maxErrors| for all non-accepting states. TEST_EQUAL(it.ErrorsMade(), 2, ()); DFAMove(it, "c"); TEST(it.Accepts(), ()); TEST(!it.Rejects(), ()); TEST_EQUAL(it.ErrorsMade(), 2, ()); TEST_EQUAL(it.PrefixErrorsMade(), 0, ()); DFAMove(it, "d"); TEST(it.Accepts(), ()); TEST(!it.Rejects(), ()); TEST_EQUAL(it.ErrorsMade(), 1, ()); TEST_EQUAL(it.PrefixErrorsMade(), 0, ()); DFAMove(it, "e"); TEST(it.Accepts(), ()); TEST(!it.Rejects(), ()); TEST_EQUAL(it.ErrorsMade(), 0, ()); TEST_EQUAL(it.PrefixErrorsMade(), 0, ()); DFAMove(it, "fghijklmn"); TEST(it.Accepts(), ()); TEST(!it.Rejects(), ()); TEST_EQUAL(it.ErrorsMade(), 0, ()); TEST_EQUAL(it.PrefixErrorsMade(), 0, ()); } } UNIT_TEST(LevenshteinDFA_PrefixDFASmoke) { vector<char> const kAlphabet = {'a', 'b', 'c'}; vector<string> sources; vector<string> queries; auto generate = [](vector<char> const & alphabet, size_t size, vector<string> & result) { result.clear(); result.resize(pow(alphabet.size(), size)); for (size_t letterNumber = 0; letterNumber < size; ++letterNumber) { for (size_t i = 0; i < result.size(); ++i) { auto const letterIndex = static_cast<size_t>(i / pow(alphabet.size(), size - letterNumber - 1)) % alphabet.size(); result[i].push_back(alphabet[letterIndex]); } } }; { generate(kAlphabet, 4, sources); generate(kAlphabet, 2, queries); for (auto const & source : sources) { for (auto const & query : queries) { PrefixDFAModifier<LevenshteinDFA> dfa(LevenshteinDFA(source, 2 /* maxErrors */)); auto it = dfa.Begin(); for (auto const c : query) DFAMove(it, strings::MakeUniString({c})); } } } } } // namespace
29.758007
97
0.602966
[ "vector" ]
600fe628590ba58bd4513ee94cace89691192774
1,992
hpp
C++
src/GlobalSettings.hpp
RasmusD/StoryTime
6d9afa0d7d8b25f64a9a59c3fc9df0edbcc60681
[ "Unlicense" ]
null
null
null
src/GlobalSettings.hpp
RasmusD/StoryTime
6d9afa0d7d8b25f64a9a59c3fc9df0edbcc60681
[ "Unlicense" ]
4
2019-03-12T13:12:03.000Z
2019-04-08T10:10:57.000Z
src/GlobalSettings.hpp
RasmusD/StoryTime
6d9afa0d7d8b25f64a9a59c3fc9df0edbcc60681
[ "Unlicense" ]
null
null
null
// Include guard #ifndef __GlobalSettings_H_INCLUDED__ #define __GlobalSettings_H_INCLUDED__ #include <filesystem> #include <stdint.h> #include <iostream> #include <SFML/Graphics.hpp> namespace StoryTime { typedef struct _Markup { /* A list of currently active markup and its previous value as a string */ std::vector<std::tuple<std::string, std::string, std::string> > activeMarkup; // Current text colour sf::Color colour = sf::Color::White; // Current background colour // This is only relevant for text segments and will define the background colour while a segment is active sf::Color backgroundColour = sf::Color::Black; // Current text speed float speed = 0.01f; // Current display image // TMP - see TODO std::string displayImage = ""; } Markup; class GlobalSettings { public: // Set defaults static void initialise(); // Width of the game window static size_t WINDOWWIDTH; // Height of the game window static size_t WINDOWHEIGHT; // Default settings static Markup currentSettings; // The default font static sf::Font DEFAULTFONT; // The ROOT directory convenience path static std::filesystem::path ROOTDIR; // The saved game default directory static std::filesystem::path SAVEDIR; // Change CHARSIZE static void setCharSize(size_t newSize); // Change LINESPACE static void setLineSpacing(size_t newSize); // Get CHARSIZE static size_t getCharSize(); // Get LINESPACE static size_t getLineSpacing(); // See if something is initialised static bool isInitialised(); // Print out the current settings that can be easily printed (for debug) static void printSettings(); private: static bool INITIALISED; // The character size relative to the game window static size_t CHARSIZE; // The line spacing relative to the charsize static size_t LINESPACE; }; } // end namespace StoryTime #endif // __GlobalSettings_H_INCLUDED__;
26.56
108
0.709337
[ "vector" ]
601253e757447e78883f7f716ce49f58d9916c1c
9,036
hpp
C++
include/mango/simd/composite_float512.hpp
heiligeslama/mango
6528e151fa70c1b02871f1e7972e6c162c945350
[ "Zlib" ]
null
null
null
include/mango/simd/composite_float512.hpp
heiligeslama/mango
6528e151fa70c1b02871f1e7972e6c162c945350
[ "Zlib" ]
null
null
null
include/mango/simd/composite_float512.hpp
heiligeslama/mango
6528e151fa70c1b02871f1e7972e6c162c945350
[ "Zlib" ]
1
2021-04-25T15:16:59.000Z
2021-04-25T15:16:59.000Z
/* MANGO Multimedia Development Platform Copyright (C) 2012-2017 Twilight Finland 3D Oy Ltd. All rights reserved. */ #pragma once #include "simd.hpp" namespace mango { namespace simd { // ----------------------------------------------------------------- // float32x16 // ----------------------------------------------------------------- static inline float32x16 float32x16_zero() { float32x16 result; result.lo = float32x8_zero(); result.hi = float32x8_zero(); return result; } static inline float32x16 float32x16_set1(float s) { float32x16 result; result.lo = float32x8_set1(s); result.hi = float32x8_set1(s); return result; } static inline float32x16 float32x16_set16(float s0, float s1, float s2, float s3, float s4, float s5, float s6, float s7, float s8, float s9, float s10, float s11, float s12, float s13, float s14, float s15) { float32x16 result; result.lo = float32x8_set8(s0, s1, s2, s3, s4, s5, s6, s7); result.hi = float32x8_set8(s8, s9, s10, s11, s12, s13, s14, s15); return result; } static inline float32x16 float32x16_uload(const float* source) { float32x16 result; result.lo = float32x8_uload(source + 0); result.hi = float32x8_uload(source + 8); return result; } static inline void float32x16_ustore(float* dest, float32x16 a) { float32x8_ustore(dest + 0, a.lo); float32x8_ustore(dest + 8, a.hi); } static inline float32x16 unpackhi(float32x16 a, float32x16 b) { float32x16 result; result.lo = unpackhi(a.lo, b.lo); result.hi = unpackhi(a.hi, b.hi); return result; } static inline float32x16 unpacklo(float32x16 a, float32x16 b) { float32x16 result; result.lo = unpacklo(a.lo, b.lo); result.hi = unpacklo(a.hi, b.hi); return result; } // bitwise static inline float32x16 bitwise_nand(float32x16 a, float32x16 b) { float32x16 result; result.lo = bitwise_nand(a.lo, b.lo); result.hi = bitwise_nand(a.hi, b.hi); return result; } static inline float32x16 bitwise_and(float32x16 a, float32x16 b) { float32x16 result; result.lo = bitwise_and(a.lo, b.lo); result.hi = bitwise_and(a.hi, b.hi); return result; } static inline float32x16 bitwise_or(float32x16 a, float32x16 b) { float32x16 result; result.lo = bitwise_or(a.lo, b.lo); result.hi = bitwise_or(a.hi, b.hi); return result; } static inline float32x16 bitwise_xor(float32x16 a, float32x16 b) { float32x16 result; result.lo = bitwise_xor(a.lo, b.lo); result.hi = bitwise_xor(a.hi, b.hi); return result; } static inline float32x16 bitwise_not(float32x16 a) { float32x16 result; result.lo = bitwise_not(a.lo); result.hi = bitwise_not(a.hi); return result; } static inline float32x16 min(float32x16 a, float32x16 b) { float32x16 result; result.lo = min(a.lo, b.lo); result.hi = min(a.hi, b.hi); return result; } static inline float32x16 max(float32x16 a, float32x16 b) { float32x16 result; result.lo = max(a.lo, b.lo); result.hi = max(a.hi, b.hi); return result; } static inline float32x16 abs(float32x16 a) { float32x16 result; result.lo = abs(a.lo); result.hi = abs(a.hi); return result; } static inline float32x16 neg(float32x16 a) { float32x16 result; result.lo = neg(a.lo); result.hi = neg(a.hi); return result; } static inline float32x16 sign(float32x16 a) { float32x16 result; result.lo = sign(a.lo); result.hi = sign(a.hi); return result; } static inline float32x16 add(float32x16 a, float32x16 b) { float32x16 result; result.lo = add(a.lo, b.lo); result.hi = add(a.hi, b.hi); return result; } static inline float32x16 sub(float32x16 a, float32x16 b) { float32x16 result; result.lo = sub(a.lo, b.lo); result.hi = sub(a.hi, b.hi); return result; } static inline float32x16 mul(float32x16 a, float32x16 b) { float32x16 result; result.lo = mul(a.lo, b.lo); result.hi = mul(a.hi, b.hi); return result; } static inline float32x16 div(float32x16 a, float32x16 b) { float32x16 result; result.lo = div(a.lo, b.lo); result.hi = div(a.hi, b.hi); return result; } static inline float32x16 div(float32x16 a, float b) { float32x16 result; result.lo = div(a.lo, b); result.hi = div(a.hi, b); return result; } static inline float32x16 madd(float32x16 a, float32x16 b, float32x16 c) { float32x16 result; result.lo = madd(a.lo, b.lo, c.lo); result.hi = madd(a.hi, b.hi, c.hi); return result; } static inline float32x16 msub(float32x16 a, float32x16 b, float32x16 c) { float32x16 result; result.lo = msub(a.lo, b.lo, c.lo); result.hi = msub(a.hi, b.hi, c.hi); return result; } static inline float32x16 fast_rcp(float32x16 a) { float32x16 result; result.lo = fast_rcp(a.lo); result.hi = fast_rcp(a.hi); return result; } static inline float32x16 fast_rsqrt(float32x16 a) { float32x16 result; result.lo = fast_rsqrt(a.lo); result.hi = fast_rsqrt(a.hi); return result; } static inline float32x16 fast_sqrt(float32x16 a) { float32x16 result; result.lo = fast_sqrt(a.lo); result.hi = fast_sqrt(a.hi); return result; } static inline float32x16 rcp(float32x16 a) { float32x16 result; result.lo = rcp(a.lo); result.hi = rcp(a.hi); return result; } static inline float32x16 rsqrt(float32x16 a) { float32x16 result; result.lo = rsqrt(a.lo); result.hi = rsqrt(a.hi); return result; } static inline float32x16 sqrt(float32x16 a) { float32x16 result; result.lo = sqrt(a.lo); result.hi = sqrt(a.hi); return result; } // compare static inline mask32x16 compare_neq(float32x16 a, float32x16 b) { mask32x16 result; result.lo = compare_neq(a.lo, b.lo); result.hi = compare_neq(a.hi, b.hi); return result; } static inline mask32x16 compare_eq(float32x16 a, float32x16 b) { mask32x16 result; result.lo = compare_eq(a.lo, b.lo); result.hi = compare_eq(a.hi, b.hi); return result; } static inline mask32x16 compare_lt(float32x16 a, float32x16 b) { mask32x16 result; result.lo = compare_lt(a.lo, b.lo); result.hi = compare_lt(a.hi, b.hi); return result; } static inline mask32x16 compare_le(float32x16 a, float32x16 b) { mask32x16 result; result.lo = compare_le(a.lo, b.lo); result.hi = compare_le(a.hi, b.hi); return result; } static inline mask32x16 compare_gt(float32x16 a, float32x16 b) { mask32x16 result; result.lo = compare_gt(a.lo, b.lo); result.hi = compare_gt(a.hi, b.hi); return result; } static inline mask32x16 compare_ge(float32x16 a, float32x16 b) { mask32x16 result; result.lo = compare_ge(a.lo, b.lo); result.hi = compare_ge(a.hi, b.hi); return result; } static inline float32x16 select(mask32x16 mask, float32x16 a, float32x16 b) { float32x16 result; result.lo = select(mask.lo, a.lo, b.lo); result.hi = select(mask.hi, a.hi, b.hi); return result; } // rounding static inline float32x16 round(float32x16 a) { float32x16 result; result.lo = round(a.lo); result.hi = round(a.hi); return result; } static inline float32x16 trunc(float32x16 a) { float32x16 result; result.lo = trunc(a.lo); result.hi = trunc(a.hi); return result; } static inline float32x16 floor(float32x16 a) { float32x16 result; result.lo = floor(a.lo); result.hi = floor(a.hi); return result; } static inline float32x16 ceil(float32x16 a) { float32x16 result; result.lo = ceil(a.lo); result.hi = ceil(a.hi); return result; } static inline float32x16 fract(float32x16 a) { float32x16 result; result.lo = fract(a.lo); result.hi = fract(a.hi); return result; } } // namespace simd } // namespace mango
25.169916
125
0.568725
[ "3d" ]
601288607359b2c01adb4f073956d531d51b0c6e
21,680
cc
C++
third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d_state.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d_state.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d_state.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d_state.h" #include <memory> #include "third_party/blink/renderer/core/css/resolver/filter_operation_resolver.h" #include "third_party/blink/renderer/core/css/resolver/style_builder.h" #include "third_party/blink/renderer/core/css/resolver/style_resolver_state.h" #include "third_party/blink/renderer/core/html/canvas/html_canvas_element.h" #include "third_party/blink/renderer/core/paint/filter_effect_builder.h" #include "third_party/blink/renderer/core/style/computed_style.h" #include "third_party/blink/renderer/core/style/filter_operation.h" #include "third_party/blink/renderer/core/svg/svg_filter_element.h" #include "third_party/blink/renderer/modules/canvas/canvas2d/canvas_gradient.h" #include "third_party/blink/renderer/modules/canvas/canvas2d/canvas_pattern.h" #include "third_party/blink/renderer/modules/canvas/canvas2d/canvas_rendering_context_2d.h" #include "third_party/blink/renderer/modules/canvas/canvas2d/canvas_style.h" #include "third_party/blink/renderer/platform/fonts/font_selector.h" #include "third_party/blink/renderer/platform/graphics/draw_looper_builder.h" #include "third_party/blink/renderer/platform/graphics/filters/filter_effect.h" #include "third_party/blink/renderer/platform/graphics/filters/paint_filter_builder.h" #include "third_party/blink/renderer/platform/graphics/paint/paint_canvas.h" #include "third_party/blink/renderer/platform/graphics/paint/paint_flags.h" #include "third_party/blink/renderer/platform/graphics/skia/skia_utils.h" #include "third_party/skia/include/effects/SkDashPathEffect.h" #include "third_party/skia/include/effects/SkDropShadowImageFilter.h" static const char defaultFont[] = "10px sans-serif"; static const char defaultFilter[] = "none"; namespace blink { CanvasRenderingContext2DState::CanvasRenderingContext2DState() : unrealized_save_count_(0), stroke_style_(CanvasStyle::CreateFromRGBA(SK_ColorBLACK)), fill_style_(CanvasStyle::CreateFromRGBA(SK_ColorBLACK)), shadow_blur_(0), shadow_color_(Color::kTransparent), global_alpha_(1), line_dash_offset_(0), unparsed_font_(defaultFont), unparsed_filter_(defaultFilter), text_align_(kStartTextAlign), text_baseline_(kAlphabeticTextBaseline), direction_(kDirectionInherit), realized_font_(false), is_transform_invertible_(true), has_clip_(false), has_complex_clip_(false), fill_style_dirty_(true), stroke_style_dirty_(true), line_dash_dirty_(false), image_smoothing_quality_(kLow_SkFilterQuality) { fill_flags_.setStyle(PaintFlags::kFill_Style); fill_flags_.setAntiAlias(true); image_flags_.setStyle(PaintFlags::kFill_Style); image_flags_.setAntiAlias(true); stroke_flags_.setStyle(PaintFlags::kStroke_Style); stroke_flags_.setStrokeWidth(1); stroke_flags_.setStrokeCap(PaintFlags::kButt_Cap); stroke_flags_.setStrokeMiter(10); stroke_flags_.setStrokeJoin(PaintFlags::kMiter_Join); stroke_flags_.setAntiAlias(true); SetImageSmoothingEnabled(true); } CanvasRenderingContext2DState::CanvasRenderingContext2DState( const CanvasRenderingContext2DState& other, ClipListCopyMode mode) : unrealized_save_count_(other.unrealized_save_count_), unparsed_stroke_color_(other.unparsed_stroke_color_), unparsed_fill_color_(other.unparsed_fill_color_), stroke_style_(other.stroke_style_), fill_style_(other.fill_style_), stroke_flags_(other.stroke_flags_), fill_flags_(other.fill_flags_), image_flags_(other.image_flags_), shadow_offset_(other.shadow_offset_), shadow_blur_(other.shadow_blur_), shadow_color_(other.shadow_color_), empty_draw_looper_(other.empty_draw_looper_), shadow_only_draw_looper_(other.shadow_only_draw_looper_), shadow_and_foreground_draw_looper_( other.shadow_and_foreground_draw_looper_), shadow_only_image_filter_(other.shadow_only_image_filter_), shadow_and_foreground_image_filter_( other.shadow_and_foreground_image_filter_), global_alpha_(other.global_alpha_), transform_(other.transform_), line_dash_(other.line_dash_), line_dash_offset_(other.line_dash_offset_), unparsed_font_(other.unparsed_font_), font_(other.font_), font_for_filter_(other.font_for_filter_), unparsed_filter_(other.unparsed_filter_), filter_value_(other.filter_value_), resolved_filter_(other.resolved_filter_), text_align_(other.text_align_), text_baseline_(other.text_baseline_), direction_(other.direction_), realized_font_(other.realized_font_), is_transform_invertible_(other.is_transform_invertible_), has_clip_(other.has_clip_), has_complex_clip_(other.has_complex_clip_), fill_style_dirty_(other.fill_style_dirty_), stroke_style_dirty_(other.stroke_style_dirty_), line_dash_dirty_(other.line_dash_dirty_), image_smoothing_enabled_(other.image_smoothing_enabled_), image_smoothing_quality_(other.image_smoothing_quality_) { if (mode == kCopyClipList) { clip_list_ = other.clip_list_; } if (realized_font_) font_.GetFontSelector()->RegisterForInvalidationCallbacks(this); } CanvasRenderingContext2DState::~CanvasRenderingContext2DState() = default; void CanvasRenderingContext2DState::FontsNeedUpdate( FontSelector* font_selector) { DCHECK_EQ(font_selector, font_.GetFontSelector()); DCHECK(realized_font_); font_.Update(font_selector); // FIXME: We only really need to invalidate the resolved filter if the font // update above changed anything and the filter uses font-dependent units. resolved_filter_.reset(); } void CanvasRenderingContext2DState::Trace(blink::Visitor* visitor) { visitor->Trace(stroke_style_); visitor->Trace(fill_style_); visitor->Trace(filter_value_); FontSelectorClient::Trace(visitor); } void CanvasRenderingContext2DState::SetLineDashOffset(double offset) { line_dash_offset_ = clampTo<float>(offset); line_dash_dirty_ = true; } void CanvasRenderingContext2DState::SetLineDash(const Vector<double>& dash) { line_dash_ = dash; // Spec requires the concatenation of two copies the dash list when the // number of elements is odd if (dash.size() % 2) line_dash_.AppendVector(dash); // clamp the double values to float std::transform(line_dash_.begin(), line_dash_.end(), line_dash_.begin(), [](double d) { return clampTo<float>(d); }); line_dash_dirty_ = true; } static bool HasANonZeroElement(const Vector<double>& line_dash) { for (size_t i = 0; i < line_dash.size(); i++) { if (line_dash[i] != 0.0) return true; } return false; } void CanvasRenderingContext2DState::UpdateLineDash() const { if (!line_dash_dirty_) return; if (!HasANonZeroElement(line_dash_)) { stroke_flags_.setPathEffect(nullptr); } else { Vector<float> line_dash(line_dash_.size()); std::copy(line_dash_.begin(), line_dash_.end(), line_dash.begin()); stroke_flags_.setPathEffect(SkDashPathEffect::Make( line_dash.data(), line_dash.size(), line_dash_offset_)); } line_dash_dirty_ = false; } void CanvasRenderingContext2DState::SetStrokeStyle(CanvasStyle* style) { stroke_style_ = style; stroke_style_dirty_ = true; } void CanvasRenderingContext2DState::SetFillStyle(CanvasStyle* style) { fill_style_ = style; fill_style_dirty_ = true; } void CanvasRenderingContext2DState::UpdateStrokeStyle() const { if (!stroke_style_dirty_) return; DCHECK(stroke_style_); stroke_style_->ApplyToFlags(stroke_flags_); stroke_flags_.setColor( ScaleAlpha(stroke_style_->PaintColor(), global_alpha_)); stroke_style_dirty_ = false; } void CanvasRenderingContext2DState::UpdateFillStyle() const { if (!fill_style_dirty_) return; DCHECK(fill_style_); fill_style_->ApplyToFlags(fill_flags_); fill_flags_.setColor(ScaleAlpha(fill_style_->PaintColor(), global_alpha_)); fill_style_dirty_ = false; } CanvasStyle* CanvasRenderingContext2DState::Style(PaintType paint_type) const { switch (paint_type) { case kFillPaintType: return FillStyle(); case kStrokePaintType: return StrokeStyle(); case kImagePaintType: return nullptr; } NOTREACHED(); return nullptr; } void CanvasRenderingContext2DState::SetShouldAntialias(bool should_antialias) { fill_flags_.setAntiAlias(should_antialias); stroke_flags_.setAntiAlias(should_antialias); image_flags_.setAntiAlias(should_antialias); } bool CanvasRenderingContext2DState::ShouldAntialias() const { DCHECK(fill_flags_.isAntiAlias() == stroke_flags_.isAntiAlias() && fill_flags_.isAntiAlias() == image_flags_.isAntiAlias()); return fill_flags_.isAntiAlias(); } void CanvasRenderingContext2DState::SetGlobalAlpha(double alpha) { global_alpha_ = alpha; stroke_style_dirty_ = true; fill_style_dirty_ = true; image_flags_.setColor(ScaleAlpha(SK_ColorBLACK, alpha)); } void CanvasRenderingContext2DState::ClipPath( const SkPath& path, AntiAliasingMode anti_aliasing_mode) { clip_list_.ClipPath(path, anti_aliasing_mode, AffineTransformToSkMatrix(transform_)); has_clip_ = true; if (!path.isRect(nullptr)) has_complex_clip_ = true; } void CanvasRenderingContext2DState::SetFont(const Font& font, FontSelector* selector) { font_ = font; font_.Update(selector); realized_font_ = true; if (selector) selector->RegisterForInvalidationCallbacks(this); } const Font& CanvasRenderingContext2DState::GetFont() const { DCHECK(realized_font_); return font_; } void CanvasRenderingContext2DState::SetTransform( const AffineTransform& transform) { is_transform_invertible_ = transform.IsInvertible(); transform_ = transform; } void CanvasRenderingContext2DState::ResetTransform() { transform_.MakeIdentity(); is_transform_invertible_ = true; } sk_sp<PaintFilter> CanvasRenderingContext2DState::GetFilterForOffscreenCanvas( IntSize canvas_size, BaseRenderingContext2D* context) const { if (!filter_value_) return nullptr; if (resolved_filter_) return resolved_filter_; FilterOperations operations = FilterOperationResolver::CreateOffscreenFilterOperations(*filter_value_); // We can't reuse m_fillFlags and m_strokeFlags for the filter, since these // incorporate the global alpha, which isn't applicable here. PaintFlags fill_flags_for_filter; fill_style_->ApplyToFlags(fill_flags_for_filter); fill_flags_for_filter.setColor(fill_style_->PaintColor()); PaintFlags stroke_flags_for_filter; stroke_style_->ApplyToFlags(stroke_flags_for_filter); stroke_flags_for_filter.setColor(stroke_style_->PaintColor()); FilterEffectBuilder filter_effect_builder( FloatRect((FloatPoint()), FloatSize(canvas_size)), 1.0f, // Deliberately ignore zoom on the canvas element. &fill_flags_for_filter, &stroke_flags_for_filter); FilterEffect* last_effect = filter_effect_builder.BuildFilterEffect( operations, !context->OriginClean()); if (last_effect) { // TODO(chrishtr): Taint the origin if needed. crbug.com/792506. resolved_filter_ = PaintFilterBuilder::Build(last_effect, kInterpolationSpaceSRGB); } return resolved_filter_; } sk_sp<PaintFilter> CanvasRenderingContext2DState::GetFilter( Element* style_resolution_host, IntSize canvas_size, CanvasRenderingContext2D* context) const { if (!filter_value_) return nullptr; // StyleResolverState cannot be used in frame-less documents. if (!style_resolution_host->GetDocument().GetFrame()) return nullptr; if (!resolved_filter_) { // Update the filter value to the proper base URL if needed. if (filter_value_->MayContainUrl()) filter_value_->ReResolveUrl(style_resolution_host->GetDocument()); scoped_refptr<ComputedStyle> filter_style = ComputedStyle::Create(); // Must set font in case the filter uses any font-relative units (em, ex) filter_style->SetFont(font_for_filter_); StyleResolverState resolver_state(style_resolution_host->GetDocument(), style_resolution_host, filter_style.get(), filter_style.get()); resolver_state.SetStyle(filter_style); StyleBuilder::ApplyProperty(GetCSSPropertyFilter(), resolver_state, *filter_value_); resolver_state.LoadPendingResources(); // We can't reuse m_fillFlags and m_strokeFlags for the filter, since these // incorporate the global alpha, which isn't applicable here. PaintFlags fill_flags_for_filter; fill_style_->ApplyToFlags(fill_flags_for_filter); fill_flags_for_filter.setColor(fill_style_->PaintColor()); PaintFlags stroke_flags_for_filter; stroke_style_->ApplyToFlags(stroke_flags_for_filter); stroke_flags_for_filter.setColor(stroke_style_->PaintColor()); FilterEffectBuilder filter_effect_builder( FloatRect((FloatPoint()), FloatSize(canvas_size)), 1.0f, // Deliberately ignore zoom on the canvas element. &fill_flags_for_filter, &stroke_flags_for_filter); if (FilterEffect* last_effect = filter_effect_builder.BuildFilterEffect( filter_style->Filter(), !context->OriginClean())) { resolved_filter_ = PaintFilterBuilder::Build(last_effect, kInterpolationSpaceSRGB); if (resolved_filter_) { context->UpdateFilterReferences(filter_style->Filter()); if (last_effect->OriginTainted()) context->SetOriginTainted(); } } } return resolved_filter_; } bool CanvasRenderingContext2DState::HasFilterForOffscreenCanvas( IntSize canvas_size, BaseRenderingContext2D* context) const { // Checking for a non-null m_filterValue isn't sufficient, since this value // might refer to a non-existent filter. return !!GetFilterForOffscreenCanvas(canvas_size, context); } bool CanvasRenderingContext2DState::HasFilter( Element* style_resolution_host, IntSize canvas_size, CanvasRenderingContext2D* context) const { // Checking for a non-null m_filterValue isn't sufficient, since this value // might refer to a non-existent filter. return !!GetFilter(style_resolution_host, canvas_size, context); } void CanvasRenderingContext2DState::ClearResolvedFilter() const { resolved_filter_.reset(); } SkDrawLooper* CanvasRenderingContext2DState::EmptyDrawLooper() const { if (!empty_draw_looper_) empty_draw_looper_ = DrawLooperBuilder().DetachDrawLooper(); return empty_draw_looper_.get(); } SkDrawLooper* CanvasRenderingContext2DState::ShadowOnlyDrawLooper() const { if (!shadow_only_draw_looper_) { DrawLooperBuilder draw_looper_builder; draw_looper_builder.AddShadow(shadow_offset_, clampTo<float>(shadow_blur_), shadow_color_, DrawLooperBuilder::kShadowIgnoresTransforms, DrawLooperBuilder::kShadowRespectsAlpha); shadow_only_draw_looper_ = draw_looper_builder.DetachDrawLooper(); } return shadow_only_draw_looper_.get(); } SkDrawLooper* CanvasRenderingContext2DState::ShadowAndForegroundDrawLooper() const { if (!shadow_and_foreground_draw_looper_) { DrawLooperBuilder draw_looper_builder; draw_looper_builder.AddShadow(shadow_offset_, clampTo<float>(shadow_blur_), shadow_color_, DrawLooperBuilder::kShadowIgnoresTransforms, DrawLooperBuilder::kShadowRespectsAlpha); draw_looper_builder.AddUnmodifiedContent(); shadow_and_foreground_draw_looper_ = draw_looper_builder.DetachDrawLooper(); } return shadow_and_foreground_draw_looper_.get(); } sk_sp<PaintFilter> CanvasRenderingContext2DState::ShadowOnlyImageFilter() const { if (!shadow_only_image_filter_) { double sigma = SkBlurRadiusToSigma(shadow_blur_); shadow_only_image_filter_ = sk_make_sp<DropShadowPaintFilter>( shadow_offset_.Width(), shadow_offset_.Height(), sigma, sigma, shadow_color_, SkDropShadowImageFilter::kDrawShadowOnly_ShadowMode, nullptr); } return shadow_only_image_filter_; } sk_sp<PaintFilter> CanvasRenderingContext2DState::ShadowAndForegroundImageFilter() const { if (!shadow_and_foreground_image_filter_) { double sigma = SkBlurRadiusToSigma(shadow_blur_); shadow_and_foreground_image_filter_ = sk_make_sp<DropShadowPaintFilter>( shadow_offset_.Width(), shadow_offset_.Height(), sigma, sigma, shadow_color_, SkDropShadowImageFilter::kDrawShadowAndForeground_ShadowMode, nullptr); } return shadow_and_foreground_image_filter_; } void CanvasRenderingContext2DState::ShadowParameterChanged() { shadow_only_draw_looper_.reset(); shadow_and_foreground_draw_looper_.reset(); shadow_only_image_filter_.reset(); shadow_and_foreground_image_filter_.reset(); } void CanvasRenderingContext2DState::SetShadowOffsetX(double x) { shadow_offset_.SetWidth(clampTo<float>(x)); ShadowParameterChanged(); } void CanvasRenderingContext2DState::SetShadowOffsetY(double y) { shadow_offset_.SetHeight(clampTo<float>(y)); ShadowParameterChanged(); } void CanvasRenderingContext2DState::SetShadowBlur(double shadow_blur) { shadow_blur_ = clampTo<float>(shadow_blur); ShadowParameterChanged(); } void CanvasRenderingContext2DState::SetShadowColor(SkColor shadow_color) { shadow_color_ = shadow_color; ShadowParameterChanged(); } void CanvasRenderingContext2DState::SetFilter(const CSSValue* filter_value) { filter_value_ = filter_value; resolved_filter_.reset(); } void CanvasRenderingContext2DState::SetGlobalComposite(SkBlendMode mode) { stroke_flags_.setBlendMode(mode); fill_flags_.setBlendMode(mode); image_flags_.setBlendMode(mode); } SkBlendMode CanvasRenderingContext2DState::GlobalComposite() const { return stroke_flags_.getBlendMode(); } void CanvasRenderingContext2DState::SetImageSmoothingEnabled(bool enabled) { image_smoothing_enabled_ = enabled; UpdateFilterQuality(); } bool CanvasRenderingContext2DState::ImageSmoothingEnabled() const { return image_smoothing_enabled_; } void CanvasRenderingContext2DState::SetImageSmoothingQuality( const String& quality_string) { if (quality_string == "low") { image_smoothing_quality_ = kLow_SkFilterQuality; } else if (quality_string == "medium") { image_smoothing_quality_ = kMedium_SkFilterQuality; } else if (quality_string == "high") { image_smoothing_quality_ = kHigh_SkFilterQuality; } else { return; } UpdateFilterQuality(); } String CanvasRenderingContext2DState::ImageSmoothingQuality() const { switch (image_smoothing_quality_) { case kLow_SkFilterQuality: return "low"; case kMedium_SkFilterQuality: return "medium"; case kHigh_SkFilterQuality: return "high"; default: NOTREACHED(); return "low"; } } void CanvasRenderingContext2DState::UpdateFilterQuality() const { if (!image_smoothing_enabled_) { UpdateFilterQualityWithSkFilterQuality(kNone_SkFilterQuality); } else { UpdateFilterQualityWithSkFilterQuality(image_smoothing_quality_); } } void CanvasRenderingContext2DState::UpdateFilterQualityWithSkFilterQuality( const SkFilterQuality& filter_quality) const { stroke_flags_.setFilterQuality(filter_quality); fill_flags_.setFilterQuality(filter_quality); image_flags_.setFilterQuality(filter_quality); } bool CanvasRenderingContext2DState::ShouldDrawShadows() const { return AlphaChannel(shadow_color_) && (shadow_blur_ || !shadow_offset_.IsZero()); } const PaintFlags* CanvasRenderingContext2DState::GetFlags( PaintType paint_type, ShadowMode shadow_mode, ImageType image_type) const { PaintFlags* flags; switch (paint_type) { case kStrokePaintType: UpdateLineDash(); UpdateStrokeStyle(); flags = &stroke_flags_; break; default: NOTREACHED(); // no break on purpose: flags needs to be assigned to avoid compiler warning // about uninitialized variable. FALLTHROUGH; case kFillPaintType: UpdateFillStyle(); flags = &fill_flags_; break; case kImagePaintType: flags = &image_flags_; break; } if ((!ShouldDrawShadows() && shadow_mode == kDrawShadowAndForeground) || shadow_mode == kDrawForegroundOnly) { flags->setLooper(nullptr); flags->setImageFilter(nullptr); return flags; } if (!ShouldDrawShadows() && shadow_mode == kDrawShadowOnly) { flags->setLooper(sk_ref_sp(EmptyDrawLooper())); // draw nothing flags->setImageFilter(nullptr); return flags; } if (shadow_mode == kDrawShadowOnly) { if (image_type == kNonOpaqueImage || filter_value_) { flags->setLooper(nullptr); flags->setImageFilter(ShadowOnlyImageFilter()); return flags; } flags->setLooper(sk_ref_sp(ShadowOnlyDrawLooper())); flags->setImageFilter(nullptr); return flags; } DCHECK(shadow_mode == kDrawShadowAndForeground); if (image_type == kNonOpaqueImage) { flags->setLooper(nullptr); flags->setImageFilter(ShadowAndForegroundImageFilter()); return flags; } flags->setLooper(sk_ref_sp(ShadowAndForegroundDrawLooper())); flags->setImageFilter(nullptr); return flags; } } // namespace blink
35.424837
97
0.755074
[ "vector", "transform" ]
60151e72316bfc5f6f901a66e4ff1cb281f67904
5,007
cc
C++
tensorflow/compiler/xla/service/tuple_simplifier.cc
uve/tensorflow
e08079463bf43e5963acc41da1f57e95603f8080
[ "Apache-2.0" ]
null
null
null
tensorflow/compiler/xla/service/tuple_simplifier.cc
uve/tensorflow
e08079463bf43e5963acc41da1f57e95603f8080
[ "Apache-2.0" ]
null
null
null
tensorflow/compiler/xla/service/tuple_simplifier.cc
uve/tensorflow
e08079463bf43e5963acc41da1f57e95603f8080
[ "Apache-2.0" ]
null
null
null
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/tuple_simplifier.h" #include <queue> #include "tensorflow/compiler/xla/service/hlo_computation.h" #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include "tensorflow/compiler/xla/service/hlo_opcode.h" #include "tensorflow/compiler/xla/status_macros.h" #include "tensorflow/compiler/xla/types.h" #include "tensorflow/compiler/xla/util.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/types.h" namespace xla { TupleSimplifier::TupleSimplifier(bool exclude_entry_computation) : exclude_entry_computation_(exclude_entry_computation) {} StatusOr<bool> TupleSimplifier::Run(HloModule* module) { // Initially add all GTE and Tuple instructions to the worklist. std::queue<HloInstruction*> worklist; for (auto* computation : module->computations()) { if (exclude_entry_computation_ && computation == module->entry_computation()) { continue; } for (auto* instruction : computation->instructions()) { if (instruction->opcode() == HloOpcode::kTuple || instruction->opcode() == HloOpcode::kGetTupleElement) { worklist.push(instruction); } } } bool changed = false; while (!worklist.empty()) { HloInstruction* instruction = worklist.front(); worklist.pop(); if (instruction->user_count() == 0 && instruction != instruction->parent()->root_instruction()) { // Tuple simplification works by replacing users of optimized away // instructions with a simpler form. If there is no user of the // instruction (including being the root), then there is nothing to do. continue; } if (instruction->opcode() == HloOpcode::kTuple) { // Collapse the following structure into just 'Tuple-shaped Op': // // Tuple-shaped Op // | // +-----+-----+ // | | | // GTE GTE GTE // | | | // +-----+-----+ // | // Tuple // HloInstruction* top_tuple = nullptr; bool can_simplify = true; for (int64 operand_number = 0; operand_number < instruction->operand_count(); ++operand_number) { HloInstruction* operand = instruction->mutable_operand(operand_number); if (operand->opcode() != HloOpcode::kGetTupleElement || operand->tuple_index() != operand_number) { can_simplify = false; break; } if (top_tuple == nullptr) { top_tuple = operand->mutable_operand(0); if (!ShapeUtil::Compatible(top_tuple->shape(), instruction->shape())) { can_simplify = false; break; } } else if (top_tuple != operand->operand(0)) { can_simplify = false; break; } } if (can_simplify && top_tuple != nullptr) { changed = true; TF_RETURN_IF_ERROR(instruction->ReplaceAllUsesWith(top_tuple)); // No need to add anything to the worklist. } } else { CHECK_EQ(instruction->opcode(), HloOpcode::kGetTupleElement); // If possible replace a GTE with the operation which produces the // element. For example, replace uses of GTE with below with just 'Op' // (assuming 'Op' is at the index of the GTE instruction): // // ... Op ... // \ | / // Tuple // | // GTE if (instruction->operand(0)->opcode() == HloOpcode::kTuple) { HloInstruction* element_source = instruction->mutable_operand(0)->mutable_operand( instruction->tuple_index()); changed = true; TF_RETURN_IF_ERROR(instruction->ReplaceAllUsesWith(element_source)); for (HloInstruction* user : element_source->users()) { if (user->opcode() == HloOpcode::kTuple || user->opcode() == HloOpcode::kGetTupleElement) { worklist.push(user); } } } } } return changed; } } // namespace xla
36.816176
81
0.597763
[ "shape" ]