text
stringlengths
54
60.6k
<commit_before>/*********************************************************************** OpenSync Plugin for KDE 3.x Copyright (C) 2004 Stewart Heitmann <sheitmann@users.sourceforge.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation; 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 OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS SOFTWARE IS DISCLAIMED. *************************************************************************/ /* * 03 Nov 2004 - Eduardo Pereira Habkost <ehabkost@conectiva.com.br> * - Ported to OpenSync plugin interface */ extern "C" { #include <opensync/opensync.h> #include "kaddrbook.h" } #include <kabc/stdaddressbook.h> #include <kabc/vcardconverter.h> #include <kcmdlineargs.h> #include <kapplication.h> #include <klocale.h> #include <qsignal.h> #include <qfile.h> static void unfold_vcard(char *vcard, size_t *size) { char* in = vcard; char* out = vcard; char *end = vcard + *size; while ( in < end) { /* remove any occurrences of "=[CR][LF]" */ /* these denote folded line markers in VCARD format. */ /* Dont know why, but Evolution uses the leading "=" */ /* character to (presumably) denote a control sequence. */ /* This is not quite how I interpret the VCARD RFC2426 */ /* spec (section 2.6 line delimiting and folding). */ /* This seems to work though, so thats the main thing! */ if (in[0]=='=' && in[1]==13 && in[2]==10) in+=3; else *out++ = *in++; } *size = out - vcard; } class kaddrbook { private: KABC::AddressBook* addressbookptr; KABC::Ticket* addressbookticket; QDateTime syncdate, newsyncdate; OSyncMember *member; OSyncHashTable *hashtable; public: kaddrbook(OSyncMember *memb) :member(memb) { //osync_debug("kde", 3, "kdepim_plugin: %s(%s)\n", __FUNCTION__); //get a handle to the standard KDE addressbook addressbookptr = KABC::StdAddressBook::self(); //ensure a NULL Ticket ptr addressbookticket=NULL; hashtable = osync_hashtable_new(); osync_hashtable_load(hashtable, member); }; int get_changes(OSyncContext *ctx) { //osync_debug("kde", 3, "kdepim_plugin: kaddrbook::%s(newdbs=%d)\n", __FUNCTION__, newdbs); //remember when we started this current sync newsyncdate = QDateTime::currentDateTime(); // We must reload the KDE addressbook in order to retrieve the latest changes. if (!addressbookptr->load()) { osync_debug("kde", 3, "kdepim_plugin: couldnt reload KDE addressbook, aborting sync.\n"); return -1; } osync_debug("kde", 3, "kdepim_plugin: KDE addressbook reloaded OK.\n"); //Lock the addressbook addressbookticket = addressbookptr->requestSaveTicket(); if (!addressbookticket) { osync_debug("kde", 3, "kdepim_plugin: couldnt lock KDE addressbook, aborting sync.\n"); return -1; } osync_debug("kde", 3, "kdepim_plugin: KDE addressbook locked OK.\n"); //osync_debug("kde", 3, "%s: %s : plugin UID list has %d entries\n", __FILE__, __FUNCTION__, uidlist.count()); //Check the entries of the KDE addressbook against the last entries seen by the sync-engine for (KABC::AddressBook::Iterator it=addressbookptr->begin(); it!=addressbookptr->end(); it++ ) { //Get the revision date of the KDE addressbook entry. //Regard entries with invalid revision dates as having just been changed. osync_debug("kde", 3, "new entry, uid: %s\n", it->uid().latin1()); QDateTime revdate = it->revision(); if (!revdate.isValid()) { revdate = newsyncdate; //use date of this sync as the revision date. it->setRevision(revdate); //update the Addressbook entry for future reference. } // gmalloc a changed_object for this phonebook entry //FIXME: deallocate it somewhere OSyncChange *chg= osync_change_new(); osync_change_set_member(chg, member); QCString hash(revdate.toString()); osync_change_set_hash(chg, hash); osync_change_set_uid(chg, it->uid().latin1()); // Convert the VCARD data into a string KABC::VCardConverter converter; QString card = converter.createVCard(*it); QString data(card.latin1()); //FIXME: deallocate data somewhere osync_change_set_data(chg, strdup(data), data.length(), 1); // set the remaining fields osync_change_set_objtype_string(chg, "contact"); osync_change_set_objformat_string(chg, "vcard"); osync_change_set_hash(chg, hash.data()); /*FIXME: slowsync */ if (osync_hashtable_detect_change(hashtable, chg, 0)) { osync_context_report_change(ctx, chg); osync_hashtable_update_hash(hashtable, chg); } } osync_hashtable_report_deleted(hashtable, ctx, 0); return 0; } int modify(OSyncChange *chg) { //osync_debug("kde", 3, "kdepim_plugin: kaddrbook::%s()\n",__FUNCTION__); int result = 0; // Ensure we still have a lock on the KDE addressbook (we ought to) if (addressbookticket==NULL) { //This should never happen, but just in case.... osync_debug("kde", 3, "kdepim_plugin: lock on KDE addressbook was lost, aborting sync.\n"); return -1; } KABC::VCardConverter converter; /* allocate and initialize return struct for this change entry */ //FIXME: check how to return errors safely //modify_result = (syncobj_modify_result*)g_malloc0(sizeof(syncobj_modify_result)); //modify_result->result = SYNC_MSG_MODIFYERROR; //modify_result->returnuid = NULL; OSyncObjType *type = osync_change_get_objtype(chg); // Do database modifications according to object type if (!strcmp(osync_objtype_get_name(type), "contact")) { OSyncChangeType chtype = osync_change_get_changetype(chg); char *uid = osync_change_get_uid(chg); /* treat modified objects without UIDs as if they were newly added objects */ if (chtype == CHANGE_MODIFIED && !uid) chtype = CHANGE_ADDED; // convert VCARD string from obj->comp into an Addresse object. char *data; size_t data_size; data = (char*)osync_change_get_data(chg); data_size = osync_change_get_datasize(chg); switch(chtype) { case CHANGE_MODIFIED: { unfold_vcard(data, &data_size); KABC::Addressee addressee = converter.parseVCard(QString::fromLatin1(data, data_size)); // ensure it has the correct UID addressee.setUid(QString(uid)); // replace the current addressbook entry (if any) with the new one addressbookptr->insertAddressee(addressee); osync_debug("kde", 3, "kdepim_plugin: KDE ADDRESSBOOK ENTRY UPDATED (UID=%s)\n", uid); result = 0; break; } case CHANGE_ADDED: { // convert VCARD string from obj->comp into an Addresse object // KABC::VCardConverter doesnt do VCARD unfolding so we must do it ourselves first. unfold_vcard(data, &data_size); KABC::Addressee addressee = converter.parseVCard(QString::fromLatin1(data, data_size)); // ensure it has a NULL UID addressee.setUid(QString(NULL)); // add the new address to the addressbook addressbookptr->insertAddressee(addressee); osync_debug("kde", 3, "kdepim_plugin: KDE ADDRESSBOOK ENTRY ADDED (UID=%s)\n", addressee.uid().latin1()); // return the UID of the new entry along with the result osync_change_set_uid(chg, addressee.uid().latin1()); result = 0; break; } case CHANGE_DELETED: { if (uid==NULL) { result = 1; break; } //find addressbook entry with matching UID and delete it KABC::Addressee addressee = addressbookptr->findByUid(QString(uid)); if(!addressee.isEmpty()) addressbookptr->removeAddressee(addressee); osync_debug("kde", 3, "kdepim_plugin: KDE ADDRESSBOOK ENTRY DELETED (UID=%s)\n", uid); result = 0; break; } default: result = 0; } } //FIXME: handle unsupported objtypes return result; } void sync_done(bool success) { //osync_debug("kde", 3, "kdepim_plugin: kaddrbook::%s(%d)\n", __FUNCTION__, success); if (!addressbookticket) { //This should never happen, but just in case osync_debug("kde", 3, "kdepim_plugin: lock on KDE addressbook was lost, aborting sync.\n"); return; } if (success) { // Save and unlock the KDE addressbook addressbookptr->save(addressbookticket); osync_debug("kde", 3, "kdepim_plugin: KDE addressbook saved and unlocked.\n"); //update the syncdate syncdate = newsyncdate; } else { // Unlock the KDE addressbook and discard all changes addressbookptr->releaseSaveTicket(addressbookticket); osync_debug("kde", 3, "kdepim_plugin: KDE addressbook unlocked and changes discarded.\n"); } addressbookticket=NULL; } }; static KApplication *applicationptr=NULL; static char name[] = "kde-opensync-plugin"; static char *argv[] = {name,0}; static kaddrbook *addrbook_for_context(OSyncContext *ctx) { return (kaddrbook *)osync_context_get_plugin_data(ctx); } static void *kde_initialize(OSyncMember *member) { kaddrbook *addrbook; osync_debug("kde", 3, "kdepim_plugin: %s()\n",__FUNCTION__); osync_debug("kde", 3, "kdepim_plugin: %s\n", __FUNCTION__); KCmdLineArgs::init(1, argv, "kde-opensync-plugin", i18n("KOpenSync"), "KDE OpenSync plugin", "0.1", false); applicationptr = new KApplication(); /* Allocate and initialise a kaddrbook object. */ addrbook = new kaddrbook(member); if (!addrbook) //FIXME: Check if OSYNC_ERROR_GENERIC is the righ error code in this case return NULL; /* Return kaddrbook object to the sync engine */ return (void*)addrbook; } static void kde_finalize(void *data) { osync_debug("kde", 3, "kdepim_plugin: %s()\n", __FUNCTION__); kaddrbook *addrbook = (kaddrbook *)data; delete addrbook; if (applicationptr) { delete applicationptr; applicationptr = 0; } } static void kde_connect(OSyncContext *ctx) { osync_context_report_success(ctx); } static void kde_disconnect(OSyncContext *ctx) { osync_context_report_success(ctx); } static void kde_get_changeinfo(OSyncContext *ctx) { kaddrbook *addrbook = addrbook_for_context(ctx); osync_debug("kde", 3, "kdepim_plugin: %s\n",__FUNCTION__); int err = addrbook->get_changes(ctx); if (err) { osync_context_report_error(ctx, OSYNC_ERROR_GENERIC, "Couldn't access KDE addressbook"); return; } osync_context_report_success(ctx); return; } static osync_bool kde_commit_change(OSyncContext *ctx, OSyncChange *change) { kaddrbook *addrbook = addrbook_for_context(ctx); int err; osync_debug("kde", 3, "kdepim_plugin: %s()\n",__FUNCTION__); err = addrbook->modify(change); //FIXME: check when call sync_done() addrbook->sync_done(!err); if (err) osync_context_report_error(ctx, OSYNC_ERROR_GENERIC, "Couldn't update KDE addressbook"); else osync_context_report_success(ctx); /*FIXME: What should be returned? */ return true; } extern "C" { void get_info(OSyncPluginInfo *info) { info->version = 1; info->name = "kde-sync"; info->description = i18n("Plugin for the KDE 3.x Addressbook"); info->functions.initialize = kde_initialize; info->functions.connect = kde_connect; info->functions.disconnect = kde_disconnect; info->functions.finalize = kde_finalize; info->functions.get_changeinfo = kde_get_changeinfo; osync_plugin_accept_objtype(info, "contact"); osync_plugin_accept_objformat(info, "contact", "vcard"); /*FIXME: check the differences between commit_change() and access() */ osync_plugin_set_commit_objformat(info, "contact", "vcard", kde_commit_change); osync_plugin_set_access_objformat(info, "contact", "vcard", kde_commit_change); } }// extern "C" <commit_msg>Honour slow_sync settings No need to check objtype, the kaddrbook->modify() method will be called only for contact changes<commit_after>/*********************************************************************** OpenSync Plugin for KDE 3.x Copyright (C) 2004 Stewart Heitmann <sheitmann@users.sourceforge.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation; 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 OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS SOFTWARE IS DISCLAIMED. *************************************************************************/ /* * 03 Nov 2004 - Eduardo Pereira Habkost <ehabkost@conectiva.com.br> * - Ported to OpenSync plugin interface */ extern "C" { #include <opensync/opensync.h> #include "kaddrbook.h" } #include <kabc/stdaddressbook.h> #include <kabc/vcardconverter.h> #include <kcmdlineargs.h> #include <kapplication.h> #include <klocale.h> #include <qsignal.h> #include <qfile.h> static void unfold_vcard(char *vcard, size_t *size) { char* in = vcard; char* out = vcard; char *end = vcard + *size; while ( in < end) { /* remove any occurrences of "=[CR][LF]" */ /* these denote folded line markers in VCARD format. */ /* Dont know why, but Evolution uses the leading "=" */ /* character to (presumably) denote a control sequence. */ /* This is not quite how I interpret the VCARD RFC2426 */ /* spec (section 2.6 line delimiting and folding). */ /* This seems to work though, so thats the main thing! */ if (in[0]=='=' && in[1]==13 && in[2]==10) in+=3; else *out++ = *in++; } *size = out - vcard; } class kaddrbook { private: KABC::AddressBook* addressbookptr; KABC::Ticket* addressbookticket; QDateTime syncdate, newsyncdate; OSyncMember *member; OSyncHashTable *hashtable; public: kaddrbook(OSyncMember *memb) :member(memb) { //osync_debug("kde", 3, "kdepim_plugin: %s(%s)\n", __FUNCTION__); //get a handle to the standard KDE addressbook addressbookptr = KABC::StdAddressBook::self(); //ensure a NULL Ticket ptr addressbookticket=NULL; hashtable = osync_hashtable_new(); osync_hashtable_load(hashtable, member); }; int get_changes(OSyncContext *ctx) { //osync_debug("kde", 3, "kdepim_plugin: kaddrbook::%s(newdbs=%d)\n", __FUNCTION__, newdbs); osync_bool slow_sync = osync_member_get_slow_sync(member, "contact"); //remember when we started this current sync newsyncdate = QDateTime::currentDateTime(); // We must reload the KDE addressbook in order to retrieve the latest changes. if (!addressbookptr->load()) { osync_debug("kde", 3, "kdepim_plugin: couldnt reload KDE addressbook, aborting sync.\n"); return -1; } osync_debug("kde", 3, "kdepim_plugin: KDE addressbook reloaded OK.\n"); //Lock the addressbook addressbookticket = addressbookptr->requestSaveTicket(); if (!addressbookticket) { osync_debug("kde", 3, "kdepim_plugin: couldnt lock KDE addressbook, aborting sync.\n"); return -1; } osync_debug("kde", 3, "kdepim_plugin: KDE addressbook locked OK.\n"); //osync_debug("kde", 3, "%s: %s : plugin UID list has %d entries\n", __FILE__, __FUNCTION__, uidlist.count()); //Check the entries of the KDE addressbook against the last entries seen by the sync-engine for (KABC::AddressBook::Iterator it=addressbookptr->begin(); it!=addressbookptr->end(); it++ ) { //Get the revision date of the KDE addressbook entry. //Regard entries with invalid revision dates as having just been changed. osync_debug("kde", 3, "new entry, uid: %s\n", it->uid().latin1()); QDateTime revdate = it->revision(); if (!revdate.isValid()) { revdate = newsyncdate; //use date of this sync as the revision date. it->setRevision(revdate); //update the Addressbook entry for future reference. } // gmalloc a changed_object for this phonebook entry //FIXME: deallocate it somewhere OSyncChange *chg= osync_change_new(); osync_change_set_member(chg, member); QCString hash(revdate.toString()); osync_change_set_hash(chg, hash); osync_change_set_uid(chg, it->uid().latin1()); // Convert the VCARD data into a string KABC::VCardConverter converter; QString card = converter.createVCard(*it); QString data(card.latin1()); //FIXME: deallocate data somewhere osync_change_set_data(chg, strdup(data), data.length(), 1); // set the remaining fields osync_change_set_objtype_string(chg, "contact"); osync_change_set_objformat_string(chg, "vcard"); osync_change_set_hash(chg, hash.data()); /*FIXME: slowsync */ if (osync_hashtable_detect_change(hashtable, chg, slow_sync)) { osync_context_report_change(ctx, chg); osync_hashtable_update_hash(hashtable, chg); } } osync_hashtable_report_deleted(hashtable, ctx, slow_sync); return 0; } int modify(OSyncChange *chg) { //osync_debug("kde", 3, "kdepim_plugin: kaddrbook::%s()\n",__FUNCTION__); int result = 0; // Ensure we still have a lock on the KDE addressbook (we ought to) if (addressbookticket==NULL) { //This should never happen, but just in case.... osync_debug("kde", 3, "kdepim_plugin: lock on KDE addressbook was lost, aborting sync.\n"); return -1; } KABC::VCardConverter converter; /* allocate and initialize return struct for this change entry */ //FIXME: check how to return errors safely //modify_result = (syncobj_modify_result*)g_malloc0(sizeof(syncobj_modify_result)); //modify_result->result = SYNC_MSG_MODIFYERROR; //modify_result->returnuid = NULL; OSyncChangeType chtype = osync_change_get_changetype(chg); char *uid = osync_change_get_uid(chg); /* treat modified objects without UIDs as if they were newly added objects */ if (chtype == CHANGE_MODIFIED && !uid) chtype = CHANGE_ADDED; // convert VCARD string from obj->comp into an Addresse object. char *data; size_t data_size; data = (char*)osync_change_get_data(chg); data_size = osync_change_get_datasize(chg); switch(chtype) { case CHANGE_MODIFIED: { unfold_vcard(data, &data_size); KABC::Addressee addressee = converter.parseVCard(QString::fromLatin1(data, data_size)); // ensure it has the correct UID addressee.setUid(QString(uid)); // replace the current addressbook entry (if any) with the new one addressbookptr->insertAddressee(addressee); osync_debug("kde", 3, "kdepim_plugin: KDE ADDRESSBOOK ENTRY UPDATED (UID=%s)\n", uid); result = 0; break; } case CHANGE_ADDED: { // convert VCARD string from obj->comp into an Addresse object // KABC::VCardConverter doesnt do VCARD unfolding so we must do it ourselves first. unfold_vcard(data, &data_size); KABC::Addressee addressee = converter.parseVCard(QString::fromLatin1(data, data_size)); // ensure it has a NULL UID addressee.setUid(QString(NULL)); // add the new address to the addressbook addressbookptr->insertAddressee(addressee); osync_debug("kde", 3, "kdepim_plugin: KDE ADDRESSBOOK ENTRY ADDED (UID=%s)\n", addressee.uid().latin1()); // return the UID of the new entry along with the result osync_change_set_uid(chg, addressee.uid().latin1()); result = 0; break; } case CHANGE_DELETED: { if (uid==NULL) { result = 1; break; } //find addressbook entry with matching UID and delete it KABC::Addressee addressee = addressbookptr->findByUid(QString(uid)); if(!addressee.isEmpty()) addressbookptr->removeAddressee(addressee); osync_debug("kde", 3, "kdepim_plugin: KDE ADDRESSBOOK ENTRY DELETED (UID=%s)\n", uid); result = 0; break; } default: result = 0; } return result; } void sync_done(bool success) { //osync_debug("kde", 3, "kdepim_plugin: kaddrbook::%s(%d)\n", __FUNCTION__, success); if (!addressbookticket) { //This should never happen, but just in case osync_debug("kde", 3, "kdepim_plugin: lock on KDE addressbook was lost, aborting sync.\n"); return; } if (success) { // Save and unlock the KDE addressbook addressbookptr->save(addressbookticket); osync_debug("kde", 3, "kdepim_plugin: KDE addressbook saved and unlocked.\n"); //update the syncdate syncdate = newsyncdate; } else { // Unlock the KDE addressbook and discard all changes addressbookptr->releaseSaveTicket(addressbookticket); osync_debug("kde", 3, "kdepim_plugin: KDE addressbook unlocked and changes discarded.\n"); } addressbookticket=NULL; } }; static KApplication *applicationptr=NULL; static char name[] = "kde-opensync-plugin"; static char *argv[] = {name,0}; static kaddrbook *addrbook_for_context(OSyncContext *ctx) { return (kaddrbook *)osync_context_get_plugin_data(ctx); } static void *kde_initialize(OSyncMember *member) { kaddrbook *addrbook; osync_debug("kde", 3, "kdepim_plugin: %s()\n",__FUNCTION__); osync_debug("kde", 3, "kdepim_plugin: %s\n", __FUNCTION__); KCmdLineArgs::init(1, argv, "kde-opensync-plugin", i18n("KOpenSync"), "KDE OpenSync plugin", "0.1", false); applicationptr = new KApplication(); /* Allocate and initialise a kaddrbook object. */ addrbook = new kaddrbook(member); if (!addrbook) //FIXME: Check if OSYNC_ERROR_GENERIC is the righ error code in this case return NULL; /* Return kaddrbook object to the sync engine */ return (void*)addrbook; } static void kde_finalize(void *data) { osync_debug("kde", 3, "kdepim_plugin: %s()\n", __FUNCTION__); kaddrbook *addrbook = (kaddrbook *)data; delete addrbook; if (applicationptr) { delete applicationptr; applicationptr = 0; } } static void kde_connect(OSyncContext *ctx) { osync_context_report_success(ctx); } static void kde_disconnect(OSyncContext *ctx) { osync_context_report_success(ctx); } static void kde_get_changeinfo(OSyncContext *ctx) { kaddrbook *addrbook = addrbook_for_context(ctx); osync_debug("kde", 3, "kdepim_plugin: %s\n",__FUNCTION__); int err = addrbook->get_changes(ctx); if (err) { osync_context_report_error(ctx, OSYNC_ERROR_GENERIC, "Couldn't access KDE addressbook"); return; } osync_context_report_success(ctx); return; } static osync_bool kde_commit_change(OSyncContext *ctx, OSyncChange *change) { kaddrbook *addrbook = addrbook_for_context(ctx); int err; osync_debug("kde", 3, "kdepim_plugin: %s()\n",__FUNCTION__); err = addrbook->modify(change); //FIXME: check when call sync_done() addrbook->sync_done(!err); if (err) osync_context_report_error(ctx, OSYNC_ERROR_GENERIC, "Couldn't update KDE addressbook"); else osync_context_report_success(ctx); /*FIXME: What should be returned? */ return true; } extern "C" { void get_info(OSyncPluginInfo *info) { info->version = 1; info->name = "kde-sync"; info->description = i18n("Plugin for the KDE 3.x Addressbook"); info->functions.initialize = kde_initialize; info->functions.connect = kde_connect; info->functions.disconnect = kde_disconnect; info->functions.finalize = kde_finalize; info->functions.get_changeinfo = kde_get_changeinfo; osync_plugin_accept_objtype(info, "contact"); osync_plugin_accept_objformat(info, "contact", "vcard"); /*FIXME: check the differences between commit_change() and access() */ osync_plugin_set_commit_objformat(info, "contact", "vcard", kde_commit_change); osync_plugin_set_access_objformat(info, "contact", "vcard", kde_commit_change); } }// extern "C" <|endoftext|>
<commit_before>// Copyright (c) 2017-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <consensus/tx_verify.h> #include <consensus/consensus.h> #include <primitives/transaction.h> #include <script/interpreter.h> #include <consensus/validation.h> // TODO remove the following dependencies #include <chain.h> #include <coins.h> #include <util/moneystr.h> // SYSCOIN #include <services/asset.h> bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime) { if (tx.nLockTime == 0) return true; if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime)) return true; for (const auto& txin : tx.vin) { if (!(txin.nSequence == CTxIn::SEQUENCE_FINAL)) return false; } return true; } std::pair<int, int64_t> CalculateSequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block) { assert(prevHeights->size() == tx.vin.size()); // Will be set to the equivalent height- and time-based nLockTime // values that would be necessary to satisfy all relative lock- // time constraints given our view of block chain history. // The semantics of nLockTime are the last invalid height/time, so // use -1 to have the effect of any height or time being valid. int nMinHeight = -1; int64_t nMinTime = -1; // tx.nVersion is signed integer so requires cast to unsigned otherwise // we would be doing a signed comparison and half the range of nVersion // wouldn't support BIP 68. bool fEnforceBIP68 = static_cast<uint32_t>(tx.nVersion) >= 2 && flags & LOCKTIME_VERIFY_SEQUENCE; // Do not enforce sequence numbers as a relative lock time // unless we have been instructed to if (!fEnforceBIP68) { return std::make_pair(nMinHeight, nMinTime); } for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) { const CTxIn& txin = tx.vin[txinIndex]; // Sequence numbers with the most significant bit set are not // treated as relative lock-times, nor are they given any // consensus-enforced meaning at this point. if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) { // The height of this input is not relevant for sequence locks (*prevHeights)[txinIndex] = 0; continue; } int nCoinHeight = (*prevHeights)[txinIndex]; if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) { int64_t nCoinTime = block.GetAncestor(std::max(nCoinHeight-1, 0))->GetMedianTimePast(); // NOTE: Subtract 1 to maintain nLockTime semantics // BIP 68 relative lock times have the semantics of calculating // the first block or time at which the transaction would be // valid. When calculating the effective block time or height // for the entire transaction, we switch to using the // semantics of nLockTime which is the last invalid block // time or height. Thus we subtract 1 from the calculated // time or height. // Time-based relative lock-times are measured from the // smallest allowed timestamp of the block containing the // txout being spent, which is the median time past of the // block prior. nMinTime = std::max(nMinTime, nCoinTime + (int64_t)((txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) << CTxIn::SEQUENCE_LOCKTIME_GRANULARITY) - 1); } else { nMinHeight = std::max(nMinHeight, nCoinHeight + (int)(txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) - 1); } } return std::make_pair(nMinHeight, nMinTime); } bool EvaluateSequenceLocks(const CBlockIndex& block, std::pair<int, int64_t> lockPair) { assert(block.pprev); int64_t nBlockTime = block.pprev->GetMedianTimePast(); if (lockPair.first >= block.nHeight || lockPair.second >= nBlockTime) return false; return true; } bool SequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block) { return EvaluateSequenceLocks(block, CalculateSequenceLocks(tx, flags, prevHeights, block)); } unsigned int GetLegacySigOpCount(const CTransaction& tx) { unsigned int nSigOps = 0; for (const auto& txin : tx.vin) { nSigOps += txin.scriptSig.GetSigOpCount(false); } for (const auto& txout : tx.vout) { nSigOps += txout.scriptPubKey.GetSigOpCount(false); } return nSigOps; } unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs) { if (tx.IsCoinBase()) return 0; unsigned int nSigOps = 0; for (unsigned int i = 0; i < tx.vin.size(); i++) { const Coin& coin = inputs.AccessCoin(tx.vin[i].prevout); assert(!coin.IsSpent()); const CTxOut &prevout = coin.out; if (prevout.scriptPubKey.IsPayToScriptHash()) nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig); } return nSigOps; } int64_t GetTransactionSigOpCost(const CTransaction& tx, const CCoinsViewCache& inputs, int flags) { int64_t nSigOps = GetLegacySigOpCount(tx) * WITNESS_SCALE_FACTOR; if (tx.IsCoinBase()) return nSigOps; if (flags & SCRIPT_VERIFY_P2SH) { nSigOps += GetP2SHSigOpCount(tx, inputs) * WITNESS_SCALE_FACTOR; } for (unsigned int i = 0; i < tx.vin.size(); i++) { const Coin& coin = inputs.AccessCoin(tx.vin[i].prevout); assert(!coin.IsSpent()); const CTxOut &prevout = coin.out; nSigOps += CountWitnessSigOps(tx.vin[i].scriptSig, prevout.scriptPubKey, &tx.vin[i].scriptWitness, flags); } return nSigOps; } // SYSCOIN bool AssetOutputRange(const CAmount& nAmount, const int32_t& nVersion, const bool &isAssetTx) { if(isAssetTx) { // can be >= 0, validate that only one output exists == 0 in checkassetinputs() if(nVersion == SYSCOIN_TX_VERSION_ASSET_SEND) return AssetMoneyRange(nAmount); else return nAmount == 0; } return AssetRange(nAmount); } // SYSCOIN remove const CTransaction bool Consensus::CheckTxInputs(CTransaction& tx, TxValidationState& state, const CCoinsViewCache &inputs, int nSpendHeight, CAmount& txfee, const CAssetAllocation &allocation) { // are the actual inputs available? if (!inputs.HaveInputs(tx)) { return state.Invalid(TxValidationResult::TX_MISSING_INPUTS, "bad-txns-inputs-missingorspent", strprintf("%s: inputs missing/spent", __func__)); } const bool &isSyscoinWithNoInputTx = IsSyscoinWithNoInputTx(tx.nVersion); const bool &isSyscoinTx = IsSyscoinTx(tx.nVersion); const bool &isAssetTx = IsAssetTx(tx.nVersion); CAmount nValueIn = 0; std::unordered_map<int32_t, CAmount> mapAssetIn; std::unordered_map<int32_t, CAmount> mapAssetOut; std::unordered_set<uint32_t> setUsedIndex; for (unsigned int i = 0; i < tx.vin.size(); ++i) { const COutPoint &prevout = tx.vin[i].prevout; const Coin& coin = inputs.AccessCoin(prevout); assert(!coin.IsSpent()); // If prev is coinbase, check that it's matured if (coin.IsCoinBase() && nSpendHeight - coin.nHeight < COINBASE_MATURITY) { return state.Invalid(TxValidationResult::TX_PREMATURE_SPEND, "bad-txns-premature-spend-of-coinbase", strprintf("tried to spend coinbase at depth %d", nSpendHeight - coin.nHeight)); } if(coin.out.assetInfo.nAsset > 0) { if(!AssetOutputRange(coin.out.assetInfo.nValue, tx.nVersion, isAssetTx)) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-asset-inputvalues-outofrange"); } auto inRes = mapAssetIn.emplace(coin.out.assetInfo.nAsset, 0); if(!inRes.second) { inRes.first->second += coin.out.assetInfo.nValue; } } // Check for negative or overflow input values nValueIn += coin.out.nValue; if (!MoneyRange(coin.out.nValue) || !MoneyRange(nValueIn)) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-inputvalues-outofrange"); } } const CAmount &value_out = tx.GetValueOut(); if (nValueIn < value_out){ return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-in-belowout", strprintf("value in (%s) < value out (%s)", FormatMoney(nValueIn), FormatMoney(value_out))); } if(isSyscoinTx) { if(allocation.voutAssets.empty()) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-asset-empty-map-out"); } // CTxOut does not serialize assetInfo to make it consistent with Bitcoin serializaion, CTxOutInfo (used by utxo db) persists assetInfo // it will add txoutinfo based on vout.assetInfo std::vector<CTxOut>& vout = *const_cast<std::vector<CTxOut>*>(&tx.vout); // clear asset info so we don't get previous assetInfo colouring for(unsigned int i =0;i< vout.size(); i++) { if(!vout[i].assetInfo.IsNull()) return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-asset-info-not-null"); } for(const auto &it: allocation.voutAssets) { const int32_t &nAsset = it.first; if(it.second.empty()) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-asset-empty-out"); } CAmount nTotal = 0; for(const auto& voutAsset: it.second){ const CAmount& nAmount = voutAsset.nValue; if(!AssetOutputRange(nAmount, tx.nVersion, isAssetTx)) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-asset-out-outofrange"); } const uint32_t& nOut = voutAsset.n; auto itSet = setUsedIndex.emplace(nOut); if(!itSet.second) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-asset-out-not-unique"); } if(nOut > vout.size()) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-asset-invalid-vout-index"); } vout[nOut].assetInfo = CAssetCoinInfo(nAsset, nAmount); nTotal += nAmount; } if(!AssetOutputRange(nTotal, tx.nVersion, isAssetTx)) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-asset-total-outofrange"); } auto itRes = mapAssetOut.emplace(it.first, nTotal); if(!itRes.second) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-asset-not-unique"); } } // if input was used, validate it against output (note, no fees for assets in == out) if(!isSyscoinWithNoInputTx && mapAssetIn != mapAssetOut) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-assets-io-mismatch"); } } // Tally transaction fees const CAmount txfee_aux = nValueIn - value_out; if (!MoneyRange(txfee_aux)) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-fee-outofrange"); } txfee = txfee_aux; return true; } <commit_msg>rmv comment<commit_after>// Copyright (c) 2017-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <consensus/tx_verify.h> #include <consensus/consensus.h> #include <primitives/transaction.h> #include <script/interpreter.h> #include <consensus/validation.h> // TODO remove the following dependencies #include <chain.h> #include <coins.h> #include <util/moneystr.h> // SYSCOIN #include <services/asset.h> bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime) { if (tx.nLockTime == 0) return true; if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime)) return true; for (const auto& txin : tx.vin) { if (!(txin.nSequence == CTxIn::SEQUENCE_FINAL)) return false; } return true; } std::pair<int, int64_t> CalculateSequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block) { assert(prevHeights->size() == tx.vin.size()); // Will be set to the equivalent height- and time-based nLockTime // values that would be necessary to satisfy all relative lock- // time constraints given our view of block chain history. // The semantics of nLockTime are the last invalid height/time, so // use -1 to have the effect of any height or time being valid. int nMinHeight = -1; int64_t nMinTime = -1; // tx.nVersion is signed integer so requires cast to unsigned otherwise // we would be doing a signed comparison and half the range of nVersion // wouldn't support BIP 68. bool fEnforceBIP68 = static_cast<uint32_t>(tx.nVersion) >= 2 && flags & LOCKTIME_VERIFY_SEQUENCE; // Do not enforce sequence numbers as a relative lock time // unless we have been instructed to if (!fEnforceBIP68) { return std::make_pair(nMinHeight, nMinTime); } for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) { const CTxIn& txin = tx.vin[txinIndex]; // Sequence numbers with the most significant bit set are not // treated as relative lock-times, nor are they given any // consensus-enforced meaning at this point. if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) { // The height of this input is not relevant for sequence locks (*prevHeights)[txinIndex] = 0; continue; } int nCoinHeight = (*prevHeights)[txinIndex]; if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) { int64_t nCoinTime = block.GetAncestor(std::max(nCoinHeight-1, 0))->GetMedianTimePast(); // NOTE: Subtract 1 to maintain nLockTime semantics // BIP 68 relative lock times have the semantics of calculating // the first block or time at which the transaction would be // valid. When calculating the effective block time or height // for the entire transaction, we switch to using the // semantics of nLockTime which is the last invalid block // time or height. Thus we subtract 1 from the calculated // time or height. // Time-based relative lock-times are measured from the // smallest allowed timestamp of the block containing the // txout being spent, which is the median time past of the // block prior. nMinTime = std::max(nMinTime, nCoinTime + (int64_t)((txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) << CTxIn::SEQUENCE_LOCKTIME_GRANULARITY) - 1); } else { nMinHeight = std::max(nMinHeight, nCoinHeight + (int)(txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) - 1); } } return std::make_pair(nMinHeight, nMinTime); } bool EvaluateSequenceLocks(const CBlockIndex& block, std::pair<int, int64_t> lockPair) { assert(block.pprev); int64_t nBlockTime = block.pprev->GetMedianTimePast(); if (lockPair.first >= block.nHeight || lockPair.second >= nBlockTime) return false; return true; } bool SequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block) { return EvaluateSequenceLocks(block, CalculateSequenceLocks(tx, flags, prevHeights, block)); } unsigned int GetLegacySigOpCount(const CTransaction& tx) { unsigned int nSigOps = 0; for (const auto& txin : tx.vin) { nSigOps += txin.scriptSig.GetSigOpCount(false); } for (const auto& txout : tx.vout) { nSigOps += txout.scriptPubKey.GetSigOpCount(false); } return nSigOps; } unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs) { if (tx.IsCoinBase()) return 0; unsigned int nSigOps = 0; for (unsigned int i = 0; i < tx.vin.size(); i++) { const Coin& coin = inputs.AccessCoin(tx.vin[i].prevout); assert(!coin.IsSpent()); const CTxOut &prevout = coin.out; if (prevout.scriptPubKey.IsPayToScriptHash()) nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig); } return nSigOps; } int64_t GetTransactionSigOpCost(const CTransaction& tx, const CCoinsViewCache& inputs, int flags) { int64_t nSigOps = GetLegacySigOpCount(tx) * WITNESS_SCALE_FACTOR; if (tx.IsCoinBase()) return nSigOps; if (flags & SCRIPT_VERIFY_P2SH) { nSigOps += GetP2SHSigOpCount(tx, inputs) * WITNESS_SCALE_FACTOR; } for (unsigned int i = 0; i < tx.vin.size(); i++) { const Coin& coin = inputs.AccessCoin(tx.vin[i].prevout); assert(!coin.IsSpent()); const CTxOut &prevout = coin.out; nSigOps += CountWitnessSigOps(tx.vin[i].scriptSig, prevout.scriptPubKey, &tx.vin[i].scriptWitness, flags); } return nSigOps; } // SYSCOIN bool AssetOutputRange(const CAmount& nAmount, const int32_t& nVersion, const bool &isAssetTx) { if(isAssetTx) { // can be >= 0, validate that only one output exists == 0 in checkassetinputs() if(nVersion == SYSCOIN_TX_VERSION_ASSET_SEND) return AssetMoneyRange(nAmount); else return nAmount == 0; } return AssetRange(nAmount); } // SYSCOIN remove const CTransaction bool Consensus::CheckTxInputs(CTransaction& tx, TxValidationState& state, const CCoinsViewCache &inputs, int nSpendHeight, CAmount& txfee, const CAssetAllocation &allocation) { // are the actual inputs available? if (!inputs.HaveInputs(tx)) { return state.Invalid(TxValidationResult::TX_MISSING_INPUTS, "bad-txns-inputs-missingorspent", strprintf("%s: inputs missing/spent", __func__)); } const bool &isSyscoinWithNoInputTx = IsSyscoinWithNoInputTx(tx.nVersion); const bool &isSyscoinTx = IsSyscoinTx(tx.nVersion); const bool &isAssetTx = IsAssetTx(tx.nVersion); CAmount nValueIn = 0; std::unordered_map<int32_t, CAmount> mapAssetIn; std::unordered_map<int32_t, CAmount> mapAssetOut; std::unordered_set<uint32_t> setUsedIndex; for (unsigned int i = 0; i < tx.vin.size(); ++i) { const COutPoint &prevout = tx.vin[i].prevout; const Coin& coin = inputs.AccessCoin(prevout); assert(!coin.IsSpent()); // If prev is coinbase, check that it's matured if (coin.IsCoinBase() && nSpendHeight - coin.nHeight < COINBASE_MATURITY) { return state.Invalid(TxValidationResult::TX_PREMATURE_SPEND, "bad-txns-premature-spend-of-coinbase", strprintf("tried to spend coinbase at depth %d", nSpendHeight - coin.nHeight)); } if(coin.out.assetInfo.nAsset > 0) { if(!AssetOutputRange(coin.out.assetInfo.nValue, tx.nVersion, isAssetTx)) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-asset-inputvalues-outofrange"); } auto inRes = mapAssetIn.emplace(coin.out.assetInfo.nAsset, 0); if(!inRes.second) { inRes.first->second += coin.out.assetInfo.nValue; } } // Check for negative or overflow input values nValueIn += coin.out.nValue; if (!MoneyRange(coin.out.nValue) || !MoneyRange(nValueIn)) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-inputvalues-outofrange"); } } const CAmount &value_out = tx.GetValueOut(); if (nValueIn < value_out){ return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-in-belowout", strprintf("value in (%s) < value out (%s)", FormatMoney(nValueIn), FormatMoney(value_out))); } if(isSyscoinTx) { if(allocation.voutAssets.empty()) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-asset-empty-map-out"); } // CTxOut does not serialize assetInfo to make it consistent with Bitcoin serializaion, CTxOutInfo (used by utxo db) persists assetInfo // it will add txoutinfo based on vout.assetInfo std::vector<CTxOut>& vout = *const_cast<std::vector<CTxOut>*>(&tx.vout); for(unsigned int i =0;i< vout.size(); i++) { if(!vout[i].assetInfo.IsNull()) return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-asset-info-not-null"); } for(const auto &it: allocation.voutAssets) { const int32_t &nAsset = it.first; if(it.second.empty()) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-asset-empty-out"); } CAmount nTotal = 0; for(const auto& voutAsset: it.second){ const CAmount& nAmount = voutAsset.nValue; if(!AssetOutputRange(nAmount, tx.nVersion, isAssetTx)) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-asset-out-outofrange"); } const uint32_t& nOut = voutAsset.n; auto itSet = setUsedIndex.emplace(nOut); if(!itSet.second) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-asset-out-not-unique"); } if(nOut > vout.size()) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-asset-invalid-vout-index"); } vout[nOut].assetInfo = CAssetCoinInfo(nAsset, nAmount); nTotal += nAmount; } if(!AssetOutputRange(nTotal, tx.nVersion, isAssetTx)) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-asset-total-outofrange"); } auto itRes = mapAssetOut.emplace(it.first, nTotal); if(!itRes.second) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-asset-not-unique"); } } // if input was used, validate it against output (note, no fees for assets in == out) if(!isSyscoinWithNoInputTx && mapAssetIn != mapAssetOut) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-assets-io-mismatch"); } } // Tally transaction fees const CAmount txfee_aux = nValueIn - value_out; if (!MoneyRange(txfee_aux)) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-fee-outofrange"); } txfee = txfee_aux; return true; } <|endoftext|>
<commit_before>//-----------------------------------------------------------------------bl- //-------------------------------------------------------------------------- // // QUESO - a library to support the Quantification of Uncertainty // for Estimation, Simulation and Optimization // // Copyright (C) 2008,2009,2010,2011,2012,2013 The PECOS Development Team // // This library is free software; you can redistribute it and/or // modify it under the terms of the Version 2.1 GNU Lesser General // Public License as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc. 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 USA // //-----------------------------------------------------------------------el- #include <iostream> #include <gsl/gsl_multimin.h> #include <queso/GslVector.h> #include <queso/VectorSpace.h> #include <queso/ScalarFunction.h> #include <queso/GslOptimizer.h> namespace QUESO { // We need to extern "C" because gsl needs a pointer to a C function to // minimize extern "C" { // This evaluate -log posterior double c_evaluate(const gsl_vector * x, void * context) { GslOptimizer * optimizer = static_cast<GslOptimizer * >(context); GslVector state( optimizer->objectiveFunction().domainSet().vectorSpace().zeroVector()); // DM: Doing this copy sucks, but whatever. It'll do for now. for (unsigned int i = 0; i < state.sizeLocal(); i++) { state[i] = gsl_vector_get(x, i); } // Bail early if GSL tries to evaluate outside of the domain if (!optimizer->objectiveFunction().domainSet().contains(state)) { return GSL_NAN; } // Should cache derivative here so we don't a) segfault in the user's code // and b) so we don't recompute stuff double result = -optimizer->objectiveFunction().lnValue(state, NULL, NULL, NULL, NULL); return result; } // This evaluates the derivative of -log posterior void c_evaluate_derivative(const gsl_vector * x, void * context, gsl_vector * derivative) { GslOptimizer * optimizer = static_cast<GslOptimizer * >(context); GslVector state( optimizer->objectiveFunction().domainSet().vectorSpace().zeroVector()); GslVector deriv( optimizer->objectiveFunction().domainSet().vectorSpace().zeroVector()); // DM: Doing this copy sucks, but whatever. It'll do for now. for (unsigned int i = 0; i < state.sizeLocal(); i++) { state[i] = gsl_vector_get(x, i); // We fill with GSL_NAN and use it as a flag to check later that the user // actually fills the derivative vector with stuff deriv[i] = GSL_NAN; } if (!optimizer->objectiveFunction().domainSet().contains(state)) { // Fill derivative with error codes if the point is outside of the // domain for (unsigned int i = 0; i < deriv.sizeLocal(); i++) { gsl_vector_set(derivative, i, GSL_NAN); } } else { // We should cache the return value here so we don't recompute stuff double fx = -optimizer->objectiveFunction().lnValue(state, NULL, &deriv, NULL, NULL); // Decide whether or not we need to do a finite difference based on // whether the user actually filled deriv with values that are not // GSL_NAN // // We're currently doing this check every time this function gets called. // We could probably pull this logic out of here and put it somewhere // where it only happens once bool userComputedDerivative = true; for (unsigned int i = 0; i < deriv.sizeLocal(); i++) { // If the user missed out a derivative in any direction, fall back to // a finite difference if (gsl_isnan(deriv[i])) { userComputedDerivative = false; break; } } if (userComputedDerivative) { for (unsigned int i = 0; i < deriv.sizeLocal(); i++) { gsl_vector_set(derivative, i, -deriv[i]); // We need the minus sign } } else { // Finite difference step-size double h = optimizer->getFiniteDifferenceStepSize(); // User did not provide a derivative, so do a finite difference for (unsigned int i = 0; i < deriv.sizeLocal(); i++) { double tempState = state[i]; state[i] += h; // User didn't provide a derivative, so we don't bother passing in // the derivative vector again double fxph = -optimizer->objectiveFunction().lnValue(state, NULL, NULL, NULL, NULL); // Reset the state back to what it was before state[i] = tempState; // Make sure we didn't do anything dumb and tell gsl if we did if (!gsl_isnan(fx) && !gsl_isnan(fxph)) { gsl_vector_set(derivative, i, (fxph - fx) / h); } else { gsl_vector_set(derivative, i, GSL_NAN); } } } } } // This evaluates -log posterior and the derivative of -log posterior void c_evaluate_with_derivative(const gsl_vector * x, void * context, double * f, gsl_vector * derivative) { // We don't need to call both of these *f = c_evaluate(x, context); c_evaluate_derivative(x, context, derivative); } } // End extern "C" GslOptimizer::GslOptimizer( const BaseScalarFunction<GslVector, GslMatrix> & objectiveFunction) : BaseOptimizer(), m_objectiveFunction(objectiveFunction), m_initialPoint(new GslVector(objectiveFunction.domainSet(). vectorSpace().zeroVector())), m_minimizer(new GslVector(this->m_objectiveFunction.domainSet(). vectorSpace().zeroVector())), m_solver_type(BFGS2) { // We initialize the minimizer to GSL_NAN just in case the optimization fails for (unsigned int i = 0; i < this->m_minimizer->sizeLocal(); i++) { (*(this->m_minimizer))[i] = GSL_NAN; } } GslOptimizer::~GslOptimizer() { delete this->m_initialPoint; } const Vector * GslOptimizer::minimize(const Vector & initialPoint) { unsigned int dim = this->m_objectiveFunction.domainSet().vectorSpace(). zeroVector().sizeLocal(); // DM: The dynamic cast is needed because the abstract base class does not // have a pure virtual operator[] method. We can implement one and remove // this dynamic cast in the future. const GslVector & initial_guess = dynamic_cast<const GslVector &>(initialPoint); const GslVector* minimizer = this->minimize_with_gradient( dim, initial_guess ); return minimizer; } const BaseScalarFunction<GslVector, GslMatrix> & GslOptimizer::objectiveFunction() const { return this->m_objectiveFunction; } void GslOptimizer::setInitialPoint(const GslVector & initialPoint) { for (unsigned int i = 0; i < initialPoint.sizeLocal(); i++) { (*(this->m_initialPoint))[i] = initialPoint[i]; } } const GslVector & GslOptimizer::minimizer() const { return *(this->m_minimizer); } void GslOptimizer::set_solver_type( SolverType solver ) { m_solver_type = solver; } bool GslOptimizer::solver_needs_gradient( SolverType solver ) { bool gradient_needed = false; switch(solver) { case(FLETCHER_REEVES_CG): case(POLAK_RIBIERE_CG): case(BFGS): case(BFGS2): case(STEEPEST_DECENT): { gradient_needed = true; break; } case(NELDER_MEAD): case(NELDER_MEAD2): case(NELDER_MEAD2_RAND): { break; } default: { // Wat?! queso_error(); } } // switch(solver) return gradient_needed; } const GslVector* GslOptimizer::minimize_with_gradient( unsigned int dim, const GslVector& initial_guess ) { // Set initial point gsl_vector * x = gsl_vector_alloc(dim); for (unsigned int i = 0; i < dim; i++) { gsl_vector_set(x, i, initial_guess[i]); } const gsl_multimin_fdfminimizer_type * T = gsl_multimin_fdfminimizer_vector_bfgs2; gsl_multimin_fdfminimizer * s = gsl_multimin_fdfminimizer_alloc(T, dim); gsl_multimin_function_fdf minusLogPosterior; minusLogPosterior.n = dim; minusLogPosterior.f = &c_evaluate; minusLogPosterior.df = &c_evaluate_derivative; minusLogPosterior.fdf = &c_evaluate_with_derivative; minusLogPosterior.params = (void *)(&(this->m_objectiveFunction)); /*! * \todo Allow the user to tweak these hard-coded values */ gsl_multimin_fdfminimizer_set(s, &minusLogPosterior, x, 0.01, 0.1); int status; size_t iter = 0; do { iter++; status = gsl_multimin_fdfminimizer_iterate(s); if (status) { std::cerr << "Error while GSL does optimisation. " << "See below for GSL error type." << std::endl; std::cerr << "Gsl error: " << gsl_strerror(status) << std::endl; break; } // TODO: Allow the user to tweak this hard-coded value status = gsl_multimin_test_gradient(s->gradient, this->getTolerance()); /*! * \todo We shouldn't be hard-coding the max number of iterations */ } while ((status == GSL_CONTINUE) && (iter < this->getMaxIterations())); // Get the minimizer GslVector * minimizer = new GslVector(this->m_objectiveFunction.domainSet(). vectorSpace().zeroVector()); for (unsigned int i = 0; i < dim; i++) { (*minimizer)[i] = gsl_vector_get(s->x, i); } // We're being good human beings and cleaning up the memory we allocated gsl_multimin_fdfminimizer_free(s); gsl_vector_free(x); return minimizer; } } // End namespace QUESO <commit_msg>Turned on multiple solvers for gradient algorithms<commit_after>//-----------------------------------------------------------------------bl- //-------------------------------------------------------------------------- // // QUESO - a library to support the Quantification of Uncertainty // for Estimation, Simulation and Optimization // // Copyright (C) 2008,2009,2010,2011,2012,2013 The PECOS Development Team // // This library is free software; you can redistribute it and/or // modify it under the terms of the Version 2.1 GNU Lesser General // Public License as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc. 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 USA // //-----------------------------------------------------------------------el- #include <iostream> #include <gsl/gsl_multimin.h> #include <queso/GslVector.h> #include <queso/VectorSpace.h> #include <queso/ScalarFunction.h> #include <queso/GslOptimizer.h> namespace QUESO { // We need to extern "C" because gsl needs a pointer to a C function to // minimize extern "C" { // This evaluate -log posterior double c_evaluate(const gsl_vector * x, void * context) { GslOptimizer * optimizer = static_cast<GslOptimizer * >(context); GslVector state( optimizer->objectiveFunction().domainSet().vectorSpace().zeroVector()); // DM: Doing this copy sucks, but whatever. It'll do for now. for (unsigned int i = 0; i < state.sizeLocal(); i++) { state[i] = gsl_vector_get(x, i); } // Bail early if GSL tries to evaluate outside of the domain if (!optimizer->objectiveFunction().domainSet().contains(state)) { return GSL_NAN; } // Should cache derivative here so we don't a) segfault in the user's code // and b) so we don't recompute stuff double result = -optimizer->objectiveFunction().lnValue(state, NULL, NULL, NULL, NULL); return result; } // This evaluates the derivative of -log posterior void c_evaluate_derivative(const gsl_vector * x, void * context, gsl_vector * derivative) { GslOptimizer * optimizer = static_cast<GslOptimizer * >(context); GslVector state( optimizer->objectiveFunction().domainSet().vectorSpace().zeroVector()); GslVector deriv( optimizer->objectiveFunction().domainSet().vectorSpace().zeroVector()); // DM: Doing this copy sucks, but whatever. It'll do for now. for (unsigned int i = 0; i < state.sizeLocal(); i++) { state[i] = gsl_vector_get(x, i); // We fill with GSL_NAN and use it as a flag to check later that the user // actually fills the derivative vector with stuff deriv[i] = GSL_NAN; } if (!optimizer->objectiveFunction().domainSet().contains(state)) { // Fill derivative with error codes if the point is outside of the // domain for (unsigned int i = 0; i < deriv.sizeLocal(); i++) { gsl_vector_set(derivative, i, GSL_NAN); } } else { // We should cache the return value here so we don't recompute stuff double fx = -optimizer->objectiveFunction().lnValue(state, NULL, &deriv, NULL, NULL); // Decide whether or not we need to do a finite difference based on // whether the user actually filled deriv with values that are not // GSL_NAN // // We're currently doing this check every time this function gets called. // We could probably pull this logic out of here and put it somewhere // where it only happens once bool userComputedDerivative = true; for (unsigned int i = 0; i < deriv.sizeLocal(); i++) { // If the user missed out a derivative in any direction, fall back to // a finite difference if (gsl_isnan(deriv[i])) { userComputedDerivative = false; break; } } if (userComputedDerivative) { for (unsigned int i = 0; i < deriv.sizeLocal(); i++) { gsl_vector_set(derivative, i, -deriv[i]); // We need the minus sign } } else { // Finite difference step-size double h = optimizer->getFiniteDifferenceStepSize(); // User did not provide a derivative, so do a finite difference for (unsigned int i = 0; i < deriv.sizeLocal(); i++) { double tempState = state[i]; state[i] += h; // User didn't provide a derivative, so we don't bother passing in // the derivative vector again double fxph = -optimizer->objectiveFunction().lnValue(state, NULL, NULL, NULL, NULL); // Reset the state back to what it was before state[i] = tempState; // Make sure we didn't do anything dumb and tell gsl if we did if (!gsl_isnan(fx) && !gsl_isnan(fxph)) { gsl_vector_set(derivative, i, (fxph - fx) / h); } else { gsl_vector_set(derivative, i, GSL_NAN); } } } } } // This evaluates -log posterior and the derivative of -log posterior void c_evaluate_with_derivative(const gsl_vector * x, void * context, double * f, gsl_vector * derivative) { // We don't need to call both of these *f = c_evaluate(x, context); c_evaluate_derivative(x, context, derivative); } } // End extern "C" GslOptimizer::GslOptimizer( const BaseScalarFunction<GslVector, GslMatrix> & objectiveFunction) : BaseOptimizer(), m_objectiveFunction(objectiveFunction), m_initialPoint(new GslVector(objectiveFunction.domainSet(). vectorSpace().zeroVector())), m_minimizer(new GslVector(this->m_objectiveFunction.domainSet(). vectorSpace().zeroVector())), m_solver_type(BFGS2) { // We initialize the minimizer to GSL_NAN just in case the optimization fails for (unsigned int i = 0; i < this->m_minimizer->sizeLocal(); i++) { (*(this->m_minimizer))[i] = GSL_NAN; } } GslOptimizer::~GslOptimizer() { delete this->m_initialPoint; } const Vector * GslOptimizer::minimize(const Vector & initialPoint) { unsigned int dim = this->m_objectiveFunction.domainSet().vectorSpace(). zeroVector().sizeLocal(); // DM: The dynamic cast is needed because the abstract base class does not // have a pure virtual operator[] method. We can implement one and remove // this dynamic cast in the future. const GslVector & initial_guess = dynamic_cast<const GslVector &>(initialPoint); const GslVector* minimizer = this->minimize_with_gradient( dim, initial_guess ); return minimizer; } const BaseScalarFunction<GslVector, GslMatrix> & GslOptimizer::objectiveFunction() const { return this->m_objectiveFunction; } void GslOptimizer::setInitialPoint(const GslVector & initialPoint) { for (unsigned int i = 0; i < initialPoint.sizeLocal(); i++) { (*(this->m_initialPoint))[i] = initialPoint[i]; } } const GslVector & GslOptimizer::minimizer() const { return *(this->m_minimizer); } void GslOptimizer::set_solver_type( SolverType solver ) { m_solver_type = solver; } bool GslOptimizer::solver_needs_gradient( SolverType solver ) { bool gradient_needed = false; switch(solver) { case(FLETCHER_REEVES_CG): case(POLAK_RIBIERE_CG): case(BFGS): case(BFGS2): case(STEEPEST_DECENT): { gradient_needed = true; break; } case(NELDER_MEAD): case(NELDER_MEAD2): case(NELDER_MEAD2_RAND): { break; } default: { // Wat?! queso_error(); } } // switch(solver) return gradient_needed; } const GslVector* GslOptimizer::minimize_with_gradient( unsigned int dim, const GslVector& initial_guess ) { // Set initial point gsl_vector * x = gsl_vector_alloc(dim); for (unsigned int i = 0; i < dim; i++) { gsl_vector_set(x, i, initial_guess[i]); } // Tell GSL which solver we're using const gsl_multimin_fdfminimizer_type* type = NULL; switch(m_solver_type) { case(FLETCHER_REEVES_CG): type = gsl_multimin_fdfminimizer_conjugate_fr; break; case(POLAK_RIBIERE_CG): type = gsl_multimin_fdfminimizer_conjugate_pr; break; case(BFGS): type = gsl_multimin_fdfminimizer_vector_bfgs; break; case(BFGS2): type = gsl_multimin_fdfminimizer_vector_bfgs2; break; case(STEEPEST_DECENT): type = gsl_multimin_fdfminimizer_steepest_descent; break; case(NELDER_MEAD): case(NELDER_MEAD2): case(NELDER_MEAD2_RAND): default: // Wat?! queso_error(); } // Init solver gsl_multimin_fdfminimizer * solver = gsl_multimin_fdfminimizer_alloc(type, dim); // Point GSL to the right functions gsl_multimin_function_fdf minusLogPosterior; minusLogPosterior.n = dim; minusLogPosterior.f = &c_evaluate; minusLogPosterior.df = &c_evaluate_derivative; minusLogPosterior.fdf = &c_evaluate_with_derivative; minusLogPosterior.params = (void *)(&(this->m_objectiveFunction)); /*! * \todo Allow the user to tweak these hard-coded values */ gsl_multimin_fdfminimizer_set(solver, &minusLogPosterior, x, 0.01, 0.1); int status; size_t iter = 0; do { iter++; status = gsl_multimin_fdfminimizer_iterate(solver); if (status) { std::cerr << "Error while GSL does optimisation. " << "See below for GSL error type." << std::endl; std::cerr << "Gsl error: " << gsl_strerror(status) << std::endl; break; } status = gsl_multimin_test_gradient(s->gradient, this->getTolerance()); /*! * \todo We shouldn't be hard-coding the max number of iterations */ } while ((status == GSL_CONTINUE) && (iter < this->getMaxIterations())); // Get the minimizer GslVector * minimizer = new GslVector(this->m_objectiveFunction.domainSet(). vectorSpace().zeroVector()); for (unsigned int i = 0; i < dim; i++) { (*minimizer)[i] = gsl_vector_get(solver->x, i); } // We're being good human beings and cleaning up the memory we allocated gsl_multimin_fdfminimizer_free(solver); gsl_vector_free(x); return minimizer; } } // End namespace QUESO <|endoftext|>
<commit_before>/* * Copyright (c) 2007 MIPS Technologies, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Korey Sewell * */ #include <list> #include <vector> #include "base/str.hh" #include "cpu/inorder/cpu.hh" #include "cpu/inorder/resource.hh" #include "cpu/inorder/resource_pool.hh" #include "debug/ExecFaulting.hh" #include "debug/RefCount.hh" #include "debug/ResReqCount.hh" #include "debug/Resource.hh" using namespace std; Resource::Resource(string res_name, int res_id, int res_width, int res_latency, InOrderCPU *_cpu) : resName(res_name), id(res_id), width(res_width), latency(res_latency), cpu(_cpu) { reqs.resize(width); // Use to deny a instruction a resource. deniedReq = new ResourceRequest(this); deniedReq->valid = true; } Resource::~Resource() { if (resourceEvent) { delete [] resourceEvent; } delete deniedReq; for (int i = 0; i < width; i++) { delete reqs[i]; } } void Resource::init() { // If the resource has a zero-cycle (no latency) // function, then no reason to have events // that will process them for the right tick if (latency > 0) { resourceEvent = new ResourceEvent[width]; } else { resourceEvent = NULL; } for (int i = 0; i < width; i++) { reqs[i] = new ResourceRequest(this); } initSlots(); } void Resource::initSlots() { // Add available slot numbers for resource for (int slot_idx = 0; slot_idx < width; slot_idx++) { availSlots.push_back(slot_idx); if (resourceEvent) { resourceEvent[slot_idx].init(this, slot_idx); } } } std::string Resource::name() { return cpu->name() + "." + resName; } int Resource::slotsAvail() { return availSlots.size(); } int Resource::slotsInUse() { return width - availSlots.size(); } void Resource::freeSlot(int slot_idx) { DPRINTF(Resource, "Deallocating [slot:%i].\n", slot_idx); // Put slot number on this resource's free list availSlots.push_back(slot_idx); // Invalidate Request & Reset it's flags reqs[slot_idx]->clearRequest(); } int Resource::findSlot(DynInstPtr inst) { int slot_num = -1; for (int i = 0; i < width; i++) { if (reqs[i]->valid && reqs[i]->getInst()->seqNum == inst->seqNum) { slot_num = reqs[i]->getSlot(); } } return slot_num; } int Resource::getSlot(DynInstPtr inst) { int slot_num = -1; if (slotsAvail() != 0) { slot_num = availSlots[0]; vector<int>::iterator vect_it = availSlots.begin(); assert(slot_num == *vect_it); availSlots.erase(vect_it); } return slot_num; } ResReqPtr Resource::request(DynInstPtr inst) { // See if the resource is already serving this instruction. // If so, use that request; bool try_request = false; int slot_num = -1; int stage_num; ResReqPtr inst_req = findRequest(inst); if (inst_req) { // If some preprocessing has to be done on instruction // that has already requested once, then handle it here. // update the 'try_request' variable if we should // re-execute the request. requestAgain(inst, try_request); slot_num = inst_req->getSlot(); stage_num = inst_req->getStageNum(); } else { // Get new slot # for instruction slot_num = getSlot(inst); if (slot_num != -1) { DPRINTF(Resource, "Allocating [slot:%i] for [tid:%i]: [sn:%i]\n", slot_num, inst->readTid(), inst->seqNum); // Get Stage # from Schedule Entry stage_num = inst->curSkedEntry->stageNum; unsigned cmd = inst->curSkedEntry->cmd; // Generate Resource Request inst_req = getRequest(inst, stage_num, id, slot_num, cmd); if (inst->staticInst) { DPRINTF(Resource, "[tid:%i]: [sn:%i] requesting this " "resource.\n", inst->readTid(), inst->seqNum); } else { DPRINTF(Resource, "[tid:%i]: instruction requesting this " "resource.\n", inst->readTid()); } try_request = true; } else { DPRINTF(Resource, "No slot available for [tid:%i]: [sn:%i]\n", inst->readTid(), inst->seqNum); } } if (try_request) { // Schedule execution of resource scheduleExecution(slot_num); } else { inst_req = deniedReq; rejectRequest(inst); } return inst_req; } void Resource::requestAgain(DynInstPtr inst, bool &do_request) { do_request = true; if (inst->staticInst) { DPRINTF(Resource, "[tid:%i]: [sn:%i] requesting this resource " "again.\n", inst->readTid(), inst->seqNum); } else { DPRINTF(Resource, "[tid:%i]: requesting this resource again.\n", inst->readTid()); } } ResReqPtr Resource::getRequest(DynInstPtr inst, int stage_num, int res_idx, int slot_num, unsigned cmd) { reqs[slot_num]->setRequest(inst, stage_num, id, slot_num, cmd); return reqs[slot_num]; } ResReqPtr Resource::findRequest(DynInstPtr inst) { for (int i = 0; i < width; i++) { if (reqs[i]->valid && reqs[i]->getInst() == inst) { return reqs[i]; } } return NULL; } void Resource::rejectRequest(DynInstPtr inst) { DPRINTF(RefCount, "[tid:%i]: Unable to grant request for [sn:%i].\n", inst->readTid(), inst->seqNum); } void Resource::execute(int slot_idx) { //@todo: have each resource print out command their executing DPRINTF(Resource, "[tid:%i]: Executing %s resource.\n", reqs[slot_idx]->getTid(), name()); reqs[slot_idx]->setCompleted(true); reqs[slot_idx]->done(); } void Resource::deactivateThread(ThreadID tid) { // In the most basic case, deactivation means squashing everything // from a particular thread DynInstPtr dummy_inst = new InOrderDynInst(cpu, NULL, 0, tid, tid); squash(dummy_inst, 0, 0, tid); } void Resource::setupSquash(DynInstPtr inst, int stage_num, ThreadID tid) { // Squash In Pipeline Stage cpu->pipelineStage[stage_num]->setupSquash(inst, tid); // Schedule Squash Through-out Resource Pool cpu->resPool->scheduleEvent( (InOrderCPU::CPUEventType)ResourcePool::SquashAll, inst, 0); } void Resource::squash(DynInstPtr inst, int stage_num, InstSeqNum squash_seq_num, ThreadID tid) { //@todo: check squash seq num before squashing. can save time going // through this function. for (int i = 0; i < width; i++) { ResReqPtr req_ptr = reqs[i]; DynInstPtr inst = req_ptr->getInst(); if (req_ptr->valid && inst->readTid() == tid && inst->seqNum > squash_seq_num) { DPRINTF(Resource, "[tid:%i]: Squashing [sn:%i].\n", req_ptr->getInst()->readTid(), req_ptr->getInst()->seqNum); req_ptr->setSquashed(); int req_slot_num = req_ptr->getSlot(); if (latency > 0) { if (resourceEvent[req_slot_num].scheduled()) unscheduleEvent(req_slot_num); } freeSlot(req_slot_num); } } } void Resource::squashDueToMemStall(DynInstPtr inst, int stage_num, InstSeqNum squash_seq_num, ThreadID tid) { squash(inst, stage_num, squash_seq_num, tid); } void Resource::squashThenTrap(int stage_num, DynInstPtr inst) { ThreadID tid = inst->readTid(); inst->setSquashInfo(stage_num); setupSquash(inst, stage_num, tid); if (inst->traceData && DTRACE(ExecFaulting)) { inst->traceData->setStageCycle(stage_num, curTick()); inst->traceData->setFetchSeq(inst->seqNum); inst->traceData->dump(); delete inst->traceData; inst->traceData = NULL; } cpu->trapContext(inst->fault, tid, inst); } Tick Resource::ticks(int num_cycles) { return cpu->ticks(num_cycles); } void Resource::scheduleExecution(int slot_num) { if (latency >= 1) { scheduleEvent(slot_num, latency); } else { execute(slot_num); } } void Resource::scheduleEvent(int slot_idx, int delay) { DPRINTF(Resource, "[tid:%i]: Scheduling event for [sn:%i] on tick %i.\n", reqs[slot_idx]->inst->readTid(), reqs[slot_idx]->inst->seqNum, cpu->ticks(delay) + curTick()); resourceEvent[slot_idx].scheduleEvent(delay); } bool Resource::scheduleEvent(DynInstPtr inst, int delay) { int slot_idx = findSlot(inst); if(slot_idx != -1) resourceEvent[slot_idx].scheduleEvent(delay); return slot_idx; } void Resource::unscheduleEvent(int slot_idx) { resourceEvent[slot_idx].unscheduleEvent(); } bool Resource::unscheduleEvent(DynInstPtr inst) { int slot_idx = findSlot(inst); if(slot_idx != -1) resourceEvent[slot_idx].unscheduleEvent(); return slot_idx; } int ResourceRequest::resReqID = 0; int ResourceRequest::maxReqCount = 0; ResourceRequest::ResourceRequest(Resource *_res) : res(_res), inst(NULL), stagePasses(0), valid(false), doneInResource(false), completed(false), squashed(false), processing(false), memStall(false) { } ResourceRequest::~ResourceRequest() { #ifdef DEBUG res->cpu->resReqCount--; DPRINTF(ResReqCount, "Res. Req %i deleted. resReqCount=%i.\n", reqID, res->cpu->resReqCount); #endif inst = NULL; } std::string ResourceRequest::name() { return csprintf("%s[slot:%i]:", res->name(), slotNum); } void ResourceRequest::setRequest(DynInstPtr _inst, int stage_num, int res_idx, int slot_num, unsigned _cmd) { valid = true; inst = _inst; stageNum = stage_num; resIdx = res_idx; slotNum = slot_num; cmd = _cmd; } void ResourceRequest::clearRequest() { valid = false; inst = NULL; stagePasses = 0; completed = false; doneInResource = false; squashed = false; memStall = false; } void ResourceRequest::freeSlot() { assert(res); // Free Slot So Another Instruction Can Use This Resource res->freeSlot(slotNum); } void ResourceRequest::done(bool completed) { DPRINTF(Resource, "done with request from " "[sn:%i] [tid:%i].\n", inst->seqNum, inst->readTid()); setCompleted(completed); doneInResource = true; } ResourceEvent::ResourceEvent() : Event((Event::Priority)Resource_Event_Pri) { } ResourceEvent::ResourceEvent(Resource *res, int slot_idx) : Event((Event::Priority)Resource_Event_Pri), resource(res), slotIdx(slot_idx) { } void ResourceEvent::init(Resource *res, int slot_idx) { resource = res; slotIdx = slot_idx; } void ResourceEvent::process() { resource->execute(slotIdx); } const char * ResourceEvent::description() { string desc = resource->name() + "-event:slot[" + to_string(slotIdx) + "]"; return desc.c_str(); } void ResourceEvent::scheduleEvent(int delay) { assert(!scheduled() || squashed()); resource->cpu->reschedule(this, curTick() + resource->ticks(delay), true); } <commit_msg>inorder:tracing: fix fault tracing bug<commit_after>/* * Copyright (c) 2007 MIPS Technologies, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Korey Sewell * */ #include <list> #include <vector> #include "base/str.hh" #include "cpu/inorder/cpu.hh" #include "cpu/inorder/resource.hh" #include "cpu/inorder/resource_pool.hh" #include "debug/ExecFaulting.hh" #include "debug/RefCount.hh" #include "debug/ResReqCount.hh" #include "debug/Resource.hh" using namespace std; Resource::Resource(string res_name, int res_id, int res_width, int res_latency, InOrderCPU *_cpu) : resName(res_name), id(res_id), width(res_width), latency(res_latency), cpu(_cpu) { reqs.resize(width); // Use to deny a instruction a resource. deniedReq = new ResourceRequest(this); deniedReq->valid = true; } Resource::~Resource() { if (resourceEvent) { delete [] resourceEvent; } delete deniedReq; for (int i = 0; i < width; i++) { delete reqs[i]; } } void Resource::init() { // If the resource has a zero-cycle (no latency) // function, then no reason to have events // that will process them for the right tick if (latency > 0) { resourceEvent = new ResourceEvent[width]; } else { resourceEvent = NULL; } for (int i = 0; i < width; i++) { reqs[i] = new ResourceRequest(this); } initSlots(); } void Resource::initSlots() { // Add available slot numbers for resource for (int slot_idx = 0; slot_idx < width; slot_idx++) { availSlots.push_back(slot_idx); if (resourceEvent) { resourceEvent[slot_idx].init(this, slot_idx); } } } std::string Resource::name() { return cpu->name() + "." + resName; } int Resource::slotsAvail() { return availSlots.size(); } int Resource::slotsInUse() { return width - availSlots.size(); } void Resource::freeSlot(int slot_idx) { DPRINTF(Resource, "Deallocating [slot:%i].\n", slot_idx); // Put slot number on this resource's free list availSlots.push_back(slot_idx); // Invalidate Request & Reset it's flags reqs[slot_idx]->clearRequest(); } int Resource::findSlot(DynInstPtr inst) { int slot_num = -1; for (int i = 0; i < width; i++) { if (reqs[i]->valid && reqs[i]->getInst()->seqNum == inst->seqNum) { slot_num = reqs[i]->getSlot(); } } return slot_num; } int Resource::getSlot(DynInstPtr inst) { int slot_num = -1; if (slotsAvail() != 0) { slot_num = availSlots[0]; vector<int>::iterator vect_it = availSlots.begin(); assert(slot_num == *vect_it); availSlots.erase(vect_it); } return slot_num; } ResReqPtr Resource::request(DynInstPtr inst) { // See if the resource is already serving this instruction. // If so, use that request; bool try_request = false; int slot_num = -1; int stage_num; ResReqPtr inst_req = findRequest(inst); if (inst_req) { // If some preprocessing has to be done on instruction // that has already requested once, then handle it here. // update the 'try_request' variable if we should // re-execute the request. requestAgain(inst, try_request); slot_num = inst_req->getSlot(); stage_num = inst_req->getStageNum(); } else { // Get new slot # for instruction slot_num = getSlot(inst); if (slot_num != -1) { DPRINTF(Resource, "Allocating [slot:%i] for [tid:%i]: [sn:%i]\n", slot_num, inst->readTid(), inst->seqNum); // Get Stage # from Schedule Entry stage_num = inst->curSkedEntry->stageNum; unsigned cmd = inst->curSkedEntry->cmd; // Generate Resource Request inst_req = getRequest(inst, stage_num, id, slot_num, cmd); if (inst->staticInst) { DPRINTF(Resource, "[tid:%i]: [sn:%i] requesting this " "resource.\n", inst->readTid(), inst->seqNum); } else { DPRINTF(Resource, "[tid:%i]: instruction requesting this " "resource.\n", inst->readTid()); } try_request = true; } else { DPRINTF(Resource, "No slot available for [tid:%i]: [sn:%i]\n", inst->readTid(), inst->seqNum); } } if (try_request) { // Schedule execution of resource scheduleExecution(slot_num); } else { inst_req = deniedReq; rejectRequest(inst); } return inst_req; } void Resource::requestAgain(DynInstPtr inst, bool &do_request) { do_request = true; if (inst->staticInst) { DPRINTF(Resource, "[tid:%i]: [sn:%i] requesting this resource " "again.\n", inst->readTid(), inst->seqNum); } else { DPRINTF(Resource, "[tid:%i]: requesting this resource again.\n", inst->readTid()); } } ResReqPtr Resource::getRequest(DynInstPtr inst, int stage_num, int res_idx, int slot_num, unsigned cmd) { reqs[slot_num]->setRequest(inst, stage_num, id, slot_num, cmd); return reqs[slot_num]; } ResReqPtr Resource::findRequest(DynInstPtr inst) { for (int i = 0; i < width; i++) { if (reqs[i]->valid && reqs[i]->getInst() == inst) { return reqs[i]; } } return NULL; } void Resource::rejectRequest(DynInstPtr inst) { DPRINTF(RefCount, "[tid:%i]: Unable to grant request for [sn:%i].\n", inst->readTid(), inst->seqNum); } void Resource::execute(int slot_idx) { //@todo: have each resource print out command their executing DPRINTF(Resource, "[tid:%i]: Executing %s resource.\n", reqs[slot_idx]->getTid(), name()); reqs[slot_idx]->setCompleted(true); reqs[slot_idx]->done(); } void Resource::deactivateThread(ThreadID tid) { // In the most basic case, deactivation means squashing everything // from a particular thread DynInstPtr dummy_inst = new InOrderDynInst(cpu, NULL, 0, tid, tid); squash(dummy_inst, 0, 0, tid); } void Resource::setupSquash(DynInstPtr inst, int stage_num, ThreadID tid) { // Squash In Pipeline Stage cpu->pipelineStage[stage_num]->setupSquash(inst, tid); // Schedule Squash Through-out Resource Pool cpu->resPool->scheduleEvent( (InOrderCPU::CPUEventType)ResourcePool::SquashAll, inst, 0); } void Resource::squash(DynInstPtr inst, int stage_num, InstSeqNum squash_seq_num, ThreadID tid) { //@todo: check squash seq num before squashing. can save time going // through this function. for (int i = 0; i < width; i++) { ResReqPtr req_ptr = reqs[i]; DynInstPtr inst = req_ptr->getInst(); if (req_ptr->valid && inst->readTid() == tid && inst->seqNum > squash_seq_num) { DPRINTF(Resource, "[tid:%i]: Squashing [sn:%i].\n", req_ptr->getInst()->readTid(), req_ptr->getInst()->seqNum); req_ptr->setSquashed(); int req_slot_num = req_ptr->getSlot(); if (latency > 0) { if (resourceEvent[req_slot_num].scheduled()) unscheduleEvent(req_slot_num); } freeSlot(req_slot_num); } } } void Resource::squashDueToMemStall(DynInstPtr inst, int stage_num, InstSeqNum squash_seq_num, ThreadID tid) { squash(inst, stage_num, squash_seq_num, tid); } void Resource::squashThenTrap(int stage_num, DynInstPtr inst) { ThreadID tid = inst->readTid(); inst->setSquashInfo(stage_num); setupSquash(inst, stage_num, tid); if (inst->traceData) { if (inst->staticInst && inst->fault != NoFault && DTRACE(ExecFaulting)) { inst->traceData->setStageCycle(stage_num, curTick()); inst->traceData->setFetchSeq(inst->seqNum); inst->traceData->dump(); } delete inst->traceData; inst->traceData = NULL; } cpu->trapContext(inst->fault, tid, inst); } Tick Resource::ticks(int num_cycles) { return cpu->ticks(num_cycles); } void Resource::scheduleExecution(int slot_num) { if (latency >= 1) { scheduleEvent(slot_num, latency); } else { execute(slot_num); } } void Resource::scheduleEvent(int slot_idx, int delay) { DPRINTF(Resource, "[tid:%i]: Scheduling event for [sn:%i] on tick %i.\n", reqs[slot_idx]->inst->readTid(), reqs[slot_idx]->inst->seqNum, cpu->ticks(delay) + curTick()); resourceEvent[slot_idx].scheduleEvent(delay); } bool Resource::scheduleEvent(DynInstPtr inst, int delay) { int slot_idx = findSlot(inst); if(slot_idx != -1) resourceEvent[slot_idx].scheduleEvent(delay); return slot_idx; } void Resource::unscheduleEvent(int slot_idx) { resourceEvent[slot_idx].unscheduleEvent(); } bool Resource::unscheduleEvent(DynInstPtr inst) { int slot_idx = findSlot(inst); if(slot_idx != -1) resourceEvent[slot_idx].unscheduleEvent(); return slot_idx; } int ResourceRequest::resReqID = 0; int ResourceRequest::maxReqCount = 0; ResourceRequest::ResourceRequest(Resource *_res) : res(_res), inst(NULL), stagePasses(0), valid(false), doneInResource(false), completed(false), squashed(false), processing(false), memStall(false) { } ResourceRequest::~ResourceRequest() { #ifdef DEBUG res->cpu->resReqCount--; DPRINTF(ResReqCount, "Res. Req %i deleted. resReqCount=%i.\n", reqID, res->cpu->resReqCount); #endif inst = NULL; } std::string ResourceRequest::name() { return csprintf("%s[slot:%i]:", res->name(), slotNum); } void ResourceRequest::setRequest(DynInstPtr _inst, int stage_num, int res_idx, int slot_num, unsigned _cmd) { valid = true; inst = _inst; stageNum = stage_num; resIdx = res_idx; slotNum = slot_num; cmd = _cmd; } void ResourceRequest::clearRequest() { valid = false; inst = NULL; stagePasses = 0; completed = false; doneInResource = false; squashed = false; memStall = false; } void ResourceRequest::freeSlot() { assert(res); // Free Slot So Another Instruction Can Use This Resource res->freeSlot(slotNum); } void ResourceRequest::done(bool completed) { DPRINTF(Resource, "done with request from " "[sn:%i] [tid:%i].\n", inst->seqNum, inst->readTid()); setCompleted(completed); doneInResource = true; } ResourceEvent::ResourceEvent() : Event((Event::Priority)Resource_Event_Pri) { } ResourceEvent::ResourceEvent(Resource *res, int slot_idx) : Event((Event::Priority)Resource_Event_Pri), resource(res), slotIdx(slot_idx) { } void ResourceEvent::init(Resource *res, int slot_idx) { resource = res; slotIdx = slot_idx; } void ResourceEvent::process() { resource->execute(slotIdx); } const char * ResourceEvent::description() { string desc = resource->name() + "-event:slot[" + to_string(slotIdx) + "]"; return desc.c_str(); } void ResourceEvent::scheduleEvent(int delay) { assert(!scheduled() || squashed()); resource->cpu->reschedule(this, curTick() + resource->ticks(delay), true); } <|endoftext|>
<commit_before>#ifndef ENTT_META_CONTAINER_HPP #define ENTT_META_CONTAINER_HPP #include <array> #include <map> #include <set> #include <type_traits> #include <unordered_map> #include <unordered_set> #include <vector> #include "../container/dense_map.hpp" #include "../container/dense_set.hpp" #include "meta.hpp" #include "type_traits.hpp" namespace entt { /** * @cond TURN_OFF_DOXYGEN * Internal details not to be documented. */ namespace internal { template<typename, typename = void> struct is_dynamic_sequence_container: std::false_type {}; template<typename Type> struct is_dynamic_sequence_container<Type, std::void_t<decltype(&Type::reserve)>>: std::true_type {}; template<typename, typename = void> struct is_key_only_meta_associative_container: std::true_type {}; template<typename Type> struct is_key_only_meta_associative_container<Type, std::void_t<typename Type::mapped_type>>: std::false_type {}; template<typename Type> struct basic_meta_sequence_container_traits { using iterator = meta_sequence_container::iterator; using size_type = std::size_t; [[nodiscard]] static size_type size(const any &container) ENTT_NOEXCEPT { return any_cast<const Type &>(container).size(); } [[nodiscard]] static bool resize([[maybe_unused]] any &container, [[maybe_unused]] size_type sz) { if constexpr(is_dynamic_sequence_container<Type>::value) { if(auto *const cont = any_cast<Type>(&container); cont) { cont->resize(sz); return true; } } return false; } [[nodiscard]] static iterator iter(any &container, const bool as_end) { using std::begin; if(auto *const cont = any_cast<Type>(&container); cont) { return iterator{begin(*cont), static_cast<typename iterator::difference_type>(as_end * cont->size())}; } const Type &as_const = any_cast<const Type &>(container); return iterator{begin(as_const), static_cast<typename iterator::difference_type>(as_end * as_const.size())}; } [[nodiscard]] static iterator insert([[maybe_unused]] any &container, [[maybe_unused]] const std::ptrdiff_t offset, [[maybe_unused]] meta_any &value) { if constexpr(is_dynamic_sequence_container<Type>::value) { if(auto *const cont = any_cast<Type>(&container); cont) { // this abomination is necessary because only on macos value_type and const_reference are different types for std::vector<bool> if(value.allow_cast<typename Type::const_reference>() || value.allow_cast<typename Type::value_type>()) { using std::begin; const auto *element = value.try_cast<std::remove_reference_t<typename Type::const_reference>>(); const auto curr = cont->insert(begin(*cont) + offset, element ? *element : value.cast<typename Type::value_type>()); return iterator{curr, curr - begin(*cont)}; } } } return {}; } [[nodiscard]] static iterator erase([[maybe_unused]] any &container, [[maybe_unused]] const std::ptrdiff_t offset) { if constexpr(is_dynamic_sequence_container<Type>::value) { if(auto *const cont = any_cast<Type>(&container); cont) { using std::begin; const auto curr = cont->erase(begin(*cont) + offset); return iterator{curr, curr - begin(*cont)}; } } return {}; } }; template<typename Type> struct basic_meta_associative_container_traits { using iterator = meta_associative_container::iterator; using size_type = std::size_t; static constexpr auto key_only = is_key_only_meta_associative_container<Type>::value; [[nodiscard]] static size_type size(const any &container) ENTT_NOEXCEPT { return any_cast<const Type &>(container).size(); } [[nodiscard]] static bool clear(any &container) { if(auto *const cont = any_cast<Type>(&container); cont) { cont->clear(); return true; } return false; } [[nodiscard]] static iterator iter(any &container, const bool as_end) { using std::begin; using std::end; if(auto *const cont = any_cast<Type>(&container); cont) { return iterator{std::integral_constant<bool, key_only>{}, as_end ? end(*cont) : begin(*cont)}; } const auto &as_const = any_cast<const Type &>(container); return iterator{std::integral_constant<bool, key_only>{}, as_end ? end(as_const) : begin(as_const)}; } [[nodiscard]] static bool insert(any &container, meta_any &key, [[maybe_unused]] meta_any &value) { if(auto *const cont = any_cast<Type>(&container); cont && key.allow_cast<const typename Type::key_type &>()) { if constexpr(is_key_only_meta_associative_container<Type>::value) { return cont->insert(key.cast<const typename Type::key_type &>()).second; } else { if(value.allow_cast<const typename Type::mapped_type &>()) { return cont->emplace(key.cast<const typename Type::key_type &>(), value.cast<const typename Type::mapped_type &>()).second; } } } return false; } [[nodiscard]] static bool erase(any &container, meta_any &key) { if(auto *const cont = any_cast<Type>(&container); cont && key.allow_cast<const typename Type::key_type &>()) { return (cont->erase(key.cast<const typename Type::key_type &>()) != cont->size()); } return false; } [[nodiscard]] static iterator find(any &container, meta_any &key) { if(key.allow_cast<const typename Type::key_type &>()) { if(auto *const cont = any_cast<Type>(&container); cont) { return iterator{std::integral_constant<bool, key_only>{}, cont->find(key.cast<const typename Type::key_type &>())}; } return iterator{std::integral_constant<bool, key_only>{}, any_cast<const Type &>(container).find(key.cast<const typename Type::key_type &>())}; } return {}; } }; } // namespace internal /** * Internal details not to be documented. * @endcond */ /** * @brief Meta sequence container traits for `std::vector`s of any type. * @tparam Type The type of elements. * @tparam Args Other arguments. */ template<typename Type, typename... Args> struct meta_sequence_container_traits<std::vector<Type, Args...>> : internal::basic_meta_sequence_container_traits<std::vector<Type, Args...>> {}; /** * @brief Meta sequence container traits for `std::array`s of any type. * @tparam Type The type of elements. * @tparam N The number of elements. */ template<typename Type, auto N> struct meta_sequence_container_traits<std::array<Type, N>> : internal::basic_meta_sequence_container_traits<std::array<Type, N>> {}; /** * @brief Meta associative container traits for `std::map`s of any type. * @tparam Key The key type of elements. * @tparam Value The value type of elements. * @tparam Args Other arguments. */ template<typename Key, typename Value, typename... Args> struct meta_associative_container_traits<std::map<Key, Value, Args...>> : internal::basic_meta_associative_container_traits<std::map<Key, Value, Args...>> {}; /** * @brief Meta associative container traits for `std::unordered_map`s of any * type. * @tparam Key The key type of elements. * @tparam Value The value type of elements. * @tparam Args Other arguments. */ template<typename Key, typename Value, typename... Args> struct meta_associative_container_traits<std::unordered_map<Key, Value, Args...>> : internal::basic_meta_associative_container_traits<std::unordered_map<Key, Value, Args...>> {}; /** * @brief Meta associative container traits for `std::set`s of any type. * @tparam Key The type of elements. * @tparam Args Other arguments. */ template<typename Key, typename... Args> struct meta_associative_container_traits<std::set<Key, Args...>> : internal::basic_meta_associative_container_traits<std::set<Key, Args...>> {}; /** * @brief Meta associative container traits for `std::unordered_set`s of any * type. * @tparam Key The type of elements. * @tparam Args Other arguments. */ template<typename Key, typename... Args> struct meta_associative_container_traits<std::unordered_set<Key, Args...>> : internal::basic_meta_associative_container_traits<std::unordered_set<Key, Args...>> {}; /** * @brief Meta associative container traits for `dense_map`s of any type. * @tparam Key The key type of the elements. * @tparam Type The value type of the elements. * @tparam Args Other arguments. */ template<typename Key, typename Type, typename... Args> struct meta_associative_container_traits<dense_map<Key, Type, Args...>> : internal::basic_meta_associative_container_traits<dense_map<Key, Type, Args...>> {}; /** * @brief Meta associative container traits for `dense_set`s of any type. * @tparam Type The value type of the elements. * @tparam Args Other arguments. */ template<typename Type, typename... Args> struct meta_associative_container_traits<dense_set<Type, Args...>> : internal::basic_meta_associative_container_traits<dense_set<Type, Args...>> {}; } // namespace entt #endif <commit_msg>meta: minor changes<commit_after>#ifndef ENTT_META_CONTAINER_HPP #define ENTT_META_CONTAINER_HPP #include <array> #include <map> #include <set> #include <type_traits> #include <unordered_map> #include <unordered_set> #include <vector> #include "../container/dense_map.hpp" #include "../container/dense_set.hpp" #include "meta.hpp" #include "type_traits.hpp" namespace entt { /** * @cond TURN_OFF_DOXYGEN * Internal details not to be documented. */ namespace internal { template<typename, typename = void> struct is_dynamic_sequence_container: std::false_type {}; template<typename Type> struct is_dynamic_sequence_container<Type, std::void_t<decltype(&Type::reserve)>>: std::true_type {}; template<typename, typename = void> struct is_key_only_meta_associative_container: std::true_type {}; template<typename Type> struct is_key_only_meta_associative_container<Type, std::void_t<typename Type::mapped_type>>: std::false_type {}; template<typename Type> struct basic_meta_sequence_container_traits { using iterator = meta_sequence_container::iterator; using size_type = std::size_t; [[nodiscard]] static size_type size(const any &container) ENTT_NOEXCEPT { return any_cast<const Type &>(container).size(); } [[nodiscard]] static bool resize([[maybe_unused]] any &container, [[maybe_unused]] size_type sz) { if constexpr(is_dynamic_sequence_container<Type>::value) { if(auto *const cont = any_cast<Type>(&container); cont) { cont->resize(sz); return true; } } return false; } [[nodiscard]] static iterator iter(any &container, const bool as_end) { using std::begin; if(auto *const cont = any_cast<Type>(&container); cont) { return iterator{begin(*cont), static_cast<typename iterator::difference_type>(as_end * cont->size())}; } const Type &as_const = any_cast<const Type &>(container); return iterator{begin(as_const), static_cast<typename iterator::difference_type>(as_end * as_const.size())}; } [[nodiscard]] static iterator insert([[maybe_unused]] any &container, [[maybe_unused]] const std::ptrdiff_t offset, [[maybe_unused]] meta_any &value) { if constexpr(is_dynamic_sequence_container<Type>::value) { if(auto *const cont = any_cast<Type>(&container); cont) { // this abomination is necessary because only on macos value_type and const_reference are different types for std::vector<bool> if(value.allow_cast<typename Type::const_reference>() || value.allow_cast<typename Type::value_type>()) { using std::begin; const auto *element = value.try_cast<std::remove_reference_t<typename Type::const_reference>>(); const auto curr = cont->insert(begin(*cont) + offset, element ? *element : value.cast<typename Type::value_type>()); return iterator{curr, curr - begin(*cont)}; } } } return {}; } [[nodiscard]] static iterator erase([[maybe_unused]] any &container, [[maybe_unused]] const std::ptrdiff_t offset) { if constexpr(is_dynamic_sequence_container<Type>::value) { if(auto *const cont = any_cast<Type>(&container); cont) { using std::begin; const auto curr = cont->erase(begin(*cont) + offset); return iterator{curr, curr - begin(*cont)}; } } return {}; } }; template<typename Type> struct basic_meta_associative_container_traits { using iterator = meta_associative_container::iterator; using size_type = std::size_t; static constexpr auto key_only = is_key_only_meta_associative_container<Type>::value; [[nodiscard]] static size_type size(const any &container) ENTT_NOEXCEPT { return any_cast<const Type &>(container).size(); } [[nodiscard]] static bool clear(any &container) { if(auto *const cont = any_cast<Type>(&container); cont) { cont->clear(); return true; } return false; } [[nodiscard]] static iterator iter(any &container, const bool as_end) { using std::begin; using std::end; if(auto *const cont = any_cast<Type>(&container); cont) { return iterator{std::integral_constant<bool, key_only>{}, as_end ? end(*cont) : begin(*cont)}; } const auto &as_const = any_cast<const Type &>(container); return iterator{std::integral_constant<bool, key_only>{}, as_end ? end(as_const) : begin(as_const)}; } [[nodiscard]] static bool insert(any &container, meta_any &key, [[maybe_unused]] meta_any &value) { auto *const cont = any_cast<Type>(&container); if constexpr(is_key_only_meta_associative_container<Type>::value) { return cont && key.allow_cast<const typename Type::key_type &>() && cont->insert(key.cast<const typename Type::key_type &>()).second; } else { return cont && key.allow_cast<const typename Type::key_type &>() && value.allow_cast<const typename Type::mapped_type &>() && cont->emplace(key.cast<const typename Type::key_type &>(), value.cast<const typename Type::mapped_type &>()).second; } } [[nodiscard]] static bool erase(any &container, meta_any &key) { auto *const cont = any_cast<Type>(&container); return cont && key.allow_cast<const typename Type::key_type &>() && (cont->erase(key.cast<const typename Type::key_type &>()) != cont->size()); } [[nodiscard]] static iterator find(any &container, meta_any &key) { if(key.allow_cast<const typename Type::key_type &>()) { if(auto *const cont = any_cast<Type>(&container); cont) { return iterator{std::integral_constant<bool, key_only>{}, cont->find(key.cast<const typename Type::key_type &>())}; } return iterator{std::integral_constant<bool, key_only>{}, any_cast<const Type &>(container).find(key.cast<const typename Type::key_type &>())}; } return {}; } }; } // namespace internal /** * Internal details not to be documented. * @endcond */ /** * @brief Meta sequence container traits for `std::vector`s of any type. * @tparam Type The type of elements. * @tparam Args Other arguments. */ template<typename Type, typename... Args> struct meta_sequence_container_traits<std::vector<Type, Args...>> : internal::basic_meta_sequence_container_traits<std::vector<Type, Args...>> {}; /** * @brief Meta sequence container traits for `std::array`s of any type. * @tparam Type The type of elements. * @tparam N The number of elements. */ template<typename Type, auto N> struct meta_sequence_container_traits<std::array<Type, N>> : internal::basic_meta_sequence_container_traits<std::array<Type, N>> {}; /** * @brief Meta associative container traits for `std::map`s of any type. * @tparam Key The key type of elements. * @tparam Value The value type of elements. * @tparam Args Other arguments. */ template<typename Key, typename Value, typename... Args> struct meta_associative_container_traits<std::map<Key, Value, Args...>> : internal::basic_meta_associative_container_traits<std::map<Key, Value, Args...>> {}; /** * @brief Meta associative container traits for `std::unordered_map`s of any * type. * @tparam Key The key type of elements. * @tparam Value The value type of elements. * @tparam Args Other arguments. */ template<typename Key, typename Value, typename... Args> struct meta_associative_container_traits<std::unordered_map<Key, Value, Args...>> : internal::basic_meta_associative_container_traits<std::unordered_map<Key, Value, Args...>> {}; /** * @brief Meta associative container traits for `std::set`s of any type. * @tparam Key The type of elements. * @tparam Args Other arguments. */ template<typename Key, typename... Args> struct meta_associative_container_traits<std::set<Key, Args...>> : internal::basic_meta_associative_container_traits<std::set<Key, Args...>> {}; /** * @brief Meta associative container traits for `std::unordered_set`s of any * type. * @tparam Key The type of elements. * @tparam Args Other arguments. */ template<typename Key, typename... Args> struct meta_associative_container_traits<std::unordered_set<Key, Args...>> : internal::basic_meta_associative_container_traits<std::unordered_set<Key, Args...>> {}; /** * @brief Meta associative container traits for `dense_map`s of any type. * @tparam Key The key type of the elements. * @tparam Type The value type of the elements. * @tparam Args Other arguments. */ template<typename Key, typename Type, typename... Args> struct meta_associative_container_traits<dense_map<Key, Type, Args...>> : internal::basic_meta_associative_container_traits<dense_map<Key, Type, Args...>> {}; /** * @brief Meta associative container traits for `dense_set`s of any type. * @tparam Type The value type of the elements. * @tparam Args Other arguments. */ template<typename Type, typename... Args> struct meta_associative_container_traits<dense_set<Type, Args...>> : internal::basic_meta_associative_container_traits<dense_set<Type, Args...>> {}; } // namespace entt #endif <|endoftext|>
<commit_before>const int MAX = 400; vector<vector<int> > adjlist; int res[MAX][MAX], n, s, t; int find_path() { const int inf = int(1e9 + 7); vector<int> visited(n, 0), from(n, -1); queue<int> q; int u, v, f; q.push(s); visited[s] = true; while (!visited[t] && !q.empty()) { u = q.front(); q.pop(); for (int i = 0; i < (int)adjlist[u].size(); ++i) { v = adjlist[u][i]; if (res[u][v] > 0 && !visited[v]) { from[v] = u; q.push(v); visited[v] = true; if (v == t) { break; } } } } f = inf; if (visited[t]) { for (v = t; from[v] > -1; v = from[v]) f = min(res[from[v]][v], f); for (v = t; from[v] > -1; v = from[v]) u = from[v], res[u][v] -= f, res[v][u] += f; } return (f == inf ? 0 : f); } int maxflow() { int mf = 0, d; while ((d = find_path())) mf += d; return mf; } <commit_msg>Improved Edmonds-Karp support for multiple edges by replacing the matrix representation with an edge list<commit_after>struct MfEdge { int v, cap; int backid; // id to the back edge }; struct MaxFlow { vector<vector<int>> g; // integers represent edges' ids vector<MfEdge> edges; // edges.size() should always be even int n, s, t; // n = # vertices, s = src vertex, t = sink vertex int find_path() { const int inf = int(1e9 + 7); vector<int> visited(n, 0), from(n, -1), used_edge(n, -1); queue<int> q; int u, v, f; q.push(s); visited[s] = true; while (!visited[t] && !q.empty()) { u = q.front(); q.pop(); for (int eid : g[u]) { int v = edges[eid].v; if (edges[eid].cap > 0 && !visited[v]) { from[v] = u, used_edge[v] = eid; q.push(v); visited[v] = true; if (v == t) { break; } } } } f = inf; if (visited[t]) { for (v = t; from[v] > -1; v = from[v]) { f = min(edges[used_edge[v]].cap, f); } for (v = t; from[v] > -1; v = from[v]) { int backid = edges[used_edge[v]].backid; edges[used_edge[v]].cap -= f; edges[backid].cap += f; } } return (f == inf ? 0 : f); } int get() { int mf = 0, d; while ((d = find_path())) mf += d; return mf; } }; <|endoftext|>
<commit_before>/* * fiberrenderer.cpp * * Created on: 28.12.2012 * @author Ralph Schurade */ #include "tuberenderer.h" #include "tuberendererthread.h" #include "glfunctions.h" #include "../../data/enums.h" #include "../../data/datasets/fiberselector.h" #include "../../data/properties/propertygroup.h" #include <QtOpenGL/QGLShaderProgram> #include <QDebug> TubeRenderer::TubeRenderer( FiberSelector* selector, QVector< QVector< float > >* data, QVector< QVector< float > >* extraData ) : ObjectRenderer(), m_selector( selector ), vboIds( new GLuint[ 4 ] ), m_data( data ), m_extraData( extraData ), m_numLines( data->size() ), m_numPoints( 0 ), m_isInitialized( false ) { m_colorField.resize( m_numLines ); } TubeRenderer::~TubeRenderer() { glDeleteBuffers( 4, vboIds ); } void TubeRenderer::init() { glGenBuffers( 4, vboIds ); } void TubeRenderer::draw( QMatrix4x4 p_matrix, QMatrix4x4 mv_matrix, int width, int height, int renderMode, PropertyGroup* props ) { float alpha = props->get( Fn::Property::D_ALPHA ).toFloat(); if ( renderMode == 0 ) // picking { return; } else if ( renderMode == 1 ) // we are drawing opaque objects { if ( alpha < 1.0 ) { // obviously not opaque return; } } else // we are drawing tranparent objects { if ( !(alpha < 1.0 ) ) { // not transparent return; } } QGLShaderProgram* program = GLFunctions::getShader( "tube" ); program->bind(); GLFunctions::setupTextures(); GLFunctions::setTextureUniforms( GLFunctions::getShader( "tube" ), "maingl" ); // Set modelview-projection matrix program->setUniformValue( "mvp_matrix", p_matrix * mv_matrix ); program->setUniformValue( "mv_matrixTI", mv_matrix.transposed().inverted() ); //glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); initGeometry(); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 0 ] ); glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 1 ] ); setShaderVars( props ); glBindBuffer( GL_ARRAY_BUFFER, vboIds[2] ); int extraLocation = program->attributeLocation( "a_extra" ); program->enableAttributeArray( extraLocation ); glVertexAttribPointer( extraLocation, 1, GL_FLOAT, GL_FALSE, sizeof(float), 0 ); glBindBuffer( GL_ARRAY_BUFFER, vboIds[3] ); int indexLocation = program->attributeLocation( "a_indexes" ); program->enableAttributeArray( indexLocation ); glVertexAttribPointer( indexLocation, 1, GL_FLOAT, GL_FALSE, sizeof(float), 0 ); program->setUniformValue( "u_alpha", alpha ); program->setUniformValue( "u_renderMode", renderMode ); program->setUniformValue( "u_canvasSize", width, height ); program->setUniformValue( "D0", 9 ); program->setUniformValue( "D1", 10 ); program->setUniformValue( "D2", 11 ); program->setUniformValue( "P0", 12 ); QVector<bool>*selected = m_selector->getSelection(); for ( int i = 0; i < m_data->size(); ++i ) { if ( selected->at( i ) ) { program->setUniformValue( "u_color", m_colorField[i].redF(), m_colorField[i].greenF(), m_colorField[i].blueF(), 1.0 ); program->setUniformValue( "u_globalColor", m_globalColorField[i].x(), m_globalColorField[i].y(), m_globalColorField[i].z(), 1.0 ); glDrawArrays( GL_QUAD_STRIP, m_startIndexes[i]*2, m_pointsPerLine[i]*2 ); } } glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); //glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); } void TubeRenderer::setupTextures() { } void TubeRenderer::setShaderVars( PropertyGroup* props ) { QGLShaderProgram* program = GLFunctions::getShader( "tube" ); program->bind(); intptr_t offset = 0; // Tell OpenGL programmable pipeline how to locate vertex position data int numFloats = 7; int vertexLocation = program->attributeLocation( "a_position" ); program->enableAttributeArray( vertexLocation ); glVertexAttribPointer( vertexLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float) * numFloats, (const void *) offset ); offset += sizeof(float) * 3; int normalLocation = program->attributeLocation( "a_normal" ); program->enableAttributeArray( normalLocation ); glVertexAttribPointer( normalLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float) * numFloats, (const void *) offset ); offset += sizeof(float) * 3; int dirLocation = program->attributeLocation( "a_direction" ); program->enableAttributeArray( dirLocation ); glVertexAttribPointer( dirLocation, 1, GL_FLOAT, GL_FALSE, sizeof(float) * numFloats, (const void *) offset ); program->setUniformValue( "u_fibGrowth", props->get( Fn::Property::D_FIBER_GROW_LENGTH).toFloat() ); program->setUniformValue( "u_colorMode", props->get( Fn::Property::D_COLORMODE ).toInt() ); program->setUniformValue( "u_colormap", props->get( Fn::Property::D_COLORMAP ).toInt() ); program->setUniformValue( "u_color", 1.0, 0.0, 0.0, 1.0 ); program->setUniformValue( "u_selectedMin", props->get( Fn::Property::D_SELECTED_MIN ).toFloat() ); program->setUniformValue( "u_selectedMax", props->get( Fn::Property::D_SELECTED_MAX ).toFloat() ); program->setUniformValue( "u_lowerThreshold", props->get( Fn::Property::D_LOWER_THRESHOLD ).toFloat() ); program->setUniformValue( "u_upperThreshold", props->get( Fn::Property::D_UPPER_THRESHOLD ).toFloat() ); program->setUniformValue( "u_thickness", props->get( Fn::Property::D_FIBER_THICKNESS ).toFloat() / 100.f ); } void TubeRenderer::initGeometry() { if ( m_isInitialized ) { return; } qDebug() << "create tube vbo's..."; int numThreads = GLFunctions::idealThreadCount; QVector<TubeRendererThread*> threads; // create threads for ( int i = 0; i < numThreads; ++i ) { threads.push_back( new TubeRendererThread( m_data, i ) ); } // run threads for ( int i = 0; i < numThreads; ++i ) { threads[i]->start(); } // wait for all threads to finish for ( int i = 0; i < numThreads; ++i ) { threads[i]->wait(); } QVector<float> verts; // combine verts from all threads m_globalColorField.clear(); for ( int i = 0; i < numThreads; ++i ) { verts += *( threads[i]->getVerts() ); m_globalColorField += *( threads[i]->getGlobalColors() ); } for ( int i = 0; i < numThreads; ++i ) { delete threads[i]; } glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 1 ] ); glBufferData( GL_ARRAY_BUFFER, verts.size() * sizeof(GLfloat), verts.data(), GL_STATIC_DRAW ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); m_pointsPerLine.resize( m_data->size() ); m_startIndexes.resize( m_data->size() ); int currentStart = 0; for ( int i = 0; i < m_data->size(); ++i ) { m_pointsPerLine[i] = m_data->at( i ).size() / 3; m_startIndexes[i] = currentStart; currentStart += m_pointsPerLine[i]; } updateExtraData( m_extraData ); qDebug() << "create tube vbo's done"; m_numPoints = verts.size() / 7; m_isInitialized = true; } void TubeRenderer::colorChanged( QVariant color ) { QVector<bool>*selected = m_selector->getSelection(); for ( int i = 0; i < m_numLines; ++i ) { if ( selected->at( i ) ) { m_colorField.replace( i, color.value<QColor>() ); } } } void TubeRenderer::updateExtraData( QVector< QVector< float > >* extraData ) { m_extraData = extraData; QVector<float>data; QVector<float>indexes; for ( int i = 0; i < extraData->size(); ++i ) { QVector<float>fib = extraData->at(i); for ( int k = 0; k < fib.size(); ++k ) { data.push_back( fib[k]); data.push_back( fib[k]); indexes.push_back( k ); indexes.push_back( k ); } } glDeleteBuffers( 1, &vboIds[2] ); glGenBuffers( 1, &vboIds[2] ); glBindBuffer( GL_ARRAY_BUFFER, vboIds[2] ); glBufferData( GL_ARRAY_BUFFER, data.size() * sizeof(GLfloat), data.data(), GL_STATIC_DRAW ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); glDeleteBuffers( 1, &vboIds[2] ); glGenBuffers( 1, &vboIds[2] ); glBindBuffer( GL_ARRAY_BUFFER, vboIds[3] ); glBufferData( GL_ARRAY_BUFFER, indexes.size() * sizeof(GLfloat), indexes.data(), GL_STATIC_DRAW ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); } <commit_msg>fixed crash with tuberenderer<commit_after>/* * fiberrenderer.cpp * * Created on: 28.12.2012 * @author Ralph Schurade */ #include "tuberenderer.h" #include "tuberendererthread.h" #include "glfunctions.h" #include "../../data/enums.h" #include "../../data/datasets/fiberselector.h" #include "../../data/properties/propertygroup.h" #include <QtOpenGL/QGLShaderProgram> #include <QDebug> TubeRenderer::TubeRenderer( FiberSelector* selector, QVector< QVector< float > >* data, QVector< QVector< float > >* extraData ) : ObjectRenderer(), m_selector( selector ), vboIds( new GLuint[ 4 ] ), m_data( data ), m_extraData( extraData ), m_numLines( data->size() ), m_numPoints( 0 ), m_isInitialized( false ) { m_colorField.resize( m_numLines ); } TubeRenderer::~TubeRenderer() { glDeleteBuffers( 4, vboIds ); } void TubeRenderer::init() { glGenBuffers( 4, vboIds ); } void TubeRenderer::draw( QMatrix4x4 p_matrix, QMatrix4x4 mv_matrix, int width, int height, int renderMode, PropertyGroup* props ) { float alpha = props->get( Fn::Property::D_ALPHA ).toFloat(); if ( renderMode == 0 ) // picking { return; } else if ( renderMode == 1 ) // we are drawing opaque objects { if ( alpha < 1.0 ) { // obviously not opaque return; } } else // we are drawing tranparent objects { if ( !(alpha < 1.0 ) ) { // not transparent return; } } QGLShaderProgram* program = GLFunctions::getShader( "tube" ); program->bind(); GLFunctions::setupTextures(); GLFunctions::setTextureUniforms( GLFunctions::getShader( "tube" ), "maingl" ); // Set modelview-projection matrix program->setUniformValue( "mvp_matrix", p_matrix * mv_matrix ); program->setUniformValue( "mv_matrixTI", mv_matrix.transposed().inverted() ); //glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); initGeometry(); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 0 ] ); glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 1 ] ); setShaderVars( props ); glBindBuffer( GL_ARRAY_BUFFER, vboIds[2] ); int extraLocation = program->attributeLocation( "a_extra" ); program->enableAttributeArray( extraLocation ); glVertexAttribPointer( extraLocation, 1, GL_FLOAT, GL_FALSE, sizeof(float), 0 ); glBindBuffer( GL_ARRAY_BUFFER, vboIds[3] ); int indexLocation = program->attributeLocation( "a_indexes" ); program->enableAttributeArray( indexLocation ); glVertexAttribPointer( indexLocation, 1, GL_FLOAT, GL_FALSE, sizeof(float), 0 ); program->setUniformValue( "u_alpha", alpha ); program->setUniformValue( "u_renderMode", renderMode ); program->setUniformValue( "u_canvasSize", width, height ); program->setUniformValue( "D0", 9 ); program->setUniformValue( "D1", 10 ); program->setUniformValue( "D2", 11 ); program->setUniformValue( "P0", 12 ); QVector<bool>*selected = m_selector->getSelection(); for ( int i = 0; i < m_data->size(); ++i ) { if ( selected->at( i ) ) { program->setUniformValue( "u_color", m_colorField[i].redF(), m_colorField[i].greenF(), m_colorField[i].blueF(), 1.0 ); program->setUniformValue( "u_globalColor", m_globalColorField[i].x(), m_globalColorField[i].y(), m_globalColorField[i].z(), 1.0 ); glDrawArrays( GL_QUAD_STRIP, m_startIndexes[i]*2, m_pointsPerLine[i]*2 ); } } glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); //glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); } void TubeRenderer::setupTextures() { } void TubeRenderer::setShaderVars( PropertyGroup* props ) { QGLShaderProgram* program = GLFunctions::getShader( "tube" ); program->bind(); intptr_t offset = 0; // Tell OpenGL programmable pipeline how to locate vertex position data int numFloats = 7; int vertexLocation = program->attributeLocation( "a_position" ); program->enableAttributeArray( vertexLocation ); glVertexAttribPointer( vertexLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float) * numFloats, (const void *) offset ); offset += sizeof(float) * 3; int normalLocation = program->attributeLocation( "a_normal" ); program->enableAttributeArray( normalLocation ); glVertexAttribPointer( normalLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float) * numFloats, (const void *) offset ); offset += sizeof(float) * 3; int dirLocation = program->attributeLocation( "a_direction" ); program->enableAttributeArray( dirLocation ); glVertexAttribPointer( dirLocation, 1, GL_FLOAT, GL_FALSE, sizeof(float) * numFloats, (const void *) offset ); program->setUniformValue( "u_fibGrowth", props->get( Fn::Property::D_FIBER_GROW_LENGTH).toFloat() ); program->setUniformValue( "u_colorMode", props->get( Fn::Property::D_COLORMODE ).toInt() ); program->setUniformValue( "u_colormap", props->get( Fn::Property::D_COLORMAP ).toInt() ); program->setUniformValue( "u_color", 1.0, 0.0, 0.0, 1.0 ); program->setUniformValue( "u_selectedMin", props->get( Fn::Property::D_SELECTED_MIN ).toFloat() ); program->setUniformValue( "u_selectedMax", props->get( Fn::Property::D_SELECTED_MAX ).toFloat() ); program->setUniformValue( "u_lowerThreshold", props->get( Fn::Property::D_LOWER_THRESHOLD ).toFloat() ); program->setUniformValue( "u_upperThreshold", props->get( Fn::Property::D_UPPER_THRESHOLD ).toFloat() ); program->setUniformValue( "u_thickness", props->get( Fn::Property::D_FIBER_THICKNESS ).toFloat() / 100.f ); } void TubeRenderer::initGeometry() { if ( m_isInitialized ) { return; } qDebug() << "create tube vbo's..."; int numThreads = GLFunctions::idealThreadCount; QVector<TubeRendererThread*> threads; // create threads for ( int i = 0; i < numThreads; ++i ) { threads.push_back( new TubeRendererThread( m_data, i ) ); } // run threads for ( int i = 0; i < numThreads; ++i ) { threads[i]->start(); } // wait for all threads to finish for ( int i = 0; i < numThreads; ++i ) { threads[i]->wait(); } QVector<float> verts; // combine verts from all threads m_globalColorField.clear(); for ( int i = 0; i < numThreads; ++i ) { verts += *( threads[i]->getVerts() ); m_globalColorField += *( threads[i]->getGlobalColors() ); } for ( int i = 0; i < numThreads; ++i ) { delete threads[i]; } glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 1 ] ); glBufferData( GL_ARRAY_BUFFER, verts.size() * sizeof(GLfloat), verts.data(), GL_STATIC_DRAW ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); m_pointsPerLine.resize( m_data->size() ); m_startIndexes.resize( m_data->size() ); int currentStart = 0; for ( int i = 0; i < m_data->size(); ++i ) { m_pointsPerLine[i] = m_data->at( i ).size() / 3; m_startIndexes[i] = currentStart; currentStart += m_pointsPerLine[i]; } updateExtraData( m_extraData ); qDebug() << "create tube vbo's done"; m_numPoints = verts.size() / 7; m_isInitialized = true; } void TubeRenderer::colorChanged( QVariant color ) { QVector<bool>*selected = m_selector->getSelection(); for ( int i = 0; i < m_numLines; ++i ) { if ( selected->at( i ) ) { m_colorField.replace( i, color.value<QColor>() ); } } } void TubeRenderer::updateExtraData( QVector< QVector< float > >* extraData ) { m_extraData = extraData; QVector<float>data; QVector<float>indexes; for ( int i = 0; i < extraData->size(); ++i ) { QVector<float>fib = extraData->at(i); for ( int k = 0; k < fib.size(); ++k ) { data.push_back( fib[k]); data.push_back( fib[k]); indexes.push_back( k ); indexes.push_back( k ); } } glDeleteBuffers( 1, &vboIds[2] ); glGenBuffers( 1, &vboIds[2] ); glBindBuffer( GL_ARRAY_BUFFER, vboIds[2] ); glBufferData( GL_ARRAY_BUFFER, data.size() * sizeof(GLfloat), data.data(), GL_STATIC_DRAW ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); glDeleteBuffers( 1, &vboIds[3] ); glGenBuffers( 1, &vboIds[3] ); glBindBuffer( GL_ARRAY_BUFFER, vboIds[3] ); glBufferData( GL_ARRAY_BUFFER, indexes.size() * sizeof(GLfloat), indexes.data(), GL_STATIC_DRAW ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); } <|endoftext|>
<commit_before>#include "qhalgroup.h" #include "debughelper.h" QHalGroup::QHalGroup(QQuickItem *parent) : QQuickItem(parent), m_halgroupUri(""), m_name("default"), m_ready(false), m_sState(Down), m_connectionState(Disconnected), m_error(NoError), m_errorString(""), m_containerItem(this), m_componentCompleted(false), m_context(NULL), m_halgroupSocket(NULL), m_halgroupHeartbeatTimer(new QTimer(this)), m_halgroupPingOutstanding(false) { connect(m_halgroupHeartbeatTimer, SIGNAL(timeout()), this, SLOT(halgroupHeartbeatTimerTick())); } QHalGroup::~QHalGroup() { disconnectSockets(); } /** componentComplete is executed when the QML component is fully loaded */ void QHalGroup::componentComplete() { m_componentCompleted = true; if (m_ready == true) // the component was set to ready before it was completed { start(); } QQuickItem::componentComplete(); } /** Recurses through a list of objects */ QList<QHalSignal *> QHalGroup::recurseObjects(const QObjectList &list) const { QList<QHalSignal*> halSignals; foreach (QObject *object, list) { QHalSignal *halSignal; halSignal = qobject_cast<QHalSignal*>(object); if (halSignal != NULL) { halSignals.append(halSignal); } if (object->children().size() > 0) { halSignals.append(recurseObjects(object->children())); } } return halSignals; } void QHalGroup::start() { #ifdef QT_DEBUG DEBUG_TAG(1, m_name, "start") #endif updateState(Connecting); if (connectSockets()) { addSignals(); subscribe(); } } void QHalGroup::stop() { #ifdef QT_DEBUG DEBUG_TAG(1, m_name, "stop") #endif // cleanup here stopHalgroupHeartbeat(); disconnectSockets(); removeSignals(); updateState(Disconnected); updateError(NoError, ""); // clear the error here } void QHalGroup::startHalgroupHeartbeat(int interval) { m_halgroupHeartbeatTimer->stop(); m_halgroupPingOutstanding = false; if (interval > 0) { m_halgroupHeartbeatTimer->setInterval(interval); m_halgroupHeartbeatTimer->start(); } } void QHalGroup::stopHalgroupHeartbeat() { m_halgroupHeartbeatTimer->stop(); } void QHalGroup::refreshHalgroupHeartbeat() { if (m_halgroupHeartbeatTimer->isActive()) { m_halgroupHeartbeatTimer->stop(); m_halgroupHeartbeatTimer->start(); } } void QHalGroup::updateState(QHalGroup::State state) { if (state != m_connectionState) { if (m_connectionState == Connected) // we are not connected anymore { unsyncSignals(); stopHalgroupHeartbeat(); } m_connectionState = state; emit connectionStateChanged(m_connectionState); } } void QHalGroup::updateError(QHalGroup::ConnectionError error, const QString &errorString) { m_error = error; m_errorString = errorString; emit errorStringChanged(m_errorString); emit errorChanged(m_error); } /** Updates a local signal with the value of a remote signal */ void QHalGroup::signalUpdate(const pb::Signal &remoteSignal, QHalSignal *localSignal) { #ifdef QT_DEBUG DEBUG_TAG(2, m_name, "signal update" << localSignal->name() << remoteSignal.halfloat() << remoteSignal.halbit() << remoteSignal.hals32() << remoteSignal.halu32()) #endif if (remoteSignal.has_halfloat()) { localSignal->setValue(QVariant(remoteSignal.halfloat())); } else if (remoteSignal.has_halbit()) { localSignal->setValue(QVariant(remoteSignal.halbit())); } else if (remoteSignal.has_hals32()) { localSignal->setValue(QVariant(remoteSignal.hals32())); } else if (remoteSignal.has_halu32()) { localSignal->setValue(QVariant(remoteSignal.halu32())); } localSignal->setSynced(true); // when the signal is updated we are synced } void QHalGroup::halgroupMessageReceived(const QList<QByteArray> &messageList) { QByteArray topic; topic = messageList.at(0); m_rx.ParseFromArray(messageList.at(1).data(), messageList.at(1).size()); #ifdef QT_DEBUG std::string s; gpb::TextFormat::PrintToString(m_rx, &s); DEBUG_TAG(3, m_name, "halgroup update" << topic << QString::fromStdString(s)) #endif if (m_rx.type() == pb::MT_HALGROUP_INCREMENTAL_UPDATE) // incremental update { for (int i = 0; i < m_rx.signal_size(); ++i) { pb::Signal remoteSignal = m_rx.signal(i); QHalSignal *localSignal = m_signalsByHandle.value(remoteSignal.handle()); signalUpdate(remoteSignal, localSignal); } if (m_sState != Up) { m_sState = Up; updateError(NoError, ""); updateState(Connected); } refreshHalgroupHeartbeat(); return; } else if (m_rx.type() == pb::MT_HALGROUP_FULL_UPDATE) // full update { for (int i = 0; i < m_rx.group_size(); ++i) { pb::Group group = m_rx.group(i); for (int j = 0; j < group.member_size(); ++j) { pb::Member member = group.member(j); if (member.has_signal()) { pb::Signal remoteSignal = member.signal(); QString name = QString::fromStdString(remoteSignal.name()); int dotIndex = name.indexOf("."); if (dotIndex != -1) // strip comp prefix { name = name.mid(dotIndex + 1); } QHalSignal *localSignal = m_signalsByName.value(name); localSignal->setHandle(remoteSignal.handle()); m_signalsByHandle.insert(remoteSignal.handle(), localSignal); signalUpdate(remoteSignal, localSignal); } } if (m_sState != Up) // will be executed only once { m_sState = Up; updateError(NoError, ""); updateState(Connected); } } if (m_rx.has_pparams()) { pb::ProtocolParameters pparams = m_rx.pparams(); startHalgroupHeartbeat(pparams.keepalive_timer()); } return; } else if (m_rx.type() == pb::MT_PING) { refreshHalgroupHeartbeat(); return; } else if (m_rx.type() == pb::MT_HALGROUP_ERROR) // error { QString errorString; for (int i = 0; i < m_rx.note_size(); ++i) { errorString.append(QString::fromStdString(m_rx.note(i)) + "\n"); } m_sState = Down; updateError(HalGroupError, errorString); updateState(Error); #ifdef QT_DEBUG DEBUG_TAG(1, m_name, "proto error on subscribe" << errorString) #endif return; } #ifdef QT_DEBUG gpb::TextFormat::PrintToString(m_rx, &s); DEBUG_TAG(1, m_name, "halgroup_update: unknown message type: " << QString::fromStdString(s)) #endif } void QHalGroup::pollError(int errorNum, const QString &errorMsg) { QString errorString; errorString = QString("Error %1: ").arg(errorNum) + errorMsg; updateError(SocketError, errorString); updateState(Error); } void QHalGroup::halgroupHeartbeatTimerTick() { unsubscribe(); updateError(TimeoutError, "Halgroup service timed out"); updateState(Error); #ifdef QT_DEBUG DEBUG_TAG(1, m_name, "halcmd timeout") #endif subscribe(); // trigger a fresh subscribe m_halgroupPingOutstanding = true; } /** Scans all children of the container item for signals and adds them to a map */ void QHalGroup::addSignals() { QList<QHalSignal*> halSignals; if (m_containerItem == NULL) { return; } halSignals = recurseObjects(m_containerItem->children()); foreach (QHalSignal *signal, halSignals) { if (signal->name().isEmpty() || (signal->enabled() == false)) // ignore signals with empty name or disabled { continue; } m_signalsByName.insert(signal->name(), signal); #ifdef QT_DEBUG DEBUG_TAG(1, m_name, "signal added: " << signal->name()) #endif } } /** Removes all previously added signals */ void QHalGroup::removeSignals() { m_signalsByHandle.clear(); m_signalsByName.clear(); } /** Sets synced of all signals to false */ void QHalGroup::unsyncSignals() { QMapIterator<QString, QHalSignal*> i(m_signalsByName); while (i.hasNext()) { i.next(); i.value()->setSynced(false); } } /** Connects the 0MQ sockets */ bool QHalGroup::connectSockets() { m_context = new PollingZMQContext(this, 1); connect(m_context, SIGNAL(pollError(int,QString)), this, SLOT(pollError(int,QString))); m_context->start(); m_halgroupSocket = m_context->createSocket(ZMQSocket::TYP_SUB, this); m_halgroupSocket->setLinger(0); try { m_halgroupSocket->connectTo(m_halgroupUri); } catch (zmq::error_t e) { QString errorString; errorString = QString("Error %1: ").arg(e.num()) + QString(e.what()); updateError(SocketError, errorString); updateState(Error); return false; } connect(m_halgroupSocket, SIGNAL(messageReceived(QList<QByteArray>)), this, SLOT(halgroupMessageReceived(QList<QByteArray>))); #ifdef QT_DEBUG DEBUG_TAG(1, m_name, "socket connected" << m_halgroupUri) #endif return true; } /** Disconnects the 0MQ sockets */ void QHalGroup::disconnectSockets() { if (m_halgroupSocket != NULL) { m_halgroupSocket->close(); m_halgroupSocket->deleteLater(); m_halgroupSocket = NULL; } if (m_context != NULL) { m_context->stop(); m_context->deleteLater(); m_context = NULL; } } void QHalGroup::subscribe() { m_sState = Trying; m_halgroupSocket->subscribeTo(m_name.toLocal8Bit()); } void QHalGroup::unsubscribe() { m_sState = Down; m_halgroupSocket->unsubscribeFrom(m_name.toLocal8Bit()); } /** If the ready property has a rising edge we try to connect * if it is has a falling edge we disconnect and cleanup */ void QHalGroup::setReady(bool arg) { if (m_ready != arg) { m_ready = arg; emit readyChanged(arg); if (m_componentCompleted == false) { return; } if (m_ready) { start(); } else { stop(); } } } <commit_msg>halremote/HalGroup: updating type of signals<commit_after>#include "qhalgroup.h" #include "debughelper.h" QHalGroup::QHalGroup(QQuickItem *parent) : QQuickItem(parent), m_halgroupUri(""), m_name("default"), m_ready(false), m_sState(Down), m_connectionState(Disconnected), m_error(NoError), m_errorString(""), m_containerItem(this), m_componentCompleted(false), m_context(NULL), m_halgroupSocket(NULL), m_halgroupHeartbeatTimer(new QTimer(this)), m_halgroupPingOutstanding(false) { connect(m_halgroupHeartbeatTimer, SIGNAL(timeout()), this, SLOT(halgroupHeartbeatTimerTick())); } QHalGroup::~QHalGroup() { disconnectSockets(); } /** componentComplete is executed when the QML component is fully loaded */ void QHalGroup::componentComplete() { m_componentCompleted = true; if (m_ready == true) // the component was set to ready before it was completed { start(); } QQuickItem::componentComplete(); } /** Recurses through a list of objects */ QList<QHalSignal *> QHalGroup::recurseObjects(const QObjectList &list) const { QList<QHalSignal*> halSignals; foreach (QObject *object, list) { QHalSignal *halSignal; halSignal = qobject_cast<QHalSignal*>(object); if (halSignal != NULL) { halSignals.append(halSignal); } if (object->children().size() > 0) { halSignals.append(recurseObjects(object->children())); } } return halSignals; } void QHalGroup::start() { #ifdef QT_DEBUG DEBUG_TAG(1, m_name, "start") #endif updateState(Connecting); if (connectSockets()) { addSignals(); subscribe(); } } void QHalGroup::stop() { #ifdef QT_DEBUG DEBUG_TAG(1, m_name, "stop") #endif // cleanup here stopHalgroupHeartbeat(); disconnectSockets(); removeSignals(); updateState(Disconnected); updateError(NoError, ""); // clear the error here } void QHalGroup::startHalgroupHeartbeat(int interval) { m_halgroupHeartbeatTimer->stop(); m_halgroupPingOutstanding = false; if (interval > 0) { m_halgroupHeartbeatTimer->setInterval(interval); m_halgroupHeartbeatTimer->start(); } } void QHalGroup::stopHalgroupHeartbeat() { m_halgroupHeartbeatTimer->stop(); } void QHalGroup::refreshHalgroupHeartbeat() { if (m_halgroupHeartbeatTimer->isActive()) { m_halgroupHeartbeatTimer->stop(); m_halgroupHeartbeatTimer->start(); } } void QHalGroup::updateState(QHalGroup::State state) { if (state != m_connectionState) { if (m_connectionState == Connected) // we are not connected anymore { unsyncSignals(); stopHalgroupHeartbeat(); } m_connectionState = state; emit connectionStateChanged(m_connectionState); } } void QHalGroup::updateError(QHalGroup::ConnectionError error, const QString &errorString) { m_error = error; m_errorString = errorString; emit errorStringChanged(m_errorString); emit errorChanged(m_error); } /** Updates a local signal with the value of a remote signal */ void QHalGroup::signalUpdate(const pb::Signal &remoteSignal, QHalSignal *localSignal) { #ifdef QT_DEBUG DEBUG_TAG(2, m_name, "signal update" << localSignal->name() << remoteSignal.halfloat() << remoteSignal.halbit() << remoteSignal.hals32() << remoteSignal.halu32()) #endif if (remoteSignal.has_halfloat()) { localSignal->setType(QHalSignal::Float); localSignal->setValue(QVariant(remoteSignal.halfloat())); } else if (remoteSignal.has_halbit()) { localSignal->setType(QHalSignal::Bit); localSignal->setValue(QVariant(remoteSignal.halbit())); } else if (remoteSignal.has_hals32()) { localSignal->setType(QHalSignal::S32); localSignal->setValue(QVariant(remoteSignal.hals32())); } else if (remoteSignal.has_halu32()) { localSignal->setType(QHalSignal::U32); localSignal->setValue(QVariant(remoteSignal.halu32())); } localSignal->setSynced(true); // when the signal is updated we are synced } void QHalGroup::halgroupMessageReceived(const QList<QByteArray> &messageList) { QByteArray topic; topic = messageList.at(0); m_rx.ParseFromArray(messageList.at(1).data(), messageList.at(1).size()); #ifdef QT_DEBUG std::string s; gpb::TextFormat::PrintToString(m_rx, &s); DEBUG_TAG(3, m_name, "halgroup update" << topic << QString::fromStdString(s)) #endif if (m_rx.type() == pb::MT_HALGROUP_INCREMENTAL_UPDATE) // incremental update { for (int i = 0; i < m_rx.signal_size(); ++i) { pb::Signal remoteSignal = m_rx.signal(i); QHalSignal *localSignal = m_signalsByHandle.value(remoteSignal.handle()); signalUpdate(remoteSignal, localSignal); } if (m_sState != Up) { m_sState = Up; updateError(NoError, ""); updateState(Connected); } refreshHalgroupHeartbeat(); return; } else if (m_rx.type() == pb::MT_HALGROUP_FULL_UPDATE) // full update { for (int i = 0; i < m_rx.group_size(); ++i) { pb::Group group = m_rx.group(i); for (int j = 0; j < group.member_size(); ++j) { pb::Member member = group.member(j); if (member.has_signal()) { pb::Signal remoteSignal = member.signal(); QString name = QString::fromStdString(remoteSignal.name()); int dotIndex = name.indexOf("."); if (dotIndex != -1) // strip comp prefix { name = name.mid(dotIndex + 1); } QHalSignal *localSignal = m_signalsByName.value(name); localSignal->setHandle(remoteSignal.handle()); m_signalsByHandle.insert(remoteSignal.handle(), localSignal); signalUpdate(remoteSignal, localSignal); } } if (m_sState != Up) // will be executed only once { m_sState = Up; updateError(NoError, ""); updateState(Connected); } } if (m_rx.has_pparams()) { pb::ProtocolParameters pparams = m_rx.pparams(); startHalgroupHeartbeat(pparams.keepalive_timer()); } return; } else if (m_rx.type() == pb::MT_PING) { refreshHalgroupHeartbeat(); return; } else if (m_rx.type() == pb::MT_HALGROUP_ERROR) // error { QString errorString; for (int i = 0; i < m_rx.note_size(); ++i) { errorString.append(QString::fromStdString(m_rx.note(i)) + "\n"); } m_sState = Down; updateError(HalGroupError, errorString); updateState(Error); #ifdef QT_DEBUG DEBUG_TAG(1, m_name, "proto error on subscribe" << errorString) #endif return; } #ifdef QT_DEBUG gpb::TextFormat::PrintToString(m_rx, &s); DEBUG_TAG(1, m_name, "halgroup_update: unknown message type: " << QString::fromStdString(s)) #endif } void QHalGroup::pollError(int errorNum, const QString &errorMsg) { QString errorString; errorString = QString("Error %1: ").arg(errorNum) + errorMsg; updateError(SocketError, errorString); updateState(Error); } void QHalGroup::halgroupHeartbeatTimerTick() { unsubscribe(); updateError(TimeoutError, "Halgroup service timed out"); updateState(Error); #ifdef QT_DEBUG DEBUG_TAG(1, m_name, "halcmd timeout") #endif subscribe(); // trigger a fresh subscribe m_halgroupPingOutstanding = true; } /** Scans all children of the container item for signals and adds them to a map */ void QHalGroup::addSignals() { QList<QHalSignal*> halSignals; if (m_containerItem == NULL) { return; } halSignals = recurseObjects(m_containerItem->children()); foreach (QHalSignal *signal, halSignals) { if (signal->name().isEmpty() || (signal->enabled() == false)) // ignore signals with empty name or disabled { continue; } m_signalsByName.insert(signal->name(), signal); #ifdef QT_DEBUG DEBUG_TAG(1, m_name, "signal added: " << signal->name()) #endif } } /** Removes all previously added signals */ void QHalGroup::removeSignals() { m_signalsByHandle.clear(); m_signalsByName.clear(); } /** Sets synced of all signals to false */ void QHalGroup::unsyncSignals() { QMapIterator<QString, QHalSignal*> i(m_signalsByName); while (i.hasNext()) { i.next(); i.value()->setSynced(false); } } /** Connects the 0MQ sockets */ bool QHalGroup::connectSockets() { m_context = new PollingZMQContext(this, 1); connect(m_context, SIGNAL(pollError(int,QString)), this, SLOT(pollError(int,QString))); m_context->start(); m_halgroupSocket = m_context->createSocket(ZMQSocket::TYP_SUB, this); m_halgroupSocket->setLinger(0); try { m_halgroupSocket->connectTo(m_halgroupUri); } catch (zmq::error_t e) { QString errorString; errorString = QString("Error %1: ").arg(e.num()) + QString(e.what()); updateError(SocketError, errorString); updateState(Error); return false; } connect(m_halgroupSocket, SIGNAL(messageReceived(QList<QByteArray>)), this, SLOT(halgroupMessageReceived(QList<QByteArray>))); #ifdef QT_DEBUG DEBUG_TAG(1, m_name, "socket connected" << m_halgroupUri) #endif return true; } /** Disconnects the 0MQ sockets */ void QHalGroup::disconnectSockets() { if (m_halgroupSocket != NULL) { m_halgroupSocket->close(); m_halgroupSocket->deleteLater(); m_halgroupSocket = NULL; } if (m_context != NULL) { m_context->stop(); m_context->deleteLater(); m_context = NULL; } } void QHalGroup::subscribe() { m_sState = Trying; m_halgroupSocket->subscribeTo(m_name.toLocal8Bit()); } void QHalGroup::unsubscribe() { m_sState = Down; m_halgroupSocket->unsubscribeFrom(m_name.toLocal8Bit()); } /** If the ready property has a rising edge we try to connect * if it is has a falling edge we disconnect and cleanup */ void QHalGroup::setReady(bool arg) { if (m_ready != arg) { m_ready = arg; emit readyChanged(arg); if (m_componentCompleted == false) { return; } if (m_ready) { start(); } else { stop(); } } } <|endoftext|>
<commit_before>/* * This file is part of `et engine` * Copyright 2009-2013 by Sergey Reznik * Please, do not modify content without approval. * */ #include <fstream> #include <libpng/png.h> #include <et/imaging/imagewriter.h> using namespace et; bool internal_writePNGtoFile(const std::string& fileName, const BinaryDataStorage& data, const vec2i& size, int components, int bitsPerComponent, bool flip); bool internal_writePNGtoBuffer(BinaryDataStorage& buffer, const BinaryDataStorage& data, const vec2i& size, int components, int bitsPerComponent, bool flip); void internal_func_writePNGtoBuffer(png_structp png_ptr, png_bytep data, png_size_t length); void internal_func_PNGflush(png_structp png_ptr); bool ImageWriter::writeImageToFile(const std::string& fileName, const BinaryDataStorage& data, const vec2i& size, int components, int bitsPerComponent, ImageFormat fmt, bool flip) { switch (fmt) { case ImageFormat_PNG: return internal_writePNGtoFile(fileName, data, size, components, bitsPerComponent, flip); default: return false; } } bool ImageWriter::writeImageToBuffer(BinaryDataStorage& buffer, const BinaryDataStorage& data, const vec2i& size, int components, int bitsPerComponent, ImageFormat fmt, bool flip) { switch (fmt) { case ImageFormat_PNG: return internal_writePNGtoBuffer(buffer, data, size, components, bitsPerComponent, flip); default: return false; } } std::string ImageWriter::extensionForImageFormat(ImageFormat fmt) { switch (fmt) { case ImageFormat_PNG: return ".png"; default: return ".unrecognizedimageformat"; } } void internal_func_writePNGtoBuffer(png_structp png_ptr, png_bytep data, png_size_t length) { BinaryDataStorage* buffer = reinterpret_cast<BinaryDataStorage*>(png_get_io_ptr(png_ptr)); buffer->fitToSize(length); etCopyMemory(buffer->current_ptr(), data, length); buffer->applyOffset(length); } bool internal_writePNGtoBuffer(BinaryDataStorage& buffer, const BinaryDataStorage& data, const vec2i& size, int components, int bitsPerComponent, bool flip) { png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) return false; png_infop info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_write_struct(&png_ptr, &info_ptr); return false; } png_init_io(png_ptr, 0); png_byte colorType = 0; switch (components) { case 3: { colorType = PNG_COLOR_TYPE_RGB; break; } case 4: { colorType = PNG_COLOR_TYPE_RGBA; break; } } png_uint_32 w = static_cast<png_uint_32>(size.x); png_uint_32 h = static_cast<png_uint_32>(size.y); png_set_IHDR(png_ptr, info_ptr, w, h, bitsPerComponent, colorType, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); png_bytep* row_pointers = new png_bytep[size.y]; int rowSize = size.x * components * bitsPerComponent / 8; if (flip) { for (int y = 0; y < size.y; y++) row_pointers[y] = (png_bytep)(&data[(size.y - 1 - y) * rowSize]); } else { for (int y = 0; y < size.y; y++) row_pointers[y] = (png_bytep)(&data[y * rowSize]); } png_set_write_fn(png_ptr, &buffer, internal_func_writePNGtoBuffer, 0); png_write_info(png_ptr, info_ptr); png_write_image(png_ptr, row_pointers); png_write_end(png_ptr, NULL); png_destroy_write_struct(&png_ptr, &info_ptr); delete [] row_pointers; return true; } bool internal_writePNGtoFile(const std::string& fileName, const BinaryDataStorage& data, const vec2i& size, int components, int bitsPerComponent, bool flip) { png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) return false; png_infop info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_write_struct(&png_ptr, &info_ptr); return false; } FILE* fp = fopen(fileName.c_str(), "wb"); if (!fp) return false; png_init_io(png_ptr, fp); png_byte colorType = 0; switch (components) { case 1: { colorType = PNG_COLOR_TYPE_GRAY; break; } case 3: { colorType = PNG_COLOR_TYPE_RGB; break; } case 4: { colorType = PNG_COLOR_TYPE_RGBA; break; } default: ET_FAIL("Invalid components number."); } png_uint_32 w = static_cast<png_uint_32>(size.x); png_uint_32 h = static_cast<png_uint_32>(size.y); int rowSize = size.x * components * bitsPerComponent / 8; png_set_IHDR(png_ptr, info_ptr, w, h, bitsPerComponent, colorType, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); png_write_info(png_ptr, info_ptr); if (flip) { for (int y = 0; y < size.y; y++) png_write_row(png_ptr, (png_bytep)(&data[(size.y - 1 - y) * rowSize])); } else { for (int y = 0; y < size.y; y++) png_write_row(png_ptr, (png_bytep)(&data[y * rowSize])); } png_write_end(png_ptr, NULL); png_destroy_write_struct(&png_ptr, &info_ptr); fclose(fp); return true; } <commit_msg>png writing improved (compression level - 3, larger but faster)<commit_after>/* * This file is part of `et engine` * Copyright 2009-2013 by Sergey Reznik * Please, do not modify content without approval. * */ #include <fstream> #include <libpng/png.h> #include <et/imaging/imagewriter.h> using namespace et; bool internal_writePNGtoFile(const std::string& fileName, const BinaryDataStorage& data, const vec2i& size, int components, int bitsPerComponent, bool flip); bool internal_writePNGtoBuffer(BinaryDataStorage& buffer, const BinaryDataStorage& data, const vec2i& size, int components, int bitsPerComponent, bool flip); void internal_func_writePNGtoBuffer(png_structp png_ptr, png_bytep data, png_size_t length); void internal_func_PNGflush(png_structp png_ptr); bool ImageWriter::writeImageToFile(const std::string& fileName, const BinaryDataStorage& data, const vec2i& size, int components, int bitsPerComponent, ImageFormat fmt, bool flip) { switch (fmt) { case ImageFormat_PNG: return internal_writePNGtoFile(fileName, data, size, components, bitsPerComponent, flip); default: return false; } } bool ImageWriter::writeImageToBuffer(BinaryDataStorage& buffer, const BinaryDataStorage& data, const vec2i& size, int components, int bitsPerComponent, ImageFormat fmt, bool flip) { switch (fmt) { case ImageFormat_PNG: return internal_writePNGtoBuffer(buffer, data, size, components, bitsPerComponent, flip); default: return false; } } std::string ImageWriter::extensionForImageFormat(ImageFormat fmt) { switch (fmt) { case ImageFormat_PNG: return ".png"; default: return ".unrecognizedimageformat"; } } void internal_func_writePNGtoBuffer(png_structp png_ptr, png_bytep data, png_size_t length) { BinaryDataStorage* buffer = reinterpret_cast<BinaryDataStorage*>(png_get_io_ptr(png_ptr)); buffer->fitToSize(length); etCopyMemory(buffer->current_ptr(), data, length); buffer->applyOffset(length); } bool internal_writePNGtoBuffer(BinaryDataStorage& buffer, const BinaryDataStorage& data, const vec2i& size, int components, int bitsPerComponent, bool flip) { png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) return false; png_infop info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_write_struct(&png_ptr, &info_ptr); return false; } png_init_io(png_ptr, 0); png_byte colorType = 0; switch (components) { case 3: { colorType = PNG_COLOR_TYPE_RGB; break; } case 4: { colorType = PNG_COLOR_TYPE_RGBA; break; } } png_uint_32 w = static_cast<png_uint_32>(size.x); png_uint_32 h = static_cast<png_uint_32>(size.y); png_set_IHDR(png_ptr, info_ptr, w, h, bitsPerComponent, colorType, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); png_bytep* row_pointers = new png_bytep[size.y]; int rowSize = size.x * components * bitsPerComponent / 8; if (flip) { for (int y = 0; y < size.y; y++) row_pointers[y] = (png_bytep)(&data[(size.y - 1 - y) * rowSize]); } else { for (int y = 0; y < size.y; y++) row_pointers[y] = (png_bytep)(&data[y * rowSize]); } png_set_write_fn(png_ptr, &buffer, internal_func_writePNGtoBuffer, 0); png_write_info(png_ptr, info_ptr); png_write_image(png_ptr, row_pointers); png_write_end(png_ptr, NULL); png_destroy_write_struct(&png_ptr, &info_ptr); delete [] row_pointers; return true; } bool internal_writePNGtoFile(const std::string& fileName, const BinaryDataStorage& data, const vec2i& size, int components, int bitsPerComponent, bool flip) { png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) return false; png_infop info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_write_struct(&png_ptr, &info_ptr); return false; } FILE* fp = fopen(fileName.c_str(), "wb"); if (!fp) return false; png_init_io(png_ptr, fp); png_byte colorType = 0; switch (components) { case 1: { colorType = PNG_COLOR_TYPE_GRAY; break; } case 3: { colorType = PNG_COLOR_TYPE_RGB; break; } case 4: { colorType = PNG_COLOR_TYPE_RGBA; break; } default: ET_FAIL("Invalid components number."); } png_uint_32 w = static_cast<png_uint_32>(size.x); png_uint_32 h = static_cast<png_uint_32>(size.y); int rowSize = size.x * components * bitsPerComponent / 8; png_set_IHDR(png_ptr, info_ptr, w, h, bitsPerComponent, colorType, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); png_write_info(png_ptr, info_ptr); png_set_compression_level(png_ptr, 3); png_set_compression_strategy(png_ptr, 0); png_set_filter(png_ptr, 0, PNG_ALL_FILTERS); if (flip) { for (int y = 0; y < size.y; y++) png_write_row(png_ptr, (png_bytep)(&data[(size.y - 1 - y) * rowSize])); } else { for (int y = 0; y < size.y; y++) png_write_row(png_ptr, (png_bytep)(&data[y * rowSize])); } png_write_end(png_ptr, NULL); png_destroy_write_struct(&png_ptr, &info_ptr); fclose(fp); return true; } <|endoftext|>
<commit_before>/* Please refer to license.txt */ #pragma once #undef interface // For some reason, the Win32 API defined 'interface' as 'struct'... *sigh* #include <string> #include <map> #include <CEGUI/CEGUI.h> #include <CEGUI/RendererModules/OpenGL/GLRenderer.h> #include <SFML/Graphics.hpp> namespace GEngine { namespace mgfx { namespace d2d { class D2D; class Sprite; } //namespace d2d class Window; } //namespace mgfx namespace mmisc { namespace mtime { class Timer; } //namespace mtime } //namespace mmisc namespace mui { //These define the standard values for the corresponding variables in the Interface class. #define CEGUI_CONFIGFILE_PATH "data/interface/cegui/cegui_config.xml" #define CEGUI_LOGFILE_PATH "log/cegui.log" #define CEGUI_FONTS_PATH "data/interface/cegui/fonts/" #define CEGUI_IMAGESETS_PATH "data/interface/cegui/imagesets/" #define CEGUI_LAYOUTS_PATH "data/interface/cegui/layouts/" #define CEGUI_LOOKNFEELS_PATH "data/interface/cegui/looknfeels/" #define CEGUI_LUASCRIPTS_PATH "data/interface/cegui/luascripts/" #define CEGUI_SCHEMES_PATH "data/interface/cegui/schemes/" class Interface { private: CEGUI::System* cegui_system; //CEGUI filepath stuff. //Default values are the corresponding #define at the beginning of this file. std::string cegui_configfile_path; std::string cegui_logfile_path; std::string cegui_schemes_path; std::string cegui_imagesets_path; std::string cegui_fonts_path; std::string cegui_layouts_path; std::string cegui_looknfeels_path; std::string cegui_luascripts_path; CEGUI::DefaultResourceProvider* cegui_resourceprovider; //The cegui resource provider. //CEGUI::WindowManager* cegui_windowmanager; //The cegui window manager. //Nah, just use: CEGUI::WindowManager::getSingleton() std::vector<std::string> loaded_schemes; //The loaded cegui schemes. I don't think this has much actual use, but we'll see. /* * Maps all SFML mouse stuff to CEGUI stuff (stores result in sfml_cegui_mousemap) for use in injecting events to CEGUI. * Intended for use only in Interface::initialize(); */ void mapSFMLMouseToCEGUI(); class impl; mmisc::mtime::Timer& timer; //Used for finding out how much time is elapsed each frame. public: std::vector<mgfx::d2d::D2D* > windows; //Not responsible for freeing these D2Ds. //TODO: Make a function to add and remove from this vector. //TODO: Make a function for getDefaultD2D() which simply returns windows[0]. sf::Font font; //TODO: Make these map stuff private again after all the interface code is consolidated into here as opposed to into the game. //sfml_cegui_keymap just holds the keymappings generated by mapSFMLKeysToCEGUI(). std::map<sf::Keyboard::Key, CEGUI::Key::Scan> sfml_cegui_keymap; /* * Maps all SFML keys to CEGUI keys (stores result in sfml_cegui_keymap) for use in injecting events to CEGUI. * Intended for use only in Interface::initialize(); */ void mapSFMLKeysToCEGUI(); //sfml_cegui_mousemap just holds the keymappings generated by mapSFMLKeysToCEGUI(). std::map<sf::Mouse::Button, CEGUI::MouseButton> sfml_cegui_mousemap; Interface(mmisc::mtime::Timer& _timer); //Interface(); ~Interface(); /* * Initializes the interface & CEGUI. * Uses the D2D provided as the main D2D. //TODO: Allow for no starting off D2D. * Parameters: * &_d2d : reference to the 2d manager that this GUI belongs to. * cegui_shemes : vector containing the NAMES of all the cegui scheme files we're using. Example: "TaharezLook", note: NOT "TaharezLook.scheme". Do NOT include the file extension, only the actual name of the theme. * gui_layout : Name of the xml file that defines the program's GUI layout. Include file extension, in contrast to cegui_schemes. Leave blank ("") if you want to specify your GUI in the code rather than in an xml file. */ bool initialize(mgfx::d2d::D2D &d2d, std::vector<std::string> cegui_schemes); /* More of a draw update, since all it does (currently) is render all of cegui's stuffs. */ void update(); //Loads a font. bool loadFont(std::string filepath); /* * Hides the mouse (regardless of whether the current active mouse belongs to CEGUI or SFML). */ void hideMouse(); //TODO: Implement. /* * Switches between the SFML mouse and the CEGUI mouse. */ void switchMouse(); //TODO: Implement. CEGUI::Window* getRootWindow(mgfx::d2d::D2D &d2d); //Returns a pointer to the root window of the specified D2D. /* * Sets the root window. * First parameter is the CEGUI window to set the root window to, second is the d2d to set the root window of. * Caller is responsible for freeing the previous root window. */ void setRootWindow(CEGUI::Window *window, mgfx::d2d::D2D &d2d); CEGUI::Window* createVirtualWindowFromLayout(std::string layout/*, bool root = false*/); //TODO: Reimplement the bool root functionality via providing a pointer to the D2D to set the the root of. void addD2D(mgfx::d2d::D2D &d2d); }; } //namespace mui } //namespace GEngine <commit_msg>Added a comment.<commit_after>/* Please refer to license.txt */ #pragma once #undef interface // For some reason, the Win32 API defined 'interface' as 'struct'... *sigh* #include <string> #include <map> #include <CEGUI/CEGUI.h> #include <CEGUI/RendererModules/OpenGL/GLRenderer.h> #include <SFML/Graphics.hpp> namespace GEngine { namespace mgfx { namespace d2d { class D2D; class Sprite; } //namespace d2d class Window; } //namespace mgfx namespace mmisc { namespace mtime { class Timer; } //namespace mtime } //namespace mmisc namespace mui { //These define the standard values for the corresponding variables in the Interface class. #define CEGUI_CONFIGFILE_PATH "data/interface/cegui/cegui_config.xml" #define CEGUI_LOGFILE_PATH "log/cegui.log" #define CEGUI_FONTS_PATH "data/interface/cegui/fonts/" #define CEGUI_IMAGESETS_PATH "data/interface/cegui/imagesets/" #define CEGUI_LAYOUTS_PATH "data/interface/cegui/layouts/" #define CEGUI_LOOKNFEELS_PATH "data/interface/cegui/looknfeels/" #define CEGUI_LUASCRIPTS_PATH "data/interface/cegui/luascripts/" #define CEGUI_SCHEMES_PATH "data/interface/cegui/schemes/" class Interface { private: CEGUI::System* cegui_system; //CEGUI filepath stuff. //Default values are the corresponding #define at the beginning of this file. std::string cegui_configfile_path; std::string cegui_logfile_path; std::string cegui_schemes_path; std::string cegui_imagesets_path; std::string cegui_fonts_path; std::string cegui_layouts_path; std::string cegui_looknfeels_path; std::string cegui_luascripts_path; CEGUI::DefaultResourceProvider* cegui_resourceprovider; //The cegui resource provider. //CEGUI::WindowManager* cegui_windowmanager; //The cegui window manager. //Nah, just use: CEGUI::WindowManager::getSingleton() std::vector<std::string> loaded_schemes; //The loaded cegui schemes. I don't think this has much actual use, but we'll see. /* * Maps all SFML mouse stuff to CEGUI stuff (stores result in sfml_cegui_mousemap) for use in injecting events to CEGUI. * Intended for use only in Interface::initialize(); */ void mapSFMLMouseToCEGUI(); class impl; mmisc::mtime::Timer& timer; //Used for finding out how much time is elapsed each frame. public: std::vector<mgfx::d2d::D2D* > windows; //Not responsible for freeing these D2Ds. //TODO: Make a function to add and remove from this vector. //TODO: Make a function for getDefaultD2D() which simply returns windows[0]. sf::Font font; //TODO: Make these map stuff private again after all the interface code is consolidated into here as opposed to into the game. //sfml_cegui_keymap just holds the keymappings generated by mapSFMLKeysToCEGUI(). std::map<sf::Keyboard::Key, CEGUI::Key::Scan> sfml_cegui_keymap; /* * Maps all SFML keys to CEGUI keys (stores result in sfml_cegui_keymap) for use in injecting events to CEGUI. * Intended for use only in Interface::initialize(); */ void mapSFMLKeysToCEGUI(); //sfml_cegui_mousemap just holds the keymappings generated by mapSFMLKeysToCEGUI(). std::map<sf::Mouse::Button, CEGUI::MouseButton> sfml_cegui_mousemap; Interface(mmisc::mtime::Timer& _timer); //TODO: Don't do this, it's ugly. I dun wanna do Interface interface(*(new mmisc::mtime::Timer)); to satisfy this constructor's arguments. Maybe if I set this as an overloaded ctor... //Interface(); ~Interface(); /* * Initializes the interface & CEGUI. * Uses the D2D provided as the main D2D. //TODO: Allow for no starting off D2D. * Parameters: * &_d2d : reference to the 2d manager that this GUI belongs to. * cegui_shemes : vector containing the NAMES of all the cegui scheme files we're using. Example: "TaharezLook", note: NOT "TaharezLook.scheme". Do NOT include the file extension, only the actual name of the theme. * gui_layout : Name of the xml file that defines the program's GUI layout. Include file extension, in contrast to cegui_schemes. Leave blank ("") if you want to specify your GUI in the code rather than in an xml file. */ bool initialize(mgfx::d2d::D2D &d2d, std::vector<std::string> cegui_schemes); /* More of a draw update, since all it does (currently) is render all of cegui's stuffs. */ void update(); //Loads a font. bool loadFont(std::string filepath); /* * Hides the mouse (regardless of whether the current active mouse belongs to CEGUI or SFML). */ void hideMouse(); //TODO: Implement. /* * Switches between the SFML mouse and the CEGUI mouse. */ void switchMouse(); //TODO: Implement. CEGUI::Window* getRootWindow(mgfx::d2d::D2D &d2d); //Returns a pointer to the root window of the specified D2D. /* * Sets the root window. * First parameter is the CEGUI window to set the root window to, second is the d2d to set the root window of. * Caller is responsible for freeing the previous root window. */ void setRootWindow(CEGUI::Window *window, mgfx::d2d::D2D &d2d); CEGUI::Window* createVirtualWindowFromLayout(std::string layout/*, bool root = false*/); //TODO: Reimplement the bool root functionality via providing a pointer to the D2D to set the the root of. void addD2D(mgfx::d2d::D2D &d2d); }; } //namespace mui } //namespace GEngine <|endoftext|>
<commit_before>// // This file is part of the Marble Desktop Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2007 Andrew Manson <g.real.ate@gmail.com> // #include "GpsTracking.h" #include "TrackPoint.h" #include "Track.h" #include "TrackSegment.h" #include "GmlSax.h" #include "GpxFile.h" #include "AbstractLayer/AbstractLayer.h" #include <QtXml/QXmlInputSource> #include <QtXml/QXmlSimpleReader> #include <QDebug> GpsTracking::GpsTracking( GpxFile *currentGpx, TrackingMethod method, QObject *parent ) :QObject( parent ) { m_trackingMethod = method; m_gpsCurrentPosition = new TrackPoint( 0,0 ); m_gpsPreviousPosition = new TrackPoint( 0,0 ); m_gpsTracking = new TrackPoint( 0,0 ); m_gpsTrack = new Track(); currentGpx->addTrack( m_gpsTrack ); m_gpsTrackSeg = 0; m_updateDelay =0; //for ip address evaluation connect( &host, SIGNAL( done( bool ) ), this, SLOT( getData( bool ) ) ) ; m_downloadFinished = false; #ifdef HAVE_LIBGPS m_gpsd = new gpsmm(); m_gpsdData = m_gpsd->open( "127.0.0.1", "2947" ); #endif } GpsTracking::~GpsTracking() { delete m_gpsCurrentPosition; delete m_gpsPreviousPosition; delete m_gpsTracking; #ifdef HAVE_LIBGPS delete m_gpsd; #endif } void GpsTracking::construct( const QSize &canvasSize, ViewParams *viewParams ) { double const radius = viewParams->m_radius; #ifdef HAVE_LIBGPS if( !m_gpsd ) { m_currentDraw.clear(); return; } #endif QPointF position; QPointF previousPosition; bool draw = false; draw = m_gpsCurrentPosition -> getPixelPos( canvasSize, viewParams, &position ); draw = m_gpsPreviousPosition -> getPixelPos( canvasSize, viewParams, &previousPosition ); if ( !draw ) { m_currentDraw.clear(); return; } double distance = sqrt( AbstractLayer::distance( position, previousPosition) ); if (distance == 0) { return; } QPointF unitVector = ( position - previousPosition ) / distance; // The normal of the unit vector between first and second QPointF unitVector2 = QPointF ( -unitVector.y(), unitVector.x()); m_previousDraw = m_currentDraw; m_currentDraw.clear(); m_currentDraw << position << ( position - ( unitVector * 9 ) + ( unitVector2 * 9 ) ) << ( position + ( unitVector * 19.0 ) ) << ( position - ( unitVector * 9 ) - ( unitVector2 * 9 ) ); } QRegion GpsTracking::genRegion( const QSize &canvasSize, ViewParams *viewParams ) { construct( canvasSize, viewParams ); QRect temp1(m_currentDraw.boundingRect().toRect()); QRect temp2(m_previousDraw.boundingRect().toRect()); temp1.adjust( -5, -5, 10, 10); temp2.adjust( -5, -5, 10, 10); return QRegion(temp1).united( QRegion(temp2) ); } void GpsTracking::getData( bool error ) { if ( !error ) { m_data = QString( host.readAll() ); updateIp(); m_downloadFinished = true; } } void GpsTracking::updateIp( ) { // QTextStream out(&gmlFile); // gmlFile.write( host.readAll() ); // out << host.readAll(); // qDebug() << gmlFile.readAll(); // qDebug() << host.readAll(); // double lon; double lat; QXmlInputSource gmlInput/*( &gmlFile )*/; gmlInput.setData( m_data ); QXmlSimpleReader gmlReader; GmlSax gmlSaxHandler( &lon, &lat ); gmlReader.setContentHandler( &gmlSaxHandler ); gmlReader.setErrorHandler( &gmlSaxHandler ); gmlReader.parse( &gmlInput ); qDebug() << "in the real world" << lon << lat; m_gpsCurrentPosition->setPosition( lat, lon ); } bool GpsTracking::update(const QSize &canvasSize, ViewParams *viewParams, QRegion &reg) { switch ( m_trackingMethod ) { case MobilePhone: qDebug("GpsTracking::update - MobilePhone case not handled in %s, line %d", __FILE__, __LINE__); exit(1); //force fail break; case IP: if ( m_updateDelay > 0 ) { --m_updateDelay; //removed need for returning empty regions //return QRegion(); return false; } host.setHost( "api.hostip.info" ); host.get( "http://api.hostip.info/"); m_updateDelay = 15000; //removed empty return //return QRegion(); return false; break; case Gps: #ifndef HAVE_LIBGPS Q_UNUSED( canvasSize ); #else //m_gpsdData has been successully set if ( m_gpsdData != 0 ){ m_gpsdData =m_gpsd->query( "p" ); m_gpsTracking ->setPosition( m_gpsdData->fix.latitude, m_gpsdData->fix.longitude ); if (m_gpsTrackSeg == 0 ){ m_gpsTrackSeg = new TrackSegment(); m_gpsTrack->append( m_gpsTrackSeg ); } if (!( m_gpsPreviousPosition->position() == m_gpsTracking->position() ) ) { m_gpsTrackSeg->append( m_gpsPreviousPosition ); m_gpsPreviousPosition = m_gpsCurrentPosition; m_gpsCurrentPosition = new TrackPoint( *m_gpsTracking); reg = genRegion( canvasSize, viewParams ); return true; } else { return false; } } else { if ( m_gpsTrackSeg != 0 && (m_gpsTrackSeg->count() > 0 ) ) { m_gpsTrackSeg = 0; } } /* construct( canvasSize, radius, invRotAxis ); QRect temp1(m_currentDraw.boundingRect().toRect()); QRect temp2(m_previousDraw.boundingRect().toRect()); temp1.adjust( -5, -5, 10, 10); temp2.adjust( -5, -5, 10, 10); return QRegion(temp1).united( QRegion(temp2) ); */ #endif } } void GpsTracking::draw( ClipPainter *painter, const QSize &canvasSize, ViewParams *viewParams ) { QPoint temp; switch( m_trackingMethod ){ case IP: if( m_gpsCurrentPosition->getPixelPos( canvasSize, viewParams, &temp ) ) { painter->drawEllipse( temp.x(), temp.y(), 10, 10 ); } break; case Gps: painter->setPen( Qt::black ); painter->setBrush( Qt::white ); painter->drawPolygon( m_currentDraw, Qt::OddEvenFill ); break; case MobilePhone: break; } } #include "GpsTracking.moc" <commit_msg>return *something*. not sure if the return value makes sense, but at least it is more consistent than uninitialized<commit_after>// // This file is part of the Marble Desktop Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2007 Andrew Manson <g.real.ate@gmail.com> // #include "GpsTracking.h" #include "TrackPoint.h" #include "Track.h" #include "TrackSegment.h" #include "GmlSax.h" #include "GpxFile.h" #include "AbstractLayer/AbstractLayer.h" #include <QtXml/QXmlInputSource> #include <QtXml/QXmlSimpleReader> #include <QDebug> GpsTracking::GpsTracking( GpxFile *currentGpx, TrackingMethod method, QObject *parent ) :QObject( parent ) { m_trackingMethod = method; m_gpsCurrentPosition = new TrackPoint( 0,0 ); m_gpsPreviousPosition = new TrackPoint( 0,0 ); m_gpsTracking = new TrackPoint( 0,0 ); m_gpsTrack = new Track(); currentGpx->addTrack( m_gpsTrack ); m_gpsTrackSeg = 0; m_updateDelay =0; //for ip address evaluation connect( &host, SIGNAL( done( bool ) ), this, SLOT( getData( bool ) ) ) ; m_downloadFinished = false; #ifdef HAVE_LIBGPS m_gpsd = new gpsmm(); m_gpsdData = m_gpsd->open( "127.0.0.1", "2947" ); #endif } GpsTracking::~GpsTracking() { delete m_gpsCurrentPosition; delete m_gpsPreviousPosition; delete m_gpsTracking; #ifdef HAVE_LIBGPS delete m_gpsd; #endif } void GpsTracking::construct( const QSize &canvasSize, ViewParams *viewParams ) { double const radius = viewParams->m_radius; #ifdef HAVE_LIBGPS if( !m_gpsd ) { m_currentDraw.clear(); return; } #endif QPointF position; QPointF previousPosition; bool draw = false; draw = m_gpsCurrentPosition -> getPixelPos( canvasSize, viewParams, &position ); draw = m_gpsPreviousPosition -> getPixelPos( canvasSize, viewParams, &previousPosition ); if ( !draw ) { m_currentDraw.clear(); return; } double distance = sqrt( AbstractLayer::distance( position, previousPosition) ); if (distance == 0) { return; } QPointF unitVector = ( position - previousPosition ) / distance; // The normal of the unit vector between first and second QPointF unitVector2 = QPointF ( -unitVector.y(), unitVector.x()); m_previousDraw = m_currentDraw; m_currentDraw.clear(); m_currentDraw << position << ( position - ( unitVector * 9 ) + ( unitVector2 * 9 ) ) << ( position + ( unitVector * 19.0 ) ) << ( position - ( unitVector * 9 ) - ( unitVector2 * 9 ) ); } QRegion GpsTracking::genRegion( const QSize &canvasSize, ViewParams *viewParams ) { construct( canvasSize, viewParams ); QRect temp1(m_currentDraw.boundingRect().toRect()); QRect temp2(m_previousDraw.boundingRect().toRect()); temp1.adjust( -5, -5, 10, 10); temp2.adjust( -5, -5, 10, 10); return QRegion(temp1).united( QRegion(temp2) ); } void GpsTracking::getData( bool error ) { if ( !error ) { m_data = QString( host.readAll() ); updateIp(); m_downloadFinished = true; } } void GpsTracking::updateIp( ) { // QTextStream out(&gmlFile); // gmlFile.write( host.readAll() ); // out << host.readAll(); // qDebug() << gmlFile.readAll(); // qDebug() << host.readAll(); // double lon; double lat; QXmlInputSource gmlInput/*( &gmlFile )*/; gmlInput.setData( m_data ); QXmlSimpleReader gmlReader; GmlSax gmlSaxHandler( &lon, &lat ); gmlReader.setContentHandler( &gmlSaxHandler ); gmlReader.setErrorHandler( &gmlSaxHandler ); gmlReader.parse( &gmlInput ); qDebug() << "in the real world" << lon << lat; m_gpsCurrentPosition->setPosition( lat, lon ); } bool GpsTracking::update(const QSize &canvasSize, ViewParams *viewParams, QRegion &reg) { switch ( m_trackingMethod ) { case MobilePhone: qDebug("GpsTracking::update - MobilePhone case not handled in %s, line %d", __FILE__, __LINE__); exit(1); //force fail break; case IP: if ( m_updateDelay > 0 ) { --m_updateDelay; //removed need for returning empty regions //return QRegion(); return false; } host.setHost( "api.hostip.info" ); host.get( "http://api.hostip.info/"); m_updateDelay = 15000; //removed empty return //return QRegion(); return false; break; case Gps: #ifndef HAVE_LIBGPS Q_UNUSED( canvasSize ); #else //m_gpsdData has been successully set if ( m_gpsdData != 0 ){ m_gpsdData =m_gpsd->query( "p" ); m_gpsTracking ->setPosition( m_gpsdData->fix.latitude, m_gpsdData->fix.longitude ); if (m_gpsTrackSeg == 0 ){ m_gpsTrackSeg = new TrackSegment(); m_gpsTrack->append( m_gpsTrackSeg ); } if (!( m_gpsPreviousPosition->position() == m_gpsTracking->position() ) ) { m_gpsTrackSeg->append( m_gpsPreviousPosition ); m_gpsPreviousPosition = m_gpsCurrentPosition; m_gpsCurrentPosition = new TrackPoint( *m_gpsTracking); reg = genRegion( canvasSize, viewParams ); return true; } else { return false; } } else { if ( m_gpsTrackSeg != 0 && (m_gpsTrackSeg->count() > 0 ) ) { m_gpsTrackSeg = 0; } } /* construct( canvasSize, radius, invRotAxis ); QRect temp1(m_currentDraw.boundingRect().toRect()); QRect temp2(m_previousDraw.boundingRect().toRect()); temp1.adjust( -5, -5, 10, 10); temp2.adjust( -5, -5, 10, 10); return QRegion(temp1).united( QRegion(temp2) ); */ #endif } return false; } void GpsTracking::draw( ClipPainter *painter, const QSize &canvasSize, ViewParams *viewParams ) { QPoint temp; switch( m_trackingMethod ){ case IP: if( m_gpsCurrentPosition->getPixelPos( canvasSize, viewParams, &temp ) ) { painter->drawEllipse( temp.x(), temp.y(), 10, 10 ); } break; case Gps: painter->setPen( Qt::black ); painter->setBrush( Qt::white ); painter->drawPolygon( m_currentDraw, Qt::OddEvenFill ); break; case MobilePhone: break; } } #include "GpsTracking.moc" <|endoftext|>
<commit_before>#include <stack> #include <memory> #include <iostream> #include <tinyxml2.h> #include "scene.h" #include "film/color.h" #include "loaders/load_scene.h" #include "volume/volume.h" #include "volume/homogeneous_volume.h" #include "volume/geometry_volume.h" #include "volume/exponential_volume.h" #include "volume/grid_volume.h" #include "volume/volume_node.h" Volume* load_volume(tinyxml2::XMLElement *elem, VolumeCache &cache, const std::string &scene_file){ if (!elem->Attribute("name")){ std::cout << "Scene error: Volumes require a name" << std::endl; return nullptr; } if (!elem->Attribute("type")){ std::cout << "Scene error: Volumes require a type" << std::endl; return nullptr; } std::string name = elem->Attribute("name"); std::string type = elem->Attribute("type"); Volume *vol = cache.get(name); if (vol){ return vol; } Colorf sig_a{1}, sig_s{1}, emit{1}; float phase_asym; read_color(elem->FirstChildElement("absorption"), sig_a); read_color(elem->FirstChildElement("scattering"), sig_s); read_color(elem->FirstChildElement("emission"), emit); read_float(elem->FirstChildElement("phase_asymmetry"), phase_asym); if (type == "homogeneous"){ Point min, max; read_point(elem->FirstChildElement("min"), min); read_point(elem->FirstChildElement("max"), max); return cache.add(name, std::make_unique<HomogeneousVolume>(sig_a, sig_s, emit, phase_asym, BBox{min, max})); } if (type == "exponential"){ float a = 0, b = 0; Vector up; Point min, max; read_float(elem->FirstChildElement("a"), a); read_float(elem->FirstChildElement("b"), b); read_vector(elem->FirstChildElement("up"), up); read_point(elem->FirstChildElement("min"), min); read_point(elem->FirstChildElement("max"), max); return cache.add(name, std::make_unique<ExponentialVolume>(sig_a, sig_s, emit, phase_asym, BBox{min, max}, a, b, up)); } if (type == "vol"){ std::string file = scene_file.substr(0, scene_file.rfind(PATH_SEP) + 1) + elem->Attribute("file"); float density_scale = 1; read_float(elem->FirstChildElement("density_scale"), density_scale); return cache.add(name, std::make_unique<GridVolume>(sig_a, sig_s, emit, phase_asym, file, density_scale)); } std::cout << "Scene error: Unrecognized volume type " << type << std::endl; return nullptr; } void load_volume_node(tinyxml2::XMLElement *elem, Scene &scene, std::stack<Transform> &transform_stack, const std::string &file){ if (!elem->Attribute("name")){ std::cout << "Scene error: Volume nodes require a name" << std::endl; std::exit(1); } std::string name = elem->Attribute("name"); Transform t; read_transform(elem, t); t = transform_stack.top() * t; Volume *vol = load_volume(elem->FirstChildElement("volume"), scene.get_volume_cache(), file); if (!vol){ std::cout << "Scene error: could not load volume attached to volume node " << name << std::endl; std::exit(1); } if (scene.get_volume_root() == nullptr){ scene.set_volume_root(std::make_unique<VolumeNode>(vol, t, name)); } else { auto &children = scene.get_volume_root()->get_children(); children.push_back(std::make_unique<VolumeNode>(vol, t, name)); } transform_stack.push(t); } <commit_msg>Use new color loading behavior to default volume attribts to 0<commit_after>#include <stack> #include <memory> #include <iostream> #include <tinyxml2.h> #include "scene.h" #include "film/color.h" #include "loaders/load_scene.h" #include "volume/volume.h" #include "volume/homogeneous_volume.h" #include "volume/geometry_volume.h" #include "volume/exponential_volume.h" #include "volume/grid_volume.h" #include "volume/volume_node.h" Volume* load_volume(tinyxml2::XMLElement *elem, VolumeCache &cache, const std::string &scene_file){ if (!elem->Attribute("name")){ std::cout << "Scene error: Volumes require a name" << std::endl; return nullptr; } if (!elem->Attribute("type")){ std::cout << "Scene error: Volumes require a type" << std::endl; return nullptr; } std::string name = elem->Attribute("name"); std::string type = elem->Attribute("type"); Volume *vol = cache.get(name); if (vol){ return vol; } Colorf sig_a, sig_s, emit; float phase_asym; read_color(elem->FirstChildElement("absorption"), sig_a); read_color(elem->FirstChildElement("scattering"), sig_s); read_color(elem->FirstChildElement("emission"), emit); read_float(elem->FirstChildElement("phase_asymmetry"), phase_asym); if (type == "homogeneous"){ Point min, max; read_point(elem->FirstChildElement("min"), min); read_point(elem->FirstChildElement("max"), max); return cache.add(name, std::make_unique<HomogeneousVolume>(sig_a, sig_s, emit, phase_asym, BBox{min, max})); } if (type == "exponential"){ float a = 0, b = 0; Vector up; Point min, max; read_float(elem->FirstChildElement("a"), a); read_float(elem->FirstChildElement("b"), b); read_vector(elem->FirstChildElement("up"), up); read_point(elem->FirstChildElement("min"), min); read_point(elem->FirstChildElement("max"), max); return cache.add(name, std::make_unique<ExponentialVolume>(sig_a, sig_s, emit, phase_asym, BBox{min, max}, a, b, up)); } if (type == "vol"){ std::string file = scene_file.substr(0, scene_file.rfind(PATH_SEP) + 1) + elem->Attribute("file"); float density_scale = 1; read_float(elem->FirstChildElement("density_scale"), density_scale); return cache.add(name, std::make_unique<GridVolume>(sig_a, sig_s, emit, phase_asym, file, density_scale)); } std::cout << "Scene error: Unrecognized volume type " << type << std::endl; return nullptr; } void load_volume_node(tinyxml2::XMLElement *elem, Scene &scene, std::stack<Transform> &transform_stack, const std::string &file){ if (!elem->Attribute("name")){ std::cout << "Scene error: Volume nodes require a name" << std::endl; std::exit(1); } std::string name = elem->Attribute("name"); Transform t; read_transform(elem, t); t = transform_stack.top() * t; Volume *vol = load_volume(elem->FirstChildElement("volume"), scene.get_volume_cache(), file); if (!vol){ std::cout << "Scene error: could not load volume attached to volume node " << name << std::endl; std::exit(1); } if (scene.get_volume_root() == nullptr){ scene.set_volume_root(std::make_unique<VolumeNode>(vol, t, name)); } else { auto &children = scene.get_volume_root()->get_children(); children.push_back(std::make_unique<VolumeNode>(vol, t, name)); } transform_stack.push(t); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: style.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2008-03-12 13:08:24 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SFXSTYLE_HXX #define _SFXSTYLE_HXX #include <com/sun/star/style/XStyle.hpp> #include <com/sun/star/lang/XUnoTunnel.hpp> #include <rtl/ref.hxx> #include <vector> #include <comphelper/weak.hxx> #include <cppuhelper/implbase2.hxx> #ifndef INCLUDED_SVTDLLAPI_H #include "svtools/svtdllapi.h" #endif #ifndef _RSCSFX_HXX #include <rsc/rscsfx.hxx> #endif #ifndef _STRING_HXX //autogen #include <tools/string.hxx> #endif #ifndef _SFXHINT_HXX //autogen #include <svtools/hint.hxx> #endif #ifndef _SFXLSTNER_HXX //autogen #include <svtools/lstner.hxx> #endif #ifndef _SFXBRDCST_HXX //autogen #include <svtools/brdcst.hxx> #endif #ifndef _SFXPOOLITEM_HXX //autogen #include <svtools/poolitem.hxx> #endif #ifndef _SFX_STYLE_HRC #include <svtools/style.hrc> #endif class SfxItemSet; class SfxItemPool; class SfxStyleSheetBasePool; class SvStream; /* Everyone changing instances of SfxStyleSheetBasePool or SfxStyleSheetBase mußt broadcast this using <SfxStyleSheetBasePool::GetBroadcaster()> broadcasten. The class <SfxStyleSheetHint> is used for this, it contains an Action-Id and a pointer to the <SfxStyleSheetBase>. The actions are: #define SFX_STYLESHEET_CREATED // style is created #define SFX_STYLESHEET_MODIFIED // style is modified #define SFX_STYLESHEET_CHANGED // style is replaced #define SFX_STYLESHEET_ERASED // style is deleted The following methods already broadcast themself SfxStyleSheetHint(SFX_STYLESHEET_MODIFIED) from: SfxStyleSheetBase::SetName( const String& rName ) SfxStyleSheetBase::SetParent( const String& rName ) SfxStyleSheetBase::SetFollow( const String& rName ) SfxSimpleHint(SFX_HINT_DYING) from: SfxStyleSheetBasePool::~SfxStyleSheetBasePool() SfxStyleSheetHint( SFX_STYLESHEET_CREATED, *p ) from: SfxStyleSheetBasePool::Make( const String& rName, SfxStyleFamily eFam, USHORT mask, USHORT nPos) SfxStyleSheetHint( SFX_STYLESHEET_CHANGED, *pNew ) from: SfxStyleSheetBasePool::Add( SfxStyleSheetBase& rSheet ) SfxStyleSheetHint( SFX_STYLESHEET_ERASED, *p ) from: SfxStyleSheetBasePool::Erase( SfxStyleSheetBase* p ) SfxStyleSheetBasePool::Clear() */ #define VIRTUAL510 virtual class SVT_DLLPUBLIC SfxStyleSheetBase : public comphelper::OWeakTypeObject { friend class SfxStyleSheetBasePool; protected: SfxStyleSheetBasePool& rPool; // zugehoeriger Pool SfxStyleFamily nFamily; // Familie UniString aName, aParent, aFollow; rtl::OUString maDisplayName; String aHelpFile; // Name der Hilfedatei SfxItemSet* pSet; // ItemSet USHORT nMask; // Flags ULONG nHelpId; // Hilfe-ID BOOL bMySet; // TRUE: Set loeschen im dtor SfxStyleSheetBase(); // do not use! SfxStyleSheetBase( const UniString&, SfxStyleSheetBasePool&, SfxStyleFamily eFam, USHORT mask ); SfxStyleSheetBase( const SfxStyleSheetBase& ); virtual ~SfxStyleSheetBase(); virtual void Load( SvStream&, USHORT ); virtual void Store( SvStream& ); public: TYPEINFO(); // returns the internal name of this style virtual const UniString& GetName() const; // sets the internal name of this style virtual BOOL SetName( const UniString& ); /** returns the display name of this style, it is used at the user interface. If the display name is empty, this method returns the internal name. */ virtual rtl::OUString GetDisplayName() const; // sets the display name of this style virtual void SetDisplayName( const rtl::OUString& ); virtual const UniString& GetParent() const; virtual BOOL SetParent( const UniString& ); virtual const UniString& GetFollow() const; virtual BOOL SetFollow( const UniString& ); virtual BOOL HasFollowSupport() const; // Default TRUE virtual BOOL HasParentSupport() const; // Default TRUE virtual BOOL HasClearParentSupport() const; // Default FALSE virtual BOOL IsUsed() const; // Default TRUE // Default aus dem Itemset; entweder dem uebergebenen // oder aus dem per GetItemSet() zurueckgelieferten Set virtual UniString GetDescription(); virtual UniString GetDescription( SfxMapUnit eMetric ); SfxStyleSheetBasePool& GetPool() { return rPool; } SfxStyleFamily GetFamily() const { return nFamily; } USHORT GetMask() const { return nMask; } void SetMask( USHORT mask) { nMask = mask; } BOOL IsUserDefined() const { return BOOL( ( nMask & SFXSTYLEBIT_USERDEF) != 0 ); } virtual ULONG GetHelpId( String& rFile ); virtual void SetHelpId( const String& r, ULONG nId ); virtual SfxItemSet& GetItemSet(); virtual USHORT GetVersion() const; }; //========================================================================= typedef std::vector< rtl::Reference< SfxStyleSheetBase > > SfxStyles; //========================================================================= class SVT_DLLPUBLIC SfxStyleSheetIterator /* [Beschreibung] Klasse zum Iterieren und Suchen auf einem SfxStyleSheetBasePool. */ { public: SfxStyleSheetIterator(SfxStyleSheetBasePool *pBase, SfxStyleFamily eFam, USHORT n=0xFFFF ); virtual USHORT GetSearchMask() const; virtual SfxStyleFamily GetSearchFamily() const; virtual USHORT Count(); virtual SfxStyleSheetBase *operator[](USHORT nIdx); virtual SfxStyleSheetBase* First(); virtual SfxStyleSheetBase* Next(); virtual SfxStyleSheetBase* Find(const UniString& rStr); virtual ~SfxStyleSheetIterator(); protected: SfxStyleSheetBasePool* pBasePool; SfxStyleFamily nSearchFamily; USHORT nMask; BOOL SearchUsed() const { return bSearchUsed; } private: USHORT GetPos(){return nAktPosition;} SVT_DLLPRIVATE BOOL IsTrivialSearch(); SVT_DLLPRIVATE BOOL DoesStyleMatch(SfxStyleSheetBase *pStyle); void* pImp; SfxStyleSheetBase* pAktStyle; USHORT nAktPosition; BOOL bSearchUsed; friend class SfxStyleSheetBasePool; }; //========================================================================= class SfxStyleSheetBasePool_Impl; class SVT_DLLPUBLIC SfxStyleSheetBasePool: public SfxBroadcaster, public comphelper::OWeakTypeObject { friend class SfxStyleSheetIterator; friend class SfxStyleSheetBase; SfxStyleSheetBasePool_Impl *pImp; private: SVT_DLLPRIVATE BOOL Load1_Impl( SvStream& ); SVT_DLLPRIVATE SfxStyleSheetIterator& GetIterator_Impl(); protected: String aAppName; SfxItemPool& rPool; SfxStyles aStyles; SfxStyleFamily nSearchFamily; USHORT nMask; SfxStyleSheetBase& Add( SfxStyleSheetBase& ); void ChangeParent( const UniString&, const UniString&, BOOL bVirtual = TRUE ); virtual SfxStyleSheetBase* Create( const UniString&, SfxStyleFamily, USHORT ); virtual SfxStyleSheetBase* Create( const SfxStyleSheetBase& ); ~SfxStyleSheetBasePool(); public: SfxStyleSheetBasePool( SfxItemPool& ); SfxStyleSheetBasePool( const SfxStyleSheetBasePool& ); static String GetStreamName(); const String& GetAppName() const { return aAppName; } SfxItemPool& GetPool(); const SfxItemPool& GetPool() const; virtual SfxStyleSheetIterator* CreateIterator(SfxStyleFamily, USHORT nMask); virtual USHORT Count(); virtual SfxStyleSheetBase* operator[](USHORT nIdx); virtual SfxStyleSheetBase& Make(const UniString&, SfxStyleFamily eFam, USHORT nMask = 0xffff , USHORT nPos = 0xffff); virtual void Replace( SfxStyleSheetBase& rSource, SfxStyleSheetBase& rTarget ); virtual void Remove( SfxStyleSheetBase* ); virtual void Insert( SfxStyleSheetBase* ); virtual void Clear(); SfxStyleSheetBasePool& operator=( const SfxStyleSheetBasePool& ); SfxStyleSheetBasePool& operator+=( const SfxStyleSheetBasePool& ); const SfxStyles& GetStyles(); virtual SfxStyleSheetBase* First(); virtual SfxStyleSheetBase* Next(); virtual SfxStyleSheetBase* Find( const UniString&, SfxStyleFamily eFam, USHORT n=0xFFFF ); virtual BOOL SetParent(SfxStyleFamily eFam, const UniString &rStyle, const UniString &rParent); SfxStyleSheetBase* Find(const UniString& rStr) { return Find(rStr, nSearchFamily, nMask); } void SetSearchMask(SfxStyleFamily eFam, USHORT n=0xFFFF ); USHORT GetSearchMask() const; SfxStyleFamily GetSearchFamily() const { return nSearchFamily; } BOOL Load( SvStream& ); BOOL Store( SvStream&, BOOL bUsed = TRUE ); }; //========================================================================= class SVT_DLLPUBLIC SfxStyleSheet: public SfxStyleSheetBase, public SfxListener, public SfxBroadcaster { public: TYPEINFO(); SfxStyleSheet( const UniString&, const SfxStyleSheetBasePool&, SfxStyleFamily, USHORT ); SfxStyleSheet( const SfxStyleSheet& ); virtual void SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType ); virtual BOOL SetParent( const UniString& ); protected: SfxStyleSheet(); // do not use! virtual ~SfxStyleSheet(); }; //========================================================================= class SVT_DLLPUBLIC SfxStyleSheetPool: public SfxStyleSheetBasePool { protected: using SfxStyleSheetBasePool::Create; virtual SfxStyleSheetBase* Create(const UniString&, SfxStyleFamily, USHORT mask); virtual SfxStyleSheetBase* Create(const SfxStyleSheet &); public: SfxStyleSheetPool( SfxItemPool const& ); // virtual BOOL CopyTo(SfxStyleSheetPool &rDest, const String &rSourceName); }; //========================================================================= #define SFX_STYLESHEET_CREATED 1 // neu #define SFX_STYLESHEET_MODIFIED 2 // ver"andert #define SFX_STYLESHEET_CHANGED 3 // gel"oscht und neu (ausgetauscht) #define SFX_STYLESHEET_ERASED 4 // gel"oscht #define SFX_STYLESHEET_INDESTRUCTION 5 // wird gerade entfernt #define SFX_STYLESHEETPOOL_CHANGES 1 // Aenderungen, die den Zustand // des Pools anedern, aber nicht // ueber die STYLESHEET Hints // verschickt werden sollen. //======================================================================== class SVT_DLLPUBLIC SfxStyleSheetPoolHint : public SfxHint { USHORT nHint; public: TYPEINFO(); SfxStyleSheetPoolHint(USHORT nArgHint) : nHint(nArgHint){} USHORT GetHint() const { return nHint; } }; //========================================================================= class SVT_DLLPUBLIC SfxStyleSheetHint: public SfxHint { SfxStyleSheetBase* pStyleSh; USHORT nHint; public: TYPEINFO(); SfxStyleSheetHint( USHORT ); SfxStyleSheetHint( USHORT, SfxStyleSheetBase& ); SfxStyleSheetBase* GetStyleSheet() const { return pStyleSh; } USHORT GetHint() const { return nHint; } }; class SVT_DLLPUBLIC SfxStyleSheetHintExtended: public SfxStyleSheetHint { String aName; public: TYPEINFO(); SfxStyleSheetHintExtended( USHORT, const String& rOld ); SfxStyleSheetHintExtended( USHORT, const String& rOld, SfxStyleSheetBase& ); const String& GetOldName() { return aName; } }; class SVT_DLLPUBLIC SfxUnoStyleSheet : public ::cppu::ImplInheritanceHelper2< SfxStyleSheet, ::com::sun::star::style::XStyle, ::com::sun::star::lang::XUnoTunnel > { public: SfxUnoStyleSheet( const UniString& _rName, const SfxStyleSheetBasePool& _rPool, SfxStyleFamily _eFamily, USHORT _nMaske ); SfxUnoStyleSheet( const SfxStyleSheet& _rSheet ); static SfxUnoStyleSheet* getUnoStyleSheet( const ::com::sun::star::uno::Reference< ::com::sun::star::style::XStyle >& xStyle ); // XUnoTunnel virtual ::sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< ::sal_Int8 >& aIdentifier ) throw (::com::sun::star::uno::RuntimeException); private: SfxUnoStyleSheet(); // not implemented static const ::com::sun::star::uno::Sequence< ::sal_Int8 >& getIdentifier(); }; #endif <commit_msg>INTEGRATION: CWS changefileheader (1.4.20); FILE MERGED 2008/04/01 15:44:35 thb 1.4.20.3: #i85898# Stripping all external header guards 2008/04/01 12:43:15 thb 1.4.20.2: #i85898# Stripping all external header guards 2008/03/31 13:01:08 rt 1.4.20.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: style.hxx,v $ * $Revision: 1.5 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SFXSTYLE_HXX #define _SFXSTYLE_HXX #include <com/sun/star/style/XStyle.hpp> #include <com/sun/star/lang/XUnoTunnel.hpp> #include <rtl/ref.hxx> #include <vector> #include <comphelper/weak.hxx> #include <cppuhelper/implbase2.hxx> #include "svtools/svtdllapi.h" #include <rsc/rscsfx.hxx> #include <tools/string.hxx> #include <svtools/hint.hxx> #include <svtools/lstner.hxx> #include <svtools/brdcst.hxx> #include <svtools/poolitem.hxx> #ifndef _SFX_STYLE_HRC #include <svtools/style.hrc> #endif class SfxItemSet; class SfxItemPool; class SfxStyleSheetBasePool; class SvStream; /* Everyone changing instances of SfxStyleSheetBasePool or SfxStyleSheetBase mußt broadcast this using <SfxStyleSheetBasePool::GetBroadcaster()> broadcasten. The class <SfxStyleSheetHint> is used for this, it contains an Action-Id and a pointer to the <SfxStyleSheetBase>. The actions are: #define SFX_STYLESHEET_CREATED // style is created #define SFX_STYLESHEET_MODIFIED // style is modified #define SFX_STYLESHEET_CHANGED // style is replaced #define SFX_STYLESHEET_ERASED // style is deleted The following methods already broadcast themself SfxStyleSheetHint(SFX_STYLESHEET_MODIFIED) from: SfxStyleSheetBase::SetName( const String& rName ) SfxStyleSheetBase::SetParent( const String& rName ) SfxStyleSheetBase::SetFollow( const String& rName ) SfxSimpleHint(SFX_HINT_DYING) from: SfxStyleSheetBasePool::~SfxStyleSheetBasePool() SfxStyleSheetHint( SFX_STYLESHEET_CREATED, *p ) from: SfxStyleSheetBasePool::Make( const String& rName, SfxStyleFamily eFam, USHORT mask, USHORT nPos) SfxStyleSheetHint( SFX_STYLESHEET_CHANGED, *pNew ) from: SfxStyleSheetBasePool::Add( SfxStyleSheetBase& rSheet ) SfxStyleSheetHint( SFX_STYLESHEET_ERASED, *p ) from: SfxStyleSheetBasePool::Erase( SfxStyleSheetBase* p ) SfxStyleSheetBasePool::Clear() */ #define VIRTUAL510 virtual class SVT_DLLPUBLIC SfxStyleSheetBase : public comphelper::OWeakTypeObject { friend class SfxStyleSheetBasePool; protected: SfxStyleSheetBasePool& rPool; // zugehoeriger Pool SfxStyleFamily nFamily; // Familie UniString aName, aParent, aFollow; rtl::OUString maDisplayName; String aHelpFile; // Name der Hilfedatei SfxItemSet* pSet; // ItemSet USHORT nMask; // Flags ULONG nHelpId; // Hilfe-ID BOOL bMySet; // TRUE: Set loeschen im dtor SfxStyleSheetBase(); // do not use! SfxStyleSheetBase( const UniString&, SfxStyleSheetBasePool&, SfxStyleFamily eFam, USHORT mask ); SfxStyleSheetBase( const SfxStyleSheetBase& ); virtual ~SfxStyleSheetBase(); virtual void Load( SvStream&, USHORT ); virtual void Store( SvStream& ); public: TYPEINFO(); // returns the internal name of this style virtual const UniString& GetName() const; // sets the internal name of this style virtual BOOL SetName( const UniString& ); /** returns the display name of this style, it is used at the user interface. If the display name is empty, this method returns the internal name. */ virtual rtl::OUString GetDisplayName() const; // sets the display name of this style virtual void SetDisplayName( const rtl::OUString& ); virtual const UniString& GetParent() const; virtual BOOL SetParent( const UniString& ); virtual const UniString& GetFollow() const; virtual BOOL SetFollow( const UniString& ); virtual BOOL HasFollowSupport() const; // Default TRUE virtual BOOL HasParentSupport() const; // Default TRUE virtual BOOL HasClearParentSupport() const; // Default FALSE virtual BOOL IsUsed() const; // Default TRUE // Default aus dem Itemset; entweder dem uebergebenen // oder aus dem per GetItemSet() zurueckgelieferten Set virtual UniString GetDescription(); virtual UniString GetDescription( SfxMapUnit eMetric ); SfxStyleSheetBasePool& GetPool() { return rPool; } SfxStyleFamily GetFamily() const { return nFamily; } USHORT GetMask() const { return nMask; } void SetMask( USHORT mask) { nMask = mask; } BOOL IsUserDefined() const { return BOOL( ( nMask & SFXSTYLEBIT_USERDEF) != 0 ); } virtual ULONG GetHelpId( String& rFile ); virtual void SetHelpId( const String& r, ULONG nId ); virtual SfxItemSet& GetItemSet(); virtual USHORT GetVersion() const; }; //========================================================================= typedef std::vector< rtl::Reference< SfxStyleSheetBase > > SfxStyles; //========================================================================= class SVT_DLLPUBLIC SfxStyleSheetIterator /* [Beschreibung] Klasse zum Iterieren und Suchen auf einem SfxStyleSheetBasePool. */ { public: SfxStyleSheetIterator(SfxStyleSheetBasePool *pBase, SfxStyleFamily eFam, USHORT n=0xFFFF ); virtual USHORT GetSearchMask() const; virtual SfxStyleFamily GetSearchFamily() const; virtual USHORT Count(); virtual SfxStyleSheetBase *operator[](USHORT nIdx); virtual SfxStyleSheetBase* First(); virtual SfxStyleSheetBase* Next(); virtual SfxStyleSheetBase* Find(const UniString& rStr); virtual ~SfxStyleSheetIterator(); protected: SfxStyleSheetBasePool* pBasePool; SfxStyleFamily nSearchFamily; USHORT nMask; BOOL SearchUsed() const { return bSearchUsed; } private: USHORT GetPos(){return nAktPosition;} SVT_DLLPRIVATE BOOL IsTrivialSearch(); SVT_DLLPRIVATE BOOL DoesStyleMatch(SfxStyleSheetBase *pStyle); void* pImp; SfxStyleSheetBase* pAktStyle; USHORT nAktPosition; BOOL bSearchUsed; friend class SfxStyleSheetBasePool; }; //========================================================================= class SfxStyleSheetBasePool_Impl; class SVT_DLLPUBLIC SfxStyleSheetBasePool: public SfxBroadcaster, public comphelper::OWeakTypeObject { friend class SfxStyleSheetIterator; friend class SfxStyleSheetBase; SfxStyleSheetBasePool_Impl *pImp; private: SVT_DLLPRIVATE BOOL Load1_Impl( SvStream& ); SVT_DLLPRIVATE SfxStyleSheetIterator& GetIterator_Impl(); protected: String aAppName; SfxItemPool& rPool; SfxStyles aStyles; SfxStyleFamily nSearchFamily; USHORT nMask; SfxStyleSheetBase& Add( SfxStyleSheetBase& ); void ChangeParent( const UniString&, const UniString&, BOOL bVirtual = TRUE ); virtual SfxStyleSheetBase* Create( const UniString&, SfxStyleFamily, USHORT ); virtual SfxStyleSheetBase* Create( const SfxStyleSheetBase& ); ~SfxStyleSheetBasePool(); public: SfxStyleSheetBasePool( SfxItemPool& ); SfxStyleSheetBasePool( const SfxStyleSheetBasePool& ); static String GetStreamName(); const String& GetAppName() const { return aAppName; } SfxItemPool& GetPool(); const SfxItemPool& GetPool() const; virtual SfxStyleSheetIterator* CreateIterator(SfxStyleFamily, USHORT nMask); virtual USHORT Count(); virtual SfxStyleSheetBase* operator[](USHORT nIdx); virtual SfxStyleSheetBase& Make(const UniString&, SfxStyleFamily eFam, USHORT nMask = 0xffff , USHORT nPos = 0xffff); virtual void Replace( SfxStyleSheetBase& rSource, SfxStyleSheetBase& rTarget ); virtual void Remove( SfxStyleSheetBase* ); virtual void Insert( SfxStyleSheetBase* ); virtual void Clear(); SfxStyleSheetBasePool& operator=( const SfxStyleSheetBasePool& ); SfxStyleSheetBasePool& operator+=( const SfxStyleSheetBasePool& ); const SfxStyles& GetStyles(); virtual SfxStyleSheetBase* First(); virtual SfxStyleSheetBase* Next(); virtual SfxStyleSheetBase* Find( const UniString&, SfxStyleFamily eFam, USHORT n=0xFFFF ); virtual BOOL SetParent(SfxStyleFamily eFam, const UniString &rStyle, const UniString &rParent); SfxStyleSheetBase* Find(const UniString& rStr) { return Find(rStr, nSearchFamily, nMask); } void SetSearchMask(SfxStyleFamily eFam, USHORT n=0xFFFF ); USHORT GetSearchMask() const; SfxStyleFamily GetSearchFamily() const { return nSearchFamily; } BOOL Load( SvStream& ); BOOL Store( SvStream&, BOOL bUsed = TRUE ); }; //========================================================================= class SVT_DLLPUBLIC SfxStyleSheet: public SfxStyleSheetBase, public SfxListener, public SfxBroadcaster { public: TYPEINFO(); SfxStyleSheet( const UniString&, const SfxStyleSheetBasePool&, SfxStyleFamily, USHORT ); SfxStyleSheet( const SfxStyleSheet& ); virtual void SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType ); virtual BOOL SetParent( const UniString& ); protected: SfxStyleSheet(); // do not use! virtual ~SfxStyleSheet(); }; //========================================================================= class SVT_DLLPUBLIC SfxStyleSheetPool: public SfxStyleSheetBasePool { protected: using SfxStyleSheetBasePool::Create; virtual SfxStyleSheetBase* Create(const UniString&, SfxStyleFamily, USHORT mask); virtual SfxStyleSheetBase* Create(const SfxStyleSheet &); public: SfxStyleSheetPool( SfxItemPool const& ); // virtual BOOL CopyTo(SfxStyleSheetPool &rDest, const String &rSourceName); }; //========================================================================= #define SFX_STYLESHEET_CREATED 1 // neu #define SFX_STYLESHEET_MODIFIED 2 // ver"andert #define SFX_STYLESHEET_CHANGED 3 // gel"oscht und neu (ausgetauscht) #define SFX_STYLESHEET_ERASED 4 // gel"oscht #define SFX_STYLESHEET_INDESTRUCTION 5 // wird gerade entfernt #define SFX_STYLESHEETPOOL_CHANGES 1 // Aenderungen, die den Zustand // des Pools anedern, aber nicht // ueber die STYLESHEET Hints // verschickt werden sollen. //======================================================================== class SVT_DLLPUBLIC SfxStyleSheetPoolHint : public SfxHint { USHORT nHint; public: TYPEINFO(); SfxStyleSheetPoolHint(USHORT nArgHint) : nHint(nArgHint){} USHORT GetHint() const { return nHint; } }; //========================================================================= class SVT_DLLPUBLIC SfxStyleSheetHint: public SfxHint { SfxStyleSheetBase* pStyleSh; USHORT nHint; public: TYPEINFO(); SfxStyleSheetHint( USHORT ); SfxStyleSheetHint( USHORT, SfxStyleSheetBase& ); SfxStyleSheetBase* GetStyleSheet() const { return pStyleSh; } USHORT GetHint() const { return nHint; } }; class SVT_DLLPUBLIC SfxStyleSheetHintExtended: public SfxStyleSheetHint { String aName; public: TYPEINFO(); SfxStyleSheetHintExtended( USHORT, const String& rOld ); SfxStyleSheetHintExtended( USHORT, const String& rOld, SfxStyleSheetBase& ); const String& GetOldName() { return aName; } }; class SVT_DLLPUBLIC SfxUnoStyleSheet : public ::cppu::ImplInheritanceHelper2< SfxStyleSheet, ::com::sun::star::style::XStyle, ::com::sun::star::lang::XUnoTunnel > { public: SfxUnoStyleSheet( const UniString& _rName, const SfxStyleSheetBasePool& _rPool, SfxStyleFamily _eFamily, USHORT _nMaske ); SfxUnoStyleSheet( const SfxStyleSheet& _rSheet ); static SfxUnoStyleSheet* getUnoStyleSheet( const ::com::sun::star::uno::Reference< ::com::sun::star::style::XStyle >& xStyle ); // XUnoTunnel virtual ::sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< ::sal_Int8 >& aIdentifier ) throw (::com::sun::star::uno::RuntimeException); private: SfxUnoStyleSheet(); // not implemented static const ::com::sun::star::uno::Sequence< ::sal_Int8 >& getIdentifier(); }; #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: extrusioncontrols.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-09-08 17:36:10 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SVX_EXTRUSION_CONTROLS_HXX #define _SVX_EXTRUSION_CONTROLS_HXX #ifndef _VALUESET_HXX //autogen #include <svtools/valueset.hxx> #endif #ifndef _SFXLSTNER_HXX //autogen #include <svtools/lstner.hxx> #endif #ifndef _SFXTBXCTRL_HXX //autogen #include <sfx2/tbxctrl.hxx> #endif #ifndef _SVTREEBOX_HXX #include <svtools/svtreebx.hxx> #endif #ifndef _SV_BUTTON_HXX #include <vcl/button.hxx> #endif #ifndef _SV_DIALOG_HXX #include <vcl/dialog.hxx> #endif #ifndef _SV_FIELD_HXX #include <vcl/field.hxx> #endif #ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_ #include <com/sun/star/frame/XFrame.hpp> #endif #ifndef INCLUDED_SVXDLLAPI_H #include "svx/svxdllapi.h" #endif class SfxBindings; class ToolbarMenu; class SfxStatusForwarder; class SvxTbxButtonColorUpdater_Impl; //======================================================================== namespace svx { class ExtrusionDirectionWindow : public SfxPopupWindow { private: ToolbarMenu* mpMenu; ValueSet* mpDirectionSet; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > mxFrame; SfxStatusForwarder* mpDirectionForewarder; SfxStatusForwarder* mpProjectionForewarder; Image maImgDirection[9]; Image maImgDirectionH[9]; Image maImgPerspective; Image maImgPerspectiveH; Image maImgParallel; Image maImgParallelH; bool mbPopupMode; DECL_LINK( SelectHdl, void * ); void FillValueSet(); void implSetDirection( sal_Int32 nSkew, bool bEnabled = true ); void implSetProjection( sal_Int32 nProjection, bool bEnabled = true ); void implInit(); protected: virtual BOOL Close(); virtual void PopupModeEnd(); /** This function is called when the window gets the focus. It grabs the focus to the line ends value set so that it can be controlled with the keyboard. */ virtual void GetFocus (void); public: ExtrusionDirectionWindow( USHORT nId, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame ); ExtrusionDirectionWindow( USHORT nId, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, Window* pParentWindow ); ~ExtrusionDirectionWindow(); void StartSelection(); virtual SfxPopupWindow* Clone() const; virtual void StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ); virtual void DataChanged( const DataChangedEvent& rDCEvt ); }; //======================================================================== class SVX_DLLPUBLIC ExtrusionDirectionControl : public SfxToolBoxControl { public: SFX_DECL_TOOLBOX_CONTROL(); ExtrusionDirectionControl( USHORT nSlotId, USHORT nId, ToolBox& rTbx ); ~ExtrusionDirectionControl(); virtual void StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ); virtual SfxPopupWindowType GetPopupWindowType() const; virtual SfxPopupWindow* CreatePopupWindow(); }; //======================================================================== class ExtrusionDepthWindow : public SfxPopupWindow { private: ToolbarMenu* mpMenu; Image maImgDepth0; Image maImgDepth1; Image maImgDepth2; Image maImgDepth3; Image maImgDepth4; Image maImgDepthInfinity; Image maImgDepth0h; Image maImgDepth1h; Image maImgDepth2h; Image maImgDepth3h; Image maImgDepth4h; Image maImgDepthInfinityh; SfxStatusForwarder* mpDepthForewarder; SfxStatusForwarder* mpMetricForewarder; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > mxFrame; bool mbPopupMode; FieldUnit meUnit; double mfDepth; bool mbEnabled; bool mbInExecute; DECL_LINK( SelectHdl, void * ); void implFillStrings( FieldUnit eUnit ); void implSetDepth( double fDepth, bool bEnabled ); void implInit(); protected: virtual BOOL Close(); virtual void PopupModeEnd(); /** This function is called when the window gets the focus. It grabs the focus to the line ends value set so that it can be controlled with the keyboard. */ virtual void GetFocus (void); public: ExtrusionDepthWindow( USHORT nId, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame ); ExtrusionDepthWindow( USHORT nId, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, Window* pParentWindow ); ~ExtrusionDepthWindow(); void StartSelection(); virtual SfxPopupWindow* Clone() const; virtual void StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ); virtual void DataChanged( const DataChangedEvent& rDCEvt ); }; //======================================================================== class SVX_DLLPUBLIC ExtrusionDepthControl : public SfxToolBoxControl { public: SFX_DECL_TOOLBOX_CONTROL(); ExtrusionDepthControl( USHORT nSlotId, USHORT nId, ToolBox& rTbx ); ~ExtrusionDepthControl(); virtual void StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ); virtual SfxPopupWindowType GetPopupWindowType() const; virtual SfxPopupWindow* CreatePopupWindow(); }; //======================================================================== class ExtrusionLightingWindow : public SfxPopupWindow { private: ToolbarMenu* mpMenu; ValueSet* mpLightingSet; Image maImgLightingOff[9]; Image maImgLightingOn[9]; Image maImgLightingPreview[9]; Image maImgLightingOffh[9]; Image maImgLightingOnh[9]; Image maImgLightingPreviewh[9]; Image maImgBright; Image maImgNormal; Image maImgDim; Image maImgBrighth; Image maImgNormalh; Image maImgDimh; SfxStatusForwarder* mpLightingDirectionForewarder; SfxStatusForwarder* mpLightingIntensityForewarder; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > mxFrame; bool mbPopupMode; int mnLevel; bool mbLevelEnabled; int mnDirection; bool mbDirectionEnabled; void implSetIntensity( int nLevel, bool bEnabled ); void implSetDirection( int nDirection, bool bEnabled ); void implInit(); DECL_LINK( SelectHdl, void * ); protected: virtual BOOL Close(); virtual void PopupModeEnd(); /** This function is called when the window gets the focus. It grabs the focus to the line ends value set so that it can be controlled with the keyboard. */ virtual void GetFocus (void); public: ExtrusionLightingWindow( USHORT nId, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame ); ExtrusionLightingWindow( USHORT nId, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, Window* pParentWindow ); ~ExtrusionLightingWindow(); void StartSelection(); virtual SfxPopupWindow* Clone() const; virtual void StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ); virtual void DataChanged( const DataChangedEvent& rDCEvt ); }; //======================================================================== class SVX_DLLPUBLIC ExtrusionLightingControl : public SfxToolBoxControl { public: SFX_DECL_TOOLBOX_CONTROL(); ExtrusionLightingControl( USHORT nSlotid, USHORT nId, ToolBox& rTbx ); ~ExtrusionLightingControl(); virtual void StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ); virtual SfxPopupWindowType GetPopupWindowType() const; virtual SfxPopupWindow* CreatePopupWindow(); }; //======================================================================== class ExtrusionSurfaceWindow : public SfxPopupWindow { private: ToolbarMenu* mpMenu; Image maImgSurface1; Image maImgSurface2; Image maImgSurface3; Image maImgSurface4; Image maImgSurface1h; Image maImgSurface2h; Image maImgSurface3h; Image maImgSurface4h; SfxStatusForwarder* mpSurfaceForewarder; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > mxFrame; bool mbPopupMode; DECL_LINK( SelectHdl, void * ); void implSetSurface( int nSurface, bool bEnabled ); void implInit(); protected: virtual BOOL Close(); virtual void PopupModeEnd(); /** This function is called when the window gets the focus. It grabs the focus to the line ends value set so that it can be controlled with the keyboard. */ virtual void GetFocus (void); public: ExtrusionSurfaceWindow( USHORT nId, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame ); ExtrusionSurfaceWindow( USHORT nId, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, Window* pParentWindow ); ~ExtrusionSurfaceWindow(); void StartSelection(); virtual SfxPopupWindow* Clone() const; virtual void StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ); virtual void DataChanged( const DataChangedEvent& rDCEvt ); }; //======================================================================== class SVX_DLLPUBLIC ExtrusionSurfaceControl : public SfxToolBoxControl { public: SFX_DECL_TOOLBOX_CONTROL(); ExtrusionSurfaceControl( USHORT nSlotId, USHORT nId, ToolBox& rTbx ); ~ExtrusionSurfaceControl(); virtual void StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ); virtual SfxPopupWindowType GetPopupWindowType() const; virtual SfxPopupWindow* CreatePopupWindow(); }; //======================================================================== class SVX_DLLPUBLIC ExtrusionColorControl : public SfxToolBoxControl { private: SvxTbxButtonColorUpdater_Impl* mpBtnUpdater; public: SFX_DECL_TOOLBOX_CONTROL(); ExtrusionColorControl( USHORT nSlotId, USHORT nId, ToolBox& rTbx ); ~ExtrusionColorControl(); virtual void StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ); virtual SfxPopupWindowType GetPopupWindowType() const; virtual SfxPopupWindow* CreatePopupWindow(); }; //======================================================================== class ExtrusionDepthDialog : public ModalDialog { FixedText maFLDepth; MetricField maMtrDepth; OKButton maOKButton; CancelButton maCancelButton; HelpButton maHelpButton; FieldUnit meDefaultUnit; public: ExtrusionDepthDialog( Window* pParent, double fDepth, FieldUnit eDefaultUnit ); ~ExtrusionDepthDialog(); double getDepth() const; }; } #endif <commit_msg>INTEGRATION: CWS impress91 (1.6.344); FILE MERGED 2006/04/11 15:14:22 sj 1.6.344.1: #i54588# fixed crash and the problem of displaying depth value divided by 10<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: extrusioncontrols.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: kz $ $Date: 2006-04-26 20:47:16 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SVX_EXTRUSION_CONTROLS_HXX #define _SVX_EXTRUSION_CONTROLS_HXX #ifndef _VALUESET_HXX //autogen #include <svtools/valueset.hxx> #endif #ifndef _SFXLSTNER_HXX //autogen #include <svtools/lstner.hxx> #endif #ifndef _SFXTBXCTRL_HXX //autogen #include <sfx2/tbxctrl.hxx> #endif #ifndef _SVTREEBOX_HXX #include <svtools/svtreebx.hxx> #endif #ifndef _SV_BUTTON_HXX #include <vcl/button.hxx> #endif #ifndef _SV_DIALOG_HXX #include <vcl/dialog.hxx> #endif #ifndef _SV_FIELD_HXX #include <vcl/field.hxx> #endif #ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_ #include <com/sun/star/frame/XFrame.hpp> #endif #ifndef INCLUDED_SVXDLLAPI_H #include "svx/svxdllapi.h" #endif class SfxBindings; class ToolbarMenu; class SfxStatusForwarder; class SvxTbxButtonColorUpdater_Impl; //======================================================================== namespace svx { class ExtrusionDirectionWindow : public SfxPopupWindow { private: ToolbarMenu* mpMenu; ValueSet* mpDirectionSet; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > mxFrame; SfxStatusForwarder* mpDirectionForewarder; SfxStatusForwarder* mpProjectionForewarder; Image maImgDirection[9]; Image maImgDirectionH[9]; Image maImgPerspective; Image maImgPerspectiveH; Image maImgParallel; Image maImgParallelH; bool mbPopupMode; DECL_LINK( SelectHdl, void * ); void FillValueSet(); void implSetDirection( sal_Int32 nSkew, bool bEnabled = true ); void implSetProjection( sal_Int32 nProjection, bool bEnabled = true ); void implInit(); protected: virtual BOOL Close(); virtual void PopupModeEnd(); /** This function is called when the window gets the focus. It grabs the focus to the line ends value set so that it can be controlled with the keyboard. */ virtual void GetFocus (void); public: ExtrusionDirectionWindow( USHORT nId, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame ); ExtrusionDirectionWindow( USHORT nId, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, Window* pParentWindow ); ~ExtrusionDirectionWindow(); void StartSelection(); virtual SfxPopupWindow* Clone() const; virtual void StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ); virtual void DataChanged( const DataChangedEvent& rDCEvt ); }; //======================================================================== class SVX_DLLPUBLIC ExtrusionDirectionControl : public SfxToolBoxControl { public: SFX_DECL_TOOLBOX_CONTROL(); ExtrusionDirectionControl( USHORT nSlotId, USHORT nId, ToolBox& rTbx ); ~ExtrusionDirectionControl(); virtual void StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ); virtual SfxPopupWindowType GetPopupWindowType() const; virtual SfxPopupWindow* CreatePopupWindow(); }; //======================================================================== class ExtrusionDepthWindow : public SfxPopupWindow { private: ToolbarMenu* mpMenu; Image maImgDepth0; Image maImgDepth1; Image maImgDepth2; Image maImgDepth3; Image maImgDepth4; Image maImgDepthInfinity; Image maImgDepth0h; Image maImgDepth1h; Image maImgDepth2h; Image maImgDepth3h; Image maImgDepth4h; Image maImgDepthInfinityh; SfxStatusForwarder* mpDepthForewarder; SfxStatusForwarder* mpMetricForewarder; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > mxFrame; bool mbPopupMode; FieldUnit meUnit; double mfDepth; bool mbEnabled; DECL_LINK( SelectHdl, void * ); void implFillStrings( FieldUnit eUnit ); void implSetDepth( double fDepth, bool bEnabled ); void implInit(); protected: virtual BOOL Close(); virtual void PopupModeEnd(); /** This function is called when the window gets the focus. It grabs the focus to the line ends value set so that it can be controlled with the keyboard. */ virtual void GetFocus (void); public: ExtrusionDepthWindow( USHORT nId, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame ); ExtrusionDepthWindow( USHORT nId, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, Window* pParentWindow ); ~ExtrusionDepthWindow(); void StartSelection(); virtual SfxPopupWindow* Clone() const; virtual void StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ); virtual void DataChanged( const DataChangedEvent& rDCEvt ); }; //======================================================================== class SVX_DLLPUBLIC ExtrusionDepthControl : public SfxToolBoxControl { public: SFX_DECL_TOOLBOX_CONTROL(); ExtrusionDepthControl( USHORT nSlotId, USHORT nId, ToolBox& rTbx ); ~ExtrusionDepthControl(); virtual void StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ); virtual SfxPopupWindowType GetPopupWindowType() const; virtual SfxPopupWindow* CreatePopupWindow(); }; //======================================================================== class ExtrusionLightingWindow : public SfxPopupWindow { private: ToolbarMenu* mpMenu; ValueSet* mpLightingSet; Image maImgLightingOff[9]; Image maImgLightingOn[9]; Image maImgLightingPreview[9]; Image maImgLightingOffh[9]; Image maImgLightingOnh[9]; Image maImgLightingPreviewh[9]; Image maImgBright; Image maImgNormal; Image maImgDim; Image maImgBrighth; Image maImgNormalh; Image maImgDimh; SfxStatusForwarder* mpLightingDirectionForewarder; SfxStatusForwarder* mpLightingIntensityForewarder; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > mxFrame; bool mbPopupMode; int mnLevel; bool mbLevelEnabled; int mnDirection; bool mbDirectionEnabled; void implSetIntensity( int nLevel, bool bEnabled ); void implSetDirection( int nDirection, bool bEnabled ); void implInit(); DECL_LINK( SelectHdl, void * ); protected: virtual BOOL Close(); virtual void PopupModeEnd(); /** This function is called when the window gets the focus. It grabs the focus to the line ends value set so that it can be controlled with the keyboard. */ virtual void GetFocus (void); public: ExtrusionLightingWindow( USHORT nId, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame ); ExtrusionLightingWindow( USHORT nId, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, Window* pParentWindow ); ~ExtrusionLightingWindow(); void StartSelection(); virtual SfxPopupWindow* Clone() const; virtual void StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ); virtual void DataChanged( const DataChangedEvent& rDCEvt ); }; //======================================================================== class SVX_DLLPUBLIC ExtrusionLightingControl : public SfxToolBoxControl { public: SFX_DECL_TOOLBOX_CONTROL(); ExtrusionLightingControl( USHORT nSlotid, USHORT nId, ToolBox& rTbx ); ~ExtrusionLightingControl(); virtual void StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ); virtual SfxPopupWindowType GetPopupWindowType() const; virtual SfxPopupWindow* CreatePopupWindow(); }; //======================================================================== class ExtrusionSurfaceWindow : public SfxPopupWindow { private: ToolbarMenu* mpMenu; Image maImgSurface1; Image maImgSurface2; Image maImgSurface3; Image maImgSurface4; Image maImgSurface1h; Image maImgSurface2h; Image maImgSurface3h; Image maImgSurface4h; SfxStatusForwarder* mpSurfaceForewarder; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > mxFrame; bool mbPopupMode; DECL_LINK( SelectHdl, void * ); void implSetSurface( int nSurface, bool bEnabled ); void implInit(); protected: virtual BOOL Close(); virtual void PopupModeEnd(); /** This function is called when the window gets the focus. It grabs the focus to the line ends value set so that it can be controlled with the keyboard. */ virtual void GetFocus (void); public: ExtrusionSurfaceWindow( USHORT nId, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame ); ExtrusionSurfaceWindow( USHORT nId, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, Window* pParentWindow ); ~ExtrusionSurfaceWindow(); void StartSelection(); virtual SfxPopupWindow* Clone() const; virtual void StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ); virtual void DataChanged( const DataChangedEvent& rDCEvt ); }; //======================================================================== class SVX_DLLPUBLIC ExtrusionSurfaceControl : public SfxToolBoxControl { public: SFX_DECL_TOOLBOX_CONTROL(); ExtrusionSurfaceControl( USHORT nSlotId, USHORT nId, ToolBox& rTbx ); ~ExtrusionSurfaceControl(); virtual void StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ); virtual SfxPopupWindowType GetPopupWindowType() const; virtual SfxPopupWindow* CreatePopupWindow(); }; //======================================================================== class SVX_DLLPUBLIC ExtrusionColorControl : public SfxToolBoxControl { private: SvxTbxButtonColorUpdater_Impl* mpBtnUpdater; public: SFX_DECL_TOOLBOX_CONTROL(); ExtrusionColorControl( USHORT nSlotId, USHORT nId, ToolBox& rTbx ); ~ExtrusionColorControl(); virtual void StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ); virtual SfxPopupWindowType GetPopupWindowType() const; virtual SfxPopupWindow* CreatePopupWindow(); }; //======================================================================== class ExtrusionDepthDialog : public ModalDialog { FixedText maFLDepth; MetricField maMtrDepth; OKButton maOKButton; CancelButton maCancelButton; HelpButton maHelpButton; FieldUnit meDefaultUnit; public: ExtrusionDepthDialog( Window* pParent, double fDepth, FieldUnit eDefaultUnit ); ~ExtrusionDepthDialog(); double getDepth() const; }; } #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: chardlg.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2006-10-12 12:06:51 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SVX_CHARDLG_HXX #define _SVX_CHARDLG_HXX // include --------------------------------------------------------------- #ifndef _CTRLBOX_HXX //autogen #include <svtools/ctrlbox.hxx> #endif #ifndef _STDCTRL_HXX //autogen #include <svtools/stdctrl.hxx> #endif #ifndef _SFXTABDLG_HXX //autogen #include <sfx2/tabdlg.hxx> #endif #ifndef _SVX_FNTCTRL_HXX #include <fntctrl.hxx> #endif #include "checklbx.hxx" #include "langbox.hxx" // forward --------------------------------------------------------------- class SvxFontListItem; class FontList; // ----------------------------------------------------------------------- #define DISABLE_CASEMAP ((USHORT)0x0001) #define DISABLE_WORDLINE ((USHORT)0x0002) #define DISABLE_BLINK ((USHORT)0x0004) #define DISABLE_UNDERLINE_COLOR ((USHORT)0x0008) #define DISABLE_LANGUAGE ((USHORT)0x0010) #define DISABLE_HIDE_LANGUAGE ((USHORT)0x0020) // class SvxCharBasePage ------------------------------------------------- class SvxCharBasePage : public SfxTabPage { protected: SvxFontPrevWindow m_aPreviewWin; FixedInfo m_aFontTypeFT; BOOL m_bPreviewBackgroundToCharacter; SvxCharBasePage( Window* pParent, const ResId& rResIdTabPage, const SfxItemSet&, USHORT nResIdPrewievWin, USHORT nResIdFontTypeFT ); virtual ~SvxCharBasePage(); virtual void ActivatePage( const SfxItemSet& rSet ); void SetPrevFontSize( const SfxItemSet& rSet, USHORT nSlot, SvxFont& rFont ); void SetPrevFont( const SfxItemSet& rSet, USHORT nSlot, SvxFont& rFont ); void SetPrevFontStyle( const SfxItemSet& rSet, USHORT nSlotPosture, USHORT nSlotWeight, SvxFont& rFont ); // posture/weight void SetPrevFontWidthScale( const SfxItemSet& rSet ); void SetPrevFontEscapement( BYTE nProp, BYTE nEscProp, short nEsc ); inline SvxFont& GetPreviewFont(); inline SvxFont& GetPreviewCJKFont(); inline SvxFont& GetPreviewCTLFont(); using TabPage::ActivatePage; using TabPage::DeactivatePage; }; // class SvxCharNamePage ------------------------------------------------- struct SvxCharNamePage_Impl; class SvxCharNamePage : public SvxCharBasePage { private: FixedLine* m_pWestLine; FixedText* m_pWestFontNameFT; FontNameBox* m_pWestFontNameLB; FixedText* m_pWestFontStyleFT; FontStyleBox* m_pWestFontStyleLB; FixedText* m_pWestFontSizeFT; FontSizeBox* m_pWestFontSizeLB; FixedText* m_pWestFontLanguageFT; SvxLanguageBox* m_pWestFontLanguageLB; FixedLine* m_pEastLine; FixedText* m_pEastFontNameFT; FontNameBox* m_pEastFontNameLB; FixedText* m_pEastFontStyleFT; FontStyleBox* m_pEastFontStyleLB; FixedText* m_pEastFontSizeFT; FontSizeBox* m_pEastFontSizeLB; FixedText* m_pEastFontLanguageFT; SvxLanguageBox* m_pEastFontLanguageLB; FixedLine* m_pCTLLine; FixedText* m_pCTLFontNameFT; FontNameBox* m_pCTLFontNameLB; FixedText* m_pCTLFontStyleFT; FontStyleBox* m_pCTLFontStyleLB; FixedText* m_pCTLFontSizeFT; FontSizeBox* m_pCTLFontSizeLB; FixedText* m_pCTLFontLanguageFT; SvxLanguageBox* m_pCTLFontLanguageLB; FixedLine* m_pColorFL; FixedText* m_pColorFT; ColorListBox* m_pColorLB; SvxCharNamePage_Impl* m_pImpl; SvxCharNamePage( Window* pParent, const SfxItemSet& rSet ); void Initialize(); const FontList* GetFontList() const; void UpdatePreview_Impl(); void FillStyleBox_Impl( const FontNameBox* rBox ); void FillSizeBox_Impl( const FontNameBox* rBox ); enum LanguageGroup { /** Language for western text. */ Western = 0, /** Language for asian text. */ Asian, /** Language for ctl text. */ Ctl }; void Reset_Impl( const SfxItemSet& rSet, LanguageGroup eLangGrp ); BOOL FillItemSet_Impl( SfxItemSet& rSet, LanguageGroup eLangGrp ); void ResetColor_Impl( const SfxItemSet& rSet ); BOOL FillItemSetColor_Impl( SfxItemSet& rSet ); DECL_LINK( UpdateHdl_Impl, Timer* ); DECL_LINK( FontModifyHdl_Impl, void* ); DECL_LINK( ColorBoxSelectHdl_Impl, ColorListBox* ); protected: virtual void ActivatePage( const SfxItemSet& rSet ); virtual int DeactivatePage( SfxItemSet* pSet = 0 ); public: ~SvxCharNamePage(); virtual void DeactivatePage(); virtual void ActivatePage(); static SfxTabPage* Create( Window* pParent, const SfxItemSet& rSet ); static USHORT* GetRanges(); virtual void Reset( const SfxItemSet& rSet ); virtual BOOL FillItemSet( SfxItemSet& rSet ); void SetFontList( const SvxFontListItem& rItem ); void EnableRelativeMode(); void EnableSearchMode(); // the writer uses SID_ATTR_BRUSH as font background void SetPreviewBackgroundToCharacter(); void DisableControls( USHORT nDisable ); virtual void PageCreated (SfxAllItemSet aSet); //add CHINA001 }; // class SvxCharEffectsPage ---------------------------------------------- class SvxCharEffectsPage : public SvxCharBasePage { using TabPage::DeactivatePage; private: FixedText m_aUnderlineFT; ListBox m_aUnderlineLB; FixedText m_aColorFT; ColorListBox m_aColorLB; FixedText m_aStrikeoutFT; ListBox m_aStrikeoutLB; CheckBox m_aIndividualWordsBtn; FixedText m_aEmphasisFT; ListBox m_aEmphasisLB; FixedText m_aPositionFT; ListBox m_aPositionLB; FixedText m_aFontColorFT; ColorListBox m_aFontColorLB; FixedText m_aEffectsFT; SvxCheckListBox m_aEffectsLB; ListBox m_aEffects2LB; FixedText m_aReliefFT; ListBox m_aReliefLB; TriStateBox m_aOutlineBtn; TriStateBox m_aShadowBtn; TriStateBox m_aBlinkingBtn; TriStateBox m_aHiddenBtn; USHORT m_nHtmlMode; String m_aTransparentColorName; SvxCharEffectsPage( Window* pParent, const SfxItemSet& rSet ); void Initialize(); void UpdatePreview_Impl(); void SetCaseMap_Impl( SvxCaseMap eCaseMap ); void ResetColor_Impl( const SfxItemSet& rSet ); BOOL FillItemSetColor_Impl( SfxItemSet& rSet ); DECL_LINK( SelectHdl_Impl, ListBox* ); DECL_LINK( CbClickHdl_Impl, CheckBox* ); DECL_LINK( TristClickHdl_Impl, TriStateBox* ); DECL_LINK( UpdatePreview_Impl, ListBox* ); DECL_LINK( ColorBoxSelectHdl_Impl, ColorListBox* ); protected: virtual int DeactivatePage( SfxItemSet* pSet = 0 ); public: static SfxTabPage* Create( Window* pParent, const SfxItemSet& rSet ); static USHORT* GetRanges(); virtual void Reset( const SfxItemSet& rSet ); virtual BOOL FillItemSet( SfxItemSet& rSet ); void DisableControls( USHORT nDisable ); void EnableFlash(); // the writer uses SID_ATTR_BRUSH as font background void SetPreviewBackgroundToCharacter(); virtual void PageCreated (SfxAllItemSet aSet); //add CHINA001 }; // class SvxCharPositionPage --------------------------------------------- class SvxCharPositionPage : public SvxCharBasePage { private: FixedLine m_aPositionLine; RadioButton m_aHighPosBtn; RadioButton m_aNormalPosBtn; RadioButton m_aLowPosBtn; FixedText m_aHighLowFT; MetricField m_aHighLowEdit; CheckBox m_aHighLowRB; FixedText m_aFontSizeFT; MetricField m_aFontSizeEdit; FixedLine m_aRotationScalingFL; FixedLine m_aScalingFL; RadioButton m_a0degRB; RadioButton m_a90degRB; RadioButton m_a270degRB; CheckBox m_aFitToLineCB; FixedText m_aScaleWidthFT; MetricField m_aScaleWidthMF; FixedLine m_aKerningLine; ListBox m_aKerningLB; FixedText m_aKerningFT; MetricField m_aKerningEdit; CheckBox m_aPairKerningBtn; short m_nSuperEsc; short m_nSubEsc; UINT16 m_nScaleWidthItemSetVal; UINT16 m_nScaleWidthInitialVal; BYTE m_nSuperProp; BYTE m_nSubProp; SvxCharPositionPage( Window* pParent, const SfxItemSet& rSet ); void Initialize(); void UpdatePreview_Impl( BYTE nProp, BYTE nEscProp, short nEsc ); void SetEscapement_Impl( USHORT nEsc ); DECL_LINK( PositionHdl_Impl, RadioButton* ); DECL_LINK( RotationHdl_Impl, RadioButton* ); DECL_LINK( FontModifyHdl_Impl, MetricField* ); DECL_LINK( AutoPositionHdl_Impl, CheckBox* ); DECL_LINK( FitToLineHdl_Impl, CheckBox* ); DECL_LINK( KerningSelectHdl_Impl, ListBox* ); DECL_LINK( KerningModifyHdl_Impl, MetricField* ); DECL_LINK( PairKerningHdl_Impl, CheckBox* ); DECL_LINK( LoseFocusHdl_Impl, MetricField* ); DECL_LINK( ScaleWidthModifyHdl_Impl, MetricField* ); protected: virtual int DeactivatePage( SfxItemSet* pSet = 0 ); virtual void ActivatePage( const SfxItemSet& rSet ); public: static SfxTabPage* Create( Window* pParent, const SfxItemSet& rSet ); static USHORT* GetRanges(); virtual void Reset( const SfxItemSet& rSet ); virtual BOOL FillItemSet( SfxItemSet& rSet ); virtual void FillUserData(); // the writer uses SID_ATTR_BRUSH as font background void SetPreviewBackgroundToCharacter(); virtual void PageCreated (SfxAllItemSet aSet); //add CHINA001 virtual void DeactivatePage(); virtual void ActivatePage(); }; // class SvxCharTwoLinesPage --------------------------------------------- class SvxCharTwoLinesPage : public SvxCharBasePage { private: FixedLine m_aSwitchOnLine; CheckBox m_aTwoLinesBtn; FixedLine m_aEncloseLine; FixedText m_aStartBracketFT; ListBox m_aStartBracketLB; FixedText m_aEndBracketFT; ListBox m_aEndBracketLB; SvxCharTwoLinesPage( Window* pParent, const SfxItemSet& rSet ); void UpdatePreview_Impl(); void Initialize(); void SelectCharacter( ListBox* pBox ); void SetBracket( sal_Unicode cBracket, BOOL bStart ); DECL_LINK( TwoLinesHdl_Impl, CheckBox* ); DECL_LINK( CharacterMapHdl_Impl, ListBox* ); protected: virtual void ActivatePage( const SfxItemSet& rSet ); virtual int DeactivatePage( SfxItemSet* pSet = 0 ); public: static SfxTabPage* Create( Window* pParent, const SfxItemSet& rSet ); static USHORT* GetRanges(); virtual void Reset( const SfxItemSet& rSet ); virtual BOOL FillItemSet( SfxItemSet& rSet ); // the writer uses SID_ATTR_BRUSH as font background void SetPreviewBackgroundToCharacter(); virtual void PageCreated (SfxAllItemSet aSet); //add CHINA001 virtual void DeactivatePage(); virtual void ActivatePage(); }; #endif // #ifndef _SVX_CHARDLG_HXX <commit_msg>INTEGRATION: CWS vgbugs07 (1.4.322); FILE MERGED 2007/06/04 13:26:12 vg 1.4.322.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: chardlg.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2007-06-27 16:51:56 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SVX_CHARDLG_HXX #define _SVX_CHARDLG_HXX // include --------------------------------------------------------------- #ifndef _CTRLBOX_HXX //autogen #include <svtools/ctrlbox.hxx> #endif #ifndef _STDCTRL_HXX //autogen #include <svtools/stdctrl.hxx> #endif #ifndef _SFXTABDLG_HXX //autogen #include <sfx2/tabdlg.hxx> #endif #ifndef _SVX_FNTCTRL_HXX #include <svx/fntctrl.hxx> #endif #include <svx/checklbx.hxx> #include <svx/langbox.hxx> // forward --------------------------------------------------------------- class SvxFontListItem; class FontList; // ----------------------------------------------------------------------- #define DISABLE_CASEMAP ((USHORT)0x0001) #define DISABLE_WORDLINE ((USHORT)0x0002) #define DISABLE_BLINK ((USHORT)0x0004) #define DISABLE_UNDERLINE_COLOR ((USHORT)0x0008) #define DISABLE_LANGUAGE ((USHORT)0x0010) #define DISABLE_HIDE_LANGUAGE ((USHORT)0x0020) // class SvxCharBasePage ------------------------------------------------- class SvxCharBasePage : public SfxTabPage { protected: SvxFontPrevWindow m_aPreviewWin; FixedInfo m_aFontTypeFT; BOOL m_bPreviewBackgroundToCharacter; SvxCharBasePage( Window* pParent, const ResId& rResIdTabPage, const SfxItemSet&, USHORT nResIdPrewievWin, USHORT nResIdFontTypeFT ); virtual ~SvxCharBasePage(); virtual void ActivatePage( const SfxItemSet& rSet ); void SetPrevFontSize( const SfxItemSet& rSet, USHORT nSlot, SvxFont& rFont ); void SetPrevFont( const SfxItemSet& rSet, USHORT nSlot, SvxFont& rFont ); void SetPrevFontStyle( const SfxItemSet& rSet, USHORT nSlotPosture, USHORT nSlotWeight, SvxFont& rFont ); // posture/weight void SetPrevFontWidthScale( const SfxItemSet& rSet ); void SetPrevFontEscapement( BYTE nProp, BYTE nEscProp, short nEsc ); inline SvxFont& GetPreviewFont(); inline SvxFont& GetPreviewCJKFont(); inline SvxFont& GetPreviewCTLFont(); using TabPage::ActivatePage; using TabPage::DeactivatePage; }; // class SvxCharNamePage ------------------------------------------------- struct SvxCharNamePage_Impl; class SvxCharNamePage : public SvxCharBasePage { private: FixedLine* m_pWestLine; FixedText* m_pWestFontNameFT; FontNameBox* m_pWestFontNameLB; FixedText* m_pWestFontStyleFT; FontStyleBox* m_pWestFontStyleLB; FixedText* m_pWestFontSizeFT; FontSizeBox* m_pWestFontSizeLB; FixedText* m_pWestFontLanguageFT; SvxLanguageBox* m_pWestFontLanguageLB; FixedLine* m_pEastLine; FixedText* m_pEastFontNameFT; FontNameBox* m_pEastFontNameLB; FixedText* m_pEastFontStyleFT; FontStyleBox* m_pEastFontStyleLB; FixedText* m_pEastFontSizeFT; FontSizeBox* m_pEastFontSizeLB; FixedText* m_pEastFontLanguageFT; SvxLanguageBox* m_pEastFontLanguageLB; FixedLine* m_pCTLLine; FixedText* m_pCTLFontNameFT; FontNameBox* m_pCTLFontNameLB; FixedText* m_pCTLFontStyleFT; FontStyleBox* m_pCTLFontStyleLB; FixedText* m_pCTLFontSizeFT; FontSizeBox* m_pCTLFontSizeLB; FixedText* m_pCTLFontLanguageFT; SvxLanguageBox* m_pCTLFontLanguageLB; FixedLine* m_pColorFL; FixedText* m_pColorFT; ColorListBox* m_pColorLB; SvxCharNamePage_Impl* m_pImpl; SvxCharNamePage( Window* pParent, const SfxItemSet& rSet ); void Initialize(); const FontList* GetFontList() const; void UpdatePreview_Impl(); void FillStyleBox_Impl( const FontNameBox* rBox ); void FillSizeBox_Impl( const FontNameBox* rBox ); enum LanguageGroup { /** Language for western text. */ Western = 0, /** Language for asian text. */ Asian, /** Language for ctl text. */ Ctl }; void Reset_Impl( const SfxItemSet& rSet, LanguageGroup eLangGrp ); BOOL FillItemSet_Impl( SfxItemSet& rSet, LanguageGroup eLangGrp ); void ResetColor_Impl( const SfxItemSet& rSet ); BOOL FillItemSetColor_Impl( SfxItemSet& rSet ); DECL_LINK( UpdateHdl_Impl, Timer* ); DECL_LINK( FontModifyHdl_Impl, void* ); DECL_LINK( ColorBoxSelectHdl_Impl, ColorListBox* ); protected: virtual void ActivatePage( const SfxItemSet& rSet ); virtual int DeactivatePage( SfxItemSet* pSet = 0 ); public: ~SvxCharNamePage(); virtual void DeactivatePage(); virtual void ActivatePage(); static SfxTabPage* Create( Window* pParent, const SfxItemSet& rSet ); static USHORT* GetRanges(); virtual void Reset( const SfxItemSet& rSet ); virtual BOOL FillItemSet( SfxItemSet& rSet ); void SetFontList( const SvxFontListItem& rItem ); void EnableRelativeMode(); void EnableSearchMode(); // the writer uses SID_ATTR_BRUSH as font background void SetPreviewBackgroundToCharacter(); void DisableControls( USHORT nDisable ); virtual void PageCreated (SfxAllItemSet aSet); //add CHINA001 }; // class SvxCharEffectsPage ---------------------------------------------- class SvxCharEffectsPage : public SvxCharBasePage { using TabPage::DeactivatePage; private: FixedText m_aUnderlineFT; ListBox m_aUnderlineLB; FixedText m_aColorFT; ColorListBox m_aColorLB; FixedText m_aStrikeoutFT; ListBox m_aStrikeoutLB; CheckBox m_aIndividualWordsBtn; FixedText m_aEmphasisFT; ListBox m_aEmphasisLB; FixedText m_aPositionFT; ListBox m_aPositionLB; FixedText m_aFontColorFT; ColorListBox m_aFontColorLB; FixedText m_aEffectsFT; SvxCheckListBox m_aEffectsLB; ListBox m_aEffects2LB; FixedText m_aReliefFT; ListBox m_aReliefLB; TriStateBox m_aOutlineBtn; TriStateBox m_aShadowBtn; TriStateBox m_aBlinkingBtn; TriStateBox m_aHiddenBtn; USHORT m_nHtmlMode; String m_aTransparentColorName; SvxCharEffectsPage( Window* pParent, const SfxItemSet& rSet ); void Initialize(); void UpdatePreview_Impl(); void SetCaseMap_Impl( SvxCaseMap eCaseMap ); void ResetColor_Impl( const SfxItemSet& rSet ); BOOL FillItemSetColor_Impl( SfxItemSet& rSet ); DECL_LINK( SelectHdl_Impl, ListBox* ); DECL_LINK( CbClickHdl_Impl, CheckBox* ); DECL_LINK( TristClickHdl_Impl, TriStateBox* ); DECL_LINK( UpdatePreview_Impl, ListBox* ); DECL_LINK( ColorBoxSelectHdl_Impl, ColorListBox* ); protected: virtual int DeactivatePage( SfxItemSet* pSet = 0 ); public: static SfxTabPage* Create( Window* pParent, const SfxItemSet& rSet ); static USHORT* GetRanges(); virtual void Reset( const SfxItemSet& rSet ); virtual BOOL FillItemSet( SfxItemSet& rSet ); void DisableControls( USHORT nDisable ); void EnableFlash(); // the writer uses SID_ATTR_BRUSH as font background void SetPreviewBackgroundToCharacter(); virtual void PageCreated (SfxAllItemSet aSet); //add CHINA001 }; // class SvxCharPositionPage --------------------------------------------- class SvxCharPositionPage : public SvxCharBasePage { private: FixedLine m_aPositionLine; RadioButton m_aHighPosBtn; RadioButton m_aNormalPosBtn; RadioButton m_aLowPosBtn; FixedText m_aHighLowFT; MetricField m_aHighLowEdit; CheckBox m_aHighLowRB; FixedText m_aFontSizeFT; MetricField m_aFontSizeEdit; FixedLine m_aRotationScalingFL; FixedLine m_aScalingFL; RadioButton m_a0degRB; RadioButton m_a90degRB; RadioButton m_a270degRB; CheckBox m_aFitToLineCB; FixedText m_aScaleWidthFT; MetricField m_aScaleWidthMF; FixedLine m_aKerningLine; ListBox m_aKerningLB; FixedText m_aKerningFT; MetricField m_aKerningEdit; CheckBox m_aPairKerningBtn; short m_nSuperEsc; short m_nSubEsc; UINT16 m_nScaleWidthItemSetVal; UINT16 m_nScaleWidthInitialVal; BYTE m_nSuperProp; BYTE m_nSubProp; SvxCharPositionPage( Window* pParent, const SfxItemSet& rSet ); void Initialize(); void UpdatePreview_Impl( BYTE nProp, BYTE nEscProp, short nEsc ); void SetEscapement_Impl( USHORT nEsc ); DECL_LINK( PositionHdl_Impl, RadioButton* ); DECL_LINK( RotationHdl_Impl, RadioButton* ); DECL_LINK( FontModifyHdl_Impl, MetricField* ); DECL_LINK( AutoPositionHdl_Impl, CheckBox* ); DECL_LINK( FitToLineHdl_Impl, CheckBox* ); DECL_LINK( KerningSelectHdl_Impl, ListBox* ); DECL_LINK( KerningModifyHdl_Impl, MetricField* ); DECL_LINK( PairKerningHdl_Impl, CheckBox* ); DECL_LINK( LoseFocusHdl_Impl, MetricField* ); DECL_LINK( ScaleWidthModifyHdl_Impl, MetricField* ); protected: virtual int DeactivatePage( SfxItemSet* pSet = 0 ); virtual void ActivatePage( const SfxItemSet& rSet ); public: static SfxTabPage* Create( Window* pParent, const SfxItemSet& rSet ); static USHORT* GetRanges(); virtual void Reset( const SfxItemSet& rSet ); virtual BOOL FillItemSet( SfxItemSet& rSet ); virtual void FillUserData(); // the writer uses SID_ATTR_BRUSH as font background void SetPreviewBackgroundToCharacter(); virtual void PageCreated (SfxAllItemSet aSet); //add CHINA001 virtual void DeactivatePage(); virtual void ActivatePage(); }; // class SvxCharTwoLinesPage --------------------------------------------- class SvxCharTwoLinesPage : public SvxCharBasePage { private: FixedLine m_aSwitchOnLine; CheckBox m_aTwoLinesBtn; FixedLine m_aEncloseLine; FixedText m_aStartBracketFT; ListBox m_aStartBracketLB; FixedText m_aEndBracketFT; ListBox m_aEndBracketLB; SvxCharTwoLinesPage( Window* pParent, const SfxItemSet& rSet ); void UpdatePreview_Impl(); void Initialize(); void SelectCharacter( ListBox* pBox ); void SetBracket( sal_Unicode cBracket, BOOL bStart ); DECL_LINK( TwoLinesHdl_Impl, CheckBox* ); DECL_LINK( CharacterMapHdl_Impl, ListBox* ); protected: virtual void ActivatePage( const SfxItemSet& rSet ); virtual int DeactivatePage( SfxItemSet* pSet = 0 ); public: static SfxTabPage* Create( Window* pParent, const SfxItemSet& rSet ); static USHORT* GetRanges(); virtual void Reset( const SfxItemSet& rSet ); virtual BOOL FillItemSet( SfxItemSet& rSet ); // the writer uses SID_ATTR_BRUSH as font background void SetPreviewBackgroundToCharacter(); virtual void PageCreated (SfxAllItemSet aSet); //add CHINA001 virtual void DeactivatePage(); virtual void ActivatePage(); }; #endif // #ifndef _SVX_CHARDLG_HXX <|endoftext|>
<commit_before>// // use implicit modeller to create a logo // #include "vtk.h" main () { vtkRenderer *aRenderer = vtkRenderer::New(); vtkRenderWindow *ourRenderingWindow = vtkRenderWindow::New(); ourRenderingWindow->AddRenderer(aRenderer); vtkRenderWindowInteractor *ourInteractor = vtkRenderWindowInteractor::New(); ourInteractor->SetRenderWindow(ourRenderingWindow); // read the geometry file containing the letter v vtkPolyDataReader *letterVBYU = vtkPolyDataReader::New(); letterVBYU->SetFileName ("v.vtk"); // read the geometry file containing the letter t vtkPolyDataReader *letterTBYU = vtkPolyDataReader::New(); letterTBYU->SetFileName ("t.vtk"); // read the geometry file containing the letter k vtkPolyDataReader *letterKBYU = vtkPolyDataReader::New(); letterKBYU->SetFileName ("k.vtk"); // create a transform and transform filter for each letter vtkTransform *VTransform = vtkTransform::New(); vtkTransformPolyDataFilter *VTransformFilter = vtkTransformPolyDataFilter::New(); VTransformFilter->SetInput (letterVBYU->GetOutput()); VTransformFilter->SetTransform (VTransform); vtkTransform *TTransform = vtkTransform::New(); vtkTransformPolyDataFilter *TTransformFilter = vtkTransformPolyDataFilter::New(); TTransformFilter->SetInput (letterTBYU->GetOutput()); TTransformFilter->SetTransform (TTransform); vtkTransform *KTransform = vtkTransform::New(); vtkTransformPolyDataFilter *KTransformFilter = vtkTransformPolyDataFilter::New(); KTransformFilter->SetInput (letterKBYU->GetOutput()); KTransformFilter->SetTransform (KTransform); // now append them all vtkAppendPolyData *appendAll = vtkAppendPolyData::New(); appendAll->AddInput (VTransformFilter->GetOutput()); appendAll->AddInput (TTransformFilter->GetOutput()); appendAll->AddInput (KTransformFilter->GetOutput()); // create normals vtkPolyDataNormals *logoNormals = vtkPolyDataNormals::New(); logoNormals->SetInput (appendAll->GetOutput()); logoNormals->SetFeatureAngle (60); // map to rendering primitives vtkPolyDataMapper *logoMapper = vtkPolyDataMapper::New(); logoMapper->SetInput (logoNormals->GetOutput()); // now an actor vtkActor *logo = vtkActor::New(); logo->SetMapper (logoMapper); // now create an implicit model of the same letter vtkImplicitModeller *blobbyLogoImp = vtkImplicitModeller::New(); blobbyLogoImp->SetInput (appendAll->GetOutput()); blobbyLogoImp->SetMaximumDistance (.075); blobbyLogoImp->SetSampleDimensions (64,64,64); blobbyLogoImp->SetAdjustDistance (0.05); // extract an iso surface vtkContourFilter *blobbyLogoIso = vtkContourFilter::New(); blobbyLogoIso->SetInput (blobbyLogoImp->GetOutput()); blobbyLogoIso->SetValue (1, 1.5); // map to rendering primitives vtkPolyDataMapper *blobbyLogoMapper = vtkPolyDataMapper::New(); blobbyLogoMapper->SetInput (blobbyLogoIso->GetOutput()); blobbyLogoMapper->ScalarVisibilityOff (); vtkProperty *tomato = vtkProperty::New(); tomato->SetDiffuseColor(1, .3882, .2784); tomato->SetSpecular(.3); tomato->SetSpecularPower(20); vtkProperty *banana = vtkProperty::New(); banana->SetDiffuseColor(.89, .81, .34); banana->SetDiffuse (.7); banana->SetSpecular(.4); banana->SetSpecularPower(20); // now an actor vtkActor *blobbyLogo = vtkActor::New(); blobbyLogo->SetMapper (blobbyLogoMapper); blobbyLogo->SetProperty (banana); // position the letters VTransform->Translate (-16,0,12.5); VTransform->RotateY (40); KTransform->Translate (14, 0, 0); KTransform->RotateY (-40); // move the polygonal letters to the front logo->SetProperty (tomato); logo->SetPosition(0,0,6); aRenderer->AddActor(logo); aRenderer->AddActor(blobbyLogo); aRenderer->SetBackground(1,1,1); ourRenderingWindow->Render(); // interact with data ourInteractor->Start(); } <commit_msg>Moved data to vtkdata<commit_after>// // use implicit modeller to create a logo // #include "vtk.h" main () { vtkRenderer *aRenderer = vtkRenderer::New(); vtkRenderWindow *ourRenderingWindow = vtkRenderWindow::New(); ourRenderingWindow->AddRenderer(aRenderer); vtkRenderWindowInteractor *ourInteractor = vtkRenderWindowInteractor::New(); ourInteractor->SetRenderWindow(ourRenderingWindow); // read the geometry file containing the letter v vtkPolyDataReader *letterVBYU = vtkPolyDataReader::New(); letterVBYU->SetFileName ("../../../vtkdata/v.vtk"); // read the geometry file containing the letter t vtkPolyDataReader *letterTBYU = vtkPolyDataReader::New(); letterTBYU->SetFileName ("../../../vtkdata/t.vtk"); // read the geometry file containing the letter k vtkPolyDataReader *letterKBYU = vtkPolyDataReader::New(); letterKBYU->SetFileName ("../../../vtkdata/k.vtk"); // create a transform and transform filter for each letter vtkTransform *VTransform = vtkTransform::New(); vtkTransformPolyDataFilter *VTransformFilter = vtkTransformPolyDataFilter::New(); VTransformFilter->SetInput (letterVBYU->GetOutput()); VTransformFilter->SetTransform (VTransform); vtkTransform *TTransform = vtkTransform::New(); vtkTransformPolyDataFilter *TTransformFilter = vtkTransformPolyDataFilter::New(); TTransformFilter->SetInput (letterTBYU->GetOutput()); TTransformFilter->SetTransform (TTransform); vtkTransform *KTransform = vtkTransform::New(); vtkTransformPolyDataFilter *KTransformFilter = vtkTransformPolyDataFilter::New(); KTransformFilter->SetInput (letterKBYU->GetOutput()); KTransformFilter->SetTransform (KTransform); // now append them all vtkAppendPolyData *appendAll = vtkAppendPolyData::New(); appendAll->AddInput (VTransformFilter->GetOutput()); appendAll->AddInput (TTransformFilter->GetOutput()); appendAll->AddInput (KTransformFilter->GetOutput()); // create normals vtkPolyDataNormals *logoNormals = vtkPolyDataNormals::New(); logoNormals->SetInput (appendAll->GetOutput()); logoNormals->SetFeatureAngle (60); // map to rendering primitives vtkPolyDataMapper *logoMapper = vtkPolyDataMapper::New(); logoMapper->SetInput (logoNormals->GetOutput()); // now an actor vtkActor *logo = vtkActor::New(); logo->SetMapper (logoMapper); // now create an implicit model of the same letter vtkImplicitModeller *blobbyLogoImp = vtkImplicitModeller::New(); blobbyLogoImp->SetInput (appendAll->GetOutput()); blobbyLogoImp->SetMaximumDistance (.075); blobbyLogoImp->SetSampleDimensions (64,64,64); blobbyLogoImp->SetAdjustDistance (0.05); // extract an iso surface vtkContourFilter *blobbyLogoIso = vtkContourFilter::New(); blobbyLogoIso->SetInput (blobbyLogoImp->GetOutput()); blobbyLogoIso->SetValue (1, 1.5); // map to rendering primitives vtkPolyDataMapper *blobbyLogoMapper = vtkPolyDataMapper::New(); blobbyLogoMapper->SetInput (blobbyLogoIso->GetOutput()); blobbyLogoMapper->ScalarVisibilityOff (); vtkProperty *tomato = vtkProperty::New(); tomato->SetDiffuseColor(1, .3882, .2784); tomato->SetSpecular(.3); tomato->SetSpecularPower(20); vtkProperty *banana = vtkProperty::New(); banana->SetDiffuseColor(.89, .81, .34); banana->SetDiffuse (.7); banana->SetSpecular(.4); banana->SetSpecularPower(20); // now an actor vtkActor *blobbyLogo = vtkActor::New(); blobbyLogo->SetMapper (blobbyLogoMapper); blobbyLogo->SetProperty (banana); // position the letters VTransform->Translate (-16,0,12.5); VTransform->RotateY (40); KTransform->Translate (14, 0, 0); KTransform->RotateY (-40); // move the polygonal letters to the front logo->SetProperty (tomato); logo->SetPosition(0,0,6); aRenderer->AddActor(logo); aRenderer->AddActor(blobbyLogo); aRenderer->SetBackground(1,1,1); ourRenderingWindow->Render(); // interact with data ourInteractor->Start(); } <|endoftext|>
<commit_before>// RUN: cat %s | %cling -Xclang -verify // Actually test clang::DeclContext::removeDecl(). This function in clang is // the main method that is used for the error recovery. This means when there // is an error in cling's input we need to revert all the declarations that came // in from the same transaction. Even when we have anonymous declarations we // need to be able to remove them from the declaration context. In a compiler's // point of view there is no way that one can call removeDecl() and pass in anon // decl, because the method is used when shadowing decls, which must have names. // The issue is (and we patched it) is that removeDecl is trying to remove the // anon decl (which doesn't have name) from the symbol (lookup) tables, which // doesn't make sense. // The current test checks if that codepath in removeDecl still exists because // it is important for the stable error recovery in cling .rawInput class MyClass { struct { int a; error_here; // expected-error {{C++ requires a type specifier for all declarations}} }; }; .rawInput .q <commit_msg>Extend the testsuite with including part of clang's anonymous-union test. Now we have two transactions that ensure further restructures on the DeclExtractor.<commit_after>// RUN: cat %s | %cling -Xclang -verify // Actually test clang::DeclContext::removeDecl(). This function in clang is // the main method that is used for the error recovery. This means when there // is an error in cling's input we need to revert all the declarations that came // in from the same transaction. Even when we have anonymous declarations we // need to be able to remove them from the declaration context. In a compiler's // point of view there is no way that one can call removeDecl() and pass in anon // decl, because the method is used when shadowing decls, which must have names. // The issue is (and we patched it) is that removeDecl is trying to remove the // anon decl (which doesn't have name) from the symbol (lookup) tables, which // doesn't make sense. // The current test checks if that codepath in removeDecl still exists because // it is important for the stable error recovery in cling class MyClass { struct { int a; error_here; // expected-error {{C++ requires a type specifier for all declarations}} }; }; struct X { union { float f3; double d2; } named; union { int i; float f; union { float f2; mutable double d; }; }; void test_unqual_references(); struct { int a; float b; }; void test_unqual_references_const() const; mutable union { // expected-error{{anonymous union at class scope must not have a storage specifier}} float c1; double c2; }; }; .q <|endoftext|>
<commit_before><commit_msg>cppcheck: multiCondition<commit_after><|endoftext|>
<commit_before>/* * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <wx/wx.h> #include <wx/timer.h> #include "ogre_tools/wx_ogre_render_window.h" #include "ogre_tools/initialization.h" #include "rviz/image/ros_image_texture.h" #include "ros/ros.h" #include <ros/package.h> #include <OGRE/OgreRoot.h> #include <OGRE/OgreSceneManager.h> #include <OGRE/OgreViewport.h> #include <OGRE/OgreRectangle2D.h> #include <OGRE/OgreMaterial.h> #include <OGRE/OgreMaterialManager.h> #include <OGRE/OgreTextureUnitState.h> #ifdef __WXMAC__ #include <ApplicationServices/ApplicationServices.h> #endif using namespace ogre_tools; using namespace rviz; class MyFrame : public wxFrame { public: MyFrame(wxWindow* parent) : wxFrame(parent, wxID_ANY, wxT("RViZ Image Viewer"), wxDefaultPosition, wxSize(800,600), wxDEFAULT_FRAME_STYLE) , timer_(this) { ogre_tools::initializeOgre(); root_ = Ogre::Root::getSingletonPtr(); try { scene_manager_ = root_->createSceneManager( Ogre::ST_GENERIC, "TestSceneManager" ); render_window_ = new ogre_tools::wxOgreRenderWindow( root_, this ); render_window_->setAutoRender(false); render_window_->SetSize( this->GetSize() ); ogre_tools::V_string paths; paths.push_back(ros::package::getPath(ROS_PACKAGE_NAME) + "/ogre_media/textures"); ogre_tools::initializeResources(paths); camera_ = scene_manager_->createCamera("Camera"); render_window_->getViewport()->setCamera( camera_ ); texture_ = new ROSImageTexture(nh_); texture_->setTopic("image"); Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().create( "Material", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME ); material->setCullingMode(Ogre::CULL_NONE); material->getTechnique(0)->getPass(0)->setDepthWriteEnabled(true); material->getTechnique(0)->setLightingEnabled(false); Ogre::TextureUnitState* tu = material->getTechnique(0)->getPass(0)->createTextureUnitState(); tu->setTextureName(texture_->getTexture()->getName()); tu->setTextureFiltering( Ogre::TFO_NONE ); Ogre::Rectangle2D* rect = new Ogre::Rectangle2D(true); rect->setCorners(-1.0f, 1.0f, 1.0f, -1.0f); rect->setMaterial(material->getName()); rect->setRenderQueueGroup(Ogre::RENDER_QUEUE_OVERLAY - 1); Ogre::AxisAlignedBox aabb; aabb.setInfinite(); rect->setBoundingBox(aabb); Ogre::SceneNode* node = scene_manager_->getRootSceneNode()->createChildSceneNode(); node->attachObject(rect); node->setVisible(true); } catch ( Ogre::Exception& e ) { printf( "Fatal error: %s\n", e.what() ); exit(1); } Connect(timer_.GetId(), wxEVT_TIMER, wxTimerEventHandler(MyFrame::onTimer), NULL, this); timer_.Start(33); render_window_->Refresh(); } void onTimer(wxTimerEvent&) { ros::spinOnce(); static bool first = true; try { if (texture_->update()) { if (first) { first = false; render_window_->SetSize(texture_->getWidth(), texture_->getHeight()); Fit(); } } root_->renderOneFrame(); } catch (UnsupportedImageEncoding& e) { ROS_ERROR("%s", e.what()); } if (!nh_.ok()) { Close(); } } ~MyFrame() { delete texture_; render_window_->Destroy(); delete root_; } private: Ogre::Root* root_; Ogre::SceneManager* scene_manager_; ogre_tools::wxOgreRenderWindow* render_window_; Ogre::Camera* camera_; ROSImageTexture* texture_; wxTimer timer_; ros::NodeHandle nh_; }; // our normal wxApp-derived class, as usual class MyApp : public wxApp { public: bool OnInit() { #ifdef __WXMAC__ ProcessSerialNumber PSN; GetCurrentProcess(&PSN); TransformProcessType(&PSN,kProcessTransformToForegroundApplication); SetFrontProcess(&PSN); #endif // create our own copy of argv, with regular char*s. char** local_argv = new char*[ argc ]; for ( int i = 0; i < argc; ++i ) { local_argv[ i ] = strdup( wxString( argv[ i ] ).mb_str() ); } ros::init(argc, local_argv, "rviz_image_view", ros::init_options::AnonymousName); wxFrame* frame = new MyFrame(NULL); SetTopWindow(frame); frame->Show(); return true; } int OnExit() { ogre_tools::cleanupOgre(); return 0; } }; DECLARE_APP(MyApp); IMPLEMENT_APP(MyApp); <commit_msg>Add image topic to titlebar (#3416)<commit_after>/* * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <wx/wx.h> #include <wx/timer.h> #include "ogre_tools/wx_ogre_render_window.h" #include "ogre_tools/initialization.h" #include "rviz/image/ros_image_texture.h" #include "ros/ros.h" #include <ros/package.h> #include <OGRE/OgreRoot.h> #include <OGRE/OgreSceneManager.h> #include <OGRE/OgreViewport.h> #include <OGRE/OgreRectangle2D.h> #include <OGRE/OgreMaterial.h> #include <OGRE/OgreMaterialManager.h> #include <OGRE/OgreTextureUnitState.h> #ifdef __WXMAC__ #include <ApplicationServices/ApplicationServices.h> #endif using namespace ogre_tools; using namespace rviz; class MyFrame : public wxFrame { public: MyFrame(wxWindow* parent) : wxFrame(parent, wxID_ANY, wxT("rviz Image Viewer"), wxDefaultPosition, wxSize(800,600), wxDEFAULT_FRAME_STYLE) , timer_(this) { ogre_tools::initializeOgre(); root_ = Ogre::Root::getSingletonPtr(); try { scene_manager_ = root_->createSceneManager( Ogre::ST_GENERIC, "TestSceneManager" ); render_window_ = new ogre_tools::wxOgreRenderWindow( root_, this ); render_window_->setAutoRender(false); render_window_->SetSize( this->GetSize() ); ogre_tools::V_string paths; paths.push_back(ros::package::getPath(ROS_PACKAGE_NAME) + "/ogre_media/textures"); ogre_tools::initializeResources(paths); camera_ = scene_manager_->createCamera("Camera"); render_window_->getViewport()->setCamera( camera_ ); std::string resolved_image = nh_.resolveName("image"); if (resolved_image == "/image") { ROS_WARN("image topic has not been remapped"); } std::stringstream title; title << "rviz Image Viewer [" << resolved_image << "]"; SetTitle(wxString::FromAscii(title.str().c_str())); texture_ = new ROSImageTexture(nh_); texture_->setTopic("image"); Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().create( "Material", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME ); material->setCullingMode(Ogre::CULL_NONE); material->getTechnique(0)->getPass(0)->setDepthWriteEnabled(true); material->getTechnique(0)->setLightingEnabled(false); Ogre::TextureUnitState* tu = material->getTechnique(0)->getPass(0)->createTextureUnitState(); tu->setTextureName(texture_->getTexture()->getName()); tu->setTextureFiltering( Ogre::TFO_NONE ); Ogre::Rectangle2D* rect = new Ogre::Rectangle2D(true); rect->setCorners(-1.0f, 1.0f, 1.0f, -1.0f); rect->setMaterial(material->getName()); rect->setRenderQueueGroup(Ogre::RENDER_QUEUE_OVERLAY - 1); Ogre::AxisAlignedBox aabb; aabb.setInfinite(); rect->setBoundingBox(aabb); Ogre::SceneNode* node = scene_manager_->getRootSceneNode()->createChildSceneNode(); node->attachObject(rect); node->setVisible(true); } catch ( Ogre::Exception& e ) { printf( "Fatal error: %s\n", e.what() ); exit(1); } Connect(timer_.GetId(), wxEVT_TIMER, wxTimerEventHandler(MyFrame::onTimer), NULL, this); timer_.Start(33); render_window_->Refresh(); } void onTimer(wxTimerEvent&) { ros::spinOnce(); static bool first = true; try { if (texture_->update()) { if (first) { first = false; render_window_->SetSize(texture_->getWidth(), texture_->getHeight()); Fit(); } } root_->renderOneFrame(); } catch (UnsupportedImageEncoding& e) { ROS_ERROR("%s", e.what()); } if (!nh_.ok()) { Close(); } } ~MyFrame() { delete texture_; render_window_->Destroy(); delete root_; } private: Ogre::Root* root_; Ogre::SceneManager* scene_manager_; ogre_tools::wxOgreRenderWindow* render_window_; Ogre::Camera* camera_; ROSImageTexture* texture_; wxTimer timer_; ros::NodeHandle nh_; }; // our normal wxApp-derived class, as usual class MyApp : public wxApp { public: bool OnInit() { #ifdef __WXMAC__ ProcessSerialNumber PSN; GetCurrentProcess(&PSN); TransformProcessType(&PSN,kProcessTransformToForegroundApplication); SetFrontProcess(&PSN); #endif // create our own copy of argv, with regular char*s. char** local_argv = new char*[ argc ]; for ( int i = 0; i < argc; ++i ) { local_argv[ i ] = strdup( wxString( argv[ i ] ).mb_str() ); } ros::init(argc, local_argv, "rviz_image_view", ros::init_options::AnonymousName); wxFrame* frame = new MyFrame(NULL); SetTopWindow(frame); frame->Show(); return true; } int OnExit() { ogre_tools::cleanupOgre(); return 0; } }; DECLARE_APP(MyApp); IMPLEMENT_APP(MyApp); <|endoftext|>
<commit_before>// $Id$ // (c) Guido Kanschat // // Show the shape functions implemented. #include <base/quadrature_lib.h> #include <base/logstream.h> #include <lac/vector.h> #include <grid/tria.h> #include <grid/tria_iterator.h> #include <dofs/dof_accessor.h> #include <grid/grid_generator.h> #include <fe/fe_q.h> #include <fe/fe_dgq.h> #include <fe/fe_system.h> #include <fe/mapping_q1.h> #include <fe/fe_values.h> #include <vector> #include <fstream> #include <string> #define PRECISION 2 char fname[50]; template<int dim> inline void plot_shape_functions(Mapping<dim>& mapping, FiniteElement<dim>& finel, const char* name) { Triangulation<dim> tr; DoFHandler<dim> dof(tr); GridGenerator::hyper_cube(tr, 0., 1.); DoFHandler<dim>::cell_iterator c = dof.begin(); dof.distribute_dofs(finel); const unsigned int div = 11; QTrapez<1> q_trapez; QIterated<dim> q(q_trapez, div); FEValues<dim> fe(mapping, finel, q, UpdateFlags(update_values)); fe.reinit(c); sprintf(fname, "Shapes%dd-%s.output", dim, name); std::ofstream gnuplot(fname); gnuplot.setf(ios::fixed); gnuplot.precision (PRECISION); unsigned int k=0; for (unsigned int mz=0;mz<=((dim>2) ? div : 0) ;++mz) { for (unsigned int my=0;my<=((dim>1) ? div : 0) ;++my) { for (unsigned int mx=0;mx<=div;++mx) { gnuplot << q.point(k); for (unsigned int i=0;i<finel.dofs_per_cell;++i) { gnuplot << " " << fe.shape_value(i,k) + 1.; } gnuplot << std::endl; k++; } gnuplot << std::endl; } gnuplot << std::endl; } } template<int dim> inline void plot_face_shape_functions(Mapping<dim>& mapping, FiniteElement<dim>& finel, const char* name) { Triangulation<dim> tr; DoFHandler<dim> dof(tr); GridGenerator::hyper_cube(tr, 0., 1.); tr.refine_global(1); DoFHandler<dim>::active_cell_iterator c = dof.begin_active(); ++c; c->set_refine_flag(); tr.execute_coarsening_and_refinement (); c = dof.begin_active(); dof.distribute_dofs(finel); const unsigned int div = 4; QTrapez<1> q_trapez; QIterated<dim-1> q(q_trapez, div); FEFaceValues<dim> fe(mapping, finel, q, UpdateFlags(update_values | update_q_points)); FESubfaceValues<dim> sub(mapping, finel, q, UpdateFlags(update_values | update_q_points)); sprintf(fname, "ShapesFace%dd-%s.output", dim, name); ofstream gnuplot(fname); gnuplot.setf(ios::fixed); gnuplot.precision (PRECISION); for (unsigned int f=0; f<GeometryInfo<dim>::faces_per_cell; ++f) { if (!c->face(f)->has_children()) { fe.reinit(c, f); unsigned int k=0; for (unsigned int my=0;my<=((dim>2) ? div : 0) ;++my) { for (unsigned int mx=0;mx<=div;++mx) { gnuplot << fe.quadrature_point(k); for (unsigned int i=0;i<finel.dofs_per_cell;++i) { gnuplot << " " << fe.shape_value(i,k) + 1.; } gnuplot << std::endl; k++; } gnuplot << std::endl; } gnuplot << std::endl; } else { for (unsigned int s=0;s<GeometryInfo<dim>::subfaces_per_face; ++s) { sub.reinit(c, f, s); unsigned int k=0; for (unsigned int my=0;my<=((dim>2) ? div : 0) ;++my) { for (unsigned int mx=0;mx<=div;++mx) { gnuplot << sub.quadrature_point(k); for (unsigned int i=0;i<finel.dofs_per_cell;++i) { gnuplot << " " << sub.shape_value(i,k) + 1.; } gnuplot << std::endl; k++; } gnuplot << std::endl; } gnuplot << std::endl; } } } } template<> void plot_face_shape_functions (Mapping<1>&, FiniteElement<1>&, const char*) {} template<int dim> void plot_FE_Q_shape_functions() { MappingQ1<dim> m; FE_Q<dim> q1(1); plot_shape_functions(m, q1, "Q1"); plot_face_shape_functions(m, q1, "Q1"); FE_Q<dim> q2(2); plot_shape_functions(m, q2, "Q2"); plot_face_shape_functions(m, q2, "Q2"); FE_Q<dim> q3(3); plot_shape_functions(m, q3, "Q3"); plot_face_shape_functions(m, q3, "Q3"); FE_Q<dim> q4(4); plot_shape_functions(m, q4, "Q4"); plot_face_shape_functions(m, q4, "Q4"); // FE_Q<dim> q5(5); // plot_shape_functions(m, q5, "Q5"); // FE_Q<dim> q6(6); // plot_shape_functions(m, q6, "Q6"); // FE_Q<dim> q7(7); // plot_shape_functions(m, q7, "Q7"); // FE_Q<dim> q8(8); // plot_shape_functions(m, q8, "Q8"); // FE_Q<dim> q9(9); // plot_shape_functions(m, q9, "Q9"); // FE_Q<dim> q10(10); // plot_shape_functions(m, q10, "Q10"); } template<int dim> void plot_FE_DGQ_shape_functions() { MappingQ1<dim> m; FE_DGQ<dim> q1(1); plot_shape_functions(m, q1, "DGQ1"); plot_face_shape_functions(m, q1, "DGQ1"); FE_DGQ<dim> q2(2); plot_shape_functions(m, q2, "DGQ2"); plot_face_shape_functions(m, q2, "DGQ2"); FE_DGQ<dim> q3(3); plot_shape_functions(m, q3, "DGQ3"); plot_face_shape_functions(m, q3, "DGQ3"); FE_DGQ<dim> q4(4); plot_shape_functions(m, q4, "DGQ4"); plot_face_shape_functions(m, q4, "DGQ4"); // FE_DGQ<dim> q5(5); // plot_shape_functions(m, q5, "DGQ5"); // FE_DGQ<dim> q6(6); // plot_shape_functions(m, q6, "DGQ6"); // FE_DGQ<dim> q7(7); // plot_shape_functions(m, q7, "DGQ7"); // FE_DGQ<dim> q8(8); // plot_shape_functions(m, q8, "DGQ8"); // FE_DGQ<dim> q9(9); // plot_shape_functions(m, q9, "DGQ9"); // FE_DGQ<dim> q10(10); // plot_shape_functions(m, q10, "DGQ10"); } int main() { ofstream logfile ("shapes.output"); logfile.precision (PRECISION); logfile.setf(ios::fixed); deallog.attach(logfile); deallog.depth_console(0); plot_FE_Q_shape_functions<1>(); plot_FE_Q_shape_functions<2>(); plot_FE_DGQ_shape_functions<2>(); // plot_FE_Q_shape_functions<3>(); // FESystem test. MappingQ1<2> m; FESystem<2> q2_q3(FE_Q<2>(2), 1, FE_Q<2>(3), 1); // plot_shape_functions(m, q2_q3, "Q2_Q3"); return 0; } <commit_msg>Implementation of tests for the new FE::shape_value, shape_grad and shape_grad_grad functions.<commit_after>// $Id$ // (c) Guido Kanschat // // Show the shape functions implemented. #include <base/quadrature_lib.h> #include <base/logstream.h> #include <lac/vector.h> #include <grid/tria.h> #include <grid/tria_iterator.h> #include <dofs/dof_accessor.h> #include <grid/grid_generator.h> #include <fe/fe_q.h> #include <fe/fe_dgq.h> #include <fe/fe_system.h> #include <fe/mapping_q1.h> #include <fe/fe_values.h> #include <vector> #include <fstream> #include <string> #define PRECISION 2 char fname[50]; template<int dim> inline void plot_shape_functions(Mapping<dim>& mapping, FiniteElement<dim>& finel, const char* name) { Triangulation<dim> tr; DoFHandler<dim> dof(tr); GridGenerator::hyper_cube(tr, 0., 1.); DoFHandler<dim>::cell_iterator c = dof.begin(); dof.distribute_dofs(finel); const unsigned int div = 11; QTrapez<1> q_trapez; QIterated<dim> q(q_trapez, div); FEValues<dim> fe(mapping, finel, q, UpdateFlags(update_values)); fe.reinit(c); sprintf(fname, "Shapes%dd-%s.output", dim, name); std::ofstream gnuplot(fname); gnuplot.setf(ios::fixed); gnuplot.precision (PRECISION); unsigned int k=0; for (unsigned int mz=0;mz<=((dim>2) ? div : 0) ;++mz) { for (unsigned int my=0;my<=((dim>1) ? div : 0) ;++my) { for (unsigned int mx=0;mx<=div;++mx) { gnuplot << q.point(k); for (unsigned int i=0;i<finel.dofs_per_cell;++i) { gnuplot << " " << fe.shape_value(i,k) + 1.; } gnuplot << std::endl; k++; } gnuplot << std::endl; } gnuplot << std::endl; } } template<int dim> inline void plot_face_shape_functions(Mapping<dim>& mapping, FiniteElement<dim>& finel, const char* name) { Triangulation<dim> tr; DoFHandler<dim> dof(tr); GridGenerator::hyper_cube(tr, 0., 1.); tr.refine_global(1); DoFHandler<dim>::active_cell_iterator c = dof.begin_active(); ++c; c->set_refine_flag(); tr.execute_coarsening_and_refinement (); c = dof.begin_active(); dof.distribute_dofs(finel); const unsigned int div = 4; QTrapez<1> q_trapez; QIterated<dim-1> q(q_trapez, div); FEFaceValues<dim> fe(mapping, finel, q, UpdateFlags(update_values | update_q_points)); FESubfaceValues<dim> sub(mapping, finel, q, UpdateFlags(update_values | update_q_points)); sprintf(fname, "ShapesFace%dd-%s.output", dim, name); ofstream gnuplot(fname); gnuplot.setf(ios::fixed); gnuplot.precision (PRECISION); for (unsigned int f=0; f<GeometryInfo<dim>::faces_per_cell; ++f) { if (!c->face(f)->has_children()) { fe.reinit(c, f); unsigned int k=0; for (unsigned int my=0;my<=((dim>2) ? div : 0) ;++my) { for (unsigned int mx=0;mx<=div;++mx) { gnuplot << fe.quadrature_point(k); for (unsigned int i=0;i<finel.dofs_per_cell;++i) { gnuplot << " " << fe.shape_value(i,k) + 1.; } gnuplot << std::endl; k++; } gnuplot << std::endl; } gnuplot << std::endl; } else { for (unsigned int s=0;s<GeometryInfo<dim>::subfaces_per_face; ++s) { sub.reinit(c, f, s); unsigned int k=0; for (unsigned int my=0;my<=((dim>2) ? div : 0) ;++my) { for (unsigned int mx=0;mx<=div;++mx) { gnuplot << sub.quadrature_point(k); for (unsigned int i=0;i<finel.dofs_per_cell;++i) { gnuplot << " " << sub.shape_value(i,k) + 1.; } gnuplot << std::endl; k++; } gnuplot << std::endl; } gnuplot << std::endl; } } } } template<> void plot_face_shape_functions (Mapping<1>&, FiniteElement<1>&, const char*) {} template<int dim> void test_compute_functions (const Mapping<dim> &mapping, const FiniteElement<dim> &fe, const char* name) { Triangulation<dim> tr; DoFHandler<dim> dof(tr); GridGenerator::hyper_cube(tr, 0., 1.); dof.distribute_dofs(fe); const QGauss6<dim> q; FEValues<dim> fe_values(mapping, fe, q, UpdateFlags(update_values| update_gradients| update_second_derivatives)); DoFHandler<dim>::active_cell_iterator cell = dof.begin_active(); fe_values.reinit(cell); bool coincide=true; for (unsigned int x=0; x<q.n_quadrature_points; ++x) for (unsigned int i=0; i<fe.dofs_per_cell; ++i) if (fabs(fe_values.shape_value(i,x)-fe.shape_value(i,q.point(x)))>1e-14) coincide=false; if (!coincide) deallog << "Error in fe.shape_value for " << name << endl; coincide=true; for (unsigned int x=0; x<q.n_quadrature_points; ++x) for (unsigned int i=0; i<fe.dofs_per_cell; ++i) { Tensor<1,dim> tmp=fe_values.shape_grad(i,x); tmp-=fe.shape_grad(i,q.point(x)); if (sqrt(tmp*tmp)>1e-14) coincide=false; } if (!coincide) deallog << "Error in fe.shape_grad for " << name << endl; coincide=true; double max_diff=0.; for (unsigned int x=0; x<q.n_quadrature_points; ++x) for (unsigned int i=0; i<fe.dofs_per_cell; ++i) { Tensor<2,dim> tmp=fe_values.shape_2nd_derivative(i,x); tmp-=fe.shape_grad_grad(i,q.point(x)); for (unsigned int j=0; j<dim; ++j) for (unsigned int k=0; k<dim; ++k) { const double diff=fabs(tmp[j][k]); if (diff>max_diff) max_diff=diff; if (fabs(tmp[j][k])>1e-6) coincide=false; } } if (!coincide) deallog << "Error in fe.shape_grad_grad for " << name << endl << "max_diff=" << max_diff << endl; } template<int dim> void plot_FE_Q_shape_functions() { MappingQ1<dim> m; FE_Q<dim> q1(1); plot_shape_functions(m, q1, "Q1"); plot_face_shape_functions(m, q1, "Q1"); test_compute_functions(m, q1, "Q1"); FE_Q<dim> q2(2); plot_shape_functions(m, q2, "Q2"); plot_face_shape_functions(m, q2, "Q2"); test_compute_functions(m, q2, "Q2"); FE_Q<dim> q3(3); plot_shape_functions(m, q3, "Q3"); plot_face_shape_functions(m, q3, "Q3"); test_compute_functions(m, q3, "Q3"); FE_Q<dim> q4(4); plot_shape_functions(m, q4, "Q4"); plot_face_shape_functions(m, q4, "Q4"); test_compute_functions(m, q4, "Q4"); // FE_Q<dim> q5(5); // plot_shape_functions(m, q5, "Q5"); // FE_Q<dim> q6(6); // plot_shape_functions(m, q6, "Q6"); // FE_Q<dim> q7(7); // plot_shape_functions(m, q7, "Q7"); // FE_Q<dim> q8(8); // plot_shape_functions(m, q8, "Q8"); // FE_Q<dim> q9(9); // plot_shape_functions(m, q9, "Q9"); // FE_Q<dim> q10(10); // plot_shape_functions(m, q10, "Q10"); } template<int dim> void plot_FE_DGQ_shape_functions() { MappingQ1<dim> m; FE_DGQ<dim> q1(1); plot_shape_functions(m, q1, "DGQ1"); plot_face_shape_functions(m, q1, "DGQ1"); test_compute_functions(m, q1, "DGQ1"); FE_DGQ<dim> q2(2); plot_shape_functions(m, q2, "DGQ2"); plot_face_shape_functions(m, q2, "DGQ2"); test_compute_functions(m, q2, "DGQ2"); FE_DGQ<dim> q3(3); plot_shape_functions(m, q3, "DGQ3"); plot_face_shape_functions(m, q3, "DGQ3"); test_compute_functions(m, q3, "DGQ3"); FE_DGQ<dim> q4(4); plot_shape_functions(m, q4, "DGQ4"); plot_face_shape_functions(m, q4, "DGQ4"); test_compute_functions(m, q4, "DGQ4"); // FE_DGQ<dim> q5(5); // plot_shape_functions(m, q5, "DGQ5"); // FE_DGQ<dim> q6(6); // plot_shape_functions(m, q6, "DGQ6"); // FE_DGQ<dim> q7(7); // plot_shape_functions(m, q7, "DGQ7"); // FE_DGQ<dim> q8(8); // plot_shape_functions(m, q8, "DGQ8"); // FE_DGQ<dim> q9(9); // plot_shape_functions(m, q9, "DGQ9"); // FE_DGQ<dim> q10(10); // plot_shape_functions(m, q10, "DGQ10"); } int main() { ofstream logfile ("shapes.output"); logfile.precision (PRECISION); logfile.setf(ios::fixed); deallog.attach(logfile); deallog.depth_console(0); plot_FE_Q_shape_functions<1>(); plot_FE_Q_shape_functions<2>(); plot_FE_DGQ_shape_functions<2>(); // plot_FE_Q_shape_functions<3>(); // FESystem test. MappingQ1<2> m; FESystem<2> q2_q3(FE_Q<2>(2), 1, FE_Q<2>(3), 1); test_compute_functions(m, q2_q3, "Q2_Q3"); // plot_shape_functions(m, q2_q3, "Q2_Q3"); return 0; } <|endoftext|>
<commit_before>#include "Midi.h" #include "MidiClock.h" // #include "GUI.h" #define MIDI_NOTE_OFF_CB 0 #define MIDI_NOTE_ON_CB 1 #define MIDI_AT_CB 2 #define MIDI_CC_CB 3 #define MIDI_PRG_CHG_CB 4 #define MIDI_CHAN_PRESS_CB 5 #define MIDI_PITCH_WHEEL_CB 6 const midi_parse_t midi_parse[] = { { MIDI_NOTE_OFF, midi_wait_byte_2 }, { MIDI_NOTE_ON, midi_wait_byte_2 }, { MIDI_AFTER_TOUCH, midi_wait_byte_2 }, { MIDI_CONTROL_CHANGE, midi_wait_byte_2 }, { MIDI_PROGRAM_CHANGE, midi_wait_byte_1 }, { MIDI_CHANNEL_PRESSURE, midi_wait_byte_1 }, { MIDI_PITCH_WHEEL, midi_wait_byte_2 }, /* special handling for SYSEX */ { MIDI_MTC_QUARTER_FRAME, midi_wait_byte_1 }, { MIDI_SONG_POSITION_PTR, midi_wait_byte_2 }, { MIDI_SONG_SELECT, midi_wait_byte_1 }, { MIDI_TUNE_REQUEST, midi_wait_status }, { 0, midi_ignore_message} }; MidiClass::MidiClass(MidiUartClass *_uart) { uart = _uart; receiveChannel = 0xFF; init(); for (int i = 0; i < 7; i++) { callbacks[i] = NULL; } } void MidiClass::init() { last_status = running_status = 0; in_state = midi_ignore_message; } void MidiClass::handleByte(uint8_t byte) { again: if (MIDI_IS_REALTIME_STATUS_BYTE(byte)) { uint8_t tmp = SREG; cli(); if (MidiClock.mode == MidiClock.EXTERNAL) { switch (byte) { case MIDI_CLOCK: // handled in interrupt routine break; case MIDI_START: MidiClock.handleMidiStart(); break; case MIDI_STOP: MidiClock.handleMidiStop(); break; } } SREG = tmp; return; } switch (in_state) { case midi_ignore_message: if (MIDI_IS_STATUS_BYTE(byte)) { in_state = midi_wait_status; goto again; } else { /* ignore */ } break; case midi_wait_sysex: // GUI.setLine(GUI.LINE2); // GUI.put_valuex(0, byte); // GUI.put_valuex(1, MidiUart.rxRb.overflow); // GUI.put_value16(1, sysex->len); if (MIDI_IS_STATUS_BYTE(byte)) { if (byte != MIDI_SYSEX_END) { in_state = midi_wait_status; if (sysex != NULL) sysex->abort(); goto again; } else { if (sysex != NULL) sysex->end(); } } else { if (sysex != NULL) { sysex->handleByte(byte); } } break; case midi_wait_status: { if (byte == MIDI_SYSEX_START) { in_state = midi_wait_sysex; if (sysex != NULL) sysex->start(); last_status = running_status = 0; return; } if (MIDI_IS_STATUS_BYTE(byte)) { last_status = byte; running_status = 0; } else { if (last_status == 0) break; running_status = 1; } uint8_t status = last_status; if (MIDI_IS_VOICE_STATUS_BYTE(status)) { status = MIDI_VOICE_TYPE_NIBBLE(status); } uint8_t i; for (i = 0; midi_parse[i].midi_status != 0; i++) { if (midi_parse[i].midi_status == status) { in_state = midi_parse[i].next_state; msg[0] = last_status; in_msg_len = 1; break; } } callback = i; if (midi_parse[i].midi_status == 0) { in_state = midi_ignore_message; return; } if (running_status) goto again; } break; case midi_wait_byte_1: msg[in_msg_len++] = byte; /* XXX check callback, note off, params, etc... */ if (callback < 7 && callbacks[callback] != NULL) { callbacks[callback](msg); } in_state = midi_wait_status; break; case midi_wait_byte_2: msg[in_msg_len++] = byte; in_state = midi_wait_byte_1; break; } } void MidiClass::setOnControlChangeCallback(midi_callback_t cb) { callbacks[MIDI_CC_CB] = cb; } void MidiClass::setOnNoteOnCallback(midi_callback_t cb) { callbacks[MIDI_NOTE_ON_CB] = cb; } void MidiClass::setOnNoteOffCallback(midi_callback_t cb) { callbacks[MIDI_NOTE_OFF_CB] = cb; } void MidiClass::setOnAfterTouchCallback(midi_callback_t cb) { callbacks[MIDI_AT_CB] = cb; } void MidiClass::setOnProgramChangeCallback(midi_callback_t cb) { callbacks[MIDI_PRG_CHG_CB] = cb; } void MidiClass::setOnChannelPressureCallback(midi_callback_t cb) { callbacks[MIDI_CHAN_PRESS_CB] = cb; } void MidiClass::setOnPitchWheelCallback(midi_callback_t cb) { callbacks[MIDI_PITCH_WHEEL_CB] = cb; } void MidiSysexClass::start() { len = 0; aborted = false; recording = false; recordLen = 0; } void MidiSysexClass::startRecord() { recording = true; recordLen = 0; } void MidiSysexClass::stopRecord() { recording = false; } void MidiSysexClass::abort() { // don't reset len, leave at maximum when aborted // len = 0; aborted = true; } void MidiSysexClass::handleByte(uint8_t byte) { if (aborted) return; len++; if (recording && data != NULL) { if (recordLen < max_len) { data[recordLen++] = byte; } } } void MididuinoSysexClass::start() { isMididuinoSysex = true; MidiSysexClass::start(); } uint8_t mididuino_hdr[3] = { MIDIDUINO_SYSEX_VENDOR_1, MIDIDUINO_SYSEX_VENDOR_2, BOARD_ID }; void MididuinoSysexClass::handleByte(uint8_t byte) { if (isMididuinoSysex) { if (len < 3 && byte != mididuino_hdr[len]) { isMididuinoSysex = false; } else if (len == 3 && byte == CMD_START_BOOTLOADER) { LCD.line1_fill((char *)"BOOTLOADER"); start_bootloader(); } } MidiSysexClass::handleByte(byte); } <commit_msg>remove bootloader string when rebooting<commit_after>#include "Midi.h" #include "MidiClock.h" // #include "GUI.h" #define MIDI_NOTE_OFF_CB 0 #define MIDI_NOTE_ON_CB 1 #define MIDI_AT_CB 2 #define MIDI_CC_CB 3 #define MIDI_PRG_CHG_CB 4 #define MIDI_CHAN_PRESS_CB 5 #define MIDI_PITCH_WHEEL_CB 6 const midi_parse_t midi_parse[] = { { MIDI_NOTE_OFF, midi_wait_byte_2 }, { MIDI_NOTE_ON, midi_wait_byte_2 }, { MIDI_AFTER_TOUCH, midi_wait_byte_2 }, { MIDI_CONTROL_CHANGE, midi_wait_byte_2 }, { MIDI_PROGRAM_CHANGE, midi_wait_byte_1 }, { MIDI_CHANNEL_PRESSURE, midi_wait_byte_1 }, { MIDI_PITCH_WHEEL, midi_wait_byte_2 }, /* special handling for SYSEX */ { MIDI_MTC_QUARTER_FRAME, midi_wait_byte_1 }, { MIDI_SONG_POSITION_PTR, midi_wait_byte_2 }, { MIDI_SONG_SELECT, midi_wait_byte_1 }, { MIDI_TUNE_REQUEST, midi_wait_status }, { 0, midi_ignore_message} }; MidiClass::MidiClass(MidiUartClass *_uart) { uart = _uart; receiveChannel = 0xFF; init(); for (int i = 0; i < 7; i++) { callbacks[i] = NULL; } } void MidiClass::init() { last_status = running_status = 0; in_state = midi_ignore_message; } void MidiClass::handleByte(uint8_t byte) { again: if (MIDI_IS_REALTIME_STATUS_BYTE(byte)) { uint8_t tmp = SREG; cli(); if (MidiClock.mode == MidiClock.EXTERNAL) { switch (byte) { case MIDI_CLOCK: // handled in interrupt routine break; case MIDI_START: MidiClock.handleMidiStart(); break; case MIDI_STOP: MidiClock.handleMidiStop(); break; } } SREG = tmp; return; } switch (in_state) { case midi_ignore_message: if (MIDI_IS_STATUS_BYTE(byte)) { in_state = midi_wait_status; goto again; } else { /* ignore */ } break; case midi_wait_sysex: // GUI.setLine(GUI.LINE2); // GUI.put_valuex(0, byte); // GUI.put_valuex(1, MidiUart.rxRb.overflow); // GUI.put_value16(1, sysex->len); if (MIDI_IS_STATUS_BYTE(byte)) { if (byte != MIDI_SYSEX_END) { in_state = midi_wait_status; if (sysex != NULL) sysex->abort(); goto again; } else { if (sysex != NULL) sysex->end(); } } else { if (sysex != NULL) { sysex->handleByte(byte); } } break; case midi_wait_status: { if (byte == MIDI_SYSEX_START) { in_state = midi_wait_sysex; if (sysex != NULL) sysex->start(); last_status = running_status = 0; return; } if (MIDI_IS_STATUS_BYTE(byte)) { last_status = byte; running_status = 0; } else { if (last_status == 0) break; running_status = 1; } uint8_t status = last_status; if (MIDI_IS_VOICE_STATUS_BYTE(status)) { status = MIDI_VOICE_TYPE_NIBBLE(status); } uint8_t i; for (i = 0; midi_parse[i].midi_status != 0; i++) { if (midi_parse[i].midi_status == status) { in_state = midi_parse[i].next_state; msg[0] = last_status; in_msg_len = 1; break; } } callback = i; if (midi_parse[i].midi_status == 0) { in_state = midi_ignore_message; return; } if (running_status) goto again; } break; case midi_wait_byte_1: msg[in_msg_len++] = byte; /* XXX check callback, note off, params, etc... */ if (callback < 7 && callbacks[callback] != NULL) { callbacks[callback](msg); } in_state = midi_wait_status; break; case midi_wait_byte_2: msg[in_msg_len++] = byte; in_state = midi_wait_byte_1; break; } } void MidiClass::setOnControlChangeCallback(midi_callback_t cb) { callbacks[MIDI_CC_CB] = cb; } void MidiClass::setOnNoteOnCallback(midi_callback_t cb) { callbacks[MIDI_NOTE_ON_CB] = cb; } void MidiClass::setOnNoteOffCallback(midi_callback_t cb) { callbacks[MIDI_NOTE_OFF_CB] = cb; } void MidiClass::setOnAfterTouchCallback(midi_callback_t cb) { callbacks[MIDI_AT_CB] = cb; } void MidiClass::setOnProgramChangeCallback(midi_callback_t cb) { callbacks[MIDI_PRG_CHG_CB] = cb; } void MidiClass::setOnChannelPressureCallback(midi_callback_t cb) { callbacks[MIDI_CHAN_PRESS_CB] = cb; } void MidiClass::setOnPitchWheelCallback(midi_callback_t cb) { callbacks[MIDI_PITCH_WHEEL_CB] = cb; } void MidiSysexClass::start() { len = 0; aborted = false; recording = false; recordLen = 0; } void MidiSysexClass::startRecord() { recording = true; recordLen = 0; } void MidiSysexClass::stopRecord() { recording = false; } void MidiSysexClass::abort() { // don't reset len, leave at maximum when aborted // len = 0; aborted = true; } void MidiSysexClass::handleByte(uint8_t byte) { if (aborted) return; len++; if (recording && data != NULL) { if (recordLen < max_len) { data[recordLen++] = byte; } } } void MididuinoSysexClass::start() { isMididuinoSysex = true; MidiSysexClass::start(); } uint8_t mididuino_hdr[3] = { MIDIDUINO_SYSEX_VENDOR_1, MIDIDUINO_SYSEX_VENDOR_2, BOARD_ID }; void MididuinoSysexClass::handleByte(uint8_t byte) { if (isMididuinoSysex) { if (len < 3 && byte != mididuino_hdr[len]) { isMididuinoSysex = false; } else if (len == 3 && byte == CMD_START_BOOTLOADER) { // LCD.line1_fill((char *)"BOOTLOADER"); start_bootloader(); } } MidiSysexClass::handleByte(byte); } <|endoftext|>
<commit_before>/* * Copyright (C) 2017 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include <boost/range/adaptor/transformed.hpp> #include <boost/range/algorithm/copy.hpp> #include <boost/range/algorithm_ext/push_back.hpp> #include <seastar/core/thread.hh> #include "partition_version.hh" #include "partition_snapshot_row_cursor.hh" #include "disk-error-handler.hh" #include "tests/test-utils.hh" #include "tests/mutation_assertions.hh" #include "tests/mutation_reader_assertions.hh" #include "tests/simple_schema.hh" thread_local disk_error_signal_type commit_error; thread_local disk_error_signal_type general_disk_error; using namespace std::chrono_literals; SEASTAR_TEST_CASE(test_apply_to_incomplete) { return seastar::async([] { logalloc::region r; simple_schema table; auto&& s = *table.schema(); auto new_mutation = [&] { return mutation(table.make_pkey(0), table.schema()); }; auto mutation_with_row = [&] (clustering_key ck) { auto m = new_mutation(); table.add_row(m, ck, "v"); return m; }; // FIXME: There is no assert_that() for mutation_partition auto assert_equal = [&] (mutation_partition mp1, mutation_partition mp2) { auto key = table.make_pkey(0); assert_that(mutation(table.schema(), key, std::move(mp1))) .is_equal_to(mutation(table.schema(), key, std::move(mp2))); }; auto apply = [&] (partition_entry& e, const mutation& m) { e.apply_to_incomplete(s, partition_entry(m.partition()), s); }; auto ck1 = table.make_ckey(1); auto ck2 = table.make_ckey(2); BOOST_TEST_MESSAGE("Check that insert falling into discontinuous range is dropped"); with_allocator(r.allocator(), [&] { logalloc::reclaim_lock l(r); auto e = partition_entry(mutation_partition::make_incomplete(s)); auto m = new_mutation(); table.add_row(m, ck1, "v"); apply(e, m); assert_equal(e.squashed(s), mutation_partition::make_incomplete(s)); }); BOOST_TEST_MESSAGE("Check that continuity from latest version wins"); with_allocator(r.allocator(), [&] { logalloc::reclaim_lock l(r); auto m1 = mutation_with_row(ck2); auto e = partition_entry(m1.partition()); auto snap1 = e.read(r, table.schema()); auto m2 = mutation_with_row(ck2); apply(e, m2); partition_version* latest = &*e.version(); partition_version* prev = latest->next(); for (rows_entry& row : prev->partition().clustered_rows()) { row.set_continuous(is_continuous::no); } auto m3 = mutation_with_row(ck1); apply(e, m3); assert_equal(e.squashed(s), (m2 + m3).partition()); // Check that snapshot data is not stolen when its entry is applied auto e2 = partition_entry(mutation_partition(table.schema())); e2.apply_to_incomplete(s, std::move(e), s); assert_equal(snap1->squashed(), m1.partition()); assert_equal(e2.squashed(s), (m2 + m3).partition()); }); }); } SEASTAR_TEST_CASE(test_schema_upgrade_preserves_continuity) { return seastar::async([] { logalloc::region r; simple_schema table; auto new_mutation = [&] { return mutation(table.make_pkey(0), table.schema()); }; auto mutation_with_row = [&] (clustering_key ck) { auto m = new_mutation(); table.add_row(m, ck, "v"); return m; }; // FIXME: There is no assert_that() for mutation_partition auto assert_entry_equal = [&] (schema_ptr e_schema, partition_entry& e, mutation m) { auto key = table.make_pkey(0); assert_that(mutation(e_schema, key, e.squashed(*e_schema))) .is_equal_to(m) .has_same_continuity(m); }; auto apply = [&] (schema_ptr e_schema, partition_entry& e, const mutation& m) { e.apply_to_incomplete(*e_schema, partition_entry(m.partition()), *m.schema()); }; with_allocator(r.allocator(), [&] { logalloc::reclaim_lock l(r); auto m1 = mutation_with_row(table.make_ckey(1)); m1.partition().clustered_rows().begin()->set_continuous(is_continuous::no); m1.partition().set_static_row_continuous(false); m1.partition().ensure_last_dummy(*m1.schema()); auto e = partition_entry(m1.partition()); auto rd1 = e.read(r, table.schema()); auto m2 = mutation_with_row(table.make_ckey(3)); m2.partition().ensure_last_dummy(*m2.schema()); apply(table.schema(), e, m2); auto new_schema = schema_builder(table.schema()).with_column("__new_column", utf8_type).build(); e.upgrade(table.schema(), new_schema); rd1 = {}; assert_entry_equal(new_schema, e, m1 + m2); auto m3 = mutation_with_row(table.make_ckey(2)); apply(new_schema, e, m3); auto m4 = mutation_with_row(table.make_ckey(0)); table.add_static_row(m4, "s_val"); apply(new_schema, e, m4); assert_entry_equal(new_schema, e, m1 + m2 + m3); }); }); } SEASTAR_TEST_CASE(test_full_eviction_marks_affected_range_as_discontinuous) { return seastar::async([] { logalloc::region r; with_allocator(r.allocator(), [&] { logalloc::reclaim_lock l(r); simple_schema table; auto&& s = *table.schema(); auto ck1 = table.make_ckey(1); auto ck2 = table.make_ckey(2); auto e = partition_entry(mutation_partition(table.schema())); auto t = table.new_tombstone(); auto&& p1 = e.open_version(s).partition(); p1.clustered_row(s, ck2); p1.apply(t); auto snap1 = e.read(r, table.schema()); auto&& p2 = e.open_version(s).partition(); p2.clustered_row(s, ck1); auto snap2 = e.read(r, table.schema()); e.evict(); BOOST_REQUIRE(snap1->squashed().fully_discontinuous(s, position_range( position_in_partition::before_all_clustered_rows(), position_in_partition::after_key(ck2) ))); BOOST_REQUIRE(snap2->squashed().fully_discontinuous(s, position_range( position_in_partition::before_all_clustered_rows(), position_in_partition::after_key(ck2) ))); BOOST_REQUIRE(!snap1->squashed().static_row_continuous()); BOOST_REQUIRE(!snap2->squashed().static_row_continuous()); BOOST_REQUIRE_EQUAL(snap1->squashed().partition_tombstone(), t); BOOST_REQUIRE_EQUAL(snap2->squashed().partition_tombstone(), t); }); }); } SEASTAR_TEST_CASE(test_eviction_with_active_reader) { return seastar::async([] { logalloc::region r; with_allocator(r.allocator(), [&] { simple_schema table; auto&& s = *table.schema(); auto ck1 = table.make_ckey(1); auto ck2 = table.make_ckey(2); auto e = partition_entry(mutation_partition(table.schema())); auto&& p1 = e.open_version(s).partition(); p1.clustered_row(s, ck2); p1.ensure_last_dummy(s); // needed by partition_snapshot_row_cursor auto snap1 = e.read(r, table.schema()); auto&& p2 = e.open_version(s).partition(); p2.clustered_row(s, ck1); auto snap2 = e.read(r, table.schema()); partition_snapshot_row_cursor cursor(s, *snap2); cursor.advance_to(position_in_partition_view::before_all_clustered_rows()); BOOST_REQUIRE(cursor.continuous()); BOOST_REQUIRE(cursor.key().equal(s, ck1)); e.evict(); cursor.maybe_refresh(); do { BOOST_REQUIRE(!cursor.continuous()); BOOST_REQUIRE(cursor.dummy()); } while (cursor.next()); }); }); } <commit_msg>tests: mvcc: Add test for partition_snapshot_row_cursor<commit_after>/* * Copyright (C) 2017 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include <boost/range/adaptor/transformed.hpp> #include <boost/range/algorithm/copy.hpp> #include <boost/range/algorithm_ext/push_back.hpp> #include <seastar/core/thread.hh> #include "partition_version.hh" #include "partition_snapshot_row_cursor.hh" #include "disk-error-handler.hh" #include "tests/test-utils.hh" #include "tests/mutation_assertions.hh" #include "tests/mutation_reader_assertions.hh" #include "tests/simple_schema.hh" thread_local disk_error_signal_type commit_error; thread_local disk_error_signal_type general_disk_error; using namespace std::chrono_literals; SEASTAR_TEST_CASE(test_apply_to_incomplete) { return seastar::async([] { logalloc::region r; simple_schema table; auto&& s = *table.schema(); auto new_mutation = [&] { return mutation(table.make_pkey(0), table.schema()); }; auto mutation_with_row = [&] (clustering_key ck) { auto m = new_mutation(); table.add_row(m, ck, "v"); return m; }; // FIXME: There is no assert_that() for mutation_partition auto assert_equal = [&] (mutation_partition mp1, mutation_partition mp2) { auto key = table.make_pkey(0); assert_that(mutation(table.schema(), key, std::move(mp1))) .is_equal_to(mutation(table.schema(), key, std::move(mp2))); }; auto apply = [&] (partition_entry& e, const mutation& m) { e.apply_to_incomplete(s, partition_entry(m.partition()), s); }; auto ck1 = table.make_ckey(1); auto ck2 = table.make_ckey(2); BOOST_TEST_MESSAGE("Check that insert falling into discontinuous range is dropped"); with_allocator(r.allocator(), [&] { logalloc::reclaim_lock l(r); auto e = partition_entry(mutation_partition::make_incomplete(s)); auto m = new_mutation(); table.add_row(m, ck1, "v"); apply(e, m); assert_equal(e.squashed(s), mutation_partition::make_incomplete(s)); }); BOOST_TEST_MESSAGE("Check that continuity from latest version wins"); with_allocator(r.allocator(), [&] { logalloc::reclaim_lock l(r); auto m1 = mutation_with_row(ck2); auto e = partition_entry(m1.partition()); auto snap1 = e.read(r, table.schema()); auto m2 = mutation_with_row(ck2); apply(e, m2); partition_version* latest = &*e.version(); partition_version* prev = latest->next(); for (rows_entry& row : prev->partition().clustered_rows()) { row.set_continuous(is_continuous::no); } auto m3 = mutation_with_row(ck1); apply(e, m3); assert_equal(e.squashed(s), (m2 + m3).partition()); // Check that snapshot data is not stolen when its entry is applied auto e2 = partition_entry(mutation_partition(table.schema())); e2.apply_to_incomplete(s, std::move(e), s); assert_equal(snap1->squashed(), m1.partition()); assert_equal(e2.squashed(s), (m2 + m3).partition()); }); }); } SEASTAR_TEST_CASE(test_schema_upgrade_preserves_continuity) { return seastar::async([] { logalloc::region r; simple_schema table; auto new_mutation = [&] { return mutation(table.make_pkey(0), table.schema()); }; auto mutation_with_row = [&] (clustering_key ck) { auto m = new_mutation(); table.add_row(m, ck, "v"); return m; }; // FIXME: There is no assert_that() for mutation_partition auto assert_entry_equal = [&] (schema_ptr e_schema, partition_entry& e, mutation m) { auto key = table.make_pkey(0); assert_that(mutation(e_schema, key, e.squashed(*e_schema))) .is_equal_to(m) .has_same_continuity(m); }; auto apply = [&] (schema_ptr e_schema, partition_entry& e, const mutation& m) { e.apply_to_incomplete(*e_schema, partition_entry(m.partition()), *m.schema()); }; with_allocator(r.allocator(), [&] { logalloc::reclaim_lock l(r); auto m1 = mutation_with_row(table.make_ckey(1)); m1.partition().clustered_rows().begin()->set_continuous(is_continuous::no); m1.partition().set_static_row_continuous(false); m1.partition().ensure_last_dummy(*m1.schema()); auto e = partition_entry(m1.partition()); auto rd1 = e.read(r, table.schema()); auto m2 = mutation_with_row(table.make_ckey(3)); m2.partition().ensure_last_dummy(*m2.schema()); apply(table.schema(), e, m2); auto new_schema = schema_builder(table.schema()).with_column("__new_column", utf8_type).build(); e.upgrade(table.schema(), new_schema); rd1 = {}; assert_entry_equal(new_schema, e, m1 + m2); auto m3 = mutation_with_row(table.make_ckey(2)); apply(new_schema, e, m3); auto m4 = mutation_with_row(table.make_ckey(0)); table.add_static_row(m4, "s_val"); apply(new_schema, e, m4); assert_entry_equal(new_schema, e, m1 + m2 + m3); }); }); } SEASTAR_TEST_CASE(test_full_eviction_marks_affected_range_as_discontinuous) { return seastar::async([] { logalloc::region r; with_allocator(r.allocator(), [&] { logalloc::reclaim_lock l(r); simple_schema table; auto&& s = *table.schema(); auto ck1 = table.make_ckey(1); auto ck2 = table.make_ckey(2); auto e = partition_entry(mutation_partition(table.schema())); auto t = table.new_tombstone(); auto&& p1 = e.open_version(s).partition(); p1.clustered_row(s, ck2); p1.apply(t); auto snap1 = e.read(r, table.schema()); auto&& p2 = e.open_version(s).partition(); p2.clustered_row(s, ck1); auto snap2 = e.read(r, table.schema()); e.evict(); BOOST_REQUIRE(snap1->squashed().fully_discontinuous(s, position_range( position_in_partition::before_all_clustered_rows(), position_in_partition::after_key(ck2) ))); BOOST_REQUIRE(snap2->squashed().fully_discontinuous(s, position_range( position_in_partition::before_all_clustered_rows(), position_in_partition::after_key(ck2) ))); BOOST_REQUIRE(!snap1->squashed().static_row_continuous()); BOOST_REQUIRE(!snap2->squashed().static_row_continuous()); BOOST_REQUIRE_EQUAL(snap1->squashed().partition_tombstone(), t); BOOST_REQUIRE_EQUAL(snap2->squashed().partition_tombstone(), t); }); }); } SEASTAR_TEST_CASE(test_eviction_with_active_reader) { return seastar::async([] { logalloc::region r; with_allocator(r.allocator(), [&] { simple_schema table; auto&& s = *table.schema(); auto ck1 = table.make_ckey(1); auto ck2 = table.make_ckey(2); auto e = partition_entry(mutation_partition(table.schema())); auto&& p1 = e.open_version(s).partition(); p1.clustered_row(s, ck2); p1.ensure_last_dummy(s); // needed by partition_snapshot_row_cursor auto snap1 = e.read(r, table.schema()); auto&& p2 = e.open_version(s).partition(); p2.clustered_row(s, ck1); auto snap2 = e.read(r, table.schema()); partition_snapshot_row_cursor cursor(s, *snap2); cursor.advance_to(position_in_partition_view::before_all_clustered_rows()); BOOST_REQUIRE(cursor.continuous()); BOOST_REQUIRE(cursor.key().equal(s, ck1)); e.evict(); cursor.maybe_refresh(); do { BOOST_REQUIRE(!cursor.continuous()); BOOST_REQUIRE(cursor.dummy()); } while (cursor.next()); }); }); } SEASTAR_TEST_CASE(test_partition_snapshot_row_cursor) { return seastar::async([] { logalloc::region r; with_allocator(r.allocator(), [&] { simple_schema table; auto&& s = *table.schema(); auto e = partition_entry(mutation_partition(table.schema())); auto snap1 = e.read(r, table.schema()); { auto&& p1 = snap1->version()->partition(); p1.clustered_row(s, table.make_ckey(0), is_dummy::no, is_continuous::no); p1.clustered_row(s, table.make_ckey(1), is_dummy::no, is_continuous::no); p1.clustered_row(s, table.make_ckey(2), is_dummy::no, is_continuous::no); p1.clustered_row(s, table.make_ckey(3), is_dummy::no, is_continuous::no); p1.clustered_row(s, table.make_ckey(6), is_dummy::no, is_continuous::no); p1.ensure_last_dummy(s); } auto snap2 = e.read(r, table.schema(), 1); partition_snapshot_row_cursor cur(s, *snap2); position_in_partition::equal_compare eq(s); { logalloc::reclaim_lock rl(r); BOOST_REQUIRE(cur.advance_to(table.make_ckey(0))); BOOST_REQUIRE(eq(cur.position(), table.make_ckey(0))); BOOST_REQUIRE(!cur.continuous()); } r.full_compaction(); { logalloc::reclaim_lock rl(r); BOOST_REQUIRE(cur.maybe_refresh()); BOOST_REQUIRE(eq(cur.position(), table.make_ckey(0))); BOOST_REQUIRE(!cur.continuous()); BOOST_REQUIRE(cur.next()); BOOST_REQUIRE(eq(cur.position(), table.make_ckey(1))); BOOST_REQUIRE(!cur.continuous()); BOOST_REQUIRE(cur.next()); BOOST_REQUIRE(eq(cur.position(), table.make_ckey(2))); BOOST_REQUIRE(!cur.continuous()); } { logalloc::reclaim_lock rl(r); BOOST_REQUIRE(cur.maybe_refresh()); BOOST_REQUIRE(eq(cur.position(), table.make_ckey(2))); BOOST_REQUIRE(!cur.continuous()); } { auto&& p2 = snap2->version()->partition(); p2.clustered_row(s, table.make_ckey(2), is_dummy::no, is_continuous::yes); } { logalloc::reclaim_lock rl(r); BOOST_REQUIRE(cur.maybe_refresh()); BOOST_REQUIRE(eq(cur.position(), table.make_ckey(2))); BOOST_REQUIRE(cur.continuous()); BOOST_REQUIRE(cur.next()); BOOST_REQUIRE(eq(cur.position(), table.make_ckey(3))); BOOST_REQUIRE(!cur.continuous()); } { auto&& p2 = snap2->version()->partition(); p2.clustered_row(s, table.make_ckey(4), is_dummy::no, is_continuous::yes); } { logalloc::reclaim_lock rl(r); BOOST_REQUIRE(cur.maybe_refresh()); BOOST_REQUIRE(eq(cur.position(), table.make_ckey(3))); BOOST_REQUIRE(cur.next()); BOOST_REQUIRE(eq(cur.position(), table.make_ckey(4))); BOOST_REQUIRE(cur.continuous()); BOOST_REQUIRE(cur.next()); BOOST_REQUIRE(eq(cur.position(), table.make_ckey(6))); BOOST_REQUIRE(!cur.continuous()); BOOST_REQUIRE(cur.next()); BOOST_REQUIRE(eq(cur.position(), position_in_partition::after_all_clustered_rows())); BOOST_REQUIRE(cur.continuous()); BOOST_REQUIRE(!cur.next()); } { logalloc::reclaim_lock rl(r); BOOST_REQUIRE(cur.advance_to(table.make_ckey(4))); BOOST_REQUIRE(cur.continuous()); } { logalloc::reclaim_lock rl(r); BOOST_REQUIRE(cur.maybe_refresh()); BOOST_REQUIRE(eq(cur.position(), table.make_ckey(4))); BOOST_REQUIRE(cur.continuous()); } { auto&& p2 = snap2->version()->partition(); p2.clustered_row(s, table.make_ckey(5), is_dummy::no, is_continuous::yes); } { logalloc::reclaim_lock rl(r); BOOST_REQUIRE(cur.maybe_refresh()); BOOST_REQUIRE(eq(cur.position(), table.make_ckey(4))); BOOST_REQUIRE(cur.continuous()); BOOST_REQUIRE(cur.next()); BOOST_REQUIRE(eq(cur.position(), table.make_ckey(5))); BOOST_REQUIRE(cur.continuous()); BOOST_REQUIRE(cur.next()); BOOST_REQUIRE(eq(cur.position(), table.make_ckey(6))); BOOST_REQUIRE(!cur.continuous()); } { logalloc::reclaim_lock rl(r); BOOST_REQUIRE(cur.advance_to(table.make_ckey(4))); BOOST_REQUIRE(cur.continuous()); } e.evict(); { auto&& p2 = snap2->version()->partition(); p2.clustered_row(s, table.make_ckey(5), is_dummy::no, is_continuous::yes); } { logalloc::reclaim_lock rl(r); BOOST_REQUIRE(!cur.maybe_refresh()); BOOST_REQUIRE(eq(cur.position(), table.make_ckey(5))); BOOST_REQUIRE(cur.continuous()); } { logalloc::reclaim_lock rl(r); BOOST_REQUIRE(!cur.advance_to(table.make_ckey(4))); BOOST_REQUIRE(eq(cur.position(), table.make_ckey(5))); BOOST_REQUIRE(cur.continuous()); } { logalloc::reclaim_lock rl(r); BOOST_REQUIRE(cur.maybe_refresh()); BOOST_REQUIRE(eq(cur.position(), table.make_ckey(5))); BOOST_REQUIRE(cur.continuous()); } }); }); } <|endoftext|>
<commit_before>#include "tests/Base.hh" #include "topology/Mesh.hh" #include "topology/MorseSmaleComplex.hh" #include <vector> void test1() { ALEPH_TEST_BEGIN( "Simple mesh"); aleph::topology::Mesh<double> M; M.addVertex( 0.0, 0.0, 0.0 ); M.addVertex( 0.0, 1.0, 0.0 ); M.addVertex( 1.0, 0.0, 0.0 ); M.addVertex( 1.5, 1.0, 0.0 ); std::vector<unsigned> f1 = { 0, 1, 2 }; std::vector<unsigned> f2 = { 2, 1, 3 }; M.addFace( f1.begin(), f1.end() ); M.addFace( f2.begin(), f2.end() ); ALEPH_ASSERT_EQUAL( M.numVertices(), 4 ); ALEPH_ASSERT_EQUAL( M.numFaces() , 2 ); ALEPH_ASSERT_THROW( M.hasEdge(0,1) ); ALEPH_ASSERT_THROW( M.hasEdge(1,0) ); ALEPH_ASSERT_THROW( M.hasEdge(1,2) ); ALEPH_ASSERT_THROW( M.hasEdge(2,1) ); ALEPH_ASSERT_THROW( M.hasEdge(0,2) ); ALEPH_ASSERT_THROW( M.hasEdge(2,0) ); { auto cl = M.closedStar( 0 ); ALEPH_ASSERT_EQUAL( cl.numVertices(), 3 ); ALEPH_ASSERT_EQUAL( cl.numFaces(), 1 ); ALEPH_ASSERT_THROW( cl.hasEdge(0,1) ); ALEPH_ASSERT_THROW( cl.hasEdge(1,0) ); ALEPH_ASSERT_THROW( cl.hasEdge(1,2) ); ALEPH_ASSERT_THROW( cl.hasEdge(2,1) ); ALEPH_ASSERT_THROW( cl.hasEdge(0,2) ); ALEPH_ASSERT_THROW( cl.hasEdge(2,0) ); } ALEPH_TEST_END(); } void test2() { ALEPH_TEST_BEGIN( "More complex mesh" ); aleph::topology::Mesh<double> M; M.addVertex( 0.0, 0.0, 0.0, 0.0 ); M.addVertex( 1.0, 0.0, 0.0, 1.0 ); M.addVertex( 2.0, 0.0, 0.0, 0.0 ); M.addVertex( 0.0, 1.0, 0.0, 1.0 ); M.addVertex( 1.0, 1.0, 0.0, 2.0 ); M.addVertex( 2.0, 1.0, 0.0, 1.0 ); M.addVertex( 0.0, 2.0, 0.0, 0.0 ); M.addVertex( 1.0, 2.0, 0.0, 1.0 ); M.addVertex( 2.0, 2.0, 0.0, 0.0 ); std::vector<unsigned> f1 = { 0, 1, 4, 3 }; std::vector<unsigned> f2 = { 1, 2, 5, 4 }; std::vector<unsigned> f3 = { 4, 5, 8, 7 }; std::vector<unsigned> f4 = { 3, 4, 7, 6 }; M.addFace( f1.begin(), f1.end() ); M.addFace( f2.begin(), f2.end() ); M.addFace( f3.begin(), f3.end() ); M.addFace( f4.begin(), f4.end() ); aleph::topology::MorseSmaleComplex<decltype(M)> msc; msc( M ); ALEPH_TEST_END(); } int main(int, char**) { test1(); test2(); } <commit_msg>Extended tests for meshes<commit_after>#include "tests/Base.hh" #include "topology/Mesh.hh" #include "topology/MorseSmaleComplex.hh" #include <vector> void test1() { ALEPH_TEST_BEGIN( "Simple mesh"); aleph::topology::Mesh<double> M; M.addVertex( 0.0, 0.0, 0.0 ); M.addVertex( 0.0, 1.0, 0.0 ); M.addVertex( 1.0, 0.0, 0.0 ); M.addVertex( 1.5, 1.0, 0.0 ); std::vector<unsigned> f1 = { 0, 1, 2 }; std::vector<unsigned> f2 = { 2, 1, 3 }; M.addFace( f1.begin(), f1.end() ); M.addFace( f2.begin(), f2.end() ); ALEPH_ASSERT_EQUAL( M.numVertices(), 4 ); ALEPH_ASSERT_EQUAL( M.numFaces() , 2 ); ALEPH_ASSERT_THROW( M.hasEdge(0,1) ); ALEPH_ASSERT_THROW( M.hasEdge(1,0) ); ALEPH_ASSERT_THROW( M.hasEdge(1,2) ); ALEPH_ASSERT_THROW( M.hasEdge(2,1) ); ALEPH_ASSERT_THROW( M.hasEdge(0,2) ); ALEPH_ASSERT_THROW( M.hasEdge(2,0) ); { auto cl = M.closedStar( 0 ); auto faces = M.faces(); ALEPH_ASSERT_EQUAL( cl.numVertices(), 3 ); ALEPH_ASSERT_EQUAL( cl.numFaces(), 1 ); ALEPH_ASSERT_THROW( cl.hasEdge(0,1) ); ALEPH_ASSERT_THROW( cl.hasEdge(1,0) ); ALEPH_ASSERT_THROW( cl.hasEdge(1,2) ); ALEPH_ASSERT_THROW( cl.hasEdge(2,1) ); ALEPH_ASSERT_THROW( cl.hasEdge(0,2) ); ALEPH_ASSERT_THROW( cl.hasEdge(2,0) ); ALEPH_ASSERT_EQUAL( faces.front().size(), 3 ); auto v1 = faces.front().at(0); auto v2 = faces.front().at(1); auto v3 = faces.front().at(2); ALEPH_ASSERT_EQUAL( v1, 0 ); ALEPH_ASSERT_EQUAL( v2, 1 ); ALEPH_ASSERT_EQUAL( v3, 2 ); } ALEPH_TEST_END(); } void test2() { ALEPH_TEST_BEGIN( "More complex mesh" ); aleph::topology::Mesh<double> M; M.addVertex( 0.0, 0.0, 0.0, 0.0 ); M.addVertex( 1.0, 0.0, 0.0, 1.0 ); M.addVertex( 2.0, 0.0, 0.0, 0.0 ); M.addVertex( 0.0, 1.0, 0.0, 1.0 ); M.addVertex( 1.0, 1.0, 0.0, 2.0 ); M.addVertex( 2.0, 1.0, 0.0, 1.0 ); M.addVertex( 0.0, 2.0, 0.0, 0.0 ); M.addVertex( 1.0, 2.0, 0.0, 1.0 ); M.addVertex( 2.0, 2.0, 0.0, 0.0 ); std::vector<unsigned> f1 = { 0, 1, 4, 3 }; std::vector<unsigned> f2 = { 1, 2, 5, 4 }; std::vector<unsigned> f3 = { 4, 5, 8, 7 }; std::vector<unsigned> f4 = { 3, 4, 7, 6 }; M.addFace( f1.begin(), f1.end() ); M.addFace( f2.begin(), f2.end() ); M.addFace( f3.begin(), f3.end() ); M.addFace( f4.begin(), f4.end() ); aleph::topology::MorseSmaleComplex<decltype(M)> msc; msc( M ); ALEPH_TEST_END(); } int main(int, char**) { test1(); test2(); } <|endoftext|>
<commit_before>/* * Copyright 2010-2015 Branimir Karadzic. All rights reserved. * License: http://www.opensource.org/licenses/BSD-2-Clause */ #include "test.h" #include <bx/uint32_t.h> TEST(StrideAlign) { CHECK(0 == bx::strideAlign(0, 12) ); for (uint32_t ii = 0; ii < 12; ++ii) { CHECK(12 == bx::strideAlign(ii+1, 12) ); } CHECK(0 == bx::strideAlign16(0, 12) ); for (uint32_t ii = 0; ii < 12; ++ii) { CHECK(48 == bx::strideAlign16(ii+1, 12) ); } CHECK(0 == bx::uint64_cnttz(UINT64_C(1) ) ); CHECK(0 == bx::uint64_cnttz_ref(UINT64_C(1) ) ); CHECK(63 == bx::uint64_cntlz(UINT64_C(1) ) ); CHECK(63 == bx::uint64_cntlz_ref(UINT64_C(1) ) ); } <commit_msg>Updated tests.<commit_after>/* * Copyright 2010-2015 Branimir Karadzic. All rights reserved. * License: http://www.opensource.org/licenses/BSD-2-Clause */ #include "test.h" #include <bx/uint32_t.h> TEST(StrideAlign) { CHECK(0 == bx::strideAlign(0, 12) ); for (uint32_t ii = 0; ii < 12; ++ii) { CHECK(12 == bx::strideAlign(ii+1, 12) ); } CHECK(0 == bx::strideAlign16(0, 12) ); for (uint32_t ii = 0; ii < 12; ++ii) { CHECK(48 == bx::strideAlign16(ii+1, 12) ); } CHECK(0 == bx::uint32_cnttz(UINT32_C(1) ) ); CHECK(0 == bx::uint32_cnttz_ref(UINT32_C(1) ) ); CHECK(31 == bx::uint32_cntlz(UINT32_C(1) ) ); CHECK(31 == bx::uint32_cntlz_ref(UINT32_C(1) ) ); CHECK(0 == bx::uint64_cnttz(UINT64_C(1) ) ); CHECK(0 == bx::uint64_cnttz_ref(UINT64_C(1) ) ); CHECK(63 == bx::uint64_cntlz(UINT64_C(1) ) ); CHECK(63 == bx::uint64_cntlz_ref(UINT64_C(1) ) ); } <|endoftext|>
<commit_before>/****************************************************************************** * This file is part of the Gluon Development Platform * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl> * Copyright (C) 2010 Dan Leinir Turthra Jensen <admin@leinir.dk> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "game.h" #include "gameprivate.h" #include "scene.h" #include "gameobject.h" #include "gameproject.h" #include "core/debughelper.h" #include <QtCore/QCoreApplication> #include <QtCore/QThread> #include <QtCore/QTime> #include <QtCore/QDebug> #include <QTimer> using namespace GluonEngine; GLUON_DEFINE_SINGLETON(Game) class I : public QThread { public: static void sleep( unsigned long secs ) { QThread::sleep( secs ); } static void msleep( unsigned long msecs ) { QThread::msleep( msecs ); } static void usleep( unsigned long usecs ) { QThread::usleep( usecs ); } }; Game::Game( QObject* parent ) { Q_UNUSED( parent ) d = new GamePrivate; qsrand(QTime(0,0,0).secsTo(QTime::currentTime())); } Game::~Game() { if( d->gameRunning ) stopGame(); } int Game::getCurrentTick() { return d->time.elapsed(); } void Game::runGameFixedUpdate( int updatesPerSecond, int maxFrameSkip ) { DEBUG_FUNC_NAME // Bail out if we're not fed a level to work with! if( !d->currentScene ) { DEBUG_TEXT( QString( "There is no scene to run!" ) ); return; } int millisecondsPerUpdate = 1000 / updatesPerSecond; DEBUG_TEXT( QString( "Running the game using fixed update at %1 updates per second (meaning %2 milliseconds between each update, and drawing as often as possible, with a maximum of %3 frames skipped before forcing a draw)" ).arg( updatesPerSecond ).arg( millisecondsPerUpdate ).arg( maxFrameSkip ) ); int nextTick = 0, loops = 0; int timeLapse = 0; d->time.start(); d->gameRunning = true; initializeAll(); // First allow everybody to initialize themselves properly startAll(); while( d->gameRunning ) { // Don't block everything... QCoreApplication::processEvents(); // Only update every updatesPerSecond times per second, but draw the scene as often as we can force it to loops = 0; while( getCurrentTick() > nextTick && loops < maxFrameSkip ) { if( !d->gamePaused ) { updateAll( millisecondsPerUpdate ); } nextTick += millisecondsPerUpdate; loops++; } timeLapse = ( getCurrentTick() + millisecondsPerUpdate - nextTick ) / millisecondsPerUpdate; drawAll( timeLapse ); } stopAll(); cleanupAll(); } void Game::runGameFixedTimestep( int framesPerSecond ) { DEBUG_FUNC_NAME // Bail out if we're not fed a level to work with! if( !d->currentScene ) { DEBUG_TEXT( QString( "There is no scene to run!" ) ); return; } int millisecondsPerUpdate = 1000 / framesPerSecond; DEBUG_TEXT( QString( "Running the game using fixed timestep at %1 frames per second (meaning %2 milliseconds between each update and draw)" ).arg( framesPerSecond ).arg( millisecondsPerUpdate ) ); int remainingSleep = 0; int nextTick = 0; d->time.start(); d->gameRunning = true; initializeAll(); // First allow everybody to initialize themselves properly startAll(); while( d->gameRunning ) { // Don't block everything... QCoreApplication::processEvents(); // Update the current level if( !d->gamePaused ) { updateAll( millisecondsPerUpdate ); } // Do drawing drawAll(); nextTick += millisecondsPerUpdate; remainingSleep = nextTick - this->getCurrentTick(); if( remainingSleep > 0 ) { DEBUG_TEXT( QString( "Sleeping for %1 milliseconds" ).arg( remainingSleep ) ) I::msleep( remainingSleep ); } else { // Oh buggery, we're falling behind... can we fix this in a generic manner? Or do we just allow for falling behind... DEBUG_TEXT( tr( "Gameloop has fallen behind by %1 milliseconds" ).arg( remainingSleep ) ) } } stopAll(); cleanupAll(); } void Game::stopGame() { DEBUG_BLOCK DEBUG_TEXT( QString( "Stopping gameloop" ) ) d->gameRunning = false; } void Game::setPause( bool pause ) { DEBUG_BLOCK if( pause ) { DEBUG_TEXT( QString( "Pausing gameloop" ) ) } else { DEBUG_TEXT( QString( "Un-pausing gameloop" ) ) } d->gamePaused = pause; } void Game::initializeAll() { d->currentScene->sceneContents()->initialize(); emit initialized(); } void Game::startAll() { d->currentScene->sceneContents()->start(); emit started(); } void Game::drawAll( int time ) { d->currentScene->sceneContents()->draw( time ); emit painted( time ); } void Game::updateAll( int time ) { d->currentScene->sceneContents()->update( time ); emit updated( time ); } void Game::stopAll() { d->currentScene->sceneContents()->stop(); emit stopped(); } void Game::cleanupAll() { d->currentScene->sceneContents()->cleanup(); emit cleaned(); } float Game::random() { return qrand() / float( RAND_MAX ); } /****************************************************************************** * Property Getter-setters *****************************************************************************/ Scene * Game::currentScene() const { return d->currentScene; } bool Game::isRunning() const { return d->gameRunning; } bool Game::isPaused() const { return d->gamePaused; } void Game::setCurrentScene( Scene* newCurrentScene ) { if( d->currentScene ) { stopAll(); cleanupAll(); } QList<const GluonCore::GluonObject*> objects = d->listAllChildren( d->currentScene ); foreach( const GluonCore::GluonObject * child, objects ) { disconnect( child, SIGNAL( showDebug( const QString& ) ), this, SIGNAL( showDebug( const QString& ) ) ); } d->currentScene = newCurrentScene; if( d->gameRunning ) { initializeAll(); startAll(); } objects = d->listAllChildren( newCurrentScene->sceneContents() ); foreach( const GluonCore::GluonObject * child, objects ) { connect( child, SIGNAL( showDebug( const QString& ) ), SIGNAL( showDebug( const QString& ) ) ); } emit currentSceneChanged( newCurrentScene ); } void Game::setCurrentScene( const QString& sceneName ) { Scene* scene = qobject_cast< GluonEngine::Scene* >( gameProject()->findItemByName( sceneName ) ); if( scene ) setCurrentScene( scene ); } void Game::resetCurrentScene() { if( d->currentScene ) { QTimer::singleShot(0, d->currentScene, SLOT(resetScene())); } } GluonEngine::GameProject * Game::gameProject() const { return d->gameProject; } void Game::setGameProject( GluonEngine::GameProject* newGameProject ) { DEBUG_FUNC_NAME if( d->gameProject ) { if( d->currentScene ) { stopAll(); cleanupAll(); } delete d->gameProject; } d->gameProject = newGameProject; if( !d->gameProject ) return; if( !d->gameProject->entryPoint() ) { DEBUG_TEXT( QString( "Entry point invalid, attempting to salvage" ) ) Scene* scene = GamePrivate::findSceneInChildren( d->gameProject ); if( scene ) { d->gameProject->setEntryPoint( scene ); DEBUG_TEXT( QString( "Entry point salvaged by resetting to first Scene in project - %1" ).arg( scene->fullyQualifiedName() ) ) } } if( d->gameProject->entryPoint() ) { DEBUG_TEXT( QString( "Set the gameproject to %1 with the entry point %2" ).arg( d->gameProject->name() ).arg( d->gameProject->entryPoint()->name() ) ) } else { DEBUG_TEXT( QString( "Somehow we have got here with no entrypoint... This is very, very wrong!" ) ) } d->currentScene = d->gameProject->entryPoint(); emit currentProjectChanged( d->gameProject ); emit currentSceneChanged( d->currentScene ); } GameObject* Game::getFromScene( const QString& name ) { return d->currentScene->sceneContents()->childGameObject( name ); } GameObject* Game::clone( GameObject* obj ) { if( obj ) { GameObject* objClone = qobject_cast<GameObject*>( obj->clone() ); QList<const GluonCore::GluonObject*> objects = d->listAllChildren( objClone ); foreach( const GluonCore::GluonObject * child, objects ) { connect( child, SIGNAL( showDebug( const QString& ) ), SIGNAL( showDebug( const QString& ) ) ); } return objClone; } return 0; } #include "game.moc" <commit_msg>Engine: Cleanup before starting so that we always initialize when starting.<commit_after>/****************************************************************************** * This file is part of the Gluon Development Platform * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl> * Copyright (C) 2010 Dan Leinir Turthra Jensen <admin@leinir.dk> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "game.h" #include "gameprivate.h" #include "scene.h" #include "gameobject.h" #include "gameproject.h" #include "core/debughelper.h" #include <QtCore/QCoreApplication> #include <QtCore/QThread> #include <QtCore/QTime> #include <QtCore/QDebug> #include <QTimer> using namespace GluonEngine; GLUON_DEFINE_SINGLETON(Game) class I : public QThread { public: static void sleep( unsigned long secs ) { QThread::sleep( secs ); } static void msleep( unsigned long msecs ) { QThread::msleep( msecs ); } static void usleep( unsigned long usecs ) { QThread::usleep( usecs ); } }; Game::Game( QObject* parent ) { Q_UNUSED( parent ) d = new GamePrivate; qsrand(QTime(0,0,0).secsTo(QTime::currentTime())); } Game::~Game() { if( d->gameRunning ) stopGame(); } int Game::getCurrentTick() { return d->time.elapsed(); } void Game::runGameFixedUpdate( int updatesPerSecond, int maxFrameSkip ) { DEBUG_FUNC_NAME // Bail out if we're not fed a level to work with! if( !d->currentScene ) { DEBUG_TEXT( QString( "There is no scene to run!" ) ); return; } //Clean any traces of existing objects. stopAll(); cleanupAll();; int millisecondsPerUpdate = 1000 / updatesPerSecond; DEBUG_TEXT( QString( "Running the game using fixed update at %1 updates per second (meaning %2 milliseconds between each update, and drawing as often as possible, with a maximum of %3 frames skipped before forcing a draw)" ).arg( updatesPerSecond ).arg( millisecondsPerUpdate ).arg( maxFrameSkip ) ); int nextTick = 0, loops = 0; int timeLapse = 0; d->time.start(); d->gameRunning = true; initializeAll(); // First allow everybody to initialize themselves properly startAll(); while( d->gameRunning ) { // Don't block everything... QCoreApplication::processEvents(); // Only update every updatesPerSecond times per second, but draw the scene as often as we can force it to loops = 0; while( getCurrentTick() > nextTick && loops < maxFrameSkip ) { if( !d->gamePaused ) { updateAll( millisecondsPerUpdate ); } nextTick += millisecondsPerUpdate; loops++; } timeLapse = ( getCurrentTick() + millisecondsPerUpdate - nextTick ) / millisecondsPerUpdate; drawAll( timeLapse ); } stopAll(); cleanupAll(); } void Game::runGameFixedTimestep( int framesPerSecond ) { DEBUG_FUNC_NAME // Bail out if we're not fed a level to work with! if( !d->currentScene ) { DEBUG_TEXT( QString( "There is no scene to run!" ) ); return; } int millisecondsPerUpdate = 1000 / framesPerSecond; DEBUG_TEXT( QString( "Running the game using fixed timestep at %1 frames per second (meaning %2 milliseconds between each update and draw)" ).arg( framesPerSecond ).arg( millisecondsPerUpdate ) ); int remainingSleep = 0; int nextTick = 0; d->time.start(); d->gameRunning = true; initializeAll(); // First allow everybody to initialize themselves properly startAll(); while( d->gameRunning ) { // Don't block everything... QCoreApplication::processEvents(); // Update the current level if( !d->gamePaused ) { updateAll( millisecondsPerUpdate ); } // Do drawing drawAll(); nextTick += millisecondsPerUpdate; remainingSleep = nextTick - this->getCurrentTick(); if( remainingSleep > 0 ) { DEBUG_TEXT( QString( "Sleeping for %1 milliseconds" ).arg( remainingSleep ) ) I::msleep( remainingSleep ); } else { // Oh buggery, we're falling behind... can we fix this in a generic manner? Or do we just allow for falling behind... DEBUG_TEXT( tr( "Gameloop has fallen behind by %1 milliseconds" ).arg( remainingSleep ) ) } } stopAll(); cleanupAll(); } void Game::stopGame() { DEBUG_BLOCK DEBUG_TEXT( QString( "Stopping gameloop" ) ) d->gameRunning = false; } void Game::setPause( bool pause ) { DEBUG_BLOCK if( pause ) { DEBUG_TEXT( QString( "Pausing gameloop" ) ) } else { DEBUG_TEXT( QString( "Un-pausing gameloop" ) ) } d->gamePaused = pause; } void Game::initializeAll() { d->currentScene->sceneContents()->initialize(); emit initialized(); } void Game::startAll() { d->currentScene->sceneContents()->start(); emit started(); } void Game::drawAll( int time ) { d->currentScene->sceneContents()->draw( time ); emit painted( time ); } void Game::updateAll( int time ) { d->currentScene->sceneContents()->update( time ); emit updated( time ); } void Game::stopAll() { d->currentScene->sceneContents()->stop(); emit stopped(); } void Game::cleanupAll() { d->currentScene->sceneContents()->cleanup(); emit cleaned(); } float Game::random() { return qrand() / float( RAND_MAX ); } /****************************************************************************** * Property Getter-setters *****************************************************************************/ Scene * Game::currentScene() const { return d->currentScene; } bool Game::isRunning() const { return d->gameRunning; } bool Game::isPaused() const { return d->gamePaused; } void Game::setCurrentScene( Scene* newCurrentScene ) { if( d->currentScene ) { stopAll(); cleanupAll(); } QList<const GluonCore::GluonObject*> objects = d->listAllChildren( d->currentScene ); foreach( const GluonCore::GluonObject * child, objects ) { disconnect( child, SIGNAL( showDebug( const QString& ) ), this, SIGNAL( showDebug( const QString& ) ) ); } d->currentScene = newCurrentScene; if( d->gameRunning ) { initializeAll(); startAll(); } objects = d->listAllChildren( newCurrentScene->sceneContents() ); foreach( const GluonCore::GluonObject * child, objects ) { connect( child, SIGNAL( showDebug( const QString& ) ), SIGNAL( showDebug( const QString& ) ) ); } emit currentSceneChanged( newCurrentScene ); } void Game::setCurrentScene( const QString& sceneName ) { Scene* scene = qobject_cast< GluonEngine::Scene* >( gameProject()->findItemByName( sceneName ) ); if( scene ) setCurrentScene( scene ); } void Game::resetCurrentScene() { if( d->currentScene ) { QTimer::singleShot(0, d->currentScene, SLOT(resetScene())); } } GluonEngine::GameProject * Game::gameProject() const { return d->gameProject; } void Game::setGameProject( GluonEngine::GameProject* newGameProject ) { DEBUG_FUNC_NAME if( d->gameProject ) { if( d->currentScene ) { stopAll(); cleanupAll(); } delete d->gameProject; } d->gameProject = newGameProject; if( !d->gameProject ) return; if( !d->gameProject->entryPoint() ) { DEBUG_TEXT( QString( "Entry point invalid, attempting to salvage" ) ) Scene* scene = GamePrivate::findSceneInChildren( d->gameProject ); if( scene ) { d->gameProject->setEntryPoint( scene ); DEBUG_TEXT( QString( "Entry point salvaged by resetting to first Scene in project - %1" ).arg( scene->fullyQualifiedName() ) ) } } if( d->gameProject->entryPoint() ) { DEBUG_TEXT( QString( "Set the gameproject to %1 with the entry point %2" ).arg( d->gameProject->name() ).arg( d->gameProject->entryPoint()->name() ) ) } else { DEBUG_TEXT( QString( "Somehow we have got here with no entrypoint... This is very, very wrong!" ) ) } d->currentScene = d->gameProject->entryPoint(); emit currentProjectChanged( d->gameProject ); emit currentSceneChanged( d->currentScene ); } GameObject* Game::getFromScene( const QString& name ) { return d->currentScene->sceneContents()->childGameObject( name ); } GameObject* Game::clone( GameObject* obj ) { if( obj ) { GameObject* objClone = qobject_cast<GameObject*>( obj->clone() ); QList<const GluonCore::GluonObject*> objects = d->listAllChildren( objClone ); foreach( const GluonCore::GluonObject * child, objects ) { connect( child, SIGNAL( showDebug( const QString& ) ), SIGNAL( showDebug( const QString& ) ) ); } return objClone; } return 0; } #include "game.moc" <|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #define MAX 0x100 struct TStack { int stack[MAX]; int next; }; // todo: Protect the stack from pushing data beyond MAX. void push(int value, struct TStack *store){ // store.stack[(*store).next++] = value; store->stack[store->next++] = value; } // todo: Protect the stack from poping data below 0. int pop(struct TStack *store){ return store->stack[--store->next]; } void muestra(struct TStack data, const char *title){ printf("Stack: %s\n\n", title); for(int i=0; i<data.next; i++) printf("%i ", data.stack[i]); printf("\n"); } int main(int argc, char *argv[]){ struct TStack student; struct TStack league_results; student.next = 0; league_results.next = 0; push(3, &student); push(4, &league_results); push(7, &student); printf("He sacado de student un %i: \n", pop(&student)); push(5, &student); muestra(student, "student"); muestra(league_results, "League Results"); return EXIT_SUCCESS; } /* * (*store).next == store->next */ <commit_msg>Delete stack.cpp<commit_after><|endoftext|>
<commit_before>#include "GLFramebuffer.h" #include "de/hackcraft/opengl/GL.h" unsigned int GLFramebuffer::getFramebuffer() { return framebuffer; } unsigned int GLFramebuffer::getColorbuffer() { return colorbuffer; } unsigned int GLFramebuffer::getDepthbuffer() { return depthbuffer; } unsigned int GLFramebuffer::getWidth() { return width; } unsigned int GLFramebuffer::getHeight() { return height; } void GLFramebuffer::initBuffers(int w, int h) { this->width = w; this->height = h; unsigned int colorbuffer; unsigned int depthbuffer; unsigned int framebuffer; void* undefinedTexels = NULL; // Generate and initialize color-buffer. GL::glGenTextures(1, &colorbuffer); GL::glBindTexture(GL_TEXTURE_2D, colorbuffer); GL::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); GL::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); GL::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); GL::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); GL::glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_BGRA, GL_UNSIGNED_BYTE, undefinedTexels); GL::glGenerateMipmapEXT(GL_TEXTURE_2D); // Generate and initialize depth-buffer. GL::glGenTextures(1, &depthbuffer); GL::glBindTexture(GL_TEXTURE_2D, depthbuffer); GL::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); GL::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); GL::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); GL::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); GL::glTexParameteri(GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE, GL_INTENSITY); GL::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE); GL::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL); GL::glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, w, h, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, undefinedTexels); GL::glGenerateMipmapEXT(GL_TEXTURE_2D); // Generate frame-buffer and attach color- and depth-buffer. GL::glGenFramebuffersEXT(1, &framebuffer); GL::glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, framebuffer); GL::glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, colorbuffer, 0/*mipmap level*/); GL::glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, depthbuffer, 0/*mipmap level*/); this->colorbuffer = colorbuffer; this->depthbuffer = depthbuffer; this->framebuffer = framebuffer; //Does the GPU support current FBO configuration? GL::GLenum status; status = GL::glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); if (status != GL_FRAMEBUFFER_COMPLETE_EXT) { throw "Could not initialize frame-buffer."; } } void GLFramebuffer::bindBuffers() { GL::glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, framebuffer); } void GLFramebuffer::unbindBuffers() { GL::glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); } void GLFramebuffer::cleanBuffers() { //Delete resources GL::glDeleteTextures(1, &colorbuffer); GL::glDeleteTextures(1, &depthbuffer); //Bind 0, which means render to back buffer, as a result, fb is unbound GL::glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); GL::glDeleteFramebuffersEXT(1, &framebuffer); } <commit_msg>GLFramebuffer: Re-enable builtin frame-buffer after initialization.<commit_after>#include "GLFramebuffer.h" #include "de/hackcraft/opengl/GL.h" unsigned int GLFramebuffer::getFramebuffer() { return framebuffer; } unsigned int GLFramebuffer::getColorbuffer() { return colorbuffer; } unsigned int GLFramebuffer::getDepthbuffer() { return depthbuffer; } unsigned int GLFramebuffer::getWidth() { return width; } unsigned int GLFramebuffer::getHeight() { return height; } void GLFramebuffer::initBuffers(int w, int h) { this->width = w; this->height = h; unsigned int colorbuffer; unsigned int depthbuffer; unsigned int framebuffer; void* undefinedTexels = NULL; // Generate and initialize color-buffer. GL::glGenTextures(1, &colorbuffer); GL::glBindTexture(GL_TEXTURE_2D, colorbuffer); GL::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); GL::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); GL::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); GL::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); GL::glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_BGRA, GL_UNSIGNED_BYTE, undefinedTexels); GL::glGenerateMipmapEXT(GL_TEXTURE_2D); // Generate and initialize depth-buffer. GL::glGenTextures(1, &depthbuffer); GL::glBindTexture(GL_TEXTURE_2D, depthbuffer); GL::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); GL::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); GL::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); GL::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); GL::glTexParameteri(GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE, GL_INTENSITY); GL::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE); GL::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL); GL::glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, w, h, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, undefinedTexels); GL::glGenerateMipmapEXT(GL_TEXTURE_2D); // Generate frame-buffer and attach color- and depth-buffer. GL::glGenFramebuffersEXT(1, &framebuffer); GL::glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, framebuffer); GL::glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, colorbuffer, 0/*mipmap level*/); GL::glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, depthbuffer, 0/*mipmap level*/); this->colorbuffer = colorbuffer; this->depthbuffer = depthbuffer; this->framebuffer = framebuffer; //Does the GPU support current FBO configuration? GL::GLenum status; status = GL::glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); if (status != GL_FRAMEBUFFER_COMPLETE_EXT) { throw "Could not initialize frame-buffer."; } // Switch back to normal builtin frame buffer for now. GL::glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); } void GLFramebuffer::bindBuffers() { GL::glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, framebuffer); } void GLFramebuffer::unbindBuffers() { GL::glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); } void GLFramebuffer::cleanBuffers() { //Delete resources GL::glDeleteTextures(1, &colorbuffer); GL::glDeleteTextures(1, &depthbuffer); //Bind 0, which means render to back buffer, as a result, fb is unbound GL::glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); GL::glDeleteFramebuffersEXT(1, &framebuffer); } <|endoftext|>
<commit_before>#include <idmlib/resys/incremcf/IncrementalItemCF.h> #include <util/PriorityQueue.h> #include <map> #include <algorithm> #include <cmath> // for sqrt #include <glog/logging.h> namespace { struct QueueItem { QueueItem(uint32_t itemId = 0, float weight = 0) :itemId_(itemId) ,weight_(weight) {} uint32_t itemId_; float weight_; }; class TopItemsQueue :public izenelib::util::PriorityQueue<QueueItem> { public: TopItemsQueue(size_t size) { this->initialize(size); } protected: bool lessThan( QueueItem o1, QueueItem o2 ) { return (o1.weight_ < o2.weight_); } }; // map from candidate item to reason items typedef std::map<uint32_t, std::vector<uint32_t> > ItemReasonMap; void getRecommendItemFromQueue( TopItemsQueue& queue, ItemReasonMap& reasonMap, idmlib::recommender::RecommendItemVec& recItems ) { recItems.resize(queue.size()); for(idmlib::recommender::RecommendItemVec::reverse_iterator rit = recItems.rbegin(); rit != recItems.rend(); ++rit) { QueueItem queueItem = queue.pop(); rit->itemId_ = queueItem.itemId_; rit->weight_ = queueItem.weight_; rit->reasonItemIds_.swap(reasonMap[queueItem.itemId_]); } } } NS_IDMLIB_RESYS_BEGIN IncrementalItemCF::IncrementalItemCF( const std::string& covisit_path, size_t covisit_row_cache_size, const std::string& item_item_similarity_path, size_t similarity_row_cache_size, const std::string& item_neighbor_path, size_t topK ) : covisitation_(covisit_path, covisit_row_cache_size) , similarity_(item_item_similarity_path,similarity_row_cache_size,item_neighbor_path,topK) { } IncrementalItemCF::~IncrementalItemCF() { } void IncrementalItemCF::updateMatrix( const std::list<uint32_t>& oldItems, const std::list<uint32_t>& newItems ) { updateVisitMatrix(oldItems, newItems); updateSimMatrix_(newItems); } void IncrementalItemCF::updateVisitMatrix( const std::list<uint32_t>& oldItems, const std::list<uint32_t>& newItems ) { covisitation_.visit(oldItems, newItems); } void IncrementalItemCF::buildSimMatrix() { LOG(INFO) << "start building similarity matrix..."; // empty set used to call updateSimRow_() std::set<uint32_t> rowSet; std::set<uint32_t> colSet; int rowNum = 0; for (ItemCoVisitation<CoVisitFreq>::iterator it_i = covisitation_.begin(); it_i != covisitation_.end(); ++it_i) { if (++rowNum % 1000 == 0) { std::cout << "\rbuilding row num: " << rowNum << std::flush; } const uint32_t row = it_i->first; const CoVisitRow& cols = it_i->second; updateSimRow_(row, cols, false, rowSet, colSet); } std::cout << "\rbuilding row num: " << rowNum << std::endl; LOG(INFO) << "finish building similarity matrix"; } void IncrementalItemCF::updateSimRow_( uint32_t row, const CoVisitRow& coVisitRow, bool isUpdateCol, const std::set<uint32_t>& rowSet, std::set<uint32_t>& colSet ) { uint32_t visit_i_i = 0; CoVisitRow::const_iterator findIt = coVisitRow.find(row); if (findIt != coVisitRow.end()) { visit_i_i = findIt->second.freq; } SimRow simRow; for (CoVisitRow::const_iterator it_j = coVisitRow.begin(); it_j != coVisitRow.end(); ++it_j) { const uint32_t col = it_j->first; // no similarity value on diagonal line if (row == col) continue; const uint32_t visit_i_j = it_j->second.freq; const uint32_t visit_j_j = covisitation_.coeff(col, col); assert(visit_i_j && visit_i_i && visit_j_j && "the freq value in visit matrix should be positive."); float sim = (float)visit_i_j / sqrt(visit_i_i * visit_j_j); simRow[col] = sim; // also update (col, row) if col does not exist in rowSet if (isUpdateCol && rowSet.find(col) == rowSet.end()) { similarity_.coeff(col, row, sim); colSet.insert(col); } } similarity_.updateRowItems(row, simRow); similarity_.loadNeighbor(row); } void IncrementalItemCF::updateSimMatrix_(const std::list<uint32_t>& rows) { std::set<uint32_t> rowSet(rows.begin(), rows.end()); std::set<uint32_t> colSet; for (std::list<uint32_t>::const_iterator it_i = rows.begin(); it_i != rows.end(); ++it_i) { uint32_t row = *it_i; boost::shared_ptr<const CoVisitRow> cols = covisitation_.rowItems(row); updateSimRow_(row, *cols, true, rowSet, colSet); } // update neighbor for col items for (std::set<uint32_t>::const_iterator it = colSet.begin(); it != colSet.end(); ++it) { similarity_.loadNeighbor(*it); } } void IncrementalItemCF::recommend( int howMany, const std::vector<uint32_t>& visitItems, RecommendItemVec& recItems, ItemRescorer* rescorer ) { std::set<uint32_t> visitSet(visitItems.begin(), visitItems.end()); std::set<uint32_t>::const_iterator visitSetEnd = visitSet.end(); // get candidate items which has similarity value with items std::set<uint32_t> candidateSet; for (std::set<uint32_t>::const_iterator it_i = visitSet.begin(); it_i != visitSetEnd; ++it_i) { getRowItems_(*it_i, candidateSet); } ItemReasonMap reasonMap; TopItemsQueue queue(howMany); for (std::set<uint32_t>::const_iterator it = candidateSet.begin(); it != candidateSet.end(); ++it) { uint32_t itemId = *it; if(visitSet.find(itemId) == visitSetEnd && (!rescorer || !rescorer->isFiltered(itemId))) { float weight = similarity_.weight(itemId, visitSet, reasonMap[itemId]); if(weight > 0) { queue.insert(QueueItem(itemId, weight)); } } } getRecommendItemFromQueue(queue, reasonMap, recItems); } void IncrementalItemCF::recommend( int howMany, const ItemWeightMap& visitItemWeights, RecommendItemVec& recItems, ItemRescorer* rescorer ) { // get candidate items which has positive weight and similarity value std::set<uint32_t> candidateSet; ItemWeightMap::const_iterator visitWeightsEnd = visitItemWeights.end(); for (ItemWeightMap::const_iterator it_i = visitItemWeights.begin(); it_i != visitWeightsEnd; ++it_i) { if (it_i->second > 0) getRowItems_(it_i->first, candidateSet); } ItemReasonMap reasonMap; TopItemsQueue queue(howMany); for (std::set<uint32_t>::const_iterator it = candidateSet.begin(); it != candidateSet.end(); ++it) { uint32_t itemId = *it; if(visitItemWeights.find(itemId) == visitWeightsEnd && (!rescorer || !rescorer->isFiltered(itemId))) { float weight = similarity_.weight(itemId, visitItemWeights, reasonMap[itemId]); if(weight > 0) { queue.insert(QueueItem(itemId, weight)); } } } getRecommendItemFromQueue(queue, reasonMap, recItems); } void IncrementalItemCF::getRowItems_( uint32_t row, std::set<uint32_t>& items ) { boost::shared_ptr<const SimRow> cols = similarity_.rowItems(row); for (SimRow::const_iterator it_j = cols->begin(); it_j != cols->end(); ++it_j) { uint32_t col = it_j->first; assert(col != row && "there should be no similarity value on diagonal line!"); items.insert(col); } } void IncrementalItemCF::flush() { covisitation_.flush(); similarity_.flush(); } NS_IDMLIB_RESYS_END <commit_msg>print covisit matrix density in IncrementalItemCF::buildSimMatrix().<commit_after>#include <idmlib/resys/incremcf/IncrementalItemCF.h> #include <util/PriorityQueue.h> #include <map> #include <algorithm> #include <cmath> // for sqrt #include <glog/logging.h> namespace { struct QueueItem { QueueItem(uint32_t itemId = 0, float weight = 0) :itemId_(itemId) ,weight_(weight) {} uint32_t itemId_; float weight_; }; class TopItemsQueue :public izenelib::util::PriorityQueue<QueueItem> { public: TopItemsQueue(size_t size) { this->initialize(size); } protected: bool lessThan( QueueItem o1, QueueItem o2 ) { return (o1.weight_ < o2.weight_); } }; // map from candidate item to reason items typedef std::map<uint32_t, std::vector<uint32_t> > ItemReasonMap; void getRecommendItemFromQueue( TopItemsQueue& queue, ItemReasonMap& reasonMap, idmlib::recommender::RecommendItemVec& recItems ) { recItems.resize(queue.size()); for(idmlib::recommender::RecommendItemVec::reverse_iterator rit = recItems.rbegin(); rit != recItems.rend(); ++rit) { QueueItem queueItem = queue.pop(); rit->itemId_ = queueItem.itemId_; rit->weight_ = queueItem.weight_; rit->reasonItemIds_.swap(reasonMap[queueItem.itemId_]); } } } NS_IDMLIB_RESYS_BEGIN IncrementalItemCF::IncrementalItemCF( const std::string& covisit_path, size_t covisit_row_cache_size, const std::string& item_item_similarity_path, size_t similarity_row_cache_size, const std::string& item_neighbor_path, size_t topK ) : covisitation_(covisit_path, covisit_row_cache_size) , similarity_(item_item_similarity_path,similarity_row_cache_size,item_neighbor_path,topK) { } IncrementalItemCF::~IncrementalItemCF() { } void IncrementalItemCF::updateMatrix( const std::list<uint32_t>& oldItems, const std::list<uint32_t>& newItems ) { updateVisitMatrix(oldItems, newItems); updateSimMatrix_(newItems); } void IncrementalItemCF::updateVisitMatrix( const std::list<uint32_t>& oldItems, const std::list<uint32_t>& newItems ) { covisitation_.visit(oldItems, newItems); } void IncrementalItemCF::buildSimMatrix() { LOG(INFO) << "start building similarity matrix..."; // empty set used to call updateSimRow_() std::set<uint32_t> rowSet; std::set<uint32_t> colSet; int rowNum = 0; uint64_t elemNum = 0; for (ItemCoVisitation<CoVisitFreq>::iterator it_i = covisitation_.begin(); it_i != covisitation_.end(); ++it_i) { if (++rowNum % 1000 == 0) { std::cout << "\rbuilding row num: " << rowNum << std::flush; } const uint32_t row = it_i->first; const CoVisitRow& cols = it_i->second; elemNum += cols.size(); updateSimRow_(row, cols, false, rowSet, colSet); } std::cout << "\rbuilding row num: " << rowNum << std::endl; float density = 0; if (rowNum) { density = (float)elemNum / (rowNum*rowNum) * 100; } LOG(INFO) << "covisit matrix element num: " << elemNum; LOG(INFO) << "covisit matrix density: " << density << "%"; LOG(INFO) << "finish building similarity matrix"; } void IncrementalItemCF::updateSimRow_( uint32_t row, const CoVisitRow& coVisitRow, bool isUpdateCol, const std::set<uint32_t>& rowSet, std::set<uint32_t>& colSet ) { uint32_t visit_i_i = 0; CoVisitRow::const_iterator findIt = coVisitRow.find(row); if (findIt != coVisitRow.end()) { visit_i_i = findIt->second.freq; } SimRow simRow; for (CoVisitRow::const_iterator it_j = coVisitRow.begin(); it_j != coVisitRow.end(); ++it_j) { const uint32_t col = it_j->first; // no similarity value on diagonal line if (row == col) continue; const uint32_t visit_i_j = it_j->second.freq; const uint32_t visit_j_j = covisitation_.coeff(col, col); assert(visit_i_j && visit_i_i && visit_j_j && "the freq value in visit matrix should be positive."); float sim = (float)visit_i_j / sqrt(visit_i_i * visit_j_j); simRow[col] = sim; // also update (col, row) if col does not exist in rowSet if (isUpdateCol && rowSet.find(col) == rowSet.end()) { similarity_.coeff(col, row, sim); colSet.insert(col); } } similarity_.updateRowItems(row, simRow); similarity_.loadNeighbor(row); } void IncrementalItemCF::updateSimMatrix_(const std::list<uint32_t>& rows) { std::set<uint32_t> rowSet(rows.begin(), rows.end()); std::set<uint32_t> colSet; for (std::list<uint32_t>::const_iterator it_i = rows.begin(); it_i != rows.end(); ++it_i) { uint32_t row = *it_i; boost::shared_ptr<const CoVisitRow> cols = covisitation_.rowItems(row); updateSimRow_(row, *cols, true, rowSet, colSet); } // update neighbor for col items for (std::set<uint32_t>::const_iterator it = colSet.begin(); it != colSet.end(); ++it) { similarity_.loadNeighbor(*it); } } void IncrementalItemCF::recommend( int howMany, const std::vector<uint32_t>& visitItems, RecommendItemVec& recItems, ItemRescorer* rescorer ) { std::set<uint32_t> visitSet(visitItems.begin(), visitItems.end()); std::set<uint32_t>::const_iterator visitSetEnd = visitSet.end(); // get candidate items which has similarity value with items std::set<uint32_t> candidateSet; for (std::set<uint32_t>::const_iterator it_i = visitSet.begin(); it_i != visitSetEnd; ++it_i) { getRowItems_(*it_i, candidateSet); } ItemReasonMap reasonMap; TopItemsQueue queue(howMany); for (std::set<uint32_t>::const_iterator it = candidateSet.begin(); it != candidateSet.end(); ++it) { uint32_t itemId = *it; if(visitSet.find(itemId) == visitSetEnd && (!rescorer || !rescorer->isFiltered(itemId))) { float weight = similarity_.weight(itemId, visitSet, reasonMap[itemId]); if(weight > 0) { queue.insert(QueueItem(itemId, weight)); } } } getRecommendItemFromQueue(queue, reasonMap, recItems); } void IncrementalItemCF::recommend( int howMany, const ItemWeightMap& visitItemWeights, RecommendItemVec& recItems, ItemRescorer* rescorer ) { // get candidate items which has positive weight and similarity value std::set<uint32_t> candidateSet; ItemWeightMap::const_iterator visitWeightsEnd = visitItemWeights.end(); for (ItemWeightMap::const_iterator it_i = visitItemWeights.begin(); it_i != visitWeightsEnd; ++it_i) { if (it_i->second > 0) getRowItems_(it_i->first, candidateSet); } ItemReasonMap reasonMap; TopItemsQueue queue(howMany); for (std::set<uint32_t>::const_iterator it = candidateSet.begin(); it != candidateSet.end(); ++it) { uint32_t itemId = *it; if(visitItemWeights.find(itemId) == visitWeightsEnd && (!rescorer || !rescorer->isFiltered(itemId))) { float weight = similarity_.weight(itemId, visitItemWeights, reasonMap[itemId]); if(weight > 0) { queue.insert(QueueItem(itemId, weight)); } } } getRecommendItemFromQueue(queue, reasonMap, recItems); } void IncrementalItemCF::getRowItems_( uint32_t row, std::set<uint32_t>& items ) { boost::shared_ptr<const SimRow> cols = similarity_.rowItems(row); for (SimRow::const_iterator it_j = cols->begin(); it_j != cols->end(); ++it_j) { uint32_t col = it_j->first; assert(col != row && "there should be no similarity value on diagonal line!"); items.insert(col); } } void IncrementalItemCF::flush() { covisitation_.flush(); similarity_.flush(); } NS_IDMLIB_RESYS_END <|endoftext|>
<commit_before>/** * \file vtkFbxExporter.cxx * 2012-06-01 LB Initial implementation * * Implementation of vtkFbxExporter class */ // ** INCLUDES ** #include "vtkFbxExporter.h" #include "vtkFbxConverter.h" #include "vtkAssemblyNode.h" #include "vtkAssemblyPath.h" #include "vtkObjectFactory.h" #include "vtkRendererCollection.h" #include "vtkRenderWindow.h" #include <fbxsdk.h> #include <QDebug> #include "../Common.h" extern FbxManager* lSdkManager; extern FbxScene* lScene; vtkStandardNewMacro(vtkFbxExporter); vtkFbxExporter::vtkFbxExporter() { this->DebugOn(); this->FileName = NULL; } vtkFbxExporter::~vtkFbxExporter() { if ( this->FileName ) delete [] this->FileName; } void vtkFbxExporter::WriteData() { // make sure the user specified a FileName or FilePointer if (this->FileName == NULL) { vtkErrorMacro(<< "Please specify FileName to use"); return; } // get the renderer vtkRenderer *ren = this->RenderWindow->GetRenderers()->GetFirstRenderer(); // make sure it has at least one actor if (ren->GetActors()->GetNumberOfItems() < 1) { vtkErrorMacro(<< "no actors found for writing Fbx file."); return; } // do the actors now vtkActor *anActor, *aPart; vtkActorCollection *ac = ren->GetActors(); ac->PrintSelf(std::cout, vtkIndent()); vtkAssemblyPath *apath; vtkCollectionSimpleIterator ait; int count = 0; for (ac->InitTraversal(ait); (anActor = ac->GetNextActor(ait)); ) { for (anActor->InitPathTraversal(); (apath=anActor->GetNextPath()); ) { if (anActor->GetMapper() != NULL && anActor->GetVisibility() != 0) { aPart=static_cast<vtkActor *>(apath->GetLastNode()->GetViewProp()); VtkFbxConverter converter(aPart, lScene); if(converter.convert(this->FileName)) { FbxNode* node = converter.getNode(); if (node != NULL) { converter.addUserProperty(node, "UseVertexColors", (bool)UseVertexColors); lScene->GetRootNode()->AddChild(node); ++count; } } } } } vtkDebugMacro(<< "Fbx converter starts writing file with " << count << " objects."); // Possible values for file format: // - FBX 6.0 binary (*.fbx) : works // - FBX 6.0 ascii (*.fbx) : works // - FBX binary (*.fbx) : Out of disk space error // - FBX ascii (*.fbx) : Out of disk space error int lFormat = lSdkManager->GetIOPluginRegistry()->FindWriterIDByDescription("FBX 6.0 binary (*.fbx)"); bool saveExitCode = SaveScene(lSdkManager, lScene, this->FileName, lFormat, true); vtkDebugMacro(<< "Fbx converter finished writing with exit code: " << saveExitCode); lScene->Clear(); } void vtkFbxExporter::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); if (this->FileName) os << indent << "FileName: " << this->FileName << "\n"; else os << indent << "FileName: (null)\n"; } <commit_msg>Fixed plugin compile error.<commit_after>/** * \file vtkFbxExporter.cxx * 2012-06-01 LB Initial implementation * * Implementation of vtkFbxExporter class */ // ** INCLUDES ** #include "vtkFbxExporter.h" #include "vtkFbxConverter.h" #include "vtkAssemblyNode.h" #include "vtkAssemblyPath.h" #include "vtkObjectFactory.h" #include "vtkRendererCollection.h" #include "vtkRenderWindow.h" #include <fbxsdk.h> #include <QDebug> #include "../Common.h" extern FbxManager* lSdkManager; extern FbxScene* lScene; vtkStandardNewMacro(vtkFbxExporter); vtkFbxExporter::vtkFbxExporter() { this->DebugOn(); this->FileName = NULL; } vtkFbxExporter::~vtkFbxExporter() { if ( this->FileName ) delete [] this->FileName; } void vtkFbxExporter::WriteData() { // make sure the user specified a FileName or FilePointer if (this->FileName == NULL) { vtkErrorMacro(<< "Please specify FileName to use"); return; } // get the renderer vtkRenderer *ren = this->RenderWindow->GetRenderers()->GetFirstRenderer(); // make sure it has at least one actor if (ren->GetActors()->GetNumberOfItems() < 1) { vtkErrorMacro(<< "no actors found for writing Fbx file."); return; } // do the actors now vtkActor *anActor, *aPart; vtkActorCollection *ac = ren->GetActors(); ac->PrintSelf(std::cout, vtkIndent()); vtkAssemblyPath *apath; vtkCollectionSimpleIterator ait; int count = 0; for (ac->InitTraversal(ait); (anActor = ac->GetNextActor(ait)); ) { for (anActor->InitPathTraversal(); (apath=anActor->GetNextPath()); ) { if (anActor->GetMapper() != NULL && anActor->GetVisibility() != 0) { aPart=static_cast<vtkActor *>(apath->GetLastNode()->GetViewProp()); VtkFbxConverter converter(aPart, lScene); if(converter.convert(this->FileName)) { FbxNode* node = converter.getNode(); if (node != NULL) { converter.addUserProperty("UseVertexColors", (bool)UseVertexColors); lScene->GetRootNode()->AddChild(node); ++count; } } } } } vtkDebugMacro(<< "Fbx converter starts writing file with " << count << " objects."); // Possible values for file format: // - FBX 6.0 binary (*.fbx) : works // - FBX 6.0 ascii (*.fbx) : works // - FBX binary (*.fbx) : Out of disk space error // - FBX ascii (*.fbx) : Out of disk space error int lFormat = lSdkManager->GetIOPluginRegistry()->FindWriterIDByDescription("FBX 6.0 binary (*.fbx)"); bool saveExitCode = SaveScene(lSdkManager, lScene, this->FileName, lFormat, true); vtkDebugMacro(<< "Fbx converter finished writing with exit code: " << saveExitCode); lScene->Clear(); } void vtkFbxExporter::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); if (this->FileName) os << indent << "FileName: " << this->FileName << "\n"; else os << indent << "FileName: (null)\n"; } <|endoftext|>
<commit_before> #include "Stack.h" #include <vector> #include <iostream> #include <iomanip> #include <cstdint> #include <cassert> #include <llvm/IR/Function.h> #ifdef _MSC_VER #define EXPORT __declspec(dllexport) #else #define EXPORT #endif namespace evmcc { struct i256 { uint64_t a; uint64_t b; uint64_t c; uint64_t d; }; static_assert(sizeof(i256) == 32, "Wrong i265 size"); using StackImpl = std::vector<i256>; Stack::Stack(llvm::IRBuilder<>& _builder, llvm::Module* _module) : m_builder(_builder) { // TODO: Clean up LLVM types auto stackPtrTy = m_builder.getInt8PtrTy(); auto i256Ty = m_builder.getIntNTy(256); auto i256PtrTy = i256Ty->getPointerTo(); auto voidTy = m_builder.getVoidTy(); auto stackCreate = llvm::Function::Create(llvm::FunctionType::get(stackPtrTy, false), llvm::GlobalValue::LinkageTypes::ExternalLinkage, "evmccrt_stack_create", _module); llvm::Type* argsTypes[] = {stackPtrTy, i256PtrTy}; auto funcType = llvm::FunctionType::get(voidTy, argsTypes, false); m_stackPush = llvm::Function::Create(funcType, llvm::GlobalValue::LinkageTypes::ExternalLinkage, "evmccrt_stack_push", _module); m_stackPop = llvm::Function::Create(funcType, llvm::GlobalValue::LinkageTypes::ExternalLinkage, "evmccrt_stack_pop", _module); llvm::Type* getArgsTypes[] = {stackPtrTy, m_builder.getInt32Ty(), i256PtrTy}; auto getFuncType = llvm::FunctionType::get(voidTy, getArgsTypes); m_stackGet = llvm::Function::Create(getFuncType, llvm::GlobalValue::LinkageTypes::ExternalLinkage, "evmccrt_stack_get", _module); m_stackSet = llvm::Function::Create(getFuncType, llvm::GlobalValue::LinkageTypes::ExternalLinkage, "evmccrt_stack_set", _module); m_args[0] = m_builder.CreateCall(stackCreate, "stack.ptr"); m_args[1] = m_builder.CreateAlloca(i256Ty, nullptr, "stack.val"); } void Stack::push(llvm::Value* _value) { m_builder.CreateStore(_value, m_args[1]); // copy value to memory m_builder.CreateCall(m_stackPush, m_args); } llvm::Value* Stack::pop() { m_builder.CreateCall(m_stackPop, m_args); return m_builder.CreateLoad(m_args[1]); } llvm::Value* Stack::get(uint32_t _index) { llvm::Value* args[] = {m_args[0], m_builder.getInt32(_index), m_args[1]}; m_builder.CreateCall(m_stackGet, args); return m_builder.CreateLoad(m_args[1]); } void Stack::set(uint32_t _index, llvm::Value* _value) { m_builder.CreateStore(_value, m_args[1]); // copy value to memory llvm::Value* args[] = {m_args[0], m_builder.getInt32(_index), m_args[1]}; m_builder.CreateCall(m_stackSet, args); } llvm::Value* Stack::top() { return get(0); } void debugStack(const char* _op, const i256& _word, uint32_t _index = 0) { std::cerr << "STACK " << std::setw(4) << std::setfill(' ') << _op << " [" << std::setw(2) << std::setfill('0') << _index << "] " << std::dec << _word.a << " HEX: " << std::hex; if (_word.b || _word.c || _word.d) { std::cerr << std::setw(16) << _word.d << " " << std::setw(16) << _word.c << " " << std::setw(16) << _word.b << " "; } std::cerr << std::setw(16) << _word.a << "\n"; } } extern "C" { using namespace evmcc; EXPORT void* evmccrt_stack_create() { auto stack = new StackImpl; std::cerr << "STACK create\n"; return stack; } EXPORT void evmccrt_stack_push(void* _stack, void* _pWord) { auto stack = static_cast<StackImpl*>(_stack); auto word = static_cast<i256*>(_pWord); debugStack("push", *word); stack->push_back(*word); } EXPORT void evmccrt_stack_pop(void* _stack, void* _pWord) { auto stack = static_cast<StackImpl*>(_stack); assert(!stack->empty()); auto word = &stack->back(); debugStack("pop", *word); auto outWord = static_cast<i256*>(_pWord); stack->pop_back(); *outWord = *word; } EXPORT void evmccrt_stack_get(void* _stack, uint32_t _index, void* _pWord) { auto stack = static_cast<StackImpl*>(_stack); assert(_index < stack->size()); auto word = stack->rbegin() + _index; debugStack("get", *word, _index); auto outWord = static_cast<i256*>(_pWord); *outWord = *word; } EXPORT void evmccrt_stack_set(void* _stack, uint32_t _index, void* _pWord) { auto stack = static_cast<StackImpl*>(_stack); auto word = static_cast<i256*>(_pWord); assert(_index < stack->size()); *(stack->rbegin() + _index) = *word; debugStack("set", *word, _index); } } // extern "C" <commit_msg>Fix stack set/get bad function signature<commit_after> #include "Stack.h" #include <vector> #include <iostream> #include <iomanip> #include <cstdint> #include <cassert> #include <llvm/IR/Function.h> #ifdef _MSC_VER #define EXPORT __declspec(dllexport) #else #define EXPORT #endif namespace evmcc { struct i256 { uint64_t a; uint64_t b; uint64_t c; uint64_t d; }; static_assert(sizeof(i256) == 32, "Wrong i265 size"); using StackImpl = std::vector<i256>; Stack::Stack(llvm::IRBuilder<>& _builder, llvm::Module* _module) : m_builder(_builder) { // TODO: Clean up LLVM types auto stackPtrTy = m_builder.getInt8PtrTy(); auto i256Ty = m_builder.getIntNTy(256); auto i256PtrTy = i256Ty->getPointerTo(); auto voidTy = m_builder.getVoidTy(); auto stackCreate = llvm::Function::Create(llvm::FunctionType::get(stackPtrTy, false), llvm::GlobalValue::LinkageTypes::ExternalLinkage, "evmccrt_stack_create", _module); llvm::Type* argsTypes[] = {stackPtrTy, i256PtrTy}; auto funcType = llvm::FunctionType::get(voidTy, argsTypes, false); m_stackPush = llvm::Function::Create(funcType, llvm::GlobalValue::LinkageTypes::ExternalLinkage, "evmccrt_stack_push", _module); m_stackPop = llvm::Function::Create(funcType, llvm::GlobalValue::LinkageTypes::ExternalLinkage, "evmccrt_stack_pop", _module); llvm::Type* getArgsTypes[] = {stackPtrTy, m_builder.getInt32Ty(), i256PtrTy}; auto getFuncType = llvm::FunctionType::get(voidTy, getArgsTypes, false); m_stackGet = llvm::Function::Create(getFuncType, llvm::GlobalValue::LinkageTypes::ExternalLinkage, "evmccrt_stack_get", _module); m_stackSet = llvm::Function::Create(getFuncType, llvm::GlobalValue::LinkageTypes::ExternalLinkage, "evmccrt_stack_set", _module); m_args[0] = m_builder.CreateCall(stackCreate, "stack.ptr"); m_args[1] = m_builder.CreateAlloca(i256Ty, nullptr, "stack.val"); } void Stack::push(llvm::Value* _value) { m_builder.CreateStore(_value, m_args[1]); // copy value to memory m_builder.CreateCall(m_stackPush, m_args); } llvm::Value* Stack::pop() { m_builder.CreateCall(m_stackPop, m_args); return m_builder.CreateLoad(m_args[1]); } llvm::Value* Stack::get(uint32_t _index) { llvm::Value* args[] = {m_args[0], m_builder.getInt32(_index), m_args[1]}; m_builder.CreateCall(m_stackGet, args); return m_builder.CreateLoad(m_args[1]); } void Stack::set(uint32_t _index, llvm::Value* _value) { m_builder.CreateStore(_value, m_args[1]); // copy value to memory llvm::Value* args[] = {m_args[0], m_builder.getInt32(_index), m_args[1]}; m_builder.CreateCall(m_stackSet, args); } llvm::Value* Stack::top() { return get(0); } void debugStack(const char* _op, const i256& _word, uint32_t _index = 0) { std::cerr << "STACK " << std::setw(4) << std::setfill(' ') << _op << " [" << std::setw(2) << std::setfill('0') << _index << "] " << std::dec << _word.a << " HEX: " << std::hex; if (_word.b || _word.c || _word.d) { std::cerr << std::setw(16) << _word.d << " " << std::setw(16) << _word.c << " " << std::setw(16) << _word.b << " "; } std::cerr << std::setw(16) << _word.a << "\n"; } } extern "C" { using namespace evmcc; EXPORT void* evmccrt_stack_create() { auto stack = new StackImpl; std::cerr << "STACK create\n"; return stack; } EXPORT void evmccrt_stack_push(void* _stack, void* _pWord) { auto stack = static_cast<StackImpl*>(_stack); auto word = static_cast<i256*>(_pWord); debugStack("push", *word); stack->push_back(*word); } EXPORT void evmccrt_stack_pop(void* _stack, void* _pWord) { auto stack = static_cast<StackImpl*>(_stack); assert(!stack->empty()); auto word = &stack->back(); debugStack("pop", *word); auto outWord = static_cast<i256*>(_pWord); stack->pop_back(); *outWord = *word; } EXPORT void evmccrt_stack_get(void* _stack, uint32_t _index, void* _pWord) { auto stack = static_cast<StackImpl*>(_stack); assert(_index < stack->size()); auto word = stack->rbegin() + _index; debugStack("get", *word, _index); auto outWord = static_cast<i256*>(_pWord); *outWord = *word; } EXPORT void evmccrt_stack_set(void* _stack, uint32_t _index, void* _pWord) { auto stack = static_cast<StackImpl*>(_stack); auto word = static_cast<i256*>(_pWord); assert(_index < stack->size()); *(stack->rbegin() + _index) = *word; debugStack("set", *word, _index); } } // extern "C" <|endoftext|>
<commit_before>#include "pbview.h" #include <cinttypes> #include <cstdio> #include <cstring> #include <ncurses.h> #include <iostream> #include <sstream> #include "config.h" #include "configcontainer.h" #include "dllist.h" #include "download.h" #include "fmtstrformatter.h" #include "help.h" #include "listformatter.h" #include "logger.h" #include "pbcontroller.h" #include "strprintf.h" #include "utils.h" using namespace newsboat; namespace podboat { PbView::PbView(PbController* c) : ctrl(c) , dllist_form(dllist_str) , help_form(help_str) , keys(0) , colorman(ctrl->get_colormanager()) , downloads_list("dls", dllist_form, ctrl->get_cfgcont()->get_configvalue_as_int("scrolloff")) , help_textview("helptext", help_form) { if (getenv("ESCDELAY") == nullptr) { set_escdelay(25); } } PbView::~PbView() { Stfl::reset(); } void PbView::run(bool auto_download, bool wrap_scroll) { bool quit = false; // Make sure curses is initialized dllist_form.run(-3); // Hide cursor using curses curs_set(0); set_dllist_keymap_hint(); do { if (ctrl->view_update_necessary()) { const double total_kbps = ctrl->get_total_kbps(); const auto speed = get_speed_human_readable(total_kbps); char parbuf[128] = ""; if (ctrl->get_maxdownloads() > 1) { snprintf(parbuf, sizeof(parbuf), _(" - %u parallel downloads"), ctrl->get_maxdownloads()); } char buf[1024]; snprintf(buf, sizeof(buf), _("Queue (%u downloads in progress, %u total) " "- %.2f %s total%s"), static_cast<unsigned int>( ctrl->downloads_in_progress()), static_cast<unsigned int>( ctrl->downloads().size()), speed.first, speed.second.c_str(), parbuf); dllist_form.set("head", buf); LOG(Level::DEBUG, "PbView::run: updating view... " "downloads().size() " "= %" PRIu64, static_cast<uint64_t>(ctrl->downloads().size())); ListFormatter listfmt; const std::string line_format = ctrl->get_cfgcont()->get_configvalue("podlist-format"); dllist_form.run(-3); // compute all widget dimensions const unsigned int width = downloads_list.get_width(); unsigned int i = 0; for (const auto& dl : ctrl->downloads()) { auto lbuf = format_line(line_format, dl, i, width); listfmt.add_line(lbuf); i++; } downloads_list.stfl_replace_lines(listfmt); // If there's no status message, we know there's no error to show // Thus, it's safe to replace with the download's status if (i >= 1 && dllist_form.get("msg").empty()) { const auto idx = downloads_list.get_position(); dllist_form.set("msg", ctrl->downloads()[idx].status_msg()); } ctrl->set_view_update_necessary(false); } const char* event = dllist_form.run(500); if (auto_download) { if (ctrl->get_maxdownloads() > ctrl->downloads_in_progress()) { ctrl->start_downloads(); } } if (!event || strcmp(event, "TIMEOUT") == 0) { continue; } if (strcmp(event, "RESIZE") == 0) { handle_resize(); continue; } Operation op = keys->get_operation(event, "podboat"); if (dllist_form.get("msg").length() > 0) { dllist_form.set("msg", ""); ctrl->set_view_update_necessary(true); } switch (op) { case OP_REDRAW: Stfl::reset(); break; case OP_PREV: case OP_SK_UP: downloads_list.move_up(wrap_scroll); ctrl->set_view_update_necessary(true); break; case OP_NEXT: case OP_SK_DOWN: downloads_list.move_down(wrap_scroll); ctrl->set_view_update_necessary(true); break; case OP_SK_HOME: downloads_list.move_to_first(); ctrl->set_view_update_necessary(true); break; case OP_SK_END: downloads_list.move_to_last(); ctrl->set_view_update_necessary(true); break; case OP_SK_PGUP: downloads_list.move_page_up(wrap_scroll); ctrl->set_view_update_necessary(true); break; case OP_SK_PGDOWN: downloads_list.move_page_down(wrap_scroll); ctrl->set_view_update_necessary(true); break; case OP_PB_TOGGLE_DLALL: auto_download = !auto_download; break; case OP_HARDQUIT: case OP_QUIT: if (ctrl->downloads_in_progress() > 0) { dllist_form.set("msg", _("Error: can't quit: download(s) in " "progress.")); ctrl->set_view_update_necessary(true); } else { quit = true; } break; case OP_PB_MOREDL: ctrl->increase_parallel_downloads(); break; case OP_PB_LESSDL: ctrl->decrease_parallel_downloads(); break; case OP_PB_DOWNLOAD: { if (ctrl->downloads().size() >= 1) { const auto idx = downloads_list.get_position(); auto& item = ctrl->downloads()[idx]; if (item.status() != DlStatus::DOWNLOADING) { ctrl->start_download(item); } } } break; case OP_PB_PLAY: { if (ctrl->downloads().size() >= 1) { const auto idx = downloads_list.get_position(); DlStatus status = ctrl->downloads()[idx].status(); if (status == DlStatus::FINISHED || status == DlStatus::PLAYED || status == DlStatus::READY) { ctrl->play_file(ctrl->downloads()[idx] .filename()); ctrl->downloads()[idx].set_status( DlStatus::PLAYED); } else { dllist_form.set("msg", _("Error: download needs to be " "finished before the file " "can be played.")); } } } break; case OP_PB_MARK_FINISHED: { if (ctrl->downloads().size() >= 1) { const auto idx = downloads_list.get_position(); DlStatus status = ctrl->downloads()[idx].status(); if (status == DlStatus::PLAYED) { ctrl->downloads()[idx].set_status( DlStatus::FINISHED); } } } break; case OP_PB_CANCEL: { if (ctrl->downloads().size() >= 1) { const auto idx = downloads_list.get_position(); if (ctrl->downloads()[idx].status() == DlStatus::DOWNLOADING) { ctrl->downloads()[idx].set_status( DlStatus::CANCELLED); } } } break; case OP_PB_DELETE: { if (ctrl->downloads().size() >= 1) { const auto idx = downloads_list.get_position(); if (ctrl->downloads()[idx].status() != DlStatus::DOWNLOADING) { ctrl->downloads()[idx].set_status( DlStatus::DELETED); } } } break; case OP_PB_PURGE: if (ctrl->downloads_in_progress() > 0) { dllist_form.set("msg", _("Error: unable to perform operation: " "download(s) in progress.")); } else { ctrl->purge_queue(); } ctrl->set_view_update_necessary(true); break; case OP_HELP: run_help(); break; default: break; } } while (!quit); } void PbView::handle_resize() { std::vector<std::reference_wrapper<newsboat::Stfl::Form>> forms = {dllist_form, help_form}; for (const auto& form : forms) { form.get().run(-3); } ctrl->set_view_update_necessary(true); } void PbView::apply_colors_to_all_forms() { using namespace std::placeholders; colorman.apply_colors(std::bind(&newsboat::Stfl::Form::set, &dllist_form, _1, _2)); colorman.apply_colors(std::bind(&newsboat::Stfl::Form::set, &help_form, _1, _2)); } std::pair<double, std::string> PbView::get_speed_human_readable(double kbps) { if (kbps < 1024) { return std::make_pair(kbps, _("KB/s")); } else if (kbps < 1024 * 1024) { return std::make_pair(kbps / 1024, _("MB/s")); } else { return std::make_pair(kbps / 1024 / 1024, _("GB/s")); } } void PbView::run_help() { set_help_keymap_hint(); help_form.set("head", _("Help")); const auto descs = keys->get_keymap_descriptions("podboat"); ListFormatter listfmt; for (const auto& desc : descs) { const std::string descline = strprintf::fmt("%-7s %-23s %s", desc.key, desc.cmd, desc.desc); listfmt.add_line(descline); } help_textview.stfl_replace_lines(listfmt.get_lines_count(), listfmt.format_list()); bool quit = false; do { const char* event = help_form.run(0); if (!event) { continue; } if (strcmp(event, "RESIZE") == 0) { handle_resize(); continue; } Operation op = keys->get_operation(event, "help"); switch (op) { case OP_SK_UP: help_textview.scroll_up(); break; case OP_SK_DOWN: help_textview.scroll_down(); break; case OP_SK_HOME: help_textview.scroll_to_top(); break; case OP_SK_END: help_textview.scroll_to_bottom(); break; case OP_SK_PGUP: help_textview.scroll_page_up(); break; case OP_SK_PGDOWN: help_textview.scroll_page_down(); break; case OP_HARDQUIT: case OP_QUIT: quit = true; break; default: break; } } while (!quit); } std::string PbView::prepare_keymaphint(KeyMapHintEntry* hints) { std::string keymap_hint; for (int i = 0; hints[i].op != OP_NIL; ++i) { std::string bound_keys = utils::join(keys->get_keys(hints[i].op, "podboat"), ","); if (bound_keys.empty()) { bound_keys = "<none>"; } keymap_hint.append(bound_keys); keymap_hint.append(":"); keymap_hint.append(hints[i].text); keymap_hint.append(" "); } return keymap_hint; } void PbView::set_help_keymap_hint() { static KeyMapHintEntry hints[] = {{OP_QUIT, _("Quit")}, {OP_NIL, nullptr}}; std::string keymap_hint = prepare_keymaphint(hints); help_form.set("help", keymap_hint); } void PbView::set_dllist_keymap_hint() { static KeyMapHintEntry hints[] = {{OP_QUIT, _("Quit")}, {OP_PB_DOWNLOAD, _("Download")}, {OP_PB_CANCEL, _("Cancel")}, {OP_PB_DELETE, _("Delete")}, {OP_PB_PURGE, _("Purge Finished")}, {OP_PB_TOGGLE_DLALL, _("Toggle Automatic Download")}, {OP_PB_PLAY, _("Play")}, {OP_PB_MARK_FINISHED, _("Mark as Finished")}, {OP_HELP, _("Help")}, {OP_NIL, nullptr} }; std::string keymap_hint = prepare_keymaphint(hints); dllist_form.set("help", keymap_hint); } std::string PbView::format_line(const std::string& podlist_format, const Download& dl, unsigned int pos, unsigned int width) { FmtStrFormatter fmt; const double speed_kbps = dl.kbps(); const auto speed = get_speed_human_readable(speed_kbps); fmt.register_fmt('i', strprintf::fmt("%u", pos + 1)); fmt.register_fmt('d', strprintf::fmt("%.1f", dl.current_size() / (1024 * 1024))); fmt.register_fmt( 't', strprintf::fmt("%.1f", dl.total_size() / (1024 * 1024))); fmt.register_fmt('p', strprintf::fmt("%.1f", dl.percents_finished())); fmt.register_fmt('k', strprintf::fmt("%.2f", speed_kbps)); fmt.register_fmt('K', strprintf::fmt("%.2f %s", speed.first, speed.second)); fmt.register_fmt('S', strprintf::fmt("%s", dl.status_text())); fmt.register_fmt('u', strprintf::fmt("%s", dl.url())); fmt.register_fmt('F', strprintf::fmt("%s", dl.filename())); fmt.register_fmt('b', strprintf::fmt("%s", dl.basename())); auto formattedLine = fmt.do_format(podlist_format, width); formattedLine = utils::quote_for_stfl(formattedLine); return formattedLine; } } // namespace podboat <commit_msg>Move to next item after marking item as finished/deleted<commit_after>#include "pbview.h" #include <cinttypes> #include <cstdio> #include <cstring> #include <ncurses.h> #include <iostream> #include <sstream> #include "config.h" #include "configcontainer.h" #include "dllist.h" #include "download.h" #include "fmtstrformatter.h" #include "help.h" #include "listformatter.h" #include "logger.h" #include "pbcontroller.h" #include "strprintf.h" #include "utils.h" using namespace newsboat; namespace podboat { PbView::PbView(PbController* c) : ctrl(c) , dllist_form(dllist_str) , help_form(help_str) , keys(0) , colorman(ctrl->get_colormanager()) , downloads_list("dls", dllist_form, ctrl->get_cfgcont()->get_configvalue_as_int("scrolloff")) , help_textview("helptext", help_form) { if (getenv("ESCDELAY") == nullptr) { set_escdelay(25); } } PbView::~PbView() { Stfl::reset(); } void PbView::run(bool auto_download, bool wrap_scroll) { bool quit = false; // Make sure curses is initialized dllist_form.run(-3); // Hide cursor using curses curs_set(0); set_dllist_keymap_hint(); do { if (ctrl->view_update_necessary()) { const double total_kbps = ctrl->get_total_kbps(); const auto speed = get_speed_human_readable(total_kbps); char parbuf[128] = ""; if (ctrl->get_maxdownloads() > 1) { snprintf(parbuf, sizeof(parbuf), _(" - %u parallel downloads"), ctrl->get_maxdownloads()); } char buf[1024]; snprintf(buf, sizeof(buf), _("Queue (%u downloads in progress, %u total) " "- %.2f %s total%s"), static_cast<unsigned int>( ctrl->downloads_in_progress()), static_cast<unsigned int>( ctrl->downloads().size()), speed.first, speed.second.c_str(), parbuf); dllist_form.set("head", buf); LOG(Level::DEBUG, "PbView::run: updating view... " "downloads().size() " "= %" PRIu64, static_cast<uint64_t>(ctrl->downloads().size())); ListFormatter listfmt; const std::string line_format = ctrl->get_cfgcont()->get_configvalue("podlist-format"); dllist_form.run(-3); // compute all widget dimensions const unsigned int width = downloads_list.get_width(); unsigned int i = 0; for (const auto& dl : ctrl->downloads()) { auto lbuf = format_line(line_format, dl, i, width); listfmt.add_line(lbuf); i++; } downloads_list.stfl_replace_lines(listfmt); // If there's no status message, we know there's no error to show // Thus, it's safe to replace with the download's status if (i >= 1 && dllist_form.get("msg").empty()) { const auto idx = downloads_list.get_position(); dllist_form.set("msg", ctrl->downloads()[idx].status_msg()); } ctrl->set_view_update_necessary(false); } const char* event = dllist_form.run(500); if (auto_download) { if (ctrl->get_maxdownloads() > ctrl->downloads_in_progress()) { ctrl->start_downloads(); } } if (!event || strcmp(event, "TIMEOUT") == 0) { continue; } if (strcmp(event, "RESIZE") == 0) { handle_resize(); continue; } Operation op = keys->get_operation(event, "podboat"); if (dllist_form.get("msg").length() > 0) { dllist_form.set("msg", ""); ctrl->set_view_update_necessary(true); } switch (op) { case OP_REDRAW: Stfl::reset(); break; case OP_PREV: case OP_SK_UP: downloads_list.move_up(wrap_scroll); ctrl->set_view_update_necessary(true); break; case OP_NEXT: case OP_SK_DOWN: downloads_list.move_down(wrap_scroll); ctrl->set_view_update_necessary(true); break; case OP_SK_HOME: downloads_list.move_to_first(); ctrl->set_view_update_necessary(true); break; case OP_SK_END: downloads_list.move_to_last(); ctrl->set_view_update_necessary(true); break; case OP_SK_PGUP: downloads_list.move_page_up(wrap_scroll); ctrl->set_view_update_necessary(true); break; case OP_SK_PGDOWN: downloads_list.move_page_down(wrap_scroll); ctrl->set_view_update_necessary(true); break; case OP_PB_TOGGLE_DLALL: auto_download = !auto_download; break; case OP_HARDQUIT: case OP_QUIT: if (ctrl->downloads_in_progress() > 0) { dllist_form.set("msg", _("Error: can't quit: download(s) in " "progress.")); ctrl->set_view_update_necessary(true); } else { quit = true; } break; case OP_PB_MOREDL: ctrl->increase_parallel_downloads(); break; case OP_PB_LESSDL: ctrl->decrease_parallel_downloads(); break; case OP_PB_DOWNLOAD: { if (ctrl->downloads().size() >= 1) { const auto idx = downloads_list.get_position(); auto& item = ctrl->downloads()[idx]; if (item.status() != DlStatus::DOWNLOADING) { ctrl->start_download(item); } } } break; case OP_PB_PLAY: { if (ctrl->downloads().size() >= 1) { const auto idx = downloads_list.get_position(); DlStatus status = ctrl->downloads()[idx].status(); if (status == DlStatus::FINISHED || status == DlStatus::PLAYED || status == DlStatus::READY) { ctrl->play_file(ctrl->downloads()[idx] .filename()); ctrl->downloads()[idx].set_status( DlStatus::PLAYED); } else { dllist_form.set("msg", _("Error: download needs to be " "finished before the file " "can be played.")); } } } break; case OP_PB_MARK_FINISHED: { auto& downloads = ctrl->downloads(); if (downloads.size() >= 1) { const auto idx = downloads_list.get_position(); DlStatus status = downloads[idx].status(); if (status == DlStatus::PLAYED) { downloads[idx].set_status(DlStatus::FINISHED); if (idx + 1 < downloads.size()) { downloads_list.set_position(idx + 1); } } } } break; case OP_PB_CANCEL: { if (ctrl->downloads().size() >= 1) { const auto idx = downloads_list.get_position(); if (ctrl->downloads()[idx].status() == DlStatus::DOWNLOADING) { ctrl->downloads()[idx].set_status( DlStatus::CANCELLED); } } } break; case OP_PB_DELETE: { auto& downloads = ctrl->downloads(); if (downloads.size() >= 1) { const auto idx = downloads_list.get_position(); if (downloads[idx].status() != DlStatus::DOWNLOADING) { downloads[idx].set_status(DlStatus::DELETED); if (idx + 1 < downloads.size()) { downloads_list.set_position(idx + 1); } } } } break; case OP_PB_PURGE: if (ctrl->downloads_in_progress() > 0) { dllist_form.set("msg", _("Error: unable to perform operation: " "download(s) in progress.")); } else { ctrl->purge_queue(); } ctrl->set_view_update_necessary(true); break; case OP_HELP: run_help(); break; default: break; } } while (!quit); } void PbView::handle_resize() { std::vector<std::reference_wrapper<newsboat::Stfl::Form>> forms = {dllist_form, help_form}; for (const auto& form : forms) { form.get().run(-3); } ctrl->set_view_update_necessary(true); } void PbView::apply_colors_to_all_forms() { using namespace std::placeholders; colorman.apply_colors(std::bind(&newsboat::Stfl::Form::set, &dllist_form, _1, _2)); colorman.apply_colors(std::bind(&newsboat::Stfl::Form::set, &help_form, _1, _2)); } std::pair<double, std::string> PbView::get_speed_human_readable(double kbps) { if (kbps < 1024) { return std::make_pair(kbps, _("KB/s")); } else if (kbps < 1024 * 1024) { return std::make_pair(kbps / 1024, _("MB/s")); } else { return std::make_pair(kbps / 1024 / 1024, _("GB/s")); } } void PbView::run_help() { set_help_keymap_hint(); help_form.set("head", _("Help")); const auto descs = keys->get_keymap_descriptions("podboat"); ListFormatter listfmt; for (const auto& desc : descs) { const std::string descline = strprintf::fmt("%-7s %-23s %s", desc.key, desc.cmd, desc.desc); listfmt.add_line(descline); } help_textview.stfl_replace_lines(listfmt.get_lines_count(), listfmt.format_list()); bool quit = false; do { const char* event = help_form.run(0); if (!event) { continue; } if (strcmp(event, "RESIZE") == 0) { handle_resize(); continue; } Operation op = keys->get_operation(event, "help"); switch (op) { case OP_SK_UP: help_textview.scroll_up(); break; case OP_SK_DOWN: help_textview.scroll_down(); break; case OP_SK_HOME: help_textview.scroll_to_top(); break; case OP_SK_END: help_textview.scroll_to_bottom(); break; case OP_SK_PGUP: help_textview.scroll_page_up(); break; case OP_SK_PGDOWN: help_textview.scroll_page_down(); break; case OP_HARDQUIT: case OP_QUIT: quit = true; break; default: break; } } while (!quit); } std::string PbView::prepare_keymaphint(KeyMapHintEntry* hints) { std::string keymap_hint; for (int i = 0; hints[i].op != OP_NIL; ++i) { std::string bound_keys = utils::join(keys->get_keys(hints[i].op, "podboat"), ","); if (bound_keys.empty()) { bound_keys = "<none>"; } keymap_hint.append(bound_keys); keymap_hint.append(":"); keymap_hint.append(hints[i].text); keymap_hint.append(" "); } return keymap_hint; } void PbView::set_help_keymap_hint() { static KeyMapHintEntry hints[] = {{OP_QUIT, _("Quit")}, {OP_NIL, nullptr}}; std::string keymap_hint = prepare_keymaphint(hints); help_form.set("help", keymap_hint); } void PbView::set_dllist_keymap_hint() { static KeyMapHintEntry hints[] = {{OP_QUIT, _("Quit")}, {OP_PB_DOWNLOAD, _("Download")}, {OP_PB_CANCEL, _("Cancel")}, {OP_PB_DELETE, _("Delete")}, {OP_PB_PURGE, _("Purge Finished")}, {OP_PB_TOGGLE_DLALL, _("Toggle Automatic Download")}, {OP_PB_PLAY, _("Play")}, {OP_PB_MARK_FINISHED, _("Mark as Finished")}, {OP_HELP, _("Help")}, {OP_NIL, nullptr} }; std::string keymap_hint = prepare_keymaphint(hints); dllist_form.set("help", keymap_hint); } std::string PbView::format_line(const std::string& podlist_format, const Download& dl, unsigned int pos, unsigned int width) { FmtStrFormatter fmt; const double speed_kbps = dl.kbps(); const auto speed = get_speed_human_readable(speed_kbps); fmt.register_fmt('i', strprintf::fmt("%u", pos + 1)); fmt.register_fmt('d', strprintf::fmt("%.1f", dl.current_size() / (1024 * 1024))); fmt.register_fmt( 't', strprintf::fmt("%.1f", dl.total_size() / (1024 * 1024))); fmt.register_fmt('p', strprintf::fmt("%.1f", dl.percents_finished())); fmt.register_fmt('k', strprintf::fmt("%.2f", speed_kbps)); fmt.register_fmt('K', strprintf::fmt("%.2f %s", speed.first, speed.second)); fmt.register_fmt('S', strprintf::fmt("%s", dl.status_text())); fmt.register_fmt('u', strprintf::fmt("%s", dl.url())); fmt.register_fmt('F', strprintf::fmt("%s", dl.filename())); fmt.register_fmt('b', strprintf::fmt("%s", dl.basename())); auto formattedLine = fmt.do_format(podlist_format, width); formattedLine = utils::quote_for_stfl(formattedLine); return formattedLine; } } // namespace podboat <|endoftext|>
<commit_before>// SA:MP Profiler plugin // // Copyright (c) 2011 Zeex // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <algorithm> #include <cerrno> #include <cstdio> #include <cstdlib> #include <cstring> #include <fstream> #include <iterator> #include <list> #include <map> #include <sstream> #include <string> #include <vector> #include "amxname.h" #include "debuginfo.h" #include "jump.h" #include "logprintf.h" #include "plugin.h" #include "profiler.h" #include "servercfg.h" #include "amx/amx.h" extern void *pAMXFunctions; // Symbolic info, used for getting function names static std::map<AMX*, DebugInfo> debugInfos; // Both x86 and x86-64 are Little Endian... static void *AMXAPI DummyAmxAlign(void *v) { return v; } static uint32_t amx_Exec_addr; static unsigned char amx_Exec_code[5]; static int AMXAPI Exec(AMX *amx, cell *retval, int index) { memcpy(reinterpret_cast<void*>(::amx_Exec_addr), ::amx_Exec_code, 5); int error = AMX_ERR_NONE; // Check if this script has a profiler attached to it Profiler *prof = Profiler::Get(amx); if (prof != 0) { error = prof->Exec(retval, index); } else { error = amx_Exec(amx, retval, index); } SetJump(reinterpret_cast<void*>(::amx_Exec_addr), (void*)::Exec, ::amx_Exec_code); return error; } // Replaces back slashes with forward slashes static std::string ToPortablePath(const std::string &path) { std::string fsPath = path; std::replace(fsPath.begin(), fsPath.end(), '\\', '/'); return fsPath; } // Returns true if the .amx should be profiled static bool WantsProfiler(const std::string &amxName) { std::string goodAmxName = ToPortablePath(amxName); /// Look at profiler.cfg /// It should be just a list of .amx files, one per line. std::ifstream config("plugins/profiler.cfg"); std::vector<std::string> filenames; std::transform( std::istream_iterator<std::string>(config), std::istream_iterator<std::string>(), std::back_inserter(filenames), ToPortablePath ); if (std::find(filenames.begin(), filenames.end(), goodAmxName) != filenames.end()) { return true; } /// Read settings from server.cfg. /// This only works if they used the defalt directories for gamemodes and filterscripts. /// Someting like ../my_scripts/awesome_script.amx obviously won't work here. ServerCfg serverCfg; if (goodAmxName.find("gamemodes/") != std::string::npos) { // This is a gamemode if (serverCfg.GetOptionAsInt("profile_gamemode") != 0) { return true; } } else if (goodAmxName.find("filterscripts/") != std::string::npos) { std::string fsList = serverCfg.GetOption("profile_filterscripts"); std::stringstream fsStream(fsList); do { std::string fsName; fsStream >> fsName; if (goodAmxName == "filterscripts/" + fsName + ".amx") { return true; } } while (!fsStream.eof()); } return false; } PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() { return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES; } PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) { pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS]; logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF]; // The server does not export amx_Align* for some reason. // They are used in amxdbg.c and amxaux.c, so they must be callable. ((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align16] = (void*)DummyAmxAlign; // amx_Align16 ((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align32] = (void*)DummyAmxAlign; // amx_Align32 ((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align64] = (void*)DummyAmxAlign; // amx_Align64 // Hook amx_Exec ::amx_Exec_addr = reinterpret_cast<uint32_t>(((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Exec]); SetJump(reinterpret_cast<void*>(::amx_Exec_addr), (void*)::Exec, ::amx_Exec_code); logprintf(" Profiler plugin v" VERSION " is OK."); return true; } PLUGIN_EXPORT void PLUGIN_CALL Unload() { return; } PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) { std::string filename = GetAmxName(amx); if (filename.empty()) { logprintf("Profiler: Failed to detect .amx name"); return AMX_ERR_NONE; } if (!Profiler::IsScriptProfilable(amx)) { logprintf("Profiler: %s can't be profiled (are you using -d0?)", filename.c_str()); return AMX_ERR_NONE; } if (WantsProfiler(filename)) { logprintf("Profiler: Will profile %s", filename.c_str()); if (DebugInfo::HasDebugInfo(amx)) { DebugInfo debugInfo; debugInfo.Load(filename); if (debugInfo.IsLoaded()) { logprintf("Profiler: Loaded debug info from %s", filename.c_str()); ::debugInfos[amx] = debugInfo; Profiler::Attach(amx, debugInfo); return AMX_ERR_NONE; } else { logprintf("Profiler: Error loading debug info from %s", filename.c_str()); } } Profiler::Attach(amx); } return AMX_ERR_NONE; } PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) { // Get an instance of Profiler attached to the unloading AMX Profiler *prof = Profiler::Get(amx); // Detach profiler if (prof != 0) { // Before doing that, print stats to <amx_file_path>.prof std::string name = GetAmxName(amx); if (!name.empty()) { std::string outfile = name + std::string(".prof"); logprintf("Profiler: Writing profile to %s", outfile.c_str()); prof->PrintStats(outfile); } Profiler::Detach(amx); } // Free debug info std::map<AMX*, DebugInfo>::iterator it = ::debugInfos.find(amx); if (it != ::debugInfos.end()) { it->second.Free(); ::debugInfos.erase(it); } return AMX_ERR_NONE; } <commit_msg>Allow names ending with .amx in profile_filterscripts<commit_after>// SA:MP Profiler plugin // // Copyright (c) 2011 Zeex // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <algorithm> #include <cerrno> #include <cstdio> #include <cstdlib> #include <cstring> #include <fstream> #include <iterator> #include <list> #include <map> #include <sstream> #include <string> #include <vector> #include "amxname.h" #include "debuginfo.h" #include "jump.h" #include "logprintf.h" #include "plugin.h" #include "profiler.h" #include "servercfg.h" #include "amx/amx.h" extern void *pAMXFunctions; // Symbolic info, used for getting function names static std::map<AMX*, DebugInfo> debugInfos; // Both x86 and x86-64 are Little Endian... static void *AMXAPI DummyAmxAlign(void *v) { return v; } static uint32_t amx_Exec_addr; static unsigned char amx_Exec_code[5]; static int AMXAPI Exec(AMX *amx, cell *retval, int index) { memcpy(reinterpret_cast<void*>(::amx_Exec_addr), ::amx_Exec_code, 5); int error = AMX_ERR_NONE; // Check if this script has a profiler attached to it Profiler *prof = Profiler::Get(amx); if (prof != 0) { error = prof->Exec(retval, index); } else { error = amx_Exec(amx, retval, index); } SetJump(reinterpret_cast<void*>(::amx_Exec_addr), (void*)::Exec, ::amx_Exec_code); return error; } // Replaces back slashes with forward slashes static std::string ToPortablePath(const std::string &path) { std::string fsPath = path; std::replace(fsPath.begin(), fsPath.end(), '\\', '/'); return fsPath; } // Returns true if the .amx should be profiled static bool WantsProfiler(const std::string &amxName) { std::string goodAmxName = ToPortablePath(amxName); /// Look at profiler.cfg /// It should be just a list of .amx files, one per line. std::ifstream config("plugins/profiler.cfg"); std::vector<std::string> filenames; std::transform( std::istream_iterator<std::string>(config), std::istream_iterator<std::string>(), std::back_inserter(filenames), ToPortablePath ); if (std::find(filenames.begin(), filenames.end(), goodAmxName) != filenames.end()) { return true; } /// Read settings from server.cfg. /// This only works if they used the defalt directories for gamemodes and filterscripts. /// Someting like ../my_scripts/awesome_script.amx obviously won't work here. ServerCfg serverCfg; if (goodAmxName.find("gamemodes/") != std::string::npos) { // This is a gamemode if (serverCfg.GetOptionAsInt("profile_gamemode") != 0) { return true; } } else if (goodAmxName.find("filterscripts/") != std::string::npos) { std::string fsList = serverCfg.GetOption("profile_filterscripts"); std::stringstream fsStream(fsList); do { std::string fsName; fsStream >> fsName; if (goodAmxName == "filterscripts/" + fsName + ".amx" || goodAmxName == "filterscripts/" + fsName) { return true; } } while (!fsStream.eof()); } return false; } PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() { return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES; } PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) { pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS]; logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF]; // The server does not export amx_Align* for some reason. // They are used in amxdbg.c and amxaux.c, so they must be callable. ((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align16] = (void*)DummyAmxAlign; // amx_Align16 ((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align32] = (void*)DummyAmxAlign; // amx_Align32 ((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align64] = (void*)DummyAmxAlign; // amx_Align64 // Hook amx_Exec ::amx_Exec_addr = reinterpret_cast<uint32_t>(((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Exec]); SetJump(reinterpret_cast<void*>(::amx_Exec_addr), (void*)::Exec, ::amx_Exec_code); logprintf(" Profiler plugin v" VERSION " is OK."); return true; } PLUGIN_EXPORT void PLUGIN_CALL Unload() { return; } PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) { std::string filename = GetAmxName(amx); if (filename.empty()) { logprintf("Profiler: Failed to detect .amx name"); return AMX_ERR_NONE; } if (!Profiler::IsScriptProfilable(amx)) { logprintf("Profiler: %s can't be profiled (are you using -d0?)", filename.c_str()); return AMX_ERR_NONE; } if (WantsProfiler(filename)) { logprintf("Profiler: Will profile %s", filename.c_str()); if (DebugInfo::HasDebugInfo(amx)) { DebugInfo debugInfo; debugInfo.Load(filename); if (debugInfo.IsLoaded()) { logprintf("Profiler: Loaded debug info from %s", filename.c_str()); ::debugInfos[amx] = debugInfo; Profiler::Attach(amx, debugInfo); return AMX_ERR_NONE; } else { logprintf("Profiler: Error loading debug info from %s", filename.c_str()); } } Profiler::Attach(amx); } return AMX_ERR_NONE; } PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) { // Get an instance of Profiler attached to the unloading AMX Profiler *prof = Profiler::Get(amx); // Detach profiler if (prof != 0) { // Before doing that, print stats to <amx_file_path>.prof std::string name = GetAmxName(amx); if (!name.empty()) { std::string outfile = name + std::string(".prof"); logprintf("Profiler: Writing profile to %s", outfile.c_str()); prof->PrintStats(outfile); } Profiler::Detach(amx); } // Free debug info std::map<AMX*, DebugInfo>::iterator it = ::debugInfos.find(amx); if (it != ::debugInfos.end()) { it->second.Free(); ::debugInfos.erase(it); } return AMX_ERR_NONE; } <|endoftext|>
<commit_before>/****************************************************************************** * This file is part of the Mula project * Copyright (c) 2011 Laszlo Papp <lpapp@kde.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "stardict.h" #include "settingsdialog.h" #include "file.h" #include <core/dictionaryplugin.h> #include <QtCore/QList> #include <QtCore/QMap> #include <QtCore/QString> #include <QtCore/QCoreApplication> #include <QtCore/QDir> #include <QtCore/QFile> #include <QtCore/QSettings> #include <QtCore/QStack> #include <QtCore/QDebug> using namespace MulaPluginStarDict; class StarDict::Private { public: Private() : dictionaryManager(new StarDictDictionaryManager) , reformatLists(false) , expandAbbreviations(false) { } ~Private() { } StarDictDictionaryManager *dictionaryManager; QStringList dictionaryDirectoryList; QHash<QString, int> loadedDictionaries; bool reformatLists; bool expandAbbreviations; QString ifoBookName; QString ifoFileName; const static int maximumFuzzy = 24; }; StarDict::StarDict(QObject *parent) : QObject(parent) , d(new Private) { QSettings settings("mula","mula"); d->dictionaryDirectoryList = settings.value("StarDict/dictionaryDirectoryList", d->dictionaryDirectoryList).toStringList(); d->reformatLists = settings.value("StarDict/reformatLists", true).toBool(); d->expandAbbreviations = settings.value("StarDict/expandAbbreviations", true).toBool(); if (d->dictionaryDirectoryList.isEmpty()) { #ifdef Q_OS_UNIX d->dictionaryDirectoryList.append("/usr/share/stardict/dic"); #else d->dictionaryDirectoryList.append(QCoreApplication::applicationDirPath() + "/dic"); #endif d->dictionaryDirectoryList.append(QDir::homePath() + "/.stardict/dic"); } } StarDict::~StarDict() { QSettings settings("mula","mula"); settings.setValue("StarDict/dictionaryDirectoryList", d->dictionaryDirectoryList); settings.setValue("StarDict/reformatLists", d->reformatLists); settings.setValue("StarDict/expandAbbreviations", d->expandAbbreviations); delete d->dictionaryManager; } QString StarDict::name() const { return "stardict"; } QString StarDict::version() const { return "0.1"; } QString StarDict::description() const { return "The StarDict plugin"; } QStringList StarDict::authors() const { return QStringList() << "Laszlo Papp <lpapp@kde.org>"; } MulaCore::DictionaryPlugin::Features StarDict::features() const { return MulaCore::DictionaryPlugin::Features(SearchSimilar | SettingsDialog); } QString StarDict::findAvailableDictionary(const QString& absolutePath) { StarDictDictionaryInfo info; if (info.loadFromIfoFile(absolutePath, false)) return info.bookName(); return QString(); } QString StarDict::findIfoFile(const QString& absolutePath) { StarDictDictionaryInfo info; if (info.loadFromIfoFile(absolutePath, false) && info.bookName() == d->ifoBookName) d->ifoFileName = absolutePath; return QString(); } template <typename Method> QStringList StarDict::recursiveTemplateFind(const QString& directoryPath, Method method) { QDir dir(directoryPath); QStringList result; // Going through the subfolders foreach (const QString& entryName, dir.entryList(QDir::Dirs & QDir::NoDotAndDotDot)) { QString absolutePath = dir.absoluteFilePath(entryName); result.append(recursiveTemplateFind(absolutePath, method)); } foreach (const QString& entryName, dir.entryList(QDir::Files & QDir::Drives & QDir::NoDotAndDotDot)) { QString absolutePath = dir.absoluteFilePath(entryName); if (absolutePath.endsWith(QLatin1String(".ifo"))) result.append((this->*method)(absolutePath)); } return result; } QStringList StarDict::availableDictionaryList() { QStringList result; foreach (const QString& directoryPath, d->dictionaryDirectoryList) result.append(recursiveTemplateFind(directoryPath, &StarDict::findAvailableDictionary)); return result; } QStringList StarDict::loadedDictionaryList() const { return d->loadedDictionaries.keys(); } void StarDict::setLoadedDictionaryList(const QStringList &loadedDictionaryList) { QStringList availableDictionaries = availableDictionaryList(); QStringList disabledDictionaries; foreach (const QString& dictionary, availableDictionaries) { if (!loadedDictionaryList.contains(dictionary)) disabledDictionaries.append(dictionary); } d->dictionaryManager->reload(d->dictionaryDirectoryList, loadedDictionaryList, disabledDictionaries); d->loadedDictionaries.clear(); for (int i = 0; i < d->dictionaryManager->dictionaryCount(); ++i) d->loadedDictionaries[d->dictionaryManager->dictionaryName(i)] = i; } MulaCore::DictionaryInfo StarDict::dictionaryInfo(const QString &dictionary) { StarDictDictionaryInfo nativeInfo; nativeInfo.setWordCount(0); if (!nativeInfo.loadFromIfoFile(findDictionary(dictionary, d->dictionaryDirectoryList), false)) return MulaCore::DictionaryInfo(); MulaCore::DictionaryInfo result(name(), dictionary); result.setAuthor(nativeInfo.author()); result.setDescription(nativeInfo.description()); result.setWordCount(nativeInfo.wordCount() ? static_cast<long>(nativeInfo.wordCount()) : -1); return result; } bool StarDict::isTranslatable(const QString &dictionary, const QString &word) { if (!d->loadedDictionaries.contains(dictionary)) return false; int index; return d->dictionaryManager->simpleLookupWord(word.toUtf8().data(), index, d->loadedDictionaries[dictionary]); } MulaCore::Translation StarDict::translate(const QString &dictionary, const QString &word) { if (!d->loadedDictionaries.contains(dictionary) || word.isEmpty()) return MulaCore::Translation(); int dictionaryIndex = d->loadedDictionaries[dictionary]; int index; if (!d->dictionaryManager->simpleLookupWord(word.toUtf8().data(), index, d->loadedDictionaries[dictionary])) return MulaCore::Translation(); return MulaCore::Translation(QString::fromUtf8(d->dictionaryManager->poWord(index, dictionaryIndex)), d->dictionaryManager->dictionaryName(dictionaryIndex), parseData(d->dictionaryManager->poWordData(index, dictionaryIndex).toUtf8(), dictionaryIndex, true, d->reformatLists, d->expandAbbreviations)); } QStringList StarDict::findSimilarWords(const QString &dictionary, const QString &word) { if (!d->loadedDictionaries.contains(dictionary)) return QStringList(); QStringList fuzzyList; if (!d->dictionaryManager->lookupWithFuzzy(word.toUtf8(), fuzzyList, d->maximumFuzzy, d->loadedDictionaries[dictionary])) return QStringList(); fuzzyList.reserve(d->maximumFuzzy); return fuzzyList; } // int // StarDict::execSettingsDialog(QWidget *parent) // { // MulaPluginStarDict::SettingsDialog dialog(this, parent); // return dialog.exec(); // } QString StarDict::parseData(const QByteArray &data, int dictionaryIndex, bool htmlSpaces, bool reformatLists, bool expandAbbreviations) { Q_UNUSED(expandAbbreviations); QString result; int position; foreach (char ch, data) { switch (ch) { case 'm': case 'l': case 'g': { position += data.length() + 1; result.append(QString::fromUtf8(data)); break; } case 't': { position += data.length() + 1; result.append("<font class=\"example\">"); result.append(QString::fromUtf8(data)); result.append("</font>"); break; } case 'x': { QString string = QString::fromUtf8(data); position += data.length() + 1; xdxf2html(string); result.append(string); break; } case 'y': { position += data.length() + 1; break; } case 'W': case 'P': { position += *reinterpret_cast<const quint32*>(data.data()) + sizeof(quint32); break; } default: ; // nothing } } if (d->expandAbbreviations) { QRegExp regExp("_\\S+[\\.:]"); int position = 0; while ((position = regExp.indexIn(result, position)) != -1) { int index; if (d->dictionaryManager->simpleLookupWord(result.mid(position, regExp.matchedLength()).toUtf8().data(), index, dictionaryIndex)) { QString expanded = "<font class=\"explanation\">"; expanded += parseData(d->dictionaryManager->poWordData(index, dictionaryIndex).toUtf8()); if (result[position + regExp.matchedLength() - 1] == ':') expanded += ':'; expanded += "</font>"; result.replace(position, regExp.matchedLength(), expanded); position += expanded.length(); } else position += regExp.matchedLength(); } } if (reformatLists) { int position = 0; QStack<QChar> openedLists; while (position < result.length()) { if (result[position].isDigit()) { int n = 0; while (result[position + n].isDigit()) ++n; position += n; if (result[position] == '&' && result.mid(position + 1, 3) == "gt;") result.replace(position, 4, ">"); QChar marker = result[position]; QString replacement; if (marker == '>' || marker == '.' || marker == ')') { if (n == 1 && result[position - 1] == '1') // open new list { if (openedLists.contains(marker)) { replacement = "</li></ol>"; while (openedLists.size() && openedLists.top() != marker) { replacement += "</li></ol>"; openedLists.pop(); } } openedLists.push(marker); replacement += "<ol>"; } else { while (openedLists.size() && openedLists.top() != marker) { replacement += "</li></ol>"; openedLists.pop(); } replacement += "</li>"; } replacement += "<li>"; position -= n; n += position; while (result[position - 1].isSpace()) --position; while (result[n + 1].isSpace()) ++n; result.replace(position, n - position + 1, replacement); position += replacement.length(); } else ++position; } else ++position; } while (openedLists.size()) { result.append("</li></ol>"); openedLists.pop(); } } if (htmlSpaces) { int n = 0; while (result[n].isSpace()) ++n; result.remove(0, n); n = 0; while (result[result.length() - 1 - n].isSpace()) ++n; result.remove(result.length() - n, n); for (int position = 0; position < result.length();) { switch (result[position].toAscii()) { case '[': result.insert(position, "<font class=\"transcription\">"); position += 28 + 1; // sizeof "<font class=\"transcription\">" + 1 break; case ']': result.insert(position + 1, "</font>"); position += 7 + 1; // sizeof "</font>" + 1 break; case '\t': result.insert(position, "&nbsp;&nbsp;&nbsp;&nbsp;"); position += 24 + 1; // sizeof "&nbsp;&nbsp;&nbsp;&nbsp;" + 1 break; case '\n': { int count = 1; n = 1; while (result[position + n].isSpace()) { if (result[position + n] == '\n') ++count; ++n; } if (count > 1) result.replace(position, n, "</p><p>"); else result.replace(position, n, "<br>"); break; } default: ++position; } } } return result; } QString StarDict::findDictionary(const QString &name, const QStringList &dictionaryDirectoryList) { d->ifoBookName = name; foreach (const QString& directoryPath, dictionaryDirectoryList) recursiveTemplateFind(directoryPath, &StarDict::findIfoFile); return d->ifoFileName; } void StarDict::xdxf2html(QString &string) { string.replace("<abr>", "<font class=\"abbreviature\">"); string.replace("<tr>", "<font class=\"transcription\">["); string.replace("</tr>", "]</font>"); string.replace("<ex>", "<font class=\"example\">"); string.remove(QRegExp("<k>.*<\\/k>")); string.replace(QRegExp("(<\\/abr>)|(<\\ex>)"), "</font"); } Q_EXPORT_PLUGIN2(stardict, StarDict) #include "stardict.moc" <commit_msg>Do not use "false" argument for the loadFromIfoFile method since it is default<commit_after>/****************************************************************************** * This file is part of the Mula project * Copyright (c) 2011 Laszlo Papp <lpapp@kde.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "stardict.h" #include "settingsdialog.h" #include "file.h" #include <core/dictionaryplugin.h> #include <QtCore/QList> #include <QtCore/QMap> #include <QtCore/QString> #include <QtCore/QCoreApplication> #include <QtCore/QDir> #include <QtCore/QFile> #include <QtCore/QSettings> #include <QtCore/QStack> #include <QtCore/QDebug> using namespace MulaPluginStarDict; class StarDict::Private { public: Private() : dictionaryManager(new StarDictDictionaryManager) , reformatLists(false) , expandAbbreviations(false) { } ~Private() { } StarDictDictionaryManager *dictionaryManager; QStringList dictionaryDirectoryList; QHash<QString, int> loadedDictionaries; bool reformatLists; bool expandAbbreviations; QString ifoBookName; QString ifoFileName; const static int maximumFuzzy = 24; }; StarDict::StarDict(QObject *parent) : QObject(parent) , d(new Private) { QSettings settings("mula","mula"); d->dictionaryDirectoryList = settings.value("StarDict/dictionaryDirectoryList", d->dictionaryDirectoryList).toStringList(); d->reformatLists = settings.value("StarDict/reformatLists", true).toBool(); d->expandAbbreviations = settings.value("StarDict/expandAbbreviations", true).toBool(); if (d->dictionaryDirectoryList.isEmpty()) { #ifdef Q_OS_UNIX d->dictionaryDirectoryList.append("/usr/share/stardict/dic"); #else d->dictionaryDirectoryList.append(QCoreApplication::applicationDirPath() + "/dic"); #endif d->dictionaryDirectoryList.append(QDir::homePath() + "/.stardict/dic"); } } StarDict::~StarDict() { QSettings settings("mula","mula"); settings.setValue("StarDict/dictionaryDirectoryList", d->dictionaryDirectoryList); settings.setValue("StarDict/reformatLists", d->reformatLists); settings.setValue("StarDict/expandAbbreviations", d->expandAbbreviations); delete d->dictionaryManager; } QString StarDict::name() const { return "stardict"; } QString StarDict::version() const { return "0.1"; } QString StarDict::description() const { return "The StarDict plugin"; } QStringList StarDict::authors() const { return QStringList() << "Laszlo Papp <lpapp@kde.org>"; } MulaCore::DictionaryPlugin::Features StarDict::features() const { return MulaCore::DictionaryPlugin::Features(SearchSimilar | SettingsDialog); } QString StarDict::findAvailableDictionary(const QString& absolutePath) { StarDictDictionaryInfo info; if (info.loadFromIfoFile(absolutePath)) return info.bookName(); return QString(); } QString StarDict::findIfoFile(const QString& absolutePath) { StarDictDictionaryInfo info; if (info.loadFromIfoFile(absolutePath) && info.bookName() == d->ifoBookName) d->ifoFileName = absolutePath; return QString(); } template <typename Method> QStringList StarDict::recursiveTemplateFind(const QString& directoryPath, Method method) { QDir dir(directoryPath); QStringList result; // Going through the subfolders foreach (const QString& entryName, dir.entryList(QDir::Dirs & QDir::NoDotAndDotDot)) { QString absolutePath = dir.absoluteFilePath(entryName); result.append(recursiveTemplateFind(absolutePath, method)); } foreach (const QString& entryName, dir.entryList(QDir::Files & QDir::Drives & QDir::NoDotAndDotDot)) { QString absolutePath = dir.absoluteFilePath(entryName); if (absolutePath.endsWith(QLatin1String(".ifo"))) result.append((this->*method)(absolutePath)); } return result; } QStringList StarDict::availableDictionaryList() { QStringList result; foreach (const QString& directoryPath, d->dictionaryDirectoryList) result.append(recursiveTemplateFind(directoryPath, &StarDict::findAvailableDictionary)); return result; } QStringList StarDict::loadedDictionaryList() const { return d->loadedDictionaries.keys(); } void StarDict::setLoadedDictionaryList(const QStringList &loadedDictionaryList) { QStringList availableDictionaries = availableDictionaryList(); QStringList disabledDictionaries; foreach (const QString& dictionary, availableDictionaries) { if (!loadedDictionaryList.contains(dictionary)) disabledDictionaries.append(dictionary); } d->dictionaryManager->reload(d->dictionaryDirectoryList, loadedDictionaryList, disabledDictionaries); d->loadedDictionaries.clear(); for (int i = 0; i < d->dictionaryManager->dictionaryCount(); ++i) d->loadedDictionaries[d->dictionaryManager->dictionaryName(i)] = i; } MulaCore::DictionaryInfo StarDict::dictionaryInfo(const QString &dictionary) { StarDictDictionaryInfo nativeInfo; nativeInfo.setWordCount(0); if (!nativeInfo.loadFromIfoFile(findDictionary(dictionary, d->dictionaryDirectoryList))) return MulaCore::DictionaryInfo(); MulaCore::DictionaryInfo result(name(), dictionary); result.setAuthor(nativeInfo.author()); result.setDescription(nativeInfo.description()); result.setWordCount(nativeInfo.wordCount() ? static_cast<long>(nativeInfo.wordCount()) : -1); return result; } bool StarDict::isTranslatable(const QString &dictionary, const QString &word) { if (!d->loadedDictionaries.contains(dictionary)) return false; int index; return d->dictionaryManager->simpleLookupWord(word.toUtf8().data(), index, d->loadedDictionaries[dictionary]); } MulaCore::Translation StarDict::translate(const QString &dictionary, const QString &word) { if (!d->loadedDictionaries.contains(dictionary) || word.isEmpty()) return MulaCore::Translation(); int dictionaryIndex = d->loadedDictionaries[dictionary]; int index; if (!d->dictionaryManager->simpleLookupWord(word.toUtf8().data(), index, d->loadedDictionaries[dictionary])) return MulaCore::Translation(); return MulaCore::Translation(QString::fromUtf8(d->dictionaryManager->poWord(index, dictionaryIndex)), d->dictionaryManager->dictionaryName(dictionaryIndex), parseData(d->dictionaryManager->poWordData(index, dictionaryIndex).toUtf8(), dictionaryIndex, true, d->reformatLists, d->expandAbbreviations)); } QStringList StarDict::findSimilarWords(const QString &dictionary, const QString &word) { if (!d->loadedDictionaries.contains(dictionary)) return QStringList(); QStringList fuzzyList; if (!d->dictionaryManager->lookupWithFuzzy(word.toUtf8(), fuzzyList, d->maximumFuzzy, d->loadedDictionaries[dictionary])) return QStringList(); fuzzyList.reserve(d->maximumFuzzy); return fuzzyList; } // int // StarDict::execSettingsDialog(QWidget *parent) // { // MulaPluginStarDict::SettingsDialog dialog(this, parent); // return dialog.exec(); // } QString StarDict::parseData(const QByteArray &data, int dictionaryIndex, bool htmlSpaces, bool reformatLists, bool expandAbbreviations) { Q_UNUSED(expandAbbreviations); QString result; int position; foreach (char ch, data) { switch (ch) { case 'm': case 'l': case 'g': { position += data.length() + 1; result.append(QString::fromUtf8(data)); break; } case 't': { position += data.length() + 1; result.append("<font class=\"example\">"); result.append(QString::fromUtf8(data)); result.append("</font>"); break; } case 'x': { QString string = QString::fromUtf8(data); position += data.length() + 1; xdxf2html(string); result.append(string); break; } case 'y': { position += data.length() + 1; break; } case 'W': case 'P': { position += *reinterpret_cast<const quint32*>(data.data()) + sizeof(quint32); break; } default: ; // nothing } } if (d->expandAbbreviations) { QRegExp regExp("_\\S+[\\.:]"); int position = 0; while ((position = regExp.indexIn(result, position)) != -1) { int index; if (d->dictionaryManager->simpleLookupWord(result.mid(position, regExp.matchedLength()).toUtf8().data(), index, dictionaryIndex)) { QString expanded = "<font class=\"explanation\">"; expanded += parseData(d->dictionaryManager->poWordData(index, dictionaryIndex).toUtf8()); if (result[position + regExp.matchedLength() - 1] == ':') expanded += ':'; expanded += "</font>"; result.replace(position, regExp.matchedLength(), expanded); position += expanded.length(); } else position += regExp.matchedLength(); } } if (reformatLists) { int position = 0; QStack<QChar> openedLists; while (position < result.length()) { if (result[position].isDigit()) { int n = 0; while (result[position + n].isDigit()) ++n; position += n; if (result[position] == '&' && result.mid(position + 1, 3) == "gt;") result.replace(position, 4, ">"); QChar marker = result[position]; QString replacement; if (marker == '>' || marker == '.' || marker == ')') { if (n == 1 && result[position - 1] == '1') // open new list { if (openedLists.contains(marker)) { replacement = "</li></ol>"; while (openedLists.size() && openedLists.top() != marker) { replacement += "</li></ol>"; openedLists.pop(); } } openedLists.push(marker); replacement += "<ol>"; } else { while (openedLists.size() && openedLists.top() != marker) { replacement += "</li></ol>"; openedLists.pop(); } replacement += "</li>"; } replacement += "<li>"; position -= n; n += position; while (result[position - 1].isSpace()) --position; while (result[n + 1].isSpace()) ++n; result.replace(position, n - position + 1, replacement); position += replacement.length(); } else ++position; } else ++position; } while (openedLists.size()) { result.append("</li></ol>"); openedLists.pop(); } } if (htmlSpaces) { int n = 0; while (result[n].isSpace()) ++n; result.remove(0, n); n = 0; while (result[result.length() - 1 - n].isSpace()) ++n; result.remove(result.length() - n, n); for (int position = 0; position < result.length();) { switch (result[position].toAscii()) { case '[': result.insert(position, "<font class=\"transcription\">"); position += 28 + 1; // sizeof "<font class=\"transcription\">" + 1 break; case ']': result.insert(position + 1, "</font>"); position += 7 + 1; // sizeof "</font>" + 1 break; case '\t': result.insert(position, "&nbsp;&nbsp;&nbsp;&nbsp;"); position += 24 + 1; // sizeof "&nbsp;&nbsp;&nbsp;&nbsp;" + 1 break; case '\n': { int count = 1; n = 1; while (result[position + n].isSpace()) { if (result[position + n] == '\n') ++count; ++n; } if (count > 1) result.replace(position, n, "</p><p>"); else result.replace(position, n, "<br>"); break; } default: ++position; } } } return result; } QString StarDict::findDictionary(const QString &name, const QStringList &dictionaryDirectoryList) { d->ifoBookName = name; foreach (const QString& directoryPath, dictionaryDirectoryList) recursiveTemplateFind(directoryPath, &StarDict::findIfoFile); return d->ifoFileName; } void StarDict::xdxf2html(QString &string) { string.replace("<abr>", "<font class=\"abbreviature\">"); string.replace("<tr>", "<font class=\"transcription\">["); string.replace("</tr>", "]</font>"); string.replace("<ex>", "<font class=\"example\">"); string.remove(QRegExp("<k>.*<\\/k>")); string.replace(QRegExp("(<\\/abr>)|(<\\ex>)"), "</font"); } Q_EXPORT_PLUGIN2(stardict, StarDict) #include "stardict.moc" <|endoftext|>
<commit_before>// // This file is part of the Marble Desktop Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2006-2007 Torsten Rahn <tackat@kde.org> // Copyright 2007 Inge Wallin <ingwa@kde.org> // #include <QtGui/QApplication> #include <QtCore/QFile> #include <QtCore/QDir> #include <QtCore/QLocale> #include <QtCore/QSettings> #include <QtCore/QTranslator> #include "QtMainWindow.h" #include "MarbleDirs.h" #include "MarbleDebug.h" #include "MarbleTest.h" #ifdef STATIC_BUILD #include <QtCore/QtPlugin> Q_IMPORT_PLUGIN(qjpeg) Q_IMPORT_PLUGIN(qsvg) #endif #ifdef Q_OS_MACX //for getting app bundle path #include <ApplicationServices/ApplicationServices.h> #endif using namespace Marble; int main(int argc, char *argv[]) { // The GraphicsSystem needs to be set before the instantiation of the // QApplication. Therefore we need to parse the current setting // in this unusual place :-/ QSettings * graphicsSettings = new QSettings("kde.org", "Marble Desktop Globe"); QString graphicsString = graphicsSettings->value("View/graphicsSystem", "native").toString(); delete graphicsSettings; QApplication::setGraphicsSystem( graphicsString ); QApplication app(argc, argv); // Widget translation QString lang = QLocale::system().name().section('_', 0, 0); QTranslator translator; translator.load( "marble-" + lang, MarbleDirs::path(QString("lang") ) ); app.installTranslator(&translator); // For non static builds on mac and win // we need to be sure we can find the qt image // plugins. In mac be sure to look in the // application bundle... #ifdef Q_WS_WIN QApplication::addLibraryPath( QApplication::applicationDirPath() + QDir::separator() + "plugins" ); #endif #ifdef Q_OS_MACX qDebug("Adding qt image plugins to plugin search path..."); CFURLRef myBundleRef = CFBundleCopyBundleURL(CFBundleGetMainBundle()); CFStringRef myMacPath = CFURLCopyFileSystemPath(myBundleRef, kCFURLPOSIXPathStyle); const char *mypPathPtr = CFStringGetCStringPtr(myMacPath,CFStringGetSystemEncoding()); CFRelease(myBundleRef); CFRelease(myMacPath); QString myPath(mypPathPtr); // if we are not in a bundle assume that the app is built // as a non bundle app and that image plugins will be // in system Qt frameworks. If the app is a bundle // lets try to set the qt plugin search path... if (myPath.contains(".app")) { myPath += "/Contents/plugins"; QApplication::addLibraryPath( myPath ); qDebug( "Added %s to plugin search path", qPrintable( myPath ) ); } #endif QString marbleDataPath; int dataPathIndex=0; MarbleGlobal::Profiles profiles = MarbleGlobal::detectProfiles(); QStringList args = QApplication::arguments(); for ( int i = 1; i < args.count(); ++i ) { const QString arg = args.at(i); if ( arg == "--debug-info" ) { MarbleDebug::enable = true; } else if ( arg.startsWith( "--marbledatapath=", Qt::CaseInsensitive ) ) { marbleDataPath = args.at(i).mid(17); } else if ( arg.compare( "--marbledatapath", Qt::CaseInsensitive ) ) { dataPathIndex = i + 1; marbleDataPath = args.value( dataPathIndex ); ++i; } else if ( arg == "--smallscreen" ) { profiles |= MarbleGlobal::SmallScreen; } else if ( arg == "--nosmallscreen" ) { profiles &= ~MarbleGlobal::SmallScreen; } else if ( arg == "--highresolution" ) { profiles |= MarbleGlobal::HighResolution; } else if ( arg == "--nohighresolution" ) { profiles &= ~MarbleGlobal::HighResolution; } } MarbleGlobal::getInstance()->setProfiles( profiles ); MainWindow *window = new MainWindow( marbleDataPath ); window->setAttribute( Qt::WA_DeleteOnClose, true ); MarbleTest *marbleTest = new MarbleTest( window->marbleWidget() ); // window->marbleWidget()->rotateTo( 0, 0, -90 ); // window->show(); for ( int i = 1; i < args.count(); ++i ) { const QString arg = args.at(i); if ( arg == "--timedemo" ) { window->resize(900, 640); marbleTest->timeDemo(); return 0; } else if( arg == "--gpsdemo" ) { window->resize( 900, 640 ); marbleTest->gpsDemo(); return 0; } else if( arg == "--fps" ) { window->marbleControl()->marbleWidget()->setShowFrameRate( true ); } else if( arg == "--enableCurrentLocation" ) { window->marbleControl()->setCurrentLocationTabShown(true); } else if( arg == "--enableFileView" ) { window->marbleControl()->setFileViewTabShown(true); } else if ( arg == "--tile-id" ) { window->marbleControl()->marbleWidget()->setShowTileId(true); } else if ( i != dataPathIndex && QFile::exists( arg ) ) ( window->marbleControl() )->addPlacemarkFile( arg ); } delete marbleTest; return app.exec(); } <commit_msg>QString::compare returns an integer, not a boolean. Compare against 0, fixes every argument being interpreted as a data path, except data path itself.<commit_after>// // This file is part of the Marble Desktop Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2006-2007 Torsten Rahn <tackat@kde.org> // Copyright 2007 Inge Wallin <ingwa@kde.org> // #include <QtGui/QApplication> #include <QtCore/QFile> #include <QtCore/QDir> #include <QtCore/QLocale> #include <QtCore/QSettings> #include <QtCore/QTranslator> #include "QtMainWindow.h" #include "MarbleDirs.h" #include "MarbleDebug.h" #include "MarbleTest.h" #ifdef STATIC_BUILD #include <QtCore/QtPlugin> Q_IMPORT_PLUGIN(qjpeg) Q_IMPORT_PLUGIN(qsvg) #endif #ifdef Q_OS_MACX //for getting app bundle path #include <ApplicationServices/ApplicationServices.h> #endif using namespace Marble; int main(int argc, char *argv[]) { // The GraphicsSystem needs to be set before the instantiation of the // QApplication. Therefore we need to parse the current setting // in this unusual place :-/ QSettings * graphicsSettings = new QSettings("kde.org", "Marble Desktop Globe"); QString graphicsString = graphicsSettings->value("View/graphicsSystem", "native").toString(); delete graphicsSettings; QApplication::setGraphicsSystem( graphicsString ); QApplication app(argc, argv); // Widget translation QString lang = QLocale::system().name().section('_', 0, 0); QTranslator translator; translator.load( "marble-" + lang, MarbleDirs::path(QString("lang") ) ); app.installTranslator(&translator); // For non static builds on mac and win // we need to be sure we can find the qt image // plugins. In mac be sure to look in the // application bundle... #ifdef Q_WS_WIN QApplication::addLibraryPath( QApplication::applicationDirPath() + QDir::separator() + "plugins" ); #endif #ifdef Q_OS_MACX qDebug("Adding qt image plugins to plugin search path..."); CFURLRef myBundleRef = CFBundleCopyBundleURL(CFBundleGetMainBundle()); CFStringRef myMacPath = CFURLCopyFileSystemPath(myBundleRef, kCFURLPOSIXPathStyle); const char *mypPathPtr = CFStringGetCStringPtr(myMacPath,CFStringGetSystemEncoding()); CFRelease(myBundleRef); CFRelease(myMacPath); QString myPath(mypPathPtr); // if we are not in a bundle assume that the app is built // as a non bundle app and that image plugins will be // in system Qt frameworks. If the app is a bundle // lets try to set the qt plugin search path... if (myPath.contains(".app")) { myPath += "/Contents/plugins"; QApplication::addLibraryPath( myPath ); qDebug( "Added %s to plugin search path", qPrintable( myPath ) ); } #endif QString marbleDataPath; int dataPathIndex=0; MarbleGlobal::Profiles profiles = MarbleGlobal::detectProfiles(); QStringList args = QApplication::arguments(); for ( int i = 1; i < args.count(); ++i ) { const QString arg = args.at(i); if ( arg == "--debug-info" ) { MarbleDebug::enable = true; } else if ( arg.startsWith( "--marbledatapath=", Qt::CaseInsensitive ) ) { marbleDataPath = args.at(i).mid(17); } else if ( arg.compare( "--marbledatapath", Qt::CaseInsensitive ) == 0 ) { dataPathIndex = i + 1; marbleDataPath = args.value( dataPathIndex ); ++i; } else if ( arg == "--smallscreen" ) { profiles |= MarbleGlobal::SmallScreen; } else if ( arg == "--nosmallscreen" ) { profiles &= ~MarbleGlobal::SmallScreen; } else if ( arg == "--highresolution" ) { profiles |= MarbleGlobal::HighResolution; } else if ( arg == "--nohighresolution" ) { profiles &= ~MarbleGlobal::HighResolution; } } MarbleGlobal::getInstance()->setProfiles( profiles ); MainWindow *window = new MainWindow( marbleDataPath ); window->setAttribute( Qt::WA_DeleteOnClose, true ); MarbleTest *marbleTest = new MarbleTest( window->marbleWidget() ); // window->marbleWidget()->rotateTo( 0, 0, -90 ); // window->show(); for ( int i = 1; i < args.count(); ++i ) { const QString arg = args.at(i); if ( arg == "--timedemo" ) { window->resize(900, 640); marbleTest->timeDemo(); return 0; } else if( arg == "--gpsdemo" ) { window->resize( 900, 640 ); marbleTest->gpsDemo(); return 0; } else if( arg == "--fps" ) { window->marbleControl()->marbleWidget()->setShowFrameRate( true ); } else if( arg == "--enableCurrentLocation" ) { window->marbleControl()->setCurrentLocationTabShown(true); } else if( arg == "--enableFileView" ) { window->marbleControl()->setFileViewTabShown(true); } else if ( arg == "--tile-id" ) { window->marbleControl()->marbleWidget()->setShowTileId(true); } else if ( i != dataPathIndex && QFile::exists( arg ) ) ( window->marbleControl() )->addPlacemarkFile( arg ); } delete marbleTest; return app.exec(); } <|endoftext|>
<commit_before>#include "robobo.h" int main(int argc, char** argv) { std::string workingDir (argv[0]); workingDir = workingDir.substr(0, workingDir.find_last_of('/')); std::string confName ("robobo.conf"); unsigned short debugLevel = 0; if (argc > 1) { opterr = 0; option validOptions[] = { {"help", 0, nullptr, 'h'}, {"version", 0, nullptr, 'v'}, {"debug", 2, nullptr, 'd'}, {"confname", 1, nullptr, 1} }; int optCode; while ((optCode = getopt_long(argc, argv, "h?vd::", validOptions, nullptr)) != EOF) { switch (optCode) { case 'h': case '?': std::cout << "RoBoBo IRC Bot Help" << std::endl; std::cout << std::endl; std::cout << "Start the bot without any parameters to start it normally." << std::endl; std::cout << "--help/-h: Displays this help notice" << std::endl; std::cout << "--version/-v: Displays bot version" << std::endl; std::cout << "--debug/-d: Starts the bot in debug mode (foreground, sends information to standard output)" << std::endl; std::cout << "\tSpecify level 1, 2, or 3 after it for more information" << std::endl; std::cout << "\tIf the debug argument is given with no level, level 1 is assumed." << std::endl; std::cout << "--confname: Specifies the name of the configuration file, along with a directory" << std::endl; std::cout << "\tif it's not in the main robobo directory (default: robobo.conf)" << std::endl; std::cout << "\te.g. '--confname ../test.conf' or '--confname /etc/robobo.conf'" << std::endl; std::cout << "\tRelative paths are relative to the main robobo directory." << std::endl; return 0; case 'v': std::cout << "RoBoBo IRC Bot " << BotVersion << std::endl; return 0; case 'd': if (optarg == 0) debugLevel = 1; else { std::istringstream debugStr (optarg); debugStr >> debugLevel; } if (debugLevel > 4) debugLevel = 4; break; case 1: confName = optarg; } } } // Default the configuration to the working directory if an absolute path is not provided // If a relative path is provided, it should be relative to the working directory if (confName[0] != '/') confName = workingDir + "/" + confName; Config* configuration = Config::getHandle(); LogManager* logger = LogManager::getHandle(); logger->setLogDir(workingDir + "/logs/"); logger->setDefaultLevel(static_cast<LogLevel> (debugLevel)); configuration->setMainConfigFile(confName); configuration->setWorkingDirectory(workingDir); configuration->addRehashNotify(std::bind(&LogManager::updateLogFiles, logger)); configuration->readConfig(); // TODO: module manager and server manager // Add signal handlers sigset_t signalSet; sigemptyset(&signalSet); sigaddset(&signalSet, SIGHUP); sigaddset(&signalSet, SIGUSR1); struct sigaction sigHandle; sigHandle.sa_handler = [&](int signum) { if (signum == SIGHUP) { daemon(1, 0); // TODO: notify server manager? and module manager of the end of debug } else if (signum == SIGUSR1) { configuration->readConfig(); // TODO: notify module manager of rehash }; sigHandle.sa_mask = signalSet; sigHandle.sa_flags = 0; const struct sigaction* sigPtr = &sigHandle; sigaction(SIGHUP, sigPtr, nullptr); sigaction(SIGUSR1, sigPtr, nullptr); /* bot = new Base (workingDir, confDir, confName, debugLevel, logDump); bot->readConfiguration(); bot->loadModules(); bot->connectServers(); if (debugLevel == 0) daemon(1, 0); bot->checkServers(); // If checkModules returns, the bot is shutting down, so kill all the things bot->unloadEverything(); delete bot; */ }<commit_msg>Actually handle the signals<commit_after>#include "robobo.h" int main(int argc, char** argv) { std::string workingDir (argv[0]); workingDir = workingDir.substr(0, workingDir.find_last_of('/')); std::string confName ("robobo.conf"); unsigned short debugLevel = 0; if (argc > 1) { opterr = 0; option validOptions[] = { {"help", 0, nullptr, 'h'}, {"version", 0, nullptr, 'v'}, {"debug", 2, nullptr, 'd'}, {"confname", 1, nullptr, 1} }; int optCode; while ((optCode = getopt_long(argc, argv, "h?vd::", validOptions, nullptr)) != EOF) { switch (optCode) { case 'h': case '?': std::cout << "RoBoBo IRC Bot Help" << std::endl; std::cout << std::endl; std::cout << "Start the bot without any parameters to start it normally." << std::endl; std::cout << "--help/-h: Displays this help notice" << std::endl; std::cout << "--version/-v: Displays bot version" << std::endl; std::cout << "--debug/-d: Starts the bot in debug mode (foreground, sends information to standard output)" << std::endl; std::cout << "\tSpecify level 1, 2, or 3 after it for more information" << std::endl; std::cout << "\tIf the debug argument is given with no level, level 1 is assumed." << std::endl; std::cout << "--confname: Specifies the name of the configuration file, along with a directory" << std::endl; std::cout << "\tif it's not in the main robobo directory (default: robobo.conf)" << std::endl; std::cout << "\te.g. '--confname ../test.conf' or '--confname /etc/robobo.conf'" << std::endl; std::cout << "\tRelative paths are relative to the main robobo directory." << std::endl; return 0; case 'v': std::cout << "RoBoBo IRC Bot " << BotVersion << std::endl; return 0; case 'd': if (optarg == 0) debugLevel = 1; else { std::istringstream debugStr (optarg); debugStr >> debugLevel; } if (debugLevel > 4) debugLevel = 4; break; case 1: confName = optarg; } } } // Default the configuration to the working directory if an absolute path is not provided // If a relative path is provided, it should be relative to the working directory if (confName[0] != '/') confName = workingDir + "/" + confName; Config* configuration = Config::getHandle(); LogManager* logger = LogManager::getHandle(); logger->setLogDir(workingDir + "/logs/"); logger->setDefaultLevel(static_cast<LogLevel> (debugLevel)); configuration->setMainConfigFile(confName); configuration->setWorkingDirectory(workingDir); configuration->addRehashNotify(std::bind(&LogManager::updateLogFiles, logger)); configuration->readConfig(); // TODO: module manager and server manager // Add signal handlers sigset_t signalSet; sigemptyset(&signalSet); sigaddset(&signalSet, SIGHUP); sigaddset(&signalSet, SIGUSR1); struct sigaction sigHandle; sigHandle.sa_handler = [](int signum) { if (signum == SIGHUP) { daemon(1, 0); LogManager* logger = LogManager::getHandle(); logger->setDefaultLevel(LOG_NONE); } else if (signum == SIGUSR1) { Config* config = Config::getHandle(); config->readConfig(); } }; sigHandle.sa_mask = signalSet; sigHandle.sa_flags = 0; const struct sigaction* sigPtr = &sigHandle; sigaction(SIGHUP, sigPtr, nullptr); sigaction(SIGUSR1, sigPtr, nullptr); /* bot = new Base (workingDir, confDir, confName, debugLevel, logDump); bot->readConfiguration(); bot->loadModules(); bot->connectServers(); if (debugLevel == 0) daemon(1, 0); bot->checkServers(); // If checkModules returns, the bot is shutting down, so kill all the things bot->unloadEverything(); delete bot; */ }<|endoftext|>
<commit_before>#include "switch.h" #include <functional> using namespace std::placeholders; Switch::Switch(const char* name, bool isSmart, int inputPin, int outputPin) : _name(name), _inputPin(inputPin), _outputPin(outputPin), _isSmart(isSmart) { _input = new Pressing(inputPin, HIGH, 400); auto didPressButton = std::bind(&Switch::didToggleViaHW, this); auto didToggleManualOverride = std::bind(&Switch::didToggleManualOverride, this); // auto handleClickAndHold = std::bind(&Switch::handleClickAndHold, this); _input->onClick(1, didPressButton); _input->onClick(5, didToggleManualOverride); // _input->onHold(1, handleClickAndHold); _input->setToggleMode(true); _input->onToggle(didPressButton); pinMode(outputPin, OUTPUT); _node = new HomieNode(name, "switch"); auto didToggleViaMQTT = std::bind(&Switch::didToggleViaMQTT, this, _1, _2); _node->advertise("on").settable(didToggleViaMQTT); } void Switch::loop() { _input->loop(); } void Switch::setDebug(bool debug) { _debug = debug; } // Handle any connect or disconnect events and set the current status. void Switch::onHomieEvent(HomieEvent event) { switch(event.type) { case HomieEventType::MQTT_CONNECTED: if (_debug) { Homie.getLogger() << "Received connected event\n"; } this->didComeOnline(); _isOnline = true; break; case HomieEventType::WIFI_DISCONNECTED: case HomieEventType::MQTT_DISCONNECTED: if (_debug) { Homie.getLogger() << "Received disconnected event\n"; } this->didGoOffline(); _isOnline = false; break; } } // offlineMode returns true if we aren't online, or if we're in manual override. bool Switch::isOfflineMode() { return !_isOnline || _isManualOverride; } void Switch::emitState() { if (_debug) { Homie.getLogger() << _name; Homie.getLogger() << " Emitting State: "; Homie.getLogger() << (_currentState ? "true\n" : "false\n"); } _node->setProperty("on").send(_currentState ? "true" : "false"); } void Switch::setOutputToState(bool state) { if (_debug) { Homie.getLogger() << _name; Homie.getLogger() << " Setting Relay Output to "; Homie.getLogger() << (_currentState ? "true\n" : "false\n"); } digitalWrite(_outputPin, state ? HIGH : LOW); } void Switch::didComeOnline() { if (!_isSmart) { this->emitState(); return; } if (!_hasChangedSinceOffline) { return; } if (_currentState == false) { this->setOutputToState(true); // Delay 1 second delayMicroseconds(1000000); } this->emitState(); } void Switch::didGoOffline() { if (this->isOfflineMode()) { return; } _hasChangedSinceOffline = false; } bool Switch::didToggleViaMQTT(HomieRange range, String value) { if (_debug) { Homie.getLogger() << _name; Homie.getLogger() << " toggled via MQTT\n"; } bool newState = value == "true"; if (_currentState == newState) { return true; } _currentState = !_currentState; if (!_isSmart) { this->setOutputToState(_currentState); } return true; } void Switch::didToggleViaHW() { if (_debug) { Homie.getLogger() << _name; Homie.getLogger() << " toggled via Hardware\n"; } _currentState = !_currentState; if (!this->isOfflineMode()) { this->emitState(); if (!_isSmart) { this->setOutputToState(_currentState); } return; } if (!_isSmart) { this->setOutputToState(_currentState); return; } if (_currentState == false) { this->setOutputToState(false); return; } if (_relayState == true) { this->setOutputToState(false); // Delay 1 second delayMicroseconds(1000000); } this->setOutputToState(true); } // TODO: Add this to flow chart void Switch::didToggleManualOverride() { if (_debug) { Homie.getLogger() << _name; Homie.getLogger() << " toggled manual override\n"; } _isManualOverride = !_isManualOverride; // Are we going offline? if (_isManualOverride && _isOnline) { this->didGoOffline(); // Are we coming online? } else if (!_isManualOverride && _isOnline) { this->didComeOnline(); } } void Switch::handleClickAndHold(int duration) { if (_debug) { Homie.getLogger() << _name; Homie.getLogger() << " click and held\n"; } } <commit_msg>Add initial state handling<commit_after>#include "switch.h" #include <functional> using namespace std::placeholders; Switch::Switch(const char* name, bool isSmart, int inputPin, int outputPin) : _name(name), _inputPin(inputPin), _outputPin(outputPin), _isSmart(isSmart) { _input = new Pressing(inputPin, HIGH, 400); auto didPressButton = std::bind(&Switch::didToggleViaHW, this); auto didToggleManualOverride = std::bind(&Switch::didToggleManualOverride, this); // auto handleClickAndHold = std::bind(&Switch::handleClickAndHold, this); _input->onClick(1, didPressButton); _input->onClick(5, didToggleManualOverride); // _input->onHold(1, handleClickAndHold); _input->setToggleMode(true); _input->onToggle(didPressButton); pinMode(outputPin, OUTPUT); _node = new HomieNode(name, "switch"); auto didToggleViaMQTT = std::bind(&Switch::didToggleViaMQTT, this, _1, _2); _node->advertise("on").settable(didToggleViaMQTT); // Now we need to set some initial state. if (_isSmart) { this->setOutputToState(true); } else { this->setOutputToState(_currentState); } } void Switch::loop() { _input->loop(); } void Switch::setDebug(bool debug) { _debug = debug; } // Handle any connect or disconnect events and set the current status. void Switch::onHomieEvent(HomieEvent event) { switch(event.type) { case HomieEventType::MQTT_CONNECTED: if (_debug) { Homie.getLogger() << "Received connected event\n"; } this->didComeOnline(); _isOnline = true; break; case HomieEventType::WIFI_DISCONNECTED: case HomieEventType::MQTT_DISCONNECTED: if (_debug) { Homie.getLogger() << "Received disconnected event\n"; } this->didGoOffline(); _isOnline = false; break; } } // offlineMode returns true if we aren't online, or if we're in manual override. bool Switch::isOfflineMode() { return !_isOnline || _isManualOverride; } void Switch::emitState() { if (_debug) { Homie.getLogger() << _name; Homie.getLogger() << " Emitting State: "; Homie.getLogger() << (_currentState ? "true\n" : "false\n"); } _node->setProperty("on").send(_currentState ? "true" : "false"); } void Switch::setOutputToState(bool state) { if (_debug) { Homie.getLogger() << _name; Homie.getLogger() << " Setting Relay Output to "; Homie.getLogger() << (_currentState ? "true\n" : "false\n"); } digitalWrite(_outputPin, state ? HIGH : LOW); } void Switch::didComeOnline() { if (!_isSmart) { this->emitState(); return; } if (!_hasChangedSinceOffline) { return; } if (_currentState == false) { this->setOutputToState(true); // Delay 1 second delayMicroseconds(1000000); } this->emitState(); } void Switch::didGoOffline() { if (this->isOfflineMode()) { return; } _hasChangedSinceOffline = false; } bool Switch::didToggleViaMQTT(HomieRange range, String value) { if (_debug) { Homie.getLogger() << _name; Homie.getLogger() << " toggled via MQTT\n"; } bool newState = value == "true"; if (_currentState == newState) { // While this shouldn't be necessary, if the state somehow gets out of sync // with the mqtt state, this is required to bring it back in line. this->emitState(); return true; } _currentState = !_currentState; if (!_isSmart) { this->setOutputToState(_currentState); } this->emitState(); return true; } void Switch::didToggleViaHW() { if (_debug) { Homie.getLogger() << _name; Homie.getLogger() << " toggled via Hardware\n"; } _currentState = !_currentState; if (!this->isOfflineMode()) { this->emitState(); if (!_isSmart) { this->setOutputToState(_currentState); } return; } if (!_isSmart) { this->setOutputToState(_currentState); return; } if (_currentState == false) { this->setOutputToState(false); return; } if (_relayState == true) { this->setOutputToState(false); // Delay 1 second delayMicroseconds(1000000); } this->setOutputToState(true); } // TODO: Add this to flow chart void Switch::didToggleManualOverride() { if (_debug) { Homie.getLogger() << _name; Homie.getLogger() << " toggled manual override\n"; } _isManualOverride = !_isManualOverride; // Are we going offline? if (_isManualOverride && _isOnline) { this->didGoOffline(); // Are we coming online? } else if (!_isManualOverride && _isOnline) { this->didComeOnline(); } } void Switch::handleClickAndHold(int duration) { if (_debug) { Homie.getLogger() << _name; Homie.getLogger() << " click and held\n"; } } <|endoftext|>
<commit_before>// Copyright 2012 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/v8.h" #include "src/version.h" // These macros define the version number for the current version. // NOTE these macros are used by some of the tool scripts and the build // system so their names cannot be changed without changing the scripts. #define MAJOR_VERSION 3 #define MINOR_VERSION 29 #define BUILD_NUMBER 45 #define PATCH_LEVEL 0 // Use 1 for candidates and 0 otherwise. // (Boolean macro values are not supported by all preprocessors.) #define IS_CANDIDATE_VERSION 1 // Define SONAME to have the build system put a specific SONAME into the // shared library instead the generic SONAME generated from the V8 version // number. This define is mainly used by the build system script. #define SONAME "" #if IS_CANDIDATE_VERSION #define CANDIDATE_STRING " (candidate)" #else #define CANDIDATE_STRING "" #endif #define SX(x) #x #define S(x) SX(x) #if PATCH_LEVEL > 0 #define VERSION_STRING \ S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "." \ S(PATCH_LEVEL) CANDIDATE_STRING #else #define VERSION_STRING \ S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) \ CANDIDATE_STRING #endif namespace v8 { namespace internal { int Version::major_ = MAJOR_VERSION; int Version::minor_ = MINOR_VERSION; int Version::build_ = BUILD_NUMBER; int Version::patch_ = PATCH_LEVEL; bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0); const char* Version::soname_ = SONAME; const char* Version::version_string_ = VERSION_STRING; // Calculate the V8 version string. void Version::GetString(Vector<char> str) { const char* candidate = IsCandidate() ? " (candidate)" : ""; #ifdef USE_SIMULATOR const char* is_simulator = " SIMULATOR"; #else const char* is_simulator = ""; #endif // USE_SIMULATOR if (GetPatch() > 0) { SNPrintF(str, "%d.%d.%d.%d%s%s", GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate, is_simulator); } else { SNPrintF(str, "%d.%d.%d%s%s", GetMajor(), GetMinor(), GetBuild(), candidate, is_simulator); } } // Calculate the SONAME for the V8 shared library. void Version::GetSONAME(Vector<char> str) { if (soname_ == NULL || *soname_ == '\0') { // Generate generic SONAME if no specific SONAME is defined. const char* candidate = IsCandidate() ? "-candidate" : ""; if (GetPatch() > 0) { SNPrintF(str, "libv8-%d.%d.%d.%d%s.so", GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate); } else { SNPrintF(str, "libv8-%d.%d.%d%s.so", GetMajor(), GetMinor(), GetBuild(), candidate); } } else { // Use specific SONAME. SNPrintF(str, "%s", soname_); } } } } // namespace v8::internal <commit_msg>[Auto-roll] Bump up version to 3.29.46.0<commit_after>// Copyright 2012 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/v8.h" #include "src/version.h" // These macros define the version number for the current version. // NOTE these macros are used by some of the tool scripts and the build // system so their names cannot be changed without changing the scripts. #define MAJOR_VERSION 3 #define MINOR_VERSION 29 #define BUILD_NUMBER 46 #define PATCH_LEVEL 0 // Use 1 for candidates and 0 otherwise. // (Boolean macro values are not supported by all preprocessors.) #define IS_CANDIDATE_VERSION 1 // Define SONAME to have the build system put a specific SONAME into the // shared library instead the generic SONAME generated from the V8 version // number. This define is mainly used by the build system script. #define SONAME "" #if IS_CANDIDATE_VERSION #define CANDIDATE_STRING " (candidate)" #else #define CANDIDATE_STRING "" #endif #define SX(x) #x #define S(x) SX(x) #if PATCH_LEVEL > 0 #define VERSION_STRING \ S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "." \ S(PATCH_LEVEL) CANDIDATE_STRING #else #define VERSION_STRING \ S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) \ CANDIDATE_STRING #endif namespace v8 { namespace internal { int Version::major_ = MAJOR_VERSION; int Version::minor_ = MINOR_VERSION; int Version::build_ = BUILD_NUMBER; int Version::patch_ = PATCH_LEVEL; bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0); const char* Version::soname_ = SONAME; const char* Version::version_string_ = VERSION_STRING; // Calculate the V8 version string. void Version::GetString(Vector<char> str) { const char* candidate = IsCandidate() ? " (candidate)" : ""; #ifdef USE_SIMULATOR const char* is_simulator = " SIMULATOR"; #else const char* is_simulator = ""; #endif // USE_SIMULATOR if (GetPatch() > 0) { SNPrintF(str, "%d.%d.%d.%d%s%s", GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate, is_simulator); } else { SNPrintF(str, "%d.%d.%d%s%s", GetMajor(), GetMinor(), GetBuild(), candidate, is_simulator); } } // Calculate the SONAME for the V8 shared library. void Version::GetSONAME(Vector<char> str) { if (soname_ == NULL || *soname_ == '\0') { // Generate generic SONAME if no specific SONAME is defined. const char* candidate = IsCandidate() ? "-candidate" : ""; if (GetPatch() > 0) { SNPrintF(str, "libv8-%d.%d.%d.%d%s.so", GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate); } else { SNPrintF(str, "libv8-%d.%d.%d%s.so", GetMajor(), GetMinor(), GetBuild(), candidate); } } else { // Use specific SONAME. SNPrintF(str, "%s", soname_); } } } } // namespace v8::internal <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkCommandLineParser.h" #include <mitkIOUtil.h> #include <mitkRegistrationWrapper.h> #include <mitkImage.h> #include <mitkImageCast.h> #include <mitkITKImageImport.h> #include <mitkImageTimeSelector.h> #include <mitkDiffusionPropertyHelper.h> #include <mitkProperties.h> // ITK #include <itksys/SystemTools.hxx> #include <itkDirectory.h> #include "itkLinearInterpolateImageFunction.h" #include "itkWindowedSincInterpolateImageFunction.h" #include "itkIdentityTransform.h" #include "itkResampleImageFilter.h" #include "itkResampleDwiImageFilter.h" typedef itk::Image<double, 3> InputImageType; static mitk::Image::Pointer TransformToReference(mitk::Image *reference, mitk::Image *moving, bool sincInterpol = false) { // Convert to itk Images InputImageType::Pointer itkReference = InputImageType::New(); InputImageType::Pointer itkMoving = InputImageType::New(); mitk::CastToItkImage(reference,itkReference); mitk::CastToItkImage(moving,itkMoving); // Identify Transform typedef itk::IdentityTransform<double, 3> T_Transform; T_Transform::Pointer _pTransform = T_Transform::New(); _pTransform->SetIdentity(); typedef itk::WindowedSincInterpolateImageFunction< InputImageType, 3> WindowedSincInterpolatorType; WindowedSincInterpolatorType::Pointer sinc_interpolator = WindowedSincInterpolatorType::New(); typedef itk::ResampleImageFilter<InputImageType, InputImageType> ResampleFilterType; ResampleFilterType::Pointer resampler = ResampleFilterType::New(); resampler->SetInput(itkMoving); resampler->SetReferenceImage( itkReference ); resampler->UseReferenceImageOn(); resampler->SetTransform(_pTransform); resampler->SetInterpolator(sinc_interpolator); resampler->Update(); // Convert back to mitk mitk::Image::Pointer result = mitk::Image::New(); result->InitializeByItk(resampler->GetOutput()); GrabItkImageMemory( resampler->GetOutput() , result ); return result; } static std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } static std::vector<std::string> split(const std::string &s, char delim) { std::vector < std::string > elems; return split(s, delim, elems); } static mitk::Image::Pointer ResampleBySpacing(mitk::Image *input, float *spacing, bool useLinInt = true) { InputImageType::Pointer itkImage = InputImageType::New(); CastToItkImage(input,itkImage); /** * 1) Resampling * */ // Identity transform. // We don't want any transform on our image except rescaling which is not // specified by a transform but by the input/output spacing as we will see // later. // So no transform will be specified. typedef itk::IdentityTransform<double, 3> T_Transform; // The resampler type itself. typedef itk::ResampleImageFilter<InputImageType, InputImageType> T_ResampleFilter; // Prepare the resampler. // Instantiate the transform and specify it should be the id transform. T_Transform::Pointer _pTransform = T_Transform::New(); _pTransform->SetIdentity(); // Instantiate the resampler. Wire in the transform and the interpolator. T_ResampleFilter::Pointer _pResizeFilter = T_ResampleFilter::New(); // Specify the input. _pResizeFilter->SetInput(itkImage); _pResizeFilter->SetTransform(_pTransform); // Set the output origin. _pResizeFilter->SetOutputOrigin(itkImage->GetOrigin()); // Compute the size of the output. // The size (# of pixels) in the output is recomputed using // the ratio of the input and output sizes. InputImageType::SpacingType inputSpacing = itkImage->GetSpacing(); InputImageType::SpacingType outputSpacing; const InputImageType::RegionType& inputSize = itkImage->GetLargestPossibleRegion(); InputImageType::SizeType outputSize; typedef InputImageType::SizeType::SizeValueType SizeValueType; // Set the output spacing. outputSpacing[0] = spacing[0]; outputSpacing[1] = spacing[1]; outputSpacing[2] = spacing[2]; outputSize[0] = static_cast<SizeValueType>(inputSize.GetSize()[0] * inputSpacing[0] / outputSpacing[0] + .5); outputSize[1] = static_cast<SizeValueType>(inputSize.GetSize()[1] * inputSpacing[1] / outputSpacing[1] + .5); outputSize[2] = static_cast<SizeValueType>(inputSize.GetSize()[2] * inputSpacing[2] / outputSpacing[2] + .5); _pResizeFilter->SetOutputSpacing(outputSpacing); _pResizeFilter->SetSize(outputSize); typedef itk::LinearInterpolateImageFunction< InputImageType > LinearInterpolatorType; LinearInterpolatorType::Pointer lin_interpolator = LinearInterpolatorType::New(); typedef itk::WindowedSincInterpolateImageFunction< InputImageType, 4> WindowedSincInterpolatorType; WindowedSincInterpolatorType::Pointer sinc_interpolator = WindowedSincInterpolatorType::New(); if (useLinInt) _pResizeFilter->SetInterpolator(lin_interpolator); else _pResizeFilter->SetInterpolator(sinc_interpolator); _pResizeFilter->Update(); mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk(_pResizeFilter->GetOutput()); mitk::GrabItkImageMemory( _pResizeFilter->GetOutput(), image); return image; } /// Save images according to file type static void SaveImage(std::string fileName, mitk::Image* image, std::string fileType ) { std::cout << "----Save to " << fileName; mitk::IOUtil::Save(image, fileName); } mitk::Image::Pointer ResampleDWIbySpacing(mitk::Image::Pointer input, float* spacing, bool useLinInt = true) { itk::Vector<double, 3> spacingVector; spacingVector[0] = spacing[0]; spacingVector[1] = spacing[1]; spacingVector[2] = spacing[2]; typedef itk::ResampleDwiImageFilter<short> ResampleFilterType; mitk::DiffusionPropertyHelper::ImageType::Pointer itkVectorImagePointer = mitk::DiffusionPropertyHelper::ImageType::New(); mitk::CastToItkImage(input, itkVectorImagePointer); ResampleFilterType::Pointer resampler = ResampleFilterType::New(); resampler->SetInput( itkVectorImagePointer ); resampler->SetInterpolation(ResampleFilterType::Interpolate_Linear); resampler->SetNewSpacing(spacingVector); resampler->Update(); mitk::Image::Pointer output = mitk::GrabItkImageMemory( resampler->GetOutput() ); output->SetProperty( mitk::DiffusionPropertyHelper::GRADIENTCONTAINERPROPERTYNAME.c_str(), mitk::GradientDirectionsProperty::New( mitk::DiffusionPropertyHelper::GetGradientContainer(input) ) ); output->SetProperty( mitk::DiffusionPropertyHelper::REFERENCEBVALUEPROPERTYNAME.c_str(), mitk::FloatProperty::New( mitk::DiffusionPropertyHelper::GetReferenceBValue(input) ) ); mitk::DiffusionPropertyHelper propertyHelper( output ); propertyHelper.InitializeImage(); return output; } int main( int argc, char* argv[] ) { mitkCommandLineParser parser; parser.setArgumentPrefix("--","-"); parser.setTitle("Image Resampler"); parser.setCategory("Preprocessing Tools"); parser.setContributor("MBI"); parser.setDescription("Resample an image to eigther a specific spacing or to a reference image."); // Add command line argument names parser.addArgument("help", "h",mitkCommandLineParser::Bool, "Show this help text"); parser.addArgument("input", "i", mitkCommandLineParser::InputImage, "Input:", "Input file",us::Any(),false); parser.addArgument("output", "o", mitkCommandLineParser::OutputFile, "Output:", "Output file",us::Any(),false); parser.addArgument("spacing", "s", mitkCommandLineParser::String, "Spacing:", "Resample provide x,y,z spacing in mm (e.g. -r 1,1,3), is not applied to tensor data",us::Any()); parser.addArgument("reference", "r", mitkCommandLineParser::InputImage, "Reference:", "Resample using supplied reference image. Also cuts image to same dimensions",us::Any()); parser.addArgument("win-sinc", "w", mitkCommandLineParser::Bool, "Windowed-sinc interpolation:", "Use windowed-sinc interpolation (3) instead of linear interpolation ",us::Any()); map<string, us::Any> parsedArgs = parser.parseArguments(argc, argv); // Handle special arguments bool useSpacing = false; bool useLinearInterpol = true; { if (parsedArgs.size() == 0) { return EXIT_FAILURE; } if (parsedArgs.count("sinc-int")) useLinearInterpol = false; // Show a help message if ( parsedArgs.count("help") || parsedArgs.count("h")) { std::cout << parser.helpText(); return EXIT_SUCCESS; } } std::string outputFile = us::any_cast<string>(parsedArgs["output"]); std::string inputFile = us::any_cast<string>(parsedArgs["input"]); std::vector<std::string> spacings; float spacing[3]; if (parsedArgs.count("spacing")) { std::string arg = us::any_cast<string>(parsedArgs["spacing"]); if (arg != "") { spacings = split(arg ,','); spacing[0] = atoi(spacings.at(0).c_str()); spacing[1] = atoi(spacings.at(1).c_str()); spacing[2] = atoi(spacings.at(2).c_str()); useSpacing = true; } } std::string refImageFile = ""; if (parsedArgs.count("reference")) { refImageFile = us::any_cast<string>(parsedArgs["reference"]); } if (refImageFile =="" && useSpacing == false) { MITK_ERROR << "No information how to resample is supplied. Use eigther --spacing or --reference !"; return EXIT_FAILURE; } mitk::Image::Pointer refImage; if (!useSpacing) refImage = mitk::IOUtil::LoadImage(refImageFile); mitk::Image::Pointer inputDWI = mitk::IOUtil::LoadImage(inputFile); if ( mitk::DiffusionPropertyHelper::IsDiffusionWeightedImage(inputDWI.GetPointer())) { mitk::Image::Pointer outputImage; if (useSpacing) outputImage = ResampleDWIbySpacing(inputDWI, spacing); else { MITK_WARN << "Not supported yet, to resample a DWI please set a new spacing."; return EXIT_FAILURE; } mitk::IOUtil::Save(outputImage, outputFile.c_str()); return EXIT_SUCCESS; } mitk::Image::Pointer inputImage = mitk::IOUtil::LoadImage(inputFile); mitk::Image::Pointer resultImage; if (useSpacing) resultImage = ResampleBySpacing(inputImage,spacing); else resultImage = TransformToReference(refImage,inputImage); mitk::IOUtil::SaveImage(resultImage, outputFile); return EXIT_SUCCESS; } <commit_msg>extend ImageResampler to NearestNeighbor Interpolation<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkCommandLineParser.h" #include <mitkIOUtil.h> #include <mitkRegistrationWrapper.h> #include <mitkImage.h> #include <mitkImageCast.h> #include <mitkITKImageImport.h> #include <mitkImageTimeSelector.h> #include <mitkDiffusionPropertyHelper.h> #include <mitkProperties.h> // ITK #include <itksys/SystemTools.hxx> #include <itkDirectory.h> #include "itkLinearInterpolateImageFunction.h" #include "itkWindowedSincInterpolateImageFunction.h" #include "itkNearestNeighborInterpolateImageFunction.h" #include "itkIdentityTransform.h" #include "itkResampleImageFilter.h" #include "itkResampleDwiImageFilter.h" typedef itk::Image<double, 3> InputImageType; typedef itk::Image<unsigned char, 3> BinaryImageType; static mitk::Image::Pointer TransformToReference(mitk::Image *reference, mitk::Image *moving, bool sincInterpol = false, bool nn = false) { // Convert to itk Images // Identify Transform typedef itk::IdentityTransform<double, 3> T_Transform; T_Transform::Pointer _pTransform = T_Transform::New(); _pTransform->SetIdentity(); typedef itk::WindowedSincInterpolateImageFunction< InputImageType, 3> WindowedSincInterpolatorType; WindowedSincInterpolatorType::Pointer sinc_interpolator = WindowedSincInterpolatorType::New(); typedef itk::LinearInterpolateImageFunction< InputImageType> LinearInterpolateImageFunctionType; LinearInterpolateImageFunctionType::Pointer lin_interpolator = LinearInterpolateImageFunctionType::New(); typedef itk::NearestNeighborInterpolateImageFunction< BinaryImageType> NearestNeighborInterpolateImageFunctionType; NearestNeighborInterpolateImageFunctionType::Pointer nn_interpolator = NearestNeighborInterpolateImageFunctionType::New(); if (!nn) { InputImageType::Pointer itkReference = InputImageType::New(); InputImageType::Pointer itkMoving = InputImageType::New(); mitk::CastToItkImage(reference,itkReference); mitk::CastToItkImage(moving,itkMoving); typedef itk::ResampleImageFilter<InputImageType, InputImageType> ResampleFilterType; ResampleFilterType::Pointer resampler = ResampleFilterType::New(); resampler->SetInput(itkMoving); resampler->SetReferenceImage( itkReference ); resampler->UseReferenceImageOn(); resampler->SetTransform(_pTransform); if ( sincInterpol) resampler->SetInterpolator(sinc_interpolator); else resampler->SetInterpolator(lin_interpolator); resampler->Update(); // Convert back to mitk mitk::Image::Pointer result = mitk::Image::New(); result->InitializeByItk(resampler->GetOutput()); GrabItkImageMemory( resampler->GetOutput() , result ); return result; } BinaryImageType::Pointer itkReference = BinaryImageType::New(); BinaryImageType::Pointer itkMoving = BinaryImageType::New(); mitk::CastToItkImage(reference,itkReference); mitk::CastToItkImage(moving,itkMoving); typedef itk::ResampleImageFilter<BinaryImageType, BinaryImageType> ResampleFilterType; ResampleFilterType::Pointer resampler = ResampleFilterType::New(); resampler->SetInput(itkMoving); resampler->SetReferenceImage( itkReference ); resampler->UseReferenceImageOn(); resampler->SetTransform(_pTransform); resampler->SetInterpolator(nn_interpolator); resampler->Update(); // Convert back to mitk mitk::Image::Pointer result = mitk::Image::New(); result->InitializeByItk(resampler->GetOutput()); GrabItkImageMemory( resampler->GetOutput() , result ); return result; } static std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } static std::vector<std::string> split(const std::string &s, char delim) { std::vector < std::string > elems; return split(s, delim, elems); } static mitk::Image::Pointer ResampleBySpacing(mitk::Image *input, float *spacing, bool useLinInt = true, bool useNN = false) { if (!useNN) { InputImageType::Pointer itkImage = InputImageType::New(); CastToItkImage(input,itkImage); /** * 1) Resampling * */ // Identity transform. // We don't want any transform on our image except rescaling which is not // specified by a transform but by the input/output spacing as we will see // later. // So no transform will be specified. typedef itk::IdentityTransform<double, 3> T_Transform; // The resampler type itself. typedef itk::ResampleImageFilter<InputImageType, InputImageType> T_ResampleFilter; // Prepare the resampler. // Instantiate the transform and specify it should be the id transform. T_Transform::Pointer _pTransform = T_Transform::New(); _pTransform->SetIdentity(); // Instantiate the resampler. Wire in the transform and the interpolator. T_ResampleFilter::Pointer _pResizeFilter = T_ResampleFilter::New(); // Specify the input. _pResizeFilter->SetInput(itkImage); _pResizeFilter->SetTransform(_pTransform); // Set the output origin. _pResizeFilter->SetOutputOrigin(itkImage->GetOrigin()); // Compute the size of the output. // The size (# of pixels) in the output is recomputed using // the ratio of the input and output sizes. InputImageType::SpacingType inputSpacing = itkImage->GetSpacing(); InputImageType::SpacingType outputSpacing; const InputImageType::RegionType& inputSize = itkImage->GetLargestPossibleRegion(); InputImageType::SizeType outputSize; typedef InputImageType::SizeType::SizeValueType SizeValueType; // Set the output spacing. outputSpacing[0] = spacing[0]; outputSpacing[1] = spacing[1]; outputSpacing[2] = spacing[2]; outputSize[0] = static_cast<SizeValueType>(inputSize.GetSize()[0] * inputSpacing[0] / outputSpacing[0] + .5); outputSize[1] = static_cast<SizeValueType>(inputSize.GetSize()[1] * inputSpacing[1] / outputSpacing[1] + .5); outputSize[2] = static_cast<SizeValueType>(inputSize.GetSize()[2] * inputSpacing[2] / outputSpacing[2] + .5); _pResizeFilter->SetOutputSpacing(outputSpacing); _pResizeFilter->SetSize(outputSize); typedef itk::LinearInterpolateImageFunction< InputImageType > LinearInterpolatorType; LinearInterpolatorType::Pointer lin_interpolator = LinearInterpolatorType::New(); typedef itk::WindowedSincInterpolateImageFunction< InputImageType, 4> WindowedSincInterpolatorType; WindowedSincInterpolatorType::Pointer sinc_interpolator = WindowedSincInterpolatorType::New(); if (useLinInt) _pResizeFilter->SetInterpolator(lin_interpolator); else _pResizeFilter->SetInterpolator(sinc_interpolator); _pResizeFilter->Update(); mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk(_pResizeFilter->GetOutput()); mitk::GrabItkImageMemory( _pResizeFilter->GetOutput(), image); return image; } BinaryImageType::Pointer itkImage = BinaryImageType::New(); CastToItkImage(input,itkImage); /** * 1) Resampling * */ // Identity transform. // We don't want any transform on our image except rescaling which is not // specified by a transform but by the input/output spacing as we will see // later. // So no transform will be specified. typedef itk::IdentityTransform<double, 3> T_Transform; // The resampler type itself. typedef itk::ResampleImageFilter<BinaryImageType, BinaryImageType> T_ResampleFilter; // Prepare the resampler. // Instantiate the transform and specify it should be the id transform. T_Transform::Pointer _pTransform = T_Transform::New(); _pTransform->SetIdentity(); // Instantiate the resampler. Wire in the transform and the interpolator. T_ResampleFilter::Pointer _pResizeFilter = T_ResampleFilter::New(); // Specify the input. _pResizeFilter->SetInput(itkImage); _pResizeFilter->SetTransform(_pTransform); // Set the output origin. _pResizeFilter->SetOutputOrigin(itkImage->GetOrigin()); // Compute the size of the output. // The size (# of pixels) in the output is recomputed using // the ratio of the input and output sizes. BinaryImageType::SpacingType inputSpacing = itkImage->GetSpacing(); BinaryImageType::SpacingType outputSpacing; const BinaryImageType::RegionType& inputSize = itkImage->GetLargestPossibleRegion(); BinaryImageType::SizeType outputSize; typedef BinaryImageType::SizeType::SizeValueType SizeValueType; // Set the output spacing. outputSpacing[0] = spacing[0]; outputSpacing[1] = spacing[1]; outputSpacing[2] = spacing[2]; outputSize[0] = static_cast<SizeValueType>(inputSize.GetSize()[0] * inputSpacing[0] / outputSpacing[0] + .5); outputSize[1] = static_cast<SizeValueType>(inputSize.GetSize()[1] * inputSpacing[1] / outputSpacing[1] + .5); outputSize[2] = static_cast<SizeValueType>(inputSize.GetSize()[2] * inputSpacing[2] / outputSpacing[2] + .5); _pResizeFilter->SetOutputSpacing(outputSpacing); _pResizeFilter->SetSize(outputSize); typedef itk::NearestNeighborInterpolateImageFunction< BinaryImageType> NearestNeighborInterpolateImageType; NearestNeighborInterpolateImageType::Pointer nn_interpolator = NearestNeighborInterpolateImageType::New(); _pResizeFilter->SetInterpolator(nn_interpolator); _pResizeFilter->Update(); mitk::Image::Pointer image = mitk::Image::New(); image->InitializeByItk(_pResizeFilter->GetOutput()); mitk::GrabItkImageMemory( _pResizeFilter->GetOutput(), image); return image; } /// Save images according to file type static void SaveImage(std::string fileName, mitk::Image* image, std::string fileType ) { std::cout << "----Save to " << fileName; mitk::IOUtil::Save(image, fileName); } mitk::Image::Pointer ResampleDWIbySpacing(mitk::Image::Pointer input, float* spacing, bool useLinInt = true) { itk::Vector<double, 3> spacingVector; spacingVector[0] = spacing[0]; spacingVector[1] = spacing[1]; spacingVector[2] = spacing[2]; typedef itk::ResampleDwiImageFilter<short> ResampleFilterType; mitk::DiffusionPropertyHelper::ImageType::Pointer itkVectorImagePointer = mitk::DiffusionPropertyHelper::ImageType::New(); mitk::CastToItkImage(input, itkVectorImagePointer); ResampleFilterType::Pointer resampler = ResampleFilterType::New(); resampler->SetInput( itkVectorImagePointer ); resampler->SetInterpolation(ResampleFilterType::Interpolate_Linear); resampler->SetNewSpacing(spacingVector); resampler->Update(); mitk::Image::Pointer output = mitk::GrabItkImageMemory( resampler->GetOutput() ); output->SetProperty( mitk::DiffusionPropertyHelper::GRADIENTCONTAINERPROPERTYNAME.c_str(), mitk::GradientDirectionsProperty::New( mitk::DiffusionPropertyHelper::GetGradientContainer(input) ) ); output->SetProperty( mitk::DiffusionPropertyHelper::REFERENCEBVALUEPROPERTYNAME.c_str(), mitk::FloatProperty::New( mitk::DiffusionPropertyHelper::GetReferenceBValue(input) ) ); mitk::DiffusionPropertyHelper propertyHelper( output ); propertyHelper.InitializeImage(); return output; } int main( int argc, char* argv[] ) { mitkCommandLineParser parser; parser.setArgumentPrefix("--","-"); parser.setTitle("Image Resampler"); parser.setCategory("Preprocessing Tools"); parser.setContributor("MBI"); parser.setDescription("Resample an image to eigther a specific spacing or to a reference image."); // Add command line argument names parser.addArgument("help", "h",mitkCommandLineParser::Bool, "Show this help text"); parser.addArgument("input", "i", mitkCommandLineParser::InputImage, "Input:", "Input file",us::Any(),false); parser.addArgument("output", "o", mitkCommandLineParser::OutputFile, "Output:", "Output file",us::Any(),false); parser.addArgument("spacing", "s", mitkCommandLineParser::String, "Spacing:", "Resample provide x,y,z spacing in mm (e.g. -r 1,1,3), is not applied to tensor data",us::Any()); parser.addArgument("reference", "r", mitkCommandLineParser::InputImage, "Reference:", "Resample using supplied reference image. Also cuts image to same dimensions",us::Any()); parser.addArgument("win-sinc", "w", mitkCommandLineParser::Bool, "Windowed-sinc interpolation:", "Use windowed-sinc interpolation (3) instead of linear interpolation ",us::Any()); parser.addArgument("nearest-neigh", "n", mitkCommandLineParser::Bool, "Nearest Neighbor:", "Use Nearest Neighbor interpolation instead of linear interpolation ",us::Any()); map<string, us::Any> parsedArgs = parser.parseArguments(argc, argv); // Handle special arguments bool useSpacing = false; bool useLinearInterpol = true; bool useNN= false; { if (parsedArgs.size() == 0) { return EXIT_FAILURE; } if (parsedArgs.count("sinc-int")) useLinearInterpol = false; if (parsedArgs.count("nearest-neigh")) useNN = true; // Show a help message if ( parsedArgs.count("help") || parsedArgs.count("h")) { std::cout << parser.helpText(); return EXIT_SUCCESS; } } std::string outputFile = us::any_cast<string>(parsedArgs["output"]); std::string inputFile = us::any_cast<string>(parsedArgs["input"]); std::vector<std::string> spacings; float spacing[3]; if (parsedArgs.count("spacing")) { std::string arg = us::any_cast<string>(parsedArgs["spacing"]); if (arg != "") { spacings = split(arg ,','); spacing[0] = atoi(spacings.at(0).c_str()); spacing[1] = atoi(spacings.at(1).c_str()); spacing[2] = atoi(spacings.at(2).c_str()); useSpacing = true; } } std::string refImageFile = ""; if (parsedArgs.count("reference")) { refImageFile = us::any_cast<string>(parsedArgs["reference"]); } if (refImageFile =="" && useSpacing == false) { MITK_ERROR << "No information how to resample is supplied. Use eigther --spacing or --reference !"; return EXIT_FAILURE; } mitk::Image::Pointer refImage; if (!useSpacing) refImage = mitk::IOUtil::LoadImage(refImageFile); mitk::Image::Pointer inputDWI = mitk::IOUtil::LoadImage(inputFile); if ( mitk::DiffusionPropertyHelper::IsDiffusionWeightedImage(inputDWI.GetPointer())) { mitk::Image::Pointer outputImage; if (useSpacing) outputImage = ResampleDWIbySpacing(inputDWI, spacing); else { MITK_WARN << "Not supported yet, to resample a DWI please set a new spacing."; return EXIT_FAILURE; } mitk::IOUtil::Save(outputImage, outputFile.c_str()); return EXIT_SUCCESS; } mitk::Image::Pointer inputImage = mitk::IOUtil::LoadImage(inputFile); mitk::Image::Pointer resultImage; if (useSpacing) resultImage = ResampleBySpacing(inputImage,spacing,useLinearInterpol,useNN); else resultImage = TransformToReference(refImage,inputImage,useLinearInterpol,useNN); mitk::IOUtil::SaveImage(resultImage, outputFile); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 "itkIncludeRequiredIOFactories.h" #include <iostream> #include "itkPSMCommandLineClass.h" #include "itkPSMCommandLineClass.cxx" #include "itkExceptionObject.h" int main( int argc, char *argv[] ) { int dim = 0; std::string output_path = ""; std::string input_path_prefix = ""; std::string errstring = ""; // Check for proper arguments if (argc < 3) { std::cout << "Wrong number of arguments. \nUse: " << "ParticleShapeModeling_CLI parameter_file shape_dimensions [output_path] [input_path]\n" << "See itk::PSMParameterFileReader for documentation on the parameter file format.\n" << "Enter number of dimensions of the shapes (2 or 3) following parameter file name.\n" << "Note that input_path will be prefixed to any file names and paths in the xml parameter file.\n" << std::endl; return EXIT_FAILURE; } if (argc > 3) { output_path = std::string(argv[3]); } if (argc > 4) { input_path_prefix = std::string(argv[4]); } try { dim = atoi(argv[2]); // This function is called to fix an ITK runtime error where image format is not recognized. RegisterRequiredFactories(); if (dim == 2) { itk::PSMCommandLineClass<2>::Pointer psmClass = itk::PSMCommandLineClass<2>::New(); psmClass->Run( argv[1], input_path_prefix, output_path ); } else if (dim == 3) { itk::PSMCommandLineClass<3>::Pointer psmClass = itk::PSMCommandLineClass<3>::New(); psmClass->Run( argv[1], input_path_prefix, output_path ); } else { std::cerr << "Please specify the input dimension as 2 or 3" << std::endl; } } catch(itk::ExceptionObject &e) { std::cerr << "ITK exception with description: " << e.GetDescription() << "\n at location:" << e.GetLocation() << "\n in file:" << e.GetFile() << std::endl; return EXIT_FAILURE; } catch(...) { errstring = "Unknown exception thrown"; return EXIT_FAILURE; } return EXIT_SUCCESS; }<commit_msg>Moved check of image dimension from command line input to the code<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 "itkIncludeRequiredIOFactories.h" #include <iostream> #include "itkPSMCommandLineClass.h" #include "itkPSMCommandLineClass.cxx" #include "itkPSMProjectReader.h" #include "itkImage.h" #include "itkImageFileReader.h" #include "itkExceptionObject.h" int main( int argc, char *argv[] ) { std::string output_path = ""; std::string input_path_prefix = ""; std::string errstring = ""; // Check for proper arguments if (argc < 2) { std::cout << "Wrong number of arguments. \nUse: " << "ParticleShapeModeling_CLI parameter_file [output_path] [input_path]\n" << "See itk::PSMParameterFileReader for documentation on the parameter file format.\n" << "Enter number of dimensions of the shapes (2 or 3) following parameter file name.\n" << "Note that input_path will be prefixed to any file names and paths in the xml parameter file.\n" << std::endl; return EXIT_FAILURE; } if (argc > 2) { output_path = std::string(argv[2]); } if (argc > 3) { input_path_prefix = std::string(argv[3]); } try { // This function is called to fix an ITK runtime error where image format is not recognized. RegisterRequiredFactories(); // The dimensions of the input images need to be checked in order to // correctly initialize PSMCommandLineClass. itk::PSMProjectReader::Pointer xmlReader = itk::PSMProjectReader::New(); xmlReader->SetFileName(argv[1]); xmlReader->Update(); itk::PSMProject::Pointer project = xmlReader->GetOutput(); // Load the distance transforms const std::vector<std::string> &dt_files = project->GetDistanceTransforms(); std::string fname = input_path_prefix + dt_files[0]; // Read the first distance transform to check the image dimensions std::cout << "Checking input image dimensions ..." << std::endl; typedef itk::ImageIOBase::IOComponentType ScalarPixelType; itk::ImageIOBase::Pointer imageIO =itk::ImageIOFactory::CreateImageIO( fname.c_str(), itk::ImageIOFactory::ReadMode); imageIO->SetFileName(fname); imageIO->ReadImageInformation(); const size_t numOfDimensions = imageIO->GetNumberOfDimensions(); std::cout << "Number of dimensions: " << numOfDimensions << std::endl; if (numOfDimensions == 2) { itk::PSMCommandLineClass<2>::Pointer psmClass = itk::PSMCommandLineClass<2>::New(); psmClass->Run( argv[1], input_path_prefix, output_path ); } else if (numOfDimensions == 3) { itk::PSMCommandLineClass<3>::Pointer psmClass = itk::PSMCommandLineClass<3>::New(); psmClass->Run( argv[1], input_path_prefix, output_path ); } } catch(itk::ExceptionObject &e) { std::cerr << "ITK exception with description: " << e.GetDescription() << "\n at location:" << e.GetLocation() << "\n in file:" << e.GetFile() << std::endl; return EXIT_FAILURE; } catch(...) { errstring = "Unknown exception thrown"; return EXIT_FAILURE; } return EXIT_SUCCESS; }<|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: elementexport.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: rt $ $Date: 2003-12-01 12:03:37 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _XMLOFF_ELEMENTEXPORT_HXX_ #define _XMLOFF_ELEMENTEXPORT_HXX_ #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_ #include <com/sun/star/container/XIndexAccess.hpp> #endif #ifndef _COM_SUN_STAR_SCRIPT_SCRIPTEVENTDESCRIPTOR_HPP_ #include <com/sun/star/script/ScriptEventDescriptor.hpp> #endif #ifndef _XMLOFF_FORMS_PROPERTYEXPORT_HXX_ #include "propertyexport.hxx" #endif #ifndef _XMLOFF_FORMS_CALLBACKS_HXX_ #include "callbacks.hxx" #endif #ifndef _XMLOFF_FORMS_CONTROLELEMENT_HXX_ #include "controlelement.hxx" #endif #ifndef _XMLOFF_FORMS_VALUEPROPERTIES_HXX_ #include "valueproperties.hxx" #endif class SvXMLElementExport; //......................................................................... namespace xmloff { //......................................................................... //===================================================================== //= OElementExport //===================================================================== class OElementExport : public OPropertyExport { protected: ::com::sun::star::uno::Sequence< ::com::sun::star::script::ScriptEventDescriptor > m_aEvents; SvXMLElementExport* m_pXMLElement; // XML element doing the concrete startElement etc. public: OElementExport(IFormsExportContext& _rContext, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxProps, const ::com::sun::star::uno::Sequence< ::com::sun::star::script::ScriptEventDescriptor >& _rEvents); ~OElementExport(); void doExport(); protected: /// get the name of the XML element virtual const sal_Char* getXMLElementName() const = 0; /// examine the element we're exporting virtual void examine(); /// export the attributes virtual void exportAttributes(); /// export any sub tags virtual void exportSubTags(); /** exports the events (as script:events tag) */ void exportEvents(); /** add the service-name attribute to the export context */ virtual void exportServiceNameAttribute(); /// start the XML element virtual void implStartElement(const sal_Char* _pName); /// ends the XML element virtual void implEndElement(); }; //===================================================================== //= OControlExport //===================================================================== /** Helper class for handling xml elements representing a form control */ class OControlExport :public OControlElement ,public OValuePropertiesMetaData ,public OElementExport { protected: DECLARE_STL_STDKEY_SET(sal_Int16, Int16Set); // used below ::rtl::OUString m_sControlId; // the control id to use when exporting ::rtl::OUString m_sReferringControls; // list of referring controls (i.e. their id's) sal_Int16 m_nClassId; // class id of the control we're representing ElementType m_eType; // (XML) type of the control we're representing sal_Int32 m_nIncludeCommon; // common control attributes to include sal_Int32 m_nIncludeDatabase; // common database attributes to include sal_Int32 m_nIncludeSpecial; // special attributes to include sal_Int32 m_nIncludeEvents; // events to include sal_Int32 m_nIncludeBindings; // binding attributes to include SvXMLElementExport* m_pOuterElement; // XML element doing the concrete startElement etc. for the outer element public: /** constructs an object capable of exporting controls <p>You need at least two pre-requisites from outside: The control to be exported needs to have a class id assigned, and you need the list control-ids of all the controls referring to this one as LabelControl.<br/> This information can't be collected when known only the control itself and not it's complete context.</p> @param _rControlId the control id to use when exporting the control @param _rReferringControls the comma-separated list of control-ids of all the controls referring to this one as LabelControl */ OControlExport(IFormsExportContext& _rContext, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxControl, const ::rtl::OUString& _rControlId, const ::rtl::OUString& _rReferringControls, const ::com::sun::star::uno::Sequence< ::com::sun::star::script::ScriptEventDescriptor >& _rxEvents); ~OControlExport(); protected: /// start the XML element virtual void implStartElement(const sal_Char* _pName); /// ends the XML element virtual void implEndElement(); /// get the name of the outer XML element virtual const sal_Char* getOuterXMLElementName() const; // get the name of the XML element virtual const sal_Char* getXMLElementName() const; /** examine the control. Some kind of CtorImpl. */ virtual void examine(); /// exports the attributes for the outer element void exportOuterAttributes(); /// exports the attributes for the inner element void exportInnerAttributes(); /// export the attributes virtual void exportAttributes(); /** writes everything which needs to be represented as sub tag */ void exportSubTags() throw (::com::sun::star::uno::Exception); /** adds common control attributes to the XMLExport context given <p>The attribute list of the context is not cleared initially, this is the responsibility of the caller.</p> */ void exportCommonControlAttributes(); /** adds database attributes to the XMLExport context given <p>The attribute list of the context is not cleared initially, this is the responsibility of the caller.</p> */ void exportDatabaseAttributes(); /** adds the XML attributes which are related to binding controls to external values and/or list sources */ void exportBindingAtributes(); /** adds attributes which are special to a control type to the export context's attribute list */ void exportSpecialAttributes(); /** exports the ListSource property of a control as attribute <p>The ListSource property may be exported in different ways: For a ComboBox, it is an attribute of the form:combobox element.</p> <p>For a ListBox, it's an attribute if the ListSourceType states that the ListBox does <em>not</em> display a value list. In case of a value list, the ListSource is not exported, and the pairs of StringItem/ValueItem are exported as sub-elements.<br/> (For a value list ListBox, As every setting of the ListSource immediately sets the ValueList to the same value, so nothing is lost when exporting this).</p> <p>It's really strange, isn't it? Don't know why we have this behaviour in our controls ...</p> <p>This method does the attribute part: It exports the ListSource property as attribute, not caring about whether the object is a ComboBox or a ListBox.</p> */ void exportListSourceAsAttribute(); /** exports the ListSource property of a control as XML elements @see exportListSourceAsAttribute */ void exportListSourceAsElements(); /** get's a Sequence&lt; sal_Int16 &gt; property value as set of sal_Int16's @param _rPropertyName the property name to use @param _rOut out parameter. The set of integers. */ void getSequenceInt16PropertyAsSet(const ::rtl::OUString& _rPropertyName, Int16Set& _rOut); /** exports the attribute which descrives a cell value binding of a control in a spreadsheet document */ void exportCellBindingAttributes( bool _bIncludeListLinkageType ); /** exports the attribute which descrives a cell range which acts as list source for a list-like control */ void exportCellListSourceRange( ); }; //===================================================================== //= OColumnExport //===================================================================== /** Helper class for exporting a grid column */ class OColumnExport : public OControlExport { public: /** ctor @see OColumnExport::OColumnExport */ OColumnExport(IFormsExportContext& _rContext, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxControl, const ::com::sun::star::uno::Sequence< ::com::sun::star::script::ScriptEventDescriptor >& _rxEvents); ~OColumnExport(); protected: // OControlExport overridables virtual const sal_Char* getOuterXMLElementName() const; virtual void exportServiceNameAttribute(); virtual void exportAttributes(); // OElementExport overridables virtual void examine(); }; //===================================================================== //= OFormExport //===================================================================== /** Helper class for handling xml elements representing a form <p>In opposite to the class <type>OControlExport</type>, OFormExport is unable to export a <em>complete</em> form. Instead the client has to care for sub elements of the form itself.</p> */ class OFormExport :public OControlElement ,public OElementExport { public: /** constructs an object capable of exporting controls */ OFormExport(IFormsExportContext& _rContext, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxForm, const ::com::sun::star::uno::Sequence< ::com::sun::star::script::ScriptEventDescriptor >& _rxEvents ); protected: virtual const sal_Char* getXMLElementName() const; virtual void exportSubTags(); virtual void exportAttributes(); }; //......................................................................... } // namespace xmloff //......................................................................... #endif // _XMLOFF_ELEMENTEXPORT_HXX_ /************************************************************************* * history: * $Log: not supported by cvs2svn $ * Revision 1.8.24.2 2003/11/24 15:02:47 obo * undo last change * * Revision 1.8 2003/10/21 08:38:25 obo * INTEGRATION: CWS formcelllinkage (1.7.198); FILE MERGED * 2003/10/01 09:55:18 fs 1.7.198.1: #i18994# merging the changes from the CWS fs002 * * Revision 1.7.198.1 2003/10/01 09:55:18 fs * #i18994# merging the changes from the CWS fs002 * * Revision 1.7.194.1 2003/09/25 14:28:36 fs * #18994# merging the changes from cws_srx645_fs002 branch * * Revision 1.7.190.2 2003/09/18 14:00:36 fs * #18995# changes for binding list boxes to cells, while exchanging selection indexes instead of strings * * Revision 1.7.190.1 2003/09/17 12:26:46 fs * #18999# #19367# persistence for cell value and cell range bindings * * Revision 1.7 2001/01/03 16:25:34 fs * file format change (extra wrapper element for controls, similar to columns) * * Revision 1.6 2001/01/02 15:58:21 fs * event ex- & import * * Revision 1.5 2000/12/18 15:14:35 fs * some changes ... now exporting/importing styles * * Revision 1.4 2000/12/13 10:38:10 fs * moved some code to a more central place to reuse it * * Revision 1.3 2000/12/06 17:28:05 fs * changes for the formlayer import - still under construction * * Revision 1.2 2000/11/19 15:41:32 fs * extended the export capabilities - generic controls / grid columns / generic properties / some missing form properties * * Revision 1.1 2000/11/17 19:01:28 fs * initial checkin - export and/or import the applications form layer * * * Revision 1.0 13.11.00 18:41:40 fs ************************************************************************/ <commit_msg>INTEGRATION: CWS dba12 (1.9.106); FILE MERGED 2004/05/17 12:06:51 fs 1.9.106.1: #i29644# don't export current-value and list entries if they're not provided by the user, but implicitly obtained from another source (such as a database, or an external binding/list source supplier)<commit_after>/************************************************************************* * * $RCSfile: elementexport.hxx,v $ * * $Revision: 1.10 $ * * last change: $Author: hjs $ $Date: 2004-06-28 17:04:51 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _XMLOFF_ELEMENTEXPORT_HXX_ #define _XMLOFF_ELEMENTEXPORT_HXX_ #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_ #include <com/sun/star/container/XIndexAccess.hpp> #endif #ifndef _COM_SUN_STAR_SCRIPT_SCRIPTEVENTDESCRIPTOR_HPP_ #include <com/sun/star/script/ScriptEventDescriptor.hpp> #endif #ifndef _XMLOFF_FORMS_PROPERTYEXPORT_HXX_ #include "propertyexport.hxx" #endif #ifndef _XMLOFF_FORMS_CALLBACKS_HXX_ #include "callbacks.hxx" #endif #ifndef _XMLOFF_FORMS_CONTROLELEMENT_HXX_ #include "controlelement.hxx" #endif #ifndef _XMLOFF_FORMS_VALUEPROPERTIES_HXX_ #include "valueproperties.hxx" #endif class SvXMLElementExport; //......................................................................... namespace xmloff { //......................................................................... //===================================================================== //= OElementExport //===================================================================== class OElementExport : public OPropertyExport { protected: ::com::sun::star::uno::Sequence< ::com::sun::star::script::ScriptEventDescriptor > m_aEvents; SvXMLElementExport* m_pXMLElement; // XML element doing the concrete startElement etc. public: OElementExport(IFormsExportContext& _rContext, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxProps, const ::com::sun::star::uno::Sequence< ::com::sun::star::script::ScriptEventDescriptor >& _rEvents); ~OElementExport(); void doExport(); protected: /// get the name of the XML element virtual const sal_Char* getXMLElementName() const = 0; /// examine the element we're exporting virtual void examine(); /// export the attributes virtual void exportAttributes(); /// export any sub tags virtual void exportSubTags(); /** exports the events (as script:events tag) */ void exportEvents(); /** add the service-name attribute to the export context */ virtual void exportServiceNameAttribute(); /// start the XML element virtual void implStartElement(const sal_Char* _pName); /// ends the XML element virtual void implEndElement(); }; //===================================================================== //= OControlExport //===================================================================== /** Helper class for handling xml elements representing a form control */ class OControlExport :public OControlElement ,public OValuePropertiesMetaData ,public OElementExport { protected: DECLARE_STL_STDKEY_SET(sal_Int16, Int16Set); // used below ::rtl::OUString m_sControlId; // the control id to use when exporting ::rtl::OUString m_sReferringControls; // list of referring controls (i.e. their id's) sal_Int16 m_nClassId; // class id of the control we're representing ElementType m_eType; // (XML) type of the control we're representing sal_Int32 m_nIncludeCommon; // common control attributes to include sal_Int32 m_nIncludeDatabase; // common database attributes to include sal_Int32 m_nIncludeSpecial; // special attributes to include sal_Int32 m_nIncludeEvents; // events to include sal_Int32 m_nIncludeBindings; // binding attributes to include SvXMLElementExport* m_pOuterElement; // XML element doing the concrete startElement etc. for the outer element public: /** constructs an object capable of exporting controls <p>You need at least two pre-requisites from outside: The control to be exported needs to have a class id assigned, and you need the list control-ids of all the controls referring to this one as LabelControl.<br/> This information can't be collected when known only the control itself and not it's complete context.</p> @param _rControlId the control id to use when exporting the control @param _rReferringControls the comma-separated list of control-ids of all the controls referring to this one as LabelControl */ OControlExport(IFormsExportContext& _rContext, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxControl, const ::rtl::OUString& _rControlId, const ::rtl::OUString& _rReferringControls, const ::com::sun::star::uno::Sequence< ::com::sun::star::script::ScriptEventDescriptor >& _rxEvents); ~OControlExport(); protected: /// start the XML element virtual void implStartElement(const sal_Char* _pName); /// ends the XML element virtual void implEndElement(); /// get the name of the outer XML element virtual const sal_Char* getOuterXMLElementName() const; // get the name of the XML element virtual const sal_Char* getXMLElementName() const; /** examine the control. Some kind of CtorImpl. */ virtual void examine(); /// exports the attributes for the outer element void exportOuterAttributes(); /// exports the attributes for the inner element void exportInnerAttributes(); /// export the attributes virtual void exportAttributes(); /** writes everything which needs to be represented as sub tag */ void exportSubTags() throw (::com::sun::star::uno::Exception); /** adds common control attributes to the XMLExport context given <p>The attribute list of the context is not cleared initially, this is the responsibility of the caller.</p> */ void exportCommonControlAttributes(); /** adds database attributes to the XMLExport context given <p>The attribute list of the context is not cleared initially, this is the responsibility of the caller.</p> */ void exportDatabaseAttributes(); /** adds the XML attributes which are related to binding controls to external values and/or list sources */ void exportBindingAtributes(); /** adds attributes which are special to a control type to the export context's attribute list */ void exportSpecialAttributes(); /** exports the ListSource property of a control as attribute The ListSource property may be exported in different ways: For a ComboBox, it is an attribute of the form:combobox element. For a ListBox, it's an attribute if the ListSourceType states that the ListBox does <em>not</em> display a value list. In case of a value list, the ListSource is not exported, and the pairs of StringItem/ValueItem are exported as sub-elements. This method does the attribute part: It exports the ListSource property as attribute, not caring about whether the object is a ComboBox or a ListBox. */ void exportListSourceAsAttribute(); /** exports the ListSource property of a control as XML elements @see exportListSourceAsAttribute */ void exportListSourceAsElements(); /** get's a Sequence&lt; sal_Int16 &gt; property value as set of sal_Int16's @param _rPropertyName the property name to use @param _rOut out parameter. The set of integers. */ void getSequenceInt16PropertyAsSet(const ::rtl::OUString& _rPropertyName, Int16Set& _rOut); /** exports the attribute which descrives a cell value binding of a control in a spreadsheet document */ void exportCellBindingAttributes( bool _bIncludeListLinkageType ); /** exports the attribute which descrives a cell range which acts as list source for a list-like control */ void exportCellListSourceRange( ); /** determines whether the control we're exporting has an active data binding. Bindings which count here are: <ul><li>an established connection to a database field</li> <li>a binding to an external value supplier (<type scope="com::sun::star::form::binding">XValueBinding</type>)</li> </ul> */ bool controlHasActiveDataBinding() const; /** retrieves the string specifying the ListSource of a list or combo box */ ::rtl::OUString OControlExport::getScalarListSourceValue() const; /** determines whether the list entries (of a combo or list box) are supplied by the user List entries may be <ul><li>specified by the user</li> <li>specified by an external list source (<type scope="com::sun::star::form::binding">XListEntrySource</type>)</li> <li>obtained from a database query (in various ways)</li> </ul> In the latter two cases, this method will return <FALSE/> */ bool controlHasUserSuppliedListEntries() const; }; //===================================================================== //= OColumnExport //===================================================================== /** Helper class for exporting a grid column */ class OColumnExport : public OControlExport { public: /** ctor @see OColumnExport::OColumnExport */ OColumnExport(IFormsExportContext& _rContext, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxControl, const ::com::sun::star::uno::Sequence< ::com::sun::star::script::ScriptEventDescriptor >& _rxEvents); ~OColumnExport(); protected: // OControlExport overridables virtual const sal_Char* getOuterXMLElementName() const; virtual void exportServiceNameAttribute(); virtual void exportAttributes(); // OElementExport overridables virtual void examine(); }; //===================================================================== //= OFormExport //===================================================================== /** Helper class for handling xml elements representing a form <p>In opposite to the class <type>OControlExport</type>, OFormExport is unable to export a <em>complete</em> form. Instead the client has to care for sub elements of the form itself.</p> */ class OFormExport :public OControlElement ,public OElementExport { public: /** constructs an object capable of exporting controls */ OFormExport(IFormsExportContext& _rContext, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxForm, const ::com::sun::star::uno::Sequence< ::com::sun::star::script::ScriptEventDescriptor >& _rxEvents ); protected: virtual const sal_Char* getXMLElementName() const; virtual void exportSubTags(); virtual void exportAttributes(); }; //......................................................................... } // namespace xmloff //......................................................................... #endif // _XMLOFF_ELEMENTEXPORT_HXX_ /************************************************************************* * history: * $Log: not supported by cvs2svn $ * Revision 1.9.106.1 2004/05/17 12:06:51 fs * #i29644# don't export current-value and list entries if they're not provided by the user, but implicitly obtained from another source (such as a database, or an external binding/list source supplier) * * Revision 1.9 2003/12/01 12:03:37 rt * INTEGRATION: CWS geordi2q09 (1.8.24); FILE MERGED * 2003/11/24 15:02:47 obo 1.8.24.2: undo last change * 2003/11/21 16:55:12 obo 1.8.24.1: #111934# join CWS comboboxlink * * Revision 1.8.24.2 2003/11/24 15:02:47 obo * undo last change * * Revision 1.8 2003/10/21 08:38:25 obo * INTEGRATION: CWS formcelllinkage (1.7.198); FILE MERGED * 2003/10/01 09:55:18 fs 1.7.198.1: #i18994# merging the changes from the CWS fs002 * * Revision 1.7.198.1 2003/10/01 09:55:18 fs * #i18994# merging the changes from the CWS fs002 * * Revision 1.7.194.1 2003/09/25 14:28:36 fs * #18994# merging the changes from cws_srx645_fs002 branch * * Revision 1.7.190.2 2003/09/18 14:00:36 fs * #18995# changes for binding list boxes to cells, while exchanging selection indexes instead of strings * * Revision 1.7.190.1 2003/09/17 12:26:46 fs * #18999# #19367# persistence for cell value and cell range bindings * * Revision 1.7 2001/01/03 16:25:34 fs * file format change (extra wrapper element for controls, similar to columns) * * Revision 1.6 2001/01/02 15:58:21 fs * event ex- & import * * Revision 1.5 2000/12/18 15:14:35 fs * some changes ... now exporting/importing styles * * Revision 1.4 2000/12/13 10:38:10 fs * moved some code to a more central place to reuse it * * Revision 1.3 2000/12/06 17:28:05 fs * changes for the formlayer import - still under construction * * Revision 1.2 2000/11/19 15:41:32 fs * extended the export capabilities - generic controls / grid columns / generic properties / some missing form properties * * Revision 1.1 2000/11/17 19:01:28 fs * initial checkin - export and/or import the applications form layer * * * Revision 1.0 13.11.00 18:41:40 fs ************************************************************************/ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: proxyaggregation.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: vg $ $Date: 2003-05-19 12:56:56 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef COMPHELPER_PROXY_AGGREGATION #define COMPHELPER_PROXY_AGGREGATION #ifndef _COM_SUN_STAR_UNO_XAGGREGATION_HPP_ #include <com/sun/star/uno/XAggregation.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_ #include <cppuhelper/interfacecontainer.hxx> #endif #ifndef _COMPHELPER_UNO3_HXX_ #include <comphelper/uno3.hxx> #endif #ifndef _COMPHELPER_BROADCASTHELPER_HXX_ #include <comphelper/broadcasthelper.hxx> #endif #ifndef _CPPUHELPER_COMPBASE_EX_HXX_ #include <cppuhelper/compbase_ex.hxx> #endif /* class hierarchy herein: +-------------------+ helper class for aggregating the proxy to another object | OProxyAggregation | - not ref counted +-------------------+ - no UNO implementation, i.e. not derived from XInterface ^ (neither direct nor indirect) | | +----------------------------------+ helper class for aggregating a proxy to an XComponent | OComponentProxyAggregationHelper | - life time coupling: if the inner component (the "aggregate") +----------------------------------+ is disposed, the outer (the delegator) is disposed, too, and ^ vice versa | - UNO based, implementing XEventListener | +----------------------------+ component aggregating another XComponent | OComponentProxyAggregation | - life time coupling as above +----------------------------+ - ref-counted - implements an XComponent itself If you need to - wrap a foreign object which is a XComponent => use OComponentProxyAggregation - call aggregateProxyFor in your ctor - call implEnsureDisposeInDtor in your dtor - wrap a foreign object which is a XComponent, but already have ref-counting mechanisms inherited from somewhere else => use OComponentProxyAggregationHelper - override dispose - don't forget to call the base class' dispose! - call aggregateProxyFor in your ctor - wrap a foreign object which is no XComponent => use OProxyAggregation - call aggregateProxyFor in your ctor */ //............................................................................. namespace comphelper { //............................................................................. //========================================================================= //= OProxyAggregation //========================================================================= /** helper class for aggregating a proxy for a foreign object */ class OProxyAggregation { private: ::com::sun::star::uno::Reference< ::com::sun::star::uno::XAggregation > m_xProxyAggregate; ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xORB; protected: inline const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& getORB() { return m_xORB; } protected: OProxyAggregation( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB ); ~OProxyAggregation(); /// to be called from within your ctor void aggregateProxyFor( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxComponent, oslInterlockedCount& _rRefCount, ::cppu::OWeakObject& _rDelegator ); // XInterface and XTypeProvider ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type& _rType ) throw (::com::sun::star::uno::RuntimeException); ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw (::com::sun::star::uno::RuntimeException); private: OProxyAggregation( ); // never implemented OProxyAggregation( const OProxyAggregation& ); // never implemented OProxyAggregation& operator=( const OProxyAggregation& ); // never implemented }; //========================================================================= //= OComponentProxyAggregationHelper //========================================================================= /** a helper class for aggregating a proxy to an XComponent <p>The object couples the life time of itself and the component: if one of the both dies (in a sense of being disposed), the other one dies, too.</p> <p>The class itself does not implement XComponent so you need to forward any XComponent::dispose calls which your derived class gets to the dispose method of this class.</p> */ class OComponentProxyAggregationHelper :public ::cppu::ImplHelper1 < com::sun::star::lang::XEventListener > ,private OProxyAggregation { private: typedef ::cppu::ImplHelper1 < ::com::sun::star::lang::XEventListener > BASE; // prevents some MSVC problems protected: ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent > m_xInner; ::cppu::OBroadcastHelper& m_rBHelper; protected: // OProxyAggregation OProxyAggregation::getORB; // XInterface ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& _rType ) throw (::com::sun::star::uno::RuntimeException); // still waiting to be overwritten virtual void SAL_CALL acquire( ) throw () = 0; virtual void SAL_CALL release( ) throw () = 0; // XTypeProvider DECLARE_XTYPEPROVIDER( ) protected: OComponentProxyAggregationHelper( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB, ::cppu::OBroadcastHelper& _rBHelper ); ~OComponentProxyAggregationHelper( ); /// to be called from within your ctor void aggregateProxyFor( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& _rxComponent, oslInterlockedCount& _rRefCount, ::cppu::OWeakObject& _rDelegator ); // XEventListener virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw (::com::sun::star::uno::RuntimeException); // XComponent virtual void SAL_CALL dispose() throw( ::com::sun::star::uno::RuntimeException ); private: OComponentProxyAggregationHelper( ); // never implemented OComponentProxyAggregationHelper( const OComponentProxyAggregationHelper& ); // never implemented OComponentProxyAggregationHelper& operator=( const OComponentProxyAggregationHelper& ); // never implemented }; //========================================================================= //= OComponentProxyAggregation //========================================================================= typedef ::cppu::WeakComponentImplHelperBase OComponentProxyAggregation_CBase; class OComponentProxyAggregation :public OBaseMutex ,public OComponentProxyAggregation_CBase ,public OComponentProxyAggregationHelper { protected: OComponentProxyAggregation( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& _rxComponent ); virtual ~OComponentProxyAggregation(); // XInterface DECLARE_XINTERFACE() // XTypeProvider DECLARE_XTYPEPROVIDER() // OComponentHelper virtual void SAL_CALL disposing() throw (::com::sun::star::uno::RuntimeException); // XEventListener virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& _rSource ) throw (::com::sun::star::uno::RuntimeException); // XComponent/OComponentProxyAggregationHelper virtual void SAL_CALL dispose() throw( ::com::sun::star::uno::RuntimeException ); protected: // be called from within the dtor of derived classes void implEnsureDisposeInDtor( ); private: OComponentProxyAggregation( ); // never implemented OComponentProxyAggregation( const OComponentProxyAggregation& ); // never implemented OComponentProxyAggregation& operator=( const OComponentProxyAggregation& ); // never implemented }; //............................................................................. } // namespace comphelper //............................................................................. #endif // COMPHELPER_PROXY_AGGREGATION <commit_msg>INTEGRATION: CWS jl3 (1.2.82); FILE MERGED 2004/03/10 11:47:13 fs 1.2.82.1: don't use queryAggregation on a proxy after the delegator has been set - the new proxy implementations do not support this<commit_after>/************************************************************************* * * $RCSfile: proxyaggregation.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2004-03-25 15:00:50 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef COMPHELPER_PROXY_AGGREGATION #define COMPHELPER_PROXY_AGGREGATION #ifndef _COM_SUN_STAR_UNO_XAGGREGATION_HPP_ #include <com/sun/star/uno/XAggregation.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_ #include <cppuhelper/interfacecontainer.hxx> #endif #ifndef _COMPHELPER_UNO3_HXX_ #include <comphelper/uno3.hxx> #endif #ifndef _COMPHELPER_BROADCASTHELPER_HXX_ #include <comphelper/broadcasthelper.hxx> #endif #ifndef _CPPUHELPER_COMPBASE_EX_HXX_ #include <cppuhelper/compbase_ex.hxx> #endif /* class hierarchy herein: +-------------------+ helper class for aggregating the proxy to another object | OProxyAggregation | - not ref counted +-------------------+ - no UNO implementation, i.e. not derived from XInterface ^ (neither direct nor indirect) | | +----------------------------------+ helper class for aggregating a proxy to an XComponent | OComponentProxyAggregationHelper | - life time coupling: if the inner component (the "aggregate") +----------------------------------+ is disposed, the outer (the delegator) is disposed, too, and ^ vice versa | - UNO based, implementing XEventListener | +----------------------------+ component aggregating another XComponent | OComponentProxyAggregation | - life time coupling as above +----------------------------+ - ref-counted - implements an XComponent itself If you need to - wrap a foreign object which is a XComponent => use OComponentProxyAggregation - call aggregateProxyFor in your ctor - call implEnsureDisposeInDtor in your dtor - wrap a foreign object which is a XComponent, but already have ref-counting mechanisms inherited from somewhere else => use OComponentProxyAggregationHelper - override dispose - don't forget to call the base class' dispose! - call aggregateProxyFor in your ctor - wrap a foreign object which is no XComponent => use OProxyAggregation - call aggregateProxyFor in your ctor */ //............................................................................. namespace comphelper { //............................................................................. //========================================================================= //= OProxyAggregation //========================================================================= /** helper class for aggregating a proxy for a foreign object */ class OProxyAggregation { private: ::com::sun::star::uno::Reference< ::com::sun::star::uno::XAggregation > m_xProxyAggregate; ::com::sun::star::uno::Reference< ::com::sun::star::lang::XTypeProvider > m_xProxyTypeAccess; ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xORB; protected: inline const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& getORB() { return m_xORB; } protected: OProxyAggregation( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB ); ~OProxyAggregation(); /// to be called from within your ctor void aggregateProxyFor( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxComponent, oslInterlockedCount& _rRefCount, ::cppu::OWeakObject& _rDelegator ); // XInterface and XTypeProvider ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type& _rType ) throw (::com::sun::star::uno::RuntimeException); ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw (::com::sun::star::uno::RuntimeException); private: OProxyAggregation( ); // never implemented OProxyAggregation( const OProxyAggregation& ); // never implemented OProxyAggregation& operator=( const OProxyAggregation& ); // never implemented }; //========================================================================= //= OComponentProxyAggregationHelper //========================================================================= /** a helper class for aggregating a proxy to an XComponent <p>The object couples the life time of itself and the component: if one of the both dies (in a sense of being disposed), the other one dies, too.</p> <p>The class itself does not implement XComponent so you need to forward any XComponent::dispose calls which your derived class gets to the dispose method of this class.</p> */ class OComponentProxyAggregationHelper :public ::cppu::ImplHelper1 < com::sun::star::lang::XEventListener > ,private OProxyAggregation { private: typedef ::cppu::ImplHelper1 < ::com::sun::star::lang::XEventListener > BASE; // prevents some MSVC problems protected: ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent > m_xInner; ::cppu::OBroadcastHelper& m_rBHelper; protected: // OProxyAggregation OProxyAggregation::getORB; // XInterface ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& _rType ) throw (::com::sun::star::uno::RuntimeException); // still waiting to be overwritten virtual void SAL_CALL acquire( ) throw () = 0; virtual void SAL_CALL release( ) throw () = 0; // XTypeProvider DECLARE_XTYPEPROVIDER( ) protected: OComponentProxyAggregationHelper( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB, ::cppu::OBroadcastHelper& _rBHelper ); ~OComponentProxyAggregationHelper( ); /// to be called from within your ctor void aggregateProxyFor( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& _rxComponent, oslInterlockedCount& _rRefCount, ::cppu::OWeakObject& _rDelegator ); // XEventListener virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw (::com::sun::star::uno::RuntimeException); // XComponent virtual void SAL_CALL dispose() throw( ::com::sun::star::uno::RuntimeException ); private: OComponentProxyAggregationHelper( ); // never implemented OComponentProxyAggregationHelper( const OComponentProxyAggregationHelper& ); // never implemented OComponentProxyAggregationHelper& operator=( const OComponentProxyAggregationHelper& ); // never implemented }; //========================================================================= //= OComponentProxyAggregation //========================================================================= typedef ::cppu::WeakComponentImplHelperBase OComponentProxyAggregation_CBase; class OComponentProxyAggregation :public OBaseMutex ,public OComponentProxyAggregation_CBase ,public OComponentProxyAggregationHelper { protected: OComponentProxyAggregation( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& _rxComponent ); virtual ~OComponentProxyAggregation(); // XInterface DECLARE_XINTERFACE() // XTypeProvider DECLARE_XTYPEPROVIDER() // OComponentHelper virtual void SAL_CALL disposing() throw (::com::sun::star::uno::RuntimeException); // XEventListener virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& _rSource ) throw (::com::sun::star::uno::RuntimeException); // XComponent/OComponentProxyAggregationHelper virtual void SAL_CALL dispose() throw( ::com::sun::star::uno::RuntimeException ); protected: // be called from within the dtor of derived classes void implEnsureDisposeInDtor( ); private: OComponentProxyAggregation( ); // never implemented OComponentProxyAggregation( const OComponentProxyAggregation& ); // never implemented OComponentProxyAggregation& operator=( const OComponentProxyAggregation& ); // never implemented }; //............................................................................. } // namespace comphelper //............................................................................. #endif // COMPHELPER_PROXY_AGGREGATION <|endoftext|>
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "kudu/server/webui_util.h" #include <sstream> #include <string> #include "kudu/gutil/strings/join.h" #include "kudu/gutil/map-util.h" #include "kudu/gutil/strings/human_readable.h" #include "kudu/gutil/strings/substitute.h" #include "kudu/server/monitored_task.h" #include "kudu/util/url-coding.h" using strings::Substitute; namespace kudu { void HtmlOutputSchemaTable(const Schema& schema, std::ostringstream* output) { *output << "<table class='table table-striped'>\n"; *output << " <tr>" << "<th>Column</th><th>ID</th><th>Type</th>" << "<th>Encoding</th><th>Compression</th>" << "<th>Read default</th><th>Write default</th>" << "</tr>\n"; for (int i = 0; i < schema.num_columns(); i++) { const ColumnSchema& col = schema.column(i); string read_default = "-"; if (col.has_read_default()) { read_default = col.Stringify(col.read_default_value()); } string write_default = "-"; if (col.has_write_default()) { write_default = col.Stringify(col.write_default_value()); } const ColumnStorageAttributes& attrs = col.attributes(); const string& encoding = EncodingType_Name(attrs.encoding); const string& compression = CompressionType_Name(attrs.compression); *output << Substitute("<tr><th>$0</th><td>$1</td><td>$2</td><td>$3</td>" "<td>$4</td><td>$5</td><td>$6</td></tr>\n", EscapeForHtmlToString(col.name()), schema.column_id(i), col.TypeToString(), EscapeForHtmlToString(encoding), EscapeForHtmlToString(compression), EscapeForHtmlToString(read_default), EscapeForHtmlToString(write_default)); } *output << "</table>\n"; } void HtmlOutputImpalaSchema(const std::string& table_name, const Schema& schema, const string& master_addresses, std::ostringstream* output) { *output << "<pre><code>\n"; // Escape table and column names with ` to avoid conflicts with Impala reserved words. *output << "CREATE EXTERNAL TABLE " << EscapeForHtmlToString("`" + table_name + "`") << " (\n"; vector<string> key_columns; for (int i = 0; i < schema.num_columns(); i++) { const ColumnSchema& col = schema.column(i); *output << EscapeForHtmlToString("`" + col.name() + "`") << " "; switch (col.type_info()->type()) { case STRING: *output << "STRING"; break; case BINARY: *output << "BINARY"; break; case UINT8: case INT8: *output << "TINYINT"; break; case UINT16: case INT16: *output << "SMALLINT"; break; case UINT32: case INT32: *output << "INT"; break; case UINT64: case INT64: *output << "BIGINT"; break; case UNIXTIME_MICROS: *output << "INT64"; break; case FLOAT: *output << "FLOAT"; break; case DOUBLE: *output << "DOUBLE"; break; case BOOL: *output << "BOOLEAN"; break; default: *output << "[unsupported type " << col.type_info()->name() << "!]"; break; } if (i < schema.num_columns() - 1) { *output << ","; } *output << "\n"; if (schema.is_key_column(i)) { key_columns.push_back(col.name()); } } *output << ")\n"; *output << "TBLPROPERTIES(\n"; *output << " 'storage_handler' = 'com.cloudera.kudu.hive.KuduStorageHandler',\n"; *output << " 'kudu.table_name' = '"; *output << EscapeForHtmlToString(table_name) << "',\n"; *output << " 'kudu.master_addresses' = '"; *output << EscapeForHtmlToString(master_addresses) << "',\n"; *output << " 'kudu.key_columns' = '"; *output << EscapeForHtmlToString(JoinElements(key_columns, ", ")) << "'\n"; *output << ");\n"; *output << "</code></pre>\n"; } void HtmlOutputTaskList(const std::vector<scoped_refptr<MonitoredTask> >& tasks, std::ostringstream* output) { *output << "<table class='table table-striped'>\n"; *output << " <tr><th>Task Name</th><th>State</th><th>Time</th><th>Description</th></tr>\n"; for (const scoped_refptr<MonitoredTask>& task : tasks) { string state; switch (task->state()) { case MonitoredTask::kStatePreparing: state = "Preparing"; break; case MonitoredTask::kStateRunning: state = "Running"; break; case MonitoredTask::kStateComplete: state = "Complete"; break; case MonitoredTask::kStateFailed: state = "Failed"; break; case MonitoredTask::kStateAborted: state = "Aborted"; break; } double running_secs = 0; if (task->completion_timestamp().Initialized()) { running_secs = (task->completion_timestamp() - task->start_timestamp()).ToSeconds(); } else if (task->start_timestamp().Initialized()) { running_secs = (MonoTime::Now() - task->start_timestamp()).ToSeconds(); } *output << Substitute( "<tr><th>$0</th><td>$1</td><td>$2</td><td>$3</td></tr>\n", EscapeForHtmlToString(task->type_name()), EscapeForHtmlToString(state), EscapeForHtmlToString(HumanReadableElapsedTime::ToShortString(running_secs)), EscapeForHtmlToString(task->description())); } *output << "</table>\n"; } } // namespace kudu <commit_msg>KUDU-1763. Fix Impala CREATE EXTERNAL TABLE statement<commit_after>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "kudu/server/webui_util.h" #include <sstream> #include <string> #include "kudu/gutil/strings/join.h" #include "kudu/gutil/map-util.h" #include "kudu/gutil/strings/human_readable.h" #include "kudu/gutil/strings/substitute.h" #include "kudu/server/monitored_task.h" #include "kudu/util/url-coding.h" using strings::Substitute; namespace kudu { void HtmlOutputSchemaTable(const Schema& schema, std::ostringstream* output) { *output << "<table class='table table-striped'>\n"; *output << " <tr>" << "<th>Column</th><th>ID</th><th>Type</th>" << "<th>Encoding</th><th>Compression</th>" << "<th>Read default</th><th>Write default</th>" << "</tr>\n"; for (int i = 0; i < schema.num_columns(); i++) { const ColumnSchema& col = schema.column(i); string read_default = "-"; if (col.has_read_default()) { read_default = col.Stringify(col.read_default_value()); } string write_default = "-"; if (col.has_write_default()) { write_default = col.Stringify(col.write_default_value()); } const ColumnStorageAttributes& attrs = col.attributes(); const string& encoding = EncodingType_Name(attrs.encoding); const string& compression = CompressionType_Name(attrs.compression); *output << Substitute("<tr><th>$0</th><td>$1</td><td>$2</td><td>$3</td>" "<td>$4</td><td>$5</td><td>$6</td></tr>\n", EscapeForHtmlToString(col.name()), schema.column_id(i), col.TypeToString(), EscapeForHtmlToString(encoding), EscapeForHtmlToString(compression), EscapeForHtmlToString(read_default), EscapeForHtmlToString(write_default)); } *output << "</table>\n"; } void HtmlOutputImpalaSchema(const std::string& table_name, const Schema& schema, const string& master_addresses, std::ostringstream* output) { *output << "<pre><code>\n"; // Escape table and column names with ` to avoid conflicts with Impala reserved words. *output << "CREATE EXTERNAL TABLE " << EscapeForHtmlToString("`" + table_name + "`") << " STORED AS KUDU\n"; *output << "TBLPROPERTIES(\n"; *output << " 'kudu.table_name' = '"; *output << EscapeForHtmlToString(table_name) << "',\n"; *output << " 'kudu.master_addresses' = '"; *output << EscapeForHtmlToString(master_addresses) << "'"; *output << ");\n"; *output << "</code></pre>\n"; } void HtmlOutputTaskList(const std::vector<scoped_refptr<MonitoredTask> >& tasks, std::ostringstream* output) { *output << "<table class='table table-striped'>\n"; *output << " <tr><th>Task Name</th><th>State</th><th>Time</th><th>Description</th></tr>\n"; for (const scoped_refptr<MonitoredTask>& task : tasks) { string state; switch (task->state()) { case MonitoredTask::kStatePreparing: state = "Preparing"; break; case MonitoredTask::kStateRunning: state = "Running"; break; case MonitoredTask::kStateComplete: state = "Complete"; break; case MonitoredTask::kStateFailed: state = "Failed"; break; case MonitoredTask::kStateAborted: state = "Aborted"; break; } double running_secs = 0; if (task->completion_timestamp().Initialized()) { running_secs = (task->completion_timestamp() - task->start_timestamp()).ToSeconds(); } else if (task->start_timestamp().Initialized()) { running_secs = (MonoTime::Now() - task->start_timestamp()).ToSeconds(); } *output << Substitute( "<tr><th>$0</th><td>$1</td><td>$2</td><td>$3</td></tr>\n", EscapeForHtmlToString(task->type_name()), EscapeForHtmlToString(state), EscapeForHtmlToString(HumanReadableElapsedTime::ToShortString(running_secs)), EscapeForHtmlToString(task->description())); } *output << "</table>\n"; } } // namespace kudu <|endoftext|>
<commit_before>#include <sys/time.h> #include "thread_private.h" #include "parameters.h" #include "exception.h" bool align_req = false; int align_size = PAGE_SIZE; extern struct timeval global_start; class cleanup_callback: public callback { rand_buf *buf; ssize_t read_bytes; int thread_id; thread_private *thread; public: #ifdef DEBUG std::tr1::unordered_map<char *, workload_t> pending_reqs; #endif cleanup_callback(rand_buf *buf, int idx, thread_private *thread) { this->buf = buf; read_bytes = 0; this->thread_id = idx; this->thread = thread; } int invoke(io_request *rqs[], int num) { assert(thread == thread::get_curr_thread()); for (int i = 0; i < num; i++) { io_request *rq = rqs[i]; if (rq->get_access_method() == READ && params.is_verify_content()) { off_t off = rq->get_offset(); for (int i = 0; i < rq->get_num_bufs(); i++) { assert(check_read_content(rq->get_buf(i), rq->get_buf_size(i), off)); off += rq->get_buf_size(i); } } #ifdef DEBUG assert(rq->get_num_bufs() == 1); pending_reqs.erase(rq->get_buf(0)); #endif for (int i = 0; i < rq->get_num_bufs(); i++) buf->free_entry(rq->get_buf(i)); read_bytes += rq->get_size(); } #ifdef STATISTICS thread->num_completes.inc(num); int res = thread->num_pending.dec(num); assert(res >= 0); #endif return 0; } ssize_t get_size() { return read_bytes; } }; ssize_t thread_private::get_read_bytes() { if (cb) return cb->get_size(); else return read_bytes; } void thread_private::init() { io = factory->create_io(this); io->set_max_num_pending_ios(params.get_aio_depth_per_file()); io->init(); rand_buf *buf = new rand_buf(config.get_buf_size(), config.get_entry_size(), node_id); this->buf = buf; if (io->support_aio()) { cb = new cleanup_callback(buf, idx, this); io->set_callback(cb); } } class work2req_converter { workload_t workload; int align_size; rand_buf *buf; io_interface *io; public: work2req_converter(io_interface *io, rand_buf * buf, int align_size) { workload.off = -1; workload.size = -1; workload.read = 0; this->align_size = align_size; this->buf = buf; this->io = io; } void init(const workload_t &workload) { this->workload = workload; if (align_size > 0) { this->workload.off = ROUND(workload.off, align_size); this->workload.size = ROUNDUP(workload.off + workload.size, align_size) - ROUND(workload.off, align_size); } } bool has_complete() const { return workload.size <= 0; } int to_reqs(int buf_type, int num, io_request reqs[]); }; int work2req_converter::to_reqs(int buf_type, int num, io_request reqs[]) { int node_id = io->get_node_id(); int access_method = workload.read ? READ : WRITE; off_t off = workload.off; int size = workload.size; if (buf_type == MULTI_BUF) { throw unsupported_exception(); #if 0 assert(off % PAGE_SIZE == 0); int num_vecs = size / PAGE_SIZE; reqs[i].init(off, io, access_method, node_id); assert(buf->get_entry_size() >= PAGE_SIZE); for (int k = 0; k < num_vecs; k++) { reqs[i].add_buf(buf->next_entry(PAGE_SIZE), PAGE_SIZE); } workload.off += size; workload.size = 0; #endif } else if (buf_type == SINGLE_SMALL_BUF) { int i = 0; while (size > 0 && i < num) { off_t next_off = ROUNDUP_PAGE(off + 1); if (next_off > off + size) next_off = off + size; char *p = buf->next_entry(next_off - off); if (p == NULL) break; if (access_method == WRITE && params.is_verify_content()) create_write_data(p, next_off - off, off); reqs[i].init(p, off, next_off - off, access_method, io, node_id); size -= next_off - off; off = next_off; i++; } workload.off = off; workload.size = size; return i; } else { char *p = buf->next_entry(size); if (p == NULL) return 0; if (access_method == WRITE && params.is_verify_content()) create_write_data(p, size, off); reqs[0].init(p, off, size, access_method, io, node_id); workload.off += size; workload.size = 0; return 1; } } void thread_private::run() { gettimeofday(&start_time, NULL); io_request reqs[NUM_REQS_BY_USER]; char *entry = NULL; if (config.is_use_aio()) assert(io->support_aio()); if (!config.is_use_aio()) { entry = (char *) valloc(config.get_entry_size()); } work2req_converter converter(io, buf, align_size); while (gen->has_next()) { if (config.is_use_aio()) { int i; bool no_mem = false; int num_reqs_by_user = min(io->get_remaining_io_slots(), NUM_REQS_BY_USER); for (i = 0; i < num_reqs_by_user; ) { if (converter.has_complete() && gen->has_next()) { converter.init(gen->next()); } if (converter.has_complete()) break; int ret = converter.to_reqs(config.get_buf_type(), num_reqs_by_user - i, reqs + i); if (ret == 0) { no_mem = true; break; } i += ret; } if (i > 0) { #ifdef DEBUG for (int k = 0; k < i; k++) { workload_t work = {reqs[k].get_offset(), (int) reqs[k].get_size(), reqs[k].get_access_method() == READ}; cb->pending_reqs.insert(std::pair<char *, workload_t>( reqs[k].get_buf(0), work)); } #endif io->access(reqs, i); } #ifdef STATISTICS int curr = num_pending.inc(i); if (max_num_pending < curr) max_num_pending = curr; if (num_accesses % 100 == 0) { num_sampling++; tot_num_pending += curr; } #endif // We wait if we don't have IO slots left or we can't issue // more requests due to the lack of memory. if (io->get_remaining_io_slots() <= 0 || no_mem) { int num_ios = io->get_max_num_pending_ios() / 10; if (num_ios == 0) num_ios = 1; io->wait4complete(num_ios); } num_accesses += i; } else { int ret = 0; workload_t workload = gen->next(); off_t off = workload.off; int access_method = workload.read ? READ : WRITE; int entry_size = workload.size; if (align_req) { off = ROUND(off, align_size); entry_size = ROUNDUP(off + entry_size, align_size) - ROUND(off, align_size); } if (config.get_buf_type() == SINGLE_SMALL_BUF) { while (entry_size > 0) { /* * generate the data for writing the file, * so the data in the file isn't changed. */ if (access_method == WRITE && params.is_verify_content()) { create_write_data(entry, entry_size, off); } // There is at least one byte we need to access in the page. // By adding 1 and rounding up the offset, we'll get the next page // behind the current offset. off_t next_off = ROUNDUP_PAGE(off + 1); if (next_off > off + entry_size) next_off = off + entry_size; io_status status = io->access(entry, off, next_off - off, access_method); assert(!(status == IO_UNSUPPORTED)); if (status == IO_OK) { num_accesses++; if (access_method == READ && params.is_verify_content()) { check_read_content(entry, next_off - off, off); } read_bytes += ret; } if (status == IO_FAIL) { perror("access"); ::exit(1); } entry_size -= next_off - off; off = next_off; } } else { if (access_method == WRITE && params.is_verify_content()) { create_write_data(entry, entry_size, off); } io_status status = io->access(entry, off, entry_size, access_method); assert(!(status == IO_UNSUPPORTED)); if (status == IO_OK) { num_accesses++; if (access_method == READ && params.is_verify_content()) { check_read_content(entry, entry_size, off); } read_bytes += ret; } if (status == IO_FAIL) { perror("access"); ::exit(1); } } } } printf("thread %d has issued all requests\n", idx); io->cleanup(); gettimeofday(&end_time, NULL); // Stop itself. stop(); } int thread_private::attach2cpu() { #if 0 cpu_set_t cpuset; pthread_t thread = pthread_self(); CPU_ZERO(&cpuset); int cpu_num = idx % NCPUS; CPU_SET(cpu_num, &cpuset); int ret = pthread_setaffinity_np(thread, sizeof(cpu_set_t), &cpuset); if (ret != 0) { perror("pthread_setaffinity_np"); exit(1); } return ret; #endif return 0; } #ifdef USE_PROCESS static int process_create(pid_t *pid, void (*func)(void *), void *priv) { pid_t id = fork(); if (id < 0) return -1; if (id == 0) { // child func(priv); exit(0); } if (id > 0) *pid = id; return 0; } static int process_join(pid_t pid) { int status; pid_t ret = waitpid(pid, &status, 0); return ret < 0 ? ret : 0; } #endif void thread_private::print_stat() { #ifdef STATISTICS #ifdef DEBUG assert(num_pending.get() == (int) cb->pending_reqs.size()); if (cb->pending_reqs.size() > 0) { for (std::tr1::unordered_map<char *, workload_t>::const_iterator it = cb->pending_reqs.begin(); it != cb->pending_reqs.end(); it++) { workload_t work = it->second; printf("missing req %lx, size %d, read: %d\n", work.off, work.size, work.read); } } #endif io->print_stat(config.get_nthreads()); int avg_num_pending = 0; if (num_sampling > 0) avg_num_pending = tot_num_pending / num_sampling; printf("access %ld bytes in %ld accesses (%d completes), avg pending: %d, max pending: %d, remaining pending: %d\n", get_read_bytes(), num_accesses, num_completes.get(), avg_num_pending, max_num_pending, num_pending.get()); #endif extern struct timeval global_start; printf("thread %d: start at %f seconds, takes %f seconds, access %ld bytes in %ld accesses\n", idx, time_diff(global_start, start_time), time_diff(start_time, end_time), get_read_bytes(), num_accesses); } <commit_msg>Fix a bug in the test program.<commit_after>#include <sys/time.h> #include "thread_private.h" #include "parameters.h" #include "exception.h" bool align_req = false; int align_size = PAGE_SIZE; extern struct timeval global_start; class cleanup_callback: public callback { rand_buf *buf; ssize_t read_bytes; int thread_id; thread_private *thread; public: #ifdef DEBUG std::tr1::unordered_map<char *, workload_t> pending_reqs; #endif cleanup_callback(rand_buf *buf, int idx, thread_private *thread) { this->buf = buf; read_bytes = 0; this->thread_id = idx; this->thread = thread; } int invoke(io_request *rqs[], int num) { assert(thread == thread::get_curr_thread()); for (int i = 0; i < num; i++) { io_request *rq = rqs[i]; if (rq->get_access_method() == READ && params.is_verify_content()) { off_t off = rq->get_offset(); for (int i = 0; i < rq->get_num_bufs(); i++) { assert(check_read_content(rq->get_buf(i), rq->get_buf_size(i), off)); off += rq->get_buf_size(i); } } #ifdef DEBUG assert(rq->get_num_bufs() == 1); pending_reqs.erase(rq->get_buf(0)); #endif for (int i = 0; i < rq->get_num_bufs(); i++) buf->free_entry(rq->get_buf(i)); read_bytes += rq->get_size(); } #ifdef STATISTICS thread->num_completes.inc(num); int res = thread->num_pending.dec(num); assert(res >= 0); #endif return 0; } ssize_t get_size() { return read_bytes; } }; ssize_t thread_private::get_read_bytes() { if (cb) return cb->get_size(); else return read_bytes; } void thread_private::init() { io = factory->create_io(this); io->set_max_num_pending_ios(params.get_aio_depth_per_file()); io->init(); rand_buf *buf = new rand_buf(config.get_buf_size(), config.get_entry_size(), node_id); this->buf = buf; if (io->support_aio()) { cb = new cleanup_callback(buf, idx, this); io->set_callback(cb); } } class work2req_converter { workload_t workload; int align_size; rand_buf *buf; io_interface *io; public: work2req_converter(io_interface *io, rand_buf * buf, int align_size) { workload.off = -1; workload.size = -1; workload.read = 0; this->align_size = align_size; this->buf = buf; this->io = io; } void init(const workload_t &workload) { this->workload = workload; if (align_size > 0) { this->workload.off = ROUND(workload.off, align_size); this->workload.size = ROUNDUP(workload.off + workload.size, align_size) - ROUND(workload.off, align_size); } } bool has_complete() const { return workload.size <= 0; } int to_reqs(int buf_type, int num, io_request reqs[]); }; int work2req_converter::to_reqs(int buf_type, int num, io_request reqs[]) { int node_id = io->get_node_id(); int access_method = workload.read ? READ : WRITE; off_t off = workload.off; int size = workload.size; if (buf_type == MULTI_BUF) { throw unsupported_exception(); #if 0 assert(off % PAGE_SIZE == 0); int num_vecs = size / PAGE_SIZE; reqs[i].init(off, io, access_method, node_id); assert(buf->get_entry_size() >= PAGE_SIZE); for (int k = 0; k < num_vecs; k++) { reqs[i].add_buf(buf->next_entry(PAGE_SIZE), PAGE_SIZE); } workload.off += size; workload.size = 0; #endif } else if (buf_type == SINGLE_SMALL_BUF) { int i = 0; while (size > 0 && i < num) { off_t next_off = ROUNDUP_PAGE(off + 1); if (next_off > off + size) next_off = off + size; char *p = buf->next_entry(next_off - off); if (p == NULL) break; if (access_method == WRITE && params.is_verify_content()) create_write_data(p, next_off - off, off); reqs[i].init(p, off, next_off - off, access_method, io, node_id); size -= next_off - off; off = next_off; i++; } workload.off = off; workload.size = size; return i; } else { char *p = buf->next_entry(size); if (p == NULL) return 0; if (access_method == WRITE && params.is_verify_content()) create_write_data(p, size, off); reqs[0].init(p, off, size, access_method, io, node_id); workload.off += size; workload.size = 0; return 1; } } void thread_private::run() { gettimeofday(&start_time, NULL); io_request reqs[NUM_REQS_BY_USER]; char *entry = NULL; if (config.is_use_aio()) assert(io->support_aio()); if (!config.is_use_aio()) { entry = (char *) valloc(config.get_entry_size()); } work2req_converter converter(io, buf, align_size); while (gen->has_next()) { if (config.is_use_aio()) { int i; bool no_mem = false; int num_reqs_by_user = min(io->get_remaining_io_slots(), NUM_REQS_BY_USER); for (i = 0; i < num_reqs_by_user; ) { if (converter.has_complete() && gen->has_next()) { converter.init(gen->next()); } if (converter.has_complete()) break; int ret = converter.to_reqs(config.get_buf_type(), num_reqs_by_user - i, reqs + i); if (ret == 0) { no_mem = true; break; } i += ret; } #ifdef STATISTICS /* * cached IO may complete a request before calling wait4complte(). * so we need to increase num_pending before access() is called. */ int curr = num_pending.inc(i); #endif if (i > 0) { #ifdef DEBUG for (int k = 0; k < i; k++) { workload_t work = {reqs[k].get_offset(), (int) reqs[k].get_size(), reqs[k].get_access_method() == READ}; cb->pending_reqs.insert(std::pair<char *, workload_t>( reqs[k].get_buf(0), work)); } #endif io->access(reqs, i); } #ifdef STATISTICS if (max_num_pending < curr) max_num_pending = curr; if (num_accesses % 100 == 0) { num_sampling++; tot_num_pending += curr; } #endif // We wait if we don't have IO slots left or we can't issue // more requests due to the lack of memory. if (io->get_remaining_io_slots() <= 0 || no_mem) { int num_ios = io->get_max_num_pending_ios() / 10; if (num_ios == 0) num_ios = 1; io->wait4complete(num_ios); } num_accesses += i; } else { int ret = 0; workload_t workload = gen->next(); off_t off = workload.off; int access_method = workload.read ? READ : WRITE; int entry_size = workload.size; if (align_req) { off = ROUND(off, align_size); entry_size = ROUNDUP(off + entry_size, align_size) - ROUND(off, align_size); } if (config.get_buf_type() == SINGLE_SMALL_BUF) { while (entry_size > 0) { /* * generate the data for writing the file, * so the data in the file isn't changed. */ if (access_method == WRITE && params.is_verify_content()) { create_write_data(entry, entry_size, off); } // There is at least one byte we need to access in the page. // By adding 1 and rounding up the offset, we'll get the next page // behind the current offset. off_t next_off = ROUNDUP_PAGE(off + 1); if (next_off > off + entry_size) next_off = off + entry_size; io_status status = io->access(entry, off, next_off - off, access_method); assert(!(status == IO_UNSUPPORTED)); if (status == IO_OK) { num_accesses++; if (access_method == READ && params.is_verify_content()) { check_read_content(entry, next_off - off, off); } read_bytes += ret; } if (status == IO_FAIL) { perror("access"); ::exit(1); } entry_size -= next_off - off; off = next_off; } } else { if (access_method == WRITE && params.is_verify_content()) { create_write_data(entry, entry_size, off); } io_status status = io->access(entry, off, entry_size, access_method); assert(!(status == IO_UNSUPPORTED)); if (status == IO_OK) { num_accesses++; if (access_method == READ && params.is_verify_content()) { check_read_content(entry, entry_size, off); } read_bytes += ret; } if (status == IO_FAIL) { perror("access"); ::exit(1); } } } } printf("thread %d has issued all requests\n", idx); io->cleanup(); gettimeofday(&end_time, NULL); // Stop itself. stop(); } int thread_private::attach2cpu() { #if 0 cpu_set_t cpuset; pthread_t thread = pthread_self(); CPU_ZERO(&cpuset); int cpu_num = idx % NCPUS; CPU_SET(cpu_num, &cpuset); int ret = pthread_setaffinity_np(thread, sizeof(cpu_set_t), &cpuset); if (ret != 0) { perror("pthread_setaffinity_np"); exit(1); } return ret; #endif return 0; } #ifdef USE_PROCESS static int process_create(pid_t *pid, void (*func)(void *), void *priv) { pid_t id = fork(); if (id < 0) return -1; if (id == 0) { // child func(priv); exit(0); } if (id > 0) *pid = id; return 0; } static int process_join(pid_t pid) { int status; pid_t ret = waitpid(pid, &status, 0); return ret < 0 ? ret : 0; } #endif void thread_private::print_stat() { #ifdef STATISTICS #ifdef DEBUG assert(num_pending.get() == (int) cb->pending_reqs.size()); if (cb->pending_reqs.size() > 0) { for (std::tr1::unordered_map<char *, workload_t>::const_iterator it = cb->pending_reqs.begin(); it != cb->pending_reqs.end(); it++) { workload_t work = it->second; printf("missing req %lx, size %d, read: %d\n", work.off, work.size, work.read); } } #endif io->print_stat(config.get_nthreads()); int avg_num_pending = 0; if (num_sampling > 0) avg_num_pending = tot_num_pending / num_sampling; printf("access %ld bytes in %ld accesses (%d completes), avg pending: %d, max pending: %d, remaining pending: %d\n", get_read_bytes(), num_accesses, num_completes.get(), avg_num_pending, max_num_pending, num_pending.get()); #endif extern struct timeval global_start; printf("thread %d: start at %f seconds, takes %f seconds, access %ld bytes in %ld accesses\n", idx, time_diff(global_start, start_time), time_diff(start_time, end_time), get_read_bytes(), num_accesses); } <|endoftext|>
<commit_before>#ifndef ITER_SLIDING_WINDOW_HPP_ #define ITER_SLIDING_WINDOW_HPP_ #include "internal/iterator_wrapper.hpp" #include "internal/iteratoriterator.hpp" #include "internal/iterbase.hpp" #include <deque> #include <iterator> #include <utility> namespace iter { namespace impl { template <typename Container> class WindowSlider; using SlidingWindowFn = IterToolFnBindSizeTSecond<WindowSlider>; } constexpr impl::SlidingWindowFn sliding_window{}; } template <typename Container> class iter::impl::WindowSlider { private: Container container; std::size_t window_size; friend SlidingWindowFn; WindowSlider(Container&& in_container, std::size_t win_sz) : container(std::forward<Container>(in_container)), window_size{win_sz} {} using IndexVector = std::deque<IteratorWrapper<Container>>; using DerefVec = IterIterWrapper<IndexVector>; public: WindowSlider(WindowSlider&&) = default; class Iterator : public std::iterator<std::input_iterator_tag, DerefVec> { private: IteratorWrapper<Container> sub_iter; DerefVec window; public: Iterator(IteratorWrapper<Container>&& in_iter, IteratorWrapper<Container>&& in_end, std::size_t window_sz) : sub_iter(std::move(in_iter)) { std::size_t i{0}; while (i < window_sz && this->sub_iter != in_end) { this->window.get().push_back(this->sub_iter); ++i; if (i != window_sz) { ++this->sub_iter; } } } bool operator!=(const Iterator& other) const { return this->sub_iter != other.sub_iter; } bool operator==(const Iterator& other) const { return !(*this != other); } DerefVec& operator*() { return this->window; } DerefVec* operator->() { return this->window; } Iterator& operator++() { ++this->sub_iter; this->window.get().pop_front(); this->window.get().push_back(this->sub_iter); return *this; } Iterator operator++(int) { auto ret = *this; ++*this; return ret; } }; Iterator begin() { return {(this->window_size != 0 ? IteratorWrapper<Container>{std::begin(this->container)} : IteratorWrapper<Container>{std::end(this->container)}), std::end(this->container), this->window_size}; } Iterator end() { return {std::end(this->container), std::end(this->container), this->window_size}; } }; #endif <commit_msg>trailing _ on data members<commit_after>#ifndef ITER_SLIDING_WINDOW_HPP_ #define ITER_SLIDING_WINDOW_HPP_ #include "internal/iterator_wrapper.hpp" #include "internal/iteratoriterator.hpp" #include "internal/iterbase.hpp" #include <deque> #include <iterator> #include <utility> namespace iter { namespace impl { template <typename Container> class WindowSlider; using SlidingWindowFn = IterToolFnBindSizeTSecond<WindowSlider>; } constexpr impl::SlidingWindowFn sliding_window{}; } template <typename Container> class iter::impl::WindowSlider { private: Container container_; std::size_t window_size_; friend SlidingWindowFn; WindowSlider(Container&& container, std::size_t win_sz) : container_(std::forward<Container>(container)), window_size_{win_sz} {} using IndexVector = std::deque<IteratorWrapper<Container>>; using DerefVec = IterIterWrapper<IndexVector>; public: WindowSlider(WindowSlider&&) = default; class Iterator : public std::iterator<std::input_iterator_tag, DerefVec> { private: IteratorWrapper<Container> sub_iter_; DerefVec window_; public: Iterator(IteratorWrapper<Container>&& sub_iter, IteratorWrapper<Container>&& sub_end, std::size_t window_sz) : sub_iter_(std::move(sub_iter)) { std::size_t i{0}; while (i < window_sz && sub_iter_ != sub_end) { window_.get().push_back(sub_iter_); ++i; if (i != window_sz) { ++sub_iter_; } } } bool operator!=(const Iterator& other) const { return sub_iter_ != other.sub_iter_; } bool operator==(const Iterator& other) const { return !(*this != other); } DerefVec& operator*() { return window_; } DerefVec* operator->() { return window_; } Iterator& operator++() { ++sub_iter_; window_.get().pop_front(); window_.get().push_back(sub_iter_); return *this; } Iterator operator++(int) { auto ret = *this; ++*this; return ret; } }; Iterator begin() { return { (window_size_ != 0 ? IteratorWrapper<Container>{std::begin(container_)} : IteratorWrapper<Container>{std::end(container_)}), std::end(container_), window_size_}; } Iterator end() { return {std::end(container_), std::end(container_), window_size_}; } }; #endif <|endoftext|>
<commit_before>/** * Process control - running other tasks and manipulating their input/output */ #include <v8.h> #include <string> #include "js_macros.h" #include <stdlib.h> namespace { JS_METHOD(_system) { if (args.Length() != 1) { return JS_EXCEPTION("Wrong argument count. Use include(\"process\").system(\"command\")"); } v8::String::Utf8Value cmd(args[0]); int result = system(*cmd); return JS_INT(result); } /** * The initial .exec method for stream buffering system commands */ JS_METHOD(_exec) { if (args.Length() != 1) { return JS_EXCEPTION("Wrong argument count. Use include(\"process\").exec(\"command\")"); } std::string data; FILE *stream; int MAX_BUFFER = 256; char buffer[MAX_BUFFER]; v8::String::Utf8Value cmd(args[0]); stream = popen(*cmd, "r"); while ( fgets(buffer, MAX_BUFFER, stream) != NULL ) { data.append(buffer); } pclose(stream); if(data.c_str() != NULL) { return JS_STR(data.c_str()); } else { return JS_NULL; } } } SHARED_INIT() { v8::HandleScope handle_scope; /* this module provides a set of (static) functions */ exports->Set(JS_STR("system"), v8::FunctionTemplate::New(_system)->GetFunction()); exports->Set(JS_STR("exec"), v8::FunctionTemplate::New(_exec)->GetFunction()); } <commit_msg>Added Function and Object templates Usage: include("process"); var proc = new Process(); proc.exec("ls -la");<commit_after>/** * Process control - running other tasks and manipulating their input/output */ #include <v8.h> #include <string> #include "js_macros.h" #include "js_common.h" #include <stdlib.h> #ifndef _JS_NULL #define JS_NULL v8::Null() #endif namespace { JS_METHOD(_process) { ASSERT_CONSTRUCTOR; SAVE_PTR(0, NULL); return args.This(); } JS_METHOD(_system) { if (args.Length() != 1) { return JS_EXCEPTION("Wrong argument count. Use include(\"process\").system(\"command\")"); } v8::String::Utf8Value cmd(args[0]); int result = system(*cmd); return JS_INT(result); } /** * The initial .exec method for stream buffering system commands */ JS_METHOD(_exec) { if (args.Length() != 1) { return JS_EXCEPTION("Wrong argument count. Use include(\"process\").exec(\"command\")"); } std::string data; FILE *stream; int MAX_BUFFER = 256; char buffer[MAX_BUFFER]; v8::String::Utf8Value cmd(args[0]); stream = popen(*cmd, "r"); while ( fgets(buffer, MAX_BUFFER, stream) != NULL ) { data.append(buffer); } pclose(stream); if(data.c_str() != NULL) { return JS_STR(data.c_str()); } else { return JS_NULL; } } } SHARED_INIT() { v8::HandleScope handle_scope; v8::Handle<v8::FunctionTemplate> funct = v8::FunctionTemplate::New(_process); funct->SetClassName(JS_STR("Process")); v8::Handle<v8::ObjectTemplate> ot = funct->InstanceTemplate(); ot->SetInternalFieldCount(1); /* connection */ v8::Handle<v8::ObjectTemplate> process = funct->PrototypeTemplate(); /* this module provides a set of (static) functions */ process->Set(JS_STR("system"), v8::FunctionTemplate::New(_system)->GetFunction()); process->Set(JS_STR("exec"), v8::FunctionTemplate::New(_exec)->GetFunction()); exports->Set(JS_STR("Process"), funct->GetFunction()); } <|endoftext|>
<commit_before>/** * Process control - running other tasks and manipulating their input/output */ #include <v8.h> #include <string> #include "js_macros.h" #include <stdlib.h> namespace { JS_METHOD(_system) { if (args.Length() != 1) { return JS_EXCEPTION("Wrong argument count. Use include(\"process\").system(\"command\")"); } v8::String::Utf8Value cmd(args[0]); int result = system(*cmd); return JS_INT(result); } /** * The initial .exec method for stream buffering system commands */ JS_METHOD(_exec) { if (args.Length() != 1) { return JS_EXCEPTION("Wrong argument count. Use include(\"process\").exec(\"command\")"); } std::string data; FILE *stream; int MAX_BUFFER = 256; char buffer[MAX_BUFFER]; v8::String::Utf8Value cmd(args[0]); stream = popen(*cmd, "r"); while ( fgets(buffer, MAX_BUFFER, stream) != NULL ) { data.append(buffer); } pclose(stream); if(data.c_str() != NULL) { return JS_STR(data.c_str()); } else { return JS_NULL; } } } SHARED_INIT() { v8::HandleScope handle_scope; /* this module provides a set of (static) functions */ exports->Set(JS_STR("system"), v8::FunctionTemplate::New(_system)->GetFunction()); exports->Set(JS_STR("exec"), v8::FunctionTemplate::New(_exec)->GetFunction()); } <commit_msg>Added Function and Object templates Usage: include("process"); var proc = new Process(); proc.exec("ls -la");<commit_after>/** * Process control - running other tasks and manipulating their input/output */ #include <v8.h> #include <string> #include "js_macros.h" #include "js_common.h" #include <stdlib.h> #ifndef _JS_NULL #define JS_NULL v8::Null() #endif namespace { JS_METHOD(_process) { ASSERT_CONSTRUCTOR; SAVE_PTR(0, NULL); return args.This(); } JS_METHOD(_system) { if (args.Length() != 1) { return JS_EXCEPTION("Wrong argument count. Use include(\"process\").system(\"command\")"); } v8::String::Utf8Value cmd(args[0]); int result = system(*cmd); return JS_INT(result); } /** * The initial .exec method for stream buffering system commands */ JS_METHOD(_exec) { if (args.Length() != 1) { return JS_EXCEPTION("Wrong argument count. Use include(\"process\").exec(\"command\")"); } std::string data; FILE *stream; int MAX_BUFFER = 256; char buffer[MAX_BUFFER]; v8::String::Utf8Value cmd(args[0]); stream = popen(*cmd, "r"); while ( fgets(buffer, MAX_BUFFER, stream) != NULL ) { data.append(buffer); } pclose(stream); if(data.c_str() != NULL) { return JS_STR(data.c_str()); } else { return JS_NULL; } } } SHARED_INIT() { v8::HandleScope handle_scope; v8::Handle<v8::FunctionTemplate> funct = v8::FunctionTemplate::New(_process); funct->SetClassName(JS_STR("Process")); v8::Handle<v8::ObjectTemplate> ot = funct->InstanceTemplate(); ot->SetInternalFieldCount(1); /* connection */ v8::Handle<v8::ObjectTemplate> process = funct->PrototypeTemplate(); /* this module provides a set of (static) functions */ process->Set(JS_STR("system"), v8::FunctionTemplate::New(_system)->GetFunction()); process->Set(JS_STR("exec"), v8::FunctionTemplate::New(_exec)->GetFunction()); exports->Set(JS_STR("Process"), funct->GetFunction()); } <|endoftext|>
<commit_before>#include "../src/meshoptimizer.h" #define CGLTF_IMPLEMENTATION #include "cgltf.h" const char* getError(cgltf_result result) { switch (result) { case cgltf_result_file_not_found: return "file not found"; case cgltf_result_io_error: return "I/O error"; case cgltf_result_invalid_json: return "invalid JSON"; case cgltf_result_invalid_gltf: return "invalid GLTF"; case cgltf_result_out_of_memory: return "out of memory"; default: return "unknown error"; } } int main(int argc, char** argv) { if (argc < 3) { fprintf(stderr, "Usage: gltfpack [options] input output\n"); return 1; } const char* input = argv[argc - 2]; const char* output = argv[argc - 1]; cgltf_options options = {}; cgltf_data* data = 0; cgltf_result result = cgltf_parse_file(&options, input, &data); result = (result == cgltf_result_success) ? cgltf_validate(data) : result; result = (result == cgltf_result_success) ? cgltf_load_buffers(&options, data, input) : result; if (result != cgltf_result_success) { cgltf_free(data); fprintf(stderr, "Error loading %s: %s\n", input, getError(result)); return 2; } FILE* out = fopen(output, "wb"); if (!out) { cgltf_free(data); fprintf(stderr, "Error saving %s\n", output); return 3; } fclose(out); cgltf_free(data); return 0; } <commit_msg>gltfpack: Implement saving to .gltf/.glb<commit_after>#include "../src/meshoptimizer.h" #include <string> #include <vector> #define CGLTF_IMPLEMENTATION #include "cgltf.h" struct Attr { float f[4]; }; struct Stream { cgltf_attribute_type type; std::vector<Attr> data; }; struct Mesh { std::vector<Stream> streams; std::vector<unsigned int> indices; }; struct Scene { cgltf_data* data; std::vector<Mesh> meshes; ~Scene() { cgltf_free(data); } }; const char* getError(cgltf_result result) { switch (result) { case cgltf_result_file_not_found: return "file not found"; case cgltf_result_io_error: return "I/O error"; case cgltf_result_invalid_json: return "invalid JSON"; case cgltf_result_invalid_gltf: return "invalid GLTF"; case cgltf_result_out_of_memory: return "out of memory"; default: return "unknown error"; } } bool process(Scene& scene, std::string& json, std::string& bin) { (void)scene; (void)json; (void)bin; return true; } void writeU32(FILE* out, uint32_t data) { fwrite(&data, 4, 1, out); } int main(int argc, char** argv) { if (argc < 3) { fprintf(stderr, "Usage: gltfpack [options] input output\n"); return 1; } const char* input = argv[argc - 2]; const char* output = argv[argc - 1]; Scene scene = {}; cgltf_options options = {}; cgltf_result result = cgltf_parse_file(&options, input, &scene.data); result = (result == cgltf_result_success) ? cgltf_validate(scene.data) : result; result = (result == cgltf_result_success) ? cgltf_load_buffers(&options, scene.data, input) : result; if (result != cgltf_result_success) { fprintf(stderr, "Error loading %s: %s\n", input, getError(result)); return 2; } std::string json, bin; if (!process(scene, json, bin)) { fprintf(stderr, "Error processing %s\n", input); return 3; } const char* ext = strrchr(output, '.'); if (ext && (strcmp(ext, ".gltf") == 0 || strcmp(ext, ".GLTF") == 0)) { std::string binpath = output; binpath.replace(binpath.size() - 5, 5, ".bin"); std::string binname = binpath; std::string::size_type slash = binname.find_last_of("/\\"); if (slash != std::string::npos) binname.erase(0, slash); FILE* outjson = fopen(output, "wb"); FILE* outbin = fopen(binpath.c_str(), "wb"); if (!outjson || !outbin) { fprintf(stderr, "Error saving %s\n", output); return 4; } fprintf(outjson, "{buffers:[{uri:\"%s\",byteLength:%zu}],", binname.c_str(), bin.size()); fwrite(json.c_str(), json.size(), 1, outjson); fprintf(outjson, "}"); fwrite(bin.c_str(), bin.size(), 1, outbin); fclose(outjson); fclose(outbin); } else if (ext && (strcmp(ext, ".glb") == 0 || strcmp(ext, ".GLB") == 0)) { FILE* out = fopen(output, "wb"); if (!out) { fprintf(stderr, "Error saving %s\n", output); return 4; } char bufferspec[32]; sprintf(bufferspec, "{buffers:[{byteLength:%zu}],", bin.size()); json.insert(0, bufferspec); json.push_back('}'); while (json.size() % 4) json.push_back(' '); while (bin.size() % 4) bin.push_back('\0'); writeU32(out, 0x46546C67); writeU32(out, 2); writeU32(out, 12 + 8 + json.size() + 8 + bin.size()); writeU32(out, 0x4E4F534A); writeU32(out, json.size()); fwrite(json.c_str(), json.size(), 1, out); writeU32(out, 0x004E4942); writeU32(out, bin.size()); fwrite(bin.c_str(), bin.size(), 1, out); fclose(out); } else { fprintf(stderr, "Error saving %s: unknown extension (expected .gltf or .glb)\n", output); return 4; } return 0; } <|endoftext|>
<commit_before>// Copyright 2011 Alessio Sclocco <a.sclocco@vu.nl> // // 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 <vector> #include <cmath> #include <Observation.hpp> #ifndef SHIFTS_HPP #define SHIFTS_HPP namespace PulsarSearch { std::vector< float > * getShifts(AstroData::Observation & observation); // Implementation std::vector< float > * getShifts(AstroData::Observation & observation) { float inverseHighFreq = 1.0f / std::pow(observation.getMaxFreq(), 2.0f); std::vector< float > * shifts = new std::vector< float >(observation.getNrPaddedChannels()); for ( unsigned int channel = 0; channel < observation.getNrChannels(); channel++ ) { float channelFreq = observation.getMinFreq() + (channel * observation.getChannelBandwidth()); float inverseFreq = 1.0f / std::pow(channelFreq, 2.0f); shifts->at(channel) = 4148.808f * (inverseFreq - inverseHighFreq); } return shifts; } } // PulsarSearch #endif // SHIFTS_HPP <commit_msg>Fix to take into account the sampling rate.<commit_after>// Copyright 2011 Alessio Sclocco <a.sclocco@vu.nl> // // 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 <vector> #include <cmath> #include <Observation.hpp> #ifndef SHIFTS_HPP #define SHIFTS_HPP namespace PulsarSearch { std::vector< float > * getShifts(AstroData::Observation & observation); // Implementation std::vector< float > * getShifts(AstroData::Observation & observation) { float inverseHighFreq = 1.0f / std::pow(observation.getMaxFreq(), 2.0f); std::vector< float > * shifts = new std::vector< float >(observation.getNrPaddedChannels()); for ( unsigned int channel = 0; channel < observation.getNrChannels(); channel++ ) { float channelFreq = observation.getMinFreq() + (channel * observation.getChannelBandwidth()); float inverseFreq = 1.0f / std::pow(channelFreq, 2.0f); shifts->at(channel) = 4148.808f * (inverseFreq - inverseHighFreq) * observation.getNrSamplesPerSecond(); } return shifts; } } // PulsarSearch #endif // SHIFTS_HPP <|endoftext|>
<commit_before>// // Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Framebuffer.cpp: Implements the gl::Framebuffer class. Implements GL framebuffer // objects and related functionality. [OpenGL ES 2.0.24] section 4.4 page 105. #include "libGLESv2/Framebuffer.h" #include "libGLESv2/main.h" #include "libGLESv2/Renderbuffer.h" #include "libGLESv2/Texture.h" #include "libGLESv2/utilities.h" namespace gl { Framebuffer::Framebuffer() { mColorbufferType = GL_NONE; mDepthbufferType = GL_NONE; mStencilbufferType = GL_NONE; } Framebuffer::~Framebuffer() { mColorbufferPointer.set(NULL); mDepthbufferPointer.set(NULL); mStencilbufferPointer.set(NULL); } Renderbuffer *Framebuffer::lookupRenderbuffer(GLenum type, GLuint handle) const { gl::Context *context = gl::getContext(); Renderbuffer *buffer = NULL; if (type == GL_NONE) { buffer = NULL; } else if (type == GL_RENDERBUFFER) { buffer = context->getRenderbuffer(handle); } else if (IsTextureTarget(type)) { buffer = context->getTexture(handle)->getColorbuffer(type); } else { UNREACHABLE(); } return buffer; } void Framebuffer::setColorbuffer(GLenum type, GLuint colorbuffer) { mColorbufferType = type; mColorbufferPointer.set(lookupRenderbuffer(type, colorbuffer)); } void Framebuffer::setDepthbuffer(GLenum type, GLuint depthbuffer) { mDepthbufferType = type; mDepthbufferPointer.set(lookupRenderbuffer(type, depthbuffer)); } void Framebuffer::setStencilbuffer(GLenum type, GLuint stencilbuffer) { mStencilbufferType = type; mStencilbufferPointer.set(lookupRenderbuffer(type, stencilbuffer)); } void Framebuffer::detachTexture(GLuint texture) { if (mColorbufferPointer.id() == texture && IsTextureTarget(mColorbufferType)) { mColorbufferType = GL_NONE; mColorbufferPointer.set(NULL); } if (mDepthbufferPointer.id() == texture && IsTextureTarget(mDepthbufferType)) { mDepthbufferType = GL_NONE; mDepthbufferPointer.set(NULL); } if (mStencilbufferPointer.id() == texture && IsTextureTarget(mStencilbufferType)) { mStencilbufferType = GL_NONE; mStencilbufferPointer.set(NULL); } } void Framebuffer::detachRenderbuffer(GLuint renderbuffer) { if (mColorbufferPointer.id() == renderbuffer && mColorbufferType == GL_RENDERBUFFER) { mColorbufferType = GL_NONE; mColorbufferPointer.set(NULL); } if (mDepthbufferPointer.id() == renderbuffer && mDepthbufferType == GL_RENDERBUFFER) { mDepthbufferType = GL_NONE; mDepthbufferPointer.set(NULL); } if (mStencilbufferPointer.id() == renderbuffer && mStencilbufferType == GL_RENDERBUFFER) { mStencilbufferType = GL_NONE; mStencilbufferPointer.set(NULL); } } unsigned int Framebuffer::getRenderTargetSerial() { Renderbuffer *colorbuffer = mColorbufferPointer.get(); if (colorbuffer) { return colorbuffer->getSerial(); } return 0; } IDirect3DSurface9 *Framebuffer::getRenderTarget() { Renderbuffer *colorbuffer = mColorbufferPointer.get(); if (colorbuffer) { return colorbuffer->getRenderTarget(); } return NULL; } IDirect3DSurface9 *Framebuffer::getDepthStencil() { Renderbuffer *depthstencilbuffer = mDepthbufferPointer.get(); if (!depthstencilbuffer) { depthstencilbuffer = mStencilbufferPointer.get(); } if (depthstencilbuffer) { return depthstencilbuffer->getDepthStencil(); } return NULL; } unsigned int Framebuffer::getDepthbufferSerial() { Renderbuffer *depthbuffer = mDepthbufferPointer.get(); if (depthbuffer) { return depthbuffer->getSerial(); } return 0; } unsigned int Framebuffer::getStencilbufferSerial() { Renderbuffer *stencilbuffer = mStencilbufferPointer.get(); if (stencilbuffer) { return stencilbuffer->getSerial(); } return 0; } Colorbuffer *Framebuffer::getColorbuffer() { Renderbuffer *rb = mColorbufferPointer.get(); if (rb != NULL && rb->isColorbuffer()) { return static_cast<Colorbuffer*>(rb->getStorage()); } else { return NULL; } } DepthStencilbuffer *Framebuffer::getDepthbuffer() { Renderbuffer *rb = mDepthbufferPointer.get(); if (rb != NULL && rb->isDepthbuffer()) { return static_cast<DepthStencilbuffer*>(rb->getStorage()); } else { return NULL; } } DepthStencilbuffer *Framebuffer::getStencilbuffer() { Renderbuffer *rb = mStencilbufferPointer.get(); if (rb != NULL && rb->isStencilbuffer()) { return static_cast<DepthStencilbuffer*>(rb->getStorage()); } else { return NULL; } } GLenum Framebuffer::getColorbufferType() { return mColorbufferType; } GLenum Framebuffer::getDepthbufferType() { return mDepthbufferType; } GLenum Framebuffer::getStencilbufferType() { return mStencilbufferType; } GLuint Framebuffer::getColorbufferHandle() { return mColorbufferPointer.id(); } GLuint Framebuffer::getDepthbufferHandle() { return mDepthbufferPointer.id(); } GLuint Framebuffer::getStencilbufferHandle() { return mStencilbufferPointer.id(); } bool Framebuffer::hasStencil() { if (mStencilbufferType != GL_NONE) { DepthStencilbuffer *stencilbufferObject = getStencilbuffer(); if (stencilbufferObject) { return stencilbufferObject->getStencilSize() > 0; } } return false; } bool Framebuffer::isMultisample() { // If the framebuffer is not complete, attachment samples may be mismatched, and it // cannot be used as a multisample framebuffer. If it is complete, it is required to // have a color attachment, and all its attachments must have the same number of samples, // so the number of samples for the colorbuffer will indicate whether the framebuffer is // multisampled. if (completeness() == GL_FRAMEBUFFER_COMPLETE && getColorbuffer()->getSamples() > 0) { return true; } else { return false; } } GLenum Framebuffer::completeness() { int width = 0; int height = 0; int samples = -1; if (mColorbufferType != GL_NONE) { Colorbuffer *colorbuffer = getColorbuffer(); if (!colorbuffer) { return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT; } if (colorbuffer->getWidth() == 0 || colorbuffer->getHeight() == 0) { return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT; } if (IsTextureTarget(mColorbufferType)) { if (IsCompressed(colorbuffer->getFormat())) { return GL_FRAMEBUFFER_UNSUPPORTED; } if (colorbuffer->isFloatingPoint() && (!getContext()->supportsFloatRenderableTextures() || !getContext()->supportsHalfFloatRenderableTextures())) { return GL_FRAMEBUFFER_UNSUPPORTED; } } width = colorbuffer->getWidth(); height = colorbuffer->getHeight(); samples = colorbuffer->getSamples(); } else { return GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT; } DepthStencilbuffer *depthbuffer = NULL; DepthStencilbuffer *stencilbuffer = NULL; if (mDepthbufferType != GL_NONE) { depthbuffer = getDepthbuffer(); if (!depthbuffer) { return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT; } if (depthbuffer->getWidth() == 0 || depthbuffer->getHeight() == 0) { return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT; } if (width == 0) { width = depthbuffer->getWidth(); height = depthbuffer->getHeight(); } else if (width != depthbuffer->getWidth() || height != depthbuffer->getHeight()) { return GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS; } if (samples == -1) { samples = depthbuffer->getSamples(); } else if (samples != depthbuffer->getSamples()) { return GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_ANGLE; } if (IsTextureTarget(mDepthbufferType)) { if (IsCompressed(depthbuffer->getFormat())) { return GL_FRAMEBUFFER_UNSUPPORTED; } } } if (mStencilbufferType != GL_NONE) { stencilbuffer = getStencilbuffer(); if (!stencilbuffer) { return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT; } if (stencilbuffer->getWidth() == 0 || stencilbuffer->getHeight() == 0) { return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT; } if (width == 0) { width = stencilbuffer->getWidth(); height = stencilbuffer->getHeight(); } else if (width != stencilbuffer->getWidth() || height != stencilbuffer->getHeight()) { return GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS; } if (samples == -1) { samples = stencilbuffer->getSamples(); } else if (samples != stencilbuffer->getSamples()) { return GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_ANGLE; } if (IsTextureTarget(mStencilbufferType)) { if (IsCompressed(stencilbuffer->getFormat())) { return GL_FRAMEBUFFER_UNSUPPORTED; } } } if (mDepthbufferType == GL_RENDERBUFFER && mStencilbufferType == GL_RENDERBUFFER) { if (depthbuffer->getFormat() != GL_DEPTH24_STENCIL8_OES || stencilbuffer->getFormat() != GL_DEPTH24_STENCIL8_OES || depthbuffer->getSerial() != stencilbuffer->getSerial()) { return GL_FRAMEBUFFER_UNSUPPORTED; } } return GL_FRAMEBUFFER_COMPLETE; } DefaultFramebuffer::DefaultFramebuffer(Colorbuffer *color, DepthStencilbuffer *depthStencil) { mColorbufferType = GL_RENDERBUFFER; mDepthbufferType = GL_RENDERBUFFER; mStencilbufferType = GL_RENDERBUFFER; mColorbufferPointer.set(new Renderbuffer(0, color)); Renderbuffer *depthStencilRenderbuffer = new Renderbuffer(0, depthStencil); mDepthbufferPointer.set(depthStencilRenderbuffer); mStencilbufferPointer.set(depthStencilRenderbuffer); } int Framebuffer::getSamples() { if (completeness() == GL_FRAMEBUFFER_COMPLETE) { return getColorbuffer()->getSamples(); } else { return 0; } } GLenum DefaultFramebuffer::completeness() { return GL_FRAMEBUFFER_COMPLETE; } } <commit_msg>Disallow rendering to L/LA textures. TRAC #13792 Signed-off-by: Daniel Koch<commit_after>// // Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Framebuffer.cpp: Implements the gl::Framebuffer class. Implements GL framebuffer // objects and related functionality. [OpenGL ES 2.0.24] section 4.4 page 105. #include "libGLESv2/Framebuffer.h" #include "libGLESv2/main.h" #include "libGLESv2/Renderbuffer.h" #include "libGLESv2/Texture.h" #include "libGLESv2/utilities.h" namespace gl { Framebuffer::Framebuffer() { mColorbufferType = GL_NONE; mDepthbufferType = GL_NONE; mStencilbufferType = GL_NONE; } Framebuffer::~Framebuffer() { mColorbufferPointer.set(NULL); mDepthbufferPointer.set(NULL); mStencilbufferPointer.set(NULL); } Renderbuffer *Framebuffer::lookupRenderbuffer(GLenum type, GLuint handle) const { gl::Context *context = gl::getContext(); Renderbuffer *buffer = NULL; if (type == GL_NONE) { buffer = NULL; } else if (type == GL_RENDERBUFFER) { buffer = context->getRenderbuffer(handle); } else if (IsTextureTarget(type)) { buffer = context->getTexture(handle)->getColorbuffer(type); } else { UNREACHABLE(); } return buffer; } void Framebuffer::setColorbuffer(GLenum type, GLuint colorbuffer) { mColorbufferType = type; mColorbufferPointer.set(lookupRenderbuffer(type, colorbuffer)); } void Framebuffer::setDepthbuffer(GLenum type, GLuint depthbuffer) { mDepthbufferType = type; mDepthbufferPointer.set(lookupRenderbuffer(type, depthbuffer)); } void Framebuffer::setStencilbuffer(GLenum type, GLuint stencilbuffer) { mStencilbufferType = type; mStencilbufferPointer.set(lookupRenderbuffer(type, stencilbuffer)); } void Framebuffer::detachTexture(GLuint texture) { if (mColorbufferPointer.id() == texture && IsTextureTarget(mColorbufferType)) { mColorbufferType = GL_NONE; mColorbufferPointer.set(NULL); } if (mDepthbufferPointer.id() == texture && IsTextureTarget(mDepthbufferType)) { mDepthbufferType = GL_NONE; mDepthbufferPointer.set(NULL); } if (mStencilbufferPointer.id() == texture && IsTextureTarget(mStencilbufferType)) { mStencilbufferType = GL_NONE; mStencilbufferPointer.set(NULL); } } void Framebuffer::detachRenderbuffer(GLuint renderbuffer) { if (mColorbufferPointer.id() == renderbuffer && mColorbufferType == GL_RENDERBUFFER) { mColorbufferType = GL_NONE; mColorbufferPointer.set(NULL); } if (mDepthbufferPointer.id() == renderbuffer && mDepthbufferType == GL_RENDERBUFFER) { mDepthbufferType = GL_NONE; mDepthbufferPointer.set(NULL); } if (mStencilbufferPointer.id() == renderbuffer && mStencilbufferType == GL_RENDERBUFFER) { mStencilbufferType = GL_NONE; mStencilbufferPointer.set(NULL); } } unsigned int Framebuffer::getRenderTargetSerial() { Renderbuffer *colorbuffer = mColorbufferPointer.get(); if (colorbuffer) { return colorbuffer->getSerial(); } return 0; } IDirect3DSurface9 *Framebuffer::getRenderTarget() { Renderbuffer *colorbuffer = mColorbufferPointer.get(); if (colorbuffer) { return colorbuffer->getRenderTarget(); } return NULL; } IDirect3DSurface9 *Framebuffer::getDepthStencil() { Renderbuffer *depthstencilbuffer = mDepthbufferPointer.get(); if (!depthstencilbuffer) { depthstencilbuffer = mStencilbufferPointer.get(); } if (depthstencilbuffer) { return depthstencilbuffer->getDepthStencil(); } return NULL; } unsigned int Framebuffer::getDepthbufferSerial() { Renderbuffer *depthbuffer = mDepthbufferPointer.get(); if (depthbuffer) { return depthbuffer->getSerial(); } return 0; } unsigned int Framebuffer::getStencilbufferSerial() { Renderbuffer *stencilbuffer = mStencilbufferPointer.get(); if (stencilbuffer) { return stencilbuffer->getSerial(); } return 0; } Colorbuffer *Framebuffer::getColorbuffer() { Renderbuffer *rb = mColorbufferPointer.get(); if (rb != NULL && rb->isColorbuffer()) { return static_cast<Colorbuffer*>(rb->getStorage()); } else { return NULL; } } DepthStencilbuffer *Framebuffer::getDepthbuffer() { Renderbuffer *rb = mDepthbufferPointer.get(); if (rb != NULL && rb->isDepthbuffer()) { return static_cast<DepthStencilbuffer*>(rb->getStorage()); } else { return NULL; } } DepthStencilbuffer *Framebuffer::getStencilbuffer() { Renderbuffer *rb = mStencilbufferPointer.get(); if (rb != NULL && rb->isStencilbuffer()) { return static_cast<DepthStencilbuffer*>(rb->getStorage()); } else { return NULL; } } GLenum Framebuffer::getColorbufferType() { return mColorbufferType; } GLenum Framebuffer::getDepthbufferType() { return mDepthbufferType; } GLenum Framebuffer::getStencilbufferType() { return mStencilbufferType; } GLuint Framebuffer::getColorbufferHandle() { return mColorbufferPointer.id(); } GLuint Framebuffer::getDepthbufferHandle() { return mDepthbufferPointer.id(); } GLuint Framebuffer::getStencilbufferHandle() { return mStencilbufferPointer.id(); } bool Framebuffer::hasStencil() { if (mStencilbufferType != GL_NONE) { DepthStencilbuffer *stencilbufferObject = getStencilbuffer(); if (stencilbufferObject) { return stencilbufferObject->getStencilSize() > 0; } } return false; } bool Framebuffer::isMultisample() { // If the framebuffer is not complete, attachment samples may be mismatched, and it // cannot be used as a multisample framebuffer. If it is complete, it is required to // have a color attachment, and all its attachments must have the same number of samples, // so the number of samples for the colorbuffer will indicate whether the framebuffer is // multisampled. if (completeness() == GL_FRAMEBUFFER_COMPLETE && getColorbuffer()->getSamples() > 0) { return true; } else { return false; } } GLenum Framebuffer::completeness() { int width = 0; int height = 0; int samples = -1; if (mColorbufferType != GL_NONE) { Colorbuffer *colorbuffer = getColorbuffer(); if (!colorbuffer) { return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT; } if (colorbuffer->getWidth() == 0 || colorbuffer->getHeight() == 0) { return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT; } if (IsTextureTarget(mColorbufferType)) { if (IsCompressed(colorbuffer->getFormat())) { return GL_FRAMEBUFFER_UNSUPPORTED; } if (colorbuffer->isFloatingPoint() && (!getContext()->supportsFloatRenderableTextures() || !getContext()->supportsHalfFloatRenderableTextures())) { return GL_FRAMEBUFFER_UNSUPPORTED; } if (colorbuffer->getFormat() == GL_LUMINANCE || colorbuffer->getFormat() == GL_LUMINANCE_ALPHA) { return GL_FRAMEBUFFER_UNSUPPORTED; } } width = colorbuffer->getWidth(); height = colorbuffer->getHeight(); samples = colorbuffer->getSamples(); } else { return GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT; } DepthStencilbuffer *depthbuffer = NULL; DepthStencilbuffer *stencilbuffer = NULL; if (mDepthbufferType != GL_NONE) { depthbuffer = getDepthbuffer(); if (!depthbuffer) { return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT; } if (depthbuffer->getWidth() == 0 || depthbuffer->getHeight() == 0) { return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT; } if (width == 0) { width = depthbuffer->getWidth(); height = depthbuffer->getHeight(); } else if (width != depthbuffer->getWidth() || height != depthbuffer->getHeight()) { return GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS; } if (samples == -1) { samples = depthbuffer->getSamples(); } else if (samples != depthbuffer->getSamples()) { return GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_ANGLE; } if (IsTextureTarget(mDepthbufferType)) { if (IsCompressed(depthbuffer->getFormat())) { return GL_FRAMEBUFFER_UNSUPPORTED; } } } if (mStencilbufferType != GL_NONE) { stencilbuffer = getStencilbuffer(); if (!stencilbuffer) { return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT; } if (stencilbuffer->getWidth() == 0 || stencilbuffer->getHeight() == 0) { return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT; } if (width == 0) { width = stencilbuffer->getWidth(); height = stencilbuffer->getHeight(); } else if (width != stencilbuffer->getWidth() || height != stencilbuffer->getHeight()) { return GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS; } if (samples == -1) { samples = stencilbuffer->getSamples(); } else if (samples != stencilbuffer->getSamples()) { return GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_ANGLE; } if (IsTextureTarget(mStencilbufferType)) { if (IsCompressed(stencilbuffer->getFormat())) { return GL_FRAMEBUFFER_UNSUPPORTED; } } } if (mDepthbufferType == GL_RENDERBUFFER && mStencilbufferType == GL_RENDERBUFFER) { if (depthbuffer->getFormat() != GL_DEPTH24_STENCIL8_OES || stencilbuffer->getFormat() != GL_DEPTH24_STENCIL8_OES || depthbuffer->getSerial() != stencilbuffer->getSerial()) { return GL_FRAMEBUFFER_UNSUPPORTED; } } return GL_FRAMEBUFFER_COMPLETE; } DefaultFramebuffer::DefaultFramebuffer(Colorbuffer *color, DepthStencilbuffer *depthStencil) { mColorbufferType = GL_RENDERBUFFER; mDepthbufferType = GL_RENDERBUFFER; mStencilbufferType = GL_RENDERBUFFER; mColorbufferPointer.set(new Renderbuffer(0, color)); Renderbuffer *depthStencilRenderbuffer = new Renderbuffer(0, depthStencil); mDepthbufferPointer.set(depthStencilRenderbuffer); mStencilbufferPointer.set(depthStencilRenderbuffer); } int Framebuffer::getSamples() { if (completeness() == GL_FRAMEBUFFER_COMPLETE) { return getColorbuffer()->getSamples(); } else { return 0; } } GLenum DefaultFramebuffer::completeness() { return GL_FRAMEBUFFER_COMPLETE; } } <|endoftext|>
<commit_before>/** * @file broker.hpp * @brief Component Broker * @author Byunghun Hwang<bhhwang@nsynapse.com> * @date 2015. 6. 21 * @details */ #ifndef _COSSB_BROKER_HPP_ #define _COSSB_BROKER_HPP_ #include <map> #include <string> #include "interface/icomponent.hpp" #include "arch/singleton.hpp" #include "manager.hpp" #include "logger.hpp" using namespace std; namespace cossb { namespace broker { //(topic, component name) pair typedef multimap<string, string> topic_map; class component_broker : public arch::singleton<component_broker> { public: component_broker() { }; virtual ~component_broker() { }; /** *@brief regist component with topic */ bool regist(interface::icomponent* component, string topic_name) { _topic_map.insert(topic_map::value_type(topic_name, component->get_name())); return true; } /** * @brief publish data pack to specific service component */ template<typename... Args> bool publish(interface::icomponent* component, const char* to_topic, const char* api, const Args&... args) { auto range = _topic_map.equal_range(to_topic); for(topic_map::iterator itr = range.first; itr!=range.second; ++itr) { if(itr->second.compare(component->get_name())==0) { driver::component_driver* _drv = cossb_component_manager->get_driver(itr->second.c_str()); if(_drv) _drv->request(api, args...); } } return true; } private: topic_map _topic_map; }; #define cossb_broker cossb::broker::component_broker::instance() } /* namespace broker */ } /* namespace cossb */ #endif <commit_msg>add exception in publish function<commit_after>/** * @file broker.hpp * @brief Component Broker * @author Byunghun Hwang<bhhwang@nsynapse.com> * @date 2015. 6. 21 * @details */ #ifndef _COSSB_BROKER_HPP_ #define _COSSB_BROKER_HPP_ #include <map> #include <string> #include "interface/icomponent.hpp" #include "arch/singleton.hpp" #include "manager.hpp" #include "logger.hpp" #include "exception.hpp" using namespace std; namespace cossb { namespace broker { //(topic, component name) pair typedef multimap<string, string> topic_map; class component_broker : public arch::singleton<component_broker> { public: component_broker() { }; virtual ~component_broker() { }; /** *@brief regist component with topic */ bool regist(interface::icomponent* component, string topic_name) { _topic_map.insert(topic_map::value_type(topic_name, component->get_name())); return true; } /** * @brief publish data pack to specific service component */ template<typename... Args> bool publish(interface::icomponent* component, const char* to_topic, const char* api, const Args&... args) { auto range = _topic_map.equal_range(to_topic); for(topic_map::iterator itr = range.first; itr!=range.second; ++itr) { if(itr->second.compare(component->get_name())==0) { driver::component_driver* _drv = cossb_component_manager->get_driver(itr->second.c_str()); if(_drv) { _drv->request(api, args...); } else throw broker::exception(cossb::broker::excode::DRIVER_NOT_FOUND); } } return true; } private: topic_map _topic_map; }; #define cossb_broker cossb::broker::component_broker::instance() } /* namespace broker */ } /* namespace cossb */ #endif <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <vector> #include <boost/foreach.hpp> using namespace std; class HDB3Parser { public: vector<string> Encode(vector<string> data) { this->_resultData = data; EncodeToHDB3(); return this->_resultData; } vector<string> Decode(vector<string> data) { this->_resultData = data; DecodeFromHDB3(); return this->_resultData; } private: vector<string> _resultData; void EncodeToHDB3() { /*for each (auto item in this->_resultData) { cout << item << endl; }*/ string test = "101000000000010"; cout << test << endl; test = ConvertToAMI(test); cout << test << endl; } string ConvertToAMI(string binaryStr) { bool prevPulseWasPositive = false; for (int i = 0; i < binaryStr.length(); i++) { if (binaryStr[i] == '1' && !prevPulseWasPositive) { binaryStr[i] = '+'; prevPulseWasPositive = true; } else if (binaryStr[i] == '1' && prevPulseWasPositive) { binaryStr[i] = '-'; prevPulseWasPositive = false; } else continue; } return binaryStr; } void DecodeFromHDB3() { cout << "Does nothing yet" << endl; } };<commit_msg>added algorithm for HDB3<commit_after>#include <iostream> #include <string> #include <vector> #include <boost/foreach.hpp> using namespace std; class HDB3Parser { public: vector<string> Encode(vector<string> data) { this->_resultData = data; EncodeToHDB3(); return this->_resultData; } vector<string> Decode(vector<string> data) { this->_resultData = data; DecodeFromHDB3(); return this->_resultData; } private: vector<string> _resultData; void EncodeToHDB3() { /*for each (auto item in this->_resultData) { cout << item << endl; }*/ string test = "101000000000010"; cout << test << endl; test = ConvertToAMI(test); cout << test << endl; /* ALGORITHM -as the iterator goes through the characters of the string ---count the number of + and - in the string (pulse counter) ---determine if that number is odd or even ---reset both after 4 zeroes are found ---count the number of zeroes ---when the number of zeroes reaches 4 ---perform substitutions ---reset the number after substitution ---make sure to add the + or - from this substitution to pulse counter ---run through string again to make sure that there are no duplicate pulses ++ or -- */ } string ConvertToAMI(string binaryStr) { bool prevPulseWasPositive = false; for (int i = 0; i < binaryStr.length(); i++) { if (binaryStr[i] == '1' && !prevPulseWasPositive) { binaryStr[i] = '+'; prevPulseWasPositive = true; } else if (binaryStr[i] == '1' && prevPulseWasPositive) { binaryStr[i] = '-'; prevPulseWasPositive = false; } else continue; } return binaryStr; } void DecodeFromHDB3() { cout << "Does nothing yet" << endl; } };<|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/process.h" #include "base/logging.h" #include "base/process_util.h" #include "base/scoped_ptr.h" namespace base { void Process::Close() { if (!process_) return; ::CloseHandle(process_); process_ = NULL; } void Process::Terminate(int result_code) { if (!process_) return; ::TerminateProcess(process_, result_code); } bool Process::IsProcessBackgrounded() const { DCHECK(process_); DWORD priority = GetPriorityClass(process_); if (priority == 0) return false; // Failure case. return priority == BELOW_NORMAL_PRIORITY_CLASS; } bool Process::SetProcessBackgrounded(bool value) { DCHECK(process_); DWORD priority = value ? BELOW_NORMAL_PRIORITY_CLASS : NORMAL_PRIORITY_CLASS; return (SetPriorityClass(process_, priority) != 0); } // According to MSDN, these are the default values which XP // uses to govern working set soft limits. // http://msdn.microsoft.com/en-us/library/ms686234.aspx static const int kWinDefaultMinSet = 50 * 4096; static const int kWinDefaultMaxSet = 345 * 4096; static const int kDampingFactor = 2; bool Process::ReduceWorkingSet() { if (!process_) return false; // The idea here is that when we the process' working set has gone // down, we want to release those pages to the OS quickly. However, // when it is not going down, we want to be careful not to release // too much back to the OS, as it could cause additional paging. // We use a damping function to lessen the working set over time. // As the process grows/shrinks, this algorithm will lag with // working set reduction. // // The intended algorithm is: // TargetWorkingSetSize = (LastWorkingSet/2 + CurrentWorkingSet) /2 scoped_ptr<ProcessMetrics> metrics( ProcessMetrics::CreateProcessMetrics(process_)); WorkingSetKBytes working_set; if (!metrics->GetWorkingSetKBytes(&working_set)) return false; // We want to compute the amount of working set that the process // needs to keep in memory. Since other processes contain the // pages which are shared, we don't need to reserve them in our // process, the system already has them tagged. Keep in mind, we // don't get to control *which* pages get released, but if we // assume reasonable distribution of pages, this should generally // be the right value. size_t current_working_set_size = working_set.priv + working_set.shareable; size_t max_size = current_working_set_size; if (last_working_set_size_) max_size = (max_size + last_working_set_size_) / 2; // Average. max_size *= 1024; // Convert to KBytes. last_working_set_size_ = current_working_set_size / kDampingFactor; BOOL rv = SetProcessWorkingSetSize(process_, kWinDefaultMinSet, max_size); return rv == TRUE; } bool Process::UnReduceWorkingSet() { if (!process_) return false; if (!last_working_set_size_) return true; // There was nothing to undo. // We've had a reduced working set. Make sure we have lots of // headroom now that we're active again. size_t limit = last_working_set_size_ * kDampingFactor * 2 * 1024; BOOL rv = SetProcessWorkingSetSize(process_, kWinDefaultMinSet, limit); return rv == TRUE; } bool Process::EmptyWorkingSet() { if (!process_) return false; BOOL rv = SetProcessWorkingSetSize(process_, -1, -1); return rv == TRUE; } ProcessId Process::pid() const { if (process_ == 0) return 0; return GetProcId(process_); } bool Process::is_current() const { return process_ == GetCurrentProcess(); } // static Process Process::Current() { return Process(GetCurrentProcess()); } } // namespace base <commit_msg>Don't call SetPriorityClass when process_ is 0.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/process.h" #include "base/logging.h" #include "base/process_util.h" #include "base/scoped_ptr.h" namespace base { void Process::Close() { if (!process_) return; ::CloseHandle(process_); process_ = NULL; } void Process::Terminate(int result_code) { if (!process_) return; ::TerminateProcess(process_, result_code); } bool Process::IsProcessBackgrounded() const { if (!process_) return false; // Failure case. DWORD priority = GetPriorityClass(process_); if (priority == 0) return false; // Failure case. return priority == BELOW_NORMAL_PRIORITY_CLASS; } bool Process::SetProcessBackgrounded(bool value) { if (!process_) return false; DWORD priority = value ? BELOW_NORMAL_PRIORITY_CLASS : NORMAL_PRIORITY_CLASS; return (SetPriorityClass(process_, priority) != 0); } // According to MSDN, these are the default values which XP // uses to govern working set soft limits. // http://msdn.microsoft.com/en-us/library/ms686234.aspx static const int kWinDefaultMinSet = 50 * 4096; static const int kWinDefaultMaxSet = 345 * 4096; static const int kDampingFactor = 2; bool Process::ReduceWorkingSet() { if (!process_) return false; // The idea here is that when we the process' working set has gone // down, we want to release those pages to the OS quickly. However, // when it is not going down, we want to be careful not to release // too much back to the OS, as it could cause additional paging. // We use a damping function to lessen the working set over time. // As the process grows/shrinks, this algorithm will lag with // working set reduction. // // The intended algorithm is: // TargetWorkingSetSize = (LastWorkingSet/2 + CurrentWorkingSet) /2 scoped_ptr<ProcessMetrics> metrics( ProcessMetrics::CreateProcessMetrics(process_)); WorkingSetKBytes working_set; if (!metrics->GetWorkingSetKBytes(&working_set)) return false; // We want to compute the amount of working set that the process // needs to keep in memory. Since other processes contain the // pages which are shared, we don't need to reserve them in our // process, the system already has them tagged. Keep in mind, we // don't get to control *which* pages get released, but if we // assume reasonable distribution of pages, this should generally // be the right value. size_t current_working_set_size = working_set.priv + working_set.shareable; size_t max_size = current_working_set_size; if (last_working_set_size_) max_size = (max_size + last_working_set_size_) / 2; // Average. max_size *= 1024; // Convert to KBytes. last_working_set_size_ = current_working_set_size / kDampingFactor; BOOL rv = SetProcessWorkingSetSize(process_, kWinDefaultMinSet, max_size); return rv == TRUE; } bool Process::UnReduceWorkingSet() { if (!process_) return false; if (!last_working_set_size_) return true; // There was nothing to undo. // We've had a reduced working set. Make sure we have lots of // headroom now that we're active again. size_t limit = last_working_set_size_ * kDampingFactor * 2 * 1024; BOOL rv = SetProcessWorkingSetSize(process_, kWinDefaultMinSet, limit); return rv == TRUE; } bool Process::EmptyWorkingSet() { if (!process_) return false; BOOL rv = SetProcessWorkingSetSize(process_, -1, -1); return rv == TRUE; } ProcessId Process::pid() const { if (process_ == 0) return 0; return GetProcId(process_); } bool Process::is_current() const { return process_ == GetCurrentProcess(); } // static Process Process::Current() { return Process(GetCurrentProcess()); } } // namespace base <|endoftext|>
<commit_before>// Copyright 2014 BVLC and contributors. // // This is a simple script that allows one to quickly test a network whose // structure is specified by text format protocol buffers, and whose parameter // are loaded from a pre-trained network. // Usage: // test_net net_proto pretrained_net_proto iterations [CPU/GPU] #include <cuda_runtime.h> #include <cstring> #include <cstdlib> #include <vector> #include "caffe/caffe.hpp" using namespace caffe; // NOLINT(build/namespaces) int main(int argc, char** argv) { if (argc < 4 || argc > 6) { LOG(ERROR) << "test_net net_proto pretrained_net_proto iterations " << "[CPU/GPU] [Device ID]"; return 1; } Caffe::set_phase(Caffe::TEST); if (argc >= 5 && strcmp(argv[4], "GPU") == 0) { LOG(ERROR) << "Using GPU"; Caffe::set_mode(Caffe::GPU); if (argc == 6) { int device_id = atoi(argv[5]); Caffe::SetDevice(device_id); } } else { LOG(ERROR) << "Using CPU"; Caffe::set_mode(Caffe::CPU); } Net<float> caffe_test_net(argv[1]); NetParameter trained_net_param; ReadProtoFromBinaryFile(argv[2], &trained_net_param); caffe_test_net.CopyTrainedLayersFrom(trained_net_param); int total_iter = atoi(argv[3]); LOG(ERROR) << "Running " << total_iter << "Iterations."; double test_accuracy = 0; vector<Blob<float>*> dummy_blob_input_vec; for (int i = 0; i < total_iter; ++i) { const vector<Blob<float>*>& result = caffe_test_net.Forward(dummy_blob_input_vec); test_accuracy += result[0]->cpu_data()[0]; LOG(ERROR) << "Batch " << i << ", accuracy: " << result[0]->cpu_data()[0]; } test_accuracy /= total_iter; LOG(ERROR) << "Test accuracy:" << test_accuracy; return 0; } <commit_msg>proofreading and trivial polish<commit_after>// Copyright 2014 BVLC and contributors. // // This is a simple script that allows one to quickly test a network whose // structure is specified by text format protocol buffers, and whose parameter // are loaded from a pre-trained network. // Usage: // test_net net_proto pretrained_net_proto iterations [CPU/GPU] #include <cuda_runtime.h> #include <cstring> #include <cstdlib> #include <vector> #include "caffe/caffe.hpp" using namespace caffe; // NOLINT(build/namespaces) int main(int argc, char** argv) { if (argc < 4 || argc > 6) { LOG(ERROR) << "test_net net_proto pretrained_net_proto iterations " << "[CPU/GPU] [Device ID]"; return 1; } Caffe::set_phase(Caffe::TEST); if (argc >= 5 && strcmp(argv[4], "GPU") == 0) { LOG(ERROR) << "Using GPU"; Caffe::set_mode(Caffe::GPU); if (argc == 6) { int device_id = atoi(argv[5]); Caffe::SetDevice(device_id); } } else { LOG(ERROR) << "Using CPU"; Caffe::set_mode(Caffe::CPU); } Net<float> caffe_test_net(argv[1]); NetParameter trained_net_param; ReadProtoFromBinaryFile(argv[2], &trained_net_param); caffe_test_net.CopyTrainedLayersFrom(trained_net_param); int total_iter = atoi(argv[3]); LOG(ERROR) << "Running " << total_iter << " iterations."; double test_accuracy = 0; for (int i = 0; i < total_iter; ++i) { const vector<Blob<float>*>& result = caffe_test_net.ForwardPrefilled(); test_accuracy += result[0]->cpu_data()[0]; LOG(ERROR) << "Batch " << i << ", accuracy: " << result[0]->cpu_data()[0]; } test_accuracy /= total_iter; LOG(ERROR) << "Test accuracy: " << test_accuracy; return 0; } <|endoftext|>
<commit_before>/* * LicenseReader.cpp * * Created on: Mar 30, 2014 * */ #ifdef _WIN32 # pragma warning(disable: 4786) #else # include <unistd.h> #endif #include <cstring> #include <ctime> #include <vector> #include <iostream> #include <iterator> #include <fstream> #include <sstream> #include <stdlib.h> #include "pc-identifiers.h" #include "LicenseReader.h" #include "base/StringUtils.h" #include "base/logger.h" #include "public-key.h" #include <build_properties.h> namespace license { const char *FullLicenseInfo::UNUSED_TIME = "0000-00-00"; FullLicenseInfo::FullLicenseInfo(const string& source, const string& product, const string& license_signature, int licenseVersion, string from_date, string to_date, const string& client_signature, unsigned int from_sw_version, unsigned int to_sw_version, const string& extra_data) : source(source), product(product), // license_signature(license_signature), license_version(licenseVersion), // from_date(from_date), to_date(to_date), // has_expiry(to_date != UNUSED_TIME), // from_sw_version(from_sw_version), to_sw_version(to_sw_version), // has_versions( from_sw_version != UNUSED_SOFTWARE_VERSION || to_sw_version != UNUSED_SOFTWARE_VERSION), // client_signature(client_signature), has_client_sig( client_signature.length() > 0), // extra_data(extra_data) { } EventRegistry FullLicenseInfo::validate(int sw_version) { EventRegistry er; os_initialize(); FUNCTION_RETURN sigVer = verifySignature(printForSign().c_str(), license_signature.c_str()); bool sigVerified = sigVer == FUNC_RET_OK; if (sigVerified) { er.addEvent(LICENSE_VERIFIED, SVRT_INFO); } else { er.addEvent(LICENSE_CORRUPTED, SVRT_ERROR); } if (has_expiry) { time_t now = time(NULL); if (expires_on() < now) { er.addEvent(PRODUCT_EXPIRED, SVRT_ERROR, ""); } if (valid_from() > now) { er.addEvent(PRODUCT_EXPIRED, SVRT_ERROR); } } if (has_client_sig) { PcSignature str_code; strncpy(str_code, client_signature.c_str(), sizeof(str_code)-1); EVENT_TYPE event = validate_pc_signature(str_code); if (event != LICENSE_OK) { er.addEvent(event, SVRT_ERROR); } } return er; } void FullLicenseInfo::toLicenseInfo(LicenseInfo* license) const { if (license != NULL) { strncpy(license->proprietary_data, extra_data.c_str(), PROPRIETARY_DATA_SIZE); license->linked_to_pc = has_client_sig; license->has_expiry = has_expiry; if (!has_expiry) { license->expiry_date[0] = '\0'; license->days_left = 999999; } else { strncpy(license->expiry_date, to_date.c_str(), 11); double secs = difftime( seconds_from_epoch(to_date.c_str()), time(NULL)); license->days_left = (int) secs / 60 * 60 * 24; } } } LicenseReader::LicenseReader(const LicenseLocation& licenseLocation) : licenseLocation(licenseLocation) { } EventRegistry LicenseReader::readLicenses(const string &product, vector<FullLicenseInfo>& licenseInfoOut) { vector<string> diskFiles; EventRegistry result = getLicenseDiskFiles(diskFiles); if (!result.isGood()) { return result; } bool loadAtLeastOneFile = false; bool atLeastOneProductLicensed = false; bool atLeastOneLicenseComplete = false; CSimpleIniA ini; for (auto it = diskFiles.begin(); it != diskFiles.end(); it++) { ini.Reset(); SI_Error rc = ini.LoadFile((*it).c_str()); if (rc < 0) { result.addEvent(FILE_FORMAT_NOT_RECOGNIZED, SVRT_WARN, *it); continue; } else { loadAtLeastOneFile = true; } const char* productNamePtr = product.c_str(); int sectionSize = ini.GetSectionSize(productNamePtr); if (sectionSize <= 0) { result.addEvent(PRODUCT_NOT_LICENSED, SVRT_WARN, *it); continue; } else { atLeastOneProductLicensed = true; } /* * sw_version_from = (optional int) * sw_version_to = (optional int) * from_date = YYYY-MM-DD (optional) * to_date = YYYY-MM-DD (optional) * client_signature = XXXX-XXXX-XXXX-XXXX (optional string 16) * license_signature = XXXXXXXXXX (mandatory, 1024) * application_data = xxxxxxxxx (optional string 16) */ const char * license_signature = ini.GetValue(productNamePtr, "license_signature", NULL); long license_version = ini.GetLongValue(productNamePtr, "license_version", -1); if (license_signature != NULL && license_version > 0) { string from_date = trim_copy( ini.GetValue(productNamePtr, "from_date", FullLicenseInfo::UNUSED_TIME)); string to_date = trim_copy( ini.GetValue(productNamePtr, "to_date", FullLicenseInfo::UNUSED_TIME)); string client_signature = trim_copy( ini.GetValue(productNamePtr, "client_signature", "")); /*client_signature.erase( std::remove(client_signature.begin(), client_signature.end(), '-'), client_signature.end());*/ int from_sw_version = ini.GetLongValue(productNamePtr, "from_sw_version", FullLicenseInfo::UNUSED_SOFTWARE_VERSION); int to_sw_version = ini.GetLongValue(productNamePtr, "to_sw_version", FullLicenseInfo::UNUSED_SOFTWARE_VERSION); string extra_data = trim_copy( ini.GetValue(productNamePtr, "extra_data", "")); FullLicenseInfo licInfo(*it, product, license_signature, (int) license_version, from_date, to_date, client_signature, from_sw_version, to_sw_version, extra_data); licenseInfoOut.push_back(licInfo); atLeastOneLicenseComplete = true; } else { result.addEvent(LICENSE_MALFORMED, SVRT_WARN, *it); } } if (!loadAtLeastOneFile) { result.turnEventIntoError(FILE_FORMAT_NOT_RECOGNIZED); } if (!atLeastOneProductLicensed) { result.turnEventIntoError(PRODUCT_NOT_LICENSED); } if (!atLeastOneLicenseComplete) { result.turnEventIntoError(LICENSE_MALFORMED); } return result; } bool LicenseReader::findLicenseWithExplicitLocation(vector<string>& diskFiles, EventRegistry& eventRegistry) { //bool hasFileLocation = false; bool licenseFoundWithExplicitLocation = false; if (licenseLocation.licenseFileLocation != NULL && licenseLocation.licenseFileLocation[0] != '\0') { //hasFileLocation = true; string varName(licenseLocation.licenseFileLocation); vector<string> declared_positions = splitLicensePositions(varName); vector<string> existing_pos = filterExistingFiles(declared_positions); if (existing_pos.size() > 0) { if (existing_pos.size() > 0) { licenseFoundWithExplicitLocation = true; for (auto it = existing_pos.begin(); it != existing_pos.end(); ++it) { diskFiles.push_back(*it); eventRegistry.addEvent(LICENSE_FILE_FOUND, SVRT_INFO, *it); } } } else { eventRegistry.addEvent(LICENSE_FILE_NOT_FOUND, SVRT_WARN, varName); } } return licenseFoundWithExplicitLocation; } bool LicenseReader::findFileWithEnvironmentVariable(vector<string>& diskFiles, EventRegistry& eventRegistry) { bool licenseFileFoundWithEnvVariable = false; if (licenseLocation.environmentVariableName != NULL && licenseLocation.environmentVariableName[0] != '\0') { string varName(licenseLocation.environmentVariableName); if (varName.length() > 0) { //var name is passed in by the calling application. char* env_var_value = getenv(varName.c_str()); if (env_var_value != NULL && env_var_value[0] != '\0') { vector<string> declared_positions = splitLicensePositions( string(env_var_value)); vector<string> existing_pos = filterExistingFiles( declared_positions); if (existing_pos.size() > 0) { licenseFileFoundWithEnvVariable = true; for (auto it = existing_pos.begin(); it != existing_pos.end(); ++it) { diskFiles.push_back(*it); eventRegistry.addEvent(LICENSE_FILE_FOUND, SVRT_INFO, *it); } } else { eventRegistry.addEvent(LICENSE_FILE_NOT_FOUND, SVRT_WARN, env_var_value); } } else { eventRegistry.addEvent(ENVIRONMENT_VARIABLE_NOT_DEFINED, SVRT_WARN); } } else { eventRegistry.addEvent(ENVIRONMENT_VARIABLE_NOT_DEFINED, SVRT_WARN); } } return licenseFileFoundWithEnvVariable; } EventRegistry LicenseReader::getLicenseDiskFiles(vector<string>& diskFiles) { EventRegistry eventRegistry; bool licenseFoundWithExplicitLocation = findLicenseWithExplicitLocation( diskFiles, eventRegistry); bool foundNearModule = false; if (licenseLocation.openFileNearModule) { char fname[MAX_PATH] = { 0 }; FUNCTION_RETURN fret = getModuleName(fname); if (fret == FUNC_RET_OK) { string temptativeLicense = string(fname) + ".lic"; ifstream f(temptativeLicense.c_str()); if (f.good()) { foundNearModule = true; diskFiles.push_back(temptativeLicense); eventRegistry.addEvent(LICENSE_FILE_FOUND, SVRT_INFO, temptativeLicense); } else { eventRegistry.addEvent(LICENSE_FILE_NOT_FOUND, SVRT_WARN, temptativeLicense); } f.close(); } else { LOG_WARN("Error determining module name."); } } bool licenseFileFoundWithEnvVariable = findFileWithEnvironmentVariable( diskFiles, eventRegistry); if (!foundNearModule && !licenseFoundWithExplicitLocation && !licenseFileFoundWithEnvVariable) { eventRegistry.turnEventIntoError(ENVIRONMENT_VARIABLE_NOT_DEFINED); eventRegistry.turnEventIntoError(LICENSE_FILE_NOT_FOUND); } return eventRegistry; } vector<string> LicenseReader::filterExistingFiles( vector<string> licensePositions) { vector<string> existingFiles; for (auto it = licensePositions.begin(); it != licensePositions.end(); it++) { ifstream f(it->c_str()); if (f.good()) { existingFiles.push_back(*it); } f.close(); } return existingFiles; } vector<string> LicenseReader::splitLicensePositions(string licensePositions) { std::stringstream streamToSplit(licensePositions); std::string segment; std::vector<string> seglist; while (std::getline(streamToSplit, segment, ';')) { seglist.push_back(segment); } return seglist; } LicenseReader::~LicenseReader() { } string FullLicenseInfo::printForSign() const { ostringstream oss; oss << toupper_copy(trim_copy(this->product)); oss << SHARED_RANDOM ; if (has_client_sig) { oss << trim_copy(this->client_signature); } if (has_versions) { oss << "|" << this->from_sw_version << "-" << this->to_sw_version; } if (has_expiry) { oss << "|" << this->from_date << "|" << this->to_date; } if (this->extra_data.length() > 0) { oss << "|" << extra_data; } #ifdef _DEBUG cout << "[" << oss.str() << "]" << endl; #endif return oss.str(); } void FullLicenseInfo::printAsIni(ostream & a_ostream) const { CSimpleIniA ini; string result; string product = toupper_copy(trim_copy(this->product)); CSimpleIniA::StreamWriter sw(a_ostream); ini.SetLongValue(product.c_str(), "license_version", PROJECT_INT_VERSION); ini.SetValue(product.c_str(), "license_signature", this->license_signature.c_str()); if (has_client_sig) { ini.SetValue(product.c_str(), "client_signature", this->client_signature.c_str()); } if (has_versions) { ini.SetLongValue(product.c_str(), "from_sw_version", from_sw_version); ini.SetLongValue(product.c_str(), "to_sw_version", to_sw_version); } if (this->from_date != UNUSED_TIME) { ini.SetValue(product.c_str(), "from_date", from_date.c_str()); } if (this->to_date != UNUSED_TIME) { ini.SetValue(product.c_str(), "to_date", to_date.c_str()); } if (this->extra_data.length() > 0) { ini.SetValue(product.c_str(), "extra_data", this->extra_data.c_str()); } ini.Save(sw); } time_t FullLicenseInfo::expires_on() const { return seconds_from_epoch(this->to_date.c_str()); } time_t FullLicenseInfo::valid_from() const { return seconds_from_epoch(this->from_date.c_str()); } } <commit_msg>fix calculation of days left in license<commit_after>/* * LicenseReader.cpp * * Created on: Mar 30, 2014 * */ #ifdef _WIN32 # pragma warning(disable: 4786) #else # include <unistd.h> #endif #include <cstring> #include <ctime> #include <vector> #include <iostream> #include <iterator> #include <fstream> #include <sstream> #include <stdlib.h> #include <math.h> #include "pc-identifiers.h" #include "LicenseReader.h" #include "base/StringUtils.h" #include "base/logger.h" #include "public-key.h" #include <build_properties.h> namespace license { const char *FullLicenseInfo::UNUSED_TIME = "0000-00-00"; FullLicenseInfo::FullLicenseInfo(const string& source, const string& product, const string& license_signature, int licenseVersion, string from_date, string to_date, const string& client_signature, unsigned int from_sw_version, unsigned int to_sw_version, const string& extra_data) : source(source), product(product), // license_signature(license_signature), license_version(licenseVersion), // from_date(from_date), to_date(to_date), // has_expiry(to_date != UNUSED_TIME), // from_sw_version(from_sw_version), to_sw_version(to_sw_version), // has_versions( from_sw_version != UNUSED_SOFTWARE_VERSION || to_sw_version != UNUSED_SOFTWARE_VERSION), // client_signature(client_signature), has_client_sig( client_signature.length() > 0), // extra_data(extra_data) { } EventRegistry FullLicenseInfo::validate(int sw_version) { EventRegistry er; os_initialize(); FUNCTION_RETURN sigVer = verifySignature(printForSign().c_str(), license_signature.c_str()); bool sigVerified = sigVer == FUNC_RET_OK; if (sigVerified) { er.addEvent(LICENSE_VERIFIED, SVRT_INFO); } else { er.addEvent(LICENSE_CORRUPTED, SVRT_ERROR); } if (has_expiry) { time_t now = time(NULL); if (expires_on() < now) { er.addEvent(PRODUCT_EXPIRED, SVRT_ERROR, ""); } if (valid_from() > now) { er.addEvent(PRODUCT_EXPIRED, SVRT_ERROR); } } if (has_client_sig) { PcSignature str_code; strncpy(str_code, client_signature.c_str(), sizeof(str_code)-1); EVENT_TYPE event = validate_pc_signature(str_code); if (event != LICENSE_OK) { er.addEvent(event, SVRT_ERROR); } } return er; } void FullLicenseInfo::toLicenseInfo(LicenseInfo* license) const { if (license != NULL) { strncpy(license->proprietary_data, extra_data.c_str(), PROPRIETARY_DATA_SIZE); license->linked_to_pc = has_client_sig; license->has_expiry = has_expiry; if (!has_expiry) { license->expiry_date[0] = '\0'; license->days_left = 999999; } else { strncpy(license->expiry_date, to_date.c_str(), 11); double secs = difftime( seconds_from_epoch(to_date.c_str()), time(NULL)); license->days_left = round(secs / (60 * 60 * 24)); } } } LicenseReader::LicenseReader(const LicenseLocation& licenseLocation) : licenseLocation(licenseLocation) { } EventRegistry LicenseReader::readLicenses(const string &product, vector<FullLicenseInfo>& licenseInfoOut) { vector<string> diskFiles; EventRegistry result = getLicenseDiskFiles(diskFiles); if (!result.isGood()) { return result; } bool loadAtLeastOneFile = false; bool atLeastOneProductLicensed = false; bool atLeastOneLicenseComplete = false; CSimpleIniA ini; for (auto it = diskFiles.begin(); it != diskFiles.end(); it++) { ini.Reset(); SI_Error rc = ini.LoadFile((*it).c_str()); if (rc < 0) { result.addEvent(FILE_FORMAT_NOT_RECOGNIZED, SVRT_WARN, *it); continue; } else { loadAtLeastOneFile = true; } const char* productNamePtr = product.c_str(); int sectionSize = ini.GetSectionSize(productNamePtr); if (sectionSize <= 0) { result.addEvent(PRODUCT_NOT_LICENSED, SVRT_WARN, *it); continue; } else { atLeastOneProductLicensed = true; } /* * sw_version_from = (optional int) * sw_version_to = (optional int) * from_date = YYYY-MM-DD (optional) * to_date = YYYY-MM-DD (optional) * client_signature = XXXX-XXXX-XXXX-XXXX (optional string 16) * license_signature = XXXXXXXXXX (mandatory, 1024) * application_data = xxxxxxxxx (optional string 16) */ const char * license_signature = ini.GetValue(productNamePtr, "license_signature", NULL); long license_version = ini.GetLongValue(productNamePtr, "license_version", -1); if (license_signature != NULL && license_version > 0) { string from_date = trim_copy( ini.GetValue(productNamePtr, "from_date", FullLicenseInfo::UNUSED_TIME)); string to_date = trim_copy( ini.GetValue(productNamePtr, "to_date", FullLicenseInfo::UNUSED_TIME)); string client_signature = trim_copy( ini.GetValue(productNamePtr, "client_signature", "")); /*client_signature.erase( std::remove(client_signature.begin(), client_signature.end(), '-'), client_signature.end());*/ int from_sw_version = ini.GetLongValue(productNamePtr, "from_sw_version", FullLicenseInfo::UNUSED_SOFTWARE_VERSION); int to_sw_version = ini.GetLongValue(productNamePtr, "to_sw_version", FullLicenseInfo::UNUSED_SOFTWARE_VERSION); string extra_data = trim_copy( ini.GetValue(productNamePtr, "extra_data", "")); FullLicenseInfo licInfo(*it, product, license_signature, (int) license_version, from_date, to_date, client_signature, from_sw_version, to_sw_version, extra_data); licenseInfoOut.push_back(licInfo); atLeastOneLicenseComplete = true; } else { result.addEvent(LICENSE_MALFORMED, SVRT_WARN, *it); } } if (!loadAtLeastOneFile) { result.turnEventIntoError(FILE_FORMAT_NOT_RECOGNIZED); } if (!atLeastOneProductLicensed) { result.turnEventIntoError(PRODUCT_NOT_LICENSED); } if (!atLeastOneLicenseComplete) { result.turnEventIntoError(LICENSE_MALFORMED); } return result; } bool LicenseReader::findLicenseWithExplicitLocation(vector<string>& diskFiles, EventRegistry& eventRegistry) { //bool hasFileLocation = false; bool licenseFoundWithExplicitLocation = false; if (licenseLocation.licenseFileLocation != NULL && licenseLocation.licenseFileLocation[0] != '\0') { //hasFileLocation = true; string varName(licenseLocation.licenseFileLocation); vector<string> declared_positions = splitLicensePositions(varName); vector<string> existing_pos = filterExistingFiles(declared_positions); if (existing_pos.size() > 0) { if (existing_pos.size() > 0) { licenseFoundWithExplicitLocation = true; for (auto it = existing_pos.begin(); it != existing_pos.end(); ++it) { diskFiles.push_back(*it); eventRegistry.addEvent(LICENSE_FILE_FOUND, SVRT_INFO, *it); } } } else { eventRegistry.addEvent(LICENSE_FILE_NOT_FOUND, SVRT_WARN, varName); } } return licenseFoundWithExplicitLocation; } bool LicenseReader::findFileWithEnvironmentVariable(vector<string>& diskFiles, EventRegistry& eventRegistry) { bool licenseFileFoundWithEnvVariable = false; if (licenseLocation.environmentVariableName != NULL && licenseLocation.environmentVariableName[0] != '\0') { string varName(licenseLocation.environmentVariableName); if (varName.length() > 0) { //var name is passed in by the calling application. char* env_var_value = getenv(varName.c_str()); if (env_var_value != NULL && env_var_value[0] != '\0') { vector<string> declared_positions = splitLicensePositions( string(env_var_value)); vector<string> existing_pos = filterExistingFiles( declared_positions); if (existing_pos.size() > 0) { licenseFileFoundWithEnvVariable = true; for (auto it = existing_pos.begin(); it != existing_pos.end(); ++it) { diskFiles.push_back(*it); eventRegistry.addEvent(LICENSE_FILE_FOUND, SVRT_INFO, *it); } } else { eventRegistry.addEvent(LICENSE_FILE_NOT_FOUND, SVRT_WARN, env_var_value); } } else { eventRegistry.addEvent(ENVIRONMENT_VARIABLE_NOT_DEFINED, SVRT_WARN); } } else { eventRegistry.addEvent(ENVIRONMENT_VARIABLE_NOT_DEFINED, SVRT_WARN); } } return licenseFileFoundWithEnvVariable; } EventRegistry LicenseReader::getLicenseDiskFiles(vector<string>& diskFiles) { EventRegistry eventRegistry; bool licenseFoundWithExplicitLocation = findLicenseWithExplicitLocation( diskFiles, eventRegistry); bool foundNearModule = false; if (licenseLocation.openFileNearModule) { char fname[MAX_PATH] = { 0 }; FUNCTION_RETURN fret = getModuleName(fname); if (fret == FUNC_RET_OK) { string temptativeLicense = string(fname) + ".lic"; ifstream f(temptativeLicense.c_str()); if (f.good()) { foundNearModule = true; diskFiles.push_back(temptativeLicense); eventRegistry.addEvent(LICENSE_FILE_FOUND, SVRT_INFO, temptativeLicense); } else { eventRegistry.addEvent(LICENSE_FILE_NOT_FOUND, SVRT_WARN, temptativeLicense); } f.close(); } else { LOG_WARN("Error determining module name."); } } bool licenseFileFoundWithEnvVariable = findFileWithEnvironmentVariable( diskFiles, eventRegistry); if (!foundNearModule && !licenseFoundWithExplicitLocation && !licenseFileFoundWithEnvVariable) { eventRegistry.turnEventIntoError(ENVIRONMENT_VARIABLE_NOT_DEFINED); eventRegistry.turnEventIntoError(LICENSE_FILE_NOT_FOUND); } return eventRegistry; } vector<string> LicenseReader::filterExistingFiles( vector<string> licensePositions) { vector<string> existingFiles; for (auto it = licensePositions.begin(); it != licensePositions.end(); it++) { ifstream f(it->c_str()); if (f.good()) { existingFiles.push_back(*it); } f.close(); } return existingFiles; } vector<string> LicenseReader::splitLicensePositions(string licensePositions) { std::stringstream streamToSplit(licensePositions); std::string segment; std::vector<string> seglist; while (std::getline(streamToSplit, segment, ';')) { seglist.push_back(segment); } return seglist; } LicenseReader::~LicenseReader() { } string FullLicenseInfo::printForSign() const { ostringstream oss; oss << toupper_copy(trim_copy(this->product)); oss << SHARED_RANDOM ; if (has_client_sig) { oss << trim_copy(this->client_signature); } if (has_versions) { oss << "|" << this->from_sw_version << "-" << this->to_sw_version; } if (has_expiry) { oss << "|" << this->from_date << "|" << this->to_date; } if (this->extra_data.length() > 0) { oss << "|" << extra_data; } #ifdef _DEBUG cout << "[" << oss.str() << "]" << endl; #endif return oss.str(); } void FullLicenseInfo::printAsIni(ostream & a_ostream) const { CSimpleIniA ini; string result; string product = toupper_copy(trim_copy(this->product)); CSimpleIniA::StreamWriter sw(a_ostream); ini.SetLongValue(product.c_str(), "license_version", PROJECT_INT_VERSION); ini.SetValue(product.c_str(), "license_signature", this->license_signature.c_str()); if (has_client_sig) { ini.SetValue(product.c_str(), "client_signature", this->client_signature.c_str()); } if (has_versions) { ini.SetLongValue(product.c_str(), "from_sw_version", from_sw_version); ini.SetLongValue(product.c_str(), "to_sw_version", to_sw_version); } if (this->from_date != UNUSED_TIME) { ini.SetValue(product.c_str(), "from_date", from_date.c_str()); } if (this->to_date != UNUSED_TIME) { ini.SetValue(product.c_str(), "to_date", to_date.c_str()); } if (this->extra_data.length() > 0) { ini.SetValue(product.c_str(), "extra_data", this->extra_data.c_str()); } ini.Save(sw); } time_t FullLicenseInfo::expires_on() const { return seconds_from_epoch(this->to_date.c_str()); } time_t FullLicenseInfo::valid_from() const { return seconds_from_epoch(this->from_date.c_str()); } } <|endoftext|>
<commit_before> #include <vector> #include <cassert> #include "types.hpp" #include "fftwmpi.hpp" #include "particle.hpp" int pic_fft(int argc, char* argv[]) { // Temp test params const int nt = 1; const int ppc = 1; // Global problem setup const FLOAT Lz = 2*M_PI; const FLOAT Ly = 2*M_PI; const FLOAT Lx = 2*M_PI; const ptrdiff_t N0 = 100; const ptrdiff_t N1 = 100; const ptrdiff_t N2 = 100; const FLOAT dz = Lz/N0; const FLOAT dy = Ly/N1; const FLOAT dx = Lx/N2; const FLOAT V = dz*dy*dx; const FLOAT Vi = dz*dy*dx; // Build solver and get local params FFTWPoisson3DMPI solver(N0, Lz, N1, Ly, N2, Lx); const int nz = solver.get_nz(); const int nx = solver.get_nx(); const int ny = solver.get_ny(); const int z0 = solver.get_z0(); // Local domain length const FLOAT Lzl = nz*dz; // Field arrays std::vector<FLOAT> phi(nx*ny*nz, 0); std::vector<FLOAT> Ex(nx*ny*nz, 0); std::vector<FLOAT> Ey(nx*ny*nz, 0); std::vector<FLOAT> Ez(nx*ny*nz, 0); // Get MPI params int rank, size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); const int right = (rank+1)%size; const int left = rank>0 ? rank-1 : size-1; assert((left>=0) && (right<size)); // Communication buffers std::vector<FLOAT> send_right(nx*ny, 0); std::vector<FLOAT> send_left(nx*ny, 0); std::vector<FLOAT> recv_right(nx*ny, 0); std::vector<FLOAT> recv_left(nx*ny, 0); std::vector<FLOAT> send_parts_right; std::vector<FLOAT> recv_parts_right; std::vector<FLOAT> send_parts_left; std::vector<FLOAT> recv_parts_left; // Construct particles ParticleList particles; // Main time stepping loop for(int it=0; it<nt; ++it) { // Weight particles to mesh // Solve for phi solver.solve(&phi[0]); // Solve for Exyz // Weight fields to particles // Accel and move // Communicate particles // Diagnostics } } int main(int argc, char* argv[]) { MPI_Init(&argc, &argv); fftw_mpi_init(); pic_fft(argc, argv); MPI_Finalize(); } <commit_msg>Init particle positions.<commit_after> #include <vector> #include <cassert> #include "types.hpp" #include "fftwmpi.hpp" #include "particle.hpp" int pic_fft(int argc, char* argv[]) { // Temp test params const int nt = 1; const int ppc = 1; // Global problem setup const FLOAT Lz = 2*M_PI; const FLOAT Ly = 2*M_PI; const FLOAT Lx = 2*M_PI; const ptrdiff_t N0 = 100; const ptrdiff_t N1 = 100; const ptrdiff_t N2 = 100; const FLOAT dz = Lz/N0; const FLOAT dy = Ly/N1; const FLOAT dx = Lx/N2; const FLOAT V = dz*dy*dx; const FLOAT Vi = dz*dy*dx; // Build solver and get local params FFTWPoisson3DMPI solver(N0, Lz, N1, Ly, N2, Lx); const int nz = solver.get_nz(); const int nx = solver.get_nx(); const int ny = solver.get_ny(); const int z0 = solver.get_z0(); // Local domain length const FLOAT Lxl = nx*dx; const FLOAT Lyl = ny*dy; const FLOAT Lzl = nz*dz; // Field arrays std::vector<FLOAT> phi(nx*ny*nz, 0); std::vector<FLOAT> Ex(nx*ny*nz, 0); std::vector<FLOAT> Ey(nx*ny*nz, 0); std::vector<FLOAT> Ez(nx*ny*nz, 0); // Get MPI params int rank, size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); const int right = (rank+1)%size; const int left = rank>0 ? rank-1 : size-1; assert((left>=0) && (right<size)); // Communication buffers std::vector<FLOAT> send_right(nx*ny, 0); std::vector<FLOAT> send_left(nx*ny, 0); std::vector<FLOAT> recv_right(nx*ny, 0); std::vector<FLOAT> recv_left(nx*ny, 0); std::vector<FLOAT> send_parts_right; std::vector<FLOAT> recv_parts_right; std::vector<FLOAT> send_parts_left; std::vector<FLOAT> recv_parts_left; // Construct init particles ParticleList particles(ppc*ppc*ppc*nx*ny*nz); { const FLOAT pdx = dx/(ppc+1); const FLOAT pdy = dy/(ppc+1); const FLOAT pdz = dz/(ppc+1); FLOAT x0, y0, z0; for(int iz=0; iz<nz; ++iz) for(int iy=0; iy<ny; ++iy) for(int ix=0; ix<nx; ++ix) { x0 = ix*dx; y0 = iy*dy; z0 = iz*dz; for(int pz=0; pz<ppc; ++pz) for(int py=0; py<ppc; ++py) for(int px=0; px<ppc; ++px) { particles.xp_.push_back(x0+px*pdx); particles.yp_.push_back(y0+py*pdy); particles.zp_.push_back(z0+pz*pdz); // TODO: Init particle velocities particles.vx_.push_back(1.0); particles.vy_.push_back(1.0); particles.vz_.push_back(1.0); particles.q_.push_back(1.0); } } } // Main time stepping loop for(int it=0; it<nt; ++it) { // Weight particles to mesh // Solve for phi solver.solve(&phi[0]); // Solve for Exyz // Weight fields to particles // Accel and move // Communicate particles // Diagnostics } } int main(int argc, char* argv[]) { MPI_Init(&argc, &argv); fftw_mpi_init(); pic_fft(argc, argv); MPI_Finalize(); } <|endoftext|>
<commit_before>// -*-coding:utf-8-unix;-*- // refactry from // https://github.com/scylladb/seastar/blob/master/core/thread.cc // #pragma once #ifdef __APPLE__ #define _XOPEN_SOURCE 700 #endif // __APPLE__ // #include <ucontext.h> #include <setjmp.h> #include "macros.hh" // namespace NAMESPACE { // // usage // struct _ContextTask // : public Context<_ContextTask, 1> { // void Run(); // }; // const size_t kDefaultStackSize(SIGSTKSZ); // template<typename Task, size_t kStackSize = kDefaultStackSize> class Context { public: static bool Init(Context& context); // static void SwitchIn(Context& to); // static void SwitchOut(Context& from); // protected: static void Routine(Context* context); // private: char _stack[kStackSize]; jmp_buf _jmpbuf; }; // template<typename Task, size_t kStackSize> bool Context<Task, kStackSize>::Init(Context& context) { typedef Context<Task, kStackSize> Self; ucontext_t initial_context; int done = getcontext(&initial_context); if (0 not_eq done) { return false; } // initial_context.uc_stack.ss_sp = context._stack; initial_context.uc_stack.ss_size = sizeof(context._stack); initial_context.uc_link = nullptr; // makecontext(&initial_context, reinterpret_cast<void (*)()>(Self::Routine), 1, &context); done = setjmp(context._jmpbuf); if (0 == done) { setcontext(&initial_context); } return true; } // template<typename Task, size_t kStackSize> void Context<Task, kStackSize>::SwitchIn(Context& to) { int done = setjmp(to._jmpbuf); if (0 == done) { longjmp(to._jmpbuf, 1); } } // template<typename Task, size_t kStackSize> void Context<Task, kStackSize>::SwitchOut(Context& from) { int done = setjmp(from._jmpbuf); if (0 == done) { longjmp(from._jmpbuf, 1); } } // template<typename Task, size_t kStackSize> void Context<Task, kStackSize>::Routine(Context* context) { static_cast<Task*>(context)->Run(); longjmp(context->_jmpbuf, 1); } // } // namespace NAMESPACE <commit_msg>remove Heap<commit_after>// -*-coding:utf-8-unix;-*- // refactry from // https://github.com/scylladb/seastar/blob/master/core/thread.cc // #pragma once #ifdef __APPLE__ #define _XOPEN_SOURCE 700 #endif // __APPLE__ // #include <ucontext.h> #include <setjmp.h> #include "macros.hh" // namespace NAMESPACE { // // usage // struct _ContextTask // : public Context<_ContextTask, 1> { // void Run(); // }; // const size_t kDefaultStackSize(SIGSTKSZ); // template<typename Task, size_t kStackSize = kDefaultStackSize> class Context { public: static bool Init(Context& context); // static void SwitchIn(Context& to); // static void SwitchOut(Context& from); // protected: static void Routine(Context* context); // private: char _stack[kStackSize]; jmp_buf _jmpbuf; }; // template<typename Task, size_t kStackSize> bool Context<Task, kStackSize>::Init(Context& context) { context._stack[sizeof(context._stack) - 1] = 0; typedef Context<Task, kStackSize> Self; ucontext_t initial_context; int done = getcontext(&initial_context); if (0 not_eq done) { return false; } // initial_context.uc_stack.ss_sp = context._stack; initial_context.uc_stack.ss_size = sizeof(context._stack); initial_context.uc_link = nullptr; // makecontext(&initial_context, reinterpret_cast<void (*)()>(Self::Routine), 1, &context); done = setjmp(context._jmpbuf); if (0 == done) { setcontext(&initial_context); } return true; } // template<typename Task, size_t kStackSize> void Context<Task, kStackSize>::SwitchIn(Context& to) { int done = setjmp(to._jmpbuf); if (0 == done) { longjmp(to._jmpbuf, 1); } } // template<typename Task, size_t kStackSize> void Context<Task, kStackSize>::SwitchOut(Context& from) { int done = setjmp(from._jmpbuf); if (0 == done) { longjmp(from._jmpbuf, 1); } } // template<typename Task, size_t kStackSize> void Context<Task, kStackSize>::Routine(Context* context) { static_cast<Task*>(context)->Run(); longjmp(context->_jmpbuf, 1); } // } // namespace NAMESPACE <|endoftext|>
<commit_before>#include "mtrace.h" #if MTRACE // Tell mtrace about switching threads struct kstack_tag { int val __mpalign__; }; extern struct kstack_tag kstack_tag[NCPU]; // Tell mtrace about switching threads/processes template<typename Ret, typename... Args> static inline void mtstart(Ret (*ip)(Args...), struct proc *p) { unsigned long new_tag; int i; pushcli(); new_tag = ++(kstack_tag[mycpu()->id].val) | (mycpu()->id<<MTRACE_TAGSHIFT); i = ++p->mtrace_stacks.curr; if (i >= MTRACE_NSTACKS) panic("mtrace_kstack_start: ran out of slots"); p->mtrace_stacks.tag[i] = new_tag; mtrace_fcall_register(p->pid, (unsigned long)ip, p->mtrace_stacks.tag[i], i, mtrace_start); popcli(); } static inline void mtstop(struct proc *p) { int i; pushcli(); i = p->mtrace_stacks.curr; if (i < 0) panic("mtrace_kstack_stop: fell off of stack"); mtrace_fcall_register(p->pid, 0, p->mtrace_stacks.tag[i], i, mtrace_done); p->mtrace_stacks.tag[i] = 0; p->mtrace_stacks.curr--; popcli(); } static inline void mtpause(struct proc *p) { int i; i = p->mtrace_stacks.curr; if (i < 0) panic("mtrace_kstack_pause: bad stack"); mtrace_fcall_register(p->pid, 0, p->mtrace_stacks.tag[i], i, mtrace_pause); } static inline void mtresume(struct proc *p) { int i; i = p->mtrace_stacks.curr; if (i < 0) panic("mtrace_kstack_resume: bad stack"); mtrace_fcall_register(p->pid, 0, p->mtrace_stacks.tag[i], i, mtrace_resume); } // Tell mtrace to start/stop recording call and ret #define mtrec() mtrace_call_set(1, ~0ull) #define mtign() mtrace_call_set(0, ~0ull) #else #define mtstart(ip, p) do { } while (0) #define mtstop(p) do { } while (0) #define mtpause(p) do { } while (0) #define mtresume(p) do { } while (0) #define mtrec(cpu) do { } while (0) #define mtign(cpu) do { } while (0) #define mtrec(cpu) do { } while (0) #define mtign(cpu) do { } while (0) #endif <commit_msg>asharing: Utilities to manage abstract sharing scopes and objects<commit_after>#pragma once #include "mtrace.h" #if MTRACE // Tell mtrace about switching threads struct kstack_tag { int val __mpalign__; }; extern struct kstack_tag kstack_tag[NCPU]; // Tell mtrace about switching threads/processes template<typename Ret, typename... Args> static inline void mtstart(Ret (*ip)(Args...), struct proc *p) { unsigned long new_tag; int i; pushcli(); new_tag = ++(kstack_tag[mycpu()->id].val) | (mycpu()->id<<MTRACE_TAGSHIFT); i = ++p->mtrace_stacks.curr; if (i >= MTRACE_NSTACKS) panic("mtrace_kstack_start: ran out of slots"); p->mtrace_stacks.tag[i] = new_tag; mtrace_fcall_register(p->pid, (unsigned long)ip, p->mtrace_stacks.tag[i], i, mtrace_start); popcli(); } static inline void mtstop(struct proc *p) { int i; pushcli(); i = p->mtrace_stacks.curr; if (i < 0) panic("mtrace_kstack_stop: fell off of stack"); mtrace_fcall_register(p->pid, 0, p->mtrace_stacks.tag[i], i, mtrace_done); p->mtrace_stacks.tag[i] = 0; p->mtrace_stacks.curr--; popcli(); } static inline void mtpause(struct proc *p) { int i; i = p->mtrace_stacks.curr; if (i < 0) panic("mtrace_kstack_pause: bad stack"); mtrace_fcall_register(p->pid, 0, p->mtrace_stacks.tag[i], i, mtrace_pause); } static inline void mtresume(struct proc *p) { int i; i = p->mtrace_stacks.curr; if (i < 0) panic("mtrace_kstack_resume: bad stack"); mtrace_fcall_register(p->pid, 0, p->mtrace_stacks.tag[i], i, mtrace_resume); } // Tell mtrace to start/stop recording call and ret #define mtrec() mtrace_call_set(1, ~0ull) #define mtign() mtrace_call_set(0, ~0ull) class mt_ascope { char name[32]; public: explicit mt_ascope(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vsnprintf(name, sizeof(name) - 1, fmt, ap); va_end(ap); mtrace_ascope_register(0, name); } ~mt_ascope() { mtrace_ascope_register(1, name); } }; static inline void mtreadavar(const char *fmt, ...) { char name[32]; va_list ap; va_start(ap, fmt); vsnprintf(name, sizeof(name), fmt, ap); va_end(ap); mtrace_avar_register(0, name); } static inline void mtwriteavar(const char *fmt, ...) { char name[32]; va_list ap; va_start(ap, fmt); vsnprintf(name, sizeof(name), fmt, ap); va_end(ap); mtrace_avar_register(1, name); } #else #define mtstart(ip, p) do { } while (0) #define mtstop(p) do { } while (0) #define mtpause(p) do { } while (0) #define mtresume(p) do { } while (0) #define mtrec(cpu) do { } while (0) #define mtign(cpu) do { } while (0) #define mtrec(cpu) do { } while (0) #define mtign(cpu) do { } while (0) class mt_ascope { public: explicit mt_ascope(const char *fmt, ...) {} }; #define mtreadavar(fmt, ...) do { } while (0) #define mtwriteavar(fmt, ...) do { } while (0) #endif <|endoftext|>
<commit_before>#include <iostream> #include <iomanip> #include <fstream> using namespace std; class Matrix { private: int **matr; int st, cl; public: Matrix(); Matrix(int, int); Matrix(Matrix &matrс); ~Matrix(); Matrix operator+ (const Matrix &mat_2) const; Matrix operator* (const Matrix &mat_2) const; Matrix& operator =(Matrix &); bool operator==(const Matrix&)const; friend istream& operator >> (istream& ist, const Matrix& cmatr); friend ostream& operator << (ostream&, const Matrix&); }; <commit_msg>Update matrix.hpp<commit_after>#include <iostream> #include <iomanip> #include <fstream> using namespace std; class Matrix { private: int **matr; int st, cl; public: Matrix(); Matrix(int, int); Matrix(Matrix &matrс); ~Matrix(); int str(); int col(); Matrix operator+ (const Matrix &mat_2) const; Matrix operator* (const Matrix &mat_2) const; Matrix& operator =(Matrix &); bool operator==(const Matrix&)const; friend istream& operator >> (istream& ist, const Matrix& cmatr); friend ostream& operator << (ostream&, const Matrix&); }; <|endoftext|>
<commit_before>#include <iostream> class matrix_t final { private: unsigned int rows_; unsigned int columns_; int** elements_; public: matrix_t() noexcept; auto rows() -> unsigned int; auto columns() -> unsigned int; }; <commit_msg>Update matrix.hpp<commit_after>using namespace std; class Matrix { private: int row, col, **mas; public: Matrix(int length = 4); Matrix(int, int); Matrix(const Matrix&); ~Matrix(); void fill(const char*); void show() const; Matrix operator+(const Matrix&) const; Matrix operator*(const Matrix&) const; }; <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////////// // Tryx Plugin System made by Avra Neel Chakraborty // // // // Copyright (c) 2017 Avra Neel Chakraborty // // // // 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. // /////////////////////////////////////////////////////////////////////////////////// #ifndef PLUGIN_HPP #define PLUGIN_HPP #include "config.hpp" #include "sharedlib.hpp" #include <string> namespace Tryx { // Representation of a plugin class Plugin { private: //Signature for the plugin's registration function typedef PluginInterface* (*PluginFactoryFunc)(); //Signature to query for plugin texts typedef char * (*Plugin_TextFunc)(); char* filename; char* pluginType; char* pluginName; char* pluginVersion; PluginFactoryFunc pluginHandle; TRYX_API_EXP void setName(char* name); TRYX_API_EXP void setType(char* type); TRYX_API_EXP void setVers(char* vers); TRYX_API_EXP void setFileName(char* name); TRYX_API_EXP Plugin_TextFunc* getTextData(SharedLib::Handle handle, const char* funcname, const std::string& filename); TRYX_API_EXP PluginInterface* getNewPlugin(SharedLib::Handle handle, const char* funcname, const std::string& filename); void clearMembers(); public: //Initializes and loads a plugin //Parameter is filename of the plugin to load TRYX_API_EXP Plugin(SharedLib::Handle handle,const std::string &filename); //Copies an existing plugin instance TRYX_API_EXP Plugin(const Plugin &other); //Unloads the plugin TRYX_API_EXP ~Plugin(); TRYX_API_EXP char* getName() { return pluginName; } TRYX_API_EXP char* getType() { return pluginType; } TRYX_API_EXP char* getVers() { return pluginVersion; } //Creates a copy of the plugin instance Plugin &operator =(const Plugin &other); }; // ----------------------------------------------------------------------- // } // namespace MyEngine #endif // MYENGINE_PLUGIN_H <commit_msg>Added documentation for the plugin class.Rewrote some functions too.<commit_after>/////////////////////////////////////////////////////////////////////////////////// // Tryx Plugin System made by Avra Neel Chakraborty // // // // Copyright (c) 2017 Avra Neel Chakraborty // // // // 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. // /////////////////////////////////////////////////////////////////////////////////// #ifndef PLUGIN_HPP #define PLUGIN_HPP #include "config.hpp" #include "sharedlib.hpp" #include <string> namespace Tryx { // Representation of a plugin class Plugin { private: //Signature for the plugin's registration function typedef PluginInterface* *(*PluginFactoryFunc)(); //Signature to query for plugin texts typedef char * (*Plugin_TextFunc)(); char* pluginName; char* pluginType; char* pluginVersion; char* filename; PluginFactoryFunc funcHandle; // Handy function to clear the data members of a plugin object. // Used in the dtor only. void clearMembers(); TRYX_API_EXP void setName(char* name); // Set name. TRYX_API_EXP void setType(char* type); // Set type. TRYX_API_EXP void setVers(char* vers); // Set version TRYX_API_EXP void setFileName(char* name); // Set filename public: // Parameterized ctor to load a plugin dll and initiate it inside // the class object.Used as the primary way of loading plugins // Parameters are:- // SharedLib::Handle handle - A handle which is passed from the // Kernal class.It helps in loading the function pointers. // std::string& filename - The filename to the dynamic library. TRYX_API_EXP Plugin(SharedLib::Handle& handle,std::string &filename); // Copy ctor for constructing a plugin from one that has already // been loaded.Required to provide correct semantics for storing // plugins in an STL map container. TRYX_API_EXP Plugin(const Plugin &other); // Unloads the plugin, unloading its library when no more // references to it exist. TRYX_API_EXP ~Plugin(); // Gets a text function handle from the dynamic library and // returns it. If found then returns it,else returns nullptr. TRYX_API_EXP Plugin_TextFunc* getTextData(SharedLib::Handle handle, const char* funcname, const std::string& filename); // Gets a PluginInterface object from the dynamic library. // If found,then returns it,else returns nullptr. TRYX_API_EXP PluginInterface* getNewPlugin(SharedLib::Handle handle, const char* funcname, const std::string& filename); TRYX_API_EXP char* getName() { return pluginName; } // Get name. TRYX_API_EXP char* getType() { return pluginType; } // Get type. TRYX_API_EXP char* getVers() { return pluginVersion; } // Get version. TRYX_API_EXP char* getFilename() { return filename; } // Get filename. //Creates a copy of the plugin instance. TRYX_API_EXP Plugin &operator =(const Plugin &other); }; } // namespace MyEngine #endif // MYENGINE_PLUGIN_H <|endoftext|>
<commit_before>#ifndef STRONG_STRONG_HPP #define STRONG_STRONG_HPP #include <type_traits> #include <utility> /** * Namespace for creating strong typedefs. */ namespace strong { /** * A strong typedef wrapper around some Type. * * Allows the programmer to define a strong type to avoid comparing values that have the same type * but are logically different. For example, IDs in a geographic map application for intersections * and streets may both be integers, but one should not logically compare an intersection ID with * a street ID. * * Strong typedefs that inherit from this class can be explicitly converted to their base Type, * but not implicitly converted. For more information please see: * http://en.cppreference.com/w/cpp/language/cast_operator * * @tparam Tag A unique identifier for this type * @tparam Type The actual type (e.g. int) to use */ template<class Tag, typename Type> class type { public: /** * The default constructor of type will attempt to initialize the underlying value with its own * default constructor. */ constexpr type() : value() { } /** * Initialize the underlying value via a copy or move. * * @param v The value to copy. */ explicit constexpr type(Type const &v) : value(v) { } /** * Move constructor. * * If Type's move constructor does not throw, then this move constructor will have noexcept * enabled, which will allow for certain optimizations. For more information, please refer * to https://akrzemi1.wordpress.com/2014/04/24/noexcept-what-for/ * * @param v The value to move. */ explicit constexpr type(Type && v) noexcept(std::is_nothrow_move_constructible<Type>::value) : value(static_cast<Type &&>(v)) { } /** * Enables explicit conversion of the type. * * @return The underlying value. */ explicit operator Type &() noexcept { return value; } /** * Enables const-correct explicit conversion of the type. * * @return The underlying value. */ explicit constexpr operator Type const &() const noexcept { return value; } private: Type value; }; namespace detail { /** * A dummy function used to help determine the type of the underlying value of a strong typedef. */ template <class Tag, typename Type> Type dummy_function(type<Tag, Type>); } /** * Determine the type of the underlying value of a strong typedef. */ template <class Typedef> using underlying_type = decltype(detail::dummy_function(std::declval<Typedef>())); /** * Operations to enable on strong typedefs. */ namespace op { /** * Tests for equality or inequality between identical strong types. * * @tparam Tag The strong typedef to compare. * @tparam Result The return type of the comparison */ template<class Tag, typename Result = bool> class equality { public: /** * Test for equality. * * @param lhs The left-hand side of the relational expression. * @param rhs The right-hand side of the relational expression. * @return The result of the comparison. */ friend constexpr Result operator==(Tag const &lhs, Tag const &rhs) { using type = underlying_type<Tag>; return static_cast<type const &>(lhs) == static_cast<type const &>(rhs); } /** * Test for inequality. * * @param lhs The left-hand side of the relational expression. * @param rhs The right-hand side of the relational expression. * @return The result of the comparison. */ friend constexpr Result operator!=(Tag const &lhs, Tag const &rhs) { return !(lhs == rhs); } }; /** * Tests for equality or inequality between different strong types. * * @tparam Tag The strong typedef to compare. * @tparam OtherTag The other strong typedef to compare. * @tparam Result The return type of the comparison */ template<class Tag, typename OtherTag, typename Result = bool> class mixed_equality { public: /** * Test for equality. * * @param lhs The left-hand side of the relational expression. * @param rhs The right-hand side of the relational expression. * @return The result of the comparison. */ friend constexpr Result operator==(Tag const &lhs, OtherTag const &rhs) { using type = underlying_type<Tag>; return static_cast<type const &>(lhs) == static_cast<type const &>(rhs); } /** * Test for inequality. * * @param lhs The left-hand side of the relational expression. * @param rhs The right-hand side of the relational expression. * @return The result of the comparison. */ friend constexpr Result operator!=(Tag const &lhs, OtherTag const &rhs) { return !(lhs == rhs); } /** * Test for equality. * * @param lhs The left-hand side of the relational expression. * @param rhs The right-hand side of the relational expression. * @return The result of the comparison. */ friend constexpr Result operator==(OtherTag const &lhs, Tag const &rhs) { using type = underlying_type<Tag>; return static_cast<type const &>(lhs) == static_cast<type const &>(rhs); } /** * Test for inequality. * * @param lhs The left-hand side of the relational expression. * @param rhs The right-hand side of the relational expression. * @return The result of the comparison. */ friend constexpr Result operator!=(OtherTag const &lhs, Tag const &rhs) { return !(lhs == rhs); } }; } } #endif //STRONG_STRONG_HPP <commit_msg>Remove mixed_equality operator<commit_after>#ifndef STRONG_STRONG_HPP #define STRONG_STRONG_HPP #include <type_traits> #include <utility> /** * Namespace for creating strong typedefs. */ namespace strong { /** * A strong typedef wrapper around some Type. * * Allows the programmer to define a strong type to avoid comparing values that have the same type * but are logically different. For example, IDs in a geographic map application for intersections * and streets may both be integers, but one should not logically compare an intersection ID with * a street ID. * * Strong typedefs that inherit from this class can be explicitly converted to their base Type, * but not implicitly converted. For more information please see: * http://en.cppreference.com/w/cpp/language/cast_operator * * @tparam Tag A unique identifier for this type * @tparam Type The actual type (e.g. int) to use */ template<class Tag, typename Type> class type { public: /** * The default constructor of type will attempt to initialize the underlying value with its own * default constructor. */ constexpr type() : value() { } /** * Initialize the underlying value via a copy or move. * * @param v The value to copy. */ explicit constexpr type(Type const &v) : value(v) { } /** * Move constructor. * * If Type's move constructor does not throw, then this move constructor will have noexcept * enabled, which will allow for certain optimizations. For more information, please refer * to https://akrzemi1.wordpress.com/2014/04/24/noexcept-what-for/ * * @param v The value to move. */ explicit constexpr type(Type && v) noexcept(std::is_nothrow_move_constructible<Type>::value) : value(static_cast<Type &&>(v)) { } /** * Enables explicit conversion of the type. * * @return The underlying value. */ explicit operator Type &() noexcept { return value; } /** * Enables const-correct explicit conversion of the type. * * @return The underlying value. */ explicit constexpr operator Type const &() const noexcept { return value; } private: Type value; }; namespace detail { /** * A dummy function used to help determine the type of the underlying value of a strong typedef. */ template <class Tag, typename Type> Type dummy_function(type<Tag, Type>); } /** * Determine the type of the underlying value of a strong typedef. */ template <class Typedef> using underlying_type = decltype(detail::dummy_function(std::declval<Typedef>())); /** * Operations to enable on strong typedefs. */ namespace op { /** * Tests for equality or inequality between identical strong types. * * @tparam Tag The strong typedef to compare. * @tparam Result The return type of the comparison */ template<class Tag, typename Result = bool> class equality { public: /** * Test for equality. * * @param lhs The left-hand side of the relational expression. * @param rhs The right-hand side of the relational expression. * @return The result of the comparison. */ friend constexpr Result operator==(Tag const &lhs, Tag const &rhs) { using type = underlying_type<Tag>; return static_cast<type const &>(lhs) == static_cast<type const &>(rhs); } /** * Test for inequality. * * @param lhs The left-hand side of the relational expression. * @param rhs The right-hand side of the relational expression. * @return The result of the comparison. */ friend constexpr Result operator!=(Tag const &lhs, Tag const &rhs) { return !(lhs == rhs); } }; } } #endif //STRONG_STRONG_HPP <|endoftext|>
<commit_before>#pragma once #include "IShapeEditor.hpp" namespace Component { class Physics; } namespace GUI { /// Plane shape editor for physics components. class PlaneShapeEditor : public IShapeEditor { public: /// Plane type label. /** * @return "Plane" string. */ virtual const char* Label() const override { return "Plane"; } /// Show controls for editing a plane shape. /** * @param comp The physics component to edit. */ virtual void Show(Component::Physics* comp) override; /// Set a sphere shape on the given physics component. /** * @param comp The physics component on which to set shape. */ virtual void Apply(Component::Physics* comp) override; /// Set internal data according the given %Shape, provided that it /// is a plane. /** * @param shape The %Shape from which to initialize data. * @return True if shape type is plane, false otherwise. */ virtual bool SetFromShape(const Physics::Shape& shape) override; private: float normal[3] = { 0.0f, 1.0f, 0.0f }; float planeCoeff = 0.0f; }; } <commit_msg>Fixed missing constructor in PlaneShapeEditor.<commit_after>#pragma once #include "IShapeEditor.hpp" namespace Component { class Physics; } namespace GUI { /// Plane shape editor for physics components. class PlaneShapeEditor : public IShapeEditor { public: /// Constructor PlaneShapeEditor() = default; /// Plane type label. /** * @return "Plane" string. */ virtual const char* Label() const override { return "Plane"; } /// Show controls for editing a plane shape. /** * @param comp The physics component to edit. */ virtual void Show(Component::Physics* comp) override; /// Set a sphere shape on the given physics component. /** * @param comp The physics component on which to set shape. */ virtual void Apply(Component::Physics* comp) override; /// Set internal data according the given %Shape, provided that it /// is a plane. /** * @param shape The %Shape from which to initialize data. * @return True if shape type is plane, false otherwise. */ virtual bool SetFromShape(const Physics::Shape& shape) override; private: float normal[3] = { 0.0f, 1.0f, 0.0f }; float planeCoeff = 0.0f; }; } <|endoftext|>
<commit_before>// Copyright 2009 Minor Gordon. // This source comes from the XtreemFS project. It is licensed under the GPLv2 (see COPYING for terms and conditions). #include "xtreemfs/dir_proxy.h" using namespace xtreemfs; DIRProxy::~DIRProxy() { for ( std::map<std::string, CachedAddressMappings*>::iterator uuid_to_address_mappings_i = uuid_to_address_mappings_cache.begin(); uuid_to_address_mappings_i != uuid_to_address_mappings_cache.end(); uuid_to_address_mappings_i++ ) yidl::runtime::Object::decRef( *uuid_to_address_mappings_i->second ); } auto_DIRProxy DIRProxy::create( const YIELD::ipc::URI& absolute_uri, uint32_t flags, YIELD::platform::auto_Log log, const YIELD::platform::Time& operation_timeout, YIELD::ipc::auto_SSLContext ssl_context ) { YIELD::ipc::URI checked_uri( absolute_uri ); if ( checked_uri.get_port() == 0 ) { if ( checked_uri.get_scheme() == org::xtreemfs::interfaces::ONCRPCG_SCHEME ) checked_uri.set_port( org::xtreemfs::interfaces::DIRInterface::DEFAULT_ONCRPCG_PORT ); else if ( checked_uri.get_scheme() == org::xtreemfs::interfaces::ONCRPCS_SCHEME ) checked_uri.set_port( org::xtreemfs::interfaces::DIRInterface::DEFAULT_ONCRPCS_PORT ); else if ( checked_uri.get_scheme() == org::xtreemfs::interfaces::ONCRPCU_SCHEME ) checked_uri.set_port( org::xtreemfs::interfaces::DIRInterface::DEFAULT_ONCRPCU_PORT ); else checked_uri.set_port( org::xtreemfs::interfaces::DIRInterface::DEFAULT_ONCRPC_PORT ); } YIELD::ipc::auto_SocketAddress peername = YIELD::ipc::SocketAddress::create( checked_uri ); if ( peername != NULL ) return new DIRProxy( flags, log, operation_timeout, peername, createSocketFactory( checked_uri, ssl_context ) ); else throw YIELD::platform::Exception(); } yidl::runtime::auto_Object<org::xtreemfs::interfaces::AddressMappingSet> DIRProxy::getAddressMappingsFromUUID( const std::string& uuid ) { if ( uuid_to_address_mappings_cache_lock.try_acquire() ) { std::map<std::string, CachedAddressMappings*>::iterator uuid_to_address_mappings_i = uuid_to_address_mappings_cache.find( uuid ); if ( uuid_to_address_mappings_i != uuid_to_address_mappings_cache.end() ) { CachedAddressMappings* cached_address_mappings = uuid_to_address_mappings_i->second; uint32_t cached_address_mappings_age_s = ( YIELD::platform::Time()- cached_address_mappings->get_creation_time() ).as_unix_time_s(); if ( cached_address_mappings_age_s < cached_address_mappings->get_ttl_s() ) { cached_address_mappings->incRef(); uuid_to_address_mappings_cache_lock.release(); return cached_address_mappings; } else { yidl::runtime::Object::decRef( cached_address_mappings ); uuid_to_address_mappings_cache.erase( uuid_to_address_mappings_i ); uuid_to_address_mappings_cache_lock.release(); } } else uuid_to_address_mappings_cache_lock.release(); } org::xtreemfs::interfaces::AddressMappingSet address_mappings; xtreemfs_address_mappings_get( uuid, address_mappings ); if ( !address_mappings.empty() ) { CachedAddressMappings* cached_address_mappings = new CachedAddressMappings( address_mappings, address_mappings[0].get_ttl_s() ); uuid_to_address_mappings_cache_lock.acquire(); uuid_to_address_mappings_cache[uuid] = &cached_address_mappings->incRef(); uuid_to_address_mappings_cache_lock.release(); return cached_address_mappings; } else throw YIELD::platform::Exception( "could not find address mappings for UUID" ); } YIELD::ipc::auto_URI DIRProxy::getVolumeURIFromVolumeName( const std::string& volume_name ) { org::xtreemfs::interfaces::ServiceSet services; xtreemfs_service_get_by_name( volume_name, services ); if ( !services.empty() ) { for ( org::xtreemfs::interfaces::ServiceSet::const_iterator service_i = services.begin(); service_i != services.end(); service_i++ ) { const org::xtreemfs::interfaces::ServiceDataMap& data = ( *service_i ).get_data(); for ( org::xtreemfs::interfaces::ServiceDataMap::const_iterator service_data_i = data.begin(); service_data_i != data.end(); service_data_i++ ) { if ( service_data_i->first == "mrc" ) { yidl::runtime::auto_Object<org::xtreemfs::interfaces::AddressMappingSet> address_mappings = getAddressMappingsFromUUID( service_data_i->second ); for ( org::xtreemfs::interfaces::AddressMappingSet::const_iterator address_mapping_i = address_mappings->begin(); address_mapping_i != address_mappings->end(); address_mapping_i++ ) { if ( ( *address_mapping_i ).get_protocol() == org::xtreemfs::interfaces::ONCRPC_SCHEME ) return new YIELD::ipc::URI( ( *address_mapping_i ).get_uri() ); } for ( org::xtreemfs::interfaces::AddressMappingSet::const_iterator address_mapping_i = address_mappings->begin(); address_mapping_i != address_mappings->end(); address_mapping_i++ ) { if ( ( *address_mapping_i ).get_protocol() == org::xtreemfs::interfaces::ONCRPCS_SCHEME ) return new YIELD::ipc::URI( ( *address_mapping_i ).get_uri() ); } for ( org::xtreemfs::interfaces::AddressMappingSet::const_iterator address_mapping_i = address_mappings->begin(); address_mapping_i != address_mappings->end(); address_mapping_i++ ) { if ( ( *address_mapping_i ).get_protocol() == org::xtreemfs::interfaces::ONCRPCU_SCHEME ) return new YIELD::ipc::URI( ( *address_mapping_i ).get_uri() ); } } } } throw YIELD::platform::Exception( "unknown volume" ); } else throw YIELD::platform::Exception( "unknown volume" ); } <commit_msg>client: dir_proxy fix for GridSSL<commit_after>// Copyright 2009 Minor Gordon. // This source comes from the XtreemFS project. It is licensed under the GPLv2 (see COPYING for terms and conditions). #include "xtreemfs/dir_proxy.h" using namespace xtreemfs; DIRProxy::~DIRProxy() { for ( std::map<std::string, CachedAddressMappings*>::iterator uuid_to_address_mappings_i = uuid_to_address_mappings_cache.begin(); uuid_to_address_mappings_i != uuid_to_address_mappings_cache.end(); uuid_to_address_mappings_i++ ) yidl::runtime::Object::decRef( *uuid_to_address_mappings_i->second ); } auto_DIRProxy DIRProxy::create( const YIELD::ipc::URI& absolute_uri, uint32_t flags, YIELD::platform::auto_Log log, const YIELD::platform::Time& operation_timeout, YIELD::ipc::auto_SSLContext ssl_context ) { YIELD::ipc::URI checked_uri( absolute_uri ); if ( checked_uri.get_port() == 0 ) { if ( checked_uri.get_scheme() == org::xtreemfs::interfaces::ONCRPCG_SCHEME ) checked_uri.set_port( org::xtreemfs::interfaces::DIRInterface::DEFAULT_ONCRPCG_PORT ); else if ( checked_uri.get_scheme() == org::xtreemfs::interfaces::ONCRPCS_SCHEME ) checked_uri.set_port( org::xtreemfs::interfaces::DIRInterface::DEFAULT_ONCRPCS_PORT ); else if ( checked_uri.get_scheme() == org::xtreemfs::interfaces::ONCRPCU_SCHEME ) checked_uri.set_port( org::xtreemfs::interfaces::DIRInterface::DEFAULT_ONCRPCU_PORT ); else checked_uri.set_port( org::xtreemfs::interfaces::DIRInterface::DEFAULT_ONCRPC_PORT ); } YIELD::ipc::auto_SocketAddress peername = YIELD::ipc::SocketAddress::create( checked_uri ); if ( peername != NULL ) return new DIRProxy( flags, log, operation_timeout, peername, createSocketFactory( checked_uri, ssl_context ) ); else throw YIELD::platform::Exception(); } yidl::runtime::auto_Object<org::xtreemfs::interfaces::AddressMappingSet> DIRProxy::getAddressMappingsFromUUID( const std::string& uuid ) { if ( uuid_to_address_mappings_cache_lock.try_acquire() ) { std::map<std::string, CachedAddressMappings*>::iterator uuid_to_address_mappings_i = uuid_to_address_mappings_cache.find( uuid ); if ( uuid_to_address_mappings_i != uuid_to_address_mappings_cache.end() ) { CachedAddressMappings* cached_address_mappings = uuid_to_address_mappings_i->second; uint32_t cached_address_mappings_age_s = ( YIELD::platform::Time()- cached_address_mappings->get_creation_time() ).as_unix_time_s(); if ( cached_address_mappings_age_s < cached_address_mappings->get_ttl_s() ) { cached_address_mappings->incRef(); uuid_to_address_mappings_cache_lock.release(); return cached_address_mappings; } else { yidl::runtime::Object::decRef( cached_address_mappings ); uuid_to_address_mappings_cache.erase( uuid_to_address_mappings_i ); uuid_to_address_mappings_cache_lock.release(); } } else uuid_to_address_mappings_cache_lock.release(); } org::xtreemfs::interfaces::AddressMappingSet address_mappings; xtreemfs_address_mappings_get( uuid, address_mappings ); if ( !address_mappings.empty() ) { CachedAddressMappings* cached_address_mappings = new CachedAddressMappings( address_mappings, address_mappings[0].get_ttl_s() ); uuid_to_address_mappings_cache_lock.acquire(); uuid_to_address_mappings_cache[uuid] = &cached_address_mappings->incRef(); uuid_to_address_mappings_cache_lock.release(); return cached_address_mappings; } else throw YIELD::platform::Exception( "could not find address mappings for UUID" ); } YIELD::ipc::auto_URI DIRProxy::getVolumeURIFromVolumeName( const std::string& volume_name ) { org::xtreemfs::interfaces::ServiceSet services; xtreemfs_service_get_by_name( volume_name, services ); if ( !services.empty() ) { for ( org::xtreemfs::interfaces::ServiceSet::const_iterator service_i = services.begin(); service_i != services.end(); service_i++ ) { const org::xtreemfs::interfaces::ServiceDataMap& data = ( *service_i ).get_data(); for ( org::xtreemfs::interfaces::ServiceDataMap::const_iterator service_data_i = data.begin(); service_data_i != data.end(); service_data_i++ ) { if ( service_data_i->first == "mrc" ) { yidl::runtime::auto_Object<org::xtreemfs::interfaces::AddressMappingSet> address_mappings = getAddressMappingsFromUUID( service_data_i->second ); // Prefer TCP URIs first for ( org::xtreemfs::interfaces::AddressMappingSet::const_iterator address_mapping_i = address_mappings->begin(); address_mapping_i != address_mappings->end(); address_mapping_i++ ) { if ( ( *address_mapping_i ).get_protocol() == org::xtreemfs::interfaces::ONCRPC_SCHEME ) return new YIELD::ipc::URI( ( *address_mapping_i ).get_uri() ); } // Then GridSSL for ( org::xtreemfs::interfaces::AddressMappingSet::const_iterator address_mapping_i = address_mappings->begin(); address_mapping_i != address_mappings->end(); address_mapping_i++ ) { if ( ( *address_mapping_i ).get_protocol() == org::xtreemfs::interfaces::ONCRPCG_SCHEME ) return new YIELD::ipc::URI( ( *address_mapping_i ).get_uri() ); } // Then SSL for ( org::xtreemfs::interfaces::AddressMappingSet::const_iterator address_mapping_i = address_mappings->begin(); address_mapping_i != address_mappings->end(); address_mapping_i++ ) { if ( ( *address_mapping_i ).get_protocol() == org::xtreemfs::interfaces::ONCRPCS_SCHEME ) return new YIELD::ipc::URI( ( *address_mapping_i ).get_uri() ); } // Then UDP for ( org::xtreemfs::interfaces::AddressMappingSet::const_iterator address_mapping_i = address_mappings->begin(); address_mapping_i != address_mappings->end(); address_mapping_i++ ) { if ( ( *address_mapping_i ).get_protocol() == org::xtreemfs::interfaces::ONCRPCU_SCHEME ) return new YIELD::ipc::URI( ( *address_mapping_i ).get_uri() ); } } } } } throw YIELD::platform::Exception( "unknown volume" ); } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include "src/Options.hpp" #include "src/Cluster.hpp" #include <map> using namespace std; int main(int argc, char *argv[]){ std::map<string,string > options2; options2["eps_iter"] = "1e-4"; /* Dirichlet, lumped */ options2["preconditioner"] = "Dirichlet"; //options2["preconditioner"] = "lumped"; options2["path2data"] = "data/"; options2["young_modulus"] = "1000"; options2["poissons_ratio"] = "0.3"; /* dissection | pardiso */ options2["linear_solver"] = "dissection"; /* {0, 1, 2, 3 } */ options2["print_matrices"] = "0"; /* ker, cor, all */ options2["typeBc"] = "ker"; /* true, false */ options2["Ac_extended_by_kerGc"] = "false"; /* true, false */ options2["GcTGc_assembl_block_by_block"] = "true"; /* true, false */ options2["Bc_fullRank"] = "true"; /* true, false */ options2["create_analytic_ker_K"] = "false"; options2["Nx"] = "2"; options2["Ny"] = "2"; options2["Nz"] = "2"; options2["nx"] = "5"; options2["ny"] = "5"; options2["nz"] = "5"; printf("+++++++++++++++++++++++++++++++++++ %s\n", options2["path2data"].c_str()); if (options2["linear_solver"] == "pardiso" && options2["create_analytic_ker_K"] == "false"){ cout <<"###########################################################" << endl; cout << "if pardiso, kernel must be provided by analytical formula" << endl; cout <<"###########################################################" << endl; options2["create_analytic_ker_K"] = true; } if (argc > 1) { options2["Nx"] = (argv[1]); } if (argc > 2) { options2["Ny"] = (argv[2]); } if (argc > 3) { options2["Nz"] = (argv[3]); } if (argc > 4) { options2["nx"] = (argv[4]); } if (argc > 5) { options2["ny"] = (argv[5]); } if (argc > 6) { options2["nz"] = (argv[6]); } cout << argv[0] << endl; Options options; Cluster cluster(options,options2); cout << "----------------- done -----------------\n" ; return 0; } // HOW TO PRINT OPTIONS2 // cout << "\t\t\tK.options2.size() " << K.options2.size() << endl; // for (std::map<string,string>::const_iterator it=K.options2.begin(); it!=K.options2.end(); ++it) // std::cout << "\t\t\t" << it->first << " => " << it->second << '\n'; <commit_msg>cosmetics<commit_after>#include <iostream> #include <string> #include "src/Options.hpp" #include "src/Cluster.hpp" #include <map> using namespace std; int main(int argc, char *argv[]){ map<string,string > options2; options2["eps_iter"] = "1e-4"; /* Dirichlet, lumped */ options2["preconditioner"] = "Dirichlet"; //options2["preconditioner"] = "lumped"; options2["path2data"] = "data/"; options2["young_modulus"] = "1000"; options2["poissons_ratio"] = "0.3"; /* dissection | pardiso */ options2["linear_solver"] = "dissection"; /* {0, 1, 2, 3 } */ options2["print_matrices"] = "0"; /* ker, cor, all */ options2["typeBc"] = "ker"; /* true, false */ options2["Ac_extended_by_kerGc"] = "false"; /* true, false */ options2["GcTGc_assembl_block_by_block"] = "true"; /* true, false */ options2["Bc_fullRank"] = "true"; /* true, false */ options2["create_analytic_ker_K"] = "false"; options2["Nx"] = "2"; options2["Ny"] = "2"; options2["Nz"] = "2"; options2["nx"] = "5"; options2["ny"] = "5"; options2["nz"] = "5"; printf("+++++++++++++++++++++++++++++++++++ %s\n", options2["path2data"].c_str()); if (options2["linear_solver"] == "pardiso" && options2["create_analytic_ker_K"] == "false"){ cout <<"###########################################################" << endl; cout << "if pardiso, kernel must be provided by analytical formula" << endl; cout <<"###########################################################" << endl; options2["create_analytic_ker_K"] = true; } if (argc > 1) { options2["Nx"] = (argv[1]); } if (argc > 2) { options2["Ny"] = (argv[2]); } if (argc > 3) { options2["Nz"] = (argv[3]); } if (argc > 4) { options2["nx"] = (argv[4]); } if (argc > 5) { options2["ny"] = (argv[5]); } if (argc > 6) { options2["nz"] = (argv[6]); } cout << argv[0] << endl; Options options; Cluster cluster(options,options2); cout << "----------------- done -----------------\n" ; // HOW TO PRINT OPTIONS2 cout << "\t\t\toptions2.size() " << options2.size() << endl; for (map<string,string>::const_iterator it=options2.begin(); it!=options2.end(); ++it) cout << "\t\t\t" << it->first << " => " << it->second << '\n'; return 0; } <|endoftext|>
<commit_before>/** * @file * Zenderer/Math/zVector.hpp - A vector class representing a position * in 3D (or 2D) space, fully supporting the mathematical operations * typical of such a structure. * * @author George Kudrayvtsev (halcyon) * @version 1.5.1 * @copyright Apache License v2.0 * Licensed under the Apache License, Version 2.0 (the "License"). \n * You may not use this file except in compliance with the License. \n * You may obtain a copy of the License at: * http://www.apache.org/licenses/LICENSE-2.0 \n * Unless required by applicable law or agreed to in writing, software \n * distributed under the License is distributed on an "AS IS" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and \n * limitations under the License. * * @addtogroup Math * @{ **/ #ifndef IRON_CLAD__MATH__VECTOR_2_HPP #define IRON_CLAD__MATH__VECTOR_2_HPP #include <cmath> #include <ostream> #include "Zenderer/Core/Types.hpp" #include "MathCore.hpp" namespace zen { namespace math { /// Forward declaration of a 4x4 matrix for use in 2D vector translation. class ZEN_API matrix4x4_t; /// Represents a point in 3D rectangular-coordinate space. template<typename T> struct ZEN_API zVector { /// The publicly-accessible vector components. T x, y, z; /// Default constructor that moves the vector to the origin. zVector() : x(0), y(0), z(1) {} /// Constructor for any coordinate space (defaults to 2D). zVector(T x, T y, T z = 1) : x(x), y(y), z(z) {} /// Copies vector components from one to another. template<typename U> zVector(const zVector<U>& C) : x(C.x), y(C.y), z(C.z) {} /// Assigns one vector to another. template<typename U> inline zVector<T>& operator=(const zVector<U>& Copy); /// Compares two vectors for equivalence. template<typename U> inline bool operator==(const zVector<U>& Other) const; /// Opposite of zVector::operator==() template<typename U> inline bool operator!=(const zVector<U>& Other) const; // Begin mathematical vector operations. /** * Calculates the cross product of two vectors. * The cross product of two vectors is a vector that is * perpendicular to both operators. e.g. i = j ^ k. * * @param Other The vector to cross with * * @return A 3D vector normal to both vectors. **/ template<typename U> inline zVector<T> operator^(const zVector<U>& Other) const; /** * Calculates the dot product of two vectors. * The dot product is useful in finding the angle between two * vectors. The formula for that is as follows: * * cos(&Theta;) = (A &sdot; B) / (||A|| * ||B||) * * Where A and B are vectors and ||A|| is the magnitude of A. * The actual operation is defined as such: * * A = (x1, y1, z1) * B = (x2, y2, z2) * A &sdot; B = x1 * x2 + y1 * y2 + z1 * z2 * * @param Other The vector to dot with. * * @return The dot product as a scalar. **/ template<typename U> inline real_t operator*(const zVector<U>& Other) const; /** * Multiplies each component by a scalar factor. * @param scalar The component scaling factor * @return A 2D resultant vector. **/ inline zVector<T> operator*(const real_t scalar) const; /** * Divides each component by a scalar factor. * @param scalar The component scaling factor * @return A 2D resultant vector. **/ inline zVector<T> operator/(const real_t scalar) const; /** * Adds a given vector to the current vector, returning the result. * @param Other The vector to add (component-wise) * @return A 2D resultant vector. **/ template<typename U> inline zVector<T> operator+(const zVector<U>& Other) const; /** * Adds a value to both components of the current vector. * @param value The value to add * @return A 2D resultant vector. **/ inline zVector<T> operator+(const real_t value) const; /** * Subtracts a given vector from the current vector, returning the result. * @param Other The vector to subtract from the current vector * @return A 2D resultant vector. **/ template<typename U> inline zVector<T> operator-(const zVector<U>& Other) const; /** * Normalizes the current vector. * This *DOES* modify the current vector, and makes it into * a unit vector version of itself. **/ inline void Normalize(); /// Returns the current vectors magnitude, or 'norm'. /// magnitude = &radic;(x<sup>2</sup> + y<sup>2</sup> + z<sup>2</sup>) inline real_t Magnitude() const; /** * Rotates the current vector using the rotation matrix. * The rotation matrix (in right-hand Cartesian plane) * is defined as being * | x | | cos(&Theta;), -sin(&Theta;) | * | y | | sin(&Theta;), cos(&Theta;) | * * But in the OpenGL coordinate system, the origin is in * the top-left, as opposed to bottom-left, as shown above. * So rotations are actually inverted and the matrix is * | x | | cos(&Theta;), sin(&Theta;) | * | y | | -sin(&Theta;), cos(&Theta;) | * * So the final rotation in OpenGL would be: * x = x * cos(&Theta;) + y * sin(&Theta;) * y = -x * sin(&Theta;) + y * cos(&Theta;) * * @param radians The rotation angle in radians. * * @note The coordinate system adjustment was removed. **/ inline void Rotate(const real_t radians); /** * Translates the current vector by a matrix. * @param TransMat Translation matrix **/ void Translate(const matrix4x4_t& TransMat); /** * Returns a scalar cross product value between two 2D vectors. * Given a vector v = <x1, y1> and a vector w = <x2, y2>, their * cross-product is determined as <0, 0, x1*y2 - y1*x2>. * So, this method returns the third component. * * This value can be used to determine which side of a vector * another vector is on. If the return value is negative, the * "Other" vector is on the left (going ccw). If positive, * it's on the right (going c/w). This can also be done by * examining the dot product. * * @param Other zVector to test cross product on * * @return 2D cross product (z-component of 3D cross). * * @see operator*(const zVector&) **/ template<typename U> inline real_t Cross2D(const zVector<U>& Other) const; /** * Returns a normalized version of the current vector. * @see zVector::Normalize() **/ inline zVector<T> GetNormalized() const; /// Outputs the vector in the form `<x, y, z>` template<typename U> friend std::ostream& operator<<(std::ostream& out, const zVector<U>& Other); /** * Finds the distance between two points (optional `sqrt`). * @todo Investigate potential problems between a signed * and unsigned `zVector<R>` or `zVector<S>`. **/ template<typename R, typename S> static real_t distance(const zVector<R>& A, const zVector<S>& B, const bool do_sqrt = false); }; #include "Vector.inl" /// A shortcut for the default vector implementation in the engine. typedef zVector<real_t> vector_t; /// Floating-point vector shortcut. typedef zVector<real_t> vectorf_t; /// 16-bit unsigned integral vector shortcut. typedef zVector<uint16_t> vectoru16_t; /// Standard 32-bit integral vector shortcut. typedef zVector<int32_t> vectori_t; } // namespace math } // namespace ic #endif // IRON_CLAD__MATH__VECTOR_2_HPP /** * @class zen::math::vector_t * @details * Supports all vector operations such as cross products, * dot products, movement, scaling, and rotation. * * The class is templated to store any sort of POD values that * you'd like, such as `float`, `int`, `uint32_t`, etc. * Beware that any operations between mixed vector types will * return the type of the vector on the left-hand side of the * operation. e.g.: * * @code * zVector<int> A(1, 2, 3); * zVector<float> B(1.1, 2.2, 3.3); * * zVector<float> C = A + B; // INVALID! * zVector<int> C = A + B; // VALID * @endcode * * Thus if you need a higher level of precision, keep that vector * instance on the right-hand side. * * There is a built-in shortcut to `vector_t` that is a floating-point * vector representation that is used throughout the engine. * * @todo Add support for translation via matrices. * * @note There is support for creating translation matrices via * vectors but not vice-versa. * * @see @ref USE_DOUBLE_PRECISION **/ /** @} **/ <commit_msg>Minor documentation tweak.<commit_after>/** * @file * Zenderer/Math/zVector.hpp - A vector class representing a position * in 3D (or 2D) space, fully supporting the mathematical operations * typical of such a structure. * * @author George Kudrayvtsev (halcyon) * @version 1.5.1 * @copyright Apache License v2.0 * Licensed under the Apache License, Version 2.0 (the "License"). \n * You may not use this file except in compliance with the License. \n * You may obtain a copy of the License at: * http://www.apache.org/licenses/LICENSE-2.0 \n * Unless required by applicable law or agreed to in writing, software \n * distributed under the License is distributed on an "AS IS" BASIS, \n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and \n * limitations under the License. * * @addtogroup Math * @{ **/ #ifndef IRON_CLAD__MATH__VECTOR_2_HPP #define IRON_CLAD__MATH__VECTOR_2_HPP #include <cmath> #include <ostream> #include "Zenderer/Core/Types.hpp" #include "MathCore.hpp" namespace zen { namespace math { /// Forward declaration of a 4x4 matrix for use in 2D vector translation. class ZEN_API matrix4x4_t; /// Represents a point in 3D rectangular-coordinate space. template<typename T> struct ZEN_API zVector { /// The publicly-accessible vector components. T x, y, z; /// Default constructor that moves the vector to the origin. zVector() : x(0), y(0), z(1) {} /// Constructor for any coordinate space (defaults to 2D). zVector(T x, T y, T z = 1) : x(x), y(y), z(z) {} /// Copies vector components from one to another. template<typename U> zVector(const zVector<U>& C) : x(C.x), y(C.y), z(C.z) {} /// Assigns one vector to another. template<typename U> inline zVector<T>& operator=(const zVector<U>& Copy); /// Compares two vectors for equivalence. template<typename U> inline bool operator==(const zVector<U>& Other) const; /// Opposite of zVector::operator==() template<typename U> inline bool operator!=(const zVector<U>& Other) const; // Begin mathematical vector operations. /** * Calculates the cross product of two vectors. * The cross product of two vectors is a vector that is * perpendicular to both operators. e.g. i = j ^ k. * * @param Other The vector to cross with * * @return A 3D vector normal to both vectors. **/ template<typename U> inline zVector<T> operator^(const zVector<U>& Other) const; /** * Calculates the dot product of two vectors. * The dot product is useful in finding the angle between two * vectors. The formula for that is as follows: * * cos(&Theta;) = (A &sdot; B) / (||A|| * ||B||) * * Where A and B are vectors and ||A|| is the magnitude of A. * The actual operation is defined as such: * * A = (x1, y1, z1) * B = (x2, y2, z2) * A &sdot; B = x1 * x2 + y1 * y2 + z1 * z2 * * @param Other The vector to dot with. * * @return The dot product as a scalar. **/ template<typename U> inline real_t operator*(const zVector<U>& Other) const; /** * Multiplies each component by a scalar factor. * @param scalar The component scaling factor * @return A 2D resultant vector. **/ inline zVector<T> operator*(const real_t scalar) const; /** * Divides each component by a scalar factor. * @param scalar The component scaling factor * @return A 2D resultant vector. **/ inline zVector<T> operator/(const real_t scalar) const; /** * Adds a given vector to the current vector, returning the result. * @param Other The vector to add (component-wise) * @return A 2D resultant vector. **/ template<typename U> inline zVector<T> operator+(const zVector<U>& Other) const; /** * Adds a value to both components of the current vector. * @param value The value to add * @return A 2D resultant vector. **/ inline zVector<T> operator+(const real_t value) const; /** * Subtracts a given vector from the current vector, returning the result. * @param Other The vector to subtract from the current vector * @return A 2D resultant vector. **/ template<typename U> inline zVector<T> operator-(const zVector<U>& Other) const; /** * Normalizes the current vector. * This *DOES* modify the current vector, and makes it into * a unit vector version of itself. **/ inline void Normalize(); /// Returns the current vectors magnitude, or 'norm'. /// magnitude = &radic;(x<sup>2</sup> + y<sup>2</sup> + z<sup>2</sup>) inline real_t Magnitude() const; /** * Rotates the current vector CCW using the rotation matrix. * The rotation matrix (in right-hand Cartesian plane) * is defined as being * | x | | cos(&Theta;), -sin(&Theta;) | * | y | | sin(&Theta;), cos(&Theta;) | * * But in the OpenGL coordinate system, the origin is in * the top-left, as opposed to bottom-left, as shown above. * So rotations are actually inverted and the matrix is * | x | | cos(&Theta;), sin(&Theta;) | * | y | | -sin(&Theta;), cos(&Theta;) | * * So the final rotation in OpenGL would be: * x = x * cos(&Theta;) + y * sin(&Theta;) * y = -x * sin(&Theta;) + y * cos(&Theta;) * * @param radians The rotation angle in radians. * * @note The coordinate system adjustment was removed. **/ inline void Rotate(const real_t radians); /** * Translates the current vector by a matrix. * @param TransMat Translation matrix **/ void Translate(const matrix4x4_t& TransMat); /** * Returns a scalar cross product value between two 2D vectors. * Given a vector v = <x1, y1> and a vector w = <x2, y2>, their * cross-product is determined as <0, 0, x1*y2 - y1*x2>. * So, this method returns the third component. * * This value can be used to determine which side of a vector * another vector is on. If the return value is negative, the * "Other" vector is on the left (going ccw). If positive, * it's on the right (going c/w). This can also be done by * examining the dot product. * * @param Other zVector to test cross product on * * @return 2D cross product (z-component of 3D cross). * * @see operator*(const zVector&) **/ template<typename U> inline real_t Cross2D(const zVector<U>& Other) const; /** * Returns a normalized version of the current vector. * @see zVector::Normalize() **/ inline zVector<T> GetNormalized() const; /// Outputs the vector in the form `<x, y, z>` template<typename U> friend std::ostream& operator<<(std::ostream& out, const zVector<U>& Other); /** * Finds the distance between two points (optional `sqrt`). * @todo Investigate potential problems between a signed * and unsigned `zVector<R>` or `zVector<S>`. **/ template<typename R, typename S> static real_t distance(const zVector<R>& A, const zVector<S>& B, const bool do_sqrt = false); }; #include "Vector.inl" /// A shortcut for the default vector implementation in the engine. typedef zVector<real_t> vector_t; /// Floating-point vector shortcut. typedef zVector<real_t> vectorf_t; /// 16-bit unsigned integral vector shortcut. typedef zVector<uint16_t> vectoru16_t; /// Standard 32-bit integral vector shortcut. typedef zVector<int32_t> vectori_t; } // namespace math } // namespace ic #endif // IRON_CLAD__MATH__VECTOR_2_HPP /** * @class zen::math::vector_t * @details * Supports all vector operations such as cross products, * dot products, movement, scaling, and rotation. * * The class is templated to store any sort of POD values that * you'd like, such as `float`, `int`, `uint32_t`, etc. * Beware that any operations between mixed vector types will * return the type of the vector on the left-hand side of the * operation. e.g.: * * @code * zVector<int> A(1, 2, 3); * zVector<float> B(1.1, 2.2, 3.3); * * zVector<float> C = A + B; // INVALID! * zVector<int> C = A + B; // VALID * @endcode * * Thus if you need a higher level of precision, keep that vector * instance on the right-hand side. * * There is a built-in shortcut to `vector_t` that is a floating-point * vector representation that is used throughout the engine. * * @todo Add support for translation via matrices. * * @note There is support for creating translation matrices via * vectors but not vice-versa. * * @see @ref USE_DOUBLE_PRECISION **/ /** @} **/ <|endoftext|>
<commit_before>// (C) Copyright Gennadiy Rozental 2001-2014. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/test for the library home page. // /// @file /// @brief Entry point into the Unit Test Framework /// /// This header sould be the only header necessary to include to start using the framework // *************************************************************************** #ifndef BOOST_TEST_UNIT_TEST_HPP_071894GER #define BOOST_TEST_UNIT_TEST_HPP_071894GER // Boost.Test #include <boost/test/test_tools.hpp> #include <boost/test/unit_test_suite.hpp> //____________________________________________________________________________// // ************************************************************************** // // ************** Auto Linking ************** // // ************************************************************************** // #if !defined(BOOST_ALL_NO_LIB) && !defined(BOOST_TEST_NO_LIB) && \ !defined(BOOST_TEST_SOURCE) && !defined(BOOST_TEST_INCLUDED) # define BOOST_LIB_NAME boost_unit_test_framework # if defined(BOOST_ALL_DYN_LINK) || defined(BOOST_TEST_DYN_LINK) # define BOOST_DYN_LINK # endif # include <boost/config/auto_link.hpp> #endif // auto-linking disabled // ************************************************************************** // // ************** unit_test_main ************** // // ************************************************************************** // namespace boost { namespace unit_test { int BOOST_TEST_DECL unit_test_main( init_unit_test_func init_func, int argc, char* argv[] ); } // !! ?? to remove namespace unit_test_framework=unit_test; } #if defined(BOOST_TEST_DYN_LINK) && defined(BOOST_TEST_MAIN) && !defined(BOOST_TEST_NO_MAIN) // ************************************************************************** // // ************** main function for tests using dll ************** // // ************************************************************************** // int BOOST_TEST_CALL_DECL main( int argc, char* argv[] ) { return ::boost::unit_test::unit_test_main( &init_unit_test, argc, argv ); } //____________________________________________________________________________// #endif // BOOST_TEST_DYN_LINK && BOOST_TEST_MAIN && !BOOST_TEST_NO_MAIN #endif // BOOST_TEST_UNIT_TEST_HPP_071894GER <commit_msg>Doc: typeo sould --> should<commit_after>// (C) Copyright Gennadiy Rozental 2001-2014. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/test for the library home page. // /// @file /// @brief Entry point into the Unit Test Framework /// /// This header should be the only header necessary to include to start using the framework // *************************************************************************** #ifndef BOOST_TEST_UNIT_TEST_HPP_071894GER #define BOOST_TEST_UNIT_TEST_HPP_071894GER // Boost.Test #include <boost/test/test_tools.hpp> #include <boost/test/unit_test_suite.hpp> //____________________________________________________________________________// // ************************************************************************** // // ************** Auto Linking ************** // // ************************************************************************** // #if !defined(BOOST_ALL_NO_LIB) && !defined(BOOST_TEST_NO_LIB) && \ !defined(BOOST_TEST_SOURCE) && !defined(BOOST_TEST_INCLUDED) # define BOOST_LIB_NAME boost_unit_test_framework # if defined(BOOST_ALL_DYN_LINK) || defined(BOOST_TEST_DYN_LINK) # define BOOST_DYN_LINK # endif # include <boost/config/auto_link.hpp> #endif // auto-linking disabled // ************************************************************************** // // ************** unit_test_main ************** // // ************************************************************************** // namespace boost { namespace unit_test { int BOOST_TEST_DECL unit_test_main( init_unit_test_func init_func, int argc, char* argv[] ); } // !! ?? to remove namespace unit_test_framework=unit_test; } #if defined(BOOST_TEST_DYN_LINK) && defined(BOOST_TEST_MAIN) && !defined(BOOST_TEST_NO_MAIN) // ************************************************************************** // // ************** main function for tests using dll ************** // // ************************************************************************** // int BOOST_TEST_CALL_DECL main( int argc, char* argv[] ) { return ::boost::unit_test::unit_test_main( &init_unit_test, argc, argv ); } //____________________________________________________________________________// #endif // BOOST_TEST_DYN_LINK && BOOST_TEST_MAIN && !BOOST_TEST_NO_MAIN #endif // BOOST_TEST_UNIT_TEST_HPP_071894GER <|endoftext|>
<commit_before>/****************************************************************************/ /* Copyright 2005-2006, Francis Russell */ /* */ /* 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 DESOLIN_INTERNAL_REPS_HPP #define DESOLIN_INTERNAL_REPS_HPP #include <cassert> #include <desolin/Desolin_fwd.hpp> #include <desolin/file-access/mtl_entry.hpp> namespace desolin { namespace detail { template<typename T_element> class InternalValue { protected: bool allocated; public: InternalValue(const bool isAllocated) : allocated(isAllocated) { } inline bool isAllocated() const { return allocated; } virtual void allocate() = 0; virtual ~InternalValue() {} }; template<typename T_element> class InternalScalar : public InternalValue<T_element> { public: InternalScalar(const bool allocated) : InternalValue<T_element>(allocated) { } virtual void accept(InternalScalarVisitor<T_element>& visitor) = 0; virtual T_element getElementValue() = 0; }; template<typename T_element> class InternalVector : public InternalValue<T_element> { protected: const int rows; public: InternalVector(const bool allocated, const int rowCount) : InternalValue<T_element>(allocated), rows(rowCount) { } const inline int getRowCount() const { return rows; } virtual void accept(InternalVectorVisitor<T_element>& visitor) = 0; virtual T_element getElementValue(const ElementIndex<vector>& index) = 0; }; template<typename T_element> class InternalMatrix : public InternalValue<T_element> { protected: const int rows; const int cols; public: InternalMatrix(const bool allocated, const int rowCount, const int colCount) : InternalValue<T_element>(allocated), rows(rowCount), cols(colCount) { } const inline int getRowCount() const { return rows; } const inline int getColCount() const { return cols; } virtual void accept(InternalMatrixVisitor<T_element>& visitor) = 0; virtual T_element getElementValue(const ElementIndex<matrix>& index) = 0; }; template<typename T_element> class ConventionalScalar : public InternalScalar<T_element> { private: T_element value; public: ConventionalScalar() : InternalScalar<T_element>(true), value(T_element(0)) { } ConventionalScalar(const T_element initialValue) : InternalScalar<T_element>(true), value(initialValue) { } virtual void allocate() { this->allocated=true; } virtual void accept(InternalScalarVisitor<T_element>& visitor) { visitor.visit(*this); } virtual T_element getElementValue() { assert(this->allocated); return value; } T_element* getValue() { assert(this->allocated); return &value; } }; template<typename T_element> class ConventionalVector : public InternalVector<T_element> { private: std::vector<T_element> value; public: ConventionalVector(const int rowCount) : InternalVector<T_element>(false, rowCount) { } ConventionalVector(const int rowCount, const T_element initialValue) : InternalVector<T_element>(true, rowCount), value(rowCount, initialValue) { } virtual void allocate() { if(!this->allocated) { value.resize(this->rows, T_element(0)); this->allocated=true; } } virtual void accept(InternalVectorVisitor<T_element>& visitor) { visitor.visit(*this); } T_element* getValue() { assert(this->allocated); return &value[0]; } virtual T_element getElementValue(const ElementIndex<vector>& index) { assert(this->allocated); return value[index.getRow()]; } }; template<typename T_element> class ConventionalMatrix : public InternalMatrix<T_element> { private: std::vector<T_element> value; public: ConventionalMatrix(const int rowCount, const int colCount) : InternalMatrix<T_element>(false, rowCount, colCount) { } ConventionalMatrix(const int rowCount, const int colCount, const T_element initialValue) : InternalMatrix<T_element>(true, rowCount, colCount), value(rowCount*colCount, initialValue) { } template<typename StreamType> ConventionalMatrix(StreamType& stream) : InternalMatrix<T_element>(true, stream.nrows(), stream.ncols()), value(stream.nrows()*stream.ncols(), T_element(0)) { while(!stream.eof()) { entry2<double> entry; stream >> entry; value[this->getRowCount()*entry.row + entry.col] = entry.value; } } virtual void allocate() { if(!this->allocated) { value.resize(this->rows * this->cols, T_element(0)); this->allocated=true; } } virtual void accept(InternalMatrixVisitor<T_element>& visitor) { visitor.visit(*this); } T_element* getValue() { assert(this->allocated); return &value[0]; } virtual T_element getElementValue(const ElementIndex<matrix>& index) { assert(this->allocated); return value[(this->cols*index.getRow())+index.getCol()]; } }; template<typename T_elementType> class InternalScalarVisitor { public: virtual void visit(ConventionalScalar<T_elementType>& value) = 0; virtual ~InternalScalarVisitor() {} }; template<typename T_elementType> class InternalVectorVisitor { public: virtual void visit(ConventionalVector<T_elementType>& value) = 0; virtual ~InternalVectorVisitor() {} }; template<typename T_elementType> class InternalMatrixVisitor { public: virtual void visit(ConventionalMatrix<T_elementType>& value) = 0; virtual ~InternalMatrixVisitor() {} }; } } #endif <commit_msg>Fixed index calculation error in routine for loading dense matrix from a Harwell-Boeing stream.<commit_after>/****************************************************************************/ /* Copyright 2005-2006, Francis Russell */ /* */ /* 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 DESOLIN_INTERNAL_REPS_HPP #define DESOLIN_INTERNAL_REPS_HPP #include <cassert> #include <desolin/Desolin_fwd.hpp> #include <desolin/file-access/mtl_entry.hpp> namespace desolin { namespace detail { template<typename T_element> class InternalValue { protected: bool allocated; public: InternalValue(const bool isAllocated) : allocated(isAllocated) { } inline bool isAllocated() const { return allocated; } virtual void allocate() = 0; virtual ~InternalValue() {} }; template<typename T_element> class InternalScalar : public InternalValue<T_element> { public: InternalScalar(const bool allocated) : InternalValue<T_element>(allocated) { } virtual void accept(InternalScalarVisitor<T_element>& visitor) = 0; virtual T_element getElementValue() = 0; }; template<typename T_element> class InternalVector : public InternalValue<T_element> { protected: const int rows; public: InternalVector(const bool allocated, const int rowCount) : InternalValue<T_element>(allocated), rows(rowCount) { } const inline int getRowCount() const { return rows; } virtual void accept(InternalVectorVisitor<T_element>& visitor) = 0; virtual T_element getElementValue(const ElementIndex<vector>& index) = 0; }; template<typename T_element> class InternalMatrix : public InternalValue<T_element> { protected: const int rows; const int cols; public: InternalMatrix(const bool allocated, const int rowCount, const int colCount) : InternalValue<T_element>(allocated), rows(rowCount), cols(colCount) { } const inline int getRowCount() const { return rows; } const inline int getColCount() const { return cols; } virtual void accept(InternalMatrixVisitor<T_element>& visitor) = 0; virtual T_element getElementValue(const ElementIndex<matrix>& index) = 0; }; template<typename T_element> class ConventionalScalar : public InternalScalar<T_element> { private: T_element value; public: ConventionalScalar() : InternalScalar<T_element>(true), value(T_element(0)) { } ConventionalScalar(const T_element initialValue) : InternalScalar<T_element>(true), value(initialValue) { } virtual void allocate() { this->allocated=true; } virtual void accept(InternalScalarVisitor<T_element>& visitor) { visitor.visit(*this); } virtual T_element getElementValue() { assert(this->allocated); return value; } T_element* getValue() { assert(this->allocated); return &value; } }; template<typename T_element> class ConventionalVector : public InternalVector<T_element> { private: std::vector<T_element> value; public: ConventionalVector(const int rowCount) : InternalVector<T_element>(false, rowCount) { } ConventionalVector(const int rowCount, const T_element initialValue) : InternalVector<T_element>(true, rowCount), value(rowCount, initialValue) { } virtual void allocate() { if(!this->allocated) { value.resize(this->rows, T_element(0)); this->allocated=true; } } virtual void accept(InternalVectorVisitor<T_element>& visitor) { visitor.visit(*this); } T_element* getValue() { assert(this->allocated); return &value[0]; } virtual T_element getElementValue(const ElementIndex<vector>& index) { assert(this->allocated); return value[index.getRow()]; } }; template<typename T_element> class ConventionalMatrix : public InternalMatrix<T_element> { private: std::vector<T_element> value; public: ConventionalMatrix(const int rowCount, const int colCount) : InternalMatrix<T_element>(false, rowCount, colCount) { } ConventionalMatrix(const int rowCount, const int colCount, const T_element initialValue) : InternalMatrix<T_element>(true, rowCount, colCount), value(rowCount*colCount, initialValue) { } template<typename StreamType> ConventionalMatrix(StreamType& stream) : InternalMatrix<T_element>(true, stream.nrows(), stream.ncols()), value(stream.nrows()*stream.ncols(), T_element(0)) { while(!stream.eof()) { entry2<double> entry; stream >> entry; value[this->getColCount()*entry.row + entry.col] = entry.value; } } virtual void allocate() { if(!this->allocated) { value.resize(this->rows * this->cols, T_element(0)); this->allocated=true; } } virtual void accept(InternalMatrixVisitor<T_element>& visitor) { visitor.visit(*this); } T_element* getValue() { assert(this->allocated); return &value[0]; } virtual T_element getElementValue(const ElementIndex<matrix>& index) { assert(this->allocated); return value[(this->cols*index.getRow())+index.getCol()]; } }; template<typename T_elementType> class InternalScalarVisitor { public: virtual void visit(ConventionalScalar<T_elementType>& value) = 0; virtual ~InternalScalarVisitor() {} }; template<typename T_elementType> class InternalVectorVisitor { public: virtual void visit(ConventionalVector<T_elementType>& value) = 0; virtual ~InternalVectorVisitor() {} }; template<typename T_elementType> class InternalMatrixVisitor { public: virtual void visit(ConventionalMatrix<T_elementType>& value) = 0; virtual ~InternalMatrixVisitor() {} }; } } #endif <|endoftext|>
<commit_before>#ifndef HTOOL_PRECONDITIONER_HPP #define HTOOL_PRECONDITIONER_HPP #include "matrix.hpp" #include "lapack.hpp" #include "wrapper_mpi.hpp" #include "wrapper_hpddm.hpp" namespace htool{ template<template<typename> class LowRankMatrix, typename T> class DDM{ private: int n; int n_inside; const std::vector<int> neighbors; // const std::vector<int> cluster_to_ovr_subdomain; std::vector<std::vector<int> > intersections; std::vector<T> vec_ovr; std::vector<std::vector<T>> snd,rcv; HPDDMDense<LowRankMatrix,T> hpddm_op; std::vector<T> mat_loc; std::vector<double> D; MPI_Comm comm; mutable std::map<std::string, double> infos; public: DDM(const IMatrix<T>& mat0, const HMatrix<LowRankMatrix,T>& hmat_0, const std::vector<int>& ovr_subdomain_to_global0, const std::vector<int>& cluster_to_ovr_subdomain0, const std::vector<int>& neighbors0, const std::vector<std::vector<int> >& intersections0, MPI_Comm comm0=MPI_COMM_WORLD): hpddm_op(hmat_0), n(ovr_subdomain_to_global0.size()), n_inside(cluster_to_ovr_subdomain0.size()), neighbors(neighbors0), vec_ovr(n),mat_loc(n*n), D(n), comm(comm0) { // Timing std::vector<double> mytime(2), maxtime(2), meantime(2); double time = MPI_Wtime(); std::vector<int> renum(n,-1); std::vector<int> renum_to_global(n); for (int i=0;i<cluster_to_ovr_subdomain0.size();i++){ renum[cluster_to_ovr_subdomain0[i]]=i; renum_to_global[i]=ovr_subdomain_to_global0[cluster_to_ovr_subdomain0[i]]; } int count =cluster_to_ovr_subdomain0.size(); // std::cout << count << std::endl; for (int i=0;i<n;i++){ if (renum[i]==-1){ renum[i]=count; renum_to_global[count++]=ovr_subdomain_to_global0[i]; } } intersections.resize(neighbors.size()); for (int i=0;i<neighbors.size();i++){ intersections[i].resize(intersections0[i].size()); for (int j=0;j<intersections[i].size();j++){ intersections[i][j]=renum[intersections0[i][j]]; } } // Building Ai bool sym=false; const std::vector<int>& MyDiagFarFieldMats = hpddm_op.HA.get_MyDiagFarFieldMats(); const std::vector<int>& MyDiagNearFieldMats= hpddm_op.HA.get_MyDiagNearFieldMats(); // Internal dense blocks const std::vector<SubMatrix<T>>& MyNearFieldMats = hpddm_op.HA.get_MyNearFieldMats(); for (int i=0;i<MyDiagNearFieldMats.size();i++){ const SubMatrix<T>& submat = MyNearFieldMats[MyDiagNearFieldMats[i]]; int local_nr = submat.nb_rows(); int local_nc = submat.nb_cols(); int offset_i = submat.get_offset_i()-hpddm_op.HA.get_local_offset();; int offset_j = submat.get_offset_j()-hpddm_op.HA.get_local_offset(); for (int i=0;i<local_nc;i++){ std::copy_n(&(submat(0,i)),local_nr,&mat_loc[offset_i+(offset_j+i)*n]); } } // Internal compressed block const std::vector<LowRankMatrix<T>>& MyFarFieldMats = hpddm_op.HA.get_MyFarFieldMats(); Matrix<T> FarFielBlock(n,n); for (int i=0;i<MyDiagFarFieldMats.size();i++){ const LowRankMatrix<T>& lmat = MyFarFieldMats[MyDiagFarFieldMats[i]]; int local_nr = lmat.nb_rows(); int local_nc = lmat.nb_cols(); int offset_i = lmat.get_offset_i()-hpddm_op.HA.get_local_offset(); int offset_j = lmat.get_offset_j()-hpddm_op.HA.get_local_offset();; FarFielBlock.resize(local_nr,local_nc); lmat.get_whole_matrix(&(FarFielBlock(0,0))); for (int i=0;i<local_nc;i++){ std::copy_n(&(FarFielBlock(0,i)),local_nr,&mat_loc[offset_i+(offset_j+i)*n]); } } // Overlap std::vector<T> horizontal_block(n-n_inside,n_inside),vertical_block(n,n-n_inside); horizontal_block = mat0.get_submatrix(std::vector<int>(renum_to_global.begin()+n_inside,renum_to_global.end()),std::vector<int>(renum_to_global.begin(),renum_to_global.begin()+n_inside)).get_mat(); vertical_block = mat0.get_submatrix(renum_to_global,std::vector<int>(renum_to_global.begin()+n_inside,renum_to_global.end())).get_mat(); for (int j=0;j<n_inside;j++){ std::copy_n(horizontal_block.begin()+j*(n-n_inside),n-n_inside,&mat_loc[n_inside+j*n]); } for (int j=n_inside;j<n;j++){ std::copy_n(vertical_block.begin()+(j-n_inside)*n,n,&mat_loc[j*n]); } // mat_loc= mat0.get_submatrix(renum_to_global,renum_to_global).get_mat(); hpddm_op.initialize(n, sym, mat_loc.data(), neighbors, intersections); fill(D.begin(),D.begin()+n_inside,1); fill(D.begin()+n_inside,D.end(),0); hpddm_op.HPDDMDense<LowRankMatrix,T>::super::super::initialize(D.data()); mytime[0] = MPI_Wtime() - time; time = MPI_Wtime(); hpddm_op.callNumfact(); mytime[1] = MPI_Wtime() - time; // Timing MPI_Reduce(&(mytime[0]), &(maxtime[0]), 2, MPI_DOUBLE, MPI_MAX, 0,comm); MPI_Reduce(&(mytime[0]), &(meantime[0]), 2, MPI_DOUBLE, MPI_SUM, 0,comm); meantime /= hmat_0.get_sizeworld(); stats["DDM setup (mean)"]= meantime[0]; stats["DDM setup (max)" ]= maxtime[0]; stats["DDM facto (mean)"]= meantime[1]; stats["DDM facto (max)" ]= maxtime[1]; } void solve(const T* const rhs, T* const x){ // int rankWorld = hpddm_op.HA.get_rankworld(); int sizeWorld = hpddm_op.HA.get_sizeworld(); int offset = hpddm_op.HA.get_local_offset(); int size = hpddm_op.HA.get_local_size(); double time = MPI_Wtime(); // std::vector<T> rhs_perm(hpddm_op.HA.nb_cols()); std::vector<T> x_local(n,0); // Permutation hpddm_op.HA.source_to_cluster_permutation(rhs,rhs_perm.data()); // Local rhs std::vector<T> local_rhs(n,0); std::copy_n(rhs_perm.begin()+offset,n_inside,local_rhs.begin()); // TODO avoid com here // for (int i=0;i<n-n_inside;i++){ // local_rhs[i]=rhs_perm[] // } hpddm_op.exchange(local_rhs.data(), 1); // Solve HPDDM::IterativeMethod::solve(hpddm_op, local_rhs.data(), x_local.data(), 1,comm); // Local to global hpddm_op.HA.local_to_global(x_local.data(),hpddm_op.in_global->data()); // Permutation hpddm_op.HA.cluster_to_target_permutation(hpddm_op.in_global->data(),x); // Timing time = MPI_Wtime()-time; stats["Solve "] = time; } void print_infos() const{ if (hpddm_op.HA.get_rankworld()==0){ for (std::map<std::string,double>::const_iterator it = infos.begin() ; it != infos.end() ; ++it){ std::cout<<it->first<<"\t"<<it->second<<std::endl; } } std::cout << std::endl; } void save_infos(const std::string& outputname) const{ if (hpddm_op.HA.get_rankworld()==0){ std::ofstream outputfile(outputname); if (outputfile){ for (std::map<std::string,double>::const_iterator it = infos.begin() ; it != infos.end() ; ++it){ outputfile<<it->first<<" : "<<it->second<<std::endl; } outputfile.close(); } else{ std::cout << "Unable to create "<<outputname<<std::endl; } } } }; } #endif <commit_msg>fixed buf in ddm infos<commit_after>#ifndef HTOOL_PRECONDITIONER_HPP #define HTOOL_PRECONDITIONER_HPP #include "matrix.hpp" #include "lapack.hpp" #include "wrapper_mpi.hpp" #include "wrapper_hpddm.hpp" namespace htool{ template<template<typename> class LowRankMatrix, typename T> class DDM{ private: int n; int n_inside; const std::vector<int> neighbors; // const std::vector<int> cluster_to_ovr_subdomain; std::vector<std::vector<int> > intersections; std::vector<T> vec_ovr; std::vector<std::vector<T>> snd,rcv; HPDDMDense<LowRankMatrix,T> hpddm_op; std::vector<T> mat_loc; std::vector<double> D; MPI_Comm comm; mutable std::map<std::string, double> infos; public: DDM(const IMatrix<T>& mat0, const HMatrix<LowRankMatrix,T>& hmat_0, const std::vector<int>& ovr_subdomain_to_global0, const std::vector<int>& cluster_to_ovr_subdomain0, const std::vector<int>& neighbors0, const std::vector<std::vector<int> >& intersections0, MPI_Comm comm0=MPI_COMM_WORLD): hpddm_op(hmat_0), n(ovr_subdomain_to_global0.size()), n_inside(cluster_to_ovr_subdomain0.size()), neighbors(neighbors0), vec_ovr(n),mat_loc(n*n), D(n), comm(comm0) { // Timing std::vector<double> mytime(2), maxtime(2), meantime(2); double time = MPI_Wtime(); std::vector<int> renum(n,-1); std::vector<int> renum_to_global(n); for (int i=0;i<cluster_to_ovr_subdomain0.size();i++){ renum[cluster_to_ovr_subdomain0[i]]=i; renum_to_global[i]=ovr_subdomain_to_global0[cluster_to_ovr_subdomain0[i]]; } int count =cluster_to_ovr_subdomain0.size(); // std::cout << count << std::endl; for (int i=0;i<n;i++){ if (renum[i]==-1){ renum[i]=count; renum_to_global[count++]=ovr_subdomain_to_global0[i]; } } intersections.resize(neighbors.size()); for (int i=0;i<neighbors.size();i++){ intersections[i].resize(intersections0[i].size()); for (int j=0;j<intersections[i].size();j++){ intersections[i][j]=renum[intersections0[i][j]]; } } // Building Ai bool sym=false; const std::vector<int>& MyDiagFarFieldMats = hpddm_op.HA.get_MyDiagFarFieldMats(); const std::vector<int>& MyDiagNearFieldMats= hpddm_op.HA.get_MyDiagNearFieldMats(); // Internal dense blocks const std::vector<SubMatrix<T>>& MyNearFieldMats = hpddm_op.HA.get_MyNearFieldMats(); for (int i=0;i<MyDiagNearFieldMats.size();i++){ const SubMatrix<T>& submat = MyNearFieldMats[MyDiagNearFieldMats[i]]; int local_nr = submat.nb_rows(); int local_nc = submat.nb_cols(); int offset_i = submat.get_offset_i()-hpddm_op.HA.get_local_offset();; int offset_j = submat.get_offset_j()-hpddm_op.HA.get_local_offset(); for (int i=0;i<local_nc;i++){ std::copy_n(&(submat(0,i)),local_nr,&mat_loc[offset_i+(offset_j+i)*n]); } } // Internal compressed block const std::vector<LowRankMatrix<T>>& MyFarFieldMats = hpddm_op.HA.get_MyFarFieldMats(); Matrix<T> FarFielBlock(n,n); for (int i=0;i<MyDiagFarFieldMats.size();i++){ const LowRankMatrix<T>& lmat = MyFarFieldMats[MyDiagFarFieldMats[i]]; int local_nr = lmat.nb_rows(); int local_nc = lmat.nb_cols(); int offset_i = lmat.get_offset_i()-hpddm_op.HA.get_local_offset(); int offset_j = lmat.get_offset_j()-hpddm_op.HA.get_local_offset();; FarFielBlock.resize(local_nr,local_nc); lmat.get_whole_matrix(&(FarFielBlock(0,0))); for (int i=0;i<local_nc;i++){ std::copy_n(&(FarFielBlock(0,i)),local_nr,&mat_loc[offset_i+(offset_j+i)*n]); } } // Overlap std::vector<T> horizontal_block(n-n_inside,n_inside),vertical_block(n,n-n_inside); horizontal_block = mat0.get_submatrix(std::vector<int>(renum_to_global.begin()+n_inside,renum_to_global.end()),std::vector<int>(renum_to_global.begin(),renum_to_global.begin()+n_inside)).get_mat(); vertical_block = mat0.get_submatrix(renum_to_global,std::vector<int>(renum_to_global.begin()+n_inside,renum_to_global.end())).get_mat(); for (int j=0;j<n_inside;j++){ std::copy_n(horizontal_block.begin()+j*(n-n_inside),n-n_inside,&mat_loc[n_inside+j*n]); } for (int j=n_inside;j<n;j++){ std::copy_n(vertical_block.begin()+(j-n_inside)*n,n,&mat_loc[j*n]); } // mat_loc= mat0.get_submatrix(renum_to_global,renum_to_global).get_mat(); hpddm_op.initialize(n, sym, mat_loc.data(), neighbors, intersections); fill(D.begin(),D.begin()+n_inside,1); fill(D.begin()+n_inside,D.end(),0); hpddm_op.HPDDMDense<LowRankMatrix,T>::super::super::initialize(D.data()); mytime[0] = MPI_Wtime() - time; time = MPI_Wtime(); hpddm_op.callNumfact(); mytime[1] = MPI_Wtime() - time; // Timing MPI_Reduce(&(mytime[0]), &(maxtime[0]), 2, MPI_DOUBLE, MPI_MAX, 0,comm); MPI_Reduce(&(mytime[0]), &(meantime[0]), 2, MPI_DOUBLE, MPI_SUM, 0,comm); meantime /= hmat_0.get_sizeworld(); infos["DDM setup (mean)"]= meantime[0]; infos["DDM setup (max)" ]= maxtime[0]; infos["DDM facto (mean)"]= meantime[1]; infos["DDM facto (max)" ]= maxtime[1]; } void solve(const T* const rhs, T* const x){ // int rankWorld = hpddm_op.HA.get_rankworld(); int sizeWorld = hpddm_op.HA.get_sizeworld(); int offset = hpddm_op.HA.get_local_offset(); int size = hpddm_op.HA.get_local_size(); double time = MPI_Wtime(); // std::vector<T> rhs_perm(hpddm_op.HA.nb_cols()); std::vector<T> x_local(n,0); // Permutation hpddm_op.HA.source_to_cluster_permutation(rhs,rhs_perm.data()); // Local rhs std::vector<T> local_rhs(n,0); std::copy_n(rhs_perm.begin()+offset,n_inside,local_rhs.begin()); // TODO avoid com here // for (int i=0;i<n-n_inside;i++){ // local_rhs[i]=rhs_perm[] // } hpddm_op.exchange(local_rhs.data(), 1); // Solve HPDDM::IterativeMethod::solve(hpddm_op, local_rhs.data(), x_local.data(), 1,comm); // Local to global hpddm_op.HA.local_to_global(x_local.data(),hpddm_op.in_global->data()); // Permutation hpddm_op.HA.cluster_to_target_permutation(hpddm_op.in_global->data(),x); // Timing time = MPI_Wtime()-time; infos["Solve "] = time; } void print_infos() const{ if (hpddm_op.HA.get_rankworld()==0){ for (std::map<std::string,double>::const_iterator it = infos.begin() ; it != infos.end() ; ++it){ std::cout<<it->first<<"\t"<<it->second<<std::endl; } } std::cout << std::endl; } void save_infos(const std::string& outputname) const{ if (hpddm_op.HA.get_rankworld()==0){ std::ofstream outputfile(outputname); if (outputfile){ for (std::map<std::string,double>::const_iterator it = infos.begin() ; it != infos.end() ; ++it){ outputfile<<it->first<<" : "<<it->second<<std::endl; } outputfile.close(); } else{ std::cout << "Unable to create "<<outputname<<std::endl; } } } }; } #endif <|endoftext|>
<commit_before>#ifndef IM_STR_CONFIG_HPP #define IM_STR_CONFIG_HPP // clang format doesn't indent neste #if blocks, so lets do it manually // clang-format off // In c++20, our destructor can be declared constexpr // that then propagetes to many member functions of im_str. #ifndef IM_STR_USE_CONSTEXPR_DESTRUCTOR #if __cpp_constexpr >= 201907 #define IM_STR_USE_CONSTEXPR_DESTRUCTOR 1 #define IM_STR_CONSTEXPR_DESTRUCTOR constexpr #else #define IM_STR_USE_CONSTEXPR_DESTRUCTOR 0 #define IM_STR_CONSTEXPR_DESTRUCTOR #endif #endif // !IM_STR_CONSTEXPR_DESTRUCTOR // Handle custom allocation logic via pmr memory_resource #ifndef IM_STR_USE_ALLOC // default to no and overwrite later if appropriate #define IM_STR_USE_ALLOC 0 #if __has_include( <memory_resource>) #include <memory_resource> #if defined( __cpp_lib_memory_resource ) && __cpp_lib_memory_resource >= 201603L #undef IM_STR_USE_ALLOC #define IM_STR_USE_ALLOC 1 #endif #endif #endif #ifndef IM_STR_USE_CUSTOM_DYN_ARRAY #define IM_STR_USE_CUSTOM_DYN_ARRAY 1 #define IM_STR_DYN_ARRAY_ABI_NAME #else #define IM_STR_USE_CUSTOM_DYN_ARRAY 0 #define IM_STR_DYN_ARRAY_ABI_NAME no_custom_dyn_array #endif #define IM_STR_ABI_NAME im_str_abi_ns_ ## IM_STR_DYN_ARRAY_ABI_NAME // clang-format on #endif<commit_msg>[config] Remove abi namespace machinery<commit_after>#ifndef IM_STR_CONFIG_HPP #define IM_STR_CONFIG_HPP // clang format doesn't indent neste #if blocks, so lets do it manually // clang-format off // In c++20, our destructor can be declared constexpr // that then propagetes to many member functions of im_str. #ifndef IM_STR_USE_CONSTEXPR_DESTRUCTOR #if __cpp_constexpr >= 201907 #define IM_STR_USE_CONSTEXPR_DESTRUCTOR 1 #define IM_STR_CONSTEXPR_DESTRUCTOR constexpr #else #define IM_STR_USE_CONSTEXPR_DESTRUCTOR 0 #define IM_STR_CONSTEXPR_DESTRUCTOR #endif #endif // !IM_STR_CONSTEXPR_DESTRUCTOR // Handle custom allocation logic via pmr memory_resource #ifndef IM_STR_USE_ALLOC // default to no and overwrite later if appropriate #define IM_STR_USE_ALLOC 0 #if __has_include( <memory_resource>) #include <memory_resource> #if defined( __cpp_lib_memory_resource ) && __cpp_lib_memory_resource >= 201603L #undef IM_STR_USE_ALLOC #define IM_STR_USE_ALLOC 1 #endif #endif #endif #ifndef IM_STR_USE_CUSTOM_DYN_ARRAY #define IM_STR_USE_CUSTOM_DYN_ARRAY 1 #else #define IM_STR_USE_CUSTOM_DYN_ARRAY 0 #endif // clang-format on #endif<|endoftext|>
<commit_before>#ifndef KGR_KANGARU_INCLUDE_KANGARU_DETAIL_ERROR_HPP #define KGR_KANGARU_INCLUDE_KANGARU_DETAIL_ERROR_HPP #include "traits.hpp" #include "service_traits.hpp" namespace kgr { namespace detail { template<typename T, typename... Args> struct ServiceError { template<typename Arg, typename Service = T, enable_if_t< is_service<Arg>::value && !dependency_trait<is_service_constructible, Service, Arg, Args...>::value && is_service_constructible<Service, Arg, Args...>::value, int> = 0> ServiceError(Arg&&) { static_assert(false_t<Arg>::value, "One or more dependencies are not constructible with it's dependencies as constructor argument. " "Please check that dependency's constructor and it's dependencies." ); } template<typename Service = T, enable_if_t< is_service<Service>::value && !dependency_trait<is_service_constructible, Service>::value && is_service_constructible<Service>::value, int> = 0> ServiceError() { static_assert(false_t<Service>::value, "One or more dependencies are not constructible with it's dependencies as constructor argument. " "Please check that dependency's constructor and dependencies." ); } template<typename Arg, typename Service = T, enable_if_t< is_service<Service>::value && !is_service_constructible<Service, Arg, Args...>::value && !is_service_constructible<Service>::value, int> = 0> ServiceError(Arg&&) { static_assert(false_t<Arg>::value, "The service type is not constructible given it's dependencies and passed arguments. " "Ensure that dependencies are correctly configured and you pass the right set of parameters." ); } template<typename Arg, typename Service = T, enable_if_t< is_service<Service>::value && !is_service_constructible<Service, Arg, Args...>::value && is_service_constructible<Service>::value, int> = 0> ServiceError(Arg&&) { static_assert(false_t<Arg>::value, "The service type is not constructible given passed arguments to kgr::Container::service(...)."); } template<typename Service = T, enable_if_t<is_service<Service>::value && !is_service_constructible<Service>::value, int> = 0> ServiceError() { static_assert(false_t<Service>::value, "The service type is not constructible given it's dependencies. " "Check if dependencies are configured correctly and if the service has the required constructor." ); } template<typename Service = T, enable_if_t<!is_service<Service>::value && !has_forward<Service>::value, int> = 0> ServiceError() { static_assert(false_t<Service>::value, "The type sent to kgr::Container::service(...) is not a service."); } template<typename Service = T, enable_if_t<!is_service<Service>::value && has_forward<Service>::value, int> = 0> ServiceError() { static_assert(false_t<Service>::value, "The service type must not not contain any virtual function or must be abstract."); } }; struct NotInvokableError { template<typename T = void> NotInvokableError(...) { static_assert(false_t<T>::value, "The function sent is not invokable. Ensure to include all services definitions " "you need and that received parameters are correct." ); } }; } // namespace detail } // namespace kgr #endif // KGR_KANGARU_INCLUDE_KANGARU_DETAIL_ERROR_HPP <commit_msg>added errors for malformed construct function<commit_after>#ifndef KGR_KANGARU_INCLUDE_KANGARU_DETAIL_ERROR_HPP #define KGR_KANGARU_INCLUDE_KANGARU_DETAIL_ERROR_HPP #include "traits.hpp" #include "single.hpp" #include "service_traits.hpp" namespace kgr { namespace detail { template<typename T, typename... Args> struct ServiceError { template<typename Arg, typename Service = T, enable_if_t< is_service<Arg>::value && dependency_trait<is_construct_function_callable, Service, Arg, Args...>::value && !dependency_trait<is_service_constructible, Service, Arg, Args...>::value && is_service_constructible<Service, Arg, Args...>::value, int> = 0> ServiceError(Arg&&) { static_assert(false_t<Arg>::value, "One or more dependencies are not constructible with it's dependencies as constructor argument. " "Please check that dependency's constructor and it's dependencies." ); } template<typename Service = T, enable_if_t< is_service<Service>::value && dependency_trait<is_construct_function_callable, Service>::value && !dependency_trait<is_service_constructible, Service>::value && is_service_constructible<Service>::value, int> = 0> ServiceError() { static_assert(false_t<Service>::value, "One or more dependencies are not constructible with it's dependencies as constructor argument. " "Please check that dependency's constructor and dependencies." ); } template<typename Arg, typename Service = T, enable_if_t< is_service<Arg>::value && !dependency_trait<is_construct_function_callable, Service, Arg, Args...>::value && is_construct_function_callable<Service, Arg, Args...>::value && is_service_constructible<Service, Arg, Args...>::value, int> = 0> ServiceError(Arg&&) { static_assert(false_t<Arg>::value, "One or more dependencies construct function cannot be called when calling kgr::Container::service<Dependency>(). " "Please check that dependency's construct function and ensure that is well formed." ); } template<typename Service = T, enable_if_t< is_service<Service>::value && !dependency_trait<is_construct_function_callable, Service>::value && is_construct_function_callable<Service>::value && is_service_constructible<Service>::value, int> = 0> ServiceError() { static_assert(false_t<Service>::value, "One or more dependencies construct function cannot be called when calling kgr::Container::service<Dependency>(). " "Please check that dependency's construct function and ensure that is well formed." ); } template<typename Arg, typename Service = T, enable_if_t< is_service<Service>::value && !is_service_constructible<Service, Arg, Args...>::value && !is_service_constructible<Service>::value, int> = 0> ServiceError(Arg&&) { static_assert(false_t<Arg>::value, "The service type is not constructible given it's dependencies and passed arguments. " "Ensure that dependencies are correctly configured and you pass the right set of parameters." ); } template<typename Arg, typename Service = T, enable_if_t< is_service<Service>::value && !is_service_constructible<Service, Arg, Args...>::value && is_service_constructible<Service>::value, int> = 0> ServiceError(Arg&&) { static_assert(false_t<Arg>::value, "The service type is not constructible given passed arguments to kgr::Container::service(...)."); } template<typename Service = T, enable_if_t< is_service<Service>::value && is_construct_function_callable<Service>::value && !is_service_constructible<Service>::value, int> = 0> ServiceError() { static_assert(false_t<Service>::value, "The service type is not constructible given it's dependencies. " "Check if dependencies are configured correctly and if the service has the required constructor." ); } template<typename Service = T, enable_if_t< is_service<Service>::value && is_single<Service>::value && !is_construct_function_callable<Service>::value, int> = 0> ServiceError() { static_assert(false_t<Service>::value, "The service construct function cannot be called. " "Check if the construct function is well formed, receive injected arguments first and additional parameters at the end." ); } template<typename Service = T, enable_if_t< is_service<Service>::value && !is_single<Service>::value && !is_construct_function_callable<Service>::value, int> = 0> ServiceError() { static_assert(false_t<Service>::value, "The service construct function cannot be called without arguments, or is not well formed. " "Check if the construct function is well formed, receive injected arguments first and additional parameters at the end." ); } template<typename Arg, typename Service = T, enable_if_t< is_service<Service>::value && !is_single<Service>::value && !is_construct_function_callable<Service, Arg, Args...>::value, int> = 0> ServiceError(Arg&&) { static_assert(false_t<Service>::value, "The service construct function cannot be called. " "Check if the construct function is well formed, receive injected arguments first and additional parameters at the end." ); } template<typename Service = T, enable_if_t<!is_service<Service>::value && !has_forward<Service>::value, int> = 0> ServiceError() { static_assert(false_t<Service>::value, "The type sent to kgr::Container::service(...) is not a service."); } template<typename Service = T, enable_if_t<!is_service<Service>::value && has_forward<Service>::value, int> = 0> ServiceError() { static_assert(false_t<Service>::value, "The service type must not not contain any virtual function or must be abstract."); } }; struct NotInvokableError { template<typename T = void> NotInvokableError(...) { static_assert(false_t<T>::value, "The function sent is not invokable. Ensure to include all services definitions " "you need and that received parameters are correct." ); } }; } // namespace detail } // namespace kgr #endif // KGR_KANGARU_INCLUDE_KANGARU_DETAIL_ERROR_HPP <|endoftext|>
<commit_before>#ifndef LIBPORT_SINGLETON_PTR_HH # define LIBPORT_SINGLETON_PTR_HH # define STATIC_INSTANCE(Cl, Name) \ class Cl ## Name; \ libport::SingletonPtr<Cl ## Name> Name; \ template<> Cl ## Name* libport::SingletonPtr<Cl ## Name>::ptr = 0 # define STATIC_INSTANCE_DECL(Cl, Name) \ class Cl ## Name \ : public Cl \ {}; \ STATIC_INSTANCE(Cl, Name) # define EXTERN_STATIC_INSTANCE(Cl, Name) \ class Cl ## Name \ : public Cl \ {}; \ extern libport::SingletonPtr<Cl ## Name> Name; \ template <> extern Cl ## Name* libport::SingletonPtr<Cl ## Name>::ptr namespace libport { /// Singleton smart pointer that creates the object on demand. template<class T> class SingletonPtr { public: operator T* () { return instance(); } operator T& () { return *instance(); } T* operator ->() { return instance(); } private: static T* instance() { if (!ptr) ptr = new T(); return ptr; } static T* ptr; }; } // namespace libport #endif // !LIBPORT_SINGLETON_PTR_HH <commit_msg>Remove useless extern keyword.<commit_after>#ifndef LIBPORT_SINGLETON_PTR_HH # define LIBPORT_SINGLETON_PTR_HH # define STATIC_INSTANCE(Cl, Name) \ class Cl ## Name; \ libport::SingletonPtr<Cl ## Name> Name; \ template<> Cl ## Name* libport::SingletonPtr<Cl ## Name>::ptr = 0 # define STATIC_INSTANCE_DECL(Cl, Name) \ class Cl ## Name \ : public Cl \ {}; \ STATIC_INSTANCE(Cl, Name) # define EXTERN_STATIC_INSTANCE(Cl, Name) \ class Cl ## Name \ : public Cl \ {}; \ extern libport::SingletonPtr<Cl ## Name> Name; \ template <> Cl ## Name* libport::SingletonPtr<Cl ## Name>::ptr namespace libport { /// Singleton smart pointer that creates the object on demand. template<class T> class SingletonPtr { public: operator T* () { return instance(); } operator T& () { return *instance(); } T* operator ->() { return instance(); } private: static T* instance() { if (!ptr) ptr = new T(); return ptr; } static T* ptr; }; } // namespace libport #endif // !LIBPORT_SINGLETON_PTR_HH <|endoftext|>
<commit_before>#pragma once #include <NvInfer.h> #include <DO/Shakti/Utilities/ErrorCheck.hpp> #include <array> #include <functional> #include <iostream> #include <map> #include <memory> #include <string> #include <vector> namespace DO::Sara::TensorRT { //! @ingroup NeuralNetworks //! @defgroup TensorRT //! @{ class Logger : public nvinfer1::ILogger { public: static auto instance() -> Logger& { static Logger instance; return instance; } void log(Severity severity, const char* msg) override { if (severity != Severity::kINFO) std::cout << msg << std::endl; } }; inline auto delete_cuda_stream(cudaStream_t* cuda_stream) { SHAKTI_STDOUT << "DELETING CUDA STREAM" << std::endl; if (cuda_stream == nullptr) return; SHAKTI_SAFE_CUDA_CALL(cudaStreamDestroy(*cuda_stream)); cuda_stream = nullptr; } inline auto delete_network_def(nvinfer1::INetworkDefinition* network_def) { SHAKTI_STDOUT << "DELETING NETWORK DEFINITION" << std::endl; if (network_def == nullptr) return; network_def->destroy(); network_def = nullptr; } inline auto delete_builder(nvinfer1::IBuilder* builder) { SHAKTI_STDOUT << "DELETING BUILDER" << std::endl; if (builder == nullptr) return; builder->destroy(); builder = nullptr; }; inline auto make_cuda_stream() -> std::unique_ptr<cudaStream_t, decltype(&delete_cuda_stream)> { auto cuda_stream_ptr = new cudaStream_t{}; SHAKTI_SAFE_CUDA_CALL(cudaStreamCreate(cuda_stream_ptr)); return {cuda_stream_ptr, &delete_cuda_stream}; } inline auto make_builder() -> std::unique_ptr<nvinfer1::IBuilder, decltype(&delete_builder)> { return {nvinfer1::createInferBuilder(Logger::instance()), &delete_builder}; } inline auto make_network(nvinfer1::IBuilder* builder) -> std::unique_ptr<nvinfer1::INetworkDefinition, decltype(&delete_network_def)> { return {builder->createNetworkV2(0u), &delete_network_def}; } class Network { public: using unique_net_ptr_type = decltype(make_network(std::declval<nvinfer1::IBuilder*>())); using model_weights_dict_type = std::map<std::string, std::vector<float>>; Network(nvinfer1::IBuilder* builder) : _model{make_network(builder)} { } inline auto model() { return _model.get(); } inline auto weights() -> model_weights_dict_type& { return _model_weights; } static auto set_current(Network& net) { _current_network = &net; } static auto current() -> Network& { if (_current_network == nullptr) throw std::runtime_error{"Error: the current network is invalid!"}; return *_current_network; } static auto current_var_index() -> int { return _current_var_index; } static auto increment_current_var_index() -> int { return ++_current_var_index; } private: static Network* _current_network; static int _current_var_index; private: unique_net_ptr_type _model; model_weights_dict_type _model_weights; }; Network* Network::_current_network = nullptr; int Network::_current_var_index = 0; inline auto make_placeholder(const std::array<int, 3>& chw_sizes, const std::string& name = "image") { auto net = Network::current().model(); auto data = net->addInput( name.c_str(), nvinfer1::DataType::kFLOAT, nvinfer1::Dims3{chw_sizes[0], chw_sizes[1], chw_sizes[2]}); return data; } inline auto operator*(nvinfer1::ITensor& x, const std::pair<float, std::string>& y) -> nvinfer1::ITensor& { auto model = Network::current().model(); auto weights = Network::current().weights(); const auto [y_value, y_name] = y; weights[y_name] = {y_value}; const auto y_weights = nvinfer1::Weights{nvinfer1::DataType::kFLOAT, reinterpret_cast<const void*>(weights[y_name].data()), static_cast<std::int64_t>(weights[y_name].size())}; const auto scale_op = model->addScale(x, nvinfer1::ScaleMode::kELEMENTWISE, {}, y_weights, {}); auto x_div_y = scale_op->getOutput(0); return *x_div_y; } inline auto operator/(nvinfer1::ITensor& x, const std::pair<float, std::string>& y) -> nvinfer1::ITensor& { return x * make_pair(1 / y.first, y.second); } inline auto operator*(nvinfer1::ITensor& x, float y) -> nvinfer1::ITensor& { const auto y_name = "weights/" + std::to_string(Network::current_var_index()); Network::increment_current_var_index(); return x * std::make_pair(y, y_name); } inline auto operator/(nvinfer1::ITensor& x, float y) -> nvinfer1::ITensor& { return x * (1 / y); } inline auto conv_2d(nvinfer1::ITensor& x, // int num_filters, // nvinfer1::DimsHW kernel_sizes, // const std::vector<float>& w = {}, // const std::vector<float>& b = {}, const std::string& name = {}) // -> nvinfer1::ITensor& { auto model = Network::current().model(); auto weights = Network::current().weights(); auto w_name = std::string{}; auto b_name = std::string{}; if (name.empty()) { w_name = "weights/" + std::to_string(Network::current_var_index()); weights[w_name] = w; Network::increment_current_var_index(); b_name = "weights/" + std::to_string(Network::current_var_index()); weights[b_name] = b; Network::increment_current_var_index(); } else { w_name = "conv/weights/" + std::to_string(Network::current_var_index()); if (weights.find(w_name) != weights.end()) throw std::runtime_error{ "Error: convolution weight name already used!"}; weights[w_name] = w; b_name = "conv/bias/" + std::to_string(Network::current_var_index()); if (weights.find(b_name) != weights.end()) throw std::runtime_error{"Error: convolution bias name already used!"}; weights[b_name] = w; } const auto w_weights = nvinfer1::Weights{nvinfer1::DataType::kFLOAT, reinterpret_cast<const void*>(weights[w_name].data()), static_cast<std::int64_t>(weights[w_name].size())}; const auto b_weights = nvinfer1::Weights{nvinfer1::DataType::kFLOAT, reinterpret_cast<const void*>(weights[b_name].data()), static_cast<std::int64_t>(weights[b_name].size())}; const auto conv_op = model->addConvolution(x, num_filters, kernel_sizes, w_weights, b_weights); auto y = conv_op->getOutput(0); return *y; } //! @} } // namespace DO::Sara::TensorRT <commit_msg>MAINT: fix memory leak.<commit_after>#pragma once #include <NvInfer.h> #include <DO/Shakti/Utilities/ErrorCheck.hpp> #include <array> #include <functional> #include <iostream> #include <map> #include <memory> #include <string> #include <vector> namespace DO::Sara::TensorRT { //! @ingroup NeuralNetworks //! @defgroup TensorRT //! @{ class Logger : public nvinfer1::ILogger { public: static auto instance() -> Logger& { static Logger instance; return instance; } void log(Severity severity, const char* msg) override { if (severity != Severity::kINFO) std::cout << msg << std::endl; } }; inline auto delete_cuda_stream(cudaStream_t* cuda_stream) { SHAKTI_STDOUT << "DELETING CUDA STREAM" << std::endl; if (cuda_stream == nullptr) return; SHAKTI_SAFE_CUDA_CALL(cudaStreamDestroy(*cuda_stream)); delete cuda_stream; cuda_stream = nullptr; } inline auto delete_network_def(nvinfer1::INetworkDefinition* network_def) { SHAKTI_STDOUT << "DELETING NETWORK DEFINITION" << std::endl; if (network_def == nullptr) return; network_def->destroy(); network_def = nullptr; } inline auto delete_builder(nvinfer1::IBuilder* builder) { SHAKTI_STDOUT << "DELETING BUILDER" << std::endl; if (builder == nullptr) return; builder->destroy(); builder = nullptr; }; inline auto make_cuda_stream() -> std::unique_ptr<cudaStream_t, decltype(&delete_cuda_stream)> { auto cuda_stream_ptr = new cudaStream_t{}; SHAKTI_SAFE_CUDA_CALL(cudaStreamCreate(cuda_stream_ptr)); return {cuda_stream_ptr, &delete_cuda_stream}; } inline auto make_builder() -> std::unique_ptr<nvinfer1::IBuilder, decltype(&delete_builder)> { return {nvinfer1::createInferBuilder(Logger::instance()), &delete_builder}; } inline auto make_network(nvinfer1::IBuilder* builder) -> std::unique_ptr<nvinfer1::INetworkDefinition, decltype(&delete_network_def)> { return {builder->createNetworkV2(0u), &delete_network_def}; } class Network { public: using unique_net_ptr_type = decltype(make_network(std::declval<nvinfer1::IBuilder*>())); using model_weights_dict_type = std::map<std::string, std::vector<float>>; Network(nvinfer1::IBuilder* builder) : _model{make_network(builder)} { } inline auto model() { return _model.get(); } inline auto weights() -> model_weights_dict_type& { return _model_weights; } static auto set_current(Network& net) { _current_network = &net; } static auto current() -> Network& { if (_current_network == nullptr) throw std::runtime_error{"Error: the current network is invalid!"}; return *_current_network; } static auto current_var_index() -> int { return _current_var_index; } static auto increment_current_var_index() -> int { return ++_current_var_index; } private: static Network* _current_network; static int _current_var_index; private: unique_net_ptr_type _model; model_weights_dict_type _model_weights; }; Network* Network::_current_network = nullptr; int Network::_current_var_index = 0; inline auto make_placeholder(const std::array<int, 3>& chw_sizes, const std::string& name = "image") { auto net = Network::current().model(); auto data = net->addInput( name.c_str(), nvinfer1::DataType::kFLOAT, nvinfer1::Dims3{chw_sizes[0], chw_sizes[1], chw_sizes[2]}); return data; } inline auto operator*(nvinfer1::ITensor& x, const std::pair<float, std::string>& y) -> nvinfer1::ITensor& { auto model = Network::current().model(); auto weights = Network::current().weights(); const auto [y_value, y_name] = y; weights[y_name] = {y_value}; const auto y_weights = nvinfer1::Weights{nvinfer1::DataType::kFLOAT, reinterpret_cast<const void*>(weights[y_name].data()), static_cast<std::int64_t>(weights[y_name].size())}; const auto scale_op = model->addScale(x, nvinfer1::ScaleMode::kELEMENTWISE, {}, y_weights, {}); auto x_div_y = scale_op->getOutput(0); return *x_div_y; } inline auto operator/(nvinfer1::ITensor& x, const std::pair<float, std::string>& y) -> nvinfer1::ITensor& { return x * make_pair(1 / y.first, y.second); } inline auto operator*(nvinfer1::ITensor& x, float y) -> nvinfer1::ITensor& { const auto y_name = "weights/" + std::to_string(Network::current_var_index()); Network::increment_current_var_index(); return x * std::make_pair(y, y_name); } inline auto operator/(nvinfer1::ITensor& x, float y) -> nvinfer1::ITensor& { return x * (1 / y); } inline auto conv_2d(nvinfer1::ITensor& x, // int num_filters, // nvinfer1::DimsHW kernel_sizes, // const std::vector<float>& w = {}, // const std::vector<float>& b = {}, const std::string& name = {}) // -> nvinfer1::ITensor& { auto model = Network::current().model(); auto weights = Network::current().weights(); auto w_name = std::string{}; auto b_name = std::string{}; if (name.empty()) { w_name = "weights/" + std::to_string(Network::current_var_index()); weights[w_name] = w; Network::increment_current_var_index(); b_name = "weights/" + std::to_string(Network::current_var_index()); weights[b_name] = b; Network::increment_current_var_index(); } else { w_name = "conv/weights/" + std::to_string(Network::current_var_index()); if (weights.find(w_name) != weights.end()) throw std::runtime_error{ "Error: convolution weight name already used!"}; weights[w_name] = w; b_name = "conv/bias/" + std::to_string(Network::current_var_index()); if (weights.find(b_name) != weights.end()) throw std::runtime_error{"Error: convolution bias name already used!"}; weights[b_name] = w; } const auto w_weights = nvinfer1::Weights{nvinfer1::DataType::kFLOAT, reinterpret_cast<const void*>(weights[w_name].data()), static_cast<std::int64_t>(weights[w_name].size())}; const auto b_weights = nvinfer1::Weights{nvinfer1::DataType::kFLOAT, reinterpret_cast<const void*>(weights[b_name].data()), static_cast<std::int64_t>(weights[b_name].size())}; const auto conv_op = model->addConvolution(x, num_filters, kernel_sizes, w_weights, b_weights); auto y = conv_op->getOutput(0); return *y; } //! @} } // namespace DO::Sara::TensorRT <|endoftext|>
<commit_before>/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ #include <aws/core/Aws.h> #include <aws/core/utils/threading/Semaphore.h> #include <aws/core/auth/AWSCredentialsProviderChain.h> #include <aws/transcribestreaming/TranscribeStreamingServiceClient.h> #include <aws/transcribestreaming/model/StartStreamTranscriptionHandler.h> #include <aws/transcribestreaming/model/StartStreamTranscriptionRequest.h> #include <aws/core/platform/FileSystem.h> #include <fstream> #include <cstdio> #include <chrono> #include <thread> using namespace Aws; using namespace Aws::TranscribeStreamingService; using namespace Aws::TranscribeStreamingService::Model; //TODO: Update path to location of local .wav test file. static const char FILE_NAME[] = "../transcribe-test-file.wav"; int main() { Aws::SDKOptions options; options.loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Trace; Aws::InitAPI(options); { //TODO: Set to the region of your AWS account. const Aws::String region = Aws::Region::US_WEST_2; Aws::Utils::Threading::Semaphore received(0 /*initialCount*/, 1 /*maxCount*/); //Load a profile that has been granted AmazonTranscribeFullAccess AWS managed permission policy. Aws::Client::ClientConfiguration config; #ifdef _WIN32 // ATTENTION: On Windows, this example only runs if the SDK is built with the curl library. (9/15/2022) // See the accompanying ReadMe. // See "Building the SDK for Windows with curl". // https://docs.aws.amazon.com/sdk-for-cpp/v1/developer-guide/setup-windows.html //TODO(User): Update to location of your .crt file. config.caFile = "C:/curl/bin/curl-ca-bundle.crt"; #endif config.region = region; TranscribeStreamingServiceClient client(config); StartStreamTranscriptionHandler handler; handler.SetOnErrorCallback([](const Aws::Client::AWSError<TranscribeStreamingServiceErrors>& error) { printf("ERROR: %s", error.GetMessage().c_str()); }); //SetTranscriptEventCallback called for every 'chunk' of file transcripted. Partial results are returned in real time. handler.SetTranscriptEventCallback([&received](const TranscriptEvent& ev) { for (auto&& r : ev.GetTranscript().GetResults()) { if (r.GetIsPartial()) { printf("[partial] "); } else { printf("[Final] "); } for (auto&& alt : r.GetAlternatives()) { printf("%s\n", alt.GetTranscript().c_str()); } } received.Release(); }); StartStreamTranscriptionRequest request; request.SetMediaSampleRateHertz(8000); request.SetLanguageCode(LanguageCode::en_US); request.SetMediaEncoding(MediaEncoding::pcm); //wav and aiff files are PCM formats request.SetEventStreamHandler(handler); auto OnStreamReady = [](AudioStream& stream) { Aws::FStream file(FILE_NAME, std::ios_base::in | std::ios_base::binary); if (!file.is_open()) { std::cout << "Failed to open " << FILE_NAME << '\n'; } char buf[1024]; int i = 0; while (file) { file.read(buf, sizeof(buf)); if (!file) std::cout << "File: only " << file.gcount() << " could be read"; Aws::Vector<unsigned char> bits{ buf, buf + file.gcount() }; AudioEvent event(std::move(bits)); if (!stream) { printf("Failed to create a stream\n"); break; } //The std::basic_istream::gcount() is used to count the characters in the given string. It returns //the number of characters extracted by the last read() operation. if (file.gcount() > 0) { if (!stream.WriteAudioEvent(event)) { printf("Failed to write an audio event\n"); break; } } else { break; } std::this_thread::sleep_for(std::chrono::milliseconds(25)); // Slow down since we are streaming from a file. } if (!stream.WriteAudioEvent(AudioEvent())) { // Per the spec, we have to send an empty event (i.e. without a payload) at the end. printf("Failed to send an empty frame\n"); } else { printf("Successfully sent the empty frame\n"); } stream.flush(); std::this_thread::sleep_for(std::chrono::milliseconds(10000)); // Workaround to prevent an error at the end of the stream for this contrived example. stream.Close(); }; Aws::Utils::Threading::Semaphore signaling(0 /*initialCount*/, 1 /*maxCount*/); auto OnResponseCallback = [&signaling](const TranscribeStreamingServiceClient*, const Model::StartStreamTranscriptionRequest&, const Model::StartStreamTranscriptionOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) { signaling.Release(); }; printf("Starting...\n"); client.StartStreamTranscriptionAsync(request, OnStreamReady, OnResponseCallback, nullptr /*context*/); signaling.WaitOne(); // Prevent the application from exiting until we're done. printf("Done\n"); } Aws::ShutdownAPI(options); return 0; }<commit_msg>clang-tidy changes<commit_after>/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ #include <aws/core/Aws.h> #include <aws/core/utils/threading/Semaphore.h> #include <aws/core/auth/AWSCredentialsProviderChain.h> #include <aws/transcribestreaming/TranscribeStreamingServiceClient.h> #include <aws/transcribestreaming/model/StartStreamTranscriptionHandler.h> #include <aws/transcribestreaming/model/StartStreamTranscriptionRequest.h> #include <aws/core/platform/FileSystem.h> #include <fstream> #include <cstdio> #include <chrono> #include <thread> #include <array> using namespace Aws; using namespace Aws::TranscribeStreamingService; using namespace Aws::TranscribeStreamingService::Model; //TODO(User): Update path to location of local .wav test file. static const Aws::String FILE_NAME{"../transcribe-test-file.wav"}; int main() { Aws::SDKOptions options; options.loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Trace; Aws::InitAPI(options); { //TODO(User): Set to the region of your AWS account. const Aws::String region = Aws::Region::US_WEST_2; Aws::Utils::Threading::Semaphore received(0 /*initialCount*/, 1 /*maxCount*/); //Load a profile that has been granted AmazonTranscribeFullAccess AWS managed permission policy. Aws::Client::ClientConfiguration config; #ifdef _WIN32 // ATTENTION: On Windows, this example only runs if the SDK is built with the curl library. (9/15/2022) // See the accompanying ReadMe. // See "Building the SDK for Windows with curl". // https://docs.aws.amazon.com/sdk-for-cpp/v1/developer-guide/setup-windows.html //TODO(User): Update to location of your .crt file. config.caFile = "C:/curl/bin/curl-ca-bundle.crt"; #endif config.region = region; TranscribeStreamingServiceClient client(config); StartStreamTranscriptionHandler handler; handler.SetOnErrorCallback([](const Aws::Client::AWSError<TranscribeStreamingServiceErrors>& error) { std::cerr << "ERROR: " + error.GetMessage() << std::endl; }); //SetTranscriptEventCallback called for every 'chunk' of file transcripted. Partial results are returned in real time. handler.SetTranscriptEventCallback([&received](const TranscriptEvent& ev) { for (auto&& r : ev.GetTranscript().GetResults()) { if (r.GetIsPartial()) { std::cout << "[partial] "; } else { std::cout << "[Final] "; } for (auto&& alt : r.GetAlternatives()) { std::cout << alt.GetTranscript() << std::endl; } } received.Release(); }); StartStreamTranscriptionRequest request; request.SetMediaSampleRateHertz(8000); request.SetLanguageCode(LanguageCode::en_US); request.SetMediaEncoding(MediaEncoding::pcm); //wav and aiff files are PCM formats request.SetEventStreamHandler(handler); auto OnStreamReady = [](AudioStream& stream) { Aws::FStream file(FILE_NAME, std::ios_base::in | std::ios_base::binary); if (!file.is_open()) { std::cerr << "Failed to open " << FILE_NAME << '\n'; } std::array<char,1024> buf; int i = 0; while (file) { file.read(buf.begin(), buf.size()); if (!file) std::cout << "File: only " << file.gcount() << " could be read" << std::endl; Aws::Vector<unsigned char> bits{ buf.begin(), buf.begin() + file.gcount() }; AudioEvent event(std::move(bits)); if (!stream) { std::cerr << "Failed to create a stream" << std::endl; break; } //The std::basic_istream::gcount() is used to count the characters in the given string. It returns //the number of characters extracted by the last read() operation. if (file.gcount() > 0) { if (!stream.WriteAudioEvent(event)) { std::cerr << "Failed to write an audio event" << std::endl; break; } } else { break; } std::this_thread::sleep_for(std::chrono::milliseconds(25)); // Slow down since we are streaming from a file. } if (!stream.WriteAudioEvent(AudioEvent())) { // Per the spec, we have to send an empty event (i.e. without a payload) at the end. std::cerr << "Failed to send an empty frame" << std::endl; } else { std::cout << "Successfully sent the empty frame" << std::endl; } stream.flush(); std::this_thread::sleep_for(std::chrono::seconds (10)); // Workaround to prevent an error at the end of the stream for this contrived example. stream.Close(); }; Aws::Utils::Threading::Semaphore signaling(0 /*initialCount*/, 1 /*maxCount*/); auto OnResponseCallback = [&signaling](const TranscribeStreamingServiceClient* /*unused*/, const Model::StartStreamTranscriptionRequest& /*unused*/, const Model::StartStreamTranscriptionOutcome& /*unused*/, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& /*unused*/) { signaling.Release(); }; std::cout << "Starting..." << std::endl; client.StartStreamTranscriptionAsync(request, OnStreamReady, OnResponseCallback, nullptr /*context*/); signaling.WaitOne(); // Prevent the application from exiting until we're done. std::cout << "Done" << std::endl; } Aws::ShutdownAPI(options); return 0; }<|endoftext|>
<commit_before>/* * Qumulus UML editor * Author: Randy Thiemann * */ #include "QumulusApplication.h" #include <Gui/Widgets/StyleType.h> #include <Gui/Widgets/SideBar.h> #include <Gui/Widgets/StatusBar.h> QUML_BEGIN_NAMESPACE_GC QumulusApplication::QumulusApplication(int& argc, char** argv) : QApplication(argc, argv) { connect(this, &QumulusApplication::focusChanged, this, &QumulusApplication::onFocusChanged); } QuGW::MainWindow* QumulusApplication::mainWindowForWidget(QWidget* w) const { QuGW::MainWindow* mw; while(w != nullptr) { w = w->parentWidget(); if((mw = dynamic_cast<QuGW::MainWindow*>(w))) return mw; } return nullptr; } void QumulusApplication::onFocusChanged(QWidget* old, QWidget* now) { #ifdef Q_OS_MAC QuGW::MainWindow* w1 = mainWindowForWidget(old); QuGW::MainWindow* w2 = mainWindowForWidget(now); if(w1 == w2) return; if(w1 != nullptr) { w1->sideBar()->setStyleType(QuGW::StyleType::Inactive); w1->statusBar()->setStyleType(QuGW::StyleType::Inactive); } if(w2 != nullptr) { w2->sideBar()->setStyleType(QuGW::StyleType::Active); w2->statusBar()->setStyleType(QuGW::StyleType::Active); } #endif } QUML_END_NAMESPACE_GC <commit_msg>I wrote half of it, better get some credit.<commit_after>/* * Qumulus UML editor * Author: Frank Erens * Author: Randy Thiemann * */ #include "QumulusApplication.h" #include <Gui/Widgets/StyleType.h> #include <Gui/Widgets/SideBar.h> #include <Gui/Widgets/StatusBar.h> QUML_BEGIN_NAMESPACE_GC QumulusApplication::QumulusApplication(int& argc, char** argv) : QApplication(argc, argv) { connect(this, &QumulusApplication::focusChanged, this, &QumulusApplication::onFocusChanged); } QuGW::MainWindow* QumulusApplication::mainWindowForWidget(QWidget* w) const { QuGW::MainWindow* mw; while(w != nullptr) { w = w->parentWidget(); if((mw = dynamic_cast<QuGW::MainWindow*>(w))) return mw; } return nullptr; } void QumulusApplication::onFocusChanged(QWidget* old, QWidget* now) { #ifdef Q_OS_MAC QuGW::MainWindow* w1 = mainWindowForWidget(old); QuGW::MainWindow* w2 = mainWindowForWidget(now); if(w1 == w2) return; if(w1 != nullptr) { w1->sideBar()->setStyleType(QuGW::StyleType::Inactive); w1->statusBar()->setStyleType(QuGW::StyleType::Inactive); } if(w2 != nullptr) { w2->sideBar()->setStyleType(QuGW::StyleType::Active); w2->statusBar()->setStyleType(QuGW::StyleType::Active); } #endif } QUML_END_NAMESPACE_GC <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ #ifndef MAPNIK_COLOR_FACTORY_HPP #define MAPNIK_COLOR_FACTORY_HPP // mapnik #include <mapnik/config.hpp> #include <mapnik/color.hpp> #include <mapnik/config_error.hpp> // boost #include <boost/utility.hpp> #include <boost/version.hpp> // boost 1.41 -> 1.44 compatibility, to be removed in mapnik 2.1 (dane) #if BOOST_VERSION >= 104500 #include <mapnik/css_color_grammar.hpp> namespace mapnik { class MAPNIK_DECL color_factory : boost::noncopyable { public: static void init_from_string(color & c, char const* css_color) { typedef char const* iterator_type; typedef mapnik::css_color_grammar<iterator_type> css_color_grammar; css_color_grammar g; iterator_type first = css_color; iterator_type last = css_color + std::strlen(css_color); bool result = boost::spirit::qi::phrase_parse(first, last, g, boost::spirit::ascii::space, c); if (!result) { throw config_error(std::string("Failed to parse color value: ") + "Expected a CSS color, but got '" + css_color + "'"); } } static color from_string(char const* css_color) { color c; init_from_string(c,css_color); return c; } }; } #else #include <mapnik/css_color_grammar_deprecated.hpp> namespace mapnik { class MAPNIK_DECL color_factory : boost::noncopyable { public: static void init_from_string(color & c, char const* css_color) { typedef char const* iterator_type; typedef mapnik::css_color_grammar<iterator_type> css_color_grammar; css_color_grammar g; iterator_type first = css_color; iterator_type last = css_color + std::strlen(css_color); mapnik::css css_; bool result = boost::spirit::qi::phrase_parse(first, last, g, boost::spirit::ascii::space, css_); if (!result) { throw config_error(std::string("Failed to parse color value: ") + "Expected a CSS color, but got '" + css_color + "'"); } c.set_red(css_.r); c.set_green(css_.g); c.set_blue(css_.b); c.set_alpha(css_.a); } static color from_string(char const* css_color) { color c; init_from_string(c,css_color); return c; } }; } #endif #endif //MAPNIK_COLOR_FACTORY_HPP <commit_msg>+ change ingterface to work with std::string<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ #ifndef MAPNIK_COLOR_FACTORY_HPP #define MAPNIK_COLOR_FACTORY_HPP // mapnik #include <mapnik/config.hpp> #include <mapnik/color.hpp> #include <mapnik/config_error.hpp> // boost #include <boost/utility.hpp> #include <boost/version.hpp> // boost 1.41 -> 1.44 compatibility, to be removed in mapnik 2.1 (dane) #if BOOST_VERSION >= 104500 #include <mapnik/css_color_grammar.hpp> namespace mapnik { class MAPNIK_DECL color_factory : boost::noncopyable { public: static void init_from_string(color & c, std::string const& css_color) { typedef std::string::const_iterator iterator_type; typedef mapnik::css_color_grammar<iterator_type> css_color_grammar; css_color_grammar g; iterator_type first = css_color.begin(); iterator_type last = css_color.end(); bool result = boost::spirit::qi::phrase_parse(first, last, g, boost::spirit::ascii::space, c); if (!result) { throw config_error(std::string("Failed to parse color value: ") + "Expected a CSS color, but got '" + css_color + "'"); } } static color from_string(std::string const& css_color) { color c; init_from_string(c,css_color); return c; } }; } #else #include <mapnik/css_color_grammar_deprecated.hpp> namespace mapnik { class MAPNIK_DECL color_factory : boost::noncopyable { public: static void init_from_string(color & c, std::string const& css_color) { typedef std::string::const_iterator iterator_type; typedef mapnik::css_color_grammar<iterator_type> css_color_grammar; css_color_grammar g; iterator_type first = css_color.begin(); iterator_type last = css_color.end(); mapnik::css css_; bool result = boost::spirit::qi::phrase_parse(first, last, g, boost::spirit::ascii::space, css_); if (!result) { throw config_error(std::string("Failed to parse color value: ") + "Expected a CSS color, but got '" + css_color + "'"); } c.set_red(css_.r); c.set_green(css_.g); c.set_blue(css_.b); c.set_alpha(css_.a); } static color from_string(std::string const& css_color) { color c; init_from_string(c,css_color); return c; } }; } #endif #endif //MAPNIK_COLOR_FACTORY_HPP <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_CONFIG_HELPERS_INCLUDED #define MAPNIK_CONFIG_HELPERS_INCLUDED #include <mapnik/enumeration.hpp> #include <mapnik/config_error.hpp> #include <mapnik/color_factory.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/lexical_cast.hpp> #include <boost/optional.hpp> #include <iostream> #include <sstream> namespace mapnik { template <typename T> T get(const boost::property_tree::ptree & node, const std::string & name, bool is_attribute, const T & default_value); template <typename T> T get(const boost::property_tree::ptree & node, const std::string & name, bool is_attribute); template <typename T> T get_own(const boost::property_tree::ptree & node, const std::string & name); template <typename T> boost::optional<T> get_optional(const boost::property_tree::ptree & node, const std::string & name, bool is_attribute); template <typename T> boost::optional<T> get_opt_attr( const boost::property_tree::ptree & node, const std::string & name) { return get_optional<T>( node, name, true); } template <typename T> boost::optional<T> get_opt_child( const boost::property_tree::ptree & node, const std::string & name) { return get_optional<T>( node, name, false); } template <typename T> T get_attr( const boost::property_tree::ptree & node, const std::string & name, const T & default_value ) { return get<T>( node, name, true, default_value); } template <typename T> T get_attr( const boost::property_tree::ptree & node, const std::string & name ) { return get<T>( node, name, true ); } template <typename T> T get_css( const boost::property_tree::ptree & node, const std::string & name ) { return get_own<T>( node, std::string("CSS parameter '") + name + "'"); } /** Stream input operator for color values */ template <typename charT, typename traits> std::basic_istream<charT, traits> & operator >> ( std::basic_istream<charT, traits> & s, mapnik::color & c ) { std::string word; s >> word; if ( s ) { try { c = mapnik::color_factory::from_string( word.c_str() ); } catch (...) { s.setstate( std::ios::failbit ); } } return s; } template <typename charT, typename traits> std::basic_ostream<charT, traits> & operator << ( std::basic_ostream<charT, traits> & s, const mapnik::color & c ) { std::string hex_string( c.to_hex_string() ); s << hex_string; return s; } /** Helper for class bool */ class boolean { public: boolean() {} boolean(bool b) : b_(b) {} boolean(const boolean & b) : b_(b.b_) {} operator bool() const { return b_; } boolean & operator = (const boolean & other) { b_ = other.b_; return * this; } boolean & operator = (bool other) { b_ = other; return * this; } private: bool b_; }; /** Special stream input operator for boolean values */ template <typename charT, typename traits> std::basic_istream<charT, traits> & operator >> ( std::basic_istream<charT, traits> & s, boolean & b ) { std::string word; s >> word; if ( s ) { if ( word == "true" || word == "yes" || word == "on" || word == "1") { b = true; } else if ( word == "false" || word == "no" || word == "off" || word == "0") { b = false; } else { s.setstate( std::ios::failbit ); } } return s; } template <typename charT, typename traits> std::basic_ostream<charT, traits> & operator << ( std::basic_ostream<charT, traits> & s, const boolean & b ) { s << ( b ? "true" : "false" ); return s; } template <typename T> void set_attr(boost::property_tree::ptree & pt, const std::string & name, const T & v) { pt.put("<xmlattr>." + name, v); } /* template <> void set_attr<bool>(boost::property_tree::ptree & pt, const std::string & name, const bool & v) { pt.put("<xmlattr>." + name, boolean(v)); } */ class boolean; template <typename T> void set_css(boost::property_tree::ptree & pt, const std::string & name, const T & v) { boost::property_tree::ptree & css_node = pt.push_back( boost::property_tree::ptree::value_type("CssParameter", boost::property_tree::ptree()))->second; css_node.put("<xmlattr>.name", name ); css_node.put_own( v ); } template <typename T> struct name_trait { static std::string name() { return "<unknown>"; } // missing name_trait for type ... // if you get here you are probably using a new type // in the XML file. Just add a name trait for the new // type below. BOOST_STATIC_ASSERT( sizeof(T) == 0 ); }; #define DEFINE_NAME_TRAIT_WITH_NAME( type, type_name ) \ template <> \ struct name_trait<type> \ { \ static std::string name() { return std::string("type ") + type_name; } \ }; #define DEFINE_NAME_TRAIT( type ) \ DEFINE_NAME_TRAIT_WITH_NAME( type, #type ); DEFINE_NAME_TRAIT( double ); DEFINE_NAME_TRAIT( float ); DEFINE_NAME_TRAIT( unsigned ); DEFINE_NAME_TRAIT( boolean ); DEFINE_NAME_TRAIT_WITH_NAME( int, "integer" ); DEFINE_NAME_TRAIT_WITH_NAME( std::string, "string" ); DEFINE_NAME_TRAIT_WITH_NAME( color, "color" ); template <typename ENUM, int MAX> struct name_trait< mapnik::enumeration<ENUM, MAX> > { typedef enumeration<ENUM, MAX> Enum; static std::string name() { std::string value_list("one of ["); for (unsigned i = 0; i < Enum::MAX; ++i) { value_list += Enum::get_string( i ); if ( i + 1 < Enum::MAX ) value_list += ", "; } value_list += "]"; return value_list; } }; template <typename T> T get(const boost::property_tree::ptree & node, const std::string & name, bool is_attribute, const T & default_value) { boost::optional<std::string> str; if (is_attribute) { str = node.get_optional<std::string>( std::string("<xmlattr>.") + name ); } else { str = node.get_optional<std::string>(name ); } if ( str ) { try { return boost::lexical_cast<T>( * str ); } catch (const boost::bad_lexical_cast & ) { throw config_error(string("Failed to parse ") + (is_attribute ? "attribute" : "child node") + " '" + name + "'. Expected " + name_trait<T>::name() + " but got '" + *str + "'"); } } else { return default_value; } } template <typename T> T get(const boost::property_tree::ptree & node, const std::string & name, bool is_attribute) { boost::optional<std::string> str; if (is_attribute) { str = node.get_optional<std::string>( std::string("<xmlattr>.") + name); } else { str = node.get_optional<std::string>(name); } if ( ! str ) { throw config_error(string("Required ") + (is_attribute ? "attribute " : "child node ") + "'" + name + "' is missing"); } try { return boost::lexical_cast<T>( *str ); } catch (const boost::bad_lexical_cast & ) { throw config_error(string("Failed to parse ") + (is_attribute ? "attribute" : "child node") + " '" + name + "'. Expected " + name_trait<T>::name() + " but got '" + *str + "'"); } } template <typename T> T get_own(const boost::property_tree::ptree & node, const std::string & name) { try { return node.get_own<T>(); } catch (...) { throw config_error(string("Failed to parse ") + name + ". Expected " + name_trait<T>::name() + " but got '" + node.data() + "'"); } } template <typename T> boost::optional<T> get_optional(const boost::property_tree::ptree & node, const std::string & name, bool is_attribute) { boost::optional<std::string> str; if (is_attribute) { str = node.get_optional<std::string>( std::string("<xmlattr>.") + name); } else { str = node.get_optional<std::string>(name); } boost::optional<T> result; if ( str ) { try { result = boost::lexical_cast<T>( *str ); } catch (const boost::bad_lexical_cast &) { throw config_error(string("Failed to parse ") + (is_attribute ? "attribute" : "child node") + " '" + name + "'. Expected " + name_trait<T>::name() + " but got '" + *str + "'"); } } return result; } } // end of namespace mapnik #endif // MAPNIK_CONFIG_HELPERS_INCLUDED <commit_msg>+ added specializations for mapnik::color to avoid to/from stream conversions<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_CONFIG_HELPERS_INCLUDED #define MAPNIK_CONFIG_HELPERS_INCLUDED #include <mapnik/enumeration.hpp> #include <mapnik/config_error.hpp> #include <mapnik/color_factory.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/lexical_cast.hpp> #include <boost/optional.hpp> #include <iostream> #include <sstream> namespace mapnik { template <typename T> T get(const boost::property_tree::ptree & node, const std::string & name, bool is_attribute, const T & default_value); template <typename T> T get(const boost::property_tree::ptree & node, const std::string & name, bool is_attribute); template <typename T> T get_own(const boost::property_tree::ptree & node, const std::string & name); template <typename T> boost::optional<T> get_optional(const boost::property_tree::ptree & node, const std::string & name, bool is_attribute); template <typename T> boost::optional<T> get_opt_attr( const boost::property_tree::ptree & node, const std::string & name) { return get_optional<T>( node, name, true); } template <typename T> boost::optional<T> get_opt_child( const boost::property_tree::ptree & node, const std::string & name) { return get_optional<T>( node, name, false); } template <typename T> T get_attr( const boost::property_tree::ptree & node, const std::string & name, const T & default_value ) { return get<T>( node, name, true, default_value); } template <typename T> T get_attr( const boost::property_tree::ptree & node, const std::string & name ) { return get<T>( node, name, true ); } template <typename T> T get_css( const boost::property_tree::ptree & node, const std::string & name ) { return get_own<T>( node, std::string("CSS parameter '") + name + "'"); } // specialization for color type template <> inline color get_css (boost::property_tree::ptree const& node, std::string const& name) { std::string str = get_own<std::string>( node, std::string("CSS parameter '") + name + "'"); ; try { return mapnik::color_factory::from_string(str.c_str()); } catch (...) { throw config_error(string("Failed to parse ") + name + "'. Expected CSS color" + " but got '" + str + "'"); } } template <typename charT, typename traits> std::basic_ostream<charT, traits> & operator << ( std::basic_ostream<charT, traits> & s, const mapnik::color & c ) { std::string hex_string( c.to_hex_string() ); s << hex_string; return s; } /** Helper for class bool */ class boolean { public: boolean() {} boolean(bool b) : b_(b) {} boolean(const boolean & b) : b_(b.b_) {} operator bool() const { return b_; } boolean & operator = (const boolean & other) { b_ = other.b_; return * this; } boolean & operator = (bool other) { b_ = other; return * this; } private: bool b_; }; /** Special stream input operator for boolean values */ template <typename charT, typename traits> std::basic_istream<charT, traits> & operator >> ( std::basic_istream<charT, traits> & s, boolean & b ) { std::string word; s >> word; if ( s ) { if ( word == "true" || word == "yes" || word == "on" || word == "1") { b = true; } else if ( word == "false" || word == "no" || word == "off" || word == "0") { b = false; } else { s.setstate( std::ios::failbit ); } } return s; } template <typename charT, typename traits> std::basic_ostream<charT, traits> & operator << ( std::basic_ostream<charT, traits> & s, const boolean & b ) { s << ( b ? "true" : "false" ); return s; } template <typename T> void set_attr(boost::property_tree::ptree & pt, const std::string & name, const T & v) { pt.put("<xmlattr>." + name, v); } /* template <> void set_attr<bool>(boost::property_tree::ptree & pt, const std::string & name, const bool & v) { pt.put("<xmlattr>." + name, boolean(v)); } */ class boolean; template <typename T> void set_css(boost::property_tree::ptree & pt, const std::string & name, const T & v) { boost::property_tree::ptree & css_node = pt.push_back( boost::property_tree::ptree::value_type("CssParameter", boost::property_tree::ptree()))->second; css_node.put("<xmlattr>.name", name ); css_node.put_own( v ); } template <typename T> struct name_trait { static std::string name() { return "<unknown>"; } // missing name_trait for type ... // if you get here you are probably using a new type // in the XML file. Just add a name trait for the new // type below. BOOST_STATIC_ASSERT( sizeof(T) == 0 ); }; #define DEFINE_NAME_TRAIT_WITH_NAME( type, type_name ) \ template <> \ struct name_trait<type> \ { \ static std::string name() { return std::string("type ") + type_name; } \ }; #define DEFINE_NAME_TRAIT( type ) \ DEFINE_NAME_TRAIT_WITH_NAME( type, #type ); DEFINE_NAME_TRAIT( double ); DEFINE_NAME_TRAIT( float ); DEFINE_NAME_TRAIT( unsigned ); DEFINE_NAME_TRAIT( boolean ); DEFINE_NAME_TRAIT_WITH_NAME( int, "integer" ); DEFINE_NAME_TRAIT_WITH_NAME( std::string, "string" ); DEFINE_NAME_TRAIT_WITH_NAME( color, "color" ); template <typename ENUM, int MAX> struct name_trait< mapnik::enumeration<ENUM, MAX> > { typedef enumeration<ENUM, MAX> Enum; static std::string name() { std::string value_list("one of ["); for (unsigned i = 0; i < Enum::MAX; ++i) { value_list += Enum::get_string( i ); if ( i + 1 < Enum::MAX ) value_list += ", "; } value_list += "]"; return value_list; } }; template <typename T> T get(const boost::property_tree::ptree & node, const std::string & name, bool is_attribute, const T & default_value) { boost::optional<std::string> str; if (is_attribute) { str = node.get_optional<std::string>( std::string("<xmlattr>.") + name ); } else { str = node.get_optional<std::string>(name ); } if ( str ) { try { return boost::lexical_cast<T>( * str ); } catch (const boost::bad_lexical_cast & ) { throw config_error(string("Failed to parse ") + (is_attribute ? "attribute" : "child node") + " '" + name + "'. Expected " + name_trait<T>::name() + " but got '" + *str + "'"); } } else { return default_value; } } template <> inline color get(boost::property_tree::ptree const& node, std::string const& name, bool is_attribute, color const& default_value) { boost::optional<std::string> str; if (is_attribute) { str = node.get_optional<std::string>( std::string("<xmlattr>.") + name ); } else { str = node.get_optional<std::string>(name ); } if ( str ) { try { return mapnik::color_factory::from_string((*str).c_str()); } catch (...) { throw config_error(string("Failed to parse ") + (is_attribute ? "attribute" : "child node") + " '" + name + "'. Expected " + name_trait<color>::name() + " but got '" + *str + "'"); } } else { return default_value; } } template <typename T> T get(const boost::property_tree::ptree & node, const std::string & name, bool is_attribute) { boost::optional<std::string> str; if (is_attribute) { str = node.get_optional<std::string>( std::string("<xmlattr>.") + name); } else { str = node.get_optional<std::string>(name); } if ( ! str ) { throw config_error(string("Required ") + (is_attribute ? "attribute " : "child node ") + "'" + name + "' is missing"); } try { return boost::lexical_cast<T>( *str ); } catch (const boost::bad_lexical_cast & ) { throw config_error(string("Failed to parse ") + (is_attribute ? "attribute" : "child node") + " '" + name + "'. Expected " + name_trait<T>::name() + " but got '" + *str + "'"); } } template <typename T> T get_own(const boost::property_tree::ptree & node, const std::string & name) { try { return node.get_own<T>(); } catch (...) { throw config_error(string("Failed to parse ") + name + ". Expected " + name_trait<T>::name() + " but got '" + node.data() + "'"); } } template <typename T> boost::optional<T> get_optional(const boost::property_tree::ptree & node, const std::string & name, bool is_attribute) { boost::optional<std::string> str; if (is_attribute) { str = node.get_optional<std::string>( std::string("<xmlattr>.") + name); } else { str = node.get_optional<std::string>(name); } boost::optional<T> result; if ( str ) { try { result = boost::lexical_cast<T>( *str ); } catch (const boost::bad_lexical_cast &) { throw config_error(string("Failed to parse ") + (is_attribute ? "attribute" : "child node") + " '" + name + "'. Expected " + name_trait<T>::name() + " but got '" + *str + "'"); } } return result; } // template <> inline boost::optional<color> get_optional(const boost::property_tree::ptree & node, const std::string & name, bool is_attribute) { boost::optional<std::string> str; if (is_attribute) { str = node.get_optional<std::string>( std::string("<xmlattr>.") + name); } else { str = node.get_optional<std::string>(name); } boost::optional<color> result; if ( str ) { try { //result = boost::lexical_cast<T>( *str ); result = mapnik::color_factory::from_string((*str).c_str()); } catch (...) { throw config_error(string("Failed to parse ") + (is_attribute ? "attribute" : "child node") + " '" + name + "'. Expected " + name_trait<color>::name() + " but got '" + *str + "'"); } } return result; } } // end of namespace mapnik #endif // MAPNIK_CONFIG_HELPERS_INCLUDED <|endoftext|>
<commit_before>#ifndef INCLUDE_AL_GRAPHICS_HPP #define INCLUDE_AL_GRAPHICS_HPP /* Copyright (C) 2006-2008. The Regents of the University of California (REGENTS). All Rights Reserved. Permission to use, copy, modify, distribute, and distribute modified versions of this software and its documentation without fee and without a signed licensing agreement, is hereby granted, provided that the above copyright notice, the list of contributors, this paragraph and the following two paragraphs appear in all copies, modifications, and distributions. IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ /* Example code: Graphics gl(); gl.begin(gl.POINTS); gl.vertex3d(0, 0, 0); gl.end(); */ #include "math/al_Vec.hpp" #include "math/al_Matrix4.hpp" #include "types/al_Buffer.hpp" #include "types/al_Color.hpp" #include <stack> using std::stack; namespace al{ namespace gfx{ enum BlendFunc { SRC_ALPHA = 0, SRC_COLOR, DST_ALPHA, DST_COLOR, ZERO, ONE, SRC_ALPHA_SATURATE }; enum PolygonMode { POINT = 0, LINE, FILL }; enum MatrixMode { MODELVIEW = 0, PROJECTION }; enum Primitive { POINTS = 0, LINES, LINE_STRIP, LINE_LOOP, TRIANGLES, QUADS, POLYGON }; namespace AntiAliasMode { enum t{ DontCare = 1<<0, Fastest = 1<<1, Nicest = 1<<2 }; inline t operator| (const t& a, const t& b){ return t(int(a) | int(b)); } inline t operator& (const t& a, const t& b){ return t(int(a) & int(b)); } } namespace AttributeBit { enum t{ ColorBuffer = 1<<0, /**< Color-buffer bit */ DepthBuffer = 1<<1, /**< Depth-buffer bit */ Enable = 1<<2, /**< Enable bit */ Viewport = 1<<3 /**< Viewport bit */ }; inline t operator| (const t& a, const t& b){ return t(int(a) | int(b)); } inline t operator& (const t& a, const t& b){ return t(int(a) & int(b)); } } struct StateChange { StateChange() : blending(false), lighting(false), depth_testing(false), polygon_mode(false), antialiasing(false) {} ~StateChange(){} bool blending; bool lighting; bool depth_testing; bool polygon_mode; bool antialiasing; }; struct State { State() : blend_enable(false), blend_src(SRC_COLOR), blend_dst(DST_COLOR), lighting_enable(false), depth_enable(true), polygon_mode(FILL), antialias_mode(AntiAliasMode::DontCare) {} ~State() {} // Blending bool blend_enable; BlendFunc blend_src; BlendFunc blend_dst; // Lighting bool lighting_enable; // Depth Testing bool depth_enable; // Polygon Mode PolygonMode polygon_mode; // Anti-Aliasing AntiAliasMode::t antialias_mode; }; class GraphicsData { public: typedef Vec<3,float> Vertex; typedef Vec<3,float> Normal; typedef Vec<4,float> Color; typedef Vec<2,float> TexCoord2; typedef Vec<3,float> TexCoord3; typedef unsigned int Index; /// Reset all buffers void resetBuffers(); void equalizeBuffers(); void getBounds(Vertex& min, Vertex& max); // destructive edits to internal vertices: void unitize(); /// scale to -1..1 void center(); // center at 0,0,0 void scale(double x, double y, double z); void scale(double s) { scale(x, y, z); } // generates smoothed normals for a set of vertices // will replace any normals currently in use // angle - maximum angle (in degrees) to smooth across void generateNormals(float angle); Primitive primitive() const { return mPrimitive; } const Buffer<Vertex>& vertices() const { return mVertices; } const Buffer<Normal>& normals() const { return mNormals; } const Buffer<Color>& colors() const { return mColors; } const Buffer<TexCoord2>& texCoord2s() const { return mTexCoord2s; } const Buffer<TexCoord3>& texCoord3s() const { return mTexCoord3s; } const Buffer<Index>& indices() const { return mIndices; } void addIndex(unsigned int i){ indices().append(i); } void addColor(float r, float g, float b, float a=1){ colors().append(Color(r,g,b,a)); } void addColor(Color& v) { colors().append(v); } void addNormal(float x, float y, float z=0){ normals().append(Normal(x,y,z)); } void addNormal(Normal& v) { normals().append(v); } void addTexCoord(float u, float v){ texCoord2s().append(TexCoord2(u,v)); } void addTexCoord(float u, float v, float w){ texCoord3s().append(TexCoord3(u,v,w)); } void addTexCoord(TexCoord2& v){ texCoord2s().append(v); } void addTexCoord(TexCoord3& v){ texCoord3s().append(v); } void addVertex(float x, float y, float z=0){ vertices().append(Vertex(x,y,z)); } void addVertex(Vertex& v){ vertices().append(v); } void primitive(Primitive prim){ mPrimitive=prim; } Buffer<Vertex>& vertices(){ return mVertices; } Buffer<Normal>& normals(){ return mNormals; } Buffer<Color>& colors(){ return mColors; } Buffer<TexCoord2>& texCoord2s(){ return mTexCoord2s; } Buffer<TexCoord3>& texCoord3s(){ return mTexCoord3s; } Buffer<Index>& indices(){ return mIndices; } protected: // Only populated (size>0) buffers will be used Buffer<Vertex> mVertices; Buffer<Normal> mNormals; Buffer<Color> mColors; Buffer<TexCoord2> mTexCoord2s; Buffer<TexCoord3> mTexCoord3s; Buffer<Index> mIndices; Primitive mPrimitive; }; class GraphicsBackend; /* Graphics knows how to draw GraphicsData It also owns a GraphicsData, to simulate immediate mode (where it draws its own data) */ class Graphics { public: // Graphics(gfx::Backend::type backend = gfx::Backend::AutoDetect); Graphics(GraphicsBackend *backend); ~Graphics(); // Rendering State void pushState(State &state); void popState(); // Frame void clear(int attribMask); void clearColor(float r, float g, float b, float a); void clearColor(const Color& color) { clearColor(color.r, color.g, color.b, color.a); } // Coordinate Transforms void viewport(int x, int y, int width, int height); void matrixMode(MatrixMode mode); MatrixMode matrixMode(); void pushMatrix(); void popMatrix(); void loadIdentity(); void loadMatrix(const Matrix4d &m); void multMatrix(const Matrix4d &m); void translate(double x, double y, double z); void translate(const Vec3d& v) { translate(v[0], v[1], v[2]); } void rotate(double angle, double x, double y, double z); void rotate(double angle, const Vec3d& v) { rotate(angle, v[0], v[1], v[2]); } void scale(double x, double y, double z); void scale(const Vec3d& v) { scale(v[0], v[1], v[2]); } // Immediate Mode void begin(Primitive mode); void end(); void vertex(double x, double y, double z=0.); void vertex(const Vec3d& v) { vertex(v[0], v[1], v[2]); } void texcoord(double u, double v); void normal(double x, double y, double z=0.); void normal(const Vec3d& v) { normal(v[0], v[1], v[2]); } void color(double r, double g, double b, double a=1.); void color(const Vec3d& v, double a=1.) { color(v[0], v[1], v[2], a); } // Other state void pointSize(double v); void lineWidth(double v); // Buffer drawing void draw(const GraphicsData& v); void draw(); GraphicsBackend * backend() { return mBackend; } GraphicsData& data() { return mGraphicsData; } protected: void compareState(State &prev_state, State &state); void enableState(); void drawBegin(); void drawEnd(); stack<Matrix4d> & matrixStackForMode(MatrixMode mode); protected: GraphicsBackend * mBackend; // graphics API implementation GraphicsData mGraphicsData; // used for immediate mode style rendering bool mInImmediateMode; // flag for whether or not in immediate mode MatrixMode mMatrixMode; // matrix stack to use stack<Matrix4d> mProjectionMatrix; // projection matrix stack stack<Matrix4d> mModelViewMatrix; // modelview matrix stack StateChange mStateChange; // state difference to mark changes stack<State> mState; // state stack }; } // ::al::gfx } // ::al #endif <commit_msg>osc apr updates<commit_after>#ifndef INCLUDE_AL_GRAPHICS_HPP #define INCLUDE_AL_GRAPHICS_HPP /* Copyright (C) 2006-2008. The Regents of the University of California (REGENTS). All Rights Reserved. Permission to use, copy, modify, distribute, and distribute modified versions of this software and its documentation without fee and without a signed licensing agreement, is hereby granted, provided that the above copyright notice, the list of contributors, this paragraph and the following two paragraphs appear in all copies, modifications, and distributions. IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ /* Example code: Graphics gl(); gl.begin(gl.POINTS); gl.vertex3d(0, 0, 0); gl.end(); */ #include "math/al_Vec.hpp" #include "math/al_Matrix4.hpp" #include "types/al_Buffer.hpp" #include "types/al_Color.hpp" #include <stack> using std::stack; namespace al{ namespace gfx{ enum BlendFunc { SRC_ALPHA = 0, SRC_COLOR, DST_ALPHA, DST_COLOR, ZERO, ONE, SRC_ALPHA_SATURATE }; enum PolygonMode { POINT = 0, LINE, FILL }; enum MatrixMode { MODELVIEW = 0, PROJECTION }; enum Primitive { POINTS = 0, LINES, LINE_STRIP, LINE_LOOP, TRIANGLES, QUADS, POLYGON }; namespace AntiAliasMode { enum t{ DontCare = 1<<0, Fastest = 1<<1, Nicest = 1<<2 }; inline t operator| (const t& a, const t& b){ return t(int(a) | int(b)); } inline t operator& (const t& a, const t& b){ return t(int(a) & int(b)); } } namespace AttributeBit { enum t{ ColorBuffer = 1<<0, /**< Color-buffer bit */ DepthBuffer = 1<<1, /**< Depth-buffer bit */ Enable = 1<<2, /**< Enable bit */ Viewport = 1<<3 /**< Viewport bit */ }; inline t operator| (const t& a, const t& b){ return t(int(a) | int(b)); } inline t operator& (const t& a, const t& b){ return t(int(a) & int(b)); } } struct StateChange { StateChange() : blending(false), lighting(false), depth_testing(false), polygon_mode(false), antialiasing(false) {} ~StateChange(){} bool blending; bool lighting; bool depth_testing; bool polygon_mode; bool antialiasing; }; struct State { State() : blend_enable(false), blend_src(SRC_COLOR), blend_dst(DST_COLOR), lighting_enable(false), depth_enable(true), polygon_mode(FILL), antialias_mode(AntiAliasMode::DontCare) {} ~State() {} // Blending bool blend_enable; BlendFunc blend_src; BlendFunc blend_dst; // Lighting bool lighting_enable; // Depth Testing bool depth_enable; // Polygon Mode PolygonMode polygon_mode; // Anti-Aliasing AntiAliasMode::t antialias_mode; }; class GraphicsData { public: typedef Vec<3,float> Vertex; typedef Vec<3,float> Normal; typedef Vec<4,float> Color; typedef Vec<2,float> TexCoord2; typedef Vec<3,float> TexCoord3; typedef unsigned int Index; /// Reset all buffers void resetBuffers(); void equalizeBuffers(); void getBounds(Vertex& min, Vertex& max); // destructive edits to internal vertices: void unitize(); /// scale to -1..1 void center(); // center at 0,0,0 void scale(double x, double y, double z); void scale(double s) { scale(s, s, s); } // generates smoothed normals for a set of vertices // will replace any normals currently in use // angle - maximum angle (in degrees) to smooth across void generateNormals(float angle); Primitive primitive() const { return mPrimitive; } const Buffer<Vertex>& vertices() const { return mVertices; } const Buffer<Normal>& normals() const { return mNormals; } const Buffer<Color>& colors() const { return mColors; } const Buffer<TexCoord2>& texCoord2s() const { return mTexCoord2s; } const Buffer<TexCoord3>& texCoord3s() const { return mTexCoord3s; } const Buffer<Index>& indices() const { return mIndices; } void addIndex(unsigned int i){ indices().append(i); } void addColor(float r, float g, float b, float a=1){ colors().append(Color(r,g,b,a)); } void addColor(Color& v) { colors().append(v); } void addNormal(float x, float y, float z=0){ normals().append(Normal(x,y,z)); } void addNormal(Normal& v) { normals().append(v); } void addTexCoord(float u, float v){ texCoord2s().append(TexCoord2(u,v)); } void addTexCoord(float u, float v, float w){ texCoord3s().append(TexCoord3(u,v,w)); } void addTexCoord(TexCoord2& v){ texCoord2s().append(v); } void addTexCoord(TexCoord3& v){ texCoord3s().append(v); } void addVertex(float x, float y, float z=0){ vertices().append(Vertex(x,y,z)); } void addVertex(Vertex& v){ vertices().append(v); } void primitive(Primitive prim){ mPrimitive=prim; } Buffer<Vertex>& vertices(){ return mVertices; } Buffer<Normal>& normals(){ return mNormals; } Buffer<Color>& colors(){ return mColors; } Buffer<TexCoord2>& texCoord2s(){ return mTexCoord2s; } Buffer<TexCoord3>& texCoord3s(){ return mTexCoord3s; } Buffer<Index>& indices(){ return mIndices; } protected: // Only populated (size>0) buffers will be used Buffer<Vertex> mVertices; Buffer<Normal> mNormals; Buffer<Color> mColors; Buffer<TexCoord2> mTexCoord2s; Buffer<TexCoord3> mTexCoord3s; Buffer<Index> mIndices; Primitive mPrimitive; }; class GraphicsBackend; /* Graphics knows how to draw GraphicsData It also owns a GraphicsData, to simulate immediate mode (where it draws its own data) */ class Graphics { public: // Graphics(gfx::Backend::type backend = gfx::Backend::AutoDetect); Graphics(GraphicsBackend *backend); ~Graphics(); // Rendering State void pushState(State &state); void popState(); // Frame void clear(int attribMask); void clearColor(float r, float g, float b, float a); void clearColor(const Color& color) { clearColor(color.r, color.g, color.b, color.a); } // Coordinate Transforms void viewport(int x, int y, int width, int height); void matrixMode(MatrixMode mode); MatrixMode matrixMode(); void pushMatrix(); void popMatrix(); void loadIdentity(); void loadMatrix(const Matrix4d &m); void multMatrix(const Matrix4d &m); void translate(double x, double y, double z); void translate(const Vec3d& v) { translate(v[0], v[1], v[2]); } void rotate(double angle, double x, double y, double z); void rotate(double angle, const Vec3d& v) { rotate(angle, v[0], v[1], v[2]); } void scale(double x, double y, double z); void scale(const Vec3d& v) { scale(v[0], v[1], v[2]); } // Immediate Mode void begin(Primitive mode); void end(); void vertex(double x, double y, double z=0.); void vertex(const Vec3d& v) { vertex(v[0], v[1], v[2]); } void texcoord(double u, double v); void normal(double x, double y, double z=0.); void normal(const Vec3d& v) { normal(v[0], v[1], v[2]); } void color(double r, double g, double b, double a=1.); void color(const Vec3d& v, double a=1.) { color(v[0], v[1], v[2], a); } // Other state void pointSize(double v); void lineWidth(double v); // Buffer drawing void draw(const GraphicsData& v); void draw(); GraphicsBackend * backend() { return mBackend; } GraphicsData& data() { return mGraphicsData; } protected: void compareState(State &prev_state, State &state); void enableState(); void drawBegin(); void drawEnd(); stack<Matrix4d> & matrixStackForMode(MatrixMode mode); protected: GraphicsBackend * mBackend; // graphics API implementation GraphicsData mGraphicsData; // used for immediate mode style rendering bool mInImmediateMode; // flag for whether or not in immediate mode MatrixMode mMatrixMode; // matrix stack to use stack<Matrix4d> mProjectionMatrix; // projection matrix stack stack<Matrix4d> mModelViewMatrix; // modelview matrix stack StateChange mStateChange; // state difference to mark changes stack<State> mState; // state stack }; } // ::al::gfx } // ::al #endif <|endoftext|>
<commit_before>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright 2019 ScyllaDB */ #pragma once #include <seastar/core/sstring.hh> #include <seastar/core/fair_queue.hh> #include <seastar/core/metrics_registration.hh> #include <seastar/core/future.hh> #include <seastar/core/internal/io_request.hh> #include <mutex> #include <array> namespace seastar { class io_priority_class; /// Renames an io priority class /// /// Renames an \ref io_priority_class previously created with register_one_priority_class(). /// /// The operation is global and affects all shards. /// The operation affects the exported statistics labels. /// /// \param pc The io priority class to be renamed /// \param new_name The new name for the io priority class /// \return a future that is ready when the io priority class have been renamed future<> rename_priority_class(io_priority_class pc, sstring new_name); namespace internal { namespace linux_abi { struct io_event; struct iocb; } } using shard_id = unsigned; class io_priority_class; class io_queue { private: struct priority_class_data { priority_class_ptr ptr; size_t bytes; uint64_t ops; uint32_t nr_queued; std::chrono::duration<double> queue_time; metrics::metric_groups _metric_groups; priority_class_data(sstring name, sstring mountpoint, priority_class_ptr ptr, shard_id owner); void rename(sstring new_name, sstring mountpoint, shard_id owner); private: void register_stats(sstring name, sstring mountpoint, shard_id owner); }; std::vector<std::vector<std::unique_ptr<priority_class_data>>> _priority_classes; fair_queue _fq; static constexpr unsigned _max_classes = 2048; static std::mutex _register_lock; static std::array<uint32_t, _max_classes> _registered_shares; static std::array<sstring, _max_classes> _registered_names; public: static io_priority_class register_one_priority_class(sstring name, uint32_t shares); static bool rename_one_priority_class(io_priority_class pc, sstring name); private: priority_class_data& find_or_create_class(const io_priority_class& pc, shard_id owner); fair_queue_ticket request_fq_ticket(const internal::io_request& req, size_t len) const; // The fields below are going away, they are just here so we can implement deprecated // functions that used to be provided by the fair_queue and are going away (from both // the fair_queue and the io_queue). Double-accounting for now will allow for easier // decoupling and is temporary size_t _queued_requests = 0; size_t _requests_executing = 0; public: // We want to represent the fact that write requests are (maybe) more expensive // than read requests. To avoid dealing with floating point math we will scale one // read request to be counted by this amount. // // A write request that is 30% more expensive than a read will be accounted as // (read_request_base_count * 130) / 100. // It is also technically possible for reads to be the expensive ones, in which case // writes will have an integer value lower than read_request_base_count. static constexpr unsigned read_request_base_count = 128; struct config { shard_id coordinator; unsigned capacity = std::numeric_limits<unsigned>::max(); unsigned max_req_count = std::numeric_limits<unsigned>::max(); unsigned max_bytes_count = std::numeric_limits<unsigned>::max(); unsigned disk_req_write_to_read_multiplier = read_request_base_count; unsigned disk_bytes_write_to_read_multiplier = read_request_base_count; sstring mountpoint = "undefined"; }; io_queue(config cfg); ~io_queue(); future<size_t> queue_request(const io_priority_class& pc, size_t len, internal::io_request req) noexcept; [[deprecated("modern I/O queues should use a property file")]] size_t capacity() const { return _config.capacity; } [[deprecated("I/O queue users should not track individual requests, but resources (weight, size) passing through the queue")]] size_t queued_requests() const { return _queued_requests; } // How many requests are sent to disk but not yet returned. [[deprecated("I/O queue users should not track individual requests, but resources (weight, size) passing through the queue")]] size_t requests_currently_executing() const { return _requests_executing; } void notify_requests_finished(fair_queue_ticket& desc) noexcept; // Dispatch requests that are pending in the I/O queue void poll_io_queue() { _fq.dispatch_requests(); } sstring mountpoint() const { return _config.mountpoint; } shard_id coordinator() const { return _config.coordinator; } future<> update_shares_for_class(io_priority_class pc, size_t new_shares); void rename_priority_class(io_priority_class pc, sstring new_name); private: config _config; static fair_queue::config make_fair_queue_config(config cfg); }; } <commit_msg>doc: io_queue: fix \ref io_priority_class<commit_after>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright 2019 ScyllaDB */ #pragma once #include <seastar/core/sstring.hh> #include <seastar/core/fair_queue.hh> #include <seastar/core/metrics_registration.hh> #include <seastar/core/future.hh> #include <seastar/core/internal/io_request.hh> #include <mutex> #include <array> namespace seastar { class io_priority_class; /// Renames an io priority class /// /// Renames an `io_priority_class` previously created with register_one_priority_class(). /// /// The operation is global and affects all shards. /// The operation affects the exported statistics labels. /// /// \param pc The io priority class to be renamed /// \param new_name The new name for the io priority class /// \return a future that is ready when the io priority class have been renamed future<> rename_priority_class(io_priority_class pc, sstring new_name); namespace internal { namespace linux_abi { struct io_event; struct iocb; } } using shard_id = unsigned; class io_priority_class; class io_queue { private: struct priority_class_data { priority_class_ptr ptr; size_t bytes; uint64_t ops; uint32_t nr_queued; std::chrono::duration<double> queue_time; metrics::metric_groups _metric_groups; priority_class_data(sstring name, sstring mountpoint, priority_class_ptr ptr, shard_id owner); void rename(sstring new_name, sstring mountpoint, shard_id owner); private: void register_stats(sstring name, sstring mountpoint, shard_id owner); }; std::vector<std::vector<std::unique_ptr<priority_class_data>>> _priority_classes; fair_queue _fq; static constexpr unsigned _max_classes = 2048; static std::mutex _register_lock; static std::array<uint32_t, _max_classes> _registered_shares; static std::array<sstring, _max_classes> _registered_names; public: static io_priority_class register_one_priority_class(sstring name, uint32_t shares); static bool rename_one_priority_class(io_priority_class pc, sstring name); private: priority_class_data& find_or_create_class(const io_priority_class& pc, shard_id owner); fair_queue_ticket request_fq_ticket(const internal::io_request& req, size_t len) const; // The fields below are going away, they are just here so we can implement deprecated // functions that used to be provided by the fair_queue and are going away (from both // the fair_queue and the io_queue). Double-accounting for now will allow for easier // decoupling and is temporary size_t _queued_requests = 0; size_t _requests_executing = 0; public: // We want to represent the fact that write requests are (maybe) more expensive // than read requests. To avoid dealing with floating point math we will scale one // read request to be counted by this amount. // // A write request that is 30% more expensive than a read will be accounted as // (read_request_base_count * 130) / 100. // It is also technically possible for reads to be the expensive ones, in which case // writes will have an integer value lower than read_request_base_count. static constexpr unsigned read_request_base_count = 128; struct config { shard_id coordinator; unsigned capacity = std::numeric_limits<unsigned>::max(); unsigned max_req_count = std::numeric_limits<unsigned>::max(); unsigned max_bytes_count = std::numeric_limits<unsigned>::max(); unsigned disk_req_write_to_read_multiplier = read_request_base_count; unsigned disk_bytes_write_to_read_multiplier = read_request_base_count; sstring mountpoint = "undefined"; }; io_queue(config cfg); ~io_queue(); future<size_t> queue_request(const io_priority_class& pc, size_t len, internal::io_request req) noexcept; [[deprecated("modern I/O queues should use a property file")]] size_t capacity() const { return _config.capacity; } [[deprecated("I/O queue users should not track individual requests, but resources (weight, size) passing through the queue")]] size_t queued_requests() const { return _queued_requests; } // How many requests are sent to disk but not yet returned. [[deprecated("I/O queue users should not track individual requests, but resources (weight, size) passing through the queue")]] size_t requests_currently_executing() const { return _requests_executing; } void notify_requests_finished(fair_queue_ticket& desc) noexcept; // Dispatch requests that are pending in the I/O queue void poll_io_queue() { _fq.dispatch_requests(); } sstring mountpoint() const { return _config.mountpoint; } shard_id coordinator() const { return _config.coordinator; } future<> update_shares_for_class(io_priority_class pc, size_t new_shares); void rename_priority_class(io_priority_class pc, sstring new_name); private: config _config; static fair_queue::config make_fair_queue_config(config cfg); }; } <|endoftext|>
<commit_before>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2015 Cloudius Systems, Ltd. */ // // Buffered input and output streams // // Two abstract classes (data_source and data_sink) provide means // to acquire bulk data from, or push bulk data to, some provider. // These could be tied to a TCP connection, a disk file, or a memory // buffer. // // Two concrete classes (input_stream and output_stream) buffer data // from data_source and data_sink and provide easier means to process // it. // #pragma once #include <seastar/core/future.hh> #include <seastar/core/temporary_buffer.hh> #include <seastar/core/scattered_message.hh> #include <seastar/util/std-compat.hh> namespace seastar { namespace net { class packet; } class data_source_impl { public: virtual ~data_source_impl() {} virtual future<temporary_buffer<char>> get() = 0; virtual future<temporary_buffer<char>> skip(uint64_t n); virtual future<> close() { return make_ready_future<>(); } }; class data_source { std::unique_ptr<data_source_impl> _dsi; protected: data_source_impl* impl() const { return _dsi.get(); } public: data_source() noexcept = default; explicit data_source(std::unique_ptr<data_source_impl> dsi) noexcept : _dsi(std::move(dsi)) {} data_source(data_source&& x) noexcept = default; data_source& operator=(data_source&& x) noexcept = default; future<temporary_buffer<char>> get() { return _dsi->get(); } future<temporary_buffer<char>> skip(uint64_t n) { return _dsi->skip(n); } future<> close() { return _dsi->close(); } }; class data_sink_impl { public: virtual ~data_sink_impl() {} virtual temporary_buffer<char> allocate_buffer(size_t size) { return temporary_buffer<char>(size); } virtual future<> put(net::packet data) = 0; virtual future<> put(std::vector<temporary_buffer<char>> data) { net::packet p; p.reserve(data.size()); for (auto& buf : data) { p = net::packet(std::move(p), net::fragment{buf.get_write(), buf.size()}, buf.release()); } return put(std::move(p)); } virtual future<> put(temporary_buffer<char> buf) { return put(net::packet(net::fragment{buf.get_write(), buf.size()}, buf.release())); } virtual future<> flush() { return make_ready_future<>(); } virtual future<> close() = 0; }; class data_sink { std::unique_ptr<data_sink_impl> _dsi; public: data_sink() noexcept = default; explicit data_sink(std::unique_ptr<data_sink_impl> dsi) noexcept : _dsi(std::move(dsi)) {} data_sink(data_sink&& x) noexcept = default; data_sink& operator=(data_sink&& x) noexcept = default; temporary_buffer<char> allocate_buffer(size_t size) { return _dsi->allocate_buffer(size); } future<> put(std::vector<temporary_buffer<char>> data) { return _dsi->put(std::move(data)); } future<> put(temporary_buffer<char> data) { return _dsi->put(std::move(data)); } future<> put(net::packet p) { return _dsi->put(std::move(p)); } future<> flush() { return _dsi->flush(); } future<> close() { return _dsi->close(); } }; struct continue_consuming {}; template <typename CharType> class stop_consuming { public: using tmp_buf = temporary_buffer<CharType>; explicit stop_consuming(tmp_buf buf) : _buf(std::move(buf)) {} tmp_buf& get_buffer() { return _buf; } const tmp_buf& get_buffer() const { return _buf; } private: tmp_buf _buf; }; class skip_bytes { public: explicit skip_bytes(uint64_t v) : _value(v) {} uint64_t get_value() const { return _value; } private: uint64_t _value; }; template <typename CharType> class consumption_result { public: using stop_consuming_type = stop_consuming<CharType>; using consumption_variant = std::variant<continue_consuming, stop_consuming_type, skip_bytes>; using tmp_buf = typename stop_consuming_type::tmp_buf; /*[[deprecated]]*/ consumption_result(std::optional<tmp_buf> opt_buf) { if (opt_buf) { _result = stop_consuming_type{std::move(opt_buf.value())}; } } consumption_result(const continue_consuming&) {} consumption_result(stop_consuming_type&& stop) : _result(std::move(stop)) {} consumption_result(skip_bytes&& skip) : _result(std::move(skip)) {} consumption_variant& get() { return _result; } const consumption_variant& get() const { return _result; } private: consumption_variant _result; }; // Consumer concept, for consume() method SEASTAR_CONCEPT( // The consumer should operate on the data given to it, and // return a future "consumption result", which can be // - continue_consuming, if the consumer has consumed all the input given // to it and is ready for more // - stop_consuming, when the consumer is done (and in that case // the contained buffer is the unconsumed part of the last data buffer - this // can also happen to be empty). // - skip_bytes, when the consumer has consumed all the input given to it // and wants to skip before processing the next chunk // // For backward compatibility reasons, we also support the deprecated return value // of type "unconsumed remainder" which can be // - empty optional, if the consumer consumed all the input given to it // and is ready for more // - non-empty optional, when the consumer is done (and in that case // the value is the unconsumed part of the last data buffer - this // can also happen to be empty). template <typename Consumer, typename CharType> concept InputStreamConsumer = requires (Consumer c) { { c(temporary_buffer<CharType>{}) } -> std::same_as<future<consumption_result<CharType>>>; }; template <typename Consumer, typename CharType> concept ObsoleteInputStreamConsumer = requires (Consumer c) { { c(temporary_buffer<CharType>{}) } -> std::same_as<future<std::optional<temporary_buffer<CharType>>>>; }; ) /// Buffers data from a data_source and provides a stream interface to the user. /// /// \note All methods must be called sequentially. That is, no method may be /// invoked before the previous method's returned future is resolved. template <typename CharType> class input_stream final { static_assert(sizeof(CharType) == 1, "must buffer stream of bytes"); data_source _fd; temporary_buffer<CharType> _buf; bool _eof = false; private: using tmp_buf = temporary_buffer<CharType>; size_t available() const { return _buf.size(); } protected: void reset() { _buf = {}; } data_source* fd() { return &_fd; } public: using consumption_result_type = consumption_result<CharType>; // unconsumed_remainder is mapped for compatibility only; new code should use consumption_result_type using unconsumed_remainder = std::optional<tmp_buf>; using char_type = CharType; input_stream() noexcept = default; explicit input_stream(data_source fd) noexcept : _fd(std::move(fd)), _buf() {} input_stream(input_stream&&) = default; input_stream& operator=(input_stream&&) = default; future<temporary_buffer<CharType>> read_exactly(size_t n); template <typename Consumer> SEASTAR_CONCEPT(requires InputStreamConsumer<Consumer, CharType> || ObsoleteInputStreamConsumer<Consumer, CharType>) future<> consume(Consumer&& c); template <typename Consumer> SEASTAR_CONCEPT(requires InputStreamConsumer<Consumer, CharType> || ObsoleteInputStreamConsumer<Consumer, CharType>) future<> consume(Consumer& c); bool eof() const { return _eof; } /// Returns some data from the stream, or an empty buffer on end of /// stream. future<tmp_buf> read(); /// Returns up to n bytes from the stream, or an empty buffer on end of /// stream. future<tmp_buf> read_up_to(size_t n); /// Detaches the \c input_stream from the underlying data source. /// /// Waits for any background operations (for example, read-ahead) to /// complete, so that the any resources the stream is using can be /// safely destroyed. An example is a \ref file resource used by /// the stream returned by make_file_input_stream(). /// /// \return a future that becomes ready when this stream no longer /// needs the data source. future<> close() { return _fd.close(); } /// Ignores n next bytes from the stream. future<> skip(uint64_t n); /// Detaches the underlying \c data_source from the \c input_stream. /// /// The intended usage is custom \c data_source_impl implementations /// wrapping an existing \c input_stream, therefore it shouldn't be /// called on an \c input_stream that was already used. /// After calling \c detach() the \c input_stream is in an unusable, /// moved-from state. /// /// \throws std::logic_error if called on a used stream /// /// \returns the data_source data_source detach() &&; private: future<temporary_buffer<CharType>> read_exactly_part(size_t n, tmp_buf buf, size_t completed); }; /// Facilitates data buffering before it's handed over to data_sink. /// /// When trim_to_size is true it's guaranteed that data sink will not receive /// chunks larger than the configured size, which could be the case when a /// single write call is made with data larger than the configured size. /// /// The data sink will not receive empty chunks. /// /// \note All methods must be called sequentially. That is, no method /// may be invoked before the previous method's returned future is /// resolved. template <typename CharType> class output_stream final { static_assert(sizeof(CharType) == 1, "must buffer stream of bytes"); data_sink _fd; temporary_buffer<CharType> _buf; net::packet _zc_bufs = net::packet::make_null_packet(); //zero copy buffers size_t _size = 0; size_t _begin = 0; size_t _end = 0; bool _trim_to_size = false; bool _batch_flushes = false; std::optional<promise<>> _in_batch; bool _flush = false; bool _flushing = false; std::exception_ptr _ex; private: size_t available() const { return _end - _begin; } size_t possibly_available() const { return _size - _begin; } future<> split_and_put(temporary_buffer<CharType> buf); future<> put(temporary_buffer<CharType> buf); void poll_flush(); future<> zero_copy_put(net::packet p); future<> zero_copy_split_and_put(net::packet p); [[gnu::noinline]] future<> slow_write(const CharType* buf, size_t n); public: using char_type = CharType; output_stream() noexcept = default; output_stream(data_sink fd, size_t size, bool trim_to_size = false, bool batch_flushes = false) noexcept : _fd(std::move(fd)), _size(size), _trim_to_size(trim_to_size), _batch_flushes(batch_flushes) {} output_stream(output_stream&&) noexcept = default; output_stream& operator=(output_stream&&) noexcept = default; ~output_stream() { assert(!_in_batch && "Was this stream properly closed?"); } future<> write(const char_type* buf, size_t n); future<> write(const char_type* buf); template <typename StringChar, typename SizeType, SizeType MaxSize, bool NulTerminate> future<> write(const basic_sstring<StringChar, SizeType, MaxSize, NulTerminate>& s); future<> write(const std::basic_string<char_type>& s); future<> write(net::packet p); future<> write(scattered_message<char_type> msg); future<> write(temporary_buffer<char_type>); future<> flush(); /// Flushes the stream before closing it (and the underlying data sink) to /// any further writes. The resulting future must be waited on before /// destroying this object. future<> close(); /// Detaches the underlying \c data_sink from the \c output_stream. /// /// The intended usage is custom \c data_sink_impl implementations /// wrapping an existing \c output_stream, therefore it shouldn't be /// called on an \c output_stream that was already used. /// After calling \c detach() the \c output_stream is in an unusable, /// moved-from state. /// /// \throws std::logic_error if called on a used stream /// /// \returns the data_sink data_sink detach() &&; private: friend class reactor; }; /*! * \brief copy all the content from the input stream to the output stream */ template <typename CharType> future<> copy(input_stream<CharType>&, output_stream<CharType>&); } #include "iostream-impl.hh" <commit_msg>iostream: document the read_exactly() function<commit_after>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2015 Cloudius Systems, Ltd. */ // // Buffered input and output streams // // Two abstract classes (data_source and data_sink) provide means // to acquire bulk data from, or push bulk data to, some provider. // These could be tied to a TCP connection, a disk file, or a memory // buffer. // // Two concrete classes (input_stream and output_stream) buffer data // from data_source and data_sink and provide easier means to process // it. // #pragma once #include <seastar/core/future.hh> #include <seastar/core/temporary_buffer.hh> #include <seastar/core/scattered_message.hh> #include <seastar/util/std-compat.hh> namespace seastar { namespace net { class packet; } class data_source_impl { public: virtual ~data_source_impl() {} virtual future<temporary_buffer<char>> get() = 0; virtual future<temporary_buffer<char>> skip(uint64_t n); virtual future<> close() { return make_ready_future<>(); } }; class data_source { std::unique_ptr<data_source_impl> _dsi; protected: data_source_impl* impl() const { return _dsi.get(); } public: data_source() noexcept = default; explicit data_source(std::unique_ptr<data_source_impl> dsi) noexcept : _dsi(std::move(dsi)) {} data_source(data_source&& x) noexcept = default; data_source& operator=(data_source&& x) noexcept = default; future<temporary_buffer<char>> get() { return _dsi->get(); } future<temporary_buffer<char>> skip(uint64_t n) { return _dsi->skip(n); } future<> close() { return _dsi->close(); } }; class data_sink_impl { public: virtual ~data_sink_impl() {} virtual temporary_buffer<char> allocate_buffer(size_t size) { return temporary_buffer<char>(size); } virtual future<> put(net::packet data) = 0; virtual future<> put(std::vector<temporary_buffer<char>> data) { net::packet p; p.reserve(data.size()); for (auto& buf : data) { p = net::packet(std::move(p), net::fragment{buf.get_write(), buf.size()}, buf.release()); } return put(std::move(p)); } virtual future<> put(temporary_buffer<char> buf) { return put(net::packet(net::fragment{buf.get_write(), buf.size()}, buf.release())); } virtual future<> flush() { return make_ready_future<>(); } virtual future<> close() = 0; }; class data_sink { std::unique_ptr<data_sink_impl> _dsi; public: data_sink() noexcept = default; explicit data_sink(std::unique_ptr<data_sink_impl> dsi) noexcept : _dsi(std::move(dsi)) {} data_sink(data_sink&& x) noexcept = default; data_sink& operator=(data_sink&& x) noexcept = default; temporary_buffer<char> allocate_buffer(size_t size) { return _dsi->allocate_buffer(size); } future<> put(std::vector<temporary_buffer<char>> data) { return _dsi->put(std::move(data)); } future<> put(temporary_buffer<char> data) { return _dsi->put(std::move(data)); } future<> put(net::packet p) { return _dsi->put(std::move(p)); } future<> flush() { return _dsi->flush(); } future<> close() { return _dsi->close(); } }; struct continue_consuming {}; template <typename CharType> class stop_consuming { public: using tmp_buf = temporary_buffer<CharType>; explicit stop_consuming(tmp_buf buf) : _buf(std::move(buf)) {} tmp_buf& get_buffer() { return _buf; } const tmp_buf& get_buffer() const { return _buf; } private: tmp_buf _buf; }; class skip_bytes { public: explicit skip_bytes(uint64_t v) : _value(v) {} uint64_t get_value() const { return _value; } private: uint64_t _value; }; template <typename CharType> class consumption_result { public: using stop_consuming_type = stop_consuming<CharType>; using consumption_variant = std::variant<continue_consuming, stop_consuming_type, skip_bytes>; using tmp_buf = typename stop_consuming_type::tmp_buf; /*[[deprecated]]*/ consumption_result(std::optional<tmp_buf> opt_buf) { if (opt_buf) { _result = stop_consuming_type{std::move(opt_buf.value())}; } } consumption_result(const continue_consuming&) {} consumption_result(stop_consuming_type&& stop) : _result(std::move(stop)) {} consumption_result(skip_bytes&& skip) : _result(std::move(skip)) {} consumption_variant& get() { return _result; } const consumption_variant& get() const { return _result; } private: consumption_variant _result; }; // Consumer concept, for consume() method SEASTAR_CONCEPT( // The consumer should operate on the data given to it, and // return a future "consumption result", which can be // - continue_consuming, if the consumer has consumed all the input given // to it and is ready for more // - stop_consuming, when the consumer is done (and in that case // the contained buffer is the unconsumed part of the last data buffer - this // can also happen to be empty). // - skip_bytes, when the consumer has consumed all the input given to it // and wants to skip before processing the next chunk // // For backward compatibility reasons, we also support the deprecated return value // of type "unconsumed remainder" which can be // - empty optional, if the consumer consumed all the input given to it // and is ready for more // - non-empty optional, when the consumer is done (and in that case // the value is the unconsumed part of the last data buffer - this // can also happen to be empty). template <typename Consumer, typename CharType> concept InputStreamConsumer = requires (Consumer c) { { c(temporary_buffer<CharType>{}) } -> std::same_as<future<consumption_result<CharType>>>; }; template <typename Consumer, typename CharType> concept ObsoleteInputStreamConsumer = requires (Consumer c) { { c(temporary_buffer<CharType>{}) } -> std::same_as<future<std::optional<temporary_buffer<CharType>>>>; }; ) /// Buffers data from a data_source and provides a stream interface to the user. /// /// \note All methods must be called sequentially. That is, no method may be /// invoked before the previous method's returned future is resolved. template <typename CharType> class input_stream final { static_assert(sizeof(CharType) == 1, "must buffer stream of bytes"); data_source _fd; temporary_buffer<CharType> _buf; bool _eof = false; private: using tmp_buf = temporary_buffer<CharType>; size_t available() const { return _buf.size(); } protected: void reset() { _buf = {}; } data_source* fd() { return &_fd; } public: using consumption_result_type = consumption_result<CharType>; // unconsumed_remainder is mapped for compatibility only; new code should use consumption_result_type using unconsumed_remainder = std::optional<tmp_buf>; using char_type = CharType; input_stream() noexcept = default; explicit input_stream(data_source fd) noexcept : _fd(std::move(fd)), _buf() {} input_stream(input_stream&&) = default; input_stream& operator=(input_stream&&) = default; /// Reads n bytes from the stream, or fewer if reached the end of stream. /// /// \returns a future that waits until n bytes are available in the /// stream and returns them. If the end of stream is reached before n /// bytes were read, fewer than n bytes will be returned - so despite /// the method's name, the caller must not assume the returned buffer /// will always contain exactly n bytes. /// /// \throws if an I/O error occurs during the read. As explained above, /// prematurely reaching the end of stream is *not* an I/O error. future<temporary_buffer<CharType>> read_exactly(size_t n); template <typename Consumer> SEASTAR_CONCEPT(requires InputStreamConsumer<Consumer, CharType> || ObsoleteInputStreamConsumer<Consumer, CharType>) future<> consume(Consumer&& c); template <typename Consumer> SEASTAR_CONCEPT(requires InputStreamConsumer<Consumer, CharType> || ObsoleteInputStreamConsumer<Consumer, CharType>) future<> consume(Consumer& c); bool eof() const { return _eof; } /// Returns some data from the stream, or an empty buffer on end of /// stream. future<tmp_buf> read(); /// Returns up to n bytes from the stream, or an empty buffer on end of /// stream. future<tmp_buf> read_up_to(size_t n); /// Detaches the \c input_stream from the underlying data source. /// /// Waits for any background operations (for example, read-ahead) to /// complete, so that the any resources the stream is using can be /// safely destroyed. An example is a \ref file resource used by /// the stream returned by make_file_input_stream(). /// /// \return a future that becomes ready when this stream no longer /// needs the data source. future<> close() { return _fd.close(); } /// Ignores n next bytes from the stream. future<> skip(uint64_t n); /// Detaches the underlying \c data_source from the \c input_stream. /// /// The intended usage is custom \c data_source_impl implementations /// wrapping an existing \c input_stream, therefore it shouldn't be /// called on an \c input_stream that was already used. /// After calling \c detach() the \c input_stream is in an unusable, /// moved-from state. /// /// \throws std::logic_error if called on a used stream /// /// \returns the data_source data_source detach() &&; private: future<temporary_buffer<CharType>> read_exactly_part(size_t n, tmp_buf buf, size_t completed); }; /// Facilitates data buffering before it's handed over to data_sink. /// /// When trim_to_size is true it's guaranteed that data sink will not receive /// chunks larger than the configured size, which could be the case when a /// single write call is made with data larger than the configured size. /// /// The data sink will not receive empty chunks. /// /// \note All methods must be called sequentially. That is, no method /// may be invoked before the previous method's returned future is /// resolved. template <typename CharType> class output_stream final { static_assert(sizeof(CharType) == 1, "must buffer stream of bytes"); data_sink _fd; temporary_buffer<CharType> _buf; net::packet _zc_bufs = net::packet::make_null_packet(); //zero copy buffers size_t _size = 0; size_t _begin = 0; size_t _end = 0; bool _trim_to_size = false; bool _batch_flushes = false; std::optional<promise<>> _in_batch; bool _flush = false; bool _flushing = false; std::exception_ptr _ex; private: size_t available() const { return _end - _begin; } size_t possibly_available() const { return _size - _begin; } future<> split_and_put(temporary_buffer<CharType> buf); future<> put(temporary_buffer<CharType> buf); void poll_flush(); future<> zero_copy_put(net::packet p); future<> zero_copy_split_and_put(net::packet p); [[gnu::noinline]] future<> slow_write(const CharType* buf, size_t n); public: using char_type = CharType; output_stream() noexcept = default; output_stream(data_sink fd, size_t size, bool trim_to_size = false, bool batch_flushes = false) noexcept : _fd(std::move(fd)), _size(size), _trim_to_size(trim_to_size), _batch_flushes(batch_flushes) {} output_stream(output_stream&&) noexcept = default; output_stream& operator=(output_stream&&) noexcept = default; ~output_stream() { assert(!_in_batch && "Was this stream properly closed?"); } future<> write(const char_type* buf, size_t n); future<> write(const char_type* buf); template <typename StringChar, typename SizeType, SizeType MaxSize, bool NulTerminate> future<> write(const basic_sstring<StringChar, SizeType, MaxSize, NulTerminate>& s); future<> write(const std::basic_string<char_type>& s); future<> write(net::packet p); future<> write(scattered_message<char_type> msg); future<> write(temporary_buffer<char_type>); future<> flush(); /// Flushes the stream before closing it (and the underlying data sink) to /// any further writes. The resulting future must be waited on before /// destroying this object. future<> close(); /// Detaches the underlying \c data_sink from the \c output_stream. /// /// The intended usage is custom \c data_sink_impl implementations /// wrapping an existing \c output_stream, therefore it shouldn't be /// called on an \c output_stream that was already used. /// After calling \c detach() the \c output_stream is in an unusable, /// moved-from state. /// /// \throws std::logic_error if called on a used stream /// /// \returns the data_sink data_sink detach() &&; private: friend class reactor; }; /*! * \brief copy all the content from the input stream to the output stream */ template <typename CharType> future<> copy(input_stream<CharType>&, output_stream<CharType>&); } #include "iostream-impl.hh" <|endoftext|>
<commit_before>#pragma once #include <iostream> #include <eigen/Dense> template<typename Type> struct SimplexSolver { Eigen::Matrix<Type, Eigen::Dynamic, Eigen::Dynamic> matrix; // see https://www.youtube.com/watch?v=Axg9OhJ4cjg (german) bottom row is negative unlike in the video // TODO< handle special cases > void iterate() { for(;;) { bool foundMaximumColumn; const int pivotColumnIndex = searchMinimumColumn(foundMaximumColumn); // all values in the target value row are < 0.0, done if( !foundMaximumColumn ) { std::cout << "no found!" << std::endl; break; } std::cout << "min column " << pivotColumnIndex << std::endl; // divide numbers of pivot column with right side and store in temporary vector Eigen::Matrix<Type, Eigen::Dynamic, 1> temporaryVector = divideRightSideWithPivotColumnWhereAboveZero(pivotColumnIndex); const int minIndexOfTargetFunctionCoefficient = getMinIndexOfVector(temporaryVector); const int pivotRowIndex = minIndexOfTargetFunctionCoefficient; std::cout << "pivotRowIndex " << pivotRowIndex << std::endl; Type pivotElement = matrix(pivotRowIndex, pivotColumnIndex); // divide the pivot row with the pivot element matrix.block(pivotRowIndex,0, 1, matrix.cols()) /= pivotElement; //std::cout << "after divide the pivot row with the pivot element " << std::endl; //std::cout << matrix << std::endl; // TODO< assert that pivot elemnt is roughtly 1.0 > // do pivot operation for(int pivotRowIteration = 0; pivotRowIteration < matrix.rows(); pivotRowIteration++ ) { if( pivotRowIteration == pivotRowIndex ) { continue; } Type iterationElementAtPivotColumn = matrix(pivotRowIteration, pivotColumnIndex); matrix.block(pivotRowIteration,0, 1, matrix.cols()) -= (matrix.block(pivotRowIndex, 0, 1, matrix.cols()) * iterationElementAtPivotColumn); } // TODO< set the variable identifier for the pivot element > std::cout << matrix << std::endl; } } protected: int searchMinimumColumn(bool &foundMinimumColumn) { foundMinimumColumn = false; const int matrixRowCount = matrix.rows(); Type minValue = static_cast<Type>(0.0); int minColumn = -1; for( int iterationColumn = 0; iterationColumn < matrix.cols()-1; iterationColumn++ ) { if( matrix(matrixRowCount-1, iterationColumn) < minValue ) { minValue = matrix(matrixRowCount-1, iterationColumn); minColumn = iterationColumn; foundMinimumColumn = true; } } return minColumn; } Eigen::Matrix<Type, Eigen::Dynamic, 1> divideRightSideWithPivotColumnWhereAboveZero(int pivotColumnIndex) { const int matrixRowCount = matrix.rows(); const int matrixColumnCount = matrix.cols(); Eigen::Matrix<Type, Eigen::Dynamic, 1> result(matrix.rows()-1, 1); for( int rowIndex = 0; rowIndex < matrixRowCount-1; rowIndex++ ) { if( matrix(rowIndex, pivotColumnIndex) > static_cast<Type>(0.0) ) { result(rowIndex) = matrix(rowIndex, matrixColumnCount-1) / matrix(rowIndex, pivotColumnIndex); } else { // ASK< we set it just to the right side > result(rowIndex) = matrix(rowIndex, matrixColumnCount-1); } } return result; } static int getMinIndexOfVector(const Eigen::Matrix<Type, Eigen::Dynamic, 1> &vector) { Type min = vector(0); int minIndex = 0; for( int index = 1; index < vector.rows(); index++ ) { if( vector(index) < min ) { min = vector(index); minIndex = 0; } } return minIndex; } }; <commit_msg>Added SimplexSolver, still incomplete<commit_after>#pragma once #include "memory/FixedAllocator.h" #include <iostream> #include <eigen/Dense> template<typename Type> struct SimplexSolver { struct Variable { enum class EnumType { NAMEME, // TODO< name me > LASTLINE, // TODO< give proper name > UNUSED }; Variable() { this->type = EnumType::UNUSED; } Variable(EnumType type, int identifier) { this->type = type; this->identifier = identifier; } int identifier; EnumType type; }; struct Result { enum class EnumSolverState { FOUNDSOLUTION, UNBOUNDEDSOLUTION, TOOMANYITERATIONS }; Result(Result::EnumSolverState state) { this->state = state; } Result::EnumSolverState state; }; Eigen::Matrix<Type, Eigen::Dynamic, Eigen::Dynamic> matrix; static const unsigned SizeOfVariableArray = 256; // FIXME< not fixed size allocator for special cases > FixedAllocator<SizeOfVariableArray, Variable> variables; SimplexSolver() {}; // see https://www.youtube.com/watch?v=Axg9OhJ4cjg (german) bottom row is negative unlike in the video // see http://de.slideshare.net/itsmedv91/special-cases-in-simplex special cases // TODO< handle other special cases > Result iterate() { setupVariables(); // for now we use a iteration counter to protect us from infinite loops // TODO< implement loop detection scheme, basic idea // * we manage a fixed sized array as a sliding window or the hashes of the operations // * if we detect a loop we apply bland's rule to resolve it (is the rule detection realy neccesary?) // // // * every operation (pivot column, pivot row, number of pivot element itself) gets an hash // * at each iteration we subtract the previous hash and add the current hash // * if the hash doesn't change in n iteration(where n == 2 for the simple loop) we are looping // > // TODO< implement https://en.wikipedia.org/wiki/Bland's_rule > unsigned iterationCounter = 0; const unsigned MaximalIterationCounter = 128; for(;;) { iterationCounter++; if( iterationCounter > MaximalIterationCounter ) { return Result(Result::EnumSolverState::TOOMANYITERATIONS); } bool foundMaximumColumn; const int pivotColumnIndex = searchMinimumColumn(foundMaximumColumn); // all values in the target value row are < 0.0, done if( !foundMaximumColumn ) { return Result(Result::EnumSolverState::FOUNDSOLUTION); } //std::cout << "min column " << pivotColumnIndex << std::endl; if( areAllEntriesOfPivotColumnNegativeOrZero(pivotColumnIndex) ) { // solution is unbounded return Result(Result::EnumSolverState::UNBOUNDEDSOLUTION); } // divide numbers of pivot column with right side and store in temporary vector Eigen::Matrix<Type, Eigen::Dynamic, 1> minRatioVector = divideRightSideWithPivotColumnWhereAboveZero(pivotColumnIndex); //std::cout << "temporary vector" << std::endl; //std::cout << minRatioVector << std::endl; const int minIndexOfTargetFunctionCoefficient = getMinIndexOfMinRatioVector(minRatioVector); const bool positiveMinRatioExists = doesPositiveMinRatioExist(minRatioVector); if( !positiveMinRatioExists ) { // solution is unbounded return Result(Result::EnumSolverState::UNBOUNDEDSOLUTION); } const int pivotRowIndex = minIndexOfTargetFunctionCoefficient; //std::cout << "pivotRowIndex " << pivotRowIndex << std::endl; Type pivotElement = matrix(pivotRowIndex, pivotColumnIndex); // divide the pivot row with the pivot element matrix.block(pivotRowIndex,0, 1, matrix.cols()) /= pivotElement; // TODO< assert that pivot elemnt is roughtly 1.0 > // do pivot operation for(int pivotRowIteration = 0; pivotRowIteration < matrix.rows(); pivotRowIteration++ ) { if( pivotRowIteration == pivotRowIndex ) { continue; } Type iterationElementAtPivotColumn = matrix(pivotRowIteration, pivotColumnIndex); matrix.block(pivotRowIteration, 0, 1, matrix.cols()) -= (matrix.block(pivotRowIndex, 0, 1, matrix.cols()) * iterationElementAtPivotColumn); } // set the variable identifier that we know which row of the matrix is for which variable variables[pivotRowIndex] = Variable(Variable::EnumType::NAMEME, pivotColumnIndex); //std::cout << matrix << std::endl; } } protected: void setupVariables() { // TODO } int searchMinimumColumn(bool &foundMinimumColumn) { foundMinimumColumn = false; const int matrixRowCount = matrix.rows(); Type minValue = static_cast<Type>(0.0); int minColumn = -1; for( int iterationColumn = 0; iterationColumn < matrix.cols()-1; iterationColumn++ ) { if( matrix(matrixRowCount-1, iterationColumn) < minValue ) { minValue = matrix(matrixRowCount-1, iterationColumn); minColumn = iterationColumn; foundMinimumColumn = true; } } return minColumn; } Eigen::Matrix<Type, Eigen::Dynamic, 1> divideRightSideWithPivotColumnWhereAboveZero(int pivotColumnIndex) { const int matrixRowCount = matrix.rows(); const int matrixColumnCount = matrix.cols(); Eigen::Matrix<Type, Eigen::Dynamic, 1> result(matrix.rows()-1, 1); for( int rowIndex = 0; rowIndex < matrixRowCount-1; rowIndex++ ) { if( matrix(rowIndex, pivotColumnIndex) > static_cast<Type>(0.0) ) { result(rowIndex) = matrix(rowIndex, matrixColumnCount-1) / matrix(rowIndex, pivotColumnIndex); } else { // ASK< we set it just to the right side > result(rowIndex) = matrix(rowIndex, matrixColumnCount-1); } } return result; } bool areAllEntriesOfPivotColumnNegativeOrZero(const int pivotColumnIndex) { for( int rowIndex = 0; rowIndex < matrix.rows()-1; rowIndex++ ) { if( matrix(rowIndex, pivotColumnIndex) > static_cast<Type>(0.0) ) { return false; } } return true; } static int getMinIndexOfMinRatioVector(const Eigen::Matrix<Type, Eigen::Dynamic, 1> &vector) { int index; vector.minCoeff(&index); return index; } static bool doesPositiveMinRatioExist(const Eigen::Matrix<Type, Eigen::Dynamic, 1> &vector) { for( int i = 0; i < vector.rows(); i++ ) { if( vector(i) > static_cast<Type>(0.0) ) { return true; } } return false; } }; <|endoftext|>
<commit_before>#ifndef _CPP_CALLSEQUENCE_HPP_ #define _CPP_CALLSEQUENCE_HPP_ #include <tuple> namespace toolbox { namespace cpp { template<typename... Functors> class call_seq { public: call_seq(Functors... functors) : functors_(functors...) {} template<typename... Args> void operator()(Args&&... args) { exec<0>(args...); } private: template<std::size_t I, typename... Args> std::enable_if_t<I < sizeof...(Functors) - 1, void> exec(Args&&... args) { std::get<I>(functors_)(args...); exec<I + 1>(args...); } template<std::size_t I, typename... Args> std::enable_if_t<I == sizeof...(Functors) - 1, void> exec(Args&&... args) { std::get<I>(functors_)(args...); } private: std::tuple<Functors...> functors_; }; template<typename... Functors> auto make_call_seq(Functors... functors) { return call_seq<Functors...>(functors...); } } // namespace cpp } // namespace toolbox #endif <commit_msg>retab<commit_after>#ifndef _CPP_CALLSEQUENCE_HPP_ #define _CPP_CALLSEQUENCE_HPP_ #include <tuple> namespace toolbox { namespace cpp { template<typename... Functors> class call_seq { public: call_seq(Functors... functors) : functors_(functors...) {} template<typename... Args> void operator()(Args&&... args) { exec<0>(args...); } private: template<std::size_t I, typename... Args> std::enable_if_t<I < sizeof...(Functors) - 1, void> exec(Args&&... args) { std::get<I>(functors_)(args...); exec<I + 1>(args...); } template<std::size_t I, typename... Args> std::enable_if_t<I == sizeof...(Functors) - 1, void> exec(Args&&... args) { std::get<I>(functors_)(args...); } private: std::tuple<Functors...> functors_; }; template<typename... Functors> auto make_call_seq(Functors... functors) { return call_seq<Functors...>(functors...); } } // namespace cpp } // namespace toolbox #endif <|endoftext|>
<commit_before>#pragma once #include <gcl/mp/concepts.hpp> #include <concepts> namespace gcl::mp::value_traits { template <auto... values> struct sequence { constexpr static auto size = sizeof...(values); }; template <auto... values> requires(std::equality_comparable_with< decltype(std::get<0>(std::tuple{values...})), decltype(values)>&&...) constexpr static auto equal_v = []() consteval { return ((values == std::get<0>(std::tuple{values...})) && ...); } (); // Only works for Clang yet, since 11.0.0 // template <auto first_value = int{}, std::equality_comparable_with<decltype(first_value)> auto... values> // constexpr inline auto equal_v = []() consteval // { // return ((values == first_value) && ...); // } // (); template <auto... values> constexpr inline auto not_equal_v = not equal_v<values...>; } #include <cstdint> #include <climits> namespace gcl::mp::value_traits { template <typename T> constexpr inline std::size_t bit_size_v = sizeof(T) * CHAR_BIT; // sizeof(bool) is implementation-defined, // but here we expect - thus, define - that a boolean is 1 bit-long template <> constexpr inline std::size_t bit_size_v<bool> = 1; template <typename T> requires(bit_size_v<std::uintmax_t> > bit_size_v<T>) constexpr static auto values_count = (std::uintmax_t{1} << bit_size_v<T>); } namespace gcl::mp::value_traits::tests::equal { static_assert(equal_v<>); static_assert(equal_v<true>); static_assert(equal_v<true, true>); static_assert(equal_v<true, true, true>); static_assert(equal_v<true, true, true, true>); static_assert(not not_equal_v<true>); static_assert(not_equal_v<true, false>); static_assert(not_equal_v<false, true>); static_assert(not_equal_v<false, true, true>); static_assert(not_equal_v<true, false, true>); static_assert(not_equal_v<true, true, false>); static_assert(not_equal_v<false, true, true, true>); static_assert(not_equal_v<true, false, true, true>); static_assert(not_equal_v<true, true, false, true>); static_assert(not_equal_v<true, true, true, false>); } #include <gcl/mp/system_info.hpp> #include <limits> namespace gcl::mp::value_traits::tests { static void bit_size_v() { if constexpr (gcl::mp::system_info::is_x64) { // might be wrong, depending on the target/plateform static_assert(gcl::mp::value_traits::bit_size_v<bool> == 1); static_assert(gcl::mp::value_traits::bit_size_v<char> == 8); static_assert(gcl::mp::value_traits::bit_size_v<int8_t> == 8); static_assert(gcl::mp::value_traits::bit_size_v<uint8_t> == 8); static_assert(gcl::mp::value_traits::bit_size_v<int16_t> == 16); static_assert(gcl::mp::value_traits::bit_size_v<uint16_t> == 16); static_assert(gcl::mp::value_traits::bit_size_v<int32_t> == 32); static_assert(gcl::mp::value_traits::bit_size_v<uint32_t> == 32); static_assert(gcl::mp::value_traits::bit_size_v<int64_t> == 64); static_assert(gcl::mp::value_traits::bit_size_v<uint64_t> == 64); } } static void values_count() { if constexpr (gcl::mp::system_info::is_x64) { // might be wrong, depending on the target/plateform static_assert(gcl::mp::value_traits::values_count<bool> == 2); static_assert(gcl::mp::value_traits::values_count<char> - 1 == std::numeric_limits<unsigned char>::max()); static_assert(gcl::mp::value_traits::values_count<int8_t> - 1 == std::numeric_limits<uint8_t>::max()); static_assert(gcl::mp::value_traits::values_count<uint8_t> - 1 == std::numeric_limits<uint8_t>::max()); static_assert(gcl::mp::value_traits::values_count<int16_t> - 1 == std::numeric_limits<uint16_t>::max()); static_assert(gcl::mp::value_traits::values_count<uint16_t> - 1 == std::numeric_limits<uint16_t>::max()); static_assert(gcl::mp::value_traits::values_count<int32_t> - 1 == std::numeric_limits<uint32_t>::max()); static_assert(gcl::mp::value_traits::values_count<uint32_t> - 1 == std::numeric_limits<uint32_t>::max()); // violate `values_count` constraint : // C4293: '<<': shift count negative or too big, undefined behavior /*static_assert(gcl::mp::value_traits::values_count<int64_t> - 1 == std::numeric_limits<uint64_t>::max()); static_assert(gcl::mp::value_traits::values_count<uint64_t> - 1 == std::numeric_limits<uint64_t>::max());*/ } } }<commit_msg>[mp/value_traits] remove static linkage on constant variable<commit_after>#pragma once #include <gcl/mp/concepts.hpp> #include <concepts> namespace gcl::mp::value_traits { template <auto... values> struct sequence { constexpr static auto size = sizeof...(values); }; template <auto... values> requires(std::equality_comparable_with< decltype(std::get<0>(std::tuple{values...})), decltype(values)>&&...) constexpr auto equal_v = []() consteval { return ((values == std::get<0>(std::tuple{values...})) && ...); } (); // Only works for Clang yet, since 11.0.0 // template <auto first_value = int{}, std::equality_comparable_with<decltype(first_value)> auto... values> // constexpr inline auto equal_v = []() consteval // { // return ((values == first_value) && ...); // } // (); template <auto... values> constexpr inline auto not_equal_v = not equal_v<values...>; } #include <cstdint> #include <climits> namespace gcl::mp::value_traits { template <typename T> constexpr inline std::size_t bit_size_v = sizeof(T) * CHAR_BIT; // sizeof(bool) is implementation-defined, // but here we expect - thus, define - that a boolean is 1 bit-long template <> constexpr inline std::size_t bit_size_v<bool> = 1; template <typename T> requires(bit_size_v<std::uintmax_t> > bit_size_v<T>) constexpr static auto values_count = (std::uintmax_t{1} << bit_size_v<T>); } namespace gcl::mp::value_traits::tests::equal { static_assert(equal_v<>); static_assert(equal_v<true>); static_assert(equal_v<true, true>); static_assert(equal_v<true, true, true>); static_assert(equal_v<true, true, true, true>); static_assert(not not_equal_v<true>); static_assert(not_equal_v<true, false>); static_assert(not_equal_v<false, true>); static_assert(not_equal_v<false, true, true>); static_assert(not_equal_v<true, false, true>); static_assert(not_equal_v<true, true, false>); static_assert(not_equal_v<false, true, true, true>); static_assert(not_equal_v<true, false, true, true>); static_assert(not_equal_v<true, true, false, true>); static_assert(not_equal_v<true, true, true, false>); } #include <gcl/mp/system_info.hpp> #include <limits> namespace gcl::mp::value_traits::tests { static void bit_size_v() { if constexpr (gcl::mp::system_info::is_x64) { // might be wrong, depending on the target/plateform static_assert(gcl::mp::value_traits::bit_size_v<bool> == 1); static_assert(gcl::mp::value_traits::bit_size_v<char> == 8); static_assert(gcl::mp::value_traits::bit_size_v<int8_t> == 8); static_assert(gcl::mp::value_traits::bit_size_v<uint8_t> == 8); static_assert(gcl::mp::value_traits::bit_size_v<int16_t> == 16); static_assert(gcl::mp::value_traits::bit_size_v<uint16_t> == 16); static_assert(gcl::mp::value_traits::bit_size_v<int32_t> == 32); static_assert(gcl::mp::value_traits::bit_size_v<uint32_t> == 32); static_assert(gcl::mp::value_traits::bit_size_v<int64_t> == 64); static_assert(gcl::mp::value_traits::bit_size_v<uint64_t> == 64); } } static void values_count() { if constexpr (gcl::mp::system_info::is_x64) { // might be wrong, depending on the target/plateform static_assert(gcl::mp::value_traits::values_count<bool> == 2); static_assert(gcl::mp::value_traits::values_count<char> - 1 == std::numeric_limits<unsigned char>::max()); static_assert(gcl::mp::value_traits::values_count<int8_t> - 1 == std::numeric_limits<uint8_t>::max()); static_assert(gcl::mp::value_traits::values_count<uint8_t> - 1 == std::numeric_limits<uint8_t>::max()); static_assert(gcl::mp::value_traits::values_count<int16_t> - 1 == std::numeric_limits<uint16_t>::max()); static_assert(gcl::mp::value_traits::values_count<uint16_t> - 1 == std::numeric_limits<uint16_t>::max()); static_assert(gcl::mp::value_traits::values_count<int32_t> - 1 == std::numeric_limits<uint32_t>::max()); static_assert(gcl::mp::value_traits::values_count<uint32_t> - 1 == std::numeric_limits<uint32_t>::max()); // violate `values_count` constraint : // C4293: '<<': shift count negative or too big, undefined behavior /*static_assert(gcl::mp::value_traits::values_count<int64_t> - 1 == std::numeric_limits<uint64_t>::max()); static_assert(gcl::mp::value_traits::values_count<uint64_t> - 1 == std::numeric_limits<uint64_t>::max());*/ } } }<|endoftext|>
<commit_before>/** * @file _httppolicy.cpp * @brief Internal definitions of the Http policy thread * * $LicenseInfo:firstyear=2012&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2012-2013, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "linden_common.h" #include "_httppolicy.h" #include "_httpoprequest.h" #include "_httpservice.h" #include "_httplibcurl.h" #include "_httppolicyclass.h" #include "lltimer.h" namespace LLCore { // Per-policy-class data for a running system. // Collection of queues, options and other data // for a single policy class. // // Threading: accessed only by worker thread struct HttpPolicy::ClassState { public: ClassState() : mThrottleEnd(0), mThrottleLeft(0L), mRequestCount(0L) {} HttpReadyQueue mReadyQueue; HttpRetryQueue mRetryQueue; HttpPolicyClass mOptions; HttpTime mThrottleEnd; long mThrottleLeft; long mRequestCount; }; HttpPolicy::HttpPolicy(HttpService * service) : mService(service) { // Create default class mClasses.push_back(new ClassState()); } HttpPolicy::~HttpPolicy() { shutdown(); for (class_list_t::iterator it(mClasses.begin()); it != mClasses.end(); ++it) { delete (*it); } mClasses.clear(); mService = NULL; } HttpRequest::policy_t HttpPolicy::createPolicyClass() { const HttpRequest::policy_t policy_class(mClasses.size()); if (policy_class >= HTTP_POLICY_CLASS_LIMIT) { return HttpRequest::INVALID_POLICY_ID; } mClasses.push_back(new ClassState()); return policy_class; } void HttpPolicy::shutdown() { for (int policy_class(0); policy_class < mClasses.size(); ++policy_class) { ClassState & state(*mClasses[policy_class]); HttpRetryQueue & retryq(state.mRetryQueue); while (! retryq.empty()) { HttpOpRequest * op(retryq.top()); retryq.pop(); op->cancel(); op->release(); } HttpReadyQueue & readyq(state.mReadyQueue); while (! readyq.empty()) { HttpOpRequest * op(readyq.top()); readyq.pop(); op->cancel(); op->release(); } } } void HttpPolicy::start() {} void HttpPolicy::addOp(HttpOpRequest * op) { const int policy_class(op->mReqPolicy); op->mPolicyRetries = 0; op->mPolicy503Retries = 0; mClasses[policy_class]->mReadyQueue.push(op); } void HttpPolicy::retryOp(HttpOpRequest * op) { static const HttpTime retry_deltas[] = { 250000, // 1st retry in 0.25 S, etc... 500000, 1000000, 2000000, 5000000 // ... to every 5.0 S. }; static const int delta_max(int(LL_ARRAY_SIZE(retry_deltas)) - 1); static const HttpStatus error_503(503); const HttpTime now(totalTime()); const int policy_class(op->mReqPolicy); HttpTime delta(retry_deltas[llclamp(op->mPolicyRetries, 0, delta_max)]); if (op->mReplyRetryAfter > 0 && op->mReplyRetryAfter < 30) { delta = op->mReplyRetryAfter * U64L(1000000); } op->mPolicyRetryAt = now + delta; ++op->mPolicyRetries; if (error_503 == op->mStatus) { ++op->mPolicy503Retries; } LL_DEBUGS("CoreHttp") << "HTTP request " << static_cast<HttpHandle>(op) << " retry " << op->mPolicyRetries << " scheduled in " << (delta / HttpTime(1000)) << " mS. Status: " << op->mStatus.toHex() << LL_ENDL; if (op->mTracing > HTTP_TRACE_OFF) { LL_INFOS("CoreHttp") << "TRACE, ToRetryQueue, Handle: " << static_cast<HttpHandle>(op) << ", Delta: " << (delta / HttpTime(1000)) << ", Retries: " << op->mPolicyRetries << LL_ENDL; } mClasses[policy_class]->mRetryQueue.push(op); } // Attempt to deliver requests to the transport layer. // // Tries to find HTTP requests for each policy class with // available capacity. Starts with the retry queue first // looking for requests that have waited long enough then // moves on to the ready queue. // // If all queues are empty, will return an indication that // the worker thread may sleep hard otherwise will ask for // normal polling frequency. // // Implements a client-side request rate throttle as well. // This is intended to mimic and predict throttling behavior // of grid services but that is difficult to do with different // time bases. This also represents a rigid coupling between // viewer and server that makes it hard to change parameters // and I hope we can make this go away with pipelining. // HttpService::ELoopSpeed HttpPolicy::processReadyQueue() { const HttpTime now(totalTime()); HttpService::ELoopSpeed result(HttpService::REQUEST_SLEEP); HttpLibcurl & transport(mService->getTransport()); for (int policy_class(0); policy_class < mClasses.size(); ++policy_class) { ClassState & state(*mClasses[policy_class]); HttpRetryQueue & retryq(state.mRetryQueue); HttpReadyQueue & readyq(state.mReadyQueue); if (retryq.empty() && readyq.empty()) { continue; } const bool throttle_enabled(state.mOptions.mThrottleRate > 0L); const bool throttle_current(throttle_enabled && now < state.mThrottleEnd); if (throttle_current && state.mThrottleLeft <= 0) { // Throttled condition, don't serve this class but don't sleep hard. result = HttpService::NORMAL; continue; } int active(transport.getActiveCountInClass(policy_class)); int needed(state.mOptions.mConnectionLimit - active); // Expect negatives here if (needed > 0) { // First see if we have any retries... while (needed > 0 && ! retryq.empty()) { HttpOpRequest * op(retryq.top()); if (op->mPolicyRetryAt > now) break; retryq.pop(); op->stageFromReady(mService); op->release(); ++state.mRequestCount; --needed; if (throttle_enabled) { if (now >= state.mThrottleEnd) { // Throttle expired, move to next window LL_DEBUGS("CoreHttp") << "Throttle expired with " << state.mThrottleLeft << " requests to go and " << state.mRequestCount << " requests issued." << LL_ENDL; state.mThrottleLeft = state.mOptions.mThrottleRate; state.mThrottleEnd = now + HttpTime(1000000); } if (--state.mThrottleLeft <= 0) { goto throttle_on; } } } // Now go on to the new requests... while (needed > 0 && ! readyq.empty()) { HttpOpRequest * op(readyq.top()); readyq.pop(); op->stageFromReady(mService); op->release(); ++state.mRequestCount; --needed; if (throttle_enabled) { if (now >= state.mThrottleEnd) { // Throttle expired, move to next window LL_DEBUGS("CoreHttp") << "Throttle expired with " << state.mThrottleLeft << " requests to go and " << state.mRequestCount << " requests issued." << LL_ENDL; state.mThrottleLeft = state.mOptions.mThrottleRate; state.mThrottleEnd = now + HttpTime(1000000); } if (--state.mThrottleLeft <= 0) { goto throttle_on; } } } } throttle_on: if (! readyq.empty() || ! retryq.empty()) { // If anything is ready, continue looping... result = HttpService::NORMAL; } } // end foreach policy_class return result; } bool HttpPolicy::changePriority(HttpHandle handle, HttpRequest::priority_t priority) { for (int policy_class(0); policy_class < mClasses.size(); ++policy_class) { ClassState & state(*mClasses[policy_class]); // We don't scan retry queue because a priority change there // is meaningless. The request will be issued based on retry // intervals not priority value, which is now moot. // Scan ready queue for requests that match policy HttpReadyQueue::container_type & c(state.mReadyQueue.get_container()); for (HttpReadyQueue::container_type::iterator iter(c.begin()); c.end() != iter;) { HttpReadyQueue::container_type::iterator cur(iter++); if (static_cast<HttpHandle>(*cur) == handle) { HttpOpRequest * op(*cur); c.erase(cur); // All iterators are now invalidated op->mReqPriority = priority; state.mReadyQueue.push(op); // Re-insert using adapter class return true; } } } return false; } bool HttpPolicy::cancel(HttpHandle handle) { for (int policy_class(0); policy_class < mClasses.size(); ++policy_class) { ClassState & state(*mClasses[policy_class]); // Scan retry queue HttpRetryQueue::container_type & c1(state.mRetryQueue.get_container()); for (HttpRetryQueue::container_type::iterator iter(c1.begin()); c1.end() != iter;) { HttpRetryQueue::container_type::iterator cur(iter++); if (static_cast<HttpHandle>(*cur) == handle) { HttpOpRequest * op(*cur); c1.erase(cur); // All iterators are now invalidated op->cancel(); op->release(); return true; } } // Scan ready queue HttpReadyQueue::container_type & c2(state.mReadyQueue.get_container()); for (HttpReadyQueue::container_type::iterator iter(c2.begin()); c2.end() != iter;) { HttpReadyQueue::container_type::iterator cur(iter++); if (static_cast<HttpHandle>(*cur) == handle) { HttpOpRequest * op(*cur); c2.erase(cur); // All iterators are now invalidated op->cancel(); op->release(); return true; } } } return false; } bool HttpPolicy::stageAfterCompletion(HttpOpRequest * op) { static const HttpStatus cant_connect(HttpStatus::EXT_CURL_EASY, CURLE_COULDNT_CONNECT); static const HttpStatus cant_res_proxy(HttpStatus::EXT_CURL_EASY, CURLE_COULDNT_RESOLVE_PROXY); static const HttpStatus cant_res_host(HttpStatus::EXT_CURL_EASY, CURLE_COULDNT_RESOLVE_HOST); static const HttpStatus send_error(HttpStatus::EXT_CURL_EASY, CURLE_SEND_ERROR); static const HttpStatus recv_error(HttpStatus::EXT_CURL_EASY, CURLE_RECV_ERROR); static const HttpStatus upload_failed(HttpStatus::EXT_CURL_EASY, CURLE_UPLOAD_FAILED); static const HttpStatus op_timedout(HttpStatus::EXT_CURL_EASY, CURLE_OPERATION_TIMEDOUT); static const HttpStatus post_error(HttpStatus::EXT_CURL_EASY, CURLE_HTTP_POST_ERROR); // Retry or finalize if (! op->mStatus) { // If this failed, we might want to retry. Have to inspect // the status a little more deeply for those reasons worth retrying... if (op->mPolicyRetries < op->mPolicyRetryLimit && ((op->mStatus.isHttpStatus() && op->mStatus.mType >= 499 && op->mStatus.mType <= 599) || cant_connect == op->mStatus || cant_res_proxy == op->mStatus || cant_res_host == op->mStatus || send_error == op->mStatus || recv_error == op->mStatus || upload_failed == op->mStatus || op_timedout == op->mStatus || post_error == op->mStatus)) { // Okay, worth a retry. We include 499 in this test as // it's the old 'who knows?' error from many grid services... retryOp(op); return true; // still active/ready } } // This op is done, finalize it delivering it to the reply queue... if (! op->mStatus) { LL_WARNS("CoreHttp") << "HTTP request " << static_cast<HttpHandle>(op) << " failed after " << op->mPolicyRetries << " retries. Reason: " << op->mStatus.toString() << " (" << op->mStatus.toHex() << ")" << LL_ENDL; } else if (op->mPolicyRetries) { LL_DEBUGS("CoreHttp") << "HTTP request " << static_cast<HttpHandle>(op) << " succeeded on retry " << op->mPolicyRetries << "." << LL_ENDL; } op->stageFromActive(mService); op->release(); return false; // not active } HttpPolicyClass & HttpPolicy::getClassOptions(HttpRequest::policy_t pclass) { llassert_always(pclass >= 0 && pclass < mClasses.size()); return mClasses[pclass]->mOptions; } int HttpPolicy::getReadyCount(HttpRequest::policy_t policy_class) const { if (policy_class < mClasses.size()) { return (mClasses[policy_class]->mReadyQueue.size() + mClasses[policy_class]->mRetryQueue.size()); } return 0; } } // end namespace LLCore <commit_msg>Add 'internal'/'external' token to DEBUG retry message so that dev/QA can know exactly where a retry value was sourced.<commit_after>/** * @file _httppolicy.cpp * @brief Internal definitions of the Http policy thread * * $LicenseInfo:firstyear=2012&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2012-2013, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "linden_common.h" #include "_httppolicy.h" #include "_httpoprequest.h" #include "_httpservice.h" #include "_httplibcurl.h" #include "_httppolicyclass.h" #include "lltimer.h" namespace LLCore { // Per-policy-class data for a running system. // Collection of queues, options and other data // for a single policy class. // // Threading: accessed only by worker thread struct HttpPolicy::ClassState { public: ClassState() : mThrottleEnd(0), mThrottleLeft(0L), mRequestCount(0L) {} HttpReadyQueue mReadyQueue; HttpRetryQueue mRetryQueue; HttpPolicyClass mOptions; HttpTime mThrottleEnd; long mThrottleLeft; long mRequestCount; }; HttpPolicy::HttpPolicy(HttpService * service) : mService(service) { // Create default class mClasses.push_back(new ClassState()); } HttpPolicy::~HttpPolicy() { shutdown(); for (class_list_t::iterator it(mClasses.begin()); it != mClasses.end(); ++it) { delete (*it); } mClasses.clear(); mService = NULL; } HttpRequest::policy_t HttpPolicy::createPolicyClass() { const HttpRequest::policy_t policy_class(mClasses.size()); if (policy_class >= HTTP_POLICY_CLASS_LIMIT) { return HttpRequest::INVALID_POLICY_ID; } mClasses.push_back(new ClassState()); return policy_class; } void HttpPolicy::shutdown() { for (int policy_class(0); policy_class < mClasses.size(); ++policy_class) { ClassState & state(*mClasses[policy_class]); HttpRetryQueue & retryq(state.mRetryQueue); while (! retryq.empty()) { HttpOpRequest * op(retryq.top()); retryq.pop(); op->cancel(); op->release(); } HttpReadyQueue & readyq(state.mReadyQueue); while (! readyq.empty()) { HttpOpRequest * op(readyq.top()); readyq.pop(); op->cancel(); op->release(); } } } void HttpPolicy::start() {} void HttpPolicy::addOp(HttpOpRequest * op) { const int policy_class(op->mReqPolicy); op->mPolicyRetries = 0; op->mPolicy503Retries = 0; mClasses[policy_class]->mReadyQueue.push(op); } void HttpPolicy::retryOp(HttpOpRequest * op) { static const HttpTime retry_deltas[] = { 250000, // 1st retry in 0.25 S, etc... 500000, 1000000, 2000000, 5000000 // ... to every 5.0 S. }; static const int delta_max(int(LL_ARRAY_SIZE(retry_deltas)) - 1); static const HttpStatus error_503(503); const HttpTime now(totalTime()); const int policy_class(op->mReqPolicy); HttpTime delta(retry_deltas[llclamp(op->mPolicyRetries, 0, delta_max)]); bool external_delta(false); if (op->mReplyRetryAfter > 0 && op->mReplyRetryAfter < 30) { delta = op->mReplyRetryAfter * U64L(1000000); external_delta = true; } op->mPolicyRetryAt = now + delta; ++op->mPolicyRetries; if (error_503 == op->mStatus) { ++op->mPolicy503Retries; } LL_DEBUGS("CoreHttp") << "HTTP request " << static_cast<HttpHandle>(op) << " retry " << op->mPolicyRetries << " scheduled in " << (delta / HttpTime(1000)) << " mS (" << (external_delta ? "external" : "internal") << "). Status: " << op->mStatus.toHex() << LL_ENDL; if (op->mTracing > HTTP_TRACE_OFF) { LL_INFOS("CoreHttp") << "TRACE, ToRetryQueue, Handle: " << static_cast<HttpHandle>(op) << ", Delta: " << (delta / HttpTime(1000)) << ", Retries: " << op->mPolicyRetries << LL_ENDL; } mClasses[policy_class]->mRetryQueue.push(op); } // Attempt to deliver requests to the transport layer. // // Tries to find HTTP requests for each policy class with // available capacity. Starts with the retry queue first // looking for requests that have waited long enough then // moves on to the ready queue. // // If all queues are empty, will return an indication that // the worker thread may sleep hard otherwise will ask for // normal polling frequency. // // Implements a client-side request rate throttle as well. // This is intended to mimic and predict throttling behavior // of grid services but that is difficult to do with different // time bases. This also represents a rigid coupling between // viewer and server that makes it hard to change parameters // and I hope we can make this go away with pipelining. // HttpService::ELoopSpeed HttpPolicy::processReadyQueue() { const HttpTime now(totalTime()); HttpService::ELoopSpeed result(HttpService::REQUEST_SLEEP); HttpLibcurl & transport(mService->getTransport()); for (int policy_class(0); policy_class < mClasses.size(); ++policy_class) { ClassState & state(*mClasses[policy_class]); HttpRetryQueue & retryq(state.mRetryQueue); HttpReadyQueue & readyq(state.mReadyQueue); if (retryq.empty() && readyq.empty()) { continue; } const bool throttle_enabled(state.mOptions.mThrottleRate > 0L); const bool throttle_current(throttle_enabled && now < state.mThrottleEnd); if (throttle_current && state.mThrottleLeft <= 0) { // Throttled condition, don't serve this class but don't sleep hard. result = HttpService::NORMAL; continue; } int active(transport.getActiveCountInClass(policy_class)); int needed(state.mOptions.mConnectionLimit - active); // Expect negatives here if (needed > 0) { // First see if we have any retries... while (needed > 0 && ! retryq.empty()) { HttpOpRequest * op(retryq.top()); if (op->mPolicyRetryAt > now) break; retryq.pop(); op->stageFromReady(mService); op->release(); ++state.mRequestCount; --needed; if (throttle_enabled) { if (now >= state.mThrottleEnd) { // Throttle expired, move to next window LL_DEBUGS("CoreHttp") << "Throttle expired with " << state.mThrottleLeft << " requests to go and " << state.mRequestCount << " requests issued." << LL_ENDL; state.mThrottleLeft = state.mOptions.mThrottleRate; state.mThrottleEnd = now + HttpTime(1000000); } if (--state.mThrottleLeft <= 0) { goto throttle_on; } } } // Now go on to the new requests... while (needed > 0 && ! readyq.empty()) { HttpOpRequest * op(readyq.top()); readyq.pop(); op->stageFromReady(mService); op->release(); ++state.mRequestCount; --needed; if (throttle_enabled) { if (now >= state.mThrottleEnd) { // Throttle expired, move to next window LL_DEBUGS("CoreHttp") << "Throttle expired with " << state.mThrottleLeft << " requests to go and " << state.mRequestCount << " requests issued." << LL_ENDL; state.mThrottleLeft = state.mOptions.mThrottleRate; state.mThrottleEnd = now + HttpTime(1000000); } if (--state.mThrottleLeft <= 0) { goto throttle_on; } } } } throttle_on: if (! readyq.empty() || ! retryq.empty()) { // If anything is ready, continue looping... result = HttpService::NORMAL; } } // end foreach policy_class return result; } bool HttpPolicy::changePriority(HttpHandle handle, HttpRequest::priority_t priority) { for (int policy_class(0); policy_class < mClasses.size(); ++policy_class) { ClassState & state(*mClasses[policy_class]); // We don't scan retry queue because a priority change there // is meaningless. The request will be issued based on retry // intervals not priority value, which is now moot. // Scan ready queue for requests that match policy HttpReadyQueue::container_type & c(state.mReadyQueue.get_container()); for (HttpReadyQueue::container_type::iterator iter(c.begin()); c.end() != iter;) { HttpReadyQueue::container_type::iterator cur(iter++); if (static_cast<HttpHandle>(*cur) == handle) { HttpOpRequest * op(*cur); c.erase(cur); // All iterators are now invalidated op->mReqPriority = priority; state.mReadyQueue.push(op); // Re-insert using adapter class return true; } } } return false; } bool HttpPolicy::cancel(HttpHandle handle) { for (int policy_class(0); policy_class < mClasses.size(); ++policy_class) { ClassState & state(*mClasses[policy_class]); // Scan retry queue HttpRetryQueue::container_type & c1(state.mRetryQueue.get_container()); for (HttpRetryQueue::container_type::iterator iter(c1.begin()); c1.end() != iter;) { HttpRetryQueue::container_type::iterator cur(iter++); if (static_cast<HttpHandle>(*cur) == handle) { HttpOpRequest * op(*cur); c1.erase(cur); // All iterators are now invalidated op->cancel(); op->release(); return true; } } // Scan ready queue HttpReadyQueue::container_type & c2(state.mReadyQueue.get_container()); for (HttpReadyQueue::container_type::iterator iter(c2.begin()); c2.end() != iter;) { HttpReadyQueue::container_type::iterator cur(iter++); if (static_cast<HttpHandle>(*cur) == handle) { HttpOpRequest * op(*cur); c2.erase(cur); // All iterators are now invalidated op->cancel(); op->release(); return true; } } } return false; } bool HttpPolicy::stageAfterCompletion(HttpOpRequest * op) { static const HttpStatus cant_connect(HttpStatus::EXT_CURL_EASY, CURLE_COULDNT_CONNECT); static const HttpStatus cant_res_proxy(HttpStatus::EXT_CURL_EASY, CURLE_COULDNT_RESOLVE_PROXY); static const HttpStatus cant_res_host(HttpStatus::EXT_CURL_EASY, CURLE_COULDNT_RESOLVE_HOST); static const HttpStatus send_error(HttpStatus::EXT_CURL_EASY, CURLE_SEND_ERROR); static const HttpStatus recv_error(HttpStatus::EXT_CURL_EASY, CURLE_RECV_ERROR); static const HttpStatus upload_failed(HttpStatus::EXT_CURL_EASY, CURLE_UPLOAD_FAILED); static const HttpStatus op_timedout(HttpStatus::EXT_CURL_EASY, CURLE_OPERATION_TIMEDOUT); static const HttpStatus post_error(HttpStatus::EXT_CURL_EASY, CURLE_HTTP_POST_ERROR); // Retry or finalize if (! op->mStatus) { // If this failed, we might want to retry. Have to inspect // the status a little more deeply for those reasons worth retrying... if (op->mPolicyRetries < op->mPolicyRetryLimit && ((op->mStatus.isHttpStatus() && op->mStatus.mType >= 499 && op->mStatus.mType <= 599) || cant_connect == op->mStatus || cant_res_proxy == op->mStatus || cant_res_host == op->mStatus || send_error == op->mStatus || recv_error == op->mStatus || upload_failed == op->mStatus || op_timedout == op->mStatus || post_error == op->mStatus)) { // Okay, worth a retry. We include 499 in this test as // it's the old 'who knows?' error from many grid services... retryOp(op); return true; // still active/ready } } // This op is done, finalize it delivering it to the reply queue... if (! op->mStatus) { LL_WARNS("CoreHttp") << "HTTP request " << static_cast<HttpHandle>(op) << " failed after " << op->mPolicyRetries << " retries. Reason: " << op->mStatus.toString() << " (" << op->mStatus.toHex() << ")" << LL_ENDL; } else if (op->mPolicyRetries) { LL_DEBUGS("CoreHttp") << "HTTP request " << static_cast<HttpHandle>(op) << " succeeded on retry " << op->mPolicyRetries << "." << LL_ENDL; } op->stageFromActive(mService); op->release(); return false; // not active } HttpPolicyClass & HttpPolicy::getClassOptions(HttpRequest::policy_t pclass) { llassert_always(pclass >= 0 && pclass < mClasses.size()); return mClasses[pclass]->mOptions; } int HttpPolicy::getReadyCount(HttpRequest::policy_t policy_class) const { if (policy_class < mClasses.size()) { return (mClasses[policy_class]->mReadyQueue.size() + mClasses[policy_class]->mRetryQueue.size()); } return 0; } } // end namespace LLCore <|endoftext|>
<commit_before>/** * @file lllandmarklist.cpp * @brief Landmark asset list class * * $LicenseInfo:firstyear=2002&license=viewergpl$ * * Copyright (c) 2002-2009, Linden Research, Inc. * * Second Life Viewer Source Code * The source code in this file ("Source Code") is provided by Linden Lab * to you under the terms of the GNU General Public License, version 2.0 * ("GPL"), unless you have obtained a separate licensing agreement * ("Other License"), formally executed by you and Linden Lab. Terms of * the GPL can be found in doc/GPL-license.txt in this distribution, or * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2 * * There are special exceptions to the terms and conditions of the GPL as * it is applied to this Source Code. View the full text of the exception * in the file doc/FLOSS-exception.txt in this software distribution, or * online at * http://secondlifegrid.net/programs/open_source/licensing/flossexception * * By copying, modifying or distributing this software, you acknowledge * that you have read and understood your obligations described above, * and agree to abide by those obligations. * * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY, * COMPLETENESS OR PERFORMANCE. * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "lllandmarklist.h" #include "message.h" #include "llassetstorage.h" #include "llagent.h" #include "llnotify.h" #include "llvfile.h" #include "llviewerstats.h" // Globals LLLandmarkList gLandmarkList; //////////////////////////////////////////////////////////////////////////// // LLLandmarkList LLLandmarkList::~LLLandmarkList() { std::for_each(mList.begin(), mList.end(), DeletePairedPointer()); } LLLandmark* LLLandmarkList::getAsset(const LLUUID& asset_uuid, loaded_callback_t cb) { LLLandmark* landmark = get_ptr_in_map(mList, asset_uuid); if(landmark) { return landmark; } else { if ( gLandmarkList.mBadList.find(asset_uuid) == gLandmarkList.mBadList.end() ) { if (cb) { loaded_callback_map_t::value_type vt(asset_uuid, cb); mLoadedCallbackMap.insert(vt); } gAssetStorage->getAssetData( asset_uuid, LLAssetType::AT_LANDMARK, LLLandmarkList::processGetAssetReply, NULL); } } return NULL; } // static void LLLandmarkList::processGetAssetReply( LLVFS *vfs, const LLUUID& uuid, LLAssetType::EType type, void* user_data, S32 status, LLExtStat ext_status ) { if( status == 0 ) { LLVFile file(vfs, uuid, type); S32 file_length = file.getSize(); std::vector<char> buffer(file_length + 1); file.read( (U8*)&buffer[0], file_length); buffer[ file_length ] = 0; LLLandmark* landmark = LLLandmark::constructFromString(&buffer[0]); if (landmark) { gLandmarkList.mList[ uuid ] = landmark; LLVector3d pos; if(!landmark->getGlobalPos(pos)) { LLUUID region_id; if(landmark->getRegionID(region_id)) { LLLandmark::requestRegionHandle( gMessageSystem, gAgent.getRegionHost(), region_id, boost::bind(&LLLandmarkList::onRegionHandle, &gLandmarkList, uuid)); } // the callback will be called when we get the region handle. } else { gLandmarkList.makeCallbacks(uuid); } } } else { LLViewerStats::getInstance()->incStat( LLViewerStats::ST_DOWNLOAD_FAILED ); // SJB: No use case for a notification here. Use lldebugs instead if( LL_ERR_ASSET_REQUEST_NOT_IN_DATABASE == status ) { LL_DEBUGS("Landmarks") << "Missing Landmark" << LL_ENDL; //LLNotifications::instance().add("LandmarkMissing"); } else { LL_DEBUGS("Landmarks") << "Unable to load Landmark" << LL_ENDL; //LLNotifications::instance().add("UnableToLoadLandmark"); } gLandmarkList.mBadList.insert(uuid); } } BOOL LLLandmarkList::assetExists(const LLUUID& asset_uuid) { return mList.count(asset_uuid) != 0 || mBadList.count(asset_uuid) != 0; } void LLLandmarkList::onRegionHandle(const LLUUID& landmark_id) { LLLandmark* landmark = getAsset(landmark_id); if (!landmark) { llwarns << "Got region handle but the landmark not found." << llendl; return; } // Calculate landmark global position. // This should succeed since the region handle is available. LLVector3d pos; if (!landmark->getGlobalPos(pos)) { llwarns << "Got region handle but the landmark global position is still unknown." << llendl; return; } makeCallbacks(landmark_id); } void LLLandmarkList::makeCallbacks(const LLUUID& landmark_id) { LLLandmark* landmark = getAsset(landmark_id); if (!landmark) { llwarns << "Landmark to make callbacks for not found." << llendl; } // make all the callbacks here. loaded_callback_map_t::iterator it; while((it = mLoadedCallbackMap.find(landmark_id)) != mLoadedCallbackMap.end()) { if (landmark) (*it).second(landmark); mLoadedCallbackMap.erase(it); } } <commit_msg>Decided that the lldebugs should really be llwarns.<commit_after>/** * @file lllandmarklist.cpp * @brief Landmark asset list class * * $LicenseInfo:firstyear=2002&license=viewergpl$ * * Copyright (c) 2002-2009, Linden Research, Inc. * * Second Life Viewer Source Code * The source code in this file ("Source Code") is provided by Linden Lab * to you under the terms of the GNU General Public License, version 2.0 * ("GPL"), unless you have obtained a separate licensing agreement * ("Other License"), formally executed by you and Linden Lab. Terms of * the GPL can be found in doc/GPL-license.txt in this distribution, or * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2 * * There are special exceptions to the terms and conditions of the GPL as * it is applied to this Source Code. View the full text of the exception * in the file doc/FLOSS-exception.txt in this software distribution, or * online at * http://secondlifegrid.net/programs/open_source/licensing/flossexception * * By copying, modifying or distributing this software, you acknowledge * that you have read and understood your obligations described above, * and agree to abide by those obligations. * * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY, * COMPLETENESS OR PERFORMANCE. * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "lllandmarklist.h" #include "message.h" #include "llassetstorage.h" #include "llagent.h" #include "llnotify.h" #include "llvfile.h" #include "llviewerstats.h" // Globals LLLandmarkList gLandmarkList; //////////////////////////////////////////////////////////////////////////// // LLLandmarkList LLLandmarkList::~LLLandmarkList() { std::for_each(mList.begin(), mList.end(), DeletePairedPointer()); } LLLandmark* LLLandmarkList::getAsset(const LLUUID& asset_uuid, loaded_callback_t cb) { LLLandmark* landmark = get_ptr_in_map(mList, asset_uuid); if(landmark) { return landmark; } else { if ( gLandmarkList.mBadList.find(asset_uuid) == gLandmarkList.mBadList.end() ) { if (cb) { loaded_callback_map_t::value_type vt(asset_uuid, cb); mLoadedCallbackMap.insert(vt); } gAssetStorage->getAssetData( asset_uuid, LLAssetType::AT_LANDMARK, LLLandmarkList::processGetAssetReply, NULL); } } return NULL; } // static void LLLandmarkList::processGetAssetReply( LLVFS *vfs, const LLUUID& uuid, LLAssetType::EType type, void* user_data, S32 status, LLExtStat ext_status ) { if( status == 0 ) { LLVFile file(vfs, uuid, type); S32 file_length = file.getSize(); std::vector<char> buffer(file_length + 1); file.read( (U8*)&buffer[0], file_length); buffer[ file_length ] = 0; LLLandmark* landmark = LLLandmark::constructFromString(&buffer[0]); if (landmark) { gLandmarkList.mList[ uuid ] = landmark; LLVector3d pos; if(!landmark->getGlobalPos(pos)) { LLUUID region_id; if(landmark->getRegionID(region_id)) { LLLandmark::requestRegionHandle( gMessageSystem, gAgent.getRegionHost(), region_id, boost::bind(&LLLandmarkList::onRegionHandle, &gLandmarkList, uuid)); } // the callback will be called when we get the region handle. } else { gLandmarkList.makeCallbacks(uuid); } } } else { LLViewerStats::getInstance()->incStat( LLViewerStats::ST_DOWNLOAD_FAILED ); // SJB: No use case for a notification here. Use lldebugs instead if( LL_ERR_ASSET_REQUEST_NOT_IN_DATABASE == status ) { LL_WARNS("Landmarks") << "Missing Landmark" << LL_ENDL; //LLNotifications::instance().add("LandmarkMissing"); } else { LL_WARNS("Landmarks") << "Unable to load Landmark" << LL_ENDL; //LLNotifications::instance().add("UnableToLoadLandmark"); } gLandmarkList.mBadList.insert(uuid); } } BOOL LLLandmarkList::assetExists(const LLUUID& asset_uuid) { return mList.count(asset_uuid) != 0 || mBadList.count(asset_uuid) != 0; } void LLLandmarkList::onRegionHandle(const LLUUID& landmark_id) { LLLandmark* landmark = getAsset(landmark_id); if (!landmark) { llwarns << "Got region handle but the landmark not found." << llendl; return; } // Calculate landmark global position. // This should succeed since the region handle is available. LLVector3d pos; if (!landmark->getGlobalPos(pos)) { llwarns << "Got region handle but the landmark global position is still unknown." << llendl; return; } makeCallbacks(landmark_id); } void LLLandmarkList::makeCallbacks(const LLUUID& landmark_id) { LLLandmark* landmark = getAsset(landmark_id); if (!landmark) { llwarns << "Landmark to make callbacks for not found." << llendl; } // make all the callbacks here. loaded_callback_map_t::iterator it; while((it = mLoadedCallbackMap.find(landmark_id)) != mLoadedCallbackMap.end()) { if (landmark) (*it).second(landmark); mLoadedCallbackMap.erase(it); } } <|endoftext|>
<commit_before><commit_msg>use the correct flag to remove notes<commit_after><|endoftext|>
<commit_before><commit_msg>Avoid expensive allocation & deallocation of local vector on every call.<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: tpcalc.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: hr $ $Date: 2004-05-10 16:04:25 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "ui_pch.hxx" #endif #pragma hdrstop //------------------------------------------------------------------ #include <math.h> #include "scitems.hxx" #include <vcl/msgbox.hxx> #ifndef INCLUDED_RTL_MATH_HXX #include <rtl/math.hxx> #endif #ifndef _UNOTOOLS_LOCALEDATAWRAPPER_HXX #include <unotools/localedatawrapper.hxx> #endif #include "global.hxx" #include "globstr.hrc" #include "uiitems.hxx" #include "docsh.hxx" #include "document.hxx" #include "docoptio.hxx" #include "scresid.hxx" #include "sc.hrc" // -> Slot-IDs #include "optdlg.hrc" #define _TPCALC_CXX #include "tpcalc.hxx" #undef _TPCALC_CXX // STATIC DATA ----------------------------------------------------------- static USHORT pCalcOptRanges[] = { SID_SCDOCOPTIONS, SID_SCDOCOPTIONS, 0 }; //======================================================================== ScTpCalcOptions::ScTpCalcOptions( Window* pParent, const SfxItemSet& rCoreAttrs ) : SfxTabPage ( pParent, ScResId( RID_SCPAGE_CALC ), rCoreAttrs ), aBtnCase ( this, ScResId( BTN_CASE ) ), aBtnCalc ( this, ScResId( BTN_CALC ) ), aBtnMatch ( this, ScResId( BTN_MATCH ) ), aBtnRegex ( this, ScResId( BTN_REGEX ) ), aBtnLookUp ( this, ScResId( BTN_LOOKUP ) ), aBtnIterate ( this, ScResId( BTN_ITERATE ) ), aFtSteps ( this, ScResId( FT_STEPS ) ), aEdSteps ( this, ScResId( ED_STEPS ) ), aFtEps ( this, ScResId( FT_EPS ) ), aEdEps ( this, ScResId( ED_EPS ) ), aGbZRefs ( this, ScResId( GB_ZREFS ) ), aBtnDateStd ( this, ScResId( BTN_DATESTD ) ), aBtnDateSc10 ( this, ScResId( BTN_DATESC10 ) ), aBtnDate1904 ( this, ScResId( BTN_DATE1904 ) ), aGbDate ( this, ScResId( GB_DATE ) ), aFtPrec ( this, ScResId( FT_PREC ) ), aEdPrec ( this, ScResId( ED_PREC ) ), aSeparatorFL ( this, ScResId( FL_SEPARATOR ) ), aHSeparatorFL ( this, ScResId( FL_H_SEPARATOR ) ), aDecSep ( GetScGlobalpLocaleData()->getNumDecimalSep() ),//CHINA001 aDecSep ( ScGlobal::pLocaleData->getNumDecimalSep() ), nWhichCalc ( GetWhich( SID_SCDOCOPTIONS ) ), pOldOptions ( new ScDocOptions( ((const ScTpCalcItem&)rCoreAttrs.Get( GetWhich( SID_SCDOCOPTIONS ))). GetDocOptions() ) ), pLocalOptions ( new ScDocOptions ) { aSeparatorFL.SetStyle( aSeparatorFL.GetStyle() | WB_VERT ); Init(); FreeResource(); SetExchangeSupport(); } //----------------------------------------------------------------------- __EXPORT ScTpCalcOptions::~ScTpCalcOptions() { delete pOldOptions; delete pLocalOptions; } //----------------------------------------------------------------------- void ScTpCalcOptions::Init() { aBtnIterate .SetClickHdl( LINK( this, ScTpCalcOptions, CheckClickHdl ) ); aBtnDateStd .SetClickHdl( LINK( this, ScTpCalcOptions, RadioClickHdl ) ); aBtnDateSc10.SetClickHdl( LINK( this, ScTpCalcOptions, RadioClickHdl ) ); aBtnDate1904.SetClickHdl( LINK( this, ScTpCalcOptions, RadioClickHdl ) ); } //----------------------------------------------------------------------- USHORT* __EXPORT ScTpCalcOptions::GetRanges() { return pCalcOptRanges; } //----------------------------------------------------------------------- SfxTabPage* __EXPORT ScTpCalcOptions::Create( Window* pParent, const SfxItemSet& rAttrSet ) { return ( new ScTpCalcOptions( pParent, rAttrSet ) ); } //----------------------------------------------------------------------- void __EXPORT ScTpCalcOptions::Reset( const SfxItemSet& rCoreAttrs ) { USHORT d,m,y; *pLocalOptions = *pOldOptions; String aStrBuf( ::rtl::math::doubleToUString( pLocalOptions->GetIterEps(), rtl_math_StringFormat_G, 6, aDecSep.GetChar(0), TRUE)); aBtnCase .Check( !pLocalOptions->IsIgnoreCase() ); aBtnCalc .Check( pLocalOptions->IsCalcAsShown() ); aBtnMatch .Check( pLocalOptions->IsMatchWholeCell() ); aBtnRegex .Check( pLocalOptions->IsFormulaRegexEnabled() ); aBtnLookUp .Check( pLocalOptions->IsLookUpColRowNames() ); aBtnIterate.Check( pLocalOptions->IsIter() ); aEdSteps .SetValue( pLocalOptions->GetIterCount() ); aEdPrec .SetValue( pLocalOptions->GetStdPrecision() ); aEdEps .SetText( aStrBuf ); pLocalOptions->GetDate( d, m, y ); switch ( y ) { case 1899: aBtnDateStd.Check(); break; case 1900: aBtnDateSc10.Check(); break; case 1904: aBtnDate1904.Check(); break; } CheckClickHdl( &aBtnIterate ); } //----------------------------------------------------------------------- BOOL __EXPORT ScTpCalcOptions::FillItemSet( SfxItemSet& rCoreAttrs ) { // alle weiteren Optionen werden in den Handlern aktualisiert pLocalOptions->SetIterCount( (USHORT)aEdSteps.GetValue() ); pLocalOptions->SetStdPrecision( aEdPrec.GetValue() ); pLocalOptions->SetIgnoreCase( !aBtnCase.IsChecked() ); pLocalOptions->SetCalcAsShown( aBtnCalc.IsChecked() ); pLocalOptions->SetMatchWholeCell( aBtnMatch.IsChecked() ); pLocalOptions->SetFormulaRegexEnabled( aBtnRegex.IsChecked() ); pLocalOptions->SetLookUpColRowNames( aBtnLookUp.IsChecked() ); if ( *pLocalOptions != *pOldOptions ) { rCoreAttrs.Put( ScTpCalcItem( nWhichCalc, *pLocalOptions ) ); return TRUE; } else return FALSE; } //------------------------------------------------------------------------ int __EXPORT ScTpCalcOptions::DeactivatePage( SfxItemSet* pSet ) { int nReturn = CheckEps() ? LEAVE_PAGE : KEEP_PAGE; if ( nReturn == KEEP_PAGE ) { ErrorBox( this, WinBits( WB_OK | WB_DEF_OK ), ScGlobal::GetRscString( STR_INVALID_EPS ) ).Execute(); aEdEps.GrabFocus(); } else if ( pSet ) FillItemSet( *pSet ); return nReturn; } //----------------------------------------------------------------------- BOOL ScTpCalcOptions::GetEps( double& rEps ) { String aStr( aEdEps.GetText() ); aStr.EraseTrailingChars( ' ' ); rtl_math_ConversionStatus eStatus; sal_Unicode const * pBegin = aStr.GetBuffer(); sal_Unicode const * pEnd; rEps = rtl_math_uStringToDouble( pBegin, pBegin + aStr.Len(), GetScGlobalpLocaleData()->getNumDecimalSep().GetChar(0),//CHINA001 ScGlobal::pLocaleData->getNumDecimalSep().GetChar(0), GetScGlobalpLocaleData()->getNumThousandSep().GetChar(0),//CHINA001 ScGlobal::pLocaleData->getNumThousandSep().GetChar(0), &eStatus, &pEnd ); BOOL bOk = ( eStatus == rtl_math_ConversionStatus_Ok && *pEnd == '\0' && rEps > 0.0 ); if ( bOk ) pLocalOptions->SetIterEps( rEps ); return bOk; } //----------------------------------------------------------------------- BOOL ScTpCalcOptions::CheckEps() { if ( aEdEps.GetText().Len() == 0 ) return FALSE; else { double d; return GetEps(d); } } //----------------------------------------------------------------------- // Handler: IMPL_LINK( ScTpCalcOptions, RadioClickHdl, RadioButton*, pBtn ) { if ( pBtn == &aBtnDateStd ) { pLocalOptions->SetDate( 30, 12, 1899 ); } else if ( pBtn == &aBtnDateSc10 ) { pLocalOptions->SetDate( 1, 1, 1900 ); } else if ( pBtn == &aBtnDate1904 ) { pLocalOptions->SetDate( 1, 1, 1904 ); } return 0; } //----------------------------------------------------------------------- IMPL_LINK( ScTpCalcOptions, CheckClickHdl, CheckBox*, pBtn ) { if ( pBtn->IsChecked() ) { pLocalOptions->SetIter( TRUE ); aFtSteps.Enable(); aEdSteps.Enable(); aFtEps .Enable(); aEdEps .Enable(); } else { pLocalOptions->SetIter( FALSE ); aFtSteps.Disable(); aEdSteps.Disable(); aFtEps .Disable(); aEdEps .Disable(); } return 0; } <commit_msg>INTEGRATION: CWS grouping (1.11.40); FILE MERGED 2004/07/05 17:26:34 dr 1.11.40.1: #i25110# DataPilot grouping dialogs<commit_after>/************************************************************************* * * $RCSfile: tpcalc.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: hr $ $Date: 2004-08-03 11:37:52 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "ui_pch.hxx" #endif #pragma hdrstop //------------------------------------------------------------------ #include <math.h> #include "scitems.hxx" #include <vcl/msgbox.hxx> #include "global.hxx" #include "globstr.hrc" #include "uiitems.hxx" #include "docsh.hxx" #include "document.hxx" #include "docoptio.hxx" #include "scresid.hxx" #include "sc.hrc" // -> Slot-IDs #include "optdlg.hrc" #define _TPCALC_CXX #include "tpcalc.hxx" #undef _TPCALC_CXX // STATIC DATA ----------------------------------------------------------- static USHORT pCalcOptRanges[] = { SID_SCDOCOPTIONS, SID_SCDOCOPTIONS, 0 }; //======================================================================== ScTpCalcOptions::ScTpCalcOptions( Window* pParent, const SfxItemSet& rCoreAttrs ) : SfxTabPage ( pParent, ScResId( RID_SCPAGE_CALC ), rCoreAttrs ), aBtnCase ( this, ScResId( BTN_CASE ) ), aBtnCalc ( this, ScResId( BTN_CALC ) ), aBtnMatch ( this, ScResId( BTN_MATCH ) ), aBtnRegex ( this, ScResId( BTN_REGEX ) ), aBtnLookUp ( this, ScResId( BTN_LOOKUP ) ), aBtnIterate ( this, ScResId( BTN_ITERATE ) ), aFtSteps ( this, ScResId( FT_STEPS ) ), aEdSteps ( this, ScResId( ED_STEPS ) ), aFtEps ( this, ScResId( FT_EPS ) ), aEdEps ( this, ScResId( ED_EPS ) ), aGbZRefs ( this, ScResId( GB_ZREFS ) ), aBtnDateStd ( this, ScResId( BTN_DATESTD ) ), aBtnDateSc10 ( this, ScResId( BTN_DATESC10 ) ), aBtnDate1904 ( this, ScResId( BTN_DATE1904 ) ), aGbDate ( this, ScResId( GB_DATE ) ), aFtPrec ( this, ScResId( FT_PREC ) ), aEdPrec ( this, ScResId( ED_PREC ) ), aSeparatorFL ( this, ScResId( FL_SEPARATOR ) ), aHSeparatorFL ( this, ScResId( FL_H_SEPARATOR ) ), nWhichCalc ( GetWhich( SID_SCDOCOPTIONS ) ), pOldOptions ( new ScDocOptions( ((const ScTpCalcItem&)rCoreAttrs.Get( GetWhich( SID_SCDOCOPTIONS ))). GetDocOptions() ) ), pLocalOptions ( new ScDocOptions ) { aSeparatorFL.SetStyle( aSeparatorFL.GetStyle() | WB_VERT ); Init(); FreeResource(); SetExchangeSupport(); } //----------------------------------------------------------------------- __EXPORT ScTpCalcOptions::~ScTpCalcOptions() { delete pOldOptions; delete pLocalOptions; } //----------------------------------------------------------------------- void ScTpCalcOptions::Init() { aBtnIterate .SetClickHdl( LINK( this, ScTpCalcOptions, CheckClickHdl ) ); aBtnDateStd .SetClickHdl( LINK( this, ScTpCalcOptions, RadioClickHdl ) ); aBtnDateSc10.SetClickHdl( LINK( this, ScTpCalcOptions, RadioClickHdl ) ); aBtnDate1904.SetClickHdl( LINK( this, ScTpCalcOptions, RadioClickHdl ) ); } //----------------------------------------------------------------------- USHORT* __EXPORT ScTpCalcOptions::GetRanges() { return pCalcOptRanges; } //----------------------------------------------------------------------- SfxTabPage* __EXPORT ScTpCalcOptions::Create( Window* pParent, const SfxItemSet& rAttrSet ) { return ( new ScTpCalcOptions( pParent, rAttrSet ) ); } //----------------------------------------------------------------------- void __EXPORT ScTpCalcOptions::Reset( const SfxItemSet& rCoreAttrs ) { USHORT d,m,y; *pLocalOptions = *pOldOptions; aBtnCase .Check( !pLocalOptions->IsIgnoreCase() ); aBtnCalc .Check( pLocalOptions->IsCalcAsShown() ); aBtnMatch .Check( pLocalOptions->IsMatchWholeCell() ); aBtnRegex .Check( pLocalOptions->IsFormulaRegexEnabled() ); aBtnLookUp .Check( pLocalOptions->IsLookUpColRowNames() ); aBtnIterate.Check( pLocalOptions->IsIter() ); aEdSteps .SetValue( pLocalOptions->GetIterCount() ); aEdPrec .SetValue( pLocalOptions->GetStdPrecision() ); aEdEps .SetValue( pLocalOptions->GetIterEps(), 6 ); pLocalOptions->GetDate( d, m, y ); switch ( y ) { case 1899: aBtnDateStd.Check(); break; case 1900: aBtnDateSc10.Check(); break; case 1904: aBtnDate1904.Check(); break; } CheckClickHdl( &aBtnIterate ); } //----------------------------------------------------------------------- BOOL __EXPORT ScTpCalcOptions::FillItemSet( SfxItemSet& rCoreAttrs ) { // alle weiteren Optionen werden in den Handlern aktualisiert pLocalOptions->SetIterCount( (USHORT)aEdSteps.GetValue() ); pLocalOptions->SetStdPrecision( (USHORT)aEdPrec.GetValue() ); pLocalOptions->SetIgnoreCase( !aBtnCase.IsChecked() ); pLocalOptions->SetCalcAsShown( aBtnCalc.IsChecked() ); pLocalOptions->SetMatchWholeCell( aBtnMatch.IsChecked() ); pLocalOptions->SetFormulaRegexEnabled( aBtnRegex.IsChecked() ); pLocalOptions->SetLookUpColRowNames( aBtnLookUp.IsChecked() ); if ( *pLocalOptions != *pOldOptions ) { rCoreAttrs.Put( ScTpCalcItem( nWhichCalc, *pLocalOptions ) ); return TRUE; } else return FALSE; } //------------------------------------------------------------------------ int __EXPORT ScTpCalcOptions::DeactivatePage( SfxItemSet* pSet ) { int nReturn = KEEP_PAGE; double fEps; if( aEdEps.GetValue( fEps ) && (fEps > 0.0) ) { pLocalOptions->SetIterEps( fEps ); nReturn = LEAVE_PAGE; } if ( nReturn == KEEP_PAGE ) { ErrorBox( this, WinBits( WB_OK | WB_DEF_OK ), ScGlobal::GetRscString( STR_INVALID_EPS ) ).Execute(); aEdEps.GrabFocus(); } else if ( pSet ) FillItemSet( *pSet ); return nReturn; } //----------------------------------------------------------------------- // Handler: IMPL_LINK( ScTpCalcOptions, RadioClickHdl, RadioButton*, pBtn ) { if ( pBtn == &aBtnDateStd ) { pLocalOptions->SetDate( 30, 12, 1899 ); } else if ( pBtn == &aBtnDateSc10 ) { pLocalOptions->SetDate( 1, 1, 1900 ); } else if ( pBtn == &aBtnDate1904 ) { pLocalOptions->SetDate( 1, 1, 1904 ); } return 0; } //----------------------------------------------------------------------- IMPL_LINK( ScTpCalcOptions, CheckClickHdl, CheckBox*, pBtn ) { if ( pBtn->IsChecked() ) { pLocalOptions->SetIter( TRUE ); aFtSteps.Enable(); aEdSteps.Enable(); aFtEps .Enable(); aEdEps .Enable(); } else { pLocalOptions->SetIter( FALSE ); aFtSteps.Disable(); aEdSteps.Disable(); aFtEps .Disable(); aEdEps .Disable(); } return 0; } <|endoftext|>
<commit_before>/* Copyright (C) 2005 Steven L. Scott This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ /* * Mathlib : A C Library of Special Functions * Copyright (C) 1998 Ross Ihaka * Copyright (C) 2000 The R Development Core Team * based on AS91 (C) 1979 Royal Statistical Society * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA. * * DESCRIPTION * * Compute the quantile function of the gamma distribution. * * NOTES * * This function is based on the Applied Statistics * Algorithm AS 91 ("ppchi2") and via pgamma(.) AS 239. * * REFERENCES * * Best, D. J. and D. E. Roberts (1975). * Percentage Points of the Chi-Squared Distribution. * Applied Statistics 24, page 385. */ #include "nmath.hpp" #include "dpq.hpp" namespace Rmath{ double qgamma(double p, double alpha, double scale, int lower_tail, int log_p) /* shape = alpha */ { #define C7 4.67 #define C8 6.66 #define C9 6.73 #define C10 13.32 #define EPS1 1e-2 #define EPS2 5e-7/* final precision */ #define MAXIT 1000/* was 20 */ #define pMIN 1e-100 /* was 0.000002 = 2e-6 */ #define pMAX (1-1e-12)/* was 0.999998 = 1 - 2e-6 */ const double i420 = 1./ 420., i2520 = 1./ 2520., i5040 = 1./ 5040; double p_, a, b, c, ch, g, p1, v; double p2, q, s1, s2, s3, s4, s5, s6, t, x; int i; /* test arguments and initialise */ // Code below checks errno, so make sure it is in a good state to begin // with. errno = 0; #ifdef IEEE_754 if (ISNAN(p) || ISNAN(alpha) || ISNAN(scale)) return p + alpha + scale; #endif R_Q_P01_check(p); if (alpha <= 0) ML_ERR_return_NAN; /* FIXME: This (cutoff to {0, +Inf}) is far from optimal when log_p: */ p_ = R_DT_qIv(p);/* lower_tail prob (in any case) */ if (/* 0 <= */ p_ < pMIN) return 0; if (/* 1 >= */ p_ > pMAX) return BOOM::infinity(); v = 2*alpha; c = alpha-1; g = lgammafn(alpha);/* log Gamma(v/2) */ /*----- Phase I : Starting Approximation */ if(v < (-1.24)*R_DT_log(p)) { /* for small chi-squared */ /* FIXME: Improve this "if (log_p)" : * (A*exp(b)) ^ 1/al */ ch = pow(p_* alpha*exp(g+alpha*M_LN2), 1/alpha); if(ch < EPS2) {/* Corrected according to AS 91; MM, May 25, 1999 */ goto END; } } else if(v > 0.32) { /* using Wilson and Hilferty estimate */ x = qnorm(p, 0, 1, lower_tail, log_p); p1 = 0.222222/v; ch = v*pow(x*sqrt(p1)+1-p1, 3); /* starting approximation for p tending to 1 */ if( ch > 2.2*v + 6 ) ch = -2*(R_DT_Clog(p) - c*log(0.5*ch) + g); } else { /* for v <= 0.32 */ ch = 0.4; a = R_DT_Clog(p) + g + c*M_LN2; do { q = ch; p1 = 1. / (1+ch*(C7+ch)); p2 = ch*(C9+ch*(C8+ch)); t = -0.5 +(C7+2*ch)*p1 - (C9+ch*(C10+3*ch))/p2; ch -= (1- exp(a+0.5*ch)*p2*p1)/t; } while(fabs(q - ch) > EPS1*fabs(ch)); } /*----- Phase II: Iteration * Call pgamma() [AS 239] and calculate seven term taylor series */ for( i=1 ; i <= MAXIT ; i++ ) { q = ch; p1 = 0.5*ch; p2 = p_ - pgamma(p1, alpha, 1, /*lower_tail*/true, /*log_p*/false); // #ifdef IEEE_754 // if(!R_FINITE(p2)) // #else // if(errno != 0) // #endif // return std::numeric_limits<double>::quiet_NaN(); if (errno != 0) { std::ostringstream err; err << "Math error in qgamma: " << strerror(errno) << std::endl; report_error(err.str()); return std::numeric_limits<double>::quiet_NaN(); } if (!std::isfinite(p2)) { return std::numeric_limits<double>::quiet_NaN(); } t = p2*exp(alpha*M_LN2+g+p1-c*log(ch)); b = t/ch; a = 0.5*t - b*c; s1 = (210+a*(140+a*(105+a*(84+a*(70+60*a))))) * i420; s2 = (420+a*(735+a*(966+a*(1141+1278*a)))) * i2520; s3 = (210+a*(462+a*(707+932*a))) * i2520; s4 = (252+a*(672+1182*a)+c*(294+a*(889+1740*a))) * i5040; s5 = (84+2264*a+c*(1175+606*a)) * i2520; s6 = (120+c*(346+127*c)) * i5040; ch += t*(1+0.5*t*s1-b*c*(s1-b*(s2-b*(s3-b*(s4-b*(s5-b*s6)))))); if(fabs(q - ch) < EPS2*ch) goto END; } ML_ERROR(ME_PRECISION);/* no convergence in MAXIT iterations */ END: return 0.5*scale*ch; } } <commit_msg>Add missing #include for strerror.<commit_after>/* Copyright (C) 2005 Steven L. Scott This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ /* * Mathlib : A C Library of Special Functions * Copyright (C) 1998 Ross Ihaka * Copyright (C) 2000 The R Development Core Team * based on AS91 (C) 1979 Royal Statistical Society * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA. * * DESCRIPTION * * Compute the quantile function of the gamma distribution. * * NOTES * * This function is based on the Applied Statistics * Algorithm AS 91 ("ppchi2") and via pgamma(.) AS 239. * * REFERENCES * * Best, D. J. and D. E. Roberts (1975). * Percentage Points of the Chi-Squared Distribution. * Applied Statistics 24, page 385. */ #include <cstring> #include "nmath.hpp" #include "dpq.hpp" namespace Rmath{ double qgamma(double p, double alpha, double scale, int lower_tail, int log_p) /* shape = alpha */ { #define C7 4.67 #define C8 6.66 #define C9 6.73 #define C10 13.32 #define EPS1 1e-2 #define EPS2 5e-7/* final precision */ #define MAXIT 1000/* was 20 */ #define pMIN 1e-100 /* was 0.000002 = 2e-6 */ #define pMAX (1-1e-12)/* was 0.999998 = 1 - 2e-6 */ const double i420 = 1./ 420., i2520 = 1./ 2520., i5040 = 1./ 5040; double p_, a, b, c, ch, g, p1, v; double p2, q, s1, s2, s3, s4, s5, s6, t, x; int i; /* test arguments and initialise */ // Code below checks errno, so make sure it is in a good state to begin // with. errno = 0; #ifdef IEEE_754 if (ISNAN(p) || ISNAN(alpha) || ISNAN(scale)) return p + alpha + scale; #endif R_Q_P01_check(p); if (alpha <= 0) ML_ERR_return_NAN; /* FIXME: This (cutoff to {0, +Inf}) is far from optimal when log_p: */ p_ = R_DT_qIv(p);/* lower_tail prob (in any case) */ if (/* 0 <= */ p_ < pMIN) return 0; if (/* 1 >= */ p_ > pMAX) return BOOM::infinity(); v = 2*alpha; c = alpha-1; g = lgammafn(alpha);/* log Gamma(v/2) */ /*----- Phase I : Starting Approximation */ if(v < (-1.24)*R_DT_log(p)) { /* for small chi-squared */ /* FIXME: Improve this "if (log_p)" : * (A*exp(b)) ^ 1/al */ ch = pow(p_* alpha*exp(g+alpha*M_LN2), 1/alpha); if(ch < EPS2) {/* Corrected according to AS 91; MM, May 25, 1999 */ goto END; } } else if(v > 0.32) { /* using Wilson and Hilferty estimate */ x = qnorm(p, 0, 1, lower_tail, log_p); p1 = 0.222222/v; ch = v*pow(x*sqrt(p1)+1-p1, 3); /* starting approximation for p tending to 1 */ if( ch > 2.2*v + 6 ) ch = -2*(R_DT_Clog(p) - c*log(0.5*ch) + g); } else { /* for v <= 0.32 */ ch = 0.4; a = R_DT_Clog(p) + g + c*M_LN2; do { q = ch; p1 = 1. / (1+ch*(C7+ch)); p2 = ch*(C9+ch*(C8+ch)); t = -0.5 +(C7+2*ch)*p1 - (C9+ch*(C10+3*ch))/p2; ch -= (1- exp(a+0.5*ch)*p2*p1)/t; } while(fabs(q - ch) > EPS1*fabs(ch)); } /*----- Phase II: Iteration * Call pgamma() [AS 239] and calculate seven term taylor series */ for( i=1 ; i <= MAXIT ; i++ ) { q = ch; p1 = 0.5*ch; p2 = p_ - pgamma(p1, alpha, 1, /*lower_tail*/true, /*log_p*/false); // #ifdef IEEE_754 // if(!R_FINITE(p2)) // #else // if(errno != 0) // #endif // return std::numeric_limits<double>::quiet_NaN(); if (errno != 0) { std::ostringstream err; err << "Math error in qgamma: " << std::strerror(errno) << std::endl; report_error(err.str()); return std::numeric_limits<double>::quiet_NaN(); } if (!std::isfinite(p2)) { return std::numeric_limits<double>::quiet_NaN(); } t = p2*exp(alpha*M_LN2+g+p1-c*log(ch)); b = t/ch; a = 0.5*t - b*c; s1 = (210+a*(140+a*(105+a*(84+a*(70+60*a))))) * i420; s2 = (420+a*(735+a*(966+a*(1141+1278*a)))) * i2520; s3 = (210+a*(462+a*(707+932*a))) * i2520; s4 = (252+a*(672+1182*a)+c*(294+a*(889+1740*a))) * i5040; s5 = (84+2264*a+c*(1175+606*a)) * i2520; s6 = (120+c*(346+127*c)) * i5040; ch += t*(1+0.5*t*s1-b*c*(s1-b*(s2-b*(s3-b*(s4-b*(s5-b*s6)))))); if(fabs(q - ch) < EPS2*ch) goto END; } ML_ERROR(ME_PRECISION);/* no convergence in MAXIT iterations */ END: return 0.5*scale*ch; } } <|endoftext|>
<commit_before>#include "vtkSmartPointer.h" #include "vtkActor.h" #include "vtkCamera.h" #include "vtkDoubleArray.h" #include "vtkPoints.h" #include "vtkPointData.h" #include "vtkPolyData.h" #include "vtkProperty.h" #include "vtkProperty2D.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderer.h" #include "vtkStdString.h" #include "vtkTextProperty.h" #include "vtkXYPlotActor.h" #include "vtkTestUtilities.h" int TestXYPlotActor( int, char *[] ) { // Create container for points vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); // Create containers for data unsigned int nPlots = 3; vtkStdString names[] = { "sqrt(x)", "sqrt(x)*sin(x/5)", "sqrt(x)*cos(x/10)", }; vtkSmartPointer<vtkDoubleArray>* data = new vtkSmartPointer<vtkDoubleArray>[nPlots]; for ( unsigned int i = 0; i < nPlots; ++ i ) { data[i] = vtkSmartPointer<vtkDoubleArray>::New(); data[i]->SetNumberOfComponents( 1 ); data[i]->SetName( names[i].c_str() ); } // Fill in points and data unsigned int nSteps = 10; unsigned int stepSize = 50; unsigned int nVals = nSteps * stepSize; for ( unsigned int i = 0; i < nVals; ++ i ) { double val0 = sqrt( i ); data[0]->InsertNextValue( val0 ); double val1 = val0 * sin( .2 * i ); data[1]->InsertNextValue( val1 ); double val2 = val0 * cos( .1 * i ); data[2]->InsertNextValue( val2 ); points->InsertNextPoint( i, 0., 0. ); } // Determine extrema double* rangeCurr = data[0]->GetRange(); double range[2]; range[0] = rangeCurr[0]; range[1] = rangeCurr[1]; for ( unsigned int i = 1; i < nPlots; ++ i ) { rangeCurr = data[i]->GetRange(); range[0] = rangeCurr[0] < range[0] ? rangeCurr[0] : range[0]; range[1] = rangeCurr[1] > range[1] ? rangeCurr[1] : range[1]; } // Create data sets with created points and data vtkSmartPointer<vtkPolyData>* polydata = new vtkSmartPointer<vtkPolyData>[nPlots]; for ( unsigned int i = 0; i < nPlots; ++ i ) { polydata[i] = vtkSmartPointer<vtkPolyData>::New(); polydata[i]->SetPoints( points ); polydata[i]->GetPointData()->SetScalars( data[i] ); } // Set XY plot actor double colors[] = { .54, .21, .06, // burnt sienna 1., .38, .01, // cadmium orange .498, 1., 0., // chartreuse 0., .78, 0.55, // turquoise blue }; vtkSmartPointer<vtkXYPlotActor> xyPlot = vtkSmartPointer<vtkXYPlotActor>::New(); for ( unsigned int i = 0; i < nPlots; ++ i ) { xyPlot->AddDataSetInput( polydata[i] ); xyPlot->SetPlotColor( i, colors[3 * i], colors[3 * i + 1], colors[3 * i + 2] ); } xyPlot->GetPositionCoordinate()->SetValue( .1, .1, .0 ); xyPlot->GetPosition2Coordinate()->SetValue( .9, .9, .0 ); xyPlot->SetLineWidth( 2 ); // Title settings xyPlot->SetTitleFontFamily( VTK_ARIAL ); xyPlot->SetTitleColor( .9, .06, .02 ); xyPlot->SetTitle( "XY Plot Actor Test"); // Axes settings xyPlot->SetAxisTitleFontFamily( VTK_TIMES ); xyPlot->SetAxisTitleColor( 0., 0., 1. ); xyPlot->SetYTitlePositionToTop(); xyPlot->SetXTitle( "x"); xyPlot->SetYTitle( "f(x)"); xyPlot->SetXValuesToIndex(); xyPlot->SetXRange( 0, nVals ); xyPlot->SetYRange( range[0], range[1] ); xyPlot->SetXAxisColor( 0., 0., 0. ); xyPlot->SetYAxisColor( 0., 0., 0. ); // Label settings xyPlot->SetAxisLabelFontFamily( VTK_COURIER ); xyPlot->SetAxisLabelColor( 0., 0., .9 ); xyPlot->SetLabelFormat("%g"); xyPlot->SetAdjustXLabels( 0 ); xyPlot->SetNumberOfXLabels( nSteps + 1 ); xyPlot->SetAdjustYLabels( 0 ); xyPlot->SetNumberOfYLabels( 3 ); // Set up rendering contraption vtkSmartPointer<vtkRenderer> ren1 = vtkSmartPointer<vtkRenderer>::New(); ren1->SetBackground( .99, 1., .94); // titanium white ren1->AddActor( xyPlot ); vtkSmartPointer<vtkRenderWindow> renWin = vtkSmartPointer<vtkRenderWindow>::New(); renWin->SetMultiSamples( 0 ); renWin->AddRenderer( ren1 ); renWin->SetSize( 600, 300 ); vtkSmartPointer<vtkRenderWindowInteractor> iren = vtkSmartPointer<vtkRenderWindowInteractor>::New(); iren->SetRenderWindow( renWin ); // Set up an interesting viewpoint vtkCamera* camera = ren1->GetActiveCamera(); camera->Elevation( 110 ); camera->SetViewUp( 0, 0, -1 ); camera->Azimuth( 45 ); camera->SetFocalPoint( 100.8, 100.8, 69. ); camera->SetPosition( 560.949, 560.949, -167.853 ); ren1->ResetCameraClippingRange(); // Render the image iren->Initialize(); renWin->Render(); iren->Start(); // Clean up delete [] polydata; delete [] data; return EXIT_SUCCESS; } <commit_msg>Testing almost all plot features<commit_after>#include "vtkSmartPointer.h" #include "vtkActor.h" #include "vtkDoubleArray.h" #include "vtkLegendBoxActor.h" #include "vtkPoints.h" #include "vtkPointData.h" #include "vtkPolyData.h" #include "vtkProperty.h" #include "vtkProperty2D.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderer.h" #include "vtkStdString.h" #include "vtkTextProperty.h" #include "vtkXYPlotActor.h" #include "vtkTestUtilities.h" int TestXYPlotActor( int, char *[] ) { // Create container for points vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); // Create containers for data unsigned int nPlots = 4; vtkStdString names[] = { "sqrt(x)", "sqrt(x)*sin(x/5)", "sqrt(x)*cos(x/10)", "-sqrt(x)", }; vtkSmartPointer<vtkDoubleArray>* data = new vtkSmartPointer<vtkDoubleArray>[nPlots]; for ( unsigned int i = 0; i < nPlots; ++ i ) { data[i] = vtkSmartPointer<vtkDoubleArray>::New(); data[i]->SetNumberOfComponents( 1 ); data[i]->SetName( names[i].c_str() ); } // Fill in points and data unsigned int nSteps = 10; unsigned int stepSize = 50; unsigned int nVals = nSteps * stepSize + 1; for ( unsigned int i = 0; i < nVals; ++ i ) { points->InsertNextPoint( i, 0., 0. ); double val0 = sqrt( i ); data[0]->InsertNextValue( val0 ); double val1 = val0 * sin( .1 * i ); data[1]->InsertNextValue( val1 ); double val2 = val0 * cos( 2. * val0 ); data[2]->InsertNextValue( val2 ); points->InsertNextPoint( i, 0., 0. ); data[3]->InsertNextValue( -val0 ); } // Determine extrema double* rangeCurr = data[0]->GetRange(); double range[2]; range[0] = rangeCurr[0]; range[1] = rangeCurr[1]; for ( unsigned int i = 1; i < nPlots; ++ i ) { rangeCurr = data[i]->GetRange(); range[0] = rangeCurr[0] < range[0] ? rangeCurr[0] : range[0]; range[1] = rangeCurr[1] > range[1] ? rangeCurr[1] : range[1]; } // Create data sets with created points and data vtkSmartPointer<vtkPolyData>* polydata = new vtkSmartPointer<vtkPolyData>[nPlots]; for ( unsigned int i = 0; i < nPlots; ++ i ) { polydata[i] = vtkSmartPointer<vtkPolyData>::New(); polydata[i]->SetPoints( points ); polydata[i]->GetPointData()->SetScalars( data[i] ); } // Set XY plot actor double colors[] = { .54, .21, .06, // burnt sienna 1., .38, .01, // cadmium orange .498, 1., 0., // chartreuse 0., .78, 0.55, // turquoise blue }; vtkSmartPointer<vtkXYPlotActor> xyPlot = vtkSmartPointer<vtkXYPlotActor>::New(); for ( unsigned int i = 0; i < nPlots; ++ i ) { xyPlot->AddDataSetInput( polydata[i] ); xyPlot->SetPlotColor( i, colors[3 * i], colors[3 * i + 1], colors[3 * i + 2] ); } xyPlot->GetPositionCoordinate()->SetValue( .05, .05, .0 ); xyPlot->GetPosition2Coordinate()->SetValue( .95, .95, .0 ); xyPlot->SetLineWidth( 2 ); // Title settings xyPlot->SetTitleItalic( 0 ); xyPlot->SetTitleBold( 0 ); xyPlot->SetTitleFontFamily( VTK_ARIAL ); xyPlot->SetTitleColor( .9, .06, .02 ); xyPlot->SetTitle( "XY Plot Actor Test"); // Legend settings xyPlot->SetLegend( 1 ); xyPlot->SetLegendPosition( .11, .77 ); xyPlot->SetLegendPosition2( .2, .2 ); xyPlot->SetLegendBorder( 1 ); xyPlot->SetLegendBox( 1 ); xyPlot->SetLegendBoxColor(0., 0., 0. );//0.4667, 0.5333, 0.6000); for ( unsigned int i = 0; i < nPlots; ++ i ) { xyPlot->GetLegendActor()->SetEntryString( i, names[i] ); } // Axes settings xyPlot->SetAxisTitleFontFamily( VTK_TIMES ); xyPlot->SetAxisTitleColor( 0., 0., 1. ); xyPlot->SetYTitlePositionToTop(); xyPlot->SetXTitle( "x"); xyPlot->SetYTitle( "f(x)"); xyPlot->SetXValuesToIndex(); xyPlot->SetXRange( 0, nVals - 1 ); xyPlot->SetYRange( range[0], range[1] ); xyPlot->SetXAxisColor( 0., 0., 0. ); xyPlot->SetYAxisColor( 0., 0., 0. ); // Label settings xyPlot->SetAxisLabelFontFamily( VTK_COURIER ); xyPlot->SetAxisLabelColor( 0., 0., .9 ); xyPlot->SetLabelFormat("%g"); xyPlot->SetAdjustXLabels( 0 ); xyPlot->SetNumberOfXLabels( nSteps + 1 ); xyPlot->SetAdjustYLabels( 0 ); xyPlot->SetNumberOfYLabels( 3 ); // Set up rendering contraption vtkSmartPointer<vtkRenderer> ren1 = vtkSmartPointer<vtkRenderer>::New(); ren1->SetBackground( .99, 1., .94 ); // titanium white ren1->AddActor( xyPlot ); vtkSmartPointer<vtkRenderWindow> renWin = vtkSmartPointer<vtkRenderWindow>::New(); renWin->SetMultiSamples( 0 ); renWin->AddRenderer( ren1 ); renWin->SetSize( 600, 400 ); vtkSmartPointer<vtkRenderWindowInteractor> iren = vtkSmartPointer<vtkRenderWindowInteractor>::New(); iren->SetRenderWindow( renWin ); // Render the image iren->Initialize(); renWin->Render(); iren->Start(); // Clean up delete [] polydata; delete [] data; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include "mem/cache/tags/wplru.hh" #include "base/intmath.hh" #include "debug/CacheRepl.hh" #include "mem/cache/tags/cacheset.hh" #include "mem/cache/tags/lru.hh" #include "mem/cache/base.hh" #include "sim/core.hh" #include "mem/cache/blk.hh" #include <typeinfo> WPLRU::WPLRU( unsigned _numSets, unsigned _blkSize, unsigned _assoc, unsigned _hit_latency, unsigned _num_tcs ) : LRU(_numSets, _blkSize, _assoc, _hit_latency ), num_tcs( _num_tcs ) { init_sets(); } CacheSet WPLRU::get_set( int setnum, uint64_t tid, Addr addr ){ CacheSet s = sets_w[tid][setnum]; #ifdef DEBUG_TP if( s.hasBlk(interesting) ){ printf( "get_set on interesting @ %lu", curTick() ); s.print(); } #endif return s; } int WPLRU::assoc_of_tc( int tcid ){ int a = assoc / num_tcs; if(tcid < (assoc%num_tcs)) a++; return a; } int WPLRU::blks_in_tc( int tcid ){ return numSets * assoc_of_tc( tcid ); } void WPLRU::init_sets(){ sets_w = new CacheSet*[num_tcs]; for( int i=0; i < num_tcs; i++ ){ sets_w[i] = new CacheSet[numSets]; std::memcpy( sets_w[i], LRU::sets, numSets * sizeof( CacheSet ) ); std::memcpy( sets_w[i]->blks, LRU::sets->blks, numSets * assoc * sizeof( BlkType ) ); for(int j; j < numSets * assoc; j++){ std::memcpy( sets_w[i]->blks[j]->data, sets->blks[j]->data, sets->blks[j]->size * sizeof( uint8_t ) ); } for( int j=0; j < numSets ; j++ ){ sets_w[i][j].assoc = assoc_of_tc( j ); } } } // void // WPLRU::init_sets(){ // sets_w = new CacheSet*[num_tcs]; // for( int i=0; i< num_tcs; i++ ){ // sets_w[i] = new CacheSet[numSets]; // } // // blks_by_tc = new BlkType**[num_tcs]; // for( int i=0; i < num_tcs; i++ ){ // blks_by_tc[i] = new BlkType*[blks_in_tc(i)]; // } // // numBlocks = numSets * assoc; // blks = new BlkType[numBlocks]; // dataBlks = new uint8_t[numBlocks * blkSize]; // // unsigned blkIndex = 0; // for( unsigned tc=0; tc< num_tcs; tc++ ){ // unsigned tcIndex = 0; // for( unsigned i = 0; i< numSets; i++ ){ // int tc_assoc = assoc_of_tc(tc); // sets_w[tc][i].assoc = tc_assoc; // sets_w[tc][i].blks = new BlkType*[tc_assoc]; // for( unsigned j = 0; j<tc_assoc; j++ ){ // BlkType *blk = &blks[blkIndex]; // blk->data = &dataBlks[blkSize*blkIndex]; // ++blkIndex; // // blk->status = 0; // blk->tag = j; // blk->whenReady = 0; // blk->isTouched = false; // blk->size = blkSize; // blk->set = i; // sets_w[tc][i].blks[j] = blk; // blks_by_tc[tc][tcIndex++] = blk; // } // } // } // } void WPLRU::flush( uint64_t tcid = 0 ){ Cache<LRU> *_cache = dynamic_cast<Cache<LRU>*>(cache); for( int i=0; i < blks_in_tc(tcid); i++ ){ BlkType* b = blks_by_tc[tcid][i]; if( b->isDirty() && b->isValid() ){ _cache->allocateWriteBuffer( _cache->writebackBlk( b, tcid ), curTick(), true ); } else { invalidateBlk( b, tcid ); } } } <commit_msg>Fix typo<commit_after>#include "mem/cache/tags/wplru.hh" #include "base/intmath.hh" #include "debug/CacheRepl.hh" #include "mem/cache/tags/cacheset.hh" #include "mem/cache/tags/lru.hh" #include "mem/cache/base.hh" #include "sim/core.hh" #include "mem/cache/blk.hh" #include <typeinfo> WPLRU::WPLRU( unsigned _numSets, unsigned _blkSize, unsigned _assoc, unsigned _hit_latency, unsigned _num_tcs ) : LRU(_numSets, _blkSize, _assoc, _hit_latency ), num_tcs( _num_tcs ) { init_sets(); } CacheSet WPLRU::get_set( int setnum, uint64_t tid, Addr addr ){ CacheSet s = sets_w[tid][setnum]; #ifdef DEBUG_TP if( s.hasBlk(interesting) ){ printf( "get_set on interesting @ %lu", curTick() ); s.print(); } #endif return s; } int WPLRU::assoc_of_tc( int tcid ){ int a = assoc / num_tcs; if(tcid < (assoc%num_tcs)) a++; return a; } int WPLRU::blks_in_tc( int tcid ){ return numSets * assoc_of_tc( tcid ); } void WPLRU::init_sets(){ sets_w = new CacheSet*[num_tcs]; for( int i=0; i < num_tcs; i++ ){ sets_w[i] = new CacheSet[numSets]; std::memcpy( sets_w[i], LRU::sets, numSets * sizeof( CacheSet ) ); std::memcpy( sets_w[i]->blks, LRU::sets->blks, numSets * assoc * sizeof( BlkType ) ); for(int j=0; j < numSets * assoc; j++){ std::memcpy( sets_w[i]->blks[j]->data, sets->blks[j]->data, sets->blks[j]->size * sizeof( uint8_t ) ); } for( int j=0; j < numSets ; j++ ){ sets_w[i][j].assoc = assoc_of_tc( j ); } } } // void // WPLRU::init_sets(){ // sets_w = new CacheSet*[num_tcs]; // for( int i=0; i< num_tcs; i++ ){ // sets_w[i] = new CacheSet[numSets]; // } // // blks_by_tc = new BlkType**[num_tcs]; // for( int i=0; i < num_tcs; i++ ){ // blks_by_tc[i] = new BlkType*[blks_in_tc(i)]; // } // // numBlocks = numSets * assoc; // blks = new BlkType[numBlocks]; // dataBlks = new uint8_t[numBlocks * blkSize]; // // unsigned blkIndex = 0; // for( unsigned tc=0; tc< num_tcs; tc++ ){ // unsigned tcIndex = 0; // for( unsigned i = 0; i< numSets; i++ ){ // int tc_assoc = assoc_of_tc(tc); // sets_w[tc][i].assoc = tc_assoc; // sets_w[tc][i].blks = new BlkType*[tc_assoc]; // for( unsigned j = 0; j<tc_assoc; j++ ){ // BlkType *blk = &blks[blkIndex]; // blk->data = &dataBlks[blkSize*blkIndex]; // ++blkIndex; // // blk->status = 0; // blk->tag = j; // blk->whenReady = 0; // blk->isTouched = false; // blk->size = blkSize; // blk->set = i; // sets_w[tc][i].blks[j] = blk; // blks_by_tc[tc][tcIndex++] = blk; // } // } // } // } void WPLRU::flush( uint64_t tcid = 0 ){ Cache<LRU> *_cache = dynamic_cast<Cache<LRU>*>(cache); for( int i=0; i < blks_in_tc(tcid); i++ ){ BlkType* b = blks_by_tc[tcid][i]; if( b->isDirty() && b->isValid() ){ _cache->allocateWriteBuffer( _cache->writebackBlk( b, tcid ), curTick(), true ); } else { invalidateBlk( b, tcid ); } } } <|endoftext|>
<commit_before><commit_msg>Fixed the wrong keyboard selection behavior in reference mode.<commit_after><|endoftext|>
<commit_before>// 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. #include "base/logging.h" #include "media/base/callback.h" #include "media/base/media.h" #include "remoting/base/capture_data.h" #include "remoting/base/encoder_vp8.h" #include "remoting/proto/video.pb.h" extern "C" { #define VPX_CODEC_DISABLE_COMPAT 1 #include "third_party/libvpx/include/vpx/vpx_codec.h" #include "third_party/libvpx/include/vpx/vpx_encoder.h" #include "third_party/libvpx/include/vpx/vp8cx.h" } namespace remoting { EncoderVp8::EncoderVp8() : initialized_(false), codec_(NULL), image_(NULL), last_timestamp_(0) { } EncoderVp8::~EncoderVp8() { if (initialized_) { vpx_codec_err_t ret = vpx_codec_destroy(codec_.get()); DCHECK(ret == VPX_CODEC_OK) << "Failed to destroy codec"; } } bool EncoderVp8::Init(int width, int height) { codec_.reset(new vpx_codec_ctx_t()); image_.reset(new vpx_image_t()); memset(image_.get(), 0, sizeof(vpx_image_t)); image_->fmt = VPX_IMG_FMT_YV12; // libvpx seems to require both to be assigned. image_->d_w = width; image_->w = width; image_->d_h = height; image_->h = height; vpx_codec_enc_cfg_t config; const vpx_codec_iface_t* algo = (const vpx_codec_iface_t*)media::GetVp8CxAlgoAddress(); CHECK(algo); vpx_codec_err_t ret = vpx_codec_enc_config_default(algo, &config, 0); if (ret != VPX_CODEC_OK) return false; // TODO(hclam): Tune the parameters to better suit the application. config.rc_target_bitrate = width * height * config.rc_target_bitrate / config.g_w / config.g_h; config.g_w = width; config.g_h = height; config.g_pass = VPX_RC_ONE_PASS; config.g_profile = 1; config.g_threads = 2; config.rc_min_quantizer = 0; config.rc_max_quantizer = 15; config.g_timebase.num = 1; config.g_timebase.den = 30; if (vpx_codec_enc_init(codec_.get(), algo, &config, 0)) return false; return true; } static int clip_byte(int x) { if (x > 255) return 255; else if (x < 0) return 0; else return x; } bool EncoderVp8::PrepareImage(scoped_refptr<CaptureData> capture_data) { const int plane_size = capture_data->width() * capture_data->height(); if (!yuv_image_.get()) { // YUV image size is 1.5 times of a plane. Multiplication is performed first // to avoid rounding error. const int size = plane_size * 3 / 2; yuv_image_.reset(new uint8[size]); // Reset image value to 128 so we just need to fill in the y plane. memset(yuv_image_.get(), 128, size); // Fill in the information for |image_|. unsigned char* image = reinterpret_cast<unsigned char*>(yuv_image_.get()); image_->planes[0] = image; image_->planes[1] = image + plane_size; // The V plane starts from 1.25 of the plane size. image_->planes[2] = image + plane_size + plane_size / 4; // In YV12 Y plane has full width, UV plane has half width because of // subsampling. image_->stride[0] = image_->w; image_->stride[1] = image_->w / 2; image_->stride[2] = image_->w / 2; } // And then do RGB->YUV conversion. // Currently we just produce the Y channel as the average of RGB. This will // giv ae gray scale image after conversion. // TODO(sergeyu): Move this code to a separate routine. // TODO(sergeyu): Optimize this code. DCHECK(capture_data->pixel_format() == media::VideoFrame::RGB32) << "Only RGB32 is supported"; uint8* in = capture_data->data_planes().data[0]; const int in_stride = capture_data->data_planes().strides[0]; uint8* y_out = yuv_image_.get(); uint8* u_out = yuv_image_.get() + plane_size; uint8* v_out = yuv_image_.get() + plane_size + plane_size / 4; const int out_stride = image_->stride[0]; for (int i = 0; i < capture_data->height(); ++i) { for (int j = 0; j < capture_data->width(); ++j) { // Since the input pixel format is RGB32, there are 4 bytes per pixel. uint8* pixel = in + 4 * j; y_out[j] = clip_byte(((pixel[2] * 66 + pixel[1] * 129 + pixel[0] * 25 + 128) >> 8) + 16); if (i % 2 == 0 && j % 2 == 0) { u_out[j / 2] = clip_byte(((pixel[2] * -38 + pixel[1] * -74 + pixel[0] * 112 + 128) >> 8) + 128); v_out[j / 2] = clip_byte(((pixel[2] * 112 + pixel[1] * -94 + pixel[1] * -18 + 128) >> 8) + 128); } } in += in_stride; y_out += out_stride; if (i % 2 == 0) { u_out += out_stride / 2; v_out += out_stride / 2; } } return true; } void EncoderVp8::Encode(scoped_refptr<CaptureData> capture_data, bool key_frame, DataAvailableCallback* data_available_callback) { if (!initialized_) { bool ret = Init(capture_data->width(), capture_data->height()); // TODO(hclam): Handle error better. DCHECK(ret) << "Initialization of encoder failed"; initialized_ = ret; } if (!PrepareImage(capture_data)) { NOTREACHED() << "Can't image data for encoding"; } // Do the actual encoding. vpx_codec_err_t ret = vpx_codec_encode(codec_.get(), image_.get(), last_timestamp_, 1, 0, VPX_DL_REALTIME); DCHECK_EQ(ret, VPX_CODEC_OK) << "Encoding error: " << vpx_codec_err_to_string(ret) << "\n" << "Details: " << vpx_codec_error(codec_.get()) << "\n" << vpx_codec_error_detail(codec_.get()); // TODO(hclam): fix this. last_timestamp_ += 100; // Read the encoded data. vpx_codec_iter_t iter = NULL; bool got_data = false; // TODO(hclam): Make sure we get exactly one frame from the packet. // TODO(hclam): We should provide the output buffer to avoid one copy. VideoPacket* message = new VideoPacket(); while (!got_data) { const vpx_codec_cx_pkt_t* packet = vpx_codec_get_cx_data(codec_.get(), &iter); if (!packet) continue; switch (packet->kind) { case VPX_CODEC_CX_FRAME_PKT: got_data = true; message->set_data(packet->data.frame.buf, packet->data.frame.sz); break; default: break; } } message->mutable_format()->set_encoding(VideoPacketFormat::ENCODING_VP8); message->set_flags(VideoPacket::FIRST_PACKET | VideoPacket::LAST_PACKET); data_available_callback->Run(message); delete data_available_callback; } } // namespace remoting <commit_msg>Revert 68384: Landed with incorrect commit message. Refactor ZLib and Verbatim encoders.<commit_after>// 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. #include "base/logging.h" #include "media/base/callback.h" #include "media/base/media.h" #include "remoting/base/capture_data.h" #include "remoting/base/encoder_vp8.h" #include "remoting/proto/video.pb.h" extern "C" { #define VPX_CODEC_DISABLE_COMPAT 1 #include "third_party/libvpx/include/vpx/vpx_codec.h" #include "third_party/libvpx/include/vpx/vpx_encoder.h" #include "third_party/libvpx/include/vpx/vp8cx.h" } namespace remoting { EncoderVp8::EncoderVp8() : initialized_(false), codec_(NULL), image_(NULL), last_timestamp_(0) { } EncoderVp8::~EncoderVp8() { if (initialized_) { vpx_codec_err_t ret = vpx_codec_destroy(codec_.get()); DCHECK(ret == VPX_CODEC_OK) << "Failed to destroy codec"; } } bool EncoderVp8::Init(int width, int height) { codec_.reset(new vpx_codec_ctx_t()); image_.reset(new vpx_image_t()); memset(image_.get(), 0, sizeof(vpx_image_t)); image_->fmt = VPX_IMG_FMT_YV12; // libvpx seems to require both to be assigned. image_->d_w = width; image_->w = width; image_->d_h = height; image_->h = height; vpx_codec_enc_cfg_t config; const vpx_codec_iface_t* algo = (const vpx_codec_iface_t*)media::GetVp8CxAlgoAddress(); CHECK(algo); vpx_codec_err_t ret = vpx_codec_enc_config_default(algo, &config, 0); if (ret != VPX_CODEC_OK) return false; // TODO(hclam): Tune the parameters to better suit the application. config.rc_target_bitrate = width * height * config.rc_target_bitrate / config.g_w / config.g_h; config.g_w = width; config.g_h = height; config.g_pass = VPX_RC_ONE_PASS; config.g_profile = 1; config.g_threads = 2; config.rc_min_quantizer = 0; config.rc_max_quantizer = 15; config.g_timebase.num = 1; config.g_timebase.den = 30; if (vpx_codec_enc_init(codec_.get(), algo, &config, 0)) return false; return true; } static int clip_byte(int x) { if (x > 255) return 255; else if (x < 0) return 0; else return x; } bool EncoderVp8::PrepareImage(scoped_refptr<CaptureData> capture_data) { const int plane_size = capture_data->width() * capture_data->height(); if (!yuv_image_.get()) { // YUV image size is 1.5 times of a plane. Multiplication is performed first // to avoid rounding error. const int size = plane_size * 3 / 2; yuv_image_.reset(new uint8[size]); // Reset image value to 128 so we just need to fill in the y plane. memset(yuv_image_.get(), 128, size); // Fill in the information for |image_|. unsigned char* image = reinterpret_cast<unsigned char*>(yuv_image_.get()); image_->planes[0] = image; image_->planes[1] = image + plane_size; // The V plane starts from 1.25 of the plane size. image_->planes[2] = image + plane_size + plane_size / 4; // In YV12 Y plane has full width, UV plane has half width because of // subsampling. image_->stride[0] = image_->w; image_->stride[1] = image_->w / 2; image_->stride[2] = image_->w / 2; } // And then do RGB->YUV conversion. // Currently we just produce the Y channel as the average of RGB. This will // giv ae gray scale image after conversion. // TODO(sergeyu): Move this code to a separate routine. // TODO(sergeyu): Optimize this code. DCHECK(capture_data->pixel_format() == media::VideoFrame::RGB32) << "Only RGB32 is supported"; uint8* in = capture_data->data_planes().data[0]; const int in_stride = capture_data->data_planes().strides[0]; uint8* y_out = yuv_image_.get(); uint8* u_out = yuv_image_.get() + plane_size; uint8* v_out = yuv_image_.get() + plane_size + plane_size / 4; const int out_stride = image_->stride[0]; for (int i = 0; i < capture_data->height(); ++i) { for (int j = 0; j < capture_data->width(); ++j) { // Since the input pixel format is RGB32, there are 4 bytes per pixel. uint8* pixel = in + 4 * j; y_out[j] = clip_byte(((pixel[0] * 66 + pixel[1] * 129 + pixel[2] * 25 + 128) >> 8) + 16); if (i % 2 == 0 && j % 2 == 0) { u_out[j / 2] = clip_byte(((pixel[0] * -38 + pixel[1] * -74 + pixel[2] * 112 + 128) >> 8) + 128); v_out[j / 2] = clip_byte(((pixel[0] * 112 + pixel[1] * -94 + pixel[2] * -18 + 128) >> 8) + 128); } } in += in_stride; y_out += out_stride; if (i % 2 == 0) { u_out += out_stride / 2; v_out += out_stride / 2; } } return true; } void EncoderVp8::Encode(scoped_refptr<CaptureData> capture_data, bool key_frame, DataAvailableCallback* data_available_callback) { if (!initialized_) { bool ret = Init(capture_data->width(), capture_data->height()); // TODO(hclam): Handle error better. DCHECK(ret) << "Initialization of encoder failed"; initialized_ = ret; } if (!PrepareImage(capture_data)) { NOTREACHED() << "Can't image data for encoding"; } // Do the actual encoding. vpx_codec_err_t ret = vpx_codec_encode(codec_.get(), image_.get(), last_timestamp_, 1, 0, VPX_DL_REALTIME); DCHECK_EQ(ret, VPX_CODEC_OK) << "Encoding error: " << vpx_codec_err_to_string(ret) << "\n" << "Details: " << vpx_codec_error(codec_.get()) << "\n" << vpx_codec_error_detail(codec_.get()); // TODO(hclam): fix this. last_timestamp_ += 100; // Read the encoded data. vpx_codec_iter_t iter = NULL; bool got_data = false; // TODO(hclam): Make sure we get exactly one frame from the packet. // TODO(hclam): We should provide the output buffer to avoid one copy. VideoPacket* message = new VideoPacket(); while (!got_data) { const vpx_codec_cx_pkt_t* packet = vpx_codec_get_cx_data(codec_.get(), &iter); if (!packet) continue; switch (packet->kind) { case VPX_CODEC_CX_FRAME_PKT: got_data = true; message->set_data(packet->data.frame.buf, packet->data.frame.sz); break; default: break; } } message->mutable_format()->set_encoding(VideoPacketFormat::ENCODING_VP8); message->set_flags(VideoPacket::FIRST_PACKET | VideoPacket::LAST_PACKET); data_available_callback->Run(message); delete data_available_callback; } } // namespace remoting <|endoftext|>
<commit_before>#include "SkCanvas.h" #include "SkColorPriv.h" #include "SkGraphics.h" #include "SkImageEncoder.h" #include "SkNWayCanvas.h" #include "SkPicture.h" #include "SkString.h" #include "SkTime.h" #include "SkBenchmark.h" static void erase(SkBitmap& bm) { if (bm.config() == SkBitmap::kA8_Config) { bm.eraseColor(0); } else { bm.eraseColor(SK_ColorWHITE); } } static bool equal(const SkBitmap& bm1, const SkBitmap& bm2) { if (bm1.width() != bm2.width() || bm1.height() != bm2.height() || bm1.config() != bm2.config()) { return false; } size_t pixelBytes = bm1.width() * bm1.bytesPerPixel(); for (int y = 0; y < bm1.height(); y++) { if (memcmp(bm1.getAddr(0, y), bm2.getAddr(0, y), pixelBytes)) { return false; } } return true; } class Iter { public: Iter() { fBench = BenchRegistry::Head(); } SkBenchmark* next() { if (fBench) { BenchRegistry::Factory f = fBench->factory(); fBench = fBench->next(); return f(0); } return NULL; } private: const BenchRegistry* fBench; }; static void make_filename(const char name[], SkString* path) { path->set(name); for (int i = 0; name[i]; i++) { switch (name[i]) { case '/': case '\\': case ' ': case ':': path->writable_str()[i] = '-'; break; default: break; } } } static void saveFile(const char name[], const char config[], const char dir[], const SkBitmap& bm) { SkBitmap copy; if (!bm.copyTo(&copy, SkBitmap::kARGB_8888_Config)) { return; } if (bm.config() == SkBitmap::kA8_Config) { // turn alpha into gray-scale size_t size = copy.getSize() >> 2; SkPMColor* p = copy.getAddr32(0, 0); for (size_t i = 0; i < size; i++) { int c = (*p >> SK_A32_SHIFT) & 0xFF; c = 255 - c; c |= (c << 24) | (c << 16) | (c << 8); *p++ = c | (SK_A32_MASK << SK_A32_SHIFT); } } SkString str; make_filename(name, &str); str.appendf("_%s.png", config); str.prepend(dir); ::remove(str.c_str()); SkImageEncoder::EncodeFile(str.c_str(), copy, SkImageEncoder::kPNG_Type, 100); } static void performClip(SkCanvas* canvas, int w, int h) { SkRect r; r.set(SkIntToScalar(10), SkIntToScalar(10), SkIntToScalar(w*2/3), SkIntToScalar(h*2/3)); canvas->clipRect(r, SkRegion::kIntersect_Op); r.set(SkIntToScalar(w/3), SkIntToScalar(h/3), SkIntToScalar(w-10), SkIntToScalar(h-10)); canvas->clipRect(r, SkRegion::kXOR_Op); } static void performRotate(SkCanvas* canvas, int w, int h) { const SkScalar x = SkIntToScalar(w) / 2; const SkScalar y = SkIntToScalar(h) / 2; canvas->translate(x, y); canvas->rotate(SkIntToScalar(35)); canvas->translate(-x, -y); } static void compare_pict_to_bitmap(SkPicture* pict, const SkBitmap& bm) { SkBitmap bm2; bm2.setConfig(bm.config(), bm.width(), bm.height()); bm2.allocPixels(); erase(bm2); SkCanvas canvas(bm2); canvas.drawPicture(*pict); if (!equal(bm, bm2)) { SkDebugf("----- compare_pict_to_bitmap failed\n"); } } static const struct { SkBitmap::Config fConfig; const char* fName; } gConfigs[] = { { SkBitmap::kARGB_8888_Config, "8888" }, { SkBitmap::kRGB_565_Config, "565", }, { SkBitmap::kARGB_4444_Config, "4444", }, { SkBitmap::kA8_Config, "A8", } }; static int findConfig(const char config[]) { for (size_t i = 0; i < SK_ARRAY_COUNT(gConfigs); i++) { if (!strcmp(config, gConfigs[i].fName)) { return i; } } return -1; } int main (int argc, char * const argv[]) { SkAutoGraphics ag; int repeatDraw = 1; int forceAlpha = 0xFF; bool forceAA = true; bool doRotate = false; bool doClip = false; bool doPict = false; SkString outDir; SkBitmap::Config outConfig = SkBitmap::kARGB_8888_Config; char* const* stop = argv + argc; for (++argv; argv < stop; ++argv) { if (strcmp(*argv, "-o") == 0) { argv++; if (argv < stop && **argv) { outDir.set(*argv); if (outDir.c_str()[outDir.size() - 1] != '/') { outDir.append("/"); } } } else if (strcmp(*argv, "-pict") == 0) { doPict = true; } else if (strcmp(*argv, "-repeat") == 0) { argv++; if (argv < stop) { repeatDraw = atoi(*argv); if (repeatDraw < 1) { repeatDraw = 1; } } else { fprintf(stderr, "missing arg for -repeat\n"); return -1; } } else if (!strcmp(*argv, "-rotate")) { doRotate = true; } else if (!strcmp(*argv, "-clip")) { doClip = true; } else if (strcmp(*argv, "-forceAA") == 0) { forceAA = true; } else if (strcmp(*argv, "-forceBW") == 0) { forceAA = false; } else if (strcmp(*argv, "-forceBlend") == 0) { forceAlpha = 0x80; } else if (strcmp(*argv, "-forceOpaque") == 0) { forceAlpha = 0xFF; } else { int index = findConfig(*argv); if (index >= 0) { outConfig = gConfigs[index].fConfig; } } } const char* configName = ""; int configCount = SK_ARRAY_COUNT(gConfigs); Iter iter; SkBenchmark* bench; while ((bench = iter.next()) != NULL) { SkIPoint dim = bench->getSize(); if (dim.fX <= 0 || dim.fY <= 0) { continue; } bench->setForceAlpha(forceAlpha); bench->setForceAA(forceAA); printf("running bench %16s", bench->getName()); for (int configIndex = 0; configIndex < configCount; configIndex++) { if (configCount > 1) { outConfig = gConfigs[configIndex].fConfig; configName = gConfigs[configIndex].fName; } SkBitmap bm; bm.setConfig(outConfig, dim.fX, dim.fY); bm.allocPixels(); erase(bm); SkCanvas canvas(bm); if (doClip) { performClip(&canvas, dim.fX, dim.fY); } if (doRotate) { performRotate(&canvas, dim.fX, dim.fY); } SkMSec now = SkTime::GetMSecs(); for (int i = 0; i < repeatDraw; i++) { SkCanvas* c = &canvas; SkNWayCanvas nway; SkPicture* pict = NULL; if (doPict) { pict = new SkPicture; nway.addCanvas(pict->beginRecording(bm.width(), bm.height())); nway.addCanvas(&canvas); c = &nway; } SkAutoCanvasRestore acr(c, true); bench->draw(c); if (pict) { compare_pict_to_bitmap(pict, bm); pict->unref(); } } if (repeatDraw > 1) { printf(" %4s:%7.2f", configName, (SkTime::GetMSecs() - now) / (double)repeatDraw); } if (outDir.size() > 0) { saveFile(bench->getName(), configName, outDir.c_str(), bm); } } printf("\n"); } return 0; } <commit_msg>add -config foo to restrict the output to just the specific config add -match foo to restrict the benchmarks to those whose names match foo<commit_after>#include "SkCanvas.h" #include "SkColorPriv.h" #include "SkGraphics.h" #include "SkImageEncoder.h" #include "SkNWayCanvas.h" #include "SkPicture.h" #include "SkString.h" #include "SkTime.h" #include "SkBenchmark.h" static void erase(SkBitmap& bm) { if (bm.config() == SkBitmap::kA8_Config) { bm.eraseColor(0); } else { bm.eraseColor(SK_ColorWHITE); } } static bool equal(const SkBitmap& bm1, const SkBitmap& bm2) { if (bm1.width() != bm2.width() || bm1.height() != bm2.height() || bm1.config() != bm2.config()) { return false; } size_t pixelBytes = bm1.width() * bm1.bytesPerPixel(); for (int y = 0; y < bm1.height(); y++) { if (memcmp(bm1.getAddr(0, y), bm2.getAddr(0, y), pixelBytes)) { return false; } } return true; } class Iter { public: Iter() { fBench = BenchRegistry::Head(); } SkBenchmark* next() { if (fBench) { BenchRegistry::Factory f = fBench->factory(); fBench = fBench->next(); return f(0); } return NULL; } private: const BenchRegistry* fBench; }; static void make_filename(const char name[], SkString* path) { path->set(name); for (int i = 0; name[i]; i++) { switch (name[i]) { case '/': case '\\': case ' ': case ':': path->writable_str()[i] = '-'; break; default: break; } } } static void saveFile(const char name[], const char config[], const char dir[], const SkBitmap& bm) { SkBitmap copy; if (!bm.copyTo(&copy, SkBitmap::kARGB_8888_Config)) { return; } if (bm.config() == SkBitmap::kA8_Config) { // turn alpha into gray-scale size_t size = copy.getSize() >> 2; SkPMColor* p = copy.getAddr32(0, 0); for (size_t i = 0; i < size; i++) { int c = (*p >> SK_A32_SHIFT) & 0xFF; c = 255 - c; c |= (c << 24) | (c << 16) | (c << 8); *p++ = c | (SK_A32_MASK << SK_A32_SHIFT); } } SkString str; make_filename(name, &str); str.appendf("_%s.png", config); str.prepend(dir); ::remove(str.c_str()); SkImageEncoder::EncodeFile(str.c_str(), copy, SkImageEncoder::kPNG_Type, 100); } static void performClip(SkCanvas* canvas, int w, int h) { SkRect r; r.set(SkIntToScalar(10), SkIntToScalar(10), SkIntToScalar(w*2/3), SkIntToScalar(h*2/3)); canvas->clipRect(r, SkRegion::kIntersect_Op); r.set(SkIntToScalar(w/3), SkIntToScalar(h/3), SkIntToScalar(w-10), SkIntToScalar(h-10)); canvas->clipRect(r, SkRegion::kXOR_Op); } static void performRotate(SkCanvas* canvas, int w, int h) { const SkScalar x = SkIntToScalar(w) / 2; const SkScalar y = SkIntToScalar(h) / 2; canvas->translate(x, y); canvas->rotate(SkIntToScalar(35)); canvas->translate(-x, -y); } static void performScale(SkCanvas* canvas, int w, int h) { const SkScalar x = SkIntToScalar(w) / 2; const SkScalar y = SkIntToScalar(h) / 2; canvas->translate(x, y); // just enough so we can't take the sprite case canvas->scale(SK_Scalar1 * 99/100, SK_Scalar1 * 99/100); canvas->translate(-x, -y); } static void compare_pict_to_bitmap(SkPicture* pict, const SkBitmap& bm) { SkBitmap bm2; bm2.setConfig(bm.config(), bm.width(), bm.height()); bm2.allocPixels(); erase(bm2); SkCanvas canvas(bm2); canvas.drawPicture(*pict); if (!equal(bm, bm2)) { SkDebugf("----- compare_pict_to_bitmap failed\n"); } } static const struct { SkBitmap::Config fConfig; const char* fName; } gConfigs[] = { { SkBitmap::kARGB_8888_Config, "8888" }, { SkBitmap::kRGB_565_Config, "565", }, { SkBitmap::kARGB_4444_Config, "4444", }, { SkBitmap::kA8_Config, "A8", } }; static int findConfig(const char config[]) { for (size_t i = 0; i < SK_ARRAY_COUNT(gConfigs); i++) { if (!strcmp(config, gConfigs[i].fName)) { return i; } } return -1; } int main (int argc, char * const argv[]) { SkAutoGraphics ag; int repeatDraw = 1; int forceAlpha = 0xFF; bool forceAA = true; bool doScale = false; bool doRotate = false; bool doClip = false; bool doPict = false; const char* matchStr = NULL; SkString outDir; SkBitmap::Config outConfig = SkBitmap::kNo_Config; const char* configName = ""; int configCount = SK_ARRAY_COUNT(gConfigs); char* const* stop = argv + argc; for (++argv; argv < stop; ++argv) { if (strcmp(*argv, "-o") == 0) { argv++; if (argv < stop && **argv) { outDir.set(*argv); if (outDir.c_str()[outDir.size() - 1] != '/') { outDir.append("/"); } } } else if (strcmp(*argv, "-pict") == 0) { doPict = true; } else if (strcmp(*argv, "-repeat") == 0) { argv++; if (argv < stop) { repeatDraw = atoi(*argv); if (repeatDraw < 1) { repeatDraw = 1; } } else { fprintf(stderr, "missing arg for -repeat\n"); return -1; } } else if (!strcmp(*argv, "-rotate")) { doRotate = true; } else if (!strcmp(*argv, "-scale")) { doScale = true; } else if (!strcmp(*argv, "-clip")) { doClip = true; } else if (strcmp(*argv, "-forceAA") == 0) { forceAA = true; } else if (strcmp(*argv, "-forceBW") == 0) { forceAA = false; } else if (strcmp(*argv, "-forceBlend") == 0) { forceAlpha = 0x80; } else if (strcmp(*argv, "-forceOpaque") == 0) { forceAlpha = 0xFF; } else if (strcmp(*argv, "-match") == 0) { argv++; if (argv < stop) { matchStr = *argv; } else { fprintf(stderr, "missing arg for -match\n"); return -1; } } else if (strcmp(*argv, "-config") == 0) { argv++; if (argv < stop) { int index = findConfig(*argv); if (index >= 0) { outConfig = gConfigs[index].fConfig; configName = gConfigs[index].fName; configCount = 1; } else { fprintf(stderr, "unrecognized config %s\n", *argv); return -1; } } else { fprintf(stderr, "missing arg for -config\n"); return -1; } } else { fprintf(stderr, "unrecognized arg %s\n", *argv); return -1; } } Iter iter; SkBenchmark* bench; while ((bench = iter.next()) != NULL) { SkIPoint dim = bench->getSize(); if (dim.fX <= 0 || dim.fY <= 0) { continue; } bench->setForceAlpha(forceAlpha); bench->setForceAA(forceAA); // only run benchmarks if their name contains matchStr if (matchStr && strstr(bench->getName(), matchStr) == NULL) { continue; } printf("running bench %16s", bench->getName()); for (int configIndex = 0; configIndex < configCount; configIndex++) { if (configCount > 1) { outConfig = gConfigs[configIndex].fConfig; configName = gConfigs[configIndex].fName; } SkBitmap bm; bm.setConfig(outConfig, dim.fX, dim.fY); bm.allocPixels(); erase(bm); SkCanvas canvas(bm); if (doClip) { performClip(&canvas, dim.fX, dim.fY); } if (doScale) { performScale(&canvas, dim.fX, dim.fY); } if (doRotate) { performRotate(&canvas, dim.fX, dim.fY); } SkMSec now = SkTime::GetMSecs(); for (int i = 0; i < repeatDraw; i++) { SkCanvas* c = &canvas; SkNWayCanvas nway; SkPicture* pict = NULL; if (doPict) { pict = new SkPicture; nway.addCanvas(pict->beginRecording(bm.width(), bm.height())); nway.addCanvas(&canvas); c = &nway; } SkAutoCanvasRestore acr(c, true); bench->draw(c); if (pict) { compare_pict_to_bitmap(pict, bm); pict->unref(); } } if (repeatDraw > 1) { printf(" %4s:%7.2f", configName, (SkTime::GetMSecs() - now) / (double)repeatDraw); } if (outDir.size() > 0) { saveFile(bench->getName(), configName, outDir.c_str(), bm); } } printf("\n"); } return 0; } <|endoftext|>
<commit_before>/* Copyright 2016 Carnegie Mellon University * * 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 "scanner/engine/op_registry.h" namespace scanner { namespace internal { void OpRegistry::add_op(const std::string& name, OpInfo* info) { if (ops_.count(name) > 0) { LOG(FATAL) << "Attempted to re-register op " << name; } if (info->input_columns().empty()) { LOG(FATAL) << "Attempted to register op " << name << " with empty input columns."; } if (info->output_columns().empty()) { LOG(FATAL) << "Attempted to register op " << name << " with empty output columns."; } ops_.insert({name, info}); } OpInfo* OpRegistry::get_op_info(const std::string& name) const { return ops_.at(name); } bool OpRegistry::has_op(const std::string& name) const { return ops_.count(name) > 0; } OpRegistry* get_op_registry() { static OpRegistry* registry = new OpRegistry; return registry; } } } <commit_msg>Allow empty input columns if variadic input<commit_after>/* Copyright 2016 Carnegie Mellon University * * 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 "scanner/engine/op_registry.h" namespace scanner { namespace internal { void OpRegistry::add_op(const std::string& name, OpInfo* info) { if (ops_.count(name) > 0) { LOG(FATAL) << "Attempted to re-register op " << name; } if (info->input_columns().empty() && !info->variadic_inputs()) { LOG(FATAL) << "Attempted to register op " << name << " with empty input columns."; } if (info->output_columns().empty()) { LOG(FATAL) << "Attempted to register op " << name << " with empty output columns."; } ops_.insert({name, info}); } OpInfo* OpRegistry::get_op_info(const std::string& name) const { return ops_.at(name); } bool OpRegistry::has_op(const std::string& name) const { return ops_.count(name) > 0; } OpRegistry* get_op_registry() { static OpRegistry* registry = new OpRegistry; return registry; } } } <|endoftext|>
<commit_before>#include <windows.h> #include <OvRender.h> #include "d3d8overlay.h" #include "d3d9overlay.h" #include "dxgioverlay.h" #include "ddraw\ddrawoverlay.h" Dx8Overlay* OvDx8Overlay; Dx9Overlay* D3D9Overlay; DxgiOverlay* DXGIOverlay; DDrawOverlay* DirectDrawOverlay; extern CRITICAL_SECTION OvCriticalSection; OvOverlay::OvOverlay() { Line = 0; VsyncOverrideMode = VSYNC_UNCHANGED; } VOID OvOverlay::Render() { Line = 0; Begin(); UserRenderFunction( this ); End(); } ULONG __stdcall CreateOverlay( LPVOID Param ) { EnterCriticalSection(&OvCriticalSection); OV_HOOK_PARAMS *hookParams = (OV_HOOK_PARAMS*) Param; OvOverlay *overlay = NULL; if (GetModuleHandleW(L"d3d8.dll") && OvDx8Overlay == NULL) { OvDx8Overlay = new Dx8Overlay( hookParams->RenderFunction ); overlay = OvDx8Overlay; } if (GetModuleHandleW(L"d3d9.dll") && D3D9Overlay == NULL) { D3D9Overlay = new Dx9Overlay( hookParams->RenderFunction ); overlay = D3D9Overlay; } if (GetModuleHandleW(L"dxgi.dll") && DXGIOverlay == NULL) { DXGIOverlay = new DxgiOverlay(hookParams->RenderFunction); overlay = DXGIOverlay; } if (GetModuleHandleW(L"ddraw.dll") && DirectDrawOverlay == NULL) { DirectDrawOverlay = new DDrawOverlay(hookParams->RenderFunction); overlay = DirectDrawOverlay; } if (overlay) overlay->VsyncOverrideMode = hookParams->VsyncOverrideMode; LeaveCriticalSection(&OvCriticalSection); return NULL; } VOID OvCreateOverlay( OV_RENDER RenderFunction ) { OV_HOOK_PARAMS hookParams = {0}; hookParams.RenderFunction = RenderFunction; OvCreateOverlayEx(&hookParams); } VOID OvCreateOverlayEx( OV_HOOK_PARAMS* HookParameters ) { OV_HOOK_PARAMS *hookParams; hookParams = (OV_HOOK_PARAMS*) HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(OV_HOOK_PARAMS) ); hookParams->RenderFunction = HookParameters->RenderFunction; hookParams->VsyncOverrideMode = HookParameters->VsyncOverrideMode; CreateThread(0, 0, &CreateOverlay, hookParams, 0, 0); } <commit_msg>added some debug messages<commit_after>#include <windows.h> #include <OvRender.h> #include "d3d8overlay.h" #include "d3d9overlay.h" #include "dxgioverlay.h" #include "ddraw\ddrawoverlay.h" Dx8Overlay* OvDx8Overlay; Dx9Overlay* D3D9Overlay; DxgiOverlay* DXGIOverlay; DDrawOverlay* DirectDrawOverlay; extern CRITICAL_SECTION OvCriticalSection; OvOverlay::OvOverlay() { Line = 0; VsyncOverrideMode = VSYNC_UNCHANGED; } VOID OvOverlay::Render() { Line = 0; Begin(); UserRenderFunction( this ); End(); } ULONG __stdcall CreateOverlay( LPVOID Param ) { EnterCriticalSection(&OvCriticalSection); OV_HOOK_PARAMS *hookParams = (OV_HOOK_PARAMS*) Param; OvOverlay *overlay = NULL; BOOLEAN d3d8, d3d9, dxgi, ddraw; if (GetModuleHandleW(L"d3d8.dll")) { OutputDebugStringW(L"GetModuleHandle(\"d3d8.dll\") returned TRUE"); d3d8 = TRUE; } else { OutputDebugStringW(L"GetModuleHandle(\"d3d8.dll\") returned FALSE"); d3d8 = FALSE; } if (GetModuleHandleW(L"d3d9.dll")) { OutputDebugStringW(L"GetModuleHandle(\"d3d9.dll\") returned TRUE"); d3d9 = TRUE; } else { OutputDebugStringW(L"GetModuleHandle(\"d3d9.dll\") returned FALSE"); d3d9 = FALSE; } if (GetModuleHandleW(L"dxgi.dll")) { OutputDebugStringW(L"GetModuleHandle(\"dxgi.dll\") returned TRUE"); dxgi = TRUE; } else { OutputDebugStringW(L"GetModuleHandle(\"dxgi.dll\") returned FALSE"); dxgi = FALSE; } if (GetModuleHandleW(L"ddraw.dll")) { OutputDebugStringW(L"GetModuleHandle(\"ddraw.dll\") returned TRUE"); ddraw = TRUE; } else { OutputDebugStringW(L"GetModuleHandle(\"ddraw.dll\") returned FALSE"); ddraw = FALSE; } if (d3d8 && OvDx8Overlay == NULL) { OutputDebugStringW(L"Hooking d3d8..."); OvDx8Overlay = new Dx8Overlay( hookParams->RenderFunction ); overlay = OvDx8Overlay; } if (d3d9 && D3D9Overlay == NULL) { OutputDebugStringW(L"Hooking d3d9..."); D3D9Overlay = new Dx9Overlay( hookParams->RenderFunction ); overlay = D3D9Overlay; } if (dxgi && DXGIOverlay == NULL) { OutputDebugStringW(L"Hooking dxgi..."); DXGIOverlay = new DxgiOverlay(hookParams->RenderFunction); overlay = DXGIOverlay; } if (ddraw && DirectDrawOverlay == NULL) { OutputDebugStringW(L"Hooking ddraw..."); DirectDrawOverlay = new DDrawOverlay(hookParams->RenderFunction); overlay = DirectDrawOverlay; } if (overlay) overlay->VsyncOverrideMode = hookParams->VsyncOverrideMode; LeaveCriticalSection(&OvCriticalSection); return NULL; } VOID OvCreateOverlay( OV_RENDER RenderFunction ) { OV_HOOK_PARAMS hookParams = {0}; hookParams.RenderFunction = RenderFunction; OvCreateOverlayEx(&hookParams); } VOID OvCreateOverlayEx( OV_HOOK_PARAMS* HookParameters ) { OV_HOOK_PARAMS *hookParams; hookParams = (OV_HOOK_PARAMS*) HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(OV_HOOK_PARAMS) ); hookParams->RenderFunction = HookParameters->RenderFunction; hookParams->VsyncOverrideMode = HookParameters->VsyncOverrideMode; CreateThread(0, 0, &CreateOverlay, hookParams, 0, 0); } <|endoftext|>
<commit_before>/** * @file * * @brief Source for yanlr plugin * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) * */ // -- Imports ------------------------------------------------------------------------------------------------------------------------------ #include <iostream> #include <kdb.hpp> #include <kdberrors.h> #include <antlr4-runtime.h> #include "YAML.h" #include "error_listener.hpp" #include "listener.hpp" #include "yaml_lexer.hpp" #include "yanlr.hpp" using CppKey = kdb::Key; using CppKeySet = kdb::KeySet; using yanlr::ErrorListener; using yanlr::KeyListener; using yanlr::YAML; using yanlr::YAMLLexer; using antlr4::ANTLRInputStream; using antlr4::CommonTokenStream; using antlr4::DiagnosticErrorListener; using ParserATNSimulator = antlr4::atn::ParserATNSimulator; using PredictionMode = antlr4::atn::PredictionMode; using ParseTree = antlr4::tree::ParseTree; using ParseTreeWalker = antlr4::tree::ParseTreeWalker; using std::ifstream; // -- Functions ---------------------------------------------------------------------------------------------------------------------------- namespace { /** * @brief This function returns a key set containing the contract of this plugin. * * @return A contract describing the functionality of this plugin. */ CppKeySet getContract () { return CppKeySet{ 30, keyNew ("system/elektra/modules/yanlr", KEY_VALUE, "yanlr plugin waits for your orders", KEY_END), keyNew ("system/elektra/modules/yanlr/exports", KEY_END), keyNew ("system/elektra/modules/yanlr/exports/get", KEY_FUNC, elektraYanlrGet, KEY_END), #include ELEKTRA_README keyNew ("system/elektra/modules/yanlr/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END), KS_END }; } /** * @brief This function parses the content of a YAML file and saves the result in the given key set. * * @param file This file contains the YAML content this function should parse. * @param keys The function adds the key set representing `file` in this key set, if the parsing process finished successfully. * @param parent The function uses this parameter to emit error information. * * @retval ELEKTRA_PLUGIN_STATUS_NO_UPDATE If parsing was successful and `keys` was not updated * @retval ELEKTRA_PLUGIN_STATUS_SUCCESS If parsing was successful and `keys` was updated * @retval ELEKTRA_PLUGIN_STATUS_ERROR If there was an error parsing `file` */ int parseYAML (ifstream & file, CppKeySet & keys, CppKey & parent) { ANTLRInputStream input{ file }; YAMLLexer lexer{ &input }; CommonTokenStream tokens{ &lexer }; YAML parser{ &tokens }; ParseTreeWalker walker{}; KeyListener listener{ parent }; ErrorListener errorListener{ parent.getString () }; parser.removeErrorListeners (); parser.addErrorListener (&errorListener); #if DEBUG DiagnosticErrorListener diagErrorListener; parser.addErrorListener (&diagErrorListener); parser.getInterpreter<ParserATNSimulator> ()->setPredictionMode (PredictionMode::LL_EXACT_AMBIG_DETECTION); #endif ParseTree * tree = parser.yaml (); if (parser.getNumberOfSyntaxErrors () > 0) { ELEKTRA_SET_VALIDATION_SYNTACTIC_ERROR (parent.getKey (), errorListener.message ()); return ELEKTRA_PLUGIN_STATUS_ERROR; } walker.walk (&listener, tree); auto readKeys = listener.keySet (); keys.append (readKeys); return readKeys.size () <= 0 ? ELEKTRA_PLUGIN_STATUS_NO_UPDATE : ELEKTRA_PLUGIN_STATUS_SUCCESS; } } // end namespace extern "C" { // ==================== // = Plugin Interface = // ==================== /** @see elektraDocGet */ int elektraYanlrGet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned, Key * parentKey) { CppKey parent{ parentKey }; CppKeySet keys{ returned }; if (parent.getName () == "system/elektra/modules/yanlr") { keys.append (getContract ()); keys.release (); parent.release (); return ELEKTRA_PLUGIN_STATUS_SUCCESS; } ifstream file (parent.getString ()); if (!file.is_open ()) { ELEKTRA_SET_RESOURCE_ERRORF (parent.getKey (), "Unable to open file '%s'", parent.getString ().c_str ()); return ELEKTRA_PLUGIN_STATUS_ERROR; } int status = parseYAML (file, keys, parent); keys.release (); parent.release (); return status; } Plugin * ELEKTRA_PLUGIN_EXPORT { return elektraPluginExport ("yanlr", ELEKTRA_PLUGIN_GET, &elektraYanlrGet, ELEKTRA_PLUGIN_END); } } // end extern "C" <commit_msg>error: yanlr fix<commit_after>/** * @file * * @brief Source for yanlr plugin * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) * */ // -- Imports ------------------------------------------------------------------------------------------------------------------------------ #include <iostream> #include <kdb.hpp> #include <kdberrors.h> #include <antlr4-runtime.h> #include "YAML.h" #include "error_listener.hpp" #include "listener.hpp" #include "yaml_lexer.hpp" #include "yanlr.hpp" using CppKey = kdb::Key; using CppKeySet = kdb::KeySet; using yanlr::ErrorListener; using yanlr::KeyListener; using yanlr::YAML; using yanlr::YAMLLexer; using antlr4::ANTLRInputStream; using antlr4::CommonTokenStream; using antlr4::DiagnosticErrorListener; using ParserATNSimulator = antlr4::atn::ParserATNSimulator; using PredictionMode = antlr4::atn::PredictionMode; using ParseTree = antlr4::tree::ParseTree; using ParseTreeWalker = antlr4::tree::ParseTreeWalker; using ckdb::keyNew; using std::ifstream; // -- Functions // ---------------------------------------------------------------------------------------------------------------------------- namespace { /** * @brief This function returns a key set containing the contract of this plugin. * * @return A contract describing the functionality of this plugin. */ CppKeySet getContract () { return CppKeySet{ 30, keyNew ("system/elektra/modules/yanlr", KEY_VALUE, "yanlr plugin waits for your orders", KEY_END), keyNew ("system/elektra/modules/yanlr/exports", KEY_END), keyNew ("system/elektra/modules/yanlr/exports/get", KEY_FUNC, elektraYanlrGet, KEY_END), #include ELEKTRA_README keyNew ("system/elektra/modules/yanlr/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END), KS_END }; } /** * @brief This function parses the content of a YAML file and saves the result in the given key set. * * @param file This file contains the YAML content this function should parse. * @param keys The function adds the key set representing `file` in this key set, if the parsing process finished successfully. * @param parent The function uses this parameter to emit error information. * * @retval ELEKTRA_PLUGIN_STATUS_NO_UPDATE If parsing was successful and `keys` was not updated * @retval ELEKTRA_PLUGIN_STATUS_SUCCESS If parsing was successful and `keys` was updated * @retval ELEKTRA_PLUGIN_STATUS_ERROR If there was an error parsing `file` */ int parseYAML (ifstream & file, CppKeySet & keys, CppKey & parent) { ANTLRInputStream input{ file }; YAMLLexer lexer{ &input }; CommonTokenStream tokens{ &lexer }; YAML parser{ &tokens }; ParseTreeWalker walker{}; KeyListener listener{ parent }; ErrorListener errorListener{ parent.getString () }; parser.removeErrorListeners (); parser.addErrorListener (&errorListener); #if DEBUG DiagnosticErrorListener diagErrorListener; parser.addErrorListener (&diagErrorListener); parser.getInterpreter<ParserATNSimulator> ()->setPredictionMode (PredictionMode::LL_EXACT_AMBIG_DETECTION); #endif ParseTree * tree = parser.yaml (); if (parser.getNumberOfSyntaxErrors () > 0) { ELEKTRA_SET_VALIDATION_SYNTACTIC_ERROR (parent.getKey (), errorListener.message ()); return ELEKTRA_PLUGIN_STATUS_ERROR; } walker.walk (&listener, tree); auto readKeys = listener.keySet (); keys.append (readKeys); return readKeys.size () <= 0 ? ELEKTRA_PLUGIN_STATUS_NO_UPDATE : ELEKTRA_PLUGIN_STATUS_SUCCESS; } } // end namespace extern "C" { // ==================== // = Plugin Interface = // ==================== /** @see elektraDocGet */ int elektraYanlrGet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned, Key * parentKey) { CppKey parent{ parentKey }; CppKeySet keys{ returned }; if (parent.getName () == "system/elektra/modules/yanlr") { keys.append (getContract ()); keys.release (); parent.release (); return ELEKTRA_PLUGIN_STATUS_SUCCESS; } ifstream file (parent.getString ()); if (!file.is_open ()) { ELEKTRA_SET_RESOURCE_ERRORF (parent.getKey (), "Unable to open file '%s'", parent.getString ().c_str ()); return ELEKTRA_PLUGIN_STATUS_ERROR; } int status = parseYAML (file, keys, parent); keys.release (); parent.release (); return status; } Plugin * ELEKTRA_PLUGIN_EXPORT { return elektraPluginExport ("yanlr", ELEKTRA_PLUGIN_GET, &elektraYanlrGet, ELEKTRA_PLUGIN_END); } } // end extern "C" <|endoftext|>
<commit_before><commit_msg>coverity#736943 Untrusted loop bound<commit_after><|endoftext|>
<commit_before>/* This file is part of KAddressBook. Copyright (c) 2002 Mike Pilone <mpilone@slac.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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., 675 Mass Ave, Cambridge, MA 02139, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <qapplication.h> #include <qclipboard.h> #include <kapplication.h> #include <kconfig.h> #include <kdebug.h> #include <klocale.h> #include <kprotocolinfo.h> #include <kxmlguiclient.h> #include <kxmlguifactory.h> #include "actionmanager.h" #include "kaddressbook.h" #include "viewmanager.h" #include "undo.h" ActionManager::ActionManager(KXMLGUIClient *client, KAddressBook *widget, bool readWrite, QObject *parent) : QObject(parent) { mGUIClient = client; mACollection = mGUIClient->actionCollection(); mWidget = widget; connect( mWidget, SIGNAL( addresseeSelected( bool ) ), SLOT( addresseeSelected( bool ) ) ); connect( mWidget, SIGNAL( modified( bool ) ), SLOT( modified( bool ) ) ); mViewManager = mWidget->viewManager(); connect( mViewManager, SIGNAL( viewConfigChanged(const QString &) ), SLOT( viewConfigChanged(const QString &) ) ); connect( QApplication::clipboard(), SIGNAL( dataChanged() ), SLOT( clipboardDataChanged() ) ); mReadWrite = readWrite; initReadOnlyActions(); if (mReadWrite) initReadWriteActions(); // Read our own config KConfig *config = kapp->config(); config->setGroup("Views"); mActiveViewName = config->readEntry("Active"); config->setGroup("MainWindow"); mActionJumpBar->setChecked(config->readBoolEntry("JumpBar", false)); mActionQuickEdit->setChecked(config->readBoolEntry("QuickEdit", false)); // Set the defaults addresseeSelected(false); modified(false); quickToolsAction(); mActionViewList.setAutoDelete(true); // Connect to the signals from the undo/redo stacks so we can update the // edit menu connect(UndoStack::instance(), SIGNAL(changed()), SLOT(updateEditMenu())); connect(RedoStack::instance(), SIGNAL(changed()), SLOT(updateEditMenu())); } ActionManager::~ActionManager() { // Write our own config KConfig *config = kapp->config(); config->setGroup("Views"); config->writeEntry("Active", mActiveViewName); config->setGroup("MainWindow"); config->writeEntry("JumpBar", mActionJumpBar->isChecked()); config->writeEntry("QuickEdit", mActionQuickEdit->isChecked()); } void ActionManager::setReadWrite(bool rw) { if (rw == mReadWrite) return; mReadWrite = rw; if (mReadWrite) initReadWriteActions(); else destroyReadWriteActions(); } void ActionManager::clipboardDataChanged() { if (mReadWrite) mActionPaste->setEnabled( !QApplication::clipboard()->text().isEmpty() ); } void ActionManager::initReadOnlyActions() { // File menu mActionSave = new KAction(i18n("&Save"), "filesave", CTRL+Key_S, mWidget, SLOT(save()), mACollection,"file_sync"); new KAction(i18n("&New Contact"), "filenew", CTRL+Key_N, mWidget, SLOT(newAddressee()),mACollection,"file_new_contact"); new KAction(i18n("&Distribution List..."), 0, mWidget, SLOT(slotDistributionList()), mACollection, "file_distribution_list"); mActionMail = KStdAction::mail(mViewManager, SLOT(sendMail()), mACollection); mActionEditAddressee = new KAction(i18n("&Edit Contact..."), "edit", 0, mWidget, SLOT(editAddressee()), mACollection, "file_properties"); KStdAction::print(mWidget, SLOT(print()), mACollection); new KAction(i18n("Import &KDE 2 Address Book..."), 0, mWidget, SLOT(importKDE2()), mACollection, "file_import_kde2"); new KAction(i18n("Import vCard2.1 ..."), 0, mWidget, SLOT(importVCard21()), mACollection, "file_import_vcard21"); new KAction(i18n("Import vCard3.0 ..."), 0, mWidget, SLOT(importVCard30()), mACollection, "file_import_vcard30"); new KAction(i18n("&Import List..."), 0, mWidget, SLOT(importCSV()), mACollection, "file_import_csv"); new KAction(i18n("&Export List..."), 0, mWidget, SLOT(exportCSV()), mACollection, "file_export_csv"); new KAction(i18n("&Export vCard3.0..."), 0, mWidget, SLOT(exportVCard30()), mACollection, "file_export_vcard30"); // Edit menu mActionCopy = KStdAction::copy(mViewManager, SLOT(copy()), mACollection); KStdAction::selectAll(mViewManager, SLOT(setSelected()), mACollection); mActionDelete = new KAction(i18n("&Delete Contact"), "editdelete", Key_Delete, mViewManager, SLOT(deleteAddressee()), mACollection, "edit_delete"); mActionUndo = KStdAction::undo(mWidget, SLOT(undo()), mACollection); mActionUndo->setEnabled(false); mActionRedo = KStdAction::redo(mWidget, SLOT(redo()), mACollection); mActionRedo->setEnabled( false ); // View menu new KAction(i18n("Modify View..."), "configure", 0, mViewManager, SLOT(modifyView()), mACollection, "view_modify"); new KAction(i18n("Add View..."), "window_new", 0, mViewManager, SLOT(addView()), mACollection, "view_add"); mActionDeleteView = new KAction(i18n("Delete View..."), "delete", 0, mViewManager, SLOT(deleteView()), mACollection, "view_delete"); new KAction(i18n("Refresh View"), "reload", 0, mViewManager, SLOT(refresh()), mACollection, "view_refresh"); // Only enable LDAP lookup if we can handle the protocol if( KProtocolInfo::isKnownProtocol( KURL("ldap://localhost") )) { // LDAP button on toolbar new KAction(i18n("&Lookup addresses in directory"), "ldap_lookup", 0, mWidget, SLOT(slotOpenLDAPDialog()), mACollection,"ldap_lookup"); } // Settings menu mActionJumpBar = new KToggleAction(i18n("Show Jump Bar"), "next", 0, this, SLOT(quickToolsAction()), mACollection, "options_show_jump_bar"); mActionQuickEdit = new KToggleAction(i18n("Show Quick Edit"), "edit", 0, this, SLOT(quickToolsAction()), mACollection, "options_show_quick_edit"); (void) new KAction(i18n("Edit &Filters"), "filter", 0, mWidget, SLOT(configureFilters()), mACollection, "options_edit_filters"); mActionSelectFilter = new KSelectAction(i18n("Select Filter"), "select_filter", 0, this, SLOT(slotFilterActivated(int)), mACollection, "select_filter"); connect(mActionSelectFilter, SIGNAL(activated(int)), SLOT(slotFilterActivated(int))); connect(this, SIGNAL(filterActivated(int)), mViewManager, SLOT(filterActivated(int))); connect(mViewManager, SIGNAL(setFilterNames(const QStringList&)), SLOT(setFilterNames(const QStringList&))); connect(mViewManager, SIGNAL(setCurrentFilterName(const QString&)), SLOT(setCurrentFilterName(const QString&))); connect(mViewManager, SIGNAL(setCurrentFilter(int index)), SLOT(setCurrentFilter(int index))); } void ActionManager::initReadWriteActions() { // Edit menu mActionCut = KStdAction::cut(mViewManager, SLOT(cut()), mACollection); mActionPaste = KStdAction::paste(mViewManager, SLOT(paste()), mACollection); clipboardDataChanged(); } void ActionManager::destroyReadWriteActions() { delete mActionCut; delete mActionPaste; } void ActionManager::updateEditMenu() { UndoStack *undo = UndoStack::instance(); RedoStack *redo = RedoStack::instance(); if (undo->isEmpty()) mActionUndo->setText( i18n( "Undo" ) ); else mActionUndo->setText( i18n( "Undo" ) + " " + undo->top()->name() ); mActionUndo->setEnabled( !undo->isEmpty() ); if (!redo->top()) mActionRedo->setText( i18n( "Redo" ) ); else mActionRedo->setText( i18n( "Redo" ) + " " + redo->top()->name() ); mActionRedo->setEnabled( !redo->isEmpty() ); } void ActionManager::addresseeSelected(bool selected) { if (mReadWrite) { mActionCut->setEnabled(selected); } mActionCopy->setEnabled(selected); mActionDelete->setEnabled(selected); mActionEditAddressee->setEnabled(selected); mActionMail->setEnabled(selected); } void ActionManager::modified(bool mod) { mActionSave->setEnabled(mod); } void ActionManager::initActionViewList() { // Create the view actions, and set the active view // Find the last active view QStringList viewNameList = mViewManager->viewNames(); KToggleAction *viewAction = 0; // Just incast there is no active view! if (mActiveViewName.isEmpty() || (viewNameList.contains(mActiveViewName) == 0)) mActiveViewName = *(viewNameList).at(0); // unplug the current ones mGUIClient->factory()->unplugActionList(mGUIClient, "view_loadedviews"); // delete the current ones mActionViewList.clear(); mActiveActionView = 0L; // Now find the active one, check the menu item, and raise it to the top QStringList::Iterator iter; QString viewName; for (iter = viewNameList.begin(); iter != viewNameList.end(); ++iter) { viewName = *iter; viewAction = new KToggleAction(viewName, QString::null, this, SLOT(selectViewAction()), mACollection, viewName.latin1()); if (mActiveViewName == viewName) { mViewManager->setActiveView(viewName); viewAction->setChecked(true); mActiveActionView = viewAction; } mActionViewList.append(viewAction); } // Now append all the actions to the menu. mGUIClient->factory()->plugActionList(mGUIClient, "view_loadedviews", mActionViewList); } void ActionManager::viewConfigChanged(const QString &newActive) { if (!newActive.isEmpty()) { mActiveViewName = newActive; } // we need to rebuild the actions initActionViewList(); // Only enable delete if there is more than one view mActionDeleteView->setEnabled(mViewManager->viewNames().size() > 1); } void ActionManager::selectViewAction() { // See if we can find the selected action KToggleAction *action = 0; QString activatedName = sender()->name(); QPtrListIterator<KAction> iter(mActionViewList); for (iter.toFirst(); iter.current(); ++iter) { action = dynamic_cast<KToggleAction*>(*iter); if (action->name() != activatedName) action->setChecked(false); else { mActiveActionView = action; mActiveActionView->setChecked(true); mActiveViewName = mActiveActionView->name(); // Last, tell the main widget to set the view. mViewManager->setActiveView(mActiveViewName); } } } void ActionManager::quickToolsAction() { mViewManager->setJumpButtonBarVisible(mActionJumpBar->isChecked()); mViewManager->setQuickEditVisible(mActionQuickEdit->isChecked()); } void ActionManager::setFilterNames(const QStringList& list) { QStringList items; items.append(i18n("None")); items+=list; mActionSelectFilter->setItems(items); } void ActionManager::slotFilterActivated(int index) { kdDebug() << "ActionManager::slotFilterActivated: Filter " << index << " activated." << endl; emit(filterActivated(index-1)); } void ActionManager::setCurrentFilterName(const QString& name) { QStringList items=mActionSelectFilter->items(); int index=items.findIndex(name); if(index!=-1) { setCurrentFilter(index); } } void ActionManager::setCurrentFilter(int index) { mActionSelectFilter->setCurrentItem(index); } #include "actionmanager.moc" <commit_msg>Corrected typographical errors<commit_after>/* This file is part of KAddressBook. Copyright (c) 2002 Mike Pilone <mpilone@slac.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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., 675 Mass Ave, Cambridge, MA 02139, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <qapplication.h> #include <qclipboard.h> #include <kapplication.h> #include <kconfig.h> #include <kdebug.h> #include <klocale.h> #include <kprotocolinfo.h> #include <kxmlguiclient.h> #include <kxmlguifactory.h> #include "actionmanager.h" #include "kaddressbook.h" #include "viewmanager.h" #include "undo.h" ActionManager::ActionManager(KXMLGUIClient *client, KAddressBook *widget, bool readWrite, QObject *parent) : QObject(parent) { mGUIClient = client; mACollection = mGUIClient->actionCollection(); mWidget = widget; connect( mWidget, SIGNAL( addresseeSelected( bool ) ), SLOT( addresseeSelected( bool ) ) ); connect( mWidget, SIGNAL( modified( bool ) ), SLOT( modified( bool ) ) ); mViewManager = mWidget->viewManager(); connect( mViewManager, SIGNAL( viewConfigChanged(const QString &) ), SLOT( viewConfigChanged(const QString &) ) ); connect( QApplication::clipboard(), SIGNAL( dataChanged() ), SLOT( clipboardDataChanged() ) ); mReadWrite = readWrite; initReadOnlyActions(); if (mReadWrite) initReadWriteActions(); // Read our own config KConfig *config = kapp->config(); config->setGroup("Views"); mActiveViewName = config->readEntry("Active"); config->setGroup("MainWindow"); mActionJumpBar->setChecked(config->readBoolEntry("JumpBar", false)); mActionQuickEdit->setChecked(config->readBoolEntry("QuickEdit", false)); // Set the defaults addresseeSelected(false); modified(false); quickToolsAction(); mActionViewList.setAutoDelete(true); // Connect to the signals from the undo/redo stacks so we can update the // edit menu connect(UndoStack::instance(), SIGNAL(changed()), SLOT(updateEditMenu())); connect(RedoStack::instance(), SIGNAL(changed()), SLOT(updateEditMenu())); } ActionManager::~ActionManager() { // Write our own config KConfig *config = kapp->config(); config->setGroup("Views"); config->writeEntry("Active", mActiveViewName); config->setGroup("MainWindow"); config->writeEntry("JumpBar", mActionJumpBar->isChecked()); config->writeEntry("QuickEdit", mActionQuickEdit->isChecked()); } void ActionManager::setReadWrite(bool rw) { if (rw == mReadWrite) return; mReadWrite = rw; if (mReadWrite) initReadWriteActions(); else destroyReadWriteActions(); } void ActionManager::clipboardDataChanged() { if (mReadWrite) mActionPaste->setEnabled( !QApplication::clipboard()->text().isEmpty() ); } void ActionManager::initReadOnlyActions() { // File menu mActionSave = new KAction(i18n("&Save"), "filesave", CTRL+Key_S, mWidget, SLOT(save()), mACollection,"file_sync"); new KAction(i18n("&New Contact"), "filenew", CTRL+Key_N, mWidget, SLOT(newAddressee()),mACollection,"file_new_contact"); new KAction(i18n("&Distribution List..."), 0, mWidget, SLOT(slotDistributionList()), mACollection, "file_distribution_list"); mActionMail = KStdAction::mail(mViewManager, SLOT(sendMail()), mACollection); mActionEditAddressee = new KAction(i18n("&Edit Contact..."), "edit", 0, mWidget, SLOT(editAddressee()), mACollection, "file_properties"); KStdAction::print(mWidget, SLOT(print()), mACollection); new KAction(i18n("Import &KDE 2 Address Book..."), 0, mWidget, SLOT(importKDE2()), mACollection, "file_import_kde2"); new KAction(i18n("Import vCard2.1..."), 0, mWidget, SLOT(importVCard21()), mACollection, "file_import_vcard21"); new KAction(i18n("Import vCard3.0..."), 0, mWidget, SLOT(importVCard30()), mACollection, "file_import_vcard30"); new KAction(i18n("&Import List..."), 0, mWidget, SLOT(importCSV()), mACollection, "file_import_csv"); new KAction(i18n("&Export List..."), 0, mWidget, SLOT(exportCSV()), mACollection, "file_export_csv"); new KAction(i18n("&Export vCard3.0..."), 0, mWidget, SLOT(exportVCard30()), mACollection, "file_export_vcard30"); // Edit menu mActionCopy = KStdAction::copy(mViewManager, SLOT(copy()), mACollection); KStdAction::selectAll(mViewManager, SLOT(setSelected()), mACollection); mActionDelete = new KAction(i18n("&Delete Contact"), "editdelete", Key_Delete, mViewManager, SLOT(deleteAddressee()), mACollection, "edit_delete"); mActionUndo = KStdAction::undo(mWidget, SLOT(undo()), mACollection); mActionUndo->setEnabled(false); mActionRedo = KStdAction::redo(mWidget, SLOT(redo()), mACollection); mActionRedo->setEnabled( false ); // View menu new KAction(i18n("Modify View..."), "configure", 0, mViewManager, SLOT(modifyView()), mACollection, "view_modify"); new KAction(i18n("Add View..."), "window_new", 0, mViewManager, SLOT(addView()), mACollection, "view_add"); mActionDeleteView = new KAction(i18n("Delete View..."), "delete", 0, mViewManager, SLOT(deleteView()), mACollection, "view_delete"); new KAction(i18n("Refresh View"), "reload", 0, mViewManager, SLOT(refresh()), mACollection, "view_refresh"); // Only enable LDAP lookup if we can handle the protocol if( KProtocolInfo::isKnownProtocol( KURL("ldap://localhost") )) { // LDAP button on toolbar new KAction(i18n("&Lookup addresses in directory"), "ldap_lookup", 0, mWidget, SLOT(slotOpenLDAPDialog()), mACollection,"ldap_lookup"); } // Settings menu mActionJumpBar = new KToggleAction(i18n("Show Jump Bar"), "next", 0, this, SLOT(quickToolsAction()), mACollection, "options_show_jump_bar"); mActionQuickEdit = new KToggleAction(i18n("Show Quick Edit"), "edit", 0, this, SLOT(quickToolsAction()), mACollection, "options_show_quick_edit"); (void) new KAction(i18n("Edit &Filters"), "filter", 0, mWidget, SLOT(configureFilters()), mACollection, "options_edit_filters"); mActionSelectFilter = new KSelectAction(i18n("Select Filter"), "select_filter", 0, this, SLOT(slotFilterActivated(int)), mACollection, "select_filter"); connect(mActionSelectFilter, SIGNAL(activated(int)), SLOT(slotFilterActivated(int))); connect(this, SIGNAL(filterActivated(int)), mViewManager, SLOT(filterActivated(int))); connect(mViewManager, SIGNAL(setFilterNames(const QStringList&)), SLOT(setFilterNames(const QStringList&))); connect(mViewManager, SIGNAL(setCurrentFilterName(const QString&)), SLOT(setCurrentFilterName(const QString&))); connect(mViewManager, SIGNAL(setCurrentFilter(int index)), SLOT(setCurrentFilter(int index))); } void ActionManager::initReadWriteActions() { // Edit menu mActionCut = KStdAction::cut(mViewManager, SLOT(cut()), mACollection); mActionPaste = KStdAction::paste(mViewManager, SLOT(paste()), mACollection); clipboardDataChanged(); } void ActionManager::destroyReadWriteActions() { delete mActionCut; delete mActionPaste; } void ActionManager::updateEditMenu() { UndoStack *undo = UndoStack::instance(); RedoStack *redo = RedoStack::instance(); if (undo->isEmpty()) mActionUndo->setText( i18n( "Undo" ) ); else mActionUndo->setText( i18n( "Undo" ) + " " + undo->top()->name() ); mActionUndo->setEnabled( !undo->isEmpty() ); if (!redo->top()) mActionRedo->setText( i18n( "Redo" ) ); else mActionRedo->setText( i18n( "Redo" ) + " " + redo->top()->name() ); mActionRedo->setEnabled( !redo->isEmpty() ); } void ActionManager::addresseeSelected(bool selected) { if (mReadWrite) { mActionCut->setEnabled(selected); } mActionCopy->setEnabled(selected); mActionDelete->setEnabled(selected); mActionEditAddressee->setEnabled(selected); mActionMail->setEnabled(selected); } void ActionManager::modified(bool mod) { mActionSave->setEnabled(mod); } void ActionManager::initActionViewList() { // Create the view actions, and set the active view // Find the last active view QStringList viewNameList = mViewManager->viewNames(); KToggleAction *viewAction = 0; // Just incast there is no active view! if (mActiveViewName.isEmpty() || (viewNameList.contains(mActiveViewName) == 0)) mActiveViewName = *(viewNameList).at(0); // unplug the current ones mGUIClient->factory()->unplugActionList(mGUIClient, "view_loadedviews"); // delete the current ones mActionViewList.clear(); mActiveActionView = 0L; // Now find the active one, check the menu item, and raise it to the top QStringList::Iterator iter; QString viewName; for (iter = viewNameList.begin(); iter != viewNameList.end(); ++iter) { viewName = *iter; viewAction = new KToggleAction(viewName, QString::null, this, SLOT(selectViewAction()), mACollection, viewName.latin1()); if (mActiveViewName == viewName) { mViewManager->setActiveView(viewName); viewAction->setChecked(true); mActiveActionView = viewAction; } mActionViewList.append(viewAction); } // Now append all the actions to the menu. mGUIClient->factory()->plugActionList(mGUIClient, "view_loadedviews", mActionViewList); } void ActionManager::viewConfigChanged(const QString &newActive) { if (!newActive.isEmpty()) { mActiveViewName = newActive; } // we need to rebuild the actions initActionViewList(); // Only enable delete if there is more than one view mActionDeleteView->setEnabled(mViewManager->viewNames().size() > 1); } void ActionManager::selectViewAction() { // See if we can find the selected action KToggleAction *action = 0; QString activatedName = sender()->name(); QPtrListIterator<KAction> iter(mActionViewList); for (iter.toFirst(); iter.current(); ++iter) { action = dynamic_cast<KToggleAction*>(*iter); if (action->name() != activatedName) action->setChecked(false); else { mActiveActionView = action; mActiveActionView->setChecked(true); mActiveViewName = mActiveActionView->name(); // Last, tell the main widget to set the view. mViewManager->setActiveView(mActiveViewName); } } } void ActionManager::quickToolsAction() { mViewManager->setJumpButtonBarVisible(mActionJumpBar->isChecked()); mViewManager->setQuickEditVisible(mActionQuickEdit->isChecked()); } void ActionManager::setFilterNames(const QStringList& list) { QStringList items; items.append(i18n("None")); items+=list; mActionSelectFilter->setItems(items); } void ActionManager::slotFilterActivated(int index) { kdDebug() << "ActionManager::slotFilterActivated: Filter " << index << " activated." << endl; emit(filterActivated(index-1)); } void ActionManager::setCurrentFilterName(const QString& name) { QStringList items=mActionSelectFilter->items(); int index=items.findIndex(name); if(index!=-1) { setCurrentFilter(index); } } void ActionManager::setCurrentFilter(int index) { mActionSelectFilter->setCurrentItem(index); } #include "actionmanager.moc" <|endoftext|>
<commit_before>/// /// @file iterator.cpp /// /// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primesieve/config.hpp> #include <primesieve/pmath.hpp> #include <primesieve/PrimeFinder.hpp> #include <primesieve.hpp> #include <algorithm> #include <cmath> #include <string> #include <vector> namespace primesieve { iterator::iterator(uint64_t start, uint64_t stop_hint) { skipto(start, stop_hint); } void iterator::clear() { skipto(0); } void iterator::skipto(uint64_t start, uint64_t stop_hint) { if (start_ > get_max_stop()) throw primesieve_error("start must be <= " + PrimeFinder::getMaxStopString()); start_ = start; stop_ = start; stop_hint_ = stop_hint; i_ = 0; last_idx_ = 0; tiny_cache_size_ = 1 << 11; primes_.clear(); } uint64_t add_overflow_safe(uint64_t a, uint64_t b) { uint64_t max_stop = get_max_stop(); return (a < max_stop - b) ? a + b : max_stop; } uint64_t subtract_underflow_safe(uint64_t a, uint64_t b) { return (a > b) ? a - b : 0; } void iterator::generate_next_primes() { bool first = primes_.empty(); primes_.clear(); while (primes_.empty()) { if (!first) start_ = add_overflow_safe(stop_, 1); first = false; stop_ = add_overflow_safe(start_, get_interval_size(start_)); if (start_ <= stop_hint_ && stop_ >= stop_hint_) stop_ = add_overflow_safe(stop_hint_, max_prime_gap(stop_hint_)); primesieve::generate_primes(start_, stop_, &primes_); if (primes_.empty() && stop_ >= get_max_stop()) throw primesieve_error("next_prime() > " + PrimeFinder::getMaxStopString()); } last_idx_ = primes_.size() - 1; i_ = 0; } void iterator::generate_previous_primes() { bool first = primes_.empty(); primes_.clear(); while (primes_.empty()) { if (!first) stop_ = subtract_underflow_safe(start_, 1); first = false; start_ = subtract_underflow_safe(stop_, get_interval_size(stop_)); if (start_ <= stop_hint_ && stop_ >= stop_hint_) start_ = subtract_underflow_safe(stop_hint_, max_prime_gap(stop_hint_)); primesieve::generate_primes(start_, stop_, &primes_); if (primes_.empty() && start_ < 2) throw primesieve_error("previous_prime(): smallest prime is 2"); } last_idx_ = primes_.size() - 1; i_ = last_idx_; } /// Calculate an interval size that ensures a good load balance. /// @param n Start or stop number. /// uint64_t iterator::get_interval_size(uint64_t n) { n = (n > 10) ? n : 10; uint64_t cache_size = config::ITERATOR_CACHE_SMALL; if (tiny_cache_size_ < cache_size) { cache_size = tiny_cache_size_; tiny_cache_size_ *= 2; } double x = static_cast<double>(n); double sqrtx = std::sqrt(x); uint64_t sqrtx_primes = static_cast<uint64_t>(sqrtx / (std::log(sqrtx) - 1)); uint64_t cache_primes = cache_size / sizeof(uint64_t); uint64_t cache_max_primes = config::ITERATOR_CACHE_MAX / sizeof(uint64_t); uint64_t primes = std::min(std::max(cache_primes, sqrtx_primes), cache_max_primes); return static_cast<uint64_t>(primes * std::log(x)); } } // end namespace <commit_msg>Simplify interface<commit_after>/// /// @file iterator.cpp /// /// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primesieve/config.hpp> #include <primesieve/pmath.hpp> #include <primesieve/PrimeFinder.hpp> #include <primesieve.hpp> #include <algorithm> #include <cmath> #include <string> #include <vector> namespace primesieve { iterator::iterator(uint64_t start, uint64_t stop_hint) { skipto(start, stop_hint); } void iterator::skipto(uint64_t start, uint64_t stop_hint) { if (start_ > get_max_stop()) throw primesieve_error("start must be <= " + PrimeFinder::getMaxStopString()); start_ = start; stop_ = start; stop_hint_ = stop_hint; i_ = 0; last_idx_ = 0; tiny_cache_size_ = 1 << 11; primes_.clear(); } uint64_t add_overflow_safe(uint64_t a, uint64_t b) { uint64_t max_stop = get_max_stop(); return (a < max_stop - b) ? a + b : max_stop; } uint64_t subtract_underflow_safe(uint64_t a, uint64_t b) { return (a > b) ? a - b : 0; } void iterator::generate_next_primes() { bool first = primes_.empty(); primes_.clear(); while (primes_.empty()) { if (!first) start_ = add_overflow_safe(stop_, 1); first = false; stop_ = add_overflow_safe(start_, get_interval_size(start_)); if (start_ <= stop_hint_ && stop_ >= stop_hint_) stop_ = add_overflow_safe(stop_hint_, max_prime_gap(stop_hint_)); primesieve::generate_primes(start_, stop_, &primes_); if (primes_.empty() && stop_ >= get_max_stop()) throw primesieve_error("next_prime() > " + PrimeFinder::getMaxStopString()); } last_idx_ = primes_.size() - 1; i_ = 0; } void iterator::generate_previous_primes() { bool first = primes_.empty(); primes_.clear(); while (primes_.empty()) { if (!first) stop_ = subtract_underflow_safe(start_, 1); first = false; start_ = subtract_underflow_safe(stop_, get_interval_size(stop_)); if (start_ <= stop_hint_ && stop_ >= stop_hint_) start_ = subtract_underflow_safe(stop_hint_, max_prime_gap(stop_hint_)); primesieve::generate_primes(start_, stop_, &primes_); if (primes_.empty() && start_ < 2) throw primesieve_error("previous_prime(): smallest prime is 2"); } last_idx_ = primes_.size() - 1; i_ = last_idx_; } /// Calculate an interval size that ensures a good load balance. /// @param n Start or stop number. /// uint64_t iterator::get_interval_size(uint64_t n) { n = (n > 10) ? n : 10; uint64_t cache_size = config::ITERATOR_CACHE_SMALL; if (tiny_cache_size_ < cache_size) { cache_size = tiny_cache_size_; tiny_cache_size_ *= 2; } double x = static_cast<double>(n); double sqrtx = std::sqrt(x); uint64_t sqrtx_primes = static_cast<uint64_t>(sqrtx / (std::log(sqrtx) - 1)); uint64_t cache_primes = cache_size / sizeof(uint64_t); uint64_t cache_max_primes = config::ITERATOR_CACHE_MAX / sizeof(uint64_t); uint64_t primes = std::min(std::max(cache_primes, sqrtx_primes), cache_max_primes); return static_cast<uint64_t>(primes * std::log(x)); } } // end namespace <|endoftext|>
<commit_before>/************************************************************************* * * REALM CONFIDENTIAL * __________________ * * [2011] - [2015] Realm Inc * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Realm Incorporated and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Realm Incorporated * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Realm Incorporated. * **************************************************************************/ #pragma once #ifndef REALM_UTIL_OPTIONAL_HPP #define REALM_UTIL_OPTIONAL_HPP #include <realm/util/features.h> #include <stdexcept> // std::logic_error #include <functional> // std::less namespace realm { namespace util { template <class T> class Optional; // some() should be the equivalent of the proposed C++17 `make_optional`. template <class T, class... Args> Optional<T> some(Args&&...); template <class T> struct Some; // Note: Should conform with the future std::nullopt_t and std::in_place_t. static REALM_CONSTEXPR struct None { REALM_CONSTEXPR explicit None(int) {} } none { 0 }; static REALM_CONSTEXPR struct InPlace { REALM_CONSTEXPR InPlace() {} } in_place; // Note: Should conform with the future std::bad_optional_access. struct BadOptionalAccess : std::logic_error { explicit BadOptionalAccess(const std::string& what_arg) : std::logic_error(what_arg) {} explicit BadOptionalAccess(const char* what_arg) : std::logic_error(what_arg) {} }; // Note: Should conform with the future std::optional. template <class T> class Optional { public: using value_type = T; REALM_CONSTEXPR Optional(); REALM_CONSTEXPR Optional(None); Optional(Optional<T>&& other); Optional(const Optional<T>& other); /*REALM_CONSTEXPR*/ Optional(T&& value); // FIXME: Can be constexpr with C++14 /*REALM_CONSTEXPR*/ Optional(const T& value); // FIXME: Can be constexpr with C++14 template <class... Args> /*REALM_CONSTEXPR*/ Optional(InPlace tag, Args&&...); // FIXME: Can be constexpr with C++14 // FIXME: std::optional specifies an std::initializer_list constructor overload as well. ~Optional(); Optional<T>& operator=(None); Optional<T>& operator=(Optional<T>&& other); Optional<T>& operator=(const Optional<T>& other); template <class U> Optional<T>& operator=(U&& value); explicit REALM_CONSTEXPR operator bool() const; REALM_CONSTEXPR const T& value() const; // Throws T& value(); // Throws, FIXME: Can be constexpr with C++14 REALM_CONSTEXPR const T& operator*() const; // Throws T& operator*(); // Throws, FIXME: Can be constexpr with C++14 REALM_CONSTEXPR const T* operator->() const; // Throws T* operator->(); // Throws, FIXME: Can be constexpr with C++14 template <class U> REALM_CONSTEXPR T value_or(U&& value) const&; template <class U> T value_or(U&& value) &&; void swap(Optional<T>& other); // FIXME: Add noexcept() clause template <class... Args> void emplace(Args&&...); // FIXME: std::optional specifies an std::initializer_list overload for `emplace` as well. private: using Storage = typename std::aligned_storage<sizeof(T), alignof(T)>::type; Storage m_storage; bool m_engaged; T* ptr() { return reinterpret_cast<T*>(&m_storage); } const T* ptr() const { return reinterpret_cast<const T*>(&m_storage); } REALM_CONSTEXPR bool is_engaged() const { return m_engaged; } void set_engaged(bool b) { m_engaged = b; } void clear(); }; /// An Optional<void> is functionally equivalent to a bool. /// Note: C++17 does not (yet) specify this specialization, but it is convenient /// as a "safer bool", especially in the presence of `fmap`. /// Disabled for compliance with std::optional. // template <> // class Optional<void> { // public: // Optional() {} // Optional(None) {} // Optional(Optional<void>&&) = default; // Optional(const Optional<void>&) = default; // explicit operator bool() const { return m_engaged; } // private: // bool m_engaged = false; // friend struct Some<void>; // }; /// An Optional<T&> is a non-owning nullable pointer that throws on dereference. template <class T> class Optional<T&> { public: using value_type = T&; using target_type = typename std::decay<T>::type; REALM_CONSTEXPR Optional() {} REALM_CONSTEXPR Optional(None) : Optional() {} Optional(const Optional<T&>& other) = default; template <class U> Optional(const Optional<U&>& other) : m_ptr(other.m_ptr) {} template <class U> Optional(std::reference_wrapper<U> ref) : m_ptr(&ref.get()) {} REALM_CONSTEXPR Optional(T& value) : m_ptr(&value) {} Optional(T&& value) = delete; // Catches accidental references to rvalue temporaries. Optional<T&>& operator=(None) { m_ptr = nullptr; return *this; } Optional<T&>& operator=(const Optional<T&>& other) { m_ptr = other.m_ptr; return *this; } template <class U> Optional<T&>& operator=(std::reference_wrapper<U> ref) { m_ptr = &ref.get(); return *this; } explicit REALM_CONSTEXPR operator bool() const { return m_ptr; } REALM_CONSTEXPR const target_type& value() const; // Throws target_type& value(); // Throws REALM_CONSTEXPR const target_type& operator*() const { return value(); } target_type& operator*() { return value(); } REALM_CONSTEXPR const target_type* operator->() const { return &value(); } target_type* operator->() { return &value(); } void swap(Optional<T&> other); // FIXME: Add noexcept() clause private: T* m_ptr = nullptr; template <class U> friend class Optional; }; /// Implementation: template <class T> struct Some { template <class... Args> static Optional<T> some(Args&&... args) { return Optional<T>{std::forward<Args>(args)...}; } }; /// Disabled for compliance with std::optional. // template <> // struct Some<void> { // static Optional<void> some() // { // Optional<void> opt; // opt.m_engaged = true; // return opt; // } // }; template <class T, class... Args> Optional<T> some(Args&&... args) { return Some<T>::some(std::forward<Args>(args)...); } template <class T> REALM_CONSTEXPR Optional<T>::Optional(): m_engaged(false) { } template <class T> REALM_CONSTEXPR Optional<T>::Optional(None): m_engaged(false) { } template <class T> Optional<T>::Optional(Optional<T>&& other): m_engaged(other.m_engaged) { if (m_engaged) { new(ptr()) T(std::move(*other.ptr())); } } template <class T> Optional<T>::Optional(const Optional<T>& other): m_engaged(other.m_engaged) { if (m_engaged) { new(ptr()) T(*other.ptr()); } } template <class T> Optional<T>::Optional(T&& value): m_engaged(true) { new(ptr()) T(std::move(value)); } template <class T> Optional<T>::Optional(const T& value): m_engaged(true) { new(ptr()) T(value); } template <class T> template <class... Args> Optional<T>::Optional(InPlace, Args&&... args): m_engaged(true) { new(ptr()) T(std::forward<Args>(args)...); } template <class T> Optional<T>::~Optional() { if (m_engaged) { ptr()->~T(); } } template <class T> void Optional<T>::clear() { if (m_engaged) { ptr()->~T(); m_engaged = false; } } template <class T> Optional<T>& Optional<T>::operator=(None) { clear(); return *this; } template <class T> Optional<T>& Optional<T>::operator=(Optional<T>&& other) { if (m_engaged) { if (other.m_engaged) { *ptr() = std::move(*other.ptr()); } else { clear(); } } else { if (other.m_engaged) { new(ptr()) T(std::move(*other.ptr())); } } return *this; } template <class T> Optional<T>& Optional<T>::operator=(const Optional<T>& other) { if (m_engaged) { if (other.m_engaged) { *ptr() = *other.ptr(); } else { clear(); } } else { if (other.m_engaged) { new(ptr()) T(*other.ptr()); } } return *this; } template <class T> template <class U> Optional<T>& Optional<T>::operator=(U&& value) { if (m_engaged) { *ptr() = std::forward<U>(value); } else { new(ptr()) T(std::forward<U>(value)); m_engaged = true; } return *this; } template <class T> REALM_CONSTEXPR Optional<T>::operator bool() const { return m_engaged; } template <class T> REALM_CONSTEXPR const T& Optional<T>::value() const { return m_engaged ? *ptr() : throw BadOptionalAccess{"bad optional access"}; } template <class T> T& Optional<T>::value() { if (!m_engaged) { throw BadOptionalAccess{"bad optional access"}; } return *ptr(); } template <class T> REALM_CONSTEXPR const typename Optional<T&>::target_type& Optional<T&>::value() const { return m_ptr ? *m_ptr : throw BadOptionalAccess{"bad optional access"}; } template <class T> typename Optional<T&>::target_type& Optional<T&>::value() { if (!m_ptr) { throw BadOptionalAccess{"bad optional access"}; } return *m_ptr; } template <class T> REALM_CONSTEXPR const T& Optional<T>::operator*() const { // Note: This differs from std::optional, which doesn't throw. return value(); } template <class T> T& Optional<T>::operator*() { // Note: This differs from std::optional, which doesn't throw. return value(); } template <class T> REALM_CONSTEXPR const T* Optional<T>::operator->() const { // Note: This differs from std::optional, which doesn't throw. return &value(); } template <class T> T* Optional<T>::operator->() { // Note: This differs from std::optional, which doesn't throw. return &value(); } template <class T> template <class U> REALM_CONSTEXPR T Optional<T>::value_or(U&& otherwise) const& { return m_engaged ? T{*ptr()} : T{std::forward<U>(otherwise)}; } template <class T> template <class U> T Optional<T>::value_or(U&& otherwise) && { if (is_engaged()) { return T(std::move(*ptr())); } else { return T(std::forward<U>(otherwise)); } } template <class T> void Optional<T>::swap(Optional<T>& other) { // FIXME: This might be optimizable. Optional<T> tmp = std::move(other); other = std::move(*this); *this = std::move(tmp); } template <class T> template <class... Args> void Optional<T>::emplace(Args&&... args) { clear(); new(ptr()) T(std::forward<Args>(args)...); m_engaged = true; } template <class T> REALM_CONSTEXPR Optional<typename std::decay<T>::type> make_optional(T&& value) { using Type = typename std::decay<T>::type; return some<Type>(std::forward<T>(value)); } template <class T> bool operator==(const Optional<T>& lhs, const Optional<T>& rhs) { if (!lhs && !rhs) { return true; } if (lhs && rhs) { return *lhs == *rhs; } return false; } template <class T> bool operator<(const Optional<T>& lhs, const Optional<T>& rhs) { if (!rhs) { return false; } if (!lhs) { return true; } return std::less<T>{}(*lhs, *rhs); } template <class T> bool operator==(const Optional<T>& lhs, None) { return !bool(lhs); } template <class T> bool operator<(const Optional<T>& lhs, None) { static_cast<void>(lhs); return false; } template <class T> bool operator==(None, const Optional<T>& rhs) { return !bool(rhs); } template <class T> bool operator<(None, const Optional<T>& rhs) { return bool(rhs); } template <class T> bool operator==(const Optional<T>& lhs, const T& rhs) { return lhs ? *lhs == rhs : false; } template <class T> bool operator<(const Optional<T>& lhs, const T& rhs) { return lhs ? std::less<T>{}(*lhs, rhs) : true; } template <class T> bool operator==(const T& lhs, const Optional<T>& rhs) { return rhs ? lhs == *rhs : false; } template <class T> bool operator<(const T& lhs, const Optional<T>& rhs) { return rhs ? std::less<T>{}(lhs, *rhs) : false; } template <class T, class F> auto operator>>(Optional<T> lhs, F&& rhs) -> decltype(fmap(lhs, std::forward<F>(rhs))) { return fmap(lhs, std::forward<F>(rhs)); } } // namespace util using util::none; } // namespace realm #endif // REALM_UTIL_OPTIONAL_HPP <commit_msg>Use an alternate approach to suppress the warning that works in both Clang and GCC.<commit_after>/************************************************************************* * * REALM CONFIDENTIAL * __________________ * * [2011] - [2015] Realm Inc * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Realm Incorporated and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Realm Incorporated * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Realm Incorporated. * **************************************************************************/ #pragma once #ifndef REALM_UTIL_OPTIONAL_HPP #define REALM_UTIL_OPTIONAL_HPP #include <realm/util/features.h> #include <stdexcept> // std::logic_error #include <functional> // std::less namespace realm { namespace util { template <class T> class Optional; // some() should be the equivalent of the proposed C++17 `make_optional`. template <class T, class... Args> Optional<T> some(Args&&...); template <class T> struct Some; // Note: Should conform with the future std::nullopt_t and std::in_place_t. static REALM_CONSTEXPR struct None { REALM_CONSTEXPR explicit None(int) {} } none { 0 }; static REALM_CONSTEXPR struct InPlace { REALM_CONSTEXPR InPlace() {} } in_place; // Note: Should conform with the future std::bad_optional_access. struct BadOptionalAccess : std::logic_error { explicit BadOptionalAccess(const std::string& what_arg) : std::logic_error(what_arg) {} explicit BadOptionalAccess(const char* what_arg) : std::logic_error(what_arg) {} }; // Note: Should conform with the future std::optional. template <class T> class Optional { public: using value_type = T; REALM_CONSTEXPR Optional(); REALM_CONSTEXPR Optional(None); Optional(Optional<T>&& other); Optional(const Optional<T>& other); /*REALM_CONSTEXPR*/ Optional(T&& value); // FIXME: Can be constexpr with C++14 /*REALM_CONSTEXPR*/ Optional(const T& value); // FIXME: Can be constexpr with C++14 template <class... Args> /*REALM_CONSTEXPR*/ Optional(InPlace tag, Args&&...); // FIXME: Can be constexpr with C++14 // FIXME: std::optional specifies an std::initializer_list constructor overload as well. ~Optional(); Optional<T>& operator=(None); Optional<T>& operator=(Optional<T>&& other); Optional<T>& operator=(const Optional<T>& other); template <class U> Optional<T>& operator=(U&& value); explicit REALM_CONSTEXPR operator bool() const; REALM_CONSTEXPR const T& value() const; // Throws T& value(); // Throws, FIXME: Can be constexpr with C++14 REALM_CONSTEXPR const T& operator*() const; // Throws T& operator*(); // Throws, FIXME: Can be constexpr with C++14 REALM_CONSTEXPR const T* operator->() const; // Throws T* operator->(); // Throws, FIXME: Can be constexpr with C++14 template <class U> REALM_CONSTEXPR T value_or(U&& value) const&; template <class U> T value_or(U&& value) &&; void swap(Optional<T>& other); // FIXME: Add noexcept() clause template <class... Args> void emplace(Args&&...); // FIXME: std::optional specifies an std::initializer_list overload for `emplace` as well. private: using Storage = typename std::aligned_storage<sizeof(T), alignof(T)>::type; Storage m_storage; bool m_engaged; T* ptr() { return reinterpret_cast<T*>(&m_storage); } const T* ptr() const { return reinterpret_cast<const T*>(&m_storage); } REALM_CONSTEXPR bool is_engaged() const { return m_engaged; } void set_engaged(bool b) { m_engaged = b; } void clear(); }; /// An Optional<void> is functionally equivalent to a bool. /// Note: C++17 does not (yet) specify this specialization, but it is convenient /// as a "safer bool", especially in the presence of `fmap`. /// Disabled for compliance with std::optional. // template <> // class Optional<void> { // public: // Optional() {} // Optional(None) {} // Optional(Optional<void>&&) = default; // Optional(const Optional<void>&) = default; // explicit operator bool() const { return m_engaged; } // private: // bool m_engaged = false; // friend struct Some<void>; // }; /// An Optional<T&> is a non-owning nullable pointer that throws on dereference. template <class T> class Optional<T&> { public: using value_type = T&; using target_type = typename std::decay<T>::type; REALM_CONSTEXPR Optional() {} REALM_CONSTEXPR Optional(None) : Optional() {} Optional(const Optional<T&>& other) = default; template <class U> Optional(const Optional<U&>& other) : m_ptr(other.m_ptr) {} template <class U> Optional(std::reference_wrapper<U> ref) : m_ptr(&ref.get()) {} REALM_CONSTEXPR Optional(T& value) : m_ptr(&value) {} Optional(T&& value) = delete; // Catches accidental references to rvalue temporaries. Optional<T&>& operator=(None) { m_ptr = nullptr; return *this; } Optional<T&>& operator=(const Optional<T&>& other) { m_ptr = other.m_ptr; return *this; } template <class U> Optional<T&>& operator=(std::reference_wrapper<U> ref) { m_ptr = &ref.get(); return *this; } explicit REALM_CONSTEXPR operator bool() const { return m_ptr; } REALM_CONSTEXPR const target_type& value() const; // Throws target_type& value(); // Throws REALM_CONSTEXPR const target_type& operator*() const { return value(); } target_type& operator*() { return value(); } REALM_CONSTEXPR const target_type* operator->() const { return &value(); } target_type* operator->() { return &value(); } void swap(Optional<T&> other); // FIXME: Add noexcept() clause private: T* m_ptr = nullptr; template <class U> friend class Optional; }; /// Implementation: template <class T> struct Some { template <class... Args> static Optional<T> some(Args&&... args) { return Optional<T>{std::forward<Args>(args)...}; } }; /// Disabled for compliance with std::optional. // template <> // struct Some<void> { // static Optional<void> some() // { // Optional<void> opt; // opt.m_engaged = true; // return opt; // } // }; template <class T, class... Args> Optional<T> some(Args&&... args) { return Some<T>::some(std::forward<Args>(args)...); } template <class T> REALM_CONSTEXPR Optional<T>::Optional(): m_engaged(false) { } template <class T> REALM_CONSTEXPR Optional<T>::Optional(None): m_engaged(false) { } template <class T> Optional<T>::Optional(Optional<T>&& other): m_engaged(other.m_engaged) { if (m_engaged) { new(ptr()) T(std::move(*other.ptr())); } } template <class T> Optional<T>::Optional(const Optional<T>& other): m_engaged(other.m_engaged) { if (m_engaged) { new(ptr()) T(*other.ptr()); } } template <class T> Optional<T>::Optional(T&& value): m_engaged(true) { new(ptr()) T(std::move(value)); } template <class T> Optional<T>::Optional(const T& value): m_engaged(true) { new(ptr()) T(value); } template <class T> template <class... Args> Optional<T>::Optional(InPlace, Args&&... args): m_engaged(true) { new(ptr()) T(std::forward<Args>(args)...); } template <class T> Optional<T>::~Optional() { if (m_engaged) { ptr()->~T(); } } template <class T> void Optional<T>::clear() { if (m_engaged) { ptr()->~T(); m_engaged = false; } } template <class T> Optional<T>& Optional<T>::operator=(None) { clear(); return *this; } template <class T> Optional<T>& Optional<T>::operator=(Optional<T>&& other) { if (m_engaged) { if (other.m_engaged) { *ptr() = std::move(*other.ptr()); } else { clear(); } } else { if (other.m_engaged) { new(ptr()) T(std::move(*other.ptr())); } } return *this; } template <class T> Optional<T>& Optional<T>::operator=(const Optional<T>& other) { if (m_engaged) { if (other.m_engaged) { *ptr() = *other.ptr(); } else { clear(); } } else { if (other.m_engaged) { new(ptr()) T(*other.ptr()); } } return *this; } template <class T> template <class U> Optional<T>& Optional<T>::operator=(U&& value) { if (m_engaged) { *ptr() = std::forward<U>(value); } else { new(ptr()) T(std::forward<U>(value)); m_engaged = true; } return *this; } template <class T> REALM_CONSTEXPR Optional<T>::operator bool() const { return m_engaged; } template <class T> REALM_CONSTEXPR const T& Optional<T>::value() const { return m_engaged ? *ptr() : (throw BadOptionalAccess{"bad optional access"}, *ptr()); } template <class T> T& Optional<T>::value() { if (!m_engaged) { throw BadOptionalAccess{"bad optional access"}; } return *ptr(); } template <class T> REALM_CONSTEXPR const typename Optional<T&>::target_type& Optional<T&>::value() const { return m_ptr ? *m_ptr : (throw BadOptionalAccess{"bad optional access"}, *m_ptr); } template <class T> typename Optional<T&>::target_type& Optional<T&>::value() { if (!m_ptr) { throw BadOptionalAccess{"bad optional access"}; } return *m_ptr; } template <class T> REALM_CONSTEXPR const T& Optional<T>::operator*() const { // Note: This differs from std::optional, which doesn't throw. return value(); } template <class T> T& Optional<T>::operator*() { // Note: This differs from std::optional, which doesn't throw. return value(); } template <class T> REALM_CONSTEXPR const T* Optional<T>::operator->() const { // Note: This differs from std::optional, which doesn't throw. return &value(); } template <class T> T* Optional<T>::operator->() { // Note: This differs from std::optional, which doesn't throw. return &value(); } template <class T> template <class U> REALM_CONSTEXPR T Optional<T>::value_or(U&& otherwise) const& { return m_engaged ? T{*ptr()} : T{std::forward<U>(otherwise)}; } template <class T> template <class U> T Optional<T>::value_or(U&& otherwise) && { if (is_engaged()) { return T(std::move(*ptr())); } else { return T(std::forward<U>(otherwise)); } } template <class T> void Optional<T>::swap(Optional<T>& other) { // FIXME: This might be optimizable. Optional<T> tmp = std::move(other); other = std::move(*this); *this = std::move(tmp); } template <class T> template <class... Args> void Optional<T>::emplace(Args&&... args) { clear(); new(ptr()) T(std::forward<Args>(args)...); m_engaged = true; } template <class T> REALM_CONSTEXPR Optional<typename std::decay<T>::type> make_optional(T&& value) { using Type = typename std::decay<T>::type; return some<Type>(std::forward<T>(value)); } template <class T> bool operator==(const Optional<T>& lhs, const Optional<T>& rhs) { if (!lhs && !rhs) { return true; } if (lhs && rhs) { return *lhs == *rhs; } return false; } template <class T> bool operator<(const Optional<T>& lhs, const Optional<T>& rhs) { if (!rhs) { return false; } if (!lhs) { return true; } return std::less<T>{}(*lhs, *rhs); } template <class T> bool operator==(const Optional<T>& lhs, None) { return !bool(lhs); } template <class T> bool operator<(const Optional<T>& lhs, None) { static_cast<void>(lhs); return false; } template <class T> bool operator==(None, const Optional<T>& rhs) { return !bool(rhs); } template <class T> bool operator<(None, const Optional<T>& rhs) { return bool(rhs); } template <class T> bool operator==(const Optional<T>& lhs, const T& rhs) { return lhs ? *lhs == rhs : false; } template <class T> bool operator<(const Optional<T>& lhs, const T& rhs) { return lhs ? std::less<T>{}(*lhs, rhs) : true; } template <class T> bool operator==(const T& lhs, const Optional<T>& rhs) { return rhs ? lhs == *rhs : false; } template <class T> bool operator<(const T& lhs, const Optional<T>& rhs) { return rhs ? std::less<T>{}(lhs, *rhs) : false; } template <class T, class F> auto operator>>(Optional<T> lhs, F&& rhs) -> decltype(fmap(lhs, std::forward<F>(rhs))) { return fmap(lhs, std::forward<F>(rhs)); } } // namespace util using util::none; } // namespace realm #endif // REALM_UTIL_OPTIONAL_HPP <|endoftext|>