text
stringlengths
65
6.05M
lang
stringclasses
8 values
type
stringclasses
2 values
id
stringlengths
64
64
/* Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration */ /// @author Nils Krumnack // // includes // #include <AsgTools/AnaToolHandle.h> // // main program // int main (int argc, char *argv []) { using namespace asg::msgUserCode; ANA_CHECK_SET_TYPE (int); if (argc < 2) { ANA_MSG_ERROR ("missing argument: [type]"); return -1; } asg::AnaToolHandle<asg::IAsgTool> tool (std::string (argv[1]) + "/tool"); for (int iter = 2; iter != argc; ++ iter) { const std::string arg = argv[iter]; const auto split = arg.find ("="); if (split == std::string::npos) { ANA_MSG_ERROR ("argument doesn't match name=value syntax: \"" << arg << "\""); return -1; } ANA_CHECK (tool.setProperty (arg.substr (0, split), arg.substr (split + 1))); } ANA_CHECK (tool.initialize()); ANA_MSG_INFO ("successfully initialized tool"); return 0; }
C++
CL
6133f708c90af131dc1c279c8071667f3bcb6ecb3da3e249263514a2ba471286
#ifndef KUKA_ROS_CONTROLLER_INTERFACE_PASSIVE_DS_H_ #define KUKA_ROS_CONTROLLER_INTERFACE_PASSIVE_DS_H_ #include <ros/ros.h> #include <tf/transform_listener.h> #include "geometry_msgs/TwistStamped.h" #include "std_msgs/Float64MultiArray.h" #include "std_msgs/Float64.h" namespace ros_controller_interface{ class Ros_passive_ds{ public: Ros_passive_ds(ros::NodeHandle& nh, const std::string& robot_name_space = "lwr",const std::string& controller_name = "joint_controllers"); public: void sendDampEig(const std_msgs::Float64MultiArray& msg); void sendCartVel(const geometry_msgs::Twist& twist_); void sendRotStiff(const std_msgs::Float64& stiff_msg); void sendRotDamp(const std_msgs::Float64& damp_msg); void sendOrient(const geometry_msgs::Quaternion &orient_msg); private: ros::Publisher velocity_pub; ros::Publisher rot_stiffness_pub; ros::Publisher rot_damp_pub; ros::Publisher orient_pub; ros::Publisher passive_ds_eig_pub; public: geometry_msgs::Twist ee_vel_msg; std_msgs::Float64 stiff_msg; std_msgs::Float64 damp_msg; std_msgs::Float64MultiArray eig_msg; geometry_msgs::Quaternion orient_msg; }; } #endif
C++
CL
9ad900352ee29d5e2e2d41857a965d95c873a7ae158c346200d11efd58ec0fe7
/********************************************************************* ** Program Filename: Backpack.hpp ** Author:Jose Bigio ** Date: December 5th, 2015 ** Description:File that provides class implemenation for Backpack class ** Input:N/A ** Output: For certain functions statements are printed indicating what ** is going on in the program *********************************************************************/ #include "Backpack.hpp" #include <iostream> #include <sstream> /********************************************************************* ** Function: Backpack constructor ** Description: Constructor for Backpack class. Sets the mergeNum to 0. ** The mergeNum is a variable that is used to help determine when the ** string shovel, and coconut items can be joined to create a shovel. ** Parameters: N/A ** Pre-Conditions: N/A ** Post-Conditions: A Backpack object is created *********************************************************************/ Backpack::Backpack() { mergeNum = 0; capacity = 3; } /********************************************************************* ** Function: Backpack destructor ** Description: Destructor for Backpack class ** Parameters: N/A ** Pre-Conditions: Backpack object must exist ** Post-Conditions: An Backpack object is destroyed *********************************************************************/ Backpack::~Backpack() { // TODO Auto-generated destructor stub } /********************************************************************* ** Function: merge ** Description: Function that checks the mergeNum to determine if the ** string, coconut, and stick items can combine to create a shovel. The ** mergeNum represents the current sum of the items in the bag.This sum is ** updated every time an item is added or when an item is removed. ** Parameters: N/A ** Pre-Conditions: Backpack object must exist ** Post-Conditions: If the mergeNum equals 6. Then the first item in the ** backpack is transformed into a shovel, and the remaining two items in ** the backpack are removed. *********************************************************************/ void Backpack::merge() { if (mergeNum == 6) { bag[0]->setId(6); bag[0]->setName("Shovel"); bag.erase(bag.begin()+1, bag.begin() + bag.size() ); std::cout << "The shovel, coconut shell, and string have combined in your bag into a shovel!!!" << std::endl; std::cout << "The shovel only takes up one space in your backpack " << std::endl; } } /********************************************************************* ** Function: hasSpace ** Description: Function that determines if backpack has space ** Parameters: N/A ** Pre-Conditions: Backpack object must exist ** Post-Conditions: If the backpack has less than 3 items the function returns ** true otherwise the function returns false ** ********************************************************************/ bool Backpack::hasSpace() { if (bag.size() < capacity) { return true; } return false; } /********************************************************************* ** Function: isEmpty ** Description: Function that determines if backpack is completely Empty ** Parameters: N/A ** Pre-Conditions: Backpack object must exist ** Post-Conditions: If the backpack has no items function returns ** true otherwise the function returns false ** ********************************************************************/ bool Backpack::isEmpty() { if (bag.size() == 0) { return true; } else return false; } /********************************************************************* ** Function: getSize ** Description: Function that determines how many items are in bag ** Parameters: N/A ** Pre-Conditions: Backpack object must exist ** Post-Conditions: Returns an int that represents the number of items ** in the bag ** ********************************************************************/ int Backpack::getSize() { return bag.size(); } /********************************************************************* ** Function: getItem(int i) ** Description: Function that takes in an integer, and uses this ** integer as an index to return an item that is stored in the vector. ** Parameters: an int ** Pre-Conditions: Backpack object must exist ** Post-Conditions: Returns an item pointer. If the index is greater than ** the number of items in the vector an error is returned. ** ********************************************************************/ Item* Backpack::getItem(int i) { if ( i < bag.size()) { return bag[i]; } else return 0; } /********************************************************************* ** Function: addItem(Item *add) ** Description: Function that takes in an item pointer, and adds the item ** to the bag if the backpack has space. The function also checks whether the ** item passed in is a null pointer to ensure that null pointers aren't added ** to the bag. ** Parameters: an Item pointer ** Pre-Conditions: Backpack object must exist ** Post-Conditions: Item that was passed in is added to the bag if the item ** wasn't null, and if the bag had capacity ** ********************************************************************/ void Backpack::addItem(Item *add) { if (!hasSpace()) { std::cout << "The bag is full " << std::endl; } else if (add == 0) { std::cout << "Nothing was added to the bag " << std::endl; } else { bag.push_back(add); std::cout << add->getName() << " was successfully added to the bag " << std::endl; mergeNum += add->getId(); merge(); } } /********************************************************************* ** Function: removeItem() ** Description: Function removes an item that the user specifies from the ** backpack if the backpack has items to remove ** Parameters: an Item pointer ** Pre-Conditions: Backpack object must exist ** Post-Conditions: Item that was passed in is added to the bag if the item ** wasn't null, and if the bag had capacity ** ********************************************************************/ Item* Backpack::removeItem() { if (bag.size() == 0) { std::cout << "There is nothing to remove " << std::endl; return 0; } else { std::cout << "Please enter the number corresponding to the item you want to remove " << std::endl; std::cout << this->toString(); std::cout << bag.size() + 1 << ". Don't remove any items " << std::endl; int choice; std::cin >> choice; if (choice <= bag.size()) { Item *remove = bag[choice-1]; mergeNum -= remove->getId(); bag.erase(bag.begin() + ( choice-1 ) ); std::cout << "The item was successfully removed from your bag " << std::endl; return remove; } else return 0; } } /********************************************************************* ** Function: toString() ** Description: Function that returns a string representing all the items ** in the backpack. ** Parameters: N/A ** Pre-Conditions: Backpack object must exist ** Post-Conditions: String that indicates what items are in the back pack ** is returned. ** ********************************************************************/ std::string Backpack::toString() { std::string contents = ""; int i; std::stringstream tempString; for (i = 0; i < bag.size(); i++) { int num = i + 1; tempString << num << ". " << bag[i]->getName() << "\n"; } contents += tempString.str(); return contents; }
C++
CL
ecd459e98f54f3b97b0a68e7ef42029ff497a04ca9106e662b617a743b48b185
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #pragma once #define MEMCACHED_ENGINE_H #include <cstdint> #include <cstdio> #include <cstring> #include <functional> #include <memory> #include <sys/types.h> #include <utility> #include "memcached/allocator_hooks.h" #include "memcached/callback.h" #include "memcached/collections.h" #include "memcached/config_parser.h" #include "memcached/dcp.h" #include "memcached/dockey.h" #include "memcached/engine_common.h" #include "memcached/extension.h" #include "memcached/protocol_binary.h" #include "memcached/server_api.h" #include "memcached/types.h" #include "memcached/vbucket.h" /*! \mainpage memcached public API * * \section intro_sec Introduction * * The memcached project provides an API for providing engines as well * as data definitions for those implementing the protocol in C. This * documentation will explain both to you. * * \section docs_sec API Documentation * * Jump right into <a href="modules.html">the modules docs</a> to get started. * * \example default_engine.cc */ /** * \defgroup Engine Storage Engine API * \defgroup Protex Protocol Extension API * \defgroup Protocol Binary Protocol Structures * * \addtogroup Engine * @{ * * Most interesting here is to implement engine_interface_v1 for your * engine. */ #define ENGINE_INTERFACE_VERSION 1 /** * Abstract interface to an engine. */ #ifdef WIN32 #undef interface #endif /* This is typedefed in types.h */ struct server_handle_v1_t { uint64_t interface; /**< The version number on the server structure */ SERVER_CORE_API* core; SERVER_STAT_API* stat; SERVER_EXTENSION_API* extension; SERVER_CALLBACK_API* callback; ENGINE_HANDLE* engine; SERVER_LOG_API* log; SERVER_COOKIE_API* cookie; ALLOCATOR_HOOKS_API* alloc_hooks; SERVER_DOCUMENT_API* document; }; typedef enum { TAP_MUTATION = 1, TAP_DELETION, TAP_FLUSH, TAP_OPAQUE, TAP_VBUCKET_SET, TAP_ACK, TAP_DISCONNECT, TAP_NOOP, TAP_PAUSE, TAP_CHECKPOINT_START, TAP_CHECKPOINT_END } tap_event_t; /** * An iterator for the tap stream. * The memcached core will keep on calling this function as long as a tap * client is connected to the server. Each event returned by the iterator * will be encoded in the binary protocol with the appropriate command opcode. * * If the engine needs to store extra information in the tap stream it should * do so by returning the data through the engine_specific pointer. This data * should be valid for the core to use (read only) until the next invocation * of the iterator, of if the connection is closed. * * @param handle the engine handle * @param cookie identification for the tap stream * @param item item to send returned here (check tap_event_t) * @param engine_specific engine specific data returned here * @param nengine_specific number of bytes of engine specific data * @param ttl ttl for this item (Tap stream hops) * @param flags tap flags for this object * @param seqno sequence number to send * @param vbucket the virtual bucket id * @return the tap event to send (or TAP_PAUSE if there isn't any events) */ typedef tap_event_t (* TAP_ITERATOR)(ENGINE_HANDLE* handle, const void* cookie, item** item, void** engine_specific, uint16_t* nengine_specific, uint8_t* ttl, uint16_t* flags, uint32_t* seqno, uint16_t* vbucket); typedef ENGINE_ERROR_CODE (* engine_get_vb_map_cb)(const void* cookie, const void* map, size_t mapsize); /** * The signature for the "create_instance" function exported from the module. * * This function should fill out an engine inteface structure according to * the interface parameter (Note: it is possible to return a lower version * number). * * @param interface The highest interface level the server supports * @param get_server_api function to get the server API from * @param Where to store the interface handle * @return See description of ENGINE_ERROR_CODE */ typedef ENGINE_ERROR_CODE (* CREATE_INSTANCE)(uint64_t interface, GET_SERVER_API get_server_api, ENGINE_HANDLE** handle); /** * The signature for the "destroy_engine" function exported from the module. * * This function is called prior to closing of the module. This function should * free any globally allocated resources. * */ typedef void (* DESTROY_ENGINE)(void); typedef enum { ENGINE_FEATURE_CAS, /**< has compare-and-set operation */ ENGINE_FEATURE_PERSISTENT_STORAGE, /**< has persistent storage support*/ ENGINE_FEATURE_SECONDARY_ENGINE, /**< performs as pseudo engine */ ENGINE_FEATURE_ACCESS_CONTROL, /**< has access control feature */ ENGINE_FEATURE_MULTI_TENANCY, ENGINE_FEATURE_LRU, /* Cache implements an LRU */ ENGINE_FEATURE_VBUCKET, /* Cache implements virtual buckets */ ENGINE_FEATURE_DATATYPE, /**< uses datatype field */ /** * The engine supports storing the items value into multiple * chunks rather than a continous segment. */ ENGINE_FEATURE_ITEM_IOVECTOR, #define LAST_REGISTERED_ENGINE_FEATURE ENGINE_FEATURE_ITEM_IOVECTOR } engine_feature_t; typedef struct { /** * The identifier of this feature. All values with the most significant bit cleared is reserved * for "registered" features. */ uint32_t feature; /** * A textual description of the feature. (null will print the registered name for the feature * (or "Unknown feature")) */ const char* description; } feature_info; typedef struct { /** * Textual description of this engine */ const char* description; /** * The number of features the server provides */ uint32_t num_features; /** * An array containing all of the features the engine supports */ feature_info features[1]; } engine_info; /** * A unique_ptr to use with items returned from the engine interface. */ namespace cb { class ItemDeleter; typedef std::unique_ptr<item, ItemDeleter> unique_item_ptr; using EngineErrorItemPair = std::pair<cb::engine_errc, cb::unique_item_ptr>; } /** * Definition of the first version of the engine interface */ typedef struct engine_interface_v1 { /** * Engine info. */ struct engine_interface interface; /** * Get a description of this engine. * * @param handle the engine handle * @return a stringz description of this engine */ const engine_info* (* get_info)(ENGINE_HANDLE* handle); /** * Initialize an engine instance. * This is called *after* creation, but before the engine may be used. * * @param handle the engine handle * @param config_str configuration this engine needs to initialize itself. */ ENGINE_ERROR_CODE (* initialize)(ENGINE_HANDLE* handle, const char* config_str); /** * Tear down this engine. * * @param handle the engine handle * @param force the flag indicating the force shutdown or not. */ void (* destroy)(ENGINE_HANDLE* handle, const bool force); /* * Item operations. */ /** * Allocate an item. * * @param handle the engine handle * @param cookie The cookie provided by the frontend * @param output variable that will receive the item * @param key the item's key * @param nbytes the number of bytes that will make up the * value of this item. * @param flags the item's flags * @param exptime the maximum lifetime of this item * @param vbucket virtual bucket to request allocation from * * @return ENGINE_SUCCESS if all goes well */ ENGINE_ERROR_CODE (* allocate)(ENGINE_HANDLE* handle, const void* cookie, item** item, const DocKey& key, const size_t nbytes, const int flags, const rel_time_t exptime, uint8_t datatype, uint16_t vbucket); /** * Allocate an item. * * @param handle the engine handle * @param cookie The cookie provided by the frontend * @param key the item's key * @param nbytes the number of bytes that will make up the * value of this item. * @param priv_nbytes The number of bytes in nbytes containing * system data (and may exceed the item limit). * @param flags the item's flags * @param exptime the maximum lifetime of this item * @param vbucket virtual bucket to request allocation from * @return pair containing the item and the items information * @thows cb::engine_error with: * * * `cb::engine_errc::no_bucket` The client is bound to the dummy * `no bucket` which don't allow * allocations. * * * `cb::engine_errc::no_memory` The bucket is full * * * `cb::engine_errc::too_big` The requested memory exceeds the * limit set for items in the bucket. * * * `cb::engine_errc::disconnect` The client should be disconnected * * * `cb::engine_errc::not_my_vbucket` The requested vbucket belongs * to someone else * * * `cb::engine_errc::temporary_failure` Temporary failure, the * _client_ should try again * * * `cb::engine_errc::too_busy` Too busy to serve the request, * back off and try again. */ std::pair<cb::unique_item_ptr, item_info> (* allocate_ex)(ENGINE_HANDLE* handle, const void* cookie, const DocKey& key, const size_t nbytes, const size_t priv_nbytes, const int flags, const rel_time_t exptime, uint8_t datatype, uint16_t vbucket); /** * Remove an item. * * @param handle the engine handle * @param cookie The cookie provided by the frontend * @param key the key identifying the item to be removed * @param vbucket the virtual bucket id * @param mut_info On a successful remove write the mutation details to * this address. * * @return ENGINE_SUCCESS if all goes well */ ENGINE_ERROR_CODE (* remove)(ENGINE_HANDLE* handle, const void* cookie, const DocKey& key, uint64_t* cas, uint16_t vbucket, mutation_descr_t* mut_info); /** * Indicate that a caller who received an item no longer needs * it. * * @param handle the engine handle * @param cookie The cookie provided by the frontend * @param item the item to be released */ void (* release)(ENGINE_HANDLE* handle, const void* cookie, item* item); /** * Retrieve an item. * * @param handle the engine handle * @param cookie The cookie provided by the frontend * @param item output variable that will receive the located item * @param key the key to look up * @param vbucket the virtual bucket id * @param documentStateFilter The document to return must be in any of * of these states. (If `Alive` is set, return * KEY_ENOENT if the document in the engine * is in another state) * * @return ENGINE_SUCCESS if all goes well */ ENGINE_ERROR_CODE (* get)(ENGINE_HANDLE* handle, const void* cookie, item** item, const DocKey& key, uint16_t vbucket, DocStateFilter documentStateFilter); /** * Optionally retrieve an item. Only non-deleted items may be fetched * through this interface (Documents in deleted state may be evicted * from memory and we don't want to go to disk in order to fetch these) * * @param handle the engine handle * @param cookie The cookie provided by the frontend * @param key the key to look up * @param vbucket the virtual bucket id * @param filter callback filter to see if the item should be returned * or not. If filter returns false the item should be * skipped. * @return A pair of the error code and (optionally) the item */ cb::EngineErrorItemPair (* get_if)(ENGINE_HANDLE* handle, const void* cookie, const DocKey& key, uint16_t vbucket, std::function<bool( const item_info&)> filter); /** * Lock and Retrieve an item. * * @param handle the engine handle * @param cookie The cookie provided by the frontend * @param item output variable that will receive the located item * @param key the key to look up * @param vbucket the virtual bucket id * @param lock_timeout the number of seconds to hold the lock * (0 == use the engines default lock time) * * @return ENGINE_SUCCESS if all goes well */ ENGINE_ERROR_CODE (* get_locked)(ENGINE_HANDLE* handle, const void* cookie, item** item, const DocKey& key, uint16_t vbucket, uint32_t lock_timeout); /** * Get and update the expiry time for the document * * @param handle the engine handle * @param cookie The cookie provided by the frontend * @param key the key to look up * @param vbucket the virtual bucket id * @param expirytime the new expiry time for the object * @return A pair of the error code and (optionally) the item */ cb::EngineErrorItemPair (*get_and_touch)(ENGINE_HANDLE* handle, const void* cookie, const DocKey& key, uint16_t vbucket, uint32_t expirytime); /** * Unlock an item. * * @param handle the engine handle * @param cookie The cookie provided by the frontend * @param key the key to look up * @param vbucket the virtual bucket id * @param cas the cas value for the locked item * * @return ENGINE_SUCCESS if all goes well */ ENGINE_ERROR_CODE (* unlock)(ENGINE_HANDLE* handle, const void* cookie, const DocKey& key, uint16_t vbucket, uint64_t cas); /** * Store an item into the underlying engine with the given * state. If the DocumentState is set to DocumentState::Deleted * the document shall not be returned unless explicitly asked for * documents in that state, and the underlying engine may choose to * purge it whenever it please. * * @param handle the engine handle * @param cookie The cookie provided by the frontend * @param item the item to store * @param cas the CAS value for conditional sets * @param operation the type of store operation to perform. * @param document_state The state the document should have after * the update * * @return ENGINE_SUCCESS if all goes well */ ENGINE_ERROR_CODE (* store)(ENGINE_HANDLE* handle, const void* cookie, item* item, uint64_t* cas, ENGINE_STORE_OPERATION operation, DocumentState document_state); /** * Flush the cache. * * @param handle the engine handle * @param cookie The cookie provided by the frontend * * @return ENGINE_SUCCESS if all goes well */ ENGINE_ERROR_CODE (* flush)(ENGINE_HANDLE* handle, const void* cookie); /* * Statistics */ /** * Get statistics from the engine. * * @param handle the engine handle * @param cookie The cookie provided by the frontend * @param stat_key optional argument to stats * @param nkey the length of the stat_key * @param add_stat callback to feed results to the output * * @return ENGINE_SUCCESS if all goes well */ ENGINE_ERROR_CODE (* get_stats)(ENGINE_HANDLE* handle, const void* cookie, const char* stat_key, int nkey, ADD_STAT add_stat); /** * Reset the stats. * * @param handle the engine handle * @param cookie The cookie provided by the frontend */ void (* reset_stats)(ENGINE_HANDLE* handle, const void* cookie); /** * Any unknown command will be considered engine specific. * * @param handle the engine handle * @param cookie The cookie provided by the frontend * @param request pointer to request header to be filled in * @param response function to transmit data * @param doc_namespace namespace the command applies to * * @return ENGINE_SUCCESS if all goes well */ ENGINE_ERROR_CODE (* unknown_command)(ENGINE_HANDLE* handle, const void* cookie, protocol_binary_request_header* request, ADD_RESPONSE response, DocNamespace doc_namespace); /* TAP operations */ /** * Callback for all incoming TAP messages. It is up to the engine * to determine what to do with the event. The core will create and send * a TAP_ACK message if the flag section contains TAP_FLAG_SEND_ACK with * the status byte mapped from the return code. * * @param handle the engine handle * @param cookie identification for the tap stream * @param engine_specific pointer to engine specific data (received) * @param nengine_specific number of bytes of engine specific data * @param ttl ttl for this item (Tap stream hops) * @param tap_flags tap flags for this object * @param tap_event the tap event from over the wire * @param tap_seqno sequence number for this item * @param key the key in the message * @param nkey the number of bytes in the key * @param flags the flags for the item * @param exptime the expiry time for the object * @param cas the cas for the item * @param data the data for the item * @param ndata the number of bytes in the object * @param vbucket the virtual bucket for the object * @return ENGINE_SUCCESS for success */ ENGINE_ERROR_CODE (* tap_notify)(ENGINE_HANDLE* handle, const void* cookie, void* engine_specific, uint16_t nengine, uint8_t ttl, uint16_t tap_flags, tap_event_t tap_event, uint32_t tap_seqno, const void* key, size_t nkey, uint32_t flags, uint32_t exptime, uint64_t cas, uint8_t datatype, const void* data, size_t ndata, uint16_t vbucket); /** * Get (or create) a Tap iterator for this connection. * @param handle the engine handle * @param cookie The connection cookie * @param client The "name" of the client * @param nclient The number of bytes in the client name * @param flags Tap connection flags * @param userdata Specific userdata the engine may know how to use * @param nuserdata The size of the userdata * @return a tap iterator to iterate through the event stream */ TAP_ITERATOR (* get_tap_iterator)(ENGINE_HANDLE* handle, const void* cookie, const void* client, size_t nclient, uint32_t flags, const void* userdata, size_t nuserdata); /** * Set the CAS id on an item. */ void (* item_set_cas)(ENGINE_HANDLE* handle, const void* cookie, item* item, uint64_t cas); /** * Get information about an item. * * The loader of the module may need the pointers to the actual data within * an item. Instead of having to create multiple functions to get each * individual item, this function will get all of them. * * @param handle the engine that owns the object * @param cookie connection cookie for this item * @param item the item to request information about * @param item_info * @return true if successful */ bool (* get_item_info)(ENGINE_HANDLE* handle, const void* cookie, const item* item, item_info* item_info); /** * Set information of an item. * * Set updated item information. * * @param handle the engine that owns the object * @param cookie connection cookie for this item * @param item the item who's information is to be updated * @param item_info * @return true if successful */ bool (* set_item_info)(ENGINE_HANDLE* handle, const void* cookie, item* item, const item_info* itm_info); /** * Get the vbucket map stored in the engine * * @param handle the engine handle * @param cookie The connection cookie * @param callback a function the engine may call to "return" the * buffer. * @return ENGINE_SUCCESS for success */ ENGINE_ERROR_CODE (* get_engine_vb_map)(ENGINE_HANDLE* handle, const void* cookie, engine_get_vb_map_cb callback); struct dcp_interface dcp; /** * Set the current log level * * @param handle the engine handle * @param level the current log level */ void (* set_log_level)(ENGINE_HANDLE* handle, EXTENSION_LOG_LEVEL level); collections_interface collections; } ENGINE_HANDLE_V1; namespace cb { class ItemDeleter { public: ItemDeleter() = delete; /** * Create a new instance of the item deleter. * * @param handle_ the handle to the the engine who owns the item */ ItemDeleter(ENGINE_HANDLE* handle_) : handle(handle_) { if (handle == nullptr) { throw std::invalid_argument( "cb::ItemDeleter: engine handle cannot be nil"); } } /** * Create a copy constructor to allow us to use std::move of the item */ ItemDeleter(const ItemDeleter& other) : handle(other.handle) { } void operator()(item* item) { auto* v1 = reinterpret_cast<ENGINE_HANDLE_V1*>(handle); v1->release(handle, nullptr, item); } private: ENGINE_HANDLE* handle; }; } /** * @} */
C++
CL
2f7afbd258ad8d80d73ce94c161b7a03a6ee497d12f83348e681149a83a117d2
/* Yelo: Open Sauce SDK See license\OpenSauce\OpenSauce for specific license information */ #pragma once //#define XLIVE_NO_NETDLL //#define XLIVE_NO_XAPI //#define XLIVE_NO_XAM #define XLIVE_NO_XLIVE extern "C" { #include "XLive/XLive.Xapi.hpp" #include "XLive/XLive.NetDll.hpp" typedef struct { DWORD SizeOfStruct; PAD32; PAD32; PAD32; PAD32; PAD32; }XLiveInitializeParams; BOOST_STATIC_ASSERT( sizeof(XLiveInitializeParams) == 0x18 ); enum { eXUserSigninState_SignedInLocally = 1, XLIVE_FEIGN_PROTECTED_BUFFER_SIG = 0xDEADC0DE, }; typedef struct { DWORD dwSignature; DWORD dwSize; PAD32; PAD32; }XLiveFeignProtectedBuffer; };
C++
CL
b025e061c392662a4c95014bb21e87f65f1c079ec973b7cef24cc2e69035883f
#pragma once #include "JN_BasicActors.h" #include "JN_Scene.h" #include "BasicActors.h" #include "PxPhysicsAPI.h" using namespace physx; namespace Actors { class JN_Paddle : public Actors::Capsule { public: // Constructor JN_Paddle(const PxTransform& pose = PxTransform(PxIdentity), PxVec2 dimensions = PxVec2(1.f, 1.f), PxReal offset = 0.0f, PxReal density = 1.f); // Add capsule to the object void AddToScene(JN_Scene* scene); // Add force void Activate(PxReal force); private: RevoluteJoint* joint; }; }
C++
CL
86becfebcaac8a3c669f78cdf98451abc4095c794d7cb8bcc9c92d6be8621324
// btlsc_timedcbchannel.h -*-C++-*- // ---------------------------------------------------------------------------- // NOTICE // // This component is not up to date with current BDE coding standards, and // should not be used as an example for new development. // ---------------------------------------------------------------------------- #ifndef INCLUDED_BTLSC_TIMEDCBCHANNEL #define INCLUDED_BTLSC_TIMEDCBCHANNEL #ifndef INCLUDED_BSLS_IDENT #include <bsls_ident.h> #endif BSLS_IDENT("$Id: $") //@PURPOSE: Provide protocol for stream-based data communication with timeout. // //@CLASSES: // btlsc::TimedCbChannel: non-blocking stream-based channel protocol w/timeout // //@SEE_ALSO: btlsc_timedchannel // //@DESCRIPTION: This component provides a class, 'btlsc::TimedCbChannel', that // defines an abstract interface for an end-point of a bi-directional // (full-duplex) non-blocking stream-based communication channel with timeout // capability. The protocol supports efficient "buffered" transport and the // syntax to enable efficient vector I/O operations (i.e., Unix-style // scatter/gather 'readv' and 'writev'). Various forms of "partial // transmission" authorizations (i.e., "raw" OS-level atomic operations and // interruptions due to a user-specified "timeout" and "asynchronous events") // are also supported for each method as appropriate. // // Read and write operations are enqueued separately (facilitating full-duplex // operation) and executed in order within each queue. In contrast, the // relative sequence in which the "read" and "write" queues are serviced is // implementation dependent. // // Users can cancel enqueued operations via the 'cancelRead', 'cancelWrite, and // 'cancelAll' methods. Also, if a read (write) operation returns with a // partial result (see below), all pending read (write) operations will be // dequeued; the callback status will reflect the reason for the incomplete // result. Such dequeued operations may be re-submitted (presumably after // inspection of the callback status) at the user's discretion. // // Finally, users can invalidate the read and write portions of a channel // separately, or the entire channel at once. // ///Protocol Hierarchy ///------------------ // The interface hierarchy (defined by direct public inheritance) of the // 'btlsc::TimedCbChannel' protocol is as follows: //.. // ,---------------------. // ( btlsc::TimedCbChannel ) // `---------------------' // | // V // ,----------------. // ( btlsc::CbChannel ) // `----------------' //.. // 'btlsc::TimedCbChannel' adds a "timeout" capability for read and write // methods. // ///Non-Blocking Stream-Based Transport ///----------------------------------- // This interface establishes methods for non-blocking stream-based transport. // A method call registers the I/O request and a user-supplied callback // function object (functor), and returns immediately with a status indicating // the success or failure of the registration. After successful registration, // the channel eventually services the enqueued I/O operation and invokes the // callback function, which in turn conveys the status of the transmission. // Note that if the initial registration is not successful, the callback // function will *not* be invoked. Also note that whether the callback is // invoked before or after the registering method returns is not specified; in // either case, if the registration was successful, then the return value will // reflect success. // // Enqueued read and write operations proceed asynchronously to one of four // possible results: (1) "success" -- the specified number of bytes was // transmitted, (2) "partial transmission" -- the operation was interrupted // (e.g., via a timeout), (3) "canceled transmission" -- the request was // dequeued (either by the user or by the channel), or (4) "error" -- an // implementation-dependent error occurred. In all cases, status information // and any appropriately available data are communicated to the user via the // registered callback function, including status information to distinguish // among various reasons for incomplete transmissions (see below). The user // may retry incomplete operations (with method arguments suitably adjusted), // with a reasonable expectation of success. // // Finally, concrete non-blocking stream-based channels do a "best effort" in // sending and receiving the specified data, but need not guarantee successful // transmission. // ///Callback Functor Registration ///- - - - - - - - - - - - - - - // Once an operation is successfully initiated, a (reference-counted) copy of // the ('bdlf') callback functor is retained by the concrete channel until the // callback is executed. Therefore, the user need not be concerned with // preserving the resources explicitly used by the 'bdlf' functor. // ///Buffered Transport ///------------------ // Most (but not all) I/O operations support a "buffered" variant that may be // more efficient in some situations. For such operations, the prefix // "buffered" (or infix "Buffered") appears before the basic operation name in // the full method name (e.g., 'bufferedRead', 'timedBufferedWrite'). // // The "buffered" read operations optimize throughput (as opposed to latency) // for relatively small transmissions under high-volume conditions. The // specific buffered-read method signatures enable the concrete transport to // read as much as it efficiently can (i.e., without blocking) and buffer that // information for current and future use. In the buffered variant, the caller // does not provide a buffer, but rather receives direct (non-modifiable) // access to the implementation's buffered data. In the event of a partial // read (see below), the data remains buffered and subsequent reads will behave // as if the buffered operation had never occurred. Once a buffered read // operation succeeds (i.e., receives the requested number of bytes) the // buffered contents will become invalid after the callback function returns. // Note that "buffered" and "vector" ('readv', see below) are incompatible read // options. // // The "buffered" write operations relieve the caller from having to preserve // an input buffer during processing. A "buffered write" operation transmits // as much data as possible without blocking, and then copies any remaining // data to a buffer owned by the channel for eventual transmission. Note that // the callback function is not invoked until the I/O operation terminates // (successfully or otherwise, see above). Also note that "buffered" and "raw" // (see below) are incompatible write options. // ///Incomplete Transmissions: "Partial" and "Canceled" ///-------------------------------------------------- // The "simple" results of read and write operations are "success" (with a // status equal to the requested number of bytes) and "error" (with a negative // status). More complex behavior is also supported, some of which is at the // option of the user. Specifically, the caller may authorize the possibility // of another outcome via combinations of the following three mechanisms: (1) a // user-requested timeout, (2) an interruption due to an asynchronous event, // and (3) a "raw" operation, i.e., accepting the results of a single low-level // (implementation dependent) atomic read/write operation. These three // mechanisms (discussed in more detail below) may each result in a "partial // transmission", characterized by a non-negative status that is less than the // requested number of bytes. Note that timeouts and asynchronous events, but // *not* raw operations, may result in a return status of zero bytes. // // A return status of exactly zero bytes may also occur via a fourth mechanism. // As discussed above, an enqueued operation may be dequeued due to the // partial-transmission status of a prior operation. Also, the 'cancelRead', // 'cancelWrite', and 'cancelAll' methods may be used to dequeue all enqueued // requests from the read queue, the write queue, and both queues, // respectively. All such dequeued operations result in "canceled // transmissions". // // "Partial" and "canceled" transmissions share some common characteristics, // and so are collectively referred to as "incomplete transmissions". The // specific cause of an incomplete transmission (as deduced from "status") can // in turn be determined by examining a second status value, called the // "augStatus", described in detail below. All incomplete transmissions may be // re-submitted with a reasonable expectation of success. // ///Asynchronous Events ///- - - - - - - - - - // Methods in this protocol anticipate the possible occurrence of an // "asynchronous event" (AE) during execution. This interface cannot specify // what an AE is, but a common example of an AE is a Unix signal. Note, // however, that a Unix signal need not be an AE, and an AE certainly need not // be a signal. It is up to the concrete implementation to define what is and // is not an AE. // // Since the specific nature of an AE is not defined here, method behavior // resulting from an AE likewise cannot be fully specified. Rather, certain // restrictions are imposed. By default, AEs are either ignored or, if that is // not possible, cause an error. The user may, however, choose to authorize // (when a method is invoked) that an AE causes a concrete implementation to // return, if possible, a "partial transmission" (which may be resumed -- see // above). This authorization is made by incorporating (i.e., bitwise OR-ing) // the 'btlsc::Flag::k_ASYNC_INTERRUPT' value into an optional (trailing) // integer 'flags' argument to the method call. // ///Timeouts /// - - - - // A timeout is registered by the caller, when a method is invoked, as a // 'bsls::TimeInterval' value indicating the absolute *system* time after which // the operation should be interrupted. A timeout expiration will result in a // "partial transmission" (see above). Information regarding the nature of a // partial result is provided via the callback as an "augStatus" argument (see // below). // // The concrete channel will make a "best effort" to honor the timeout request // promptly, but no guarantee can be made as to the maximum duration of any // particular I/O attempt. Any implementation of this interface will support a // timeout granularity of ten milliseconds (0.01s) or less. The timeout is // guaranteed *not* to occur before the specified time has passed. If a // timeout is specified with a time that has already passed, the I/O operation // will be attempted, but will not block. Note that since respective read and // write operations are enqueued separately, a long-running read (write) // operation will not impact the behavior of a concurrent write (read) // operation, but *can* affect subsequent read (write) operations. // ///Raw Transmissions ///- - - - - - - - - // All read and unbuffered write operations support a "raw" variant in which // the function is allowed to return with a "partial transmission" if (1) *at* // *least* *one* *byte* has been transmitted and (2) no additional bytes are // *immediately* transmittable. The "raw" mode is particularly useful to // callers waiting for some read activity, who will then follow up with // additional read requests after observing the initial transmission. Raw // transmissions are authorized by methods whose names end in the suffix 'Raw'. // Note that the "raw" mode is not supported (and nonsensical) for // buffered-write operations. // ///'augStatus' ///- - - - - - // Since any enqueued I/O request can be dequeued (canceled) by the channel or // the user, and the user can authorize various modes supporting "partial // transmission", the caller may wish to know the cause of an incomplete // transmission. Callback functions therefore take a second 'int' status // value, 'augStatus' ("augmented status"). This value will be 0 if the // operation timed out, a positive value if the interruption was due to an // "asynchronous event", and a negative value if the request was dequeued by // the channel or the user. // ///Scatter/Gather ('readv'/'writev') ///--------------------------------- // This interface supports "vector I/O" -- the simultaneous reading from or // writing to multiple buffers -- via Unix-style 'readv' and 'writev' variants // of the normal single-buffer methods. These vector methods rely on two // auxiliary data structures defined in the 'btls_iovec' component. // // The 'btls::Iovec' structure will be familiar to most Unix systems // programmers. The 'Ovec' variant enables read operations to avoid having to // cast away 'const' in order to hold the address of non-modifiable data to be // written. In either structure, the total number of bytes to be read or // written is determined by the sum of the non-negative 'length' method values // in the contiguous sequence of structures supplied to the method along with a // *positive* sequence length (note that at least one of the 'length' values // must be positive). The following simple example shows how to create and // populate an 'Ovec' structure array in preparation for a 'bufferedWritev' // operation: //.. // static void myPrintWriteStatus(int status, int augStatus, int numBytes) // // Print to the user console the result of attempting to write the // // specified 'numBytes' based on the specified write 'status' and // // the auxiliary 'augStatus' (discussed below). The behavior is // // undefined unless '0 < numBytes' and 'status <= numBytes'. Note // // that 'augStatus' is ignored unless '0 <= status < numBytes'. // { // assert(0 < numBytes); // assert(status <= numBytes); // // if (status == numBytes) { // bsl::cout << "All requested bytes written successfully." // << bsl::endl; // } // else if (0 <= status) { // PARTIAL RESULTS ARE NOT AUTHORIZED BELOW // // if (0 < augStatus) { // bsl::cout << "Write interrupted (not by time out) after " // << "writing " << status << " of " << numBytes // << " bytes." << bsl::endl; // } // else (0 == augStatus) { // bsl::cout << "Write timed out after writing " << // << status << " of " << numBytes << " bytes." // << bsl::endl; // } // else { // assert(augStatus < 0); // if (0 == status) { // bsl::cout // << "Write operation dequeued due to partial " // << "write in some preceding enqueued operation." // << bsl::endl; // } // else { // assert(status > 0); // bsl::cout << "Write (efficiently) transmitted " // << status // << " of " << numBytes << bytes." << bsl::endl; // } // } // } // else if (-1 == status) { // bsl::cout << "Write failed: connection was closed by peer." // << bsl::endl; // } // else { // assert(status < -1); // bsl::cout << "Write failed: the reason is unknown." // << bsl::endl; // } // } // // void myWritevAndPrintStatusWhenAvailable(btlsc::TimedCbChannel *channel) // // Write the integer representation of the length of a character // // string followed by the (non-terminated) string data itself to // // the specified 'channel'; upon completion, report the status // // of the "write" operation to 'cout'. // { // const char *const MESSAGE = "Hello World!"; // const int HEADER = strlen(MESSAGE); // const int NUM_BUFFERS = 2; // // btls::Ovec buffers[NUM_BUFFERS]; // // buffers[0].setBuffer(&HEADER, sizeof HEADER); // buffers[1].setBuffer(MESSAGE, HEADER); // // const int TOTAL_NUM_BYTES = buffers[0].length() // + buffers[1].length()); // // // Create a functor. // // using namespace bdlf::PlaceHolders; // btlsc::TimedCbChannel::WriteCallback functor( // bdlf::BindUtil::bind( // &myPrintWriteStatus, // _1, _2, // TOTAL_NUM_BYTES)); // extra user argument // // if (0 != channel->bufferedWritev(buffers, NUM_BUFFERS)) { // bsl::cout << "Buffered write operation failed immediately!" // << bsl::endl; // } // // // Notice that the 'bufferedWritev' operation above does not // // authorize any partial write operations whatsoever. When // // invoked, the "status" passed to the callback will be either // // 'TOTAL_NUM_BYTES' for *success* or negative for *error* // // (baring some other pending "write" operation on this channel // // that explicitly enabled a partial result). // } //.. // Note that once the 'bufferedWritev' operation returns, there is no need to // preserve either the output buffers or the array of 'Ovec' (or 'Iovec') // structures used to identify them (they would potentially be needed only to // continue after a partial write, say, due to an interruption if such were // authorized). By contrast, both the output buffers and the array of 'Ovec' // (or 'Iovec') structures must remain valid until an *unbuffered* 'writev' // operation completes and its corresponding 'WriteCallback' is invoked. Since // all 'readv' operations are necessarily unbuffered, both the array of 'Iovec' // structures and each input buffer must remain valid until the 'readv' // operation completes and its 'ReadCallback' is invoked. Note that "vectored" // and "buffered" reads are inherently incompatible. // ///Synopsis ///-------- // The following chart summarizes the set of 20 transmission methods that are // available to read and write data from and to a 'btlsc::TimedCbChannel'; note // that, for efficiency reasons, only three vector operations, 'readvRaw', // 'writevRaw', and 'bufferedWritev' (and their "timed" counterparts) are // provided. Also, the "buffered write raw" operations are not supported by // this protocol: //.. // Buffered Re/Wr Vec Raw Untimed Method Name Timed Method Name // -------- ----- --- --- ------------------- ----------------- // READ read timedRead // READ RAW readRaw timedReadRaw // // READ VEC RAW readvRaw timedReadvRaw // // BUFFERED READ bufferedRead timedBufferedRead // BUFFERED READ RAW bufferedReadRaw timedBufferedReadRaw // // WRITE write timedWrite // WRITE RAW writeRaw timedWriteRaw // // WRITE VEC RAW writevRaw timedWritevRaw // // BUFFERED WRITE bufferedWrite timedBufferedWrite // BUFFERED WRITE VEC bufferedWritev timedBufferedWritev //.. // Each of these methods supports the specification of a flag value: //.. // btlsc::Flag::k_ASYNC_INTERRUPT //.. // supplied in an optional trailing integer to enable interruptions due to // "asynchronous events" to result in partial transmissions; by default, // asynchronous events are ignored. // // The following summarizes the return status values for a request to transmit // 'N' bytes. //.. // 'status' 'augStatus' meaning // ---------- ---------- -------------------------------------------- // N x Success // [0..(N-1)] positive Interruption by an "asynchronous event" // [0..(N-1)] 0 Interruption by a user-requested timeout // [1..(N-1)] x Raw operation could not complete w/o blocking // 0 negative Pending operation dequeued before execution // negative x Error //.. #ifndef INCLUDED_BTLSCM_VERSION #include <btlscm_version.h> #endif #ifndef INCLUDED_BTLSC_CBCHANNEL #include <btlsc_cbchannel.h> #endif #ifndef INCLUDED_BTLS_IOVEC #include <btls_iovec.h> #endif #ifndef INCLUDED_BSL_FUNCTIONAL #include <bsl_functional.h> #endif namespace BloombergLP { namespace bsls { class TimeInterval; } namespace btlsc { // ==================== // class TimedCbChannel // ==================== class TimedCbChannel : public CbChannel { // This class represents a protocol (pure abstract interface) for a // communications channel that supports timed (non-blocking) buffered read // and write operations on a byte stream. In general, a non-negative // status indicates the number of bytes read or written, while a negative // status implies an unspecified error. Note that an error status of -1 // indicates that the connection is *known* to have been closed by the // peer. The converse -- that -1 will be returned if/when a peer drops a // connection -- cannot be guaranteed by implementations of this interface // and must not be relied upon by users. private: // NOT IMPLEMENTED TimedCbChannel& operator=(const TimedCbChannel&); public: // CREATORS virtual ~TimedCbChannel(); // Destroy this object. // TYPES typedef bsl::function<void(int, int)> ReadCallback; // Invoked as a result of any non-buffered read method, 'ReadCallback' // is an alias for a callback function object (functor) that returns // 'void' and takes as arguments an integer "status" indicating // *success*, an *incomplete* *read*, or an *error*, and a second // integer "augStatus". Together, the two status values indicate four // possible reasons for any incomplete result: (1) interruption by a // timeout, (2) a (caller-authorized) interruption by an asynchronous // event, (3) a (caller-authorized) implementation-dependent, // data-driven optimization, or (4) an operation dequeued (canceled) // by the implementation or the user. typedef bsl::function<void(const char *, int, int)> BufferedReadCallback; // Invoked as a result of any buffered read method, // 'BufferedReadCallback' is an alias for a callback function object // (functor) that returns 'void' and takes as arguments the (potential) // address of a non-modifiable character "buffer"; an integer "status" // indicating *success*, an *incomplete* *read*, or an *error*, and a // second integer "augStatus". Together, the two status values // indicate four possible reasons for any incomplete result: (1) // interruption by a timeout, (2) a (caller-authorized) interruption by // an asynchronous event, (3) a (caller-authorized) // implementation-dependent, data-driven optimization, or (4) an // operation dequeued (canceled) by the implementation or the user. typedef bsl::function<void(int, int)> WriteCallback; // Invoked as a result of any write method, 'WriteCallback' is an alias // for a callback function object (functor) that returns 'void' and // takes as arguments an integer "status" indicating *success*, an // *incomplete* *write*, or an *error*, and a second integer // "augStatus". Together, the two status values indicate four possible // reasons for any incomplete result: (1) interruption by a timeout, // (2) a (caller-authorized) interruption by an asynchronous event, (3) // a (caller-authorized) implementation-dependent, data-driven // optimization, or (4) an operation dequeued (canceled) by the // implementation or the user. // MANIPULATORS virtual int read(char *buffer, int numBytes, const ReadCallback& readCallback, int flags = 0) = 0; // Initiate a non-blocking operation to read the specified 'numBytes' // from this channel into the specified 'buffer'; execute the specified // 'readCallback' functor after this read operation terminates. If the // optionally specified 'flags' incorporates // 'btlsc::Flag::k_ASYNC_INTERRUPT', "asynchronous events" are // permitted to interrupt this operation; by default, such events are // ignored. Return 0 on successful initiation, and a non-zero value // otherwise (in which case 'readCallback' will not be invoked). // // When invoked, the 'readCallback' is passed an integer "status" and a // second integer "augStatus" (which is meaningful only upon an // incomplete transmission). If "status" is equal to 'numBytes', the // operation was successful and 'buffer' is loaded with 'numBytes' of // incoming data. Otherwise, if "status" is non-negative (incomplete // read), it indicates the number of bytes read into 'buffer' in which // case "augStatus" will be positive if the operation was interrupted // due to an asynchronous event, and negative ("status" identically 0) // if this operation was canceled. If the transmission is incomplete, // the channel itself potentially remains valid; hence, this (or // another) operation may be retried (with arguments suitably adjusted) // with some reasonable hope of success. A negative "status", however, // indicates a permanent error (leaving the contents of 'buffer' // undefined); -1 implies that the connection was closed by the peer // (but the converse is not guaranteed). The behavior is undefined // unless 'buffer' has sufficient capacity to hold the requested data // and remains valid until the (non-null) 'readCallback' completes, and // '0 < numBytes'. virtual int timedRead(char *buffer, int numBytes, const bsls::TimeInterval& timeout, const ReadCallback& readCallback, int flags = 0) = 0; // Initiate a non-blocking operation to read the specified 'numBytes' // from this channel into the specified 'buffer' or interrupt after the // specified absolute 'timeout' time is reached; execute the specified // 'readCallback' functor after this read operation terminates. If the // optionally specified 'flags' incorporates // 'btlsc::Flag::k_ASYNC_INTERRUPT', "asynchronous events" are // permitted to interrupt this operation; by default, such events are // ignored. Return 0 on successful initiation, and a non-zero value // otherwise (in which case 'readCallback' will not be invoked). // // When invoked, 'readCallback' is passed an integer "status" and a // second integer "augStatus" (which is meaningful only upon an // incomplete transmission). If "status" is equal to 'numBytes', the // operation was successful and 'buffer' is loaded with 'numBytes' of // incoming data. Otherwise, if "status" is non-negative (incomplete // read), it indicates the number of bytes read into 'buffer' in which // case "augStatus" will be 0 if the interrupt was caused by the // caller-requested timeout event, positive if the operation was // interrupted due to an asynchronous event, and negative ("status" // identically 0) if this operation was canceled. If the transmission // is incomplete, the channel itself potentially remains valid; hence, // this (or another) operation may be retried (with arguments suitably // adjusted) with some reasonable hope of success. A negative // "status", however, indicates a permanent error (leaving the contents // of 'buffer' undefined); -1 implies that the connection was closed by // the peer (but the converse is not guaranteed). The behavior is // undefined unless 'buffer' has sufficient capacity to hold the // requested data and remains valid until the (non-null) 'readCallback' // completes, and '0 < numBytes'. Note that if the 'timeout' value has // already passed, the "read" operation will still be attempted, but // the attempt, once initiated, will not be permitted to block. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - virtual int readRaw(char *buffer, int numBytes, const ReadCallback& readCallback, int flags = 0) = 0; // Initiate a non-blocking operation to *atomically* read *up* *to* the // specified 'numBytes' from this channel into the specified 'buffer'; // execute the specified 'readCallback' functor after this read // operation terminates. If the optionally specified 'flags' // incorporates 'btlsc::Flag::k_ASYNC_INTERRUPT', "asynchronous // events" are permitted to interrupt this operation; by default, such // events are ignored. Return 0 on successful initiation, and a // non-zero value otherwise (in which case 'readCallback' will not be // invoked). // // When invoked, 'readCallback' is passed an integer "status" and a // second integer "augStatus" (which is meaningful for this method only // when "status" is zero). A non-negative "status" indicates the // number of bytes read into 'buffer'. If "status" is positive, the // atomic OS-level ("raw") read operation completed; "status" equals // 'numBytes' upon success. In either case, "augStatus" has no // meaning. If "status" is zero, the atomic read operation did not // complete, in which case "augStatus" is positive if an "asynchronous // event" interrupted the operation, and negative if the operation was // canceled. If the transmission was interrupted, the channel itself // potentially remains valid; hence, this (or another) operation may be // retried (with arguments suitably adjusted) with some reasonable hope // of success. A negative "status", however, indicates a permanent // error: -1 implies that the connection was closed by the peer (but // the converse is not guaranteed). The behavior is undefined unless // 'buffer' has sufficient capacity to hold the requested data and // remains valid until the (non-null) 'readCallback' completes, and // '0 < numBytes'. virtual int timedReadRaw(char *buffer, int numBytes, const bsls::TimeInterval& timeout, const ReadCallback& readCallback, int flags = 0) = 0; // Initiate a non-blocking operation to *atomically* read *up* *to* the // specified 'numBytes' from this channel into the specified 'buffer' // or interrupt after the specified absolute 'timeout' time is reached; // execute the specified 'readCallback' functor after this read // operation terminates. If the optionally specified 'flags' // incorporates 'btlsc::Flag::k_ASYNC_INTERRUPT', "asynchronous // events" are permitted to interrupt this operation; by default, such // events are ignored. Return 0 on successful initiation, and a // non-zero value otherwise (in which case 'readCallback' will not be // invoked). // // When invoked, 'readCallback' is passed an integer "status" and a // second integer "augStatus" (which is meaningful for this method only // when "status" is zero). A non-negative "status" indicates the // number of bytes read into 'buffer'. If "status" is positive, the // atomic OS-level ("raw") read operation completed; "status" equals // 'numBytes' upon success. In either case, "augStatus" has no // meaning. If "status" is zero, the atomic read operation did not // complete, in which case "augStatus" is positive if an "asynchronous // event" interrupted the operation, zero if the operation timed out, // and negative if the operation was canceled. If the transmission // was interrupted, the channel itself potentially remains valid; // hence, this (or another) operation may be retried (with arguments // suitably adjusted) with some reasonable hope of success. A negative // "status", however, indicates a permanent error (leaving the contents // of 'buffer' undefined); -1 implies that the connection was closed by // the peer (but the converse is not guaranteed). The behavior is // undefined unless 'buffer' has sufficient capacity to hold the // requested data and remains valid until the (non-null) 'readCallback' // completes, and '0 < numBytes'. Note that if the 'timeout' value has // already passed, the "read" operation will still be attempted, but // the attempt, once initiated, will not be permitted to block. virtual int readvRaw(const btls::Iovec *buffers, int numBuffers, const ReadCallback& readCallback, int flags = 0) = 0; // Initiate a non-blocking operation to *atomically* read from this // channel into the specified sequence of 'buffers' of the specified // sequence length 'numBuffers' *up* *to* the respective number of // bytes as defined by the 'length' method of each 'Iovec' structure; // execute the specified 'readCallback' functor after this read // operation terminates. If the optionally specified 'flags' // incorporates 'btlsc::Flag::k_ASYNC_INTERRUPT', "asynchronous // events" are permitted to interrupt this operation; by default, such // events are ignored. Return 0 on successful initiation, and a // non-zero value otherwise (in which case 'readCallback' will not be // invoked). // // When invoked, 'readCallback' is passed an integer "status" and a // second integer "augStatus" (which is meaningful for this method only // when "status" is zero). A non-negative "status" indicates the total // number of bytes read into 'buffers'. If "status" is positive, the // atomic ("raw") vector-read operation completed; "status" equals the // requested number of bytes (i.e., the sum of the lengths of the // 'numBuffers' 'buffers') upon success. In either case, "augStatus" // has no meaning. If "status" is zero, the atomic read operation did // not complete, in which case "augStatus" is positive if an // "asynchronous event" interrupted the operation, and negative if the // operation was canceled. A negative "status", however, indicates a // permanent error (leaving the contents of 'buffers' undefined); -1 // implies that the connection was closed by the peer (but the converse // is not guaranteed). The behavior is undefined unless 'buffers' has // sufficient capacity to hold the requested data and remains valid // until the (non-null) 'readCallback' completes, and '0 < numBytes'. virtual int timedReadvRaw(const btls::Iovec *buffers, int numBuffers, const bsls::TimeInterval& timeout, const ReadCallback& readCallback, int flags = 0) = 0; // Initiate a non-blocking operation to *atomically* read from this // channel into the specified sequence of 'buffers' of the specified // sequence length 'numBuffers' *up* *to* the respective number of // bytes as defined by the 'length' method of each 'Iovec' structure // or interrupt after the specified absolute 'timeout' time is reached; // execute the specified 'readCallback' functor after this read // operation terminates. If the optionally specified 'flags' // incorporates 'btlsc::Flag::k_ASYNC_INTERRUPT', "asynchronous // events" are permitted to interrupt this operation; by default, such // events are ignored. Return 0 on successful initiation, and a // non-zero value otherwise (in which case 'readCallback' will not be // invoked). // // When invoked, 'readCallback' is passed an integer "status" and a // second integer "augStatus" (which is meaningful for this method only // when "status" is zero). A non-negative "status" indicates the total // number of bytes read into 'buffers'. If "status" is positive, the // atomic ("raw") vector-read operation completed; "status" equals the // requested number of bytes (i.e., the sum of the lengths of the // 'numBuffers' 'buffers') upon success. In either case, "augStatus" // has no meaning. If "status" is zero, the atomic read operation did // not complete, in which case "augStatus" is positive if an // "asynchronous event" interrupted the operation, zero if the // operation timed out, and negative if the operation was canceled. A // negative "status", however, indicates a permanent error (leaving the // contents of 'buffers' undefined); -1 implies that the connection was // closed by the peer (but the converse is not guaranteed). The // behavior is undefined unless 'buffers' has sufficient capacity to // hold the requested data and remains valid until the (non-null) // 'readCallback' completes, and '0 < numBytes'. Note that if the // 'timeout' value has already passed, the "read" operation will still // be attempted, but the attempt, once initiated, will not be permitted // to block. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - virtual int bufferedRead(int numBytes, const BufferedReadCallback& bufferedReadCallback, int flags = 0) = 0; // Initiate a non-blocking operation to read the specified 'numBytes' // from this channel into a channel-supplied buffer; execute the // specified 'bufferedReadCallback' functor after this read operation // terminates. If the optionally specified 'flags' incorporates // 'btlsc::Flag::k_ASYNC_INTERRUPT', "asynchronous events" are // permitted to interrupt this operation; by default, such events are // ignored. Return 0 on successful initiation, and a non-zero value // otherwise (in which case 'bufferedReadCallback' will not be // invoked). // // When invoked, 'bufferedReadCallback' is passed the address of a // non-modifiable character "buffer", an integer "status", and a second // integer "augStatus" (which is meaningful only upon an incomplete // transmission). If "status" is equal to 'numBytes', the operation // was successful and "buffer" contains 'numBytes' of incoming data // (which will remain valid only until the callback completes). // Otherwise, if "status" is non-negative (incomplete read), it // indicates the number of (accessible) bytes in "buffer", in which // case "augStatus" will be positive if the operation was interrupted // due to an asynchronous event, and negative ("status" identically 0) // if this operation was canceled. If the transmission is partial, // the data is retained in the channel's buffer and the channel itself // potentially remains valid; hence, this (or another) operation may be // retried (with arguments suitably adjusted) with some reasonable hope // of success. A negative "status", however, indicates a permanent // error (leaving the contents of "buffer" undefined); -1 implies that // the connection was closed by the peer (but the converse is not // guaranteed). The behavior is undefined unless '0 < numBytes' and // 'bufferedReadCallback' is non-null. virtual int timedBufferedRead( int numBytes, const bsls::TimeInterval& timeout, const BufferedReadCallback& bufferedReadCallback, int flags = 0) = 0; // Initiate a non-blocking operation to read the specified 'numBytes' // from this channel into a channel-supplied buffer or interrupt after // the specified absolute 'timeout' time is reached; execute the // specified 'bufferedReadCallback' functor after this read operation // terminates. If the optionally specified 'flags' incorporates // 'btlsc::Flag::k_ASYNC_INTERRUPT', "asynchronous events" are // permitted to interrupt this operation; by default, such events are // ignored. Return 0 on successful initiation, and a non-zero value // otherwise (in which case 'bufferedReadCallback' will not be // invoked). // // When invoked, 'bufferedReadCallback' is passed the address of a // non-modifiable character "buffer", an integer "status", and a second // integer "augStatus" (which is meaningful only upon an incomplete // transmission). If "status" is equal to 'numBytes', the operation // was successful and "buffer" contains 'numBytes' of newly read data // (which will remain valid only until the callback completes). // Otherwise, if "status" is non-negative (incomplete read), it // indicates the number of (accessible) bytes in "buffer", in which // case "augStatus" will be 0 if the interrupt was caused by the // caller-requested timeout event, positive if the operation was // interrupted due to an asynchronous event, and negative ("status" // identically 0) if this operation was canceled. If the transmission // is partial, the data is retained in the channel's buffer and the // channel itself potentially remains valid; hence, this (or another) // operation may be retried (with arguments suitably adjusted) with // some reasonable hope of success. A negative "status", however, // indicates a permanent error (leaving the contents of "buffer" // undefined); -1 implies that the connection was closed by the peer // (but the converse is not guaranteed). The behavior is undefined // unless '0 < numBytes' and 'bufferedReadCallback' is non-null. Note // that if the 'timeout' value has already passed, the "read" operation // will still be attempted, but the attempt, once initiated, will not // be permitted to block. virtual int bufferedReadRaw( int numBytes, const BufferedReadCallback& bufferedReadCallback, int flags = 0) = 0; // Initiate a non-blocking operation to *atomically* read *up* *to* the // specified 'numBytes' from this channel into a channel-supplied // buffer; execute the specified 'bufferedReadCallback' functor after // this read operation terminates. If the optionally specified 'flags' // incorporates 'btlsc::Flag::k_ASYNC_INTERRUPT', "asynchronous // events" are permitted to interrupt this operation; by default, such // events are ignored. Return 0 on successful initiation, and a // non-zero value otherwise (in which case 'bufferedReadCallback' will // not be invoked). // // When invoked, 'bufferedReadCallback' is passed the address of a // non-modifiable character "buffer", an integer "status", and a second // integer "augStatus" (which is meaningful for this method only when // "status" is zero). A non-negative "status" indicates the total // number of bytes read into "buffer". If "status" is positive, the // atomic OS-level ("raw") read operation completed; "status" equals // 'numBytes' upon success. In either case, "augStatus" has no // meaning. If "status" is zero, the atomic read operation did not // complete, in which case "augStatus" is positive if an "asynchronous // event" interrupted the operation, and negative if the operation was // canceled. If the transmission is incomplete (i.e., "status" less // than 'numBytes') the data is retained in the channel's buffer and // the channel itself potentially remains valid; hence, this (or // another) operation may be retried (with arguments suitably adjusted) // with some reasonable hope of success. A negative "status", however, // indicates a permanent error (leaving the contents of "buffer" // undefined); -1 implies that the connection was closed by the peer // (but the converse is not guaranteed). The behavior is undefined // unless '0 < numBytes' and 'bufferedReadCallback' is non-null. virtual int timedBufferedReadRaw(int numBytes, const bsls::TimeInterval& timeout, const BufferedReadCallback& bufferedReadCallback, int flags = 0) = 0; // Initiate a non-blocking operation to *atomically* read *up* *to* the // specified 'numBytes' from this channel into a channel-supplied // buffer or interrupt after the specified absolute 'timeout' time is // reached; execute the specified 'bufferedReadCallback' functor after // this read operation terminates. If the optionally specified 'flags' // incorporates 'btlsc::Flag::k_ASYNC_INTERRUPT', "asynchronous // events" are permitted to interrupt this operation; by default, such // events are ignored. Return 0 on successful initiation, and a // non-zero value otherwise (in which case 'bufferedReadCallback' will // not be invoked). // // When invoked, 'bufferedReadCallback' is passed the address of a // non-modifiable character "buffer", an integer "status", and a second // integer "augStatus" (which is meaningful for this method only when // "status" is zero). A non-negative "status" indicates the total // number of bytes read into "buffer". If "status" is positive, the // atomic OS-level ("raw") read operation completed; "status" equals // 'numBytes' upon success. In either case, "augStatus" has no // meaning. If "status" is zero, the atomic read operation did not // complete, in which case "augStatus" is positive if an "asynchronous // event" interrupted the operation, zero if the operation timed out, // and negative if the operation was canceled. If the transmission is // incomplete (i.e., "status" less than 'numBytes') the data is // retained in the channel's buffer and the channel itself potentially // remains valid; hence, this (or another) operation may be retried // (with arguments suitably adjusted) with some reasonable hope of // success. A negative "status", however, indicates a permanent error // (leaving the contents of "buffer" undefined); -1 implies that the // connection was closed by the peer (but the converse is not // guaranteed). The behavior is undefined unless '0 < numBytes' and // 'bufferedReadCallback' is non-null. Note that if the 'timeout' // value has already passed, the "read" operation will still be // attempted, but the attempt, once initiated, will not be permitted to // block. // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = virtual int write(const char *buffer, int numBytes, const WriteCallback& writeCallback, int flags = 0) = 0; // Initiate a non-blocking operation to write the specified 'numBytes' // from the specified 'buffer' to this channel; execute the specified // 'writeCallback' functor after this write operation terminates. If // the optionally specified 'flags' incorporates // 'btlsc::Flag::k_ASYNC_INTERRUPT', "asynchronous events" are // permitted to interrupt this operation; by default, such events are // ignored. Return 0 on successful initiation, and a non-zero value // otherwise (in which case 'writeCallback' will not be invoked). // // When invoked, 'writeCallback' is passed an integer "status" and a // second integer "augStatus" (which is meaningful only upon an // incomplete transmission). If "status" is equal to 'numBytes', the // operation was successful and all 'numBytes' of data were transmitted // to the channel. Otherwise, if "status" is non-negative (incomplete // write), it indicates the number of bytes written from 'buffer', in // which case "augStatus" will be positive if the operation was // interrupted due to an asynchronous event, and negative ("status" // identically 0) if this operation was canceled. If the transmission // is incomplete, the channel itself potentially remains valid; hence, // this (or another) operation may be retried (with arguments suitably // adjusted) with some reasonable hope of success. A negative // "status", however, indicates a permanent error; -1 implies that the // connection was closed by the peer (but the converse is not // guaranteed). The behavior is undefined unless 'buffer' remains // valid until the (non-null) 'writeCallback' completes and // '0 < numBytes'. virtual int timedWrite(const char *buffer, int numBytes, const bsls::TimeInterval& timeout, const WriteCallback& writeCallback, int flags = 0) = 0; // Initiate a non-blocking operation to write the specified 'numBytes' // from the specified 'buffer' to this channel or interrupt after the // specified absolute 'timeout' time is reached; execute the specified // 'writeCallback' functor after this write operation terminates. If // the optionally specified 'flags' incorporates // 'btlsc::Flag::k_ASYNC_INTERRUPT', "asynchronous events" are // permitted to interrupt this operation; by default, such events are // ignored. Return 0 on successful initiation, and a non-zero value // otherwise (in which case 'writeCallback' will not be invoked). // // When invoked, 'writeCallback' is passed an integer "status" and a // second integer "augStatus" (which is meaningful only upon an // incomplete transmission). If "status" is equal to 'numBytes', the // operation was successful and all 'numBytes' of data were transmitted // to the channel. Otherwise, if "status" is non-negative (incomplete // write), it indicates the number of bytes written from 'buffer', in // which case "augStatus" will be 0 if the interrupt was caused by the // caller-requested timeout event, positive if the operation was // interrupted due to an asynchronous event, and negative ("status" // identically 0) if this operation was canceled. If the transmission // is incomplete, the channel itself potentially remains valid; hence, // this (or another) operation may be retried (with arguments suitably // adjusted) with some reasonable hope of success. A negative // "status", however, indicates a permanent error; -1 implies that the // connection was closed by the peer (but the converse is not // guaranteed). The behavior is undefined unless 'buffer' remains // valid until the (non-null) 'writeCallback' completes and // '0 < numBytes'. Note that if the 'timeout' value has already // passed, the "write" operation will still be attempted, but the // attempt, once initiated, will not be permitted to block. virtual int writeRaw(const char *buffer, int numBytes, const WriteCallback& writeCallback, int flags = 0) = 0; // Initiate a non-blocking operation to *atomically* write *up* *to* // the specified 'numBytes' from the specified 'buffer' to this // channel; execute the specified 'writeCallback' functor after this // write operation terminates. If the optionally specified 'flags' // incorporates 'btlsc::Flag::k_ASYNC_INTERRUPT', "asynchronous // events" are permitted to interrupt this operation; by default, such // events are ignored. Return 0 on successful initiation, and a // non-zero value otherwise (in which case 'writeCallback' will not be // invoked). // // When invoked, 'writeCallback' is passed an integer "status" and a // second integer "augStatus" (which is meaningful for this method only // when "status" is zero). A non-negative "status" indicates the // number of bytes written from 'buffer'. If "status" is positive, the // atomic OS-level ("raw") write operation completed; "status" equals // 'numBytes' upon success. In either case, "augStatus" has no // meaning. If "status" is zero, the atomic write operation did not // complete, in which case "augStatus" is positive if an "asynchronous // event" interrupted the operation, and negative if the operation was // canceled. If the transmission was interrupted, the channel itself // potentially remains valid; hence, this (or another) operation may be // retried (with arguments suitably adjusted) with some reasonable hope // of success. A negative "status", however, indicates a permanent // error; -1 implies that the connection was closed by the peer (but // the converse is not guaranteed). The behavior is undefined unless // 'buffer' remains valid until the (non-null) 'writeCallback' // completes and '0 < numBytes'. virtual int timedWriteRaw(const char *buffer, int numBytes, const bsls::TimeInterval& timeout, const WriteCallback& writeCallback, int flags = 0) = 0; // Initiate a non-blocking operation to *atomically* write *up* *to* // the specified 'numBytes' from the specified 'buffer' to this channel // or interrupt after the specified absolute 'timeout' time is reached; // execute the specified 'writeCallback' functor after this write // operation terminates. If the optionally specified 'flags' // incorporates 'btlsc::Flag::k_ASYNC_INTERRUPT', "asynchronous // events" are permitted to interrupt this operation; by default, such // events are ignored. Return 0 on successful initiation, and a // non-zero value otherwise (in which case 'writeCallback' will not be // invoked). // // When invoked, 'writeCallback' is passed an integer "status" and a // second integer "augStatus" (which is meaningful for this method only // when "status" is zero). A non-negative "status" indicates the // number of bytes written from 'buffer'. If "status" is positive, the // atomic OS-level ("raw") write operation completed; "status" equals // 'numBytes' upon success. In either case, "augStatus" has no // meaning. If "status" is zero, the atomic write operation did not // complete, in which case "augStatus" is positive if an "asynchronous // event" interrupted the operation, zero if the operation timed out, // and negative if the operation was canceled. If the transmission // was interrupted, the channel itself potentially remains valid; // hence, this (or another) operation may be retried (with arguments // suitably adjusted) with some reasonable hope of success. A negative // "status", however, indicates a permanent error; -1 implies that the // connection was closed by the peer (but the converse is not // guaranteed). The behavior is undefined unless 'buffer' remains // valid until the (non-null) 'writeCallback' completes and // '0 < numBytes'. Note that if the 'timeout' value has already // passed, the "write" operation will still be attempted, but the // attempt, once initiated, will not be permitted to block. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - virtual int writevRaw(const btls::Iovec *buffers, int numBuffers, const WriteCallback& writeCallback, int flags = 0) = 0; virtual int writevRaw(const btls::Ovec *buffers, int numBuffers, const WriteCallback& writeCallback, int flags = 0) = 0; // Initiate a non-blocking operation to *atomically* write *up* *to* // the total number of bytes indicated by the specified sequence of // 'buffers' of the specified sequence length 'numBuffers' the // respective number of bytes as defined by the 'length' method of // each 'Ovec' (or 'Iovec') structure; execute the specified // 'writeCallback' functor after this write operation terminates. If // the optionally specified 'flags' incorporates // 'btlsc::Flag::k_ASYNC_INTERRUPT', "asynchronous events" are // permitted to interrupt this operation; by default, such events are // ignored. Return 0 on successful initiation, and a non-zero value // otherwise (in which case 'writeCallback' will not be invoked). // // When invoked, 'writeCallback' is passed an integer "status" and a // second integer "augStatus" (which is meaningful for this method only // when "status" is zero). A non-negative "status" indicates the total // number of bytes written from 'buffers'. If "status" is positive, // the atomic ("raw") vector-write operation completed; "status" equals // the requested number of bytes (i.e., the sum of the lengths of the // 'numBuffers' 'buffers') upon success. In either case, "augStatus" // has no meaning. If "status" is zero, the atomic write operation did // not complete, in which case "augStatus" is positive if an // "asynchronous event" interrupted the operation, and negative if the // operation was canceled. If the transmission is incomplete, the // channel itself potentially remains valid; hence, this (or another) // operation may be retried (with arguments suitably adjusted) with // some reasonable hope of success. A negative "status", however, // indicates a permanent error; -1 implies that the connection was // closed by the peer (but the converse is not guaranteed). The // behavior is undefined unless the total number of bytes to be written // is *positive* and 'buffers' (and the data to which it refers) // remains valid until the (non-null) 'writeCallback' completes. virtual int timedWritevRaw(const btls::Iovec *buffers, int numBuffers, const bsls::TimeInterval& timeout, const WriteCallback& writeCallback, int flags = 0) = 0; virtual int timedWritevRaw(const btls::Ovec *buffers, int numBuffers, const bsls::TimeInterval& timeout, const WriteCallback& writeCallback, int flags = 0) = 0; // Initiate a non-blocking operation to *atomically* write *up* *to* // the total number of bytes indicated by the specified sequence of // 'buffers' of the specified sequence length 'numBuffers' the // respective number of bytes as defined by the 'length' method of // each 'Ovec' (or 'Iovec') structure or interrupt after the specified // absolute 'timeout' time is reached; execute the specified // 'writeCallback' functor after this write operation terminates. If // the optionally specified 'flags' incorporates // 'btlsc::Flag::k_ASYNC_INTERRUPT', "asynchronous events" are // permitted to interrupt this operation; by default, such events are // ignored. Return 0 on successful initiation, and a non-zero value // otherwise (in which case 'writeCallback' will not be invoked). // // When invoked, 'writeCallback' is passed an integer "status" and a // second integer "augStatus" (which is meaningful for this method only // when "status" is zero). A non-negative "status" indicates the total // number of bytes written from 'buffers'. If "status" is positive, // the atomic ("raw") vector-write operation completed; "status" equals // the requested number of bytes (i.e., the sum of the lengths of the // 'numBuffers' 'buffers') upon success. In either case, "augStatus" // has no meaning. If "status" is zero, the atomic write operation did // not complete, in which case "augStatus" is positive if an // "asynchronous event" interrupted the operation, zero if the // operation timed out, and negative if the operation was canceled. If // the transmission is incomplete, the channel itself potentially // remains valid; hence, this (or another) operation may be retried // (with arguments suitably adjusted) with some reasonable hope of // success. A negative "status", however, indicates a permanent error; // -1 implies that the connection was closed by the peer (but the // converse is not guaranteed). The behavior is undefined unless the // total number of bytes to be written is *positive* and 'buffers' (and // the data to which it refers) remains valid until the (non-null) // 'writeCallback' completes. Note that if the 'timeout' value has // already passed, the "write" operation will still be attempted, but // the attempt, once initiated, will not be permitted to block. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - virtual int bufferedWrite(const char *buffer, int numBytes, const WriteCallback& writeCallback, int flags = 0) = 0; // Initiate a non-blocking operation to write the specified 'numBytes' // from the specified 'buffer' to this channel; execute the specified // 'writeCallback' functor after this write operation terminates. If // the optionally specified 'flags' incorporates // 'btlsc::Flag::k_ASYNC_INTERRUPT', "asynchronous events" are // permitted to interrupt this operation; by default, such events are // ignored. Return 0 on successful initiation, and a non-zero value // otherwise (in which case 'writeCallback' will not be invoked). Note // that the contents of 'buffer' need not be preserved after this // method returns (except for the purpose of initiating a retry in the // event that this operation results in a partial write). // // When invoked, 'writeCallback' is passed an integer "status" and a // second integer "augStatus" (which is meaningful only upon an // incomplete transmission). If "status" is equal to 'numBytes', the // operation was successful and all 'numBytes' of data were transmitted // to the channel. Otherwise, if "status" is non-negative (incomplete // write), it indicates the number of bytes written from 'buffer', in // which case "augStatus" will be positive if the operation was // interrupted due to an asynchronous event and negative (with "status" // identically 0) if this operation was canceled. If the transmission // is incomplete, the remaining buffered data is discarded, but the // channel itself potentially remains valid; hence, this (or another) // operation may be retried (with arguments suitably adjusted) with // some reasonable hope of success. A negative "status", however, // indicates a permanent error; -1 implies that the connection was // closed by the peer (but the converse is not guaranteed). The // behavior is undefined unless '0 < numBytes'. virtual int timedBufferedWrite(const char *buffer, int numBytes, const bsls::TimeInterval& timeout, const WriteCallback& writeCallback, int flags = 0) = 0; // Initiate a non-blocking operation to write the specified 'numBytes' // from the specified 'buffer' to this channel or interrupt after the // specified absolute 'timeout' time is reached; execute the specified // 'writeCallback' functor after this write operation terminates. If // the optionally specified 'flags' incorporates // 'btlsc::Flag::k_ASYNC_INTERRUPT', "asynchronous events" are // permitted to interrupt this operation; by default, such events are // ignored. Return 0 on successful initiation, and a non-zero value // otherwise (in which case 'writeCallback' will not be invoked). Note // that the contents of 'buffer' need not be preserved after this // method returns (except for the purpose of initiating a retry in the // event that this operation results in a partial write). // // When invoked, 'writeCallback' is passed an integer "status" and a // second integer "augStatus" (which is meaningful only upon an // incomplete transmission). If "status" is equal to 'numBytes', the // operation was successful and all 'numBytes' of data were transmitted // to the channel. Otherwise, if "status" is non-negative (incomplete // write), it indicates the number of bytes written from 'buffer', in // which case "augStatus" will be 0 if the interrupt was caused by the // caller-requested timeout event, positive if the operation was // interrupted due to an asynchronous event, and negative ("status" // identically 0) if this operation was canceled. If the transmission // is incomplete, the remaining buffered data is discarded, but the // channel itself potentially remains valid; hence, this (or another) // operation may be retried (with arguments suitably adjusted) with // some reasonable hope of success. A negative "status", however, // indicates a permanent error; -1 implies that the connection was // closed by the peer (but the converse is not guaranteed). The // behavior is undefined unless '0 < numBytes'. Note that if the // 'timeout' value has already passed, the "write" operation will still // be attempted, but the attempt, once initiated, will not be permitted // to block. virtual int bufferedWritev(const btls::Iovec *buffers, int numBuffers, const WriteCallback& writeCallback, int flags = 0) = 0; virtual int bufferedWritev(const btls::Ovec *buffers, int numBuffers, const WriteCallback& writeCallback, int flags = 0) = 0; // Initiate a non-blocking operation to write to this channel from the // specified sequence of 'buffers' of the specified sequence length // 'numBuffers' the respective number of bytes as defined by the // 'length' method of each 'Ovec' (or 'Iovec') structure; execute the // specified 'writeCallback' functor after this write operation // terminates. If the optionally specified 'flags' incorporates // 'btlsc::Flag::k_ASYNC_INTERRUPT', "asynchronous events" are // permitted to interrupt this operation; by default, such events are // ignored. Return 0 on successful initiation, and a non-zero value // otherwise (in which case 'writeCallback' will not be invoked). // // When invoked, 'writeCallback' is passed an integer "status" and a // second integer "augStatus" (which is meaningful only upon an // incomplete transmission). If "status" is equal to the total number // bytes to be written (i.e., the sum of calls to 'length' on the // 'numBuffers' 'buffers'), all indicated data was transmitted to the // channel. Otherwise, if "status" is non-negative (incomplete write), // it indicates the number of bytes written in sequence from the // indicated buffers, in which case "augStatus" will be positive if the // operation was interrupted due to an asynchronous event, and negative // ("status" identically 0) if this operation was canceled. If the // transmission is incomplete, the remaining buffered data is // discarded, but the channel itself potentially remains valid; hence, // this (or another) operation may be retried (with arguments suitably // adjusted) with some reasonable hope of success. A negative // "status", however, indicates a permanent error; -1 implies that the // connection was closed by the peer (but the converse is not // guaranteed). The behavior is undefined unless the total number of // bytes to be written is *positive*. Note that neither 'buffers' nor // the data to which it refers need be preserved after this method // returns (except for the purpose of initiating a retry in the event // that this operation results in a partial write). virtual int timedBufferedWritev(const btls::Iovec *buffers, int numBuffers, const bsls::TimeInterval& timeout, const WriteCallback& writeCallback, int flags = 0) = 0; virtual int timedBufferedWritev(const btls::Ovec *buffers, int numBuffers, const bsls::TimeInterval& timeout, const WriteCallback& writeCallback, int flags = 0) = 0; // Initiate a non-blocking operation to write to this channel from the // specified sequence of 'buffers' of the specified sequence length // 'numBuffers' the respective number of bytes as defined by the // 'length' method of each 'Ovec' (or 'Iovec') structure or interrupt // after the specified absolute 'timeout' time is reached; execute the // specified 'writeCallback' functor after this write operation // terminates. If the optionally specified 'flags' incorporates // 'btlsc::Flag::k_ASYNC_INTERRUPT', "asynchronous events" are // permitted to interrupt this operation; by default, such events are // ignored. Return 0 on successful initiation, and a non-zero value // otherwise (in which case 'writeCallback' will not be invoked). // // When invoked, 'writeCallback' is passed an integer "status" and a // second integer "augStatus" (which is meaningful only upon an // incomplete transmission). If "status" is equal to the total number // bytes to be written (i.e., the sum of calls to 'length' on the // 'numBuffers' 'buffers') all indicated data was transmitted to the // channel. Otherwise, if "status" is non-negative (incomplete write), // it indicates the number of bytes written in sequence from the // indicated buffers, in which case "augStatus" will be 0 if the // interrupt was caused by the caller-requested timeout event, // positive if the operation was interrupted due to an asynchronous // event, and negative ("status" identically 0) if this operation was // canceled. If the transmission is incomplete, the remaining // buffered data is discarded, but the channel itself potentially // remains valid; hence, this (or another) operation may be retried // (with arguments suitably adjusted) with some reasonable hope of // success. A negative "status", however, indicates a permanent error; // -1 implies that the connection was closed by the peer (but the // converse is not guaranteed). The behavior is undefined unless the // total number of bytes to be written is *positive*. Note that if the // 'timeout' value has already passed, the "write" operation will still // be attempted, but the attempt, once initiated, will not be permitted // to block. Also note that neither 'buffers' nor the data to which it // refers need be preserved after this method returns (except for the // purpose of initiating a retry in the event that this operation // results in a partial write). // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = virtual void cancelAll() = 0; // Remove all enqueued operations from both the read queue and the // write queue of this channel, and, in turn, invoke each callback with // a 0 "status" and a negative "augStatus". Note that the validity of // this channel is not altered by this operation. virtual void cancelRead() = 0; // Remove all enqueued read operations from this channel, and, in turn, // invoke each read callback with a 0 "status" and a negative // "augStatus". Note that the validity of this channel is not altered // by this operation. virtual void cancelWrite() = 0; // Remove all enqueued write operations from this channel, and, in // turn, invoke each write callback with a 0 "status" and a negative // "augStatus". Note that the validity of this channel is not altered // by this operation. virtual void invalidate() = 0; // Make this channel invalid; no new operations can be initiated // successfully. Pending operations are not affected. virtual void invalidateRead() = 0; // Invalidate the read portion of this channel; no new read operations // can be initiated successfully. Pending operations are not affected. virtual void invalidateWrite() = 0; // Invalidate the write portion of this channel; no new write // operations can be initiated successfully. Pending operations are // not affected. // ACCESSORS virtual int isInvalidRead() const = 0; // Return 1 if the read portion of this (full-duplex) channel is // invalid (e.g., due to a read error or an explicit call to // 'invalidateRead'), and 0 otherwise. Once the read portion of a // channel is invalid, no new read operations can be initiated // successfully. Note that a 0 return value cannot be relied upon to // indicate that the read portion of this channel *is* valid. virtual int isInvalidWrite() const = 0; // Return 1 if the write portion of this (full-duplex) channel is // invalid (e.g., due to a write error or an explicit call to // 'invalidateWrite'), and 0 otherwise. Once the write portion of a // channel is invalid, no new write operations can be initiated // successfully. Note that a 0 return value cannot be relied upon to // indicate that the write portion of this channel *is* valid. virtual int numPendingReadOperations() const = 0; // Return the total number of pending read operations for this channel. virtual int numPendingWriteOperations() const = 0; // Return the total number of pending write operations for this // channel. }; } // close package namespace } // close enterprise namespace #endif // ---------------------------------------------------------------------------- // Copyright 2015 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
C++
CL
1866625dbb3e2e3f4b7231a4b2f89852b0dd9c29f3c4fff35a6c32ab41dcfa93
#pragma once #include "info.h" #include "../common.h" #include <CL/cl.h> namespace cl { namespace sycl { // Forward declaration template <typename EnumClass, EnumClass Value> struct param_traits; // Not in the specification, but is a nice addition template <typename EnumClass, EnumClass Value> using param_traits_t = typename param_traits<EnumClass, Value>::type; namespace detail { template <typename EnumClass, EnumClass Value, typename ReturnType, typename CLType> struct param_traits_helper { using type = ReturnType; using cl_flag_type = CLType; }; template <typename ReturnType> struct traits_buffer_default { static const ::size_t size = 1; }; template <typename Contained> struct traits_buffer_default<vector_class<Contained>> { static const ::size_t size = 1024; }; template <> struct traits_buffer_default<string_class> { static const ::size_t size = 8192; }; template <typename Contained_, ::size_t BufferSize, class Container_ = vector_class<Contained_>> struct traits_helper { using Container = Container_; using Contained = Contained_; static const int BUFFER_SIZE = BufferSize; static const ::size_t type_size = sizeof(Contained); }; template <typename Contained_, ::size_t BufferSize = traits_buffer_default<vector_class<Contained_>>::size> struct traits : traits_helper<Contained_, BufferSize> {}; template <::size_t BufferSize> struct traits<string_class, BufferSize> : traits_helper<char, BufferSize, string_class>{}; template <typename cl_input_t> using opencl_info_f = ::cl_int(CL_API_CALL*)(cl_input_t, cl_uint, ::size_t, void*, ::size_t*); template <typename cl_input_t, opencl_info_f<cl_input_t> F> struct info_function_helper { template <class... Args> static ::cl_int get(Args... args) { return F(args...); } }; template <typename EnumClass> struct info_function; template <> struct info_function<info::detail::buffer> : info_function_helper<cl_mem, clGetMemObjectInfo>{}; template <> struct info_function<info::context> : info_function_helper<cl_context, clGetContextInfo>{}; template <> struct info_function<info::device> : info_function_helper<cl_device_id, clGetDeviceInfo>{}; template <> struct info_function<info::event> : info_function_helper<cl_event, clGetEventInfo>{}; template <> struct info_function<info::event_profiling> : info_function_helper<cl_event, clGetEventProfilingInfo>{}; template <> struct info_function<info::kernel> : info_function_helper<cl_kernel, clGetKernelInfo>{}; template <> struct info_function<info::platform> : info_function_helper<cl_platform_id, clGetPlatformInfo>{}; template <> struct info_function<info::program> : info_function_helper<cl_program, clGetProgramInfo>{}; template <> struct info_function<info::queue> : info_function_helper<cl_command_queue, clGetCommandQueueInfo>{}; template <bool IsSingleValue> struct trait_return; template <> struct trait_return<false> { template <class Contained> static Contained* get(Contained* value) { return value; } }; template <> struct trait_return<true> { template <class Contained> static Contained get(Contained* value) { return value[0]; } }; } // namespace detail #define SYCL_ADD_TRAIT(EnumClass, Value, ReturnType, CLType) \ template <> \ struct param_traits<EnumClass, Value> \ : detail::param_traits_helper< \ EnumClass, Value, ReturnType, CLType \ > {}; // 3.3.3.2 Context information descriptors // https://www.khronos.org/registry/cl/sdk/1.2/docs/man/xhtml/clGetContextInfo.html #define SYCL_ADD_CONTEXT_TRAIT(Value, ReturnType) \ SYCL_ADD_TRAIT(info::context, Value, ReturnType, cl_context_info) SYCL_ADD_CONTEXT_TRAIT(info::context::reference_count, cl_uint) SYCL_ADD_CONTEXT_TRAIT(info::context::num_devices, cl_uint) SYCL_ADD_CONTEXT_TRAIT(info::context::devices, vector_class<cl_device_id>) SYCL_ADD_CONTEXT_TRAIT(info::context::gl_interop, info::gl_context_interop) #undef SYCL_ADD_CONTEXT_TRAIT // 3.3.2.1 Platform information descriptors // https://www.khronos.org/registry/cl/sdk/1.2/docs/man/xhtml/clGetPlatformInfo.html #define SYCL_ADD_PLATFORM_TRAIT(Value) \ SYCL_ADD_TRAIT(info::platform, Value, string_class, cl_platform_info) SYCL_ADD_PLATFORM_TRAIT(info::platform::profile) SYCL_ADD_PLATFORM_TRAIT(info::platform::version) SYCL_ADD_PLATFORM_TRAIT(info::platform::name) SYCL_ADD_PLATFORM_TRAIT(info::platform::vendor) SYCL_ADD_PLATFORM_TRAIT(info::platform::extensions) #undef SYCL_ADD_PLATFORM_TRAIT // 3.3.4.2 Device information descriptors // https://www.khronos.org/registry/cl/sdk/1.2/docs/man/xhtml/clGetDeviceInfo.html #define SYCL_ADD_DEVICE_TRAIT(Value, ReturnType) \ SYCL_ADD_TRAIT(info::device, Value, ReturnType, cl_device_info) // Forward declaration template <int dimensions> struct id; SYCL_ADD_DEVICE_TRAIT(info::device::device_type, info::device_type) SYCL_ADD_DEVICE_TRAIT(info::device::vendor_id, cl_uint) SYCL_ADD_DEVICE_TRAIT(info::device::max_compute_units, cl_uint) SYCL_ADD_DEVICE_TRAIT(info::device::max_work_item_dimensions, cl_uint) SYCL_ADD_DEVICE_TRAIT(info::device::max_work_item_sizes, id<3>) SYCL_ADD_DEVICE_TRAIT(info::device::max_work_group_size, ::size_t) SYCL_ADD_DEVICE_TRAIT(info::device::preferred_vector_width_char, cl_uint) SYCL_ADD_DEVICE_TRAIT(info::device::preferred_vector_width_short, cl_uint) SYCL_ADD_DEVICE_TRAIT(info::device::preferred_vector_width_int, cl_uint) SYCL_ADD_DEVICE_TRAIT(info::device::preferred_vector_width_long_long, cl_uint) SYCL_ADD_DEVICE_TRAIT(info::device::preferred_vector_width_float, cl_uint) SYCL_ADD_DEVICE_TRAIT(info::device::preferred_vector_width_double, cl_uint) SYCL_ADD_DEVICE_TRAIT(info::device::preferred_vector_width_half, cl_uint) SYCL_ADD_DEVICE_TRAIT(info::device::native_vector_width_char, cl_uint) SYCL_ADD_DEVICE_TRAIT(info::device::native_vector_width_short, cl_uint) SYCL_ADD_DEVICE_TRAIT(info::device::native_vector_width_int, cl_uint) SYCL_ADD_DEVICE_TRAIT(info::device::native_vector_width_long_long, cl_uint) SYCL_ADD_DEVICE_TRAIT(info::device::native_vector_width_float, cl_uint) SYCL_ADD_DEVICE_TRAIT(info::device::native_vector_width_double, cl_uint) SYCL_ADD_DEVICE_TRAIT(info::device::native_vector_width_half, cl_uint) SYCL_ADD_DEVICE_TRAIT(info::device::max_clock_frequency, cl_uint) SYCL_ADD_DEVICE_TRAIT(info::device::address_bits, cl_uint) SYCL_ADD_DEVICE_TRAIT(info::device::max_mem_alloc_size, cl_ulong) SYCL_ADD_DEVICE_TRAIT(info::device::image_support, cl_bool) SYCL_ADD_DEVICE_TRAIT(info::device::max_read_image_args, cl_uint) SYCL_ADD_DEVICE_TRAIT(info::device::max_write_image_args, cl_uint) SYCL_ADD_DEVICE_TRAIT(info::device::image2d_max_height, ::size_t) SYCL_ADD_DEVICE_TRAIT(info::device::image2d_max_width, ::size_t) SYCL_ADD_DEVICE_TRAIT(info::device::image3d_max_height, ::size_t) SYCL_ADD_DEVICE_TRAIT(info::device::image3d_max_width, ::size_t) SYCL_ADD_DEVICE_TRAIT(info::device::image3d_max_depth, ::size_t) SYCL_ADD_DEVICE_TRAIT(info::device::image_max_buffer_size, ::size_t) SYCL_ADD_DEVICE_TRAIT(info::device::image_max_array_size, ::size_t) SYCL_ADD_DEVICE_TRAIT(info::device::max_samplers, cl_uint) SYCL_ADD_DEVICE_TRAIT(info::device::max_parameter_size, ::size_t) SYCL_ADD_DEVICE_TRAIT(info::device::mem_base_addr_align, cl_uint) SYCL_ADD_DEVICE_TRAIT(info::device::single_fp_config, info::device_fp_config) SYCL_ADD_DEVICE_TRAIT(info::device::double_fp_config, info::device_fp_config) SYCL_ADD_DEVICE_TRAIT(info::device::global_mem_cache_type, info::global_mem_cache_type) SYCL_ADD_DEVICE_TRAIT(info::device::global_mem_cache_line_size, cl_uint) SYCL_ADD_DEVICE_TRAIT(info::device::global_mem_cache_size, cl_ulong) SYCL_ADD_DEVICE_TRAIT(info::device::global_mem_size, cl_ulong) SYCL_ADD_DEVICE_TRAIT(info::device::max_constant_buffer_size, cl_ulong) SYCL_ADD_DEVICE_TRAIT(info::device::max_constant_args, cl_uint) SYCL_ADD_DEVICE_TRAIT(info::device::local_mem_type, info::local_mem_type) SYCL_ADD_DEVICE_TRAIT(info::device::local_mem_size, cl_ulong) SYCL_ADD_DEVICE_TRAIT(info::device::error_correction_support, cl_bool) SYCL_ADD_DEVICE_TRAIT(info::device::host_unified_memory, cl_bool) SYCL_ADD_DEVICE_TRAIT(info::device::profiling_timer_resolution, ::size_t) SYCL_ADD_DEVICE_TRAIT(info::device::endian_little, cl_bool) SYCL_ADD_DEVICE_TRAIT(info::device::is_available, cl_bool) SYCL_ADD_DEVICE_TRAIT(info::device::is_compiler_available, cl_bool) SYCL_ADD_DEVICE_TRAIT(info::device::is_linker_available, cl_bool) SYCL_ADD_DEVICE_TRAIT(info::device::execution_capabilities, info::device_exec_capabilities) SYCL_ADD_DEVICE_TRAIT(info::device::queue_properties, info::device_queue_properties) SYCL_ADD_DEVICE_TRAIT(info::device::built_in_kernels, string_class) SYCL_ADD_DEVICE_TRAIT(info::device::platform, cl_platform_id) SYCL_ADD_DEVICE_TRAIT(info::device::name, string_class) SYCL_ADD_DEVICE_TRAIT(info::device::vendor, string_class) SYCL_ADD_DEVICE_TRAIT(info::device::driver_version, string_class) SYCL_ADD_DEVICE_TRAIT(info::device::profile, string_class) SYCL_ADD_DEVICE_TRAIT(info::device::device_version, string_class) SYCL_ADD_DEVICE_TRAIT(info::device::opencl_version, string_class) SYCL_ADD_DEVICE_TRAIT(info::device::extensions, string_class) SYCL_ADD_DEVICE_TRAIT(info::device::printf_buffer_size, ::size_t) SYCL_ADD_DEVICE_TRAIT(info::device::preferred_interop_user_sync, cl_bool) SYCL_ADD_DEVICE_TRAIT(info::device::parent_device, cl_device_id) SYCL_ADD_DEVICE_TRAIT(info::device::partition_max_sub_devices, cl_uint) SYCL_ADD_DEVICE_TRAIT(info::device::partition_properties, vector_class<info::device_partition_property>) SYCL_ADD_DEVICE_TRAIT(info::device::partition_affinity_domain, info::device_affinity_domain) SYCL_ADD_DEVICE_TRAIT(info::device::partition_type, vector_class<info::device_partition_type>) // TODO SYCL_ADD_DEVICE_TRAIT(info::device::reference_count, cl_uint) #undef SYCL_ADD_DEVICE_TRAIT // 3.3.5.2 Queue information descriptors // https://www.khronos.org/registry/cl/sdk/1.2/docs/man/xhtml/clGetCommandQueueInfo.html #define SYCL_ADD_QUEUE_TRAIT(Value, ReturnType) \ SYCL_ADD_TRAIT(info::queue, Value, ReturnType, cl_command_queue_info) SYCL_ADD_QUEUE_TRAIT(info::queue::context, cl_context) SYCL_ADD_QUEUE_TRAIT(info::queue::device, cl_device_id) SYCL_ADD_QUEUE_TRAIT(info::queue::reference_count, cl_uint) SYCL_ADD_QUEUE_TRAIT(info::queue::properties, info::queue_profiling) #undef SYCL_ADD_QUEUE_TRAIT // https://www.khronos.org/registry/cl/sdk/1.2/docs/man/xhtml/clGetMemObjectInfo.html #define SYCL_ADD_BUFFER_TRAIT(Value, ReturnType) \ SYCL_ADD_TRAIT(info::detail::buffer, Value, ReturnType, cl_mem_info) SYCL_ADD_BUFFER_TRAIT(info::detail::buffer::type, cl_mem_object_type) SYCL_ADD_BUFFER_TRAIT(info::detail::buffer::flags, cl_mem_flags) SYCL_ADD_BUFFER_TRAIT(info::detail::buffer::size, ::size_t) SYCL_ADD_BUFFER_TRAIT(info::detail::buffer::host_pointer, void*) SYCL_ADD_BUFFER_TRAIT(info::detail::buffer::map_count, cl_uint) SYCL_ADD_BUFFER_TRAIT(info::detail::buffer::reference_count, cl_uint) SYCL_ADD_BUFFER_TRAIT(info::detail::buffer::context, cl_context) SYCL_ADD_BUFFER_TRAIT(info::detail::buffer::associated_memory_object, cl_mem) SYCL_ADD_BUFFER_TRAIT(info::detail::buffer::offset, ::size_t) #undef SYCL_ADD_BUFFER_TRAIT // Table 3.62: Kernel class information descriptors. // https://www.khronos.org/registry/cl/sdk/1.2/docs/man/xhtml/clGetKernelInfo.html #define SYCL_ADD_KERNEL_TRAIT(Value, ReturnType) \ SYCL_ADD_TRAIT(info::kernel, Value, ReturnType, cl_kernel_info) SYCL_ADD_KERNEL_TRAIT(info::kernel::function_name, string_class) SYCL_ADD_KERNEL_TRAIT(info::kernel::num_args, cl_uint) SYCL_ADD_KERNEL_TRAIT(info::kernel::reference_count, cl_uint) SYCL_ADD_KERNEL_TRAIT(info::kernel::attributes, string_class) // Not part of the SYCL specification SYCL_ADD_KERNEL_TRAIT(info::kernel::context, cl_context) SYCL_ADD_KERNEL_TRAIT(info::kernel::program, cl_program) #undef SYCL_ADD_KERNEL_TRAIT // Table 3.65: Program class information descriptors // https://www.khronos.org/registry/cl/sdk/1.2/docs/man/xhtml/clGetProgramInfo.html #define SYCL_ADD_PROGRAM_TRAIT(Value, ReturnType) \ SYCL_ADD_TRAIT(info::program, Value, ReturnType, cl_program_info) SYCL_ADD_PROGRAM_TRAIT(info::program::reference_count, cl_uint) SYCL_ADD_PROGRAM_TRAIT(info::program::context, cl_context) SYCL_ADD_PROGRAM_TRAIT(info::program::devices, vector_class<cl_device_id>) // Not part of the SYCL specification SYCL_ADD_PROGRAM_TRAIT(info::program::num_devices, cl_uint) SYCL_ADD_PROGRAM_TRAIT(info::program::source, string_class) SYCL_ADD_PROGRAM_TRAIT(info::program::binary_sizes, vector_class<::size_t>) SYCL_ADD_PROGRAM_TRAIT(info::program::binaries, vector_class<vector_class<unsigned char>>) SYCL_ADD_PROGRAM_TRAIT(info::program::num_kernels, ::size_t) SYCL_ADD_PROGRAM_TRAIT(info::program::kernel_names, string_class) #undef SYCL_ADD_PROGRAM_TRAIT // 3.3.6.1 Event information and profiling descriptors // https://www.khronos.org/registry/cl/sdk/1.2/docs/man/xhtml/clGetEventInfo.html #define SYCL_ADD_EVENT_TRAIT(Value, ReturnType) \ SYCL_ADD_TRAIT(info::event, Value, ReturnType, cl_event_info) SYCL_ADD_EVENT_TRAIT(info::event::command_type, cl_command_type) SYCL_ADD_EVENT_TRAIT(info::event::command_execution_status, ::cl_int) SYCL_ADD_EVENT_TRAIT(info::event::reference_count, ::cl_int) // Not part of the SYCL specification SYCL_ADD_EVENT_TRAIT(info::event::command_queue, cl_command_queue) SYCL_ADD_EVENT_TRAIT(info::event::context, cl_context) #undef SYCL_ADD_EVENT_TRAIT // https://www.khronos.org/registry/cl/sdk/1.2/docs/man/xhtml/clGetEventProfilingInfo.html #define SYCL_ADD_EVENT_PROFILING_TRAIT(Value, ReturnType) \ SYCL_ADD_TRAIT(info::event_profiling, Value, ReturnType, cl_profiling_info) SYCL_ADD_EVENT_PROFILING_TRAIT(info::event_profiling::command_queued, cl_ulong) SYCL_ADD_EVENT_PROFILING_TRAIT(info::event_profiling::command_submit, cl_ulong) SYCL_ADD_EVENT_PROFILING_TRAIT(info::event_profiling::command_start, cl_ulong) SYCL_ADD_EVENT_PROFILING_TRAIT(info::event_profiling::command_end, cl_ulong) #undef SYCL_ADD_EVENT_PROFILING_TRAIT #undef SYCL_ADD_TRAIT namespace detail { template <class Contained_, class EnumClass, EnumClass param, ::size_t BufferSize = traits<Contained_>::BUFFER_SIZE> struct array_traits : traits<Contained_, BufferSize> { using Base = array_traits<Contained_, EnumClass, param, BufferSize>; using RealBase = traits<Contained_, BufferSize>; using Contained = typename RealBase::Contained; using return_t = typename std::conditional<BufferSize == 1, Contained, Contained*>::type; Contained param_value[RealBase::BUFFER_SIZE]; ::size_t actual_size = 0; template <typename cl_input_t> return_t get(cl_input_t data_ptr) { auto error_code = info_function<EnumClass>::get( data_ptr, (typename param_traits<EnumClass, param>::cl_flag_type)param, RealBase::BUFFER_SIZE * RealBase::type_size, param_value, &actual_size ); error::report(error_code); return trait_return<BufferSize == 1>::get(param_value); } }; // Meant for scalar and string cases template <class EnumClass, EnumClass param, ::size_t BufferSize = traits<param_traits_t<EnumClass, param>>::BUFFER_SIZE> struct non_vector_traits : array_traits<param_traits_t<EnumClass, param>, EnumClass, param, BufferSize> {}; } // namespace detail } // namespace sycl } // namespace cl
C++
CL
b2b644ab3d060669e6ad94b75bf26876bfa44d8d660d998af88e3ebdaef5d6e0
#include <ctime> #include <memory> #include "libg3logger/g3logger.h" #include "serdp_recorder/VideoRecorder.h" #include "gpmf-write/GPMF_writer.h" using namespace libvideoencoder; namespace serdp_recorder { using namespace std; static char FileExtension[] = "mov"; using namespace libvideoencoder; //================================================================= VideoRecorder::VideoRecorder( const std::string &filename, int width, int height, float frameRate, int numStreams, bool doSonar ) : _frameNum(0), _sonarFrameNum(0), // _pending(0), // _mutex(), _writer(FileExtension, AV_CODEC_ID_PRORES), _writerThread( _writer ), _videoTracks(), _dataTrack( doSonar ? new DataTrack(_writer) : nullptr ), _gpmfEncoder() { for( int i = 0; i < numStreams; ++i ) { _videoTracks.push_back( std::shared_ptr<VideoTrack>(new VideoTrack(_writer, width, height, frameRate) ) ); } _writer.open( filename ); } VideoRecorder::~VideoRecorder() { sleep(2); _writer.close(); } bool VideoRecorder::addMats( const std::vector<cv::Mat> &mats ) { std::deque< std::shared_ptr<std::thread> > recordThreads; for( unsigned int i=0; i < mats.size(); ++i ) { recordThreads.push_back( shared_ptr<std::thread>( new std::thread( &VideoRecorder::addMat, this, mats[i], _frameNum, i ) ) ); // AVPacket *pkt = _videoTracks[i]->encodeFrame( mats[i], _frameNum ); // _writerThread.writePacket( pkt ); } // // Wait for all recorder threads for( auto thread : recordThreads ) thread->join(); ++_frameNum; return true; } bool VideoRecorder::addMat( const cv::Mat &image, unsigned int frameNum, unsigned int stream ) { AVPacket *pkt = _videoTracks[stream]->encodeFrame( image, frameNum ); if( !pkt ) return false; // Insert into the _writerThread queue _writerThread.writePacket( pkt ); return true; } bool VideoRecorder::addSonar( const liboculus::SimplePingResult &ping, const std::chrono::time_point< std::chrono::system_clock > timePt ) { if( !_dataTrack ) return false; // // { // std::lock_guard<std::mutex> lock(_mutex); // ++_pending; // } { uint32_t *buffer; auto payloadSize = _gpmfEncoder.writeSonar( ping, &buffer, 0 ); if( payloadSize == 0) { LOG(WARNING) << "Failed to write sonar!"; // { // std::lock_guard<std::mutex> lock(_mutex); // --_pending; // } return false; } //LOG(WARNING) << " packet->pts " << pkt->pts; AVPacket *pkt = _dataTrack->encodeData( (uint8_t *)buffer, payloadSize, timePt ); _writerThread.writePacket( pkt ); ++_sonarFrameNum; } // { // std::lock_guard<std::mutex> lock(_mutex); // --_pending; // } return true; } fs::path VideoRecorder::MakeFilename( std::string &outputDir ) { std::time_t t = std::time(nullptr); char mbstr[100]; std::strftime(mbstr, sizeof(mbstr), "vid_%Y%m%d_%H%M%S", std::localtime(&t)); // TODO. Test if file is existing strcat( mbstr, "."); strcat( mbstr, FileExtension); return fs::path(outputDir) /= mbstr; } //================================================================= VideoRecorder::VideoWriterThread::VideoWriterThread( libvideoencoder::VideoWriter &writer ) : _writer(writer), _thread( active_object::Active::createActive() ) {;} VideoRecorder::VideoWriterThread::~VideoWriterThread() {;} void VideoRecorder::VideoWriterThread::writePacket( AVPacket *packet ) { if( _thread->size() > 10 ) { LOG( WARNING ) << "More than 10 frames queued ... skipping"; return; } _thread->send( std::bind( &VideoRecorder::VideoWriterThread::writePacketImpl, this, packet ) ); } void VideoRecorder::VideoWriterThread::writePacketImpl( AVPacket *packet ) { _writer.writePacket( packet ); } }
C++
CL
cac2d0fd0a9f4ac80583e8a32545187e3e3ee3c223ad61d65901cf49becdec15
/********************************************************************** qtVlm: Virtual Loup de mer GUI Copyright (C) 2008 - Christophe Thomas aka Oxygen77 http://qtvlm.sf.net 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/>. ***********************************************************************/ #ifndef MYCENTRALWIDGET_H #define MYCENTRALWIDGET_H #ifdef QT_V5 #include <QtWidgets/QGraphicsScene> #include <QtWidgets/QGraphicsView> #include <QtMultimedia/qsound.h> #else #include <QGraphicsScene> #include <QGraphicsView> #include <qsound.h> #endif #include "class_list.h" #include "dataDef.h" #include "DialogUnits.h" #include "DialogGraphicsParams.h" #include "selectionWidget.h" #include "MainWindow.h" #include "Magnifier.h" #include "DataManager.h" #include <qdatetime.h> /* Z value according to type */ #define Z_VALUE_TERRE 0 #define Z_VALUE_LOADIMG 0.4 #define Z_VALUE_FAXMETEO 0.5 #define Z_VALUE_ROUTAGE 1 #define Z_VALUE_OPP 2 #define Z_VALUE_GATE 3 #define Z_VALUE_NEXT_GATE 3.5 #define Z_VALUE_ESTIME 4 #define Z_VALUE_ROUTE 5 #define Z_VALUE_POI 7 #define Z_VALUE_BOAT 10 #define Z_VALUE_COMPASS 11 #define Z_VALUE_ISOPOINT 12 #define Z_VALUE_SELECTION 15 #define Z_VALUE_MAGNIFIER 80 /* graphicsWidget type */ #define TERRE_WTYPE 1 #define POI_WTYPE 2 #define COMPASS_WTYPE 3 #define BOAT_WTYPE 4 #define SELECTION_WTYPE 5 #define OPP_WTYPE 6 #define ISOPOINT 7 #define BOATREAL_WTYPE 8 #define FAXMETEO_WTYPE 9 #define BARRIERPOINT_WTYPE 10 /* compass mode */ #define COMPASS_NOTHING 0 #define COMPASS_LINEON 1 #define COMPASS_UNDER 2 class myScene : public QGraphicsScene { Q_OBJECT public: myScene(myCentralWidget * parent = 0); void setPinching(const bool &b){this->pinching=b;} bool getPinching() const {return this->pinching;} protected: void keyPressEvent (QKeyEvent *e); void keyReleaseEvent (QKeyEvent *e); void mouseMoveEvent (QGraphicsSceneMouseEvent * event); void mouseDoubleClickEvent(QGraphicsSceneMouseEvent* e); void wheelEvent(QGraphicsSceneWheelEvent* e); bool event(QEvent * event); signals: void paramVLMChanged(); void eraseWay(); private slots: void wheelTimerElapsed(); private: myCentralWidget * parent; bool hasWay; int wheelStrokes; QTimer *wheelTimer; int wheelPosX; int wheelPosY; bool wheelCenter; bool pinching; }; class myCentralWidget : public QWidget { Q_OBJECT public: myCentralWidget(Projection * proj,MainWindow * parent,MenuBar *menuBar); void loadBoat(void); void loadPOI(void); ~myCentralWidget(); /* access to pointer & data */ myScene * getScene(void) { return scene; } bool compassHasLine(void); int getCompassMode(int m_x,int m_y); bool isSelecting(void); QList<boatVLM*> * getBoats() { return this->boat_list; } QList<boat*> get_boatList(void); QList<Player*> & getPlayers() { return this->player_list; } QList<raceData*> & getRaces() { return this->race_list; } QList<POI*> & getPois() { return this->poi_list; } QList<POI*> * getPoisList() { return & this->poi_list; } GshhsReader * get_gshhsReader(void) { return gshhsReader; } opponentList * getOppList() { return opponents; } inetConnexion * getInet(void) { return inetManager; } boat * getSelectedBoat(void); bool hornIsActivated(void){return hornActivated;} void setHornIsActivated(bool b){this->hornActivated=b;} QDateTime getHornDate(void){return this->hornDate;} void setHornDate(QDateTime t){this->hornDate=t;} void setHorn(); void twaDraw(double lon, double lat); Player * getPlayer(void) { return currentPlayer; } boatReal * getRealBoat(void) {return realBoat; } bool getIsStartingUp(void){return mainW->isStartingUp;} MainWindow * getMainWindow(void) { return mainW; } MyView * getView() const {return this->view;} void removeRoute(); FCT_SETGET(ToolBar*,toolBar) FCT_SETGET_CST(bool, noSave) /*** Barrier ***/ FCT_GET(int,barrierEditMode) void escKey_barrier(void); void insert_barrierPointAfterPoint(BarrierPoint * point); FCT_SETGET(QPoint,cursorPositionOnPopup) void loadGshhs(void); void manageAccount(bool * res=NULL); void updatePlayer(Player * player); bool getIsSelecting(){return this->selection->isSelecting();} /* route */ QList<ROUTE*> & getRouteList(){ return this->route_list;} bool freeRouteName(QString name, ROUTE * route); void assignPois(); void emitUpdateRoute(boat * boat){emit updateRoute(boat);} ROUTE * addRoute(); void setCompassFollow(ROUTE * route); ROUTE * getCompassFollow(){return this->compassRoute;} void centerCompass(double lon,double lat); void simpAllPOIs(bool b); void setRouteToClipboard(ROUTE * route){this->routeClipboard=route;} ROUTE * getRouteToClipboard(){return this->routeClipboard;} bool myDeleteRoute(ROUTE * route, bool silent=false); /* routage */ QList<ROUTAGE*> & getRoutageList(){ return this->routage_list;} bool freeRoutageName(QString name, ROUTAGE * routage); ROUTAGE * addRoutage(); int getNbRoutage(){return nbRoutage;} void addPivot(ROUTAGE * fromRoutage,bool editOptions=false); void deleteRoutage(ROUTAGE * routage, ROUTE * route=NULL); /*Other*/ Projection * getProj(void){return proj;} void send_redrawAll() { emit redrawAll(); } /* grib */ void setCurrentDate(time_t t, bool uRoute=true); time_t getCurrentDate(void); void showGribDate_dialog(void); void loadGribFile(QString fileName, bool zoom); void loadGribFileCurrent(QString fileName, bool zoom); void closeGribFile(void); void closeGribFileCurrent(void); void updateGribMenu(void); FCT_GET(MapDataDrawer*,mapDataDrawer) FCT_GET(DataManager*,dataManager) void fileInfo_GRIB(int grbType); void fileInfo_GRIB(Grib * grib); /* events */ void mouseMove(int x, int y, QGraphicsItem * item); void mouseDoubleClick(int x, int y, QGraphicsItem * item); void keyModif(QKeyEvent *e); void escapeKeyPressed(void); bool getAboutToQuit(void){return aboutToQuit;} void setAboutToQuit(void){this->aboutToQuit=true;} /* item state */ bool get_shLab_st(void) { return shLab_st; } bool get_shPoi_st(void) { return shPoi_st; } bool get_shRoute_st(void) { return shRoute_st; } bool get_shOpp_st(void) { return shOpp_st; } bool get_shPor_st(void) { return shPor_st; } FCT_GET(bool,shBarSet_st) void exportRouteFromMenu(ROUTE * route); void exportRouteFromMenuGPX(ROUTE * route,QString fileName,bool POIonly); void exportRouteFromMenuKML(ROUTE * route,QString fileName,bool toClipboard); void importRouteFromMenuKML(QString fileName,bool toClipboard, bool ortho=false); /*races*/ void drawNSZ(int i); void removeOpponent(QString oppId, QString raceId); Terrain * getTerre(){return terre;} time_t getNextVac(); void setPilototo(QList<POI*> poiList); void treatRoute(ROUTE* route); loadImg * getKap(){return kap;} void removePOI(void); bool getKeepPos(){return keepPos;} void zoom_Pinch(double scale, int XX, int YY); void setMagnifier(Magnifier * m){this->magnifier=m;} Magnifier * getMagnifier(){return this->magnifier;} void imgKap_open(const QString &kapname); public slots : /* Zoom & position */ void slot_Zoom_All(); void slot_Zoom_In(double quantity=1.3); void slot_Zoom_Out(double quantity=1.3); void slot_Zoom_Wheel(double quantity, int XX, int YY, bool centerOnWheel); void slot_Go_Left(); void slot_Go_Right(); void slot_Go_Up(); void slot_Go_Down(); void slot_Zoom_Sel(); void slot_keepPos(const bool &b); void slot_abortRequest(); void slot_selectionTool(); void slot_magnify(); /* POI */ POI * slot_addPOI(QString name,int type,double lat,double lon, double wph,int timestamp,bool useTimeStamp, boat *boat); void slot_addPOI_list(POI * poi); void slot_delPOI_list(POI * poi); void slot_POISave(void); void slot_POIRestore(void); void slot_POIimport(void); // import data from zyGrib void slot_POIimportGeoData(void); void slot_delAllPOIs(void); void slot_removePOIType(void); void slot_delSelPOIs(void); void slot_notSimpAllPOIs(void); void slot_simpAllPOIs(void); /*** Barrier ***/ void slot_newBarrier(void); void slot_addBarrier(void); /* item state */ void slot_showALL(bool); void slot_hideALL(bool); void slot_shLab(bool); void slot_shPoi(bool); void slot_shRoute(bool); void slot_shOpp(bool); void slot_shPor(bool); void slot_shFla(bool); void slot_shNig(bool); void slot_shBarSet(bool); /*Routes */ void slot_addRouteFromMenu(); void slot_importRouteFromMenu(bool ortho=false); void slot_importRouteFromMenu2(); void slot_editRoute(ROUTE * route,bool createMode=false); void slot_twaLine(); void slot_releaseCompassFollow(){this->compassRoute=NULL;} void slot_deleteRoute(); void withdrawRouteFromBank(QString routeName,QList<QVariant> details); void slot_routeTimer(); void update_menuRoute(); /*Routages */ void slot_addRoutageFromMenu(); void slot_editRoutage(ROUTAGE * routage,bool createMode=false,POI * endPOI=NULL); void slot_deleteRoutage(); void update_menuRoutage(); /* Players */ void slot_addPlayer_list(Player* player); void slot_delPlayer_list(Player* player); void slot_playerSelected(Player * player); /* Boats */ void slot_addBoat(boat* boat); void slot_delBoat(boat* boat); void slot_writeBoatData(void); void slot_readBoatData(void); void slot_moveBoat(double lat, double lon); /* Races */ void slot_addRace_list(raceData* race); void slot_delRace_list(raceData* race); void slot_readRaceData(void); /* Grib */ void slot_fileLoad_GRIB(void); void slot_fileInfo_GRIB_main(void); void slot_fileInfo_GRIB_current(void); void slotLoadSailsDocGrib(void); void slotFax_open(); void slotFax_close(); void slotImg_open(); void slotImg_close(); void zoomOnGrib(int grbType=DataManager::GRIB_NONE); /* Dialogs */ void slot_boatDialog(void); void slot_manageAccount(); void slot_raceDialog(void); /* Events */ void slot_mousePress(QGraphicsSceneMouseEvent*); void slot_mouseRelease(QGraphicsSceneMouseEvent* e); /* Menu */ void slot_map_CitiesNames(); void slot_clearSelection(void); void slotIsobarsStep(); void slotIsotherms0Step(); void slot_setColorMapMode(QAction*); void slot_editHorn(); void slot_playHorn(); void slot_startReplay(); void slot_replay(); void slot_takeScreenshot(); void slot_showVlmLog(); void slot_fetchVLMTrack(); void slot_resetGestures(); void slot_shTdb(bool); signals: /* drawing */ void redrawAll(void); void redrawGrib(void); void startReplay(bool); void replay(int); /* POI */ void writePOIData(QList<ROUTE*> &,QList<POI*> &,QString); void POI_selectAborted(POI*); void updateRoute(boat *); void updateRoutage(); void twaDelPoi(POI*); /* Boats */ void writeBoatData(QList<Player*> & player_list,QList<raceData*> & race_list,QString fname); void readBoatData(QString fname, bool readAll); void boatPointerHasChanged(boat *); void accountListUpdated(void); void resetTraceCache(void); /* compass */ void stopCompassLine(void); void compassLineToggle(bool); /*show-hide*/ void hideALL(bool); void showALL(bool); void shOpp(bool); void shPoi(bool); void shCom(bool); void shRou(bool); void shRouBis(); void shPor(bool); void shPol(bool); void shLab(bool); void shBarSet(bool); void shFla(); protected: void resizeEvent (QResizeEvent * e); private: //QCursor cur_cursor; bool resizing; Projection * proj; MainWindow * mainW; MenuBar *menuBar; ToolBar *toolBar; /* item child */ Terrain * terre; mapCompass * compass; selectionWidget * selection; opponentList * opponents; vlmLine * NSZ; /* Grib */ MapDataDrawer * mapDataDrawer; DataManager * dataManager; /* other child */ GshhsReader *gshhsReader; GshhsDwnload * gshhsDwnload; inetConnexion * inetManager; /* Scene & view */ myScene *scene; MyView * view; /* Dialogs */ DialogGribDate * gribDateDialog; DialogBoatAccount * boatAcc; DialogPlayerAccount * playerAcc; DialogRace * raceDialog; DialogLoadGrib * dialogLoadGrib; DialogUnits dialogUnits; DialogGraphicsParams dialogGraphicsParams; DialogRealBoatConfig * realBoatConfig; DialogVlmLog * vlmLogViewer; DialogDownloadTracks * vlmTrackRetriever; /* Lists, POI*/ QList<POI*> poi_list; QList<ROUTE*> route_list; QList<ROUTAGE*> routage_list; QList<boatVLM*> * boat_list; QList<Player*> player_list; QList<raceData*> race_list; Player * currentPlayer; boatReal * realBoat; ROUTE * routeClipboard; void connectPois(void); /*** Barrier ***/ int barrierEditMode; BarrierSet * currentSet; BarrierPoint * basePoint; QGraphicsLineItem * barrierEditLine; void move_barrierEditLine(QPoint evtPos); void manage_barrier(void); QPoint cursorPositionOnPopup; /* Data file */ xml_POIData * xmlPOI; xml_boatData * xmlData; bool aboutToQuit; /* items state */ bool shLab_st; bool shPoi_st; bool shRoute_st; bool shOpp_st; bool shPor_st; bool shBarSet_st; void do_shLab(bool val); void do_shPoi(bool val); void do_shRoute(bool val); void do_shOpp(bool val); void do_shPor(bool val); void do_shBarSet(bool val); QSound *horn; bool hornActivated; QDateTime hornDate; QTimer *hornTimer; DialogTwaLine *twaTrace; ROUTE * compassRoute; int nbRoutage; bool keepPos; void deleteRoute(ROUTE * route); int replayStep; QTimer *replayTimer; void doSimplifyRoute(ROUTE * route, bool fast=false); bool abortRequest; faxMeteo * fax; loadImg * kap; ROUTE * routeSimplify; bool selectionTool; Magnifier * magnifier; bool noSave; }; #endif // MYCENTRALWIDGET_H
C++
CL
865211d09d3f90704079f046eda64bf69112321fe57d3157aadb0dbf74706e6e
/* * StmpTransPassive.h * * Created on: Jan 15, 2018 * Author: root */ #ifndef STMP_STMPTRANSPASSIVE_H_ #define STMP_STMPTRANSPASSIVE_H_ #include "StmpTrans.h" class StmpTransPassive: public StmpTrans { public: StmpTransPassive(StmpNet* stmpNet, Message* begin, uint dtid); virtual ~StmpTransPassive(); }; #endif /* STMP_STMPTRANSPASSIVE_H_ */
C++
CL
0fb3746cca528b7adba7179a8bb6548cf9f1077b57158daf135eff4543367dcb
/* Copyright (c) Stanford University, The Regents of the University of * California, and others. * * All Rights Reserved. * * See Copyright-SimVascular.txt for additional details. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef SV4GUI_ROM_SIMULATION_EXTRACT_CENTERLINES_H #define SV4GUI_ROM_SIMULATION_EXTRACT_CENTERLINES_H #include <org_sv_gui_qt_romsimulation_Export.h> #include "sv4gui_DataNodeOperationInterface.h" #include <sv4gui_mitkIContextMenuAction.h> #include <mitkDataNode.h> #include <QObject> #include <QThread> #include <vtkSmartPointer.h> #include <vtkPolyData.h> class SV_QT_ROMSIMULATION sv4guiROMSimulationExtractCenterlines : public QObject, public svmitk::IContextMenuAction { Q_OBJECT Q_INTERFACES(svmitk::IContextMenuAction) public: sv4guiROMSimulationExtractCenterlines(); ~sv4guiROMSimulationExtractCenterlines(); // IContextMenuAction void Run(const QList<mitk::DataNode::Pointer> &selectedNodes) override; void SetDataStorage(mitk::DataStorage *dataStorage) override; void SetSmoothed(bool smoothed) override {} void SetDecimated(bool decimated) override {} void SetFunctionality(berry::QtViewPart *functionality) override { m_View = functionality; } vtkSmartPointer<vtkPolyData> GetCenterlineGeometry(); // Custom functionality void SetSourceCapIds(std::vector<int> sourceCapIds); mitk::DataNode::Pointer m_JobNode; QString m_CenterlinesFileName; public slots: void UpdateStatus(); private: sv4guiROMSimulationExtractCenterlines(const sv4guiROMSimulationExtractCenterlines &); sv4guiROMSimulationExtractCenterlines & operator=(const sv4guiROMSimulationExtractCenterlines &); mitk::DataStorage::Pointer m_DataStorage; mitk::DataNode::Pointer m_ProjFolderNode; sv4guiDataNodeOperationInterface* m_Interface; std::vector<int> m_SourceCapIds; vtkSmartPointer<vtkPolyData> m_CenterlineGeometry; berry::QtViewPart* m_View; class WorkThread : public QThread { public: WorkThread(mitk::DataStorage::Pointer dataStorage, mitk::DataNode::Pointer selectedNode, std::vector<int> sourceCapIds); QString GetStatus(){return m_Status;} mitk::DataNode::Pointer GetPathFolderNode(){return m_PathFolderNode;} std::vector<mitk::DataNode::Pointer> GetPathNodes(){return m_PathNodes;} mitk::DataNode::Pointer GetCenterlinesModelNode() {return m_CenterlinesModelNode;} mitk::DataNode::Pointer GetMergedCenterlinesModelNode() {return m_MergedCenterlinesModelNode;} mitk::DataNode::Pointer GetSelectedNode(){return m_SelectedNode;} vtkSmartPointer<vtkPolyData> m_CenterlineGeometry; mitk::DataNode::Pointer m_JobNode; QString m_CenterlinesFileName; private: mitk::DataNode::Pointer m_SelectedNode; mitk::DataStorage::Pointer mm_DataStorage; mitk::DataNode::Pointer m_PathFolderNode; QString m_Status; std::vector<mitk::DataNode::Pointer> m_PathNodes; mitk::DataNode::Pointer m_CenterlinesModelNode; mitk::DataNode::Pointer m_MergedCenterlinesModelNode; std::vector<int> mm_SourceCapIds; void run(); }; WorkThread* m_Thread; }; #endif
C++
CL
76290d60db17725af7e7d496f28006836738f16afb330134f2d57a841cdf4f20
/** * Copyright (C) 2011 * University of Rochester Department of Computer Science * and * Lehigh University Department of Computer Science and Engineering * * License: Modified BSD * Please see the file LICENSE.RSTM for licensing information */ /** * Pipeline Implementation * * This algorithm is inspired by FastPath [LCPC 2009], and by Oancea et * al. SPAA 2009. We induce a total order on transactions at start time, * via a global counter, and then we require them to commit in this order. * For concurrency control, we use an orec table, but atomics are not * needed, since the counter also serves as a commit token. * * In addition, the lead thread uses in-place writes, via a special * version of the read and write functions. However, the lead thread * can't self-abort. */ #include "../profiling.hpp" #include "algs.hpp" #include "RedoRAWUtils.hpp" #include <stm/UndoLog.hpp> // STM_DO_MASKED_WRITE using stm::TxThread; using stm::threads; using stm::threadcount; using stm::last_complete; using stm::timestamp; using stm::timestamp_max; using stm::orec_t; using stm::get_orec; using stm::OrecList; using stm::WriteSet; using stm::UNRECOVERABLE; using stm::WriteSetEntry; /** * Declare the functions that we're going to implement, so that we can avoid * circular dependencies. */ namespace { struct Pipeline { static TM_FASTCALL bool begin(TxThread*); static TM_FASTCALL void* read_ro(STM_READ_SIG(,,)); static TM_FASTCALL void* read_rw(STM_READ_SIG(,,)); static TM_FASTCALL void* read_turbo(STM_READ_SIG(,,)); static TM_FASTCALL void write_ro(STM_WRITE_SIG(,,,)); static TM_FASTCALL void write_rw(STM_WRITE_SIG(,,,)); static TM_FASTCALL void write_turbo(STM_WRITE_SIG(,,,)); static TM_FASTCALL void commit_ro(STM_COMMIT_SIG(,)); static TM_FASTCALL void commit_rw(STM_COMMIT_SIG(,)); static TM_FASTCALL void commit_turbo(STM_COMMIT_SIG(,)); static stm::scope_t* rollback(STM_ROLLBACK_SIG(,,,)); static bool irrevoc(STM_IRREVOC_SIG(,)); static void onSwitchTo(); static NOINLINE void validate(TxThread*, uintptr_t finish_cache); }; /** * Pipeline begin: * * Pipeline is very fair: on abort, we keep our old order. Thus only if we * are starting a new transaction do we get an order. We always check if we * are oldest, in which case we can move straight to turbo mode. * * ts_cache is important: when this tx starts, it knows its commit time. * However, earlier txns have not yet committed. The difference between * ts_cache and order tells how many transactions need to commit. Whenever * one does, this tx will need to validate. */ bool Pipeline::begin(TxThread* tx) { tx->allocator.onTxBegin(); // only get a new start time if we didn't just abort if (tx->order == -1) tx->order = 1 + faiptr(&timestamp.val); tx->ts_cache = last_complete.val; if (tx->ts_cache == ((uintptr_t)tx->order - 1)) GoTurbo(tx, read_turbo, write_turbo, commit_turbo); return false; } /** * Pipeline commit (read-only): * * For the sake of ordering, read-only transactions must wait until they * are the oldest, then they validate. This introduces a lot of * overhead, but it gives SGLA (in the [Menon SPAA 2008] sense) * semantics. */ void Pipeline::commit_ro(STM_COMMIT_SIG(tx,)) { // wait our turn, then validate while (last_complete.val != ((uintptr_t)tx->order - 1)) { // in this wait loop, we need to check if an adaptivity action is // underway :( if (TxThread::tmbegin != begin) tx->tmabort(tx); } foreach (OrecList, i, tx->r_orecs) { // read this orec uintptr_t ivt = (*i)->v.all; // if it has a timestamp of ts_cache or greater, abort if (ivt > tx->ts_cache) tx->tmabort(tx); } // mark self as complete last_complete.val = tx->order; // set status to committed... tx->order = -1; // commit all frees, reset all lists tx->r_orecs.reset(); OnReadOnlyCommit(tx); } /** * Pipeline commit (writing context): * * Given the total order, RW commit is just like RO commit, except that we * need to acquire locks and do writeback, too. One nice thing is that * acquisition is with naked stores, and it is on a path that always * commits. */ void Pipeline::commit_rw(STM_COMMIT_SIG(tx,upper_stack_bound)) { // wait our turn, validate, writeback while (last_complete.val != ((uintptr_t)tx->order - 1)) { if (TxThread::tmbegin != begin) tx->tmabort(tx); } foreach (OrecList, i, tx->r_orecs) { // read this orec uintptr_t ivt = (*i)->v.all; // if it has a timestamp of ts_cache or greater, abort if (ivt > tx->ts_cache) tx->tmabort(tx); } // mark every location in the write set, and perform write-back // NB: we cannot abort anymore foreach (WriteSet, i, tx->writes) { #ifdef STM_PROTECT_STACK volatile void* top_of_stack; if (i->addr >= &top_of_stack && i->addr < upper_stack_bound) continue; #endif // get orec orec_t* o = get_orec(i->addr); // mark orec o->v.all = tx->order; CFENCE; // WBW // write-back *i->addr = i->val; } last_complete.val = tx->order; // set status to committed... tx->order = -1; // commit all frees, reset all lists tx->r_orecs.reset(); tx->writes.reset(); OnReadWriteCommit(tx, read_ro, write_ro, commit_ro); } /** * Pipeline commit (turbo mode): * * The current transaction is oldest, used in-place writes, and eagerly * acquired all locks. There is nothing to do but mark self as done. * * NB: we do not distinguish between RO and RW... we should, and could * via tx->writes */ void Pipeline::commit_turbo(STM_COMMIT_SIG(tx,)) { CFENCE; last_complete.val = tx->order; // set status to committed... tx->order = -1; // commit all frees, reset all lists tx->r_orecs.reset(); tx->writes.reset(); OnReadWriteCommit(tx, read_ro, write_ro, commit_ro); } /** * Pipeline read (read-only transaction) * * Since the commit time is determined before final validation (because the * commit time is determined at begin time!), we can skip pre-validation. * Otherwise, this is a standard orec read function. */ void* Pipeline::read_ro(STM_READ_SIG(tx,addr,)) { void* tmp = *addr; CFENCE; // RBR between dereference and orec check // get the orec addr, read the orec's version# orec_t* o = get_orec(addr); uintptr_t ivt = o->v.all; // abort if this changed since the last time I saw someone finish if (ivt > tx->ts_cache) tx->tmabort(tx); // log orec tx->r_orecs.insert(o); // validate if necessary if (last_complete.val > tx->ts_cache) validate(tx, last_complete.val); return tmp; } /** * Pipeline read (writing transaction) */ void* Pipeline::read_rw(STM_READ_SIG(tx,addr,mask)) { // check the log for a RAW hazard, we expect to miss WriteSetEntry log(STM_WRITE_SET_ENTRY(addr, NULL, mask)); bool found = tx->writes.find(log); REDO_RAW_CHECK(found, log, mask); void* tmp = *addr; CFENCE; // RBR between dereference and orec check // get the orec addr, read the orec's version# orec_t* o = get_orec(addr); uintptr_t ivt = o->v.all; // abort if this changed since the last time I saw someone finish if (ivt > tx->ts_cache) tx->tmabort(tx); // log orec tx->r_orecs.insert(o); // validate if necessary if (last_complete.val > tx->ts_cache) validate(tx, last_complete.val); REDO_RAW_CLEANUP(tmp, found, log, mask) return tmp; } /** * Pipeline read (turbo mode) */ void* Pipeline::read_turbo(STM_READ_SIG(,addr,)) { return *addr; } /** * Pipeline write (read-only context) */ void Pipeline::write_ro(STM_WRITE_SIG(tx,addr,val,mask)) { // record the new value in a redo log tx->writes.insert(WriteSetEntry(STM_WRITE_SET_ENTRY(addr, val, mask))); OnFirstWrite(tx, read_rw, write_rw, commit_rw); } /** * Pipeline write (writing context) */ void Pipeline::write_rw(STM_WRITE_SIG(tx,addr,val,mask)) { // record the new value in a redo log tx->writes.insert(WriteSetEntry(STM_WRITE_SET_ENTRY(addr, val, mask))); } /** * Pipeline write (turbo mode) * * The oldest transaction needs to mark the orec before writing in-place. */ void Pipeline::write_turbo(STM_WRITE_SIG(tx,addr,val,mask)) { orec_t* o = get_orec(addr); o->v.all = tx->order; CFENCE; STM_DO_MASKED_WRITE(addr, val, mask); } /** * Pipeline unwinder: * * For now, unwinding always happens before locks are held, and can't * happen in turbo mode. * * NB: Self-abort is not supported in Pipeline. Adding undo logging to * turbo mode would resolve the issue. */ stm::scope_t* Pipeline::rollback(STM_ROLLBACK_SIG(tx, upper_stack_bound, except, len)) { PreRollback(tx); // we cannot be in fast mode if (CheckTurboMode(tx, read_turbo)) UNRECOVERABLE("Attempting to abort a turbo-mode transaction!"); // Perform writes to the exception object if there were any... taking the // branch overhead without concern because we're not worried about // rollback overheads. STM_ROLLBACK(tx->writes, upper_stack_bound, except, len); tx->r_orecs.reset(); tx->writes.reset(); // NB: at one time, this implementation could not reset pointers on // abort. This situation may remain, but it is not certain that it // has not been resolved. return PostRollback(tx); } /** * Pipeline in-flight irrevocability: */ bool Pipeline::irrevoc(STM_IRREVOC_SIG(,)) { UNRECOVERABLE("Pipeline Irrevocability not yet supported"); return false; } /** * Pipeline validation * * Make sure all orec version#s are valid. Then see about switching to * turbo mode. Note that to do the switch, the current write set must be * written to memory. */ void Pipeline::validate(TxThread* tx, uintptr_t finish_cache) { foreach (OrecList, i, tx->r_orecs) { // read this orec uintptr_t ivt = (*i)->v.all; // if it has a timestamp of ts_cache or greater, abort if (ivt > tx->ts_cache) tx->tmabort(tx); } // now update the finish_cache to remember that at this time, we were // still valid tx->ts_cache = finish_cache; // and if we are now the oldest thread, transition to fast mode if (tx->ts_cache == ((uintptr_t)tx->order - 1)) { if (tx->writes.size() != 0) { // mark every location in the write set, and perform write-back foreach (WriteSet, i, tx->writes) { // get orec orec_t* o = get_orec(i->addr); // mark orec o->v.all = tx->order; CFENCE; // WBW // write-back *i->addr = i->val; } GoTurbo(tx, read_turbo, write_turbo, commit_turbo); } } } /** * Switch to Pipeline: * * The timestamp must be >= the maximum value of any orec. Some algs use * timestamp as a zero-one mutex. If they do, then they back up the * timestamp first, in timestamp_max. * * Also, last_complete must equal timestamp * * Also, all threads' order values must be -1 */ void Pipeline::onSwitchTo() { timestamp.val = MAXIMUM(timestamp.val, timestamp_max.val); last_complete.val = timestamp.val; for (uint32_t i = 0; i < threadcount.val; ++i) threads[i]->order = -1; } } namespace stm { /** * Pipeline initialization */ template<> void initTM<Pipeline>() { // set the name stms[Pipeline].name = "Pipeline"; // set the pointers stms[Pipeline].begin = ::Pipeline::begin; stms[Pipeline].commit = ::Pipeline::commit_ro; stms[Pipeline].read = ::Pipeline::read_ro; stms[Pipeline].write = ::Pipeline::write_ro; stms[Pipeline].rollback = ::Pipeline::rollback; stms[Pipeline].irrevoc = ::Pipeline::irrevoc; stms[Pipeline].switcher = ::Pipeline::onSwitchTo; stms[Pipeline].privatization_safe = true; } }
C++
CL
1dfcbc3e678d79e0dced878eb441e8920d0f5bc0ae44e38cc70c2a7745ea4ceb
/**************************************************************************** ** ** Copyright (C) 2011 Kirill (spirit) Klochkov. ** Contact: [email protected] ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #ifndef BATTLECITYGLOBAL_H #define BATTLECITYGLOBAL_H #include <QString> #include <QDeclarativeItem> class BattleCity : public QObject { Q_OBJECT Q_ENUMS(ObstacleType) Q_ENUMS(TankType) Q_ENUMS(MoveDirection) public: enum MoveDirection { Forward, Backward, Left, Right }; enum ObstacleType { Ground = QDeclarativeItem::UserType + 1, BricksWall, ConcreteWall, Ice, Camouflage, Falcon, FalconDestroyed, Water }; enum ItemProperty { Traversable, Nontraversable, Destroyable, Movable }; enum TankType { Basic = Water + 1, Fast, Power, Armor }; enum Edge { NoneEdge, TopEdge, RightEdge, BottomEdge, LeftEdge }; typedef QMap<ObstacleType, QString> ObstacleTexturesMap; typedef QMap<MoveDirection, QStringList> TankTexturesMap; typedef QMap<MoveDirection, QString> ProjectileTexturesMap; BattleCity(QObject *parent = 0) : QObject(parent) { } static void init(); static const quint8 tankAnimationSteps = 2; Q_INVOKABLE static QPixmap obstacleTexture(ObstacleType type); static QPixmap cursorPixmap(ObstacleType type); Q_INVOKABLE static QPixmap projectileTexture(MoveDirection direction); Q_INVOKABLE static QPixmap tankTexture(TankType type, MoveDirection direction, int step, bool bonus); static QPixmap armorTankGoldTexture(MoveDirection direction, int step); static QPixmap armorTankGreenTexture(MoveDirection direction, int step); static QPixmap player1TankTexture(MoveDirection direction, int step); static QPixmap player1TankOneStarTexture(MoveDirection direction, int step); static QPixmap player1TankTwoStarsTexture(MoveDirection direction, int step); static QPixmap player1TankThreeStarsTexture(MoveDirection direction, int step); private: static QMap<TankType, TankTexturesMap> initNormalTankTexturesMap(); static QMap<TankType, TankTexturesMap> initBonusTankTexturesMap(); private: static const ObstacleTexturesMap obstacleNames; static const ObstacleTexturesMap cursorNames; static const ProjectileTexturesMap projectileTextureNames; static const TankTexturesMap basicTankNormalTexturesNames; static const TankTexturesMap basicTankBonusTexturesNames; static const TankTexturesMap fastTankNormalTexturesNames; static const TankTexturesMap fastTankBonusTexturesNames; static const TankTexturesMap powerTankNormalTexturesNames; static const TankTexturesMap powerTankBonusTexturesNames; static const TankTexturesMap armorTankNormalTexturesNames; static const TankTexturesMap armorTankBonusTexturesNames; static const TankTexturesMap armorTankGreenTexturesNames; static const TankTexturesMap armorTankGoldTexturesNames; static const TankTexturesMap player1TankTexturesNames; static const TankTexturesMap player1TankOneStarTexturesNames; static const TankTexturesMap player1TankTwoStarsTexturesNames; static const TankTexturesMap player1TankThreeStarsTexturesNames; static const QMap<TankType, TankTexturesMap> normalTankTextures; static const QMap<TankType, TankTexturesMap> bonusTankTextures; }; class Pixmap : public QDeclarativeItem { Q_OBJECT Q_PROPERTY(QPixmap pixmap READ pixmap WRITE setPixmap NOTIFY pixmapChcanged) public: Pixmap(QDeclarativeItem *parent = 0); void setPixmap(const QPixmap &pixmap) { m_pixmap = pixmap; emit pixmapChcanged(); update(); } QPixmap pixmap() const { return m_pixmap; } virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0); signals: void pixmapChcanged(); private: QPixmap m_pixmap; }; #endif // BATTLECITYGLOBAL_H
C++
CL
2f05ba77ec875c171e65cc64a94d04623beb8d605321c9b8bd499b7f2221c73a
#include <windows.h> #include <d3d11.h> #include <d3dx11.h> #include <dxerr.h> #include <stdio.h> #include "bullet.h" //Move the bullet foward, used by player to move based on camera direction, uses delta speed to ensure its the same speed across different frame rates void bullet::moveForward(double deltaTime) { m_moveBackForward += (deltaTime*m_speed); } //Set the direction the bullet should be moving when fired by player, based on angle of camera void bullet::UpdateBulletRotation() { //Create matrix based on z angle of player's camera XMMATRIX RotateYTempMatrix; RotateYTempMatrix = XMMatrixRotationY(m_zAngle); m_bulletRight = XMVector3TransformCoord(m_defaultRight, RotateYTempMatrix); m_bulletForward = XMVector3TransformCoord(m_defaultForward, RotateYTempMatrix); //calculate new position vector to move in, reset this value after movement m_position += m_moveLeftRight*m_bulletRight; m_position += m_moveBackForward*m_bulletForward; m_moveLeftRight = 0.0f; m_moveBackForward = 0.0f; //set new position setXPos(getXPos() + XMVectorGetX(m_position)); setYPos(getYPos() + XMVectorGetY(m_position)); setZPos(getZPos() + XMVectorGetZ(m_position)); } //Set the direction to look at and move, used when fired by an enemy void bullet::SetDirection(float x_lookAt, float y_lookAt) { m_dir = XMVectorSet(x_lookAt - m_xPos, 0.0, y_lookAt - m_zPos, 0.0); m_dir = XMVector3Normalize(m_dir); } //Move bullet forward based on direction, used by enemies when fired as they have a set direction to use, unlike player's camera void bullet::MoveTowards(double deltaTime) { setXPos(m_xPos + (XMVectorGetX(m_dir)*(deltaTime*m_speed))); setZPos(m_zPos + (XMVectorGetZ(m_dir)*(deltaTime*m_speed))); } //Update bullet, moving it and checking collision void bullet::UpdateBullet(Scene_node* root_node, double deltaTime) { //If active, move and check collisions, otherwise, set to inactive position outside o map if (m_active) { //Reduce current life time m_activeTime -= (deltaTime*0.05); if (m_activeTime < 0) m_activeTime = 0; //If life time has ended, set inactive if (m_activeTime == 0) { m_active = false; m_activeTime = m_activeTimeReset; setXPos(-100); setYPos(-100); setZPos(-100); } //If this bullet belongs to the player, move based on camera rotation, otherwise move based on enemy's direction vector if (m_sceneNode->GetBelongsToPlayer()) { moveForward(deltaTime); UpdateBulletRotation(); } else { MoveTowards(deltaTime); } //Update collision tree XMMATRIX identity = XMMatrixIdentity(); root_node->UpdateCollisionTree(&identity, 1.0); //If colliding with any object, deactivate if(m_sceneNode->check_collision(root_node, m_sceneNode) == true) { m_active = false; m_activeTime = m_activeTimeReset; setXPos(-100); setYPos(-100); setZPos(-100); } } else { setXPos(-100); setYPos(-100); setZPos(-100); } } //Spawn bullet, setting active, position, and angle void bullet::SetActive(float xPos, float yPos, float zPos, float dx, float dz) { m_active = true; setXPos(xPos); setYPos(yPos); setZPos(zPos); m_position = XMVectorSet(0.0, 0.0, 0.0, 0.0); m_xAngle = dx; m_zAngle = dz; } void bullet::Deactivate() { m_active = false; m_activeTime = m_activeTimeReset; setXPos(-100); setYPos(-100); setZPos(-100); } bool bullet::IsActive() { return m_active; } int bullet::GetDamage() { return m_damage; }
C++
CL
cccc589ee8ee3b9292d5f54c6cf72be25b1638de869765e1807db1b5d978b573
#ifndef __PLATFORM_H__ #define __PLATFORM_H__ #ifdef __WINDOWS__ #pragma warning(disable:4996) #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include <Winsock2.h> #include <MSWSock.h> #include <WS2tcpip.h> #include <direct.h> #include <unordered_map> #else #endif #include "vector" #include "queue" #include "map" #include "set" #ifdef __WINDOWS__ #define _CRT_SECURE_NO_WARNINGS #endif #ifndef FD_SETSIZE #define FD_SETSIZE 4096 #else #undef FD_SETSIZE #define FD_SETSIZE 4096 #endif typedef int TInt32; typedef short TInt16; typedef char TInt8; typedef unsigned int TUInt32; typedef unsigned short TUInt16; typedef unsigned char TUInt8; #ifdef __WINDOWS__ typedef __int64 TInt64; typedef unsigned __int64 TUInt64; #else typedef long long TInt64; typedef unsigned long long TUInt64; typedef sockaddr_in SOCKADDR_IN; typedef fd_set FD_SET; #endif typedef TInt32 TSocket; typedef TUInt64 TThreadID; typedef TInt32 TPacketID; #ifdef __WINDOWS__ typedef TInt32 TSockLen; #else typedef TUInt32 TSockLen; #endif typedef std::vector<char> TVecChar; typedef std::vector<TInt8> TVecInt8; typedef std::vector<TInt16> TVecInt16; typedef std::vector<TInt32> TVecInt32; typedef std::vector<TInt64> TVecInt64; typedef std::vector<TUInt8> TVecUInt8; typedef std::vector<TUInt16> TVecUInt16; typedef std::vector<TUInt32> TVecUInt32; typedef std::vector<TUInt64> TVecUInt64; enum E_MSG_MODE { EMM_WRITE = 0, //写消息包到输出流 EMM_READ, //读输入流到消息包 }; #define __ENTER_FUNCTION try{ #define __LEAVE_FUNCTION }catch(...){}; #endif
C++
CL
d6979f0910be59fa03d9d74126454db88c411e31a219ac3f02a6115365be6076
#include "LaneDetector.h" #include <errno.h> #include <poll.h> #include <cmath> #include "sensor_msgs/Image.h" #include "std_msgs/ColorRGBA.h" #include "cv_bridge/cv_bridge.h" using namespace std; cv::Mat* current_img = NULL; pthread_rwlock_t imgproc_semaphore = PTHREAD_RWLOCK_INITIALIZER; void img_listener(const sensor_msgs::Image& img) { // printf("new image\n"); pthread_rwlock_wrlock(&imgproc_semaphore); // copy the image onto the heap meaning it can exist without the global binding current_img = new cv::Mat(cv_bridge::toCvCopy(img, string("bgr8"))->image); pthread_rwlock_unlock(&imgproc_semaphore); } void* lane_detection_loop(void* detector_ptr) { LaneDetector* detector = (LaneDetector*)detector_ptr; pthread_rwlock_rdlock(&detector->exit_semaphore); bool running = detector->running; pthread_rwlock_unlock(&detector->exit_semaphore); while (running) { struct timeval now; gettimeofday(&now, NULL); unsigned long start_time = now.tv_sec * 1000 + now.tv_usec / 1000; detector->detect_lane(); gettimeofday(&now, NULL); unsigned long end_time = now.tv_sec * 1000 + now.tv_usec / 1000; usleep(1000000 - ((end_time - start_time) * 1000)); pthread_rwlock_rdlock(&detector->exit_semaphore); running = detector->running; pthread_rwlock_unlock(&detector->exit_semaphore); } return NULL; } LaneDetector::LaneDetector() : running(true), median_blur_radius(25), rosnode(ros::NodeHandle()), canny_grad_thresh(80), canny_cont_thresh(30), hough_radius_inc(10), hough_theta_inc(4.0 * CV_PI / 180.0), hough_min_votes(300) { laneimg_listener = rosnode.subscribe("camera/rgb/image_rect_color", 2, img_listener); pose_publisher = rosnode.advertise<std_msgs::ColorRGBA>("lane_pose", 2); if (pthread_rwlock_init(&exit_semaphore, NULL) == -1) { throw runtime_error(string("pthread_rwlock_init: failed to initialize LaneDetector.exit_semaphore: ") + to_string(errno)); } if (pthread_create(&lane_detection_thread, NULL, &lane_detection_loop, (void*)this) == -1) { throw runtime_error(string("pthread_create(): failed to start background processing thread: ") + to_string(errno)); } } LaneDetector::~LaneDetector() { pthread_rwlock_wrlock(&exit_semaphore); running = false; pthread_rwlock_unlock(&exit_semaphore); pthread_join(lane_detection_thread, NULL); } double detection_confidence(const vector<cv::Vec2d>& lane_lines_left, const vector<cv::Vec2d>& lane_lines_right) { const int RADIUS_L = 0; const int THETA_L = 1; const int RADIUS_R = 2; const int THETA_R = 3; vector<double> averages = {0.0, 0.0, 0.0, 0.0}; vector<double> stddevs = {0.0, 0.0, 0.0, 0.0}; // calculate average radius and angles for left lane markers for (const cv::Vec2d& line : lane_lines_left) { averages[RADIUS_L] += abs(line[0]); averages[THETA_L] += line[1]; } averages[RADIUS_L] /= (double)lane_lines_left.size(); averages[THETA_L] /= (double)lane_lines_left.size(); // calculate the average radius and angles for the right lane markers for (const cv::Vec2d& line : lane_lines_right) { averages[RADIUS_R] += abs(line[0]); averages[THETA_R] += line[1]; } averages[RADIUS_R] /= (double)lane_lines_right.size(); averages[THETA_R] /= (double)lane_lines_right.size(); // comput standard variance / deviation for the left sample for (const cv::Vec2d& line : lane_lines_left) { double radius_var2 = abs(line[0]) - averages[RADIUS_L]; double theta_var2 = line[1] - averages[THETA_L]; stddevs[RADIUS_L] += radius_var2 * radius_var2; stddevs[THETA_L] += theta_var2 * theta_var2; } stddevs[RADIUS_L] /= (double)lane_lines_left.size(); stddevs[THETA_L] /= (double)lane_lines_left.size(); // compute standard variance / deviation for the right sample for (const cv::Vec2d& line : lane_lines_right) { double radius_var2 = abs(line[0]) - averages[RADIUS_R]; double theta_var2 = line[1] - averages[THETA_R]; stddevs[RADIUS_R] += radius_var2 * radius_var2; stddevs[THETA_R] += theta_var2 * theta_var2; } stddevs[RADIUS_R] /= (double)lane_lines_right.size(); stddevs[THETA_R] /= (double)lane_lines_right.size(); vector<double> confidence = { 0.0, 0.0, 0.0, 0.0}; const double P95_ANG_VARIANCE = (CV_PI * CV_PI / 4.0); // Absolute angular variance for the 95th percentile (4 sigma) const double P95_RAD_VARIANCE = 2 * (150.0 * 150.0); // Absolute radial variance for the 95th percentile (4 sigma) // compute the confidence of lane detection. Actual lane detections should // have few samples of lines and thus low variances. when variances approach // the maximum possible or reasonable variance, this should drop the confidence // to zero. confidence[RADIUS_L] = (P95_RAD_VARIANCE - 2.0 * stddevs[RADIUS_L]) / P95_RAD_VARIANCE; confidence[THETA_L] = (P95_ANG_VARIANCE - 2.0 * stddevs[THETA_L]) / P95_ANG_VARIANCE; confidence[RADIUS_R] = (P95_RAD_VARIANCE - 2.0 * stddevs[RADIUS_R]) / P95_RAD_VARIANCE; confidence[THETA_R] = (P95_ANG_VARIANCE - 2.0 * stddevs[THETA_R]) / P95_ANG_VARIANCE; if (confidence[RADIUS_L] < 0.0 || confidence[RADIUS_R] < 0.0) { return 0.0; } double min_confidence = 1.0; // always work with minimum confidenc for (int index = 0; index < 4; index++) { if (confidence[index] < min_confidence) { min_confidence = confidence[index]; } } return min_confidence; } void LaneDetector::detect_lane() { pthread_rwlock_rdlock(&imgproc_semaphore); if (!current_img) { pthread_rwlock_unlock(&imgproc_semaphore); printf("No image to process. Sleeping\n"); std_msgs::ColorRGBA mesg; mesg.r = 0; mesg.b = 0; return; } // get the most recent image and allow for the background listener to overwrite the binding // this avoids blocking the listener while processing images cv::Mat* source_img = current_img; cv::Mat& img_color = *current_img; pthread_rwlock_unlock(&imgproc_semaphore); int hres = 1280; int vres = (int)((double)img_color.rows * ((double)hres / img_color.cols)); cv::resize(img_color, img_color, cv::Size(hres, vres), cv::INTER_AREA); struct timeval now; gettimeofday(&now, NULL); unsigned long start_time = now.tv_sec * 1000 + now.tv_usec / 1000; // remove localized noise and unnecessary detail using median filter cv::medianBlur(img_color, img_color, median_blur_radius); // convert image to grayscale cv::Mat img_gray; cv::cvtColor(img_color, img_gray, cv::COLOR_BGR2GRAY); // perform canny edge detection cv::Mat edge_img; cv::Canny(img_gray, edge_img, canny_cont_thresh, canny_grad_thresh); // blot out top half of image cv::rectangle(edge_img, cv::Point2i(0, 0), cv::Point2i(img_gray.cols - 1, img_gray.rows / 3), cv::Scalar(0.0), cv::FILLED); vector<cv::Vec2d> lines; // 25.0 pix radius granularity, 1 deg angular granularity, 200 votes min for a line // 200 pixels min for a segment, up to 300 pixels between disconnected colinear segments cv::HoughLines(edge_img, lines, hough_radius_inc, hough_theta_inc, hough_min_votes); printf("Found %lu lines in the image\n", lines.size()); vector<cv::Vec2d> raw_lines_left; vector<cv::Vec2d> raw_lines_right; vector<cv::Vec2d> lane_lines_left; vector<cv::Vec2d> lane_lines_right; for (auto& line : lines) { printf(" Radius: %f Theta: %f\n", line[0], line[1] / CV_PI * 180.0); if ((line[1] > 7.0 * CV_PI / 180.0) && (line[1] < 173.0 * CV_PI / 180.0) && ((line[1] < 8.0 * CV_PI / 18.0) || (line[1] > 10.0 * CV_PI / 18.0))) { double slope = -1.0 / tan(line[1]); double y_init = line[0] * sin(line[1]); double x_init = line[0] * cos(line[1]); double x1, y1, x2, y2 = 0.0; x1 = 0.0; y1 = -slope * x_init + y_init; if (slope < 0.0) { x2 = -y_init / slope + x_init; y2 = 0.0; lane_lines_left.push_back(cv::Vec2d(slope, -slope * x_init + y_init)); raw_lines_left.push_back(line); } else { x2 = (double)edge_img.cols; y2 = slope * x2 - slope * x_init + y_init; lane_lines_right.push_back(cv::Vec2d(slope, -slope * x_init + y_init)); raw_lines_right.push_back(line); } cv::line(edge_img, cv::Point2i((int)x1, (int)y1), cv::Point2i((int)x2, (int)y2), cv::Scalar(255.0), 10); printf(" (%f, %f), (%f, %f)\n", x1, y1, x2, y2); } } if (!lane_lines_left.empty() && !lane_lines_right.empty()) { cv::Vec2d lane_left(lane_lines_left[0][0], lane_lines_left[0][1]); cv::Vec2d lane_right(lane_lines_right[0][0], lane_lines_right[0][1]); for (int index = 1; index < lane_lines_left.size(); index++) { lane_left[0] += lane_lines_left[index][0]; lane_left[1] += lane_lines_left[index][1]; } lane_left[0] /= (double)lane_lines_left.size(); lane_left[1] /= (double)lane_lines_left.size(); for (int index = 1; index < lane_lines_right.size(); index++) { lane_right[0] += lane_lines_right[index][0]; lane_right[1] += lane_lines_right[index][1]; } lane_right[0] /= (double)lane_lines_right.size(); lane_right[1] /= (double)lane_lines_right.size(); int lane_start_y = edge_img.rows; int lane_left_start_x = ((double)lane_start_y - lane_left[1]) / lane_left[0]; int lane_right_start_x = ((double)lane_start_y - lane_right[1]) / lane_right[0]; int lane_center = lane_left_start_x + ((double)lane_right_start_x - lane_left_start_x) / 2.0; int xint = (lane_right[1] - lane_left[1]) / (lane_left[0] - lane_right[0]); int yint = lane_right[0] * xint + lane_right[1]; cv::line(edge_img, cv::Point2i(xint, yint), cv::Point2i(lane_center, lane_start_y), cv::Scalar(255.0), 5); printf("\n Distance from Center: %d px\n" " Right / Left X: %d, %d\n", edge_img.cols / 2 - lane_center, lane_right_start_x, lane_left_start_x); struct LanePose pose; pose.center_offset = edge_img.cols / 2 - lane_center; pose.heading = 0.0; pose.confidence = detection_confidence(raw_lines_left, raw_lines_right); current_pose = pose; printf(" Detection Confidence: %%%3.1f\n", pose.confidence * 100.0); } else { struct LanePose pose; pose.center_offset = 0; pose.heading = 0.0; pose.confidence = 0.0; current_pose = pose; } gettimeofday(&now, NULL); unsigned long end_time = now.tv_sec * 1000 + now.tv_usec / 1000; char filename[128]; memset(filename, '\0', 128); sprintf(filename, "/media/nvidia/seniorDesign/LaneDetectionDebug/%lu_img.jpg", end_time); cv::imwrite(filename, img_color); memset(filename, '\0', 32); sprintf(filename, "/media/nvidia/seniorDesign/LaneDetectionDebug/%lu_edges.jpg", end_time); cv::imwrite(filename, edge_img); printf("Processing took: %lu msec\n\n----\n\n", end_time - start_time); std_msgs::ColorRGBA mesg; mesg.r = current_pose.center_offset / 850.0; if (mesg.r > 1.0) { mesg.r = 1.0; } else if (mesg.r < -1.0) { mesg.r = -1.0; } mesg.g = current_pose.confidence; pose_publisher.publish(mesg); delete source_img; } bool LaneDetector::set_median_blur_radius(int radius) { if (radius % 2 == 1) { median_blur_radius = radius; return true; } return false; } void LaneDetector::set_hough_theta_inc(double degrees) { hough_theta_inc = degrees * CV_PI / 180.0; } struct LanePose LaneDetector::get_vehicle_pose() { return current_pose; } void LaneDetector::lane_guidance() { struct pollfd stdin_timeout[1]; stdin_timeout[0].fd = STDIN_FILENO; stdin_timeout[0].events = POLLIN | POLLPRI; while (ros::ok()) { int poll_status = poll(stdin_timeout, 1, 10); if (poll_status > 0) { int ch = getchar(); if ((char)ch == '\n' || (char)ch == '\r') { break; } } else { ros::spinOnce(); } } }
C++
CL
367cc5a4374e19baec0ed8258a80f1bcfc23746d50962f85a59760aebdbe7a24
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: EquipRefitCfg.proto #define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION #include "EquipRefitCfg.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> // @@protoc_insertion_point(includes) namespace com { namespace cfg { namespace vo { void protobuf_ShutdownFile_EquipRefitCfg_2eproto() { delete EquipRefitConsumeElement::default_instance_; delete EquipRefitCfg::default_instance_; delete EquipRefitCfgSet::default_instance_; } #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER void protobuf_AddDesc_EquipRefitCfg_2eproto_impl() { GOOGLE_PROTOBUF_VERIFY_VERSION; #else void protobuf_AddDesc_EquipRefitCfg_2eproto() { static bool already_here = false; if (already_here) return; already_here = true; GOOGLE_PROTOBUF_VERIFY_VERSION; #endif EquipRefitConsumeElement::default_instance_ = new EquipRefitConsumeElement(); EquipRefitCfg::default_instance_ = new EquipRefitCfg(); EquipRefitCfgSet::default_instance_ = new EquipRefitCfgSet(); EquipRefitConsumeElement::default_instance_->InitAsDefaultInstance(); EquipRefitCfg::default_instance_->InitAsDefaultInstance(); EquipRefitCfgSet::default_instance_->InitAsDefaultInstance(); ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_EquipRefitCfg_2eproto); } #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AddDesc_EquipRefitCfg_2eproto_once_); void protobuf_AddDesc_EquipRefitCfg_2eproto() { ::google::protobuf::::google::protobuf::GoogleOnceInit(&protobuf_AddDesc_EquipRefitCfg_2eproto_once_, &protobuf_AddDesc_EquipRefitCfg_2eproto_impl); } #else // Force AddDescriptors() to be called at static initialization time. struct StaticDescriptorInitializer_EquipRefitCfg_2eproto { StaticDescriptorInitializer_EquipRefitCfg_2eproto() { protobuf_AddDesc_EquipRefitCfg_2eproto(); } } static_descriptor_initializer_EquipRefitCfg_2eproto_; #endif // =================================================================== #ifndef _MSC_VER const int EquipRefitConsumeElement::kElementIDFieldNumber; const int EquipRefitConsumeElement::kElementTypeFieldNumber; const int EquipRefitConsumeElement::kElementCntFieldNumber; #endif // !_MSC_VER EquipRefitConsumeElement::EquipRefitConsumeElement() : ::google::protobuf::MessageLite() { SharedCtor(); } void EquipRefitConsumeElement::InitAsDefaultInstance() { } EquipRefitConsumeElement::EquipRefitConsumeElement(const EquipRefitConsumeElement& from) : ::google::protobuf::MessageLite() { SharedCtor(); MergeFrom(from); } void EquipRefitConsumeElement::SharedCtor() { _cached_size_ = 0; elementid_ = 0u; elementtype_ = 0u; elementcnt_ = 0u; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } EquipRefitConsumeElement::~EquipRefitConsumeElement() { SharedDtor(); } void EquipRefitConsumeElement::SharedDtor() { #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER if (this != &default_instance()) { #else if (this != default_instance_) { #endif } } void EquipRefitConsumeElement::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const EquipRefitConsumeElement& EquipRefitConsumeElement::default_instance() { #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER protobuf_AddDesc_EquipRefitCfg_2eproto(); #else if (default_instance_ == NULL) protobuf_AddDesc_EquipRefitCfg_2eproto(); #endif return *default_instance_; } EquipRefitConsumeElement* EquipRefitConsumeElement::default_instance_ = NULL; EquipRefitConsumeElement* EquipRefitConsumeElement::New() const { return new EquipRefitConsumeElement; } void EquipRefitConsumeElement::Clear() { if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { elementid_ = 0u; elementtype_ = 0u; elementcnt_ = 0u; } ::memset(_has_bits_, 0, sizeof(_has_bits_)); } bool EquipRefitConsumeElement::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) return false ::google::protobuf::uint32 tag; while ((tag = input->ReadTag()) != 0) { switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // required uint32 ElementID = 1; case 1: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( input, &elementid_))); set_has_elementid(); } else { goto handle_uninterpreted; } if (input->ExpectTag(16)) goto parse_ElementType; break; } // required uint32 ElementType = 2; case 2: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { parse_ElementType: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( input, &elementtype_))); set_has_elementtype(); } else { goto handle_uninterpreted; } if (input->ExpectTag(24)) goto parse_ElementCnt; break; } // required uint32 ElementCnt = 3; case 3: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { parse_ElementCnt: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( input, &elementcnt_))); set_has_elementcnt(); } else { goto handle_uninterpreted; } if (input->ExpectAtEnd()) return true; break; } default: { handle_uninterpreted: if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { return true; } DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); break; } } } return true; #undef DO_ } void EquipRefitConsumeElement::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // required uint32 ElementID = 1; if (has_elementid()) { ::google::protobuf::internal::WireFormatLite::WriteUInt32(1, this->elementid(), output); } // required uint32 ElementType = 2; if (has_elementtype()) { ::google::protobuf::internal::WireFormatLite::WriteUInt32(2, this->elementtype(), output); } // required uint32 ElementCnt = 3; if (has_elementcnt()) { ::google::protobuf::internal::WireFormatLite::WriteUInt32(3, this->elementcnt(), output); } } int EquipRefitConsumeElement::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // required uint32 ElementID = 1; if (has_elementid()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::UInt32Size( this->elementid()); } // required uint32 ElementType = 2; if (has_elementtype()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::UInt32Size( this->elementtype()); } // required uint32 ElementCnt = 3; if (has_elementcnt()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::UInt32Size( this->elementcnt()); } } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void EquipRefitConsumeElement::CheckTypeAndMergeFrom( const ::google::protobuf::MessageLite& from) { MergeFrom(*::google::protobuf::down_cast<const EquipRefitConsumeElement*>(&from)); } void EquipRefitConsumeElement::MergeFrom(const EquipRefitConsumeElement& from) { GOOGLE_CHECK_NE(&from, this); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_elementid()) { set_elementid(from.elementid()); } if (from.has_elementtype()) { set_elementtype(from.elementtype()); } if (from.has_elementcnt()) { set_elementcnt(from.elementcnt()); } } } void EquipRefitConsumeElement::CopyFrom(const EquipRefitConsumeElement& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool EquipRefitConsumeElement::IsInitialized() const { if ((_has_bits_[0] & 0x00000007) != 0x00000007) return false; return true; } void EquipRefitConsumeElement::Swap(EquipRefitConsumeElement* other) { if (other != this) { std::swap(elementid_, other->elementid_); std::swap(elementtype_, other->elementtype_); std::swap(elementcnt_, other->elementcnt_); std::swap(_has_bits_[0], other->_has_bits_[0]); std::swap(_cached_size_, other->_cached_size_); } } ::std::string EquipRefitConsumeElement::GetTypeName() const { return "com.cfg.vo.EquipRefitConsumeElement"; } // =================================================================== #ifndef _MSC_VER const int EquipRefitCfg::kPartFieldNumber; const int EquipRefitCfg::kColorFieldNumber; const int EquipRefitCfg::kCostCoinFieldNumber; const int EquipRefitCfg::kElmtListFieldNumber; #endif // !_MSC_VER EquipRefitCfg::EquipRefitCfg() : ::google::protobuf::MessageLite() { SharedCtor(); } void EquipRefitCfg::InitAsDefaultInstance() { } EquipRefitCfg::EquipRefitCfg(const EquipRefitCfg& from) : ::google::protobuf::MessageLite() { SharedCtor(); MergeFrom(from); } void EquipRefitCfg::SharedCtor() { _cached_size_ = 0; part_ = 0u; color_ = 0u; costcoin_ = 0u; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } EquipRefitCfg::~EquipRefitCfg() { SharedDtor(); } void EquipRefitCfg::SharedDtor() { #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER if (this != &default_instance()) { #else if (this != default_instance_) { #endif } } void EquipRefitCfg::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const EquipRefitCfg& EquipRefitCfg::default_instance() { #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER protobuf_AddDesc_EquipRefitCfg_2eproto(); #else if (default_instance_ == NULL) protobuf_AddDesc_EquipRefitCfg_2eproto(); #endif return *default_instance_; } EquipRefitCfg* EquipRefitCfg::default_instance_ = NULL; EquipRefitCfg* EquipRefitCfg::New() const { return new EquipRefitCfg; } void EquipRefitCfg::Clear() { if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { part_ = 0u; color_ = 0u; costcoin_ = 0u; } elmtlist_.Clear(); ::memset(_has_bits_, 0, sizeof(_has_bits_)); } bool EquipRefitCfg::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) return false ::google::protobuf::uint32 tag; while ((tag = input->ReadTag()) != 0) { switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // required uint32 Part = 1; case 1: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( input, &part_))); set_has_part(); } else { goto handle_uninterpreted; } if (input->ExpectTag(16)) goto parse_Color; break; } // required uint32 Color = 2; case 2: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { parse_Color: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( input, &color_))); set_has_color(); } else { goto handle_uninterpreted; } if (input->ExpectTag(24)) goto parse_CostCoin; break; } // required uint32 CostCoin = 3; case 3: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { parse_CostCoin: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( input, &costcoin_))); set_has_costcoin(); } else { goto handle_uninterpreted; } if (input->ExpectTag(34)) goto parse_ElmtList; break; } // repeated .com.cfg.vo.EquipRefitConsumeElement ElmtList = 4; case 4: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { parse_ElmtList: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, add_elmtlist())); } else { goto handle_uninterpreted; } if (input->ExpectTag(34)) goto parse_ElmtList; if (input->ExpectAtEnd()) return true; break; } default: { handle_uninterpreted: if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { return true; } DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); break; } } } return true; #undef DO_ } void EquipRefitCfg::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // required uint32 Part = 1; if (has_part()) { ::google::protobuf::internal::WireFormatLite::WriteUInt32(1, this->part(), output); } // required uint32 Color = 2; if (has_color()) { ::google::protobuf::internal::WireFormatLite::WriteUInt32(2, this->color(), output); } // required uint32 CostCoin = 3; if (has_costcoin()) { ::google::protobuf::internal::WireFormatLite::WriteUInt32(3, this->costcoin(), output); } // repeated .com.cfg.vo.EquipRefitConsumeElement ElmtList = 4; for (int i = 0; i < this->elmtlist_size(); i++) { ::google::protobuf::internal::WireFormatLite::WriteMessage( 4, this->elmtlist(i), output); } } int EquipRefitCfg::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // required uint32 Part = 1; if (has_part()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::UInt32Size( this->part()); } // required uint32 Color = 2; if (has_color()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::UInt32Size( this->color()); } // required uint32 CostCoin = 3; if (has_costcoin()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::UInt32Size( this->costcoin()); } } // repeated .com.cfg.vo.EquipRefitConsumeElement ElmtList = 4; total_size += 1 * this->elmtlist_size(); for (int i = 0; i < this->elmtlist_size(); i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->elmtlist(i)); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void EquipRefitCfg::CheckTypeAndMergeFrom( const ::google::protobuf::MessageLite& from) { MergeFrom(*::google::protobuf::down_cast<const EquipRefitCfg*>(&from)); } void EquipRefitCfg::MergeFrom(const EquipRefitCfg& from) { GOOGLE_CHECK_NE(&from, this); elmtlist_.MergeFrom(from.elmtlist_); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_part()) { set_part(from.part()); } if (from.has_color()) { set_color(from.color()); } if (from.has_costcoin()) { set_costcoin(from.costcoin()); } } } void EquipRefitCfg::CopyFrom(const EquipRefitCfg& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool EquipRefitCfg::IsInitialized() const { if ((_has_bits_[0] & 0x00000007) != 0x00000007) return false; for (int i = 0; i < elmtlist_size(); i++) { if (!this->elmtlist(i).IsInitialized()) return false; } return true; } void EquipRefitCfg::Swap(EquipRefitCfg* other) { if (other != this) { std::swap(part_, other->part_); std::swap(color_, other->color_); std::swap(costcoin_, other->costcoin_); elmtlist_.Swap(&other->elmtlist_); std::swap(_has_bits_[0], other->_has_bits_[0]); std::swap(_cached_size_, other->_cached_size_); } } ::std::string EquipRefitCfg::GetTypeName() const { return "com.cfg.vo.EquipRefitCfg"; } // =================================================================== #ifndef _MSC_VER const int EquipRefitCfgSet::kEquiprefitcfgFieldNumber; #endif // !_MSC_VER EquipRefitCfgSet::EquipRefitCfgSet() : ::google::protobuf::MessageLite() { SharedCtor(); } void EquipRefitCfgSet::InitAsDefaultInstance() { } EquipRefitCfgSet::EquipRefitCfgSet(const EquipRefitCfgSet& from) : ::google::protobuf::MessageLite() { SharedCtor(); MergeFrom(from); } void EquipRefitCfgSet::SharedCtor() { _cached_size_ = 0; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } EquipRefitCfgSet::~EquipRefitCfgSet() { SharedDtor(); } void EquipRefitCfgSet::SharedDtor() { #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER if (this != &default_instance()) { #else if (this != default_instance_) { #endif } } void EquipRefitCfgSet::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const EquipRefitCfgSet& EquipRefitCfgSet::default_instance() { #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER protobuf_AddDesc_EquipRefitCfg_2eproto(); #else if (default_instance_ == NULL) protobuf_AddDesc_EquipRefitCfg_2eproto(); #endif return *default_instance_; } EquipRefitCfgSet* EquipRefitCfgSet::default_instance_ = NULL; EquipRefitCfgSet* EquipRefitCfgSet::New() const { return new EquipRefitCfgSet; } void EquipRefitCfgSet::Clear() { equiprefitcfg_.Clear(); ::memset(_has_bits_, 0, sizeof(_has_bits_)); } bool EquipRefitCfgSet::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) return false ::google::protobuf::uint32 tag; while ((tag = input->ReadTag()) != 0) { switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // repeated .com.cfg.vo.EquipRefitCfg equiprefitcfg = 1; case 1: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { parse_equiprefitcfg: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, add_equiprefitcfg())); } else { goto handle_uninterpreted; } if (input->ExpectTag(10)) goto parse_equiprefitcfg; if (input->ExpectAtEnd()) return true; break; } default: { handle_uninterpreted: if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { return true; } DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); break; } } } return true; #undef DO_ } void EquipRefitCfgSet::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // repeated .com.cfg.vo.EquipRefitCfg equiprefitcfg = 1; for (int i = 0; i < this->equiprefitcfg_size(); i++) { ::google::protobuf::internal::WireFormatLite::WriteMessage( 1, this->equiprefitcfg(i), output); } } int EquipRefitCfgSet::ByteSize() const { int total_size = 0; // repeated .com.cfg.vo.EquipRefitCfg equiprefitcfg = 1; total_size += 1 * this->equiprefitcfg_size(); for (int i = 0; i < this->equiprefitcfg_size(); i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->equiprefitcfg(i)); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void EquipRefitCfgSet::CheckTypeAndMergeFrom( const ::google::protobuf::MessageLite& from) { MergeFrom(*::google::protobuf::down_cast<const EquipRefitCfgSet*>(&from)); } void EquipRefitCfgSet::MergeFrom(const EquipRefitCfgSet& from) { GOOGLE_CHECK_NE(&from, this); equiprefitcfg_.MergeFrom(from.equiprefitcfg_); } void EquipRefitCfgSet::CopyFrom(const EquipRefitCfgSet& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool EquipRefitCfgSet::IsInitialized() const { for (int i = 0; i < equiprefitcfg_size(); i++) { if (!this->equiprefitcfg(i).IsInitialized()) return false; } return true; } void EquipRefitCfgSet::Swap(EquipRefitCfgSet* other) { if (other != this) { equiprefitcfg_.Swap(&other->equiprefitcfg_); std::swap(_has_bits_[0], other->_has_bits_[0]); std::swap(_cached_size_, other->_cached_size_); } } ::std::string EquipRefitCfgSet::GetTypeName() const { return "com.cfg.vo.EquipRefitCfgSet"; } // @@protoc_insertion_point(namespace_scope) } // namespace vo } // namespace cfg } // namespace com // @@protoc_insertion_point(global_scope)
C++
CL
c1840bbe330d77b4fbfd7e69149ee50177b398364695c733c10d42cc41419c90
#ifndef _ZQ_CNN_VIDEO_FACE_DETECTION_INTERFACE_H_ #define _ZQ_CNN_VIDEO_FACE_DETECTION_INTERFACE_H_ #pragma once #include "ZQ_CNN_Net_Interface.h" #include "ZQ_CNN_BBoxUtils.h" #include "ZQ_CNN_MTCNN_Interface.h" #include "ZQ_CNN_CascadeOnet_Interface.h" #include "ZQ_CNN_FaceCropUtils.h" #include "ZQlib/ZQ_SVD.h" #include <float.h> #include <vector> namespace ZQ { template<class ZQ_CNN_Net_Interface, class ZQ_CNN_Tensor4D_Interface, class ZQ_CNN_Tensor4D_Interface_Base> class ZQ_CNN_VideoFaceDetection_Interface { using string = std::string; public: enum VFD_MSG { VFD_MSG_MAX_TRACE_NUM, VFD_MSG_WEIGHT_DECAY, VFD_MSG_FORCE_FIRST_FRAME }; ZQ_CNN_VideoFaceDetection_Interface() { max_trace_num = 4; weight_decay = 0; show_debug_info = false; enable_iou_filter = false; is_first_frame = true; thread_num = 1; has_lnet106 = false; key_cooldown = 50; } ~ZQ_CNN_VideoFaceDetection_Interface() {} private: int max_trace_num; float weight_decay; bool show_debug_info; bool enable_iou_filter; float othresh; bool is_first_frame; int thread_num; ZQ_CNN_MTCNN_Interface<ZQ_CNN_Net_Interface, ZQ_CNN_Tensor4D_Interface, ZQ_CNN_Tensor4D_Interface_Base> mtcnn; std::vector<ZQ_CNN_CascadeOnet_Interface<ZQ_CNN_Net_Interface, ZQ_CNN_Tensor4D_Interface, ZQ_CNN_Tensor4D_Interface_Base>> cascade_Onets; std::vector<ZQ_CNN_Net_Interface> onets; bool has_lnet106; std::vector<ZQ_CNN_Net_Interface> lnets106; bool has_headposegaze; std::vector<ZQ_CNN_Net_Interface> headposegaze_nets; int key_cooldown; int cur_key_cooldown; std::vector<std::vector<ZQ_CNN_BBox106> > trace; std::vector<ZQ_CNN_BBox106> backup_results; ZQ_CNN_Tensor4D_Interface input, lnet106_image; int lnet106_size; int onet_size; public: void TurnOnShowDebugInfo() { show_debug_info = true; } void TurnOffShowDebugInfo() { show_debug_info = false; } void TurnOnFilterIOU() { enable_iou_filter = true; } void TurnOffFilterIOU() { enable_iou_filter = false; } bool Init(const string& pnet_param, const string& pnet_model, const string& rnet_param, const string& rnet_model, const string& onet_param, const string& onet_model, int thread_num = 1, bool has_lnet106 = false, const string& lnet106_param = "", const std::string& lnet106_model = "", bool has_headposegaze = false, const string& headposegaze_param = "", const std::string& headposegaze_model = "") { if (!mtcnn.Init(pnet_param, pnet_model, rnet_param, rnet_model, onet_param, onet_model, thread_num, has_lnet106, lnet106_param, lnet106_model)) return false; this->thread_num = __max(1, thread_num); cascade_Onets.resize(this->thread_num); for (int i = 0; i < cascade_Onets.size(); i++) { if (!cascade_Onets[i].Init(onet_param, onet_model, onet_param, onet_model, onet_param, onet_model)) return false; } onets.resize(this->thread_num); for (int i = 0; i < onets.size(); i++) { if (!onets[i].LoadFrom(onet_param, onet_model, true, 1e-9, true)) return false; } int C, H, W; onets[0].GetInputDim(C, H, W); onet_size = H; this->has_lnet106 = has_lnet106; if (has_lnet106) { lnets106.resize(this->thread_num); for (int i = 0; i < lnets106.size(); i++) { if (!lnets106[i].LoadFrom(lnet106_param, lnet106_model, true, 1e-9, true)) return false; } int C, H, W; lnets106[0].GetInputDim(C, H, W); lnet106_size = H; } this->has_headposegaze = has_headposegaze; if (has_headposegaze) { headposegaze_nets.resize(this->thread_num); for (int i = 0; i < headposegaze_nets.size(); i++) { if (!headposegaze_nets[i].LoadFrom(headposegaze_param, headposegaze_model, true, 1e-9, true)) return false; } } return true; } void SetPara(int w, int h, int min_face_size = 60, float pthresh = 0.6, float rthresh = 0.7, float othresh = 0.7, float nms_pthresh = 0.6, float nms_rthresh = 0.7, float nms_othresh = 0.7, float scale_factor = 0.709, int pnet_overlap_thresh_count = 3, int pnet_size = 20, int pnet_stride = 4, int key_cooldown = 50) { this->key_cooldown = key_cooldown; mtcnn.SetPara(w, h, min_face_size, pthresh, rthresh, othresh, nms_pthresh, nms_rthresh, nms_othresh, scale_factor, pnet_overlap_thresh_count, pnet_size, pnet_stride, true, 1.0); this->othresh = othresh; } void Message(const VFD_MSG msg, double val) { switch (msg) { case VFD_MSG_FORCE_FIRST_FRAME: is_first_frame = true; break; case VFD_MSG_MAX_TRACE_NUM: max_trace_num = __max(0, val); break; case VFD_MSG_WEIGHT_DECAY: weight_decay = val; break; } } bool Find(const unsigned char* bgr_img, int _width, int _height, int _widthStep, std::vector<ZQ_CNN_BBox106>& results) { if (!input.ConvertFromBGR(bgr_img, _width, _height, _widthStep)) return false; results.clear(); if (is_first_frame) { mtcnn.EnableLnet(true); if (!mtcnn.Find106(input, results)) return false; _refine_landmark106(results, true); _recompute_bbox(results); int cur_box_num = results.size(); trace.clear(); trace.resize(cur_box_num); for (int i = 0; i < cur_box_num; i++) trace[i].push_back(results[i]); is_first_frame = results.size() == 0; cur_key_cooldown = key_cooldown; backup_results = results; } else { std::vector<ZQ_CNN_BBox106> results106_part1, results106_part2; std::vector<int> good_idx; std::vector<ZQ_CNN_OrderScore> orders; std::vector<ZQ_CNN_BBox106> tmp_boxes; ZQ_CNN_OrderScore tmp_order; int ori_count = 0; //static int fr_id = 0; //fr_id++; /********** Stage 1: detect around the old positions ************/ const double m_pi = 4 * atan(1.0); std::vector<ZQ_CNN_BBox106> boxes; std::vector<ZQ_CNN_BBox106> last_boxes(trace.size()); std::vector<ZQ_CNN_Tensor4D_Interface> task_images(trace.size()); std::vector<ZQ_CNN_Tensor4D_Interface> task_images_gray(trace.size()); for (int i = 0; i < trace.size(); i++) { /**************** First: L106 ******************/ float last_rot = _get_rot_of_landmark106(trace[i][0].ppoint, m_pi); float cx, cy, min_x, max_x, min_y, max_y; _get_landmark106_info(trace[i][0].ppoint, cx, cy, min_x, max_x, min_y, max_y); float cur_w = max_x - min_x; float cur_h = max_y - min_y; float cur_size = 1.15*__max(cur_w, cur_h); std::vector<float> map_x, map_y; _compute_map(cx, cy, last_rot, cur_size, cur_size, lnet106_size, lnet106_size, map_x, map_y); input.Remap(task_images[0], lnet106_size, lnet106_size, 0, 0, map_x, map_y, true, 0); task_images[0].ConvertColor_BGR2GRAY(task_images_gray[0], 1, 1); lnets106[0].Forward(task_images_gray[0]); ZQ_CNN_BBox106 tmp_box106; //const ZQ_CNN_Tensor4D_Interface_Base* keyPoint = lnets106[0].GetBlobByName("conv6-3"); const ZQ_CNN_Tensor4D_Interface_Base* keyPoint = lnets106[0].GetBlobByName("landmark_fc2/BiasAdd"); const float* keyPoint_ptr = keyPoint->GetFirstPixelPtr(); int keypoint_num = keyPoint->GetC() / 2; int keyPoint_sliceStep = keyPoint->GetSliceStep(); float cos_rot = cos(last_rot); float sin_rot = sin(last_rot); for (int num = 0; num < keypoint_num; num++) { float tmp_w = cur_size * (keyPoint_ptr[num * 2] - 0.5); float tmp_h = cur_size * (keyPoint_ptr[num * 2 + 1] - 0.5); tmp_box106.ppoint[num * 2] = cx + tmp_w*cos_rot + tmp_h*sin_rot; tmp_box106.ppoint[num * 2 + 1] = cy - tmp_w*sin_rot + tmp_h*cos_rot; } /**************** Second: Onet ******************/ float rot1 = _get_rot_of_landmark106(tmp_box106.ppoint, m_pi); _get_landmark106_info(tmp_box106.ppoint, cx, cy, min_x, max_x, min_y, max_y); cur_w = max_x - min_x; cur_h = max_y - min_y; cur_size = 1.1*__max(cur_w, cur_h); _compute_map(cx, cy, rot1, cur_size, cur_size, onet_size, onet_size, map_x, map_y); input.Remap(task_images[0], onet_size, onet_size, 0, 0, map_x, map_y, true, 0); onets[0].Forward(task_images[0]); const ZQ_CNN_Tensor4D_Interface_Base* prob = onets[0].GetBlobByName("prob1"); const float* prob_ptr = prob->GetFirstPixelPtr(); if (prob_ptr[1] < __max(0.2, othresh - 0.3)) { printf("here:lost %f\n", prob_ptr[1]); continue; } ZQ_CNN_BBox106 tmp_box; _get_landmark106_info(tmp_box106.ppoint, cx, cy, min_x, max_x, min_y, max_y); cur_w = 1.1*(max_x - min_x); cur_h = 1.1*(max_y - min_y); tmp_box.col1 = cx - 0.5*cur_w; tmp_box.col2 = cx + 0.5*cur_w; tmp_box.row1 = cy - 0.5*cur_h; tmp_box.row2 = cy + 0.5*cur_h; tmp_box.score = 2.0; tmp_box.exist = true; tmp_box106.col1 = tmp_box.col1; tmp_box106.col2 = tmp_box.col2; tmp_box106.row1 = tmp_box.row1; tmp_box106.row2 = tmp_box.row2; tmp_box106.score = tmp_box.score; tmp_box106.exist = tmp_box.exist; good_idx.push_back(i); tmp_order.score = 2.0; tmp_order.oriOrder = ori_count++; boxes.push_back(tmp_box); orders.push_back(tmp_order); results106_part1.push_back(tmp_box106); } /********** Stage 2: detect globally ************/ if (cur_key_cooldown <= 0 || results106_part1.size() == 0) { std::vector<ZQ_CNN_BBox106> tmp_boxes; cur_key_cooldown = key_cooldown; mtcnn.Find106(input, tmp_boxes); for (int j = 0; j < tmp_boxes.size(); j++) { ZQ_CNN_BBox106& cur_box = tmp_boxes[j]; float ori_area = (cur_box.col2 - cur_box.col1) * (cur_box.row2 - cur_box.row1); float valid_col1 = __max(0, cur_box.col1); float valid_col2 = __min(_width - 1, cur_box.col2); float valid_row1 = __max(0, cur_box.row1); float valid_row2 = __min(_height - 1, cur_box.row2); float valid_area = (valid_col2 - valid_col1) * (valid_row2 - valid_row1); if (valid_area < ori_area*0.95) { //printf("here\n"); continue; } //printf("here:global\n"); tmp_order.oriOrder = ori_count++; tmp_order.score = tmp_boxes[j].score; boxes.push_back(tmp_boxes[j]); orders.push_back(tmp_order); good_idx.push_back(-1); } } /********** Stage 3: nms ************/ std::vector<int> keep_orders; _nms(boxes, orders, keep_orders, 0.3, "Min"); std::vector<int> old_good_idx = good_idx; std::vector<ZQ_CNN_BBox106> old_boxes = boxes; good_idx.clear(); boxes.clear(); for (int i = 0; i < keep_orders.size(); i++) { good_idx.push_back(old_good_idx[keep_orders[i]]); if (keep_orders[i] >= results106_part1.size()) boxes.push_back(old_boxes[keep_orders[i]]); } /********** Stage 4: get 106 & 240 landmark ************/ _Lnet106_stage(boxes, results106_part2); if (true) { results106_part1.insert(results106_part1.end(), results106_part2.begin(), results106_part2.end()); _refine_landmark106(results106_part1, true); } else { _refine_landmark106(results106_part2, true); results106_part1.insert(results106_part1.end(), results106_part2.begin(), results106_part2.end()); } results.swap(results106_part1); /********** Stage 5: filtering ************/ int cur_box_num = results.size(); std::vector<std::vector<ZQ_CNN_BBox106> > old_trace(trace); trace.clear(); trace.resize(cur_box_num); for (int i = 0; i < cur_box_num; i++) { trace[i].push_back(results[i]); if (good_idx[i] >= 0) { std::vector<ZQ_CNN_BBox106>& tmp_old_trace = old_trace[good_idx[i]]; for (int j = 0; j < tmp_old_trace.size() && j < max_trace_num; j++) trace[i].push_back(tmp_old_trace[j]); } } _filtering(trace, results); if (enable_iou_filter) { //_filtering_iou(results, good_idx, backup_results); } /********** Stage 6: update bbox ************/ _recompute_bbox(results); /********** Stage 7: compute headposegaze ************/ _headposegaze_stage(results, has_headposegaze); if (results.size() == 0) is_first_frame = true; backup_results = results; } cur_key_cooldown--; return true; } private: static bool _cmp_score(const ZQ_CNN_OrderScore& lsh, const ZQ_CNN_OrderScore& rsh) { return lsh.score < rsh.score; } static void _nms(const std::vector<ZQ_CNN_BBox106> &ori_boundingBox, const std::vector<ZQ_CNN_OrderScore> &orderScore, std::vector<int>& keep_orders, const float overlap_threshold, const std::string& modelname = "Union") { std::vector<ZQ_CNN_BBox106> boundingBox = ori_boundingBox; std::vector<ZQ_CNN_OrderScore> bboxScore = orderScore; if (boundingBox.empty() || overlap_threshold >= 1.0) { return; } std::vector<int> heros; //sort the score sort(bboxScore.begin(), bboxScore.end(), _cmp_score); int order = 0; float IOU = 0; float maxX = 0; float maxY = 0; float minX = 0; float minY = 0; while (bboxScore.size() > 0) { order = bboxScore.back().oriOrder; bboxScore.pop_back(); if (order < 0)continue; heros.push_back(order); boundingBox[order].exist = false;//delete it int box_num = boundingBox.size(); for (int num = 0; num < box_num; num++) { if (boundingBox[num].exist) { //the iou maxY = __max(boundingBox[num].row1, boundingBox[order].row1); maxX = __max(boundingBox[num].col1, boundingBox[order].col1); minY = __min(boundingBox[num].row2, boundingBox[order].row2); minX = __min(boundingBox[num].col2, boundingBox[order].col2); //maxX1 and maxY1 reuse maxX = __max(minX - maxX + 1, 0); maxY = __max(minY - maxY + 1, 0); //IOU reuse for the area of two bbox IOU = maxX * maxY; float area1 = boundingBox[num].area; float area2 = boundingBox[order].area; if (!modelname.compare("Union")) IOU = IOU / (area1 + area2 - IOU); else if (!modelname.compare("Min")) { IOU = IOU / __min(area1, area2); } if (IOU > overlap_threshold) { boundingBox[num].exist = false; for (std::vector<ZQ_CNN_OrderScore>::iterator it = bboxScore.begin(); it != bboxScore.end(); it++) { if ((*it).oriOrder == num) { (*it).oriOrder = -1; break; } } } } } } for (int i = 0; i < heros.size(); i++) { boundingBox[heros[i]].exist = true; } //clear exist= false; for (int i = boundingBox.size() - 1; i >= 0; i--) { if (!boundingBox[i].exist) { boundingBox.erase(boundingBox.begin() + i); } } keep_orders = heros; } bool _Lnet106_stage(std::vector<ZQ_CNN_BBox106>& thirdBbox, std::vector<ZQ_CNN_BBox106>& resultBbox) { double t4 = omp_get_wtime(); std::vector<ZQ_CNN_BBox106> fourthBbox; std::vector<ZQ_CNN_BBox106>::iterator it = thirdBbox.begin(); std::vector<int> src_off_x, src_off_y, src_rect_w, src_rect_h; int l_count = 0; for (; it != thirdBbox.end(); it++) { if ((*it).exist) { int off_x = it->col1; int off_y = it->row1; int rect_w = it->col2 - off_x; int rect_h = it->row2 - off_y; l_count++; fourthBbox.push_back(*it); } } std::vector<ZQ_CNN_BBox106> copy_fourthBbox = fourthBbox; ZQ_CNN_BBoxUtils::_square_bbox(copy_fourthBbox, input.GetW(), input.GetH()); for (it = copy_fourthBbox.begin(); it != copy_fourthBbox.end(); ++it) { int off_x = it->col1; int off_y = it->row1; int rect_w = it->col2 - off_x; int rect_h = it->row2 - off_y; src_off_x.push_back(off_x); src_off_y.push_back(off_y); src_rect_w.push_back(rect_w); src_rect_h.push_back(rect_h); } int batch_size = 1; int per_num = ceil((float)l_count / thread_num); int need_thread_num = thread_num; if (per_num > batch_size) { need_thread_num = ceil((float)l_count / batch_size); per_num = batch_size; } std::vector<ZQ_CNN_Tensor4D_Interface> task_lnet_images(need_thread_num); std::vector<ZQ_CNN_Tensor4D_Interface> task_lnet_images_gray(need_thread_num); std::vector<std::vector<int> > task_src_off_x(need_thread_num); std::vector<std::vector<int> > task_src_off_y(need_thread_num); std::vector<std::vector<int> > task_src_rect_w(need_thread_num); std::vector<std::vector<int> > task_src_rect_h(need_thread_num); std::vector<std::vector<ZQ_CNN_BBox106> > task_fourthBbox(need_thread_num); for (int i = 0; i < need_thread_num; i++) { int st_id = per_num*i; int end_id = __min(l_count, per_num*(i + 1)); int cur_num = end_id - st_id; if (cur_num > 0) { task_src_off_x[i].resize(cur_num); task_src_off_y[i].resize(cur_num); task_src_rect_w[i].resize(cur_num); task_src_rect_h[i].resize(cur_num); task_fourthBbox[i].resize(cur_num); for (int j = 0; j < cur_num; j++) { task_src_off_x[i][j] = src_off_x[st_id + j]; task_src_off_y[i][j] = src_off_y[st_id + j]; task_src_rect_w[i][j] = src_rect_w[st_id + j]; task_src_rect_h[i][j] = src_rect_h[st_id + j]; task_fourthBbox[i][j].col1 = copy_fourthBbox[st_id + j].col1; task_fourthBbox[i][j].col2 = copy_fourthBbox[st_id + j].col2; task_fourthBbox[i][j].row1 = copy_fourthBbox[st_id + j].row1; task_fourthBbox[i][j].row2 = copy_fourthBbox[st_id + j].row2; task_fourthBbox[i][j].area = copy_fourthBbox[st_id + j].area; task_fourthBbox[i][j].score = copy_fourthBbox[st_id + j].score; task_fourthBbox[i][j].exist = copy_fourthBbox[st_id + j].exist; } } } resultBbox.resize(l_count); for (int i = 0; i < l_count; i++) { resultBbox[i].col1 = fourthBbox[i].col1; resultBbox[i].col2 = fourthBbox[i].col2; resultBbox[i].row1 = fourthBbox[i].row1; resultBbox[i].row2 = fourthBbox[i].row2; resultBbox[i].score = fourthBbox[i].score; resultBbox[i].exist = fourthBbox[i].exist; resultBbox[i].area = fourthBbox[i].area; } for (int pp = 0; pp < need_thread_num; pp++) { if (task_src_off_x[pp].size() == 0) continue; if (!input.ResizeBilinearRect(task_lnet_images[pp], lnet106_size, lnet106_size, 0, 0, task_src_off_x[pp], task_src_off_y[pp], task_src_rect_w[pp], task_src_rect_h[pp])) { continue; } if (!task_lnet_images[pp].ConvertColor_BGR2GRAY(task_lnet_images_gray[pp], 1, 1)) { continue; } task_lnet_images_gray[pp].MulScalar(128.0f); task_lnet_images_gray[pp].AddScalar(127.5f); double t31 = omp_get_wtime(); lnets106[0].Forward(task_lnet_images_gray[pp]); double t32 = omp_get_wtime(); //const ZQ_CNN_Tensor4D_Interface_Base* keyPoint = lnets106[0].GetBlobByName("conv6-3"); const ZQ_CNN_Tensor4D_Interface_Base* keyPoint = lnets106[0].GetBlobByName("landmark_fc2/BiasAdd"); const float* keyPoint_ptr = keyPoint->GetFirstPixelPtr(); int keypoint_num = keyPoint->GetC() / 2; int keyPoint_sliceStep = keyPoint->GetSliceStep(); for (int i = 0; i < task_fourthBbox[pp].size(); i++) { for (int num = 0; num < keypoint_num; num++) { if ((num >= 33 && num < 43) || (num >= 64 && num < 72) || (num >= 84 && num < 104)) { task_fourthBbox[pp][i].ppoint[num * 2] = task_fourthBbox[pp][i].col1 + (task_fourthBbox[pp][i].col2 - task_fourthBbox[pp][i].col1)*keyPoint_ptr[i*keyPoint_sliceStep + num * 2]/**0.25*/; task_fourthBbox[pp][i].ppoint[num * 2 + 1] = task_fourthBbox[pp][i].row1 + (task_fourthBbox[pp][i].row2 - task_fourthBbox[pp][i].row1)*keyPoint_ptr[i*keyPoint_sliceStep + num * 2 + 1]/**0.25*/; } else { task_fourthBbox[pp][i].ppoint[num * 2] = task_fourthBbox[pp][i].col1 + (task_fourthBbox[pp][i].col2 - task_fourthBbox[pp][i].col1)*keyPoint_ptr[i*keyPoint_sliceStep + num * 2]; task_fourthBbox[pp][i].ppoint[num * 2 + 1] = task_fourthBbox[pp][i].row1 + (task_fourthBbox[pp][i].row2 - task_fourthBbox[pp][i].row1)*keyPoint_ptr[i*keyPoint_sliceStep + num * 2 + 1]; } } } } int count = 0; for (int i = 0; i < need_thread_num; i++) { count += task_fourthBbox[i].size(); } resultBbox.resize(count); int id = 0; for (int i = 0; i < need_thread_num; i++) { for (int j = 0; j < task_fourthBbox[i].size(); j++) { memcpy(resultBbox[id].ppoint, task_fourthBbox[i][j].ppoint, sizeof(float) * 212); id++; } } double t5 = omp_get_wtime(); if (show_debug_info) printf("run Lnet [%d] times \n", l_count); if (show_debug_info) printf("stage 4: cost %.3f ms\n", 1000 * (t5 - t4)); return true; } bool _refine_landmark106(std::vector<ZQ_CNN_BBox106>& resultBbox, bool refine_lnet106) { if (!refine_lnet106) return true; const double m_pi = atan(1.0) * 4; double t1 = omp_get_wtime(); std::vector<ZQ_CNN_Tensor4D_Interface> task_lnet_images(thread_num); std::vector<ZQ_CNN_Tensor4D_Interface> task_lnet_images_gray(thread_num); for (int pp = 0; pp < resultBbox.size(); pp++) { float min_x, max_x, min_y, max_y, cx, cy; _get_landmark106_info(resultBbox[pp].ppoint, cx, cy, min_x, max_x, min_y, max_y); float cur_w = max_x - min_x; float cur_h = max_y - min_y; float cur_size = 1.2*__max(cur_w, cur_h); float half_size = ceil(0.5*cur_size); //get rot of 106 landmark float cur_rot = _get_rot_of_landmark106(resultBbox[pp].ppoint, m_pi); // compute map std::vector<float> map_x, map_y; _compute_map(cx, cy, cur_rot, cur_size, cur_size, lnet106_size, lnet106_size, map_x, map_y); if (!input.Remap(task_lnet_images[0], lnet106_size, lnet106_size, 0, 0, map_x, map_y, true, 0)) { continue; } task_lnet_images[0].ConvertColor_BGR2GRAY(task_lnet_images_gray[0], 1, 1); task_lnet_images_gray[0].MulScalar(128.0f); task_lnet_images_gray[0].AddScalar(127.5f); lnets106[0].Forward(task_lnet_images_gray[0]); //const ZQ_CNN_Tensor4D* keyPoint = lnets106[0].GetBlobByName("conv6-3"); const ZQ_CNN_Tensor4D_Interface_Base* keyPoint = lnets106[0].GetBlobByName("landmark_fc2/BiasAdd"); const float* keyPoint_ptr = keyPoint->GetFirstPixelPtr(); int keypoint_num = keyPoint->GetC() / 2; int keyPoint_sliceStep = keyPoint->GetSliceStep(); float cos_rot = cos(cur_rot); float sin_rot = sin(cur_rot); for (int num = 0; num < keypoint_num; num++) { float tmp_w = cur_size * (keyPoint_ptr[num * 2] - 0.5); float tmp_h = cur_size * (keyPoint_ptr[num * 2 + 1] - 0.5); resultBbox[pp].ppoint[num * 2] = cx + tmp_w*cos_rot + tmp_h*sin_rot; resultBbox[pp].ppoint[num * 2 + 1] = cy - tmp_w*sin_rot + tmp_h*cos_rot; } } double t2 = omp_get_wtime(); if (show_debug_info) printf("run refine_Lnet [%d] times, cost %.3f ms\n", resultBbox.size(), 1000 * (t2 - t1)); return true; } bool _headposegaze_stage(std::vector<ZQ_CNN_BBox106>& resultBbox, bool enable_headposegaze) { if (!enable_headposegaze) { for (int i = 0; i < resultBbox.size(); i++) resultBbox[i].has_headposegaze = false; return true; } double t1 = omp_get_wtime(); std::vector<ZQ_CNN_Tensor4D_Interface> task_hpg_images(thread_num); std::vector<ZQ_CNN_Tensor4D_Interface> task_hpg_images_gray(thread_num); for (int pp = 0; pp < resultBbox.size(); pp++) { const float* cur_pts = resultBbox[pp].ppoint; //5 points float face5pts[10] = { 0.5f*(cur_pts[72 * 2 + 0] + cur_pts[73 * 2 + 0]), //left eye cx (left of image) 0.5f*(cur_pts[72 * 2 + 1] + cur_pts[73 * 2 + 1]), //left eye cy (left of image) 0.5f*(cur_pts[75 * 2 + 0] + cur_pts[76 * 2 + 0]), //right eye cx (right of image) 0.5f*(cur_pts[75 * 2 + 1] + cur_pts[76 * 2 + 1]), //right eye cy (right of image) cur_pts[46 * 2 + 0], //nose x cur_pts[46 * 2 + 1], //nose y cur_pts[84 * 2 + 0], //left mouth corner x (left of image) cur_pts[84 * 2 + 1], //left mouth corner y (left of image) cur_pts[90 * 2 + 0], //right mouth corner x (right of image) cur_pts[90 * 2 + 1] //right mouth corner y (right of image) }; float transform[6]; ZQ_CNN_FaceCropUtils::CropImage_112x112_translate_scale_roll(input, face5pts, task_hpg_images[pp], transform, -1); float sc = transform[0]; float ss = transform[1]; float tx = transform[2]; float ty = transform[5]; float rot = atan2(ss, sc); resultBbox[pp].center_and_rot[0] = tx; resultBbox[pp].center_and_rot[1] = ty; resultBbox[pp].center_and_rot[2] = rot; task_hpg_images[pp].ConvertColor_BGR2GRAY(task_hpg_images_gray[pp],1,1); task_hpg_images_gray[pp].MulScalar(128.0f); task_hpg_images_gray[pp].AddScalar(127.5f); headposegaze_nets[0].Forward(task_hpg_images_gray[0]); const ZQ_CNN_Tensor4D_Interface_Base* hpg = headposegaze_nets[0].GetBlobByName("headposegaze_fc3/BiasAdd"); const float* hpg_ptr = hpg->GetFirstPixelPtr(); memcpy(resultBbox[pp].headposegaze, hpg_ptr, sizeof(float) * 9); resultBbox[pp].has_headposegaze = true; } double t2 = omp_get_wtime(); if (show_debug_info) printf("run headposegaze_stage [%d] times, cost %.3f ms\n", resultBbox.size(), 1000 * (t2 - t1)); return true; } void _filtering(const std::vector<std::vector<ZQ_CNN_BBox106> >& trace, std::vector<ZQ_CNN_BBox106>& results) { float reproj_coords[212]; for (int i = 0; i < results.size(); i++) { const std::vector<ZQ_CNN_BBox106>& cur_trace = trace[i]; results[i] = cur_trace[0]; const ZQ_CNN_BBox106& cur_box = trace[i][0]; const float ori_thresh_L1 = 0.01f; const float ori_thresh_L2 = 0.01f; const float ori_thresh_Linf = 0.015f; const float reproj_thresh_L1 = 0.005f; const float reproj_thresh_L2 = 0.005f; const float reproj_thresh_Linf = 0.008f; float box_len_sum = cur_box.col2 - cur_box.col1 + cur_box.row2 - cur_box.row1; float real_ori_thresh_L1 = ori_thresh_L1*box_len_sum; float real_ori_thresh_L2 = ori_thresh_L2*box_len_sum; float real_ori_thresh_Linf = ori_thresh_Linf*box_len_sum; float real_thresh_L1 = reproj_thresh_L1*box_len_sum; float real_thresh_L2 = reproj_thresh_L2*box_len_sum; float real_thresh_Linf = reproj_thresh_Linf*box_len_sum; float sum_weight = 1.0f; int cur_trace_len = cur_trace.size(); if (cur_trace_len <= 1) continue; for (int j = 1; j < cur_trace_len; j++) { double ori_dis_L2 = 0; double ori_dis_L1 = 0; double ori_dis_Linf = 0; double reproj_err_L2 = 0; double reproj_err_L1 = 0; double reproj_err_Linf = 0; float last_weight = exp(-weight_decay*j); const ZQ_CNN_BBox106& last_box = trace[i][j]; _compute_transform(last_box.ppoint, cur_box.ppoint, ori_dis_L2, ori_dis_L1, ori_dis_Linf, reproj_err_L2, reproj_err_L1, reproj_err_Linf, reproj_coords); if (ori_dis_L2 < real_ori_thresh_L2 && ori_dis_L1 < real_ori_thresh_L1 && ori_dis_Linf < real_ori_thresh_Linf && reproj_err_L2 < real_thresh_L2 && reproj_err_L1 < real_thresh_L1 && reproj_err_Linf < real_thresh_Linf) { //printf("[%d,%d]reproj_err_ratio = %5.2f,%5.2f,%5.2f\n", i, j, reproj_err_L2 / real_thresh_L2, // reproj_err_L1 / real_thresh_L1, reproj_err_Linf / real_thresh_Linf); for (int j = 0; j < 212; j++) { results[i].ppoint[j] += last_box.ppoint[j] * last_weight; } sum_weight += last_weight; } else { //printf("reproj_err = %f\n", reproj_err); } } for (int j = 0; j < 212; j++) { results[i].ppoint[j] /= sum_weight; } } } void _compute_transform(const float last_pts[], const float cur_pts[], double& ori_dis_L2, double& ori_dis_L1, double& ori_dis_Linf, double& reproj_err_L2, double& reproj_err_L1, double& reproj_err_Linf, float reproj_coords[]) { ZQ_Matrix<double> A(212, 6), b(212, 1), x(6, 1); for (int i = 0; i < 106; i++) { A.SetData(i * 2, 0, last_pts[i * 2]); A.SetData(i * 2, 1, last_pts[i * 2 + 1]); A.SetData(i * 2, 4, 1); b.SetData(i * 2, 0, cur_pts[i * 2]); A.SetData(i * 2 + 1, 2, last_pts[i * 2]); A.SetData(i * 2 + 1, 3, last_pts[i * 2 + 1]); A.SetData(i * 2 + 1, 5, 1); b.SetData(i * 2 + 1, 0, cur_pts[i * 2 + 1]); } if (!ZQ_SVD::Solve(A, x, b)) { ori_dis_L2 = FLT_MAX; ori_dis_L1 = FLT_MAX; ori_dis_Linf = FLT_MAX; reproj_err_L2 = FLT_MAX; reproj_err_L1 = FLT_MAX; reproj_err_Linf = FLT_MAX; } else { bool flag; float R[4], T[2]; R[0] = x.GetData(0, 0, flag); R[1] = x.GetData(1, 0, flag); R[2] = x.GetData(2, 0, flag); R[3] = x.GetData(3, 0, flag); T[0] = x.GetData(4, 0, flag); T[1] = x.GetData(5, 0, flag); ori_dis_L2 = 0; ori_dis_L1 = 0; ori_dis_Linf = 0; reproj_err_L2 = 0; reproj_err_L1 = 0; reproj_err_Linf = 0; for (int i = 0; i < 106; i++) { reproj_coords[i * 2 + 0] = last_pts[i * 2 + 0] * R[0] + last_pts[i * 2 + 1] * R[1] + T[0]; reproj_coords[i * 2 + 1] = last_pts[i * 2 + 0] * R[2] + last_pts[i * 2 + 1] * R[3] + T[1]; double dis_x = fabs(reproj_coords[i * 2 + 0] - cur_pts[i * 2 + 0]); double dis_y = fabs(reproj_coords[i * 2 + 1] - cur_pts[i * 2 + 1]); reproj_err_L1 += dis_x + dis_y; reproj_err_L2 += dis_x*dis_x + dis_y*dis_y; reproj_err_Linf = __max(reproj_err_Linf, __max(dis_x, dis_y)); double ori_dis_x = fabs(last_pts[i * 2 + 0] - cur_pts[i * 2 + 0]); double ori_dis_y = fabs(last_pts[i * 2 + 1] - cur_pts[i * 2 + 1]); ori_dis_L1 += ori_dis_x + ori_dis_y; ori_dis_L2 += ori_dis_x*ori_dis_x + ori_dis_y*ori_dis_y; ori_dis_Linf = __max(ori_dis_Linf, __max(ori_dis_x, ori_dis_y)); } reproj_err_L1 /= 212.0; reproj_err_L2 = sqrt(reproj_err_L2 / 212.0); ori_dis_L1 /= 212.0; ori_dis_L2 = sqrt(ori_dis_L2 / 212.0); } } void _filtering_iou(std::vector<ZQ_CNN_BBox106>& results, const std::vector<int>& good_idx, const std::vector<ZQ_CNN_BBox106>& backup_results) { const float thresh = 1.0f; int last_num = backup_results.size(); for (int bb = 0; bb < results.size(); bb++) { int last_id = good_idx[bb]; if (last_id >= 0) { bool flag = true; for (int k = 0; k < 212; k++) { if (fabs(results[bb].ppoint[k] - backup_results[last_id].ppoint[k]) > thresh) { flag = false; break; } } if (flag) results[bb] = backup_results[last_id]; } } } void _recompute_bbox(std::vector<ZQ_CNN_BBox106>& boxes) { for (int i = 0; i < boxes.size(); i++) { float xmin = FLT_MAX; float ymin = FLT_MAX; float xmax = -FLT_MAX; float ymax = -FLT_MAX; float cx, cy, max_side; for (int j = 0; j < 106; j++) { float* coords = boxes[i].ppoint; xmin = __min(xmin, coords[j * 2]); xmax = __max(xmax, coords[j * 2]); ymin = __min(ymin, coords[j * 2 + 1]); ymax = __max(ymax, coords[j * 2 + 1]); } cx = 0.5*(xmin + xmax); cy = 0.5*(ymin + ymax); max_side = __max((xmax - xmin), (ymax - ymin)); xmin = round(cx - 0.5*max_side); xmax = round(cx + 0.5*max_side); ymin = round(cy - 0.5*max_side); ymax = round(cy + 0.5*max_side); boxes[i].col1 = xmin; boxes[i].col2 = xmax; boxes[i].row1 = ymin; boxes[i].row2 = ymax; boxes[i].area = (xmax - xmin)*(ymax - ymin); } } static float _get_rot_of_landmark106(const float* pp, double m_pi) { float eye_cx = 0.25*(pp[52 * 2 + 0] + pp[55 * 2 + 0] + pp[58 * 2 + 0] + pp[61 * 2 + 0]); float eye_cy = 0.25*(pp[52 * 2 + 1] + pp[55 * 2 + 1] + pp[58 * 2 + 1] + pp[61 * 2 + 1]); float mouth_cx = 0.25*(pp[84 * 2 + 0] + pp[96 * 2 + 0] + pp[100 * 2 + 0] + pp[90 * 2 + 0]); float mouth_cy = 0.25*(pp[84 * 2 + 1] + pp[96 * 2 + 1] + pp[100 * 2 + 1] + pp[90 * 2 + 1]); float dir_x = mouth_cx - eye_cx; float dir_y = mouth_cy - eye_cy; float init_rot = 0.5*m_pi - atan2(dir_y, dir_x); return init_rot; } static void _get_landmark106_info(const float* pp, float& cx, float& cy, float& min_x, float& max_x, float& min_y, float& max_y) { min_x = FLT_MAX; min_y = FLT_MAX; max_x = -FLT_MAX; max_y = -FLT_MAX; for (int i = 0; i < 106; i++) { min_x = __min(min_x, pp[i * 2]); max_x = __max(max_x, pp[i * 2]); min_y = __min(min_y, pp[i * 2 + 1]); max_y = __max(max_y, pp[i * 2 + 1]); } cx = 0.5*(min_x + max_x); cy = 0.5*(min_y + max_y); } static void _compute_map(float cx, float cy, float rot, float cur_size_w, float cur_size_h, int dst_W, int dst_H, std::vector<float>& map_x, std::vector<float>& map_y) { map_x.resize(dst_H*dst_W); map_y.resize(dst_H*dst_W); float half_net_size_W = (dst_W - 1) / 2.0; float half_net_size_H = (dst_H - 1) / 2.0; float sin_rot = sin(rot); float cos_rot = cos(rot); float step_w = cur_size_w / dst_W; float step_h = cur_size_h / dst_H; for (int h = 0; h < dst_H; h++) { for (int w = 0; w < dst_W; w++) { map_x[h*dst_W + w] = cx + (w - half_net_size_W)*step_w*cos_rot + (h - half_net_size_H)*step_h*sin_rot; map_y[h*dst_W + w] = cy - (w - half_net_size_W)*step_w*sin_rot + (h - half_net_size_H)*step_h*cos_rot; } } } }; } #endif
C++
CL
c678920119a1283fd4df7d3956874e975bf24c1037f3be87b95c42fb58824f5a
#include "send_break.h" #include "c_types.h" #include "eagle_soc.h" #include "uart_register.h" #include "Arduino.h" // More detailled information on the DMX protocol can be found on // http://www.erwinrol.com/dmx512/ // https://erg.abdn.ac.uk/users/gorry/eg3576/DMX-frame.html // there are two different implementations, both should work #define USE_SERIAL_BREAK /* UART for DMX output */ #define SEROUT_UART 1 /* DMX minimum timings per E1.11 */ #define DMX_BREAK 92 #define DMX_MAB 12 void sendBreak() { #ifdef USE_SERIAL_BREAK // switch to another baud rate, see https://forum.arduino.cc/index.php?topic=382040.0 Serial1.flush(); Serial1.begin(90000, SERIAL_8N2); while(Serial1.available()) Serial1.read(); // send the break as a "slow" byte Serial1.write(0); // switch back to the original baud rate Serial1.flush(); Serial1.begin(250000, SERIAL_8N2); while(Serial1.available()) Serial1.read(); #else // send break using low-level code SET_PERI_REG_MASK(UART_CONF0(SEROUT_UART), UART_TXD_BRK); delayMicroseconds(DMX_BREAK); CLEAR_PERI_REG_MASK(UART_CONF0(SEROUT_UART), UART_TXD_BRK); delayMicroseconds(DMX_MAB); #endif }
C++
CL
1e84737f5e41d52304ccdb2f8918900acac699974aaf7783c798f246f2d9f590
//-------------------------------------------------------------------------------- // // ウインドウ表示プログラム // Author : Xu Wenjie // Date : 2016-04-26 //-------------------------------------------------------------------------------- // Update : // //-------------------------------------------------------------------------------- #include "main.h" #include "UI_mainball.h" //-------------------------------------------------------------------------------- // 定数定義 //-------------------------------------------------------------------------------- #define UI_MAIN_BALL_RADIUS (13.0f)//ボールの半径 #define UI_MAIN_BALL_TEXTURENAME "data/TEXTURE/circle.png"//ファイル名 #define UI_MAIN_BALL_ALPHA_MAX (1.0f) #define UI_MAIN_BALL_COUNT_MAX (30) #define NUM_LIFE (3) //-------------------------------------------------------------------------------- // 構造体定義 //-------------------------------------------------------------------------------- typedef struct { D3DXVECTOR3 vPos;//中心点 float fAlpha;//アルファ値 int nCnt;//動画カウンター }UI_MAIN_BALL; //-------------------------------------------------------------------------------- // プロトタイプ宣言 //-------------------------------------------------------------------------------- HRESULT MakeVerTexUIMainBall(LPDIRECT3DDEVICE9 pDevice); //-------------------------------------------------------------------------------- // グローバル変数 //-------------------------------------------------------------------------------- LPDIRECT3DTEXTURE9 g_pTextureUIMainBall = NULL;//textureインターフェース LPDIRECT3DVERTEXBUFFER9 g_pVtxBufferUIMainBall = NULL;//頂点バッファ管理インターフェースポインタ UI_MAIN_BALL g_aUIMainBall[NUM_LIFE]; //-------------------------------------------------------------------------------- // 初期化処理 //-------------------------------------------------------------------------------- void InitUIMainBall(void) { LPDIRECT3DDEVICE9 pDevice = GetDevice();//デバイス取得 for (int nCnt = 0; nCnt < NUM_LIFE; nCnt++) { g_aUIMainBall[nCnt].fAlpha = 0.0f; g_aUIMainBall[nCnt].nCnt = 0; } //set ball pos g_aUIMainBall[0].vPos = D3DXVECTOR3(552.0f, 97.0f, 0.0f);//one g_aUIMainBall[1].vPos = D3DXVECTOR3(597.0f, 97.0f, 0.0f);//two g_aUIMainBall[2].vPos = D3DXVECTOR3(642.0f, 97.0f, 0.0f);//three if (FAILED(MakeVerTexUIMainBall(pDevice)))//textureポインタへのポインタ { MessageBox(NULL, "MakeVerTexUI ERROR!!", "エラー", MB_OK | MB_ICONWARNING); } //ハードディスクからTextureの読み込み //※エラーチェック必須 if (FAILED(D3DXCreateTextureFromFile(pDevice, UI_MAIN_BALL_TEXTURENAME, &g_pTextureUIMainBall)))//textureポインタへのポインタ { MessageBox(NULL, "D3DXCreateUITextureFromFile ERROR!!", "エラー", MB_OK | MB_ICONWARNING); } } //-------------------------------------------------------------------------------- // 終了処理 //-------------------------------------------------------------------------------- void UninitUIMainBall(void) { if (g_pVtxBufferUIMainBall != NULL) { g_pVtxBufferUIMainBall->Release(); g_pVtxBufferUIMainBall = NULL; } if (g_pTextureUIMainBall != NULL) { g_pTextureUIMainBall->Release(); g_pTextureUIMainBall = NULL; } } //-------------------------------------------------------------------------------- // 更新処理 //-------------------------------------------------------------------------------- void UpdateUIMainBall(void) { VERTEX_2D *pVtx = NULL; g_pVtxBufferUIMainBall->Lock(0, 0, (void**)&pVtx, 0); for (int nCnt = 0; nCnt < NUM_LIFE; nCnt++) { if (g_aUIMainBall[nCnt].nCnt != 0) { g_aUIMainBall[nCnt].nCnt--; g_aUIMainBall[nCnt].fAlpha = (float)(UI_MAIN_BALL_COUNT_MAX - g_aUIMainBall[nCnt].nCnt) / (float)UI_MAIN_BALL_COUNT_MAX * UI_MAIN_BALL_ALPHA_MAX; } //頂点カラーの設定 pVtx[nCnt * 4 + 0].color = D3DXCOLOR(0.1f, 0.1f, 0.1f, g_aUIMainBall[nCnt].fAlpha); pVtx[nCnt * 4 + 1].color = D3DXCOLOR(0.1f, 0.1f, 0.1f, g_aUIMainBall[nCnt].fAlpha); pVtx[nCnt * 4 + 2].color = D3DXCOLOR(0.1f, 0.1f, 0.1f, g_aUIMainBall[nCnt].fAlpha); pVtx[nCnt * 4 + 3].color = D3DXCOLOR(0.1f, 0.1f, 0.1f, g_aUIMainBall[nCnt].fAlpha); } g_pVtxBufferUIMainBall->Unlock(); } //-------------------------------------------------------------------------------- // 描画処理 //-------------------------------------------------------------------------------- void DrawUIMainBall(void) { LPDIRECT3DDEVICE9 pDevice = GetDevice();//デバイス取得 pDevice->SetStreamSource( 0,//ストリーム番号 g_pVtxBufferUIMainBall, 0,//オフセット(開始位置) sizeof(VERTEX_2D));//ストライド量 //頂点フォーマットの設定 pDevice->SetFVF(FVF_VERTEX_2D); //Textureの設定 pDevice->SetTexture(0, g_pTextureUIMainBall); for (int nCnt = 0; nCnt < NUM_LIFE; nCnt++) { //プリミティブ描画 pDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, nCnt * 4,//オフセット(頂点数) NUM_POLYGON); } } //-------------------------------------------------------------------------------- // 頂点の作成 //-------------------------------------------------------------------------------- HRESULT MakeVerTexUIMainBall(LPDIRECT3DDEVICE9 pDevice) { if (FAILED(pDevice->CreateVertexBuffer( sizeof(VERTEX_2D) * NUM_VERTEX * NUM_LIFE,//作成したい頂点バッファのサイズ D3DUSAGE_WRITEONLY,//頂点バッファの使用方法 FVF_VERTEX_2D,//書かなくても大丈夫 D3DPOOL_MANAGED,//メモリ管理方法(managed:デバイスにお任せ) &g_pVtxBufferUIMainBall,// NULL// ))) { return E_FAIL; } //仮想アドレスを取得するためのポインタ VERTEX_2D *pVtx; //頂点バッファをロックして、仮想アドレスを取得する g_pVtxBufferUIMainBall->Lock( 0,//範囲 0,//範囲 (void**)&pVtx,//アドレスが書かれたメモ帳のアドレス 0); for (int nCnt = 0; nCnt < NUM_LIFE; nCnt++) { //頂点座標の設定(2D座標、右回り) pVtx[nCnt * 4 + 0].pos = D3DXVECTOR3(g_aUIMainBall[nCnt].vPos.x - UI_MAIN_BALL_RADIUS, g_aUIMainBall[nCnt].vPos.y - UI_MAIN_BALL_RADIUS, 0.0f); pVtx[nCnt * 4 + 1].pos = D3DXVECTOR3(g_aUIMainBall[nCnt].vPos.x + UI_MAIN_BALL_RADIUS, g_aUIMainBall[nCnt].vPos.y - UI_MAIN_BALL_RADIUS, 0.0f); pVtx[nCnt * 4 + 2].pos = D3DXVECTOR3(g_aUIMainBall[nCnt].vPos.x - UI_MAIN_BALL_RADIUS, g_aUIMainBall[nCnt].vPos.y + UI_MAIN_BALL_RADIUS, 0.0f); pVtx[nCnt * 4 + 3].pos = D3DXVECTOR3(g_aUIMainBall[nCnt].vPos.x + UI_MAIN_BALL_RADIUS, g_aUIMainBall[nCnt].vPos.y + UI_MAIN_BALL_RADIUS, 0.0f); //rhwの設定(必ず1.0f) pVtx[nCnt * 4 + 0].rhw = 1.0f; pVtx[nCnt * 4 + 1].rhw = 1.0f; pVtx[nCnt * 4 + 2].rhw = 1.0f; pVtx[nCnt * 4 + 3].rhw = 1.0f; //頂点カラーの設定 pVtx[nCnt * 4 + 0].color = D3DXCOLOR(0.1f, 0.1f, 0.1f, g_aUIMainBall[nCnt].fAlpha); pVtx[nCnt * 4 + 1].color = D3DXCOLOR(0.1f, 0.1f, 0.1f, g_aUIMainBall[nCnt].fAlpha); pVtx[nCnt * 4 + 2].color = D3DXCOLOR(0.1f, 0.1f, 0.1f, g_aUIMainBall[nCnt].fAlpha); pVtx[nCnt * 4 + 3].color = D3DXCOLOR(0.1f, 0.1f, 0.1f, g_aUIMainBall[nCnt].fAlpha); //texture頂点 pVtx[nCnt * 4 + 0].tex = D3DXVECTOR2(0.0f, 0.0f); pVtx[nCnt * 4 + 1].tex = D3DXVECTOR2(1.0f, 0.0f); pVtx[nCnt * 4 + 2].tex = D3DXVECTOR2(0.0f, 1.0f); pVtx[nCnt * 4 + 3].tex = D3DXVECTOR2(1.0f, 1.0f); } //仮想アドレス解放 g_pVtxBufferUIMainBall->Unlock(); return S_OK; } //-------------------------------------------------------------------------------- // UI Cnt設定 //-------------------------------------------------------------------------------- void SetUIMainBallCnt(int nNumBall) { g_aUIMainBall[nNumBall].nCnt = UI_MAIN_BALL_COUNT_MAX; }
C++
CL
a5cbfa490a4c869dacfbb3f90f76bbf6b78b95f98795524fc1a34c0b38e16d15
#include "pch.h" #include "App/Log.h" #include <crtdbg.h> // STATIC_DATA (pod) static long s_staticMemAlloc = 0; ff::ScopeStaticMemAlloc::ScopeStaticMemAlloc() { LockMutex crit(GCS_MEM_ALLOC); if (++s_staticMemAlloc == 1) { _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) & ~_CRTDBG_ALLOC_MEM_DF); } assert(s_staticMemAlloc >= 1); } ff::ScopeStaticMemAlloc::~ScopeStaticMemAlloc() { LockMutex crit(GCS_MEM_ALLOC); if (!--s_staticMemAlloc) { _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_ALLOC_MEM_DF); } assert(s_staticMemAlloc >= 0); } ff::AtScopeClose::AtScopeClose(std::function<void()> func) : _func(func) { } ff::AtScopeClose::~AtScopeClose() { _func(); } void ff::AtScopeClose::Close() { _func(); _func = [](){}; } #ifdef _DEBUG // Keep CRT memory usage statistics static size_t s_totalAlloc = 0; static size_t s_curAlloc = 0; static size_t s_maxAlloc = 0; static size_t s_allocCount = 0; static int CrtAllocHook( int allocType, void *userData, size_t size, int blockType, long requestNumber, const unsigned char *filename, int lineNumber) { // don't call any CRT functions when blockType == _CRT_BLOCK switch(allocType) { case _HOOK_ALLOC: case _HOOK_REALLOC: { ff::LockMutex crit(ff::GCS_MEM_ALLOC_HOOK); s_allocCount++; s_totalAlloc += size; s_curAlloc += size; s_maxAlloc = std::max(s_curAlloc, s_maxAlloc); } break; case _HOOK_FREE: { ff::LockMutex crit(ff::GCS_MEM_ALLOC_HOOK); size = _msize(userData); s_curAlloc = (size > s_curAlloc) ? 0 : s_curAlloc - size; } break; } return TRUE; } #endif // _DEBUG void ff::HookCrtMemAlloc() { _CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF | _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG)); _CrtSetAllocHook(CrtAllocHook); } void ff::UnhookCrtMemAlloc() { _CrtSetAllocHook(nullptr); #ifdef _DEBUG Log::DebugTraceF(L"- DUMPING MEMORY ALLOCATION STATS ---------------------\n"); Log::DebugTraceF(L" Number of allocations: %lu\n", s_allocCount); Log::DebugTraceF(L" Total allocated bytes: %lu\n", s_totalAlloc); Log::DebugTraceF(L" Max simultaneous bytes: %lu\n", s_maxAlloc); Log::DebugTraceF(L"- completed memory dumping ----------------------------\n\n"); #endif }
C++
CL
737f003dce18e42404c144bd23b9ebdeda0d21dd6621ac31363f6f227951b15a
/* * The MIT License * * Copyright 2014 Robxley. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "Mesh.hpp" #include "Logger.hpp" #include "Common.hpp" #include "Assertion.hpp" #include <algorithm> namespace BH3D { Mesh::~Mesh() { Destroy(); } bool Mesh::AddSubMesh(std::size_t _nFaces, const unsigned int *_ptFaces, std::size_t _nVertices, const float * _ptPositions, const float * _ptTexCoords, char _textureFormat, const float * _ptNormals, const float *_ptColors, char _colorFormat, const Material *_pMaterial) { if (!_nFaces || _ptFaces == nullptr || !_nVertices || _ptPositions == nullptr) { BH3D_LOGGERERROR("invalid param"); return BH3D_ERROR; } boundingBox.Reset(); computed = 0; if (!LoadSubMesh(_nFaces, _ptFaces, _nVertices, _ptPositions, _ptTexCoords, _textureFormat, _ptNormals, _ptColors, _colorFormat, _pMaterial)) { BH3D_LOGGERERROR("Fucking big FAIL !!!! Can destroy your computer"); return BH3D_ERROR; } return BH3D_OK; } bool Mesh::AddSubMesh(const std::vector<Face> & tFace, const std::vector<glm::vec3> & tPosition, const std::vector<glm::vec2> & tTexCoord, std::vector<glm::vec3> & tNormal, const std::vector<glm::vec3> & tColor, const Material *_pMaterial) { std::size_t nFaces = tFace.size(); const unsigned int *ptFaces = (tFace.empty() ? nullptr : tFace[0].id); std::size_t nVertex = tPosition.size(); const float * ptPosition = tPosition.empty() ? nullptr : &tPosition[0].x; const float * ptTexCoord = tTexCoord.empty() ? nullptr : &tTexCoord[0].x; const float * ptNormal = tNormal.empty() ? nullptr : &tNormal[0].x; const float * ptColor = tColor.empty() ? nullptr : &tColor[0].x; return AddSubMesh(nFaces, ptFaces, nVertex, ptPosition, ptTexCoord, 2, ptNormal, ptColor, 0, _pMaterial); } bool Mesh::AddSubMesh(const std::vector<Face> & tFace, const std::vector<glm::vec3> & tPosition, const std::vector<glm::vec3> & tTexCoord, std::vector<glm::vec3> & tNormal, const std::vector<glm::vec3> & tColor, const Material *_pMaterial) { std::size_t nFaces = tFace.size(); const unsigned int *ptFaces = (tFace.empty() ? nullptr : tFace[0].id); std::size_t nVertex = tPosition.size(); const float * ptPosition = tPosition.empty() ? nullptr : &tPosition[0].x; const float * ptTexCoord = tTexCoord.empty() ? nullptr : &tTexCoord[0].x; const float * ptNormal = tNormal.empty() ? nullptr : &tNormal[0].x; const float * ptColor = tColor.empty() ? nullptr : &tColor[0].x; return AddSubMesh(nFaces, ptFaces, nVertex, ptPosition, ptTexCoord, 3, ptNormal, ptColor, 0, _pMaterial); } bool Mesh::AddSubMesh(const std::vector<Face> & tFace, const std::vector<glm::vec3> & tPosition, const std::vector<glm::vec2> & tTexCoord, std::vector<glm::vec3> & tNormal, const std::vector<glm::vec4> & tColor, const Material *_pMaterial) { std::size_t nFaces = tFace.size(); const unsigned int *ptFaces = (tFace.empty() ? nullptr : tFace[0].id); std::size_t nVertex = tPosition.size(); const float * ptPosition = tPosition.empty() ? nullptr : &tPosition[0].x; const float * ptTexCoord = tTexCoord.empty() ? nullptr : &tTexCoord[0].x; const float * ptNormal = tNormal.empty() ? nullptr : &tNormal[0].x; const float * ptColor = tColor.empty() ? nullptr : &tColor[0].x; return AddSubMesh(nFaces, ptFaces, nVertex, ptPosition, ptTexCoord, 2, ptNormal, ptColor, 1, _pMaterial); } bool Mesh::AddSubMesh(const std::vector<Face> & tFace, const std::vector<glm::vec3> & tPosition, const std::vector<glm::vec3> & tTexCoord, std::vector<glm::vec3> & tNormal, const std::vector<glm::vec4> & tColor, const Material *_pMaterial) { std::size_t nFaces = tFace.size(); const unsigned int *ptFaces = (tFace.empty() ? nullptr : tFace[0].id); std::size_t nVertex = tPosition.size(); const float * ptPosition = tPosition.empty() ? nullptr : &tPosition[0].x; const float * ptTexCoord = tTexCoord.empty() ? nullptr : &tTexCoord[0].x; const float * ptNormal = tNormal.empty() ? nullptr : &tNormal[0].x; const float * ptColor = tColor.empty() ? nullptr : &tColor[0].x; return AddSubMesh(nFaces, ptFaces, nVertex, ptPosition, ptTexCoord, 3, ptNormal, ptColor, 1, _pMaterial); } bool Mesh::AddSubMesh(const std::vector<Face> & tFace, const std::vector<glm::vec3> & tPosition, const std::vector<glm::vec2> & tTexCoord, std::vector<glm::vec3> & tNormal) { std::size_t nFaces = tFace.size(); const unsigned int *ptFaces = (tFace.empty() ? nullptr : tFace[0].id); std::size_t nVertex = tPosition.size(); const float * ptPosition = tPosition.empty() ? nullptr : &tPosition[0].x; const float * ptTexCoord = tTexCoord.empty() ? nullptr : &tTexCoord[0].x; const float * ptNormal = tNormal.empty() ? nullptr : &tNormal[0].x; return AddSubMesh(nFaces, ptFaces, nVertex, ptPosition, ptTexCoord, 2, ptNormal, nullptr, 0, nullptr); } void Mesh::FreeArrays() { //clear ne libère pas la mémoire ;D //tPosition.clear(); //tNormal.clear(); //tTexCoord2.clear(); //tTexCoord3.clear(); //tColor3.clear(); //tColor4.clear(); //tTangent.clear(); //libère vraiment la mémoire. std::vector<glm::vec3>().swap(tPosition); std::vector<glm::vec3>().swap(tNormal); std::vector<glm::vec2>().swap(tTexCoord2); std::vector<glm::vec3>().swap(tTexCoord3); std::vector<glm::vec3>().swap(tColor3); std::vector<glm::vec4>().swap(tColor4); std::vector<glm::vec3>().swap(tTangent); reserveFaceNumber = 0; reserveVertexNumber = 0; reserveMeshNumber = 0; } bool Mesh::ComputeMesh() { //already computed if (IsValid()) { BH3D_LOGGERWARNING("Mesh is already computed") return BH3D_OK; } if (tPosition.empty()) { BH3D_LOGGERERROR("No vertices to compute - Sucker"); BH3D_ASSERT(0); return BH3D_ERROR; } ComputeBoundingBox(); // //construction du vbo // vbo.AddArrayBufferData(BH3D_VERTEX_ATTRIB_INDEX, tPosition); if (tNormal.size()) vbo.AddArrayBufferData(BH3D_NORMAL_ATTRIB_INDEX, tNormal); if (tTexCoord2.size()) vbo.AddArrayBufferData(BH3D_COORD0_ATTRIB_INDEX, tTexCoord2); else if (tTexCoord3.size()) vbo.AddArrayBufferData(BH3D_COORD0_ATTRIB_INDEX, tTexCoord3); if (tColor3.size()) vbo.AddArrayBufferData(BH3D_COLOR_ATTRIB_INDEX, tColor3); else if (tColor4.size()) vbo.AddArrayBufferData(BH3D_COLOR_ATTRIB_INDEX, tColor4); if (tTangent.size()) vbo.AddArrayBufferData(BH3D_DATA0_ATTRIB_INDEX, tTangent); vbo.AddElementBufferData(tFace[0].id, tFace.size() * 3); if (vbo.Create()) { computed = BH3D_OK; return BH3D_OK; } else { BH3D_LOGGERERROR("VBO Fail"); } return BH3D_ERROR; } void Mesh::Destroy() { vbo.Destroy(); tSubMeshes.clear(); computed = 0; tPosition.clear(); tNormal.clear(); tTexCoord2.clear(); tTexCoord3.clear(); tColor3.clear(); tColor4.clear(); tTangent.clear(); reserveFaceNumber = 0; reserveVertexNumber = 0; reserveMeshNumber = 0; } bool Mesh::LoadSubMesh(std::size_t _nFaces, const unsigned int *_ptFaces, std::size_t _nVertices, const float * _ptPositions, const float * _ptTexCoords, char _textureFormat, const float * _ptNormals, const float *_ptColors, char _colorFormat, const Material *_pMaterial) { //les données de chaque groupe doivent avoir le même format de vertex (4,3,2...) if (tSubMeshes.size()) { if (textureFormat != _textureFormat) { BH3D_LOGGERERROR("textureFormat mismatch"); BH3D_ASSERT(0); return BH3D_ERROR; //coordonnées textures : format différent } if (colorFormat != _colorFormat) { BH3D_LOGGERERROR("colorFormat mismatch"); BH3D_ASSERT(0); return BH3D_ERROR;//couleurs : format différent } } else //premier SubMesh on sauvegarde le format des coordonnées textures et couleurs { textureFormat = _textureFormat; colorFormat = _colorFormat; } if (tNormal.size() && _ptNormals == nullptr) { BH3D_LOGGERERROR("New mesh description not match with existing meshes : normal missing"); BH3D_ASSERT(0); return BH3D_ERROR;//couleurs : format différent } if ((tTexCoord2.size() || tTexCoord3.size()) && _ptTexCoords == nullptr) { BH3D_LOGGERERROR("New mesh description not match with existing meshes : texture Coordonates missing"); BH3D_ASSERT(0); return BH3D_ERROR;//couleurs : format différent } if ((tColor4.size() || tColor3.size()) && _ptColors == nullptr) { BH3D_LOGGERERROR("New mesh description not match with existing meshes : color missing"); BH3D_ASSERT(0); return BH3D_ERROR;//couleurs : format différent } std::size_t positionOffset = tPosition.size(); std::size_t offsetFace = tFace.size(); //allocation de la mémoire if (reserveFaceNumber && tSubMeshes.empty()) tFace.reserve(reserveFaceNumber); else if (reserveFaceNumber == 0) tFace.reserve(offsetFace + _nFaces); if (reserveVertexNumber && tSubMeshes.empty()) { tPosition.reserve(reserveVertexNumber); if (_ptNormals != nullptr) tNormal.reserve(reserveVertexNumber); if (_ptTexCoords != nullptr) { if (textureFormat == 3) tTexCoord3.reserve(reserveVertexNumber); else tTexCoord2.reserve(reserveVertexNumber); } if (_ptColors != nullptr) { if (colorFormat == 4) tColor4.reserve(reserveVertexNumber); else tColor3.reserve(reserveVertexNumber); } } else if (reserveVertexNumber == 0) { tPosition.reserve(positionOffset + _nVertices); if (_ptNormals != nullptr) tNormal.reserve(positionOffset + _nVertices); if (_ptTexCoords != nullptr) { if (textureFormat == 3) tTexCoord3.reserve(positionOffset + _nVertices); else tTexCoord2.reserve(positionOffset + _nVertices); } if (_ptColors != nullptr) { if (colorFormat == 4) tColor4.reserve(positionOffset + _nVertices); else tColor3.reserve(positionOffset + _nVertices); } } if (reserveMeshNumber && tSubMeshes.empty()) tSubMeshes.reserve(reserveMeshNumber); tSubMeshes.push_back(Mesh::SubMesh()); auto & subMesh = tSubMeshes.back(); subMesh.vertexOffset = positionOffset; subMesh.faceOffset = offsetFace; subMesh.nFaces = _nFaces; subMesh.nVertices = _nVertices; //recopie des vertices for (unsigned int i = 0; i < _nVertices; i++) { tPosition.push_back(glm::vec3(_ptPositions[i * 3], _ptPositions[i * 3 + 1], _ptPositions[i * 3 + 2])); if (_ptNormals != nullptr) tNormal.push_back(glm::vec3(_ptNormals[i * 3], _ptNormals[i * 3 + 1], _ptNormals[i * 3 + 2])); if (_ptTexCoords != nullptr) { if (textureFormat == 3) tTexCoord3.push_back(glm::vec3(_ptTexCoords[i * 3], _ptTexCoords[i * 3 + 1], _ptTexCoords[i * 3 + 2])); else tTexCoord2.push_back(glm::vec2(_ptTexCoords[i * 2], _ptTexCoords[i * 2 + 1])); } if (_ptColors != nullptr) { if (colorFormat == 4) tColor4.push_back(glm::vec4(_ptColors[i * 4], _ptColors[i * 4 + 1], _ptColors[i * 4 + 2], _ptColors[i * 4 + 3])); else tColor3.push_back(glm::vec3(_ptColors[i * 3], _ptColors[i * 3 + 1], _ptColors[i * 3 + 2])); } } Face face; for (unsigned int i = 0; i < _nFaces; i++) { face.id[0] = _ptFaces[i * 3 + 0] + positionOffset; face.id[1] = _ptFaces[i * 3 + 1] + positionOffset; face.id[2] = _ptFaces[i * 3 + 2] + positionOffset; tFace.push_back(face); } if (_pMaterial) subMesh.nMaterial = (*_pMaterial); return BH3D_OK; } void Mesh::ScaleMesh(glm::vec3 scale, int submeshid) { BH3D_ASSERT_MSG(tPosition.size(),"Empty Mesh (no vertex)",); computed = 0; boundingBox.Reset(); if (scale == glm::vec3(0.0f, 0.0f, 0.0f) || scale == glm::vec3(1.0f, 1.0f, 1.0f)) return; std::size_t i, start = 0, end = tPosition.size(); if (submeshid >= 0 && submeshid < tSubMeshes.size()) { start = tSubMeshes[submeshid].vertexOffset; end = start + tSubMeshes[submeshid].nVertices; } for (i = start; i < end; i++) { tPosition[i].x *= scale.x; tPosition[i].y *= scale.y; tPosition[i].z *= scale.z; } boundingBox.Reset(); } void Mesh::Draw() const { BH3D_ASSERT_MSG(IsValid(),"No valid Mesh, can't draw it",); vbo.Enable(); //glDrawElements(GL_TRIANGLES, tFace.size()*3, GL_UNSIGNED_INT, 0); for (unsigned int i = 0; i < tSubMeshes.size(); i++) { tSubMeshes[i].nMaterial.Bind(); glDrawElements(GL_TRIANGLES, (GLsizei)tSubMeshes[i].nFaces * 3, GL_UNSIGNED_INT, BH3D_BUFFER_OFFSET(tSubMeshes[i].faceOffset * 3 * sizeof(unsigned int))); } #ifndef NDEBUG vbo.Disable(); #endif } void Mesh::DrawSubMesh(unsigned int id) const { BH3D_ASSERT_MSG(IsValid(), "No valid Mesh, can't draw it",); vbo.Enable(); tSubMeshes[id].nMaterial.Bind(); glDrawElements(GL_TRIANGLES, (GLsizei)tSubMeshes[id].nFaces * 3, GL_UNSIGNED_INT, BH3D_BUFFER_OFFSET( tSubMeshes[id].faceOffset * 3 * sizeof(unsigned int)) ); #ifndef NDEBUG vbo.Disable(); #endif } void Mesh::ComputeBoundingBox() { BH3D_ASSERT_MSG(tPosition.size(),"Mesh is empty, (No vertices)",); if (boundingBox.IsValid()) return; glm::vec3 vmin, vmax; vmin = vmax = tPosition[0]; //initialisation for (const auto & v : tPosition) { for (int j = 0; j < 3; j++) //pour chacune des composantes { if (vmin[j] > v[j]) vmin[j] = v[j]; if (vmax[j] < v[j]) vmax[j] = v[j]; } } boundingBox.size = (vmax - vmin); boundingBox.position = 0.5f*(vmax + vmin); } void Mesh::CenterDataToOrigin(glm::vec3 offset) { BH3D_ASSERT_MSG(tPosition.size(),"Mesh is empty (no vertices)",); if (!boundingBox.IsValid()) ComputeBoundingBox(); glm::vec3 origine = boundingBox.position - offset; if (boundingBox.position != glm::vec3(0, 0, 0)) { for (auto & v : tPosition) { v -= (origine); } boundingBox.position = glm::vec3(0.0f, 0.0f, 0.0f); } //boundingBox.size = glm::vec3(0.0,0.0,0.0); } void Mesh::NormalizeData(bool keepRatio) { BH3D_ASSERT_MSG(tPosition.size(), "Mesh is empty (no vertices)",); if (!boundingBox.IsValid()) ComputeBoundingBox(); float dx = 1.0f, dy = 1.0f, dz = 1.0f; if (boundingBox.size.x) { dx = 1.0f / boundingBox.size.x; boundingBox.size.x = 1.0f; } if (boundingBox.size.y) { dy = 1.0f / boundingBox.size.y; boundingBox.size.y = 1.0f; } if (boundingBox.size.z) { dz = 1.0f / boundingBox.size.z; boundingBox.size.z = 1.0f; } if (keepRatio) { dx = dy = dz = std::min(std::min(dx, dy), dz); } ScaleMesh(glm::vec3(dx,dy,dz)); boundingBox.size = glm::vec3(0.0, 0.0, 0.0); } void Mesh::TransformMesh(glm::mat4 &mat, int submeshid) { BH3D_ASSERT_MSG(tPosition.size(), "Mesh is empty (no vertices)",); computed = 0; boundingBox.Reset(); std::size_t i, start = 0, end = tPosition.size(); if (submeshid >= 0 && submeshid < tSubMeshes.size()) { start = tSubMeshes[submeshid].vertexOffset; end = start + tSubMeshes[submeshid].nVertices; } for (i = start; i < end; i++) tPosition[i] = glm::vec3(mat*glm::vec4(tPosition[i], 1)); if (tNormal.size()) { for (i = start; i < end; i++) tNormal[i] = glm::vec3(mat*glm::vec4(tNormal[i], 1)); } if (tTangent.size()) { for (i = start; i < end; i++) tTangent[i] = glm::vec3(mat*glm::vec4(tTangent[i], 1)); } } }
C++
CL
025238bf891ead8b1321898022b629df4a602973a2408a28e4591f7dddc6e450
/* Controls the assigning of randomized data to the nuclide grid structs and the material map. */ #include "vexs_header.h" void assign_random_data(problem_data &problem){ cout << "\n[Assigning random data]" << endl; unsigned long seed = 5; // TEMPORARY SEED //Kick the RNG off, since it initially gives a very low value random_number(seed); //If we have read in data from binary file, we don't need to assign values to nuclide grids, we assume they've been assigned. //We do still need to assign random values for the material nuclide concentrations, however. if (problem.binary){ assign_random_concentrations(problem, seed); return; } assign_random_xs(problem, seed); seed = 5; random_number(seed); assign_random_concentrations(problem, seed); //This isn't really the best place to put this, but since this is the last place where we can modify the problem class //I think this is best; this just calculates and sets small numbers that users commonly want to know that aren't set //anywhere else, such as the number of nuclides in all nuclide grids, etc. }
C++
CL
89826d01ee77a6db02019fe5324d53987cefb9e7e76bc5d5cc663a9a36791ed2
// Copyright (c) 2013 Vasili Baranau // Distributed under the MIT software license // See the accompanying file License.txt or http://opensource.org/licenses/MIT #ifndef Generation_PackingServices_PostProcessing_Headers_PressureService_h #define Generation_PackingServices_PostProcessing_Headers_PressureService_h #include "Generation/PackingServices/DistanceServices/Headers/BaseDistanceService.h" namespace PackingServices { // Class capable of computing pressure tensor, bulk modulus, shear modulus. // See O'�Hern et al (2003) The epitome of disorder. class PressureService : public BaseDistanceService { public: PressureService(MathService* mathService, INeighborProvider* neighborProvider); void SetParticles(const Model::Packing& particles); void FillPressures(const std::vector<Core::FLOAT_TYPE>& contractionRatios, const std::vector<Core::FLOAT_TYPE>& energyPowers, std::vector<Core::FLOAT_TYPE>* pressures) const; Core::FLOAT_TYPE GetBulkModulus() const; private: Core::FLOAT_TYPE GetPressure(Core::FLOAT_TYPE contractionRatio, Core::FLOAT_TYPE energyPower) const; void FillPressureTensor(Core::FLOAT_TYPE contractionRatio, Core::FLOAT_TYPE energyPower, Core::FLOAT_TYPE pressureTensor[DIMENSIONS][DIMENSIONS]) const; void UpdatePressureTensor(Core::FLOAT_TYPE contractionRatio, Core::FLOAT_TYPE energyPower, const Model::DomainParticle& particle, const Model::DomainParticle& neighbor, Core::FLOAT_TYPE pressureTensor[DIMENSIONS][DIMENSIONS]) const; Core::FLOAT_TYPE GetPressureEntry(const Model::DomainParticle& particle, const Model::DomainParticle& neighbor, int firstPressureDimension, int secondPressureDimension, const Core::SpatialVector& direction, Core::FLOAT_TYPE distance, Core::FLOAT_TYPE energyPower) const; DISALLOW_COPY_AND_ASSIGN(PressureService); }; } #endif /* Generation_PackingServices_PostProcessing_Headers_PressureService_h */
C++
CL
3b67b83c3a85b4322e6ab41e6a4206dc521ffc5104e78150aad1317934cfda27
/* * dnn_inference_engine.cpp - dnn inference engine * * Copyright (c) 2019 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. * * Author: Zong Wei <[email protected]> */ #include "dnn_inference_engine.h" #include "dnn_inference_utils.h" #include <iomanip> #include <format_reader_ptr.h> #include <ext_list.hpp> #if HAVE_OPENCV #include "ocv/cv_std.h" #endif using namespace std; using namespace InferenceEngine; namespace XCam { DnnInferenceEngine::DnnInferenceEngine (DnnInferConfig& config) : _model_created (false) , _model_loaded (false) , _model_type (config.model_type) { XCAM_LOG_DEBUG ("DnnInferenceEngine::DnnInferenceEngine"); _input_image_width.clear (); _input_image_height.clear (); create_model (config); } DnnInferenceEngine::~DnnInferenceEngine () { } XCamReturn DnnInferenceEngine::create_model (DnnInferConfig& config) { XCAM_LOG_DEBUG ("DnnInferenceEngine::create_model"); if (_model_created) { XCAM_LOG_INFO ("model already created!"); return XCAM_RETURN_NO_ERROR; } // 1. Read the Intermediate Representation XCAM_LOG_DEBUG ("pre-trained model file name: %s", config.model_filename); if (NULL == config.model_filename) { XCAM_LOG_ERROR ("Model file name is empty!"); return XCAM_RETURN_ERROR_PARAM; } _network_reader.ReadNetwork (get_filename_prefix (config.model_filename) + ".xml"); _network_reader.ReadWeights (get_filename_prefix (config.model_filename) + ".bin"); // 2. read network from model _network = _network_reader.getNetwork (); // 3. Select Plugin - Select the plugin on which to load your network. // 3.1. Create the plugin with the InferenceEngine::PluginDispatcher load helper class. if (NULL == config.plugin_path) { InferenceEngine::PluginDispatcher dispatcher ({""}); _plugin = dispatcher.getPluginByDevice (getDeviceName (get_device_from_id (config.target_id))); } else { InferenceEngine::PluginDispatcher dispatcher ({config.plugin_path}); _plugin = dispatcher.getPluginByDevice (getDeviceName (get_device_from_id (config.target_id))); } // 3.2. Pass per device loading configurations specific to this device, // and register extensions to this device. if (DnnInferDeviceCPU == config.target_id) { /** * cpu_extensions library is compiled from "extension" folder containing * custom MKLDNNPlugin layer implementations. These layers are not supported * by mkldnn, but they can be useful for inferring custom topologies. **/ _plugin.AddExtension (std::make_shared<Extensions::Cpu::CpuExtensions>()); if (NULL != config.cpu_ext_path) { std::string cpu_ext_path (config.cpu_ext_path); // CPU(MKLDNN) extensions are loaded as a shared library and passed as a pointer to base extension auto extensionPtr = InferenceEngine::make_so_pointer<InferenceEngine::IExtension>(cpu_ext_path); _plugin.AddExtension (extensionPtr); XCAM_LOG_DEBUG ("CPU Extension loaded: %s", cpu_ext_path); } } else if (DnnInferDeviceGPU == config.target_id) { if (NULL != config.cldnn_ext_path) { std::string cldnn_ext_path (config.cldnn_ext_path); // clDNN Extensions are loaded from an .xml description and OpenCL kernel files _plugin.SetConfig ({ { InferenceEngine::PluginConfigParams::KEY_CONFIG_FILE, cldnn_ext_path } }); XCAM_LOG_DEBUG ("GPU Extension loaded: %s", cldnn_ext_path); } } if (config.perf_counter > 0) { _plugin.SetConfig ({ { InferenceEngine::PluginConfigParams::KEY_PERF_COUNT, InferenceEngine::PluginConfigParams::YES } }); } _model_created = true; return XCAM_RETURN_NO_ERROR; } XCamReturn DnnInferenceEngine::load_model (DnnInferConfig& config) { XCAM_LOG_DEBUG ("DnnInferenceEngine::load_model"); if (! _model_created) { XCAM_LOG_ERROR ("Please create the model firstly!"); return XCAM_RETURN_ERROR_ORDER; } if (_model_loaded) { XCAM_LOG_INFO ("model already loaded!"); return XCAM_RETURN_NO_ERROR; } InferenceEngine::ExecutableNetwork execute_network = _plugin.LoadNetwork (_network, {}); _infer_request = execute_network.CreateInferRequest (); _model_loaded = true; return XCAM_RETURN_NO_ERROR; } XCamReturn DnnInferenceEngine::get_info (DnnInferenceEngineInfo& info, DnnInferInfoType type) { XCAM_LOG_DEBUG ("DnnInferenceEngine::get_info type %d", type); if (! _model_created) { XCAM_LOG_ERROR ("Please create the model firstly!"); return XCAM_RETURN_ERROR_ORDER; } info.type = type; if (DnnInferInfoEngine == type) { info.major = GetInferenceEngineVersion ()->apiVersion.major; info.minor = GetInferenceEngineVersion ()->apiVersion.minor; } else if (DnnInferInfoPlugin == type) { const InferenceEngine::Version *plugin_version = NULL; static_cast<InferenceEngine::InferenceEnginePluginPtr>(_plugin)->GetVersion (plugin_version); info.major = plugin_version->apiVersion.major; info.minor = plugin_version->apiVersion.minor; info.desc = plugin_version->description; } else if (DnnInferInfoNetwork == type) { info.major = _network_reader.getVersion (); info.desc = _network_reader.getDescription ().c_str (); info.name = _network_reader.getName ().c_str (); } else { XCAM_LOG_WARNING ("DnnInferenceEngine::get_info type %d not supported!", type); } return XCAM_RETURN_NO_ERROR; } XCamReturn DnnInferenceEngine::set_batch_size (const size_t size) { if (! _model_created) { XCAM_LOG_ERROR ("Please create the model firstly!"); return XCAM_RETURN_ERROR_ORDER; } _network.setBatchSize (size); return XCAM_RETURN_NO_ERROR; } size_t DnnInferenceEngine::get_batch_size () { if (! _model_created) { XCAM_LOG_ERROR ("Please create the model firstly!"); return -1; } return _network.getBatchSize (); } XCamReturn DnnInferenceEngine::start (bool sync) { XCAM_LOG_DEBUG ("Start inference %s", sync ? "Sync" : "Async"); if (! _model_loaded) { XCAM_LOG_ERROR ("Please load the model firstly!"); return XCAM_RETURN_ERROR_ORDER; } if (sync) { _infer_request.Infer (); } else { _infer_request.StartAsync (); _infer_request.Wait (IInferRequest::WaitMode::RESULT_READY); } return XCAM_RETURN_NO_ERROR; } size_t DnnInferenceEngine::get_input_size () { if (! _model_created) { XCAM_LOG_ERROR ("Please create the model firstly!"); return -1; } InputsDataMap inputs_info (_network.getInputsInfo()); return inputs_info.size (); } size_t DnnInferenceEngine::get_output_size () { if (! _model_created) { XCAM_LOG_ERROR ("Please create the model firstly!"); return -1; } OutputsDataMap outputs_info (_network.getOutputsInfo()); return outputs_info.size (); } XCamReturn DnnInferenceEngine::set_input_precision (uint32_t idx, DnnInferPrecisionType precision) { if (! _model_created) { XCAM_LOG_ERROR ("Please create the model firstly!"); return XCAM_RETURN_ERROR_ORDER; } InputsDataMap inputs_info (_network.getInputsInfo ()); if (idx > inputs_info.size ()) { XCAM_LOG_ERROR ("Input is out of range"); return XCAM_RETURN_ERROR_PARAM; } uint32_t i = 0; for (auto & in : inputs_info) { if (i == idx) { Precision input_precision = convert_precision_type (precision); in.second->setPrecision (input_precision); break; } i++; } return XCAM_RETURN_NO_ERROR; } DnnInferPrecisionType DnnInferenceEngine::get_input_precision (uint32_t idx) { if (! _model_created) { XCAM_LOG_ERROR ("Please create the model firstly!"); return DnnInferPrecisionUnspecified; } DnnInferInputOutputInfo inputs_info; get_model_input_info (inputs_info); if (idx > get_input_size ()) { XCAM_LOG_ERROR ("Index is out of range"); return DnnInferPrecisionUnspecified; } return inputs_info.precision[idx]; } XCamReturn DnnInferenceEngine::set_output_precision (uint32_t idx, DnnInferPrecisionType precision) { if (! _model_created) { XCAM_LOG_ERROR ("Please create the model firstly!"); return XCAM_RETURN_ERROR_ORDER; } OutputsDataMap outputs_info (_network.getOutputsInfo ()); if (idx > outputs_info.size ()) { XCAM_LOG_ERROR ("Output is out of range"); return XCAM_RETURN_ERROR_PARAM; } uint32_t i = 0; for (auto & out : outputs_info) { if (i == idx) { Precision output_precision = convert_precision_type (precision); out.second->setPrecision (output_precision); break; } i++; } return XCAM_RETURN_NO_ERROR; } DnnInferPrecisionType DnnInferenceEngine::get_output_precision (uint32_t idx) { if (! _model_created) { XCAM_LOG_ERROR ("Please create the model firstly!"); return DnnInferPrecisionUnspecified; } DnnInferInputOutputInfo outputs_info; get_model_output_info (outputs_info); if (idx > get_output_size ()) { XCAM_LOG_ERROR ("Index is out of range"); return DnnInferPrecisionUnspecified; } return outputs_info.precision[idx]; } DnnInferImageFormatType DnnInferenceEngine::get_output_format (uint32_t idx) { if (! _model_created) { XCAM_LOG_ERROR ("Please create the model firstly!"); return DnnInferImageFormatUnknown; } DnnInferInputOutputInfo outputs_info; get_model_output_info (outputs_info); if (idx > get_output_size ()) { XCAM_LOG_ERROR ("Index is out of range"); return DnnInferImageFormatUnknown; } return outputs_info.format[idx]; } XCamReturn DnnInferenceEngine::set_input_layout (uint32_t idx, DnnInferLayoutType layout) { if (! _model_created) { XCAM_LOG_ERROR ("Please create the model firstly!"); return XCAM_RETURN_ERROR_ORDER; } InputsDataMap inputs_info (_network.getInputsInfo ()); if (idx > inputs_info.size ()) { XCAM_LOG_ERROR ("Input is out of range"); return XCAM_RETURN_ERROR_PARAM; } uint32_t i = 0; for (auto & in : inputs_info) { if (i == idx) { Layout input_layout = convert_layout_type (layout); in.second->setLayout (input_layout); break; } i++; } return XCAM_RETURN_NO_ERROR; } XCamReturn DnnInferenceEngine::set_output_layout (uint32_t idx, DnnInferLayoutType layout) { if (! _model_created) { XCAM_LOG_ERROR ("Please create the model firstly!"); return XCAM_RETURN_ERROR_ORDER; } OutputsDataMap outputs_info (_network.getOutputsInfo ()); if (idx > outputs_info.size ()) { XCAM_LOG_ERROR ("Output is out of range"); return XCAM_RETURN_ERROR_PARAM; } uint32_t i = 0; for (auto & out : outputs_info) { if (i == idx) { Layout output_layout = convert_layout_type (layout); out.second->setLayout (output_layout); break; } i++; } return XCAM_RETURN_NO_ERROR; } XCamReturn DnnInferenceEngine::set_input_blob (uint32_t idx, DnnInferData& data) { unsigned int id = 0; std::string input_name; InputsDataMap inputs_info (_network.getInputsInfo ()); if (idx > inputs_info.size()) { XCAM_LOG_ERROR ("Input is out of range"); return XCAM_RETURN_ERROR_PARAM; } for (auto & in : inputs_info) { if (id == idx) { input_name = in.first; break; } id++; } if (input_name.empty ()) { XCAM_LOG_ERROR ("input name is empty!"); return XCAM_RETURN_ERROR_PARAM; } if (data.batch_idx > get_batch_size ()) { XCAM_LOG_ERROR ("Too many input, it is bigger than batch size!"); return XCAM_RETURN_ERROR_PARAM; } Blob::Ptr blob = _infer_request.GetBlob (input_name); if (data.precision == DnnInferPrecisionFP32) { if (data.data_type == DnnInferDataTypeImage) { copy_image_to_blob<PrecisionTrait<Precision::FP32>::value_type>(data, blob, data.batch_idx); } else { copy_data_to_blob<PrecisionTrait<Precision::FP32>::value_type>(data, blob, data.batch_idx); } } else { if (data.data_type == DnnInferDataTypeImage) { copy_image_to_blob<uint8_t>(data, blob, data.batch_idx); } else { copy_data_to_blob<uint8_t>(data, blob, data.batch_idx); } } return XCAM_RETURN_NO_ERROR; } XCamReturn DnnInferenceEngine::set_inference_data (std::vector<std::string> images) { if (!_model_created) { XCAM_LOG_ERROR ("Please create the model firstly!"); return XCAM_RETURN_ERROR_ORDER; } uint32_t idx = 0; InputsDataMap inputs_info (_network.getInputsInfo ()); for (auto & i : images) { FormatReader::ReaderPtr reader (i.c_str ()); if (reader.get () == NULL) { XCAM_LOG_WARNING ("Image %d cannot be read!", i); continue; } _input_image_width.push_back (reader->width ()); _input_image_height.push_back (reader->height ()); uint32_t image_width = 0; uint32_t image_height = 0; for (auto & in : inputs_info) { image_width = inputs_info[in.first]->getDims()[0]; image_height = inputs_info[in.first]->getDims()[1]; } std::shared_ptr<unsigned char> data (reader->getData (image_width, image_height)); if (data.get () != NULL) { DnnInferData image; image.width = image_width; image.height = image_height; image.width_stride = image_width; image.height_stride = image_height; image.buffer = data.get (); image.channel_num = 3; image.batch_idx = idx; image.image_format = DnnInferImageFormatBGRPacked; // set precision & data type image.precision = get_input_precision (idx); image.data_type = DnnInferDataTypeImage; set_input_blob (idx, image); idx ++; } else { XCAM_LOG_WARNING ("Valid input images were not found!"); continue; } } return XCAM_RETURN_NO_ERROR; } XCamReturn DnnInferenceEngine::set_inference_data (const VideoBufferList& images) { if (!_model_created) { XCAM_LOG_ERROR ("Please create the model firstly!"); return XCAM_RETURN_ERROR_ORDER; } uint32_t idx = 0; InputsDataMap inputs_info (_network.getInputsInfo ()); for (VideoBufferList::const_iterator iter = images.begin(); iter != images.end (); ++iter) { SmartPtr<VideoBuffer> buf = *iter; XCAM_ASSERT (buf.ptr ()); VideoBufferInfo buf_info = buf->get_video_info (); _input_image_width.push_back (buf_info.width); _input_image_height.push_back (buf_info.height); uint32_t image_width = 0; uint32_t image_height = 0; for (auto & in : inputs_info) { image_width = inputs_info[in.first]->getDims()[0]; image_height = inputs_info[in.first]->getDims()[1]; } float x_ratio = float(image_width) / float(buf_info.width); float y_ratio = float(image_height) / float(buf_info.height); uint8_t* data = NULL; if (buf_info.format == V4L2_PIX_FMT_NV12) { data = XCamDNN::convert_NV12_to_BGR (buf, x_ratio, y_ratio); } else if (buf_info.format == V4L2_PIX_FMT_BGR24) { data = buf->map (); } if (data != NULL) { DnnInferData image; image.width = image_width; image.height = image_height; image.width_stride = image_width; image.height_stride = image_height; image.buffer = data; image.channel_num = 3; image.batch_idx = idx; image.image_format = DnnInferImageFormatBGRPacked; // set precision & data type image.precision = get_input_precision (idx); image.data_type = DnnInferDataTypeImage; set_input_blob (idx, image); idx ++; } else { XCAM_LOG_WARNING ("Valid input images were not found!"); continue; } if (buf_info.format != V4L2_PIX_FMT_NV12) { buf->unmap (); } } return XCAM_RETURN_NO_ERROR; } std::shared_ptr<uint8_t> DnnInferenceEngine::read_input_image (std::string& image) { FormatReader::ReaderPtr reader (image.c_str ()); if (reader.get () == NULL) { XCAM_LOG_WARNING ("Image cannot be read!"); return NULL; } uint32_t image_width = reader->width (); uint32_t image_height = reader->height (); std::shared_ptr<uint8_t> data (reader->getData (image_width, image_height)); if (data.get () != NULL) { return data; } else { XCAM_LOG_WARNING ("Valid input images were not found!"); return NULL; } } XCamReturn DnnInferenceEngine::save_output_image (const std::string& image_name, uint32_t index) { if (! _model_created || ! _model_loaded) { XCAM_LOG_ERROR ("Please create and load the model firstly!"); return XCAM_RETURN_ERROR_ORDER; } if (NULL == _output_layer_type[_model_type]) { XCAM_LOG_ERROR ("Please set model output layer type!"); return XCAM_RETURN_ERROR_PARAM; } OutputsDataMap outputs_info (_network.getOutputsInfo ()); if (index > outputs_info.size ()) { XCAM_LOG_ERROR ("Output is out of range"); return XCAM_RETURN_ERROR_PARAM; } std::string output_name; for (auto & out : outputs_info) { if ( !strncmp (out.second->creatorLayer.lock()->type.c_str (), _output_layer_type[_model_type], strlen(_output_layer_type[_model_type]))) { output_name = out.first; break; } } if (output_name.empty ()) { XCAM_LOG_ERROR ("out name is empty!"); return XCAM_RETURN_ERROR_PARAM; } const Blob::Ptr output_blob = _infer_request.GetBlob (output_name); const auto output_data = output_blob->buffer ().as<PrecisionTrait<Precision::FP32>::value_type*> (); size_t image_count = output_blob->getTensorDesc ().getDims ()[0]; size_t channels = output_blob->getTensorDesc ().getDims ()[1]; size_t image_height = output_blob->getTensorDesc ().getDims ()[2]; size_t image_width = output_blob->getTensorDesc ().getDims ()[3]; size_t pixel_count = image_width * image_height; XCAM_LOG_DEBUG ("Output size [image count, channels, width, height]: %d, %d, %d, %d", image_count, channels, image_width, image_height); if (index > image_count) { return XCAM_RETURN_ERROR_PARAM; } #if HAVE_OPENCV std::vector<cv::Mat> image_planes; if (3 == channels) { image_planes.push_back (cv::Mat (image_height, image_width, CV_32FC1, &(output_data[index * pixel_count * channels + pixel_count * 2]))); image_planes.push_back (cv::Mat (image_height, image_width, CV_32FC1, &(output_data[index * pixel_count * channels + pixel_count]))); image_planes.push_back (cv::Mat (image_height, image_width, CV_32FC1, &(output_data[index * pixel_count * channels]))); } else if (1 == channels) { image_planes.push_back (cv::Mat (image_height, image_width, CV_32FC1, &(output_data[index * pixel_count]))); } for (auto & image : image_planes) { image.convertTo (image, CV_8UC1, 255); } cv::Mat result_image; cv::merge (image_planes, result_image); cv::imwrite (image_name.c_str (), result_image); #else if (3 == channels) { XCamDNN::save_bmp_file (image_name, &output_data[index * pixel_count * channels], get_output_format (index), get_output_precision (index), image_width, image_height); } #endif return XCAM_RETURN_NO_ERROR; } void* DnnInferenceEngine::get_inference_results (uint32_t idx, uint32_t& size) { if (! _model_created || ! _model_loaded) { XCAM_LOG_ERROR ("Please create and load the model firstly!"); return NULL; } std::string output_name; OutputsDataMap outputs_info (_network.getOutputsInfo ()); if (idx > outputs_info.size ()) { XCAM_LOG_ERROR ("Output is out of range"); return NULL; } if (NULL == _output_layer_type[_model_type]) { XCAM_LOG_ERROR ("Please set model output layer type!"); return NULL; } for (auto & out : outputs_info) { if ( !strncmp (out.second->creatorLayer.lock()->type.c_str (), _output_layer_type[_model_type], strlen(_output_layer_type[_model_type]))) { output_name = out.first; break; } } if (output_name.empty ()) { XCAM_LOG_ERROR ("out name is empty!"); return NULL; } const Blob::Ptr blob = _infer_request.GetBlob (output_name); float* output_result = static_cast<PrecisionTrait<Precision::FP32>::value_type*>(blob->buffer ()); size = blob->byteSize (); return (reinterpret_cast<void *>(output_result)); } InferenceEngine::TargetDevice DnnInferenceEngine::get_device_from_string (const std::string &device_name) { return InferenceEngine::TargetDeviceInfo::fromStr (device_name); } InferenceEngine::TargetDevice DnnInferenceEngine::get_device_from_id (DnnInferTargetDeviceType device) { switch (device) { case DnnInferDeviceDefault: return InferenceEngine::TargetDevice::eDefault; case DnnInferDeviceBalanced: return InferenceEngine::TargetDevice::eBalanced; case DnnInferDeviceCPU: return InferenceEngine::TargetDevice::eCPU; case DnnInferDeviceGPU: return InferenceEngine::TargetDevice::eGPU; case DnnInferDeviceFPGA: return InferenceEngine::TargetDevice::eFPGA; case DnnInferDeviceMyriad: return InferenceEngine::TargetDevice::eMYRIAD; case DnnInferDeviceHetero: return InferenceEngine::TargetDevice::eHETERO; default: return InferenceEngine::TargetDevice::eCPU; } } InferenceEngine::Layout DnnInferenceEngine::estimate_layout_type (const int ch_num) { if (ch_num == 4) { return InferenceEngine::Layout::NCHW; } else if (ch_num == 3) { return InferenceEngine::Layout::CHW; } else if (ch_num == 2) { return InferenceEngine::Layout::NC; } else { return InferenceEngine::Layout::ANY; } } InferenceEngine::Layout DnnInferenceEngine::convert_layout_type (DnnInferLayoutType layout) { switch (layout) { case DnnInferLayoutNCHW: return InferenceEngine::Layout::NCHW; case DnnInferLayoutNHWC: return InferenceEngine::Layout::NHWC; case DnnInferLayoutOIHW: return InferenceEngine::Layout::OIHW; case DnnInferLayoutC: return InferenceEngine::Layout::C; case DnnInferLayoutCHW: return InferenceEngine::Layout::CHW; case DnnInferLayoutHW: return InferenceEngine::Layout::HW; case DnnInferLayoutNC: return InferenceEngine::Layout::NC; case DnnInferLayoutCN: return InferenceEngine::Layout::CN; case DnnInferLayoutBlocked: return InferenceEngine::Layout::BLOCKED; case DnnInferLayoutAny: return InferenceEngine::Layout::ANY; default: return InferenceEngine::Layout::ANY; } } DnnInferLayoutType DnnInferenceEngine::convert_layout_type (InferenceEngine::Layout layout) { switch (layout) { case InferenceEngine::Layout::NCHW: return DnnInferLayoutNCHW; case InferenceEngine::Layout::NHWC: return DnnInferLayoutNHWC; case InferenceEngine::Layout::OIHW: return DnnInferLayoutOIHW; case InferenceEngine::Layout::C: return DnnInferLayoutC; case InferenceEngine::Layout::CHW: return DnnInferLayoutCHW; case InferenceEngine::Layout::HW: return DnnInferLayoutHW; case InferenceEngine::Layout::NC: return DnnInferLayoutNC; case InferenceEngine::Layout::CN: return DnnInferLayoutCN; case InferenceEngine::Layout::BLOCKED: return DnnInferLayoutBlocked; case InferenceEngine::Layout::ANY: return DnnInferLayoutAny; default: return DnnInferLayoutAny; } } InferenceEngine::Precision DnnInferenceEngine::convert_precision_type (DnnInferPrecisionType precision) { switch (precision) { case DnnInferPrecisionU8: return InferenceEngine::Precision::U8; case DnnInferPrecisionI8: return InferenceEngine::Precision::I8; case DnnInferPrecisionU16: return InferenceEngine::Precision::U16; case DnnInferPrecisionI16: return InferenceEngine::Precision::I16; case DnnInferPrecisionQ78: return InferenceEngine::Precision::Q78; case DnnInferPrecisionFP16: return InferenceEngine::Precision::FP16; case DnnInferPrecisionI32: return InferenceEngine::Precision::I32; case DnnInferPrecisionFP32: return InferenceEngine::Precision::FP32; case DnnInferPrecisionMixed: return InferenceEngine::Precision::MIXED; case DnnInferPrecisionCustom: return InferenceEngine::Precision::CUSTOM; case DnnInferPrecisionUnspecified: return InferenceEngine::Precision::UNSPECIFIED; default: return InferenceEngine::Precision::UNSPECIFIED; } } DnnInferPrecisionType DnnInferenceEngine::convert_precision_type (InferenceEngine::Precision precision) { switch (precision) { case InferenceEngine::Precision::MIXED: return DnnInferPrecisionMixed; case InferenceEngine::Precision::FP32: return DnnInferPrecisionFP32; case InferenceEngine::Precision::FP16: return DnnInferPrecisionFP16; case InferenceEngine::Precision::Q78: return DnnInferPrecisionQ78; case InferenceEngine::Precision::I16: return DnnInferPrecisionI16; case InferenceEngine::Precision::U8: return DnnInferPrecisionU8; case InferenceEngine::Precision::I8: return DnnInferPrecisionI8; case InferenceEngine::Precision::U16: return DnnInferPrecisionU16; case InferenceEngine::Precision::I32: return DnnInferPrecisionI32; case InferenceEngine::Precision::CUSTOM: return DnnInferPrecisionCustom; case InferenceEngine::Precision::UNSPECIFIED: return DnnInferPrecisionUnspecified; default: return DnnInferPrecisionUnspecified; } } std::string DnnInferenceEngine::get_filename_prefix (const std::string &file_path) { auto pos = file_path.rfind ('.'); if (pos == std::string::npos) { return file_path; } return file_path.substr (0, pos); } template <typename T> XCamReturn DnnInferenceEngine::copy_image_to_blob (const DnnInferData& data, Blob::Ptr& blob, int batch_index) { SizeVector blob_size = blob.get()->dims (); const size_t width = blob_size[0]; const size_t height = blob_size[1]; const size_t channels = blob_size[2]; const size_t image_size = width * height; unsigned char* buffer = (unsigned char*)data.buffer; T* blob_data = blob->buffer ().as<T*>(); if (width != data.width || height != data.height) { XCAM_LOG_ERROR ("Input Image size (%dx%d) is not matched with model required size (%dx%d)!", data.width, data.height, width, height); return XCAM_RETURN_ERROR_PARAM; } int batch_offset = batch_index * height * width * channels; if (DnnInferImageFormatBGRPlanar == data.image_format) { // B G R planar input image size_t image_stride_size = data.height_stride * data.width_stride; if (data.width == data.width_stride && data.height == data.height_stride) { std::memcpy (blob_data + batch_offset, buffer, image_size * channels); } else if (data.width == data.width_stride) { for (size_t ch = 0; ch < channels; ++ch) { std::memcpy (blob_data + batch_offset + ch * image_size, buffer + ch * image_stride_size, image_size); } } else { for (size_t ch = 0; ch < channels; ch++) { for (size_t h = 0; h < height; h++) { std::memcpy (blob_data + batch_offset + ch * image_size + h * width, buffer + ch * image_stride_size + h * data.width_stride, width); } } } } else if (DnnInferImageFormatBGRPacked == data.image_format) { for (size_t pid = 0; pid < image_size; pid++) { for (size_t ch = 0; ch < channels; ch++) { blob_data[batch_offset + ch * image_size + pid] = buffer[pid * channels + ch]; } } } return XCAM_RETURN_NO_ERROR; } template <typename T> XCamReturn DnnInferenceEngine::copy_data_to_blob (const DnnInferData& data, Blob::Ptr& blob, int batch_index) { SizeVector blob_size = blob.get ()->dims (); T * buffer = (T *)data.buffer; T* blob_data = blob->buffer ().as<T*>(); int batch_offset = batch_index * data.size; memcpy (blob_data + batch_offset, buffer, data.size); return XCAM_RETURN_NO_ERROR; } void DnnInferenceEngine::print_performance_counts (const std::map<std::string, InferenceEngine::InferenceEngineProfileInfo>& performance_map) { long long total_time = 0; XCAM_LOG_DEBUG ("performance counts:"); for (const auto & it : performance_map) { std::string to_print(it.first); const int max_layer_name = 30; if (it.first.length () >= max_layer_name) { to_print = it.first.substr (0, max_layer_name - 4); to_print += "..."; } XCAM_LOG_DEBUG ("layer: %s", to_print.c_str ()); switch (it.second.status) { case InferenceEngine::InferenceEngineProfileInfo::EXECUTED: XCAM_LOG_DEBUG ("EXECUTED"); break; case InferenceEngine::InferenceEngineProfileInfo::NOT_RUN: XCAM_LOG_DEBUG ("NOT_RUN"); break; case InferenceEngine::InferenceEngineProfileInfo::OPTIMIZED_OUT: XCAM_LOG_DEBUG ("OPTIMIZED_OUT"); break; } XCAM_LOG_DEBUG ("layerType: %s", std::string (it.second.layer_type).c_str ()); XCAM_LOG_DEBUG ("realTime: %d", it.second.realTime_uSec); XCAM_LOG_DEBUG ("cpu: %d", it.second.cpu_uSec); XCAM_LOG_DEBUG ("execType: %s", it.second.exec_type); if (it.second.realTime_uSec > 0) { total_time += it.second.realTime_uSec; } } XCAM_LOG_DEBUG ("Total time: %d microseconds", total_time); } void DnnInferenceEngine::print_log (uint32_t flag) { std::map<std::string, InferenceEngine::InferenceEngineProfileInfo> perfomance_map; if (flag == DnnInferLogLevelNone) { return; } if (flag & DnnInferLogLevelEngine) { static_cast<InferenceEngine::InferenceEnginePluginPtr>(_plugin)->GetPerformanceCounts (perfomance_map, NULL); print_performance_counts (perfomance_map); } if (flag & DnnInferLogLevelLayer) { perfomance_map = _infer_request.GetPerformanceCounts (); print_performance_counts (perfomance_map); } } } // namespace XCam
C++
CL
e27773c77c65b48c4a15e246f0ec57e46dc74aa5fd49bba4c1cb2198c2cf2d44
/* * Copyright (c) 2007, 2011 University of Michigan, Ann Arbor. * All rights reserved. * * Redistribution and use in source and binary forms are permitted * provided that the above copyright notice and this paragraph are * duplicated in all such forms and that any documentation, * advertising materials, and other materials related to such * distribution and use acknowledge that the software was developed * by the University of Michigan, Ann Arbor. The name of the University * may not be used to endorse or promote products derived from this * software without specific prior written permission. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * Authors: Igor Guskov, Sugih Jamin * */ #include <stdlib.h> #include <sys/stat.h> #include <iostream> #include <fstream> #include <string> #define _USE_MATH_DEFINES #include <math.h> using namespace std; #ifndef _WIN32 #include <libgen.h> #else string buf_name; // define the dirname function for win32. const char* dirname(const char* path) { string path_copy(path); string::size_type last_slash = path_copy.find_last_of("/\\"); if (last_slash==string::npos) { buf_name.assign("."); } else { buf_name = path_copy.substr(0, last_slash); } cerr << buf_name << endl; return buf_name.c_str(); } const char* basename(const char* path) { string path_copy(path); string::size_type last_slash = path_copy.find_last_of("/\\"); if (last_slash == string::npos) { buf_name = path_copy; } else { buf_name = path_copy.substr(last_slash+1); } cerr << buf_name << endl; return buf_name.c_str(); } #endif #ifdef __APPLE__ #include <GLUT/glut.h> #else #include <GL/glew.h> #include <GL/glut.h> #endif #include "parseX3D.h" #include "scene.h" #include "shaders.h" // Global constants (image dimensions). const int WIDTH = 640; const int HEIGHT = 480; int screen_w = WIDTH; int screen_h = HEIGHT; int mouse_x, mouse_y; bool lb_down = false; bool rb_down = false; X3Scene* scene = NULL; //const float DEG_PER_PIXEL = 0.1f; typedef struct { char *vs; char *fs; GLuint pd; } shader_t; enum ShaderModeEnum { NONE, GOURAUD, PHONG, BLINN, INTERESTING, NSHADERS } shader_mode = NONE; shader_t shaders[] = { { NULL, NULL, 0 }, { (char *)"gouraud", NULL, 0 }, { (char *)"phong", (char *)"phong", 0 }, { (char *)"phong", (char *)"blinn", 0 }, { (char *)"interesting", (char *)"interesting", 0 }, }; bool shaders_supported = true; GLuint spd; // shader program object handle int count_lights = 0; void display() { glClearColor(0.0f, 0.0f, 0.4f, 0.0f); glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(shaders[shader_mode].pd); if (scene) { // setup the viewpoint cam if (shaders_supported) { // pass count_lights to shaders as a uniform variable int uid; if (shader_mode != NONE) { uid = glGetUniformLocation(shaders[shader_mode].pd, "numlights"); glUniform1i(uid, count_lights); } } // Render scene. glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glEnable(GL_LIGHTING); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glEnable(GL_NORMALIZE); glShadeModel(GL_SMOOTH); glColor3f(1.0f, 0.0f, 0.0f); scene->Render(); } glUseProgram(0); glutSwapBuffers(); return; } void kbd(unsigned char key, int x, int y) { switch(key) { case 'q': case 27: // ESC key exit(0); break; case '@': if (scene) { scene->viewpoint()->reset(); } break; case 'i': //if (GLEW_ARB_vertex_shader && GLEW_ARB_fragment_shader) { cout << "Loading interesting shaders." << endl; shader_mode = INTERESTING; //} else { // cerr << "shaders not supported." << endl; //} break; case 'g': cout << "Loading per-vertex Gouraud shaders." << endl; shader_mode = GOURAUD; break; case 'p': cout << "Loading per-pixel Phong shaders." << endl; shader_mode = PHONG; break; case 'b': cout << "Loading per-pixel Blinn-Phong shaders." << endl; shader_mode = BLINN; break; case 'n': shader_mode = NONE; cout << "Fixed-function pipeline mode (no programmable shaders)." << endl; break; } glutPostRedisplay(); return; } void reshape(int w, int h) { glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); if (scene) { float aspect = float(w) / h; gluPerspective(45.0f, aspect, 0.1f, 1000.0f); } screen_w = w; screen_h = h; return; } void mouse(int button, int state, int x, int y) { if (!scene) { return; } switch(button) { case GLUT_LEFT_BUTTON: if (state == GLUT_DOWN) { lb_down = true; mouse_x = x; mouse_y = y; } else if (state == GLUT_UP){ lb_down = false; } break; case GLUT_RIGHT_BUTTON: if (state == GLUT_DOWN) { rb_down = true; mouse_x = x; mouse_y = y; } else { rb_down = false; } break; default: break; } return; } void motion(int x, int y) { if (lb_down) { scene->viewpoint()->track_latlong(((float) (x - mouse_x))/screen_w, ((float) (y - mouse_y))/screen_h); } if (rb_down) { scene->viewpoint()->dolly(((float) (y - mouse_y))/screen_h); } mouse_x = x; mouse_y = y; glutPostRedisplay(); return; } int main(int argc, char** argv) { int i; struct stat filestat; if (argc<2) { cerr << "Usage: " << basename(argv[0]) << " <input>.x3d" << endl; return -1; } if (stat(argv[1], &filestat)) { cerr << basename(argv[0]) << ": " << argv[1] << ": No such file or directory" << endl; return(-1); } glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_ALPHA | GLUT_DEPTH); glutInitWindowSize(WIDTH, HEIGHT); glutInitWindowPosition(100, 100); glutCreateWindow(argv[1]); #ifndef __APPLE__ GLenum err = glewInit(); if (GLEW_OK != err) { /* Problem: glewInit failed, something is seriously wrong. */ cerr << "Error: " << glewGetErrorString(err) << endl; } cout << "Status: Using GLEW " << glewGetString(GLEW_VERSION) << endl; #endif /* __APPLE__ */ for (i = GOURAUD; i < NSHADERS; i++) { shaders_supported = InitShaders(shaders[i].vs, shaders[i].fs, &shaders[i].pd); if (!shaders_supported) { cerr << "Shaders init failed. Exiting." << endl; exit(-1); } } ifstream input_stream(argv[1]); X3Reader x3reader; scene = x3reader.Read(input_stream); // Setup lights. glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); scene->SetupLights(&count_lights); glPopMatrix(); // If there are no lights in the scene file, setup a default light. if (count_lights==0) { XVec4f light_pos(1, 1, 0, 1); glLightfv(GL_LIGHT0, GL_POSITION, light_pos); glEnable(GL_LIGHT0); count_lights = 1; } glutDisplayFunc(display); glutKeyboardFunc(kbd); glutReshapeFunc(reshape); glutMouseFunc(mouse); glutMotionFunc(motion); glutMainLoop(); exit(0); }
C++
CL
5562ab8f9c2e1a5eb066298b17d9a2d2e5419673086e3bf874c029178a0eba8c
#include "gfx_i.h" #include "GFX\gfx_bkgrndfx.h" #define MAX_ALPHA 255 //message for FX functions typedef enum { BKFXM_CREATE, BKFXM_UPDATE, BKFXM_DISPLAY, BKFXM_DESTROY } FXmessage; //signals for FX update typedef enum { BKFXsignal_animate, BKFXsignal_noanimate } BKFXsignal; /********************************************************** *********************************************************** Data structs for the background FXs *********************************************************** **********************************************************/ // // background FX main data struct for each type // #define GFXCLRVTX (GFXFVF_XYZRHW | GFXFVF_DIFFUSE) //xyzw and color typedef struct _gfxClrVtx { f32 x, y, z, rhw; u32 color; } gfxClrVtx; //fade in/out typedef struct _fadeinout { u8 r,g,b; //the color s32 curA; //current alpha u8 bFadeIn; //are we fading to the color? GFXVTXBUFF *vtx; //four point vtx } fadeinout; typedef struct _imgfadeinout { hTXT theImg; //image to transit to s32 curA; //current alpha u8 bFadeIn; //are we fading to the color? } imgfadeinout; //curtain typedef struct _curtain { hTXT curtainImg; //curtain to fall down u32 fadeColor; //fadeout color after curtain goes down } curtain; //fade away /* typedef struct _fadeaway_init { BYTE r,g,b; double delay; } curtain_init;*/ typedef struct _fadeaway { u8 rStart,gStart,bStart; u8 rEnd,gEnd,bEnd; s32 r,g,b; //current r/g/b s32 curA; //current alpha } fadeaway; /********************************************************** *********************************************************** The methods for all FX *********************************************************** **********************************************************/ //fade in/out s32 bkFadeInOutFunc(hBKFX bkFX, u32 message, LPARAM dumbParam, WPARAM otherParam) { fadeinout *thisData = (fadeinout *)bkFX->Data; switch(message) { case BKFXM_UPDATE: { f32 t = bkFX->time/bkFX->timeDelay; if(thisData->bFadeIn) thisData->curA = (s32)(t*MAX_ALPHA); else thisData->curA = (s32)(MAX_ALPHA - (t*MAX_ALPHA)); if(thisData->curA > MAX_ALPHA) thisData->curA = MAX_ALPHA; else if(thisData->curA < 0) thisData->curA = 0; gfxClrVtx *vtxData; u32 clr = D3DCOLOR_RGBA(thisData->r, thisData->g, thisData->b, thisData->curA); if(VtxLock(thisData->vtx, 0, 0,0, (void**)&vtxData, 0)) { vtxData[0].color = clr; vtxData[1].color = clr; vtxData[2].color = clr; vtxData[3].color = clr; VtxUnlock(thisData->vtx, 0); } if(t >= 1) { if(thisData->curA == MAX_ALPHA) //now fade out thisData->bFadeIn = FALSE; else if(thisData->curA == 0) //check to see if we are over return GFXRET_BREAK; } } break; case BKFXM_DISPLAY: if(thisData->bFadeIn) { TextureBegin(); GFXScreenDisplay(0,0,0); TextureEnd(); } VtxSet(thisData->vtx); g_p3DDevice->DrawPrimitive(D3DPT_TRIANGLEFAN, 0, 2); VtxUnset(thisData->vtx); break; case BKFXM_CREATE: { fadeinout_init *initData = (fadeinout_init *)dumbParam; if(!initData) return GFXRET_FAILURE; fadeinout *newData = (fadeinout *)MemAlloc(sizeof(fadeinout)); if(!newData) return GFXRET_FAILURE; newData->r = initData->r; newData->g = initData->g; newData->b = initData->b; //start at alpha = 0 and bFadeIn = true newData->curA = 0; newData->bFadeIn = TRUE; //create flat plane newData->vtx = GFXCreateVtxBuff(sizeof(gfxClrVtx), 4, GFXUSAGE_WRITEONLY, GFXCLRVTX, GFXPOOL_MANAGED); if(!newData->vtx) return GFXRET_FAILURE; gfxClrVtx *vtxData; u32 clr = D3DCOLOR_RGBA(newData->r, newData->g, newData->b, newData->curA); if(VtxLock(newData->vtx, 0, 0,0, (void**)&vtxData, 0)) { vtxData[0].x = 0; vtxData[0].y = 0; vtxData[0].z = 0; vtxData[0].rhw = 1.0f; vtxData[0].color = clr; vtxData[1].x = 0; vtxData[1].y = g_mode.height; vtxData[1].z = 0; vtxData[1].rhw = 1.0f; vtxData[1].color = clr; vtxData[2].x = g_mode.width; vtxData[2].y = g_mode.height; vtxData[2].z = 0; vtxData[2].rhw = 1.0f; vtxData[2].color = clr; vtxData[3].x = g_mode.width; vtxData[3].y = 0; vtxData[3].z = 0; vtxData[3].rhw = 1.0f; vtxData[3].color = clr; VtxUnlock(newData->vtx, 0); } bkFX->Data = newData; //get a snap-shot of the screen GFXScreenCapture(); } break; case BKFXM_DESTROY: { if(thisData) GFXDestroyVtxBuff(thisData->vtx); } break; } return GFXRET_SUCCESS; } //image fade in/out s32 bkImgFadeInOutFunc(hBKFX bkFX, u32 message, LPARAM dumbParam, WPARAM otherParam) { imgfadeinout *thisData = (imgfadeinout *)bkFX->Data; switch(message) { case BKFXM_UPDATE: { f32 t = bkFX->time/bkFX->timeDelay; if(thisData->bFadeIn) thisData->curA = (s32)(t*MAX_ALPHA); else thisData->curA = (s32)(MAX_ALPHA - (t*MAX_ALPHA)); if(thisData->curA > MAX_ALPHA) thisData->curA = MAX_ALPHA; else if(thisData->curA < 0) thisData->curA = 0; if(t >= 1) { if(thisData->curA == MAX_ALPHA) //now fade out thisData->bFadeIn = FALSE; else if(thisData->curA == 0) //check to see if we are over return GFXRET_BREAK; } } break; case BKFXM_DISPLAY: { TextureBegin(); if(thisData->bFadeIn) GFXScreenDisplay(0,0,0); gfxBlt bltDat={0}; bltDat.clr = GFXCOLOR_RGBA(255, 255, 255, thisData->curA); thisData->theImg->StretchBlt(0, 0, g_mode.width,g_mode.height,0,&bltDat); TextureEnd(); } break; case BKFXM_CREATE: { imgfadeinout_init *initData = (imgfadeinout_init *)dumbParam; if(!initData) return GFXRET_FAILURE; imgfadeinout *newData = (imgfadeinout *)MemAlloc(sizeof(imgfadeinout)); if(!newData) return GFXRET_FAILURE; //start at alpha = 0 and bFadeIn = true newData->curA = 0; newData->bFadeIn = TRUE; //add ref to texture newData->theImg = initData->theImg; newData->theImg->AddRef(); bkFX->Data = newData; //get a snap-shot of the screen GFXScreenCapture(); } break; case BKFXM_DESTROY: if(thisData) SAFE_RELEASE(thisData->theImg); break; } return GFXRET_SUCCESS; } //fade away s32 bkFadeAwayFunc(hBKFX bkFX, u32 message, LPARAM dumbParam, WPARAM otherParam) { fadeaway *thisData = (fadeaway *)bkFX->Data; switch(message) { case BKFXM_UPDATE: { f32 t = bkFX->time/bkFX->timeDelay; thisData->curA = (s32)(MAX_ALPHA - (t*MAX_ALPHA)); if(thisData->curA < 0) thisData->curA = 0; thisData->r = thisData->rStart + t*(thisData->rEnd-thisData->rStart); thisData->g = thisData->gStart + t*(thisData->gEnd-thisData->gStart); thisData->b = thisData->bStart + t*(thisData->bEnd-thisData->bStart); if(t >= 1) { if(thisData->curA == 0) //check to see if we are over return GFXRET_BREAK; } } break; case BKFXM_DISPLAY: { gfxBlt bltDat={0}; bltDat.clr = GFXCOLOR_RGBA(thisData->r,thisData->g,thisData->b,thisData->curA); TextureBegin(); GFXScreenDisplay(0,0,&bltDat); TextureEnd(); } break; case BKFXM_CREATE: { fadeaway_init *initData = (fadeaway_init *)dumbParam; if(!initData) return GFXRET_FAILURE; fadeaway *newData = (fadeaway *)MemAlloc(sizeof(fadeaway)); if(!newData) return GFXRET_FAILURE; //start at alpha = 255 newData->curA = MAX_ALPHA; newData->rEnd = initData->r; newData->gEnd = initData->g; newData->bEnd = initData->b; newData->rStart = newData->gStart = newData->bStart = MAX_ALPHA; bkFX->Data = newData; //get a snap-shot of the screen GFXScreenCapture(); } break; case BKFXM_DESTROY: break; } return GFXRET_SUCCESS; } // // A bunch of FX functions // static BKEFFECT BKEffectTable[eBKFX_MAX] = {bkFadeInOutFunc,bkImgFadeInOutFunc,bkFadeAwayFunc}; ///////////////////////////////////// // Name: BKFXDestroy // Purpose: destroys given bkFX // Output: stuff destroyed // Return: none ///////////////////////////////////// void F_API BKFXDestroy(hBKFX bkFX) { if(bkFX) { if(bkFX->Effect) bkFX->Effect(bkFX, BKFXM_DESTROY, 0, 0); if(bkFX->Data) MemFree(bkFX->Data); MemFree(bkFX); } bkFX=0; } ///////////////////////////////////// // Name: BKFXCreate // Purpose: creates a background FX // Output: none // Return: the new background FX ///////////////////////////////////// hBKFX F_API BKFXCreate(u32 type, f32 delay, void *initStruct) { hBKFX newBkFX = (hBKFX)MemAlloc(sizeof(gfxBkFX)); if(!newBkFX) { LogMsg(LOG_FILE, L"BKFXCreate", L"Unable to allocate new background FX"); return 0; } newBkFX->Type = type; newBkFX->time = 0; newBkFX->timeDelay = delay; newBkFX->Effect = BKEffectTable[type]; if(newBkFX->Effect(newBkFX, BKFXM_CREATE, (LPARAM)initStruct, 0) != GFXRET_SUCCESS) { LogMsg(LOG_FILE, L"BKFXCreate", L"Unable to allocate new background FX"); BKFXDestroy(newBkFX); return 0; } return newBkFX; } ///////////////////////////////////// // Name: BKFXUpdate // Purpose: updates and displays the // background FX // Output: stuff displayed // Return: -1 if duration // is over or FX expired ///////////////////////////////////// s32 F_API BKFXUpdate(hBKFX bkFX) { bkFX->time += g_time; s32 ret = bkFX->Effect(bkFX, BKFXM_UPDATE, 0, 0); if(bkFX->time >= bkFX->timeDelay) bkFX->time = 0; return ret; } ///////////////////////////////////// // Name: BKFXDisplay // Purpose: display background FX // Output: stuff // Return: success ///////////////////////////////////// s32 F_API BKFXDisplay(hBKFX bkFX) { return bkFX->Effect(bkFX, BKFXM_DISPLAY, 0, 0); }
C++
CL
fe0ec83b4314f1bfd2f1bba9ed762a71eb17547be781a4410aec108f1c4b4856
#ifndef MAINWINDOWMF_H #define MAINWINDOWMF_H #include <QMainWindow> #include <QObject> #include <QGridLayout> #include <QPushButton> #include<QLabel> #include <QFileInfo> #include<QFileDialog> #include "preprocessing.h" #include "recorder.h" #include "renderarea.h" #include "indexmanager.h" namespace Ui { class MainWindowMF; } class MainWindowMF : public QMainWindow { Q_OBJECT public: explicit MainWindowMF(QWidget *parent = 0); ~MainWindowMF(); Preprocessing* preprocessing; Recorder* recorder; IndexManager* indexManager; RenderArea* renderArea; private slots: void Decode(); void RecordSwitch(); void ChooseFile(); void StartSearch(); void UpdateLibrary(); void DisplaySearchResult(QString res); void UpdateTag(std::vector<int> newTag); void OnDecodeFinish(); void on_pushButton_clicked(); void on_pushButton_3_clicked(); void on_pushButton_5_clicked(); private: Ui::MainWindowMF *ui; void DisableUpdate(); void EnableUpdate(); QLabel* fileLabel; bool isRecording; bool isImported; bool isLibraryToBeUpdated; }; #endif // MAINWINDOWMF_H
C++
CL
dd2203e680745cad3e2a36ff2c79c88634a0066db2ab06848361b7712f6f059c
// File: TopOpeBRepDS_Explorer.cxx // Created: Tue Jan 5 17:12:38 1999 // Author: Jean Yves LEBEY // <[email protected]> #define No_Standard_NoMoreObject #define No_Standard_NoSuchObject #include <TopOpeBRepDS_Explorer.ixx> #include <TopOpeBRepDS_define.hxx> #include <TopoDS.hxx> //======================================================================= //function : TopOpeBRepDS_Explorer //purpose : //======================================================================= TopOpeBRepDS_Explorer::TopOpeBRepDS_Explorer() :myT(TopAbs_SHAPE),myI(1),myN(0),myB(Standard_False),myFK(Standard_True) { } //======================================================================= //function : TopOpeBRepDS_Explorer //purpose : //======================================================================= TopOpeBRepDS_Explorer::TopOpeBRepDS_Explorer (const Handle(TopOpeBRepDS_HDataStructure)& HDS,const TopAbs_ShapeEnum T,const Standard_Boolean FK) { Init(HDS,T,FK); } //======================================================================= //function : Init //purpose : //======================================================================= void TopOpeBRepDS_Explorer::Init (const Handle(TopOpeBRepDS_HDataStructure)& HDS,const TopAbs_ShapeEnum T,const Standard_Boolean FK) { myI = 1; myN = 0; myB = Standard_False; myFK = Standard_True; myT = T; myHDS = HDS; if (myHDS.IsNull()) return; myN = myHDS->NbShapes(); myFK = FK; Find(); } //======================================================================= //function : Type //purpose : //======================================================================= TopAbs_ShapeEnum TopOpeBRepDS_Explorer::Type() const { return myT; } //======================================================================= //function : Find //purpose : //======================================================================= void TopOpeBRepDS_Explorer::Find() { Standard_Boolean found = Standard_False; const TopOpeBRepDS_DataStructure& BDS = myHDS->DS(); while ( (myI <= myN) && (!found) ) { Standard_Boolean b = BDS.KeepShape(myI,myFK); if (b) { const TopoDS_Shape& s = BDS.Shape(myI,Standard_False); TopAbs_ShapeEnum t = s.ShapeType(); if ( t == myT || myT == TopAbs_SHAPE ) found = Standard_True; else myI++; } else myI++; } myB = found; } //======================================================================= //function : More //purpose : //======================================================================= Standard_Boolean TopOpeBRepDS_Explorer::More() const { return myB; } //======================================================================= //function : Next //purpose : //======================================================================= void TopOpeBRepDS_Explorer::Next() { Standard_NoMoreObject_Raise_if(!myB,"TopOpeBRepDS_Explorer::Next"); myI++; Find(); } //======================================================================= //function : Current //purpose : //======================================================================= const TopoDS_Shape& TopOpeBRepDS_Explorer::Current() const { Standard_NoSuchObject_Raise_if(!More(),"TopOpeBRepDS_Explorer::Current"); return myHDS->Shape(myI); } //======================================================================= //function : Index //purpose : //======================================================================= Standard_Integer TopOpeBRepDS_Explorer::Index() const { Standard_NoSuchObject_Raise_if(!More(),"TopOpeBRepDS_Explorer::Index"); return myI; } //======================================================================= //function : Face //purpose : //======================================================================= const TopoDS_Face& TopOpeBRepDS_Explorer::Face() const { Standard_NoSuchObject_Raise_if(!More(),"TopOpeBRepDS_Explorer::Face"); const TopoDS_Shape& s = Current(); const TopoDS_Face& f = TopoDS::Face(s); return f; } //======================================================================= //function : Edge //purpose : //======================================================================= const TopoDS_Edge& TopOpeBRepDS_Explorer::Edge() const { Standard_NoSuchObject_Raise_if(!More(),"TopOpeBRepDS_Explorer::Edge"); const TopoDS_Shape& s = Current(); const TopoDS_Edge& e = TopoDS::Edge(s); return e; } //======================================================================= //function : Vertex //purpose : //======================================================================= const TopoDS_Vertex& TopOpeBRepDS_Explorer::Vertex() const { Standard_NoSuchObject_Raise_if(!More(),"TopOpeBRepDS_Explorer::Vertex"); const TopoDS_Shape& s = Current(); const TopoDS_Vertex& v = TopoDS::Vertex(s); return v; }
C++
CL
6876afddb59f070bf3cbac2de3eaa988b37017c0f3ae8dd2b427996fb6632ce5
#pragma once #include "Vertex.h" #include "Line.h" #include <vector> //projection plane constants const int DEPTH_X = 1; const int DEPTH_Y = 2; const int DEPTH_Z = 3; class Triangle { //vertex indices int v1index; int v2index; int v3index; //Vertices Vertex v1; Vertex v2; Vertex v3; Line lines[3]; glm::vec3 depth; //Depth in each direction float projdepth; //Depth in one direction (x, y, or z) glm::vec3 normal; public: Triangle(); ~Triangle(); void InitializeTriangle(ifstream &inputfile, vector<Vertex> vertices); void CreateLines(); void WriteToOutput(ofstream &outputfile); //World Plane //Calculating the depth void calculateDepth(vector<Vertex> vertices); float MinX(vector<Vertex> vertices); float MinY(vector<Vertex> vertices); float MinZ(vector<Vertex> vertices); glm::vec3 getNormal(); //Misc bool containsVertex(int vertexindex); //NDC Plane //Projection Plane //Pixel Plane void setPixel(float *buffer, int x, int y, int height, glm::vec3 color); //Rasterization glm::vec3 GouraudShading(int x, int y, Vertex v1, Vertex v2, Vertex v3); float calculateArea(glm::vec2 p1, glm::vec2 p2, glm::vec2 p3); //Triangle-by-triangle rendering //Drawing the vertices void drawVertices(float *buffer, int bufferheight); //Drawing the lines void drawLinesDDA(float *buffer, int bufferHeight); //Rasterization void Rasterize(int xresolution, int yresolution, float *polygonBuffer); bool RasterizeException(int x, int y, int xresolution, int yresolution, float *polygonBuffer); bool RastHorizontalLine(int x, int y, int xresolution, int yresolution, float *polygonBuffer); bool RastVertex(int x, int y, int yresolution, float *polygonBuffer); bool loneHorizontalLine(int y, int xresolution, int yresolution, float *polygonBuffer); //Misc bool isZero(int x, int y, int height, float *buffer); void shadePixel(int x, int y, int height, float *buffer, Vertex v1, Vertex v2, Vertex v3); void setVertices(vector<Vertex> vertices); void verticesToLines(vector<Vertex> vertices); void setProjDepth(int depthaxis); friend bool operator <(Triangle t1, Triangle t2); //~~~~~~~~~~~~~~~~~~~~~~~~~~Experimental Functions~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //Experimental Rasterization algorithm void RasterizeTriangle(int xresolution, int yresolution, float *buffer); int numPixelsInRow(float *buffer, int y, int xresolution, int yresolution); int leftMostX(float *buffer, int y, int xresolution, int yresolution); int rightMostX(float *buffer, int y, int xresolution, int yresolution); //~~~~~~~~~~~~~~~~~~~~~~~~~~~Unused functions~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //Calculate the normal (incomplete) void calculateNormal(vector <Vertex> vertices, int vertexnum); //Polygon by polygon rendering //Line Drawing (polygon by polgon) void DrawLinesDDA(float *buffer, int yresolution, vector<Vertex> vertices); };
C++
CL
13e64497fea82d0ea949c6980527cc9eee51f7d26f4f21c6ac6aebfef8d1ca52
#ifndef __XSD_ENUMERATION_GRAPH_NODE_H__ #define __XSD_ENUMERATION_GRAPH_NODE_H__ #include <yars/configuration/xsd/graphviz/graph/XsdGraphNode.h> #include <yars/configuration/xsd/specification/XsdEnumeration.h> #include <string> #include <sstream> using namespace std; class XsdEnumerationGraphNode : public XsdGraphNode { public: XsdEnumerationGraphNode(XsdEnumeration *spec); string customLabel(string label); string content(); string name(); XsdEnumeration* spec(); private: stringstream _oss; XsdEnumeration *_spec; string _specification; string _type; }; #endif // __XSD_ENUMERATION_GRAPH_NODE_H__
C++
CL
11de6f27cd8a93bda32832a322264be1381aa29adbfb538e2373e964dd81f498
// // libtgvoip is free and unencumbered public domain software. // For more information, see http://unlicense.org or the UNLICENSE file // you should have received with this source code distribution. // #include "AudioOutputAndroid.h" #include <stdio.h> #include "../../logging.h" extern JavaVM* sharedJVM; jmethodID CAudioOutputAndroid::initMethod=NULL; jmethodID CAudioOutputAndroid::releaseMethod=NULL; jmethodID CAudioOutputAndroid::startMethod=NULL; jmethodID CAudioOutputAndroid::stopMethod=NULL; jclass CAudioOutputAndroid::jniClass=NULL; CAudioOutputAndroid::CAudioOutputAndroid(){ JNIEnv* env=NULL; bool didAttach=false; sharedJVM->GetEnv((void**) &env, JNI_VERSION_1_6); if(!env){ sharedJVM->AttachCurrentThread(&env, NULL); didAttach=true; } jmethodID ctor=env->GetMethodID(jniClass, "<init>", "(J)V"); jobject obj=env->NewObject(jniClass, ctor, (jlong)(intptr_t)this); javaObject=env->NewGlobalRef(obj); if(didAttach){ sharedJVM->DetachCurrentThread(); } running=false; } CAudioOutputAndroid::~CAudioOutputAndroid(){ JNIEnv* env=NULL; bool didAttach=false; sharedJVM->GetEnv((void**) &env, JNI_VERSION_1_6); if(!env){ sharedJVM->AttachCurrentThread(&env, NULL); didAttach=true; } env->CallVoidMethod(javaObject, releaseMethod); env->DeleteGlobalRef(javaObject); javaObject=NULL; if(didAttach){ sharedJVM->DetachCurrentThread(); } } void CAudioOutputAndroid::Configure(uint32_t sampleRate, uint32_t bitsPerSample, uint32_t channels){ JNIEnv* env=NULL; bool didAttach=false; sharedJVM->GetEnv((void**) &env, JNI_VERSION_1_6); if(!env){ sharedJVM->AttachCurrentThread(&env, NULL); didAttach=true; } env->CallVoidMethod(javaObject, initMethod, sampleRate, bitsPerSample, channels, 960*2); if(didAttach){ sharedJVM->DetachCurrentThread(); } } void CAudioOutputAndroid::Start(){ JNIEnv* env=NULL; bool didAttach=false; sharedJVM->GetEnv((void**) &env, JNI_VERSION_1_6); if(!env){ sharedJVM->AttachCurrentThread(&env, NULL); didAttach=true; } env->CallVoidMethod(javaObject, startMethod); if(didAttach){ sharedJVM->DetachCurrentThread(); } running=true; } void CAudioOutputAndroid::Stop(){ running=false; JNIEnv* env=NULL; bool didAttach=false; sharedJVM->GetEnv((void**) &env, JNI_VERSION_1_6); if(!env){ sharedJVM->AttachCurrentThread(&env, NULL); didAttach=true; } env->CallVoidMethod(javaObject, stopMethod); if(didAttach){ sharedJVM->DetachCurrentThread(); } } void CAudioOutputAndroid::HandleCallback(JNIEnv* env, jbyteArray buffer){ if(!running) return; unsigned char* buf=(unsigned char*) env->GetByteArrayElements(buffer, NULL); size_t len=(size_t) env->GetArrayLength(buffer); InvokeCallback(buf, len); env->ReleaseByteArrayElements(buffer, (jbyte *) buf, 0); } bool CAudioOutputAndroid::IsPlaying(){ return false; } float CAudioOutputAndroid::GetLevel(){ return 0; }
C++
CL
a2b528b636b134ea3fa730b4246980f57ba93fc46d5c5ba57c467351560dc361
/********************************* PCF8574_HD44780_I2C Library for PCF8574 Breakout Board by Testato on ArduinoForum based on code from: - Mario H. **********************************/ #ifndef PCF8574_HD44780_I2C_h #define PCF8574_HD44780_I2C_h #include <inttypes.h> #include "Print.h" #include <Wire.h> // Expander I/O port #define P7 7 #define P6 6 #define P5 5 #define P4 4 #define P3 3 #define P2 2 #define P1 1 #define P0 0 // LCD signals #define LCD_BACKLIGHT _BV(P3) // Led ON #define LCD_NOBACKLIGHT 0x00 // Led OFF #define En _BV(P2) // Enable #define Rw _BV(P1) // Read/Write #define Rs _BV(P0) // Register select // commands #define LCD_CLEARDISPLAY 0x01 #define LCD_RETURNHOME 0x02 #define LCD_ENTRYMODESET 0x04 #define LCD_DISPLAYCONTROL 0x08 #define LCD_CURSORSHIFT 0x10 #define LCD_FUNCTIONSET 0x20 #define LCD_SETCGRAMADDR 0x40 #define LCD_SETDDRAMADDR 0x80 // flags for display entry mode #define LCD_ENTRYLEFT 0x02 // I/D Increment #define LCD_ENTRYRIGHT 0x00 // I/D Decrement #define LCD_ENTRYSHIFTINCREMENT 0x01// S Accompanies display shift #define LCD_ENTRYSHIFTDECREMENT 0x00 // flags for display on/off control #define LCD_DISPLAYON 0x04 // D #define LCD_DISPLAYOFF 0x00 #define LCD_CURSORON 0x02 // C #define LCD_CURSOROFF 0x00 #define LCD_BLINKON 0x01 // B #define LCD_BLINKOFF 0x00 // flags for cursor/display shift #define LCD_DISPLAYMOVE 0x08 // S/C Display shift #define LCD_CURSORMOVE 0x00 // S/C Cursor move #define LCD_MOVERIGHT 0x04 // R/L Shift to the right #define LCD_MOVELEFT 0x00 // R/L Shift to the left // flags for function set #define LCD_8BITMODE 0x10 // DL #define LCD_4BITMODE 0x00 #define LCD_2LINE 0x08 // N #define LCD_1LINE 0x00 #define LCD_5x10DOTS 0x04 // F #define LCD_5x8DOTS 0x00 class PCF8574_HD44780_I2C : public Print { public: PCF8574_HD44780_I2C(uint8_t lcd_Addr,uint8_t lcd_cols,uint8_t lcd_rows); void begin(uint8_t cols, uint8_t rows, uint8_t charsize = LCD_5x8DOTS ); void clear(); void home(); void noDisplay(); void display(); void noBlink(); void blink(); void noCursor(); void cursor(); void scrollDisplayLeft(); void scrollDisplayRight(); void printLeft(); void printRight(); void leftToRight(); void rightToLeft(); void shiftIncrement(); void shiftDecrement(); void noBacklight(); void backlight(); void autoscroll(); void noAutoscroll(); void createChar(uint8_t, uint8_t[]); void setCursor(uint8_t, uint8_t); virtual size_t write(uint8_t); void command(uint8_t); void init(); ////compatibility API function aliases void blink_on(); // alias for blink() void blink_off(); // alias for noBlink() void cursor_on(); // alias for cursor() void cursor_off(); // alias for noCursor() void setBacklight(uint8_t new_val); // alias for backlight() and nobacklight() void load_custom_character(uint8_t char_num, uint8_t *rows); // alias for createChar() void printstr(const char[]); ////Unsupported API functions (not implemented in this library) uint8_t status(); void setContrast(uint8_t new_val); uint8_t keypad(); void setDelay(int,int); void on(); void off(); uint8_t init_bargraph(uint8_t graphtype); void draw_horizontal_graph(uint8_t row, uint8_t column, uint8_t len, uint8_t pixel_col_end); void draw_vertical_graph(uint8_t row, uint8_t column, uint8_t len, uint8_t pixel_col_end); private: void init_priv(); void send(uint8_t, uint8_t); void write4bits(uint8_t); void expanderWrite(uint8_t); void pulseEnable(uint8_t); uint8_t _Addr; uint8_t _displayfunction; uint8_t _displaycontrol; uint8_t _displaymode; uint8_t _numlines; uint8_t _cols; uint8_t _rows; uint8_t _backlightval; }; #endif
C++
CL
c5d5d19cebdfdc294966649bc8dcfede253cd317b9156b2455a4f1dc936d6221
#include "DataExchangeReaderListener.h" #include "AmbassadorPrivate.h" #include "DataExchangeTypeSupportC.h" #include "DataExchangeTypeSupportImpl.h" #include "InterationClass.h" #include "InterationInstanceImpl.h" #include "ObjectClass.h" #include "ObjectInstanceImpl.h" #include <iostream> #include <sstream> #include <boost/archive/text_iarchive.hpp> #include <boost/archive/binary_iarchive.hpp> #include <boost/serialization/string.hpp> #include <boost/serialization/vector.hpp> #include <boost/serialization/variant.hpp> #include <stdio.h> #include <time.h> #include <fstream> #include <stdlib.h> #include <exception> #include <boost/log/core.hpp> #include <boost/log/trivial.hpp> //#include <boost/log/expressions.hpp> //#include <boost/log/sinks/text_file_backend.hpp> //#include <boost/log/utility/setup/file.hpp> //#include <boost/log/utility/setup/common_attributes.hpp> //#include <boost/log/sources/severity_logger.hpp> //#include <boost/log/sources/record_ostream.hpp> #include "AmbassadorPrivate.h" #include "Ambassador.h" #include "InterationClass.h" #include "ObjectInstanceImpl.h" #include "DataExchangeReaderListener.h" #include <dds\DCPS\Time_helper.h> //namespace logging = boost::log; //namespace src = boost::log::sources; //namespace sinks = boost::log::sinks; //namespace keywords = boost::log::keywords; using namespace std; namespace Data_Exchange_Platform { DataExchangeReaderListener::DataExchangeReaderListener(AmbassadorPrivate* ambassador) :m_ambassador(ambassador), m_recvThread(boost::bind(&DataExchangeReaderListener::receiveInteration, this)), m_loop(true), m_max(100), m_num_samples(0) { inter = NULL; } DataExchangeReaderListener::DataExchangeReaderListener(InterationClass* interationClass, AmbassadorPrivate* amb) :inter(interationClass), m_ambassador(amb), m_recvThread(boost::bind(&DataExchangeReaderListener::receiveInteration, this)), m_loop(true), m_num_samples(0) { } void DataExchangeReaderListener::interrupt() { m_loop = false; m_recvThread.interrupt(); m_recvThread.join(); } void DataExchangeReaderListener::on_requested_deadline_missed(DDS::DataReader_ptr reader, const DDS::RequestedDeadlineMissedStatus & status) { BOOST_LOG_TRIVIAL(info) << reader->get_topicdescription()->get_name() << " reader on_requested_deadline_missed" << endl; } void DataExchangeReaderListener::on_requested_incompatible_qos(DDS::DataReader_ptr reader, const DDS::RequestedIncompatibleQosStatus & status) { BOOST_LOG_TRIVIAL(info) << reader->get_topicdescription()->get_name() << " reader on_requested_incompatible_qos" << endl; } void DataExchangeReaderListener::on_sample_rejected(DDS::DataReader_ptr reader, const DDS::SampleRejectedStatus & status) { BOOST_LOG_TRIVIAL(info) << reader->get_topicdescription()->get_name() << " reader on_sample_rejected" << endl; } void DataExchangeReaderListener::on_liveliness_changed(DDS::DataReader_ptr reader, const DDS::LivelinessChangedStatus & status) { BOOST_LOG_TRIVIAL(info) << reader->get_topicdescription()->get_name() << " reader on_liveliness_changed" << endl; } void DataExchangeReaderListener::on_data_available(DDS::DataReader_ptr reader) { DDS::SampleInfo info; try{ if (m_ambassador->m_attrDataListenerMap.find(this) != m_ambassador->m_attrDataListenerMap.end()) { ObjectClass::Attribute* attr = m_ambassador->m_attrDataListenerMap.at(this); ObjectAttributeDataReader_var attrReader = ObjectAttributeDataReader::_narrow(reader); if (!attrReader) { return; } ObjectAttribute objattr; DDS::ReturnCode_t error = attrReader->take_next_sample(objattr, info); if (error != DDS::RETCODE_OK) { return; } Variant value; std::istringstream is(std::string(objattr.attributeValue.get_buffer(), objattr.attributeValue.length())); boost::archive::binary_iarchive ia(is, boost::archive::no_header); ia >> value; ObjectInstanceImpl* instance = m_ambassador->objectInstance(objattr.instanceName.in(), objattr.className.in()); if (instance) { try { BOOST_LOG_TRIVIAL(trace) << "recv obj beg" << " runtime:" << std::setprecision(16) << Ambassador::runtime() << "ms"; m_ambassador->receiveObjectAttribute(instance, attr, value); BOOST_LOG_TRIVIAL(trace) << "recv obj end" << " runtime:" << std::setprecision(16) << Ambassador::runtime() << "ms"; } catch (...) { BOOST_LOG_TRIVIAL(error) << objattr.className << "." <<attr->attributeName() << "对象类处理异常" << endl; return; } } } if (m_ambassador->m_interDataListenerMap.find(this) != m_ambassador->m_interDataListenerMap.end()) { InterationClass* interClass = m_ambassador->m_interDataListenerMap.at(this); InterationsDataReader_var interReader = InterationsDataReader::_narrow(reader); if (!interReader) { return; } Interations interlst; DDS::ReturnCode_t error = interReader->take_next_sample(interlst, info); if (error != DDS::RETCODE_OK) { return ; } BOOST_LOG_TRIVIAL(trace) << "recv beg " << interClass->interationName() << " timeStamp: " << interlst.timeStamp << " runtime:" << std::setprecision(16) << Ambassador::runtime() << "ms"; std::istringstream is; boost::archive::binary_iarchive ia(is, boost::archive::no_header); for (int i = 0; i < interlst.interationlst.length(); i++) { Interation& inter = interlst.interationlst[i]; InterationInstanceImpl* instance = new InterationInstanceImpl(interClass); instance->setPubHandle(info.publication_handle); try { instance->setTimeStamp(inter.timeStamp); for (size_t i = 0; i < inter.parameterList.length()/*+1*/; i++) { Variant value; is.str(std::string(inter.parameterList[i].parameterValue.get_buffer(), inter.parameterList[i].parameterValue.length())); ia >> value; instance->setParameterValue(inter.parameterList[i].parameterName.in(), value); is.clear(); } } catch (...) { BOOST_LOG_TRIVIAL(error) << "接收序列化异常" << endl; return; } if (!interClass->persistent()) { BOOST_LOG_TRIVIAL(trace) << "mutex beg " << interClass->interationName() << " timeStamp: " << inter.timeStamp << " runtime:" << std::setprecision(16) << Ambassador::runtime() << "ms"; boost::mutex::scoped_lock lock(m_mutex); if (!m_queInstance.empty()) { while (m_ambassador->pushCheckInterationQueue(m_queInstance)) { delete m_queInstance.front(); m_queInstance.pop(); } } m_queInstance.push(instance); m_condition.notify_one(); BOOST_LOG_TRIVIAL(trace) << "mutex end " << interClass->interationName() << " timeStamp: " << inter.timeStamp << " runtime:" << std::setprecision(16) << Ambassador::runtime() << "ms"; } else { BOOST_LOG_TRIVIAL(trace) << "cu_op beg " << interClass->interationName() << " timeStamp: " << inter.timeStamp << " runtime:" << std::setprecision(16) << Ambassador::runtime() << "ms"; m_ambassador->receiveInterationInstance(instance); delete instance; BOOST_LOG_TRIVIAL(trace) << "cu_op end " << interClass->interationName() << " timeStamp: " << inter.timeStamp << " runtime:" << std::setprecision(16) << Ambassador::runtime() << "ms"; } } BOOST_LOG_TRIVIAL(trace) << "recv end " << interClass->interationName() << " timeStamp: " << interlst.timeStamp << " runtime:" << std::setprecision(16) << Ambassador::runtime() << "ms"; } } catch(...) { BOOST_LOG_TRIVIAL(error) << "接收函数on_data_available异常" << endl; return; } } void DataExchangeReaderListener::on_subscription_matched(DDS::DataReader_ptr reader, const DDS::SubscriptionMatchedStatus & status) { BOOST_LOG_TRIVIAL(info) << reader->get_topicdescription()->get_name() << " reader on_subscription_matched" << endl; } void DataExchangeReaderListener::on_sample_lost(DDS::DataReader_ptr reader, const DDS::SampleLostStatus & status) { BOOST_LOG_TRIVIAL(info) << reader->get_topicdescription()->get_name() << " reader on_sample_lost" << endl; } void DataExchangeReaderListener::receiveInteration() { try { std::string className; if (m_ambassador->m_interDataListenerMap.find(this) != m_ambassador->m_interDataListenerMap.end()) { InterationClass* interClass = m_ambassador->m_interDataListenerMap.at(this); className = interClass->interationName(); } while(this->m_loop) { boost::mutex::scoped_lock lock(this->m_mutex); InterationInstanceImpl* instance = nullptr; try { if (!this->m_queInstance.empty()) { if (this->m_ambassador->popCheckInterationQueue(this->m_queInstance)) { instance = this->m_queInstance.front(); BOOST_LOG_TRIVIAL(trace) << "th_op beg " << instance->interationClass()->interationName() << " timeStamp: " << instance->timeStamp() << " runtime:" << std::setprecision(16) << Ambassador::runtime() << "ms"; this->m_queInstance.pop(); this->m_ambassador->receiveInterationInstance(instance); BOOST_LOG_TRIVIAL(trace) << "th_op end " << instance->interationClass()->interationName() << " timeStamp: " << instance->timeStamp() << " runtime:" << std::setprecision(16) << Ambassador::runtime() << "ms"; delete instance; } else { this->m_condition.wait(lock); } } else { this->m_condition.wait(lock); } } catch (...) { BOOST_LOG_TRIVIAL(error) << className << " 接收交互类处理函数异常" << endl; //if (instance) //{ // delete instance; //} //this->m_condition.wait(lock); } } } catch (...) { BOOST_LOG_TRIVIAL(error) << "接收交互类线程异常" << endl; } } void DataExchangeReaderListener::on_subscription_disconnected(::DDS::DataReader_ptr reader, const ::OpenDDS::DCPS::SubscriptionDisconnectedStatus & status) { BOOST_LOG_TRIVIAL(info) << reader->get_topicdescription()->get_name() << " reader on_subscription_disconnected" << endl; } void DataExchangeReaderListener::on_subscription_reconnected(::DDS::DataReader_ptr reader, const ::OpenDDS::DCPS::SubscriptionReconnectedStatus & status) { BOOST_LOG_TRIVIAL(info) << reader->get_topicdescription()->get_name() << " reader on_subscription_reconnected" << endl; } void DataExchangeReaderListener::on_subscription_lost(::DDS::DataReader_ptr reader, const ::OpenDDS::DCPS::SubscriptionLostStatus & status) { BOOST_LOG_TRIVIAL(info) << reader->get_topicdescription()->get_name() << "reader on_subscription_lost" << endl; try { CORBA::ULong len = status.publication_handles.length(); for (CORBA::ULong i = 0; i < len; ++i) { BOOST_LOG_TRIVIAL(info) << "publication handles:" << status.publication_handles[i] << endl; if (m_loop&&m_ambassador->m_interDataListenerMap.find(this) != m_ambassador->m_interDataListenerMap.end()) { InterationClass* interClass = m_ambassador->m_interDataListenerMap.at(this); m_ambassador->subscriptionLost(interClass->interationName(), status.publication_handles[i]); } } } catch (...) { BOOST_LOG_TRIVIAL(error) << "subscription lost 异常" << endl; } } void DataExchangeReaderListener::on_connection_deleted(::DDS::DataReader_ptr reader) { BOOST_LOG_TRIVIAL(info) << reader->get_topicdescription()->get_name() << " reader on_connection_deleted" << endl; } void DataExchangeReaderListener::on_budget_exceeded(::DDS::DataReader_ptr reader, const ::OpenDDS::DCPS::BudgetExceededStatus & status) { BOOST_LOG_TRIVIAL(info) << reader->get_topicdescription()->get_name() << " reader on_budget_exceeded" << endl; } }
C++
CL
7b0708fc50e7ea6f76f6f1972bee87812bc2c1ce4c297f342f8ec2e84535209c
// // Created by views on 26.05.18. // #ifndef SERVER_PLAYER_H #define SERVER_PLAYER_H #include "../NetWork/Client.h" #include "../Graph/SetGraph.h" #include "../../common/Constants/ConstValues.h" #include "GameObject.h" class Pacman : public Samples::Unit { public: explicit Pacman(Client *client); Samples::Direction newDirection; bool haveCollision(SetGraph &gameMap, Samples::Direction direction); bool step(SetGraph &gameMap); void stepToDirection(Samples::Direction direction); void setRoundPosition(); // TODO: make private bool injured; const Client *client; // TODO: make shared ptr unsigned int injuredTimer; unsigned int dyingTimer; RoundPosition rPos; }; #endif //SERVER_PLAYER_H
C++
CL
8cedfff6b8fa96451fcccddb8dae0dc15037643012c8a832676d9c12f3ccec5c
/*=========================================================================== * * File: EsmBook.H * Author: Dave Humphrey ([email protected]) * Created On: February 3, 2003 * * Description * *=========================================================================*/ #ifndef __ESMBOOK_H #define __ESMBOOK_H /*=========================================================================== * * Begin Required Includes * *=========================================================================*/ #include "EsmItem3.h" #include "EsmSubBKDT.h" /*=========================================================================== * End of Required Includes *=========================================================================*/ /*=========================================================================== * * Begin Definitions * *=========================================================================*/ /*=========================================================================== * End of Definitions *=========================================================================*/ /*=========================================================================== * * Begin Class CEsmBook Definition * * Description * *=========================================================================*/ class CEsmBook : public CEsmItem3 { DECLARE_SUBRECCREATE(); /*---------- Begin Protected Class Members --------------------*/ protected: CEsmSubBKDT* m_pBookData; /* Reference to subrecords */ CEsmSubName* m_pText; /*---------- Begin Protected Class Methods --------------------*/ protected: /*---------- Begin Public Class Methods -----------------------*/ public: /* Class Constructors/Destructors */ CEsmBook(); //virtual ~CEsmBook() { Destroy(); } virtual void Destroy (void); /* Compare two fields of the record */ virtual int CompareFields (const int FieldID, CEsmRecord* pRecord); /* Return a new record object */ static CEsmRecord* Create (void); /* Create a new, empty, record */ virtual void CreateNew (CEsmFile* pFile); /* Get a string representation of a particular field */ virtual const TCHAR* GetFieldString (const int FieldID); /* Return a text representation of the item type */ virtual const TCHAR* GetItemType (void) { return _T("Book"); } /* Get class members */ bookdata_t* GetBookData (void) { return (m_pBookData == NULL ? NULL : m_pBookData->GetBookData() ); } const TCHAR* GetBookText (void) { return (m_pText ? m_pText->GetName() : _T("")); } virtual float GetWeight (void) { return (m_pBookData == NULL ? 0 : m_pBookData->GetWeight()); } virtual long GetValue (void) { return (m_pBookData == NULL ? 0 : m_pBookData->GetValue()); } virtual long GetEnchantPts (void) { return (m_pBookData == NULL ? 0 : m_pBookData->GetEnchantPts()); } int GetSkillID (void) { return (m_pBookData == NULL ? -1 : m_pBookData->GetSkillID()); } bool IsScroll (void) { return (m_pBookData == NULL ? false : m_pBookData->IsScroll()); } /* Used to save the various record elements */ virtual void OnAddSubRecord (CEsmSubRecord* pSubRecord); /* Set class members */ void SetScroll (const bool Flag) { if (m_pBookData) m_pBookData->SetScroll(Flag); } void SetSkillID (const int Skill) { if (m_pBookData) m_pBookData->SetSkillID(Skill); } void SetEnchantPts (const int Value) { if (m_pBookData) m_pBookData->SetEnchantPts(Value); } void SetWeight (const float Weight) { if (m_pBookData) m_pBookData->SetWeight(Weight); } void SetBookText (const TCHAR* pText) { if (m_pText) m_pText->SetName(pText); } virtual void SetValue (const long Value) { if (m_pBookData) m_pBookData->SetValue(Value); } /* Set a certain field of the record */ virtual bool SetFieldValue (const int FieldID, const TCHAR* pString); }; /*=========================================================================== * End of Class CEsmBook Definition *=========================================================================*/ /*=========================================================================== * * Begin Function Prototypes * *=========================================================================*/ /* Convert an armor type to a string */ const TCHAR* GetESMArmorType (const int ArmorType); /*=========================================================================== * End of Function Prototypes *=========================================================================*/ #endif /*=========================================================================== * End of File Esmarmor.H *=========================================================================*/
C++
CL
5da96396ebe2ab005a932d7fb171e71336fb37dbc6f4841ce2c7ec3cacecf69b
#ifndef YMLESSONMANAGERADAPTER_H #define YMLESSONMANAGERADAPTER_H #include <QObject> #include <QJsonArray> #include <QJsonObject> #include "YMHttpClient.h" #include<QSsl> #include<QSslSocket> #include <openssl/des.h> #include "ymcrypt.h" #include<QDataStream> #include<QTextStream> #include<QSettings> #include <QMutex> #include <QHttpMultiPart> #include"../../pc-common/qosManager/YMQosManager.h" #include<QNetworkConfigurationManager> #include"../../pc-common/AESCryptManager/AESCryptManager.h" #include "lessonevaluation/httpclient.h" class YMLessonManagerAdapter : public QObject , public YMHttpResponseHandler { Q_OBJECT public: YMLessonManagerAdapter(QObject *parent = 0); ~YMLessonManagerAdapter(); Q_INVOKABLE void getTeachLessonInfo(QString dateTime); Q_INVOKABLE void getTeachLessonListInfo(QJsonObject data); Q_INVOKABLE void getEnterClass(QString lessonId,int interNetGrade); Q_INVOKABLE void getListen(QString userId); //旁听 Q_INVOKABLE void getLookCourse(QJsonObject lessonInfo); Q_INVOKABLE void getRepeatPlayer(QJsonObject lessonInfo); Q_INVOKABLE int getCloudDiskList(QString roomId, QString apiUrl, QString appId, bool isRefreshCloudDisk = true); Q_INVOKABLE int upLoadCourseware(QString upFileMark, QString roomId, QString userId, QString fileUrl, long fileSize, QString apiUrl, QString appId); Q_INVOKABLE int findFileStatus(QString coursewareId, QString apiUrl, QString appId);// 查询文件转换状态,返回值0-转换中 1-成功 2-失败 Q_INVOKABLE int deleteCourseware(QString coursewareId, QString roomId, QString apiUrl, QString appId);// 删除云盘课件 Q_INVOKABLE QJsonObject getLiveLessonDetailData(QString lessonId); //年级、科目查询 Q_INVOKABLE void getUserSubjectInfo(); //教研课表查询 Q_INVOKABLE void getEmLessons(QJsonObject data); //查看是否有报告 Q_INVOKABLE int getReportFlag(QString lessonId); //获取服务IP进行转换 Q_INVOKABLE void getCloudServer(); //显示课程详情课后评价信息 Q_INVOKABLE int getLessonComment(QString lessonId); //获取文件大小 Q_INVOKABLE long getFileSize(const QString &filePath); //设置 Q_PROPERTY(QString lessonType READ getLessonType WRITE setLessonType) Q_PROPERTY(QString lessonPlanStartTime READ getLessonPlanStartTime WRITE setLessonPlanStartTime) Q_PROPERTY(QString lessonPlanEndTime READ getLessonPlanEndTime WRITE setLessonPlanEndTime) //获取年级信息 Q_INVOKABLE QJsonObject getGrades(); public slots: void getEnterClassresult(QNetworkReply *reply); void enterClassTimerOut(); void getCloudServerIpTimeOut();//获取服务端ip超时 void runClassRoom(QJsonObject roomData); void runPlayer(QJsonObject roomData); void runCourse(QJsonObject roomData); void getDayLessonData(QString dayData);//根据日期获取当天课程 void getMonthLessonData(QString startDay,QString endDay); void getMiniClassLessonList(QString startDay,QString endDay,int opationType,int pageNum ,int pageSize ,QString roomId ); void onGetMonthLessonDataFinish(QNetworkReply *reply); void onGetDayLessonDataFinish(QNetworkReply *reply); void onGetMiniClassLessonList(QNetworkReply *reply); void getMiniClassTimeTable(QString startDay,QString endDay,int opationType); void getCurrentMonthLessonData(QString currentMonth); void getCurrentDayLessonData(QString currentDay); void onGetCurrentMonthLessonDataFinish(QNetworkReply *reply); void onGetCurrentDayLessonDataFinish(QNetworkReply *reply); public: void enterClass(); void enterListen(); //旁听 void downLoadFile(QJsonObject data, QString filePath); void errorLog(QString message); QVariantList getStuTraila(QString trailId, QString fileName, QString fileDir); void getStuVideo(QString videoId, QString fileName, QString fileDir); QString des_decrypt(const std::string &cipherText); QString des_encrypt(const QString &clearText); void encrypt(QString source, QString target); QList<QString> decrypt(QString source); QString lessonPlanStartTime = ""; QString getLessonPlanStartTime() { return lessonPlanStartTime; } void setLessonPlanStartTime(QString time) { lessonPlanStartTime = time; } QString lessonPlanEndTime = ""; QString getLessonPlanEndTime() { return lessonPlanEndTime; } void setLessonPlanEndTime(QString time) { lessonPlanEndTime = time; } QString currentLessonId = ""; QString lessonType; void setLessonType( QString v) { if(v == "10" || v == "O") { lessonType = "O"; } else { lessonType = "A"; } } QString getLessonType() { return lessonType; } //重设进入教室的Ip选择 以服务器指定的优先级为最高( type =1 ) 若服务器未指定则次优先级为 用户自己选择的ip (type = 2) void resetSelectIp(int type, QString ip); protected: virtual void onResponse(int reqCode, const QString &data); void onRespGetRepeatPlayer(const QString &data); private: YMHttpClient * m_httpClint; typedef void (YMLessonManagerAdapter::* HttpRespHandler)(const QString& data); QMap<int, HttpRespHandler> m_respHandlers; QVariantList m_ipPort; QJsonObject m_repeatData; QJsonObject m_classData; QString m_domain; QString m_ipAddress; QString m_port; //查看课件字段 QString requestData; int m_listen;//旁听状态 bool m_listenOrClass;//监听或者进入教室状态 true 进入教室, false进入旁听 QTimer *m_timer; bool isStop; QString m_udpPort;// bool teaInClassRoomFlag;//true在教室false不在、当前老师是否在教室 int offSingle;// 0关单 1 不能关单 是否关单, int applicationType;// 0不是标准试听课,1是 int reportFlag;// 0没有 1有、是否有报告 QTimer *m_getIpTimer;//获取serverIp是否超时 QString currentDayBuffer = ""; HttpClient* m_CloudhttpClient; QMutex m_mutex; QJsonArray m_coursewareListInfo; QString m_apiUrl; signals: void teachLessonInfoChanged(QJsonObject lessonInfo); void teacherLesonListInfoChanged(QJsonObject lessonInfo); void lessonlistRenewSignal(); void programRuned(); void setDownValue(int min, int max); void downloadChanged(int currentValue); void downloadFinished(); void listenChange(int status); void loadingFinished(); void requstTimeOuted();//请求超时 //年级、科目信号 void sigUserSubjectInfo(QJsonObject subjectInfo); //教研课表信号 void sigEmLesson(QJsonObject dataObj); //录播未生成信号 void sigRepeatPlayer(); //是否在教室弹窗 void sigIsJoinClassroom(QString teacherName); void sigMessageBoxInfo(QString strMsg); //需要提示message box的信号 //cc已经在教室弹窗 void sigCCHasInRoom(); void sigGetMonthLessonData(QJsonArray monthData); void sigGetDayLessonData(QJsonArray dayData); void sigInvalidToken(); void sigGetLessonListDate(QJsonObject lessonData); // @param clouddiskInfo包含信息:"date": "string","docType": "string","id": 0,"jsonData": "string","name": "string","path": "string","type": 0 void sigCloudDiskInfo(QJsonArray clouddiskInfo); void sigSaveResourceSuccess(QString coursewareId, QString originFilename, QString suffix, QString upFileMark);// 保存资源成功信号 void sigSaveResourceFailed(QString originFilename, QString suffix, QString upFileMark);// 保存资源失败信号 void sigFindFileStatus(int status);// 查询文件转码状态,status 转换状态 0-转换中 1-成功 2-失败 void sigDeleteResult(QString coursewareId, bool isSuccess);// 云盘课件删除结果 private: void setBufferEnterRoomIp(QString currentIp,QString port); QString getBufferEnterRoomIP(); QString getBufferEnterRoomPort(); }; #endif // YMLESSONMANAGERADAPTER_H
C++
CL
fb783bf363ddb64fbfb54f5c7c01417739b639be7dd83f2aa01851e685c290e4
// Declares clang::SyntaxOnlyAction. #include "clang/Frontend/FrontendActions.h" #include "clang/Tooling/CommonOptionsParser.h" #include "clang/Tooling/Tooling.h" // Declares llvm::cl::extrahelp. #include "llvm/Support/CommandLine.h" // recursive converter #include "clang/AST/ASTConsumer.h" #include "clang/AST/RecursiveASTVisitor.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/FrontendAction.h" // lexer and writer #include "clang/Lex/Lexer.h" #include "clang/Rewrite/Core/Rewriter.h" // preprocesser #include "clang/Basic/FileManager.h" #include "clang/Basic/SourceManager.h" #include "clang/Frontend/FrontendPluginRegistry.h" #include "clang/Lex/PPCallbacks.h" #include "clang/Lex/Preprocessor.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/FormattedStream.h" #include <stdio.h> #include <string> #include <sstream> using namespace clang; using namespace clang::tooling; using namespace llvm; using namespace std; // Apply a custom category to all command-line options so that they are the // only ones displayed. static llvm::cl::OptionCategory MyToolCategory("my-tool options"); // CommonOptionsParser declares HelpMessage with a description of the common // command-line options related to the compilation database and input files. // It's nice to have this help message in all tools. static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage); // A help message for this specific tool can be added afterwards. static cl::extrahelp MoreHelp("\nMore help text..."); //------------Formatter class decl---------------------------------------------------------------------------------------------------- class CToFTypeFormatter { public: QualType c_qualType; ASTContext &ac; CToFTypeFormatter(QualType qt, ASTContext &ac); string getFortranTypeASString(bool typeWrapper); string getFortranIdASString(string raw_id); bool isSameType(QualType qt2); static bool isIntLike(const string input); static bool isDoubleLike(const string input); static bool isType(const string input); static bool isString(const string input); static bool isChar(const string input); static string createFortranType(const string macroName, const string macroVal); }; class RecordDeclFormatter { public: const int ANONYMOUS = 0; const int ID_ONLY = 1; const int TAG_ONLY = 2; const int ID_TAG = 3; const int TYPEDEF = 4; const int UNION = 0; const int STRUCT = 1; RecordDecl *recordDecl; int mode = ANONYMOUS; bool structOrUnion = STRUCT; string tag_name; bool isInSystemHeader; // Member functions declarations RecordDeclFormatter(RecordDecl *rd, Rewriter &r); void setMode(); void setTagName(string name); bool isStruct(); bool isUnion(); string getFortranStructASString(); string getFortranFields(); private: Rewriter &rewriter; }; class EnumDeclFormatter { public: EnumDecl *enumDecl; bool isInSystemHeader; // Member functions declarations EnumDeclFormatter(EnumDecl *e, Rewriter &r); string getFortranEnumASString(); private: Rewriter &rewriter; }; class VarDeclFormatter { public: VarDecl *varDecl; bool isInSystemHeader; // Member functions declarations VarDeclFormatter(VarDecl *v, Rewriter &r); string getInitValueASString(); string getFortranVarDeclASString(); string getFortranArrayDeclASString(); void getFortranArrayEleASString(InitListExpr *ile, string &arrayValues, string arrayShapes, bool &evaluatable, bool firstEle); private: Rewriter &rewriter; string arrayShapes_fin; }; class TypedefDeclFormater { public: TypedefDecl *typedefDecl; bool isInSystemHeader; // Member functions declarations TypedefDeclFormater(TypedefDecl *t, Rewriter &r); string getFortranTypedefDeclASString(); private: Rewriter &rewriter; bool isLocValid; }; class FunctionDeclFormatter { public: FunctionDecl *funcDecl; bool isInSystemHeader; // Member functions declarations FunctionDeclFormatter(FunctionDecl *f, Rewriter &r); string getParamsNamesASString(); string getParamsDeclASString(); string getFortranFunctDeclASString(); string getParamsTypesASString(); bool argLocValid(); private: QualType returnQType; llvm::ArrayRef<ParmVarDecl *> params; Rewriter &rewriter; }; class MacroFormatter { public: const MacroDirective *md; string macroName; string macroVal; string macroDef; bool isInSystemHeader; MacroFormatter(const Token MacroNameTok, const MacroDirective *md, CompilerInstance &ci); bool isObjectLike(); bool isFunctionLike(); string getFortranMacroASString(); private: bool isObjectOrFunction; //CompilerInstance &ci; }; //------------Visitor class decl---------------------------------------------------------------------------------------------------- class TraverseNodeVisitor : public RecursiveASTVisitor<TraverseNodeVisitor> { public: TraverseNodeVisitor(Rewriter &R) : TheRewriter(R) {} bool TraverseDecl(Decl *d); bool TraverseStmt(Stmt *x); bool TraverseType(QualType x); string allFunctionDecls; private: Rewriter &TheRewriter; };
C++
CL
270691561434f1e828748939c51b08d8da96295e8c237bc71d2f8bd1105776b9
#pragma once #include "laser_agregator/Mesh.h" class Scene: public Mesh{ public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW void add(const Mesh& local_mesh); void clear(); void commit_sensor_poses(); void split_in_parts(); void sanity_check() const; friend std::ostream &operator<<(std::ostream&, const Mesh& m); Scene& operator= (const Mesh& mesh); //vector of poses for each of the added local_meshes; std::vector<Eigen::Affine3d, Eigen::aligned_allocator<Eigen::Affine3d> > m_sensor_poses; std::vector<Eigen::Affine3d, Eigen::aligned_allocator<Eigen::Affine3d> > m_tfs_alg_worldgl; //vector of transforms for each local mesh from the worldgl to the algorithm frame Eigen::MatrixXf m_per_vertex_classes_probs; // VxNrClasses matrix, for each vertex store the probabilities of being in a certain class (updated on each new fuse) Eigen::VectorXd m_per_vertex_weights; //Vx1 matrix, for each vertex store the weight of it being in said class (updated on each new fuse) };
C++
CL
c860c8f559758ed438086d6d6484d54ecff726abffb09fe056694594cdb99437
#ifndef SERVOSWRAPPER_H #define SERVOSWRAPPER_H #include <node.h> #include <node_object_wrap.h> #include "../Servos.h" class ServosWrapper : public node::ObjectWrap { public: static void Init(); static void NewInstance(const v8::FunctionCallbackInfo<v8::Value>& args); private: explicit ServosWrapper(uint8_t _add = 0x00); ~ServosWrapper(); static void New(const v8::FunctionCallbackInfo<v8::Value>& args); static void setAngle(const v8::FunctionCallbackInfo<v8::Value>& args); static void drive(const v8::FunctionCallbackInfo<v8::Value>& args); static void release(const v8::FunctionCallbackInfo<v8::Value>& args); static v8::Persistent<v8::Function> constructor; Servos *servos; }; #endif
C++
CL
facb9925158dec4b0bbf441afe961d9087881965a397d63618313aebbfdcda36
/* Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #pragma once #include "library/metavar_context.h" #include "library/equations_compiler/equations.h" namespace lean { class elaborator; expr compile_equations(environment & env, elaborator & elab, metavar_context & mctx, local_context const & lctx, expr const & eqns); void initialize_compiler(); void finalize_compiler(); }
C++
CL
e6516a55a7841bf05becf3f6f7ffaf6f5ed09da207318f996edfb204998d6413
// Copyright (c) 2010 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. #ifndef CHROME_BROWSER_CHROMEOS_DOM_UI_PROXY_HANDLER_H_ #define CHROME_BROWSER_CHROMEOS_DOM_UI_PROXY_HANDLER_H_ #include "chrome/browser/chromeos/dom_ui/cros_options_page_ui_handler.h" namespace chromeos { // ChromeOS proxy options page UI handler. class ProxyHandler : public CrosOptionsPageUIHandler { public: ProxyHandler(); virtual ~ProxyHandler(); // OptionsUIHandler implementation. virtual void GetLocalizedValues(DictionaryValue* localized_strings); private: DISALLOW_COPY_AND_ASSIGN(ProxyHandler); }; } // namespace chromeos #endif // CHROME_BROWSER_CHROMEOS_DOM_UI_PROXY_HANDLER_H_
C++
CL
a1cfa70e7c080450fde05a8202f30e1aeaedffe1080cd7d49bbc3204c911469f
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2020 Ryo Suzuki // Copyright (c) 2016-2020 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # include <Siv3D/EngineLog.hpp> # include <Siv3D/ShaderStatge.hpp> # include "GL4VertexShader.hpp" namespace s3d { GL4VertexShader::GL4VertexShader(Null) { m_initialized = true; } GL4VertexShader::~GL4VertexShader() { if (m_vsProgram) { ::glDeleteProgram(m_vsProgram); m_vsProgram = 0; } } GL4VertexShader::GL4VertexShader(const StringView source, const Array<ConstantBufferBinding>& bindings) { // 頂点シェーダプログラムを作成 { const std::string sourceUTF8 = source.toUTF8(); const char* pSource = sourceUTF8.c_str(); m_vsProgram = ::glCreateShaderProgramv(GL_VERTEX_SHADER, 1, &pSource); } GLint status = GL_FALSE; ::glGetProgramiv(m_vsProgram, GL_LINK_STATUS, &status); GLint logLen = 0; ::glGetProgramiv(m_vsProgram, GL_INFO_LOG_LENGTH, &logLen); // ログメッセージ if (logLen > 4) { std::string log(logLen + 1, '\0'); ::glGetProgramInfoLog(m_vsProgram, logLen, &logLen, &log[0]); LOG_FAIL(U"❌ Vertex shader compilation failed: {0}"_fmt(Unicode::Widen(log))); } if (status == GL_FALSE) // もしリンクに失敗していたら { ::glDeleteProgram(m_vsProgram); m_vsProgram = 0; } if (m_vsProgram) { setUniformBlockBindings(bindings); } m_initialized = (m_vsProgram != 0); } bool GL4VertexShader::isInitialized() const noexcept { return m_initialized; } const Blob& GL4VertexShader::getBinary() const noexcept { return m_binary; } GLint GL4VertexShader::getProgram() const { return m_vsProgram; } void GL4VertexShader::setUniformBlockBinding(const StringView name, const GLuint index) { const GLuint blockIndex = ::glGetUniformBlockIndex(m_vsProgram, name.narrow().c_str()); if (blockIndex == GL_INVALID_INDEX) { LOG_FAIL(U"Uniform block `{}` not found"_fmt(name)); return; } const GLuint uniformBlockBinding = Shader::Internal::MakeUniformBlockBinding(ShaderStage::Vertex, index); LOG_TRACE(U"Uniform block `{}`: binding = VS_{} ({})"_fmt(name, index, uniformBlockBinding)); ::glUniformBlockBinding(m_vsProgram, blockIndex, uniformBlockBinding); } void GL4VertexShader::setUniformBlockBindings(const Array<ConstantBufferBinding>& bindings) { for (const auto& binding : bindings) { setUniformBlockBinding(binding.name, binding.index); } } }
C++
CL
dd59bc70ff21c93398e4cf6626dffc1906317e9430a779cc1122f5817e1a4f06
#if !defined(AFX_FONTDLG_H__4241C445_D36D_11D5_BFC5_0050BABDFD68__INCLUDED_) #define AFX_FONTDLG_H__4241C445_D36D_11D5_BFC5_0050BABDFD68__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "../../resource.h" // FontDlg.h : header file // ///////////////////////////////////////////////////////////////////////////// // CFontDlg dialog class CFontDlg : public CPropertyPage { // Construction public: COLORREF GetTextColor(); void GetCurLogfont(LOGFONT* logfont); void SetFontDlg(LOGFONT* plogfont,BOOL sizeenable,BOOL colorenable,COLORREF textcolor); CFontDlg(); // standard constructor // Dialog Data //{{AFX_DATA(CFontDlg) enum { IDD = CZ_IDD_LOGFONTDIALOG }; CEdit m_styleeditctr; CEdit m_sizeeditctr; CEdit m_fonteditctr; CComboBox m_colorcombo; CListBox m_sizelist; CListBox m_stylelist; CListBox m_fontlist; CString m_fontedit; CString m_styleedit; CString m_sizeedit; CString m_font; CString m_style; CString m_size; BOOL m_strikeout; BOOL m_underline; //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CFontDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: BOOL m_colorenable; COLORREF m_textcolor; LOGFONT m_logfont; LOGFONT* p_logfont; BOOL m_sizeenable; // Generated message map functions //{{AFX_MSG(CFontDlg) virtual BOOL OnInitDialog(); afx_msg void OnSelchangeFontlist(); afx_msg void OnSelchangeSizelist(); afx_msg void OnSelchangeStylelist(); afx_msg void OnUnderline(); afx_msg void OnStrikeout(); afx_msg void OnSelchangeColorcombo(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_FONTDLG_H__4241C445_D36D_11D5_BFC5_0050BABDFD68__INCLUDED_)
C++
CL
3441b39352f5e8919f87acdcf752913751d9917501335017d3e89959f1aaf171
/**************************************************************************** Copyright (c) 2013 Zynga Inc. Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include <vector> #include "ccUTF8.h" #include "CCLabelTextFormatter.h" #include "CCDirector.h" #include "CCLabel.h" using namespace std; NS_CC_BEGIN bool LabelTextFormatter::multilineText(Label *theLabel) { //int strLen = theLabel->getStringLength(); auto limit = theLabel->_limitShowCount; auto strWhole = theLabel->_currentUTF16String; vector<unsigned short> multiline_string; multiline_string.reserve( limit ); vector<unsigned short> last_word; last_word.reserve( 25 ); bool isStartOfLine = false, isStartOfWord = false; float startOfLine = -1, startOfWord = -1; int skip = 0; int tIndex = 0; float scalsX = theLabel->getScaleX(); float lineWidth = theLabel->_maxLineWidth; bool breakLineWithoutSpace = theLabel->_lineBreakWithoutSpaces; Label::LetterInfo* info = nullptr; for (int j = 0; j+skip < limit; j++) { info = & theLabel->_lettersInfo.at(j+skip); unsigned int justSkipped = 0; while (info->def.validDefinition == false) { justSkipped++; tIndex = j+skip+justSkipped; if (strWhole[tIndex-1] == '\n') { cc_utf8_trim_ws(&last_word); last_word.push_back('\n'); multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end()); last_word.clear(); isStartOfWord = false; isStartOfLine = false; startOfWord = -1; startOfLine = -1; } if(tIndex < limit) { info = & theLabel->_lettersInfo.at( tIndex ); } else break; } skip += justSkipped; tIndex = j + skip; if (tIndex >= limit) break; unsigned short character = strWhole[tIndex]; if (!isStartOfWord) { startOfWord = info->position.x * scalsX; isStartOfWord = true; } if (!isStartOfLine) { startOfLine = startOfWord; isStartOfLine = true; } // 1) Whitespace. // 2) This character is non-CJK, but the last character is CJK bool isspace = isspace_unicode(character); bool isCJK = false; if(!isspace) { isCJK = iscjk_unicode(character); } if (isspace || (!last_word.empty() && iscjk_unicode(last_word.back()) && !isCJK)) { // if current character is white space, put it into the current word if (isspace) last_word.push_back(character); multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end()); last_word.clear(); isStartOfWord = false; startOfWord = -1; // put the CJK character in the last word // and put the non-CJK(ASCII) character in the current word if (!isspace) last_word.push_back(character); continue; } float posRight = (info->position.x + info->contentSize.width) * scalsX; // Out of bounds. if (posRight - startOfLine > lineWidth) { if (!breakLineWithoutSpace && !isCJK) { last_word.push_back(character); int found = cc_utf8_find_last_not_char(multiline_string, ' '); if (found != -1) cc_utf8_trim_ws(&multiline_string); else multiline_string.clear(); if (multiline_string.size() > 0) multiline_string.push_back('\n'); isStartOfLine = false; startOfLine = -1; } else { cc_utf8_trim_ws(&last_word); last_word.push_back('\n'); multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end()); last_word.clear(); isStartOfWord = false; isStartOfLine = false; startOfWord = -1; startOfLine = -1; --j; } } else { // Character is normal. last_word.push_back(character); } } multiline_string.insert(multiline_string.end(), last_word.begin(), last_word.end()); size_t size = multiline_string.size(); unsigned short* strNew = new unsigned short[size + 1]; for (size_t j = 0; j < size; ++j) { strNew[j] = multiline_string[j]; } strNew[size] = 0; theLabel->setCurrentString(strNew); return true; } bool LabelTextFormatter::alignText(Label *theLabel) { int i = 0; int lineNumber = 0; int strLen = cc_wcslen(theLabel->_currentUTF16String); vector<unsigned short> lastLine; auto strWhole = theLabel->_currentUTF16String; if (theLabel->_labelWidth > theLabel->_contentSize.width) { theLabel->setContentSize(Size(theLabel->_labelWidth,theLabel->_contentSize.height)); } for (int ctr = 0; ctr <= strLen; ++ctr) { unsigned short currentChar = strWhole[ctr]; if (currentChar == '\n' || currentChar == 0) { auto lineLength = lastLine.size(); // if last line is empty we must just increase lineNumber and work with next line if (lineLength == 0) { lineNumber++; continue; } int index = static_cast<int>(i + lineLength - 1 + lineNumber); if (index < 0) continue; auto info = & theLabel->_lettersInfo.at( index ); if(info->def.validDefinition == false) continue; float shift = 0; switch (theLabel->_hAlignment) { case TextHAlignment::CENTER: { float lineWidth = info->position.x + info->contentSize.width; shift = theLabel->_contentSize.width/2.0f - lineWidth/2.0f; break; } case TextHAlignment::RIGHT: { float lineWidth = info->position.x + info->contentSize.width; shift = theLabel->_contentSize.width - lineWidth; break; } default: break; } if (shift != 0) { for (unsigned j = 0; j < lineLength; ++j) { index = i + j + lineNumber; if (index < 0) continue; info = & theLabel->_lettersInfo.at( index ); if(info) { info->position.x += shift; } } } i += lineLength; ++lineNumber; lastLine.clear(); continue; } lastLine.push_back(currentChar); } return true; } bool LabelTextFormatter::createStringSprites(Label *theLabel) { // check for string unsigned int stringLen = theLabel->getStringLength(); theLabel->_limitShowCount = 0; // no string if (stringLen == 0) return false; int longestLine = 0; unsigned int totalHeight = theLabel->_commonLineHeight * theLabel->_currNumLines; int nextFontPositionX = 0; int nextFontPositionY = totalHeight; auto contentScaleFactor = CC_CONTENT_SCALE_FACTOR(); if (theLabel->_labelHeight > 0) { auto labelHeightPixel = theLabel->_labelHeight * contentScaleFactor; if (totalHeight > labelHeightPixel) { int numLines = labelHeightPixel / theLabel->_commonLineHeight; totalHeight = numLines * theLabel->_commonLineHeight; } switch (theLabel->_vAlignment) { case TextVAlignment::TOP: nextFontPositionY = labelHeightPixel; break; case TextVAlignment::CENTER: nextFontPositionY = (labelHeightPixel + totalHeight) / 2.0f; break; case TextVAlignment::BOTTOM: nextFontPositionY = totalHeight; break; default: break; } } Rect charRect; int charXOffset = 0; int charYOffset = 0; int charAdvance = 0; auto strWhole = theLabel->_currentUTF16String; auto fontAtlas = theLabel->_fontAtlas; FontLetterDefinition tempDefinition; Point letterPosition; const auto& kernings = theLabel->_horizontalKernings; for (unsigned int i = 0; i < stringLen; i++) { unsigned short c = strWhole[i]; if (fontAtlas->getLetterDefinitionForChar(c, tempDefinition)) { charXOffset = tempDefinition.offsetX; charYOffset = tempDefinition.offsetY; charAdvance = tempDefinition.xAdvance; } else { charXOffset = -1; charYOffset = -1; charAdvance = -1; } if (c == '\n') { nextFontPositionX = 0; nextFontPositionY -= theLabel->_commonLineHeight; theLabel->recordPlaceholderInfo(i); if(nextFontPositionY < theLabel->_commonLineHeight) break; continue; } letterPosition.x = (nextFontPositionX + charXOffset + kernings[i]) / contentScaleFactor; letterPosition.y = (nextFontPositionY - charYOffset) / contentScaleFactor; if( theLabel->recordLetterInfo(letterPosition,tempDefinition,i) == false) { log("WARNING: can't find letter definition in font file for letter: %c", c); continue; } nextFontPositionX += charAdvance + kernings[i]; if (longestLine < nextFontPositionX) { longestLine = nextFontPositionX; } } float lastCharWidth = tempDefinition.width * contentScaleFactor; Size tmpSize; // If the last character processed has an xAdvance which is less that the width of the characters image, then we need // to adjust the width of the string to take this into account, or the character will overlap the end of the bounding // box if(charAdvance < lastCharWidth) { tmpSize.width = longestLine - charAdvance + lastCharWidth; } else { tmpSize.width = longestLine; } tmpSize.height = totalHeight; if (theLabel->_labelHeight > 0) { tmpSize.height = theLabel->_labelHeight * contentScaleFactor; } theLabel->setContentSize(CC_SIZE_PIXELS_TO_POINTS(tmpSize)); return true; } NS_CC_END
C++
CL
e84768425c852b0787a4893adfe8b387d067d1242706d523bf42534e50f3f0fa
#include "FileTools.h" #include <ipl98/cpp/image.h> #include <time/time_date.h> /* Without the next line, an object must be declared like this: ipl::CImage Img; */ using namespace ipl; class ImageProcessor { public: ImageProcessor(void); ~ImageProcessor (void); bool Setup(char *directoryName, int &imgWidth, int &imgHeight); bool k_copyTImageToBMP_bmBits(const TImage *colorImage, unsigned char *screen_bmp_bmBits); bool ProcessNextFrame(unsigned char *screenBitmap_bmBits); private: FileTools imageDir; // gets the names of the files in a directory char *readDirectory; // the directory of files to read char *imageFileName; // the full path name of the next file CImage image; // the next image to be displayed int imageWidth, imageHeight; // dimensions of the first image int bitmapFileBits; // number of bits used for each pixel in the first image int numberOfImages; // number of images loaded };
C++
CL
8ef9f5b1c846bfeba25e079c30c51c90e30626de41d3a3b62eba30a9755d19ca
/* Author: Ryan Luna */ #ifndef MOVEIT_R2_TREE_KINEMATICS_PLUGIN_ #define MOVEIT_R2_TREE_KINEMATICS_PLUGIN_ // ROS #include <ros/ros.h> // MoveIt! #include <moveit/kinematics_base/kinematics_base.h> #include <moveit/robot_model/robot_model.h> #include <moveit/robot_state/robot_state.h> // NASA R2 #include <nasa_robodyn_controllers_core/MobileTreeIk.h> #include <nasa_robodyn_controllers_core/KdlTreeFk.h> #include <boost/thread/mutex.hpp> namespace moveit_r2_kinematics { /// \brief Custom structure for IK requests on a kinematic tree. class TreeIkRequest { public: /// \brief Set the given link as fixed in the IK request. This link will serve as a base for the IK solver. void addFixedLink(const std::string& link_name); /// \brief Add an IK task to move link_name to the given pose (in global coordinates) with the given priority void addLinkPose(const std::string& link_name, const geometry_msgs::Pose& pose, const int priority=KdlTreeIk::CRITICAL); /// \brief Add an IK task to move link_name to the given pose (in global coordinates) with the given priority void addLinkPose(const std::string& link_name, const geometry_msgs::Pose& pose, const std::vector<int>& priority); /// \brief Set the pose of the robot in the world. This pose corresponds to the "mobile joints" of the IK solver. void setWorldState(const Eigen::Affine3d& pose); /// \brief Set the current (seed) values for the robot. void setJointValues(const std::vector<double>& values); const std::vector<std::string>& getFixedLinks() const; const std::vector<std::string>& getMovingLinks() const; const std::vector<geometry_msgs::Pose>& getMovingLinkPoses() const; const std::vector<double>& getJointValues() const; const geometry_msgs::Pose& getWorldState() const; const std::vector<double>& getWorldStateRPY() const; const std::vector<KdlTreeIk::NodePriority>& getPriorities() const; protected: std::vector<std::string> fixed_links_; std::vector<std::string> moving_links_; std::vector<geometry_msgs::Pose> poses_; std::vector<KdlTreeIk::NodePriority> priorities_; std::vector<double> initial_joints_; std::vector<double> world_state_rpy_; geometry_msgs::Pose world_state_; }; /// \brief Custom structure for an IK response class TreeIkResponse { public: /// \brief True if the IK request was successful. bool successful() const; /// \brief Return the new pose of the robot in the world. This pose corresponds to the "mobile joints" of the IK solver. const Eigen::Affine3d& getWorldState() const; /// \brief Return the new joint values for the robot const std::vector<double>& getJointValues() const; /// \brief Mark the IK request as a failure void setFailure(); /// \brief Set the world state and joint values after a successful IK request void setValues(const Eigen::Affine3d& world, const std::vector<double>& joints); protected: bool success_; Eigen::Affine3d world_pose_; std::vector<double> joint_values_; }; /// \brief Custom kinematics routines for R2. NOTE: Currently this implementation is only be functional on the legs. See implementation of initialize(...). class MoveItR2TreeKinematicsPlugin : public kinematics::KinematicsBase { public: MoveItR2TreeKinematicsPlugin(); virtual ~MoveItR2TreeKinematicsPlugin (); /// @group KinematicsBase interface /// @{ /// @brief Given a desired pose of the end-effector, compute the joint angles to reach it /// @param ik_pose the desired pose of the link /// @param ik_seed_state an initial guess solution for the inverse kinematics /// @param solution the solution vector /// @param error_code an error code that encodes the reason for failure or success /// @param lock_redundant_joints if setRedundantJoints() was previously called, keep the values of the joints marked as redundant the same as in the seed /// @return True if a valid solution was found, false otherwise virtual bool getPositionIK(const geometry_msgs::Pose &ik_pose, const std::vector<double> &ik_seed_state, std::vector<double> &solution, moveit_msgs::MoveItErrorCodes &error_code, const kinematics::KinematicsQueryOptions &options = kinematics::KinematicsQueryOptions()) const; /// @brief Given a desired pose of the end-effector, search for the joint angles required to reach it. /// This particular method is intended for "searching" for a solutions by stepping through the redundancy /// (or other numerical routines). /// @param ik_pose the desired pose of the link /// @param ik_seed_state an initial guess solution for the inverse kinematics /// @param timeout The amount of time (in seconds) available to the solver /// @param solution the solution vector /// @param error_code an error code that encodes the reason for failure or success /// @param lock_redundant_joints if setRedundantJoints() was previously called, keep the values of the joints marked as redundant the same as in the seed /// @return True if a valid solution was found, false otherwise virtual bool searchPositionIK(const geometry_msgs::Pose &ik_pose, const std::vector<double> &ik_seed_state, double timeout, std::vector<double> &solution, moveit_msgs::MoveItErrorCodes &error_code, const kinematics::KinematicsQueryOptions &options = kinematics::KinematicsQueryOptions()) const; /// @brief Given a desired pose of the end-effector, search for the joint angles required to reach it. /// This particular method is intended for "searching" for a solutions by stepping through the redundancy /// (or other numerical routines). /// @param ik_pose the desired pose of the link /// @param ik_seed_state an initial guess solution for the inverse kinematics /// @param timeout The amount of time (in seconds) available to the solver /// @param consistency_limits the distance that any joint in the solution can be from the corresponding joints in the current seed state /// @param solution the solution vector /// @param error_code an error code that encodes the reason for failure or success /// @param lock_redundant_joints if setRedundantJoints() was previously called, keep the values of the joints marked as redundant the same as in the seed /// @return True if a valid solution was found, false otherwise virtual bool searchPositionIK(const geometry_msgs::Pose &ik_pose, const std::vector<double> &ik_seed_state, double timeout, const std::vector<double> &consistency_limits, std::vector<double> &solution, moveit_msgs::MoveItErrorCodes &error_code, const kinematics::KinematicsQueryOptions &options = kinematics::KinematicsQueryOptions()) const; /// @brief Given a desired pose of the end-effector, search for the joint angles required to reach it. /// This particular method is intended for "searching" for a solutions by stepping through the redundancy /// (or other numerical routines). /// @param ik_pose the desired pose of the link /// @param ik_seed_state an initial guess solution for the inverse kinematics /// @param timeout The amount of time (in seconds) available to the solver /// @param solution the solution vector /// @param desired_pose_callback A callback function for the desired link pose - could be used, e.g. to check for collisions for the end-effector /// @param solution_callback A callback solution for the IK solution /// @param error_code an error code that encodes the reason for failure or success /// @param lock_redundant_joints if setRedundantJoints() was previously called, keep the values of the joints marked as redundant the same as in the seed /// @return True if a valid solution was found, false otherwise virtual bool searchPositionIK(const geometry_msgs::Pose &ik_pose, const std::vector<double> &ik_seed_state, double timeout, std::vector<double> &solution, const IKCallbackFn &solution_callback, moveit_msgs::MoveItErrorCodes &error_code, const kinematics::KinematicsQueryOptions &options = kinematics::KinematicsQueryOptions()) const; /// @brief Given a desired pose of the end-effector, search for the joint angles required to reach it. /// This particular method is intended for "searching" for a solutions by stepping through the redundancy /// (or other numerical routines). /// @param ik_pose the desired pose of the link /// @param ik_seed_state an initial guess solution for the inverse kinematics /// @param timeout The amount of time (in seconds) available to the solver /// @param consistency_limits the distance that any joint in the solution can be from the corresponding joints in the current seed state /// @param solution the solution vector /// @param desired_pose_callback A callback function for the desired link pose - could be used, e.g. to check for collisions for the end-effector /// @param solution_callback A callback solution for the IK solution /// @param error_code an error code that encodes the reason for failure or success /// @param lock_redundant_joints if setRedundantJoints() was previously called, keep the values of the joints marked as redundant the same as in the seed /// @return True if a valid solution was found, false otherwise virtual bool searchPositionIK(const geometry_msgs::Pose &ik_pose, const std::vector<double> &ik_seed_state, double timeout, const std::vector<double> &consistency_limits, std::vector<double> &solution, const IKCallbackFn &solution_callback, moveit_msgs::MoveItErrorCodes &error_code, const kinematics::KinematicsQueryOptions &options) const; /// @brief Given a set of desired poses for a planning group with multiple end-effectors, search for the joint angles /// required to reach them. This is useful for e.g. biped robots that need to perform whole-body IK. /// Not necessary for most robots that have kinematic chains. /// This particular method is intended for "searching" for a solutions by stepping through the redundancy /// (or other numerical routines). /// @param ik_poses the desired pose of each tip link /// @param ik_seed_state an initial guess solution for the inverse kinematics /// @param timeout The amount of time (in seconds) available to the solver /// @param consistency_limits the distance that any joint in the solution can be from the corresponding joints in the current seed state /// @param solution the solution vector /// @param solution_callback A callback solution for the IK solution /// @param error_code an error code that encodes the reason for failure or success /// @param options container for other IK options /// @param context_state (optional) the context in which this request /// is being made. The position values corresponding to /// joints in the current group may not match those in /// ik_seed_state. The values in ik_seed_state are the ones /// to use. This is passed just to provide the \em other /// joint values, in case they are needed for context, like /// with an IK solver that computes a balanced result for a /// biped. /// @return True if a valid solution was found, false otherwise virtual bool searchPositionIK(const std::vector<geometry_msgs::Pose> &ik_poses, const std::vector<double> &ik_seed_state, double timeout, const std::vector<double> &consistency_limits, std::vector<double> &solution, const IKCallbackFn &solution_callback, moveit_msgs::MoveItErrorCodes &error_code, const kinematics::KinematicsQueryOptions &options = kinematics::KinematicsQueryOptions(), const moveit::core::RobotState* context_state = NULL) const; /// @brief Given a set of joint angles and a set of links, compute their pose /// @param link_names A set of links for which FK needs to be computed /// @param joint_angles The state for which FK is being computed /// @param poses The resultant set of poses (in the frame returned by getBaseFrame()) /// @return True if a valid solution was found, false otherwise virtual bool getPositionFK(const std::vector<std::string> &link_names, const std::vector<double> &joint_angles, std::vector<geometry_msgs::Pose> &poses) const; /// @brief Initialization function for the kinematics /// @param robot_description This parameter can be used as an identifier for the robot kinematics is computed for; For example, rhe name of the ROS parameter that contains the robot description; /// @param group_name The group for which this solver is being configured /// @param base_frame The base frame in which all input poses are expected. /// This may (or may not) be the root frame of the chain that the solver operates on /// @param tip_frame The tip of the chain /// @param search_discretization The discretization of the search when the solver steps through the redundancy /// @return True if initialization was successful, false otherwise virtual bool initialize(const std::string& robot_description, const std::string& group_name, const std::string& base_frame, const std::string& tip_frame, double search_discretization); /// @brief Initialization function for the kinematics, for use with non-chain IK solvers /// @param robot_description This parameter can be used as an identifier for the robot kinematics is computed for; /// For example, rhe name of the ROS parameter that contains the robot description; /// @param group_name The group for which this solver is being configured /// @param base_frame The base frame in which all input poses are expected. /// This may (or may not) be the root frame of the chain that the solver operates on /// @param tip_frames A vector of tips of the kinematic tree /// @param search_discretization The discretization of the search when the solver steps through the redundancy /// @return True if initialization was successful, false otherwise virtual bool initialize(const std::string& robot_description, const std::string& group_name, const std::string& base_frame, const std::vector<std::string>& tip_frames, double search_discretization); /// @brief Return all the joint names in the order they are used internally virtual const std::vector<std::string>& getJointNames() const; /// @brief Return all the link names in the order they are represented internally virtual const std::vector<std::string>& getLinkNames() const; /** * \brief Check if this solver supports a given JointModelGroup. * * Override this function to check if your kinematics solver * implementation supports the given group. * * The default implementation just returns jmg->isChain(), since * solvers written before this function was added all supported only * chain groups. * * \param jmg the planning group being proposed to be solved by this IK solver * \param error_text_out If this pointer is non-null and the group is * not supported, this is filled with a description of why it's not * supported. * \return True if the group is supported, false if not. */ virtual const bool supportsGroup(const moveit::core::JointModelGroup *jmg, std::string* error_text_out = NULL) const; /// @brief Redundant joints are disallowed in this kinematics solver virtual bool setRedundantJoints(const std::vector<unsigned int> &redundant_joint_indices) { return false; } /// @} // Custom interface // Tree IK request and response virtual bool getPositionIk(const TreeIkRequest& request, TreeIkResponse& response) const; // Return the order of ALL actuable joints in the entire system, not just the group virtual const std::vector<std::string>& getAllJointNames() const; protected: /// \brief A model of the entire robot robot_model::RobotModelPtr robot_model_; /// \brief True if the robot is mobile (the robot is not fixed in place) bool mobile_base_; /// \brief The IK solver MobileTreeIk* ik_; /// \brief The FK solver KdlTreeFk* fk_; /// \brief Mutex locking access to the ik_ member mutable boost::mutex ik_mutex_; /// \brief Mutex locking access to the fk_ member mutable boost::mutex fk_mutex_; /// \brief The default joint position for ALL joints in R2 KDL::JntArray default_joint_positions_; /// \brief The number of actuable DOFs in R2 unsigned int total_dofs_; /// \brief The number of passive DOFs in the mobile base joint unsigned int mobile_base_variable_count_; /// \brief The number of variables in the IK joint group (actuable and passive) unsigned int group_variable_count_; /// \brief A mapping of joints in the group to their index in jointNames_, default_joint_positions_, etc.. std::map<std::string, unsigned int> group_joint_index_map_; /// \brief The set of joints to perform IK for. std::vector<std::string> group_joints_; /// \brief The set of links to perform IK for. std::vector<std::string> group_links_; /// \brief A list of every joint in the system std::vector<std::string> joint_names_; /// \brief A mapping of group joint variables to their indices in the full robot state std::vector<int> group_joint_to_robot_state_bijection_; /// \brief A mapping of joint variables in the IK representation to their indices in the full robot state std::vector<int> ik_joints_to_robot_joints_bijection_; }; } #endif
C++
CL
f825ce80155f95d50886ea2fcb3f8a5f1aeca79f1e4d3774c8a2ccf1b4dd4679
#pragma once #include "core/assert.h" #include "core/status.h" #include "core/types.h" // clang-format off // #if SDS_OS_WINDOWS // NOTE(sdsmith): windows.h must be included before GLAD. GLAD1 defines // APIENTRY, which is also defined by windows. GLAD2 solves this problem, but // there is no easy way around this in GLAD1. # include "core/platform/win32_include.h" #endif // NOTE(sdsmith): GLAD must be included before any other OpenGL related header. // GLAD includes the OpenGL headers. #include <glad/glad.h> #include <GLFW/glfw3.h> // clang-format on // Check that glfw peimitives types match the engine's RK_STATIC_ASSERT_MSG(sizeof(int) == sizeof(rk::s32), "glfw sizes don't match"); // Check that OpenGL primitives match the engine's RK_STATIC_ASSERT_MSG(sizeof(GLboolean) == sizeof(bool), "OpenGL sizes don't match"); RK_STATIC_ASSERT_MSG(sizeof(GLchar) == sizeof(char), "OpenGL sizes don't match"); RK_STATIC_ASSERT_MSG(sizeof(GLbyte) == sizeof(rk::s8), "OpenGL sizes don't match"); RK_STATIC_ASSERT_MSG(sizeof(GLubyte) == sizeof(rk::u8), "OpenGL sizes don't match"); RK_STATIC_ASSERT_MSG(sizeof(GLshort) == sizeof(rk::s16), "OpenGL sizes don't match"); RK_STATIC_ASSERT_MSG(sizeof(GLushort) == sizeof(rk::u16), "OpenGL sizes don't match"); RK_STATIC_ASSERT_MSG(sizeof(GLint) == sizeof(rk::s32), "OpenGL sizes don't match"); RK_STATIC_ASSERT_MSG(sizeof(GLuint) == sizeof(rk::u32), "OpenGL sizes don't match"); // GLfixed RK_STATIC_ASSERT_MSG(sizeof(GLint64) == sizeof(rk::s64), "OpenGL sizes don't match"); RK_STATIC_ASSERT_MSG(sizeof(GLuint64) == sizeof(rk::u64), "OpenGL sizes don't match"); RK_STATIC_ASSERT_MSG(sizeof(GLsizei) == sizeof(rk::s32), "OpenGL sizes don't match"); // GLenum // GLintptr // GLsizeiptr // GLsync // GLbitfield // GLhalf RK_STATIC_ASSERT_MSG(sizeof(GLfloat) == sizeof(rk::f32), "OpenGL sizes don't match"); // GLclampf RK_STATIC_ASSERT_MSG(sizeof(GLdouble) == sizeof(rk::f64), "OpenGL sizes don't match"); // GLclampd /** * \file glfw.h * \brief GLFW wrapper. Initialize here and then use GLFW as normal. */ /* * NOTE(sdsmith): GLFW errors are always non-fatal. The lib will remain in a valid state as long as * glfwInit was successful. */ // TODO(sdsmith): use glfwSetCharCallback for unicode input for text namespace rk::platform::glfw { /** * \brief Check for a GLFW error. Terminate glfw on error. Return appropriate status code. */ Status handle_error() noexcept; /** * \brief Initialize GLFW. */ [[nodiscard]] Status initialize() noexcept; /** * \brief Destroy GLFW. */ Status destroy() noexcept; /** * \def RK_CHECK_GLFW * \brief Check for GLFW error. Handle and return on error. */ #define RK_CHECK_GLFW(func_call) \ do { \ func_call; \ RK_CHECK(::rk::platform::glfw::handle_error()); \ } while (0) } // namespace rk::platform::glfw
C++
CL
4fd9480588672187add6cf52b8d79bd50f2d1fd2d28d17454f9d2d4feccea74f
/* * Copyright (C) 2002, Trent Waddington * * See the file "LICENSE.TERMS" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. * */ /** \file boomerang.h * \brief Interface for the boomerang singleton object. */ /** \mainpage Introduction * * \section Introduction * * Welcome to the Doxygen generated documentation for the * %Boomerang decompiler. Not all classes and functions have been documented * yet, but eventually they will. If you have figured out what a function is doing * please update the documentation and submit it as a patch. * * More information on the %Boomerang decompiler can be found at * http://boomerang.sourceforge.net. * */ #ifndef BOOMERANG_H #define BOOMERANG_H #include "msvc_fixes.h" #include "config.h" #include "types.h" #include "IBoomerang.h" #include "IProject.h" #include <QObject> #include <QDir> #include <QTextStream> #include <string> #include <set> #include <vector> #include <map> class QString; class SeparateLogger; class Log; class Prog; class Function; class UserProc; class HLLCode; class ObjcModule; class IBinaryImage; class IBinarySymbolTable; class Project; enum LogLevel { LL_Debug = 0, LL_Default=1, LL_Warn = 2, LL_Error= 3, }; #define LOG Boomerang::get()->log() #define LOG_SEPARATE(x) Boomerang::get()->separate_log(x) #define LOG_VERBOSE(x) Boomerang::get()->if_verbose_log(x) #define LOG_STREAM Boomerang::get()->getLogStream /// Virtual class to monitor the decompilation. class Watcher { public: Watcher() {} virtual ~Watcher() {} // Prevent gcc4 warning virtual void alert_complete() {} virtual void alertNew(Function *) {} virtual void alertRemove(Function *) {} virtual void alertUpdateSignature(Function *) {} virtual void alertDecode(ADDRESS /*pc*/, int /*nBytes*/) {} virtual void alertBadDecode(ADDRESS /*pc*/) {} virtual void alertStartDecode(ADDRESS /*start*/, int /*nBytes*/) {} virtual void alertEndDecode() {} virtual void alertDecode(Function *, ADDRESS /*pc*/, ADDRESS /*last*/, int /*nBytes*/) {} virtual void alertStartDecompile(UserProc *) {} virtual void alertProcStatusChange(UserProc *) {} virtual void alertDecompileSSADepth(UserProc *, int /*depth*/) {} virtual void alertDecompileBeforePropagate(UserProc *, int /*depth*/) {} virtual void alertDecompileAfterPropagate(UserProc *, int /*depth*/) {} virtual void alertDecompileAfterRemoveStmts(UserProc *, int /*depth*/) {} virtual void alertEndDecompile(UserProc *) {} virtual void alert_load(Function *) {} virtual void alertConsidering(Function * /*parent*/, Function *) {} virtual void alertDecompiling(UserProc *) {} virtual void alertDecompileDebugPoint(UserProc *, const char * /*description*/) {} }; /** * Controls the loading, decoding, decompilation and code generation for a program. * This is the main class of the decompiler. */ class Boomerang : public QObject,public IBoomerang { Q_OBJECT private: static Boomerang *boomerang; IBinaryImage *Image = nullptr; IBinarySymbolTable *Symbols = nullptr; QString progPath; //!< String with the path to the boomerang executable. QString outputPath; //!< The path where all output files are created. Log *logger = nullptr; //!< Takes care of the log messages. std::set<Watcher *> watchers; //!< The watchers which are interested in this decompilation. /* Documentation about a function should be at one place only * So: Document all functions at the point of implementation (in the .c file) */ void helpcmd() const; Boomerang(); virtual ~Boomerang(); void miniDebugger(UserProc *p, const char *description); public: /** * \return The global boomerang object. It will be created if it didn't already exist. */ static Boomerang *get(); IBinaryImage *getImage() override; IBinarySymbolTable *getSymbols() override; IProject *project() override { return currentProject; } int processCommand(QStringList &args); static const char *getVersionStr(); Log &log(); SeparateLogger separate_log(const QString &); Log &if_verbose_log(int verbosity_level); void setLogger(Log *l); bool setOutputDirectory(const QString &path); HLLCode *getHLLCode(UserProc *p = nullptr); void setPluginPath(const QString &p); void setProgPath(const QString &p); /// Get the path to the %Boomerang executable. const QString &getProgPath() { return progPath; } /// Get the path to the %Boomerang executable. QDir getProgDir() { return QDir(progPath); } /// Set the path where the output files are saved. void setOutputPath(const QString &p) { outputPath = p; } /// Returns the path to where the output files are saved. const QString &getOutputPath() { return outputPath; } Prog *loadAndDecode(const QString &fname, const char *pname = nullptr); int decompile(const QString &fname, const char *pname = nullptr); /// Add a Watcher to the set of Watchers for this Boomerang object. void addWatcher(Watcher *watcher) { watchers.insert(watcher); } void persistToXML(Prog *prog); Prog *loadFromXML(const char *fname); void objcDecode(const std::map<QString, ObjcModule> &modules, Prog *prog); /// Alert the watchers that decompilation has completed. void alert_complete() { for (Watcher *it : watchers) it->alert_complete(); } /// Alert the watchers we have found a new %Proc. void alertNew(Function *p) { for (Watcher *it : watchers) it->alertNew(p); } /// Alert the watchers we have removed a %Proc. void alertRemove(Function *p) { for (Watcher *it : watchers) it->alertRemove(p); } /// Alert the watchers we have updated this Procs signature void alertUpdateSignature(Function *p) { for (Watcher *it : watchers) it->alertUpdateSignature(p); } /// Alert the watchers we are currently decoding \a nBytes bytes at address \a pc. void alertDecode(ADDRESS pc, int nBytes) { for (Watcher *it : watchers) it->alertDecode(pc, nBytes); } /// Alert the watchers of a bad decode of an instruction at \a pc. void alertBadDecode(ADDRESS pc) { for (Watcher *it : watchers) it->alertBadDecode(pc); } /// Alert the watchers we have succesfully decoded this function void alertDecode(Function *p, ADDRESS pc, ADDRESS last, int nBytes) { for (Watcher *it : watchers) it->alertDecode(p, pc, last, nBytes); } /// Alert the watchers we have loaded the Proc. void alertLoad(Function *p) { for (Watcher *it : watchers) it->alert_load(p); } /// Alert the watchers we are starting to decode. void alertStartDecode(ADDRESS start, int nBytes) { for (Watcher *it : watchers) it->alertStartDecode(start, nBytes); } /// Alert the watchers we finished decoding. void alertEndDecode() { for (Watcher *it : watchers) it->alertEndDecode(); } void alertStartDecompile(UserProc *p) { for (Watcher *it : watchers) it->alertStartDecompile(p); } void alertProcStatusChange(UserProc *p) { for (Watcher *it : watchers) it->alertProcStatusChange(p); } void alertDecompileSSADepth(UserProc *p, int depth) { for (Watcher *it : watchers) it->alertDecompileSSADepth(p, depth); } void alertDecompileBeforePropagate(UserProc *p, int depth) { for (Watcher *it : watchers) it->alertDecompileBeforePropagate(p, depth); } void alertDecompileAfterPropagate(UserProc *p, int depth) { for (Watcher *it : watchers) it->alertDecompileAfterPropagate(p, depth); } void alertDecompileAfterRemoveStmts(UserProc *p, int depth) { for (Watcher *it : watchers) it->alertDecompileAfterRemoveStmts(p, depth); } void alertEndDecompile(UserProc *p) { for (Watcher *it : watchers) it->alertEndDecompile(p); } void alertConsidering(Function *parent, Function *p) { for (Watcher *it : watchers) it->alertConsidering(parent, p); } void alertDecompiling(UserProc *p) { for (Watcher *it : watchers) it->alertDecompiling(p); } void alertDecompileDebugPoint(UserProc *p, const char *description); QTextStream &getLogStream(int level=LL_Default); //!< Return overall logging target QString filename() const; // Command line flags bool vFlag = false; bool debugSwitch = false; bool debugLiveness = false; bool debugTA = false; bool debugDecoder = false; bool debugProof = false; bool debugUnused = false; bool debugRangeAnalysis = false; bool printRtl = false; bool noBranchSimplify = false; bool noRemoveNull = false; bool noLocals = false; bool noRemoveLabels = false; bool noDataflow = false; bool noDecompile = false; bool stopBeforeDecompile = false; bool traceDecoder = false; /// The file in which the dotty graph is saved QString dotFile; int numToPropagate = -1; bool noPromote = false; bool propOnlyToAll = false; bool debugGen = false; int maxMemDepth = 99; bool noParameterNames = false; bool stopAtDebugPoints = false; /// When true, attempt to decode main, all children, and all procs. /// \a decodeMain is set when there are no -e or -E switches given bool decodeMain = true; bool printAST = false; bool dumpXML = false; bool noRemoveReturns = false; bool decodeThruIndCall = false; bool noDecodeChildren = false; bool loadBeforeDecompile = false; bool saveBeforeDecompile = false; bool noProve = false; bool noChangeSignatures = false; bool conTypeAnalysis = false; bool dfaTypeAnalysis = true; int propMaxDepth = 3; ///< Max depth of expression that'll be propagated to more than one dest bool generateCallGraph = false; bool generateSymbols = false; bool noGlobals = false; bool assumeABI = false; ///< Assume ABI compliance bool experimental = false; ///< Activate experimental code. Caution! QTextStream LogStream; QTextStream ErrStream; std::vector<ADDRESS> entrypoints; /// A vector which contains all know entrypoints for the Prog. std::vector<QString> symbolFiles; /// A vector containing the names off all symbolfiles to load. std::map<ADDRESS, QString> symbols; /// A map to find a name by a given address. IProject *currentProject; }; #define VERBOSE (Boomerang::get()->vFlag) #define DEBUG_TA (Boomerang::get()->debugTA) #define DEBUG_PROOF (Boomerang::get()->debugProof) #define DEBUG_UNUSED (Boomerang::get()->debugUnused) #define DEBUG_LIVENESS (Boomerang::get()->debugLiveness) #define DEBUG_RANGE_ANALYSIS Boomerang::get()->debugRangeAnalysis #define DFA_TYPE_ANALYSIS (Boomerang::get()->dfaTypeAnalysis) #define CON_TYPE_ANALYSIS (Boomerang::get()->conTypeAnalysis) #define ADHOC_TYPE_ANALYSIS (!Boomerang::get()->dfaTypeAnalysis && !Boomerang::get()->conTypeAnalysis) #define DEBUG_GEN (Boomerang::get()->debugGen) #define DUMP_XML (Boomerang::get()->dumpXML) #define DEBUG_SWITCH (Boomerang::get()->debugSwitch) #define EXPERIMENTAL (Boomerang::get()->experimental) #endif
C++
CL
d4932b9f51f79d95df45b4bc72c8b910c845fb139b4baaa34b31c7e2ba5c61e3
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* info.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mjose <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/06/22 14:31:39 by mjose #+# #+# */ /* Updated: 2018/08/01 03:39:01 by mjose ### ########.fr */ /* */ /* ************************************************************************** */ #include "../Includes/ft_ls.h" unsigned long get_block_size(t_parms parms) { unsigned long block_size; block_size = 0; block_size = parms.cur_dir.infent.st_blocks; return (block_size); } int get_nlinks(t_parms parms) { int nlinks; nlinks = 0; nlinks = parms.cur_dir.infent.st_nlink; return (nlinks); } char *get_user(t_parms parms) { struct passwd *pinf; char *user; int uid; user = NULL; uid = parms.cur_dir.infent.st_uid; if (uid == 0) return ("root"); else if (uid == 4389) return ("4389"); pinf = getpwuid(uid); user = pinf->pw_name; return (user); } char *get_group(t_parms parms) { struct group *ginf; char *group; int gid; group = NULL; gid = parms.cur_dir.infent.st_gid; ginf = getgrgid(gid); group = ginf->gr_name; return (group); } t_parms get_info_for_padding(t_parms parms, int ctrl, char type) { int tmp; int len; if (!ctrl) { tmp = get_block_size(parms); parms.info.totblocks += tmp; } tmp = get_nlinks(parms); len = ft_intlen(tmp, 10); parms.infsiz.lnk = (len > parms.infsiz.lnk) ? len : parms.infsiz.lnk; len = ft_strlen(get_user(parms)); parms.infsiz.usr = (len > parms.infsiz.usr) ? len : parms.infsiz.usr; len = ft_strlen(get_group(parms)); parms.infsiz.grp = (len > parms.infsiz.grp) ? len : parms.infsiz.grp; if (type == 'b' || type == 'c') parms = get_info_for_pad_majmin(parms); tmp = get_size(parms); len = ft_intlen(tmp, 10); parms.infsiz.siz = (len > parms.infsiz.siz) ? len : parms.infsiz.siz; return (parms); }
C
CL
75d6378b663ce24ac6d259ee25383f32ba861cb582e383ec3a546dda5f6a01a8
// Copyright 2016 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 <ddk/device.h> #include <ddk/driver.h> #include <ddk/binding.h> #include <ddk/common/usb.h> #include <ddk/protocol/bluetooth-hci.h> #include <magenta/listnode.h> #include <magenta/device/bt-hci.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <threads.h> #include <unistd.h> #define EVENT_REQ_COUNT 8 #define ACL_READ_REQ_COUNT 8 #define ACL_WRITE_REQ_COUNT 8 #define ACL_BUF_SIZE 2048 // Uncomment these to force using a particular Bluetooth module // #define USB_VID 0x0a12 // CSR // #define USB_PID 0x0001 typedef struct { mx_device_t device; mx_device_t* usb_device; mx_handle_t control_pipe[2]; mx_handle_t acl_pipe[2]; void* intr_queue; // for accumulating HCI events uint8_t event_buffer[2 + 255]; // 2 byte header and 0 - 255 data size_t event_buffer_offset; size_t event_buffer_packet_length; // pool of free USB requests list_node_t free_event_reqs; list_node_t free_acl_read_reqs; list_node_t free_acl_write_reqs; mtx_t mutex; } hci_t; #define get_hci(dev) containerof(dev, hci_t, device) static void queue_acl_read_requests_locked(hci_t* hci) { list_node_t* node; while ((node = list_remove_head(&hci->free_acl_read_reqs)) != NULL) { iotxn_t* txn = containerof(node, iotxn_t, node); iotxn_queue(hci->usb_device, txn); } } static void queue_interrupt_requests_locked(hci_t* hci) { list_node_t* node; while ((node = list_remove_head(&hci->free_event_reqs)) != NULL) { iotxn_t* txn = containerof(node, iotxn_t, node); iotxn_queue(hci->usb_device, txn); } } static void hci_event_complete(iotxn_t* txn, void* cookie) { hci_t* hci = (hci_t*)cookie; mtx_lock(&hci->mutex); if (txn->status == NO_ERROR) { uint8_t* buffer; txn->ops->mmap(txn, (void **)&buffer); size_t length = txn->actual; size_t packet_size = buffer[1] + 2; // simple case - packet fits in received data if (hci->event_buffer_offset == 0 && length >= 2) { if (packet_size == length) { mx_status_t status = mx_channel_write(hci->control_pipe[0], 0, buffer, length, NULL, 0); if (status < 0) { printf("hci_interrupt failed to write\n"); } goto out; } } // complicated case - need to accumulate into hci->event_buffer if (hci->event_buffer_offset + length > sizeof(hci->event_buffer)) { printf("hci->event_buffer would overflow!\n"); goto out2; } memcpy(&hci->event_buffer[hci->event_buffer_offset], buffer, length); if (hci->event_buffer_offset == 0) { hci->event_buffer_packet_length = packet_size; } else { packet_size = hci->event_buffer_packet_length; } hci->event_buffer_offset += length; // check to see if we have a full packet if (packet_size <= hci->event_buffer_offset) { mx_status_t status = mx_channel_write(hci->control_pipe[0], 0, hci->event_buffer, packet_size, NULL, 0); if (status < 0) { printf("hci_interrupt failed to write\n"); } uint32_t remaining = hci->event_buffer_offset - packet_size; memmove(hci->event_buffer, hci->event_buffer + packet_size, remaining); hci->event_buffer_offset = 0; hci->event_buffer_packet_length = 0; } } out: list_add_head(&hci->free_event_reqs, &txn->node); queue_interrupt_requests_locked(hci); out2: mtx_unlock(&hci->mutex); } static void hci_acl_read_complete(iotxn_t* txn, void* cookie) { hci_t* hci = (hci_t*)cookie; if (txn->status == NO_ERROR) { void* buffer; txn->ops->mmap(txn, &buffer); mx_status_t status = mx_channel_write(hci->acl_pipe[0], 0, buffer, txn->actual, NULL, 0); if (status < 0) { printf("hci_acl_read_complete failed to write\n"); } } mtx_lock(&hci->mutex); list_add_head(&hci->free_acl_read_reqs, &txn->node); queue_acl_read_requests_locked(hci); mtx_unlock(&hci->mutex); } static void hci_acl_write_complete(iotxn_t* txn, void* cookie) { hci_t* hci = (hci_t*)cookie; // FIXME what to do with error here? mtx_lock(&hci->mutex); list_add_tail(&hci->free_acl_write_reqs, &txn->node); mtx_unlock(&hci->mutex); } static int hci_read_thread(void* arg) { hci_t* hci = (hci_t*)arg; mx_wait_item_t items[2]; items[0].handle = hci->control_pipe[0]; items[1].handle = hci->acl_pipe[0]; items[0].waitfor = MX_SIGNAL_READABLE; items[1].waitfor = MX_SIGNAL_READABLE; while (1) { mx_status_t status = mx_handle_wait_many(items, countof(items), MX_TIME_INFINITE); if (status < 0) { printf("mx_handle_wait_many fail\n"); break; } if (items[0].pending & MX_SIGNAL_READABLE) { uint8_t buf[256]; uint32_t length = sizeof(buf); status = mx_channel_read(items[0].handle, 0, buf, length, &length, NULL, 0, NULL); if (status >= 0) { status = usb_control(hci->usb_device, USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_DEVICE, 0, 0, 0, buf, length); if (status < 0) { printf("hci_read_thread control failed\n"); } } else { printf("event read failed\n"); break; } } if (items[1].pending & MX_SIGNAL_READABLE) { uint8_t buf[ACL_BUF_SIZE]; uint32_t length = sizeof(buf); status = mx_channel_read(items[1].handle, 0, buf, length, &length, NULL, 0, NULL); if (status >= 0) { mtx_lock(&hci->mutex); list_node_t* node; do { node = list_remove_head(&hci->free_acl_write_reqs); if (!node) { // FIXME this is nasty mtx_unlock(&hci->mutex); usleep(10 * 1000); mtx_lock(&hci->mutex); } } while (!node); mtx_unlock(&hci->mutex); iotxn_t* txn = containerof(node, iotxn_t, node); txn->ops->copyto(txn, buf, length, 0); txn->length = length; iotxn_queue(hci->usb_device, txn); } } } return 0; } static mx_handle_t hci_get_control_pipe(mx_device_t* device) { hci_t* hci = get_hci(device); return hci->control_pipe[1]; } static mx_handle_t hci_get_acl_pipe(mx_device_t* device) { hci_t* hci = get_hci(device); return hci->acl_pipe[1]; } static bluetooth_hci_protocol_t hci_proto = { .get_control_pipe = hci_get_control_pipe, .get_acl_pipe = hci_get_acl_pipe, }; static ssize_t hci_ioctl(mx_device_t* device, uint32_t op, const void* in_buf, size_t in_len, void* out_buf, size_t out_len) { switch (op) { case IOCTL_BT_HCI_GET_CONTROL_PIPE: { mx_handle_t* reply = out_buf; if (out_len < sizeof(*reply)) return ERR_BUFFER_TOO_SMALL; *reply = hci_get_control_pipe(device); return sizeof(*reply); } case IOCTL_BT_HCI_GET_ACL_PIPE: { mx_handle_t* reply = out_buf; if (out_len < sizeof(*reply)) return ERR_BUFFER_TOO_SMALL; *reply = hci_get_acl_pipe(device); return sizeof(*reply); } default: return ERR_NOT_SUPPORTED; } } static void hci_unbind(mx_device_t* device) { hci_t* hci = get_hci(device); device_remove(&hci->device); } static mx_status_t hci_release(mx_device_t* device) { hci_t* hci = get_hci(device); iotxn_t* txn; while ((txn = list_remove_head_type(&hci->free_event_reqs, iotxn_t, node)) != NULL) { txn->ops->release(txn); } while ((txn = list_remove_head_type(&hci->free_acl_read_reqs, iotxn_t, node)) != NULL) { txn->ops->release(txn); } while ((txn = list_remove_head_type(&hci->free_acl_write_reqs, iotxn_t, node)) != NULL) { txn->ops->release(txn); } mx_handle_close(hci->control_pipe[0]); mx_handle_close(hci->control_pipe[1]); mx_handle_close(hci->acl_pipe[0]); mx_handle_close(hci->acl_pipe[1]); free(hci); return NO_ERROR; } static mx_protocol_device_t hci_device_proto = { .ioctl = hci_ioctl, .unbind = hci_unbind, .release = hci_release, }; static mx_status_t hci_bind(mx_driver_t* driver, mx_device_t* device) { // find our endpoints usb_desc_iter_t iter; mx_status_t result = usb_desc_iter_init(device, &iter); if (result < 0) return result; usb_interface_descriptor_t* intf = usb_desc_iter_next_interface(&iter, true); if (!intf || intf->bNumEndpoints != 3) { usb_desc_iter_release(&iter); return ERR_NOT_SUPPORTED; } uint8_t bulk_in_addr = 0; uint8_t bulk_out_addr = 0; uint8_t intr_addr = 0; uint16_t intr_max_packet = 0; usb_endpoint_descriptor_t* endp = usb_desc_iter_next_endpoint(&iter); while (endp) { if (usb_ep_direction(endp) == USB_ENDPOINT_OUT) { if (usb_ep_type(endp) == USB_ENDPOINT_BULK) { bulk_out_addr = endp->bEndpointAddress; } } else { if (usb_ep_type(endp) == USB_ENDPOINT_BULK) { bulk_in_addr = endp->bEndpointAddress; } else if (usb_ep_type(endp) == USB_ENDPOINT_INTERRUPT) { intr_addr = endp->bEndpointAddress; intr_max_packet = usb_ep_max_packet(endp); } } endp = usb_desc_iter_next_endpoint(&iter); } usb_desc_iter_release(&iter); if (!bulk_in_addr || !bulk_out_addr || !intr_addr) { printf("hci_bind could not find endpoints\n"); return ERR_NOT_SUPPORTED; } hci_t* hci = calloc(1, sizeof(hci_t)); if (!hci) { printf("Not enough memory for hci_t\n"); return ERR_NO_MEMORY; } mx_status_t status = mx_channel_create(0, &hci->control_pipe[0], &hci->control_pipe[1]); if (status < 0) { goto fail; } status = mx_channel_create(0, &hci->acl_pipe[0], &hci->acl_pipe[1]); if (status < 0) { goto fail; } list_initialize(&hci->free_event_reqs); list_initialize(&hci->free_acl_read_reqs); list_initialize(&hci->free_acl_write_reqs); hci->usb_device = device; for (int i = 0; i < EVENT_REQ_COUNT; i++) { iotxn_t* txn = usb_alloc_iotxn(intr_addr, intr_max_packet, 0); if (!txn) { status = ERR_NO_MEMORY; goto fail; } txn->length = intr_max_packet; txn->complete_cb = hci_event_complete; txn->cookie = hci; list_add_head(&hci->free_event_reqs, &txn->node); } for (int i = 0; i < ACL_READ_REQ_COUNT; i++) { iotxn_t* txn = usb_alloc_iotxn(bulk_in_addr, ACL_BUF_SIZE, 0); if (!txn) { status = ERR_NO_MEMORY; goto fail; } txn->length = ACL_BUF_SIZE; txn->complete_cb = hci_acl_read_complete; txn->cookie = hci; list_add_head(&hci->free_acl_read_reqs, &txn->node); } for (int i = 0; i < ACL_WRITE_REQ_COUNT; i++) { iotxn_t* txn = usb_alloc_iotxn(bulk_out_addr, ACL_BUF_SIZE, 0); if (!txn) { status = ERR_NO_MEMORY; goto fail; } txn->length = ACL_BUF_SIZE; txn->complete_cb = hci_acl_write_complete; txn->cookie = hci; list_add_head(&hci->free_acl_write_reqs, &txn->node); } device_init(&hci->device, driver, "usb_bt_hci", &hci_device_proto); mtx_lock(&hci->mutex); queue_interrupt_requests_locked(hci); queue_acl_read_requests_locked(hci); mtx_unlock(&hci->mutex); thrd_t thread; thrd_create_with_name(&thread, hci_read_thread, hci, "hci_read_thread"); thrd_detach(thread); hci->device.protocol_id = MX_PROTOCOL_BLUETOOTH_HCI; hci->device.protocol_ops = &hci_proto; status = device_add(&hci->device, device); if (status == NO_ERROR) return NO_ERROR; fail: printf("hci_bind failed: %d\n", status); hci_release(&hci->device); return status; } mx_driver_t _driver_usb_bt_hci = { .ops = { .bind = hci_bind, }, }; MAGENTA_DRIVER_BEGIN(_driver_usb_bt_hci, "usb-bt-hci", "magenta", "0.1", 4) BI_ABORT_IF(NE, BIND_PROTOCOL, MX_PROTOCOL_USB), #if defined(USB_VID) && defined(USB_PID) BI_ABORT_IF(NE, BIND_USB_VID, USB_VID), BI_MATCH_IF(EQ, BIND_USB_PID, USB_PID), BI_ABORT(), #else BI_ABORT_IF(NE, BIND_USB_CLASS, 224), BI_ABORT_IF(NE, BIND_USB_SUBCLASS, 1), BI_MATCH_IF(EQ, BIND_USB_PROTOCOL, 1), #endif MAGENTA_DRIVER_END(_driver_usb_bt_hci)
C
CL
8dc08c07ae14e25b5618ea57c4d594084fbe9b9deaf189e2fdfb91f0db54ffe7
/****************************************************************************/ /* */ /* Module IOSVC */ /* External Declarations */ /* */ /****************************************************************************/ #define MAX_PAGE 16 /* max num of pages in a process */ /* external enumeration constants */ typedef enum { false, true /* the boolean data type */ } BOOL; typedef enum { read, write /* type of actions for I/O requests */ } IO_ACTION; typedef enum { running, ready, waiting, done /* types of status */ } STATUS; /* external type definitions */ typedef struct page_tbl_node PAGE_TBL; typedef struct event_node EVENT; typedef struct ofile_node OFILE; typedef struct pcb_node PCB; typedef struct iorb_node IORB; /* external data structures */ extern struct pcb_node { int pcb_id; /* PCB id */ int size; /* process size in bytes; assigned by SIMCORE */ int creation_time; /* assigned by SIMCORE */ int last_dispatch; /* last time the process was dispatched */ int last_cpuburst; /* length of the previous cpu burst */ int accumulated_cpu;/*accumulated CPU time */ PAGE_TBL *page_tbl; /* page table associated with the PCB */ STATUS status; /* status of process */ EVENT *event; /* event upon which process may be suspended */ int priority; /* user-defined priority; used for scheduling */ PCB *next; /* next pcb in whatever queue */ PCB *prev; /* previous pcb in whatever queue */ int *hook; /* can hook up anything here */ }; extern struct iorb_node { int iorb_id; /* iorb id */ int dev_id; /* associated device; index into the device table */ IO_ACTION action; /* read/write */ int block_id; /* block involved in the I/O */ int page_id; /* buffer page in the main memory */ PCB *pcb; /* PCB of the process that issued the request */ EVENT *event; /* event used to synchronize processes with I/O */ OFILE *file; /* associated entry in the open files table */ IORB *next; /* next iorb in the device queue */ IORB *prev; /* previous iorb in the device queue */ int *hook; /* can hook up anything here */ }; /* external variables */ extern PAGE_TBL *PTBR; /* page table base register */ /* external routines */ extern enq_io(/* iorb */); /* IORB *iorb; */ /****************************************************************************/ /* */ /* */ /* Module IOSVC */ /* Internal Routines */ /* */ /* */ /****************************************************************************/ void iosvc_handler(iorb) IORB *iorb; { } /* end of module */
C
CL
f4894c94b7e821b52f8d92aaf54e4749733e521186aa4e2235fe0204b18d519d
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <windows.h> #include "slab.h" #include "buddy.h" #define SLAB_SIZE (2*BLOCK_SIZE) #define CACHE_NAMELEN (20) int blockNum; void* spaceS; char* cache_list; char* sizeN_list; CRITICAL_SECTION slabMutex; struct kmem_cache_s { char* slabs_full; char* slabs_partial; char* slabs_free; int objsize; int num; int colour; int slabsCreated; int expand; void (*Ctor)(void*); void (*Dtor)(void*); char name[CACHE_NAMELEN]; char* next; int pos; }; typedef struct cache_sizes { size_t cs_size; kmem_cache_t* cs_cachep; } cache_sizes_t; typedef struct slab_s { char* next; char* s_mem; unsigned long colouroff; unsigned int inuse; int free[SLAB_SIZE]; } slab_t; void kmem_init(void* space, int block_num) { buddy_init(space, block_num); cache_list = NULL; spaceS = space; blockNum = block_num; sizeN_list = (char*)(buddy_alloc(spaceS, BLOCK_SIZE)); for (int i = 0; i < 13; i++) { char* sizeN = sizeN_list + i * sizeof(cache_sizes_t); int powTwo = i + 5; ((cache_sizes_t*)sizeN)->cs_size = pow(2, powTwo); ((cache_sizes_t*)sizeN)->cs_cachep = NULL; } printf("koliko keseva ima u blocku %d\n", BLOCK_SIZE/sizeof(kmem_cache_t)); InitializeCriticalSection(&slabMutex); } kmem_cache_t* kmem_cache_create(const char* name, size_t size, void (*ctor)(void*), void (*dtor)(void*)) { EnterCriticalSection(&slabMutex); if (size <= 0 || (ctor == NULL && dtor != NULL)) { printf("Wrong parameters for cache create!\n"); LeaveCriticalSection(&slabMutex); exit(1); } char* tek = cache_list; char* prev = NULL; kmem_cache_t cache; cache.slabs_full = NULL; cache.slabs_partial = NULL; cache.slabs_free = NULL; cache.objsize = size; if (name != NULL) strcpy_s(cache.name, 20, name); else name = NULL; cache.num = SLAB_SIZE / size; cache.colour = (SLAB_SIZE % size) / CACHE_L1_LINE_SIZE; cache.slabsCreated = 0; cache.expand = 0; cache.next = NULL; if (ctor != NULL) cache.Ctor = ctor; else cache.Ctor = NULL; if (dtor != NULL) cache.Dtor = dtor; else cache.Dtor = NULL; if (cache_list == NULL) { cache.pos = 0; cache_list = (char*)(buddy_alloc(spaceS, BLOCK_SIZE)); memcpy(cache_list, &cache, sizeof(kmem_cache_t)); tek = cache_list; } else { char* help = tek; while (((kmem_cache_t*)help)->next != NULL) { prev = tek; tek = ((kmem_cache_t*)help)->next; help = tek; } prev = tek; cache.pos = ((kmem_cache_t*)prev)->pos + 1; if (cache.pos != BLOCK_SIZE / sizeof(kmem_cache_t)) { tek += sizeof(kmem_cache_t); ((kmem_cache_t*)prev)->next = tek; memcpy(tek, &cache, sizeof(kmem_cache_t)); } else { cache.pos = 0; tek = (char*)(buddy_alloc(spaceS, BLOCK_SIZE)); ((kmem_cache_t*)prev)->next = tek; memcpy(tek, &cache, sizeof(kmem_cache_t)); } } printf("Napravljen kes sa imenom %s\n", ((kmem_cache_t*)tek)->name); LeaveCriticalSection(&slabMutex); return (kmem_cache_t*)tek; } void* kmem_cache_alloc(kmem_cache_t* cachep) { EnterCriticalSection(&slabMutex); if (cachep == NULL) { printf("Can't allocate cache that is not initialized!\n"); LeaveCriticalSection(&slabMutex); exit(1); } char* temp = cache_list; int gotIt = 0; if (cachep->name == NULL) { while (((kmem_cache_t*)temp) != NULL) { if ((((kmem_cache_t*)temp)->objsize == cachep->objsize) && (((kmem_cache_t*)temp)->name == NULL)) { gotIt = 1; break; } temp = ((kmem_cache_t*)temp)->next; } } else { while (((kmem_cache_t*)temp) != NULL) { if (((kmem_cache_t*)temp)->name == cachep->name && ((kmem_cache_t*)temp)->objsize == cachep->objsize) { gotIt = 1; break; } temp = ((kmem_cache_t*)temp)->next; } } if (gotIt == 0) { printf("Can't allocate object that does not have a cache\n"); LeaveCriticalSection(&slabMutex); exit(1); } if (((kmem_cache_t*)temp)->slabs_partial != NULL) { //printf("Ima delimicno popunjenih ploca\n"); char* help = ((kmem_cache_t*)temp)->slabs_partial; int i = 0; for (i = 0; i < ((kmem_cache_t*)temp)->num; i++) { if (((slab_t*)help)->free[i] == 0) break; } char* ret = (char*)(((slab_t*)help)->s_mem + ((slab_t*)help)->colouroff + i * ((kmem_cache_t*)temp)->objsize); ((slab_t*)help)->inuse++; ((slab_t*)help)->free[i] = 1; if (((kmem_cache_t*)temp)->Ctor != NULL) ((kmem_cache_t*)temp)->Ctor(ret); //printf("Alociramo element na lokaciji %d\n", ret); if (((slab_t*)help)->inuse == ((kmem_cache_t*)temp)->num) { printf("Popunili smo jedan delimican slab pa ga prebacujemo u listu punih slabova\n"); if (((slab_t*)help)->next != NULL) ((kmem_cache_t*)temp)->slabs_partial = ((slab_t*)help)->next; else ((kmem_cache_t*)temp)->slabs_partial = NULL; if (((kmem_cache_t*)temp)->slabs_full != NULL) ((slab_t*)help)->next = ((kmem_cache_t*)temp)->slabs_full; else ((slab_t*)help)->next = NULL; ((kmem_cache_t*)temp)->slabs_full = help; } LeaveCriticalSection(&slabMutex); return ret; } else if (((kmem_cache_t*)temp)->slabs_free != NULL) { printf("Ima slobodnih ploca\n"); char* help = ((kmem_cache_t*)temp)->slabs_free; char* ret = ((slab_t*)help)->s_mem = ((slab_t*)help)->colouroff; ((slab_t*)help)->inuse++; ((slab_t*)help)->free[0] = 1; if (((slab_t*)help)->next != NULL) ((kmem_cache_t*)temp)->slabs_free = ((slab_t*)help)->next; else ((kmem_cache_t*)temp)->slabs_free = NULL; if (((kmem_cache_t*)temp)->slabs_partial != NULL) ((slab_t*)help)->next = ((kmem_cache_t*)temp)->slabs_partial; else ((slab_t*)help)->next = NULL; ((kmem_cache_t*)temp)->slabs_partial = help; LeaveCriticalSection(&slabMutex); return ret; } else if ((((kmem_cache_t*)temp)->slabs_free == NULL) && (((kmem_cache_t*)temp)->slabs_partial == NULL)) { printf("Nema nista slobodno - moramo da pravimo novi slab\n"); ((kmem_cache_t*)temp)->slabs_partial = (char*)(buddy_alloc(spaceS, sizeof(slab_t))); char* initSlabManager = ((kmem_cache_t*)temp)->slabs_partial; ((slab_t*)initSlabManager)->next = NULL; for (int i = 0; i < ((kmem_cache_t*)temp)->num; i++) ((slab_t*)initSlabManager)->free[i] = 0; ((slab_t*)initSlabManager)->inuse = 1; if (cachep->colour != 0) { ((slab_t*)initSlabManager)->colouroff = (cachep->slabsCreated % cachep->colour) * CACHE_L1_LINE_SIZE; } else ((slab_t*)initSlabManager)->colouroff = 0; ((slab_t*)initSlabManager)->s_mem = (char*)(buddy_alloc(spaceS, SLAB_SIZE)); void* ObjectStart = (void*)(((slab_t*)initSlabManager)->s_mem + ((slab_t*)initSlabManager)->colouroff); if (((kmem_cache_t*)temp)->Ctor != NULL) ((kmem_cache_t*)temp)->Ctor(ObjectStart); /*if (((kmem_cache_t*)temp)->Ctor != NULL) { for (int i = 0; i < ((kmem_cache_t*)temp)->num; i++) { void* ObjectStart = (void*)(((slab_t*)initSlabManager)->s_mem + ((slab_t*)initSlabManager)->colouroff + i* ((kmem_cache_t*)temp)->objsize); ((kmem_cache_t*)temp)->Ctor(ObjectStart); } }**/ ((slab_t*)initSlabManager)->free[0] = 1; ((kmem_cache_t*)temp)->slabsCreated++; if (((kmem_cache_t*)temp)->expand != 0) ((kmem_cache_t*)temp)->expand = 2; printf("Napravljen novi slab, kes sa imenom %s ima ukupno %d slabova\n", ((kmem_cache_t*)temp)->name, ((kmem_cache_t*)temp)->slabsCreated); char* ret = ((slab_t*)initSlabManager)->s_mem + ((slab_t*)initSlabManager)->colouroff; if (((slab_t*)initSlabManager)->inuse == ((kmem_cache_t*)temp)->num) { printf("Popunili smo jedan delimican slab pa ga prebacujemo u listu punih slabova\n"); if (((slab_t*)initSlabManager)->next != NULL) ((kmem_cache_t*)temp)->slabs_partial = ((slab_t*)initSlabManager)->next; else ((kmem_cache_t*)temp)->slabs_partial = NULL; if (((kmem_cache_t*)temp)->slabs_full != NULL) ((slab_t*)initSlabManager)->next = ((kmem_cache_t*)temp)->slabs_full; else ((slab_t*)initSlabManager)->next = NULL; ((kmem_cache_t*)temp)->slabs_full = initSlabManager; } LeaveCriticalSection(&slabMutex); return ret; } LeaveCriticalSection(&slabMutex); return NULL; } void kmem_cache_free(kmem_cache_t* cachep, void* objp) { EnterCriticalSection(&slabMutex); if (cachep == NULL || objp == NULL) { printf("Can't deallocate cache that is not allocated!\n"); LeaveCriticalSection(&slabMutex); exit(1); } char* temp = cache_list; int gotIt = 0; if (cachep->name == NULL) { while (((kmem_cache_t*)temp) != NULL) { if ((((kmem_cache_t*)temp)->objsize == cachep->objsize) && (((kmem_cache_t*)temp)->name == NULL)) { gotIt = 1; break; } temp = ((kmem_cache_t*)temp)->next; } } else { while (((kmem_cache_t*)temp) != NULL) { if (((kmem_cache_t*)temp)->name == cachep->name && ((kmem_cache_t*)temp)->objsize == cachep->objsize) { gotIt = 1; break; } temp = ((kmem_cache_t*)temp)->next; } } if (gotIt == 0) { printf("Can't deallocate object that does not have a cache\n"); LeaveCriticalSection(&slabMutex); exit(1); } if (((kmem_cache_t*)temp)->slabs_full != NULL) { char* help = ((kmem_cache_t*)temp)->slabs_full; char* prev = NULL; int found = 0; while (((slab_t*)help) != NULL) { char* deObj = NULL; for (int i = 0; i < ((kmem_cache_t*)temp)->num; i++) { deObj = ((slab_t*)help)->s_mem + ((slab_t*)help)->colouroff + ((kmem_cache_t*)temp)->objsize * i; if (deObj == objp) { found = 1; ((slab_t*)help)->free[i] = 0; ((slab_t*)help)->inuse--; break; } } if (found == 1) break; prev = help; help = ((slab_t*)help)->next; } if (found == 1) { if (((slab_t*)help)->inuse == 0) { if (prev == NULL)((kmem_cache_t*)temp)->slabs_partial = ((slab_t*)help)->next; else if (((slab_t*)help)->next != NULL) ((slab_t*)prev)->next = ((slab_t*)help)->next; else ((slab_t*)prev)->next = NULL; if (((kmem_cache_t*)temp)->slabs_free != NULL) ((slab_t*)help)->next = ((kmem_cache_t*)temp)->slabs_free; else ((slab_t*)help)->next = NULL; ((kmem_cache_t*)temp)->slabs_free = ((slab_t*)help); printf("Partial slab je prebacen u free listu\n"); LeaveCriticalSection(&slabMutex); return; } if (prev == NULL)((kmem_cache_t*)temp)->slabs_full = ((slab_t*)help)->next; else if (((slab_t*)help)->next != NULL) ((slab_t*)prev)->next = ((slab_t*)help)->next; else ((slab_t*)prev)->next = NULL; if (((kmem_cache_t*)temp)->slabs_partial != NULL) ((slab_t*)help)->next = ((kmem_cache_t*)temp)->slabs_partial; else ((slab_t*)help)->next = NULL; ((kmem_cache_t*)temp)->slabs_partial = ((slab_t*)help); printf("Dealociran objekat iz full liste\n"); LeaveCriticalSection(&slabMutex); return; } } if (((kmem_cache_t*)temp)->slabs_partial != NULL) { char* help = ((kmem_cache_t*)temp)->slabs_partial; char* prev = NULL; int found = 0; char* deObj = NULL; while (((slab_t*)help) != NULL) { for (int i = 0; i < ((kmem_cache_t*)temp)->num; i++) { deObj = ((slab_t*)help)->s_mem + ((slab_t*)help)->colouroff + ((kmem_cache_t*)temp)->objsize * i; if (deObj == objp && ((slab_t*)help)->free[i] == 1) { found = 1; ((slab_t*)help)->free[i] = 0; ((slab_t*)help)->inuse--; break; } } if (found == 1) break; prev = help; help = ((slab_t*)help)->next; } if (found == 1) { //printf("Dealociran objekat iz partial liste!\n"); if (((slab_t*)help)->inuse == 0) { if (prev == NULL)((kmem_cache_t*)temp)->slabs_partial = ((slab_t*)help)->next; else if (((slab_t*)help)->next != NULL) ((slab_t*)prev)->next = ((slab_t*)help)->next; else ((slab_t*)prev)->next = NULL; if (((kmem_cache_t*)temp)->slabs_free != NULL) ((slab_t*)help)->next = ((kmem_cache_t*)temp)->slabs_free; else ((slab_t*)help)->next = NULL; ((kmem_cache_t*)temp)->slabs_free = ((slab_t*)help); printf("Partial slab je prebacen u free listu\n"); LeaveCriticalSection(&slabMutex); return; } } else { printf("Deallocation not possible!\n"); LeaveCriticalSection(&slabMutex); exit(1); } } else { printf("No allocated objects in this cache!\n"); LeaveCriticalSection(&slabMutex); return; } LeaveCriticalSection(&slabMutex); } void* kmalloc(size_t size) { EnterCriticalSection(&slabMutex); printf("E "); char* str = NULL; int i = -1; if (size > 0 && size <= 32) i = 0; else if (size > 32 && size <= 64) i = 1; else if (size > 64 && size <= 128) i = 2; else if (size > 128 && size <= 256) i = 3; else if (size > 256 && size <= 512) i = 4; else if (size > 512 && size <= 1024) i = 5; else if (size > 1024 && size <= 2048) i = 6; else if (size > 2048 && size <= 4096) i = 7; else if (size > 4196 && size <= 8192) i = 8; else if (size > 8192 && size <= 16384) i = 9; else if (size > 16384 && size <= 32768) i = 10; else if (size > 32768 && size <= 65536) i = 11; else if (size > 65536 && size <= 131072) i = 12; else { printf("That size can not be allocated with small memory buffers!\n"); LeaveCriticalSection(&slabMutex); exit(1); } str = sizeN_list + i * sizeof(cache_sizes_t); if (((cache_sizes_t*)str)->cs_cachep == NULL) { ((cache_sizes_t*)str)->cs_cachep = kmem_cache_create(NULL, size, NULL, NULL); } void* ret = kmem_cache_alloc(((cache_sizes_t*)str)->cs_cachep); printf("L\n"); LeaveCriticalSection(&slabMutex); return ret; } void kfree(const void* objp) { EnterCriticalSection(&slabMutex); kmem_cache_t* cache = cache_list; char* buffer = sizeN_list; if (cache == NULL || buffer == NULL || objp == NULL) { printf("Wrong parameters!\n"); LeaveCriticalSection(&slabMutex); exit(1); } while (cache != NULL) { for (int i = 0; i < 13; i++) { buffer = sizeN_list + i * sizeof(cache_sizes_t); if (((cache_sizes_t*)buffer)->cs_cachep == cache) { char* objFreeF = ((cache_sizes_t*)buffer)->cs_cachep->slabs_full; while (objFreeF != 0) { for (int i = 0; i < ((cache_sizes_t*)buffer)->cs_cachep->num; i++) { objFreeF = ((slab_t*)(((cache_sizes_t*)buffer)->cs_cachep->slabs_full))->s_mem + ((slab_t*)(((cache_sizes_t*)buffer)->cs_cachep->slabs_full))->colouroff + i * ((cache_sizes_t*)buffer)->cs_cachep->objsize; if (objFreeF = objp) { kmem_cache_free(((cache_sizes_t*)buffer)->cs_cachep, objp); LeaveCriticalSection(&slabMutex); return; } } objFreeF = ((slab_t*)(((cache_sizes_t*)buffer)->cs_cachep->slabs_full))->next; } objFreeF = ((cache_sizes_t*)buffer)->cs_cachep->slabs_partial; while (objFreeF != 0) { for (int i = 0; i < ((cache_sizes_t*)buffer)->cs_cachep->num; i++) { objFreeF = ((slab_t*)(((cache_sizes_t*)buffer)->cs_cachep->slabs_partial))->s_mem + ((slab_t*)(((cache_sizes_t*)buffer)->cs_cachep->slabs_partial))->colouroff + i * ((cache_sizes_t*)buffer)->cs_cachep->objsize; if (objFreeF = objp) { kmem_cache_free(((cache_sizes_t*)buffer)->cs_cachep, objp); LeaveCriticalSection(&slabMutex); return; } } objFreeF = ((slab_t*)(((cache_sizes_t*)buffer)->cs_cachep->slabs_partial))->next; } } } cache = cache->next; } LeaveCriticalSection(&slabMutex); } int kmem_cache_shrink(kmem_cache_t* cachep) { EnterCriticalSection(&slabMutex); if (cachep == NULL) { printf("Can't shrink cache that does not exist!\n"); LeaveCriticalSection(&slabMutex); exit(1); } char* temp = cache_list; int gotIt = 0; if (cachep->name == NULL) { while (((kmem_cache_t*)temp) != NULL) { if ((((kmem_cache_t*)temp)->objsize == cachep->objsize) && (((kmem_cache_t*)temp)->name == NULL)) { gotIt = 1; break; } temp = ((kmem_cache_t*)temp)->next; } } else { while (((kmem_cache_t*)temp) != NULL) { if (((kmem_cache_t*)temp)->name == cachep->name && ((kmem_cache_t*)temp)->objsize == cachep->objsize) { gotIt = 1; break; } temp = ((kmem_cache_t*)temp)->next; } } if (gotIt == 0) { printf("Can't shrink cache that is not initialized!\n"); LeaveCriticalSection(&slabMutex); exit(1); } if (((kmem_cache_t*)temp)->slabs_free == NULL) return 0; else if (((kmem_cache_t*)temp)->expand == 0 || ((kmem_cache_t*)temp)->expand == 1) { if (((kmem_cache_t*)temp)->expand == 0) ((kmem_cache_t*)temp)->expand = 1; char* help = ((kmem_cache_t*)temp)->slabs_free; char* deObj = NULL; int ret = 0; while (help != NULL) { for (int i = 0; i < ((kmem_cache_t*)temp)->num; i++) { deObj = ((slab_t*)help)->s_mem + ((slab_t*)help)->colouroff + ((kmem_cache_t*)temp)->objsize * i; if (((kmem_cache_t*)temp)->Dtor != NULL) ((kmem_cache_t*)temp)->Dtor(deObj); } buddy_dealloc(spaceS, blockNum, ((slab_t*)help)->s_mem); deObj = help; help = ((slab_t*)help)->next; buddy_dealloc(spaceS, blockNum, deObj); ret += SLAB_SIZE / BLOCK_SIZE; } ((kmem_cache_t*)temp)->slabs_free = NULL; printf("Obrisana free lista!\n"); LeaveCriticalSection(&slabMutex); return ret; } LeaveCriticalSection(&slabMutex); return 0; } void kmem_cache_destroy(kmem_cache_t* cachep) { EnterCriticalSection(&slabMutex); kmem_cache_t* cache = cache_list; kmem_cache_t* prevCache = NULL; if (cachep == NULL) { printf("Wrong parameters for destroying cache!\n"); LeaveCriticalSection(&slabMutex); exit(1); } int gotIt = 0; while (cache != NULL) { if (cache == cachep) { gotIt = 1; break; } prevCache = cache; cache = cache->next; } if (gotIt == 0) { printf("No such cache to destroy!\n"); LeaveCriticalSection(&slabMutex); exit(1); } slab_t* free = cache->slabs_free; slab_t* prev = NULL; while (free != NULL) { buddy_dealloc(spaceS, blockNum, free->s_mem); prev = free; free = free->next; buddy_dealloc(spaceS, blockNum, prev); } cache->slabs_free = NULL; free = cache->slabs_partial; prev = NULL; while (free != NULL) { buddy_dealloc(spaceS, blockNum, free->s_mem); prev = free; free = free->next; buddy_dealloc(spaceS, blockNum, prev); } cache->slabs_partial = NULL; free = cache->slabs_full; prev = NULL; while (free != NULL) { buddy_dealloc(spaceS, blockNum, free->s_mem); prev = free; free = free->next; buddy_dealloc(spaceS, blockNum, prev); } cache->slabs_full = NULL; if (cache->next != NULL && prevCache != NULL) prevCache->next = cache->next; else if(cache->next == NULL && prevCache != NULL) prevCache->next = NULL; if (cache_list == cache && cache->next == NULL) cache_list = NULL; else if (cache_list == cache && cache->next != NULL) cache_list = cache->next; cache->next = NULL; //buddy_dealloc(spaceS, blockNum, cache); printf("Cache on %d deallocated\n", cache); cache = NULL; LeaveCriticalSection(&slabMutex); } void kmem_cache_info(kmem_cache_t* cachep) { EnterCriticalSection(&slabMutex); if (cachep == NULL) { printf("Wrong parameters for cache info!\n"); LeaveCriticalSection(&slabMutex); exit(1); } printf("\nCACHE INFORMATION: \n\tCache name is \"%s\"\n", cachep->name); printf("\tSize of one object in cache is %d\n", cachep->objsize); int slabs = 0; int inUse = 0; if (cachep->slabs_full != NULL) { slab_t* help = cachep->slabs_full; while (help != NULL) { slabs++; help = help->next; } } inUse += slabs * cachep->num; if (cachep->slabs_partial != NULL) { slab_t* help = cachep->slabs_partial; while (help != NULL) { slabs++; inUse += help->inuse; help = help->next; } } if (cachep->slabs_free != NULL) { slab_t* help = cachep->slabs_free; while (help != NULL) { slabs++; help = help->next; } } int ret = 0; if (slabs != 0) { ret = SLAB_SIZE / BLOCK_SIZE; ret *= slabs; } printf("\tSize of cache in blocks is %d blocks\n", ret); printf("\tNumber of slabs in cache is %d\n", slabs); printf("\tNumber of objects in one slab is %d\n", cachep->num); printf("\tProcent of used cache is %lf \n\n", ((double)inUse / (cachep->num * slabs))*100); LeaveCriticalSection(&slabMutex); } int kmem_cache_error(kmem_cache_t* cachep) { EnterCriticalSection(&slabMutex); if (cachep == NULL) { LeaveCriticalSection(&slabMutex); return 0; } kmem_cache_t* tmp = cache_list; int gotIt = 0; while (tmp != 0) { if (tmp == cachep) gotIt = 1; tmp = tmp->next; } if (gotIt == 0) { LeaveCriticalSection(&slabMutex); return 0; } else { LeaveCriticalSection(&slabMutex); return 1; } }
C
CL
1d267d927852be486e79a7689889ecdcc92b19312032556f7ee6e1e99bb3bdf8
#include <stdint.h> /* Declarations of uint_32 and the like */ #include <pic32mx.h> /* Declarations of system-specific addresses etc */ #include "header.h" /* Declatations for these labs */ #define TMR2PERIOD ((80000000 / 256) / 10) // 100ms #if TMR2PERIOD > 0xffff #error "TimerPeriodIsTooBig" #endif int timeoutcount = 0; void setupOS ( void ) { /* This will set the peripheral bus clock to the same frequency as the sysclock. That means 80 MHz, when the microcontroller is running at 80 MHz. Changed 2017, as recommended by Axel. */ SYSKEY = 0xAA996655; /* Unlock OSCCON, step 1 */ SYSKEY = 0x556699AA; /* Unlock OSCCON, step 2 */ while(OSCCON & (1 << 21)); /* Wait until PBDIV ready */ OSCCONCLR = 0x180000; /* clear PBDIV bit <0,1> */ while(OSCCON & (1 << 21)); /* Wait until PBDIV ready */ SYSKEY = 0x0; /* Lock OSCCON */ } void setupTimers ( void ) { PR2 = TMR2PERIOD; T2CONSET = 0x70; // setting the prescale TMR2 = 0; // reset timer to 0 T2CONSET = 0x8000; // turn timer on, set bit 15 to 1 IEC(0) = 0x100; // IFS0 bit 8 for enable interrupt IPC(2) = 0x4; // timer 2 interrupt bits 4:2 for IPC2 enable_interrupt(); return; } void setupSPI ( void ) { /* Set up SPI as master */ SPI2CON = 0; SPI2BRG = 4; /* SPI2STAT bit SPIROV = 0; */ SPI2STATCLR = 0x40; /* SPI2CON bit CKP = 1; */ SPI2CONSET = 0x40; /* SPI2CON bit MSTEN = 1; */ SPI2CONSET = 0x20; /* SPI2CON bit ON = 1; */ SPI2CONSET = 0x8000; } void setupPorts ( void ) { /* Set up output pins */ AD1PCFG = 0xFFFF; ODCE = 0x0; TRISECLR = 0xFF; PORTE = 0x0; /* Output pins for display signals */ PORTF = 0xFFFF; PORTG = (1 << 9); ODCF = 0x0; ODCG = 0x0; TRISFCLR = 0x70; TRISGCLR = 0x200; /* Set up input pins */ TRISDSET = (1 << 8); TRISFSET = (1 << 1); }
C
CL
e509974087b9370c891355df9323c9a05f19b15340e659e41310fa2e4fbadb74
#include <util/delay.h> #include <avr/io.h> #include <stdio.h> #include "uart.h" #include "leds.h" #include "adc.h" /* * Wait (100 * 160000) cycles = wait 16000000 cycles. * Equivalent to 1 second at 16 MHz. */ void delay_10ms(int num) { uint16_t i; for (i=0; i < num; i++){ /* wait (40000 x 4) cycles = wait 160000 cycles */ _delay_loop_2(40000); } } uint32_t read_gas_mq(void) { uint32_t result; result = adc_scm_read(); /* * Sanity check: * ADC = Vin*1024/Vref = (Vin/Vref)*1024 * Vref = 5.0v, Vin <= 5.0v => * Vin/Vref <= 1 => * ADC = (Vin/Vref)*1024 < 1024 => * ADC fits to 10bit resolution * * Calculate Vcc in mV: * ADC = (Vin/Vref)*1024 = Vin*1024/5000mV * Vin = 5000mV * (ADC/1024) */ result = result * 5000 / 1024; return result; } int main (void) { uint32_t gas = 0; uart_init(); leds_init(); /* Vref = AVcc = Vcc = 5V, input channel Vin = A0(ADC0) */ adc_scm_init(0x1, 0x0); while (1) { gas = read_gas_mq(); printf("gas[%u]\n", gas); led_on(0); delay_10ms(100); gas = read_gas_mq(); printf("gas[%u]\n", gas); led_off(0); delay_10ms(100); } return 1; }
C
CL
234bc91142eabee942941e8d65ab9aa493505e7c78715b8e51cc60c79d7945cf
#ifndef __GENERAL_H__ #define __GENERAL_H__ #define CONFIG_SUPPORT_DEBUG_MESSAGE /** standar C * */ extern "C"{ #ifdef __cplusplus #define __STDC_CONSTANT_MACROS #define __STDC_FORMAT_MACROS #ifdef _STDINT_H #undef _STDINT_H #endif #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <unistd.h> #endif #ifndef INT64_C #define INT64_C #define UINT64_C //#define UINT64_C(value) __CONCAT(value,ULL) #endif #define SUCCESS 0 #define FAILED -1 #ifndef CONFIG_SUPPORT_DEBUG_MESSAGE #define UMFDBG(level, fmt, args...) #else #define UMFDEBUG #ifdef UMFDEBUG #define UMFDBG(fmt, args...) do {fprintf(stderr, "[UMF] " fmt, ## args); fflush(stderr);}while(0) #else #define UMFDBG(level, fmt, args...) #endif #endif #define MPEG_FUNC_CALL(funcCall) if(SUCCESS!=(funcCall)) \ {UMFDBG("[RET ERROR][FUNC]:[%s] [LINE]:[%d]\n", __FUNCTION__,__LINE__);} #define MEM_FUNC_CALL(funcCall) if(NULL==(funcCall)) \ {UMFDBG("[MEM ERROR][FUNC]:[%s] [LINE]:[%d]\n", __FUNCTION__,__LINE__);} } /** FFMPEG * */ extern "C" { #include <libavcodec/avcodec.h> #include <libavformat/avformat.h> #include <libswscale/swscale.h> #include <libavdevice/avdevice.h> #include <libavformat/version.h> #include <libavutil/time.h> #include <libavutil/mathematics.h> #include <libswresample/swresample.h> #include <libavutil/frame.h> #include <libavutil/mem.h> #include <libavutil/opt.h> #include <libavutil/imgutils.h> #include <libavutil/timestamp.h> /*** FFmpeg log System * av_log_set_level(AV_LOG_DEBUG); * av_log(NULL, AV_LOG_INFO, "...%s\n", op); **/ #include <libavutil/log.h> } /* SDL * */ extern "C"{ #include <SDL.h> } #undef main /** for QT * */ #include <QMainWindow> #include <QDebug> #include <QFileDialog> #include <QString> #include <QByteArray> #include <QDir> #include <QString> #include <QStringList> #include <QTextEdit> #include <QContextMenuEvent> #include <QMessageBox> #endif
C
CL
15a3bd24976e67fbb21b533a6c8bf36c347b817f85d440b5c3eff97d8524a0fa
#include<stdio.h> // The first index of the tag array is the 'index' // The second index of the tag array is the 'way' int tag[2][4]; int mru[2][4] = {{3, 2, 1, 0}, {3, 2, 1, 0}}; // This stores the ways for each set in the // most recently used order, that is the // 0th position for a set corresponds to // the most recently used way, and the 3rd // position corresponds to the least recently // used way. // This function updates the most recently used // array using the way recently used void mruUpdate(int set, int way) { int j; for(j = 0;j < 4;j++) // Finds the position of way in the mru[set] array { if(mru[set][j] == way) break; } // If the way used is not at the start of the mru[set] array // then shift all the elements which were initially to // the left of the way, one unit to the right while(j > 0) { mru[set][j] = mru[set][j-1]; j--; } // set the 0th index of mru[set] to the way mru[set][0] = way; } int main() { int addr; // variable for address int hits, accesses; // variables for number of hits and number of accesses int i, t, j, x; // variables for index, tag, way, LRU way FILE *fp; // file pointer fp = fopen("trace.txt", "r"); // opening trace.txt hits = 0; accesses = 0; while(fscanf(fp, "%x", &addr) > 0) // While input is present { // In this cache design we have two offset bits - 0 and 1, // one index bit - 2 and 29 tag bits 3 to 31 i = (addr>>2)&1; // extracting the index from the address t = addr | 0x7; // extracting the tag from the address accesses ++; // incrementing the number of accesses for(j = 0;j < 4;j++) { if(tag[i][j] == t) // If tag is found in the ith set, then it's a hit { hits++; // incrementing the number of hits printf(" Hit\n"); mruUpdate(i, j); // update the mru array using the way just used break; } } if(j == 4) // tag is not present in the ith set { printf(" Miss\n"); x = mru[i][3]; // set x to the least recently used way in the ith set tag[i][x] = t; // set the tag corresponding to the ith set and xth way to be t mruUpdate(i, x); // update the mru array using the way just used } for(i = 0;i < 2;i++) // printing the tag array { for(j = 0;j < 4;j++) printf("0x%08x ", tag[i][j]); printf("\n"); } for(i = 0;i < 2;i++) // printing the mru array { for(j = 0;j < 4;j++) printf("%d ", mru[i][j]); printf("\n"); } } printf("Hits = %d, Accesses = %d, Hit ratio = %f\n", hits, accesses, (float)hits/accesses); // printing the number of hits, number of accesses and hit rate fclose(fp); // closing the file used return 0; }
C
CL
2c6024c942bb8c6fdc3d0248b41ecdae86d56868bb15c7141b3f7d26da389c73
/* Copyright (C) 2010-2015 Marvell International Ltd. Copyright (C) 2002-2010 Kinoma, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef __KPRCONTENT__ #define __KPRCONTENT__ #include "kpr.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ FskAPI(void) KprMarginsApply(KprMargins margins, FskRectangle src, FskRectangle dst); FskAPI(void) KprCoordinatesSet(KprCoordinates coordinates, UInt16 horizontal, SInt32 left, SInt32 width, SInt32 right, UInt16 vertical, SInt32 top, SInt32 height, SInt32 bottom); typedef void (*KprContentActivatedProc)(void* it, Boolean activateIt); typedef void (*KprContentAddedProc)(void* it, KprContent content); typedef void (*KprContentCascadeProc)(void* it, KprStyle style); typedef void (*KprContentDisposeProc)(void* it); typedef void (*KprContentDrawProc)(void* it, FskPort port, FskRectangle area); typedef void (*KprContentFitProc)(void* it); typedef FskBitmap (*KprContentGetBitmapProc)(void* it, FskPort port, Boolean* owned); typedef KprContent (*KprContentHitProc)(void* it, SInt32 x, SInt32 y); typedef void (*KprContentIdleProc)(void* it, double ticks); typedef void (*KprContentInvalidatedProc)(void* it, FskRectangle area); typedef void (*KprContentLayeredProc)(void* it, KprLayer layer, Boolean layerIt); typedef void (*KprContentMarkProc)(void* it, xsMarkRoot markRoot); typedef void (*KprContentMeasureProc)(void* it); typedef void (*KprContentPlaceProc)(void* it); typedef void (*KprContentPlacedProc)(void* it); typedef void (*KprContentPredictProc)(void* it, FskRectangle area); typedef void (*KprContentReflowingProc)(void* it, UInt32 flags); typedef void (*KprContentRemovingProc)(void* it, KprContent content); typedef void (*KprContentSetWindowProc)(void* it, KprShell shell, KprStyle style); typedef void (*KprContentShowingProc)(void* it, Boolean showIt); typedef void (*KprContentShownProc)(void* it, Boolean showIt); typedef void (*KprContentUpdateProc)(void* it, FskPort port, FskRectangle area); struct KprDispatchStruct { char* type; KprContentActivatedProc activated; KprContentAddedProc added; KprContentCascadeProc cascade; KprContentDisposeProc dispose; KprContentDrawProc draw; KprContentFitProc fitHorizontally; KprContentFitProc fitVertically; KprContentGetBitmapProc getBitmap; KprContentHitProc hit; KprContentIdleProc idle; KprContentInvalidatedProc invalidated; KprContentLayeredProc layered; KprContentMarkProc mark; KprContentMeasureProc measureHorizontally; KprContentMeasureProc measureVertically; KprContentPlaceProc place; KprContentPlacedProc placed; KprContentPredictProc predict; KprContentReflowingProc reflowing; KprContentRemovingProc removing; KprContentSetWindowProc setWindow; KprContentShowingProc showing; KprContentShownProc shown; KprContentUpdateProc update; }; struct KprContentStruct { KprSlotPart; KprContentPart; }; FskAPI(FskErr) KprContentNew(KprContent *self, KprCoordinates coordinates, KprSkin skin, KprStyle style); FskAPI(void) KprContentCancel(KprContent self); FskAPI(void) KprContentClose(KprContent self); FskAPI(void) KprContentComplete(KprMessage message, void* it); FskAPI(Boolean) KprContentFindFocus(KprContent self, UInt32 axis, SInt32 delta, KprContent current); FskAPI(void) KprContentFromWindowCoordinates(KprContent self, SInt32 x0, SInt32 y0, SInt32 *x1, SInt32 *y1); FskAPI(KprStyle) KprContentGetStyle(KprContent self); FskAPI(SInt32) KprContentIndex(KprContent self); FskAPI(void) KprContentInitialize(KprContent self, KprCoordinates coordinates, KprSkin skin, KprStyle style); FskAPI(void) KprContentInvalidate(KprContent self); FskAPI(Boolean) KprContentIsFocus(KprContent self); FskAPI(Boolean) KprContentIsShown(KprContent self); FskAPI(void) KprContentMoveBy(KprContent self, SInt32 dx, SInt32 dy); FskAPI(void) KprContentPlacing(KprContent self); FskAPI(void) KprContentReflow(KprContent self, UInt32 flags); FskAPI(void) KprContentSetBehavior(KprContent self, KprBehavior behavior); FskAPI(void) KprContentSetCoordinates(void* it, KprCoordinates coordinates); FskAPI(void) KprContentSetDuration(KprContent self, double duration); FskAPI(void) KprContentSetFraction(KprContent self, double fraction); FskAPI(void) KprContentSetInterval(KprContent self, double interval); FskAPI(void) KprContentSetSkin(KprContent self, KprSkin skin); FskAPI(void) KprContentSetStyle(KprContent self, KprStyle style); FskAPI(void) KprContentSetTime(KprContent self, double time); FskAPI(void) KprContentShow(KprContent self, Boolean showIt); FskAPI(void) KprContentSizeBy(KprContent self, SInt32 dx, SInt32 dy); FskAPI(void) KprContentStart(KprContent self); FskAPI(void) KprContentStop(KprContent self); FskAPI(void) KprContentToWindowCoordinates(KprContent self, SInt32 x0, SInt32 y0, SInt32 *x1, SInt32 *y1); extern void KprContentActivated(void* it, Boolean activateIt); extern void KprContentAdded(void* it, KprContent content); extern void KprContentCascade(void* it, KprStyle style); extern void KprContentDispose(void* it); extern void KprContentDraw(void* it, FskPort port, FskRectangle area); extern void KprContentFitHorizontally(void* it); extern void KprContentFitVertically(void* it); extern FskBitmap KprContentGetBitmap(void* it, FskPort port, Boolean* owned); extern KprContent KprContentHit(void* it, SInt32 x, SInt32 y); extern void KprContentIdle(void* it, double ticks); extern void KprContentLayered(void* it, KprLayer layer, Boolean layerIt); extern void KprContentInvalidated(void* it, FskRectangle area); extern void KprContentMark(void* it, xsMarkRoot markRoot); extern void KprContentMeasureHorizontally(void* it); extern void KprContentMeasureVertically(void* it); extern void KprContentPlace(void* it); extern void KprContentPlaced(void* it); extern void KprContentPlaceHorizontally(KprContent self, SInt32 containerWidth); extern void KprContentPlaceVertically(KprContent self, SInt32 containerHeight); extern void KprContentPredict(void* it, FskRectangle area); extern void KprContentReflowing(void* it, UInt32 flags); extern void KprContentRemoving(void* it, KprContent content); extern void KprContentSetWindow(void* it, KprShell shell, KprStyle style); extern void KprContentShowing(void* it, Boolean showIt); extern void KprContentShown(void* it, Boolean showIt); extern void KprContentUpdate(void* it, FskPort port, FskRectangle area); struct KprContainerStruct { KprSlotPart; KprContentPart; KprContainerPart; }; FskAPI(FskErr) KprContainerNew(KprContainer *self, KprCoordinates coordinates, KprSkin skin, KprStyle style); FskAPI(void) KprContainerAdd(KprContainer self, KprContent content); FskAPI(KprContent) KprContainerContent(KprContainer self, SInt32 index); FskAPI(SInt32) KprContainerCount(KprContainer self); FskAPI(void) KprContainerEmpty(KprContainer self, SInt32 start, SInt32 stop); FskAPI(void) KprContainerInsert(KprContainer self, KprContent content, KprContent before); FskAPI(void) KprContainerRemove(KprContainer self, KprContent content); FskAPI(void) KprContainerReplace(KprContainer self, KprContent current, KprContent content); FskAPI(void) KprContainerSetTransition(KprContainer self, KprTransition transition); FskAPI(void) KprContainerSwap(KprContainer self, KprContent content0, KprContent content1); extern void KprContainerActivated(void* it, Boolean activateIt); extern void KprContainerAdded(void* it, KprContent content); extern void KprContainerCascade(void* it, KprStyle style); extern void KprContainerDispose(void* it); extern void KprContainerFitHorizontally(void* it); extern void KprContainerFitVertically(void* it); extern KprContent KprContainerHit(void* it, SInt32 x, SInt32 y); extern void KprContentIdle(void* it, double interval); extern void KprContainerLayered(void* it, KprLayer layer, Boolean layerIt); extern void KprContainerInvalidated(void* it, FskRectangle area) ; extern void KprContainerMark(void* it, xsMarkRoot markRoot); extern void KprContainerMeasureHorizontally(void* it); extern void KprContainerMeasureVertically(void* it); extern void KprContainerPlace(void* it); extern void KprContainerPlaced(void* it); extern void KprContainerPlaceHorizontally(void* it); extern void KprContainerPlaceVertically(void* it); extern void KprContainerPredict(void* it, FskRectangle area); extern void KprContainerRemoving(void* it, KprContent content); extern void KprContainerReflowing(void* it, UInt32 flags); extern void KprContainerSetWindow(void* it, KprShell shell, KprStyle style); extern void KprContainerShowing(void* it, Boolean showIt); extern void KprContainerShown(void* it, Boolean showIt); extern void KprContainerUpdate(void* it, FskPort port, FskRectangle area); struct KprLayoutStruct { KprSlotPart; KprContentPart; KprContainerPart; }; FskAPI(FskErr) KprLayoutNew(KprLayout *self, KprCoordinates coordinates, KprSkin skin, KprStyle style); extern FskErr KprContentChainAppend(KprContentChain chain, void* it, UInt32 size, KprContentLink *result); extern Boolean KprContentChainContains(KprContentChain chain, void* it); extern KprContentLink KprContentChainGetFirst(KprContentChain chain); extern KprContentLink KprContentChainGetNext(KprContentChain chain); extern Boolean KprContentChainIsEmpty(KprContentChain chain); extern FskErr KprContentChainPrepend(KprContentChain chain, void* it, UInt32 size, KprContentLink *result); extern FskErr KprContentChainRemove(KprContentChain chain, void* it); #define KprBounds(CONTENT) (&((CONTENT)->bounds)) #ifdef __cplusplus } #endif /* __cplusplus */ #endif
C
CL
a60e26b0396a1d589c0848d83ae66697d204128889b552be3c38ba835f41b9e6
/************************************************************************** ************************* Restricted access *************************** *************************************************************************** This file must only be used for the development of the HSUSB driver for the AMSS / BREW SW baselines using the Jungo USB Stack. This file must not be used in any way for the development of any functionally equivalent USB driver not using the Jungo USB stack. For any questions please contact: Sergio Kolor, Liron Manor, Yoram Rimoni, Dedy Lansky. ************************************************************************** ************************* Restricted access ************************** **************************************************************************/ /* Jungo Confidential, Copyright (c) 2008 Jungo Ltd. http://www.jungo.com */ /* * Copyright (c) 2004 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Lennart Augustsson ([email protected]) and by Charles M. Hannum. * * 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the NetBSD * Foundation, Inc. and its contributors. * 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef _DEV_PCI_EHCIREG_H_ #define _DEV_PCI_EHCIREG_H_ /*** PCI config registers ***/ #define PCI_CBMEM 0x10 /* configuration base MEM */ #define PCI_INTERFACE_EHCI 0x20 #define PCI_USBREV 0x60 /* RO USB protocol revision */ #define PCI_USBREV_MASK 0xff #define PCI_USBREV_PRE_1_0 0x00 #define PCI_USBREV_1_0 0x10 #define PCI_USBREV_1_1 0x11 #define PCI_USBREV_2_0 0x20 #define PCI_EHCI_FLADJ 0x61 /*RW Frame len adj, SOF=59488+6*fladj */ #define PCI_EHCI_PORTWAKECAP 0x62 /* RW Port wake caps (opt) */ /* EHCI Extended Capabilities */ #define EHCI_EC_LEGSUP 0x01 #define EHCI_EECP_NEXT(x) (((x) >> 8) & 0xff) #define EHCI_EECP_ID(x) ((x) & 0xff) /* Legacy support extended capability */ #define EHCI_LEGSUP_LEGSUP 0x01 #define EHCI_LEGSUP_OSOWNED 0x01000000UL /* OS owned semaphore */ #define EHCI_LEGSUP_BIOSOWNED 0x00010000UL /* BIOS owned semaphore */ #define EHCI_LEGSUP_USBLEGCTLSTS 0x04 /* Regs at EECP + offset */ #define PCI_EHCI_USBLEGSUP 0x00 #define EHCI_LEG_HC_OS_OWNED 0x01000000UL #define EHCI_LEG_HC_BIOS_OWNED 0x00010000UL #define PCI_EHCI_USBLEGCTLSTS 0x04 #define EHCI_CAP_GET_ID(cap) ((cap) & 0xff) #define EHCI_CAP_GET_NEXT(cap) (((cap) >> 8) & 0xff) #define EHCI_CAP_ID_LEGACY 1 /*** EHCI capability registers ***/ #define EHCI_CAPLENGTH 0x00 /*RO Capability register length field */ /* reserved 0x01 */ #define EHCI_HCIVERSION 0x02 /* RO Interface version number */ #define EHCI_HCSPARAMS 0x04 /* RO Structural parameters */ #define EHCI_HCS_DEBUGPORT(x) (((x) >> 20) & 0xf) #define EHCI_HCS_P_INDICATOR(x) ((x) & 0x10000) #define EHCI_HCS_N_CC(x) (((x) >> 12) & 0xf) /* # of companion ctlrs */ #define EHCI_HCS_N_PCC(x) (((x) >> 8) & 0xf) /* # of ports per comp. */ #define EHCI_HCS_PPC(x) ((x) & 0x10) /* port power control */ #define EHCI_HCS_N_PORTS(x) ((x) & 0xf) /* # of ports */ #define EHCI_HCCPARAMS 0x08 /* RO Capability parameters */ #define EHCI_HCC_EECP(x) (((x) >> 8) & 0xff) /* extended ports caps */ #define EHCI_HCC_IST(x) (((x) >> 4) & 0xf) /* isoc sched threshold */ #define EHCI_HCC_ASPC(x) ((x) & 0x4) /* async sched park cap */ #define EHCI_HCC_PFLF(x) ((x) & 0x2) /* prog frame list flag */ #define EHCI_HCC_64BIT(x) ((x) & 0x1) /* 64 bit address cap */ #define EHCI_HCSP_PORTROUTE 0x0c /*RO Companion port route description */ /* EHCI operational registers. Offset given by EHCI_CAPLENGTH register */ #define EHCI_USBCMD 0x00 /* RO, RW, WO Command register */ #define EHCI_CMD_ITC_M 0x00ff0000UL /* RW interrupt threshold ctrl */ #define EHCI_CMD_ITC_1 0x00010000UL #define EHCI_CMD_ITC_2 0x00020000UL #define EHCI_CMD_ITC_4 0x00040000UL #define EHCI_CMD_ITC_8 0x00080000UL #define EHCI_CMD_ITC_16 0x00100000UL #define EHCI_CMD_ITC_32 0x00200000UL #define EHCI_CMD_ITC_64 0x00400000UL #define EHCI_CMD_ASPME 0x00000800UL /* RW/RO async park enable */ #define EHCI_CMD_ASPMC 0x00000300UL /* RW/RO async park count */ #define EHCI_CMD_LHCR 0x00000080UL /* RW light host ctrl reset */ #define EHCI_CMD_IAAD 0x00000040UL /* RW intr on async adv door bell */ #define EHCI_CMD_ASE 0x00000020UL /* RW async sched enable */ #define EHCI_CMD_PSE 0x00000010UL /* RW periodic sched enable */ #define EHCI_CMD_FLS_M 0x0000000cUL /* RW/RO frame list size */ #define EHCI_CMD_FLS(x) (((x) >> 2) & 3) /* RW/RO frame list size */ #define EHCI_CMD_HCRESET 0x00000002UL /* RW reset */ #define EHCI_CMD_RS 0x00000001UL /* RW run/stop */ #define EHCI_USBSTS 0x04 /* RO, RW, RWC Status register */ #define EHCI_STS_ASS 0x00008000UL /* RO async sched status */ #define EHCI_STS_PSS 0x00004000UL /* RO periodic sched status */ #define EHCI_STS_REC 0x00002000UL /* RO reclamation */ #define EHCI_STS_HCH 0x00001000UL /* RO host controller halted */ #define EHCI_STS_IAA 0x00000020UL /* RWC interrupt on async adv */ #define EHCI_STS_HSE 0x00000010UL /* RWC host system error */ #define EHCI_STS_FLR 0x00000008UL /* RWC frame list rollover */ #define EHCI_STS_PCD 0x00000004UL /* RWC port change detect */ #define EHCI_STS_ERRINT 0x00000002UL /* RWC error interrupt */ #define EHCI_STS_INT 0x00000001UL /* RWC interrupt */ #define EHCI_STS_INTRS(x) ((x) & 0x3f) #define EHCI_NORMAL_INTRS (EHCI_STS_IAA | EHCI_STS_HSE | EHCI_STS_PCD | EHCI_STS_ERRINT | EHCI_STS_INT | EHCI_STS_FLR) #define EHCI_USBINTR 0x08 /* RW Interrupt register */ #define EHCI_INTR_IAAE 0x00000020UL /* interrupt on async advance ena */ #define EHCI_INTR_HSEE 0x00000010UL /* host system error ena */ #define EHCI_INTR_FLRE 0x00000008UL /* frame list rollover ena */ #define EHCI_INTR_PCIE 0x00000004UL /* port change ena */ #define EHCI_INTR_UEIE 0x00000002UL /* USB error intr ena */ #define EHCI_INTR_UIE 0x00000001UL /* USB intr ena */ #define EHCI_FRINDEX 0x0c /* RW Frame Index register */ #define EHCI_CTRLDSSEGMENT 0x10 /* RW Control Data Structure Segment */ #define EHCI_PERIODICLISTBASE 0x14 /* RW Periodic List Base */ #define EHCI_ASYNCLISTADDR 0x18 /* RW Async List Base */ #define EHCI_CONFIGFLAG 0x40 /* RW Configure Flag register */ #define EHCI_CONF_CF 0x00000001UL /* RW configure flag */ #define EHCI_PORTSC(n) (0x40+4*(n)) /* RO, RW, RWC Port Status reg */ #ifdef CONFIG_TDI_4X #define TDI_4X_PFSC 0x01000000 /* RW Port Force Full Speed Connect */ #define TDI_4X_PSPD 0x0C000000UL /* RO, Port speed*/ #define TDI_4X_IS_HISPD(x) (((x) & TDI_4X_PSPD) == 0x08000000UL) #define TDI_4X_IS_LOWSPD(x) (((x) & TDI_4X_PSPD) == 0x04000000UL) #define TDI_4X_IS_FULLSPD(x) (((x) & TDI_4X_PSPD) == 0x0UL) #endif #define EHCI_PS_WKOC_E 0x00400000UL /* RW wake on over current ena */ #define EHCI_PS_WKDSCNNT_E 0x00200000UL /* RW wake on disconnect ena */ #define EHCI_PS_WKCNNT_E 0x00100000UL /* RW wake on connect ena */ #define EHCI_PS_PTC 0x000f0000UL /* RW port test control */ #define EHCI_PS_TEST_J_STATE 0x00010000UL /* RW J-State test mode */ #define EHCI_PS_TEST_K_STATE 0x00020000UL /* RW K_State test mode */ #define EHCI_PS_TEST_SE0_NAK 0x00030000UL /* RW SE0_NAK test mode */ #define EHCI_PS_TEST_PACKET 0x00040000UL /* RW Packet test mode */ #define EHCI_PS_TEST_FORCE_ENABLE_HS 0x00050000UL /* RW Force Enable test mode */ #define EHCI_PS_PIC 0x0000c000UL /* RW port indicator control */ #define EHCI_PS_PO 0x00002000UL /* RW port owner */ #define EHCI_PS_PP 0x00001000UL /* RW,RO port power */ #define EHCI_PS_LS 0x00000c00UL /* RO line status */ #define EHCI_PS_IS_LOWSPEED(x) (((x) & EHCI_PS_LS) == 0x00000400UL) #define EHCI_PS_PR 0x00000100UL /* RW port reset */ #define EHCI_PS_SUSP 0x00000080UL /* RW suspend */ #define EHCI_PS_FPR 0x00000040UL /* RW force port resume */ #define EHCI_PS_OCC 0x00000020UL /* RWC over current change */ #define EHCI_PS_OCA 0x00000010UL /* RO over current active */ #define EHCI_PS_PEC 0x00000008UL /* RWC port enable change */ #define EHCI_PS_PE 0x00000004UL /* RW port enable */ #define EHCI_PS_CSC 0x00000002UL /* RWC connect status change */ #define EHCI_PS_CS 0x00000001UL /* RO connect status */ #define EHCI_PS_CLEAR (EHCI_PS_OCC|EHCI_PS_PEC|EHCI_PS_CSC) #ifdef CONFIG_TDI_4X #define TDI_4X_USBMODE 0x68 #define TDI_4X_USBMODE_DEVICE 0x2 #define TDI_4X_USBMODE_HOST 0x3 #define TDI_4X_USBMODE_BIGENDIAN 0x4 #define TDI_4X_USBMODE_SDIS_ACTIVE 0x10 #define TDI_4X_TTCTRL 0x1C #define TDI_4X_BURST_SIZE 0x20 #define TDI_4X_BURST_SIZE_QUIRK 0x00000404UL #endif #define EHCI_PORT_RESET_COMPLETE 2 /* ms */ #define EHCI_FLALIGN_ALIGN 0x1000UL #define EHCI_MAX_PORTS 16 /* only 4 bits available in EHCI_HCS_N_PORTS */ /* No data structure may cross a page boundary. */ #define EHCI_PAGE_SIZE 0x1000UL #define EHCI_PAGE(x) ((x) &~ 0xfff) #define EHCI_PAGE_OFFSET(x) ((x) & 0xfff) #define EHCI_PAGE_MASK(x) ((x) & 0xfff) typedef juint32_t ehci_link_t; #define EHCI_LINK_TERMINATE 0x00000001UL #define EHCI_LINK_TYPE(x) ((x) & 0x00000006UL) #define EHCI_LINK_ITD 0x0 #define EHCI_LINK_QH 0x2 #define EHCI_LINK_SITD 0x4 #define EHCI_LINK_FSTN 0x6 #define EHCI_LINK_ADDR(x) ((x) &~ 0x1fUL) typedef juint32_t ehci_physaddr_t; #define BSET(x, shift, mask) ((juint32_t)(x) << (shift)) #define BGET(x, shift, mask) (((juint32_t)(x) >> (shift)) & (mask)) #define BMASK(x, shift, mask) ((juint32_t)(mask) << (shift)) /* Isochronous Transfer Descriptor */ #define EHCI_ITD_NTRANS 8 #define EHCI_ITD_NBUFFERS 7 typedef struct { ehci_link_t itd_next; juint32_t itd_trans[EHCI_ITD_NTRANS]; #define EHCI_ITD_STATUS(gs, x) gs(x, 28, 0xf) #define EHCI_ITD_ACTIVE 0x08 #define EHCI_ITD_BUFERR 0x04 #define EHCI_ITD_BABBLE 0x02 #define EHCI_ITD_XACTERR 0x01 #define EHCI_ITD_LEN(gs, x) gs(x, 16, 0xfff) #define EHCI_ITD_IOC(gs, x) gs(x, 15, 0x1) #define EHCI_ITD_PG(gs, x) gs(x, 12, 0x7) #define EHCI_ITD_OFS(gs, x) gs(x, 0, 0xfff) juint32_t itd_buffer[EHCI_ITD_NBUFFERS]; #define EHCI_ITD_BUFP(gs, x) gs(x, 12, 0xfffffUL) #define EHCI_ITD_BUFP_0 0 #define EHCI_ITD_EPT(gs, x) gs(x, 8, 0xf) #define EHCI_ITD_DEVADDR(gs, x) gs(x, 0, 0x7f) #define EHCI_ITD_BUFP_1 1 #define EHCI_ITD_DIR(gs, x) gs(x, 11, 0x1) #define EHCI_ITD_OUT 0 #define EHCI_ITD_IN 1 #define EHCI_ITD_MAXPKT(gs, x) gs(x, 0, 0x7ff) #define EHCI_ITD_BUFP_2 2 #define EHCI_ITD_MULT(gs, x) gs(x, 0, 0x3) juint32_t itd_buffer_hi[EHCI_ITD_NBUFFERS]; } ehci_itd_t; #ifdef CONFIG_CX2417X #define EHCI_ITD_ALIGN 64 #else #define EHCI_ITD_ALIGN 32 #endif /* Split Transaction Isochronous Transfer Descriptor */ #define EHCI_SITD_NBUFFERS 2 typedef struct { ehci_link_t sitd_next; juint32_t sitd_addr; #define EHCI_SITD_DIR(gs, x) gs(x, 31, 0x01) #define EHCI_SITD_OUT 0 #define EHCI_SITD_IN 1 #define EHCI_SITD_PORTNUM(gs, x) gs(x, 24, 0x3f) #define EHCI_SITD_HUBADDR(gs, x) gs(x, 16, 0x3f) #define EHCI_SITD_EPT(gs, x) gs(x, 8, 0x0f) #define EHCI_SITD_DEVADDR(gs, x) gs(x, 0, 0x3f) juint32_t sitd_mask; #define EHCI_SITD_CMASK(gs, x) gs(x, 8, 0xff) #define EHCI_SITD_SMASK(gs, x) gs(x, 0, 0xff) juint32_t sitd_status; #define EHCI_SITD_IOC(gs, x) gs(x, 31, 0x1) #define EHCI_SITD_PG(gs, x) gs(x, 30, 0x1) #define EHCI_SITD_LEN(gs, x) gs(x, 16, 0x3ff) #define EHCI_SITD_CPROGMASK(gs, x) gs(x, 8, 0xff) #define EHCI_SITD_STATUS(gs, x) gs(x, 0, 0xff) #define EHCI_SITD_ACTIVE 0x80 #define EHCI_SITD_ERR 0x40 #define EHCI_SITD_BUFERR 0x20 #define EHCI_SITD_BABBLE 0x10 #define EHCI_SITD_XACTERR 0x08 #define EHCI_SITD_MISSEDUF 0x04 #define EHCI_SITD_COMPLETE 0x02 #define EHCI_SITD_START 0x00 juint32_t sitd_buffer[EHCI_SITD_NBUFFERS]; #define EHCI_SITD_BUFP(gs, x) gs(x, 12, 0xfffffUL) #define EHCI_SITD_BUFP_0 0 #define EHCI_SITD_OFS(gs, x) gs(x, 0, 0xfff) #define EHCI_SITD_BUFP_1 1 #define EHCI_SITD_TPOS(gs, x) gs(x, 3, 0x3) #define EHCI_SITD_TCOUNT(gs, x) gs(x, 0, 0x7) juint32_t sitd_back; juint32_t sitd_buffer_hi[EHCI_SITD_NBUFFERS]; } ehci_sitd_t; #define EHCI_SITD_ALIGN 32 /* Queue Element Transfer Descriptor */ #define EHCI_QTD_NBUFFERS 5 typedef struct { ehci_link_t qtd_next; ehci_link_t qtd_altnext; juint32_t qtd_status; #define EHCI_QTD_GET_STATUS(x) (((x) >> 0) & 0xff) #define EHCI_QTD_SET_STATUS(x) ((x) << 0) #define EHCI_QTD_ACTIVE 0x80UL #define EHCI_QTD_HALTED 0x40UL #define EHCI_QTD_BUFERR 0x20UL #define EHCI_QTD_BABBLE 0x10UL #define EHCI_QTD_XACTERR 0x08UL #define EHCI_QTD_MISSEDMICRO 0x04UL #define EHCI_QTD_SPLITXSTATE 0x02UL #define EHCI_QTD_PINGSTATE 0x01UL #define EHCI_QTD_STATERRS 0x3cUL #define EHCI_QTD_GET_PID(x) (((x) >> 8) & 0x3) #define EHCI_QTD_SET_PID(x) ((juint32_t)(x) << 8) #define EHCI_QTD_PID_OUT 0x0UL #define EHCI_QTD_PID_IN 0x1UL #define EHCI_QTD_PID_SETUP 0x2UL #define EHCI_QTD_GET_CERR(x) (((x) >> 10) & 0x3) #define EHCI_QTD_SET_CERR(x) ((juint32_t)(x) << 10) #define EHCI_QTD_GET_C_PAGE(x) (((x) >> 12) & 0x7) #define EHCI_QTD_SET_C_PAGE(x) ((juint32_t)(x) << 12) #define EHCI_QTD_GET_IOC(x) (((x) >> 15) & 0x1) #define EHCI_QTD_IOC 0x00008000UL #define EHCI_QTD_GET_BYTES(x) (((x) >> 16) & 0x7fff) #define EHCI_QTD_SET_BYTES(x) ((juint32_t)(x) << 16) #define EHCI_QTD_GET_TOGGLE(x) (((x) >> 31) & 0x1) #define EHCI_QTD_SET_TOGGLE(x) ((juint32_t)(x) << 31) #define EHCI_QTD_TOGGLE_MASK 0x80000000UL ehci_physaddr_t qtd_buffer[EHCI_QTD_NBUFFERS]; ehci_physaddr_t qtd_buffer_hi[EHCI_QTD_NBUFFERS]; } ehci_qtd_t; #define EHCI_QTD_ALIGN 32 /* Queue Head */ typedef struct { ehci_link_t qh_link; juint32_t qh_endp; #define EHCI_QH_GET_ADDR(x) (((x) >> 0) & 0x7f) /* endpoint addr */ #define EHCI_QH_SET_ADDR(x) (x) #define EHCI_QH_ADDRMASK 0x0000007fUL #define EHCI_QH_GET_INACT(x) (((x) >> 7) & 0x01) /* inactivate on next */ #define EHCI_QH_INACT 0x00000080UL #define EHCI_QH_GET_ENDPT(x) (((x) >> 8) & 0x0f) /* endpoint no */ #define EHCI_QH_SET_ENDPT(x) ((juint32_t)(x) << 8) #define EHCI_QH_GET_EPS(x) (((x) >> 12) & 0x03) /* endpoint speed */ #define EHCI_QH_SET_EPS(x) ((juint32_t)(x) << 12) #define EHCI_QH_SPEED_FULL 0x0 #define EHCI_QH_SPEED_LOW 0x1 #define EHCI_QH_SPEED_HIGH 0x2 #define EHCI_QH_GET_DTC(x) (((x) >> 14) & 0x01) /* data toggle control */ #define EHCI_QH_DTC 0x00004000UL #define EHCI_QH_GET_HRECL(x) (((x) >> 15) & 0x01) /* head of reclamation */ #define EHCI_QH_HRECL 0x00008000UL #define EHCI_QH_GET_MPL(x) (((x) >> 16) & 0x7ff) /* max packet len */ #define EHCI_QH_SET_MPL(x) ((juint32_t)(x) << 16) #define EHCI_QH_MPLMASK 0x07ff0000UL #define EHCI_QH_GET_CTL(x) (((x) >> 27) & 0x01) /* control endpoint */ #define EHCI_QH_CTL 0x08000000UL #define EHCI_QH_GET_NRL(x) (((x) >> 28) & 0x0f) /* NAK reload */ #define EHCI_QH_SET_NRL(x) ((juint32_t)(x) << 28) juint32_t qh_endphub; #define EHCI_QH_GET_SMASK(x) (((x) >> 0) & 0xff) /* intr sched mask */ #define EHCI_QH_SET_SMASK(x) ((juint32_t)(x) << 0) #define EHCI_QH_GET_CMASK(x) (((x) >> 8) & 0xff) /* split completion mask */ #define EHCI_QH_SET_CMASK(x) ((juint32_t)(x) << 8) #define EHCI_QH_GET_HUBA(x) (((x) >> 16) & 0x7f) /* hub address */ #define EHCI_QH_SET_HUBA(x) ((juint32_t)(x) << 16) #define EHCI_QH_GET_PORT(x) (((x) >> 23) & 0x7f) /* hub port */ #define EHCI_QH_SET_PORT(x) ((juint32_t)(x) << 23) #define EHCI_QH_GET_MULT(x) (((x) >> 30) & 0x03) /* pipe multiplier */ #define EHCI_QH_SET_MULT(x) ((juint32_t)(x) << 30) ehci_link_t qh_curqtd; ehci_qtd_t qh_qtd; } ehci_qh_t; #ifdef CONFIG_CX2417X #define EHCI_QH_ALIGN 64 #else #define EHCI_QH_ALIGN 32 #endif /* Periodic Frame Span Traversal Node */ typedef struct { ehci_link_t fstn_link; ehci_link_t fstn_back; } ehci_fstn_t; #define EHCI_FSTN_ALIGN 32 #define EHCI_OTG_PORT_NUM 1 #endif /* _DEV_PCI_EHCIREG_H_ */
C
CL
0f6025285a78fcec82a27160da46a15cd8deaa725679d40cc249588f7244165e
/** * \file timer.c * \brief Simple command-line timing utility. */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <oski/common.h> #include <oski/timer.h> static void usage (const char *progname) { fprintf (stderr, "%s [options] prog [prog_options ...]\n", progname); fprintf (stderr, "\n"); fprintf (stderr, "Similar to 'time' utility, but uses OSKI's timer.\n"); fprintf (stderr, "\n"); fprintf (stderr, "Valid [options]:\n"); fprintf (stderr, " --help\n Prints this message.\n"); fprintf (stderr, " --calibrate\n" " Print the ticks-to-seconds conversion factor.\n"); fprintf (stderr, "\n"); } int main (int argc, char *argv[]) { oski_timer_t timer; int i_arg = 1; char **new_args; int err; /* Process arguments */ while (i_arg < argc && argv[i_arg][0] == '-') { if (strcmp (argv[i_arg], "--calibrate") == 0) { double secs_per_tick = oski_GetTimerSecsPerTick (); printf ("%g\n", 1.0 / secs_per_tick); return 0; } else if (strcmp (argv[i_arg], "--help") == 0 || strcmp (argv[i_arg], "-h") == 0 || strcmp (argv[i_arg], "-H") == 0) { usage (argv[0]); return 0; } else { fprintf (stderr, "*** Unrecognized option, '%s' ***\n", argv[i_arg]); usage (argv[0]); return 1; } i_arg++; } if (i_arg >= argc) { usage (argv[0]); return 0; } /* Duplicate arguments */ if ((i_arg + 1) < argc) { new_args = oski_Malloc (char *, argc - i_arg + 1); if (new_args == NULL) { fprintf (stderr, "*** Out of memory ***\n"); return 1; } else { int i; new_args[0] = argv[i_arg]; for (i = 1; i <= argc - i_arg; i++) new_args[i] = argv[i_arg + i]; new_args[i] = NULL; for (i = 0; i < argc - i_arg + 1; i++) { fprintf (stderr, "[%d] '%s'\n", i, new_args[i]); } } } timer = oski_CreateTimer (); if (timer == NULL) { fprintf (stderr, "*** Couldn't create a timer. (?) ***\n"); return 1; } oski_RestartTimer (timer); err = execv (argv[i_arg], new_args); oski_StopTimer (timer); printf ("%g\n", oski_ReadElapsedTime (timer)); oski_Free (new_args); oski_DestroyTimer (timer); return err; } /* eof */
C
CL
cafe82a39617848c65a3f8602d8382cc766c1aecc9ba8479cc964cd1b315e8ce
#include "game_server.h" #define SERVER_CMD_HELLO_WORLD 0 #define SERVER_CMD_JOIN 1 #define SERVER_CMD_ACK 2 #define SERVER_CMD_UPDATE 3 #define CLIENT_CMD_WELCOME 0 #define CLIENT_CMD_SPAWN_OBJ 1 void cmd_hello_world(game_server_t *game_server, packet_t *packet); void cmd_join(game_server_t *game_server, packet_t *packet); void cmd_ack(game_server_t *game_server, packet_t *packet); void cmd_update(game_server_t *game_server, packet_t *packet); int main(int argc, char **argv) { game_server_t *server = game_server_new(9999, 10, 10, 10, 2.0); add_command(server, SERVER_CMD_HELLO_WORLD, cmd_hello_world); add_command(server, SERVER_CMD_JOIN, cmd_join); add_command(server, SERVER_CMD_ACK, cmd_ack); add_command(server, SERVER_CMD_UPDATE, cmd_update); for (;;) { game_server_run(server); } return 1; } void cmd_hello_world(game_server_t *game_server, packet_t *packet) { printf("HELLO WORLD!\n"); } void cmd_join(game_server_t *game_server, packet_t *packet) { game_client_t *new_client = game_client_new(packet->sender_adress); printf("adress %s has been created\n", inet_ntoa(new_client->adress.sin_addr)); game_client_t *bad_client = (game_client_t *)get_value(game_server->connected_clients, (void *)&new_client->adress.sin_addr, sizeof(new_client->adress.sin_addr)); if (bad_client != NULL) { bad_client->malus += 1; printf("Client already joined! Increased malus to: %d\n", bad_client->malus); free(new_client); } else { key_value_t *connected_client_kv = new_key_value((void *)&new_client->adress.sin_addr, (void *)new_client, sizeof(new_client->adress.sin_addr)); register_key_value(game_server->connected_clients, connected_client_kv); game_server->number_of_connected_clients += 1; game_object_t *avatar = game_object_new(game_server); //NOT SURE IF I SHOULD LET THE USER PUT THE ID //MANUALLY OR GIVE IT AUTOMATICALLY IN THE NEW avatar->owner = new_client; printf("here\n"); char data[sizeof(char) + sizeof(char) + sizeof(unsigned int) + (sizeof(float) * 3)]; data[0] = CLIENT_CMD_WELCOME; data[1] = 0; // useless memcpy(&data[2], &avatar->game_object_id, sizeof(unsigned int)); memcpy(&data[6], &avatar->x, sizeof(float)); memcpy(&data[10], &avatar->y, sizeof(float)); memcpy(&data[14], &avatar->z, sizeof(float)); unsigned int rec_id; float rec_x, rec_y, rec_z; memcpy(&rec_id, &data[2], sizeof(unsigned int)); memcpy(&rec_x, &data[6], sizeof(float)); memcpy(&rec_y, &data[10], sizeof(float)); memcpy(&rec_z, &data[14], sizeof(float)); printf("Created data buffer with the following data:\ndata 0 = %d, data 1 = %d, id = %u, x = %f, y = %f, z = %f\n", (char)data[0], (char)data[1], rec_id, rec_x, rec_y, rec_z); packet_t *welcome_pkt = packet_new(game_server, data, new_client->adress, sizeof(data)); welcome_pkt->need_ack = 1; enqueue(new_client->send_queue, welcome_pkt); key_value_t *current_game_object_kv = game_server->game_objects->first_entry; while (current_game_object_kv != NULL) { game_object_t *game_obj = current_game_object_kv->value; char data_to_spw_obj[sizeof(char) + (sizeof(unsigned int) * 2) + (sizeof(float) * 3)]; data[0] = CLIENT_CMD_SPAWN_OBJ; memcpy(&data_to_spw_obj[2], &game_obj->game_object_id, sizeof(unsigned int)); memcpy(&data_to_spw_obj[6], &game_obj->game_object_client_type, sizeof(unsigned int)); memcpy(&data_to_spw_obj[10], &game_obj->x, sizeof(float)); memcpy(&data_to_spw_obj[14], &game_obj->y, sizeof(float)); memcpy(&data_to_spw_obj[18], &game_obj->z, sizeof(float)); packet_t *spawn_pkt = packet_new(game_server, data_to_spw_obj, new_client->adress, sizeof(data_to_spw_obj)); spawn_pkt->need_ack = 1; enqueue(new_client->send_queue, spawn_pkt); current_game_object_kv = current_game_object_kv->next_dict_entry; } key_value_t *game_object_kv = new_key_value((void *)&avatar->game_object_id, avatar, sizeof(avatar->game_object_id)); register_key_value(game_server->game_objects, game_object_kv); key_value_t *current_connected_client_kv = game_server->connected_clients->first_entry; while (current_connected_client_kv != NULL) { if (memcmp((game_client_t *)current_connected_client_kv->value, new_client, sizeof(game_client_t))) { game_client_t *client_to_spawn_yourself = (game_client_t *)current_connected_client_kv->value; char data_to_spw_self[sizeof(char) + (sizeof(unsigned int) * 2) + (sizeof(float) * 3)]; data[0] = CLIENT_CMD_SPAWN_OBJ; memcpy(&data_to_spw_self[2], &avatar->game_object_id, sizeof(unsigned int)); memcpy(&data_to_spw_self[6], &avatar->game_object_client_type, sizeof(unsigned int)); memcpy(&data_to_spw_self[10], &avatar->x, sizeof(float)); memcpy(&data_to_spw_self[14], &avatar->y, sizeof(float)); memcpy(&data_to_spw_self[18], &avatar->z, sizeof(float)); packet_t *spawn_yourself_pkt = packet_new(game_server, data_to_spw_self, new_client->adress, sizeof(data_to_spw_self)); spawn_yourself_pkt->need_ack = 1; enqueue(client_to_spawn_yourself->send_queue, spawn_yourself_pkt); } current_connected_client_kv = current_connected_client_kv->next_dict_entry; } } } void cmd_ack(game_server_t *game_server, packet_t *packet) { IN_ADDR sender_adress = packet->sender_adress.sin_addr; game_client_t *retrieved_client = get_value(game_server->connected_clients, (void *)&sender_adress, sizeof(sender_adress)); if (retrieved_client != NULL) { if (get_key_value(retrieved_client->ack_table, (void *)&packet->data[1], sizeof(packet->data[1]))) { remove_key_value(retrieved_client->ack_table, (void *)&packet->data[1], sizeof(packet->data[1])); } } } void cmd_update(game_server_t *game_server, packet_t *packet) { IN_ADDR sender_adress = packet->sender_adress.sin_addr; game_client_t *retrieved_client = get_value(game_server->connected_clients, (void *)&sender_adress, sizeof(sender_adress)); if (retrieved_client != NULL) { printf("\n\n\nFOUND CLIENT\n"); unsigned int game_object_id = -1; memcpy(&game_object_id, &packet->data[2], sizeof(unsigned int)); game_object_t *retrieved_game_object = get_value(game_server->game_objects, (void *)&game_object_id, sizeof(unsigned int)); if (retrieved_game_object != NULL && !memcmp(retrieved_game_object->owner, retrieved_client, sizeof(game_client_t))) { printf("\nFOUND GAMEOBJECT: %d\n", game_object_id); float new_x, new_y, new_z; memcpy(&new_x, &packet->data[5], sizeof(float)); memcpy(&new_y, &packet->data[9], sizeof(float)); memcpy(&new_z, &packet->data[13], sizeof(float)); retrieved_game_object->x = new_x; retrieved_game_object->y = new_y; retrieved_game_object->z = new_z; } } }
C
CL
55c4e005b1a26a19f27a6b078c4bb079c70512f97bbdab337fcd8a6b3833d5a7
/*************************************************************************** Atari I, Robot hardware Games supported: * I, Robot Known issues: * none at this time **************************************************************************** I-Robot Memory Map 0000 - 07FF R/W RAM 0800 - 0FFF R/W Banked RAM 1000 - 1000 INRD1 Bit 7 = Right Coin Bit 6 = Left Coin Bit 5 = Aux Coin Bit 4 = Self Test Bit 3 = ? Bit 2 = ? Bit 1 = ? Bit 0 = ? 1040 - 1040 INRD2 Bit 7 = Start 1 Bit 6 = Start 2 Bit 5 = ? Bit 4 = Fire Bit 3 = ? Bit 2 = ? Bit 1 = ? Bit 0 = ? 1080 - 1080 STATRD Bit 7 = VBLANK Bit 6 = Polygon generator done Bit 5 = Mathbox done Bit 4 = Unused Bit 3 = ? Bit 2 = ? Bit 1 = ? Bit 0 = ? 10C0 - 10C0 INRD3 Dip switch 1140 - 1140 STATWR Bit 7 = Select Polygon RAM banks Bit 6 = BFCALL Bit 5 = Cocktail Flip Bit 4 = Start Mathbox Bit 3 = Connect processor bus to mathbox bus Bit 2 = Start polygon generator Bit 1 = Select polygon image RAM bank Bit 0 = Erase polygon image memory 1180 - 1180 OUT0 Bit 7 = Alpha Map 1 Bit 6,5 = RAM bank select Bit 4,3 = Mathbox memory select Bit 2,1 = Mathbox bank select 11C0 - 11C0 OUT1 Bit 7 = Coin Counter R Bit 6 = Coin Counter L Bit 5 = LED2 Bit 4 = LED1 Bit 3,2,1 = ROM bank select 1200 - 12FF R/W NVRAM (bits 0..3 only) 1300 - 13FF W Select analog controller 1300 - 13FF R Read analog controller 1400 - 143F R/W Quad Pokey 1800 - 18FF Palette RAM 1900 - 1900 W Watchdog reset 1A00 - 1A00 W FIREQ Enable 1B00 - 1BFF W Start analog controller ADC 1C00 - 1FFF R/W Character RAM 2000 - 3FFF R/W Mathbox/Vector Gen Shared RAM 4000 - 5FFF R Banked ROM 6000 - FFFF R Fixed ROM Notes: - There is no flip screen nor cocktail mode in the original game 02/2010 - Added XTAL values based on the parts listing the manual. The divisors for the cpus make sense, however, they are not verified. ****************************************************************************/ #include "emu.h" #include "cpu/m6809/m6809.h" #include "sound/pokey.h" #include "machine/nvram.h" #include "includes/irobot.h" #define MAIN_CLOCK XTAL_12_096MHz #define VIDEO_CLOCK XTAL_20MHz /************************************* * * NVRAM handler * *************************************/ static WRITE8_HANDLER( irobot_nvram_w ) { irobot_state *state = space->machine().driver_data<irobot_state>(); state->m_nvram[offset] = data & 0x0f; } /************************************* * * IRQ acknowledgement * *************************************/ static WRITE8_HANDLER( irobot_clearirq_w ) { cputag_set_input_line(space->machine(), "maincpu", M6809_IRQ_LINE ,CLEAR_LINE); } static WRITE8_HANDLER( irobot_clearfirq_w ) { cputag_set_input_line(space->machine(), "maincpu", M6809_FIRQ_LINE ,CLEAR_LINE); } /************************************* * * Main CPU memory handlers * *************************************/ static ADDRESS_MAP_START( irobot_map, AS_PROGRAM, 8 ) AM_RANGE(0x0000, 0x07ff) AM_RAM AM_RANGE(0x0800, 0x0fff) AM_RAMBANK("bank2") AM_RANGE(0x1000, 0x103f) AM_READ_PORT("IN0") AM_RANGE(0x1040, 0x1040) AM_READ_PORT("IN1") AM_RANGE(0x1080, 0x1080) AM_READ(irobot_status_r) AM_RANGE(0x10c0, 0x10c0) AM_READ_PORT("DSW1") AM_RANGE(0x1100, 0x1100) AM_WRITE(irobot_clearirq_w) AM_RANGE(0x1140, 0x1140) AM_WRITE(irobot_statwr_w) AM_RANGE(0x1180, 0x1180) AM_WRITE(irobot_out0_w) AM_RANGE(0x11c0, 0x11c0) AM_WRITE(irobot_rom_banksel_w) AM_RANGE(0x1200, 0x12ff) AM_RAM_WRITE(irobot_nvram_w) AM_SHARE("nvram") AM_RANGE(0x1300, 0x13ff) AM_READ(irobot_control_r) AM_RANGE(0x1400, 0x143f) AM_READWRITE(quad_pokey_r, quad_pokey_w) AM_RANGE(0x1800, 0x18ff) AM_WRITE(irobot_paletteram_w) AM_RANGE(0x1900, 0x19ff) AM_WRITEONLY /* Watchdog reset */ AM_RANGE(0x1a00, 0x1a00) AM_WRITE(irobot_clearfirq_w) AM_RANGE(0x1b00, 0x1bff) AM_WRITE(irobot_control_w) AM_RANGE(0x1c00, 0x1fff) AM_RAM AM_BASE_MEMBER(irobot_state, m_videoram) AM_RANGE(0x2000, 0x3fff) AM_READWRITE(irobot_sharedmem_r, irobot_sharedmem_w) AM_RANGE(0x4000, 0x5fff) AM_ROMBANK("bank1") AM_RANGE(0x6000, 0xffff) AM_ROM ADDRESS_MAP_END /************************************* * * Port definitions * *************************************/ static INPUT_PORTS_START( irobot ) PORT_START("IN0") /* IN0 */ PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_SERVICE( 0x10, IP_ACTIVE_LOW ) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_COIN3 ) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_COIN2 ) PORT_START("IN1") /* IN1 */ PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_START2 ) PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START1 ) PORT_START("IN2") /* IN2 */ PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_UNKNOWN ) /* MB DONE */ PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_UNKNOWN ) /* EXT DONE */ PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_VBLANK ) PORT_START("DSW2") /* DSW2 - 5E*/ PORT_DIPNAME( 0x01, 0x01, DEF_STR( Language ) ) PORT_DIPLOCATION("SW5E:1") PORT_DIPSETTING( 0x01, DEF_STR( English ) ) PORT_DIPSETTING( 0x00, DEF_STR( German ) ) // Printed Manual States Dip (0x01) adjusts Doodle City playtime: ON=2M10S / OFF=3M5S PORT_DIPNAME( 0x02, 0x02, "Minimum Game Time" ) PORT_DIPLOCATION("SW5E:2") PORT_DIPSETTING( 0x00, "90 Seconds on Level 1" ) PORT_DIPSETTING( 0x02, DEF_STR( None ) ) PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Bonus_Life ) ) PORT_DIPLOCATION("SW5E:3,4") PORT_DIPSETTING( 0x08, DEF_STR( None ) ) PORT_DIPSETTING( 0x0c, "20000" ) PORT_DIPSETTING( 0x00, "30000" ) PORT_DIPSETTING( 0x04, "50000" ) PORT_DIPNAME( 0x30, 0x30, DEF_STR( Lives ) ) PORT_DIPLOCATION("SW5E:5,6") PORT_DIPSETTING( 0x20, "2" ) PORT_DIPSETTING( 0x30, "3" ) PORT_DIPSETTING( 0x00, "4" ) PORT_DIPSETTING( 0x10, "5" ) PORT_DIPNAME( 0x40, 0x40, DEF_STR( Difficulty ) ) PORT_DIPLOCATION("SW5E:7") PORT_DIPSETTING( 0x00, DEF_STR( Easy ) ) PORT_DIPSETTING( 0x40, DEF_STR( Medium ) ) PORT_DIPNAME( 0x80, 0x80, "Demo Mode" ) PORT_DIPLOCATION("SW5E:8") PORT_DIPSETTING( 0x80, DEF_STR( Off ) ) PORT_DIPSETTING( 0x00, DEF_STR( On ) ) PORT_START("DSW1") /* DSW1 - 3J */ PORT_DIPNAME( 0x03, 0x00, "Coins Per Credit" ) PORT_DIPLOCATION("SW3J:!1,!2") PORT_DIPSETTING( 0x00, "1 Coin 1 Credit" ) PORT_DIPSETTING( 0x01, "2 Coins 1 Credit" ) PORT_DIPSETTING( 0x02, "3 Coins 1 Credit" ) PORT_DIPSETTING( 0x03, "4 Coins 1 Credit" ) PORT_DIPNAME( 0x0c, 0x00, "Right Coin" ) PORT_DIPLOCATION("SW3J:!3,!4") PORT_DIPSETTING( 0x00, "1 Coin for 1 Coin Unit" ) PORT_DIPSETTING( 0x04, "1 Coin for 4 Coin Units" ) PORT_DIPSETTING( 0x08, "1 Coin for 5 Coin Units" ) PORT_DIPSETTING( 0x0c, "1 Coin for 6 Coin Units" ) PORT_DIPNAME( 0x10, 0x00, "Left Coin" ) PORT_DIPLOCATION("SW3J:!5") PORT_DIPSETTING( 0x00, "1 Coin for 1 Coin Unit" ) PORT_DIPSETTING( 0x10, "1 Coin for 2 Coin Units" ) PORT_DIPNAME( 0xe0, 0x00, "Bonus Adder" ) PORT_DIPLOCATION("SW3J:!6,!7,!8") PORT_DIPSETTING( 0x00, DEF_STR( None ) ) PORT_DIPSETTING( 0x20, "1 Credit for 2 Coin Units" ) PORT_DIPSETTING( 0xa0, "1 Credit for 3 Coin Units" ) PORT_DIPSETTING( 0x40, "1 Credit for 4 Coin Units" ) PORT_DIPSETTING( 0x80, "1 Credit for 5 Coin Units" ) PORT_DIPSETTING( 0x60, "2 Credits for 4 Coin Units" ) PORT_DIPSETTING( 0xe0, DEF_STR( Free_Play ) ) PORT_START("AN0") /* IN4 */ PORT_BIT( 0xff, 0x80, IPT_AD_STICK_Y ) PORT_MINMAX(96,163) PORT_SENSITIVITY(70) PORT_KEYDELTA(50) PORT_START("AN1") /* IN5 */ PORT_BIT( 0xff, 0x80, IPT_AD_STICK_X ) PORT_MINMAX(96,159) PORT_SENSITIVITY(50) PORT_KEYDELTA(50) PORT_REVERSE INPUT_PORTS_END /************************************* * * Graphics definitions * *************************************/ static const gfx_layout charlayout = { 8,8, 64, 1, { 0 }, { 4, 5, 6, 7, 12, 13, 14, 15}, { 0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16}, 16*8 }; static GFXDECODE_START( irobot ) GFXDECODE_ENTRY( "gfx1", 0, charlayout, 64, 16 ) GFXDECODE_END /************************************* * * Sound interfaces * *************************************/ static const pokey_interface pokey_config = { { DEVCB_NULL }, DEVCB_INPUT_PORT("DSW2") }; /************************************* * * Machine driver * *************************************/ static MACHINE_CONFIG_START( irobot, irobot_state ) /* basic machine hardware */ MCFG_CPU_ADD("maincpu", M6809, MAIN_CLOCK/8) MCFG_CPU_PROGRAM_MAP(irobot_map) MCFG_MACHINE_RESET(irobot) MCFG_NVRAM_ADD_0FILL("nvram") /* video hardware */ MCFG_SCREEN_ADD("screen", RASTER) MCFG_SCREEN_REFRESH_RATE(60) MCFG_SCREEN_VBLANK_TIME(ATTOSECONDS_IN_USEC(2500) /* not accurate */) MCFG_SCREEN_FORMAT(BITMAP_FORMAT_INDEXED16) MCFG_SCREEN_SIZE(32*8, 32*8) MCFG_SCREEN_VISIBLE_AREA(0*8, 32*8-1, 0*8, 29*8-1) MCFG_SCREEN_UPDATE(irobot) MCFG_GFXDECODE(irobot) MCFG_PALETTE_LENGTH(64 + 32) /* 64 for polygons, 32 for text */ MCFG_PALETTE_INIT(irobot) MCFG_VIDEO_START(irobot) MCFG_TIMER_ADD("irvg_timer", irobot_irvg_done_callback) MCFG_TIMER_ADD("irmb_timer", irobot_irmb_done_callback) /* sound hardware */ MCFG_SPEAKER_STANDARD_MONO("mono") MCFG_SOUND_ADD("pokey1", POKEY, MAIN_CLOCK/8) MCFG_SOUND_CONFIG(pokey_config) MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 0.25) MCFG_SOUND_ADD("pokey2", POKEY, MAIN_CLOCK/8) MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 0.25) MCFG_SOUND_ADD("pokey3", POKEY, MAIN_CLOCK/8) MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 0.25) MCFG_SOUND_ADD("pokey4", POKEY, MAIN_CLOCK/8) MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 0.25) MACHINE_CONFIG_END /************************************* * * ROM definitions * *************************************/ ROM_START( irobot ) ROM_REGION( 0x20000, "maincpu", 0 ) /* 64k for code + 48K Banked ROM*/ ROM_LOAD( "136029-208.bin", 0x06000, 0x2000, CRC(b4d0be59) SHA1(5b476dbee8b171a96301b2204420161333d4ca97) ) ROM_LOAD( "136029-209.bin", 0x08000, 0x4000, CRC(f6be3cd0) SHA1(a88ae0cc9ee22aa5dd3db0173f24313189f894f8) ) ROM_LOAD( "136029-210.bin", 0x0c000, 0x4000, CRC(c0eb2133) SHA1(daa77293678b7e822d0672b90789c53098c5451e) ) ROM_LOAD( "136029-405.bin", 0x10000, 0x4000, CRC(9163efe4) SHA1(5d71d8ec80c9be4726189d48ad519b4638160d64) ) ROM_LOAD( "136029-206.bin", 0x14000, 0x4000, CRC(e114a526) SHA1(bd94ad4d536f681efa81153050a12098a31d79cf) ) ROM_LOAD( "136029-207.bin", 0x18000, 0x4000, CRC(b4556cb0) SHA1(2e0c1e4c265e7d232ca86d5c8760e32fc49fe08d) ) ROM_REGION16_BE( 0x10000, "mathbox", 0 ) /* mathbox region */ ROM_LOAD16_BYTE( "136029-104.bin", 0x0000, 0x2000, CRC(0a6cdcca) SHA1(b9fd76eae8ca24fa3abc30c46bbf30d89943d97d) ) ROM_LOAD16_BYTE( "136029-103.bin", 0x0001, 0x2000, CRC(0c83296d) SHA1(c1f4041a58f395e24855254849604dfe3b8b0d71) ) /* ROM data from 0000-bfff */ ROM_LOAD16_BYTE( "136029-102.bin", 0x4000, 0x4000, CRC(9d588f22) SHA1(787ec3e642e1dc3417477348afa88c764e1f2a88) ) ROM_LOAD16_BYTE( "136029-101.bin", 0x4001, 0x4000, CRC(62a38c08) SHA1(868bb3fe5657a4ce45c3dd04ba26a7fb5a5ded42) ) /* RAM data from c000-dfff */ /* COMRAM from e000-ffff */ ROM_REGION( 0x800, "gfx1", 0 ) ROM_LOAD( "136029-124.bin", 0x0000, 0x0800, CRC(848948b6) SHA1(743c6570c787bc9a2a14716adc66b8e2fe57129f) ) ROM_REGION( 0x3420, "proms", 0 ) ROM_LOAD( "136029-125.bin", 0x0000, 0x0020, CRC(446335ba) SHA1(5b42cc065bfac467028ae883844c8f94465c3666) ) ROM_LOAD( "136029-111.bin", 0x0020, 0x0400, CRC(9fbc9bf3) SHA1(33dee2382e1e3899ffbaea859a67af7334270b4a) ) /* program ROMs from c000-f3ff */ ROM_LOAD( "136029-112.bin", 0x0420, 0x0400, CRC(b2713214) SHA1(4e1ea039e7a3e341796097b0c6943a4805b89f56) ) ROM_LOAD( "136029-113.bin", 0x0820, 0x0400, CRC(7875930a) SHA1(63a3818450a76d230a75f038b140c3934659313e) ) ROM_LOAD( "136029-114.bin", 0x0c20, 0x0400, CRC(51d29666) SHA1(34887df0f1ac064b4cf4252a225406e8b30872c6) ) ROM_LOAD( "136029-115.bin", 0x1020, 0x0400, CRC(00f9b304) SHA1(46b4495002ddf80668a66a4f85cab99432677b50) ) ROM_LOAD( "136029-116.bin", 0x1420, 0x0400, CRC(326aba54) SHA1(e4caab90910b3aa16c314909f8c02eaf212449a1) ) ROM_LOAD( "136029-117.bin", 0x1820, 0x0400, CRC(98efe8d0) SHA1(39532fc1b14714396764500a9b1c9e4fed97a970) ) ROM_LOAD( "136029-118.bin", 0x1c20, 0x0400, CRC(4a6aa7f9) SHA1(163e8e764b400d726c725b6a45901c311e62667e) ) ROM_LOAD( "136029-119.bin", 0x2020, 0x0400, CRC(a5a13ad8) SHA1(964a87c879c953563ca84f8e3c1201302c7b2b91) ) ROM_LOAD( "136029-120.bin", 0x2420, 0x0400, CRC(2a083465) SHA1(35ca23d5bbdc2827afb823a974864b96eb135797) ) ROM_LOAD( "136029-121.bin", 0x2820, 0x0400, CRC(adebcb99) SHA1(4628f8af43d82e578833b1452ec747eeb822b4e4) ) ROM_LOAD( "136029-122.bin", 0x2c20, 0x0400, CRC(da7b6f79) SHA1(02398ba6e7c56d961bf92e2755e530db1144219d) ) ROM_LOAD( "136029-123.bin", 0x3020, 0x0400, CRC(39fff18f) SHA1(85f338eeff7d8ed58804611bf8446ebb697d196d) ) ROM_END /* Colorprom from John's driver. ? */ /* ROM_LOAD( "136029.125", 0x0000, 0x0020, CRC(c05abf82) ) */ /************************************* * * Game drivers * *************************************/ GAME( 1983, irobot, 0, irobot, irobot, irobot, ROT0, "Atari", "I, Robot", 0 )
C
CL
ddb53765583f37ac0bc77801d1d4fad057b2d497dfc146f0047a81dbe60cf1e8
/***********************************************************/ /*Constants */ /***********************************************************/ #define ISENSOR_SLOPE_DUT 0.998 //2.8292 //3.484 //slope of the current sensor in [A/V] #define Y_INTERCEPT_DUT -2.491 //-5.862 //-5.244 //sensor voltage at 0 current #define NUM_HALF_CYCLES 4 //set the number of ticks over which to measure speed #define WAIT_BEFORE_SPEEDSTOP 7.5 //amount of time to wait before declaring that the motor is not moving. 7.5s corresponds to a speed of 1 rev/min #define R1 22000 //voltage measurement resistor connected to device under measurement [Ohm] #define R2 100000 //voltage measurement resistor connected to ground [Ohm] /***********************************************************/ /*Variables */ /***********************************************************/ float end, begin, current_read, current_read_cap ; int current_state; int count = 0; Timer speed_timer; /***********************************************************/ /*Pin setup */ /***********************************************************/ //Encoder DigitalIn speed_yellow(p6); //Connected to the cathode of TLP424-4 whose o/p(pin 14-collector) is connected to the Yellow Wire from the motor(Hall sensor o/p) /***********************************************************/ /*Subroutines */ /***********************************************************/ //get the voltage for one of the energy storage devices. Takes pin as a parameter float get_voltage (AnalogIn& pin) { float voltage; voltage = pin.read();//*3.3*((R1+R2)/R2); //scaling to account for voltage divider return voltage; } //returns current in amps #ifdef CURRENT_SENSOR_ON void get_current() { current_read = current_sense.read(); //read raw AnalogIn value of current current = ISENSOR_SLOPE_DUT * current_read * 3.3 + Y_INTERCEPT_DUT; //scaling to get DUT current in A current_read_cap = current_sense_cap.read(); //read raw AnalogIn value of current current_cap = ISENSOR_SLOPE_DUT * current_read_cap * 3.3 + Y_INTERCEPT_DUT; //scaling to get DUT current in A } #endif //returns speed in rad/sec void get_speed() { current_state = speed_yellow; //get the current state of speed_yellow pin (0 or 1) speed_timer.start(); while (speed_yellow == current_state && speed_timer <= WAIT_BEFORE_SPEEDSTOP) {} //wait for value of the speed_yellow to change, indicating the beginning of a new cycle if (speed_timer < WAIT_BEFORE_SPEEDSTOP) { //check that the timer is less than WAIT_BEFORE_SPEEDSTOP, to make sure it has not been running for too long. This will happen if speed = 0 speed_timer.reset(); //reset the timer so that it starts timing from the beginning of the new cycle begin = speed_timer.read(); for (int i = 1; i <= NUM_HALF_CYCLES; i++) { //loop to allow timing over a set number of encoder cycles current_state = speed_yellow; while (speed_yellow == current_state && speed_timer <= WAIT_BEFORE_SPEEDSTOP) {}//wait for speed_yellow pin to change. If it does not change, the loop will exit when speed_timer = WAIT_BEFORE_SPEEDSTOP } if (speed_timer < WAIT_BEFORE_SPEEDSTOP) { end = speed_timer.read(); //time at the end of timing NUM_HALF_CYCLES cycles speed_timer.stop(); speed =((60.0/16)*NUM_HALF_CYCLES)/(end-begin); //record speed in rev/min } else { speed = 0; //speed = 0 if the timer has exceeded WAIT_BEFORE_SPEEDSTOP } } else { speed = 0; //speed = 0 if the timer has exceeded WAIT_BEFORE_SPEEDSTOP } }
C
CL
f835e5047ce45cf6fd6ae93f4ec18b1e22d1ecf3f524b4eba13efb0be16f0ee0
/* * Project name: OLED B Click (SPI) * Copyright: (c) mikroElektronika, 2014. * Revision History: 20140918: - Initial release (BD); * Description: OLED B click carries a 96 x 39px blue monochrome passive matrix OLED display. The display is bright, has a wide viewing angle and low power consumption. To drive the display, OLED B click features an SSD1306 controller. It's built-in functionalities include contrast control, normal or inverse image display, vertical and horizontal scrolling functions and more. OLED B click can communicate with the target board MCU either through SPI or I2C mikroBUS lines. You switch between output options by resoldering the onboard SEL COMM jumpers (J1, J2 and J3) to the appropriate position. OLED B click uses a 3.3V power supply. Description of some terms: OLED M - OLED Monochrome module, OLED B - OLED Blue, OLED W - OLED White, OLED C - OLED Color Test configuration: MCU: P32MX795F512L http://ww1.microchip.com/downloads/en/DeviceDoc/61156F.pdf Dev.Board: EasyPIC Fusion v7 http://www.mikroe.com/easypic-fusion/ Oscillator: XT-PLL, 80.000MHz ext. modules: OLED B click http://www.mikroe.com/click/oled-b/ SW: mikroC PRO for PIC32 http://www.mikroe.com/mikroc/pic32/ NOTES: - Place OLED B Click board in the mikroBUS socket 1. - This code example is for SPI protocol. Set SEL COMM jumpers (J1, J2 and J3) to the appropriate position for SPI. */ //#include "Oled_M.h" #include "SSD1306.h" #include "Oled_font.h" #include <lib/type.h> #include <exosite_api.h> #include "display_ctrl.h" uint8_t buffer[96 * 64 / 8]; int myTextAlignment = TEXT_ALIGN_LEFT; int myColor = WHITE; unsigned char lastChar; const char *myFontData = Droid_Serif_Plain_10; //ArialMT_Plain_10; extern DISPLAY_CTRL_DATA display_ctrlData; unsigned char pic[] = { 0xFF, 0xFF, 0x3F, 0x1F, 0x0F, 0x07, 0x07, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x83, 0xC3, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0xE3, 0xE3, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x83, 0xC3, 0xE3, 0x63, 0x63, 0x63, 0x63, 0x63, 0xE3, 0xE3, 0x03, 0x03, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0xE3, 0xE3, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0xE3, 0xE3, 0x03, 0x03, 0x03, 0x83, 0xC3, 0xE3, 0x63, 0x63, 0x63, 0x63, 0xC3, 0xC3, 0x83, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x07, 0x07, 0x0F, 0x1F, 0x3F, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF3, 0xFF, 0x8C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0xFF, 0xC1, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x3E, 0xFF, 0xC1, 0x80, 0x00, 0x00, 0x00, 0x00, 0x80, 0xC1, 0xFF, 0x3E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x81, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x03, 0x03, 0x03, 0x03, 0x03, 0x83, 0x83, 0x03, 0x00, 0x80, 0x83, 0x03, 0x03, 0xC3, 0xC3, 0xC3, 0x83, 0x03, 0x03, 0x03, 0x00, 0x00, 0x83, 0xC3, 0xC3, 0xC3, 0x03, 0x03, 0x03, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x03, 0x03, 0x03, 0x03, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0xFF, 0xFF, 0x00, 0x00, 0xF0, 0xF8, 0x1C, 0x0C, 0x0C, 0x1C, 0xF8, 0xF0, 0x00, 0x0C, 0x0C, 0x18, 0xFC, 0xFC, 0x00, 0x00, 0x04, 0x8C, 0xF8, 0x70, 0xE0, 0xFF, 0xFF, 0x00, 0x00, 0xFD, 0xFD, 0x00, 0x00, 0xFF, 0xFF, 0x03, 0x1F, 0xFC, 0xC0, 0x00, 0xC0, 0xFC, 0x1F, 0x03, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x3C, 0xF0, 0xC0, 0x00, 0xC0, 0xF0, 0x3C, 0x0C, 0x00, 0xF0, 0xF8, 0x1C, 0x0C, 0x0C, 0x18, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFE, 0xF8, 0xF0, 0xE0, 0xC0, 0xC0, 0x80, 0x80, 0x80, 0x86, 0x86, 0x86, 0x86, 0x86, 0x86, 0x86, 0x87, 0x87, 0x80, 0x80, 0x81, 0x83, 0x87, 0x86, 0x86, 0x87, 0x83, 0x81, 0x80, 0x80, 0x80, 0x80, 0x87, 0x87, 0x80, 0x80, 0x86, 0x87, 0x81, 0x80, 0x80, 0x87, 0x87, 0x80, 0x80, 0x87, 0x87, 0x80, 0x80, 0x87, 0x87, 0x80, 0x80, 0x81, 0x87, 0x86, 0x87, 0x81, 0x80, 0x80, 0x87, 0x87, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x81, 0x87, 0x9F, 0xBF, 0xB1, 0xB0, 0x80, 0x80, 0x81, 0x83, 0x87, 0x86, 0x86, 0x83, 0x87, 0x87, 0x80, 0x80, 0x80, 0xC0, 0xC0, 0xE0, 0xF0, 0xF8, 0xFE, 0xFF }; int getStringWidth(unsigned char * text) { int value; value = (int)(*(myFontData+WIDTH_POS)) * (int)strlen((const char *) text); return value; } void OLED_M_data(unsigned char value); void OLED_M_command(unsigned char value); void Set_Page_Address(unsigned char add); void setFont (const char * font) { myFontData = (const char*) font; } void SSD1306_display(void) { unsigned char i, j; for (i = 0; i < 0x08; i++) { Set_Page_Address(i); // Set_Column_Address(0x00); OLED_M_command(0x10); OLED_M_command(0x40); for (j = 0; j < 0x60; j++) { OLED_M_data(buffer[i * 0x60 + (0x5f-j)]); } } // OLED_M_command(COLUMNADDR); // OLED_M_command(0x0); // OLED_M_command(0x0); //// OLED_M_command(0x7F); // // OLED_M_command(PAGEADDR); // OLED_M_command(0x0); // OLED_M_command(0x0); //// OLED_M_command(0x7); // uint16_t i; // for ( i=0; i<(96*39/8); i++) { // // send a bunch of data in one xmission // uint8_t x; // for ( x=0; x<16; x++) { // OLED_M_data(buffer[i]); // i++; // } // i--; // // } // } void SSD1306_setPixel(int x, int y) { if (x >= 0 && x < 96 && y >= 0 && y < 64) { switch (myColor) { case WHITE: buffer[x + (y/8)*96] |= (1 << (y&7)); break; case BLACK: buffer[x + (y/8)*96] &= ~(1 << (y&7)); break; case INVERSE: buffer[x + (y/8)*96] ^= (1 << (y&7)); break; } } } void SSD1306_clearPixel(int x, int y) { if (x >= 0 && x < 96 && y >= 0 && y < 64) { switch (myColor) { case WHITE: buffer[x + (y/8)*96] &= ~(1 << (y&7)); break; case BLACK: buffer[x + (y/8)*96] |= (1 << (y&7)); break; case INVERSE: buffer[x + (y/8)*96] ^= (1 << (y&7)); break; } } } unsigned char currentByte; unsigned int charX, charY; unsigned int currentBitCount; unsigned int charCode; unsigned int currentCharWidth; unsigned int currentCharStartPos; unsigned int cursorX = 0; unsigned char numberOfChars; // iterate over string //int firstChar = *(myFontData + FIRST_CHAR_POS); unsigned char charHeight ; unsigned int currentCharByteNum = 0; unsigned int startX; unsigned int startY; void SSD1306_drawString(int x, int y, unsigned char * text) { //text = utf8ascii(text); //myFontData = ArialMT_Plain_10; numberOfChars = *(myFontData + CHAR_NUM_POS); charHeight = *(myFontData + HEIGHT_POS); startX = 0; startY = y; cursorX = 0; if (myTextAlignment == TEXT_ALIGN_LEFT) { startX = x; } else if (myTextAlignment == TEXT_ALIGN_CENTER) { int width = getStringWidth(text); startX = x - width / 2; } else if (myTextAlignment == TEXT_ALIGN_RIGHT) { int width = getStringWidth(text); startX = x - width; } unsigned int j; unsigned int lenght; lenght = strlen((const char *)text); for ( j=0; j < lenght; j++) { charCode = *(text+j)-0x20; currentCharWidth = *(myFontData + CHAR_WIDTH_START_POS + charCode); // Jump to font data beginning currentCharStartPos = CHAR_WIDTH_START_POS + numberOfChars; unsigned int m; for ( m = 0; m < charCode; m++) { currentCharStartPos += *(myFontData + CHAR_WIDTH_START_POS + m) * charHeight / 8 + 1; } currentCharByteNum = ((charHeight * currentCharWidth) / 8) + 1; // iterate over all bytes of character unsigned int i; for ( i = 0; i < currentCharByteNum; i++) { currentByte = *(myFontData + currentCharStartPos + i); //Serial.println(String(charCode) + ", " + String(currentCharWidth) + ", " + String(currentByte)); // iterate over all bytes of character unsigned int bite; for( bite = 0; bite < 8; bite++) { //int currentBit = bitRead(currentByte, bit); currentBitCount = i * 8 + bite; charX = currentBitCount % currentCharWidth; charY = currentBitCount / currentCharWidth; if (currentByte & (1<<bite)) { SSD1306_setPixel(startX + cursorX + charX, startY + charY); }else{ SSD1306_clearPixel(startX + cursorX + charX, startY + charY); } } //Lucyield(); } cursorX += currentCharWidth; } SSD1306_display(); } void InitMCU() { // Init MCU function // SPI config } void Delay_ms(unsigned int delay) { system_sleep_ms(delay); /* unsigned int i; for (i = 0; i <= delay*10000; i++); */ } void SPI3_Write(unsigned char value, unsigned char num_of_bytes) { /* Add the buffer to transmit */ display_ctrlData.drvSPIWRBUFHandle = DRV_SPI_BufferAddWrite(display_ctrlData.drvSPIHandle, (SPI_DATA_TYPE *) & value, num_of_bytes, 0, 0); while (!(DRV_SPI_BUFFER_EVENT_COMPLETE & DRV_SPI_BufferStatus(display_ctrlData.drvSPIWRBUFHandle))); } //Send command to OLED m display void OLED_M_command(unsigned char value) { OLED_CS(0); OLED_DC(0); SPI3_Write(value, 1); OLED_CS(1); } //Send data to OLED m display void OLED_M_data(unsigned char value) { OLED_CS(0); OLED_DC(1); SPI3_Write(value, 1); OLED_CS(1); } void OLED_M_Init() { OLED_RST(0); Delay_ms(1000); OLED_RST(1); Delay_ms(1000); OLED_M_command(SSD1306_DISPLAYOFF); //0xAE Set OLED Display Off OLED_M_command(SSD1306_SETDISPLAYCLOCKDIV); //0xD5 Set Display Clock Divide Ratio/Oscillator Frequency OLED_M_command(0x80); OLED_M_command(SSD1306_SETMULTIPLEX); //0xA8 Set Multiplex Ratio OLED_M_command(0x27); OLED_M_command(SSD1306_SETDISPLAYOFFSET); //0xD3 Set Display Offset OLED_M_command(0x00); OLED_M_command(SSD1306_SETSTARTLINE); //0x40 Set Display Start Line OLED_M_command(SSD1306_CHARGEPUMP); //0x8D Set Charge Pump OLED_M_command(0x14); //0x14 Enable Charge Pump // OLED_M_command(SSD1306_SETSTARTLINE | 0x0); //A0 OLED_M_command(SSD1306_COMSCANDEC); //0xC8 Set COM Output Scan Direction OLED_M_command(SSD1306_SETCOMPINS); //0xDA Set COM Pins Hardware Configuration OLED_M_command(0x12); OLED_M_command(SSD1306_SETCONTRAST); //0x81 Set Contrast Control OLED_M_command(0xAF); OLED_M_command(SSD1306_SETPRECHARGE); //0xD9 Set Pre-Charge Period OLED_M_command(0x25); OLED_M_command(SSD1306_SETVCOMDETECT); //0xDB Set VCOMH Deselect Level OLED_M_command(0x20); OLED_M_command(SSD1306_DISPLAYALLON_RESUME); //0xA4 Set Entire Display On/Off OLED_M_command(SSD1306_NORMALDISPLAY); //0xA6 Set Normal/Inverse Display OLED_M_command(SSD1306_DISPLAYON); //0xAF Set OLED Display On } //Set page adress for Page Addressing Mode void Set_Page_Address(unsigned char add) { add = 0xb0 | add; OLED_M_command(add); } //Set column adress for Page Addressing Mode void Set_Column_Address(unsigned char add) { OLED_M_command((0x10 | (add >> 4))); OLED_M_command((0x0f & add)); } //Display picture for Page Addressing Mode void Display_Picture(unsigned char pic[]) { unsigned char i, j; for (i = 0; i < 0x05; i++) { Set_Page_Address(i); // Set_Column_Address(0x00); OLED_M_command(0x10); OLED_M_command(0x40); for (j = 0x0; j < 0x60; j++) { OLED_M_data(pic[i * 0x60 + j]); } } } //Set contrast control void contrast_control(unsigned char temp) { OLED_M_command(SSD1306_SETCONTRAST); //0x81 Set Contrast Control OLED_M_command(temp); // contrast step 1 to 256 } void startscroll_Right(unsigned char x, unsigned char y) { OLED_M_command(SSD1306_RIGHT_HORIZONTAL_SCROLL); //0x26 Right Horizontal scroll OLED_M_command(0X00); //dummy byte OLED_M_command(x); //define start page address OLED_M_command(0X00); //Set time interval between each scroll OLED_M_command(y); //Define end page address OLED_M_command(0X00); //dummy byte OLED_M_command(0XFF); //dummy byte OLED_M_command(SSD1306_ACTIVATE_SCROLL); } void startscroll_Left(unsigned char x, unsigned char y) { OLED_M_command(SSD1306_LEFT_HORIZONTAL_SCROLL); //0x27 Right Horizontal scroll OLED_M_command(0X00); //dummy byte OLED_M_command(x); //define start page address OLED_M_command(0X00); //Set time interval between each scroll OLED_M_command(y); //Define end page address OLED_M_command(0X00); //dummy byte OLED_M_command(0XFF); //dummy byte OLED_M_command(SSD1306_ACTIVATE_SCROLL); //0x2F Activate scroll } void startscroll_DiagRight(unsigned char x, unsigned char y) { OLED_M_command(SSD1306_SET_VERTICAL_SCROLL_AREA); //0xA3 Set Vertical Scroll Area OLED_M_command(0X00); //Set No. of rows in top fixed area OLED_M_command(SSD1306_LCDHEIGHT); //Set No. of rows in scroll area OLED_M_command(SSD1306_VERTICAL_AND_RIGHT_HORIZONTAL_SCROLL); //0x29 Vertical and Right Horizontal Scroll OLED_M_command(0X00); //dummy byte OLED_M_command(x); //Define start page address OLED_M_command(0X00); //Set time interval between each scroll OLED_M_command(y); //Define end page address OLED_M_command(0X01); //Vertical scrolling offset OLED_M_command(SSD1306_ACTIVATE_SCROLL); //0x2F Activate scroll } void startscroll_DiagLeft(unsigned char x, unsigned char y) { OLED_M_command(SSD1306_SET_VERTICAL_SCROLL_AREA); //0xA3 Set Vertical Scroll Area OLED_M_command(0X00); //Set No. of rows in top fixed area OLED_M_command(SSD1306_LCDHEIGHT); //Set No. of rows in scroll area OLED_M_command(SSD1306_VERTICAL_AND_LEFT_HORIZONTAL_SCROLL); //0x2A Vertical and Right Horizontal Scroll OLED_M_command(0X00); //dummy byte OLED_M_command(x); //Define start page address OLED_M_command(0X00); //Set time interval between each scroll OLED_M_command(y); //Define end page address OLED_M_command(0X01); //Vertical scrolling offset OLED_M_command(SSD1306_ACTIVATE_SCROLL); //2F Activate scroll } void scroll_STOP() { OLED_M_command(0x2E); //0x2E deactivate scroll } unsigned char once = 0; void SSD1306_clearLine(unsigned char line) { unsigned char str[50]; setFont(Droid_Serif_Plain_10); sprintf (( char *)str," "); SSD1306_drawString (0,line,(unsigned char *)str); } void OLED_DisplayBanner() { int i = 0x00; SSD1306_display(); setFont(Droid_Serif_Bold_Bold_14); SSD1306_drawString (5,0,(unsigned char *)"Microchip"); // unsigned char str[20],val=0; // // setFont(Droid_Serif_Plain_10); // sprintf (( char *)str,"Allo %x",val++); // SSD1306_drawString (0,LINE1,(unsigned char *)str); // // //sprintf (( char *)str,"Allo %x",val++); // //SSD1306_drawString (0,LINE2,(unsigned char *)str); // // // // for (val = 10; val <=0; val--) // { // sprintf (( char *)str,"Allo %d",val); // SSD1306_drawString (0,LINE1,(unsigned char *)str); // Delay_ms(2000); // // } // // sprintf (( char *)str," "); // SSD1306_drawString (0,LINE1,(unsigned char *)str); while (1) { Display_Picture(pic); Delay_ms(2000); OLED_M_command(SSD1306_INVERTDISPLAY); Delay_ms(2000); OLED_M_command(SSD1306_NORMALDISPLAY); Delay_ms(2000); return; for (i = 0xAF; i > 0x00; i--) { contrast_control(i); Delay_ms(20); } for (i = 0x00; i < 0xAF; i++) { contrast_control(i); Delay_ms(20); } startscroll_Right(0x00, 0x05); Delay_ms(3000); scroll_STOP(); Display_Picture(pic); startscroll_Left(0x00, 0x05); Delay_ms(3000); scroll_STOP(); Display_Picture(pic); startscroll_DiagRight(0x00, 0x05); Delay_ms(3000); scroll_STOP(); Display_Picture(pic); startscroll_DiagLeft(0x00, 0x05); Delay_ms(3000); scroll_STOP(); return; } }
C
CL
0d4475b27f47e0aac4de975e40e48a3dcf89650dc34bbbd764adbf4fa3e7b31b
/* * Copyright (C) 2008-2014 Chelsio Communications. All rights reserved. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the LICENSE file included in * this release for licensing terms and conditions. * * Description: This file implements the FCOE management interface function. * */ #include <csio_defs.h> #include <csio_hw.h> #include <csio_mgmt.h> #include <csio_lnode.h> #include <csio_rnode.h> /* * csio_mgmt_req_lookup - Lookup the given IO req exist in Active Q. * mgmt - mgmt module * @io_req - io request * * Return - CSIO_SUCCESS:if given IO Req exists in active Q. * CSIO_INVAL :if lookup fails. */ enum csio_oss_error csio_mgmt_req_lookup(struct csio_mgmtm *mgmtm, struct csio_ioreq *io_req) { struct csio_list *tmp; /* Lookup ioreq in the ACTIVEQ */ csio_list_for_each(tmp, &mgmtm->active_q) { if(io_req == (struct csio_ioreq *) tmp) { return CSIO_SUCCESS; } } return CSIO_INVAL; } /* * csio_mgmts_tmo_handler - MGMT IO Timeout handler. * @data - Event data. * * Return - none. */ static void csio_mgmt_tmo_handler(uintptr_t data) { struct csio_mgmtm *mgmtm = (struct csio_mgmtm *) data; struct csio_list *tmp; struct csio_ioreq *io_req; /* io request */ csio_dbg(mgmtm->hw, "Mgmt timer invoked!\n"); csio_spin_lock_irq(mgmtm->hw, &mgmtm->hw->lock); csio_list_for_each(tmp, &mgmtm->active_q) { io_req = (struct csio_ioreq *) tmp; io_req->tmo -= CSIO_MIN(io_req->tmo, ECM_MIN_TMO); if(!io_req->tmo) { /* Dequeue the request from retry Q. */ tmp = csio_list_prev(tmp); csio_deq_elem(io_req); if(io_req->io_cbfn) { /* io_req will be freed by completion handler */ io_req->wr_status = CSIO_TIMEOUT; io_req->io_cbfn(mgmtm->hw, io_req); } else { CSIO_DB_ASSERT(0); } } } /* If retry queue is not empty, re-arm timer */ if(!csio_list_empty(&mgmtm->active_q)) csio_timer_start(&mgmtm->mgmt_timer, ECM_MIN_TMO); csio_spin_unlock_irq(mgmtm->hw, &mgmtm->hw->lock); return; } /* * csio_map_fw_retval - Maps FW retval into driver retval. * * Returns: driver retval value. */ csio_retval_t csio_map_fw_retval(uint8_t fw_ret) { switch(fw_ret) { case FW_SUCCESS: return CSIO_SUCCESS; case FW_EPERM: return CSIO_NOPERM; case FW_EINVAL: return CSIO_INVAL; case FW_EIO: return CSIO_EIO; case FW_EAGAIN: return CSIO_RETRY; case FW_ENOMEM: return CSIO_NOMEM; case FW_EBUSY: return CSIO_BUSY; case FW_ENOSYS: return CSIO_NOSUPP; case FW_EPROTO: return CSIO_EPROTO; default : return CSIO_INVAL; } } void csio_mgmtm_cleanup(struct csio_mgmtm *mgmtm) { struct csio_hw *hw = mgmtm->hw; struct csio_ioreq *io_req; struct csio_list *tmp; uint32_t count; count = 30; /* Wait for all outstanding req to complete gracefully */ while ((!csio_list_empty(&mgmtm->active_q)) && count--) { csio_spin_unlock_irq(hw, &hw->lock); csio_msleep(2000); csio_spin_lock_irq(hw, &hw->lock); } /* release outstanding req from ACTIVEQ */ csio_list_for_each(tmp, &mgmtm->active_q) { io_req = (struct csio_ioreq *) tmp; tmp = csio_list_prev(tmp); csio_deq_elem(io_req); mgmtm->stats.n_active--; if (io_req->io_cbfn) { /* io_req will be freed by completion handler */ io_req->wr_status = CSIO_TIMEOUT; io_req->io_cbfn(mgmtm->hw, io_req); } } } /* * csio_mgmt_init - Mgmt module init entry point * @mgmtsm - mgmt module * @hw - HW module * * Initialize mgmt timer, resource wait queue, active queue, * completion q. Allocate Egress and Ingress * WR queues and save off the queue index returned by the WR * module for future use. Allocate and save off mgmt reqs in the * mgmt_req_freelist for future use. Make sure their SM is initialized * to uninit state. * Returns: CSIO_SUCCESS - on success * CSIO_NOMEM - on error. */ csio_retval_t csio_mgmtm_init(struct csio_mgmtm *mgmtm, struct csio_hw *hw) { csio_head_init(&mgmtm->active_q); csio_head_init(&mgmtm->cbfn_q); csio_timer_init(&mgmtm->mgmt_timer, csio_mgmt_tmo_handler,(void *)mgmtm); mgmtm->hw = hw; /*mgmtm->iq_idx = hw->fwevt_iq_idx;*/ csio_dbg(hw, "MGMT module init done\n"); return CSIO_SUCCESS; } /* * csio_mgmtm_exit - MGMT module exit entry point * @mgmtsm - mgmt module * * This function called during MGMT module uninit. * Stop timers, free ioreqs allocated. * Returns: None * */ void csio_mgmtm_exit(struct csio_mgmtm *mgmtm) { #if 0 struct csio_ioreq *io_req; struct csio_list *tmp; /* release outstanding req from cbfnQ */ csio_list_for_each(tmp, &mgmtm->cbfn_q) { io_req = (struct csio_ioreq *) tmp; tmp = csio_list_prev(tmp); csio_deq_elem(io_req); if(io_req->io_cbfn) { /* io_req will be freed by completion handler */ io_req->wr_status = CSIO_TIMEOUT; io_req->io_cbfn(mgmtm->hw, io_req); } } #endif csio_timer_stop(&mgmtm->mgmt_timer); csio_dbg(mgmtm->hw, "MGMT module exit done\n"); return; }
C
CL
e3f60410cfda858d8fc430c30a2dddc53f3e6f7fe044ac13eab8a7d8f186306b
/* * Copyright 2011 Ben Matthews <[email protected]> * * 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <termios.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <arpa/inet.h> //for endianness conversion function #include "libroomba.h" struct termios old_settings; int roomba_init(char* device) { int port_fd; char buf; /* Setup the Port.. Roomba Discovery starts at 57600/8n1 */ struct termios t = { .c_cflag = B57600 | CS8 | CLOCAL | CREAD, .c_iflag = IGNPAR | IGNBRK | ICRNL, .c_oflag = 0, .c_lflag = 0, .c_cc[VMIN] = 26, /* At most 26 char's expected from roomba */ .c_cc[VTIME] = 5, /*Wait 1/2 a second for read */ }; port_fd = open(device, O_RDWR | O_NOCTTY); if(port_fd == 0) { printf("Error opening port\n"); return 0; } tcgetattr(port_fd,&old_settings); /* Backup Old Settings for later */ tcflush(port_fd,TCIOFLUSH); tcsetattr(port_fd,TCSANOW,&t); buf = 128; write(port_fd,&buf,1); /* Start SCI */ buf = 130; write(port_fd,&buf,1); /* Enable Serial Control */ tcflush(port_fd,TCIOFLUSH); current_speed = 0; return(port_fd); } int roomba_safe(int roomba_fd) { char cmd = 131; if(write(roomba_fd,&cmd,1) == 1) return(roomba_fd); printf("Error Writing to Roomba\n"); tcflush(roomba_fd,TCIOFLUSH); return(0); } int roomba_full(int roomba_fd) { char cmd = 132; if(write(roomba_fd,&cmd,1) == 1) return(roomba_fd); printf("Error Writing to Roomba\n"); tcflush(roomba_fd,TCIOFLUSH); return(0); } int roomba_off(int roomba_fd) { char cmd=133; if(write(roomba_fd,&cmd,1) == 1) return(roomba_fd); printf("Error Writing to Roomba\n"); tcflush(roomba_fd,TCIOFLUSH); return(0); } int roomba_play_song(int roomba_fd,char song) { char cmd[2]; cmd[0] = 141; cmd[1] = song; if(write(roomba_fd,&cmd,2) == 2) return(roomba_fd); printf("Error Writing to Roomba\n"); tcflush(roomba_fd,TCIOFLUSH); return(0); } int roomba_define_song(int roomba_fd,char song, char song_data[][2], char length) { if(length>16 || length < 1) { printf("Song not a valid length\n"); return(0); } if(song < 0 || song > 15) { printf("Invalid Song\n"); return(0); } char* cmd_str = malloc(sizeof(char)*length*2+3); int i,j; int k = 0; cmd_str[0] = 140; cmd_str[1] = song; cmd_str[2] = length; for(i=0;i<length;i++) { for(j=0;j<2;j++) { cmd_str[k] = song_data[i][j]; k++; /* song_data[i][0] == note (see SCI Spec P.5) */ /* song_data[i][1] == note length (in 1/64" 0<x<255) */ } } write(roomba_fd,cmd_str,(length*2)+3); tcflush(roomba_fd,TCIOFLUSH); free(cmd_str); return(roomba_fd); } int roomba_free(int roomba_fd) { tcflush(roomba_fd,TCIOFLUSH); tcsetattr(roomba_fd,TCSANOW,&old_settings); close(roomba_fd); return(0); } int roomba_set_motors(int roomba_fd,char motor_status) { char cmd[2]; cmd[0]=138; cmd[1]=motor_status; write(roomba_fd,cmd,2); tcflush(roomba_fd,TCIOFLUSH); return(roomba_fd); } int roomba_drive(int roomba_fd, int16_t speed, int16_t radius) { /* Waste the first 8bits to get the alignment right */ union drivecmd { uint8_t cmdstr[6]; uint16_t cmdints[3]; } cmd; cmd.cmdstr[0] = 0; cmd.cmdstr[1] = 137; cmd.cmdints[1] = htons((uint16_t)speed); cmd.cmdints[2] = htons((uint16_t)radius); write(roomba_fd,(cmd.cmdstr+1),5); tcflush(roomba_fd,TCIOFLUSH); current_speed = speed; return(roomba_fd); } int roomba_ramp(int roomba_fd, int16_t speed, int16_t radius, int16_t increment) { int16_t i; i=current_speed; while(i!=speed) { if(current_speed>speed) { i-=increment; if(i>speed)i=speed; } if(current_speed<speed) { i+=increment; if(i<speed)i=speed; } if(roomba_drive(roomba_fd,i,radius) == 0) { printf("Error Setting Drive Speed\n"); return(0); } usleep(RAMP_DELAY); } return(roomba_drive(roomba_fd,i,radius)); } int roomba_force_seeking_dock(int roomba_fd) { char cmd = 143; if(write(roomba_fd,&cmd,1) != 1) return(0); tcflush(roomba_fd,TCIOFLUSH); return(roomba_fd); } int roomba_read_sensor_data(int roomba_fd, struct roomba_sensor_data* data) { char cmd[2] = {142,0}; char reply[26]; if(write(roomba_fd,cmd,2) != 2) { perror("Error Requesting Sensor Data"); return(0); } tcflush(roomba_fd,TCIOFLUSH); if(read(roomba_fd,reply,26) != 26) { perror("Error Getting Sensor Data"); return(0); } #ifdef STRUCT_JUST_WORKS memcpy(data,reply,26); return(roomba_fd); #else data->bumps_wheeldrops = reply[0]; data->wall = reply[1]; data->cliff_left = reply[2]; data->cliff_front_left = reply[3]; data->cliff_front_right = reply[4]; data->cliff_right = reply[5]; data->virtual_wall = reply[6]; data->motor_overcurrent = reply[7]; data->dirt_detector_left = reply[8]; data->dirt_detector_right = reply[9]; data->remote_opcode = reply[10]; data->buttons = reply[11]; data->distance = (int16_t) (0 | reply[12] << 8) | reply[13]; data->angle = (int16_t) (0 | reply[14] << 8) | reply[15]; data->charging_state = reply[16]; data->voltage = (uint16_t) 0 |(reply[17] << 8) | reply[18]; data->current = (int16_t) 0 | (reply[19] << 8) | reply[20]; data->temperature = reply[21]; data->charge = (uint16_t) 0 | (reply[22] << 8) | reply[23]; data->capacity = (uint16_t) 0 | (reply[24] << 8) | reply[25]; return(roomba_fd); #endif } int roomba_set_leds(int roomba_fd,struct roomba_led_status* data, uint8_t power_color, uint8_t power_intensity) { char cmd[4] = {139,0,0,0}; if(data->dirt_detect) cmd[1] |= 0x01; if(data->max) cmd[1] |= 0x02; if(data->clean) cmd[1] |= 0x04; if(data->spot) cmd[1] |= 0x08; if(data->status_red) cmd[1] |= 0x10; if(data->status_red) cmd[1] |= 0x20; cmd[2] = power_color; cmd[3] = power_intensity; if(write(roomba_fd,cmd,4) != 4) perror("Error Writing LED Byte"); return(roomba_fd); }
C
CL
bdec65d9729a88907adeb39a7c1bed4140766ef9e481d4aaac4298e67be139d5
#ifndef PS_PPP_SNOOP_H #define PS_PPP_SNOOP_H /*=========================================================================== P S _ P P P _ S N O O P . H DESCRIPTION The Data Services Snoop Header File. Contains shared variables and enums, as well as declarations for functions. Copyright (c) 1998-2011 QUALCOMM Technologies Incorporated. All Rights Reserved. Qualcomm Confidential and Proprietary ===========================================================================*/ /*=========================================================================== EDIT HISTORY FOR FILE $PVCSPath: L:/src/asw/MM_DATA/vcs/ps_ppp_snoop.h_v 1.2 13 Feb 2003 14:12:46 ubabbar $ $Header: //source/qcom/qct/modem/datamodem/protocols/api/main/latest/ps_ppp_snoop.h#2 $ $DateTime: 2011/04/05 13:14:02 $ $Author: opatel $ when who what, where, why -------- --- ---------------------------------------------------------- 03/23/11 op Data SU API cleanup 05/07/09 pp CMI Phase-4: SU Level API Effort. 09/12/08 pp Metainfo optimizations. 10/14/04 ifk Added meta info ** argument to snoop callback function 02/11/03 usb Added SNOOP_CB_FORWARD_PKT to snoop_cb_ret_val_enum_type to indicate that pkt should be forwarded to bridged dev 02/02/03 usb Changed return value of snoop_proto_msg_detect() from boolean to snoop_cb_ret_val_enum_type. 07/25/02 mvl removed netmodel dependency. Updates for PPP renaming. 05/23/02 mvl Renamed iface_stack_type. 11/07/01 vr added FEATURE_DS_MOBILE_IP wrapper 11/05/01 vr added function snoop_is_registration_pkt for increasing laptop throughput during re-registration 10/27/99 mvl Code review updates: general cleanup. 08/31/98 na/mvl Created module. ===========================================================================*/ /*=========================================================================== INCLUDE FILES FOR MODULE ===========================================================================*/ #include "comdef.h" #include "ps_ppp_defs.h" #include "dsm.h" #include "ps_rx_meta_info.h" /*=========================================================================== REGIONAL DATA DECLARATIONS ===========================================================================*/ #define SNOOP_ANY_MSG 0 /* snoop all messages of a protocol */ #define PPP_PROTO_SIZ 2 /* Size of PPP protocol field */ #define PPP_ACF_PROTO_SIZ 4 /* Proto field without Addr & Ctl compres */ /*--------------------------------------------------------------------------- Type that is used as the return value for all the snooping callback functions. It is used to determine what action needs to be taken on the return from that function. ---------------------------------------------------------------------------*/ typedef enum { SNOOP_CB_IGNORE_PKT, /* packet processing complete, ignore it */ SNOOP_CB_SNOOP_AGAIN, /* call snoop callback again */ SNOOP_CB_PROCESS_PKT, /* send pkt up the stack for further processing */ SNOOP_CB_FORWARD_PKT /* forward pkt to the bridged PPP device */ } snoop_cb_ret_val_enum_type; /*--------------------------------------------------------------------------- This is the type declaration for all of the callback functions that are registered for snooping. ---------------------------------------------------------------------------*/ typedef snoop_cb_ret_val_enum_type (*snoop_cb_f_ptr_type)(ppp_dev_enum_type iface, uint16 protocol, dsm_item_type ** item_head_ptr, ps_rx_meta_info_type ** meta_info_ref_ptr); /*= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = PUBLIC FUNCTION DECLARATIONS = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =*/ /*=========================================================================== FUNCTION SNOOP_REG_EVENT() DESCRIPTION This function stores a function pointer that will be used as a callback when a particular PPP protocol and message are seen. DEPENDENCIES None RETURN VALUE A 32bit opaque identifier that can be used to unregister the function that has been registered. SIDE EFFECTS If this function is called for a protocol and message combination that already has a function call associated with it, it will remove the old function and replace it with the new function that is being added. ===========================================================================*/ uint32 snoop_reg_event ( ppp_dev_enum_type iface, /* the stack the registration is for */ uint16 protocol, /* the protocol the registration is for */ byte msg_type, /* the message the registration is for */ snoop_cb_f_ptr_type f_ptr /* the callback funtion being registered */ ); /*=========================================================================== FUNCTION SNOOP_UNREG_EVENT() DESCRIPTION This function removes a particular callback function from the snoop registration data structure. This stops it from being called when its associated protocol and message are found. DEPENDENCIES None RETURN VALUE None SIDE EFFECTS None ===========================================================================*/ void snoop_unreg_event ( uint32 reg_tag /* the xparent reg tag returned by snoop_reg_event */ ); #endif /* PS_PPP_SNOOP_H */
C
CL
86b8052224ef6d3a4577607e60c34c662f0d4e77a67bc43c17300da7046808fe
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ DYNAMIC LINKING LIBRARY Copyright(c) 1997-2002 BNSoft Corp. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ #ifndef _BNSOFT__PROCMNGR_H_ #define _BNSOFT__PROCMNGR_H_ #include "../ProcMngr.h" typedef H_PROCESS (*T_pfnProcMngr_FindHandle) (H_PROCESS hBase, E_PROCFIND enFind); typedef BOOL (*T_pfnProcMngr_MoveHandle) (H_PROCESS hProc, H_PROCESS hAfter); typedef T_NUM (*T_pfnProcMngr_GetNum) (H_PROCESS hBase, E_PROCTYPE enType); typedef QUAD (*T_pfnProcMngr_GetInfo) (H_PROCESS hProc, E_PROCINFO enProcInfo); typedef BOOL (*T_pfnProcMngr_IsAscendant) (H_PROCESS hBase, H_PROCESS hProc); typedef BOOL (*T_pfnProcMngr_IsDescendant) (H_PROCESS hBase, H_PROCESS hProc); typedef H_PROCESS (*T_pfnProcMngr_SearchApp) (T_CSTR rcszAppName); typedef BOOL (*T_pfnProcMngr_SetTimer) (H_PROCESS hProc, T_ID ID, QUAD Duration, BOOL bRepeat, E_PROCSTATUS enStatus); typedef BOOL (*T_pfnProcMngr_KillTimer) (T_ID ID); typedef struct { T_pfnProcMngr_FindHandle pfnFindHandle; T_pfnProcMngr_MoveHandle pfnMoveHandle; T_pfnProcMngr_GetNum pfnGetNum; T_pfnProcMngr_GetInfo pfnGetInfo; T_pfnProcMngr_IsAscendant pfnIsAscendant; T_pfnProcMngr_IsDescendant pfnIsDescendant; T_pfnProcMngr_SearchApp pfnSearchApp; T_pfnProcMngr_SetTimer pfnSetTimer; T_pfnProcMngr_KillTimer pfnKillTimer; } TApiGrp_ProcMngr; //------------------------------------------------------------------------------------------------- #define ProcMngr_FindHandle(p1,p2) __ApiLink2(ProcMngr,FindHandle,p1,p2) #define ProcMngr_MoveHandle(p1,p2) __ApiLink2(ProcMngr,MoveHandle,p1,p2) #define ProcMngr_GetNum(p1,p2) __ApiLink2(ProcMngr,GetNum,p1,p2) #define ProcMngr_GetInfo(p1,p2) __ApiLink2(ProcMngr,GetInfo,p1,p2) #define ProcMngr_IsAscendant(p1,p2) __ApiLink2(ProcMngr,IsAscendant,p1,p2) #define ProcMgr_IsDescendant(p1,p2) __ApiLink2(ProcMngr,IsDescendant,p1,p2) #define ProcMngr_SearchApp(p1) __ApiLink1(ProcMngr,SearchApp,p1) #define ProcMngr_SetTimer(p1,p2,p3,p4,p5) __ApiLink5(ProcMngr,SetTimer,p1,p2,p3,p4,p5) #define ProcMngr_KillTimer(p1) __ApiLink1(ProcMngr,KillTimer,p1) #endif // _BNSOFT__PROCMNGR_H_
C
CL
3b3d4f50d99de1e9e7587b416358b9df38db6d3eb42a75f6330e7f0a073234bc
/* Copyright (c) 2018 Evan Wyatt * 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. */ #include <server.h> #include <logging.h> #include <acct.h> #include <json.h> #include <ctype.h> #include <glob.h> int jobToJSON(struct job *j, buff_t *buf); int queueToJSON(struct queue *q, buff_t *buf); int resourceToJSON(struct resource *r, buff_t *buf); acctClient *acctClientList = NULL; static void acctMain(acctClient *a); void addAcctClient(acctClient *a) { if (acctClientList) { a->next = acctClientList; a->next->prev = a; } acctClientList = a; } void removeAcctClient(acctClient *a) { if (a->next) a->next->prev = a->prev; if (a->prev) a->prev->next = a->next; if (a == acctClientList) acctClientList = a->next; } int handleAcctClientConnection(struct connectionType * conn) { acctClient *a = NULL; int acct_fd = _accept(conn->socket); if (acct_fd < 0) { print_msg(JERS_LOG_INFO, "accept() failed on accounting connection: %s", strerror(errno)); return 1; } a = calloc(sizeof(acctClient), 1); if (!a) { error_die("Failed to malloc memory for client: %s\n", strerror(errno)); } /* Get the client UID off the socket */ struct ucred creds; socklen_t len = sizeof(struct ucred); if (getsockopt(acct_fd, SOL_SOCKET, SO_PEERCRED, &creds, &len) == -1) { print_msg(JERS_LOG_WARNING, "Failed to get peercred from accounting connection: %s", strerror(errno)); print_msg(JERS_LOG_WARNING, "Closing connection to accounting client"); close(acct_fd); free(a); return 1; } a->uid = creds.uid; a->connection.type = ACCT_CLIENT; a->connection.ptr = a; a->connection.socket = acct_fd; addAcctClient(a); /* Fork off to handle this stream * This is done to have a consistent view of the jobs * We also save our current position in the journal so * that we can start streaming of that location */ print_msg(JERS_LOG_INFO, "Starting accounting stream client for fd:%d uid:%d", a->connection.socket, a->uid); pid_t pid = fork(); if (pid == -1) { print_msg(JERS_LOG_WARNING, "Failed to fork for accounting stream client: %s", strerror(errno)); close(acct_fd); free(a); return 1; } if (pid != 0) { /* Parent, just return. We will check on this child periodically */ a->pid = pid; return 0; } /* Child does not return */ acctMain(a); exit(1); } /* Handle read activity on a client socket */ static int handleAcctClientRead(acctClient *a) { int len = 0; buffResize(&a->request, 0); len = _recv(a->connection.socket, a->request.data + a->request.used, a->request.size - a->request.used); if (len < 0) { if ((errno == EAGAIN || errno == EWOULDBLOCK)) return 0; print_msg(JERS_LOG_WARNING, "failed to read from accounting client: %s\n", strerror(errno)); return 1; } else if (len == 0) { /* Disconnected */ print_msg(JERS_LOG_WARNING, "Accounting stream client disconnected\n"); return 1; } /* Got some data from the client. * Update the buffer and length in the * reader, so we can try to parse this request */ a->request.used += len; return 0; } static int handleAcctClientWrite(acctClient * a) { int len = 0; len = _send(a->connection.socket, a->response.data + a->response_sent, a->response.used - a->response_sent); if (len == -1) { print_msg(JERS_LOG_WARNING, "send to accounting client failed: %s", strerror(errno)); return 1; } a->response_sent += len; /* If we have sent all our data, remove EPOLLOUT * from the event. Leave readable on, as we might read another request * from the client, or process their disconnect */ if (a->response_sent == a->response.used) { pollSetReadable(&a->connection); a->response_sent = a->response.used = 0; } return 0; } /* Convert all jobs/queues/resources to JSON messages and send them to the client */ static int sendInitial(acctClient *a) { for(struct queue *q = server.queueTable; q; q = q->hh.next) queueToJSON(q, &a->response); for(struct resource *r = server.resTable; r; r = r->hh.next) resourceToJSON(r, &a->response); for(struct job *j = server.jobTable; j; j = j->hh.next) jobToJSON(j, &a->response); /* Send a 'stream-start' message */ buff_t b; buffNew(&b, 0); JSONStart(&b); JSONStartObject(&b, "STREAM_START", 12); asprintf(&a->id, "%s:%ld", server.journal.datetime, server.journal.record); JSONAddString(&b, ACCT_ID, a->id); JSONEndObject(&b); JSONEnd(&b); buffAddBuff(&a->response, &b); buffFree(&b); pollSetWritable(&a->connection); return 0; } /* Locate to 'id' */ int locateJournal(acctClient *a, char *id) { print_msg_debug("LOCATING Journal to : %s\n", id); /* Break up and validate the id */ char *sep = strchr(id, ':'); if (sep == NULL) return 1; *sep = '\0'; sep++; if (strlen(id) > 8) //YYYYMMDD return 1; strcpy(a->datetime, id); while(*id) { if (!isdigit(*id)) return 1; id++; } a->record = atol(sep); char journal[PATH_MAX]; sprintf(journal, "%s/journal.%s", server.state_dir, a->datetime); a->journal = fopen(journal, "rb"); if (a->journal == NULL) error_die("Failed to open journal file '%s': %s", journal, strerror(errno)); /* Now locate to the requested record */ char *record = NULL; size_t record_size = 0; ssize_t record_len = 0; off_t current = 0; while ((record_len = getline(&record, &record_size, a->journal)) != -1) { if (*record == '\0') break; if (++current == a->record) break; } free(record); return 0; } static int processRequest(acctClient *a, const char *cmd) { print_msg(JERS_LOG_DEBUG, "Got accounting stream cmd: %s\n", cmd); if (strncasecmp(cmd, "START", 5) == 0) { /* The START command might have an additional parameter */ if (strlen(cmd) > 6) { /* They have provided an ID to use in an acknowledged stream * We need to save this and the journal positions of what we sent them */ a->id = strdup(cmd + 6); if (a->id == NULL) { print_msg(JERS_LOG_WARNING, "Failed to allocate ID string for accounting client: %s", strerror(errno)); return 1; } if (*a->id == '\0') { print_msg(JERS_LOG_WARNING, "No/Invalid ID sent in stream start: %s", cmd); return 1; } /* Locate onto the provided position */ locateJournal(a, a->id); } else { if (a->initalised == 0) { /* Need to send them the current list of jobs/queue/resources */ sendInitial(a); a->initalised = 1; asprintf(&a->id, "%s:%ld", server.journal.datetime, server.journal.record); locateJournal(a, a->id); } } a->state = ACCT_STARTED; } else if (strcasecmp(cmd, "STOP") == 0) { a->state = ACCT_STOPPED; } else { print_msg(JERS_LOG_WARNING, "Unknown command sent from accounting stream client: %s", cmd); return 1; } return 0; } static int checkRequests(acctClient *a) { char *start = a->request.data + a->pos; char *cmd = start; /* Break the request stream by newlines */ while (start < a->request.data + a->request.used) { if (*start == '\n') { *start = '\0'; processRequest(a, cmd); cmd = start + 1; } start++; } a->pos = cmd - a->request.data; return 0; } volatile sig_atomic_t shutdown_flag = 0; static void acctShutdownHandler(int signo) { UNUSED(signo); shutdown_flag = 1; return; } /* Does not return */ static void acctMain(acctClient *a) { setproctitle("jersd_acct[%d]", a->connection.socket); buff_t b; char *record = NULL; size_t record_size = 0; ssize_t record_len = 0; char id[32]; off_t current_pos = 0; /* Termination handler */ struct sigaction sigact; /* Wrapup & shutdown signals */ sigemptyset(&sigact.sa_mask); sigact.sa_flags = 0; sigact.sa_handler = acctShutdownHandler; sigaction(SIGTERM, &sigact, NULL); sigaction(SIGINT, &sigact, NULL); /* Setup a polling loop to listen for command send from the client */ a->connection.event_fd = epoll_create(1024); if (a->connection.event_fd < 0) error_die("Failed to create epoll fd in accounting stream client: %s\n", strerror(errno)); struct epoll_event *events = malloc(sizeof(struct epoll_event) * MAX_EVENTS); if (pollSetReadable(&a->connection) != 0) { print_msg(JERS_LOG_WARNING, "Failed to set accounting client as readable: %s", strerror(errno)); exit(1); } /* Buffer to read client requests into */ buffNew(&a->request, 0); buffNew(&b, 0); /* Main processing loop */ while (1) { if (shutdown_flag) { print_msg(JERS_LOG_INFO, "Shutdown of accounting stream requested.\n"); break; } /* Poll for any events on our sockets */ int status = epoll_wait(a->connection.event_fd, events, MAX_EVENTS, 2000); for (int i = 0; i < status; i++) { struct epoll_event * e = &events[i]; /* The socket is readable */ if (e->events &EPOLLIN) { if (handleAcctClientRead(a) != 0) { print_msg(JERS_LOG_WARNING, "Unable to handle accounting client request."); exit(1); } } /* Socket is writeable */ if (e->events &EPOLLOUT) { if (handleAcctClientWrite(a) != 0) { print_msg(JERS_LOG_WARNING, "Unable to handle write event."); exit(1); } } } checkRequests(a); if (a->state == ACCT_STOPPED) continue; /* Read the current journal, sending any new messages. * We need to also check if we need to open the next journal. */ current_pos = ftell(a->journal); while ((record_len = getline(&record, &record_size, a->journal)) != -1) { if (*record == '\0') { fseek(a->journal, current_pos, SEEK_SET); /* Check if we need to switch to a new journal file */ /* Get a list of all journal files, find the one we currently have open */ char glob_pattern[PATH_MAX]; char current_journal[PATH_MAX]; sprintf(glob_pattern, "%s/journal.*", server.state_dir); sprintf(current_journal, "%s/journal.%s", server.state_dir, a->datetime); glob_t glob_buff; if (glob(glob_pattern, 0, NULL, &glob_buff) == 0) { size_t i = 0; for (i = 0; i < glob_buff.gl_pathc; i++) { if (strcmp(current_journal, glob_buff.gl_pathv[i]) == 0) { i++; break; } } if (i < glob_buff.gl_pathc) { /* Have a new journal to open */ FILE *new_journal = fopen(glob_buff.gl_pathv[i], "rb"); if (new_journal == NULL) error_die("Failed to open journal file '%s': %s", glob_buff.gl_pathv[i], strerror(errno)); /* Opened a new journal. Reset the current stats */ fclose(a->journal); a->record = 0; char *dot = strchr(glob_buff.gl_pathv[i], '.'); dot++; strcpy(a->datetime, dot); a->journal = new_journal; current_pos = 0; print_msg_info("Switched to new journal %s\n", a->datetime); } globfree(&glob_buff); } break; } current_pos = ftell(a->journal); if (record[record_len - 1] == '\n') record[record_len - 1] = '\0'; a->record++; /* Load this message */ char timestamp[64]; int64_t revision; char command[64]; uid_t uid; jobid_t jobid; int msg_offset; int field_count = sscanf(record, "%*c%64s\t%d\t%64s\t%u\t%ld\t%n", timestamp, (int *)&uid, command, &jobid, &revision, &msg_offset); if (field_count != 5) error_die("Failed to load 5 required fields from message"); if (strcmp(command, "REPLAY_COMPLETE") == 0) continue; /* Serialize this message */ JSONStart(&b); JSONStartObject(&b, "UPDATE", 6); sprintf(id, "%s:%ld", a->datetime, a->record); JSONAddString(&b, ACCT_ID, id); JSONAddString(&b, TIMESTAMP, timestamp); JSONAddString(&b, COMMAND, command); JSONAddInt(&b, UID, uid); if (jobid) JSONAddInt(&b, JOBID, jobid); buffAdd(&b, "\"MESSAGE\":", 10); buffAdd(&b, record + msg_offset, strlen(record + msg_offset)); JSONEndObject(&b); JSONEnd(&b); //fprintf(stderr, "Sending: '%.*s' to accounting stream\n", (int)b.used, b.data); buffAddBuff(&a->response, &b); buffAdd(&a->response, "\n", 1); buffClear(&b, 0); pollSetWritable(&a->connection); if (shutdown_flag) break; } } free(record); free(a->id); exit(0); }
C
CL
cb7d9ba4c332219a2a8d34530aabf906581518289700fdf55720a290f254378c
/******************************************************************************* @ddblock_begin copyright Copyright (c) 1997-2018 Maryland DSPCAD Research Group, The University of Maryland at College Park Permission is hereby granted, without written agreement and without license or royalty fees, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following two paragraphs appear in all copies of this software. IN NO EVENT SHALL THE UNIVERSITY OF MARYLAND BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF MARYLAND HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE UNIVERSITY OF MARYLAND SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF MARYLAND HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. @ddblock_end copyright *******************************************************************************/ #include "lide_c_util.h" #include <stdio.h> #include <stdlib.h> /* Open a file. Exit with an error message if the file cannot be opened with the specified mode ("r", "w", etc. as in coventional fopen). Otherwise return the file pointer of the opened file. */ FILE *lide_c_util_fopen(const char *fname, const char *mode) { FILE *fp; if ((fp=fopen(fname, mode))==NULL) { fprintf(stderr, "could not open file named '%s' with mode '%s'", fname, mode); exit(1); } return fp; } void *lide_c_util_malloc(size_t size) { void *p; if ((p = malloc(size)) != NULL) { return(p); } else { fprintf(stderr, "lide_c_util_malloc error: insufficient memory"); exit(1); } return NULL; /*NOTREACHED*/ } boolean lide_c_util_guarded_execution(lide_c_actor_context_type *context, char *descriptor) { if (context->enable(context)) { context->invoke(context); //printf("%s visit complete.\n", descriptor); return TRUE; } else { return FALSE; } } void lide_c_util_simple_scheduler(lide_c_actor_context_type *actors[], int actor_count, char *descriptors[]) { boolean progress = FALSE; int i = 0; do { progress = 0; for (i = 0; i < actor_count; i++) { progress |= lide_c_util_guarded_execution(actors[i], descriptors[i]); } } while (progress); } void lide_c_set_actor_mode(lide_c_actor_context_type *context, int mode){ if(context != NULL){ context->mode = mode; } return; } int lide_c_get_actor_mode(lide_c_actor_context_type *context){ if(context != NULL){ return context->mode; }else{ fprintf(stderr, "actor context does not exist.\n"); return -1; } }
C
CL
fe6ecfd661285b39326fb975f2c28dd2508a886071df7eae13ce3f34033c79b8
/*****************************************************/ // Copyright © 2007-2012 Navico // Confidential and proprietary. All rights reserved. /*****************************************************/ #include "Pgn130826Mercury.h" #include "Nmea2kDefMercury.h" #include <string.h> /* for memcpy */ #include <assert.h> //----------------------------------------------------------------------------- void cEncodePgn130826Mercury( const tEncodePgnInfo* pEncodeInfo, tNmea2KMsg* pMsg ) { tPgn130826MercuryCalibration *pEncodeData = (tPgn130826MercuryCalibration*) pEncodeInfo->pPgnData; unsigned char size = pEncodeData->dataSize; pMsg->priority = 7; pMsg->msgId.whole = 130826; pMsg->data[0] = MERCURY_TAG_LO; pMsg->data[1] = MERCURY_TAG_HI; pMsg->data[2] = pEncodeData->destAddr; pMsg->data[3] = pEncodeData->operation; pMsg->data[4] = pEncodeData->network & 0x03; pMsg->data[5] = pEncodeData->instance; if (size > PGN130826_MERCURY_MAX_DATA) { size = PGN130826_MERCURY_MAX_DATA; assert( 0 ); } if (size > 0) memcpy( pMsg->data+6, pEncodeData->data, size ); pMsg->lengthUsed = 6 + size; } //----------------------------------------------------------------------------- void cDecodePgn130826Mercury( const tNmea2KMsg* pMsg, void* pData ) { tPgn130826MercuryCalibration *pDecodeData = (tPgn130826MercuryCalibration*) pData; unsigned size = pMsg->lengthUsed; if (size < 6) { assert( 0 ); pDecodeData->operation = eMercuryCalibrationOp_END; pDecodeData->dataSize = 0; } else { size -= 6; if (size > PGN130826_MERCURY_MAX_DATA) size = PGN130826_MERCURY_MAX_DATA; pDecodeData->destAddr = pMsg->data[2]; pDecodeData->operation = (eMercuryCalibrationOp) pMsg->data[3]; pDecodeData->network = pMsg->data[4] & 0x03; pDecodeData->instance = pMsg->data[5]; pDecodeData->dataSize = (unsigned char)size; if (size > 0) memcpy( pDecodeData->data, pMsg->data+6, size ); } }
C
CL
f70371c3cc42a8b21f91e3b0390c4b29bb0ac7be6a3b676e3a95e92828d67dd8
# ifndef TKERROR_CODES /* 0 = tkNO_ERROR 1-200 = Common 201-400 = tkshp 401-600 = tkgrd 601-800 = tkimg 801-1000 = tkdbf 1001-1200 = tkutils 1201-1400 = tkmap 1401-1600 = tktinvuc 1501-1600 = tkFeatureSpecific 1601-5000 = Reserved 5001- = UserDefined */ const char * ErrorMsg( long ErrorCode ); // 0 = tkNO_ERROR # define tkNO_ERROR 0 //1-200 = Common # define tkINDEX_OUT_OF_BOUNDS 1 # define tkUNEXPECTED_NULL_PARAMETER 2 # define tkINVALID_FILE_EXTENSION 3 # define tkINVALID_FILENAME 4 # define tkUNRECOVERABLE_ERROR 5 # define tkFILE_NOT_OPEN 6 # define tkZERO_LENGTH_STRING 7 # define tkINCORRECT_VARIANT_TYPE 8 # define tkINVALID_PARAMETER_VALUE 9 # define tkINTERFACE_NOT_SUPPORTED 10 # define tkUNAVAILABLE_IN_DISK_MODE 11 # define tkCANT_OPEN_FILE 12 # define tkUNSUPPORTED_FILE_EXTENSION 13 # define tkCANT_CREATE_FILE 14 # define tkINVALID_FILE 15 # define tkINVALID_VARIANT_TYPE 16 # define tkOUT_OF_RANGE_0_TO_1 17 # define tkCANT_COCREATE_COM_INSTANCE 18 # define tkFAILED_TO_ALLOCATE_MEMORY 19 # define tkUNSUPPORTED_FORMAT 20 # define tkPROPERTY_DEPRECATED 21 # define tkPROPERTY_NOT_IMPLEMENTED 22 # define tkINVALID_FOR_INMEMORY_OBJECT 23 # define tkCANT_DELETE_FILE 24 # define tkINVALID_EXPRESSION 25 //201 - 400 = tkshp # define tkUNSUPPORTED_SHAPEFILE_TYPE 201 # define tkINCOMPATIBLE_SHAPEFILE_TYPE 202 # define tkCANT_OPEN_SHP 203 # define tkCANT_OPEN_SHX 204 # define tkINVALID_SHP_FILE 205 # define tkINVALID_SHX_FILE 206 # define tkSHPFILE_IN_EDIT_MODE 207 # define tkSHPFILE_NOT_IN_EDIT_MODE 208 # define tkCANT_CREATE_SHP 209 # define tkCANT_CREATE_SHX 210 # define tkSHP_FILE_EXISTS 211 # define tkSHX_FILE_EXISTS 212 # define tkINCOMPATIBLE_SHAPE_TYPE 213 # define tkPARENT_SHAPEFILE_NOT_EXISTS 214 # define tkCANT_CONVERT_SHAPE_GEOS 215 # define tkSHAPEFILE_UNINITIALIZED 216 # define tkSHP_READ_VIOLATION 217 # define tkSHP_WRITE_VIOLATION 218 # define tkSELECTION_EMPTY 219 # define tkINVALID_SHAPE 220 # define tkUNEXPECTED_SHAPE_TYPE 221 //401-600 = tkgrd # define tkGRID_NOT_INITIALIZED 401 # define tkINVALID_DATA_TYPE 402 # define tkINVALID_GRID_FILE_TYPE 403 # define tkZERO_ROWS_OR_COLS 404 # define tkINCOMPATIBLE_DATA_TYPE 405 # define tkESRI_DLL_NOT_INITIALIZED 406 # define tkESRI_INVALID_BOUNDS 407 # define tkESRI_ACCESS_WINDOW_SET 408 # define tkCANT_ALLOC_MEMORY 409 # define tkESRI_LAYER_OPEN 410 # define tkESRI_LAYER_CREATE 411 # define tkESRI_CANT_DELETE_FILE 412 # define tkSDTS_BAD_FILE_HEADER 413 //601-800 = tkimg # define tkCANT_WRITE_WORLD_FILE 601 # define tkINVALID_WIDTH_OR_HEIGHT 602 # define tkINVALID_DY 603 # define tkINVALID_DX 604 # define tkCANT_CREATE_DDB_BITMAP 605 # define tkNOT_APPLICABLE_TO_BITMAP 606 # define tkNOT_APPLICABLE_TO_GDAL 607 # define tkGDAL_DATASET_IS_READONLY 608 # define tkIMAGE_BUFFER_IS_EMPTY 609 # define tkICON_OR_TEXTURE_TOO_BIG 610 # define tkFAILED_TO_OBTAIN_DC 611 # define tkIMAGE_UNINITIALIZED 612 //801-1000 = tkdbf # define tkCANT_OPEN_DBF 801 # define tkDBF_IN_EDIT_MODE 802 # define tkDBF_NOT_IN_EDIT_MODE 803 # define tkDBF_FILE_EXISTS 804 # define tkDBF_FILE_DOES_NOT_EXIST 805 # define tkCANT_CREATE_DBF 806 # define tkDBF_CANT_ADD_DBF_FIELD 807 # define tkCANT_CHANGE_FIELD_TYPE 808 //1001-1200 = tkutils # define tkOUT_OF_RANGE_0_TO_180 1001 # define tkOUT_OF_RANGE_M360_TO_360 1002 # define tkSHAPEFILE_LARGER_THAN_GRID 1003 # define tkCONCAVE_POLYGONS 1004 # define tkINCOMPATIBLE_DX 1005 # define tkINCOMPATIBLE_DY 1006 # define tkINVALID_FINAL_POINT_INDEX 1007 # define tkTOLERANCE_TOO_LARGE 1008 # define tkNOT_ALIGNED 1009 # define tkINVALID_NODE 1010 # define tkNODE_AT_OUTLET 1011 # define tkNO_NETWORK 1012 # define tkCANT_CHANGE_OUTLET_PARENT 1013 # define tkNET_LOOP 1014 # define tkMISSING_FIELD 1015 # define tkINVALID_FIELD 1016 # define tkINVALID_FIELD_VALUE 1017 //1201-1400 = tkmap # define tkINVALID_LAYER_HANDLE 1201 # define tkINVALID_DRAW_HANDLE 1202 # define tkWINDOW_LOCKED 1203 # define tkINVALID_LAYER_POSITION 1204 # define tkINIT_INVALID_DC 1205 # define tkINIT_CANT_SETUP_PIXEL_FORMAT 1206 # define tkINIT_CANT_CREATE_CONTEXT 1207 # define tkINIT_CANT_MAKE_CURRENT 1208 # define tkUNEXPECTED_LAYER_TYPE 1209 # define tkMAP_NOT_INITIALIZED 1210 # define tkMAP_INVALID_MAPSTATE 1211 # define tkMAP_MAPSTATE_LAYER_LOAD_FAILED 1212 //1401-1600 = tktinvuc # define tkVALUE_MUST_BE_2_TO_N 1401 # define tkNOT_INITIALIZED 1402 //1501-1600 = Itkfeature //1601-1800 = labels # define tkLABELS_CANT_SYNCHRONIZE 1601 # define tkLABELS_NOT_SYNCHRONIZE 1602 # define tkLABELS_NOT_SAVED 1603 //1801-2000 = geoprojections #define tkOGR_NOT_ENOUGH_DATA 1801 /* not enough data to deserialize */ #define tkOGR_NOT_ENOUGH_MEMORY 1802 #define tkOGR_UNSUPPORTED_GEOMETRY_TYPE 1803 #define tkOGR_UNSUPPORTED_OPERATION 1804 #define tkOGR_CORRUPT_DATA 1805 #define tkOGR_FAILURE 1806 #define tkOGR_UNSUPPORTED_SRS 1807 #define tkOGR_INVALID_HANDLE 1808 #define tkFAILED_TO_REPROJECT 1809 #define tkPROJECTION_NOT_INITIALIZED 1810 #define tkPRJ_FILE_EXISTS 1811 #define tkTRANSFORMATION_NOT_INITIALIZED 1812 # endif
C
CL
006786e51de029f987a8b612ee4b51f6079bde1d0dc56a2a40c95475c1282da6
/* Copyright 2017 The Chromium OS Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "adc.h" #include "adc_chip.h" #include "common.h" #include "console.h" #include "gpio.h" #include "hooks.h" #include "registers.h" #include "task.h" #include "timer.h" #include "util.h" #include "tfdp_chip.h" /* * Conversion on a single channel takes less than 12 ms. Set timeout to * 15 ms so that we have a 3-ms margin. */ #define ADC_SINGLE_READ_TIME 15000 struct mutex adc_lock; /* * Volatile should not be needed. * ADC ISR only reads task_waiting. * Two other non-ISR routines only write task_waiting when * interrupt is disabled or before starting ADC. */ static task_id_t task_waiting; /* * Start ADC single-shot conversion. * 1. Disable ADC interrupt. * 2. Clear sticky hardware status. * 3. Start conversion. * 4. Enable interrupt. * 5. Wait with timeout for ADC ISR to * to set TASK_EVENT_TIMER. */ static int start_single_and_wait(int timeout) { int event; MCHP_INT_DISABLE(MCHP_ADC_GIRQ) = MCHP_ADC_GIRQ_SINGLE_BIT; task_waiting = task_get_current(); /* clear all R/W1C channel status */ MCHP_ADC_STS = 0xffffu; /* clear R/W1C single done status */ MCHP_ADC_CTRL |= BIT(7); /* clear GIRQ single status */ MCHP_INT_SOURCE(MCHP_ADC_GIRQ) = MCHP_ADC_GIRQ_SINGLE_BIT; /* make sure all writes are issued before starting conversion */ asm volatile ("dsb"); /* Start conversion */ MCHP_ADC_CTRL |= BIT(1); MCHP_INT_ENABLE(MCHP_ADC_GIRQ) = MCHP_ADC_GIRQ_SINGLE_BIT; /* Wait for interrupt, ISR disables interrupt */ event = task_wait_event(timeout); task_waiting = TASK_ID_INVALID; return event != TASK_EVENT_TIMER; } int adc_read_channel(enum adc_channel ch) { const struct adc_t *adc = adc_channels + ch; int value; mutex_lock(&adc_lock); MCHP_ADC_SINGLE = 1 << adc->channel; if (start_single_and_wait(ADC_SINGLE_READ_TIME)) value = (MCHP_ADC_READ(adc->channel) * adc->factor_mul) / adc->factor_div + adc->shift; else value = ADC_READ_ERROR; mutex_unlock(&adc_lock); return value; } int adc_read_all_channels(int *data) { int i; int ret = EC_SUCCESS; const struct adc_t *adc; mutex_lock(&adc_lock); MCHP_ADC_SINGLE = 0; for (i = 0; i < ADC_CH_COUNT; ++i) MCHP_ADC_SINGLE |= 1 << adc_channels[i].channel; if (!start_single_and_wait(ADC_SINGLE_READ_TIME * ADC_CH_COUNT)) { ret = EC_ERROR_TIMEOUT; goto exit_all_channels; } for (i = 0; i < ADC_CH_COUNT; ++i) { adc = adc_channels + i; data[i] = (MCHP_ADC_READ(adc->channel) * adc->factor_mul) / adc->factor_div + adc->shift; } exit_all_channels: mutex_unlock(&adc_lock); return ret; } /* * Enable GPIO pins. * Using MEC17xx direct mode interrupts. Do not * set Interrupt Aggregator Block Enable bit * for GIRQ containing ADC. */ static void adc_init(void) { trace0(0, ADC, 0, "adc_init"); gpio_config_module(MODULE_ADC, 1); /* clear ADC sleep enable */ MCHP_PCR_SLP_DIS_DEV(MCHP_PCR_ADC); /* Activate ADC module */ MCHP_ADC_CTRL |= BIT(0); /* Enable interrupt */ task_waiting = TASK_ID_INVALID; MCHP_INT_ENABLE(MCHP_ADC_GIRQ) = MCHP_ADC_GIRQ_SINGLE_BIT; task_enable_irq(MCHP_IRQ_ADC_SNGL); } DECLARE_HOOK(HOOK_INIT, adc_init, HOOK_PRIO_INIT_ADC); void adc_interrupt(void) { MCHP_INT_DISABLE(MCHP_ADC_GIRQ) = MCHP_ADC_GIRQ_SINGLE_BIT; /* clear individual chan conversion status */ MCHP_ADC_STS = 0xffffu; /* Clear interrupt status bit */ MCHP_ADC_CTRL |= BIT(7); MCHP_INT_SOURCE(MCHP_ADC_GIRQ) = MCHP_ADC_GIRQ_SINGLE_BIT; if (task_waiting != TASK_ID_INVALID) task_wake(task_waiting); } DECLARE_IRQ(MCHP_IRQ_ADC_SNGL, adc_interrupt, 2);
C
CL
0dd023059cfd3d308e32ff204d5cfa5166eb60caecb3acf0529ae3c7459c5e99
#ifndef GUARD_CONSTANTS_ABILITIES_H #define GUARD_CONSTANTS_ABILITIES_H #define ABILITY_NONE 0 #define ABILITY_STENCH 1 #define ABILITY_DRIZZLE 2 #define ABILITY_SPEED_BOOST 3 #define ABILITY_BATTLE_ARMOR 4 #define ABILITY_STURDY 5 #define ABILITY_DAMP 6 #define ABILITY_LIMBER 7 #define ABILITY_SAND_VEIL 8 #define ABILITY_STATIC 9 #define ABILITY_VOLT_ABSORB 10 #define ABILITY_WATER_ABSORB 11 #define ABILITY_OBLIVIOUS 12 #define ABILITY_CLOUD_NINE 13 #define ABILITY_COMPOUND_EYES 14 #define ABILITY_INSOMNIA 15 #define ABILITY_COLOR_CHANGE 16 #define ABILITY_IMMUNITY 17 #define ABILITY_FLASH_FIRE 18 #define ABILITY_SHIELD_DUST 19 #define ABILITY_OWN_TEMPO 20 #define ABILITY_SUCTION_CUPS 21 #define ABILITY_INTIMIDATE 22 #define ABILITY_SHADOW_TAG 23 #define ABILITY_ROUGH_SKIN 24 #define ABILITY_WONDER_GUARD 25 #define ABILITY_LEVITATE 26 #define ABILITY_EFFECT_SPORE 27 #define ABILITY_SYNCHRONIZE 28 #define ABILITY_CLEAR_BODY 29 #define ABILITY_NATURAL_CURE 30 #define ABILITY_LIGHTNING_ROD 31 #define ABILITY_SERENE_GRACE 32 #define ABILITY_SWIFT_SWIM 33 #define ABILITY_CHLOROPHYLL 34 #define ABILITY_ILLUMINATE 35 #define ABILITY_TRACE 36 #define ABILITY_HUGE_POWER 37 #define ABILITY_POISON_POINT 38 #define ABILITY_INNER_FOCUS 39 #define ABILITY_MAGMA_ARMOR 40 #define ABILITY_WATER_VEIL 41 #define ABILITY_MAGNET_PULL 42 #define ABILITY_SOUNDPROOF 43 #define ABILITY_RAIN_DISH 44 #define ABILITY_SAND_STREAM 45 #define ABILITY_PRESSURE 46 #define ABILITY_THICK_FAT 47 #define ABILITY_EARLY_BIRD 48 #define ABILITY_FLAME_BODY 49 #define ABILITY_RUN_AWAY 50 #define ABILITY_KEEN_EYE 51 #define ABILITY_HYPER_CUTTER 52 #define ABILITY_PICKUP 53 #define ABILITY_TRUANT 54 #define ABILITY_HUSTLE 55 #define ABILITY_CUTE_CHARM 56 #define ABILITY_PLUS 57 #define ABILITY_MINUS 58 #define ABILITY_FORECAST 59 #define ABILITY_STICKY_HOLD 60 #define ABILITY_SHED_SKIN 61 #define ABILITY_GUTS 62 #define ABILITY_MARVEL_SCALE 63 #define ABILITY_LIQUID_OOZE 64 #define ABILITY_OVERGROW 65 #define ABILITY_BLAZE 66 #define ABILITY_TORRENT 67 #define ABILITY_SWARM 68 #define ABILITY_ROCK_HEAD 69 #define ABILITY_DROUGHT 70 #define ABILITY_ARENA_TRAP 71 #define ABILITY_VITAL_SPIRIT 72 #define ABILITY_WHITE_SMOKE 73 #define ABILITY_PURE_POWER 74 #define ABILITY_SHELL_ARMOR 75 #define ABILITY_CACOPHONY 76 #define ABILITY_AIR_LOCK 77 #define ABILITIES_COUNT_GEN3 78 // Gen4 abilities. #define ABILITY_TANGLED_FEET 78 #define ABILITY_MOTOR_DRIVE 79 #define ABILITY_RIVALRY 80 #define ABILITY_STEADFAST 81 #define ABILITY_SNOW_CLOAK 82 #define ABILITY_GLUTTONY 83 #define ABILITY_ANGER_POINT 84 #define ABILITY_UNBURDEN 85 #define ABILITY_HEATPROOF 86 #define ABILITY_SIMPLE 87 #define ABILITY_DRY_SKIN 88 #define ABILITY_DOWNLOAD 89 #define ABILITY_IRON_FIST 90 #define ABILITY_POISON_HEAL 91 #define ABILITY_ADAPTABILITY 92 #define ABILITY_SKILL_LINK 93 #define ABILITY_HYDRATION 94 #define ABILITY_SOLAR_POWER 95 #define ABILITY_QUICK_FEET 96 #define ABILITY_NORMALIZE 97 #define ABILITY_SNIPER 98 #define ABILITY_MAGIC_GUARD 99 #define ABILITY_NO_GUARD 100 #define ABILITY_STALL 101 #define ABILITY_TECHNICIAN 102 #define ABILITY_LEAF_GUARD 103 #define ABILITY_KLUTZ 104 #define ABILITY_MOLD_BREAKER 105 #define ABILITY_SUPER_LUCK 106 #define ABILITY_AFTERMATH 107 #define ABILITY_ANTICIPATION 108 #define ABILITY_FOREWARN 109 #define ABILITY_UNAWARE 110 #define ABILITY_TINTED_LENS 111 #define ABILITY_FILTER 112 #define ABILITY_SLOW_START 113 #define ABILITY_SCRAPPY 114 #define ABILITY_STORM_DRAIN 115 #define ABILITY_ICE_BODY 116 #define ABILITY_SOLID_ROCK 117 #define ABILITY_SNOW_WARNING 118 #define ABILITY_HONEY_GATHER 119 #define ABILITY_FRISK 120 #define ABILITY_RECKLESS 121 #define ABILITY_MULTITYPE 122 #define ABILITY_FLOWER_GIFT 123 #define ABILITY_BAD_DREAMS 124 #define ABILITIES_COUNT_GEN4 125 // Gen5 abilities. #define ABILITY_PICKPOCKET 125 #define ABILITY_SHEER_FORCE 126 #define ABILITY_CONTRARY 127 #define ABILITY_UNNERVE 128 #define ABILITY_DEFIANT 129 #define ABILITY_DEFEATIST 130 #define ABILITY_CURSED_BODY 131 #define ABILITY_HEALER 132 #define ABILITY_FRIEND_GUARD 133 #define ABILITY_WEAK_ARMOR 134 #define ABILITY_HEAVY_METAL 135 #define ABILITY_LIGHT_METAL 136 #define ABILITY_MULTISCALE 137 #define ABILITY_TOXIC_BOOST 138 #define ABILITY_FLARE_BOOST 139 #define ABILITY_HARVEST 140 #define ABILITY_TELEPATHY 141 #define ABILITY_MOODY 142 #define ABILITY_OVERCOAT 143 #define ABILITY_POISON_TOUCH 144 #define ABILITY_REGENERATOR 145 #define ABILITY_BIG_PECKS 146 #define ABILITY_SAND_RUSH 147 #define ABILITY_WONDER_SKIN 148 #define ABILITY_ANALYTIC 149 #define ABILITY_ILLUSION 150 #define ABILITY_IMPOSTER 151 #define ABILITY_INFILTRATOR 152 #define ABILITY_MUMMY 153 #define ABILITY_MOXIE 154 #define ABILITY_JUSTIFIED 155 #define ABILITY_RATTLED 156 #define ABILITY_MAGIC_BOUNCE 157 #define ABILITY_SAP_SIPPER 158 #define ABILITY_PRANKSTER 159 #define ABILITY_SAND_FORCE 160 #define ABILITY_IRON_BARBS 161 #define ABILITY_ZEN_MODE 162 #define ABILITY_VICTORY_STAR 163 #define ABILITY_TURBOBLAZE 164 #define ABILITY_TERAVOLT 165 #define ABILITIES_COUNT_GEN5 166 // Gen6 abilities. #define ABILITY_AROMA_VEIL 166 #define ABILITY_FLOWER_VEIL 167 #define ABILITY_CHEEK_POUCH 168 #define ABILITY_PROTEAN 169 #define ABILITY_FUR_COAT 170 #define ABILITY_MAGICIAN 171 #define ABILITY_BULLETPROOF 172 #define ABILITY_COMPETITIVE 173 #define ABILITY_STRONG_JAW 174 #define ABILITY_REFRIGERATE 175 #define ABILITY_SWEET_VEIL 176 #define ABILITY_STANCE_CHANGE 177 #define ABILITY_GALE_WINGS 178 #define ABILITY_MEGA_LAUNCHER 179 #define ABILITY_GRASS_PELT 180 #define ABILITY_SYMBIOSIS 181 #define ABILITY_TOUGH_CLAWS 182 #define ABILITY_PIXILATE 183 #define ABILITY_GOOEY 184 #define ABILITY_AERILATE 185 #define ABILITY_PARENTAL_BOND 186 #define ABILITY_DARK_AURA 187 #define ABILITY_FAIRY_AURA 188 #define ABILITY_AURA_BREAK 189 #define ABILITY_PRIMORDIAL_SEA 190 #define ABILITY_DESOLATE_LAND 191 #define ABILITY_DELTA_STREAM 192 #define ABILITIES_COUNT_GEN6 193 // Gen7 abilities. #define ABILITY_STAMINA 193 #define ABILITY_WIMP_OUT 194 #define ABILITY_EMERGENCY_EXIT 195 #define ABILITY_WATER_COMPACTION 196 #define ABILITY_MERCILESS 197 #define ABILITY_SHIELDS_DOWN 198 #define ABILITY_STAKEOUT 199 #define ABILITY_WATER_BUBBLE 200 #define ABILITY_STEELWORKER 201 #define ABILITY_BERSERK 202 #define ABILITY_SLUSH_RUSH 203 #define ABILITY_LONG_REACH 204 #define ABILITY_LIQUID_VOICE 205 #define ABILITY_TRIAGE 206 #define ABILITY_GALVANIZE 207 #define ABILITY_SURGE_SURFER 208 #define ABILITY_SCHOOLING 209 #define ABILITY_DISGUISE 210 #define ABILITY_BATTLE_BOND 211 #define ABILITY_POWER_CONSTRUCT 212 #define ABILITY_CORROSION 213 #define ABILITY_COMATOSE 214 #define ABILITY_QUEENLY_MAJESTY 215 #define ABILITY_INNARDS_OUT 216 #define ABILITY_DANCER 217 #define ABILITY_BATTERY 218 #define ABILITY_FLUFFY 219 #define ABILITY_DAZZLING 220 #define ABILITY_SOUL_HEART 221 #define ABILITY_TANGLING_HAIR 222 #define ABILITY_RECEIVER 223 #define ABILITY_POWER_OF_ALCHEMY 224 #define ABILITY_BEAST_BOOST 225 #define ABILITY_RKS_SYSTEM 226 #define ABILITY_ELECTRIC_SURGE 227 #define ABILITY_PSYCHIC_SURGE 228 #define ABILITY_MISTY_SURGE 229 #define ABILITY_GRASSY_SURGE 230 #define ABILITY_FULL_METAL_BODY 231 #define ABILITY_SHADOW_SHIELD 232 #define ABILITY_PRISM_ARMOR 233 #define ABILITIES_COUNT_GEN7 234 #define ABILITIES_COUNT ABILITIES_COUNT_GEN6 #endif // GUARD_CONSTANTS_ABILITIES_H
C
CL
1d631b91098e7345920478482d246274364b21230dedd1937ed1bb7e4e398a03
/*============================================================================= * Copyright 2002-2003 Texas Instruments Incorporated. All Rights Reserved. */ #ifndef BSP_I2C_PLATFORM_HEADER #define BSP_I2C_PLATFORM_HEADER #include "chipset.cfg" #include "types.h" /*=========================================================================== * Component Description: */ /*! * @header bspI2c_Platform * Platform specific public interface to the I2C master device driver. * * This contains assignments for devices on the differnt platforms. */ /*============================================================================= * Defines *============================================================================*/ /*===========================================================================*/ /*! * @typedef BspI2c_DeviceId * * @discussion * <b> Description </b><br> * This is the data type for a device on the I2C Bus. This is a subset of * the 128 devices an I2C bus supports. There shuold only be as many devices * as exist on the target platform */ #if defined(PLATFORM_TCS4100TORPHINS) enum { BSP_I2C_DEVICE_ID_TLV320AIC23 = 0, BSP_I2C_DEVICE_ID_NUM_DEVICES }; typedef Uint8 BspI2c_DeviceId; #elif defined(PLATFORM_TCS4100EVM) || \ defined(PLATFORM_TCS4102EVM) || \ defined(PLATFORM_TCS3100CEVM) || \ defined(PLATFORM_TCS3100EVM) || \ defined(PLATFORM_TCS4103EVM) enum { BSP_I2C_DEVICE_ID_EEPROM_A = 0, BSP_I2C_DEVICE_ID_EEPROM_B = 1, BSP_I2C_DEVICE_ID_TLV320AIC23 = 2, BSP_I2C_DEVICE_ID_TWL3024 = 3, BSP_I2C_DEVICE_ID_TWL3029 = 4, BSP_I2C_DEVICE_ID_NUM_DEVICES }; typedef Uint8 BspI2c_DeviceId; #elif defined(PLATFORM_TCS4105EVM) || \ defined(PLATFORM_TCS3100EVM) || \ defined(PLATFORM_TCS4105STORNOWAY) || \ defined(PLATFORM_TCS4105DBM) enum { BSP_I2C_DEVICE_ID_EEPROM_A = 0, BSP_I2C_DEVICE_ID_EEPROM_B = 1, BSP_I2C_DEVICE_ID_TWL3024 = 2, BSP_I2C_DEVICE_ID_NUM_DEVICES }; typedef Uint8 BspI2c_DeviceId; #elif defined(PLATFORM_OMAP1509EVM) enum { BSP_I2C_DEVICE_ID_EEPROM_A = 0, /* SDRAM Module */ BSP_I2C_DEVICE_ID_EEPROM_B = 1, /* Flash Module */ BSP_I2C_DEVICE_ID_RTC = 2, BSP_I2C_DEVICE_ID_CAMERA = 3, BSP_I2C_DEVICE_ID_NUM_DEVICES }; typedef Uint8 BspI2c_DeviceId; #elif defined(PLATFORM_OMAP1510INNOVATOR) enum { BSP_I2C_DEVICE_ID_EEPROM_A = 0, /* Atmel lower page */ BSP_I2C_DEVICE_ID_EEPROM_B = 1, /* Atmel upper page */ BSP_I2C_DEVICE_ID_TLV320AIC23 = 2, BSP_I2C_DEVICE_ID_NUM_DEVICES }; typedef Uint8 BspI2c_DeviceId; #elif defined(PLATFORM_OMAP1610EVM) || \ defined(PLATFORM_OMAP1623STORNOWAY) enum { BSP_I2C_DEVICE_ID_ISP1301 = 0, /* USB OTG */ BSP_I2C_DEVICE_ID_TPS65010 = 1, /* Power management IC */ BSP_I2C_DEVICE_ID_TWL3024 = 2, BSP_I2C_DEVICE_ID_NUM_DEVICES }; typedef Uint8 BspI2c_DeviceId; #endif /*===========================================================================*/ /*! * @typedef BspI2c_DeviceAddress * * @discussion * <b> Description </b><br> * The I2C can address multiple devices. This type is used to address an * individual device. Range: 0 - 127 */ #if defined(PLATFORM_TCS4100TORPHINS) enum { BSP_I2C_DEVICE_ADDRESS_TLV320AIC23 = 0x1A }; typedef Uint8 BspI2c_DeviceAddress; #elif defined(PLATFORM_TCS4100EVM) || \ defined(PLATFORM_TCS4102EVM) || \ defined(PLATFORM_TCS3100CEVM) || \ defined(PLATFORM_TCS3100EVM) || \ defined(PLATFORM_TCS4103EVM) enum { BSP_I2C_DEVICE_ADDRESS_EEPROM_A = 0x50, BSP_I2C_DEVICE_ADDRESS_EEPROM_B = 0x52, BSP_I2C_DEVICE_ADDRESS_TLV320AIC23 = 0x1A, BSP_I2C_DEVICE_ADDRESS_TWL3024_PRIMARY = 0x48, BSP_I2C_DEVICE_ADDRESS_TWL3024_SECONDARY = 0x4A, BSP_I2C_DEVICE_ADDRESS_TWL3029 = 0x2D }; typedef Uint8 BspI2c_DeviceAddress; #elif defined(PLATFORM_TCS4105EVM) || \ defined(PLATFORM_TCS3100EVM) || \ defined(PLATFORM_TCS4105STORNOWAY) || \ defined(PLATFORM_TCS4105DBM) enum { BSP_I2C_DEVICE_ADDRESS_EEPROM_A = 0x57, BSP_I2C_DEVICE_ADDRESS_TWL3024_PRIMARY = 0x48, BSP_I2C_DEVICE_ADDRESS_TWL3024_SECONDARY = 0x4A }; typedef Uint8 BspI2c_DeviceAddress; #elif defined(PLATFORM_OMAP1509EVM) enum { BSP_I2C_DEVICE_ADDRESS_EEPROM_A = 0x51, BSP_I2C_DEVICE_ADDRESS_EEPROM_B = 0x52, BSP_I2C_DEVICE_ADDRESS_RTC = 0x62, BSP_I2C_DEVICE_ADDRESS_CAMERA = 0x1A }; typedef Uint8 BspI2c_DeviceAddress; #elif defined(PLATFORM_OMAP1510INNOVATOR) enum { BSP_I2C_DEVICE_ADDRESS_EEPROM_A = 0x50, /* Atmel lower page */ BSP_I2C_DEVICE_ADDRESS_EEPROM_B = 0x51, /* Atmel Upper page */ BSP_I2C_DEVICE_ADDRESS_TLV320AIC23 = 0x1A }; typedef Uint8 BspI2c_DeviceAddress; #elif defined(PLATFORM_OMAP1610EVM) || \ defined(PLATFORM_OMAP1623STORNOWAY) enum { BSP_I2C_DEVICE_ADDRESS_ISP1301 = 0x2D, BSP_I2C_DEVICE_ADDRESS_TPS65010 = 0x48, BSP_I2C_DEVICE_ADDRESS_TWL3024_PRIMARY = 0x48, BSP_I2C_DEVICE_ADDRESS_TWL3024_SECONDARY = 0x4A }; typedef Uint8 BspI2c_DeviceAddress; #endif #if (CHIPSET==15) enum { BSP_I2C_DEVICE_ADDRESS_TWL3029 = 0x2D, BSP_I2C_DEVICE_ADDRESS_I2C_1 = 0x15, BSP_I2C_DEVICE_ADDRESS_I2C_2 = 0x16, #if (CAM_SENSOR==0) BSP_I2C_DEVICE_ADDRESS_CAMERA = 0x53 #else BSP_I2C_DEVICE_ADDRESS_CAMERA = 0x5D #endif }; typedef Uint8 BspI2c_DeviceAddress; enum { BSP_I2C_DEVICE_ID_TWL3029 = 0, BSP_I2C_DEVICE_ID_I2C_1 = 1, BSP_I2C_DEVICE_ID_I2C_2 = 2, BSP_I2C_DEVICE_ID_CAMERA = 3, BSP_I2C_DEVICE_ID_NUM_DEVICES }; typedef Uint8 BspI2c_DeviceId; #endif #endif
C
CL
19758209c744aabf4912b439392fc83d061b3e8f1aa86ac7d7af9107269f5e5b
/* * @file * * header file that contains the declarations for our structs * used in the shell as well as the function prototypes */ #ifndef _HISTORY_H_ #define _HISTORY_H_ #define HIST_MAX 100 #include <stdbool.h> /** * struct containing tokens of commands * and whether it is a pipe * and whether it is piping in to a file **/ struct command_line { char **tokens; bool stdout_pipe; char *stdout_file; }; /** * struct for background jobs **/ struct jobs { char *tokens; int id; }; //struct jobs job[10]= { 0 }; //int numjobs = 0; /** * struct that contains id of command and the * command char pointer as well as the nested * structure containg the tokenized commands * and further information **/ struct history_entry { int cmd_id; char *command; struct command_line cmds[200]; struct history_entry *next; }; /** * Function prototypes **/ void print_history(); char* get_last(struct history_entry *head); char* get_by_count(struct history_entry *head, char* count); char* get_by_name(struct history_entry *head, char* name, int count); char *next_token(char **str_ptr, const char *delim); void execute_pipeline(struct history_entry *com, int count); void sig_jobs(int signo); void sig_handler(int signo); void print_prompt(bool ran, int count); //void killthe(pid_t child); #endif
C
CL
0ebfded4b7b3153ca25c1b743b8fe25e6ef55fe085ff4b3dea3ffebd8b92fb9c
/** * \file * \brief Pmap arch-independent code for serialisation */ /* * Copyright (c) 2018, ETH Zurich. * All rights reserved. * * This file is distributed under the terms in the attached LICENSE file. * If you do not find this file, copies can be found by writing to: * ETH Zurich D-INFK, Universitaetstrasse 6, CH-8092 Zurich. Attn: Systems Group. */ #include <barrelfish/barrelfish.h> #include <pmap_ds.h> #include <pmap_priv.h> /* * The serialisation format is depressingly ad-hoc, and assumes a depth-first * walk of the tree. Each vnode is encoded as an entry in an array. * * We abuse the slot of the first entry, which is the root and thus is always * zero, to store the number of entries in the array. */ struct serial_entry { uint16_t entry; ///< Entry # uint8_t depth; ///< Depth of this node (0 = root) cslot_t slot; ///< Slot number (in page cnode) of vnode cap cslot_t mapping; ///< Slot number (in page cnode) of mapping cap for vnode enum objtype type; ///< Type of the vnode cap }; static errval_t serialise_tree(int depth, struct pmap *pmap, struct vnode_public *v, struct serial_entry *out, size_t outlen, size_t *outpos) { assert(v != NULL); errval_t err; // don't serialise leaf pages (yet!) if (!v->is_vnode) { return SYS_ERR_OK; } if (*outpos >= outlen) { return LIB_ERR_SERIALISE_BUFOVERFLOW; } // serialise this node out[(*outpos)++] = (struct serial_entry) { .depth = depth, .entry = v->entry, .type = v->type, .slot = v->cap.slot, .mapping = v->mapping.slot, }; // TODO: we want a way to only ever see vnode_public part of vnode // depth-first walk struct vnode *c; pmap_foreach_child((struct vnode*)v, c) { if (c) { /* allocate slot in pagecn for mapping */ struct capref mapping; #ifdef PMAP_ARRAY /* here we rely on the fact that pmap_foreach_child uses `int i` * as its internal loop counter for PMAP_ARRAY. This is not very * clean, but may eliminate itself, if we move pmap serialization * to arch-independent code, which should be possible. */ if (i == c->v.entry) { // only copy each mapping cap to page cn for the first page of // a multi-page mapping. err = pmap->slot_alloc->alloc(pmap->slot_alloc, &mapping); if (err_is_fail(err)) { return err; } err = cap_copy(mapping, c->v.mapping); if (err_is_fail(err)) { return err; } c->v.mapping = mapping; } #else err = pmap->slot_alloc->alloc(pmap->slot_alloc, &mapping); if (err_is_fail(err)) { return err; } err = cap_copy(mapping, c->v.mapping); if (err_is_fail(err)) { return err; } c->v.mapping = mapping; #endif err = serialise_tree(depth + 1, pmap, &c->v, out, outlen, outpos); if (err_is_fail(err)) { return err; } } } return SYS_ERR_OK; } /** * \brief Serialise vtree to a flat structure, for passing to another process * * This is used by spawn_vspace to communicate the vnode capabilities to the child. */ errval_t pmap_serialise(struct pmap *pmap, void *buf, size_t buflen) { errval_t err; // XXX: check alignment of buffer assert((uintptr_t)buf % sizeof(uintptr_t) == 0); struct serial_entry *out = buf; size_t outlen = buflen / sizeof(struct serial_entry); size_t outpos = 0; err = serialise_tree(0, pmap, pmap_get_vroot(pmap), out, outlen, &outpos); if (err_is_ok(err)) { // store length in first entry's slot number assert(out[0].slot == 0); out[0].slot = outpos; } return err; } static errval_t deserialise_tree(struct pmap *pmap, struct serial_entry **in, size_t *inlen, int depth, struct vnode_public *parent) { errval_t err; if (*inlen == 0) { return SYS_ERR_OK; } while (*inlen > 0 && (*in)->depth == depth) { // ensure slab allocator has sufficient space err = pmap_refill_slabs(pmap, 16); if (err_is_fail(err)) { return err; } // allocate storage for the new vnode struct vnode *n = slab_alloc(&pmap->m.slab); assert(n != NULL); // populate it and append to parent's list of children n->v.is_vnode = true; n->v.entry = (*in)->entry; n->v.cap.cnode = cnode_page; n->v.cap.slot = (*in)->slot; n->v.u.vnode.invokable = n->v.cap; pmap_vnode_init(pmap, n); pmap_vnode_insert_child((struct vnode *)parent, n); n->v.type = (*in)->type; /* XXX: figure out if we want this // Count cnode_page slots that are in use pmapx->used_cap_slots ++; */ #if GLOBAL_MCN /* allocate mapping cnodes */ for (int i = 0; i < MCN_COUNT; i++) { err = cnode_create_l2(&n->u.vnode.mcn[i], &n->u.vnode.mcnode[i]); if (err_is_fail(err)) { return err_push(err, LIB_ERR_PMAP_ALLOC_CNODE); } } #endif set_mapping_cap(pmap, n, (struct vnode *)parent, n->v.entry); /* copy mapping cap into mapping cnode of parent */ struct capref orig; orig.cnode = cnode_page; orig.slot = (*in)->mapping; err = cap_copy(n->v.mapping, orig); if (err_is_fail(err)) { return err; } (*in)++; (*inlen)--; // is next entry a child of the last node? if (*inlen > 0 && (*in)->depth > depth) { assert((*in)->depth == depth + 1); // depth-first, no missing nodes err = deserialise_tree(pmap, in, inlen, depth + 1, &n->v); if (err_is_fail(err)) { return err; } } } assert((*in)->depth < depth); return SYS_ERR_OK; } /** * \brief Deserialise vtree from a flat structure, for importing from another process * * This is used in a newly-spawned child */ errval_t pmap_deserialise(struct pmap *pmap, void *buf, size_t buflen) { errval_t err; // XXX: check alignment of buffer assert((uintptr_t)buf % sizeof(uintptr_t) == 0); // extract length and sanity-check struct serial_entry *in = buf; assert(buflen > sizeof(struct serial_entry)); size_t inlen = in[0].slot; assert(inlen * sizeof(struct serial_entry) <= buflen); in++; inlen--; err = deserialise_tree(pmap, &in, &inlen, 1, pmap_get_vroot(pmap)); if (err_is_ok(err)) { // XXX: now that we know where our vnodes are, we can support mappings // in the bottom of the address space. However, we still don't know // exactly where our text and data are mapped (because we don't yet // serialise vregions or memobjs), so instead we pad _end. extern char _end; pmap_set_min_mappable_va(pmap, ROUND_UP((lvaddr_t)&_end, 64 * 1024) + 64 * 1024); } return err; }
C
CL
aeeabf1a030a89032e44262493fb72df9f60c0564d053e721b7c8058d414ef91
#include "bits.h" #include <errno.h> #include "platform.h" #include "fe310_gpio.h" #include "gpio.h" #define MAX_GPIO_NUMBER 23 #define MIN_GPIO_NUMBER 0 struct fe310_gpio { uint8_t gpio_number; }; static int fe310_gpio_init(struct gpio_protocol *gpio, uint8_t gpio_number) { struct fe310_gpio *fe310_private_data = ((struct fe310_gpio_protocol*)gpio)->private_data; if (gpio_number > MAX_GPIO_NUMBER || gpio_number < MIN_GPIO_NUMBER) { return -EINVAL; } fe310_private_data->gpio_number = gpio_number; return 0; } static int fe310_gpio_set_direction(struct gpio_protocol *gpio, uint8_t direction) { struct fe310_gpio *fe310_private_data = ((struct fe310_gpio_protocol*)gpio)->private_data; if (direction == OUTPUT) { GPIO_REG(GPIO_INPUT_EN) &= ~(0x1 << fe310_private_data->gpio_number); GPIO_REG(GPIO_OUTPUT_EN) |= (0x1 << fe310_private_data->gpio_number); } else if (direction == INPUT) { GPIO_REG(GPIO_INPUT_EN) |= (0x1 << fe310_private_data->gpio_number); GPIO_REG(GPIO_OUTPUT_EN) &= ~(0x1 << fe310_private_data->gpio_number); } else { return -EINVAL; } return 0; } static int fe310_gpio_set_value(struct gpio_protocol *gpio, uint8_t value) { struct fe310_gpio *fe310_private_data = ((struct fe310_gpio_protocol*)gpio)->private_data; if (value == 0) { GPIO_REG(GPIO_OUTPUT_VAL) &= ~(0x1 << fe310_private_data->gpio_number); } else if (value == 1) { GPIO_REG(GPIO_OUTPUT_VAL) |= (0x1 << fe310_private_data->gpio_number); } else { return -EINVAL; } return 0; } static uint8_t fe310_gpio_get_value(struct gpio_protocol *gpio) { struct fe310_gpio *fe310_private_data = ((struct fe310_gpio_protocol*)gpio)->private_data; return (GPIO_REG(GPIO_INPUT_VAL) >> fe310_private_data->gpio_number) & BIT0; } struct gpio_protocol* install_gpio_protocol(void) { struct fe310_gpio_protocol *fe310_gpio = malloc (sizeof (struct fe310_gpio_protocol)); struct fe310_gpio *fe310_private_data; if (fe310_gpio != NULL) { fe310_gpio->init = &fe310_gpio_init; fe310_gpio->set_value = &fe310_gpio_set_value; fe310_gpio->get_value = &fe310_gpio_get_value; fe310_gpio->set_direction = &fe310_gpio_set_direction; } else { return NULL; } fe310_private_data = malloc (sizeof (fe310_gpio)); if (fe310_private_data != NULL) { fe310_gpio->private_data = (void *)fe310_private_data; } else { free(fe310_gpio); return NULL; } return (struct gpio_protocol*) fe310_gpio; } void uninstall_gpio_protocol(struct gpio_protocol* gpio) { struct fe310_gpio_protocol *fe310_gpio = ((struct fe310_gpio_protocol*)gpio)->private_data; free(fe310_gpio->private_data); free(gpio); }
C
CL
f3a75329dbd282dbe6897566d0f4e5fbda0eba0955c2faf0b262182831dc59ae
/* * $Id: $ */ /* * Mesa 3-D graphics library * Version: 3.1 * Copyright (C) 1995 Brian Paul ([email protected]) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the Free * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /**********************************************************************/ /***** write arrays of RGBA pixels *****/ /**********************************************************************/ void natGWriteRGBAPixel(const GLcontext * ctx, GLuint n, const GLint x[], const GLint y[], CONST GLubyte rgba[][4], const GLubyte mask[]) { amigaMesaContext amesa; struct RastPort *rp; amesa = (amigaMesaContext) ctx->DriverCtx; rp = amesa->rp; DEBUGOUT(1, "natGWriteRGBAPixel(%d)\n", n); (GLshort)n--; for ((GLshort)n; (GLshort)n >= 0; (GLshort)n--, RGBAi++, Xx++, Yy++) { if (*mask++) { /* write pixel x[i], y[i] using rgba[i][0],rgba[i][1],rgba[i][2],rgba[i][3] */ SetAPen(rp, PLG_RGBA(amesa, *RGBAb0, *RGBAb1, *RGBAb2)); DEBUGOUT(9, " WritePixel(%d, %d)\n", FIXx(*Xx), FIXy(*Yy)); WritePixel(rp, FIXx(*Xx), FIXy(*Yy)); } } } /**********************************************************************/ /***** write arrays of RGBA pixels doublebuffered *****/ /**********************************************************************/ void natGWriteRGBAPixelDB(const GLcontext * ctx, GLuint n, const GLint x[], const GLint y[], CONST GLubyte rgba[][4], const GLubyte mask[]) { amigaMesaContext amesa; GLubyte *db; amesa = (amigaMesaContext) ctx->DriverCtx; db = dbPenGet(amesa); DEBUGOUT(1, "natGWriteRGBAPixelDB(%d)\n", n); (GLshort)n--; for ((GLshort)n; (GLshort)n >= 0; (GLshort)n--, RGBAi++, Xx++, Yy++) if (*mask++) *(dbPen(db, *Xx, *Yy)) = PLG_RGBA(amesa, *RGBAb0, *RGBAb1, *RGBAb2); }
C
CL
0c1464e1505537c1cc01000eaf0439619aca0817943fa161044744aa1b1bb9e1
/* paving.f -- translated by f2c (version 20160102). You must link the resulting object file with libf2c: on Microsoft Windows system, link with libf2c.lib; on Linux or Unix systems, link with .../path/to/libf2c.a -lm or, if you install libf2c.a in a standard place, with -lf2c -lm -- in that order, at the end of the command line, as in cc *.o -lf2c -lm Source for libf2c is in /netlib/f2c/libf2c.zip, e.g., http://www.netlib.org/f2c/libf2c.zip */ #ifdef __cplusplus extern "C" { #endif #include "f2c.h" /* Common Block Declarations */ struct { real timea, timep, timec, timepc, timeaj, times; } timing_; #define timing_1 timing_ /* Table of constant values */ static integer c__10 = 10; static integer c__1024 = 1024; static integer c__10240 = 10240; static integer c__20 = 20; static logical c_true = TRUE_; static integer c__1 = 1; /* Copyright(C) 1999-2020 National Technology & Engineering Solutions */ /* of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with */ /* NTESS, the U.S. Government retains certain rights in this software. */ /* See packages/seacas/LICENSE for details */ /* Subroutine */ int paving_(integer *nbnode, integer *nprm, integer *mln, integer *iptper, integer *numper, integer *lperim, real *xn, real *yn, real *zn, integer *iexk, integer *inxe, integer *nnn, integer *lll, integer *kkk, integer *mxnd, real *angle, real *bnsize, integer * lnodes, integer *linkpr, integer *nperim, integer *lxk, integer *kxl, integer *nxl, integer *lxn, integer *nuid, integer *iavail, integer * navail, logical *graph, logical *timer, logical *video, real *defsiz, logical *sizeit, char *dev1, integer *kreg, logical *batch, logical * noroom, logical *err, real *amesur, real *xnold, real *ynold, integer *nxkold, integer *mmpold, integer *linkeg, integer *listeg, real * bmesur, integer *mlink, integer *nprold, integer *npnold, integer * npeold, integer *nnxk, logical *remesh, real *rexmin, real *rexmax, real *reymin, real *reymax, integer *idivis, real *sizmin, real *emax, real *emin, ftnlen dev1_len) { /* System generated locals */ integer lnodes_dim1, lnodes_offset, nxkold_dim1, nxkold_offset, i__1, i__2; real r__1; /* Builtin functions */ integer s_wsfe(cilist *), do_fio(integer *, char *, ftnlen), e_wsfe(); /* Local variables */ static integer i__, j, n0, n1, nnn2, nend; static logical done; static real xmin, xmax, ymin, ymax, zmin, zmax; static integer nadj1, nadj2, node1; static real time1, time2, xmin1, ymin1, xmax1, ymax1, zmin1, zmax1; static integer icomb[10240] /* was [10][1024] */; extern /* Subroutine */ int pinch_(integer *, integer *, integer *, integer *, real *, real *, real *, integer *, integer *, integer * , integer *, real *, integer *, real *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, logical *, real *, real *, real *, real *, real *, real *, char *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, logical *, logical *, integer *, logical *, logical *, ftnlen); static integer lcorn[10], ncorn, kloop, nloop[20], itype[1024], iuppr; extern /* Subroutine */ int close4_(integer *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, logical *), close6_(integer *, integer *, integer *, integer *, real *, real *, integer *, integer *, integer *, integer *, real *, real *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, logical *, real *, real *, real *, real *, char *, integer *, integer *, integer *, integer *, integer *, logical *, logical *, logical *, logical *, logical *, real *, real *, integer *, integer *, integer *, real *, integer *, integer *, integer *, integer *, logical *, real *, real *, real *, real *, integer *, real *, real *, real *, ftnlen); static integer nextn1[20]; static logical adjted; extern /* Subroutine */ int mesage_(char *, ftnlen), getime_(real *), ringbl_(); static integer kkkold; extern /* Subroutine */ int addrow_(integer *, integer *, integer *, integer *, integer *, integer *, real *, real *, real *, integer * , integer *, integer *, integer *, real *, real *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, real *, real *, real *, real *, real *, real *, char *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, logical *, logical *, integer *, logical *, logical *, logical *, logical *, real *, real *, integer *, integer *, integer *, real *, integer *, integer *, integer *, integer *, logical *, real *, real *, real *, real *, integer *, real *, real *, real *, ftnlen); extern logical cpubrk_(logical *); extern /* Subroutine */ int periml_(integer *, integer *, integer *, integer *, integer *, real *, real *, real *, integer *, integer * , integer *, integer *, real *, real *, integer *, integer *, integer *, integer *, real *, real *, real *, real *, real *, real *, char *, integer *, logical *, ftnlen); static integer lllold, itnper, nnnold; extern /* Subroutine */ int rplotl_(integer *, real *, real *, real *, integer *, real *, real *, real *, real *, real *, real *, integer *, char *, integer *, ftnlen); static integer kperim; extern /* Subroutine */ int getrow_(integer *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, real *, real *, real *, real *, real *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, logical *, logical *, real *, real *, real *, real *, real *, real *, char *, integer *, logical *, integer *, logical *, logical *, ftnlen), filsmo_(integer *, integer *, real *, real *, real *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, real *, integer *, real *, real *, real *, real *, real *, real *, char *, integer *, ftnlen), sflush_(), adjrow_( integer *, integer *, integer *, real *, real *, real *, integer * , integer *, integer *, integer *, real *, real *, integer *, integer *, integer *, integer *, real *, real *, real *, real *, real *, real *, char *, integer *, integer *, integer *, integer * , integer *, integer *, integer *, integer *, integer *, logical * , logical *, integer *, real *, logical *, logical *, logical *, ftnlen), pcross_(integer *, integer *, integer *, integer *, integer *, integer *, real *, real *, real *, integer *, integer * , integer *, integer *, real *, integer *, real *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, logical *, real *, real *, real * , real *, real *, real *, char *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, logical *, logical *, integer *, logical *, logical *, ftnlen), colaps_( integer *, integer *, integer *, integer *, integer *, real *, real *, real *, integer *, integer *, integer *, integer *, real * , integer *, real *, integer *, integer *, integer *, integer *, integer *, integer *, logical *, real *, real *, real *, real *, real *, real *, char *, integer *, integer *, integer *, integer * , integer *, integer *, integer *, integer *, logical *, logical * , integer *, logical *, logical *, ftnlen), flmnmx_(integer *, integer *, integer *, integer *, integer *, integer *, real *, real *, integer *, integer *, real *, real *, real *, real *, logical *), tridel_(integer *, integer *, real *, real *, real *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, integer *, real *, integer *, real *, integer *, char *, integer *, real *, real *, real *, real *, real *, real *, logical *, logical *, logical *, logical * , ftnlen); /* Fortran I/O blocks */ static cilist io___39 = { 0, 6, 0, " (A, F10.5)", 0 }; static cilist io___40 = { 0, 6, 0, " (A, F10.5)", 0 }; static cilist io___41 = { 0, 6, 0, " (A, F10.5)", 0 }; static cilist io___42 = { 0, 6, 0, " (A, F10.5)", 0 }; static cilist io___43 = { 0, 6, 0, " (A, F10.5)", 0 }; static cilist io___44 = { 0, 6, 0, " (A, F10.5)", 0 }; static cilist io___45 = { 0, 6, 0, " (A, F10.5)", 0 }; static cilist io___46 = { 0, 6, 0, " (A, F10.5)", 0 }; static cilist io___47 = { 0, 6, 0, " (A, F10.5)", 0 }; /* *********************************************************************** */ /* SUBROUTINE PAVING = A SUBROUTINE TO PAVE A REGION GIVEN THE INITIAL */ /* BOUNDARY AS A LIST OF NODES. */ /* *********************************************************************** */ /* EXTERNAL VARIABLES: */ /* NBNODE = NUMBER OF NODES ON THE INITIAL BOUNDARY */ /* NPRM = NUMBER OF SEPARATE PERIMETERS IN THE BOUNDARY */ /* (THERE IS ONE OUTSIDE PERIMETER AND ONE PERIMETER FOR */ /* EACH HOLE IN THE BOUNDARY) */ /* MLN = NUMBER OF ATTRIBUTES NEEDED IN LNODES ARRAY. THIS */ /* NUMBER SHOULD BE PASSED IN AS EIGHT (8) CURRENTLY. */ /* IPTPER = INTEGER ARRAY OF POINTERS INTO THE BNODE ARRAY. */ /* EACH POINTER INDICATES THE BEGINNING NODE FOR THAT */ /* PERIMETER IN LPERIM */ /* NUMPER = INTEGER ARRAY CONTAINING THE NUMBER OF NODES IN EACH */ /* OF THE PERIMETERS */ /* LPERIM = LIST OF PERIMETER NODES */ /* X = REAL ARRAY OF X VALUES OF NODES DIMENSIONED TO MXND */ /* Y = REAL ARRAY OF Y VALUES OF NODES DIMENSIONED TO MXND */ /* Z = REAL ARRAY OF Z VALUES OF NODES DIMENSIONED TO MXND */ /* IEXK = INTEGER ARRAY OF EDGES ATTACHED TO EACH ELEMENT */ /* DIMENSIONED AS (4, MXND) */ /* INXE = INTEGER ARRAY OF NODES ATTACHED TO EACH EDGE */ /* = DIMENSIONED AS (2, MXND) */ /* NNODE = NUMBER OF NODES IN THE FINAL MESH */ /* NEDGE = NUMBER OF EDGES IN THE FINAL MESH */ /* NELEM = NUMBER OF ELEMENTS IN THE FINAL MESH */ /* MAXND = MAXIMUM NUMBER OF NODES EXPECTED IN THE MESH */ /* (IF THIS IS EXCEEDED, NOROOM IS RETURNED AS .TRUE.) */ /* RWORK1 = REAL ARRAY FOR WORKING SPACE IN PAVING - DIMENSIONED */ /* TO (MXND) - THIS BECOMES THE ANGLE ARRAY */ /* RWORK2 = REAL ARRAY FOR WORKING SPACE IN PAVING - DIMENSIONED */ /* TO (MXND * 2) - THIS BECOMES THE BNSIZE ARRAY */ /* IWORK3 = INTEGER ARRAY FOR WORKING SPACE IN PAVING - DIMENSIONED */ /* TO (MXND * 8) - THIS BECOMES THE LNODES ARRAY */ /* IWORK4 = INTEGER ARRAY FOR WORKING SPACE IN PAVING - DIMENSIONED */ /* TO (NPRM * 3) - THIS BECOMES THE LINKPR ARRAY */ /* IWORK5 = INTEGER ARRAY FOR WORKING SPACE IN PAVING - DIMENSIONED */ /* TO (NPRM) - THIS BECOMES THE NPERIM ARRAY */ /* IWORK6 = INTEGER ARRAY FOR WORKING SPACE IN PAVING - DIMENSIONED */ /* TO (MXND * 4) - THIS BECOMES THE LXK ARRAY */ /* IWORK7 = INTEGER ARRAY FOR WORKING SPACE IN PAVING - DIMENSIONED */ /* TO (MXND * 6) - THIS BECOMES THE KXL ARRAY */ /* IWORK8 = INTEGER ARRAY FOR WORKING SPACE IN PAVING - DIMENSIONED */ /* TO (MXND * 6) - THIS BECOMES THE NXL ARRAY */ /* IWORK9 = INTEGER ARRAY FOR WORKING SPACE IN PAVING - DIMENSIONED */ /* TO (MXND * 4) - THIS BECOMES THE LXN ARRAY */ /* IWORK10 = INTEGER ARRAY FOR WORKING SPACE IN PAVING - DIMENSIONED */ /* TO (MXND) - THIS BECOMES THE NUID ARRAY */ /* IDUM1 = A DUMMY INTEGER PARAMETER NEEDED BY FASTQ - THIS BECOMES */ /* IAVAIL */ /* IDUM2 = A DUMMY INTEGER PARAMETER NEEDED BY FASTQ - THIS BECOMES */ /* NAVAIL */ /* GRAPH = .TRUE. IF PLOTTING AT EACH STAGE IS DESIRED */ /* TIMER = .TRUE. IF A TIMING REPORT IS DESIRED */ /* VIDEO = .TRUE. IF A VIDEO ANIMATION SEQUENCE PLOT IS DESIRED */ /* DEFSIZ = THE DEFAULT SIZE OF THE ELEMENTS IN THIS REGION */ /* (SET IT TO ZERO IF YOU DON'T KNOW WHAT ELSE TO DO.) */ /* SIZEIT = .TRUE. IF A SIZING FUNCTION IS TO BE USED WITH PAVING */ /* DEV1 = A CHARACTER VARIABLE OF LENGTH 3 DESCRIBING THE */ /* PLOTTING DEVICE BEING USED. */ /* KREG = THE REGION NUMBER BEING PROCESSED (FOR PLOTTING ID) */ /* BATCH = .TRUE. IF THE PROGRAM IS BEING RUN WITHOUT */ /* GRAPHICS CAPABILITIES */ /* NOROOM = .TRUE. IF ARRAY SIZES BUILT ACCORDING TO MAXND ARE */ /* EXCEEDED (MORE SPACE IS NEEDED) */ /* ERR = .TRUE. IF AN ERROR OCCURS DURING PAVING OR IF NOROOM */ /* IS .TRUE. */ /* AMESUR = THE NODAL ERROR MEASURE VARIABLE (USED IN ADAPTIVE MESHING) */ /* XNOLD = THE OLD XN ARRAY FOR THE OLD MESH (USED IN ADAPTIVE MESHING) */ /* YNOLD = THE OLD YN ARRAY FOR THE OLD MESH (USED IN ADAPTIVE MESHING) */ /* NXKOLD = THE OLD CONNECTIVITY ARRAY OF THE OLD MESH */ /* (USED IN ADAPTIVE MESHING) */ /* MMPOLD = THE OLD MATERIAL MAP ARRAY (USED IN ADAPTIVE MESHING) */ /* LINKEG = THE LINKING ARRAY MAPPING ELEMENTS TO A SEARCH GRID */ /* LISTEG = THE LIST OF ELEMENT THAT THE LINK POINTS TO */ /* MLINK = THE MAXIMUM SPACE NEEDED FOR THE SEARCH GRID LINK (LINKEG) */ /* NPROLD = THE NUMBER OF PROCESSED REGIONS IN THE OLD MESH */ /* NPNOLD = THE NUMBER OF PROCESSED NODES IN THE OLD MESH */ /* NPEOLD = THE NUMBER OF PROCESSED ELEMENTS IN THE OLD MESH */ /* NNXK = THE NUMBER OF NODES PER ELEMENT IN THE OLD MESH */ /* REMESH = .TRUE. IF AN ADAPTIVE MESHING IS REQUESTED */ /* REXMIN = MIN X FOR THE OLD MESH */ /* REXMAX = MAX X FOR THE OLD MESH */ /* REYMIN = MIN Y FOR THE OLD MESH */ /* REYMAX = MAX Y FOR THE OLD MESH */ /* IDIVIS = NUMBER OF DIVISIONS IN THE SEARCH GRID LINK */ /* *********************************************************************** */ /* INTERNAL VARIABLES: */ /* ANGLE = ARRAY OF REALS FOR STORING BOUNDARY NODE ANGLES. */ /* BNSIZE = ARRAY OF REALS FOR STORING ELEMENT SIZE PROPAGATION INFO. */ /* LNODES = ARRAY OF INTEGERS FOR STORING BOUNDARY NODE INFORMATION. */ /* IN THE LNODES ARRAY, */ /* THE CORNER STATUS IS STORED IN LNODES (1, N1): */ /* 0 = NOT DECIDED */ /* 1 = ROW END */ /* 3 = ROW SIDE */ /* 5 = ROW CORNER */ /* 7 = ROW REVERSAL */ /* THE PRECEDING NODE IN LNODES (2, N1), */ /* THE NEXT NODE IN LNODES (3, N1), */ /* THE INTERIOR/EXTERIOR STATUS OF NODE IS IN LNODES (4, N1). */ /* 1 = EXTERIOR OR ON THE BOUNDARY OF THE MESH */ /* (NEGATED FOR SMOOTHING) */ /* 2 = INTERIOR TO THE MESH (NEGATED FOR SMOOTHING) */ /* THE NEXT COUNTERCLOCKWISE LINE IS STORED IN LNODES (5, N1). */ /* THE ANGLE STATUS OF LNODES IS STORED IN (6, N1), */ /* 1 = ROW END ONLY */ /* 2 = ROW END OR SIDE */ /* 3 = ROW SIDE ONLY */ /* 4 = ROW SIDE OR ROW CORNER */ /* 5 = ROW CORNER ONLY */ /* 6 = ROW CORNER OR REVERSAL */ /* 7 = ROW REVERSAL ONLY */ /* THE NUMBER OF NODES TO THE NEXT CORNER IS STORED IN (7, N1). */ /* THE DEPTH OF THE ROW OF THIS NODE IS STORED IN (8, N1) */ /* LINKPR = ARRAY FOR STORING LINKS TO PERIMETERS. */ /* LXK = LINES PER ELEMENT */ /* KXL = ELEMENTS PER LINE */ /* NXL = NODES PER LINE */ /* LXN = LINES PER NODE */ /* NOTE: */ /* FOR *XN TABLES A NEGATIVE FLAG IN THE FOURTH COLUMN MEANS */ /* GO TO THAT ROW FOR A CONTINUATION OF THE LIST. IN THAT ROW */ /* THE FIRST ELEMENT WILL BE NEGATED TO INDICATE THAT THIS IS */ /* A CONTINUATION ROW. */ /* A NEGATIVE FLAG IN THE SECOND COLUMN OF THE LXN ARRAY MEANS */ /* THAT THIS NODE IS AN EXTERIOR BOUNDARY NODE. */ /* *********************************************************************** */ /* MXPICK MUST BE SET AT (2 ** MXCORN) */ /* Parameter adjustments */ --lperim; --nperim; linkpr -= 4; --numper; --iptper; --nuid; lxn -= 5; nxl -= 3; kxl -= 3; lxk -= 5; lnodes_dim1 = *mln; lnodes_offset = 1 + lnodes_dim1; lnodes -= lnodes_offset; bnsize -= 3; --angle; inxe -= 3; iexk -= 5; --zn; --yn; --xn; linkeg -= 3; mmpold -= 4; --bmesur; --ynold; --xnold; --listeg; --amesur; nxkold_dim1 = *nnxk; nxkold_offset = 1 + nxkold_dim1; nxkold -= nxkold_offset; /* Function Body */ if (*remesh) { *sizeit = TRUE_; } timing_1.timea = (float)0.; timing_1.timep = (float)0.; timing_1.timec = (float)0.; timing_1.timepc = (float)0.; timing_1.timeaj = (float)0.; timing_1.times = (float)0.; getime_(&time1); *err = FALSE_; done = FALSE_; /* ZERO ALL THE LINK ARRAYS */ i__1 = *mxnd; for (i__ = 1; i__ <= i__1; ++i__) { for (j = 1; j <= 4; ++j) { lxk[j + (i__ << 2)] = 0; lxn[j + (i__ << 2)] = 0; /* L100: */ } /* L110: */ } i__1 = *mxnd; for (i__ = *nnn + 1; i__ <= i__1; ++i__) { nuid[i__] = 0; /* L120: */ } i__1 = *mxnd * 3; for (i__ = 1; i__ <= i__1; ++i__) { for (j = 1; j <= 2; ++j) { kxl[j + (i__ << 1)] = 0; nxl[j + (i__ << 1)] = 0; /* L130: */ } /* L140: */ } /* ZERO THE LOOP COUNTING AND CONNECTING ARRAYS */ for (i__ = 1; i__ <= 20; ++i__) { nloop[i__ - 1] = 0; nextn1[i__ - 1] = 0; /* L150: */ } i__1 = *nprm; for (i__ = 1; i__ <= i__1; ++i__) { linkpr[i__ * 3 + 1] = 0; linkpr[i__ * 3 + 2] = 0; linkpr[i__ * 3 + 3] = 0; /* L160: */ } /* FIND THE EXTREMES OF THE PERIMETERS */ xmin = xn[iptper[1]]; xmax = xn[iptper[1]]; ymin = yn[iptper[1]]; ymax = yn[iptper[1]]; zmin = zn[iptper[1]]; zmax = zn[iptper[1]]; i__1 = *nprm; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = iptper[i__] + numper[i__] - 1; for (j = iptper[i__]; j <= i__2; ++j) { node1 = lperim[j]; /* Computing MIN */ r__1 = xn[node1]; xmin = dmin(r__1,xmin); /* Computing MAX */ r__1 = xn[node1]; xmax = dmax(r__1,xmax); /* Computing MIN */ r__1 = yn[node1]; ymin = dmin(r__1,ymin); /* Computing MAX */ r__1 = yn[node1]; ymax = dmax(r__1,ymax); /* Computing MIN */ r__1 = zn[node1]; zmin = dmin(r__1,zmin); /* Computing MAX */ r__1 = zn[node1]; zmax = dmax(r__1,zmax); /* L170: */ } /* L180: */ } /* LINK ALL THE NODES IN THE ORIGINAL PERIMETERS TOGETHER */ i__1 = *nprm; for (i__ = 1; i__ <= i__1; ++i__) { periml_(nbnode, mxnd, &numper[i__], &iptper[i__], mln, &xn[1], &yn[1], &zn[1], &lxk[5], &kxl[3], &nxl[3], &lxn[5], &angle[1], & bnsize[3], &lnodes[lnodes_offset], &lperim[1], lll, &lllold, & xmin, &xmax, &ymin, &ymax, &zmin, &zmax, dev1, kreg, err, ( ftnlen)3); if (*err) { goto L310; } linkpr[i__ * 3 + 1] = lperim[iptper[i__]]; if (i__ > 1) { linkpr[(i__ - 1) * 3 + 2] = i__; linkpr[i__ * 3 + 2] = 1; } else { linkpr[i__ * 3 + 2] = 0; } linkpr[i__ * 3 + 3] = numper[i__]; nperim[1] = numper[i__]; /* L190: */ } itnper = *nbnode; /* LINK UP THE REST OF THE LXN ARRAY */ nnnold = *nnn; lllold = *lll; *iavail = *nnn + 1; *navail = *mxnd - *nnn; i__1 = *mxnd; for (i__ = *iavail; i__ <= i__1; ++i__) { lxn[(i__ << 2) + 1] = 0; lxn[(i__ << 2) + 2] = 0; lxn[(i__ << 2) + 3] = 0; lxn[(i__ << 2) + 4] = i__ + 1; /* L200: */ } /* PLOT THE INITIAL BOUNDARIES */ if (*graph) { rplotl_(mxnd, &xn[1], &yn[1], &zn[1], &nxl[3], &xmin, &xmax, &ymin, & ymax, &zmin, &zmax, lll, dev1, kreg, (ftnlen)3); } xmin1 = xmin; xmax1 = xmax; ymin1 = ymin; ymax1 = ymax; zmin1 = zmin; zmax1 = zmax; /* CHECK INPUT FOR ODDNESS */ if (itnper / 2 << 1 != itnper) { mesage_("IN PAVING, NO. OF PERIMETER NODES IS ODD", (ftnlen)40); *err = TRUE_; goto L310; } /* NOW BEGIN TO LOOP THROUGH THE INTERIOR NODE LIST */ /* FILLING ROWS WITH ELEMENTS */ n1 = linkpr[4]; n0 = lnodes[n1 * lnodes_dim1 + 2]; kloop = 1; kperim = 1; nloop[0] = numper[1]; L210: /* SEE IF IT IS TIME TO SWITCH TO THE NEXT PERIMETER */ /* BY WHETHER THE CURRENT N0 IS INTERIOR OR NOT */ if ((i__1 = lnodes[n0 * lnodes_dim1 + 4], abs(i__1)) == 2) { if (linkpr[kperim * 3 + 2] != 0) { linkpr[kperim * 3 + 3] = nloop[0]; linkpr[kperim * 3 + 1] = n1; kperim = linkpr[kperim * 3 + 2]; n1 = linkpr[kperim * 3 + 1]; nloop[0] = linkpr[kperim * 3 + 3]; n0 = lnodes[n1 * lnodes_dim1 + 2]; } else { n0 = lnodes[n1 * lnodes_dim1 + 2]; } } /* NOW GET THE BEST CORNERS FOR THE NEXT ROW */ getrow_(mxnd, &c__10, &c__1024, mln, &nuid[1], &lxk[5], &kxl[3], &nxl[3], &lxn[5], &lnodes[lnodes_offset], &ncorn, lcorn, &bnsize[3], & angle[1], &xn[1], &yn[1], &zn[1], icomb, itype, nloop, &n1, &nend, iavail, navail, lll, kkk, nnn, graph, video, &xmin, &xmax, &ymin, &ymax, &zmin, &zmax, dev1, kreg, sizeit, &linkpr[kperim * 3 + 2], noroom, err, (ftnlen)3); if (*noroom || *err) { goto L310; } /* CHECK TO SEE IF WE ARE DONE WITH ONLY A QUAD LEFT */ /* (AND THAT THE LOOP IS NOT AN INTERIOR HOLE) */ if (nloop[0] == 4 && linkpr[kperim * 3 + 2] == 0) { close4_(mxnd, mln, &lxk[5], &kxl[3], &nxl[3], &lxn[5], &lnodes[ lnodes_offset], &lnodes[n1 * lnodes_dim1 + 2], &n1, &lnodes[ n1 * lnodes_dim1 + 3], &lnodes[lnodes[n1 * lnodes_dim1 + 3] * lnodes_dim1 + 3], kkk, err); if (*err) { goto L310; } filsmo_(mxnd, mln, &xn[1], &yn[1], &zn[1], &lxk[5], &kxl[3], &nxl[3], &lxn[5], lll, nnn, nnn, &lnodes[lnodes_offset], &bnsize[3], nloop, &xmin, &xmax, &ymin, &ymax, &zmin, &zmax, dev1, kreg, ( ftnlen)3); if (*graph) { rplotl_(mxnd, &xn[1], &yn[1], &zn[1], &nxl[3], &xmin, &xmax, & ymin, &ymax, &zmin, &zmax, lll, dev1, kreg, (ftnlen)3); } goto L240; /* CHECK TO SEE IF WE ARE DONE WITH ONLY 6 NODES LEFT */ } else if (nloop[0] == 6 && linkpr[kperim * 3 + 2] == 0) { close6_(mxnd, &c__10, mln, &nuid[1], &xn[1], &yn[1], &lxk[5], &kxl[3], &nxl[3], &lxn[5], &angle[1], &bnsize[3], &lnodes[ lnodes_offset], &n1, nloop, &kkkold, &lllold, &nnnold, navail, iavail, &done, &xmin, &xmax, &ymin, &ymax, dev1, lll, kkk, nnn, lcorn, &ncorn, graph, video, sizeit, noroom, err, &xnold[ 1], &ynold[1], &nxkold[nxkold_offset], &linkeg[3], &listeg[1], &bmesur[1], mlink, npnold, npeold, nnxk, remesh, rexmin, rexmax, reymin, reymax, idivis, sizmin, emax, emin, (ftnlen)3) ; if (*noroom || *err) { goto L310; } filsmo_(mxnd, mln, &xn[1], &yn[1], &zn[1], &lxk[5], &kxl[3], &nxl[3], &lxn[5], lll, nnn, nnn, &lnodes[lnodes_offset], &bnsize[3], nloop, &xmin, &xmax, &ymin, &ymax, &zmin, &zmax, dev1, kreg, ( ftnlen)3); if (*graph) { rplotl_(mxnd, &xn[1], &yn[1], &zn[1], &nxl[3], &xmin, &xmax, & ymin, &ymax, &zmin, &zmax, lll, dev1, kreg, (ftnlen)3); sflush_(); } goto L240; } /* GENERATE A NEW ROW OF ELEMENTS */ addrow_(mxnd, &c__10240, &c__20, mln, nprm, &nuid[1], &xn[1], &yn[1], &zn[ 1], &lxk[5], &kxl[3], &nxl[3], &lxn[5], &angle[1], &bnsize[3], & lnodes[lnodes_offset], &n1, &nend, nloop, nextn1, &linkpr[4], & kperim, &kkkold, &lllold, &nnnold, iavail, navail, &xmin, &xmax, & ymin, &ymax, &zmin, &zmax, dev1, lll, kkk, nnn, &nnn2, &nadj1, & nadj2, icomb, &kloop, graph, video, kreg, &done, sizeit, noroom, err, &xnold[1], &ynold[1], &nxkold[nxkold_offset], &linkeg[3], & listeg[1], &bmesur[1], mlink, npnold, npeold, nnxk, remesh, rexmin, rexmax, reymin, reymax, idivis, sizmin, emax, emin, ( ftnlen)3); if (*noroom || *err) { goto L310; } if (done) { goto L240; } /* TRY COLLAPSING CORNERS WITH SMALL ANGLES AFTER A ROW HAS BEEN */ /* COMPLETED - NOTE THAT THE ICOMB ARRAY IS SENT TO PINCH IN PLACE */ /* OF THE LCORN ARRAY FOR MORE CORNER PROCESSING CAPABILITIES */ L220: pinch_(mxnd, &c__10240, mln, &nuid[1], &xn[1], &yn[1], &zn[1], &lxk[5], & kxl[3], &nxl[3], &lxn[5], &angle[1], &lnodes[lnodes_offset], & bnsize[3], &n1, nloop, &kkkold, &lllold, &nnnold, iavail, navail, &done, &xmin, &xmax, &ymin, &ymax, &zmin, &zmax, dev1, lll, kkk, nnn, icomb, &ncorn, &nadj1, &nadj2, graph, video, kreg, noroom, err, (ftnlen)3); if (*noroom || *err) { goto L310; } if (done) { goto L240; } /* C */ /* C CHECK TO SEE IF ANY ISOLATED ELEMENTS HAVE BEEN FORMED AND */ /* C TAKE CARE OF THEM IF THEY HAVE */ /* C */ /* IF (NLOOP(1) .GT. 6) THEN */ /* CALL ISOEL (MXND, MLN, NUID, XN, YN, ZN, LXK, KXL, NXL, LXN, */ /* & LNODES, ANGLE, BNSIZE, IAVAIL, NAVAIL, LLL, KKK, NNN, N1, */ /* & NLOOP (1), XMIN, XMAX, YMIN, YMAX, ZMIN, ZMAX, DEV1, KREG, */ /* & ISOELM, GRAPH, VIDEO, NOROOM, ERR) */ /* IF ((NOROOM) .OR. (ERR)) GOTO 220 */ /* IF (ISOELM) GOTO 180 */ /* ENDIF */ /* ADJUST THE NEW ROW BY TAKING TUCKS OR INSERTING WEDGES AS NEEDED */ if (nadj1 > 0 && nadj2 > 0 && nloop[0] > 4) { adjrow_(mxnd, mln, &nuid[1], &xn[1], &yn[1], &zn[1], &lxk[5], &kxl[3], &nxl[3], &lxn[5], &angle[1], &bnsize[3], &lnodes[ lnodes_offset], nloop, iavail, navail, &xmin, &xmax, &ymin, & ymax, &zmin, &zmax, dev1, lll, kkk, nnn, &lllold, &nnnold, & n1, &nadj1, &nadj2, &nnn2, graph, video, kreg, defsiz, & adjted, noroom, err, (ftnlen)3); if (*noroom || *err) { goto L310; } if (adjted) { goto L220; } } /* CHECK TO SEE IF ANY OF THE CONCURRENT PERIMETERS OVERLAP */ if (linkpr[kperim * 3 + 2] != 0) { linkpr[kperim * 3 + 3] = nloop[0]; pcross_(mxnd, &c__10240, mln, &c__20, nprm, &nuid[1], &xn[1], &yn[1], &zn[1], &lxk[5], &kxl[3], &nxl[3], &lxn[5], &angle[1], & lnodes[lnodes_offset], &bnsize[3], &linkpr[4], &kperim, &n1, & nadj1, &nadj2, &kkkold, &lllold, &nnnold, iavail, navail, & done, &xmin, &xmax, &ymin, &ymax, &zmin, &zmax, dev1, lll, kkk, nnn, icomb, &ncorn, nloop, nextn1, &kloop, graph, video, kreg, noroom, err, (ftnlen)3); if (*noroom || *err) { goto L310; } } /* TRY COLLAPSING OVERLAPPING SIDES TO FORM TWO LOOPS OUT OF THE */ /* CURRENT SINGLE LOOP - NOTE THAT THE ICOMB ARRAY IS SENT AS */ /* WHEN CALLING PINCH IN PLACE OF THE LCORN ARRAY */ L230: if (nloop[0] > 6) { colaps_(mxnd, &c__10240, mln, &c__20, &nuid[1], &xn[1], &yn[1], &zn[1] , &lxk[5], &kxl[3], &nxl[3], &lxn[5], &angle[1], &lnodes[ lnodes_offset], &bnsize[3], &n1, &kkkold, &lllold, &nnnold, iavail, navail, &done, &xmin, &xmax, &ymin, &ymax, &zmin, & zmax, dev1, lll, kkk, nnn, icomb, &ncorn, nloop, nextn1, & kloop, graph, video, kreg, noroom, err, (ftnlen)3); if (*noroom || *err) { goto L310; } if (done) { goto L240; } } /* ADJUST THE ZOOMS TO FIT THE NEW AREA */ if (*graph || cpubrk_(&c_true)) { linkpr[kperim * 3 + 3] = nloop[0]; flmnmx_(mxnd, mln, nprm, &linkpr[4], &kperim, &lnodes[lnodes_offset], &xn[1], &yn[1], nloop, &n1, &xmin, &xmax, &ymin, &ymax, err); if (*err) { goto L310; } rplotl_(mxnd, &xn[1], &yn[1], &zn[1], &nxl[3], &xmin, &xmax, &ymin, & ymax, &zmin, &zmax, lll, dev1, kreg, (ftnlen)3); } goto L210; /* CHECK TO MAKE SURE THAT OTHER LOOPS ARE NOT REMAINING TO BE FILLED */ L240: if (kloop > 1) { n1 = nextn1[0]; i__1 = kloop - 1; for (i__ = 1; i__ <= i__1; ++i__) { nloop[i__ - 1] = nloop[i__]; nextn1[i__ - 1] = nextn1[i__]; /* L250: */ } nloop[kloop - 1] = 0; nextn1[kloop - 1] = 0; --kloop; /* ADJUST THE ZOOMS TO FIT THE NEW AREA */ if (*graph) { flmnmx_(mxnd, mln, nprm, &linkpr[4], &kperim, &lnodes[ lnodes_offset], &xn[1], &yn[1], nloop, &n1, &xmin, &xmax, &ymin, &ymax, err); if (*err) { goto L310; } rplotl_(mxnd, &xn[1], &yn[1], &zn[1], &nxl[3], &xmin, &xmax, & ymin, &ymax, &zmin, &zmax, lll, dev1, kreg, (ftnlen)3); } done = FALSE_; /* ENTER THE FILL LOOP WHERE IT CAN CHECK TO SEE IF ANY CROSSINGS */ /* ALREADY EXIST IN THIS LOOP */ goto L230; } /* THE FILL HAS BEEN COMPLETED - NOW FIX UP ANY BAD SPOTS */ i__1 = *nnn; for (i__ = 1; i__ <= i__1; ++i__) { lnodes[i__ * lnodes_dim1 + 4] = (i__2 = lnodes[i__ * lnodes_dim1 + 4], abs(i__2)); /* L260: */ } filsmo_(mxnd, mln, &xn[1], &yn[1], &zn[1], &lxk[5], &kxl[3], &nxl[3], & lxn[5], lll, nnn, nnn, &lnodes[lnodes_offset], &bnsize[3], nloop, &xmin, &xmax, &ymin, &ymax, &zmin, &zmax, dev1, kreg, (ftnlen)3); tridel_(mxnd, mln, &xn[1], &yn[1], &zn[1], &nuid[1], &lxk[5], &kxl[3], & nxl[3], &lxn[5], nnn, lll, kkk, navail, iavail, &angle[1], & lnodes[lnodes_offset], &bnsize[3], nloop, dev1, kreg, &xmin, & xmax, &ymin, &ymax, &zmin, &zmax, graph, video, noroom, err, ( ftnlen)3); if (*noroom || *err) { goto L310; } i__1 = *nnn; for (i__ = 1; i__ <= i__1; ++i__) { lnodes[i__ * lnodes_dim1 + 4] = -(i__2 = lnodes[i__ * lnodes_dim1 + 4] , abs(i__2)); /* L270: */ } filsmo_(mxnd, mln, &xn[1], &yn[1], &zn[1], &lxk[5], &kxl[3], &nxl[3], & lxn[5], lll, nnn, nnn, &lnodes[lnodes_offset], &bnsize[3], nloop, &xmin, &xmax, &ymin, &ymax, &zmin, &zmax, dev1, kreg, (ftnlen)3); /* SUCCESSFUL EXIT */ if (*graph) { rplotl_(mxnd, &xn[1], &yn[1], &zn[1], &nxl[3], &xmin1, &xmax1, &ymin1, &ymax1, &zmin1, &zmax1, lll, dev1, kreg, (ftnlen)3); } iuppr = min(*lll,*mxnd); i__1 = iuppr; for (i__ = 1; i__ <= i__1; ++i__) { for (j = 1; j <= 4; ++j) { iexk[j + (i__ << 2)] = lxk[j + (i__ << 2)]; /* L280: */ } /* L300: */ } /* Computing MIN */ i__1 = *lll, i__2 = *mxnd * 3; iuppr = min(i__1,i__2); i__1 = iuppr; for (i__ = 1; i__ <= i__1; ++i__) { for (j = 1; j <= 2; ++j) { inxe[j + (i__ << 1)] = nxl[j + (i__ << 1)]; /* L290: */ } /* L301: */ } /* EXIT WITH ERROR */ L310: if (*err && ! (*batch)) { rplotl_(mxnd, &xn[1], &yn[1], &zn[1], &nxl[3], &xmin1, &xmax1, &ymin1, &ymax1, &zmin1, &zmax1, lll, dev1, kreg, (ftnlen)3); ringbl_(); sflush_(); } if (*timer) { getime_(&time2); s_wsfe(&io___39); do_fio(&c__1, " CPU SECONDS USED: ", (ftnlen)20); r__1 = time2 - time1; do_fio(&c__1, (char *)&r__1, (ftnlen)sizeof(real)); e_wsfe(); s_wsfe(&io___40); do_fio(&c__1, " ADDROW: ", (ftnlen)20); do_fio(&c__1, (char *)&timing_1.timea, (ftnlen)sizeof(real)); e_wsfe(); s_wsfe(&io___41); do_fio(&c__1, " PINCH: ", (ftnlen)20); do_fio(&c__1, (char *)&timing_1.timep, (ftnlen)sizeof(real)); e_wsfe(); s_wsfe(&io___42); do_fio(&c__1, " COLAPS: ", (ftnlen)20); do_fio(&c__1, (char *)&timing_1.timec, (ftnlen)sizeof(real)); e_wsfe(); s_wsfe(&io___43); do_fio(&c__1, " PCROSS: ", (ftnlen)20); do_fio(&c__1, (char *)&timing_1.timepc, (ftnlen)sizeof(real)); e_wsfe(); s_wsfe(&io___44); do_fio(&c__1, " ADJROW: ", (ftnlen)20); do_fio(&c__1, (char *)&timing_1.timeaj, (ftnlen)sizeof(real)); e_wsfe(); s_wsfe(&io___45); do_fio(&c__1, " SMOOTH: ", (ftnlen)20); do_fio(&c__1, (char *)&timing_1.times, (ftnlen)sizeof(real)); e_wsfe(); s_wsfe(&io___46); do_fio(&c__1, " MISCELLANEOUS: ", (ftnlen)20); r__1 = time2 - time1 - timing_1.timea - timing_1.timep - timing_1.timec - timing_1.timepc - timing_1.timeaj - timing_1.times; do_fio(&c__1, (char *)&r__1, (ftnlen)sizeof(real)); e_wsfe(); s_wsfe(&io___47); do_fio(&c__1, " % SMOOTH: ", (ftnlen)20); r__1 = timing_1.times * (float)100. / (time2 - time1); do_fio(&c__1, (char *)&r__1, (ftnlen)sizeof(real)); e_wsfe(); } return 0; } /* paving_ */ #ifdef __cplusplus } #endif
C
CL
5468f8870e5f112ff73e21b13af2ca38fc811323500449e2666baf112dab2cc6
/* From: CFE Id: cfe_api.c,v 1.16 2002/07/09 23:29:11 cgd Exp $ */ /* * Copyright 2000, 2001, 2002 * Broadcom Corporation. All rights reserved. * * This software is furnished under license and may be used and copied only * in accordance with the following terms and conditions. Subject to these * conditions, you may download, copy, install, use, modify and distribute * modified or unmodified copies of this software in source and/or binary * form. No title or ownership is transferred hereby. * * 1) Any source code used, modified or distributed must reproduce and * retain this copyright notice and list of conditions as they appear in * the source file. * * 2) No right is granted to use any trade name, trademark, or logo of * Broadcom Corporation. The "Broadcom Corporation" name may not be * used to endorse or promote products derived from this software * without the prior written permission of Broadcom Corporation. * * 3) THIS SOFTWARE IS PROVIDED "AS-IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING BUT NOT LIMITED TO, ANY IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR * NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL BROADCOM BE LIABLE * FOR ANY DAMAGES WHATSOEVER, AND IN PARTICULAR, BROADCOM SHALL NOT BE * LIABLE FOR 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), EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* ********************************************************************* * * Broadcom Common Firmware Environment (CFE) * * Device Function stubs File: cfe_api.c * * This module contains device function stubs (small routines to * call the standard "iocb" interface entry point to CFE). * There should be one routine here per iocb function call. * * Authors: Mitch Lichtenberg, Chris Demetriou * ********************************************************************* */ #include "cfe_api.h" #include "cfe_api_int.h" /* Cast from a native pointer to a cfe_xptr_t and back. */ #define XPTR_FROM_NATIVE(n) ((cfe_xptr_t) (intptr_t) (n)) #define NATIVE_FROM_XPTR(x) ((void *) (intptr_t) (x)) #ifdef CFE_API_IMPL_NAMESPACE #define cfe_iocb_dispatch(a) __cfe_iocb_dispatch(a) #endif int cfe_iocb_dispatch(cfe_xiocb_t *xiocb); #if defined(CFE_API_common) || defined(CFE_API_ALL) /* * Declare the dispatch function with args of "intptr_t". * This makes sure whatever model we're compiling in * puts the pointers in a single register. For example, * combining -mlong64 and -mips1 or -mips2 would lead to * trouble, since the handle and IOCB pointer will be * passed in two registers each, and CFE expects one. */ static int (*cfe_dispfunc)(intptr_t handle, intptr_t xiocb) = 0; static cfe_xuint_t cfe_handle = 0; int cfe_init(cfe_xuint_t handle, cfe_xuint_t ept) { cfe_dispfunc = NATIVE_FROM_XPTR(ept); cfe_handle = handle; return 0; } int cfe_iocb_dispatch(cfe_xiocb_t *xiocb) { if (!cfe_dispfunc) return -1; return (*cfe_dispfunc)((intptr_t)cfe_handle, (intptr_t)xiocb); } #endif /* CFE_API_common || CFE_API_ALL */ #if defined(CFE_API_close) || defined(CFE_API_ALL) int cfe_close(int handle) { cfe_xiocb_t xiocb; xiocb.xiocb_fcode = CFE_CMD_DEV_CLOSE; xiocb.xiocb_status = 0; xiocb.xiocb_handle = handle; xiocb.xiocb_flags = 0; xiocb.xiocb_psize = 0; cfe_iocb_dispatch(&xiocb); return xiocb.xiocb_status; } #endif /* CFE_API_close || CFE_API_ALL */ #if defined(CFE_API_cpu_start) || defined(CFE_API_ALL) int cfe_cpu_start(int cpu, void (*fn)(void), long sp, long gp, long a1) { cfe_xiocb_t xiocb; xiocb.xiocb_fcode = CFE_CMD_FW_CPUCTL; xiocb.xiocb_status = 0; xiocb.xiocb_handle = 0; xiocb.xiocb_flags = 0; xiocb.xiocb_psize = sizeof(xiocb_cpuctl_t); xiocb.plist.xiocb_cpuctl.cpu_number = cpu; xiocb.plist.xiocb_cpuctl.cpu_command = CFE_CPU_CMD_START; xiocb.plist.xiocb_cpuctl.gp_val = gp; xiocb.plist.xiocb_cpuctl.sp_val = sp; xiocb.plist.xiocb_cpuctl.a1_val = a1; xiocb.plist.xiocb_cpuctl.start_addr = (long)fn; cfe_iocb_dispatch(&xiocb); return xiocb.xiocb_status; } #endif /* CFE_API_cpu_start || CFE_API_ALL */ #if defined(CFE_API_cpu_stop) || defined(CFE_API_ALL) int cfe_cpu_stop(int cpu) { cfe_xiocb_t xiocb; xiocb.xiocb_fcode = CFE_CMD_FW_CPUCTL; xiocb.xiocb_status = 0; xiocb.xiocb_handle = 0; xiocb.xiocb_flags = 0; xiocb.xiocb_psize = sizeof(xiocb_cpuctl_t); xiocb.plist.xiocb_cpuctl.cpu_number = cpu; xiocb.plist.xiocb_cpuctl.cpu_command = CFE_CPU_CMD_STOP; cfe_iocb_dispatch(&xiocb); return xiocb.xiocb_status; } #endif /* CFE_API_cpu_stop || CFE_API_ALL */ #if defined(CFE_API_enumenv) || defined(CFE_API_ALL) int cfe_enumenv(int idx, char *name, int namelen, char *val, int vallen) { cfe_xiocb_t xiocb; xiocb.xiocb_fcode = CFE_CMD_ENV_SET; xiocb.xiocb_status = 0; xiocb.xiocb_handle = 0; xiocb.xiocb_flags = 0; xiocb.xiocb_psize = sizeof(xiocb_envbuf_t); xiocb.plist.xiocb_envbuf.enum_idx = idx; xiocb.plist.xiocb_envbuf.name_ptr = XPTR_FROM_NATIVE(name); xiocb.plist.xiocb_envbuf.name_length = namelen; xiocb.plist.xiocb_envbuf.val_ptr = XPTR_FROM_NATIVE(val); xiocb.plist.xiocb_envbuf.val_length = vallen; cfe_iocb_dispatch(&xiocb); return xiocb.xiocb_status; } #endif /* CFE_API_enumenv || CFE_API_ALL */ #if defined(CFE_API_enummem) || defined(CFE_API_ALL) int cfe_enummem(int idx, int flags, cfe_xuint_t *start, cfe_xuint_t *length, cfe_xuint_t *type) { cfe_xiocb_t xiocb; xiocb.xiocb_fcode = CFE_CMD_FW_MEMENUM; xiocb.xiocb_status = 0; xiocb.xiocb_handle = 0; xiocb.xiocb_flags = flags; xiocb.xiocb_psize = sizeof(xiocb_meminfo_t); xiocb.plist.xiocb_meminfo.mi_idx = idx; cfe_iocb_dispatch(&xiocb); if (xiocb.xiocb_status < 0) return xiocb.xiocb_status; *start = xiocb.plist.xiocb_meminfo.mi_addr; *length = xiocb.plist.xiocb_meminfo.mi_size; *type = xiocb.plist.xiocb_meminfo.mi_type; return 0; } #endif /* CFE_API_enummem || CFE_API_ALL */ #if defined(CFE_API_exit) || defined(CFE_API_ALL) int cfe_exit(int warm, int status) { cfe_xiocb_t xiocb; xiocb.xiocb_fcode = CFE_CMD_FW_RESTART; xiocb.xiocb_status = 0; xiocb.xiocb_handle = 0; xiocb.xiocb_flags = warm ? CFE_FLG_WARMSTART : 0; xiocb.xiocb_psize = sizeof(xiocb_exitstat_t); xiocb.plist.xiocb_exitstat.status = status; cfe_iocb_dispatch(&xiocb); return xiocb.xiocb_status; } #endif /* CFE_API_exit || CFE_API_ALL */ #if defined(CFE_API_flushcache) || defined(CFE_API_ALL) int cfe_flushcache(int flg) { cfe_xiocb_t xiocb; xiocb.xiocb_fcode = CFE_CMD_FW_FLUSHCACHE; xiocb.xiocb_status = 0; xiocb.xiocb_handle = 0; xiocb.xiocb_flags = flg; xiocb.xiocb_psize = 0; cfe_iocb_dispatch(&xiocb); return xiocb.xiocb_status; } #endif /* CFE_API_flushcache || CFE_API_ALL */ #if defined(CFE_API_getdevinfo) || defined(CFE_API_ALL) int cfe_getdevinfo(char *name) { cfe_xiocb_t xiocb; xiocb.xiocb_fcode = CFE_CMD_DEV_GETINFO; xiocb.xiocb_status = 0; xiocb.xiocb_handle = 0; xiocb.xiocb_flags = 0; xiocb.xiocb_psize = sizeof(xiocb_buffer_t); xiocb.plist.xiocb_buffer.buf_offset = 0; xiocb.plist.xiocb_buffer.buf_ptr = XPTR_FROM_NATIVE(name); xiocb.plist.xiocb_buffer.buf_length = cfe_strlen(name); cfe_iocb_dispatch(&xiocb); if (xiocb.xiocb_status < 0) return xiocb.xiocb_status; return xiocb.plist.xiocb_buffer.buf_devflags; } #endif /* CFE_API_getdevinfo || CFE_API_ALL */ #if defined(CFE_API_getenv) || defined(CFE_API_ALL) int cfe_getenv(char *name, char *dest, int destlen) { cfe_xiocb_t xiocb; *dest = 0; xiocb.xiocb_fcode = CFE_CMD_ENV_GET; xiocb.xiocb_status = 0; xiocb.xiocb_handle = 0; xiocb.xiocb_flags = 0; xiocb.xiocb_psize = sizeof(xiocb_envbuf_t); xiocb.plist.xiocb_envbuf.enum_idx = 0; xiocb.plist.xiocb_envbuf.name_ptr = XPTR_FROM_NATIVE(name); xiocb.plist.xiocb_envbuf.name_length = cfe_strlen(name); xiocb.plist.xiocb_envbuf.val_ptr = XPTR_FROM_NATIVE(dest); xiocb.plist.xiocb_envbuf.val_length = destlen; cfe_iocb_dispatch(&xiocb); return xiocb.xiocb_status; } #endif /* CFE_API_getenv || CFE_API_ALL */ #if defined(CFE_API_getfwinfo) || defined(CFE_API_ALL) int cfe_getfwinfo(cfe_fwinfo_t *info) { cfe_xiocb_t xiocb; xiocb.xiocb_fcode = CFE_CMD_FW_GETINFO; xiocb.xiocb_status = 0; xiocb.xiocb_handle = 0; xiocb.xiocb_flags = 0; xiocb.xiocb_psize = sizeof(xiocb_fwinfo_t); cfe_iocb_dispatch(&xiocb); if (xiocb.xiocb_status < 0) return xiocb.xiocb_status; info->fwi_version = xiocb.plist.xiocb_fwinfo.fwi_version; info->fwi_totalmem = xiocb.plist.xiocb_fwinfo.fwi_totalmem; info->fwi_flags = xiocb.plist.xiocb_fwinfo.fwi_flags; info->fwi_boardid = xiocb.plist.xiocb_fwinfo.fwi_boardid; info->fwi_bootarea_va = xiocb.plist.xiocb_fwinfo.fwi_bootarea_va; info->fwi_bootarea_pa = xiocb.plist.xiocb_fwinfo.fwi_bootarea_pa; info->fwi_bootarea_size = xiocb.plist.xiocb_fwinfo.fwi_bootarea_size; #if 0 info->fwi_reserved1 = xiocb.plist.xiocb_fwinfo.fwi_reserved1; info->fwi_reserved2 = xiocb.plist.xiocb_fwinfo.fwi_reserved2; info->fwi_reserved3 = xiocb.plist.xiocb_fwinfo.fwi_reserved3; #endif return 0; } #endif /* CFE_API_getfwinfo || CFE_API_ALL */ #if defined(CFE_API_getstdhandle) || defined(CFE_API_ALL) int cfe_getstdhandle(int flg) { cfe_xiocb_t xiocb; xiocb.xiocb_fcode = CFE_CMD_DEV_GETHANDLE; xiocb.xiocb_status = 0; xiocb.xiocb_handle = 0; xiocb.xiocb_flags = flg; xiocb.xiocb_psize = 0; cfe_iocb_dispatch(&xiocb); if (xiocb.xiocb_status < 0) return xiocb.xiocb_status; return xiocb.xiocb_handle; } #endif /* CFE_API_getstdhandle || CFE_API_ALL */ #if defined(CFE_API_getticks) || defined(CFE_API_ALL) int64_t #ifdef CFE_API_IMPL_NAMESPACE __cfe_getticks(void) #else cfe_getticks(void) #endif { cfe_xiocb_t xiocb; xiocb.xiocb_fcode = CFE_CMD_FW_GETTIME; xiocb.xiocb_status = 0; xiocb.xiocb_handle = 0; xiocb.xiocb_flags = 0; xiocb.xiocb_psize = sizeof(xiocb_time_t); xiocb.plist.xiocb_time.ticks = 0; cfe_iocb_dispatch(&xiocb); return xiocb.plist.xiocb_time.ticks; } #endif /* CFE_API_getticks || CFE_API_ALL */ #if defined(CFE_API_inpstat) || defined(CFE_API_ALL) int cfe_inpstat(int handle) { cfe_xiocb_t xiocb; xiocb.xiocb_fcode = CFE_CMD_DEV_INPSTAT; xiocb.xiocb_status = 0; xiocb.xiocb_handle = handle; xiocb.xiocb_flags = 0; xiocb.xiocb_psize = sizeof(xiocb_inpstat_t); xiocb.plist.xiocb_inpstat.inp_status = 0; cfe_iocb_dispatch(&xiocb); if (xiocb.xiocb_status < 0) return xiocb.xiocb_status; return xiocb.plist.xiocb_inpstat.inp_status; } #endif /* CFE_API_inpstat || CFE_API_ALL */ #if defined(CFE_API_ioctl) || defined(CFE_API_ALL) int cfe_ioctl(int handle, unsigned int ioctlnum, unsigned char *buffer, int length, int *retlen, cfe_xuint_t offset) { cfe_xiocb_t xiocb; xiocb.xiocb_fcode = CFE_CMD_DEV_IOCTL; xiocb.xiocb_status = 0; xiocb.xiocb_handle = handle; xiocb.xiocb_flags = 0; xiocb.xiocb_psize = sizeof(xiocb_buffer_t); xiocb.plist.xiocb_buffer.buf_offset = offset; xiocb.plist.xiocb_buffer.buf_ioctlcmd = ioctlnum; xiocb.plist.xiocb_buffer.buf_ptr = XPTR_FROM_NATIVE(buffer); xiocb.plist.xiocb_buffer.buf_length = length; cfe_iocb_dispatch(&xiocb); if (retlen) *retlen = xiocb.plist.xiocb_buffer.buf_retlen; return xiocb.xiocb_status; } #endif /* CFE_API_ioctl || CFE_API_ALL */ #if defined(CFE_API_open) || defined(CFE_API_ALL) int cfe_open(char *name) { cfe_xiocb_t xiocb; xiocb.xiocb_fcode = CFE_CMD_DEV_OPEN; xiocb.xiocb_status = 0; xiocb.xiocb_handle = 0; xiocb.xiocb_flags = 0; xiocb.xiocb_psize = sizeof(xiocb_buffer_t); xiocb.plist.xiocb_buffer.buf_offset = 0; xiocb.plist.xiocb_buffer.buf_ptr = XPTR_FROM_NATIVE(name); xiocb.plist.xiocb_buffer.buf_length = cfe_strlen(name); cfe_iocb_dispatch(&xiocb); if (xiocb.xiocb_status < 0) return xiocb.xiocb_status; return xiocb.xiocb_handle; } #endif /* CFE_API_open || CFE_API_ALL */ #if defined(CFE_API_read) || defined(CFE_API_ALL) int cfe_read(int handle, unsigned char *buffer, int length) { return cfe_readblk(handle, 0, buffer, length); } #endif /* CFE_API_read || CFE_API_ALL */ #if defined(CFE_API_readblk) || defined(CFE_API_ALL) int cfe_readblk(int handle, cfe_xint_t offset, unsigned char *buffer, int length) { cfe_xiocb_t xiocb; xiocb.xiocb_fcode = CFE_CMD_DEV_READ; xiocb.xiocb_status = 0; xiocb.xiocb_handle = handle; xiocb.xiocb_flags = 0; xiocb.xiocb_psize = sizeof(xiocb_buffer_t); xiocb.plist.xiocb_buffer.buf_offset = offset; xiocb.plist.xiocb_buffer.buf_ptr = XPTR_FROM_NATIVE(buffer); xiocb.plist.xiocb_buffer.buf_length = length; cfe_iocb_dispatch(&xiocb); if (xiocb.xiocb_status < 0) return xiocb.xiocb_status; return xiocb.plist.xiocb_buffer.buf_retlen; } #endif /* CFE_API_readblk || CFE_API_ALL */ #if defined(CFE_API_setenv) || defined(CFE_API_ALL) int cfe_setenv(char *name, char *val) { cfe_xiocb_t xiocb; xiocb.xiocb_fcode = CFE_CMD_ENV_SET; xiocb.xiocb_status = 0; xiocb.xiocb_handle = 0; xiocb.xiocb_flags = 0; xiocb.xiocb_psize = sizeof(xiocb_envbuf_t); xiocb.plist.xiocb_envbuf.enum_idx = 0; xiocb.plist.xiocb_envbuf.name_ptr = XPTR_FROM_NATIVE(name); xiocb.plist.xiocb_envbuf.name_length = cfe_strlen(name); xiocb.plist.xiocb_envbuf.val_ptr = XPTR_FROM_NATIVE(val); xiocb.plist.xiocb_envbuf.val_length = cfe_strlen(val); cfe_iocb_dispatch(&xiocb); return xiocb.xiocb_status; } #endif /* CFE_API_setenv || CFE_API_ALL */ #if (defined(CFE_API_strlen) || defined(CFE_API_ALL)) \ && !defined(CFE_API_STRLEN_CUSTOM) int cfe_strlen(char *name) { int count = 0; while (*name++) count++; return count; } #endif /* CFE_API_strlen || CFE_API_ALL */ #if defined(CFE_API_write) || defined(CFE_API_ALL) int cfe_write(int handle, unsigned char *buffer, int length) { return cfe_writeblk(handle, 0, buffer, length); } #endif /* CFE_API_write || CFE_API_ALL */ #if defined(CFE_API_writeblk) || defined(CFE_API_ALL) int cfe_writeblk(int handle, cfe_xint_t offset, unsigned char *buffer, int length) { cfe_xiocb_t xiocb; xiocb.xiocb_fcode = CFE_CMD_DEV_WRITE; xiocb.xiocb_status = 0; xiocb.xiocb_handle = handle; xiocb.xiocb_flags = 0; xiocb.xiocb_psize = sizeof(xiocb_buffer_t); xiocb.plist.xiocb_buffer.buf_offset = offset; xiocb.plist.xiocb_buffer.buf_ptr = XPTR_FROM_NATIVE(buffer); xiocb.plist.xiocb_buffer.buf_length = length; cfe_iocb_dispatch(&xiocb); if (xiocb.xiocb_status < 0) return xiocb.xiocb_status; return xiocb.plist.xiocb_buffer.buf_retlen; } #endif /* CFE_API_writeblk || CFE_API_ALL */
C
CL
d33c763472e0337a40b58762412a209bb91bea36d1bfad79e2bc3ea608f3473e
/*********************************************************** * Name of program: * Authors: Benjamin Mankowitz Ari Roffe * Description: FIXME: Need a descr **********************************************************/ /* These are the included libraries. You may need to add more. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdint.h> #include <unistd.h> #include <dirent.h> #include <arpa/inet.h> #include <ctype.h> #include <stdbool.h> /* Put any symbolic constants (defines) here */ #define True 1 /* C has no booleans! -Ben: Now it does!*/ #define False 0 #define L_ENDIAN 0 /* NOTE that fat32 is always little endian */ #define B_ENDIAN 1 /* The local OS may be big endian */ #define DEBUG 0 #define MAX_CMD 80 #define MAX_DIR 255 #define MAX_FAT 8192 #define MAX_BUF 512 #define ATTR_READ_ONLY 0x01 #define ATTR_HIDDEN 0x02 #define ATTR_SYSTEM 0x04 #define ATTR_VOLUME_ID 0x08 #define ATTR_DIRECTORY 0x10 #define ATTR_ARCHIVE 0x20 #define ATTR_DEVICE_FILE 0x40 #define EOC 0x0FFFFFF8 #define FREE 0x00000000 #define BAD_CLUSTER 0x0FFFFFF7 //image file being made global, represented by the descriptor supplied when first access in init FILE *fd; /* Register Functions and Global Variables */ uint32_t convertToLocalEndain(uint32_t original); uint32_t convertToFAT32Endian(uint32_t original); void refreshDir(uint32_t cluster); void init(char* argv); bool cd(char *newDir, bool shouldPrint); /*strDummy variable for the compiler */ char* strDummy = ""; int intDummy = 0; size_t sizeTDummy = 5; /*End of strDummy stuff */ int localEndian = -1; uint32_t *fat; uint32_t clusterSize; /** * Making the Directory struct * This is technically also a file * */ struct directory{ char DIR_Name[11];//11 bytes uint8_t DIR_Attr; //1 byte char padding[8];//8 bytes of padding uint16_t DIR_FstClusHi;//2 bytes char more_padding[4];//4 bytes padding uint16_t DIR_FstClusLo;//2 bytes uint32_t DIR_FileSize;//4 bytes //in total, 32 bytes }; struct directory dir[MAX_DIR]; struct directory stagingDir[MAX_DIR]; struct directory rootDir;//the root directory, set during init, accessed by volume (and maybe 1 more) struct directory zeroDir; /********************************************************** * HELPER FUNCTIONS * Use these for all IO operations **********************************************************/ /* * endian functions * ---------------------------- * determineLocalEndian is called during init() * Both of the converting functions take a 32-bit word and convert */ void determineLocalEndian() { int i = 1; char *p = (char *)&i; if (p[0] == 1) localEndian = L_ENDIAN; else localEndian = B_ENDIAN; } uint32_t convertToLocalEndian(uint32_t original){ if(localEndian == L_ENDIAN){ //there is nothing to do return original; } else{ //To swap endian: uint32_t b0,b1,b2,b3; uint32_t returnValue; b0 = (original & 0x000000ff) << 24u; b1 = (original & 0x0000ff00) << 8u; b2 = (original & 0x00ff0000) >> 8u; b3 = (original & 0xff000000) >> 24u; returnValue = b0 | b1 | b2 | b3; return returnValue; } } uint32_t convertToFAT32Endian(uint32_t original){ if(localEndian == L_ENDIAN){ //there is nothing to do return original; } else{ //convert from big endian to little endian //To swap endian: uint32_t b0,b1,b2,b3; uint32_t returnValue; b0 = (original & 0x000000ff) << 24u; b1 = (original & 0x0000ff00) << 8u; b2 = (original & 0x00ff0000) >> 8u; b3 = (original & 0xff000000) >> 24u; returnValue = b0 | b1 | b2 | b3; return returnValue; } } /* * init * ---------------------------- * open the file image and set it up */ /*pointers for the fread() function*/ int BPB_BytesPerSec; int BPB_SecPerClus; int BPB_RsvdSecCnt; int BPB_NumFATS; int BPB_FATSz32; int BPB_RootCluster; int first_sector_of_cluster; int bytes_for_reserved; int fat_bytes; char * dir_name; void init(char* argv){ /* Determine whether our machine is big endian or little endian */ determineLocalEndian(); /* Parse args and open our image file */ fd = fopen(argv, "r+s"); //https://www.tutorialspoint.com/c_standard_library/c_function_fopen.htm printf("%s Opened\n", argv); //fd is our pointer to the file, as a reminder if(fd == NULL){ printf("File does not exist\n"); return; } /* Parse boot sector and get information, move to here*/ fseek(fd, 0xB, SEEK_SET); //SEEK_SET is the beginning of File, skip to position 11 as per Wiki //Super helpful, https://en.wikipedia.org/wiki/Design_of_the_FAT_file_system sizeTDummy = fread(&BPB_BytesPerSec, 2, 1, fd); //one element that is 2 bytes, 2 Hex's on the HexEdit tool sizeTDummy = fread(&BPB_SecPerClus, 1, 1, fd); //starts at 0xD sizeTDummy = fread(&BPB_RsvdSecCnt, 2, 1, fd);// number of reserved sectors, aka number of sectors before "data" sectors sizeTDummy = fread(&BPB_NumFATS, 1, 1, fd); //"next line" //BPB_FATSz32 offset is 0x2C from the SEEK_SET, Kelly's slides/hints for project fseek(fd, 0x24, SEEK_SET); sizeTDummy = fread(&BPB_FATSz32, 4, 1, fd); /*Get root directory address */ fseek(fd, 0x2C, SEEK_SET); sizeTDummy = fread(&BPB_RootCluster, 4, 1, fd); bytes_for_reserved = BPB_BytesPerSec * BPB_RsvdSecCnt; fat_bytes = BPB_BytesPerSec * BPB_FATSz32 * BPB_NumFATS; //multiply how many FATS by amount of fat sectors and bytes per each sector first_sector_of_cluster = ((BPB_RootCluster - 2) * BPB_SecPerClus) + bytes_for_reserved + fat_bytes; clusterSize = BPB_BytesPerSec * BPB_SecPerClus; //set FAT table: fat = malloc(fat_bytes); fseek(fd, bytes_for_reserved, SEEK_SET); sizeTDummy = fread(fat, 4 /*bytes*/, fat_bytes/4, fd); //populate dir array refreshDir(BPB_RootCluster); //set rootDir: rootDir = dir[0]; //set zeroDir: memset(&zeroDir, 0, sizeof(struct directory)); return; } /* * freeAll * ---------------------------- * free all allocated memory */ void freeAll() { //TODO } /* * convertToShortName * ---------------------------- * Converts the given string into the appropriate short (internal) name * BUG: This is not (yet) equipped to handle filenames * that need to be truncated. EX: reallylongname.txt -> REALLY~0.txt * BUG: If called with no input, will segfault */ char* convertToShortName(char* input) { //printf("\nInside of convertToShortName"); if(input == NULL){ return input;//return original string for '.' or '..', and do nothing for null } else if(input[0] == '.' && input[1] != '.') return ". "; else if(input[0] == '.' && input[1] == '.' && input[2] != '.') return ".. "; char* baseName = calloc(sizeof(char), 12);//+1 for the null terminator char* extension = calloc(sizeof(char), 4); int i = 0;//position in input int j = 0;//position in output while(i < 8){ if(iscntrl(input[i]) || input[i] == '.'){ //the end of the string is reached before 8 characters while(j<8){ baseName[j++] = ' '; } break; } else{ baseName[i++] = toupper(input[j++]); } } j = 0; //reset the counter; while(j < 3){ i++;//i++ here to skip the '.' if it exists if(isalnum((unsigned char)input[i])){//the character is alphanumeric extension[j++] = toupper(input[i]); } else{ extension[j++] = ' '; } } strcat(baseName, extension); free(extension); return baseName; //and the extension added by strcat } /* * convertToPrettyName * ---------------------------- * Converts the given string into the appropriate external name * EX: CONST TXT -> const.txt * BUG: If called with no input, will segfault * that need to be truncated. EX: reallylongname.txt -> REALLY~0.txt */ char* convertToPrettyName(char* input) { char* name = calloc(sizeof(char), 12);//+1 for the null terminator int namePos = 0; int inputPos = 0; for(;namePos < 11;namePos++){ if(input[inputPos] != ' ' && inputPos != 8){ name[namePos]=tolower(input[inputPos++]); } else if(inputPos == 8){ if(input[9] == ' '){ inputPos=11; break; } name[namePos]='.'; name[++namePos] = tolower(input[inputPos++]); } else {//whitespace inputPos++; namePos--; } } return name; } int getCluster(struct directory thisDir){ int cluster = (thisDir.DIR_FstClusLo) +(thisDir.DIR_FstClusHi << 16); if(cluster == 0) return 2; else{ return (thisDir.DIR_FstClusLo) + (thisDir.DIR_FstClusHi << 16); } } uint32_t getOffset(struct directory thisDir){ return ((getCluster(thisDir) - 2) * BPB_SecPerClus*BPB_BytesPerSec) + (BPB_BytesPerSec * BPB_RsvdSecCnt) + (BPB_NumFATS * BPB_FATSz32 * BPB_BytesPerSec); } uint32_t getOffsetInt(uint32_t currentCluster){ //returns THIS cluster's offset if(currentCluster < 0) currentCluster = 2; return ((currentCluster - 2) * BPB_SecPerClus*BPB_BytesPerSec) + (BPB_BytesPerSec * BPB_RsvdSecCnt) + (BPB_NumFATS * BPB_FATSz32 * BPB_BytesPerSec); } uint32_t getNextClusterOffset(struct directory currentDir){ //use this to get the next page address whenver accessing multiple clusters of memory //ex: large files or folders with getNextCluster subdirectories uint32_t cluster = getCluster(currentDir); if(cluster == EOC || cluster == FREE) return -1; return getOffsetInt(fat[cluster]); } uint32_t getNextClusterOffsetInt(int currentCluster){ return getOffsetInt(fat[currentCluster]); } uint32_t getNextCluster(int currentCluster){ if(currentCluster == EOC || currentCluster == BAD_CLUSTER){ return -1; } return fat[currentCluster]; } uint32_t getFirstFreeCluster(){ //if i < 5, there may be some issues with overwriting data. for(int i=5; i < MAX_FAT; i++){ if(fat[i] == FREE) return i; } //otherwise no available space: return -1; } bool setCluster(uint32_t cluster, uint32_t newValue){ if(cluster >= 0 && cluster <= MAX_FAT){ fat[cluster] = newValue; return true; } //invalid cluster number: return false; } void refreshDir(uint32_t cluster){ //zero out previous data: memset(dir,0,sizeof(dir)); memset(stagingDir,0,sizeof(stagingDir)); //add elements to stagingDir array: int dirsToSkip = 0; int dirsPerCluster = clusterSize/32;//32=size of dir entry while(cluster != FREE && cluster < EOC && cluster != BAD_CLUSTER){ fseek(fd, getOffsetInt(cluster), SEEK_SET);//at the first sector of data sizeTDummy = fread(&stagingDir[dirsToSkip], 32, dirsPerCluster, fd);//shorthand for 512 bytes 32*16=512, read into the first dir struct, ie root, everything offset from here if(DEBUG) printf("Dec: %d\t Hex: %x\t EOC: %d\n",cluster, cluster, cluster==EOC); cluster = getNextCluster(cluster); dirsToSkip += dirsPerCluster; } //clean remove entries that do not exist in this directory by assuming //that a blank space means the end of the directory: for(int i = 0; i < MAX_DIR; i++){ //determine if dir exists: //TODO: check also if the first bute is 0xE5... In a future version if(strncmp(stagingDir[i].DIR_Name, "",11) == 0 && stagingDir[i].DIR_Attr == 0 && stagingDir[i].DIR_FileSize == 0 && stagingDir[i].DIR_FstClusLo == 0 && stagingDir[i].DIR_FstClusHi == 0) break; else if(stagingDir[i].DIR_Name[0]=='_') continue;//ignore mac artifacts dir[i]= stagingDir[i]; } //read in the FAT: fseek(fd, bytes_for_reserved, SEEK_SET); sizeTDummy = fread(fat, 4 /*bytes*/, fat_bytes/4, fd); } void printFullPath(){ struct directory dirCopy[MAX_DIR]; struct directory prevDir; //copy dir into dirCopy: const char* buf[MAX_BUF]; int bufPos = 0; memcpy(dirCopy, dir, sizeof(dir)); prevDir = dir[0]; while(cd(convertToShortName(".."), false)){ for(int i = 0; i < MAX_DIR; i++){ if(getCluster(dir[i]) == getCluster(prevDir)){ buf[bufPos++] = convertToPrettyName(dir[i].DIR_Name); prevDir = dir[0]; break; } } } //now to print out the saved strings in reverse order: printf("\n/"); for(bufPos--; bufPos >= 0; bufPos--){ if(buf[bufPos] == NULL){ continue; } printf("%s/",buf[bufPos]); } printf("] "); //restore the original dir: memcpy(dir, dirCopy, sizeof(dirCopy)); } /*********************************************************** * CMD FUNCTIONS * Implementation of all command line arguments **********************************************************/ /* * info * ---------------------------- * Description: prints out information about the following fields in both hex and base 10: * BPB_BytesPerSec, Bytes per Sector * BPB_SecPerClus, amount of sectors in a cluster * BPB_RsvdSecCnt, # of reserved sector * BPB_NumFATS, Number of File Allocation Tables * BPB_FATSz32, Sectors per Fat */ void info(){ //Now print out all the info that was recorded in the init() method when we started the program char buff[20]; sprintf(buff, "%04x", BPB_BytesPerSec); printf("BPB_BytesPerSec is: 0x%s %d \n", buff, BPB_BytesPerSec); sprintf(buff, "%04x", BPB_SecPerClus); printf("BPB_SecPerClus: 0x%s %d\n", buff, BPB_SecPerClus); sprintf(buff, "%04x", BPB_RsvdSecCnt); printf("BPB_RsvdSecCnt: 0x%s %d\n", buff, BPB_RsvdSecCnt); sprintf(buff, "%04x", BPB_NumFATS); printf("BPB_NumFATS: 0x%s %d\n", buff, BPB_NumFATS); sprintf(buff, "%04x", BPB_FATSz32); printf("BPB_FATSz32: 0x%s %d\n", buff, BPB_FATSz32); } /* * ls * ---------------------------- * Description: lists the contents of DIR_NAME, including “.” and “..”. * path: the path to examine * TODO: use the path parameter */ void ls(char* path){ int changedDir = False; if(strncmp(path, " ",11)){ //the path is not blank, so we need to cd to the specified dir, then cd to '..' if(cd(path, false)) changedDir = True; else{ //cd returned an error. abort. printf("Error: '%s' could not be opened. Ensure it exists (and is a directory) and try again", convertToPrettyName(path)); return; } } if(DEBUG) printf("Cluster Number: %d\tOffset: %d\n", getCluster(dir[0]), getOffset(dir[0])); for(int i = 0; i < MAX_DIR; i++){ if((dir[i].DIR_Name[0] != (char)0xe5 || dir[i].DIR_Name[0] != ' ')&& !(dir[i].DIR_Attr & ATTR_HIDDEN || dir[i].DIR_Attr & ATTR_SYSTEM || dir[i].DIR_Attr & ATTR_VOLUME_ID)){ char temp[12]; strncpy(temp, convertToPrettyName(dir[i].DIR_Name), 11); if(!isalnum(temp[10])) temp[10] = '\0';//remove the question marks temp[11] = '\0'; printf("%s\t",temp);//this seperates the directories by follow up tab } } if(changedDir){ cd(convertToShortName(".."), 0); } } /** * cd command * return true of successful cd, false for error */ bool cd(char *newDir, bool shouldPrint){ //check if the input is a valid dir entry for (int i = 0; i < MAX_DIR; i++){ if (strncmp(dir[i].DIR_Name, newDir, 11) == 0){ //we have a name match! make sure it is not a file: if(!(dir[i].DIR_Attr & ATTR_DIRECTORY)){ if(shouldPrint) printf("Error: Tried to cd into a directory, but found file instead"); return false; } refreshDir(getCluster(dir[i])); if(DEBUG) printf("Going to offset: %d\n",getOffset(dir[i])); return true; } } //no results: if(shouldPrint) printf("Error: unable to find '%s'",convertToPrettyName(newDir)); return false; } /* * filestat * ---------------------------- * Description: prints the size of the file or directory name, the attributes of the * file or directory name, and the first cluster number of the file or directory name * if it is in the present working directory. Return an error if FILE_NAME/DIR_NAME * does not exist. (Note: The size of a directory will always be zero.) * * path: the path to examine. Determine if this is a file or directory and print accordingly */ void filestat(char *path){ for(int i = 0; i < MAX_DIR; i++){ if(!strncmp(path, dir[i].DIR_Name, 11)/* using strncmp bc DIR_Name has a trailing space */){ //found match! printf("Size is %d\n", dir[i].DIR_FileSize); if(!!(ATTR_READ_ONLY & dir[i].DIR_Attr)) printf("Attribute: ATTR_READ_ONLY\n"); if(!!(ATTR_HIDDEN & dir[i].DIR_Attr)){ printf("Attribute: ATTR_HIDDEN\n"); } if(!!(ATTR_SYSTEM & dir[i].DIR_Attr)){ printf("Attribute: ATTR_SYSTEM\n"); } if(!!(ATTR_VOLUME_ID & dir[i].DIR_Attr)){ printf("Attribute: ATTR_VOLUME_ID\n"); } if(!!(ATTR_DIRECTORY & dir[i].DIR_Attr)){ printf("Attribute: ATTR_DIRECTORY\n"); } if(!!(ATTR_ARCHIVE & dir[i].DIR_Attr)){ printf("Attribute: ATTR_ARCHIVE\n"); } //TODO: verify this is what we should print printf("First cluster number is 0x%x\n", getCluster(dir[i])); return; } } //File not found printf("Error: unable to find '%s'",convertToPrettyName(path)); return; } /* * size * ---------------------------- * Description: prints the size of file FILE_NAME in the present working directory. * Log an error if FILE_NAME does not exist. * * path: the path to examine. Determine if this is a file or directory and print accordingly * shouldPrint: Whether we should print details to the console or just return the size * return: returns the size if file exists, otherwise 0 shouldPrint: whether or not to print the size to the console */ int size(char* path, int shouldPrint){ for(int i = 0; i < MAX_DIR; i++){ if(!strncmp(path, dir[i].DIR_Name, 11) /* TODO: show hidden files? */){ if(dir[i].DIR_Attr & ATTR_DIRECTORY){ if(shouldPrint) printf("This is a folder\nSize is %d",dir[i].DIR_FileSize); return 0; } if(shouldPrint) printf("Size is %d", dir[i].DIR_FileSize); return dir[i].DIR_FileSize; } } //if we got here, there were no matches if(shouldPrint) printf("Error: unable to find '%s'",convertToPrettyName(path)); return -1; } /* * read * ---------------------------- * Description: reads from a file named FILE_NAME, starting at POSITION, and prints NUM_BYTES. * Return an error when trying to read an unopened file. * * file: the file to examine. Determine if this is a file or directory and if it exists */ void fileread(char* file, int startPos, int numBytes){ for(int i = 0; i < MAX_DIR; i++){ if(!strncmp(dir[i].DIR_Name, file, 11)){ //Name match! //check if directory if((dir[i].DIR_Attr & ATTR_DIRECTORY) || (dir[i].DIR_Attr & ATTR_VOLUME_ID)){ //TODO: this does not work printf("ERROR: attempt to read directory"); return; } //ensure what we want to read is within the length: int fsize = size(file, False); if(numBytes + startPos >= fsize || startPos < 0){ printf("ERROR: Attempted to read outside of file bounds"); return; } //find the position of the file to read: char buf[numBytes+1/*null terminator*/]; //New plan: read in the entire cluster that has any relevant byte, then only print out //the parts that we need. Something like printf(buf[startingPosition] //While there is probably a cleaner way, this is what I thought of and is easy to implement int bytesToSkip = 0;//buffer offset int bytesPerCluster = clusterSize; int bytesToRead = clusterSize;//how many bytes to read for this iteration int bufInitialOffset = startPos % clusterSize; int totalRemainingBytes = numBytes; //the bytes left to read for the entire file uint32_t cluster = getCluster(dir[i]); while(cluster != FREE && cluster != BAD_CLUSTER && (totalRemainingBytes > 0)){ if(totalRemainingBytes >= clusterSize){ bytesToRead = clusterSize;} else{ bytesToRead = totalRemainingBytes;} totalRemainingBytes -= clusterSize; fseek(fd, getOffsetInt(cluster), SEEK_SET);//at the first sector of data sizeTDummy = fread(&buf[bytesToSkip], sizeof(char), bytesToRead, fd);//shorthand for 512 bytes 32*16=512, read into the first dir struct, ie root, everything offset from here if(DEBUG) printf("\nDec: %d\t Hex: %x\t EOC: %d\n",cluster, cluster, cluster==EOC); //now that we finished, check if EOC and increment values: if(cluster >= EOC){ break; } cluster = getNextCluster(cluster); bytesToSkip += bytesPerCluster; } buf[numBytes] = '\0'; printf("\n%s", buf + bufInitialOffset); return; } } printf("Error: unable to find '%s'", convertToPrettyName(file)); } void volume(){ if(rootDir.DIR_Name == NULL){ printf("ERROR: Volume name not found"); return; } rootDir.DIR_Name[11] = '\0'; printf("%s",rootDir.DIR_Name); return; } void filemkdir(char* file){ //read the fileread and cd commands to figure out how to get the location/offset. //Once we have the offset, we need to add a new dir entry into the dir table //and write it back to the underlying file. //check if file exists: for(int i = 0; i < MAX_DIR; i++){ if(!strncmp(dir[i].DIR_Name, file, 11)){ //Name match! printf("Error: '%s' already exists", convertToPrettyName(file)); return; } } //get the cluster number uint32_t newDirCluster; if((newDirCluster = getFirstFreeCluster()) == -1){ printf("Error: unable to find free cluster"); return; } //setup the new dir: struct directory dot; struct directory dotdot; struct directory newDir; newDir.DIR_Attr = ATTR_DIRECTORY; newDir.DIR_FileSize = 0; newDir.DIR_FstClusHi = newDirCluster & 0xFFFF0000; newDir.DIR_FstClusLo = newDirCluster & 0x0000FFFF; strncpy(newDir.DIR_Name, convertToShortName(file),11); //set dot: dot = newDir; memcpy(dot.DIR_Name, ". ", 11);//using memcpy so there is no trailing space //set dotdot: dotdot = dir[0]; memcpy(dotdot.DIR_Name, ".. ", 11); //set the fat as taken: if (!setCluster(newDirCluster, EOC)){ printf("ERROR: unable to set fat table cluster"); return; } //add new entry to dir: for(int i = 0; i < MAX_DIR; i++){ if(strncmp(dir[i].DIR_Name, "",11) == 0 && dir[i].DIR_Attr == 0 && dir[i].DIR_FileSize == 0 && dir[i].DIR_FstClusLo == 0 && dir[i].DIR_FstClusHi == 0){ //found empty spot in dir. Add the new entry. dir[i] = newDir; dir[i+1] = zeroDir; //write data to fat32 img (to add this entry to previous dir): int dirsToSkip = 0; int dirsPerCluster = clusterSize / 32; //32=size of dir entry int cluster = getCluster(dir[0]); //TODO: this will probably fail if we need to allocate a new cluster to contain the newDir while (cluster != FREE && cluster != BAD_CLUSTER){ fseek(fd, getOffsetInt(cluster), SEEK_SET); sizeTDummy = fwrite(&dir[dirsToSkip], 32, dirsPerCluster, fd); if(cluster == EOC || dirsToSkip >= i+1) break; cluster = getNextCluster(cluster); dirsToSkip += dirsPerCluster; } //write dot and dotdot to the fat32 img: fseek(fd, getOffset(newDir), SEEK_SET); sizeTDummy = fwrite(&dot, 32, 32, fd); fseek(fd, getOffset(newDir)+32, SEEK_SET); sizeTDummy = fwrite(&dotdot, 32, 32, fd); fseek(fd, getOffset(newDir)+64, SEEK_SET); sizeTDummy = fwrite(&zeroDir, 32, 32, fd); break; } } //write the FAT to fat32 img: fseek(fd, bytes_for_reserved, SEEK_SET); sizeTDummy = fwrite(fat, 4 /*bytes*/, fat_bytes/4, fd); //for some reason the file doesn't appear unless we start from the very beginning refreshDir(BPB_RootCluster); //refresh the current directory: refreshDir(getCluster(dotdot)); return; } void filermdir(char* file){ // set the first byte to deleted and write back. remove FAT entry and write back. //check if file exists: for(int i = 0; i < MAX_DIR; i++){ if(!strncmp(dir[i].DIR_Name, file, 11)){ //Name match! //check if file: if(!(dir[i].DIR_Attr & ATTR_DIRECTORY)){ printf("Error: '%s' is not a directory", convertToPrettyName(file)); return; } //check if empty: if(!cd(file, 0)) printf("Error: '%s' is malformed", convertToPrettyName(file)); if(!(memcmp(&dir[2], &zeroDir, sizeof(struct directory)) || dir[2].DIR_Name[0] != 0x0)){ printf("Error: '%s' is not empty", convertToPrettyName(file)); if(!cd(convertToShortName(".."), 0)) printf("Error: '%s' is malformed", convertToPrettyName(file)); return; } if(!cd(convertToShortName(".."), 0)) printf("Error: '%s' is malformed", convertToPrettyName(file)); //set DIR_Name[0] to 0x0: //TODO: in a future version, implement 0xe5 meaning end of dir cluster. also change refreshDir dir[i].DIR_Name[0] = (char) 0x0; //write data to fat32 img: int dirsToSkip = 0; int dirsPerCluster = clusterSize / 32; //32=size of dir entry int cluster = getCluster(dir[0]); while (cluster != FREE && cluster != BAD_CLUSTER){ fseek(fd, getOffsetInt(cluster), SEEK_SET); sizeTDummy = fwrite(&dir[dirsToSkip], 32, dirsPerCluster, fd); if(cluster == EOC || dirsToSkip > i) break; cluster = getNextCluster(cluster); dirsToSkip += dirsPerCluster; } //set the cluster chain as free: //yes, this is wasteful. Not sure how to dynamically add elements in C uint32_t clustersToBeCleared[MAX_FAT]; cluster = getCluster(dir[i]); clustersToBeCleared[0] = cluster; cluster = getCluster(dir[i]); for(int i = 1; i < MAX_FAT; i++){ if((cluster = getNextCluster(cluster)) == EOC){ //found the last cluster. set all previous entries to free i--; for(;i > 0; i--){ setCluster(clustersToBeCleared[i], FREE); } //write the new FAT to fat32 img fseek(fd, bytes_for_reserved, SEEK_SET); sizeTDummy = fwrite(fat, 4 /*bytes*/, fat_bytes/4, fd); break; } clustersToBeCleared[i] = cluster; } //refresh the dir: refreshDir(getCluster(dir[0])); return; } } //unable to find dir: printf("Error: unable to find '%s'", convertToPrettyName(file)); } /*********************************************************** * MAIN * Program main **********************************************************/ int main(int argc, char *argv[]) { char cmd_line[MAX_CMD]; //printf("This is the file: %s", argv[1]); init(argv[1]); /*for Ari to work on */ /* Main loop. You probably want to create a helper function for each command besides quit. */ while(True) { bzero(cmd_line, MAX_CMD); printFullPath(); strDummy = fgets(cmd_line,MAX_CMD,stdin); /* Start comparing input */ if(strncmp(cmd_line,"info",4)==0) { printf("Going to display info.\n"); info(); } else if(strncmp(cmd_line, "stat",4)==0){ printf("Going to stat!\n"); //cmd_line[strlen(&cmd_line[0])-1] = '\0';//remove trailing newline filestat(convertToShortName(&cmd_line[5])); } else if(strncmp(cmd_line,"ls",2)==0) { printf("Going to ls.\n"); ls(convertToShortName(&cmd_line[3])); } else if(strncmp(cmd_line,"read",4)==0) { printf("Going to read!\n"); char* file = convertToShortName(strtok(&cmd_line[5], " ")); char* strStartingPosition = strtok(NULL, " "); char* strNumBytes = strtok(NULL, " "); if(strStartingPosition != NULL && strNumBytes != NULL){ int startingPosition = atoi(strStartingPosition); int numBytes = atoi(strNumBytes); fileread(file, startingPosition, numBytes); } else{ printf("Error: improper formatting.\nUse read <filename> <startingPosition> <numBytes>"); } } else if(strncmp(cmd_line,"size",4)==0) { printf("Going to size!\n"); size(convertToShortName(&cmd_line[5]), True); } else if(strncmp(cmd_line,"volume",6)==0) { printf("Going to volume!\n"); volume(); } else if(strncmp(cmd_line,"cd",2)==0) { printf("Going to cd into %s\n", &cmd_line[3]);//fix this line cd(convertToShortName(&cmd_line[3]), true); } else if(strncmp(cmd_line,"mkdir",5)==0) { printf("Going to mkdir!\n"); filemkdir(convertToShortName(&cmd_line[6])); } else if(strncmp(cmd_line,"rmdir",5)==0) { printf("Going to rmdir!\n"); filermdir(convertToShortName(&cmd_line[6])); } else if(strncmp(cmd_line,"quit",4)==0) { printf("Quitting.\n"); break; } else printf("Unrecognized command.\n"); } /* Close the file */ return 0; /* Success */ }
C
CL
da116676e31ffeb5eed45eb0e4628e3d7ba6402db90e318dedfa50eb22176c6c
/* $**************** KCG Version 6.4 (build i21) **************** ** Command: kcg64.exe -config R:/Repositories/modeling/model/Scade/System/OBU_PreIntegrations/Demonstrators/ERSA_EVC_Testrunner/config.txt ** Generation date: 2015-12-10T15:16:03 *************************************************************$ */ #include "kcg_consts.h" #include "kcg_sensors.h" #include "C_DMI_Driver_Reqest_to_int_DATA_Packets_DMI_to_EVC.h" /* DATA::Packets::DMI_to_EVC::C_DMI_Driver_Reqest_to_int */ void C_DMI_Driver_Reqest_to_int_DATA_Packets_DMI_to_EVC( /* DATA::Packets::DMI_to_EVC::C_DMI_Driver_Reqest_to_int::dmi_driver_request_ct */ DMI_Driver_Request_T_DMI_Messages_DMI_to_EVC_Pkg *dmi_driver_request_ct, /* DATA::Packets::DMI_to_EVC::C_DMI_Driver_Reqest_to_int::dmi_driver_request_int */ DMI_Driver_Request_int_array_T_DATA *dmi_driver_request_int) { (*dmi_driver_request_int)[0] = 1; (*dmi_driver_request_int)[1] = (*dmi_driver_request_ct).systemTime; (*dmi_driver_request_int)[2] = /* 1 */ CAST_DMI_Request_to_int_DATA_Variables((*dmi_driver_request_ct).m_request); } /* $**************** KCG Version 6.4 (build i21) **************** ** C_DMI_Driver_Reqest_to_int_DATA_Packets_DMI_to_EVC.c ** Generation date: 2015-12-10T15:16:03 *************************************************************$ */
C
CL
b2b356fc4027c947bd2e90035f1b874db7fdcb4ebb9d12fec322ec9ba1e04798
#include <stdio.h> #include <ctype.h> // per les funcions isalpha, isdigit, ... #include <stdlib.h> #include "extract-words.h" /* Generator of next word of file (taking into account given criteria) */ char *extractWord(FILE *fileToSeparate) { int tmpWordCount = 0, isEndWord = FALSE; char tmpChar = ' '; char *tmpWord = calloc(MAXCHAR, sizeof(char)); while (isEndWord == FALSE && tmpChar != EOF) { tmpChar = (char) fgetc(fileToSeparate); tmpChar = (char) tolower(tmpChar); switch (categorizeCharacter(tmpChar)) { case DUMP_WORD : free(tmpWord); tmpWord = calloc(MAXCHAR, sizeof(char)); tmpWordCount = 0; break; case ADD_CHARACTER : tmpWord[tmpWordCount++] = tmpChar; break; case FINISH_WORD : // If it's a false positive (there are no letters in tmpWord), we ignore it if (tmpWordCount == 0) break; isEndWord = TRUE; tmpWordCount = 0; break; } } /* This is subtle, let's break it down, we first see if we reached the end of the file, if we haven't then it means we have a word (isEndWord is TRUE). Otherwise, it means we reached the end of the file, so we see if we have extracted anything until now. */ if (tmpChar != EOF || tmpWordCount > 0) { return tmpWord; } else { free(tmpWord); return NULL; } } /* Function that tells us what to do with the characterh */ int categorizeCharacter(char character) { if (isalpha(character)) { return ADD_CHARACTER; } else if (isdigit(character)) { return DUMP_WORD; } else if (ispunct(character)) { if (character == '\'') { return ADD_CHARACTER; } else { return FINISH_WORD; } } else if (isspace(character)) { return FINISH_WORD; } else { return DUMP_WORD; } }
C
CL
e0d6953d7e9ba64353ef783cdd08bf76cdb8103b6053779d8632e482a1ec81cb
/* * Copyright (C) 2010-2016 Marvell International Ltd. * Copyright (C) 2002-2010 Kinoma, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "mc_stdio.h" #include "mc_file.h" #include "mc_module.h" #if !XS_ARCHIVE #include "xm_files.xs.c" MC_MOD_DECL(files); #endif void xs_file_constructor(xsMachine *the) { const char *path = xsToString(xsArg(0)); uint32_t permissions = xsToInteger(xsArgc) > 1 ? xsToInteger(xsArg(1)) : 0; MC_FILE *fp; static int initialized = 0; if (!initialized) { mc_file_init(); initialized++; } if ((fp = mc_fopen(path, permissions ? "w+" : "r")) == NULL) { if (errno == ENOENT && permissions) { mc_creat(path, 0666); fp = mc_fopen(path, "r+"); } } if (fp == NULL) { mc_xs_throw(the, "Files.constructor"); } xsSetHostData(xsThis, fp); } void xs_file_destructor(void *data) { MC_FILE *fp = data; if (fp != NULL) mc_fclose(fp); } void xs_file_close(xsMachine *the) { MC_FILE *fp = xsGetHostData(xsThis); if (fp != NULL) mc_fclose(fp); xsSetHostData(xsThis, NULL); } void xs_file_read(xsMachine *the) { MC_FILE *fp = xsGetHostData(xsThis); int n = xsToInteger(xsArg(0)); size_t nread; void *buf; if (xsToInteger(xsArgc) > 1 && (xsTypeOf(xsArg(1)) == xsReferenceType)) { int len = xsGetArrayBufferLength(xsArg(1)); if (len < n) n = len; xsResult = xsArg(1); } else xsResult = xsArrayBuffer(NULL, n); buf = xsToArrayBuffer(xsResult); if ((nread = mc_fread(buf, 1, (size_t)n, fp)) == 0) { if (errno != 0) mc_xs_throw(the, "files.read"); /* return EOF */ xsSetUndefined(xsResult); } else if (nread != (size_t)n) xsSetArrayBufferLength(xsResult, nread); } void xs_file_readChar(xsMachine *the) { MC_FILE *fp = xsGetHostData(xsThis); int c; if ((c = mc_fgetc(fp)) != EOF) xsSetInteger(xsResult, c); } int mc_files_write_element(xsMachine *the, MC_FILE *fp, xsSlot *slot) { size_t datasize; void *data; uint8_t intdata; int n; xsVars(1); switch (xsTypeOf(*slot)) { case xsIntegerType: datasize = 1; intdata = (uint8_t)xsToInteger(*slot); data = &intdata; break; case xsStringType: data = xsToString(*slot); datasize = strlen(data); break; case xsReferenceType: if (xsIsInstanceOf(*slot, xsArrayPrototype)) { xsGet(xsVar(0), *slot, xsID("length")); int len = xsToInteger(xsVar(0)), j; for (j = 0, n = 0; j < len; j++) { xsGet(xsVar(0), *slot, j); if ((n = mc_files_write_element(the, fp, &xsVar(0))) < 0) return -1; } return n; } else { /* assume it's an ArrayBuffer */ datasize = xsGetArrayBufferLength(*slot); data = xsToArrayBuffer(*slot); } break; default: mc_xs_throw(the, "bad arg"); return -1; } if (mc_fwrite(data, 1, datasize, fp) == 0) return -1; return 0; } void xs_file_write(xsMachine *the) { MC_FILE *fp = xsGetHostData(xsThis); int ac = xsToInteger(xsArgc), i; for (i = 0; i < ac; i++) { if (mc_files_write_element(the, fp, &xsArg(i)) < 0) break; } xsSetInteger(xsResult, i); } void xs_file_getPosition(xsMachine *the) { MC_FILE *fp = xsGetHostData(xsThis); xsSetInteger(xsResult, mc_ftell(fp)); } void xs_file_setPosition(xsMachine *the) { MC_FILE *fp = xsGetHostData(xsThis); long pos = xsToInteger(xsArg(0)); if (mc_fseek(fp, pos, SEEK_SET) != 0) mc_xs_throw(the, "fseek failed"); } void xs_file_getLength(xsMachine *the) { MC_FILE *fp = xsGetHostData(xsThis); xsSetInteger(xsResult, mc_fsize(fp)); } void xs_file_setLength(xsMachine *the) { MC_FILE *fp = xsGetHostData(xsThis); long length = xsToInteger(xsArg(0)); if (mc_ftruncate(fp, length) != 0) mc_xs_throw(the, "ftruncate failed"); }
C
CL
939591c1a06e8ef9ec372a555b5a7f2e335e4f780716699be09d0e3628fd106f
/********************************************************************* * Copyright 2018, UCAR/Unidata * See netcdf/COPYRIGHT file for copying and redistribution conditions. *********************************************************************/ #include "config.h" #include <stdlib.h> #include <string.h> #include <stdio.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_SYS_STAT_H #include <sys/stat.h> #endif #ifdef HAVE_FCNTL_H #include <fcntl.h> #endif #ifdef _MSC_VER #include <io.h> #endif #include "netcdf.h" #include "ncuri.h" #include "ncbytes.h" #include "nclist.h" #include "nclog.h" #include "ncpathmgr.h" #define NC_MAX_PATH 4096 #define LBRACKET '[' #define RBRACKET ']' /**************************************************/ /** * Provide a hidden interface to allow utilities * to check if a given path name is really an ncdap4 url. * If no, return null, else return basename of the url * minus any extension. */ int NC__testurl(const char* path, char** basenamep) { NCURI* uri; int ok = NC_NOERR; if(ncuriparse(path,&uri)) ok = NC_EURL; else { char* slash = (uri->path == NULL ? NULL : strrchr(uri->path, '/')); char* dot; if(slash == NULL) slash = (char*)path; else slash++; slash = nulldup(slash); if(slash == NULL) dot = NULL; else dot = strrchr(slash, '.'); if(dot != NULL && dot != slash) *dot = '\0'; if(basenamep) *basenamep=slash; else if(slash) free(slash); } ncurifree(uri); return ok; } /* Return 1 if this machine is little endian */ int NC_isLittleEndian(void) { union { unsigned char bytes[SIZEOF_INT]; int i; } u; u.i = 1; return (u.bytes[0] == 1 ? 1 : 0); } char* NC_backslashEscape(const char* s) { const char* p; char* q; size_t len; char* escaped = NULL; len = strlen(s); escaped = (char*)malloc(1+(2*len)); /* max is everychar is escaped */ if(escaped == NULL) return NULL; for(p=s,q=escaped;*p;p++) { char c = *p; switch (c) { case '\\': case '/': case '.': case '@': *q++ = '\\'; *q++ = '\\'; break; default: *q++ = c; break; } } *q = '\0'; return escaped; } char* NC_backslashUnescape(const char* esc) { size_t len; char* s; const char* p; char* q; if(esc == NULL) return NULL; len = strlen(esc); s = (char*)malloc(len+1); if(s == NULL) return NULL; for(p=esc,q=s;*p;) { switch (*p) { case '\\': p++; /* fall thru */ default: *q++ = *p++; break; } } *q = '\0'; return s; } char* NC_entityescape(const char* s) { const char* p; char* q; size_t len; char* escaped = NULL; const char* entity; len = strlen(s); escaped = (char*)malloc(1+(6*len)); /* 6 = |&apos;| */ if(escaped == NULL) return NULL; for(p=s,q=escaped;*p;p++) { char c = *p; switch (c) { case '&': entity = "&amp;"; break; case '<': entity = "&lt;"; break; case '>': entity = "&gt;"; break; case '"': entity = "&quot;"; break; case '\'': entity = "&apos;"; break; default : entity = NULL; break; } if(entity == NULL) *q++ = c; else { len = strlen(entity); memcpy(q,entity,len); q+=len; } } *q = '\0'; return escaped; } char* /* Depending on the platform, the shell will sometimes pass an escaped octotherpe character without removing the backslash. So this function is appropriate to be called on possible url paths to unescape such cases. See e.g. ncgen. */ NC_shellUnescape(const char* esc) { size_t len; char* s; const char* p; char* q; if(esc == NULL) return NULL; len = strlen(esc); s = (char*)malloc(len+1); if(s == NULL) return NULL; for(p=esc,q=s;*p;) { switch (*p) { case '\\': if(p[1] == '#') p++; /* fall thru */ default: *q++ = *p++; break; } } *q = '\0'; return s; } /** Wrap mktmp and return the generated path, or null if failed. Base is the base file path. XXXXX is appended to allow mktmp add its unique id. Return the generated path. */ char* NC_mktmp(const char* base) { int fd = -1; char* tmp = NULL; size_t len; len = strlen(base)+6+1; if((tmp = (char*)malloc(len))==NULL) goto done; strncpy(tmp,base,len); strlcat(tmp, "XXXXXX", len); fd = NCmkstemp(tmp); if(fd < 0) { nclog(NCLOGERR, "Could not create temp file: %s",tmp); goto done; } done: if(fd >= 0) close(fd); return tmp; } int NC_readfile(const char* filename, NCbytes* content) { int ret = NC_NOERR; FILE* stream = NULL; char part[1024]; #ifdef _WIN32 stream = NCfopen(filename,"rb"); #else stream = NCfopen(filename,"r"); #endif if(stream == NULL) {ret=errno; goto done;} for(;;) { size_t count = fread(part, 1, sizeof(part), stream); if(count <= 0) break; ncbytesappendn(content,part,count); if(ferror(stream)) {ret = NC_EIO; goto done;} if(feof(stream)) break; } ncbytesnull(content); done: if(stream) fclose(stream); return ret; } int NC_writefile(const char* filename, size_t size, void* content) { int ret = NC_NOERR; FILE* stream = NULL; void* p; size_t remain; #ifdef _WIN32 stream = NCfopen(filename,"wb"); #else stream = NCfopen(filename,"w"); #endif if(stream == NULL) {ret=errno; goto done;} p = content; remain = size; while(remain > 0) { size_t written = fwrite(p, 1, remain, stream); if(ferror(stream)) {ret = NC_EIO; goto done;} if(feof(stream)) break; remain -= written; } done: if(stream) fclose(stream); return ret; } /* Parse a path as a url and extract the modelist. If the path is not a URL, then return a NULL list. If a URL, but modelist is empty or does not exist, then return empty list. */ int NC_getmodelist(const char* path, NClist** modelistp) { int stat=NC_NOERR; NClist* modelist = NULL; NCURI* uri = NULL; const char* modestr = NULL; const char* p = NULL; const char* endp = NULL; ncuriparse(path,&uri); if(uri == NULL) goto done; /* not a uri */ /* Get the mode= arg from the fragment */ modelist = nclistnew(); modestr = ncurifragmentlookup(uri,"mode"); if(modestr == NULL || strlen(modestr) == 0) goto done; /* Parse the mode string at the commas or EOL */ p = modestr; for(;;) { char* s; ptrdiff_t slen; endp = strchr(p,','); if(endp == NULL) endp = p + strlen(p); slen = (endp - p); if((s = malloc(slen+1)) == NULL) {stat = NC_ENOMEM; goto done;} memcpy(s,p,slen); s[slen] = '\0'; nclistpush(modelist,s); if(*endp == '\0') break; p = endp+1; } done: if(stat == NC_NOERR) { if(modelistp) {*modelistp = modelist; modelist = NULL;} } ncurifree(uri); nclistfree(modelist); return stat; } /* Check "mode=" list for a path and return 1 if present, 0 otherwise. */ int NC_testmode(const char* path, const char* tag) { int stat = NC_NOERR; int found = 0; int i; NClist* modelist = NULL; if((stat = NC_getmodelist(path, &modelist))) goto done; for(i=0;i<nclistlength(modelist);i++) { const char* value = nclistget(modelist,i); if(strcasecmp(tag,value)==0) {found = 1; break;} } done: nclistfreeall(modelist); return found; } #ifdef __APPLE__ int isinf(double x) { union { unsigned long long u; double f; } ieee754; ieee754.f = x; return ( (unsigned)(ieee754.u >> 32) & 0x7fffffff ) == 0x7ff00000 && ( (unsigned)ieee754.u == 0 ); } int isnan(double x) { union { unsigned long long u; double f; } ieee754; ieee754.f = x; return ( (unsigned)(ieee754.u >> 32) & 0x7fffffff ) + ( (unsigned)ieee754.u != 0 ) > 0x7ff00000; } #endif /*APPLE*/
C
CL
448517bcfdc2746c78edbfb01a930d11cbd86aec4adefd7f26009354c9b620b7
// Nerd - Win32 platform layer // Copyright (C)2018 Matt Davies, all rights reserved. #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include <crtdbg.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <nerd.h> //---------------------------------------------------------------------------------------------------------------------- // Returns the path of the executable. // Free the return value with free(). //---------------------------------------------------------------------------------------------------------------------- char* getExePathName() { int len = MAX_PATH; for(;;) { char* buf = malloc(len); if (!buf) return 0; DWORD pathLen = GetModuleFileName(0, buf, len); if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) { // Not enough memory! len = 2 * len; free(buf); continue; } while (buf[pathLen] != '\\') --pathLen; buf[pathLen] = 0; return buf; } } //---------------------------------------------------------------------------------------------------------------------- // Entry point //---------------------------------------------------------------------------------------------------------------------- extern size_t getline(char **lineptr, size_t *n, FILE *stream); void SigHandler(int sig) { _CrtCheckMemory(); } void out(Nerd N, const char* msg) { OutputDebugStringA(msg); printf("%s", msg); } int _main(int argc, char** argv) { char* exePath = getExePathName(); signal(SIGINT, &SigHandler); int cont = 1; while(cont) { printf("Nerd REPL (V0.0)\n"); printf("PWD: %s\n", exePath); printf("\nEnter ,q to quit.\n\n"); cont = 0; NeConfig config; NeDefaultConfig(&config); config.outputFunc = &out; Nerd N = NeOpen(&config); if (N) { for (;;) { char* input = 0; size_t size = 0; size_t numChars = 0; printf("> "); numChars = getline(&input, &size, stdin); if ((-1 != numChars) && (*input == ',')) { switch (input[1]) { case 'q': numChars = -1; break; case 'r': numChars = -1; cont = 1; break; } } if (-1 == numChars) { free(input); break; } if (size) { Atom result = { AT_Nil }; int success = NeRun(N, "<stdin>", input, numChars, &result); free(input); NeString resultString = NeToString(N, result, success ? NSM_REPL : NSM_Normal); printf(success ? "==> %s\n" : "ERROR: %s\n", resultString); #ifndef NDEBUG _CrtCheckMemory(); #endif } } } NeClose(N); } free(exePath); return 0; } int main(int argc, char** argv) { #ifndef NDEBUG _CrtSetBreakAlloc(0); _CrtSetDbgFlag(_CRTDBG_CHECK_ALWAYS_DF | _CRTDBG_LEAK_CHECK_DF); #endif int result = _main(argc, argv); _CrtCheckMemory(); return result; }
C
CL
fd1ba307df9bd0d22b613b97b327ff94d88965f67436cb475e61fbb7c0336dae
/******************************************************************************* * Copyright (c) 2013 protos software gmbh (http://www.protos.de). * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * CONTRIBUTORS: * Thomas Schuetz (initial contribution) * *******************************************************************************/ #include "helpers/etTimeHelpers.h" void etTimeHelpers_subtract(etTime *first, etTime* second){ /* TODO: implement */ } void etTimeHelpers_add(etTime *first, etTime* second){ /* TODO: implement */ } etInt32 etTimeHelpers_convertToMSec(etTime *time){ return time->sec * 1000 + time->nSec / 1000000; } void etTimeHelpers_convertToEtTime(etTime *result, etInt32 milliSeconds){ result->sec = milliSeconds/1000; result->nSec = milliSeconds%1000 * 1000000; }
C
CL
a41d2ec931715f7f5c5c285bdfc57095e01d78b6d8fd589f793baffa325599f1
/* * File: l3gd20.h * Author: Rich Primerano * * Created on September 2, 2013, 1:23 PM */ #ifndef L3GD20_H #define L3GD20_H #ifdef __cplusplus extern "C" { #endif #include "robot.h" // Accelerometer defines #define GYRO_FS_CODE 0 // full-scale: 0=250dps, 1=500dps, 2=2000dps #define GYRO_I2C_ADDR 0x6b // I2C address of device #define WHO_AM_I_G 0x0f #define CTRL_REG1_G 0x20 // control register 1 #define CTRL_REG2_G 0x21 // control register 2 #define CTRL_REG3_G 0x22 // control register 3 #define CTRL_REG4_G 0x23 // control register 4 #define CTRL_REG5_G 0x24 // control register 5 #define STATUS_REG_G 0x27 // status register #define GYRO_DATA_BASE_ADD 0xa8 // base address of sensor registers //Gyroscope sensitivity in (rad/sec/LSB) #if GYRO_FS_CODE == 0 #define GYRO_RES 0.00875f / 180.0f * PI #elif GYRO_FS_CODE == 1 #define GYRO_RES 0.01750f / 180.0f * PI #elif GYRO_FS_CODE == 2 #define GYRO_RES 0.07000f / 180.0f * PI #endif #ifdef __cplusplus } #endif #endif /* L3GD20_H */
C
CL
f093c109825b9a9761e54b16fdd70aa658b003edccf4ac3358d8a87786119a8e
// Queues.c // // Routines for keeping track of players // #include "WOFBot.h" void RemoveFromQueue(QueueHeader *qh, short nbr) { short i; QueueElement *qp,*lq; lq = NULL; for (i = 0,qp = qh->firstElement; i < qh->nbrElements; ++i,qp = qp->nextElement) { if (i == nbr) { if (lq) lq->nextElement = qp->nextElement; else qh->firstElement = qp->nextElement; if (((PlayerRecord *) qp)->heapRecord) { // Free Heap Record DisposePtr((Ptr) qp); } else { // Free up for use in freeplayerpool ((PlayerRecord *) qp)->inUse = false; } --qh->nbrElements; return; } lq = qp; } } void AddToQueue(QueueHeader *qh, QueueElement *pr) { QueueElement *qp; if (qh->firstElement == NULL) { qh->firstElement = pr; } else { qp = qh->firstElement; while (qp->nextElement) qp = qp->nextElement; qp->nextElement = pr; } qh->nbrElements++; } void CountActivePlayers() { QueueElement *qp; short i; gWOF.nbrActivePlayers = 0; for (i = 0,qp = gWOF.playerList.firstElement; i < gWOF.playerList.nbrElements; ++i,qp = qp->nextElement) { if (((PlayerRecord *) qp)->present && ((PlayerRecord *) qp)->playing) ++gWOF.nbrActivePlayers; } } #define MaxPlayerPool 32 PlayerRecord gPlayerPool[MaxPlayerPool]; PlayerRecord *GetFreePlayerPool(); PlayerRecord *GetFreePlayerPool() { short i; for (i = 0; i < MaxPlayerPool; ++i) { if (!gPlayerPool[i].inUse) { memset(&gPlayerPool[i],0,sizeof(PlayerRecord)); gPlayerPool[i].inUse = true; return &gPlayerPool[i]; } } return NULL; } PlayerRecord *NewPlayer(PersonID userID) { PlayerRecord *pr; pr = GetFreePlayerPool(); if (pr == NULL) { pr = (PlayerRecord *) NewPtrClear(sizeof(PlayerRecord)); pr->heapRecord = true; } pr->playerID = userID; pr->present = true; pr->playing = true; pr->lastPresent = TickCount(); pr->lastActive = TickCount(); pr->newbie = 4; AddToQueue(&gWOF.playerList, (QueueElement *) pr); gWOF.nbrActivePlayers++; CheckCuteNick(pr); return pr; } PlayerRecord *GetPlayerRecord(PersonID whoID) { QueueElement *qp; short i; for (i = 0,qp = gWOF.playerList.firstElement; i < gWOF.playerList.nbrElements; ++i,qp = qp->nextElement) { if (((PlayerRecord *) qp)->playerID == whoID) return (PlayerRecord *) qp; } return NULL; } PlayerRecord *GetPlayerRecordByName(char *name) { UserRecPtr up = NULL; up = GetPersonByName(name); if (up) { return GetPlayerRecord(up->userID); } else return NULL; } char *GetPlayerName(PersonID userID) { UserRecPtr up; PlayerRecord *pr; pr = GetPlayerRecord(userID); if (pr == NULL) return ""; up = GetPersonByID(userID); if (up) { BlockMove(up->name,pr->nick,up->name[0]+1); PtoCstr((StringPtr) pr->nick); } return pr->nick; } void ClearPlayers() { while (gWOF.playerList.nbrElements) { RemoveFromQueue(&gWOF.playerList, 0); } }
C
CL
58334e0580667725c3c8634fe4d77ed570df1cdcf24c8a54f74607766784a3b6
/* * This is a RANDOMLY GENERATED PROGRAM. * * Generator: csmith 2.2.0 * Git version: dcef523 * Options: --no-structs --no-pointers --no-math64 --max-funcs 4 --no-unions --output 18485.c * Seed: 3948471244 */ #include "csmith.h" static long __undefined; /* --- Struct/Union Declarations --- */ /* --- GLOBAL VARIABLES --- */ static int16_t g_6 = 0xDEDBL; static int8_t g_8 = 1L; static int32_t g_9 = 0x27213EC7L; static int16_t g_10[6] = {(-1L),0xF6E2L,(-1L),(-1L),0xF6E2L,(-1L)}; static volatile uint8_t g_29 = 0x77L;/* VOLATILE GLOBAL g_29 */ static int32_t g_41 = 0x5CF63547L; static int16_t g_49 = 0x7B1EL; static volatile uint32_t g_56 = 0xFFBBA6F2L;/* VOLATILE GLOBAL g_56 */ static uint32_t g_62 = 0UL; static uint32_t g_69[1] = {0x33A03155L}; static int8_t g_91 = 0xA4L; static uint32_t g_92 = 0xC16D4618L; /* --- FORWARD DECLARATIONS --- */ static int16_t func_1(void); static const uint8_t func_2(int32_t p_3, uint8_t p_4); static int32_t func_16(uint32_t p_17, uint32_t p_18, uint16_t p_19, uint16_t p_20); static int32_t func_37(uint32_t p_38, int32_t p_39, int16_t p_40); /* --- FUNCTIONS --- */ /* ------------------------------------------ */ /* * reads : g_8 g_10 g_6 g_9 g_29 g_56 g_69 g_62 g_49 g_91 g_41 g_92 * writes: g_9 g_29 g_8 g_41 g_49 g_56 g_62 g_69 g_91 g_92 */ static int16_t func_1(void) { /* block id: 0 */ int32_t l_5 = 0x4BC662A2L; int32_t l_7[5] = {0x74006310L,0x74006310L,0x74006310L,0x74006310L,0x74006310L}; uint32_t l_11 = 18446744073709551607UL; uint8_t l_25 = 1UL; int32_t l_26 = (-1L); int32_t l_27 = 0x3523E24BL; uint32_t l_90 = 4294967295UL; int i; g_62 = ((func_2(((4294967288UL ^ (l_27 ^= ((++l_11) != (g_8 | (((((safe_div_func_uint16_t_u_u(((g_8 >= (l_7[1] = ((g_10[1] | func_16(g_8, g_10[0], l_5, ((g_9 = g_10[0]) || (safe_div_func_uint16_t_u_u((((safe_mul_func_uint16_t_u_u((((l_7[3] && l_7[3]) != (-1L)) <= l_5), (-1L))) , 65529UL) , l_25), g_6))))) | g_8))) && l_26), 0x7C76L)) | l_26) ^ 65535UL) == g_8) != g_8))))) , g_6), l_5) != (-8L)) ^ l_5); g_91 |= ((g_29 && (((safe_sub_func_int32_t_s_s(((((0xABA0L > (((safe_rshift_func_int16_t_s_u((safe_div_func_uint32_t_u_u((((g_69[0] |= l_7[3]) || (safe_rshift_func_int16_t_s_s(((safe_add_func_int8_t_s_s((-8L), (safe_lshift_func_int8_t_s_s((safe_add_func_uint32_t_u_u((g_29 > (((safe_mul_func_uint8_t_u_u((safe_mul_func_int16_t_s_s((((safe_rshift_func_int8_t_s_u(l_7[0], 3)) , (l_11 == (safe_lshift_func_uint16_t_u_u((((((safe_rshift_func_int16_t_s_u(((l_7[4] ^= ((((safe_mul_func_uint32_t_u_u(((247UL | l_90) , 0xCC6B82E5L), 0UL)) <= g_62) | l_5) , l_27)) || l_25), g_69[0])) | (-7L)) , g_10[1]) != g_10[3]) >= g_62), 2)))) ^ l_5), g_49)), l_11)) >= 0x4094L) == g_69[0])), 0UL)), 5)))) | g_10[0]), g_6))) >= g_49), 0x3D54CDCAL)), 1)) ^ l_5) , l_25)) <= 0x7171L) > 1L) , g_49), g_49)) && l_26) <= g_8)) <= g_9); l_7[3] = g_41; g_92--; return g_62; } /* ------------------------------------------ */ /* * reads : g_6 g_9 g_29 g_8 g_10 g_56 * writes: g_9 g_29 g_8 g_41 g_49 g_56 */ static const uint8_t func_2(int32_t p_3, uint8_t p_4) { /* block id: 7 */ uint32_t l_28 = 0xD8EB7BFBL; int32_t l_54 = 0xBC31B53AL; int16_t l_59[9] = {(-1L),(-1L),(-1L),(-1L),(-1L),(-1L),(-1L),(-1L),(-1L)}; const uint8_t l_61 = 0UL; int i; g_9 ^= (l_28 , (p_3 = g_6)); lbl_55: g_29++; p_3 |= g_29; for (g_8 = 22; (g_8 < (-21)); g_8 = safe_sub_func_uint8_t_u_u(g_8, 8)) { /* block id: 14 */ int16_t l_48 = 0x2F90L; int32_t l_50 = 0x880E1B4AL; int32_t l_51 = (-9L); l_54 &= (!(g_9 || (safe_mul_func_int8_t_s_s(((p_3 && func_37((g_41 = 5UL), (safe_mul_func_uint8_t_u_u((((((l_50 = (g_9 , ((l_28 >= ((((g_49 = (safe_rshift_func_int16_t_s_u((l_28 != g_10[0]), (l_48 = (safe_mod_func_int16_t_s_s(l_28, 0xCB81L)))))) <= p_3) & p_3) | 1UL)) & l_50))) && l_28) >= 4294967286UL) , l_50) > p_4), p_4)), l_51)) , l_28), (-1L))))); if (g_10[0]) { /* block id: 27 */ if (l_50) goto lbl_55; g_56--; } else { /* block id: 30 */ uint32_t l_60 = 6UL; l_60 &= (l_59[2] && 0xD35EL); } } return l_61; } /* ------------------------------------------ */ /* * reads : g_10 * writes: */ static int32_t func_16(uint32_t p_17, uint32_t p_18, uint16_t p_19, uint16_t p_20) { /* block id: 3 */ return g_10[5]; } /* ------------------------------------------ */ /* * reads : g_10 * writes: */ static int32_t func_37(uint32_t p_38, int32_t p_39, int16_t p_40) { /* block id: 19 */ for (p_39 = (-6); (p_39 == (-16)); p_39 = safe_sub_func_uint32_t_u_u(p_39, 6)) { /* block id: 22 */ if (p_38) break; } return g_10[5]; } /* ---------------------------------------- */ int main (int argc, char* argv[]) { int i; int print_hash_value = 0; platform_main_begin(); crc32_gentab(); func_1(); transparent_crc(g_6, "g_6", print_hash_value); transparent_crc(g_8, "g_8", print_hash_value); transparent_crc(g_9, "g_9", print_hash_value); for (i = 0; i < 6; i++) { transparent_crc(g_10[i], "g_10[i]", print_hash_value); if (print_hash_value) printf("index = [%d]\n", i); } transparent_crc(g_29, "g_29", print_hash_value); transparent_crc(g_41, "g_41", print_hash_value); transparent_crc(g_49, "g_49", print_hash_value); transparent_crc(g_56, "g_56", print_hash_value); transparent_crc(g_62, "g_62", print_hash_value); for (i = 0; i < 1; i++) { transparent_crc(g_69[i], "g_69[i]", print_hash_value); if (print_hash_value) printf("index = [%d]\n", i); } transparent_crc(g_91, "g_91", print_hash_value); transparent_crc(g_92, "g_92", print_hash_value); int checksum = platform_main_end(crc32_context ^ 0xFFFFFFFFUL, print_hash_value); return checksum; } /************************ statistics ************************* XXX max struct depth: 0 breakdown: depth: 0, occurrence: 27 XXX total union variables: 0 XXX non-zero bitfields defined in structs: 0 XXX zero bitfields defined in structs: 0 XXX const bitfields defined in structs: 0 XXX volatile bitfields defined in structs: 0 XXX structs with bitfields in the program: 0 breakdown: XXX full-bitfields structs in the program: 0 breakdown: XXX times a bitfields struct's address is taken: 0 XXX times a bitfields struct on LHS: 0 XXX times a bitfields struct on RHS: 0 XXX times a single bitfield on LHS: 0 XXX times a single bitfield on RHS: 0 XXX max expression depth: 45 breakdown: depth: 1, occurrence: 22 depth: 2, occurrence: 3 depth: 3, occurrence: 1 depth: 26, occurrence: 1 depth: 34, occurrence: 1 depth: 45, occurrence: 1 XXX total number of pointers: 0 XXX times a non-volatile is read: 74 XXX times a non-volatile is write: 21 XXX times a volatile is read: 3 XXX times read thru a pointer: 0 XXX times a volatile is write: 2 XXX times written thru a pointer: 0 XXX times a volatile is available for access: 19 XXX percentage of non-volatile access: 95 XXX forward jumps: 0 XXX backward jumps: 1 XXX stmts: 19 XXX max block depth: 2 breakdown: depth: 0, occurrence: 13 depth: 1, occurrence: 3 depth: 2, occurrence: 3 XXX percentage a fresh-made variable is used: 23.9 XXX percentage an existing variable is used: 76.1 ********************* end of statistics **********************/
C
CL
eabee3e032ca0512648476ace4cf222ed27648b077e233458660ab0a142dbeb8
#include "oomph.h" #include <assert.h> #include <errno.h> #include <stdarg.h> #include <stdio.h> #include <spawn.h> #include <sys/types.h> #include <sys/wait.h> // TODO: copy/pasted from generated c code, not ideal // ------------ copy/pasta BEGIN struct StringList { REFCOUNT_HEADER int64_t len; int64_t alloc; struct String smalldata[8]; struct String *data; }; struct AtExitFunction { REFCOUNT_HEADER void (*func)(void *); void *data; struct DestroyCallback cblist[]; }; static void at_exit_function_dtor(void *ptr) { struct AtExitFunction *obj = ptr; for (const struct DestroyCallback *cb = obj->cblist; cb->func; cb++) cb->func(cb->arg); free(obj); } // ------------ copy/pasta END extern char **environ; int64_t oomph_run_subprocess(void *args) { struct StringList *arglst = args; assert(arglst->len != 0); char **argarr = malloc(sizeof(argarr[0]) * (arglst->len + 1)); assert(argarr); for (int i = 0; i < arglst->len; i++) argarr[i] = string_to_cstr(arglst->data[i]); argarr[arglst->len] = NULL; pid_t pid; int ret = posix_spawnp(&pid, argarr[0], NULL, NULL, argarr, environ); if (ret != 0) { errno = ret; panic_printf_errno("posix_spawnp() failed"); } for (int i = 0; i < arglst->len; i++) free(argarr[i]); free(argarr); int wstatus; if (waitpid(pid, &wstatus, 0) <= 0) panic_printf("waitpid() failed"); // TODO: represent signals etc nicely return WIFEXITED(wstatus) ? WEXITSTATUS(wstatus) : -1; } noreturn void oomph_exit(int64_t status) { exit((int)status); } void oomph_assert(bool cond, struct String path, int64_t lineno) { if (!cond) panic_printf("assert() failed in \"%s\", line %d", string_to_cstr(path), (int)lineno); } static int global_argc = -1; static const char *const *global_argv = NULL; noreturn void panic_printf_errno(const char *fmt, ...) { int er = errno; // Make sure that what is printed here goes after everything else fflush(stdout); fflush(stderr); assert(global_argc != -1); fprintf(stderr, "%s: ", global_argv[0]); va_list ap; va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); if (er) fprintf(stderr, " (errno %d: %s)", er, strerror(er)); fputc('\n', stderr); exit(1); } int64_t oomph_argv_count(void) { assert(global_argc != -1); return global_argc; } struct String oomph_argv_get(int64_t i) { assert(global_argv != NULL); assert(0 <= i && i < global_argc); return cstr_to_string(global_argv[i]); } static struct AtExitFunction *atexit_callbacks[100] = {0}; static size_t atexit_callbacks_len = 0; void oomph_run_at_exit(void *func) { if (atexit_callbacks_len >= sizeof(atexit_callbacks)/sizeof(atexit_callbacks[0])) panic_printf("too many run_at_exit() calls"); atexit_callbacks[atexit_callbacks_len++] = func; incref(func); } static void atexit_callback(void) { for (size_t i = 0; i < atexit_callbacks_len; i++) { struct AtExitFunction *f = atexit_callbacks[i]; f->func(f->data); at_exit_function_dtor(f); } } void oomph_main(void); int main(int argc, char **argv) { global_argc = argc; global_argv = (const char*const*)argv; atexit(atexit_callback); oomph_main(); return 0; }
C
CL
ead4910a8c954d76dc20b9db6b7199278ebc7b6ffc30d73abebfc60065d1f224
/*** *wrt2err.c - write an LSTRING to stderr (OS/2 version) * * Copyright (c) 1996-2000, Microsoft Corporation. All rights reserved. * *Purpose: * This module contains a routine __wrt2err that writes an LSTRING * (one byte length followed by the several bytes of the string) * to the standard error handle (2). This is a helper routine used * for MATH error messages (and also FORTRAN error messages). It * is in the C library rather than the math library because there * are separate MS-DOS and MS OS/2 versions. * *Revision History: * 06-30-89 PHG module created, based on asm version * 03-16-90 GJF Made calling type _CALLTYPE1, added #include * <cruntime.h> and fixed the copyright. Also, cleaned * up the formatting a bit. * 07-24-90 SBM Removed '32' from API names * 10-04-90 GJF New-style function declarator. * 12-04-90 SRW Changed to include <oscalls.h> instead of <doscalls.h> * 04-26-91 SRW Removed level 3 warnings * 07-18-91 GJF Replaced call to DbgPrint with WriteFile to standard * error handle [_WIN32_]. * *******************************************************************************/ #ifndef _POSIX_ #include <cruntime.h> #include <oscalls.h> #include <internal.h> /*** *__wrt2err(msg) - write an LSTRING to stderr * *Purpose: * Takes a near pointer in BX, which is a pointer to an LSTRING which * is to be written to standard error. An LSTRING is a one-byte length * followed by that many bytes for the character string (as opposed to * a null-terminated string). * *Entry: * char *msg = pointer to LSTRING to write to standard error. * *Exit: * Nothing returned. * *Exceptions: * None handled. * *******************************************************************************/ void __wrt2err ( char *msg ) { unsigned long length; /* length of string to write */ unsigned long numwritten; /* number of bytes written */ length = *msg++; /* 1st byte is length */ /* write the message to stderr */ #ifdef _CRUISER_ DOSWRITE(2, msg, length, &numwritten); #else /* ndef _CRUISER_ */ #ifdef _WIN32_ WriteFile((HANDLE)_osfhnd[2], msg, length, &numwritten, NULL); #else /* ndef _WIN32_ */ #error ERROR - ONLY CRUISER OR WIN32 TARGET SUPPORTED! #endif /* _WIN32_ */ #endif /* _CRUISER_ */ } #endif /* _POSIX_ */
C
CL
4c092a9c6c0a16a94e8326e4185bcfcae90494abf64198e6db073d9ea63ffabe
/* * Copyright (c) 2002-2019 Julien Nadeau Carriere <[email protected]> * 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 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 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 <agar/core/core.h> #include <agar/gui/scrollbar.h> #include <agar/gui/window.h> #include <agar/gui/primitive.h> #include <agar/gui/text.h> #include <agar/gui/gui_math.h> #define SBPOS(sb,x,y) (((sb)->type == AG_SCROLLBAR_HORIZ) ? (x) : (y)) #define SBLEN(sb) (((sb)->type == AG_SCROLLBAR_HORIZ) ? WIDTH(sb) : HEIGHT(sb)) AG_Scrollbar * AG_ScrollbarNew(void *parent, enum ag_scrollbar_type type, Uint flags) { AG_Scrollbar *sb; sb = Malloc(sizeof(AG_Scrollbar)); AG_ObjectInit(sb, &agScrollbarClass); sb->type = type; sb->flags |= flags; if (flags & AG_SCROLLBAR_HFILL) { AG_ExpandHoriz(sb); } if (flags & AG_SCROLLBAR_VFILL) { AG_ExpandVert(sb); } if (flags & AG_SCROLLBAR_NOAUTOHIDE) { sb->flags &= ~(AG_SCROLLBAR_AUTOHIDE); } AG_ObjectAttach(parent, sb); return (sb); } AG_Scrollbar * AG_ScrollbarNewHoriz(void *parent, Uint flags) { return AG_ScrollbarNew(parent, AG_SCROLLBAR_HORIZ, flags); } AG_Scrollbar * AG_ScrollbarNewVert(void *parent, Uint flags) { return AG_ScrollbarNew(parent, AG_SCROLLBAR_VERT, flags); } /* Configure an initial length for the size requisition. */ void AG_ScrollbarSizeHint(AG_Scrollbar *sb, int len) { AG_ObjectLock(sb); sb->lenPre = len; AG_ObjectUnlock(sb); } /* Set/retrieve scrolling control length */ void AG_ScrollbarSetControlLength(AG_Scrollbar *sb, int bsize) { AG_ObjectLock(sb); sb->wBar = (bsize > 10 || bsize == -1) ? bsize : 10; sb->length = (sb->type == AG_SCROLLBAR_VERT) ? AGWIDGET(sb)->h : AGWIDGET(sb)->w; sb->length -= sb->width*2; sb->length -= sb->wBar; AG_ObjectUnlock(sb); } /* Set scrollbar width in pixels. */ void AG_ScrollbarSetWidth(AG_Scrollbar *sb, int width) { AG_ObjectLock(sb); sb->width = width; AG_ObjectUnlock(sb); } /* Return the current width of a scrollbar in pixels. */ int AG_ScrollbarWidth(AG_Scrollbar *sb) { int w; AG_ObjectLock(sb); w = sb->width; AG_ObjectUnlock(sb); return (w); } /* Set an alternate handler for UP/LEFT button click. */ void AG_ScrollbarSetIncFn(AG_Scrollbar *sb, AG_EventFn fn, const char *fmt, ...) { AG_ObjectLock(sb); if (fn != NULL) { sb->buttonIncFn = AG_SetEvent(sb, NULL, fn, NULL); AG_EVENT_GET_ARGS(sb->buttonIncFn, fmt); } else { sb->buttonIncFn = NULL; } AG_ObjectUnlock(sb); } /* Set an alternate handler for DOWN/RIGHT button click. */ void AG_ScrollbarSetDecFn(AG_Scrollbar *sb, AG_EventFn fn, const char *fmt, ...) { AG_ObjectLock(sb); sb->buttonDecFn = AG_SetEvent(sb, NULL, fn, NULL); AG_EVENT_GET_ARGS(sb->buttonDecFn, fmt); AG_ObjectUnlock(sb); } /* * Return the the current position and size (in pixels) of the scrollbar * control. Returns 0 on success, or -1 if the values are outside the range. */ #undef GET_EXTENT_PX #define GET_EXTENT_PX(TYPE) { \ if (vis > 0) { \ if ((max - min) > 0) { \ extentPx = sb->length - \ (int)(vis * sb->length / (max - min)); \ } else { \ extentPx = 0; \ } \ } else { \ extentPx = (sb->wBar == -1) ? 0 : (sb->length - sb->wBar); \ } \ } #define GET_PX_COORDS(TYPE) { \ TYPE min = *(TYPE *)pMin; \ TYPE max = *(TYPE *)pMax; \ TYPE vis = *(TYPE *)pVis; \ int extentPx, divPx; \ \ if (min >= (max - vis)) { \ goto fail; \ } \ GET_EXTENT_PX(TYPE); \ divPx = (int)(max - vis - min); \ if (divPx < 1) { goto fail; } \ *x = (int)(((*(TYPE *)pVal - min) * extentPx) / divPx); \ *len = (vis > 0) ? (vis * sb->length / (max - min)) : \ (sb->wBar == -1) ? sb->length : sb->wBar; \ } static __inline__ int GetPxCoords(AG_Scrollbar *_Nonnull sb, int *_Nonnull x, int *_Nonnull len) { AG_Variable *bMin, *bMax, *bVis, *bVal; void *pMin, *pMax, *pVal, *pVis; *x = 0; *len = 0; bVal = AG_GetVariable(sb, "value", &pVal); bMin = AG_GetVariable(sb, "min", &pMin); bMax = AG_GetVariable(sb, "max", &pMax); bVis = AG_GetVariable(sb, "visible", &pVis); switch (AG_VARIABLE_TYPE(bVal)) { case AG_VARIABLE_INT: GET_PX_COORDS(int); break; case AG_VARIABLE_UINT: GET_PX_COORDS(Uint); break; #ifdef HAVE_FLOAT case AG_VARIABLE_FLOAT: GET_PX_COORDS(float); break; case AG_VARIABLE_DOUBLE: GET_PX_COORDS(double); break; # ifdef HAVE_LONG_DOUBLE case AG_VARIABLE_LONG_DOUBLE: GET_PX_COORDS(long double); break; # endif #endif case AG_VARIABLE_UINT8: GET_PX_COORDS(Uint8); break; case AG_VARIABLE_SINT8: GET_PX_COORDS(Sint8); break; case AG_VARIABLE_UINT16: GET_PX_COORDS(Uint16); break; case AG_VARIABLE_SINT16: GET_PX_COORDS(Sint16); break; #if AG_MODEL != AG_SMALL case AG_VARIABLE_UINT32: GET_PX_COORDS(Uint32); break; case AG_VARIABLE_SINT32: GET_PX_COORDS(Sint32); break; #endif #ifdef HAVE_64BIT case AG_VARIABLE_UINT64: GET_PX_COORDS(Uint64); break; case AG_VARIABLE_SINT64: GET_PX_COORDS(Sint64); break; #endif default: break; } AG_UnlockVariable(bVis); AG_UnlockVariable(bMax); AG_UnlockVariable(bMin); AG_UnlockVariable(bVal); return (0); fail: AG_UnlockVariable(bVis); AG_UnlockVariable(bMax); AG_UnlockVariable(bMin); AG_UnlockVariable(bVal); return (-1); } #undef GET_PX_COORDS /* * Map specified pixel coordinates to a value. */ #define MAP_PX_COORDS(TYPE) { \ TYPE min = *(TYPE *)pMin; \ TYPE max = *(TYPE *)pMax; \ TYPE vis = *(TYPE *)pVis; \ int extentPx; \ \ if (*(TYPE *)pMax > *(TYPE *)pVis) { \ GET_EXTENT_PX(TYPE); \ if (x <= 0) { \ *(TYPE *)pVal = min; \ } else if (x >= (int)extentPx) { \ *(TYPE *)pVal = MAX(min, (max - vis)); \ } else { \ *(TYPE *)pVal = min + x*(max-vis-min)/extentPx; \ if (*(TYPE *)pVal < min) { *(TYPE *)pVal = min; } \ if (*(TYPE *)pVal > max) { *(TYPE *)pVal = max; } \ } \ } \ } static __inline__ void SeekToPxCoords(AG_Scrollbar *_Nonnull sb, int x) { AG_Variable *bMin, *bMax, *bVis, *bVal; void *pMin, *pMax, *pVal, *pVis; bVal = AG_GetVariable(sb, "value", &pVal); bMin = AG_GetVariable(sb, "min", &pMin); bMax = AG_GetVariable(sb, "max", &pMax); bVis = AG_GetVariable(sb, "visible", &pVis); switch (AG_VARIABLE_TYPE(bVal)) { case AG_VARIABLE_INT: MAP_PX_COORDS(int); break; case AG_VARIABLE_UINT: MAP_PX_COORDS(Uint); break; #ifdef HAVE_FLOAT case AG_VARIABLE_FLOAT: MAP_PX_COORDS(float); break; case AG_VARIABLE_DOUBLE: MAP_PX_COORDS(double); break; # ifdef HAVE_LONG_DOUBLE case AG_VARIABLE_LONG_DOUBLE: MAP_PX_COORDS(long double); break; # endif #endif case AG_VARIABLE_UINT8: MAP_PX_COORDS(Uint8); break; case AG_VARIABLE_SINT8: MAP_PX_COORDS(Sint8); break; case AG_VARIABLE_UINT16: MAP_PX_COORDS(Uint16); break; case AG_VARIABLE_SINT16: MAP_PX_COORDS(Sint16); break; #if AG_MODEL != AG_SMALL case AG_VARIABLE_UINT32: MAP_PX_COORDS(Uint32); break; case AG_VARIABLE_SINT32: MAP_PX_COORDS(Sint32); break; #endif #ifdef HAVE_64BIT case AG_VARIABLE_UINT64: MAP_PX_COORDS(Uint64); break; case AG_VARIABLE_SINT64: MAP_PX_COORDS(Sint64); break; #endif default: break; } AG_PostEvent(NULL, sb, "scrollbar-changed", NULL); AG_UnlockVariable(bVis); AG_UnlockVariable(bMax); AG_UnlockVariable(bMin); AG_UnlockVariable(bVal); AG_Redraw(sb); } #undef MAP_PX_COORDS /* * Type-independent increment/decrement operation. */ #undef INCREMENT #define INCREMENT(TYPE) { \ if (*(TYPE *)pMax > *(TYPE *)pVis) { \ if ((*(TYPE *)pVal + *(TYPE *)pInc) > \ (*(TYPE *)pMax - (*(TYPE *)pVis))) { \ *(TYPE *)pVal = (*(TYPE *)pMax) - (*(TYPE *)pVis); \ rv = 1; \ } else { \ *(TYPE *)pVal += *(TYPE *)pInc; \ } \ } \ } #undef DECREMENT #define DECREMENT(TYPE) { \ if (*(TYPE *)pMax > *(TYPE *)pVis) { \ if (*(TYPE *)pVal < *(TYPE *)pMin + *(TYPE *)pInc) { \ *(TYPE *)pVal = *(TYPE *)pMin; \ rv = 1; \ } else { \ *(TYPE *)pVal -= *(TYPE *)pInc; \ } \ } \ } static int Increment(AG_Scrollbar *_Nonnull sb) { AG_Variable *bVal, *bMin, *bMax, *bInc, *bVis; void *pVal, *pMin, *pMax, *pInc, *pVis; int rv = 0; bVal = AG_GetVariable(sb, "value", &pVal); bMin = AG_GetVariable(sb, "min", &pMin); bMax = AG_GetVariable(sb, "max", &pMax); bInc = AG_GetVariable(sb, "inc", &pInc); bVis = AG_GetVariable(sb, "visible", &pVis); switch (AG_VARIABLE_TYPE(bVal)) { case AG_VARIABLE_INT: INCREMENT(int); break; case AG_VARIABLE_UINT: INCREMENT(Uint); break; #ifdef HAVE_FLOAT case AG_VARIABLE_FLOAT: INCREMENT(float); break; case AG_VARIABLE_DOUBLE: INCREMENT(double); break; # ifdef HAVE_LONG_DOUBLE case AG_VARIABLE_LONG_DOUBLE: INCREMENT(long double); break; # endif #endif case AG_VARIABLE_UINT8: INCREMENT(Uint8); break; case AG_VARIABLE_SINT8: INCREMENT(Sint8); break; case AG_VARIABLE_UINT16: INCREMENT(Uint16); break; case AG_VARIABLE_SINT16: INCREMENT(Sint16); break; #if AG_MODEL != AG_SMALL case AG_VARIABLE_UINT32: INCREMENT(Uint32); break; case AG_VARIABLE_SINT32: INCREMENT(Sint32); break; #endif #ifdef HAVE_64BIT case AG_VARIABLE_UINT64: INCREMENT(Uint64); break; case AG_VARIABLE_SINT64: INCREMENT(Sint64); break; #endif default: break; } AG_PostEvent(NULL, sb, "scrollbar-changed", NULL); AG_UnlockVariable(bVal); AG_UnlockVariable(bMin); AG_UnlockVariable(bMax); AG_UnlockVariable(bInc); AG_UnlockVariable(bVis); AG_Redraw(sb); return (rv); } static int Decrement(AG_Scrollbar *_Nonnull sb) { AG_Variable *bVal, *bMin, *bMax, *bInc, *bVis; void *pVal, *pMin, *pMax, *pInc, *pVis; int rv = 0; bVal = AG_GetVariable(sb, "value", &pVal); bMin = AG_GetVariable(sb, "min", &pMin); bMax = AG_GetVariable(sb, "max", &pMax); bInc = AG_GetVariable(sb, "inc", &pInc); bVis = AG_GetVariable(sb, "visible", &pVis); switch (AG_VARIABLE_TYPE(bVal)) { case AG_VARIABLE_INT: DECREMENT(int); break; case AG_VARIABLE_UINT: DECREMENT(Uint); break; #ifdef HAVE_FLOAT case AG_VARIABLE_FLOAT: DECREMENT(float); break; case AG_VARIABLE_DOUBLE: DECREMENT(double); break; # ifdef HAVE_LONG_DOUBLE case AG_VARIABLE_LONG_DOUBLE: DECREMENT(long double); break; # endif #endif case AG_VARIABLE_UINT8: DECREMENT(Uint8); break; case AG_VARIABLE_SINT8: DECREMENT(Sint8); break; case AG_VARIABLE_UINT16: DECREMENT(Uint16); break; case AG_VARIABLE_SINT16: DECREMENT(Sint16); break; #if AG_MODEL != AG_SMALL case AG_VARIABLE_UINT32: DECREMENT(Uint32); break; case AG_VARIABLE_SINT32: DECREMENT(Sint32); break; #endif #ifdef HAVE_64BIT case AG_VARIABLE_UINT64: DECREMENT(Uint64); break; case AG_VARIABLE_SINT64: DECREMENT(Sint64); break; #endif default: break; } AG_PostEvent(NULL, sb, "scrollbar-changed", NULL); AG_UnlockVariable(bVal); AG_UnlockVariable(bMin); AG_UnlockVariable(bMax); AG_UnlockVariable(bInc); AG_UnlockVariable(bVis); AG_Redraw(sb); return (rv); } #undef INCREMENT #undef DECREMENT static void MouseButtonUp(AG_Event *_Nonnull event) { AG_Scrollbar *sb = AG_SELF(); #ifdef AG_TIMERS AG_DelTimer(sb, &sb->moveTo); #endif if (sb->curBtn == AG_SCROLLBAR_BUTTON_DEC && sb->buttonDecFn != NULL) { AG_PostEventByPtr(NULL, sb, sb->buttonDecFn, "%i", 0); } if (sb->curBtn == AG_SCROLLBAR_BUTTON_INC && sb->buttonIncFn != NULL) { AG_PostEventByPtr(NULL, sb, sb->buttonIncFn, "%i", 0); } if (sb->curBtn != AG_SCROLLBAR_BUTTON_NONE) { sb->curBtn = AG_SCROLLBAR_BUTTON_NONE; sb->xOffs = 0; } AG_PostEvent(NULL, sb, "scrollbar-drag-end", NULL); AG_Redraw(sb); } #ifdef AG_TIMERS /* Timer for scrolling controlled by buttons (mouse spin setting). */ static Uint32 MoveButtonsTimeout(AG_Timer *_Nonnull to, AG_Event *_Nonnull event) { AG_Scrollbar *sb = AG_SELF(); int dir = AG_INT(1); int rv; if (dir == -1) { rv = Decrement(sb); } else { rv = Increment(sb); } if (sb->xSeek != -1) { int pos, len; if (GetPxCoords(sb, &pos, &len) == -1 || ((dir == -1 && sb->xSeek >= pos) || (dir == +1 && sb->xSeek <= pos+len))) { sb->curBtn = AG_SCROLLBAR_BUTTON_SCROLL; sb->xSeek = -1; if (dir == +1) { sb->xOffs = len; } return (0); } } return (rv != 1) ? agMouseScrollIval : 0; } /* Timer for scrolling controlled by keyboard (keyrepeat setting). */ static Uint32 MoveKbdTimeout(AG_Timer *_Nonnull to, AG_Event *_Nonnull event) { AG_Scrollbar *sb = AG_SELF(); int dir = AG_INT(1); int rv; if (dir == -1) { rv = Decrement(sb); } else { rv = Increment(sb); } return (rv != 1) ? agKbdRepeat : 0; } #endif /* AG_TIMERS */ static void MouseButtonDown(AG_Event *_Nonnull event) { AG_Scrollbar *sb = AG_SELF(); int button = AG_INT(1); int x = SBPOS(sb, AG_INT(2), AG_INT(3)) - sb->width; int totsize = SBLEN(sb); if (button != AG_MOUSE_LEFT) { return; } if (!AG_WidgetIsFocused(sb)) { AG_WidgetFocus(sb); } if (x < 0) { /* Decrement */ sb->curBtn = AG_SCROLLBAR_BUTTON_DEC; if (sb->buttonDecFn != NULL) { AG_PostEventByPtr(NULL, sb, sb->buttonDecFn, "%i", 1); } else { if (Decrement(sb) != 1) { sb->xSeek = -1; #ifdef AG_TIMERS AG_AddTimer(sb, &sb->moveTo, agMouseScrollDelay, MoveButtonsTimeout, "%i", -1); #endif } } } else if (x > totsize - (sb->width << 1)) { /* Increment */ sb->curBtn = AG_SCROLLBAR_BUTTON_INC; if (sb->buttonIncFn != NULL) { AG_PostEventByPtr(NULL, sb, sb->buttonIncFn, "%i", 1); } else { if (Increment(sb) != 1) { sb->xSeek = -1; #ifdef AG_TIMERS AG_AddTimer(sb, &sb->moveTo, agMouseScrollDelay, MoveButtonsTimeout, "%i", +1); #endif } } } else { int pos, len; if (GetPxCoords(sb, &pos, &len) == -1) { /* No range */ sb->curBtn = AG_SCROLLBAR_BUTTON_SCROLL; sb->xOffs = x; } else if (x >= pos && x <= pos+len) { sb->curBtn = AG_SCROLLBAR_BUTTON_SCROLL; sb->xOffs = (x - pos); } else { if (x < pos) { sb->curBtn = AG_SCROLLBAR_BUTTON_DEC; if (Decrement(sb) != 1) { sb->xSeek = x; #ifdef AG_TIMERS AG_AddTimer(sb, &sb->moveTo, agMouseScrollDelay, MoveButtonsTimeout, "%i,", -1); #endif } } else { sb->curBtn = AG_SCROLLBAR_BUTTON_INC; if (Increment(sb) != 1) { sb->xSeek = x; #ifdef AG_TIMERS AG_AddTimer(sb, &sb->moveTo, agMouseScrollDelay, MoveButtonsTimeout, "%i", +1); #endif } } } } AG_PostEvent(NULL, sb, "scrollbar-drag-begin", NULL); AG_Redraw(sb); } static void MouseMotion(AG_Event *_Nonnull event) { AG_Scrollbar *sb = AG_SELF(); int mx = AG_INT(1); int my = AG_INT(2); int x = SBPOS(sb,mx,my) - sb->width; enum ag_scrollbar_button mouseOverBtn; if (sb->curBtn == AG_SCROLLBAR_BUTTON_SCROLL) { SeekToPxCoords(sb, x - sb->xOffs); } else if (AG_WidgetRelativeArea(sb, mx,my)) { if (x < 0) { mouseOverBtn = AG_SCROLLBAR_BUTTON_DEC; } else if (x > SBLEN(sb) - (sb->width << 1)) { mouseOverBtn = AG_SCROLLBAR_BUTTON_INC; } else { int pos, len; if (GetPxCoords(sb, &pos, &len) == -1 || /* No range */ (x >= pos && x <= pos+len)) { mouseOverBtn = AG_SCROLLBAR_BUTTON_SCROLL; } else { mouseOverBtn = AG_SCROLLBAR_BUTTON_NONE; if (sb->xSeek != -1) sb->xSeek = x; } } if (mouseOverBtn != sb->mouseOverBtn) { sb->mouseOverBtn = mouseOverBtn; AG_Redraw(sb); } } else { if (sb->mouseOverBtn != AG_SCROLLBAR_BUTTON_NONE) { sb->mouseOverBtn = AG_SCROLLBAR_BUTTON_NONE; AG_Redraw(sb); } } } static void KeyDown(AG_Event *_Nonnull event) { AG_Scrollbar *sb = AG_SELF(); int keysym = AG_INT(1); switch (keysym) { case AG_KEY_UP: case AG_KEY_LEFT: if (Decrement(sb) != 1) { #ifdef AG_TIMERS AG_AddTimer(sb, &sb->moveTo, agKbdDelay, MoveKbdTimeout, "%i", -1); #endif } break; case AG_KEY_DOWN: case AG_KEY_RIGHT: if (Increment(sb) != 1) { #ifdef AG_TIMERS AG_AddTimer(sb, &sb->moveTo, agKbdDelay, MoveKbdTimeout, "%i", +1); #endif } break; } } #ifdef AG_TIMERS static void KeyUp(AG_Event *_Nonnull event) { AG_Scrollbar *sb = AG_SELF(); int keysym = AG_INT(1); switch (keysym) { case AG_KEY_UP: case AG_KEY_LEFT: case AG_KEY_DOWN: case AG_KEY_RIGHT: AG_DelTimer(sb, &sb->moveTo); break; } } #if 0 /* Timer for AUTOHIDE visibility test. */ static Uint32 AutoHideTimeout(AG_Timer *_Nonnull to, AG_Event *_Nonnull event) { AG_Scrollbar *sb = AG_SELF(); AG_Window *pwin; int rv, x, len; if ((pwin = WIDGET(sb)->window) == NULL || !pwin->visible) { return (to->ival); } rv = GetPxCoords(sb, &x, &len); if (rv == -1 || len == sb->length) { if (AG_WidgetVisible(sb)) AG_WidgetHide(sb); } else { if (!AG_WidgetVisible(sb)) { AG_WidgetShow(sb); AG_Redraw(sb); } } return (to->ival); } #endif static void OnFocusLoss(AG_Event *_Nonnull event) { AG_Scrollbar *sb = AG_SELF(); AG_DelTimer(sb, &sb->moveTo); } #endif /* AG_TIMERS */ #undef SET_DEF #define SET_DEF(fn,dmin,dmax,dinc) { \ if (!AG_Defined(sb, "min")) { fn(sb, "min", dmin); } \ if (!AG_Defined(sb, "max")) { fn(sb, "max", dmax); } \ if (!AG_Defined(sb, "inc")) { fn(sb, "inc", dinc); } \ if (!AG_Defined(sb, "visible")) { fn(sb, "visible", 0); } \ } static void OnShow(AG_Event *_Nonnull event) { AG_Scrollbar *sb = AG_SELF(); AG_Variable *V; if ((V = AG_AccessVariable(sb, "value")) == NULL) { V = AG_BindInt(sb, "value", &sb->value); } switch (AG_VARIABLE_TYPE(V)) { #ifdef HAVE_FLOAT case AG_VARIABLE_FLOAT: SET_DEF(AG_SetFloat, 0.0f, 1.0f, 0.1f); break; case AG_VARIABLE_DOUBLE: SET_DEF(AG_SetDouble, 0.0, 1.0, 0.1); break; # ifdef HAVE_LONG_DOUBLE case AG_VARIABLE_LONG_DOUBLE: SET_DEF(AG_SetLongDouble, 0.0l, 1.0l, 0.1l); break; # endif #endif case AG_VARIABLE_INT: SET_DEF(AG_SetInt, 0, AG_INT_MAX-1, 1); break; case AG_VARIABLE_UINT: SET_DEF(AG_SetUint, 0U, AG_UINT_MAX-1, 1U); break; case AG_VARIABLE_UINT8: SET_DEF(AG_SetUint8, 0U, 0xffU, 1U); break; case AG_VARIABLE_SINT8: SET_DEF(AG_SetSint8, 0, 0x7f, 1); break; case AG_VARIABLE_UINT16: SET_DEF(AG_SetUint16, 0U, 0xffffU, 1U); break; case AG_VARIABLE_SINT16: SET_DEF(AG_SetSint16, 0, 0x7fff, 1); break; #if AG_MODEL != AG_SMALL case AG_VARIABLE_UINT32: SET_DEF(AG_SetUint32, 0UL, 0xffffffffUL, 1UL); break; case AG_VARIABLE_SINT32: SET_DEF(AG_SetSint32, 0L, 0x7fffffffL, 1L); break; #endif #ifdef HAVE_64BIT case AG_VARIABLE_UINT64: SET_DEF(AG_SetUint64, 0ULL, 0xffffffffffffffffULL, 1ULL); break; case AG_VARIABLE_SINT64: SET_DEF(AG_SetSint64, 0LL, 0x7fffffffffffffffLL, 1LL); break; #endif default: break; } AG_UnlockVariable(V); if ((sb->flags & AG_SCROLLBAR_EXCL) == 0) { /* Trigger redraw upon external changes to the bindings. */ AG_RedrawOnChange(sb, 500, "value"); AG_RedrawOnChange(sb, 500, "min"); AG_RedrawOnChange(sb, 500, "max"); AG_RedrawOnChange(sb, 500, "visible"); } #if 0 if (sb->flags & AG_SCROLLBAR_AUTOHIDE) AG_AddTimer(sb, &sb->autoHideTo, 250, AutoHideTimeout, NULL); #endif } #undef SET_DEF #ifdef AG_TIMERS static void OnHide(AG_Event *_Nonnull event) { AG_Scrollbar *sb = AG_SELF(); AG_DelTimer(sb, &sb->moveTo); } static void OnDetach(AG_Event *_Nonnull event) { AG_Scrollbar *sb = AG_SELF(); if (sb->flags & AG_SCROLLBAR_AUTOHIDE) AG_DelTimer(sb, &sb->autoHideTo); } #endif /* AG_TIMERS */ static void Init(void *_Nonnull obj) { AG_Scrollbar *sb = obj; WIDGET(sb)->flags |= AG_WIDGET_UNFOCUSED_BUTTONUP| AG_WIDGET_UNFOCUSED_MOTION| AG_WIDGET_FOCUSABLE; sb->type = AG_SCROLLBAR_HORIZ; sb->curBtn = AG_SCROLLBAR_BUTTON_NONE; sb->mouseOverBtn = AG_SCROLLBAR_BUTTON_NONE; sb->flags = AG_SCROLLBAR_AUTOHIDE; sb->buttonIncFn = NULL; sb->buttonDecFn = NULL; sb->xOffs = 0; sb->xSeek = -1; sb->length = 0; sb->lenPre = 32; sb->wBar = agTextFontHeight >> 1; sb->wBarMin = 16; sb->width = agTextFontHeight; sb->hArrow = sb->width >> 1; sb->value = 0; AG_AddEvent(sb, "widget-shown", OnShow, NULL); AG_SetEvent(sb, "mouse-button-down", MouseButtonDown, NULL); AG_SetEvent(sb, "mouse-button-up", MouseButtonUp, NULL); AG_SetEvent(sb, "mouse-motion", MouseMotion, NULL); AG_SetEvent(sb, "key-down", KeyDown, NULL); #ifdef AG_TIMERS AG_InitTimer(&sb->moveTo, "move", 0); AG_InitTimer(&sb->autoHideTo, "autoHide", 0); AG_AddEvent(sb, "detached", OnDetach, NULL); AG_AddEvent(sb, "widget-hidden", OnHide, NULL); AG_SetEvent(sb, "widget-lostfocus", OnFocusLoss, NULL); AG_SetEvent(sb, "key-up", KeyUp, NULL); #endif #if 0 AG_BindInt(sb, "width", &sb->width); AG_BindInt(sb, "length", &sb->length); AG_BindInt(sb, "wBar", &sb->wBar); AG_BindInt(sb, "xOffs", &sb->xOffs); #endif } static void SizeRequest(void *_Nonnull obj, AG_SizeReq *_Nonnull r) { AG_Scrollbar *sb = obj; switch (sb->type) { case AG_SCROLLBAR_HORIZ: r->w = (sb->width << 1) + sb->lenPre; r->h = sb->width; break; case AG_SCROLLBAR_VERT: r->w = sb->width; r->h = (sb->width << 1) + sb->lenPre; break; } } static int SizeAllocate(void *_Nonnull obj, const AG_SizeAlloc *_Nonnull a) { AG_Scrollbar *sb = obj; sb->length = ((sb->type == AG_SCROLLBAR_VERT) ? a->h : a->w) - (sb->width << 1); if (sb->length < 0) { sb->length = 0; } return (0); } static void DrawText(AG_Scrollbar *_Nonnull sb) { char label[32]; AG_Driver *drv = WIDGET(sb)->drv; AG_Surface *txt; AG_Rect r; AG_PushTextState(); AG_TextColor(&WCOLOR(sb,TEXT_COLOR)); Snprintf(label, sizeof(label), (sb->type == AG_SCROLLBAR_HORIZ) ? "%d|%d|%d|%d" : "%d\n:%d\n%d\nv%d\n", AG_GetInt(sb,"min"), AG_GetInt(sb,"value"), AG_GetInt(sb,"max"), AG_GetInt(sb,"visible")); txt = AG_TextRender(label); /* XXX inefficient */ r.x = (WIDTH(sb) >> 1) - (txt->w >> 1); r.y = (HEIGHT(sb) >> 1) - (txt->h >> 1); r.w = txt->w; r.h = txt->h; AG_WidgetBlit(sb, txt, r.x, r.y); AG_SurfaceFree(txt); if (AGDRIVER_CLASS(drv)->updateRegion != NULL) { AG_RectTranslate(&r, WIDGET(sb)->rView.x1, WIDGET(sb)->rView.y1); AGDRIVER_CLASS(drv)->updateRegion(drv, &r); } AG_PopTextState(); } static void DrawVertUndersize(AG_Scrollbar *_Nonnull sb) { AG_Rect r; int w_2, s; r.x = 0; r.y = 0; r.w = WIDTH(sb); r.h = HEIGHT(sb); AG_DrawBox(sb, &r, 1, &WCOLOR(sb,0)); w_2 = (r.w >> 1); s = MIN(r.h>>2, r.w); AG_DrawArrowUp(sb, w_2, s, s, &WCOLOR(sb,SHAPE_COLOR)); AG_DrawArrowDown(sb, w_2, (r.h>>1)+s, s, &WCOLOR(sb,SHAPE_COLOR)); } static void DrawVert(AG_Scrollbar *_Nonnull sb, int y, int len) { AG_Rect r; int w = WIDTH(sb); int h = HEIGHT(sb); int mid = (w >> 1); int wBar = sb->width, wBar2 = (wBar<<1), wBar_2 = (wBar>>1); int hArrow = MIN(w, sb->hArrow); if (h < wBar2) { DrawVertUndersize(sb); return; } r.x = 0; r.y = 0; r.w = w; r.h = h; AG_DrawBox(sb, &r, -1, &WCOLOR(sb,0)); /* Background */ /* XXX overdraw */ /* Up button */ r.h = wBar; AG_DrawBox(sb, &r, (sb->curBtn == AG_SCROLLBAR_BUTTON_DEC) ? -1 : 1, (sb->mouseOverBtn == AG_SCROLLBAR_BUTTON_DEC) ? &WCOLOR_HOV(sb,0) : &WCOLOR(sb,0)); AG_DrawArrowUp(sb, mid, wBar_2, hArrow, &WCOLOR(sb,SHAPE_COLOR)); /* Down button */ r.y = h - wBar; r.h = wBar; AG_DrawBox(sb, &r, (sb->curBtn == AG_SCROLLBAR_BUTTON_INC) ? -1 : 1, (sb->mouseOverBtn == AG_SCROLLBAR_BUTTON_INC) ? &WCOLOR_HOV(sb,0) : &WCOLOR(sb,0)); AG_DrawArrowDown(sb, mid, r.y + wBar_2, hArrow, &WCOLOR(sb,SHAPE_COLOR)); /* Scrollbar */ if (len > 0) { r.y = wBar + y; r.h = MIN(len, h-wBar2); AG_DrawBox(sb, &r, (sb->curBtn == AG_SCROLLBAR_BUTTON_SCROLL) ? -1 : 1, (sb->mouseOverBtn == AG_SCROLLBAR_BUTTON_SCROLL) ? &WCOLOR_HOV(sb,0) : &WCOLOR(sb,0)); } else { r.y = wBar; r.h = h-wBar2; AG_DrawBox(sb, &r, (sb->curBtn == AG_SCROLLBAR_BUTTON_SCROLL) ? -1 : 1, (sb->mouseOverBtn == AG_SCROLLBAR_BUTTON_SCROLL) ? &WCOLOR_HOV(sb,0) : &WCOLOR(sb,0)); } } static void DrawHorizUndersize(AG_Scrollbar *_Nonnull sb) { AG_Rect r; int h_2, s; r.x = 0; r.y = 0; r.w = WIDTH(sb); r.h = HEIGHT(sb); AG_DrawBox(sb, &r, 1, &WCOLOR(sb,0)); h_2 = (r.h >> 1); s = MIN(r.w>>2, r.h); AG_DrawArrowLeft(sb, s, h_2, s, &WCOLOR(sb,SHAPE_COLOR)); AG_DrawArrowRight(sb, (r.w>>1)+s, h_2, s, &WCOLOR(sb,SHAPE_COLOR)); } static void DrawHoriz(AG_Scrollbar *_Nonnull sb, int x, int len) { AG_Rect r; int w = WIDTH(sb); int h = HEIGHT(sb); int h_2 = h >> 1; int wBar = sb->width, wBar2 = (wBar << 1), wBar_2 = (wBar >> 1); int hArrow = MIN(h, sb->hArrow); if (w < wBar2) { DrawHorizUndersize(sb); return; } r.x = 0; r.y = 0; r.w = w; r.h = h; AG_DrawBox(sb, &r, -1, &WCOLOR(sb,0)); /* Background */ /* XXX overdraw */ /* Left button */ r.w = wBar; r.h = h; AG_DrawBox(sb, &r, (sb->curBtn == AG_SCROLLBAR_BUTTON_DEC) ? -1 : 1, &WCOLOR(sb,0)); AG_DrawArrowLeft(sb, wBar_2, h_2, hArrow, &WCOLOR(sb,SHAPE_COLOR)); /* Right button */ r.x = w - wBar; AG_DrawBox(sb, &r, (sb->curBtn == AG_SCROLLBAR_BUTTON_INC) ? -1 : 1, &WCOLOR(sb,0)); AG_DrawArrowRight(sb, r.x + wBar_2, h_2, hArrow, &WCOLOR(sb,SHAPE_COLOR)); /* Scrollbar */ if (len > 0) { r.x = wBar + x; r.w = MIN(len, w-wBar2); AG_DrawBox(sb, &r, (sb->curBtn == AG_SCROLLBAR_BUTTON_SCROLL) ? -1 : 1, &WCOLOR(sb,0)); } else { r.x = wBar; r.w = w - wBar2; AG_DrawBox(sb, &r, (sb->curBtn == AG_SCROLLBAR_BUTTON_SCROLL) ? -1 : 1, &WCOLOR(sb,0)); } } static void Draw(void *_Nonnull obj) { AG_Scrollbar *sb = obj; int x, len; if (GetPxCoords(sb, &x, &len) == -1) { /* No range */ x = 0; len = sb->length; } if (sb->flags & AG_SCROLLBAR_AUTOHIDE && len == sb->length) return; /* * TODO set the Draw() operation vector to DrawVert() or DrawHoriz() * at initialization time and merge this code into both. */ switch (sb->type) { case AG_SCROLLBAR_VERT: DrawVert(sb, x, len); break; case AG_SCROLLBAR_HORIZ: DrawHoriz(sb, x, len); break; } if (sb->flags & AG_SCROLLBAR_TEXT) DrawText(sb); } /* Return 1 if it is useful to display the scrollbar given the current range. */ int AG_ScrollbarVisible(AG_Scrollbar *sb) { int rv, x, len; AG_ObjectLock(sb); if (!AG_Defined(sb, "value") || !AG_Defined(sb, "min") || !AG_Defined(sb, "max") || !AG_Defined(sb, "visible")) { AG_ObjectUnlock(sb); return (1); } rv = (GetPxCoords(sb, &x, &len) == -1) ? 0 : 1; AG_ObjectUnlock(sb); return (rv); } AG_WidgetClass agScrollbarClass = { { "Agar(Widget:Scrollbar)", sizeof(AG_Scrollbar), { 0,0 }, Init, NULL, /* reset */ NULL, /* destroy */ NULL, /* load */ NULL, /* save */ NULL /* edit */ }, Draw, SizeRequest, SizeAllocate };
C
CL
f942d66e7a36fc92a6394284e5eac52541669da1b16586c528c55764e811439f
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <time.h> #include <string.h> #include <math.h> #include "graf_ER.h" #include "double_random.h" /* * gcc -o program main_one_thread.c graf_ER.c double_random.c -I. -std=c99 -Wall -lm -Ofast -O3 -m64 -march=native -fipa-pure-const -fipa-reference -fmerge-constants -fshrink-wrap -fsplit-wide-types -ftree-builtin-call-dce -ftree-copyrename -ftree-dce -ftree-dominator-opts -ftree-dse -ftree-forwprop -ftree-fre -ftree-phiprop -ftree-sra -ftree-pta -ftree-ter -funit-at-a-time -fkeep-inline-functions -fkeep-static-consts -fmerge-constants -fmodulo-sched -fgcse -fdce -fdse -fexpensive-optimizations -fipa-cp-clone -fipa-matrix-reorg -ftree-loop-linear -floop-interchange -floop-strip-mine -floop-block -ftree-loop-distribution -ffast-math -fassociative-math -freciprocal-math -funroll-all-loops -fpeel-loops */ int main(int argc, char *argv[]){ uint N = 320000; double p = 1./(N-1); if (argc == 3){ N = atoi(argv[1]); p = (double) atof(argv[2])/(N-1); printf("%s %f\n", argv[2], (double) atof(argv[2])/(N-1)); } printf("N %d, k %.4f, p %.10f\n",N, (double) p*(N-1), (double) p); init_random(); //present(); clock_t start = clock(); clock_t total = 0; uint64_t num_edges = 0; Vertex* graph = create_graph_ER(N, p, &num_edges); total = clock(); printf("Stworzono graf %.4f s\n", (total - start) / (double)CLOCKS_PER_SEC); start=total; uint num_of_clusters = 0; uint* array_clusters_sizes = calloc((size_t) N , sizeof(uint)); enumerate_clusters(graph,N,array_clusters_sizes, &num_of_clusters); total = clock(); printf("Zliczono klastry %.4f s\n", (total - start) / (double) CLOCKS_PER_SEC ); start=total; uint* array_histogram = calloc((size_t) N, sizeof(uint)); uint S = histogram_clusters(array_clusters_sizes, array_histogram, N, num_of_clusters); total = clock(); printf("Utworzono histogram %.4f s\n", (total - start) / (double) CLOCKS_PER_SEC ); start=total; // preparing file name int str_lenght = 21 + ceil(log10(N)); char filename1[str_lenght]; sprintf(filename1,"point_N%dk%.9f.txt", N, (double) p*(N-1)); str_lenght-=1; char filename2[str_lenght]; sprintf(filename2,"hist_N%dk%.9f.txt", N, (double) p*(N-1)); bin_logaritmic(array_histogram, N, 2., filename2); save_point(N, num_of_clusters, num_edges, S, (double) p*(N-1), filename1); total = clock(); printf("Zapisano dane %.4f s\n", (total - start) / (double) CLOCKS_PER_SEC ); start=total; printf("\nZapisywanie histogramu %s\n", filename2); //print_graph(graph, N); //for (int ii = 0; ii < num_of_clusters; ii++) { // printf("%d. cluster \t%d vertices\n",ii,array_clusters_sizes[ii]); //} printf("\n%d klastrów\n",num_of_clusters); printf("klaster perkolacyjny %d\n\n",S); printf("\t\t wartosci wylosowane / teoretyczne\n"); printf("calkowita ilosc krawedzi E:\t%lu / %.1f \n", num_edges,(double) p*(N-1)*N/2.); printf("prawodopodobienstwo p:\t\t%f/%f\n", (double) 2.*num_edges/(N*(N-1)), (double) p ); printf("sredni stopien grafu k:\t\t%f/%f\n\n",(double) 2.*num_edges/N, (double) p*(N-1)); delete_graph(graph,N); free(array_clusters_sizes); free(array_histogram); return 0; }
C
CL
a469cee7f640a646cf5562d5816cbda86c71a4c63c85372a47c4997fa6580b00
// Copyright (c) Microsoft Corporation // Licensed under the MIT license. See LICENSE file in the project root for full license information. #if !defined(__cplusplus) #error C++11 required #endif #pragma once #include <PFEntity.h> #include <httpClient/async.h> extern "C" { /// <summary> /// Handle to a PlayFabEventManagerEvent. Create events using PlayFabEventManagerEventCreate and write them to PlayFab /// with PlayFabEventManagerWriteEventAsync. When an event is no longer needed, call PlayFabEventManagerEventCloseHandle /// to release the event object. /// </summary> typedef struct PlayFabEventManagerEvent* PlayFabEventManagerEventHandle; /// <summary> /// PlayFab Event types /// </summary> enum class PlayFabEventManagerEventType : uint32_t { /// <summary> /// Default event type (set in global configuration). /// </summary> Default, /// <summary> /// Lightweight event. Will be sent to WriteTelemetryEvents endpoint. /// </summary> Lightweight, /// <summary> /// Lightweight event. Will be sent to WriteEvents endpoint. /// </summary> Heavyweight }; /// <summary> /// PlayFab EventPipeline types /// </summary> enum class PlayFabEventManagerPipelineType : uint32_t { /// <summary> /// PlayStream event pipeline /// </summary> PlayStream = 0x1, /// <summary> /// PlayFab telemetry pipeline (bypasses PlayStream) /// </summary> Telemetry = 0x2, /// <summary> /// All pipelines. Passed to PlayFabEventManagerCustomizeEventPipelineSettings to configure settings for all pipelines at once. /// </summary> All = 0x3 }; DEFINE_ENUM_FLAG_OPERATORS(PlayFabEventManagerPipelineType); // TODO consider fire and forget style (auto retry etc.) /// <summary> /// Callback routine that is invoked when an event is uploaded to PlayFab. /// </summary> /// <param name='context'>A context pointer that was passed during PlayFabEventManagerWriteEventAsync.</param> /// <param name='result'>A result value indicating whether the upload was successful.</param> /// <param name='assignedEventId'>Unique identifier assigned to the event by the server. Will be null if no ID is assigned.</param> /// <seealso cref='PlayFabEventManagerWriteEventAsync' /> typedef void CALLBACK PlayFabEventManagerWriteEventCompletionCallback(_In_opt_ void* context, _In_ HRESULT result, _In_opt_ const char* assignedEventId); /// <summary> /// A callback that is invoked when EventManger termination completes. /// </summary> /// <param name='context'>A context pointer that was passed during PlayFabEventManagerTerminate.</param> /// <seealso cref='PlayFabEventManagerTerminate' /> typedef void CALLBACK PlayFabEventManagerTerminatedCallback(_In_opt_ void* context); /// <summary> /// Creates a PlayFab Event to upload with EventManager. /// </summary> /// <param name="eventType">The type of event.</param> /// <param name="eventName">The name of the event.</param> /// <param name="eventNamespace">Optional namespace. The namespace of the Event must be 'custom' or start with 'custom'. 'custom' will be used if no namespace is provided</param> /// <param name="entityId">Optional entity ID for entity associated with the event. If not provided, the event will apply to the entity that writes it.</param> /// <param name="entityType">Optional entity type for entity associated with the event. If not provided, the event will apply to the entity that writes it.</param> /// <param name="eventHandle">Returned PlayFabEventManagerEventHandle.</param> /// <returns>Result code for this API operation.</returns> /// <remarks> /// The returned eventHandle must be closed with PlayFabEventManagerEventCloseHandle when it is no longer needed. /// </remarks> HRESULT PlayFabEventManagerEventCreate( _In_ PlayFabEventManagerEventType eventType, _In_ const char* eventName, _In_opt_ const char* eventNamespace, _In_opt_ const char* entityId, _In_opt_ const char* entityType, _Out_ PlayFabEventManagerEventHandle* eventHandle ) noexcept; /// <summary> /// Duplicates a PlayFabEventManagerEventHandle. /// </summary> /// <param name="eventHandle">Event handle to duplicate.</param> /// <param name="duplicatedEventHandle">The duplicated handle.</param> /// <returns>Result code for this API operation.</returns> /// <remarks> /// Both the duplicated handle and the original handle need to be closed with PlayFabEventManagerEventCloseHandle when they /// are no longer needed. /// </remarks> HRESULT PlayFabEventManagerEventDuplicateHandle( _In_ PlayFabEventManagerEventHandle eventHandle, _Out_ PlayFabEventManagerEventHandle* duplicatedEventHandle ) noexcept; /// <summary> /// Closes a PlayFabEventManagerEventHandle. /// </summary> /// <param name="eventHandle">Event handle to close.</param> /// <returns>Result code for this API operation.</returns> void PlayFabEventManagerEventCloseHandle( _In_ PlayFabEventManagerEventHandle eventHandle ) noexcept; /// <summary> /// Set the namespace for the event. /// </summary> /// <param name="eventHandle">Event to modify.</param> /// <param name="eventNamespace">Event namespace. The namespace of the Event must be 'custom' or start with 'custom'.</param> /// <returns>Result code for this API operation.</returns> HRESULT PlayFabEventManagerEventSetNamespace( _In_ PlayFabEventManagerEventHandle eventHandle, _In_ const char* eventNamespace ) noexcept; /// <summary> /// Set the Entity associated with the event. If not set, the event will apply to the entity that writes it. /// </summary> /// <param name="eventHandle">Event to modify.</param> /// <param name="entityId">Unique ID of the entity.</param> /// <param name="entityType">(Optional) Entity type. See https://docs.microsoft.com/gaming/playfab/features/data/entities/available-built-in-entity-types. </param> /// <returns>Result code for this API operation.</returns> HRESULT PlayFabEventManagerEventSetEntity( _In_ PlayFabEventManagerEventHandle eventHandle, _In_ const char* entityId, _In_opt_ const char* entityType ) noexcept; /// <summary> /// Set a property associated with the event. Properties are arbitrary key/value pairs that will be added to a JSON payload. /// </summary> /// <param name="eventHandle">Event to modify.</param> /// <param name="key">Property key.</param> /// <param name="value">Property value.</param> /// <returns>Result code for this API operation.</returns> HRESULT PlayFabEventManagerEventSetStringProperty( _In_ PlayFabEventManagerEventHandle eventHandle, _In_ const char* key, _In_ const char* value ) noexcept; /// <summary> /// Set a property associated with the event. Properties are arbitrary key/value pairs that will be added to a JSON payload. /// </summary> /// <param name="eventHandle">Event to modify.</param> /// <param name="key">Property key.</param> /// <param name="value">Property value.</param> /// <returns>Result code for this API operation.</returns> HRESULT PlayFabEventManagerEventSetBooleanProperty( _In_ PlayFabEventManagerEventHandle eventHandle, _In_ const char* key, _In_ bool value ) noexcept; /// <summary> /// Set a property associated with the event. Properties are arbitrary key/value pairs that will be added to a JSON payload. /// </summary> /// <param name="eventHandle">Event to modify.</param> /// <param name="key">Property key.</param> /// <param name="value">Property value.</param> /// <returns>Result code for this API operation.</returns> HRESULT PlayFabEventManagerEventSetIntProperty( _In_ PlayFabEventManagerEventHandle eventHandle, _In_ const char* key, _In_ int64_t value ) noexcept; /// <summary> /// Set a property associated with the event. Properties are arbitrary key/value pairs that will be added to a JSON payload. /// </summary> /// <param name="eventHandle">Event to modify.</param> /// <param name="key">Property key.</param> /// <param name="value">Property value.</param> /// <returns>Result code for this API operation.</returns> HRESULT PlayFabEventManagerEventSetUintProperty( _In_ PlayFabEventManagerEventHandle eventHandle, _In_ const char* key, _In_ uint64_t value ) noexcept; /// <summary> /// Set a property associated with the event. Properties are arbitrary key/value pairs that will be added to a JSON payload. /// </summary> /// <param name="eventHandle">Event to modify.</param> /// <param name="key">Property key.</param> /// <param name="value">Property value.</param> /// <returns>Result code for this API operation.</returns> HRESULT PlayFabEventManagerEventSetDoubleProperty( _In_ PlayFabEventManagerEventHandle eventHandle, _In_ const char* key, _In_ double value ) noexcept; /// <summary> /// Default values for event pipeline settings. /// </summary> /// <seealso cref='PlayFabEventManagerCustomizeEventPipelineSettings' /> const size_t PlayFabEventManagerBufferSizeBytesDefault = 256; const uint32_t PlayFabEventManagerMaxItemsInBatchDefault = 5; const uint32_t PlayFabEventManagerMaxBatchWaitTimeInSecondsDefault = 3; const uint32_t PlayFabEventManagerMaxBatchesInFlightDefault = 16; const uint32_t PlayFabEventManagerPollDelayInMsDefault = 10; /// <summary> /// Optional API set set custom event pipeline settings. Pipeline settings apply to a single entity and must be they must be configured /// prior to calling PlayFabEventManagerWriteEventAsync. If values are not provided PlayFabEventManagerCustomizeEventPipelineSettings /// is never called) the above defaults will be used. /// </summary> /// <param name="entityHandle">PFEntityHandle to customize settings for.</param> /// <param name="pipeline">The event pipeline the provided settings will be applied to. Pass PlayFabEventManagerPipelineType::All to configure settings for all event pipelines.</param> /// <param name="queue">XTaskQueue where background work will be scheduled. If not default value is "null" (process default queue will be used).</param> /// <param name="minimumBufferSizeBytes">The minimum size of the event buffer, in bytes. The actually allocated size will be a power of 2 that is equal or greater than this value.</param> /// <param name="maxItemsInBatch">The max number of items (events) a batch can hold before it is sent out.</param> /// <param name="maxBatchWaitTimeInSeconds">The max wait time before a batch must be sent out even if it's still incomplete, in seconds.</param> /// <param name="maxBatchesInFlight">The max number of batches currently "in flight" (sent to PlayFab service but pending response).</param> /// <param name="pollDelayInMs">The delay between each time the background operation will poll the event buffer and evaluate if events should be uploaded.</param> /// <returns>Result code for this API operation.</returns> HRESULT PlayFabEventManagerCustomizeEventPipelineSettings( _In_ PFEntityHandle entityHandle, _In_ PlayFabEventManagerPipelineType pipeline, _In_opt_ XTaskQueueHandle queue, _In_opt_ size_t* minimumBufferSizeBytes, _In_opt_ size_t* maxItemsInBatch, _In_opt_ uint32_t* maxBatchWaitTimeInSeconds, _In_opt_ size_t* maxBatchesInFlight, _In_opt_ uint32_t* pollDelayInMs ) noexcept; /// <summary> /// Write an event to PlayFab server. Events will be buffered, batched, and uploaded in the background. /// Prior to shutdown, PlayFabEventManagerTerminate should be called to ensure any pending events /// get written to the service. /// </summary> /// <param name="entityHandle">PFEntityHandle returned from a auth call.</param> /// <param name="eventHandle">Event to upload.</param> /// <param name="callbackContext">Optional context pointer to pass to the callback.</param> /// <param name="callback">Optional callback to be called when the event upload (attempt) completes.</param> /// <returns>Result code for this API operation.</returns> HRESULT PlayFabEventManagerWriteEventAsync( _In_ PFEntityHandle entityHandle, _In_ PlayFabEventManagerEventHandle eventHandle, _In_opt_ void* callbackContext, _In_opt_ PlayFabEventManagerWriteEventCompletionCallback* callback ) noexcept; /// <summary> /// Terminate event pipelines prior to shutdown. Ensures pending events are written and in-flight write requests complete. /// If the entityHandle is closed without calling PlayFabEventManagerTerminate, some buffered /// events may be lost. Note that the write result for each event will still be delivered normally via the /// callback provided to PlayFabEventManagerWriteEventAsync. /// </summary> /// <param name="entityHandle">PFEntityHandle returned from a auth call.</param> /// <param name='wait'>True to synchronously wait for the termination to complete.</param> /// <param name="callbackContext">Optional context pointer to pass to the callback.</param> /// <param name="callback">An optional callback that will be called when termination completes.</param> /// <returns>Result code for this API operation.</returns> HRESULT PlayFabEventManagerTerminate( _In_ PFEntityHandle entityHandle, _In_ bool wait, _In_opt_ void* callbackContext, _In_opt_ PlayFabEventManagerTerminatedCallback* callback ) noexcept; }
C
CL
2cc100849a08fe9f3b821c711c624a9b23dadfd850d07f7d3bfff8e8daeaec33
#ifndef STATE_H #define STATE_H #define MAX_EVENT_CNT 5 typedef void (*State)(uint8_t); #define DEFAULT_EVENTS IDLE=0,ENTER=1,EXIT=2 typedef struct { State current_state; uint8_t event_code; State next_state; } Transition; typedef struct { uint8_t event_queue[MAX_EVENT_CNT]; uint8_t start; uint8_t event_cnt; Transition* transitions; uint8_t transition_table_size; /**< Size of transition table */ State state; /**< Current state of the state machine */ } StateMachine; extern StateMachine StateMachineCreate(Transition* rules, uint8_t t_size, State state); extern int8_t StateMachinePublishEvent(StateMachine* s, uint8_t event); extern void StateMachineRun(StateMachine* s); #endif
C
CL
376071100403d42400a8bdcb1141d6b09a98fcfeea5081c95d46137769df13ea
#ifndef CUT_GLOBALS_H #define CUT_GLOBALS_H #ifndef CUT_MAIN #error "cannot be standalone" #endif #define CUT_MAX_LOCAL_MESSAGE_LENGTH 4096 CUT_PRIVATE struct cut_Arguments cut_arguments; CUT_PRIVATE struct cut_UnitTestArray cut_unitTests = {0, 0, NULL}; CUT_PRIVATE FILE *cut_output = NULL; CUT_PRIVATE int cut_outputsRedirected = 0; CUT_PRIVATE int cut_pipeWrite = 0; CUT_PRIVATE int cut_pipeRead = 0; CUT_PRIVATE int cut_originalStdOut = 0; CUT_PRIVATE int cut_originalStdErr = 0; CUT_PRIVATE FILE *cut_stdout = NULL; CUT_PRIVATE FILE *cut_stderr = NULL; CUT_PRIVATE jmp_buf cut_executionPoint; CUT_PRIVATE const char *cut_emergencyLog = "cut.log"; CUT_PRIVATE int cut_localMessageSize = 0; CUT_PRIVATE char cut_localMessage[CUT_MAX_LOCAL_MESSAGE_LENGTH]; CUT_PRIVATE char *cut_localMessageCursor = NULL; CUT_PRIVATE cut_GlobalTear cut_globalTearUp = NULL; CUT_PRIVATE cut_GlobalTear cut_globalTearDown = NULL; #endif // CUT_GLOBALS_H
C
CL
ad5f9f0d27635ab6648d92d4710cc6ef6454f5a58c288e8400327e431a880b3c
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ typedef struct TYPE_3__ TYPE_1__ ; /* Type definitions */ struct TYPE_3__ {struct journal_head* t_checkpoint_list; } ; typedef TYPE_1__ transaction_t ; struct journal_head {struct journal_head* b_cpprev; struct journal_head* b_cpnext; TYPE_1__* b_cp_transaction; } ; /* Variables and functions */ int /*<<< orphan*/ JBUFFER_TRACE (struct journal_head*,char*) ; int /*<<< orphan*/ J_ASSERT_JH (struct journal_head*,int) ; scalar_t__ buffer_dirty (int /*<<< orphan*/ ) ; scalar_t__ buffer_jbddirty (int /*<<< orphan*/ ) ; int /*<<< orphan*/ jbd2_journal_grab_journal_head (int /*<<< orphan*/ ) ; int /*<<< orphan*/ jh2bh (struct journal_head*) ; void __jbd2_journal_insert_checkpoint(struct journal_head *jh, transaction_t *transaction) { JBUFFER_TRACE(jh, "entry"); J_ASSERT_JH(jh, buffer_dirty(jh2bh(jh)) || buffer_jbddirty(jh2bh(jh))); J_ASSERT_JH(jh, jh->b_cp_transaction == NULL); /* Get reference for checkpointing transaction */ jbd2_journal_grab_journal_head(jh2bh(jh)); jh->b_cp_transaction = transaction; if (!transaction->t_checkpoint_list) { jh->b_cpnext = jh->b_cpprev = jh; } else { jh->b_cpnext = transaction->t_checkpoint_list; jh->b_cpprev = transaction->t_checkpoint_list->b_cpprev; jh->b_cpprev->b_cpnext = jh; jh->b_cpnext->b_cpprev = jh; } transaction->t_checkpoint_list = jh; }
C
CL
07d6e63becc0a37eab297fba4af49ce87fd84ae22357005b05b0afb2b1d327d9