blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 122
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
320ff4b86c7a7febf7737bae1be9b0737864467b | 3f935da243e0839f15392d914d45f9c7037e1ddf | /DriverStation/main.cpp | 9bb5d42d925531b4588cef53e6522af150fe1f4a | [] | no_license | dgitz/DriverStation | d7fe1ab0c3f9ad9f6e8fa6acd9d309b4b65f6771 | 0110d75b465e75bf3c4514fb76006bf2aaecc1b0 | refs/heads/master | 2021-01-19T07:55:14.316051 | 2020-04-05T20:05:58 | 2020-04-05T20:05:58 | 83,970,385 | 0 | 1 | null | 2020-04-05T20:05:59 | 2017-03-05T13:04:31 | C++ | UTF-8 | C++ | false | false | 1,669 | cpp | #include "mainwindow.h"
#include <QApplication>
#include <QtCharts/QChartView>
#include <QDesktopWidget>
/*
class Player : public QCoreApplication
{
public:
Player(int argc, char **argv);
~Player();
private:
void onBusMessage(const QGst::MessagePtr & message);
private:
QGst::PipelinePtr pipeline1;
};
Player::Player(int argc, char **argv)
: VideoWidget(argc, argv)
{
QGst::init(&argc, &argv);
Need to implement this string as a string
gst-launch -v udpsrc port=8888 caps='application/x-rtp, media=(string)video, clock-rate=(int)90000, encoding-name=(string)H264' ! rtph264depay ! ffdec_h264 ! xvimagesink sync=false
const char *caps = "application/x-rtp, encoding-name=JPEG,payload=26";
QString pipe1Descr = QString("udpsrc port=5001 ! %1 ! rtpjpegdepay ! "
"jpegdec ! "
"autovideosink").arg(caps);
pipeline1 = QGst::Parse::launch(pipe1Descr).dynamicCast<QGst::Pipeline>();
QGlib::connect(pipeline1->bus(), "message::error", this, &Player::onBusMessage);
pipeline1->bus()->addSignalWatch();
pipeline1->setState(QGst::StatePlaying);
}
Player::~Player()
{
pipeline1->setState(QGst::StateNull);
}
void Player::onBusMessage(const QGst::MessagePtr & message)
{
switch (message->type()) {
case QGst::MessageEos:
quit();
break;
case QGst::MessageError:
qCritical() << message.staticCast<QGst::ErrorMessage>()->error();
break;
default:
break;
}
}
*/
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.showFullScreen();
return a.exec();
}
| [
"davidgitz@gmail.com"
] | davidgitz@gmail.com |
821567d7cb92f5489ccb9e22de5f2b342291fb29 | dac5254630fefae851da7c843dcab7f6a6af9703 | /Linux/Sources/Application/Address_Book/CGroupTable.cp | 020888673ec3609dc3131eac23720497d2e01393 | [
"Apache-2.0"
] | permissive | gpreviato/Mulberry-Mail | dd4e3618468fff36361bd2aeb0a725593faa0f8d | ce5c56ca7044e5ea290af8d3d2124c1d06f36f3a | refs/heads/master | 2021-01-20T03:31:39.515653 | 2017-09-21T13:09:55 | 2017-09-21T13:09:55 | 18,178,314 | 5 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 34,723 | cp | /*
Copyright (c) 2007 Cyrus Daboo. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Source for CGroupTable class
#include "CGroupTable.h"
#include "CAddressBook.h"
#include "CAddressBookView.h"
#include "CAddressBookWindow.h"
#include "CAddressList.h"
#include "CAddressView.h"
#include "CClipboard.h"
#include "CCommands.h"
#include "CEditGroupDialog.h"
#include "CErrorHandler.h"
#include "CGroup.h"
#include "CGroupList.h"
#include "CGroupTableAction.h"
#include "CIconLoader.h"
#include "CMessage.h"
#include "CMulberryApp.h"
#include "CMulSelectionData.h"
#include "CPreferences.h"
#include "CReplyChooseDialog.h"
#include "CTableRowGeometry.h"
#include "CTableRowSelector.h"
#include "CTaskClasses.h"
#include "CUserAction.h"
#include <UNX_LTableArrayStorage.h>
#include <JXColormap.h>
#include <JXDisplay.h>
#include <JXTextMenu.h>
#include <JTableSelection.h>
#include <jASCIIConstants.h>
#include <jXKeysym.h>
#include <algorithm>
#include <memory>
/////////////////////////////////////////////////////////////////////////////
// CGroupTable
// C O N S T R U C T I O N / D E S T R U C T I O N M E T H O D S
// Default constructor
CGroupTable::CGroupTable(JXScrollbarSet* scrollbarSet,
JXContainer* enclosure,
const HSizingOption hSizing,
const VSizingOption vSizing,
const JCoordinate x, const JCoordinate y,
const JCoordinate w, const JCoordinate h)
: CHierarchyTableDrag(scrollbarSet, enclosure, hSizing, vSizing, x,y,w,h)
{
SetBorderWidth(0);
mAdbk = NULL;
mTableView = NULL;
mEditAction = NULL;
mReplaceAction = NULL;
mLastTyping = 0UL;
mLastChars[0] = 0;
mTableGeometry = new CTableRowGeometry(this, 128, 18);
mTableSelector = new CTableRowSelector(this);
mTableStorage = new LTableArrayStorage(this, sizeof(SGroupTableItem));
SetRowSelect(true);
}
// Default destructor
CGroupTable::~CGroupTable()
{
if (mEditAction || mReplaceAction)
{
mTableView->GetUndoer()->PostAction(NULL);
mEditAction = NULL;
mReplaceAction = NULL;
}
}
// O T H E R M E T H O D S ____________________________________________________________________________
void CGroupTable::OnCreate()
{
// Find table view in super view chain
const JXContainer* parent = GetEnclosure();
while(parent && !dynamic_cast<const CAddressBookView*>(parent))
parent = parent->GetEnclosure();
mTableView = const_cast<CAddressBookView*>(dynamic_cast<const CAddressBookView*>(parent));
CHierarchyTableDrag::OnCreate();
// Get keys but not Tab which is used to shift focus
WantInput(kTrue);
SetKeySelection(true);
// Set Drag & Drop info
AddDropFlavor(CMulberryApp::sFlavorGrpList);
AddDragFlavor(GetDisplay()->GetSelectionManager()->GetMimePlainTextXAtom());
AddDragFlavor(GetDisplay()->GetSelectionManager()->GetTextXAtom());
AddDropFlavor(CMulberryApp::sFlavorMsgList);
AddDropFlavor(CMulberryApp::sFlavorAddrList);
AddDropFlavor(CMulberryApp::sFlavorGrpList);
AddDropFlavor(GetDisplay()->GetSelectionManager()->GetMimePlainTextXAtom());
AddDropFlavor(GetDisplay()->GetSelectionManager()->GetTextXAtom());
SetReadOnly(false);
SetDropCell(true);
SetAllowDrag(true);
SetSelfDrag(true);
SetAllowMove(false);
// Context menu
CreateContextMenu(CMainMenu::eContextAdbkGroup);
}
// Resize columns
void CGroupTable::ApertureResized(const JCoordinate dw, const JCoordinate dh)
{
CHierarchyTableDrag::ApertureResized(dw, dh);
// Single column always fills table width
if (mCols)
{
JCoordinate cw = GetApertureWidth();
if (cw < 32)
cw = 32;
SetColWidth(cw, 1, 1);
}
}
// Set dirty flag
void CGroupTable::SetDirty(bool dirty)
{
mDirty = dirty;
}
// Is it dirty
bool CGroupTable::IsDirty()
{
return mDirty;
}
void CGroupTable::DoSelectionChanged()
{
CHierarchyTableDrag::DoSelectionChanged();
// Determine whether preview is triggered
const CUserAction& preview = mTableView->GetPreviewAction();
if (preview.GetSelection())
DoPreview();
// Determine whether full view is triggered
const CUserAction& fullview = mTableView->GetFullViewAction();
if (fullview.GetSelection())
DoFullView();
}
// Handle single click
void CGroupTable::DoSingleClick(TableIndexT row, const CKeyModifiers& mods)
{
// Determine whether preview is triggered
const CUserAction& preview = mTableView->GetPreviewAction();
if (preview.GetSingleClick() &&
(preview.GetSingleClickModifiers() == mods))
DoPreview();
// Determine whether full view is triggered
const CUserAction& fullview = mTableView->GetFullViewAction();
if (fullview.GetSingleClick() &&
(fullview.GetSingleClickModifiers() == mods))
DoFullView();
}
// Handle double click
void CGroupTable::DoDoubleClick(TableIndexT row, const CKeyModifiers& mods)
{
// Determine whether preview is triggered
const CUserAction& preview = mTableView->GetPreviewAction();
if (preview.GetDoubleClick() &&
(preview.GetDoubleClickModifiers() == mods))
DoPreview();
// Determine whether full view is triggered
const CUserAction& fullview = mTableView->GetFullViewAction();
if (fullview.GetDoubleClick() &&
(fullview.GetDoubleClickModifiers() == mods))
DoFullView();
}
void CGroupTable::DoPreview()
{
// Ignore if no preview pane
if (!mTableView->GetPreview())
return;
CGroup* grp = NULL;
// Determine whether to do groups or address only
if (TestSelectionOr((TestSelectionPP) &CGroupTable::TestSelectionGroup))
{
// Create list to hold preview items (make sure list does not delete them when it is destroyed)
CGroupList grps;
grps.set_delete_data(false);
// Add each selected group
DoToSelection1((DoToSelection1PP) &CGroupTable::AddGroupToList, &grps);
// Set to single group only
if (grps.size() == 1)
grp = grps.front();
}
// Only do preview if there has been a change
if (grp != mTableView->GetPreview()->GetGroup())
{
// Always clear out message preview immediately, otherwise
// do preview at idle time to prevent re-entrant network calls
if (grp)
{
// Give it to preview (if its NULL the preview will be cleared)
CGroupPreviewTask* task = new CGroupPreviewTask(mTableView->GetPreview(), mAdbk, grp);
task->Go();
}
else
// do immediate update of preview
mTableView->GetPreview()->SetGroup(mAdbk, grp);
}
}
// Just edit the item
void CGroupTable::DoFullView()
{
DoEditEntry();
}
// Set the entry list
void CGroupTable::SetAddressBook(CAddressBook* adbk)
{
// Cache list
mAdbk = adbk;
if (mAdbk)
mAdbk->GetGroupList()->SetComparator(new CGroupComparator());
// Force reset
ResetTable();
}
// Insert group into display
TableIndexT CGroupTable::InsertGroup(TableIndexT pos, CGroup* grp)
{
// Prevent selection changes
StDeferSelectionChanged _defer(this);
// Find position of previous group
TableIndexT woRow;
for(woRow = 0; woRow < mCollapsableTree->CountNodes(); woRow++)
{
if (GetNestingLevel(woRow) == 0)
pos--;
if (pos < 0) break;
}
SGroupTableItem item(true, grp);
TableIndexT newRow = InsertSiblingRows(1, woRow, &item, sizeof(SGroupTableItem), true, false);
// Add all addresses in group
for(unsigned long i = 0; i < grp->GetAddressList().size(); i++)
{
SGroupTableItem addr_item(false, grp);
AddLastChildRow(newRow, &addr_item, sizeof(SGroupTableItem), false, false);
}
DeepCollapseRow(newRow);
return GetExposedIndex(newRow);
}
// Delete group from display
void CGroupTable::DeleteGroup(TableIndexT pos)
{
// Prevent selection changes
StDeferSelectionChanged _defer(this);
// Find position of group
TableIndexT woRow;
for(woRow = 0; woRow < mCollapsableTree->CountNodes(); woRow++)
{
if (GetNestingLevel(woRow) == 0)
pos--;
if (pos < 0) break;
}
RemoveRows(1, woRow, false);
}
// Replace one group with another
void CGroupTable::ReplaceGroup(CGroup* old_grp, CGroup* new_grp)
{
// Prevent selection changes
StDeferSelectionChanged _defer(this);
// Get change
short diff = new_grp->GetAddressList().size() - old_grp->GetAddressList().size();
// Do replace
CGroupList::iterator replace = find(mAdbk->GetGroupList()->begin(), mAdbk->GetGroupList()->end(), old_grp);
if (replace < mAdbk->GetGroupList()->end())
{
*replace = new_grp;
// Force change in adbk
mAdbk->UpdateGroup(new_grp);
short pos = mAdbk->GetGroupList()->FetchIndexOf(new_grp);
// Find position of group
TableIndexT woRow;
for(woRow = 0; woRow <= mCollapsableTree->CountNodes(); woRow++)
{
if (GetNestingLevel(woRow) == 0)
pos--;
if (pos < 1) break;
}
// Replace group item in table
SGroupTableItem grp_item(true, new_grp);
STableCell aCell(woRow, 1);
SetCellData(aCell, &grp_item, sizeof(SGroupTableItem));
// Change address rows
SGroupTableItem addr_item(false, new_grp);
short num = (diff > 0) ? diff : -diff;
while(num--)
{
if (diff > 0)
AddLastChildRow(woRow, &addr_item, sizeof(SGroupTableItem), false, false);
else
RemoveRows(1, woRow+1, false);
}
// Refill address rows with new group
for(short i = 0; i < new_grp->GetAddressList().size(); i++)
{
SGroupTableItem addr_item(false, new_grp);
STableCell aCell(woRow + 1 + i, 1);
SetCellData(aCell, &addr_item, sizeof(SGroupTableItem));
}
}
}
// Insert address into display
void CGroupTable::InsertedAddress(CGroup* grp, int num)
{
// Prevent selection changes
StDeferSelectionChanged _defer(this);
short pos = mAdbk->GetGroupList()->FetchIndexOf(grp);
// Find position of group
TableIndexT woRow;
for(woRow = 0; woRow < mCollapsableTree->CountNodes(); woRow++)
{
if (GetNestingLevel(woRow) == 0)
pos--;
if (pos < 0) break;
}
// Replace group item
SGroupTableItem grp_item(true, grp);
STableCell aCell(woRow + 1, 1);
SetCellData(aCell, &grp_item, sizeof(SGroupTableItem));
// Add required number of new addresses
SGroupTableItem addr_item(false, grp);
while(num--)
AddLastChildRow(woRow, &addr_item, sizeof(SGroupTableItem), false, false);
// Refill address rows with new group
for(short i = 0; i < grp->GetAddressList().size(); i++)
{
SGroupTableItem addr_item(false, grp);
STableCell aCell(woRow + 1 + i, 1);
SetCellData(aCell, &addr_item, sizeof(SGroupTableItem));
}
}
// Delete address from display
void CGroupTable::DeletedAddress(CGroup* grp, int num)
{
// Prevent selection changes
StDeferSelectionChanged _defer(this);
// Prevent window update during changes
StDeferTableAdjustment changing(this);
short pos = mAdbk->GetGroupList()->FetchIndexOf(grp);
// Find position of group
UInt32 woRow;
for(woRow = 0; woRow < mCollapsableTree->CountNodes(); woRow++)
{
if (GetNestingLevel(woRow) == 0)
pos--;
if (pos < 0) break;
}
// Replace group item
SGroupTableItem grp_item(true, grp);
STableCell aCell(woRow + 1, 1);
SetCellData(aCell, &grp_item, sizeof(SGroupTableItem));
// Remove number of required rows
while(num--)
RemoveRows(1, woRow+1, false);
// Refill address rows with new group
for(short i = 0; i < grp->GetAddressList().size(); i++)
{
SGroupTableItem addr_item(false, grp);
STableCell aCell(woRow + 1 + i, 1);
SetCellData(aCell, &addr_item, sizeof(SGroupTableItem));
}
}
// Keep cached list in sync
void CGroupTable::ResetTable()
{
// Prevent selection changes
StDeferSelectionChanged _defer(this);
// Delete all existing rows
RemoveAllRows(true);
// Add all groups
if (mAdbk)
{
UInt32 last_grp_row = 0;
for(CGroupList::iterator iter = mAdbk->GetGroupList()->begin(); iter != mAdbk->GetGroupList()->end(); iter++)
{
// Insert group item
SGroupTableItem grp_item(true, *iter);
last_grp_row = InsertSiblingRows(1, last_grp_row, &grp_item, sizeof(SGroupTableItem), true, false);
// Add all addresses in group
for(short i = 0; i < (*iter)->GetAddressList().size(); i++)
{
SGroupTableItem addr_item(false, *iter);
AddLastChildRow(last_grp_row, &addr_item, sizeof(SGroupTableItem), false, false);
}
}
}
mTableView->UpdateCaptions();
Refresh();
}
// Reset the table from the address list
void CGroupTable::ClearTable()
{
// Prevent selection changes
StDeferSelectionChanged _defer(this);
// Remove all rows
Clear();
}
void CGroupTable::OnNewMessage(void)
{
CreateNewLetter(GetDisplay()->GetLatestKeyModifiers().meta());
}
void CGroupTable::OnNewGroup(void)
{
CreateNewEntry();
}
void CGroupTable::OnEditGroup(void)
{
DoEditEntry();
}
void CGroupTable::OnDeleteGroup(void)
{
DoDeleteEntry();
}
// Create new letter from selection
void CGroupTable::CreateNewLetter(bool option_key)
{
// Create list of selected addresses
CAddressList list;
// Copy selection into list for active list only
AddSelectionToList(&list);
CReplyChooseDialog::ProcessChoice(&list,
!(CPreferences::sPrefs->mOptionKeyAddressDialog.GetValue() ^ option_key) && (list.size() > 0));
}
// Create a new group
void CGroupTable::CreateNewEntry()
{
// Create new group and add to list
CGroup* new_grp = new CGroup;
// Let DialogHandler process events
if (CEditGroupDialog::PoseDialog(new_grp))
{
// Only add if some text available
if (!new_grp->IsEmpty())
{
// Initiate action
mTableView->GetUndoer()->PostAction(new CGroupTableNewAction(this, new_grp, IsDirty()));
}
else
delete new_grp;
}
else
delete new_grp;
}
// Edit selected entries
void CGroupTable::DoEditEntry()
{
// Create new edit action ready to store edits (force previous one to be committed)
CGroupTableEditAction* oldEditAction = mEditAction;
mEditAction = new CGroupTableEditAction(this, IsDirty());
// Do edit for each selection
if (TestSelectionOr((TestSelectionPP) &CGroupTable::EditEntry))
// Initiate action - will commit previous
mTableView->GetUndoer()->PostAction(mEditAction);
else
{
// Delete attempted action and restore previous
delete mEditAction;
mEditAction = oldEditAction;
}
}
// Edit specified group
bool CGroupTable::EditEntry(TableIndexT row)
{
bool done_edit = false;
// Get its info
TableIndexT woRow = GetWideOpenIndex(row);
STableCell woCell(woRow, 1);
SGroupTableItem item;
UInt32 dataSize = sizeof(SGroupTableItem);
GetCellData(woCell, &item, dataSize);
// Copy original address
CGroup* copy = new CGroup(*item.mGroup);
// Only edit groups
if (item.mIsGroup)
{
// Let DialogHandler process events
if (CEditGroupDialog::PoseDialog(copy))
{
// Add info to action
mEditAction->AddEdit(item.mGroup, copy);
done_edit = true;
}
else
{
delete copy;
done_edit = false;
}
}
return done_edit;
}
// Delete selected entries
void CGroupTable::DoDeleteEntry()
{
// Determine whether to do groups or address only
if (TestSelectionOr((TestSelectionPP) &CGroupTable::TestSelectionGroup))
{
// Create list to hold deleted items
CGroupList* grps = new CGroupList();
// Add each selected group
DoToSelection1((DoToSelection1PP) &CGroupTable::AddGroupToList, grps);
// Initiate delete action if some selected
if (grps->size() > 0)
mTableView->GetUndoer()->PostAction(new CGroupTableDeleteAction(this, grps, IsDirty()));
else
delete grps;
}
else
{
CGroup* aGrp = NULL;
if (TestSelectionAnd1((TestSelection1PP) &CGroupTable::TestSameGroup, &aGrp) && aGrp)
{
// Copy original group
CGroup* copy = new CGroup(*aGrp);
// Delete selected addresses (in reverse)
STableCell delCell(0, 0);
while (GetPreviousSelectedCell(delCell))
{
// Get its info
TableIndexT woRow = GetWideOpenIndex(delCell.row);
STableCell woCell(woRow, delCell.col);
SGroupTableItem item;
UInt32 dataSize = sizeof(SGroupTableItem);
GetCellData(woCell, &item, dataSize);
// Determine position in group
short pos = woRow - GetParentIndex(woRow) - 1;
// Delete address
copy->GetAddressList().erase(copy->GetAddressList().begin() + pos);
}
// Initiate delete action
mReplaceAction = new CGroupTableReplaceAction(this, aGrp, copy, IsDirty());
mTableView->GetUndoer()->PostAction(mReplaceAction);
}
else if (aGrp)
CErrorHandler::PutStopAlertRsrc("Alerts::Adbk::DeleteAddressSameGroup");
}
}
// Add from list - not unique
void CGroupTable::AddGroupsFromList(CGroupList* grps)
{
// Prevent selection changes
StDeferSelectionChanged _defer(this);
// Add all groups
mAdbk->AddGroup(grps, true);
SelectGroups(grps);
mTableView->UpdateCaptions();
SetDirty(false);
}
// Change from list
void CGroupTable::ChangeGroupsFromList(CGroupList* old_grps, CGroupList* new_grps)
{
// Prevent selection changes
StDeferSelectionChanged _defer(this);
// Delete from list
mAdbk->UpdateGroup(old_grps, new_grps);
// Reset only after all changes have happened
UnselectAllCells();
Refresh();
mTableView->UpdateCaptions();
SetDirty(false);
}
// Delete from list
void CGroupTable::RemoveGroupsFromList(CGroupList* grps)
{
// Prevent selection changes
StDeferSelectionChanged _defer(this);
// Delete from list
mAdbk->RemoveGroup(grps);
// Reset only after all changes have happened
UnselectAllCells();
Refresh();
mTableView->UpdateCaptions();
SetDirty(false);
}
// Delete from list
void CGroupTable::SelectGroups(CGroupList* grps)
{
// Prevent selection changes
StDeferSelectionChanged _defer(this);
// Remove existing selection
UnselectAllCells();
// Loop over all rows selecting from list
for(TableIndexT row = 1; row <= mRows; row++)
{
TableIndexT woRow = GetWideOpenIndex(row);
STableCell woCell(woRow, 1);
SGroupTableItem item;
UInt32 dataSize = sizeof(SGroupTableItem);
GetCellData(woCell, &item, dataSize);
if (item.mIsGroup)
{
CGroup* grp = item.mGroup;
CGroupList::const_iterator found = std::find(grps->begin(), grps->end(), grp);
if (found != grps->end())
SelectCell(STableCell(row, 1));
}
}
// Bring first item into view
ShowFirstSelection();
// Reset only after all changes have happened
SetDirty(false);
}
// Add selected addresses to list
void CGroupTable::AddSelectionToList(CAddressList* list)
{
// Add all selected address to drag
DoToSelection1((DoToSelection1PP) &CGroupTable::AddAddressesToList, list);
}
// Add group to list
bool CGroupTable::AddAddressesToList(TableIndexT row, CAddressList* list)
{
// Get its info
TableIndexT woRow = GetWideOpenIndex(row);
STableCell woCell(woRow, 1);
SGroupTableItem item;
UInt32 dataSize = sizeof(SGroupTableItem);
GetCellData(woCell, &item, dataSize);
// Check for group
if (item.mIsGroup)
{
// Add all addresses in this group
for(short i = 0; i < item.mGroup->GetAddressList().size(); i++)
{
cdstring& aStr = item.mGroup->GetAddressList().at(i);
list->push_back(new CAddress(aStr));
}
}
else
{
// Determine position in group
short pos = woRow - GetParentIndex(woRow) - 1;
// Copy and save in selected list
list->push_back(new CAddress(item.mGroup->GetAddressList().at(pos)));
}
return true;
}
// Add to text
bool CGroupTable::AddToText(TableIndexT row, cdstring* txt)
{
// Get its info
TableIndexT woRow = GetWideOpenIndex(row);
STableCell woCell(woRow, 1);
SGroupTableItem item;
UInt32 dataSize = sizeof(SGroupTableItem);
GetCellData(woCell, &item, dataSize);
// Check for group
if (item.mIsGroup)
{
// Add all addresses in this group
for(unsigned long i = 0; i < item.mGroup->GetAddressList().size(); i++)
{
*txt += item.mGroup->GetAddressList().at(i);
*txt += os_endl;
}
}
else
{
// Determine position in group
UInt32 pos = woRow - GetParentIndex(woRow) - 1;
// Copy and save in selected list
*txt += item.mGroup->GetAddressList().at(pos);
*txt += os_endl;
}
return true;
}
// Add group to list
bool CGroupTable::AddGroupToList(TableIndexT row, CGroupList* list)
{
// Get its info
TableIndexT woRow = GetWideOpenIndex(row);
STableCell woCell(woRow, 1);
SGroupTableItem item;
UInt32 dataSize = sizeof(SGroupTableItem);
GetCellData(woCell, &item, dataSize);
// Check for group and attempt unique insert
if (item.mIsGroup)
return list->InsertUniqueItem(item.mGroup);
return false;
}
// Test for selected item group
bool CGroupTable::TestSelectionGroup(TableIndexT row)
{
// Get its info
TableIndexT woRow = GetWideOpenIndex(row);
STableCell woCell(woRow, 1);
SGroupTableItem item;
UInt32 dataSize = sizeof(SGroupTableItem);
GetCellData(woCell, &item, dataSize);
// This is deleted
return item.mIsGroup;
}
// Test for selected items in same group
bool CGroupTable::TestSameGroup(TableIndexT row, CGroup** test)
{
// Get its info
TableIndexT woRow = GetWideOpenIndex(row);
STableCell woCell(woRow, 1);
SGroupTableItem item;
UInt32 dataSize = sizeof(SGroupTableItem);
GetCellData(woCell, &item, dataSize);
// This is deleted
return *test ? (item.mGroup == *test) : ((*test = item.mGroup) != NULL);
}
// Common updaters
void CGroupTable::OnUpdateEditPaste(JXTextMenu* menu, JIndex item)
{
// Check for text in clipboard
menu->EnableItem(item);
}
// Command handlers
void CGroupTable::OnEditCut()
{
// Copy first
OnEditCopy();
// Delete selection
DoDeleteEntry();
}
void CGroupTable::OnEditCopy()
{
cdstring txt;
// Add all selected groups to text
DoToSelection1((DoToSelection1PP) &CGroupTable::AddGroupText, &txt);
// Now copy to scrap
CClipboard::CopyToSecondaryClipboard(GetDisplay(), txt);
}
// Add groups as text to handle
bool CGroupTable::AddGroupText(TableIndexT row , cdstring* txt)
{
// Determine whether to do groups or address only
bool got_grp = TestSelectionOr((TestSelectionPP) &CGroupTable::TestSelectionGroup);
// Get its info
TableIndexT woRow = GetWideOpenIndex(row);
STableCell woCell(woRow, 1);
SGroupTableItem item;
UInt32 dataSize = sizeof(SGroupTableItem);
GetCellData(woCell, &item, dataSize);
// Do not do mixture - copy only groups or only addresses
if (got_grp && !item.mIsGroup) return false;
// Check for single address or group
if (got_grp)
{
CGroup* theGrp = item.mGroup;
for(unsigned long i = 0; i < theGrp->GetAddressList().size(); i++)
{
cdstring& aStr = theGrp->GetAddressList().at(i);
// Add CR before if multi-copy
if (txt->length())
*txt += "\r\n";
*txt += aStr;
}
}
else
{
// Determine position in group
UInt32 pos = woRow - GetParentIndex(woRow) - 1;
// Get address
CGroup* theGrp = item.mGroup;
cdstring& aStr = theGrp->GetAddressList().at(pos);
// Add CR before if multi-copy
if (txt->length())
*txt += os_endl;
*txt += aStr;
}
return true;
}
void CGroupTable::OnEditPaste()
{
cdstring txt;
CClipboard::GetSecondaryClipboard(GetDisplay(), txt);
if (txt.length())
DoToSelection1((DoToSelection1PP) &CGroupTable::AddAddressTextToGroup, txt);
}
// Add address as text to handle
bool CGroupTable::AddAddressTextToGroup(TableIndexT row, char* txt)
{
// Get its info
TableIndexT woRow = GetWideOpenIndex(row);
STableCell woCell(woRow, 1);
SGroupTableItem item;
UInt32 dataSize = sizeof(SGroupTableItem);
GetCellData(woCell, &item, dataSize);
// Check for group
if (item.mIsGroup)
DropDataIntoCell(GetDisplay()->GetSelectionManager()->GetMimePlainTextXAtom(), (unsigned char*) txt, ::strlen(txt), STableCell(row, 1));
return true;
}
void CGroupTable::ActionDeleted()
{
if (mEditAction)
mEditAction = NULL;
if (mReplaceAction)
mReplaceAction = NULL;
}
#pragma mark ____________________________________Keyboard/Mouse
// Double-clicked item
void CGroupTable::LClickCell(const STableCell& inCell, const JXKeyModifiers& modifiers)
{
CHierarchyTableDrag::LClickCell(inCell, modifiers);
DoSingleClick(inCell.row, CKeyModifiers(modifiers));
}
// Double-clicked item
void CGroupTable::LDblClickCell(const STableCell& inCell, const JXKeyModifiers& modifiers)
{
DoDoubleClick(inCell.row, CKeyModifiers(modifiers));
}
// Handle key down
bool CGroupTable::HandleChar(const int key, const JXKeyModifiers& modifiers)
{
// Look for preview/full view based on key stroke
// Determine whether preview is triggered
CKeyModifiers mods(modifiers);
const CUserAction& preview = mTableView->GetPreviewAction();
if ((preview.GetKey() == key) &&
(preview.GetKeyModifiers() == mods))
{
DoPreview();
return true;
}
// Determine whether full view is triggered
const CUserAction& fullview = mTableView->GetFullViewAction();
if ((fullview.GetKey() == key) &&
(fullview.GetKeyModifiers() == mods))
{
DoFullView();
return true;
}
switch(key)
{
case kJDeleteKey:
case kJForwardDeleteKey:
DoDeleteEntry();
return true;
case '\t':
//mTableView->FocusAddress();
//mTableView->SetFocus();
return true;
default:
// Did not handle key
return CHierarchyTableDrag::HandleChar(key, modifiers);
}
}
// Select from key press
void CGroupTable::DoKeySelection()
{
// Create new address for typed chars
CGroup* temp = new CGroup(mLastChars);
// Get low bound insert pos
long select = mAdbk->GetGroupList()->FetchInsertIndexOf(temp);
// Clip to end of list
if (select > mAdbk->GetGroupList()->size()) select--;
// Find exposed position of group
UInt32 pos;
for(pos = 0; pos < mCollapsableTree->CountNodes(); pos++)
{
if (GetNestingLevel(pos) == 0)
select--;
if (select < 0) break;
}
STableCell aCell(GetExposedIndex(pos), 2);
UnselectAllCells();
FakeClickSelect(aCell, false);
ScrollCellIntoFrame(aCell);
delete temp;
}
bool CGroupTable::ObeyCommand(unsigned long cmd, SMenuCommandChoice* menu)
{
switch (cmd)
{
case CCommand::eFileNewMessage:
case CCommand::eToolbarNewLetter:
OnNewMessage();
return true;
case CCommand::eEditCut:
OnEditCut();
return true;
case CCommand::eEditCopy:
OnEditCopy();
return true;
case CCommand::eEditPaste:
OnEditPaste();
return true;
case CCommand::eAddressEdit:
case CCommand::eToolbarAddressBookEditBtn:
DoEditEntry();
return true;
case CCommand::eAddressDelete:
case CCommand::eToolbarAddressBookDeleteBtn:
DoDeleteEntry();
return true;
default:;
}
return CHierarchyTableDrag::ObeyCommand(cmd, menu);
}
void CGroupTable::UpdateCommand(unsigned long cmd, CCmdUI* cmdui)
{
switch(cmd)
{
case CCommand::eEditCut:
case CCommand::eEditCopy:
case CCommand::eAddressEdit:
case CCommand::eToolbarAddressBookEditBtn:
case CCommand::eAddressDelete:
case CCommand::eToolbarAddressBookDeleteBtn:
OnUpdateSelection(cmdui);
return;
case CCommand::eFileNewMessage:
case CCommand::eToolbarNewLetter:
case CCommand::eEditPaste:
OnUpdateAlways(cmdui);
return;
default:;
}
CHierarchyTableDrag::UpdateCommand(cmd, cmdui);
}
// Draw the titles
void CGroupTable::DrawCell(JPainter* pDC, const STableCell& inCell, const JRect& inLocalRect)
{
TableIndexT woRow = GetWideOpenIndex(inCell.row);
STableCell woCell(woRow, inCell.col);
SGroupTableItem item;
UInt32 dataSize = sizeof(SGroupTableItem);
GetCellData(woCell, &item, dataSize);
unsigned long bkgnd = 0x00FFFFFF;
if (item.mIsGroup && CellIsSelected(inCell) && IsActive() && HasFocus())
{
JColorIndex bkgnd_index = GetColormap()->GetDefaultSelectionColor();
JSize r, g, b;
GetColormap()->GetRGB(bkgnd_index, &r, &g, &b);
bkgnd = ((r & 0xFF00) << 8) | (g & 0xFF00) | ((b & 0xFF00) >> 8);
}
JXImage* icon;
const char* content;
if (item.mIsGroup)
{
CGroup* grp = item.mGroup;
icon = CIconLoader::GetIcon(IDI_GROUP_FLAG, this, 16, bkgnd);
content = grp->GetName();
}
else
{
CGroup* grp = item.mGroup;
icon = CIconLoader::GetIcon(IDI_ADDRESS_FLAG, this, 16, bkgnd);
// Determine position in group
UInt32 pos = woRow - GetParentIndex(woRow) - 1;
// Determine name to use
content = grp->GetAddressList().at(pos);
}
DrawHierarchyRow(pDC, inCell.row, inLocalRect, content, icon);
}
#pragma mark ____________________________________Drag&Drop
// Limit flavors based on selection
bool CGroupTable::GetSelectionAtom(CFlavorsList& atoms)
{
// Determine whether to do groups or address only
bool all_grp = TestSelectionAnd((TestSelectionPP) &CGroupTable::TestSelectionGroup);
// If all groups allow group list drag
if (all_grp)
atoms.push_back(CMulberryApp::sFlavorGrpList);
else
atoms.push_back(CMulberryApp::sFlavorAddrList);
// Always do text
atoms.push_back(GetDisplay()->GetSelectionManager()->GetMimePlainTextXAtom());
atoms.push_back(GetDisplay()->GetSelectionManager()->GetTextXAtom());
return true;
}
// Determine if drop into cell
bool CGroupTable::IsDropCell(JArray<Atom>& typeList, const STableCell& cell)
{
if (IsValidCell(cell))
{
TableIndexT woRow = GetWideOpenIndex(cell.row);
STableCell woCell(woRow, cell.col);
SGroupTableItem item;
UInt32 dataSize = sizeof(SGroupTableItem);
GetCellData(woCell, &item, dataSize);
return item.mIsGroup;
}
else
return false;
}
bool CGroupTable::RenderSelectionData(CMulSelectionData* seldata, Atom type)
{
bool rendered = false;
if (type == CMulberryApp::sFlavorGrpList)
{
// Create list to hold dragged items
std::auto_ptr<CGroupList> grps(new CGroupList);
grps->set_delete_data(false);
// Add each selected address
DoToSelection1((DoToSelection1PP) &CGroupTable::AddGroupToList, grps.get());
seldata->SetData(type, reinterpret_cast<unsigned char*>(grps.release()), sizeof(CGroupList*));
rendered = true;
}
else if (type == CMulberryApp::sFlavorAddrList)
{
// Create list to hold deleted items
std::auto_ptr<CAddressList> addrs(new CAddressList);
addrs->set_delete_data(false);
// Add each selected address
DoToSelection1((DoToSelection1PP) &CGroupTable::AddAddressesToList, addrs.get());
seldata->SetData(type, reinterpret_cast<unsigned char*>(addrs.release()), sizeof(CAddressList*));
rendered = true;
}
else if ((type == GetDisplay()->GetSelectionManager()->GetMimePlainTextXAtom()) ||
(type == GetDisplay()->GetSelectionManager()->GetTextXAtom()))
{
cdstring txt;
// Add all selected address to text
DoToSelection1((DoToSelection1PP) &CGroupTable::AddToText, &txt);
// Add all selected address to text
unsigned long dataLength = txt.length() + 1;
unsigned char* data = new unsigned char[dataLength];
if (data)
{
::memcpy(data, txt.c_str(), dataLength);
seldata->SetData(type, data, dataLength);
rendered = true;
}
}
return rendered;
}
// Drop data into whole table
bool CGroupTable::DropData(Atom inFlavor, unsigned char* drag_data, unsigned long data_size)
{
if (inFlavor == CMulberryApp::sFlavorGrpList)
{
CGroupList* grps = reinterpret_cast<CGroupList*>(drag_data);
CGroupTableNewAction* add_action = NULL;
for(CGroupList::const_iterator iter = grps->begin(); iter != grps->end(); iter++)
{
// Does it already exist?
if (!mAdbk->GetGroupList()->IsDuplicate(*iter))
{
CGroup* copy = new CGroup(**iter);
// Check for existing action
if (add_action)
add_action->AddGroup(copy);
else
// Create new action - action owns list
add_action = new CGroupTableNewAction(this, copy, IsDirty());
}
}
// Post action after all added
mTableView->GetUndoer()->PostAction(add_action);
}
return true;
}
// Drop data into cell
bool CGroupTable::DropDataIntoCell(Atom theFlavor,
unsigned char* drag_data,
unsigned long data_size, const STableCell& inCell)
{
bool added = false;
// Only allow drag to group
TableIndexT woRow = GetWideOpenIndex(inCell.row);
STableCell woCell(woRow, inCell.col);
SGroupTableItem item;
UInt32 dataSize = sizeof(SGroupTableItem);
GetCellData(woCell, &item, dataSize);
if (!item.mIsGroup)
return false;
CGroup* old_grp = item.mGroup;
// Create new group
CGroup* new_grp = new CGroup(*old_grp);
if (theFlavor == CMulberryApp::sFlavorMsgList)
{
CMessageList* msgs = reinterpret_cast<CMessageList*>(drag_data);
for(CMessageList::const_iterator iter = msgs->begin(); iter != msgs->end(); iter++)
{
CEnvelope* theEnv = (*iter)->GetEnvelope();
// Add From
if (theEnv->GetFrom()->size())
{
// Add to list
cdstring txt = theEnv->GetFrom()->front()->GetFullAddress();
new_grp->AddAddress(txt);
added = true;
}
// Add Reply-To
if (theEnv->GetReplyTo()->size())
{
// Add to list
cdstring txt = theEnv->GetReplyTo()->front()->GetFullAddress();
new_grp->AddAddress(txt);
added = true;
}
// Add all To: except me
for(CAddressList::iterator iter = theEnv->GetTo()->begin(); iter != theEnv->GetTo()->end(); iter++)
{
// Add to list
cdstring txt = (*iter)->GetFullAddress();
new_grp->AddAddress(txt);
added = true;
}
// Add all Ccs except me
for(CAddressList::iterator iter = theEnv->GetCC()->begin(); iter != theEnv->GetCC()->end(); iter++)
{
// Add to list
cdstring txt = (*iter)->GetFullAddress();
new_grp->AddAddress(txt);
added = true;
}
}
}
else if (theFlavor == CMulberryApp::sFlavorAddrList)
{
CAddressList* addrs = reinterpret_cast<CAddressList*>(drag_data);
for(CAddressList::const_iterator iter = addrs->begin(); iter != addrs->end(); iter++)
{
// Add to list
cdstring txt = (*iter)->GetFullAddress();
new_grp->AddAddress(txt);
added = true;
}
}
else if (theFlavor == CMulberryApp::sFlavorGrpList)
{
unsigned long count = *((unsigned long*) drag_data);
drag_data += sizeof(unsigned long);
for(unsigned long i = 0; i < count; i++)
{
CGroup* theGrp = ((CGroup**) drag_data)[i];
// Add group to new group
new_grp->AddAddress(theGrp->GetNickName());
added = true;
}
}
else if ((theFlavor == GetDisplay()->GetSelectionManager()->GetMimePlainTextXAtom()) ||
(theFlavor == GetDisplay()->GetSelectionManager()->GetTextXAtom()))
{
// Parse text into list
CAddressList list(reinterpret_cast<const char*>(drag_data), data_size);
// Try to add these to table
for(CAddressList::iterator iter = list.begin(); iter != list.end(); iter++)
{
// Now add to group
cdstring txt = (*iter)->GetFullAddress();
new_grp->AddAddress(txt);
added = true;
}
}
// If there was a change reset both tables
if (added)
{
// Check for existing action and force close
if (mReplaceAction)
mTableView->GetUndoer()->PostAction(NULL);
// Create new action and post
mReplaceAction = new CGroupTableReplaceAction(this, old_grp, new_grp, IsDirty());
mTableView->GetUndoer()->PostAction(mReplaceAction);
}
else
delete new_grp;
return added;
}
| [
"svnusers@a91246af-f21b-0410-bd1c-c3c7fc455132"
] | svnusers@a91246af-f21b-0410-bd1c-c3c7fc455132 |
69bb2dc63c1e5b5e632f2a5a288cb89432338cd2 | 12937c90030aa0a9d14f20e55a593ac81186b384 | /posix_qextserialport.h | 1f789aa92cb0ca8e069d8a8e94f09686fafe8596 | [] | no_license | iuvei/baccarat-1 | 8c61d4b124e266337353cc5710abff6c9b828804 | 617c0eb1a1de7e347aafc7026923a6eb03591128 | refs/heads/master | 2020-11-26T15:17:31.785402 | 2016-02-19T09:03:27 | 2016-02-19T09:03:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,943 | h | #ifndef _POSIX_QEXTSERIALPORT_H_
#define _POSIX_QEXTSERIALPORT_H_
#include <stdio.h>
#include <termios.h>
#include <errno.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include "qextserialbase.h"
class Posix_QextSerialPort:public QextSerialBase
{
private:
/*!
* This method is a part of constructor.
*/
void init();
protected:
struct termios Posix_CommConfig;
struct timeval Posix_Timeout;
struct timeval Posix_Copy_Timeout;
virtual qint64 readData(char * data, qint64 maxSize);
virtual qint64 writeData(const char * data, qint64 maxSize);
public:
QFile* Posix_File;
Posix_QextSerialPort();
Posix_QextSerialPort(const Posix_QextSerialPort& s);
Posix_QextSerialPort(const QString & name, QextSerialBase::QueryMode mode = QextSerialBase::Polling);
Posix_QextSerialPort(const PortSettings& settings, QextSerialBase::QueryMode mode = QextSerialBase::Polling);
Posix_QextSerialPort(const QString & name, const PortSettings& settings, QextSerialBase::QueryMode mode = QextSerialBase::Polling);
Posix_QextSerialPort& operator=(const Posix_QextSerialPort& s);
virtual ~Posix_QextSerialPort();
virtual void setBaudRate(BaudRateType);
virtual void setDataBits(DataBitsType);
virtual void setParity(ParityType);
virtual void setStopBits(StopBitsType);
virtual void setFlowControl(FlowType);
virtual void setTimeout(long);
virtual bool open(OpenMode mode);
virtual void close();
virtual void flush();
virtual qint64 size() const;
virtual qint64 bytesAvailable();
virtual void ungetChar(char c);
virtual void translateError(ulong error);
virtual void setDtr(bool set=true);
virtual void setRts(bool set=true);
virtual ulong lineStatus();
};
#endif
| [
"weison86@sina.cn"
] | weison86@sina.cn |
6e6c83345c9a86cb4e3793ca8383bd0570ca2b4c | e2bf73db30f6efbe12675b8ed11dbb7e03d7fd44 | /codigo_alfa/codigo_alfa.ino | 7977f765aaa2048900685ebe9b247ec658c85d56 | [
"BSD-3-Clause"
] | permissive | AlejoJamC/Blitz-arduino | edf8c47c8cb5f6770fbe83d0a099838d9cfb61b7 | 96f80efa805b077694cf57ea34da00f91ceca23e | refs/heads/master | 2021-01-22T08:47:20.547547 | 2017-11-10T20:10:46 | 2017-11-10T20:10:46 | 92,631,321 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,288 | ino | // instancio las variables globales y librerias requeridas
#include <SD.h>
File Archivo;
void setup() {
//Se esablece comunicación con el monitor serial para la comprobación de la
//carga de datos.
Serial.begin(9600);
if (!SD.begin(10)) {
return;
}
// Se crear el archivo
Archivo = SD.open("datos.txt", FILE_WRITE);
}
void loop() {
// Lectura del puerto analogo de la señal resultante del filtro de pasabanda
int sensorValue = analogRead(A0);
// Conversion analogo a digital
float voltage = sensorValue * (5.0 / 1023.0);
// Se intenta abrir el archivo
Archivo = SD.open("datos.txt");
if (Archivo) {
//Se muestra por el monitor que la información que va a aparecer es la del
//archivo datos.txt.
Serial.print(voltage);
Serial.println('\n\r');
//Se implementa un bucle que recorrerá el archivo hasta que no encuentre más
//información (Archivo.available()==FALSE).
while (Archivo.available()) {
//Se escribe la información que ha sido leída del archivo.
Serial.write(Archivo.read());
}
//Si todo ha ido bien cierra el archivo para no perder datos.
Archivo.close();
}
else {
// Mensaje en caso de error
Serial.println("El archivo datos.txt no se abrió correctamente");
}
}
| [
"alejandromantilla7@hotmail.com"
] | alejandromantilla7@hotmail.com |
21af0c478474880ed18fa6183185392b5c617a69 | 8cd626538767888c92a94d2db5ef6b6713dbeef6 | /cpp_d13_2018/ex05/Picture.cpp | 585a1f7552a3fac9d92e6f0a4f261f44b28360e7 | [] | no_license | simonprovost/cppPool | e3be0746e1a3e67d739a8effa67ce9a676af6213 | 8d604708d2dfe0778b95c8a510f6efdcc54b6c61 | refs/heads/master | 2020-05-19T13:03:00.318979 | 2019-05-14T09:42:12 | 2019-05-14T09:42:12 | 185,029,336 | 12 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,044 | cpp | /*
** EPITECH PROJECT, 2018
** //name_project
** File description:
** //todo
*/
#include <fstream>
#include <sstream>
#include <cstring>
#include "Picture.hpp"
bool Picture::getPictureFromFile(const std::string &file)
{
std::ifstream PicFile(file.data());
if (PicFile.is_open()) {
std::stringstream buff;
buff << PicFile.rdbuf();
this->data = buff.str();
PicFile.close();
return (true);
}
this->data = "ERROR";
return (false);
}
Picture::Picture(const std::string &file)
{
if (strcmp(file.data(), "") == 0)
this->data = "";
else
this->getPictureFromFile(file);
}
const std::string &Picture::getData() const
{
return data;
}
Picture::~Picture()
{
}
Picture &Picture::operator=(const Picture &obj)
{
this->data = obj.getData();
return *this;
}
Picture::Picture(const Picture &obj)
{
this->data = obj.getData();
}
Picture::Picture()
{
this->data = "";
}
void Picture::setData(const std::string &data)
{
Picture::data = data;
}
| [
"simon1.provost@epitech.eu"
] | simon1.provost@epitech.eu |
f5d6ff01751adc38596c32372922a7f2d4ddf3fe | 27698cb6fc1a958c772f3439166b8f109ac27e4d | /models/ideal_am.cpp | 67cb74f77c84c7bb923aa5e1719a5bd1b70200b3 | [] | no_license | gxhen/WirelessModelCPP | 321177b3dfa736ae1289a48c12e3c04fbe6749f6 | 67983fdebfe24710db023711d0fff58b49a4dc7d | refs/heads/master | 2023-05-29T04:57:23.448902 | 2015-09-19T18:28:03 | 2015-09-19T18:28:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,094 | cpp | //
// File = ideal_am.cpp
//
#include <stdlib.h>
#include <fstream>
#include "parmfile.h"
#include "ideal_am.h"
#include "model_graph.h"
//#include "uni_rand.h"
extern ParmFile *ParmInput;
//======================================================
IdealAmplitudeModulator::IdealAmplitudeModulator( char* instance_name,
PracSimModel* outer_model,
Signal<float>* carrier_sig,
Signal<float>* mod_sig,
Signal<float>* out_sig )
:PracSimModel(instance_name,
outer_model)
{
MODEL_NAME(IdealAmplitudeModulator);
//ENABLE_MULTIRATE;
//---------------------------------------
// Read model config parms
OPEN_PARM_BLOCK;
GET_DOUBLE_PARM( Modulation_Index );
//--------------------------------------
// Connect input and output signals
Carrier_Sig = carrier_sig;
Mod_Sig = mod_sig;
Out_Sig = out_sig;
MAKE_OUTPUT( Out_Sig );
MAKE_INPUT( Carrier_Sig );
MAKE_INPUT( Mod_Sig );
}
//======================================
IdealAmplitudeModulator::~IdealAmplitudeModulator( void ){ };
//=======================================
void IdealAmplitudeModulator::Initialize(void)
{
//------------------
double samp_intvl = Out_Sig->GetSampIntvl();
Out_Avg_Block_Size = Out_Sig->GetBlockSize();
}
//=======================================================
int IdealAmplitudeModulator::Execute()
{
float *out_sig_ptr;
float out_sig_val;
float *carrier_sig_ptr;
float *mod_sig_ptr;
int is;
int block_size;
out_sig_ptr = GET_OUTPUT_PTR( Out_Sig );
carrier_sig_ptr = GET_INPUT_PTR( Carrier_Sig );
mod_sig_ptr = GET_INPUT_PTR( Mod_Sig );
block_size = Mod_Sig->GetValidBlockSize();
Out_Sig->SetValidBlockSize(block_size);
for (is=0; is<block_size; is++) {
out_sig_val = (1.0 + Modulation_Index*(*mod_sig_ptr++))
* (*carrier_sig_ptr++);
*out_sig_ptr++ = out_sig_val;
}
return(_MES_AOK);
}
| [
"410090357@qq.com"
] | 410090357@qq.com |
7460aa3ffe22f81d4469c6be9668f2bd6165afbe | 90f518ee59a241d39752ba0c7ab2ed4f7325de31 | /src/NetWidgets/Widgets/nSldClassifier.cpp | f6100d8a15a716890788984c57dcdc51cb3a4cd3 | [
"MIT"
] | permissive | Vladimir-Lin/QtNetWidgets | 86999fcae79914f319cbd8cd671215ed0f09012e | e09339c47d40b65875f15bd0839e0bdf89951601 | refs/heads/main | 2023-05-23T14:32:03.824075 | 2021-06-16T17:12:13 | 2021-06-16T17:12:13 | 377,571,914 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,087 | cpp | #include <netwidgets.h>
N::SldClassifier:: SldClassifier (QObject * parent,Plan * p)
: QThread ( parent )
, NetworkManager ( p)
, plan ( p)
, Go (NULL )
, Progress (NULL )
, Mode (None )
, Chunk (10000 )
{
connect(this,SIGNAL(currentProgress(int,QString)) ,
this,SLOT (showProgress (int,QString)) ) ;
}
N::SldClassifier::~SldClassifier(void)
{
}
void N::SldClassifier::DefaultUI(void)
{
Go = new QToolButton(plan->status) ;
Go -> setAutoRaise (true) ;
Go -> setCheckable (true) ;
Go -> setIcon (QIcon(":/images/StopPlay.png")) ;
Go -> setToolTip (tr("Stop analyizing") ) ;
plan -> status -> addPermanentWidget ( Go ) ;
Progress = plan -> Progress ( "%v/%m" ) ;
Progress -> setTextVisible ( true ) ;
}
void N::SldClassifier::showProgress(int index,QString message)
{
Progress -> setValue ( index ) ;
plan -> showMessage ( message ) ;
}
bool N::SldClassifier::OneSecond(void)
{
QDateTime D = Lastest ;
QDateTime S = QDateTime::currentDateTime() ;
time_t d = D.toTime_t() ;
time_t s = S.toTime_t() ;
return (d!=s) ;
}
void N::SldClassifier::doTLDs(SqlConnection & Connection)
{
bool done = false ;
QString Limit = QString ( " limit 0,%1 ;" ) . arg(Chunk) ;
TUID TOTAL = SiteTotal ( Connection ) ;
SUID LUID = LastestTld ( Connection ) ;
TUID FUID = 0 ;
TUID AUID = 0 ;
UUIDs Uuids ;
NAMEs URLs ;
QMap<SUID,TUID> IDs ;
QString Q ;
QString Options ;
QDateTime Start ;
if (LUID>0) FUID = SiteId( Connection , LUID ) ;
Go -> setChecked ( true ) ;
Progress -> setRange ( 0,(int)TOTAL) ;
Limit = " order by id asc" + Limit ;
Lastest = QDateTime::currentDateTime ( ) ;
Start = QDateTime::currentDateTime ( ) ;
AUID = FUID ;
while (!done) {
Uuids . clear ( ) ;
URLs . clear ( ) ;
IDs . clear ( ) ;
Options = QString(" where id > %1").arg(FUID) ;
Q = Connection.sql.SelectFrom (
"id,uuid,url" ,
PlanTable(SiteDepot) ,
Options + Limit ) ;
SqlLoopNow ( Connection , Q ) ;
TUID fuid = Connection . Value ( 0 ) . toLongLong () ;
SUID uuid = Connection . Uuid ( 1 ) ;
QString url = Connection . String( 2 ) ;
Uuids << uuid ;
IDs [ uuid ] = fuid ;
URLs [ uuid ] = url ;
SqlLoopErr ( Connection , Q ) ;
SqlLoopEnd ( Connection , Q ) ;
if (Uuids.count()<=0) done = true; else {
for (int i=0;Go->isChecked() && i<Uuids.count();i++) {
SUID uuid = Uuids [ i ] ;
FUID = IDs [ uuid ] ;
QUrl url ;
url . setHost (URLs[uuid]) ;
SUID tld = UrlTLD ( url ) ;
if (tld>0) InsertTldMap ( Connection , uuid , tld ) ;
if (OneSecond()) {
TUID INDEX = FUID - AUID ;
TUID STOTA = TOTAL - AUID ;
QString msg ;
QDateTime ETA ;
ETA = Time::ETA(Start,(int)INDEX,(int)STOTA) ;
msg = tr("Estimated complete time : %1" )
.arg(ETA.toString("yyyy/MM/dd hh:mm:ss") ) ;
emit currentProgress( (int)FUID , msg ) ;
Lastest = QDateTime::currentDateTime ( ) ;
} ;
} ;
} ;
if (!Go->isChecked()) done = true ;
} ;
}
void N::SldClassifier::doSLDs(SqlConnection & Connection)
{
bool done = false ;
QString Limit = QString ( " limit 0,%1 ;" ) . arg(Chunk) ;
TUID TOTAL = SiteTotal ( Connection ) ;
SUID LUID = LastestSld ( Connection ) ;
TUID FUID = 0 ;
TUID AUID = 0 ;
UUIDs Uuids ;
NAMEs URLs ;
QMap<SUID,TUID> IDs ;
QString Q ;
QString Options ;
QDateTime Start ;
if (LUID>0) FUID = SiteId( Connection , LUID ) ;
Go -> setChecked ( true ) ;
Progress -> setRange ( 0,(int)TOTAL) ;
Limit = " order by id asc" + Limit ;
Lastest = nTimeNow ;
Start = nTimeNow ;
AUID = FUID ;
while (!done) {
Uuids . clear ( ) ;
URLs . clear ( ) ;
IDs . clear ( ) ;
Options = QString(" where id > %1").arg(FUID) ;
Q = Connection.sql.SelectFrom (
"id,uuid,url" ,
PlanTable(SiteDepot) ,
Options + Limit ) ;
SqlLoopNow ( Connection , Q ) ;
TUID fuid = Connection . Value ( 0 ) . toLongLong () ;
SUID uuid = Connection . Uuid ( 1 ) ;
QString url = Connection.String( 2 ) ;
Uuids << uuid ;
IDs [ uuid ] = fuid ;
URLs [ uuid ] = url ;
SqlLoopErr ( Connection , Q ) ;
SqlLoopEnd ( Connection , Q ) ;
if (Uuids.count()<=0) done = true; else {
for (int i=0;Go->isChecked() && i<Uuids.count();i++) {
SUID uuid = Uuids [ i ] ;
FUID = IDs [ uuid ] ;
QUrl url ;
url . setHost (URLs[uuid]) ;
SUID sld = UrlSLD ( url ) ;
if (sld>0) InsertSldMap ( Connection , uuid , sld ) ;
if (OneSecond()) {
TUID INDEX = FUID - AUID ;
TUID STOTA = TOTAL - AUID ;
QString msg ;
QDateTime ETA ;
ETA = Time::ETA(Start,(int)INDEX,(int)STOTA) ;
msg = tr("Estimated complete time : %1" )
.arg(ETA.toString("yyyy/MM/dd hh:mm:ss") ) ;
emit currentProgress( (int)FUID , msg ) ;
Lastest = QDateTime::currentDateTime ( ) ;
} ;
} ;
} ;
if (!Go->isChecked()) done = true ;
} ;
}
void N::SldClassifier::run(void)
{
SqlConnection SC ( NetPlan->sql ) ;
if (SC.open("nSldClassifier","run")) {
if (LoadDomainIndex(SC)) {
PrepareDomainMap ( ) ;
switch (Mode) {
case None :
break ;
case DoTLD :
plan->showMessage(tr("Counting sites...")) ;
plan->processEvents ( ) ;
doTLDs(SC) ;
break ;
case DoSLD :
plan->showMessage(tr("Counting sites...")) ;
plan->processEvents ( ) ;
doSLDs(SC) ;
break ;
} ;
} ;
SC . close ( ) ;
} ;
SC.remove() ;
Go -> hide ( ) ;
Progress -> hide ( ) ;
Go -> deleteLater ( ) ;
Progress -> deleteLater ( ) ;
Go = NULL ;
Progress = NULL ;
emit Finished ( ) ;
}
| [
"lin.vladimir@gmail.com"
] | lin.vladimir@gmail.com |
af637682100426d51140e248394fa4b975862726 | 66daa8fdb9aecce0dc4df5b0e1ea10fb983705a8 | /WatSat_arduino_code/sensor_shield_code/mux2/mux2.ino | 385cfe3cf92866392deb8f229d1e7b6ad6d668c1 | [
"MIT"
] | permissive | cjski/Arduino-ish | 7e964e77b866d3e777c6b1ff06de491765e32978 | b9c6612a2ee971f05d913fbcd5d136d4f3fdec65 | refs/heads/master | 2021-01-21T05:20:58.088739 | 2016-12-01T00:27:58 | 2016-12-01T00:27:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,053 | ino | // 74HC4067 demultiplexer demonstration (1 to 16)
// control pins output table in array form
// see truth table on page 2 of TI 74HC4067 data sheet
// connect 74HC4067 S0~S3 to Arduino D7~D4 respectively
// 5V to 74HC4067 pin 1 to power the LEDs :)
byte controlPins[] = {B00000000,
B10000000,
B01000000,
B11000000,
B00100000,
B10100000,
B01100000,
B11100000,
B00010000,
B10010000,
B01010000,
B11010000,
B00110000,
B10110000,
B01110000,
B11110000 };
void setup()
{
DDRD = B11111111; // set PORTD (digital 7~0) to outputs
}
void setPin(int outputPin)
// function to select pin on 74HC4067
{
PORTD = controlPins[outputPin];
}
void loop()
{
for (int i = 0; i < 16; i++)
{
setPin(i);
delay(250);
}
}
| [
"herman.stubeda@outlook.com"
] | herman.stubeda@outlook.com |
a3a45905576b7b28985e8abe2e5f6ca9481ea67a | 81b1e98f8a4b964e4db70d17ca61f2d9fbff2606 | /GameEngine/cGLColourHelper.cpp | f930dd2ae046ae14169bb1876148aa7ac51d9e8e | [] | no_license | niral3737/GameJam | 07f47349341b53dc5c8bc23253c92afd61eb3b97 | f3a9f7fa161770976f21d724a1a7aa683cfc1122 | refs/heads/master | 2020-05-16T06:23:59.768707 | 2019-04-24T00:22:18 | 2019-04-24T00:22:18 | 182,845,158 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,075 | cpp | #include "cGLColourHelper.h"
#include <algorithm>
cGLColourHelper::cColour::cColour( std::string sName, cGLColourHelper::enumColours colourEnum, glm::vec3 initRGB )
{
this->enumName = colourEnum;
this->name = sName;
this->rgb = initRGB;
return;
}
cGLColourHelper::cColour::cColour( std::string sName, cGLColourHelper::enumColours colourEnum, float r, float g, float b )
{
this->enumName = colourEnum;
this->name = sName;
this->rgb.r = r;
this->rgb.g = g;
this->rgb.b = b;
return;
}
//static
cGLColourHelper* cGLColourHelper::m_p_theInstance = 0;
//static
cGLColourHelper* cGLColourHelper::getInstance( void )
{
if ( cGLColourHelper::m_p_theInstance == 0 )
{
cGLColourHelper::m_p_theInstance = new cGLColourHelper();
}
return cGLColourHelper::m_p_theInstance;
}
cGLColourHelper::cGLColourHelper()
{
this->m_mapColours[ ALICE_BLUE ] = cGLColourHelper::cColour( "AliceBlue", ALICE_BLUE, 0.941f, 0.973f, 1.000f);
this->m_mapColours[ ANTIQUE_WHITE ] = cGLColourHelper::cColour( "AntiqueWhite", ANTIQUE_WHITE, 0.980f, 0.922f, 0.843f);
this->m_mapColours[ AQUA ] = cGLColourHelper::cColour( "Aqua", AQUA, 0.000f, 1.000f, 1.000f);
this->m_mapColours[ AQUAMARINE ] = cGLColourHelper::cColour( "Aquamarine", AQUAMARINE, 0.498f, 1.000f, 0.831f);
this->m_mapColours[ AZURE ] = cGLColourHelper::cColour( "Azure", AZURE, 0.941f, 1.000f, 1.000f);
this->m_mapColours[ BEIGE ] = cGLColourHelper::cColour( "Beige", BEIGE, 0.961f, 0.961f, 0.863f);
this->m_mapColours[ BISQUE ] = cGLColourHelper::cColour( "Bisque", BISQUE, 1.000f, 0.894f, 0.769f);
this->m_mapColours[ BLACK ] = cGLColourHelper::cColour( "Black", BLACK, 0.000f, 0.000f, 0.000f);
this->m_mapColours[ BLANCHED_ALMOND ] = cGLColourHelper::cColour( "BlanchedAlmond", BLANCHED_ALMOND, 1.000f, 0.922f, 0.804f);
this->m_mapColours[ BLUE ] = cGLColourHelper::cColour( "Blue", BLUE, 0.000f, 0.000f, 1.000f);
this->m_mapColours[ BLUE_VIOLET ] = cGLColourHelper::cColour( "BlueViolet", BLUE_VIOLET, 0.541f, 0.169f, 0.886f);
this->m_mapColours[ BROWN ] = cGLColourHelper::cColour( "Brown", BROWN, 0.647f, 0.165f, 0.165f);
this->m_mapColours[ BURLY_WOOD ] = cGLColourHelper::cColour( "BurlyWood", BURLY_WOOD, 0.871f, 0.722f, 0.529f);
this->m_mapColours[ CADET_BLUE ] = cGLColourHelper::cColour( "CadetBlue", CADET_BLUE, 0.373f, 0.620f, 0.627f);
this->m_mapColours[ CHARTREUSE ] = cGLColourHelper::cColour( "Chartreuse", CHARTREUSE, 0.498f, 1.000f, 0.000f);
this->m_mapColours[ CHOCOLATE ] = cGLColourHelper::cColour( "Chocolate", CHOCOLATE, 0.824f, 0.412f, 0.118f);
this->m_mapColours[ CORAL ] = cGLColourHelper::cColour( "Coral", CORAL, 1.000f, 0.498f, 0.314f);
this->m_mapColours[ CORNFLOWER_BLUE ] = cGLColourHelper::cColour( "CornflowerBlue", CORNFLOWER_BLUE, 0.392f, 0.584f, 0.929f);
this->m_mapColours[ CORNSILK ] = cGLColourHelper::cColour( "Cornsilk", CORNSILK, 1.000f, 0.973f, 0.863f);
this->m_mapColours[ CRIMSON ] = cGLColourHelper::cColour( "Crimson", CRIMSON, 0.863f, 0.078f, 0.235f);
this->m_mapColours[ CYAN ] = cGLColourHelper::cColour( "Cyan", CYAN, 0.000f, 1.000f, 1.000f);
this->m_mapColours[ DARK_BLUE ] = cGLColourHelper::cColour( "DarkBlue", DARK_BLUE, 0.000f, 0.000f, 0.545f);
this->m_mapColours[ DARK_CYAN ] = cGLColourHelper::cColour( "DarkCyan", DARK_CYAN, 0.000f, 0.545f, 0.545f);
this->m_mapColours[ DARK_GOLDEN_ROD ] = cGLColourHelper::cColour( "DarkGoldenRod", DARK_GOLDEN_ROD, 0.722f, 0.525f, 0.043f);
this->m_mapColours[ DARK_GRAY ] = cGLColourHelper::cColour( "DarkGray", DARK_GRAY, 0.663f, 0.663f, 0.663f);
this->m_mapColours[ DARK_GREEN ] = cGLColourHelper::cColour( "DarkGreen", DARK_GREEN, 0.000f, 0.392f, 0.000f);
this->m_mapColours[ DARK_KHAKI ] = cGLColourHelper::cColour( "DarkKhaki", DARK_KHAKI, 0.741f, 0.718f, 0.420f);
this->m_mapColours[ DARK_MAGENTA ] = cGLColourHelper::cColour( "DarkMagenta", DARK_MAGENTA, 0.545f, 0.000f, 0.545f);
this->m_mapColours[ DARK_OLIVE_GREEN ] = cGLColourHelper::cColour( "DarkOliveGreen", DARK_OLIVE_GREEN, 0.333f, 0.420f, 0.184f);
this->m_mapColours[ DARK_ORANGE ] = cGLColourHelper::cColour( "DarkOrange", DARK_ORANGE, 1.000f, 0.549f, 0.000f);
this->m_mapColours[ DARK_ORCHID ] = cGLColourHelper::cColour( "DarkOrchid", DARK_ORCHID, 0.600f, 0.196f, 0.800f);
this->m_mapColours[ DARK_RED ] = cGLColourHelper::cColour( "DarkRed", DARK_RED, 0.545f, 0.000f, 0.000f);
this->m_mapColours[ DARK_SALMON ] = cGLColourHelper::cColour( "DarkSalmon", DARK_SALMON, 0.914f, 0.588f, 0.478f);
this->m_mapColours[ DARK_SEA_GREEN ] = cGLColourHelper::cColour( "DarkSeaGreen", DARK_SEA_GREEN, 0.561f, 0.737f, 0.561f);
this->m_mapColours[ DARK_SLATE_BLUE ] = cGLColourHelper::cColour( "DarkSlateBlue", DARK_SLATE_BLUE, 0.282f, 0.239f, 0.545f);
this->m_mapColours[ DARK_SLATE_GRAY ] = cGLColourHelper::cColour( "DarkSlateGray", DARK_SLATE_GRAY, 0.184f, 0.310f, 0.310f);
this->m_mapColours[ DARK_TURQUOISE ] = cGLColourHelper::cColour( "DarkTurquoise", DARK_TURQUOISE, 0.000f, 0.808f, 0.820f);
this->m_mapColours[ DARK_VIOLET ] = cGLColourHelper::cColour( "DarkViolet", DARK_VIOLET, 0.580f, 0.000f, 0.827f);
this->m_mapColours[ DEEP_PINK ] = cGLColourHelper::cColour( "DeepPink", DEEP_PINK, 1.000f, 0.078f, 0.576f);
this->m_mapColours[ DEEP_SKY_BLUE ] = cGLColourHelper::cColour( "DeepSkyBlue", DEEP_SKY_BLUE, 0.000f, 0.749f, 1.000f);
this->m_mapColours[ DIM_GRAY ] = cGLColourHelper::cColour( "DimGray", DIM_GRAY, 0.412f, 0.412f, 0.412f);
this->m_mapColours[ DODGER_BLUE ] = cGLColourHelper::cColour( "DodgerBlue", DODGER_BLUE, 0.118f, 0.565f, 1.000f);
this->m_mapColours[ FIRE_BRICK ] = cGLColourHelper::cColour( "FireBrick", FIRE_BRICK, 0.698f, 0.133f, 0.133f);
this->m_mapColours[ FLORAL_WHITE ] = cGLColourHelper::cColour( "FloralWhite", FLORAL_WHITE, 1.000f, 0.980f, 0.941f);
this->m_mapColours[ FOREST_GREEN ] = cGLColourHelper::cColour( "ForestGreen", FOREST_GREEN, 0.133f, 0.545f, 0.133f);
this->m_mapColours[ FUCHSIA ] = cGLColourHelper::cColour( "Fuchsia", FUCHSIA, 1.000f, 0.000f, 1.000f);
this->m_mapColours[ GAINSBORO ] = cGLColourHelper::cColour( "Gainsboro", GAINSBORO, 0.863f, 0.863f, 0.863f);
this->m_mapColours[ GHOST_WHITE ] = cGLColourHelper::cColour( "GhostWhite", GHOST_WHITE, 0.973f, 0.973f, 1.000f);
this->m_mapColours[ GOLD ] = cGLColourHelper::cColour( "Gold", GOLD, 1.000f, 0.843f, 0.000f);
this->m_mapColours[ GOLDEN_ROD ] = cGLColourHelper::cColour( "GoldenRod", GOLDEN_ROD, 0.855f, 0.647f, 0.125f);
this->m_mapColours[ GRAY ] = cGLColourHelper::cColour( "Gray", GRAY, 0.502f, 0.502f, 0.502f);
this->m_mapColours[ GREEN ] = cGLColourHelper::cColour( "Green", GREEN, 0.000f, 0.502f, 0.000f);
this->m_mapColours[ GREEN_YELLOW ] = cGLColourHelper::cColour( "GreenYellow", GREEN_YELLOW, 0.678f, 1.000f, 0.184f);
this->m_mapColours[ HONEY_DEW ] = cGLColourHelper::cColour( "HoneyDew", HONEY_DEW, 0.941f, 1.000f, 0.941f);
this->m_mapColours[ HOT_PINK ] = cGLColourHelper::cColour( "HotPink", HOT_PINK, 1.000f, 0.412f, 0.706f);
this->m_mapColours[ INDIAN_RED ] = cGLColourHelper::cColour( "IndianRed", INDIAN_RED, 0.804f, 0.361f, 0.361f);
this->m_mapColours[ INDIGO ] = cGLColourHelper::cColour( "Indigo", INDIGO, 0.294f, 0.000f, 0.510f);
this->m_mapColours[ IVORY ] = cGLColourHelper::cColour( "Ivory", IVORY, 1.000f, 1.000f, 0.941f);
this->m_mapColours[ KHAKI ] = cGLColourHelper::cColour( "Khaki", KHAKI, 0.941f, 0.902f, 0.549f);
this->m_mapColours[ LAVENDER ] = cGLColourHelper::cColour( "Lavender", LAVENDER, 0.902f, 0.902f, 0.980f);
this->m_mapColours[ LAVENDER_BLUSH ] = cGLColourHelper::cColour( "LavenderBlush", LAVENDER_BLUSH, 1.000f, 0.941f, 0.961f);
this->m_mapColours[ LAWN_GREEN ] = cGLColourHelper::cColour( "LawnGreen", LAWN_GREEN, 0.486f, 0.988f, 0.000f);
this->m_mapColours[ LEMON_CHIFFON ] = cGLColourHelper::cColour( "LemonChiffon", LEMON_CHIFFON, 1.000f, 0.980f, 0.804f);
this->m_mapColours[ LIGHT_BLUE ] = cGLColourHelper::cColour( "LightBlue", LIGHT_BLUE, 0.678f, 0.847f, 0.902f);
this->m_mapColours[ LIGHT_CORAL ] = cGLColourHelper::cColour( "LightCoral", LIGHT_CORAL, 0.941f, 0.502f, 0.502f);
this->m_mapColours[ LIGHT_CYAN ] = cGLColourHelper::cColour( "LightCyan", LIGHT_CYAN, 0.878f, 1.000f, 1.000f);
this->m_mapColours[ LIGHT_GOLDEN_ROD_YELLOW ] = cGLColourHelper::cColour( "LightGoldenRodYellow", LIGHT_GOLDEN_ROD_YELLOW, 0.980f, 0.980f, 0.824f);
this->m_mapColours[ LIGHT_GRAY ] = cGLColourHelper::cColour( "LightGray", LIGHT_GRAY, 0.827f, 0.827f, 0.827f);
this->m_mapColours[ LIGHT_GREEN ] = cGLColourHelper::cColour( "LightGreen", LIGHT_GREEN, 0.565f, 0.933f, 0.565f);
this->m_mapColours[ LIGHT_PINK ] = cGLColourHelper::cColour( "LightPink", LIGHT_PINK, 1.000f, 0.714f, 0.757f);
this->m_mapColours[ LIGHT_SALMON ] = cGLColourHelper::cColour( "LightSalmon", LIGHT_SALMON, 1.000f, 0.627f, 0.478f);
this->m_mapColours[ LIGHT_SEA_GREEN ] = cGLColourHelper::cColour( "LightSeaGreen", LIGHT_SEA_GREEN, 0.125f, 0.698f, 0.667f);
this->m_mapColours[ LIGHT_SKY_BLUE ] = cGLColourHelper::cColour( "LightSkyBlue", LIGHT_SKY_BLUE, 0.529f, 0.808f, 0.980f);
this->m_mapColours[ LIGHT_SLATE_GRAY ] = cGLColourHelper::cColour( "LightSlateGray", LIGHT_SLATE_GRAY, 0.467f, 0.533f, 0.600f);
this->m_mapColours[ LIGHT_STEEL_BLUE ] = cGLColourHelper::cColour( "LightSteelBlue", LIGHT_STEEL_BLUE, 0.690f, 0.769f, 0.871f);
this->m_mapColours[ LIGHT_YELLOW ] = cGLColourHelper::cColour( "LightYellow", LIGHT_YELLOW, 1.000f, 1.000f, 0.878f);
this->m_mapColours[ LIME ] = cGLColourHelper::cColour( "Lime", LIME, 0.000f, 1.000f, 0.000f);
this->m_mapColours[ LIME_GREEN ] = cGLColourHelper::cColour( "LimeGreen", LIME_GREEN, 0.196f, 0.804f, 0.196f);
this->m_mapColours[ LINEN ] = cGLColourHelper::cColour( "Linen", LINEN, 0.980f, 0.941f, 0.902f);
this->m_mapColours[ MAGENTA ] = cGLColourHelper::cColour( "Magenta", MAGENTA, 1.000f, 0.000f, 1.000f);
this->m_mapColours[ MAROON ] = cGLColourHelper::cColour( "Maroon", MAROON, 0.502f, 0.000f, 0.000f);
this->m_mapColours[ MEDIUM_AQUA_MARINE ] = cGLColourHelper::cColour( "MediumAquaMarine", MEDIUM_AQUA_MARINE, 0.400f, 0.804f, 0.667f);
this->m_mapColours[ MEDIUM_BLUE ] = cGLColourHelper::cColour( "MediumBlue", MEDIUM_BLUE, 0.000f, 0.000f, 0.804f);
this->m_mapColours[ MEDIUM_ORCHID ] = cGLColourHelper::cColour( "MediumOrchid", MEDIUM_ORCHID, 0.729f, 0.333f, 0.827f);
this->m_mapColours[ MEDIUM_PURPLE ] = cGLColourHelper::cColour( "MediumPurple", MEDIUM_PURPLE, 0.576f, 0.439f, 0.859f);
this->m_mapColours[ MEDIUM_SEA_GREEN ] = cGLColourHelper::cColour( "MediumSeaGreen", MEDIUM_SEA_GREEN, 0.235f, 0.702f, 0.443f);
this->m_mapColours[ MEDIUM_SLATE_BLUE ] = cGLColourHelper::cColour( "MediumSlateBlue", MEDIUM_SLATE_BLUE, 0.482f, 0.408f, 0.933f);
this->m_mapColours[ MEDIUM_SPRING_GREEN ] = cGLColourHelper::cColour( "MediumSpringGreen", MEDIUM_SPRING_GREEN, 0.000f, 0.980f, 0.604f);
this->m_mapColours[ MEDIUM_TURQUOISE ] = cGLColourHelper::cColour( "MediumTurquoise", MEDIUM_TURQUOISE, 0.282f, 0.820f, 0.800f);
this->m_mapColours[ MEDIUM_VIOLET_RED ] = cGLColourHelper::cColour( "MediumVioletRed", MEDIUM_VIOLET_RED, 0.780f, 0.082f, 0.522f);
this->m_mapColours[ MIDNIGHT_BLUE ] = cGLColourHelper::cColour( "MidnightBlue", MIDNIGHT_BLUE, 0.098f, 0.098f, 0.439f);
this->m_mapColours[ MINT_CREAM ] = cGLColourHelper::cColour( "MintCream", MINT_CREAM, 0.961f, 1.000f, 0.980f);
this->m_mapColours[ MISTY_ROSE ] = cGLColourHelper::cColour( "MistyRose", MISTY_ROSE, 1.000f, 0.894f, 0.882f);
this->m_mapColours[ MOCCASIN ] = cGLColourHelper::cColour( "Moccasin", MOCCASIN, 1.000f, 0.894f, 0.710f);
this->m_mapColours[ NAVAJO_WHITE ] = cGLColourHelper::cColour( "NavajoWhite", NAVAJO_WHITE, 1.000f, 0.871f, 0.678f);
this->m_mapColours[ NAVY ] = cGLColourHelper::cColour( "Navy", NAVY, 0.000f, 0.000f, 0.502f);
this->m_mapColours[ OLD_LACE ] = cGLColourHelper::cColour( "OldLace", OLD_LACE, 0.992f, 0.961f, 0.902f);
this->m_mapColours[ OLIVE ] = cGLColourHelper::cColour( "Olive", OLIVE, 0.502f, 0.502f, 0.000f);
this->m_mapColours[ OLIVE_DRAB ] = cGLColourHelper::cColour( "OliveDrab", OLIVE_DRAB, 0.420f, 0.557f, 0.137f);
this->m_mapColours[ ORANGE ] = cGLColourHelper::cColour( "Orange", ORANGE, 1.000f, 0.647f, 0.000f);
this->m_mapColours[ ORANGE_RED ] = cGLColourHelper::cColour( "OrangeRed", ORANGE_RED, 1.000f, 0.271f, 0.000f);
this->m_mapColours[ ORCHID ] = cGLColourHelper::cColour( "Orchid", ORCHID, 0.855f, 0.439f, 0.839f);
this->m_mapColours[ PALE_GOLDEN_ROD ] = cGLColourHelper::cColour( "PaleGoldenRod", PALE_GOLDEN_ROD, 0.933f, 0.910f, 0.667f);
this->m_mapColours[ PALE_GREEN ] = cGLColourHelper::cColour( "PaleGreen", PALE_GREEN, 0.596f, 0.984f, 0.596f);
this->m_mapColours[ PALE_TURQUOISE ] = cGLColourHelper::cColour( "PaleTurquoise", PALE_TURQUOISE, 0.686f, 0.933f, 0.933f);
this->m_mapColours[ PALE_VIOLET_RED ] = cGLColourHelper::cColour( "PaleVioletRed", PALE_VIOLET_RED, 0.859f, 0.439f, 0.576f);
this->m_mapColours[ PAPAYA_WHIP ] = cGLColourHelper::cColour( "PapayaWhip", PAPAYA_WHIP, 1.000f, 0.937f, 0.835f);
this->m_mapColours[ PEACH_PUFF ] = cGLColourHelper::cColour( "PeachPuff", PEACH_PUFF, 1.000f, 0.855f, 0.725f);
this->m_mapColours[ PERU ] = cGLColourHelper::cColour( "Peru", PERU, 0.804f, 0.522f, 0.247f);
this->m_mapColours[ PINK ] = cGLColourHelper::cColour( "Pink", PINK, 1.000f, 0.753f, 0.796f);
this->m_mapColours[ PLUM ] = cGLColourHelper::cColour( "Plum", PLUM, 0.867f, 0.627f, 0.867f);
this->m_mapColours[ POWDER_BLUE ] = cGLColourHelper::cColour( "PowderBlue", POWDER_BLUE, 0.690f, 0.878f, 0.902f);
this->m_mapColours[ PURPLE ] = cGLColourHelper::cColour( "Purple", PURPLE, 0.502f, 0.000f, 0.502f);
this->m_mapColours[ REBECCA_PURPLE ] = cGLColourHelper::cColour( "RebeccaPurple", REBECCA_PURPLE, 0.400f, 0.200f, 0.600f);
this->m_mapColours[ RED ] = cGLColourHelper::cColour( "Red", RED, 1.000f, 0.000f, 0.000f);
this->m_mapColours[ ROSY_BROWN ] = cGLColourHelper::cColour( "RosyBrown", ROSY_BROWN, 0.737f, 0.561f, 0.561f);
this->m_mapColours[ ROYAL_BLUE ] = cGLColourHelper::cColour( "RoyalBlue", ROYAL_BLUE, 0.255f, 0.412f, 0.882f);
this->m_mapColours[ SADDLE_BROWN ] = cGLColourHelper::cColour( "SaddleBrown", SADDLE_BROWN, 0.545f, 0.271f, 0.075f);
this->m_mapColours[ SALMON ] = cGLColourHelper::cColour( "Salmon", SALMON, 0.980f, 0.502f, 0.447f);
this->m_mapColours[ SANDY_BROWN ] = cGLColourHelper::cColour( "SandyBrown", SANDY_BROWN, 0.957f, 0.643f, 0.376f);
this->m_mapColours[ SEA_GREEN ] = cGLColourHelper::cColour( "SeaGreen", SEA_GREEN, 0.180f, 0.545f, 0.341f);
this->m_mapColours[ SEA_SHELL ] = cGLColourHelper::cColour( "SeaShell", SEA_SHELL, 1.000f, 0.961f, 0.933f);
this->m_mapColours[ SIENNA ] = cGLColourHelper::cColour( "Sienna", SIENNA, 0.627f, 0.322f, 0.176f);
this->m_mapColours[ SILVER ] = cGLColourHelper::cColour( "Silver", SILVER, 0.753f, 0.753f, 0.753f);
this->m_mapColours[ SKY_BLUE ] = cGLColourHelper::cColour( "SkyBlue", SKY_BLUE, 0.529f, 0.808f, 0.922f);
this->m_mapColours[ SLATE_BLUE ] = cGLColourHelper::cColour( "SlateBlue", SLATE_BLUE, 0.416f, 0.353f, 0.804f);
this->m_mapColours[ SLATE_GRAY ] = cGLColourHelper::cColour( "SlateGray", SLATE_GRAY, 0.439f, 0.502f, 0.565f);
this->m_mapColours[ SNOW ] = cGLColourHelper::cColour( "Snow", SNOW, 1.000f, 0.980f, 0.980f);
this->m_mapColours[ SPRING_GREEN ] = cGLColourHelper::cColour( "SpringGreen", SPRING_GREEN, 0.000f, 1.000f, 0.498f);
this->m_mapColours[ STEEL_BLUE ] = cGLColourHelper::cColour( "SteelBlue", STEEL_BLUE, 0.275f, 0.510f, 0.706f);
this->m_mapColours[ TAN ] = cGLColourHelper::cColour( "Tan", TAN, 0.824f, 0.706f, 0.549f);
this->m_mapColours[ TEAL ] = cGLColourHelper::cColour( "Teal", TEAL, 0.000f, 0.502f, 0.502f);
this->m_mapColours[ THISTLE ] = cGLColourHelper::cColour( "Thistle", THISTLE, 0.847f, 0.749f, 0.847f);
this->m_mapColours[ TOMATO ] = cGLColourHelper::cColour( "Tomato", TOMATO, 1.000f, 0.388f, 0.278f);
this->m_mapColours[ TURQUOISE ] = cGLColourHelper::cColour( "Turquoise", TURQUOISE, 0.251f, 0.878f, 0.816f);
this->m_mapColours[ VIOLET ] = cGLColourHelper::cColour( "Violet", VIOLET, 0.933f, 0.510f, 0.933f);
this->m_mapColours[ WHEAT ] = cGLColourHelper::cColour( "Wheat", WHEAT, 0.961f, 0.871f, 0.702f);
this->m_mapColours[ WHITE ] = cGLColourHelper::cColour( "White", WHITE, 1.000f, 1.000f, 1.000f);
this->m_mapColours[ WHITE_SMOKE ] = cGLColourHelper::cColour( "WhiteSmoke", WHITE_SMOKE, 0.961f, 0.961f, 0.961f);
this->m_mapColours[ YELLOW ] = cGLColourHelper::cColour( "Yellow", YELLOW, 1.000f, 1.000f, 0.000f);
this->m_mapColours[ YELLOW_GREEN ] = cGLColourHelper::cColour( "YellowGreen", YELLOW_GREEN, 0.604f, 0.804f, 0.196f);
this->m_mapColourNameToEnum[ "AliceBlue" ] = ALICE_BLUE;
this->m_mapColourNameToEnum[ "AntiqueWhite" ] = ANTIQUE_WHITE;
this->m_mapColourNameToEnum[ "Aqua" ] = AQUA;
this->m_mapColourNameToEnum[ "Aquamarine" ] = AQUAMARINE;
this->m_mapColourNameToEnum[ "Azure" ] = AZURE;
this->m_mapColourNameToEnum[ "Beige" ] = BEIGE;
this->m_mapColourNameToEnum[ "Bisque" ] = BISQUE;
this->m_mapColourNameToEnum[ "Black" ] = BLACK;
this->m_mapColourNameToEnum[ "BlanchedAlmond" ] = BLANCHED_ALMOND;
this->m_mapColourNameToEnum[ "Blue" ] = BLUE;
this->m_mapColourNameToEnum[ "BlueViolet" ] = BLUE_VIOLET;
this->m_mapColourNameToEnum[ "Brown" ] = BROWN;
this->m_mapColourNameToEnum[ "BurlyWood" ] = BURLY_WOOD;
this->m_mapColourNameToEnum[ "CadetBlue" ] = CADET_BLUE;
this->m_mapColourNameToEnum[ "Chartreuse" ] = CHARTREUSE;
this->m_mapColourNameToEnum[ "Chocolate" ] = CHOCOLATE;
this->m_mapColourNameToEnum[ "Coral" ] = CORAL;
this->m_mapColourNameToEnum[ "CornflowerBlue" ] = CORNFLOWER_BLUE;
this->m_mapColourNameToEnum[ "Cornsilk" ] = CORNSILK;
this->m_mapColourNameToEnum[ "Crimson" ] = CRIMSON;
this->m_mapColourNameToEnum[ "Cyan" ] = CYAN;
this->m_mapColourNameToEnum[ "DarkBlue" ] = DARK_BLUE;
this->m_mapColourNameToEnum[ "DarkCyan" ] = DARK_CYAN;
this->m_mapColourNameToEnum[ "DarkGoldenRod" ] = DARK_GOLDEN_ROD;
this->m_mapColourNameToEnum[ "DarkGray" ] = DARK_GRAY;
this->m_mapColourNameToEnum[ "DarkGreen" ] = DARK_GREEN;
this->m_mapColourNameToEnum[ "DarkKhaki" ] = DARK_KHAKI;
this->m_mapColourNameToEnum[ "DarkMagenta" ] = DARK_MAGENTA;
this->m_mapColourNameToEnum[ "DarkOliveGreen" ] = DARK_OLIVE_GREEN;
this->m_mapColourNameToEnum[ "DarkOrange" ] = DARK_ORANGE;
this->m_mapColourNameToEnum[ "DarkOrchid" ] = DARK_ORCHID;
this->m_mapColourNameToEnum[ "DarkRed" ] = DARK_RED;
this->m_mapColourNameToEnum[ "DarkSalmon" ] = DARK_SALMON;
this->m_mapColourNameToEnum[ "DarkSeaGreen" ] = DARK_SEA_GREEN;
this->m_mapColourNameToEnum[ "DarkSlateBlue" ] = DARK_SLATE_BLUE;
this->m_mapColourNameToEnum[ "DarkSlateGray" ] = DARK_SLATE_GRAY;
this->m_mapColourNameToEnum[ "DarkTurquoise" ] = DARK_TURQUOISE;
this->m_mapColourNameToEnum[ "DarkViolet" ] = DARK_VIOLET;
this->m_mapColourNameToEnum[ "DeepPink" ] = DEEP_PINK;
this->m_mapColourNameToEnum[ "DeepSkyBlue" ] = DEEP_SKY_BLUE;
this->m_mapColourNameToEnum[ "DimGray" ] = DIM_GRAY;
this->m_mapColourNameToEnum[ "DodgerBlue" ] = DODGER_BLUE;
this->m_mapColourNameToEnum[ "FireBrick" ] = FIRE_BRICK;
this->m_mapColourNameToEnum[ "FloralWhite" ] = FLORAL_WHITE;
this->m_mapColourNameToEnum[ "ForestGreen" ] = FOREST_GREEN;
this->m_mapColourNameToEnum[ "Fuchsia" ] = FUCHSIA;
this->m_mapColourNameToEnum[ "Gainsboro" ] = GAINSBORO;
this->m_mapColourNameToEnum[ "GhostWhite" ] = GHOST_WHITE;
this->m_mapColourNameToEnum[ "Gold" ] = GOLD;
this->m_mapColourNameToEnum[ "GoldenRod" ] = GOLDEN_ROD;
this->m_mapColourNameToEnum[ "Gray" ] = GRAY;
this->m_mapColourNameToEnum[ "Green" ] = GREEN;
this->m_mapColourNameToEnum[ "GreenYellow" ] = GREEN_YELLOW;
this->m_mapColourNameToEnum[ "HoneyDew" ] = HONEY_DEW;
this->m_mapColourNameToEnum[ "HotPink" ] = HOT_PINK;
this->m_mapColourNameToEnum[ "IndianRed" ] = INDIAN_RED;
this->m_mapColourNameToEnum[ "Indigo" ] = INDIGO;
this->m_mapColourNameToEnum[ "Ivory" ] = IVORY;
this->m_mapColourNameToEnum[ "Khaki" ] = KHAKI;
this->m_mapColourNameToEnum[ "Lavender" ] = LAVENDER;
this->m_mapColourNameToEnum[ "LavenderBlush" ] = LAVENDER_BLUSH;
this->m_mapColourNameToEnum[ "LawnGreen" ] = LAWN_GREEN;
this->m_mapColourNameToEnum[ "LemonChiffon" ] = LEMON_CHIFFON;
this->m_mapColourNameToEnum[ "LightBlue" ] = LIGHT_BLUE;
this->m_mapColourNameToEnum[ "LightCoral" ] = LIGHT_CORAL;
this->m_mapColourNameToEnum[ "LightCyan" ] = LIGHT_CYAN;
this->m_mapColourNameToEnum[ "LightGoldenRodYellow" ] = LIGHT_GOLDEN_ROD_YELLOW;
this->m_mapColourNameToEnum[ "LightGray" ] = LIGHT_GRAY;
this->m_mapColourNameToEnum[ "LightGreen" ] = LIGHT_GREEN;
this->m_mapColourNameToEnum[ "LightPink" ] = LIGHT_PINK;
this->m_mapColourNameToEnum[ "LightSalmon" ] = LIGHT_SALMON;
this->m_mapColourNameToEnum[ "LightSeaGreen" ] = LIGHT_SEA_GREEN;
this->m_mapColourNameToEnum[ "LightSkyBlue" ] = LIGHT_SKY_BLUE;
this->m_mapColourNameToEnum[ "LightSlateGray" ] = LIGHT_SLATE_GRAY;
this->m_mapColourNameToEnum[ "LightSteelBlue" ] = LIGHT_STEEL_BLUE;
this->m_mapColourNameToEnum[ "LightYellow" ] = LIGHT_YELLOW;
this->m_mapColourNameToEnum[ "Lime" ] = LIME;
this->m_mapColourNameToEnum[ "LimeGreen" ] = LIME_GREEN;
this->m_mapColourNameToEnum[ "Linen" ] = LINEN;
this->m_mapColourNameToEnum[ "Magenta" ] = MAGENTA;
this->m_mapColourNameToEnum[ "Maroon" ] = MAROON;
this->m_mapColourNameToEnum[ "MediumAquaMarine" ] = MEDIUM_AQUA_MARINE;
this->m_mapColourNameToEnum[ "MediumBlue" ] = MEDIUM_BLUE;
this->m_mapColourNameToEnum[ "MediumOrchid" ] = MEDIUM_ORCHID;
this->m_mapColourNameToEnum[ "MediumPurple" ] = MEDIUM_PURPLE;
this->m_mapColourNameToEnum[ "MediumSeaGreen" ] = MEDIUM_SEA_GREEN;
this->m_mapColourNameToEnum[ "MediumSlateBlue" ] = MEDIUM_SLATE_BLUE;
this->m_mapColourNameToEnum[ "MediumSpringGreen" ] = MEDIUM_SPRING_GREEN;
this->m_mapColourNameToEnum[ "MediumTurquoise" ] = MEDIUM_TURQUOISE;
this->m_mapColourNameToEnum[ "MediumVioletRed" ] = MEDIUM_VIOLET_RED;
this->m_mapColourNameToEnum[ "MidnightBlue" ] = MIDNIGHT_BLUE;
this->m_mapColourNameToEnum[ "MintCream" ] = MINT_CREAM;
this->m_mapColourNameToEnum[ "MistyRose" ] = MISTY_ROSE;
this->m_mapColourNameToEnum[ "Moccasin" ] = MOCCASIN;
this->m_mapColourNameToEnum[ "NavajoWhite" ] = NAVAJO_WHITE;
this->m_mapColourNameToEnum[ "Navy" ] = NAVY;
this->m_mapColourNameToEnum[ "OldLace" ] = OLD_LACE;
this->m_mapColourNameToEnum[ "Olive" ] = OLIVE;
this->m_mapColourNameToEnum[ "OliveDrab" ] = OLIVE_DRAB;
this->m_mapColourNameToEnum[ "Orange" ] = ORANGE;
this->m_mapColourNameToEnum[ "OrangeRed" ] = ORANGE_RED;
this->m_mapColourNameToEnum[ "Orchid" ] = ORCHID;
this->m_mapColourNameToEnum[ "PaleGoldenRod" ] = PALE_GOLDEN_ROD;
this->m_mapColourNameToEnum[ "PaleGreen" ] = PALE_GREEN;
this->m_mapColourNameToEnum[ "PaleTurquoise" ] = PALE_TURQUOISE;
this->m_mapColourNameToEnum[ "PaleVioletRed" ] = PALE_VIOLET_RED;
this->m_mapColourNameToEnum[ "PapayaWhip" ] = PAPAYA_WHIP;
this->m_mapColourNameToEnum[ "PeachPuff" ] = PEACH_PUFF;
this->m_mapColourNameToEnum[ "Peru" ] = PERU;
this->m_mapColourNameToEnum[ "Pink" ] = PINK;
this->m_mapColourNameToEnum[ "Plum" ] = PLUM;
this->m_mapColourNameToEnum[ "PowderBlue" ] = POWDER_BLUE;
this->m_mapColourNameToEnum[ "Purple" ] = PURPLE;
this->m_mapColourNameToEnum[ "RebeccaPurple" ] = REBECCA_PURPLE;
this->m_mapColourNameToEnum[ "Red" ] = RED;
this->m_mapColourNameToEnum[ "RosyBrown" ] = ROSY_BROWN;
this->m_mapColourNameToEnum[ "RoyalBlue" ] = ROYAL_BLUE;
this->m_mapColourNameToEnum[ "SaddleBrown" ] = SADDLE_BROWN;
this->m_mapColourNameToEnum[ "Salmon" ] = SALMON;
this->m_mapColourNameToEnum[ "SandyBrown" ] = SANDY_BROWN;
this->m_mapColourNameToEnum[ "SeaGreen" ] = SEA_GREEN;
this->m_mapColourNameToEnum[ "SeaShell" ] = SEA_SHELL;
this->m_mapColourNameToEnum[ "Sienna" ] = SIENNA;
this->m_mapColourNameToEnum[ "Silver" ] = SILVER;
this->m_mapColourNameToEnum[ "SkyBlue" ] = SKY_BLUE;
this->m_mapColourNameToEnum[ "SlateBlue" ] = SLATE_BLUE;
this->m_mapColourNameToEnum[ "SlateGray" ] = SLATE_GRAY;
this->m_mapColourNameToEnum[ "Snow" ] = SNOW;
this->m_mapColourNameToEnum[ "SpringGreen" ] = SPRING_GREEN;
this->m_mapColourNameToEnum[ "SteelBlue" ] = STEEL_BLUE;
this->m_mapColourNameToEnum[ "Tan" ] = TAN;
this->m_mapColourNameToEnum[ "Teal" ] = TEAL;
this->m_mapColourNameToEnum[ "Thistle" ] = THISTLE;
this->m_mapColourNameToEnum[ "Tomato" ] = TOMATO;
this->m_mapColourNameToEnum[ "Turquoise" ] = TURQUOISE;
this->m_mapColourNameToEnum[ "Violet" ] = VIOLET;
this->m_mapColourNameToEnum[ "Wheat" ] = WHEAT;
this->m_mapColourNameToEnum[ "White" ] = WHITE;
this->m_mapColourNameToEnum[ "WhiteSmoke" ] = WHITE_SMOKE;
this->m_mapColourNameToEnum[ "Yellow" ] = YELLOW;
this->m_mapColourNameToEnum[ "YellowGreen" ] = YELLOW_GREEN;
// Generate the random lookup
for ( std::map< cGLColourHelper::enumColours, cGLColourHelper::cColour >::iterator itColour = this->m_mapColours.begin();
itColour != this->m_mapColours.end(); itColour++ )
{
this->m_vecRandomColourEnumLookup.push_back( itColour->first );
}
// Scramble them
std::random_shuffle( this->m_vecRandomColourEnumLookup.begin(), this->m_vecRandomColourEnumLookup.begin() );
// Start the 'next' loop up at the start of the vector
this->m_nextRandomIndex = 0;
return;
}
cGLColourHelper::enumColours cGLColourHelper::getRandomColourEnum(void)
{
cGLColourHelper::enumColours randColourEnum = this->m_vecRandomColourEnumLookup[this->m_nextRandomIndex];
this->m_nextRandomIndex++;
if ( this->m_nextRandomIndex >= this->m_vecRandomColourEnumLookup.size() )
{
this->m_nextRandomIndex = 0;
}
return randColourEnum;
}
cGLColourHelper::cColour cGLColourHelper::getRandomColour(void)
{
cColour randColour;
randColour.rgb.r = this->getRand(0.0f, 1.0f);
randColour.rgb.g = this->getRand(0.0f, 1.0f);
randColour.rgb.b = this->getRand(0.0f, 1.0f);
randColour.enumName = CUSTOM;
return randColour;
}
glm::vec3 cGLColourHelper::getRandomColourRGB(void)
{
return this->getRandomColour().rgb;
}
void cGLColourHelper::ShuffleRandomColours(void)
{
std::random_shuffle( this->m_vecRandomColourEnumLookup.begin(), this->m_vecRandomColourEnumLookup.begin() );
return;
}
glm::vec3 cGLColourHelper::getColourRGB( cGLColourHelper::enumColours colourEnum )
{
cColour theColour = this->getColour( colourEnum );
return theColour.rgb;
}
glm::vec3 cGLColourHelper::getColourRGB( std::string colourName )
{
cGLColourHelper::cColour returnColour = this->getColour( colourName );
return returnColour.rgb;
}
cGLColourHelper::cColour cGLColourHelper::getColour( std::string colourName )
{
cGLColourHelper::enumColours colourEnum = this->getColourEnumFromName( colourName );
if ( colourEnum == cGLColourHelper::UNKNOWN )
{ // Didn't find it
return this->m_getUnknownColour();
}
// Look up the colour
cGLColourHelper::cColour returnColour = this->getColour( colourEnum );
return returnColour;
}
cGLColourHelper::cColour cGLColourHelper::getColour( cGLColourHelper::enumColours colourEnum )
{
//
std::map< cGLColourHelper::enumColours, cGLColourHelper::cColour >::iterator itColour = m_mapColours.find( colourEnum );
if ( itColour == this->m_mapColours.end() )
{ // Didn't find a match (should "never" happen as it's an enum... but you could pass an int, I suppose
return this->m_getUnknownColour();
}
// Found it
return itColour->second;
}
cGLColourHelper::cColour cGLColourHelper::m_getUnknownColour(void)
{
cGLColourHelper::cColour unknownColour = cGLColourHelper::cColour();
unknownColour.enumName = UNKNOWN;
unknownColour.name = "Unknown";
unknownColour.rgb = glm::vec3( 0.0f, 0.0f, 0.0f );
return unknownColour;
}
std::string cGLColourHelper::getColourNameFromEnum( cGLColourHelper::enumColours colourEnum )
{
cGLColourHelper::cColour returnColour = this->getColour( colourEnum );
return returnColour.name;
}
cGLColourHelper::enumColours cGLColourHelper::getColourEnumFromName( std::string sColour )
{
std::map< std::string, cGLColourHelper::enumColours >::iterator itColour = this->m_mapColourNameToEnum.find( sColour );
if ( itColour == this->m_mapColourNameToEnum.end() )
{ // Didn't find it
return cGLColourHelper::UNKNOWN;
}
return itColour->second;
}
| [
"niral.eagle100@gmail.com"
] | niral.eagle100@gmail.com |
c929d3ea98a71c12d07ae37cd8353cf42bbde8b5 | 03d3231478373089a3de04db162f61b79a388fd3 | /l2detect/ConfigIni.h | ed6c015d21824129fa479d4b9209630775070b85 | [] | no_license | minlexx/l2-unlegits | f4b0e9d70afe2a0a26f81daa16123eb2fe31cc13 | fc189ca35edf14439a5eeac81359b30112496b80 | refs/heads/master | 2021-01-17T05:35:09.738039 | 2015-06-28T09:16:13 | 2015-06-28T09:16:13 | 38,192,499 | 6 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,516 | h | #ifndef CONFIGINI_H_
#define CONFIGINI_H_
class CConfig
{
public:
CConfig();
virtual ~CConfig();
public:
bool ReadConfig( const char *szConfigFileName );
bool ReadConfig( const wchar_t *szConfigFilename );
bool SaveConfig();
void SetDefault();
protected:
void _initNull();
public:
char szCfgFileName[256];
bool isInGameMode;
int L2_version;
int L2_client_version;
// Listen port setup
char FakeListenLoginIP[32];
int FakeListenLoginPort;
char FakeListenGameIP[32];
int FakeListenGamePort;
// Forward connection to
char RealLoginServerIP[128];
int RealLoginServerPort;
// Catch game server traffic
//int PlayGameServerNo; // removed!
char ForceGameServerIP[32];
int ForceGameServerPort;
int IngameGameServerPort;
// Logging setup
int LogGamePackets;
char LogGameFileNamePrefix[128];
int WarnUnknownPacketsToStdout;
int DumpUnknownToStdout;
int WarnMessageLevel;
// hacks
int EnableModifyGameTraffic; // enable or disable game protocol-level hacks
int OverrideGameProtocolVersion;
int ReplyL2JGameGuardQuery;
int GraciaEpilogueProtocol_148_hacks;
int TeonPvP_hacks;
// L2Walker fixes
int L2Walker_DropRequestGMList;
int L2Walker_FixMoveBackwardToLocation;
int L2Walker_FixChangeWaitType2;
int L2Walker_InjectStatusUpdate;
// tweaks
int ThreadProirityRaiseEnable;
// invis GM detection
int InvisGMTrackEnable;
int InvisGMSpeed;
};
#endif /* CONFIGINI_H_ */
| [
"alexey.min@gmail.com"
] | alexey.min@gmail.com |
2da1706a3ff86cb174a36160d72ba4a9c27a937c | fd944c61dc1a10b7b2cacaccc32d94af0b8c7a0a | /ofxUI/Old/simpleButton.h | 4cfe0be57e29b768cdcdee5220b7d3d4a6d1c987 | [] | no_license | vtron/ofxVtron | 6878af2090c4d4053c2b466e0b4988e409af253b | 23d1c5641b8b7ea8b43b99ed07dfd77c201a8e6a | refs/heads/master | 2016-09-06T16:06:27.322694 | 2011-03-02T02:40:17 | 2011-03-02T02:40:17 | 1,428,337 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 688 | h | /*
* test.h
* openFrameworks
*
* Created by StephenVarga on 10/6/09.
* Copyright 2009. All rights reserved.
*
*/
#ifndef _simpleButton
#define _simpleButton
#include "uiObserver.h"
#include "ofMain.h"
class uiObserver;
class simpleButton {
public:
simpleButton();
virtual ~simpleButton();
uiObserver* ui;
virtual void setup();
virtual void update();
virtual void draw();
virtual void mouseMoved(int x, int y);
virtual void mouseDragged(int x, int y, int button);
virtual void mousePressed(int x, int y, int button);
virtual void mouseReleased(int x, int y, int button);
int x;
int y;
int width;
int height;
bool bDraw;
};
#endif | [
"steve@vargatron.com"
] | steve@vargatron.com |
81b9b48ef557ff8d7424698e7aed8620600efc37 | 16a753af9647c88408e7854dd04cef1a6183e2c4 | /CC3k/src/things/character/pc/decorator/wdDecorator.cc | 8f8c59b0cadb2a3fee9063b181a84b34f913acbf | [] | no_license | pfryerda/project-IMDD | a8c88f15ed43c55b34a1439b777686a347adc757 | e2e56ed78043f148d799fd48bba1e318b158e932 | refs/heads/master | 2016-09-06T18:18:54.252083 | 2013-12-16T17:04:12 | 2013-12-16T17:04:12 | 14,460,137 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 218 | cc | #include "wdDecorator.h"
using namespace std;
wdDecorator::wdDecorator(PC* pc):Decorator(pc) {}
unsigned int wdDecorator::getDef() const {
if ((pc->getDef() - 5) < 0) return 0;
else return (pc->getDef() - 5);
}
| [
"Luke.Michael.Brown@gmail.com"
] | Luke.Michael.Brown@gmail.com |
0b3ab25185408b8541ce311244a78afe64ff5a00 | e3ef6ff25d8322cf479210846ebc677702e8edab | /necrodancer/weapon_bow_basic.h | cfab545dcbf9e9fccc2f560339fed6af748a0163 | [] | no_license | dongnamyoooooooooon/yoOoOoOon | 885dbfe0c982ddc3c79eca8b129a2b11bbfd53c5 | 8a1e84a053bcf752532fb102d54fe5d810ce255b | refs/heads/master | 2020-05-01T14:05:27.437184 | 2019-04-09T08:44:05 | 2019-04-09T08:44:05 | 177,509,953 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 331 | h | #pragma once
#include "item.h"
class weapon_bow_basic : public item
{
private:
bool _isLong;
public:
weapon_bow_basic();
~weapon_bow_basic();
HRESULT init(string imgName, int idxX, int idxY, ITEM_TYPE type);
void release();
void update();
void render();
void drawHint();
bool useItem(int idxX, int idxY, int way);
};
| [
"46731689+dongnamyoooooooooon@users.noreply.github.com"
] | 46731689+dongnamyoooooooooon@users.noreply.github.com |
93d47b0ab338a83bede886ce8f16dc0362f3a8b0 | 4a64577b9c517d876047ea7d16a8fd75c1c30295 | /JadenCase 문자열 만들기.cpp | 050bf8e365207cd7c3a37f4a9ef8ee19fc757474 | [] | no_license | Hyeon97/Problem_solve | 1f2ddef70281b511d8cfbf02a05a2b04346bf790 | 5b035852b79136b7720bd9d86ac65a6e249580bc | refs/heads/master | 2023-06-25T10:57:56.843495 | 2021-07-29T01:03:59 | 2021-07-29T01:03:59 | 289,007,224 | 1 | 0 | null | null | null | null | UHC | C++ | false | false | 702 | cpp | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
string solution(string s) {
string answer = "";
for (int i = 0; i < s.length(); i++) {
if (i == 0) {//문장 맨 첫 글자
if ('a' <= s[i] && s[i] <= 'z') {
answer += (s[i] - 32);
}
else answer += s[i];
}
else {
if (s[i - 1] == ' ' && 'a' <= s[i] && s[i] <= 'z') answer += (s[i] - 32);
else if (s[i - 1] != ' ' && 'A' <= s[i] && s[i] <= 'Z') {
answer += (s[i] + 32);
}
else answer += s[i];
}
}
return answer;
}
int main(void) {
ios_base::sync_with_stdio(0); cin.tie(0);
solution("a 3Sdf ffTt Afftt fftt3133Sdf");
return 0;
} | [
"noreply@github.com"
] | Hyeon97.noreply@github.com |
f982bc8553cb3a0e221830c9b0527e93bff6b77c | 784f9eac2b9c8f3e604487a5b8127be1bd55f1ce | /evenodd.cpp | c262267fbf3a366ba1b8bcdb846ab8c08ba6c172 | [] | no_license | NikitaVerma26/Programming-Of-CPP | 36013df885f506d024ad4dedfee5ae843801c196 | 727bfc21af246816cd1ab67ab45dcaabe4bb6292 | refs/heads/main | 2023-08-30T15:21:31.871095 | 2021-11-10T05:02:26 | 2021-11-10T05:02:26 | 426,490,005 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 277 | cpp | #include<iostream>
using namespace std;
int main()
{
int num;
cout<<"Please enter a number to check whether it is even or odd : "<<endl;
cin>>num;
if(num%2==0)
cout<<"number is even";
else
cout<<"number is odd";
return 0;
}
| [
"noreply@github.com"
] | NikitaVerma26.noreply@github.com |
27bf2721eaa69963019d393585c09f24d4391a6d | a36d39f47661e70148ad5b068baddd26f2d6c68a | /UVMProject/methodCallStack.cpp | cbefea99ee7e39f228f80de87898172ede31ceb7 | [] | no_license | mrthetkhine/UVMForMac | d5203f0de3baf2e7acc9ed431d2e01d3f99c2fc1 | 866baa644f9c1ae111de311b348abb25dd184f51 | refs/heads/master | 2020-05-30T23:22:20.078924 | 2019-06-03T13:57:19 | 2019-06-03T13:57:19 | 190,015,221 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,500 | cpp | #ifndef uvm_h
#include "uvm.h"
#endif
#ifndef methodCallStack_h
#include "methodCallStack.h"
#endif
#include <iostream>
using namespace std;
MethodCallStack* MethodCallStack::methodCallStack = NULL;
MethodCallStack::MethodCallStack()
{
for(int i=0; i< maxNoOfFrame;i++)
{
frames[i] = NULL;
}
top = -1;
currentFrame = NULL;
}
MethodCallStack * MethodCallStack::getMethodCallStack()
{
if( methodCallStack == NULL)
{
methodCallStack = new MethodCallStack();
}
return methodCallStack;
}
MethodFrame* MethodCallStack::getCurrentFrame()
{
///cout<<"ACCESSING "<<currentFrame->theClass->className<<" "<<currentFrame->constantPool<<endl;
return currentFrame;
}
void MethodCallStack::pushAFrame(MethodFrame *newFrame)
{
frames[++top]= newFrame;
currentFrame = newFrame;
///cout<<"PUSH top "<<top<<" "<<newFrame->theClass->className<<" of method "<<newFrame->method->methodName<<" "<<newFrame->constantPool<<endl;
}
void MethodCallStack::popAFrame()
{
///cout<<"POP top "<<top;
top--;
if(top < 0)
{
currentFrame = NULL;
}
else
{
///cout<<" "<< currentFrame->theClass->className<<" of method "<<currentFrame->method->methodName<<" "<< currentFrame->constantPool<<endl;
currentFrame = frames[top];
///cout<<"CURRENT Class "<<currentFrame->theClass->className<<"top "<<top<<endl;
}
}
| [
"mrthetkhine@gmail.com"
] | mrthetkhine@gmail.com |
2d6f9a47d6b8f3560ac1d702577d3920ce83d93c | 711d7074da3939f11b7f56e359ed37ec42795133 | /test/VSidoService/test_gpio.cpp | 38e076973e6c39b4036c70c646c10cb25d051015 | [
"BSD-3-Clause"
] | permissive | Asratec/VSidoConnServer | 6ff9ad346721d6fd9e22fb3b9fe9947bea5241c6 | a465b87e1843b8945b14440c9bd407c562bb3439 | refs/heads/master | 2020-04-25T18:12:34.037523 | 2016-08-12T03:00:57 | 2016-08-12T03:00:57 | 31,400,816 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,959 | cpp | /*
Copyright (c) 2015, Asratec Corp.
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 VSidoConnServer nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "cmd_gpio.hpp"
#include "cmd_parser.hpp"
using namespace VSido;
#include <boost/test/unit_test.hpp>
#include <boost/test/unit_test.hpp>
#include <typeinfo>
#include "test_dump.hpp"
#include "test_uart.hpp"
BOOST_AUTO_TEST_CASE(test_case_GpioJSONRequest_0)
{
JSONRequestParser parser("{\"cmd\":\"SetGPIOValue\",\"gpio\":[{\"port\":4,\"val\":1},{\"port\":5,\"val\":0},{\"port\":6,\"val\":0},{\"port\":7,\"val\":1}]}}");
/// uart data
list<unsigned char> uartExpectedSend =
{
4,1,
5,0,
6,0,
7,1,
};
GEN_COMMON_SEND_UART('i');
auto request = parser.create();
DUMP_VAR(typeid(request).name());
auto _request = std::dynamic_pointer_cast<GpioJSONRequest>(request);
DUMP_VAR(typeid(_request).name());
BOOST_CHECK(nullptr != _request);
DO_ACK_GOOD_CHECK();
}
BOOST_AUTO_TEST_CASE(test_case_GpioJSONRequest_1)
{
JSONRequestParser parser("{\"cmd\":\"SetGPIOConfig\",\"gpio\":[{\"port\":4,\"val\":0},{\"port\":5,\"val\":1},{\"port\":6,\"val\":1},{\"port\":7,\"val\":0}]}}");
/// uart data
list<unsigned char> uartExpectedSend =
{
4,0,
5,1,
6,1,
7,0,
};
GEN_COMMON_SEND_UART('i');
auto request = parser.create();
DUMP_VAR(typeid(request).name());
auto _request = std::dynamic_pointer_cast<GpioJSONRequest>(request);
DUMP_VAR(typeid(_request).name());
BOOST_CHECK(nullptr != _request);
DO_ACK_GOOD_CHECK();
}
| [
"yma@asratec.co.jp"
] | yma@asratec.co.jp |
90ce9e138bf5805d32267874f2b0a1004a23b17c | 48eb7edd9acb951db2b7b088977cf56ebac5987c | /DIC_Labor_1.2/src/main.cpp | 3b9461df427a5d9bea48908c6bdef100bdf397be | [] | no_license | Weesy1712/platformIoProjects | 3cb6f504fbe2e60ee65bebc1bc1b2e045a352622 | 1f43d0ba272dc0dc2a6548ea8ff145f6bd764c27 | refs/heads/main | 2023-02-02T19:55:11.933045 | 2020-12-17T15:04:52 | 2020-12-17T15:04:52 | 322,327,786 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 930 | cpp | #include <Arduino.h>
int ledr = 3;
void setup() {
Serial.begin(9600);
pinMode(ledr, OUTPUT);
Serial.println("Zum Steuern müssen Sie in diesem Format eingeben!" );
Serial.println("Zum Einschalten: ");
Serial.println("switch.on");
Serial.println("switch.off");
}
void loop() {
int fadingState;
if(Serial.available()){
if(Serial.read() == "switch.on"){
fadingState = 1;
}
if(Serial.read() == "h"){
fadingState = 0;
}
}
if(fadingState == 1){
fading();
}
}
int millis2;
void fading(){
for (int i = 0; i <= 255; i++)
{millis2 = millis()+ 5;
//delay(5);
if(millis()>= millis2){
analogWrite(ledr,i);
}
}
for (int i = 255; i >= 0; i--)
{
//delay(5);
millis2 = millis()+ 5;
//delay(5);
if(millis()>= millis2){
analogWrite(ledr,i);
}
}
}
| [
"karim.tayari@htl-klu.at"
] | karim.tayari@htl-klu.at |
9e83226a7107d5e67e9129a522871df559e438b1 | ff4055860f0adf927a9401e4019b771d0dfc2d02 | /animaMCMEstimation/animaMCMEstimationPlugin.cpp | 32c2d5bde3d5896e3810a34ecd53daf74883956e | [] | no_license | medInria/medInria-visages | 2b02695f673542a460791ed99f9f93200e3c1bad | a80e69d846c59eb667ad3def8fe42e34104b3503 | refs/heads/master | 2023-01-18T19:13:38.521506 | 2020-11-27T10:01:17 | 2020-11-27T10:01:17 | 9,451,653 | 0 | 2 | null | 2020-11-27T10:01:19 | 2013-04-15T15:20:44 | C++ | UTF-8 | C++ | false | false | 833 | cpp | #include <animaMCMEstimationPlugin.h>
#include <medCore.h>
#include <medWidgets.h>
#include <animaMCMEstimationProcess.h>
#include <animaMCMEstimationProcessPresenter.h>
void animaMCMEstimationPlugin::initialize(void)
{
medCore::diffusionModelEstimation::pluginFactory().record(animaMCMEstimationProcess::staticMetaObject.className(),
animaMCMEstimationProcessCreator);
medWidgets::diffusionModelEstimation::presenterFactory().record(animaMCMEstimationProcess::staticMetaObject.className(),
animaMCMEstimationProcessPresenterCreator);
}
void animaMCMEstimationPlugin::uninitialize(void)
{
}
DTK_DEFINE_PLUGIN(animaMCMEstimationProcess)
DTK_DEFINE_PLUGIN(animaMCMEstimationProcessPresenter)
| [
"olivier.commowick@inria.fr"
] | olivier.commowick@inria.fr |
895c81d739b8ff1d1a2f9c7c81697fdd002cabc9 | fc9509b72acc753eaae129a1fcb27cd9f8ee56b0 | /zhengtu/libscenesserver/Trade.cpp | fd6c3b502901013c0e9abf5df6fdcc8d6f873e79 | [] | no_license | edolphin-ydf/hydzhengtu | 25df5567226c5b7533e24631ae3d641ee0182aa9 | 724601751c00702438ffb93c1411226ae21f46a0 | refs/heads/master | 2020-12-31T03:25:48.625000 | 2012-10-24T10:58:00 | 2012-10-24T10:58:00 | 49,243,199 | 2 | 1 | null | null | null | null | GB18030 | C++ | false | false | 69,523 | cpp | #include <zebra/ScenesServer.h>
PrivateStore::PrivateStore() : _step(NONE)
{
}
PrivateStore::~PrivateStore()
{
clear();
_step = NONE;
}
void PrivateStore::step(STEP step_,SceneUser *pUser)
{
_step = step_;
if (_step == BEGIN) {
pUser->setUState(Cmd::USTATE_SITDOWN);
pUser->setUState(Cmd::USTATE_PRIVATE_STORE);
}
if (_step == NONE) {
pUser->clearUState(Cmd::USTATE_PRIVATE_STORE);
pUser->clearUState(Cmd::USTATE_SITDOWN);
clear();
}
}
PrivateStore::STEP PrivateStore::step()
{
return _step;
}
void PrivateStore::clear()
{
_items.clear();
}
void PrivateStore::add(zObject* ob,DWORD money,BYTE x,BYTE y)
{
_items[ob->data.qwThisID] = SellInfo(ob,money,x,y);
}
void PrivateStore::remove(DWORD id)
{
_items.erase(id);
}
void PrivateStore::show(SceneUser* target)
{
#if 0
std::map<DWORD,SellInfo>::iterator it = _items.begin();
for ( ; it!=_items.end(); ++it) {
Cmd::stAddObjectSellUserCmd cmd;
cmd.object = (*it).second.object()->data;
cmd.price = (*it).second.money();
cmd.x = (*it).second.x();
cmd.y = (*it).second.y();
target->sendCmdToMe(&cmd,sizeof(cmd));
}
#else
using namespace Cmd;
std::map<DWORD,SellInfo>::iterator it = _items.begin();
char buffer[zSocket::MAX_USERDATASIZE];
stAddObjectSellListUserCmd *cmd = (stAddObjectSellListUserCmd *)buffer;
constructInPlace(cmd);
for ( ; it!=_items.end(); ++it) {
if (sizeof(stAddObjectSellListUserCmd) + (cmd->num + 1) * sizeof(cmd->list[0])>= zSocket::MAX_USERDATASIZE)
{
target->sendCmdToMe(cmd,sizeof(stAddObjectSellListUserCmd) + cmd->num * sizeof(cmd->list[0]));
cmd->num = 0;
}
cmd->list[cmd->num].object = (*it).second.object()->data;
cmd->list[cmd->num].price = (*it).second.money();
cmd->list[cmd->num].x = (*it).second.x();
cmd->list[cmd->num].y = (*it).second.y();
cmd->num ++;
}
if (cmd->num)
{
target->sendCmdToMe(cmd,sizeof(Cmd::stAddObjectSellListUserCmd) + cmd->num * sizeof(cmd->list[0]));
cmd->num = 0;
}
#endif
Cmd::stSellTradeUserCmd ret;
target->sendCmdToMe(&ret,sizeof(ret));
}
PrivateStore::SellInfo* PrivateStore::sell_ob(DWORD id)
{
std::map<DWORD,SellInfo>::iterator it = _items.find(id);
if (it != _items.end()) {
return &(it->second);
}
return NULL;
}
TradeOrder::TradeOrder(SceneUser* owner) : _me(owner),_target(NULL),_targetid(0),_money(0)
{
finish();
}
TradeOrder::~TradeOrder()
{
reset();
}
void TradeOrder::reset()
{
SceneUser *pUser=_me->scene->getUserByID(_targetid);
if (pUser && (pUser == _target) && _target->tradeorder.target() == _me)
{
_target->tradeorder.finish();
Cmd::stCancelTradeUserCmd cancel;
cancel.dwUserTempID = _target->tempid;
_target->sendCmdToMe(&cancel,sizeof(cancel));
Channel::sendSys(_target,Cmd::INFO_TYPE_FAIL,"交易被取消");
Zebra::logger->info("[交易:玩家<------>玩家]%s取消与%s的交易",_me->name,_target->name);
}
else
{
if (_targetid)
{
Zebra::logger->debug("[交易:玩家<------>玩家]%s取消与%d的交易,但这个人已经不在了",_me->name,_targetid);
}
}
}
void TradeOrder::cancel()
{
// Channel::sendSys(_me,Cmd::INFO_TYPE_FAIL,"交易被取消");
Cmd::stCancelTradeUserCmd cancel;
cancel.dwUserTempID = _me->tempid;
_me->sendCmdToMe(&cancel,sizeof(cancel));
reset();
finish();
}
SceneUser* TradeOrder::target() const
{
return _target;
}
bool TradeOrder::can_trade()
{
if (_target->packs.uom.space(_target) < (int)_items.size() ||!_me->packs.checkMoney( _money) ) {
return false;
}
return true;
}
void TradeOrder::trade()
{
bool changed = false;
for (std::map<DWORD,zObject*>::iterator it=_items.begin(); it!=_items.end(); ++it) {
_me->packs.removeObject(it->second,false,false); //not delete and not notify
if (it->second->data.pos.loc() == Cmd::OBJECTCELLTYPE_EQUIP) {
changed = true;
}
it->second->data.exp = 0;
/*
it->second->data.pos.dwLocation = Cmd::OBJECTCELLTYPE_COMMON;
if (_target->packsaddObject(it->second,true)) {
*/
if (_target->packs.addObject(it->second,true,AUTO_PACK)) {
zObject::logger(it->second->createid,it->second->data.qwThisID,it->second->data.strName,it->second->data.dwNum,it->second->data.dwNum,0,_me->id,_me->name,_target->id,_target->name,"trade_ok",NULL,0,0);
Zebra::logger->info("[交易:玩家<------>玩家]用户%s交易%s给%s成功",_me->name,it->second->data.strName,_target->name);
Cmd::stAddObjectPropertyUserCmd ret;
ret.byActionType = Cmd::EQUIPACTION_OBTAIN;
bcopy(&it->second->data,&ret.object,sizeof(ret.object),sizeof(ret.object));
_target->sendCmdToMe(&ret,sizeof(ret));
}else {
zObject::logger(it->second->createid,it->second->data.qwThisID,it->second->data.strName,it->second->data.dwNum,0,0,_me->id,_me->name,_target->id,_target->name,"trade_err",it->second->base,it->second->data.kind,it->second->data.upgrade);
Zebra::logger->info("[交易:玩家<------>玩家]用户%s交易%s给%s失败",_me->name,it->second->data.strName,_target->name);
}
}
if (changed) {
_me->packs.equip.calcAll();
_me->setupCharBase();
Cmd::stMainUserDataUserCmd userinfo;
_me->full_t_MainUserData(userinfo.data);
_me->sendCmdToMe(&userinfo,sizeof(userinfo));
_me->sendMeToNine();
}
/*
zObject* m_gold = _me->packs.getGold();
m_gold->data.dwNum -= _money;
if (_money) {
zObject* t_gold = _target->packs.getGold();
if (t_gold->base->maxnum - t_gold->data.dwNum > (DWORD)_money) {
t_gold->data.dwNum += _money;
}else {
t_gold->data.dwNum = t_gold->base->maxnum;
}
}
*/
if (_money) {
_me->packs.removeMoney(_money,"交易");
_target->packs.addMoney(_money,"交易");
Zebra::logger->info("[交易:玩家<------>玩家]用户%s交易银子%d给%s",_me->name,_money,_target->name);
}
}
bool TradeOrder::canRequest()
{
return (_target == NULL);
}
void TradeOrder::ready(SceneUser* target)
{
_target = target;
_targetid = target->id;
}
bool TradeOrder::canAnswer()
{
return (_target!=NULL && !begined);
}
void TradeOrder::begin()
{
begined = true;
}
bool TradeOrder::hasBegin()
{
return begined;
}
bool TradeOrder::commit()
{
if (begined)
{
commited = true;
return true;
}
return false;
}
void TradeOrder::rollback()
{
commited = false;
}
bool TradeOrder::hasCommit()
{
return commited;
}
void TradeOrder::finish()
{
if (_me->name[0] && _targetid) Zebra::logger->info("[交易:玩家<------>玩家]%s的交易状态完成",_me->name);
_targetid=0;
_target = NULL;
_money = 0;
commited = false;
lastmove= 0;
begined = false;
clear();
}
void TradeOrder::clear()
{
_items.clear();
}
void TradeOrder::add_money(DWORD money)
{
_money = money;
Zebra::logger->info("[交易:玩家<------>玩家]用户%s对%s更改交易银子数量(%d)",_me->name,_target->name,money);
}
void TradeOrder::add(zObject* ob)
{
_items[ob->data.qwThisID] = ob;
Zebra::logger->info("[交易:玩家<------>玩家]用户%s对%s添加交易物品%s(%d)",_me->name,_target->name,ob->data.strName,ob->data.qwThisID);
}
void TradeOrder::remove(DWORD id)
{
std::map<DWORD,zObject*>::iterator it = _items.find(id);
if (it != _items.end()) {
Zebra::logger->info("[交易:玩家<------>玩家]用户%s对%s删除交易物品%s(%d)",_me->name,_target->name,it->second->data.strName,it->second->data.qwThisID);
_items.erase(it);
}
}
bool TradeOrder::in_trade(zObject* ob) const
{
std::map<DWORD,zObject*>::const_iterator it = _items.find(ob->data.qwThisID);
return it != _items.end();
}
#define ISPROPERTY(value) if (ob->data.value!=0) ++num
WORD get_prop_num(zObject* ob)
{
WORD num = 0;
ISPROPERTY(fivepoint);
ISPROPERTY(maxmp);
ISPROPERTY(mvspeed);
ISPROPERTY(bang);
ISPROPERTY(hpr);
ISPROPERTY(mpr);
ISPROPERTY(spr);
ISPROPERTY(akspeed);
ISPROPERTY(pdam);
ISPROPERTY(pdef);
ISPROPERTY(mdam);
ISPROPERTY(mdef);
ISPROPERTY(atrating);
ISPROPERTY(akdodge);
ISPROPERTY(poisondef);
ISPROPERTY(lulldef);
ISPROPERTY(reeldef);
ISPROPERTY(evildef);
ISPROPERTY(bitedef);
ISPROPERTY(chaosdef);
ISPROPERTY(colddef);
ISPROPERTY(petrifydef);
ISPROPERTY(blinddef);
ISPROPERTY(stabledef);
ISPROPERTY(slowdef);
ISPROPERTY(luredef);
ISPROPERTY(skill[0].point);
ISPROPERTY(skills.point);
ISPROPERTY(holy);
ISPROPERTY(hpleech.odds);
ISPROPERTY(mpleech.odds);
ISPROPERTY(hptomp);
ISPROPERTY(dhpp);
ISPROPERTY(dmpp);
ISPROPERTY(incgold);
ISPROPERTY(doublexp);
ISPROPERTY(mf);
ISPROPERTY(dpdam);
ISPROPERTY(dmdam);
ISPROPERTY(bdam);
ISPROPERTY(rdam);
ISPROPERTY(ignoredef);
ISPROPERTY(poison);
ISPROPERTY(lull);
ISPROPERTY(reel);
ISPROPERTY(evil);
ISPROPERTY(bite);
ISPROPERTY(chaos);
ISPROPERTY(cold);
ISPROPERTY(petrify);
ISPROPERTY(blind);
ISPROPERTY(stable);
ISPROPERTY(slow);
ISPROPERTY(lure);
return num;
}
float get_kind_bonus(BYTE kind)
{
float bonus = 0.0f;
if (kind & 0x4)
{
bonus = 2.0f;
}
else if (kind & 0x2)
{
bonus = 1.5f;
}
else if (kind & 0x1)
{
bonus = 1.2f;
}
else
bonus = 1.0f;
return bonus;
}
float get_sell_dur_rate(zObject* ob)
{
if (!ob->data.maxdur) return 1;
return (float)((ob->data.dur+49)/50) / ((ob->base->durability+49)/50) ;
}
float get_repair_dur_rate(zObject* ob)
{
if (!ob->data.maxdur) return 1;
float temp=(float)(((ob->data.maxdur - ob->data.dur)+49)/50) / ((ob->base->durability+49)/50) ;
//Zebra::logger->debug("get_repair_dur_rate=%f",temp);
return temp;
return (float)(((ob->data.maxdur - ob->data.dur)+49)/50) / ((ob->base->durability+49)/50) ;
//return 1 - get_sell_dur_rate(ob);
}
float get_sell_price(zObject* ob)
{
float money = 0;
if (!ob) return money;
money = (0.25*ob->base->price*(1+get_prop_num(ob)*0.1f)*get_kind_bonus(ob->data.kind));
if (money > 0 ) money += 1;
//Zebra::logger->debug("get_sell_price=%f",money);
return money;
}
DWORD get_sell_price_by_dur(zObject* ob)
{
return (DWORD)(get_sell_price(ob)*get_sell_dur_rate(ob));
}
DWORD get_repair_price(zObject* ob)
{
DWORD money = 0;
if (!ob) return money;
money = (DWORD)(2*get_sell_price(ob)*get_repair_dur_rate(ob));
return money;
}
bool SceneUser::do_trade_rs_cmd(const Cmd::stTradeUserCmd *rev,DWORD cmdLen)
{
Cmd::stRequestSellBuyUserCmd* cmd = (Cmd::stRequestSellBuyUserCmd *)rev;
if (cmd->temp_id == tempid) {
return true;
}
SceneUser *target = scene->getUserByTempID(cmd->temp_id);
if (!target || target->privatestore.step() != PrivateStore::BEGIN) {
Zebra::logger->warn("%s(%ld)请求购买摆摊物品的用户不存在或者没有摆摊",name,id);
return true;
}
if (abs((long)(pos.x- target->getPos().x)) > (SCREEN_WIDTH ) || abs((long)(pos.y-target->getPos().y)) > (SCREEN_HEIGHT)) {
return true;
}
PrivateStore::SellInfo* sf = target->privatestore.sell_ob(cmd->object_id);
if (!sf || !sf->object() ) {
Zebra::logger->debug("%s(%ld)请求购买摆摊物品不存在",name,id);
return true;
}
if (packs.uom.space(this) < 1) {
return Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"包裹空间不足");
}
if (packs.checkMoney(sf->money()) && target->packs.removeObject(sf->object(),true,false) ) //notify but not delete)
{
packs.addObject(sf->object(),true,AUTO_PACK);
//notify client about add
zObject::logger(sf->object()->createid,sf->object()->data.qwThisID,sf->object()->data.strName,sf->object()->data.dwNum,sf->object()->data.dwNum,0,target->id,target->name,this->id,this->name,"摆摊",NULL,0,0);
Cmd::stAddObjectPropertyUserCmd ret1;
ret1.byActionType = Cmd::EQUIPACTION_OBTAIN;
bcopy(&(sf->object()->data),&ret1.object,sizeof(t_Object),sizeof(ret1.object));
sendCmdToMe(&ret1,sizeof(ret1));
//compute money
target->packs.addMoney(sf->money(),"摆摊");
packs.removeMoney(sf->money(),"摆摊");
//clear from list
target->privatestore.remove(cmd->object_id);
}
return true;
}
bool SceneUser::doTradeCmd(const Cmd::stTradeUserCmd *rev,DWORD cmdLen)
{
using namespace Cmd;
switch(rev->byParam)
{
/// 领赠品品精致升级宝石
case GOLD_GIVE_USERCMD_PARAMETER:
{
Zebra::logger->debug("收到指令");
stGoldGiveTradeUserCmd *rett = ( Cmd::stGoldGiveTradeUserCmd * )rev;
Zebra::logger->debug("%d是收到的类型",rett->type);
if (rett->type == STORN)
{
if (this->charbase.goldgive == 0 && this->Card_num>0)
{
this->Card_num --;
if (this->Card_num > 60000)
this->Card_num = 0;
this->charbase.goldgive += 70;
if (this->charbase.goldgive>70)
this->charbase.goldgive = 70;
}
if (this->charbase.goldgive)
{
if (this->packs.uom.space(this))
{
zObjectB *base = objectbm.get(795);
if (base)
{
zObject *o = zObject::create(base,1);
if (o)
{
zObject::logger(o->createid,o->data.qwThisID,o->data.strName,o->data.dwNum,1,1,0,NULL,this->id,this->name,"赠品",o->base,o->data.kind,o->data.upgrade);
packs.addObject(o,true,AUTO_PACK);
this->charbase.goldgive--;
// if (this->charbase.goldgive > 70)
// this->charbase.goldgive = 0;
Cmd::stAddObjectPropertyUserCmd ret1;
ret1.byActionType = Cmd::EQUIPACTION_OBTAIN;
bcopy(&o->data,&ret1.object,sizeof(t_Object),sizeof(ret1.object));
sendCmdToMe(&ret1,sizeof(ret1));
stReturnGoldGiveTradeUserCmd ret;
ret.Storn_num=this->charbase.goldgive;
ret.Matarial_num=this->Give_MatarialNum;
ret.Card_num=this->Card_num;
sendCmdToMe(&ret,sizeof(ret));
}
}
}
else
{
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"你的包裹已满,领取精致升级宝石失败");
}
}
}
else
{
if (this->Give_MatarialNum == 0 && this->Card_num>0)
{
this->Card_num --;
if (this->Card_num >60000)
this->Card_num = 0;
this->Give_MatarialNum +=6;
if (this->Give_MatarialNum > 6)
this->Give_MatarialNum = 6;
}
if (this->Give_MatarialNum)
{
DWORD Matarial_id = 0;
switch(rett->type){
case SIVER :
{ Matarial_id = 517;}
break;
case SILK :
{ Matarial_id = 507;}
break;
case CRYSTAL:
{ Matarial_id = 527;}
break;
case EBONY :
{ Matarial_id = 537;}
break;
case YINGPI :
{ Matarial_id = 547;}
break;
default :
break;}
if (this->packs.uom.space(this))
{
zObjectB *base = objectbm.get(Matarial_id);
if (base)
{
zObject *o = zObject::create(base,50,0);
if (o)
{
zObject::logger(o->createid,o->data.qwThisID,o->data.strName,o->data.dwNum,1,1,0,NULL,this->id,this->name,"赠品",o->base,o->data.kind,o->data.upgrade);
packs.addObject(o,true,AUTO_PACK);
this->Give_MatarialNum--;
if (this->Give_MatarialNum > 6)
Give_MatarialNum = 0;
Cmd::stAddObjectPropertyUserCmd ret1;
ret1.byActionType = Cmd::EQUIPACTION_OBTAIN;
bcopy(&o->data,&ret1.object,sizeof(t_Object),sizeof(ret1.object));
sendCmdToMe(&ret1,sizeof(ret1));
stReturnGoldGiveTradeUserCmd ret;
ret.Storn_num=this->charbase.goldgive;
ret.Matarial_num=this->Give_MatarialNum;
ret.Card_num=this->Card_num;
sendCmdToMe(&ret,sizeof(ret));
}
}
}
else
{
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"你的包裹已满,领取材料赠品失败");
}
}
}
return true;
}
break;
case REQUEST_GOLD_GIVE_USERCMD_PARAMETER:
{
stReturnGoldGiveTradeUserCmd ret;
ret.Storn_num=this->charbase.goldgive;
ret.Matarial_num=this->Give_MatarialNum;
ret.Card_num=this->Card_num;
sendCmdToMe(&ret,sizeof(ret));
return true;
}
break;
/* ////领赠品 材料
case MATARIAL_GIVE_USERCMD_PARAMETER:
{
if (this->Give_MatarialNum)
{
if (this->packs.uom.space(this))
{
zObjectB *base = objectbm.get(795);
if (base)
{
zObject *o = zObject::create(base,1);
if (o)
{
zObject::logger(o->createid,o->data.qwThisID,o->data.strName,o->data
.dwNum,1,1,0,NULL,this->id,this->name,"赠品",o->base,o->data.kind,o->data.upgrade);
packs.addObject(o,true,AUTO_PACK);
this->Give_MatarialNum--;
Cmd::stAddObjectPropertyUserCmd ret1;
ret1.byActionType = Cmd::EQUIPACTION_OBTAIN;
bcopy(&o->data,&ret1.object,sizeof(t_Object));
sendCmdToMe(&ret1,sizeof(ret1));
}
}
}
else
{
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"你的包裹已满,领取精致升级宝石失败");
}
}
return true;
}
break;
case REQUEST_MATARIAL_GIVE_USERCMD_PARAMETER:
{
stReturnMatarialGiveTradeUserCmd ret;
ret.num=this->Give_MatarialNum;
sendCmdToMe(&ret,sizeof(ret));
return true;
}
break;
*/
case REQUEST_TRADE_USERCMD_PARAMETER:
{
stRequestTradeUserCmd *request=(stRequestTradeUserCmd *)rev;
if (tradeorder.canRequest())
{
if (request->dwAnswerTempID==tempid)
{
Zebra::logger->warn("[交易:玩家<------>玩家]%s(%ld)向自己请求交易",name,id);
return true;
}
SceneUser *pAnswer=scene->getUserByTempID(request->dwAnswerTempID);
if (pAnswer)
{
if (!isset_state(pAnswer->sysSetting,USER_SETTING_TRADE))
{
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"对方交易未开启");
return true;
}
if (abs((long)(pos.x- pAnswer->getPos().x)) > (SCREEN_WIDTH >> 1) || abs((long)(pos.y-pAnswer->getPos().y)) > (SCREEN_HEIGHT >> 1)) {
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"距离太远,不能交易!");
return true;
}
if (mask.is_masking() || pAnswer->mask.is_masking()) {
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"蒙面人不可交易 !");
return true;
}
//mask.on_trade();
Zebra::logger->info("[交易:玩家<------>玩家]%s(%ld)请求%s(%ld)交易",name,id,pAnswer->name,pAnswer->id);
if (pAnswer->tradeorder.canRequest())
{
tradeorder.ready(pAnswer);
pAnswer->tradeorder.ready(this);
stRequestTradeUserCmd req;
req.dwAskerTempID = tempid;
req.dwAnswerTempID = pAnswer->tempid;
pAnswer->sendCmdToMe(&req,sizeof(req));
return true;
}
else
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"对方不能交易接受你的请求",name);
}
else
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"对方不在!");
}
else
Zebra::logger->warn("[交易:玩家<------>玩家]%s(%ld)不能请求交易时请求交易",name,id);
return true;
}
break;
case ANSWER_TRADE_USERCMD_PARAMETER:
{
stAnswerTradeUserCmd *answer=(stAnswerTradeUserCmd *)rev;
if (tradeorder.canAnswer())
{
SceneUser *pAsker=tradeorder.target();
if (!pAsker)
{
tradeorder.finish();
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"对方不在了");
return true;
}
if (abs((long)(pos.x- pAsker->getPos().x)) > (SCREEN_WIDTH >> 1) || abs((long)(pos.y-pAsker->getPos().y)) > (SCREEN_HEIGHT >> 1)) {
tradeorder.cancel();
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"距离太远,不能交易!");
return true;
}
Zebra::logger->info("[交易:玩家<------>玩家]%s(%ld)应答%s(%ld)的交易",name,id,pAsker->name,pAsker->id);
if (pAsker->tradeorder.canAnswer() && pAsker->tradeorder.target()==this)
{
if (answer->byAgree)
{
tradeorder.begin();
pAsker->tradeorder.begin();
stBeginTradeUserCmd begin;
begin.dwAskerTempID=pAsker->tempid;
begin.dwAnswerTempID=tempid;
pAsker->sendCmdToMe(&begin,sizeof(begin));
sendCmdToMe(&begin,sizeof(begin));
// 发送现有物品到对方
//packs.trademyself->sendAllToAnother();
//pAsker->packs.trademyself->sendAllToAnother();
}
else
{
tradeorder.finish();
pAsker->tradeorder.finish();
Channel::sendSys(pAsker,Cmd::INFO_TYPE_FAIL,"对方不同意和你交易");
}
}
else
Zebra::logger->warn("[交易:玩家<------>玩家]%s(%ld)交易应答另一个用户",name,id);
}
else
Zebra::logger->warn("[交易:玩家<------>玩家]%s(%ld)不能应答交易时应答交易",name,id);
return true;
}
break;
case COMMIT_TRADE_USERCMD_PARAMETER:
{
if (tradeorder.commit())
{
SceneUser *pAnother = tradeorder.target();
if (pAnother)
{
if (pAnother->tradeorder.hasCommit())
{
//packs.trade();
//pAnother->packs.trade();
if (tradeorder.can_trade() && pAnother->tradeorder.can_trade() ) {
stFinishTradeUserCmd finish;
pAnother->sendCmdToMe(&finish,sizeof(finish));
sendCmdToMe(&finish,sizeof(finish));
tradeorder.trade();
pAnother->tradeorder.trade();
}else {
stCancelTradeUserCmd cancel;
cancel.dwUserTempID=tempid;
sendCmdToMe(&cancel,sizeof(cancel));
pAnother->sendCmdToMe(&cancel,sizeof(cancel));
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"%s包裹已满或银子不足,交易失败",
tradeorder.can_trade()?name:pAnother->name);
Channel::sendSys(pAnother,Cmd::INFO_TYPE_FAIL,"%s包裹已满或银子不足,交易失败",
tradeorder.can_trade()?name:pAnother->name);
}
pAnother->tradeorder.finish();
tradeorder.finish();
}
else
{
stCommitTradeUserCmd ci;
ci.dwUserTempID=tempid;
pAnother->sendCmdToMe(&ci,sizeof(ci));
sendCmdToMe(&ci,sizeof(ci));
}
}
else
{
tradeorder.finish();
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"对方不在了");
stCancelTradeUserCmd cancel;
cancel.dwUserTempID=tempid;
sendCmdToMe(&cancel,sizeof(cancel));
}
}
else
Zebra::logger->warn("[交易:玩家<------>玩家]%s(%ld)不能确定交易时确定交易",name,id);
return true;
}
break;
case CANCEL_TRADE_USERCMD_PARAMETER:
{
SceneUser *pAnother=tradeorder.target();
tradeorder.finish();
stCancelTradeUserCmd cancel;
cancel.dwUserTempID=tempid;
sendCmdToMe(&cancel,sizeof(cancel));
if (pAnother)
{
pAnother->tradeorder.finish();
cancel.dwUserTempID=pAnother->tempid;
pAnother->sendCmdToMe(&cancel,sizeof(cancel));
}
return true;
}
break;
case ADD_OBJECT_TRADE_USERCMD_PARAMETER:
{
stAddObjectTradeUserCmd *cmd = (stAddObjectTradeUserCmd *)rev;
if (!tradeorder.hasBegin() || tradeorder.hasCommit() ) {
return true;
}
if (cmd->x > TradeOrder::WIDTH || cmd->y > TradeOrder::HEIGHT) {
Zebra::logger->warn("[交易:玩家<------>玩家]%s(%ld)请求交易的物品坐标非法",name,id);
return true;
}
zObject* ob = packs.uom.getObjectByThisID(cmd->object.qwThisID);
if (!ob) {
Zebra::logger->warn("[交易:玩家<------>玩家]%s(%ld)请求交易的物品不存在",name,id);
return true;
}
if (ob->base->kind == ItemType_Money && cmd->object.dwNum > ob->data.dwNum ){
Zebra::logger->warn("[交易:玩家<------>玩家]%s(%ld)请求交易的物品数量非法",name,id);
return true;
}
if (ob->data.bind || ob->data.dwObjectID == 800 || ob->base->kind == ItemType_Quest) {
Zebra::logger->warn("[交易:玩家<------>玩家]%s(%ld)用户试图交易不能交易的物品",name,id);
return true;
}
if (ob->data.pos.loc() != Cmd::OBJECTCELLTYPE_COMMON) {
Zebra::logger->warn("[交易:玩家<------>玩家]%s(%ld)用户试图交易不在主包裹中的物品",name,id);
return true;
}
SceneUser *pAnother=tradeorder.target();
if (pAnother && pAnother->tradeorder.hasBegin() && !pAnother->tradeorder.hasCommit())
{
if (ob->base->kind ==ItemType_Money) {
tradeorder.add_money(cmd->object.dwNum);
}else {
tradeorder.add(ob);
}
stAddObjectTradeUserCmd ret;
ret.user_id = tempid;
memccpy(&ret.object,&(ob->data),sizeof(ret.object),sizeof(ret.object));
ret.x = cmd->x;
ret.y = cmd->y;
if (ob->base->kind == ItemType_Money) {
ret.object.dwNum = cmd->object.dwNum;
}
//this->sendCmdToMe(&ret,sizeof(ret));
pAnother->sendCmdToMe(&ret,sizeof(ret));
}
return true;
}
break;
case REMOVE_OBJECT_TRADE_USERCMD_PARAMETER:
{
stRemoveObjectTradeUserCmd *cmd = (stRemoveObjectTradeUserCmd *)rev;
if (!tradeorder.hasBegin() || tradeorder.hasCommit() ) {
return true;
}
SceneUser *pAnother=tradeorder.target();
if (pAnother && pAnother->tradeorder.hasBegin() && !pAnother->tradeorder.hasCommit())
{
tradeorder.remove(cmd->object_id);
cmd->user_id = tempid;
//this->sendCmdToMe(cmd,sizeof(stRemoveObjectTradeUserCmd));
pAnother->sendCmdToMe(cmd,sizeof(stRemoveObjectTradeUserCmd));
}
return true;
}
break;
case VISITNPC_TRADE_USERCMD_PARAMETER:
{
stVisitNpcTradeUserCmd *ptCmd=(stVisitNpcTradeUserCmd *)rev;
BYTE buf[zSocket::MAX_DATASIZE];
stVisitNpcTradeUserCmd *cmd=(stVisitNpcTradeUserCmd *)buf;
bzero(buf,sizeof(buf));
constructInPlace(cmd);
if( ptCmd->dwNpcTempID == 100000000 )
{
OnVisit event( 5281);
EventTable::instance().execute(*this,event);
int status;
int len = quest_list.get_menu(cmd->menuTxt,status);
if (NpcTrade::getInstance().getNpcMenu( 5281,cmd->menuTxt+len))
{
//Zebra::logger->debug("%ld\n%s",strlen(cmd->menuTxt),cmd->menuTxt);
visitNpc( 5281,100000000 );
cmd->byReturn = 1;
}
}
SceneNpc *sceneNpc = SceneNpcManager::getMe().getNpcByTempID( ptCmd->dwNpcTempID);
if ( (sceneNpc && this->canVisitNpc(sceneNpc)) /*|| ( sceneNpc->id == 5281 )*/ )/*( (sceneNpc->id>=5000&&sceneNpc->id<=6000) || (sceneNpc->scene && (sceneNpc->scene->getCountryID() == charbase.country || changeface)) ) */
{
//TODO 检查Npc是否在同一个场景,并且检查距离
OnVisit event(sceneNpc->id);
EventTable::instance().execute(*this,event);
int status;
int len = quest_list.get_menu(cmd->menuTxt,status);
//Zebra::logger->debug("TODO 检查Npc(%lu)是否在同一个场景,并且检查距离",sceneNpc->id);
if ( (sceneNpc->scene && sceneNpc->scene == this->scene &&
this->scene->zPosShortRange(this->getPos(),sceneNpc->getPos(),SCREEN_WIDTH,SCREEN_HEIGHT)) /*|| ( sceneNpc->id == 5281 )*/ )
{
if (NpcTrade::getInstance().getNpcMenu(sceneNpc->id,cmd->menuTxt+len))
{
//Zebra::logger->debug("%ld\n%s",strlen(cmd->menuTxt),cmd->menuTxt);
visitNpc(sceneNpc->id,sceneNpc->tempid);
cmd->byReturn = 1;
}
if (ScriptQuest::get_instance().has(ScriptQuest::NPC_VISIT,sceneNpc->id)) {
char func_name[32];
sprintf(func_name,"%s_%d","visit",sceneNpc->id);
if (execute_script_event(this,func_name,sceneNpc)) return true;
}
}
else
{
Zebra::logger->warn("用户%s(%d)检查Npc(%lu)距离不合法(%u,%d,%d),(%u,%d,%d)",this->name,this->id,sceneNpc->id,this->scene->id,this->getPos().x,this->getPos().y,sceneNpc->scene->id,sceneNpc->getPos().x,sceneNpc->getPos().y);
}
// Zebra::logger->debug("动态菜单(%s)",cmd->menuTxt);
}
else
Zebra::logger->error("%s(%d)访问不能访问的Npc",this->name,this->id);
sendCmdToMe(cmd,sizeof(stVisitNpcTradeUserCmd) + strlen(cmd->menuTxt));
return true;
}
break;
case BUYOBJECT_NPCTRADE_USERCMD_PARAMETER:
{
stBuyObjectNpcTradeUserCmd *ptCmd=(stBuyObjectNpcTradeUserCmd *)rev;
zObjectB *base = objectbm.get(ptCmd->dwObjectID);
ptCmd->itemLevel = 0;
///如果需要用金币或者积分买
if (base)
{
if (base->cointype & eBuyGold || base->cointype & eBuyTicket)
{
this->npcTradeGold(ptCmd,base,ptCmd->itemLevel);
return true;
}
}
SceneNpc * n = SceneNpcManager::getMe().getNpcByTempID(npc_dwNpcTempID);
if (!n && npc_dwNpcTempID != 100000000 )
{
Zebra::logger->debug("[交易:玩家<------商店]%s 交易时,找不到该npc tempID=%u",name,npc_dwNpcTempID);
return true;
}
if ((getGoodnessState() != Cmd::GOODNESS_6)
|| ((getGoodnessState()==Cmd::GOODNESS_6) && (NPC_TYPE_MOBILETRADE==n->npc->kind)) )
{
if (base)
{
DWORD price = (DWORD )(this->getGoodnessPrice(base->price,true)+0.99f);
if (this->scene->getCountryID() == PUBLIC_COUNTRY)
{//在公共国买东西,价格上涨10%
price = price + (DWORD)(price*0.1);
}
if (ptCmd->dwNum == 0) {
ptCmd->dwNum = 1;
}
if (ptCmd->dwNum > base->maxnum) {
ptCmd->dwNum = base->maxnum;
}
DWORD need = price*ptCmd->dwNum;
int dayssize=packs.store.days;
if (this->charbase.bitmask & CHARBASE_VIP)
{
dayssize=dayssize?(dayssize - 1):dayssize;
}
if (base->kind == ItemType_Store) {
need = price*base->durability;
if (dayssize==1) //the second page
need = 2000;
if (dayssize==2) //the third page
need = 100000;
}
// if (base->kind == ItemType_HORSE && charbase.level<30)
if (base->kind == ItemType_HORSE && charbase.level<2)
{
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"你还没满30级,不能购买马匹");
return true;
}
DWORD taxMoney;
if( npc_dwNpcTempID == 100000000 )
{
taxMoney = (DWORD)((price*ptCmd->dwNum/100.0f)+0.5f);
}
else
taxMoney = (DWORD)((price*ptCmd->dwNum*n->scene->getTax()/100.0f)+0.5f); // 买东西收税
if ((base->kind == ItemType_DoubleExp && this->charbase.honor >= need) ||
(base->kind == ItemType_HORSE && packs.checkMoney(need))||
(base->kind == ItemType_Store && packs.checkMoney(need))||
(base->kind != ItemType_DoubleExp && packs.checkMoney(need+taxMoney)))
{
NpcTrade::NpcItem item;
item.id = base->id;
item.kind = base->kind;
item.lowLevel = 0;
item.level = base->needlevel;
item.itemlevel = ptCmd->itemLevel;
item.action = NpcTrade::NPC_BUY_OBJECT;
if (NpcTrade::getInstance().verifyNpcAction(npc_dwNpcDataID,item))
{
if (base->kind == ItemType_HORSE) {
if (horse.horse()) {
return Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"你已经有马了!");
}
//DWORD taxMoney = (DWORD)((need*n->scene->getTax()/100.0f)+0.5f); // 买东西收税
//need = need + taxMoney;
if (packs.removeMoney(need,"买东西")) {
horse.horse(base->id);
/*
Cmd::Session::t_taxAddCountry_SceneSession send;
send.dwCountryID = n->scene->getCountryID();
send.qwTaxMoney = taxMoney;
sessionClient->sendCmd(&send,sizeof(send));
// */
Channel::sendSys(this,Cmd::INFO_TYPE_GAME,"你得到一匹枣红马");
Zebra::logger->info("[交易:玩家<------商店]用户(%s,%u)买马(%d)花费银子%d",name,id,base->id,need);
}else {
Zebra::logger->fatal("[交易:玩家<------商店]用户(%s)买马时银子计算错误!",name);
}
return true;
}
/*if (base->kind == ItemType_Store)
{
if (dayssize>1)
return Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"已经买了两个储物箱了,无法再购买!");
if (packs.removeMoney(need,"买东西") ) {
Zebra::logger->info("[交易:玩家<------商店]用户(%s,%u)买储物箱花费银子%d",name,id,need);
Channel::sendMoney(this,Cmd::INFO_TYPE_GAME,need,"买储物箱花费银子");
packs.store.days.push_back(base->durability);
packs.store.notify(this);
}
else
{
Zebra::logger->fatal("[交易:玩家<------商店]用户(%s)买储物箱时银子计算错误!",name);
}
return true;
}*/
zObject* o = NULL;
if (base->recast)
{
o = zObject::create(base,ptCmd->dwNum,0);
if (o && ptCmd->itemLevel)
{
do
{
//Upgrade::upgrade(*this,o,100); //must success
}
while (--ptCmd->itemLevel >0);
}
}else
{
o = zObject::create(base,ptCmd->dwNum,ptCmd->itemLevel);
}
if (o)
{
Combination callback(this,o);
packs.main.execEvery(callback);
if (packs.equip.pack(EquipPack::L_PACK)) packs.equip.pack(EquipPack::L_PACK)->execEvery(callback);
if (packs.equip.pack(EquipPack::R_PACK)) packs.equip.pack(EquipPack::R_PACK)->execEvery(callback);
int free = 0;
if (o->data.dwNum) {
if (packs.addObject(o,true,AUTO_PACK)) {
free = o->data.dwNum;
//如果是双倍经验道具和荣誉道具需要绑定
o->checkBind();
Cmd::stAddObjectPropertyUserCmd status;
status.byActionType = Cmd::EQUIPACTION_OBTAIN;
bcopy(&o->data,&status.object,sizeof(t_Object),sizeof(status.object));
sendCmdToMe(&status,sizeof(status));
}
}
if (callback.num() || free) {
//get object
int count = callback.num() + free;
if (base->kind == ItemType_DoubleExp)
{
this->charbase.honor -= price*count;
if ((int)this->charbase.honor <0)
{
Zebra::logger->fatal("[交易:玩家<------商店]用户(%s)买%s时荣誉点数计算错误!",name,o->base->name);
this->charbase.honor=0;
}
Cmd::stMainUserDataUserCmd userinfo;
full_t_MainUserData(userinfo.data);
sendCmdToMe(&userinfo,sizeof(userinfo));
zObject::logger(0,0,"荣誉值",this->charbase.honor,price*count,0,this->id,this->name,0,NULL,"买东西扣除荣誉值",NULL,0,0);
zObject::logger(o->createid,o->data.qwThisID,o->data.strName,o->data.dwNum,count,1,n->id,n->name,this->id,this->name,"buy_npc",o->base,o->data.kind,o->data.upgrade);
Channel::sendSys(this,Cmd::INFO_TYPE_GAME,"得到物品 %s(%d)个,花费荣誉点数%u",o->name,count,price*count);
Zebra::logger->info("[交易:玩家<------商店]用户(%s,%u)买%s(%d)个花费荣誉点%d",name,id,o->name,count,price*count);
}
else
{
DWORD taxMoney;
if( npc_dwNpcTempID == 100000000 )
{
taxMoney = (DWORD)((price*count/100.0f)+0.5f);
}
else
taxMoney = (DWORD)((price*count*n->scene->getTax()/100.0f)+0.5f); // 买东西收税
if (!packs.removeMoney(price*count+taxMoney,"买东西")) {
Zebra::logger->fatal("[交易:玩家<------商店]用户(%s)买%s时银子计算错误!",name,o->base->name);
}
Cmd::Session::t_taxAddCountry_SceneSession send;
if( npc_dwNpcTempID == 100000000 )
{
send.dwCountryID = 2;
}
else
{
send.dwCountryID = n->scene->getCountryID();
}
send.qwTaxMoney = taxMoney;
sessionClient->sendCmd(&send,sizeof(send));
if( npc_dwNpcTempID == 100000000 )
{
Zebra::logger->info("[交易:玩家<------随身商店]用户(%s,%u)买%s(%d)个花费银子%d",name,id,o->name,count,price*count+taxMoney);
}
else
zObject::logger(o->createid,o->data.qwThisID,o->data.strName,o->data.dwNum,count,1,n->id,n->name,this->id,this->name,"buy_npc",o->base,o->data.kind,o->data.upgrade);
Channel::sendMoney(this,Cmd::INFO_TYPE_GAME,price*count+taxMoney,"得到物品 %s(%d)个,花费银子",o->name,count);
Zebra::logger->info("[交易:玩家<------商店]用户(%s,%u)买%s(%d)个花费银子%d",name,id,o->name,count,price*count+taxMoney);
}
}
if (!free) { //package is full
//Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"你的包裹已满");
zObject::destroy(o);
}
}
}
else
Zebra::logger->error("[交易:玩家<------商店]不能在这里买这样物品 %u,%u,%s",npc_dwNpcDataID,base->id,base->name);
}
else
{
if (base->kind == ItemType_DoubleExp)
{
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"你的荣誉点数不够买这件物品");
}
else
{
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"你的银子不够买这件物品");
}
}
}
}
else
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"本人不与大魔头交易");
return true;
}
break;
case SELLOBJECT_NPCTRADE_USERCMD_PARAMETER:
{
stSellObjectNpcTradeUserCmd *ptCmd=(stSellObjectNpcTradeUserCmd *)rev;
zObject *srcobj=packs.uom.getObjectByThisID(ptCmd->qwThisID);
if (srcobj)
{
if (this->getGoodnessState() != Cmd::GOODNESS_6)
{
//交易处理
if (tradeorder.hasBegin() && tradeorder.in_trade(srcobj))
{
return true;
}
if (mask.is_use(srcobj)) {
return Channel::sendSys(this,Cmd::INFO_TYPE_GAME,"请先解除该蒙面巾!");
}
if (srcobj->base->kind == ItemType_Quest) {
return Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"任务物品不可买卖");
};
NpcTrade::NpcItem item;
item.id = srcobj->data.dwObjectID;
item.kind = srcobj->base->kind;
item.lowLevel = 0;
item.level = srcobj->data.needlevel;
item.action = NpcTrade::NPC_SELL_OBJECT;
if (NpcTrade::getInstance().verifyNpcAction(npc_dwNpcDataID,item))
{
// 卖东西要收钱
if (srcobj->data.price>0)
{
DWORD price = 0;
DWORD real_price = 0;
if (srcobj->base->id == 655)
{
if (srcobj->base->durability)
{
real_price = (DWORD)(((float)((srcobj->data.dur+49)/50.0f)/((srcobj->base->durability+49)/50.0f)) * 4000.0f);
}
}
else if (srcobj->base->id == 685) //魔力之源
{
if (srcobj->base->durability)
{
real_price = (DWORD)(((float)((srcobj->data.dur+49)/50.0f)/((srcobj->base->durability+49)/50.0f)) * 4000.0f);
}
}
else if (srcobj->base->id == 882) // 龙之魔力
{
if (srcobj->base->durability)
{
real_price = (DWORD)(((float)((srcobj->data.dur+49)/50.0f)/((srcobj->base->durability+49)/50.0f)) * 20000.0f);
}
}
else if (srcobj->base->id == 760) //洗髓宝珠
{
//if (srcobj->base->durability)
//{
real_price = (DWORD)(((float)((srcobj->data.dur+49)/50.0f)/((srcobj->base->durability+49)/50.0f)) * 200000.0f);
//}
}
else if (srcobj->base->id == 761) // 易筋宝珠
{
//if (srcobj->base->durability)
//{
real_price = (DWORD)(((float)((srcobj->data.dur+49)/50.0f)/((srcobj->base->durability+49)/50.0f)) * 200000.0f);
//}
}
else if (srcobj->base->id == 881)
{
if (srcobj->base->durability)
{
real_price = (DWORD)(((float)((srcobj->data.dur+49)/50.0f)/((srcobj->base->durability+49)/50.0f)) * 20000.0f);
}
}
else
{
price = get_sell_price_by_dur(srcobj);
if (srcobj->base->maxnum &&
(srcobj->base->kind == ItemType_Arrow/* || srcobj->base->kind == ItemType_Arrow2*/))
{
if (srcobj->base->durability)
{
real_price = (DWORD)(getGoodnessPrice((srcobj->data.dwNum * price
),false));
}
}
else
{
if (srcobj->base->durability)
{
real_price = (DWORD)(getGoodnessPrice((srcobj->data.dwNum * price
),false));
}
else
{
real_price = (DWORD)(getGoodnessPrice((srcobj->data.dwNum * price
),false));
}
}
}
Channel::sendMoney(this,Cmd::INFO_TYPE_GAME,real_price,"卖%s得到银子",srcobj->name );
Zebra::logger->info("[交易:玩家------>商店]用户(%s,%u)卖%s得到银子%d",name,id,srcobj->name,real_price);
packs.addMoney(real_price,"卖东西");
}
if (srcobj->data.exp && srcobj->base->kind != ItemType_Pack ) {
Zebra::logger->info("[交易:玩家------>商店]%s(%u) 卖装备增加经验 %u",name,id,srcobj->data.exp);
addExp(srcobj->data.exp);
}
zObject::logger(srcobj->createid,srcobj->data.qwThisID,srcobj->base->name,srcobj->data.dwNum,srcobj->data.dwNum,0,npc_dwNpcDataID,NULL,this->id,this->name,"sell_npc",srcobj->base,srcobj->data.kind,srcobj->data.upgrade);
packs.removeObject(srcobj); //notify and delete
if (packs.equip.needRecalc)
{
notifyEquipChange();
setupCharBase();
Cmd::stMainUserDataUserCmd userinfo;
full_t_MainUserData(userinfo.data);
sendCmdToMe(&userinfo,sizeof(userinfo));
sendMeToNine();
}
}
else
{
Zebra::logger->warn("[交易:玩家------>商店]不能在这里卖这样物品 %u,%u,%s",
npc_dwNpcDataID,srcobj->data.dwObjectID,srcobj->data.strName);
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"对不起,小店不收购%s",srcobj->base->name);
}
}
else
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"本人不与大魔头交易");
}
return true;
}
break;
case SELLHORSE_NPCTRADE_USERCMD_PARAMETER:
{
stSellHorseNpcTradeUserCmd *ptCmd=(stSellHorseNpcTradeUserCmd *)rev;
//放逐
if (ptCmd->action) {
if (horse.horse()) {
horse.mount(false);
horse.putAway();
horse.horse(0);
Zebra::logger->info("[卖马]%s 放逐了他的马",name);
}
return true;
}
//卖
if (this->getGoodnessState() != Cmd::GOODNESS_6)
{
if (!horse.horse()) {
return Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"你还没有马匹,卖什么马?");
}
zObjectB *base = objectbm.get(horse.horse());
if (!base) {
Zebra::logger->warn("[卖马]用户马匹在道具表中不存在,请检查道具基本表!");
return true;
}
NpcTrade::NpcItem item;
item.id = base->id;
item.kind = base->kind;
item.lowLevel = 0;
item.level = base->needlevel;
item.action = NpcTrade::NPC_SELL_OBJECT;
if (NpcTrade::getInstance().verifyNpcAction(npc_dwNpcDataID,item)) {
if (base->price>0) {
DWORD price = (DWORD)(getGoodnessPrice(base->price,false)*0.5f + 0.99f);
char info[MAX_CHATINFO];
sprintf(info,"卖%s得到银子",base->name);
Zebra::logger->info("[卖马]用户(%s,%u)卖%s得到银子%d",name,id,base->name,price);
packs.addMoney(price,"卖东西",info);
}
horse.putAway();
//horse.sendData();
horse.mount(false);
horse.horse(0);
}else {
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"对不起,小店不收购%s",base->name);
}
}
else Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"本人不与大魔头交易");
return true;
}
break;
case STORE_INFO_NPCTRADE_USERCMD_PARAMETER:
{
/*stStoreInfoNpcTradeUserCmd* cmd = (stStoreInfoNpcTradeUserCmd*)rev;
if ((signed char)cmd->page < 0 || cmd->page >= packs.store.days.size() ) return false;
packs.store.days[cmd->page] += *(BYTE*)(&cmd->day[0]);
packs.store.notify(this);*/
return true;
}
break;
case REPAIROBJECT_GOLD_NPCTRADE_USERCMD_PARAMETER:
{
DWORD price = 0;
stRepairObjectGoldNpcTradeUserCmd *cmd = (stRepairObjectGoldNpcTradeUserCmd *)rev;
if (cmd->id == 0)
{
//compute cost
RepairCost cost;
packs.equip.execEvery(cost);
price = zObject::RepairMoney2RepairGold(cost.cost());
//价格为0时拒绝修里
if (!price)
{
return true;
}
//test money
if (!packs.checkGold(price)) {
return Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"你的金子不足,不能全部修理!");
}
//repair equip
RepairEquipUseGold repair(this);
packs.equip.execEvery(repair);
}
else
{
zObject* ob = packs.uom.getObjectByThisID(cmd->id);
if (!ob || !ob->base->recast || /*!ob->data.dur ||// */ !ob->data.maxdur) return false;
price = zObject::RepairMoney2RepairGold(get_repair_price(ob));
//test money
if (!packs.checkGold(price)) {
return Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"你的金子子不足,不能修理这件物品!");
}
ob->data.dur = ob->data.maxdur;
Cmd::stDurabilityUserCmd ret;
ret.dwThisID = ob->data.qwThisID;
ret.dwDur = ob->data.dur;
ret.dwMaxDur = ob->data.maxdur;
sendCmdToMe(&ret,sizeof(ret));
}
if (!packs.removeGold(price,"修理"))
{
Zebra::logger->fatal("用户(%s)修理装备时金子子计算错误!",name);
}
}
break;
case REPAIROBJECT_NPCTRADE_USERCMD_PARAMETER:
{
DWORD price = 0;
stRepairObjectNpcTradeUserCmd *cmd = (stRepairObjectNpcTradeUserCmd *)rev;
#if 0
NpcTrade::NpcItem item;
item.id = 0 /*base->id*/;
item.kind = 0 /*base->kind*/;
item.lowLevel = 0;
item.level = 0 /*base->needlevel*/;
item.action = NpcTrade::NPC_REPAIR_OBJECT;
if (!NpcTrade::getInstance().verifyNpcAction(npc_dwNpcDataID,item)) {
return false;
}
#endif
if (cmd->gem_id)
{
zObject* gem_ob = packs.uom.getObjectByThisID(cmd->gem_id);
if (!gem_ob || gem_ob->base->kind != ItemType_Repair ) return true;
zObject* ob = packs.uom.getObjectByThisID(cmd->id);
if (!ob || !ob->base->recast) return true;
//repair equip
//每次修复两点最大耐久,同时增加当前耐久至最大耐久
ob->data.maxdur += 100;
if (ob->data.maxdur > ob->base->durability)
{
ob->data.maxdur = ob->base->durability;
}
ob->data.dur = ob->data.maxdur;
Cmd::stDurabilityUserCmd ret;
ret.dwThisID = ob->data.qwThisID;
ret.dwDur = ob->data.dur;
ret.dwMaxDur = ob->data.maxdur;
sendCmdToMe(&ret,sizeof(ret));
packs.removeObject(gem_ob); //notify and delete
return true;
}
if (cmd->id == 0)
{
//compute cost
RepairCost cost;
packs.equip.execEvery(cost);
price = cost.cost();
//价格为0时拒绝修里
if (!price)
{
return true;
}
//test money
if (!packs.checkMoney(price)) {
return Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"你的银子不足,不能全部修理!");
}
//repair equip
RepairEquip repair(this);
packs.equip.execEvery(repair);
}
else
{
zObject* ob = packs.uom.getObjectByThisID(cmd->id);
if (!ob || !ob->base->recast || !ob->data.dur || !ob->data.maxdur) return false;
price = get_repair_price(ob);
if (!price)
{
return true;
}
//test money
if (!packs.checkMoney(price))
{
return Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"你的银子不足,不能修理这件物品!");
}
//repair equip
//武器,盾,帽子,衣服,护腕,腰带,靴子,戒指,手镯,项链需要消耗最大耐久
/*
switch(ob->base->kind)
{
case ItemType_ClothBody:
case ItemType_FellBody:
case ItemType_MetalBody:
case ItemType_Blade:
case ItemType_Sword:
case ItemType_Axe:
case ItemType_Hammer:
case ItemType_Staff:
case ItemType_Crossbow:
case ItemType_Fan:
case ItemType_Stick:
case ItemType_Shield:
case ItemType_Helm:
case ItemType_Caestus:
case ItemType_Cuff:
case ItemType_Shoes:
case ItemType_Necklace:
case ItemType_Fing:
case ItemType_FashionBody:
{
//消耗最大耐久公式
DWORD reduce = ((DWORD)((((float)(ob->data.maxdur-ob->data.dur))/ob->base->durability)*10)+1)*5;
if (reduce > ob->data.maxdur)
{
ob->data.maxdur=0;
}
else
{
ob->data.maxdur -=reduce;
}
}
break;
default:
break;
}
// */
ob->data.dur = ob->data.maxdur;
Cmd::stDurabilityUserCmd ret;
ret.dwThisID = ob->data.qwThisID;
ret.dwDur = ob->data.dur;
ret.dwMaxDur = ob->data.maxdur;
sendCmdToMe(&ret,sizeof(ret));
}
if (!packs.removeMoney(price,"修理"))
{
Zebra::logger->fatal("用户(%s)修理装备时银子计算错误!",name);
}
/*
else {
Zebra::logger->info("[修理装备]用户(%s)修理装备花费银子(%d)",name,price);
}
// */
}
break;
case START_SELL_USERCMD_PARAMETER:
//by RAY 去掉摆摊
//Channel::sendSys(this, Cmd::INFO_TYPE_FAIL, "摆摊系统开 发中!");
//#if 0
if (this->charbase.level <20)
{
Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"等级低于20,不能摆摊!");
return true;
}
if (this->isSitdown())
{
this->standup();
}
if (privatestore.step() == PrivateStore::NONE)
{
/*
if (!scene->checkZoneType(getPos(),ZoneTypeDef::ZONE_PRIVATE_STORE)) {
return Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"这里不能摆摊!");
}
*/
Cmd::stCanSellTradeUserCmd cmd;
if (!scene->checkZoneType(getPos(),ZoneTypeDef::ZONE_PRIVATE_STORE))
{
cmd.status = 1;
sendCmdToMe(&cmd,sizeof(cmd));
return true;
}
cmd.status = 0;
privatestore.step(PrivateStore::START,this);
sendCmdToMe(&cmd,sizeof(cmd));
Zebra::logger->info("[交易:玩家------>摆摊]用户(%s)请求开始摆摊",name);
return true;
}
if (privatestore.step() == PrivateStore::START) {
horse.mount(false,false);
privatestore.step(PrivateStore::BEGIN,this);
sendMeToNine();
Zebra::logger->info("[交易:玩家------>摆摊]用户(%s)开始摆摊",name);
return true;
}
//#endif
break;
case FINISH_SELL_USERCMD_PARAMETER:
{
privatestore.step(PrivateStore::NONE,this);
Zebra::logger->info("[交易:玩家------>摆摊]用户(%s)完成摆摊",name);
sendMeToNine();
}
break;
case REQUEST_ADD_OBJECT_SELL_USERCMD_PARAMETER:
{
stRequestAddObjectSellUserCmd *cmd = (stRequestAddObjectSellUserCmd *)rev;
for(int i = 0; i < cmd->num && i < 200; i++)
{
if (privatestore.step() != PrivateStore::START ) {
return true;
}
if (cmd->list[i].x > PrivateStore::WIDTH || cmd->list[i].y > PrivateStore::HEIGHT) {
Zebra::logger->warn("[交易:玩家------>摆摊]%s(%ld)请求摆摊的物品坐标非法",name,id);
return true;
}
zObject* ob = packs.uom.getObjectByThisID(cmd->list[i].qwThisID);
if (!ob) {
Zebra::logger->warn("[交易:玩家------>摆摊]%s(%ld)请求摆摊的物品不存在",name,id);
return true;
}
if (mask.is_use(ob)) {
return Channel::sendSys(this,Cmd::INFO_TYPE_GAME,"请先解除该蒙面巾!");
}
if (ob->data.bind || ob->data.dwObjectID == 800 || ob->base->kind == ItemType_Quest) {
Zebra::logger->warn("[交易:玩家------>摆摊]%s(%ld)用户试图使用不能摆摊的物品",name,id);
return true;
}
if (ob->data.pos.loc() != Cmd::OBJECTCELLTYPE_COMMON && ob->data.pos.loc()!=Cmd::OBJECTCELLTYPE_PACKAGE) {
Zebra::logger->warn("[交易:玩家------>摆摊]%s(%ld)用户试图摆摊不在主副包裹中的物品",name,id);
return true;
}
privatestore.add(ob,cmd->list[i].price,cmd->list[i].x,cmd->list[i].y);
Zebra::logger->info("[交易:玩家------>摆摊]用户%s添加摆摊物品%s(%d)",name,ob->data.strName,ob->data.qwThisID);
}
}
break;
case ADD_OBJECT_SELL_USERCMD_PARAMETER:
{
stAddObjectSellUserCmd *cmd = (stAddObjectSellUserCmd *)rev;
if (privatestore.step() != PrivateStore::START ) {
return true;
}
if (cmd->x > PrivateStore::WIDTH || cmd->y > PrivateStore::HEIGHT) {
Zebra::logger->warn("[交易:玩家------>摆摊]%s(%ld)请求摆摊的物品坐标非法",name,id);
return true;
}
zObject* ob = packs.uom.getObjectByThisID(cmd->object.qwThisID);
if (!ob) {
Zebra::logger->warn("[交易:玩家------>摆摊]%s(%ld)请求摆摊的物品不存在",name,id);
return true;
}
/*
if (ob->base->kind == ItemType_Money && cmd->object.dwNum > ob->data.dwNum ){
Zebra::logger->warn("%s(%ld)请求交易的物品数量非法",name,id);
return true;
}
*/
if (mask.is_use(ob)) {
return Channel::sendSys(this,Cmd::INFO_TYPE_GAME,"请先解除该蒙面巾!");
}
if (ob->data.bind || ob->data.dwObjectID == 800 || ob->base->kind == ItemType_Quest) {
Zebra::logger->warn("[交易:玩家------>摆摊]%s(%ld)用户试图使用不能摆摊的物品",name,id);
return true;
}
if (ob->data.pos.loc() != Cmd::OBJECTCELLTYPE_COMMON && ob->data.pos.loc()!=Cmd::OBJECTCELLTYPE_PACKAGE) {
Zebra::logger->warn("[交易:玩家------>摆摊]%s(%ld)用户试图摆摊不在主副包裹中的物品",name,id);
return true;
}
privatestore.add(ob,cmd->price,cmd->x,cmd->y);
Zebra::logger->info("[交易:玩家------>摆摊]用户%s添加摆摊物品%s(%d)",name,ob->data.strName,ob->data.qwThisID);
}
break;
case REMOVE_OBJECT_SELL_USERCMD_PARAMETER:
{
stRemoveObjectSellUserCmd*cmd = (stRemoveObjectSellUserCmd *)rev;
if (privatestore.step() != PrivateStore::START) {
return true;
}
privatestore.remove(cmd->object_id);
//just for info,it's very ugly
zObject* ob = packs.uom.getObjectByThisID(cmd->object_id);
if (ob) {
Zebra::logger->info("[交易:玩家------>摆摊]用户%s移除摆摊物品%s(%d)",name,ob->data.strName,ob->data.qwThisID);
}
}
break;
case REQUEST_SELL_INFO_USERCMD_PARAMETER:
{
stRequestSellInfoUserCmd *cmd=(stRequestSellInfoUserCmd *)rev;
if (cmd->temp_id == tempid) {
//Zebra::logger->warn("[交易:玩家<------摆摊]%s(%ld)请求自己的摆摊信息",name,id);
return true;
}
SceneUser *target = scene->getUserByTempID(cmd->temp_id);
if (!target || target->privatestore.step() != PrivateStore::BEGIN) {
Zebra::logger->warn("[交易:玩家<------摆摊]%s(%ld)请求摆摊信息的用户不存在或者没有摆摊",name,id);
return true;
}
if (abs((long)(pos.x- target->getPos().x)) > (SCREEN_WIDTH ) || abs((long)(pos.y-target->getPos().y)) > (SCREEN_HEIGHT)) {
return true;
}
//Zebra::logger->info("[交易:玩家<------摆摊]%s(%ld)请求%s(%ld)摆摊信息",name,id,target->name,target->id);
target->privatestore.show(this);
}
break;
case REQUEST_SELL_BUY_USERCMD_PARAMETER:
{
do_trade_rs_cmd(rev,cmdLen);
return true;
}
break;
case UPDATE_STORE_PASS_USERCMD_PARAMETER:
/*
{
stUpdateStorePassUserCmd * cmd = (stUpdateStorePassUserCmd*)rev;
if (strncmp(cmd->oldpass,charbase.pass,sizeof(charbase.pass)) == 0) {
strncpy(charbase.pass,cmd->newpass,sizeof(charbase.pass));
return true;
}
return Channel::sendSys(this,Cmd::INFO_TYPE_FAIL,"密码错误,不能修改密码!")
}
*/
break;
//[Shx Add 发送广告牌更新消息]
case UPDATE_SHOP_ADV_USERCMD_PARAMETER:
{
stUpdateShopAdvcmd* pCmd = (stUpdateShopAdvcmd*)rev;
pCmd->size = 1;
pCmd->Datas[0].dwID = tempid;
pCmd->Datas[0].strShopAdv[MAX_SHOPADV - 1] = '\0';
strncpy(ShopAdv, pCmd->Datas[0].strShopAdv,MAX_SHOPADV);
this->scene->sendCmdToNine(this->getPosI(),pCmd,sizeof(stUpdateShopAdvcmd) + 1 * sizeof(stUpdateShopAdvcmd::stAdv), this->dupIndex);
}
break;
// [Shx Add 转发交易玩家修改金钱数量]
case UPDATE_TRADE_MONEY_USERCMD:
{
stUpdateTradeMoneycmd* pCmd = (stUpdateTradeMoneycmd*)rev;
SceneUser* pTarget = tradeorder.target();
if(pTarget && pCmd->dwMyID == tempid && pCmd->dwOtherID == pTarget->tempid)
{
pTarget->sendCmdToMe(pCmd, cmdLen);
}
}
break;
default:
break;
}
return false;
}
bool RepairCost::exec(zObject* ob)
{
if (!ob || !ob->base->recast || !ob->data.maxdur ) return true;
_cost += get_repair_price(ob);
return true;
}
bool RepairEquipUseGold::exec(zObject* ob)
{
if (!ob || !ob->base->recast || !ob->data.maxdur) return true;
ob->data.dur = ob->data.maxdur;
Cmd::stDurabilityUserCmd ret;
ret.dwThisID = ob->data.qwThisID;
ret.dwDur = ob->data.dur;
ret.dwMaxDur = ob->data.maxdur;
_user->sendCmdToMe(&ret,sizeof(ret));
return true;
}
bool RepairEquip::exec(zObject* ob)
{
if (!ob || !ob->base->recast || !ob->data.maxdur) return true;
//武器,盾,帽子,衣服,护腕,腰带,靴子,戒指,手镯,项链需要消耗最大耐久
/*
switch(ob->base->kind)
{
case ItemType_ClothBody:
case ItemType_FellBody:
case ItemType_MetalBody:
case ItemType_Blade:
case ItemType_Sword:
case ItemType_Axe:
case ItemType_Hammer:
case ItemType_Staff:
case ItemType_Crossbow:
case ItemType_Fan:
case ItemType_Stick:
case ItemType_Shield:
case ItemType_Helm:
case ItemType_Caestus:
case ItemType_Cuff:
case ItemType_Shoes:
case ItemType_Necklace:
case ItemType_Fing:
case ItemType_FashionBody:
{
//消耗最大耐久公式
DWORD reduce = ((DWORD)((((float)(ob->data.maxdur-ob->data.dur))/ob->base->durability)*10)+1)*5;
if (reduce > ob->data.maxdur)
{
ob->data.maxdur=0;
}
else
{
ob->data.maxdur -=reduce;
}
}
break;
default:
break;
}
// */
ob->data.dur = ob->data.maxdur;
Cmd::stDurabilityUserCmd ret;
ret.dwThisID = ob->data.qwThisID;
ret.dwDur = ob->data.dur;
ret.dwMaxDur = ob->data.maxdur;
_user->sendCmdToMe(&ret,sizeof(ret));
return true;
}
| [
"hyd998877@gmail.com"
] | hyd998877@gmail.com |
dc3fc45a2a80b41cb7573ae0d49f23370edd92e8 | 5740ea2c2d9d5fb5626ff5ad651f3789048ae86b | /PlasmaLibraries/Common/Time.cpp | a9e88440be533e8d68d0a384330782bdbb9ad462 | [
"MIT"
] | permissive | donovan680/Plasma | 4945b92b7c6e642a557f12e05c7d53819186de55 | 51d40ef0669b7a3015f95e3c84c6d639d5469b62 | refs/heads/master | 2022-04-15T02:42:26.469268 | 2020-02-26T22:32:12 | 2020-02-26T22:32:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,412 | cpp | ///////////////////////////////////////////////////////////////////////////////
///
/// \file Time.cpp
///
/// Authors: Joshua Davis
/// Copyright 2010-2015, DigiPen Institute of Technology
///
///////////////////////////////////////////////////////////////////////////////
#include "Precompiled.hpp"
namespace Plasma
{
TimeType Time::GetTime()
{
return time(0);
}
TimeType Time::Clock()
{
return clock();
}
TimeType Time::GenerateSeed()
{
return clock();
}
CalendarDateTime Time::GetLocalTime(const TimeType& timer)
{
CalendarDateTime result;
tm* lt = localtime(&timer);
result.Seconds = lt->tm_sec;
result.Minutes = lt->tm_min;
result.Hour = lt->tm_hour;
result.Day = lt->tm_mday;
result.Month = lt->tm_mon;
result.Year = lt->tm_year + 1900;
result.Weekday = lt->tm_wday;
result.Yearday = lt->tm_yday;
result.IsDaylightSavings = lt->tm_isdst;
return result;
}
TimeType Time::CalendarDateTimeToTimeType(const CalendarDateTime& time)
{
tm newTime;
newTime.tm_sec = time.Seconds;
newTime.tm_min = time.Minutes;
newTime.tm_hour = time.Hour;
newTime.tm_mday = time.Day;
newTime.tm_mon = time.Month;
newTime.tm_year = time.Year - 1900;
newTime.tm_wday = time.Weekday;
newTime.tm_yday = time.Yearday;
newTime.tm_isdst = time.IsDaylightSavings;
return mktime(&newTime);
}
TimeType Time::ClocksPerSecond()
{
return CLOCKS_PER_SEC;
}
}//namespace Plasma
| [
"dragonCASTjosh@gmail.com"
] | dragonCASTjosh@gmail.com |
4c5d4d28060f48082ed6929861621d4ff6ec7fc6 | a7e1ea450087be3c6f01daa7d4215239310f6320 | /string_class/String.cpp | 7b4de30fbc50b523e12ed5e3a5e672328a18cfa7 | [] | no_license | lohani2280/c-plus-plus_stuffs | 3b0bfb6e4b7a639311eba4404605913059c4a302 | a18c8f883df23ff541af8d7d962399ecb19970ae | refs/heads/master | 2021-06-08T03:08:26.890932 | 2016-11-14T12:05:52 | 2016-11-14T12:05:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,737 | cpp | #include<iostream>
#include<cstring>
#include"String.h"
String::String()
{
len=0;
str=new char[1];
str[0]='\0';
}
String::String(const char* st)
{
len=std::strlen(st);
str=new char[len+1];
std::strcpy(str,st);
}
String::String(const String &st)
{
len=st.len;
str=new char[len+1];
std::strcpy(str,st.str);
}
int String::length()
{
len=std::strlen(str);
return len;
}
String::~String()
{
delete [] str;
}
const char* String::c_str() const
{
return str;
}
String& String::operator=(const String& st)
{
if(this==&st)
return *this;
delete [] str;
len=st.len;
str=new char[len+1];
std::strcpy(str,st.str);
return *this;//returns a refernce to yoursself(i.e, return refence of the invoking object)
}
String& String::operator=(const char* st)//LHS waala object String object hoga while RHS waala const char* type ka hoga!!!
{
delete [] str;
len=std::strlen(st);
str=new char[len+1];
std::strcpy(str,st);
return *this; //returns a refernce to yoursself(i.e, return refence of the invoking object)
// yahan NOTICE karo ki hum (return *this) kar rahe h naa ki (return str) coz former m ek pointer string
// return hoga while latter m String object return hoga ...an humaare prototyppe k accoording hume return
// invoking String object hi karna h jo ki sirf (*this) se hi ho sakta h.
}
const String& String::operator+=(const String& st)
{
int templen;
templen=st.len+len;
char *temp=new char[templen+1];
std::strcpy(temp,str);
std::strcat(temp,st.str);
*this=temp; // this is operator overloading of = operator of (const char* type)[L.H.S is a str.ing objeect and R.H.S is cons char* type].
return *this;
/*
U can also think this way which is a wrong path
str=temp; // ye nhi ho sakta coz isme str and temp dono ho string pointer h const char* type waale.
Thus, ye dono hi ek hi string ko point karenge.
temp ek temprory variable h and therefore jab iss function ka execution khatm hoga then the block of memory pointed by
temp will get deleted and so str pointer would be pointing smwhere undefined.
*this=temp will invoke const char* type of = overloaded operator which wii work fine.
return str; //ye nhi hoga coz hume ek string object return karna h na ki ek string pointer.
*/
}
bool operator==(const String& st1,const String& st2)
{
return (std::strcmp(st1.str,st2.str)==0);
}
bool operator<(const String& st1, const String& st2)
{
return (std::strcmp(st1.str,st2.str)<0);
}
bool operator>(const String& st1, const String& st2)
{
return (std::strcmp(st1.str,st2.str)>0);
}
char& String::operator[](int i)
{
return str[i];
}
std::ostream& operator<<(std::ostream& os, const String& st)
{
os<<st.str;
return os;
}
std::istream& operator>>(std::istream& is, String& st)//NHI CLEAR HAI!!!!!!!
{
char temp[String::CINMAX];
is.get(temp,String::CINMAX);// why didnt we used getline function here??...if u use getline function here then after input of the string u have to ENTER two times to see the output.
if(is)
st=temp; // shouldnt it be st.str=temp?//this is operator overloading of = operator of (const char* type).[L.H.S is a str.ing objeect and R.H.S is cons char* type
while(is&&is.get()!='\n')// couldnt understand this loop.This loop is basically to remove the strays of character from the input streaam.
continue;
return is;
}
std::istream& getline(std::istream& in, String& st)// NHI CLEAR HAI!!!!
{
char ch;
while(in.get(ch)&&ch!='\n')
st.str+=ch;
return in;
}
| [
"lohani.ayush@gmail.com"
] | lohani.ayush@gmail.com |
d555cd6225e1e7085330379b47f7bb13d25ce7d3 | 5679731cee36c537615d285ed72810f4c6b17380 | /011_ContainerWithMostWater.cpp | 781e6f69bc2774638d57559f90d7b218c11ab98c | [] | no_license | manofmountain/LeetCode | 6b76105190a9b62df65a7b56b6def4120498b9fa | 718f688b3d316e8c10ef680d9c21ecd518d062f8 | refs/heads/master | 2021-01-12T03:41:48.318116 | 2017-07-18T12:35:58 | 2017-07-18T12:35:58 | 78,252,164 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 878 | cpp | //29.38%
class Solution {
public:
int maxArea(vector<int>& height) {
int left(0), right(height.size() - 1), maxRes(-1);
while(left < right){
if(height[left] > height[right]){
int lowerBound(height[right]);
maxRes = max(maxRes, lowerBound * (right - left));
while(height[--right] <= lowerBound);
}else{
int lowerBound(height[left]);
maxRes = max(maxRes, lowerBound * (right - left));
while(left < right && height[++left] <= lowerBound);
}
}
return maxRes;
}
};
//A more clear way
int maxArea(vector<int>& height) {
int water = 0;
int i = 0, j = height.size() - 1;
while (i < j) {
int h = min(height[i], height[j]);
water = max(water, (j - i) * h);
while (height[i] <= h && i < j) i++;
while (height[j] <= h && i < j) j--;
}
return water;
} | [
"noreply@github.com"
] | manofmountain.noreply@github.com |
ef77374d7b29a90bd26fa7bbc7f5026765643c34 | b193a4bf6ab67851256cca7f2f3259a5c57d7180 | /ZSUM.cpp | 2de45bedfc78f74bc3ed660d0cc3afc44691ac5a | [] | no_license | kaushik12048/Spoj_Solutions | ec133fb82bd6b1e9fe20a156183d111d42b21f07 | 20a893fd5ea9bd108ec367ddce71d3092ab63a4c | refs/heads/master | 2016-08-10T11:56:05.796740 | 2015-05-25T06:56:24 | 2015-05-25T06:56:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 493 | cpp | #include<bits/stdc++.h>
using namespace std;
#define m 10000007
long long int mod(long long int x,long long int y){
long long int ans=1;
long long int t=x;
while(y>0)
{
if(y%2==1)
ans=(ans*t)%m;
y=y>>1;
t=(t*t)%m;
}
return ans;
}
int main()
{
while(1){
long long int n,k,ans;
scanf("%lld %lld",&n,&k);
if(n==0 && k==0)
break;
ans=(mod(n,k)%m)+(mod(n,n)%m)+2*(mod(n-1,k)%m)+2*(mod(n-1,n-1)%m);
printf("%lld\n",ans%m);
}
return 0;
}
| [
"kaushik12048@iiitd.ac.in"
] | kaushik12048@iiitd.ac.in |
1ecf73072fefc3cb87c5daf1ef6e72abd829ca97 | 6fcf6e0ace3541a78e6aab26a98bf9c0a8fd879e | /src/bmplib.cpp | 330e68b4a7a73291e03d4e08424bc422a610b793 | [] | no_license | allusai/Chromakey | a3e5f6f858517a80cd9d66b1de965fe5fbca4d35 | dbb59122e8d9530bce8a3e4a31f0e358aa3cebf7 | refs/heads/master | 2021-08-20T05:31:16.447787 | 2017-11-28T08:23:19 | 2017-11-28T08:23:19 | 106,965,275 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 12,216 | cpp | #include <stdio.h>
#include <iostream>
#include <cstdlib>
#include "bmplib.h"
#include "unistd.h"
using namespace std;
using std::cout;
using std::cin;
using std::endl;
typedef unsigned char uint8;
typedef unsigned short int uint16;
typedef unsigned int uint32;
//#define BMP_BIG_ENDIAN
#define BYTE_SWAP(num) (((num>>24)&0xff) | ((num<<8)&&0xff0000) | ((num>>8)&0xff00) | ((num<<24)&0xff000000))
typedef struct {
uint8 bfType1;
uint8 bfType2;
uint32 bfSize;
uint16 bfReserved1;
uint16 bfReserved2;
uint32 bfOffBits;
uint32 biSize; // size of structure, in bytes
uint32 biWidth; // bitmap width, in pixels
uint32 biHeight; // bitmap height, in pixels
uint16 biPlanes; // see below
uint16 biBitCount; // see below
uint32 biCompression; // see below
uint32 biSizeImage; // see below
uint32 biXPelsPerMeter; // see below
uint32 biYPelsPerMeter; // see below
uint32 biClrUsed; // see below
uint32 biClrImportant; // see below
} BITMAPFILEHEADER, *PBITMAPFILEHEADER;
typedef struct {
uint8 rgbBlue;
uint8 rgbGreen;
uint8 rgbRed;
} RGBTRIPLE;
void write_hdr(uint8 *hdr, int *hdr_idx, uint32 data, uint32 size);
uint8 tempImage[SIZE][SIZE][RGB];
uint8 tempGSImage[SIZE][SIZE];
int readRGBBMP(const char* filename, unsigned char inputImage[][SIZE][RGB])
{
uint8 type[2];
int headersize = 0;
int i,j,k;
//BITMAPFILEHEADER bfh;
/* file pointer */
FILE *file;
/* read input bmp into the data matrix */
if (!(file=fopen(filename,"rb")))
{
cout << "Cannot open file: " << filename <<endl;
return(1);
}
fread(type, sizeof(unsigned char), 0x2, file);
if(type[0] != 'B' and type[1] != 'M'){
cout << "Not a BMP file" << endl;
return(1);
}
fseek(file, 8, SEEK_CUR);
fread(&headersize, sizeof(uint32), 1, file);
#ifdef BMP_BIG_ENDIAN
headersize = BYTE_SWAP(headersize);
#endif
//cout << "Header size is " << headersize << endl;
fseek(file, headersize, SEEK_SET);
fread(tempImage, sizeof(uint8), SIZE*SIZE*RGB, file);
//cout << (int)tempImage[0][0][0] << "," << (int)tempImage[0][0][1] << "," << (int)tempImage[0][0][2] << endl;
fclose(file);
for(i=0; i < SIZE; i++){
for(j=0; j < SIZE; j++){
for(k=0; k < RGB; k++){
inputImage[SIZE-1-i][j][RGB-1-k] = tempImage[i][j][k];
//cerr << tempImage[i][j][k] << ",";
}
}
//cerr << endl;
}
return 0;
}
int writeRGBBMP(const char* filename, unsigned char outputImage[][SIZE][RGB])
{
uint8 hdr[54];
int hdr_idx = 0;
int i,j,k;
BITMAPFILEHEADER bfh;
// file pointer
FILE *file;
bfh.bfType1 = 'B';
bfh.bfType2 = 'M';
bfh.bfSize = 0x36;
bfh.bfReserved1 = 0x0;
bfh.bfReserved2 = 0x0;
bfh.bfOffBits = 0x36;
bfh.biSize = 0x28;
bfh.biWidth = SIZE;
bfh.biHeight = SIZE;
bfh.biPlanes = 1;
bfh.biBitCount = 24;
bfh.biCompression = 0;
bfh.biSizeImage = sizeof(RGBTRIPLE)*SIZE*SIZE;
bfh.biXPelsPerMeter = 2400;
bfh.biYPelsPerMeter = 2400;
bfh.biClrUsed = 0;
bfh.biClrImportant = 0;
write_hdr(hdr, &hdr_idx, bfh.bfType1, sizeof(uint8));
write_hdr(hdr, &hdr_idx, bfh.bfType2, sizeof(uint8));
write_hdr(hdr, &hdr_idx, bfh.bfSize, sizeof(uint32));
write_hdr(hdr, &hdr_idx, bfh.bfReserved1, sizeof(uint16));
write_hdr(hdr, &hdr_idx, bfh.bfReserved2, sizeof(uint16));
write_hdr(hdr, &hdr_idx, bfh.bfOffBits, sizeof(uint32));
write_hdr(hdr, &hdr_idx, bfh.biSize, sizeof(uint32));
write_hdr(hdr, &hdr_idx, bfh.biWidth, sizeof(uint32));
write_hdr(hdr, &hdr_idx, bfh.biHeight, sizeof(uint32));
write_hdr(hdr, &hdr_idx, bfh.biPlanes, sizeof(uint16));
write_hdr(hdr, &hdr_idx, bfh.biBitCount, sizeof(uint16));
write_hdr(hdr, &hdr_idx, bfh.biCompression, sizeof(uint32));
write_hdr(hdr, &hdr_idx, bfh.biSizeImage, sizeof(uint32));
write_hdr(hdr, &hdr_idx, bfh.biXPelsPerMeter, sizeof(uint32));
write_hdr(hdr, &hdr_idx, bfh.biYPelsPerMeter, sizeof(uint32));
write_hdr(hdr, &hdr_idx, bfh.biClrUsed, sizeof(uint32));
write_hdr(hdr, &hdr_idx, bfh.biClrImportant, sizeof(uint32));
for(i=0; i < SIZE; i++){
for(j=0; j < SIZE; j++){
for(k=0; k < RGB; k++){
tempImage[SIZE-1-i][j][RGB-1-k] = outputImage[i][j][k];
}
}
}
// write result bmp file
if (!(file=fopen(filename,"wb")))
{
cout << "Cannot open file: " << filename << endl;
return(1);
}
fwrite(&hdr, sizeof(unsigned char), 0x36, file);
fwrite(tempImage, sizeof(unsigned char), SIZE*SIZE*RGB, file);
fclose(file);
return 0;
}
void write_hdr(uint8 *hdr, int *hdr_idx, uint32 data, uint32 size)
{
if(size == 1){
hdr[*hdr_idx] = (uint8) data;
(*hdr_idx) += 1;
}
else if(size == 2){
hdr[*hdr_idx] = (uint8) (data & 0x00ff);
(*hdr_idx) += 1;
hdr[*hdr_idx] = (uint8) ((data & 0xff00) >> 8);
(*hdr_idx) += 1;
}
else if(size == 4){
hdr[*hdr_idx] = (uint8) (data & 0x000000ff);
(*hdr_idx) += 1;
hdr[*hdr_idx] = (uint8) ((data & 0x0000ff00) >> 8);
(*hdr_idx) += 1;
hdr[*hdr_idx] = (uint8) ((data & 0x00ff0000) >> 16);
(*hdr_idx) += 1;
hdr[*hdr_idx] = (uint8) ((data & 0xff000000) >> 24);
(*hdr_idx) += 1;
}
else {
printf("Illegal size in write_hdr...consult your instructor\n");
}
}
int readGSBMP(const char* filename, unsigned char inputImage[][SIZE])
{
uint8 type[2];
int headersize = 0;
int i,j;
//BITMAPFILEHEADER bfh;
/* file pointer */
FILE *file;
/* read input bmp into the data matrix */
if (!(file=fopen(filename,"rb")))
{
cout << "Cannot open file: " << filename <<endl;
return(1);
}
fread(type, sizeof(unsigned char), 0x2, file);
if(type[0] != 'B' and type[1] != 'M'){
cout << "Not a BMP file" << endl;
return(1);
}
fseek(file, 8, SEEK_CUR);
fread(&headersize, sizeof(uint32), 1, file);
#ifdef BMP_BIG_ENDIAN
headersize = BYTE_SWAP(headersize);
#endif
//cout << "Header size is " << headersize << endl;
fseek(file, headersize, SEEK_SET);
fread(tempGSImage, sizeof(uint8), SIZE*SIZE, file);
// cout << (int)tempGSImage[0][0][0] << "," << (int)tempGSImage[0][0][1] << "," << (int)tempGSImage[0][0][2] << endl;
fclose(file);
for(i=0; i < SIZE; i++){
for(j=0; j < SIZE; j++){
inputImage[SIZE-1-i][j] = tempGSImage[i][j];
// inputImage[SIZE-1-i][SIZE-1-j] = tempGSImage[i][j];
//cerr << tempGSImage[i][j][k] << ",";
}
//cerr << endl;
}
return 0;
}
int writeGSBMP(const char* filename, unsigned char outputImage[][SIZE])
{
uint8 hdr[54];
int hdr_idx = 0;
int i,j;
BITMAPFILEHEADER bfh;
// file pointer
FILE *file;
bfh.bfType1 = 'B';
bfh.bfType2 = 'M';
// 0x10436 = 2^16 + 1024 for color def + 0x36 for header
bfh.bfSize = 0x010436; //0x36;
bfh.bfReserved1 = 0x0;
bfh.bfReserved2 = 0x0;
// 0x0436
bfh.bfOffBits = 0x436; //0x36;
bfh.biSize = 0x28;
bfh.biWidth = SIZE;
bfh.biHeight = SIZE;
bfh.biPlanes = 1;
bfh.biBitCount = 8;
bfh.biCompression = 0;
bfh.biSizeImage = SIZE*SIZE;
bfh.biXPelsPerMeter = 0; //2400;
bfh.biYPelsPerMeter = 0; //2400;
bfh.biClrUsed = SIZE; // 0;
bfh.biClrImportant = SIZE; // 0;
write_hdr(hdr, &hdr_idx, bfh.bfType1, sizeof(uint8));
write_hdr(hdr, &hdr_idx, bfh.bfType2, sizeof(uint8));
write_hdr(hdr, &hdr_idx, bfh.bfSize, sizeof(uint32));
write_hdr(hdr, &hdr_idx, bfh.bfReserved1, sizeof(uint16));
write_hdr(hdr, &hdr_idx, bfh.bfReserved2, sizeof(uint16));
write_hdr(hdr, &hdr_idx, bfh.bfOffBits, sizeof(uint32));
write_hdr(hdr, &hdr_idx, bfh.biSize, sizeof(uint32));
write_hdr(hdr, &hdr_idx, bfh.biWidth, sizeof(uint32));
write_hdr(hdr, &hdr_idx, bfh.biHeight, sizeof(uint32));
write_hdr(hdr, &hdr_idx, bfh.biPlanes, sizeof(uint16));
write_hdr(hdr, &hdr_idx, bfh.biBitCount, sizeof(uint16));
write_hdr(hdr, &hdr_idx, bfh.biCompression, sizeof(uint32));
write_hdr(hdr, &hdr_idx, bfh.biSizeImage, sizeof(uint32));
write_hdr(hdr, &hdr_idx, bfh.biXPelsPerMeter, sizeof(uint32));
write_hdr(hdr, &hdr_idx, bfh.biYPelsPerMeter, sizeof(uint32));
write_hdr(hdr, &hdr_idx, bfh.biClrUsed, sizeof(uint32));
write_hdr(hdr, &hdr_idx, bfh.biClrImportant, sizeof(uint32));
for(i=0; i < SIZE; i++){
for(j=0; j < SIZE; j++){
//tempGSImage[SIZE-1-i][SIZE-1-j] = outputImage[i][j];
tempGSImage[SIZE-1-i][j] = outputImage[i][j];
}
}
// write result bmp file
if (!(file=fopen(filename,"wb")))
{
cout << "Cannot open file: " << filename << endl;
return(1);
}
uint8 z = 0;
fwrite(&hdr, sizeof(unsigned char), 0x36, file);
for(i=0; i < SIZE; i++){
uint8 x = (uint8) i;
//cout << (int)x << endl;
fwrite(&x, sizeof(uint8), 0x01, file);
fwrite(&x, sizeof(uint8), 0x01, file);
fwrite(&x, sizeof(uint8), 0x01, file);
fwrite(&z, sizeof(uint8), 0x01, file);
}
fwrite(tempGSImage, sizeof(unsigned char), SIZE*SIZE, file);
fclose(file);
return 0;
}
// int readGS_BMP(char filename[], unsigned char image[][SIZE], BMPHDR *hdr)
// {
// int i,j;
// // Open the file for reading and ensure it opened successfully
// // Print a message and return -1 if it fails
// ifstream ifile(filename);
// if( ! ifile.good() ){
// cerr << "Unable to open file: " << filename << endl;
// return -1;
// }
// BMPTYPE type;
// // Read in the BMP Header
// ifile.read( reinterpret_cast<char *>(&type), sizeof(BMPTYPE) );
// // Check its the format we want
// if(type.signature[0] != 'B' && type.signature[1] != 'M'){
// cerr << "Not a BMP file" << endl;
// return -1;
// }
// // Read in the BMP Header
// ifile.read( reinterpret_cast<char *>(hdr), sizeof(BMPHDR) );
// // Print out the file size in bytes and the byte offset to the pixel array
// cout << "Size of the file: " << hdr->fh.fileSize << endl;
// cout << "Pixel offset: " << hdr->fh.pixelOffset << endl;
// // Print out the dimensions (height x width) read in from the file header
// cout << "Dimensions: " << hdr->bh.height << "x" << hdr->bh.width << endl;
// // Print out the color depth (planes * bits_per_pixel)
// // read in from the file header
// cout << "Color depth: " << hdr->bh.planes * hdr->bh.bpp << endl;
// // Seek to the point in the file where the pixel data starts
// ifile.seekg(hdr->fh.pixelOffset, ios::beg);
// // Ensure the SEEK (read) pointer of the FILE is now pointing at the
// // pixel array
// // Data is read in opposite order (it is stored backwards in the file)
// for(i=0; i < SIZE; i++){
// for(j=0; j < SIZE; j++){
// ifile.read( reinterpret_cast<char *>(&image[SIZE-1-i][j]), sizeof(uint8));
// }
// }
// return 0;
// }
// int writeGS_BMP(char *filename, uint8 outputImage[][SIZE], BMPHDR *hdr)
// {
// ofstream ofile(filename);
// if(! ofile.good() ){
// cerr << "Can't open file: " << filename << endl;
// return -1;
// }
// BMPTYPE type;
// type.signature[0] = 'B';
// type.signature[1] = 'M';
// ofile.write( reinterpret_cast<char *>(&type), sizeof(BMPTYPE) );
// // Write the hdr (which is of size: sizeof(BMPHDR size) ) data to the file
// ofile.write( reinterpret_cast<char *>(hdr), sizeof(BMPHDR) );
// // For bits_per_pixel <= 8 we have to write in the color table
// uint8 colorVal[4] = {0,0,0,0};
// for(int i=0; i < SIZE; i++){
// colorVal[0] = colorVal[1] = colorVal[2] = i;
// ofile.write( reinterpret_cast<char *>(colorVal), 4*sizeof(uint8) );
// }
// // Write the data in opposite order
// for(int i=0; i < SIZE; i++){
// for(int j=0; j < SIZE; j++){
// ofile.write( reinterpret_cast<char *>(&outputImage[SIZE-1-i][j]), sizeof(uint8) );
// }
// }
// ofile.close();
// return 0;
// }
int shows = 0;
void show() {
system("eog --single-window /tmp/bmplib.bmp &");
// wait longer on the first show, OS takes time to start eog
if (shows == 0) sleep(1);
// generally, wait 0.2 seconds = 200000 milliseconds
usleep(200000);
shows++;
}
void showRGBBMP(unsigned char inputImage[][SIZE][RGB]) {
writeRGBBMP("/tmp/bmplib.bmp", inputImage);
show();
}
void showGSBMP(unsigned char inputImage[][SIZE]) {
writeGSBMP("/tmp/bmplib.bmp", inputImage);
show();
}
| [
"noreply@github.com"
] | allusai.noreply@github.com |
3a5d2291822cb44be7b1167ff28a97806225df60 | 0a9efa427df98fc6ce599a929b8b0c137a3d2eb7 | /XML Parser/main.cpp | f1bcdb49660eae350959fff422f56dc8a5342ffa | [] | no_license | jdkizer9/cs540p1 | 1e820a2bffc5e7bf0edc76f2836be88818bdd000 | 16bf7f65da8fba11c9cc08a438d35d0cbc323a31 | refs/heads/master | 2016-09-01T18:28:39.963097 | 2013-12-24T16:52:16 | 2013-12-24T16:52:16 | 30,951,390 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,704 | cpp | //
// main.cpp
// XML Parser
//
// Created by James Kizer on 2/18/13.
// Copyright (c) 2013 James Kizer. All rights reserved.
//
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <iostream>
#include "Parser.hpp"
#include "Element.hpp"
#include "Text.hpp"
#include "Visitor.hpp"
#include <string.h>
#include <errno.h>
#include <sys/time.h>
#include <new>
#include <execinfo.h>
#include <stdio.h>
#include <regex.h>
#include <cxxabi.h>
using namespace xml;
using namespace std;
int main(int argc, const char * argv[])
{
char infile[32];
int ec;
// insert code here...
printf("Hello, World!\n");
strncpy(infile, "test.xml", sizeof(infile));
int fd = open(infile, O_RDONLY);
if (fd < 0) {
cerr << "Open file failed : " << strerror(errno) << endl;
return 1;
}
struct stat sb;
ec = fstat(fd, &sb);
if ( ec != 0) {
cerr << "Get file information failed : " << strerror(errno)<<endl;
return 1;
}
const char *doc = (const char *) mmap(NULL, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
if(doc == MAP_FAILED) {
cerr << "mmap document failed : " << strerror(errno) << endl;
return 1;
}
Parser parser;
const Element *r, *r2;
cout<<"Calling Parser"<<endl;
r = parser.parse(doc, sb.st_size);
cout<<"Returned from Parser\nDeleting Root Node"<<endl;
cout<<"Calling Parser"<<endl;
r2 = parser.parse(doc, sb.st_size);
cout<<"Returned from Parser\nDeleting Root Node"<<endl;
delete r;
return 0;
}
| [
"jk@Jamess-MacBook-Pro.local"
] | jk@Jamess-MacBook-Pro.local |
18658de618a466dd243c8f9b9f42e41971a7f707 | f379e7d99b72f44a71d76066fdf68406ae9187c0 | /GameClient/character.h | 7056376f1c34550475673dba4591aa933e21dcc7 | [] | no_license | Weaver-JS/Redes_UDP_Taller_6 | 09fc962da6204e7ba423b0b3b97fb86c67a05280 | 1660f33cf2a8a30d6f4cc27fe89648aa9aa41018 | refs/heads/master | 2021-01-19T09:10:47.282164 | 2017-04-09T20:11:05 | 2017-04-09T20:11:05 | 87,736,021 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 430 | h | #include "SFML\System.hpp"
#include "SFML\Graphics.hpp"
#define RADIUS 60
class character
{
private:
sf::Vector2<int16_t> position;
sf::Texture circle_texture;
sf::CircleShape* circle_shape;
//character();
public:
character(int16_t x, int16_t y);
character(sf::Vector2<int16_t> pos);
~character();
sf::Vector2<int16_t> & getPosition();
void setPosition(sf::Vector2<int16_t> & v);
sf::CircleShape* getCircleshape();
}; | [
"josesweaver@gmail.com"
] | josesweaver@gmail.com |
e1017088228e88f1ab878575d80b67087d678230 | d5adbe2194ef53fa93c2d643398638b302e6c326 | /Procedural-Midi/MidiAsset/Source/ProceduralAudio/Public/ProceduralAudio.h | 17b00c30cf24740f811a5cea6fde2c3eafccc09d | [] | no_license | risooonho/Midi-Unreal | 4fe8f8f036120068624bd2d5f13103f4894d88de | b08b2d5ab1c2f5f01e9cb66f49d80335a716f6fe | refs/heads/main | 2022-11-15T07:20:14.593335 | 2020-06-30T02:28:15 | 2020-06-30T02:28:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 271 | h | // Copyright -> Scott Bishel
#pragma once
#include "Modules/ModuleManager.h"
class FProceduralAudioModule : public IModuleInterface
{
public:
/** IModuleInterface implementation */
virtual void StartupModule() override;
virtual void ShutdownModule() override;
}; | [
"scott.bishel@yahoo.com"
] | scott.bishel@yahoo.com |
6132857258158331acc820f30497a3cf1a49e1f9 | 5c0a7c7ae18ce37c29f93f2272166fe759569643 | /C-pp/chapter12/12.7.cpp | 5a2a7131d2e4e413419858c3d6be73b28751f4a6 | [] | no_license | liushengxi13689209566/Programming-language-learning | 21a330c257f56f2f3f0ed3525d2faf76bdc0eb31 | fcc6b10a852a0dcc2dce41f0abaa438f92a34a80 | refs/heads/master | 2020-04-07T02:36:00.268533 | 2019-04-15T08:34:29 | 2019-04-15T08:34:29 | 157,982,315 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 726 | cpp | /*************************************************************************
> File Name: 12.6.cpp
> Author:
> Mail:
> Created Time: 2018年02月17日 星期六 19时09分38秒
************************************************************************/
#include<iostream>
#include<vector>
#include<string>
#include<new>
using namespace std;
vector<int> *fun(){
auto vec = new vector<int> ;
return vec ;
}
void input(vector<int> *ptr){
int temp ;
for(int i=0;i< 5 ;++i){
cin >> temp ;
ptr->push_back(temp);
}
}
auto print(vector<int> *ptr) -> ostream & {
for(auto i : *ptr)
cout << i << " ";
return cout ;
}
int main(void){
auto ptr = fun();
input(ptr);
print(ptr) << endl ;
delete ptr ;
return 0 ;
}
| [
"liushengxi13689209566@163.com"
] | liushengxi13689209566@163.com |
5535ef017b5009e4c3b9832878265c24668c4be2 | f95975d9454984803586de7f0600f3ecf9918f60 | /include/algorithms/pca/pca_batch.h | 42d322025b37407989cd7393bd58b654c960a42b | [
"Intel",
"Apache-2.0"
] | permissive | jjuribe/daal | f4e05656ca5f01e56debdbd2de51eeb2f506ca3d | 242d358db584dd4c9c65826b345fe63313ff8f2a | refs/heads/master | 2020-09-15T01:33:34.752543 | 2019-11-21T08:27:26 | 2019-11-21T08:27:26 | 223,316,648 | 0 | 0 | Apache-2.0 | 2019-11-22T03:33:41 | 2019-11-22T03:33:39 | null | UTF-8 | C++ | false | false | 6,600 | h | /* file: pca_batch.h */
/*******************************************************************************
* Copyright 2014-2019 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
/*
//++
// Implementation of the interface for the PCA algorithm in the batch processing mode
//--
*/
#ifndef __PCA_BATCH_H__
#define __PCA_BATCH_H__
#include "algorithms/algorithm.h"
#include "data_management/data/numeric_table.h"
#include "services/daal_defines.h"
#include "services/daal_memory.h"
#include "algorithms/pca/pca_types.h"
namespace daal
{
namespace algorithms
{
namespace pca
{
namespace interface3
{
/**
* \brief Contains version 3.0 of Intel(R) Data Analytics Acceleration Library (Intel(R) DAAL) interface.
*/
/**
* <a name="DAAL-CLASS-ALGORITHMS__PCA__BATCHCONTAINER"></a>
* \brief Class containing methods to compute the results of the PCA algorithm */
template<typename algorithmFPType, Method method, CpuType cpu>
class BatchContainer : public AnalysisContainerIface<batch>
{};
/**
* <a name="DAAL-CLASS-ALGORITHMS__PCA__BATCHCONTAINER_ALGORITHMFPTYPE_CORRELATIONDENSE_CPU"></a>
* \brief Class containing methods to compute the results of the PCA algorithm */
template<typename algorithmFPType, CpuType cpu>
class BatchContainer<algorithmFPType, correlationDense, cpu> : public AnalysisContainerIface<batch>
{
public:
/**
* Constructs a container for the PCA algorithm with a specified environment
* in the batch processing mode
* \param[in] daalEnv Environment object
*/
BatchContainer(daal::services::Environment::env *daalEnv);
/** Default destructor */
~BatchContainer();
/**
* Computes the result of the PCA algorithm in the batch processing mode
*/
services::Status compute() DAAL_C11_OVERRIDE;
};
/**
* @defgroup pca_batch Batch
* @ingroup pca
* @{
*/
/**
* <a name="DAAL-CLASS-ALGORITHMS__PCA__BATCHCONTAINER_ALGORITHMFPTYPE_SVDDENSE_CPU"></a>
* \brief Class containing methods to compute the results of the PCA algorithm */
template<typename algorithmFPType, CpuType cpu>
class BatchContainer<algorithmFPType, svdDense, cpu> : public AnalysisContainerIface<batch>
{
public:
/**
* Constructs a container for the PCA algorithm with a specified environment
* in the batch processing mode
* \param[in] daalEnv Environment object
*/
BatchContainer(daal::services::Environment::env *daalEnv);
/** Default destructor */
~BatchContainer();
/**
* Computes the result of the PCA algorithm in the batch processing mode
*/
services::Status compute() DAAL_C11_OVERRIDE;
};
/**
* <a name="DAAL-CLASS-ALGORITHMS__PCA__BATCH"></a>
* \brief Computes the results of the PCA algorithm
* <!-- \n<a href="DAAL-REF-PCA-ALGORITHM">PCA algorithm description and usage models</a> -->
*
* \tparam algorithmFPType Data type to use in intermediate computations for PCA, double or float
* \tparam method PCA computation method, \ref Method
*
* \par Enumerations
* - \ref Method Computation methods for the algorithm
*/
template<typename algorithmFPType = DAAL_ALGORITHM_FP_TYPE, Method method = correlationDense>
class DAAL_EXPORT Batch : public Analysis<batch>
{
public:
typedef algorithms::pca::Input InputType;
typedef algorithms::pca::BatchParameter<algorithmFPType, method> ParameterType;
typedef algorithms::pca::Result ResultType;
/** Default constructor */
Batch()
{
initialize();
}
/**
* Constructs a PCA algorithm by copying input objects and parameters of another PCA algorithm
* \param[in] other An algorithm to be used as the source to initialize the input objects
* and parameters of the algorithm
*/
Batch(const Batch<algorithmFPType, method> &other) : input(other.input), parameter(other.parameter)
{
initialize();
}
~Batch() {}
/**
* Returns method of the algorithm
* \return Method of the algorithm
*/
virtual int getMethod() const DAAL_C11_OVERRIDE { return method; };
/**
* Registers user-allocated memory to store the results of the PCA algorithm
* \param[in] res Structure for storing the results of the PCA algorithm
*/
services::Status setResult(const ResultPtr& res)
{
DAAL_CHECK(res, services::ErrorNullResult)
_result = res;
_res = _result.get();
return services::Status();
}
/**
* Returns the structure that contains final results of the PCA algorithm
* \return Structure that contains final results of the PCA
*/
ResultPtr getResult() { return _result; }
/**
* Returns a pointer to the newly allocated PCA algorithm
* with a copy of input objects and parameters of this PCA algorithm
* \return Pointer to the newly allocated algorithm
*/
services::SharedPtr<Batch<algorithmFPType, method> > clone() const
{
return services::SharedPtr<Batch<algorithmFPType, method> >(cloneImpl());
}
InputType input; /*!< Input data structure */
BatchParameter<algorithmFPType, method> parameter; /*!< Parameters */
protected:
ResultPtr _result;
virtual Batch<algorithmFPType, method> * cloneImpl() const DAAL_C11_OVERRIDE
{
return new Batch<algorithmFPType, method>(*this);
}
services::Status allocateResult() DAAL_C11_OVERRIDE
{
services::Status s = _result->allocate<algorithmFPType>(&input, ¶meter, method);
_res = _result.get();
return s;
}
void initialize()
{
_ac = new __DAAL_ALGORITHM_CONTAINER(batch, BatchContainer, algorithmFPType, method)(&_env);
_in = &input;
_par = ¶meter;
_result.reset(new ResultType());
}
};
/** @} */
} // namespace interface3
using interface3::BatchContainer;
using interface3::Batch;
} // namespace pca
} // namespace algorithms
} // namespace daal
#endif
| [
"nikolay.a.petrov@intel.com"
] | nikolay.a.petrov@intel.com |
adbe0a572c903fa1fa934b5ed54bd2ba47c577e7 | 2624367eff0831094a2f5a76f41f69ee70a7940b | /Stuff/SmartcardWrap.h | 8eb05e0325b5da4e9e245d00011597a0f3807c42 | [
"MIT"
] | permissive | cabralfilho/Omnikey-SyncAPI-NodeJS-Wrapper | 1086b9a628ee037b23a712ecbd4eb7b94eb588c3 | 360c15eaa56bd3b28a417dc6ca2cac24aba3eb24 | refs/heads/master | 2021-04-19T07:08:06.690460 | 2019-05-10T18:55:28 | 2019-05-10T18:55:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 575 | h | #include <napi.h>
#include "SmartcardClass.h"
class Smartcard : public Napi::ObjectWrap<Smartcard> {
public:
static Napi::Object Init(Napi::Env, Napi::Object exports);
Smartcard(const Napi::CallbackInfo& info);
SmartcardClass* GetInternalInstance();
private:
static Napi::FunctionReference constructor;
Napi::Value read(const Napi::CallbackInfo& info);
Napi::Value write(const Napi::CallbackInfo& info);
Napi::Value reset(const Napi::CallbackInfo& info);
SmartcardClass* candy;
}; | [
"meatdeli97@gmail.com"
] | meatdeli97@gmail.com |
576ff1b74182d3aa4db3122acf1197fe05607512 | 67a53e3ba09a6b8f83fc1d40b85b5941310702bd | /src/lib/collision_prevention/CollisionPreventionTest.cpp | 0e4940f16e9809f6e3dcac27bf7d11286981be80 | [
"BSD-3-Clause"
] | permissive | Diksha-agg/Firmware_val | f3bd60c7356b2f21b8c8ea4db98955f41d43e848 | 1efc1ba06997d19df3ed9bd927cfb24401b0fe03 | refs/heads/main | 2023-07-13T11:12:47.831945 | 2021-08-26T02:06:15 | 2021-08-26T02:06:15 | 397,618,511 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 130 | cpp | version https://git-lfs.github.com/spec/v1
oid sha256:f6a2c2503ff0077fd1e33be104473da29d3bd41fe5a428edbbcac3dafd2e99eb
size 44642
| [
"diksha.dtu@gmail.com"
] | diksha.dtu@gmail.com |
b5d7813c37270cae361e3525bb606eccc31f41c1 | 0bcf6cf143f30781288d67d23ef3fa5efdf10b94 | /cs16/lab05/pointsApproxEqualTest.cpp | bb98c90f74bd9bf2bd50a4e5fcbe7e7f367abbe8 | [] | no_license | Gopu2001/ucsb_ccs_labs | e787f2f2a330a512563cd9d1f03b09693c045278 | c02ae4c698bd8e9e1662c8ad09c3ce4a504180d5 | refs/heads/master | 2023-01-29T18:43:20.583703 | 2020-12-14T21:40:22 | 2020-12-14T21:40:22 | 301,958,082 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 500 | cpp | #include "shapes.h"
#include "shapeFuncs.h"
#include "tddFuncs.h"
int main() {
struct Point p1,p2;
p1.x = 6.0; p1.y = 3.0;
p2.x = 7.0; p2.y = 11.0;
// p1 should be equal to itself
assertTrue(pointsApproxEqual(p1,p1),"pointsApproxEqual(p1,p1)");
// p1 and p2 should not be equal: note the ! meaning "not"
assertFalse(pointsApproxEqual(p1,p2), "pointsApproxEqual(p1,p2)");
assertFalse(pointsApproxEqual(p2,p1), "assertFalse(pointsApproxEqual(p2,p1))");
}
| [
"41317321+Gopu2001@users.noreply.github.com"
] | 41317321+Gopu2001@users.noreply.github.com |
a4c738092670555d782242981acc39cf48ad0f2b | aec7485b03ce1883db548f26b71b4fda2555130d | /GLSLCookbook/GLSLProgram.cpp | edbe9e714d7643b2a551f19a12f6a21f858bd85a | [] | no_license | Sunnyoung/OpenGL-Shading-Cookbook | d5d7a6071a21063ca3b068ff26926869fda34fd5 | 0a25c436e2b9948871b3a814eb966eb5121b6c98 | refs/heads/master | 2016-09-11T02:25:49.814410 | 2014-03-02T13:22:33 | 2014-03-02T13:22:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,565 | cpp | #include "GLSLProgram.h"
#include <fstream>
#include <sstream>
using namespace glm;
using namespace std;
GLSLProgram::GLSLProgram(const std::string &vertexfile, const std::string &fragfile) : mIsDebug(true){
mProgram = createProgram(vertexfile, fragfile);
use();
}
GLSLProgram::~GLSLProgram(void){
}
void GLSLProgram::setUniform( const std::string &name, const glm::mat4 &mat ){
int loc = glGetUniformLocation(mProgram, name.c_str());
checkLocation(name, loc);
glUniformMatrix4fv(loc, 1, GL_FALSE, &mat[0][0]);
}
void GLSLProgram::setUniform( const std::string &name, const glm::mat3 &mat ){
int loc = glGetUniformLocation(mProgram, name.c_str());
checkLocation(name, loc);
glUniformMatrix3fv(loc, 1, GL_FALSE, &mat[0][0]);
}
void GLSLProgram::setUniform( const std::string &name, const glm::vec4 &vec ){
int loc = glGetUniformLocation(mProgram, name.c_str());
checkLocation(name, loc);
glUniform4fv(loc, 1, &vec[0]);
}
void GLSLProgram::setUniform( const std::string &name, float x, float y, float z, float w ){
setUniform(name, vec4(x, y, z, w));
}
void GLSLProgram::setUniform( const std::string &name, const glm::vec3 &vec ){
int loc = glGetUniformLocation(mProgram, name.c_str());
checkLocation(name, loc);
glUniform3fv(loc, 1, &vec[0]);
}
void GLSLProgram::setUniform( const std::string &name, float x, float y, float z ){
setUniform(name, vec3(x, y, z));
}
void GLSLProgram::setUniform( const std::string &name, float value ){
int loc = glGetUniformLocation(mProgram, name.c_str());
checkLocation(name, loc);
glUniform1f(loc, value);
}
void GLSLProgram::setUniform( const std::string &name, int value ){
int loc = glGetUniformLocation(mProgram, name.c_str());
checkLocation(name, loc);
glUniform1i(loc, value);
}
void GLSLProgram::use(){
glUseProgram(mProgram);
}
GLuint GLSLProgram::createShader( GLenum shadertype, std::string filename ){
ifstream inFile( filename );
if (!inFile) {
fprintf(stderr, "Error opening file : %s \n", filename.c_str() );
exit(1);
}
std::stringstream code;
code << inFile.rdbuf();
inFile.close();
string codeStr(code.str());
GLuint shader = glCreateShader( shadertype );
if (0 == shader) {
fprintf(stderr, "Error creating vertex shader.\n");
exit(EXIT_FAILURE);
}
// Load the source code into the shader object
const GLchar* codeArray[] = {codeStr.c_str()};
glShaderSource(shader, 1, codeArray, NULL);
// Compile the shader
glCompileShader( shader );
// Check compilation status
GLint result;
glGetShaderiv( shader, GL_COMPILE_STATUS, &result );
if( GL_FALSE == result ) {
string type;
GL_VERTEX_SHADER == shadertype ? type = "Vertex Shader" : type = "Fragment Shader";
fprintf( stderr, "%s compilation failed!\n", type.c_str());
GLint logLen;
glGetShaderiv( shader, GL_INFO_LOG_LENGTH, &logLen );
if (logLen > 0) {
char * log = (char *)malloc(logLen);
GLsizei written;
glGetShaderInfoLog(shader, logLen, &written, log);
fprintf(stderr, "Shader log: \n%s", log);
free(log);
}
glDeleteShader(shader);
}
return shader;
}
GLuint GLSLProgram::createProgram( const std::string &vertexfile, const std::string &fragfile ){
GLuint vertexShader = createShader(GL_VERTEX_SHADER, vertexfile);
GLuint fragShader = createShader(GL_FRAGMENT_SHADER, fragfile);
GLuint program = glCreateProgram();
if(0 == program) {
fprintf(stderr, "Error creating program object.\n");
exit(1);
}
// Bind index 0 to the shader input variable "VertexPosition"
//glBindAttribLocation(programHandle, 0, "VertexPosition");
// Bind index 1 to the shader input variable "VertexColor"
//glBindAttribLocation(programHandle, 1, "VertexColor");
// Attach the shaders to the program object
glAttachShader( program, vertexShader );
glAttachShader( program, fragShader );
// Link the program
glLinkProgram( program );
// Check for successful linking
GLint status;
glGetProgramiv( program, GL_LINK_STATUS, &status );
if (GL_FALSE == status) {
fprintf( stderr, "Failed to link shader program!\n" );
GLint logLen;
glGetProgramiv( program, GL_INFO_LOG_LENGTH, &logLen );
if (logLen > 0) {
char * log = (char *)malloc(logLen);
GLsizei written;
glGetProgramInfoLog(program, logLen, &written, log);
fprintf(stderr, "Program log: \n%s", log);
free(log);
}
glDeleteProgram(program);
}
return program;
}
void GLSLProgram::checkLocation( const std::string &name, int location ){
if(location < 0 && mIsDebug)
fprintf(stderr, "location of %s is not valid. please checkout the %s \n", name.c_str(), name.c_str());
}
| [
"wuqiyang429@gmail.com"
] | wuqiyang429@gmail.com |
d5405675581960556922973604733ba74aa65001 | a6bb89b2ff6c1fc8c45a4f105ef528416100a360 | /contrib/framewave_1.3.1_src/SampleConvert/SRC/process_illusion.cpp | b6d2fb5fa3bf3daca22a590570bade75edffde77 | [
"Apache-2.0"
] | permissive | dudochkin-victor/ngxe | 2c03717c45431b5a88a7ca4f3a70a2f23695cd63 | 34687494bcbb4a9ce8cf0a7327a7296bfa95e68a | refs/heads/master | 2016-09-06T02:28:20.233312 | 2013-01-05T19:59:28 | 2013-01-05T19:59:28 | 7,311,793 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 14,670 | cpp | /*
Copyright (c) 2006-2009 Advanced Micro Devices, Inc. All Rights Reserved.
This software is subject to the Apache v2.0 License.
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
#include<math.h>
#include"process_API.h"
/*!
*************************************************************************************
* \function process_illusion
*
* \brief
* This function processes the illusion effect opertation.
*
*
*************************************************************************************
*/
void
process_illusion(st_API_parameters *p)
{
int api_return_val ;
TIME_START /* Start Timer */
p->spare_roiSize.width = 1 ;
p->spare_roiSize.height = 1 ;
p->srcStep = 1 ;
int k =0 ;
Fw32f *sqrwidth ;
Fw32f *sqrheight ;
Fw32f val = 2 ;
Fw32f threshold ;
sqrwidth = (float*)malloc(4);
sqrheight = (float*)malloc(4);
sqrwidth[0] = (Fw32f)p->bor_width ;
sqrheight[0] = (Fw32f)p->bor_height ;
/*--------------------------------------------------------------------------------*/
/* Calling API "fwiSqr_32f_C1IR" : */
/* */
/* This functions steps through an ROI in a source buffer and calculates */
/* the square of the source data. Result is written back to the source location */
/* */
/*--------------------------------------------------------------------------------*/
api_return_val = fwiSqr_32f_C1IR ( sqrwidth , p->srcStep, p->spare_roiSize );
if (api_return_val<0)
throw api_return_val ;
api_return_val = fwiSqr_32f_C1IR ( sqrheight , p->srcStep, p->spare_roiSize );
if (api_return_val<0)
throw api_return_val ;
/*--------------------------------------------------------------------------------*/
/* Calling API "fwiAdd_32f_C1IR" : */
/* */
/* This functions steps through an ROI in two source buffers and add the */
/* data in buffer 2 to the data in buffer 1. Result is written back to the */
/* destination location */
/* */
/*--------------------------------------------------------------------------------*/
api_return_val = fwiAdd_32f_C1IR ( sqrwidth , p->srcStep , sqrheight , p->srcStep ,p->spare_roiSize );
if (api_return_val<0)
throw api_return_val ;
/*--------------------------------------------------------------------------------*/
/* Calling API "fwiSqrt_32f_C1IR" : */
/* */
/* This functions steps through an ROI in a source buffer and calculates */
/* the square root of the source data. Result is written back to the source */
/* location */
/* */
/*--------------------------------------------------------------------------------*/
api_return_val = fwiSqrt_32f_C1IR( sqrheight , p->srcStep , p->spare_roiSize );
if (api_return_val<0)
throw api_return_val ;
/*--------------------------------------------------------------------------------*/
/* Calling API "fwiDivC_32f_C1IR" : */
/* */
/* This functions steps through an ROI in a source buffer and divides the */
/* source data by a constant value. The quotient is written back to the source */
/* location */
/* */
/*--------------------------------------------------------------------------------*/
api_return_val = fwiDivC_32f_C1IR( val , sqrheight, p->srcStep, p->spare_roiSize );
if (api_return_val<0)
throw api_return_val ;
float fscale = sqrheight[0] ;
/*--------------------------------------------------------------------------------*/
/* Calling API "fwiDivC_32f_C1IR" : */
/* */
/* This functions steps through an ROI in a source buffer and divides the */
/* source data by a constant value. The quotient is written back to the source */
/* location */
/* */
/*--------------------------------------------------------------------------------*/
api_return_val = fwiDivC_32f_C1IR( val , sqrheight, p->srcStep, p->spare_roiSize );
if (api_return_val<0)
throw api_return_val ;
int foffset = (int)sqrheight[0] ;
double xcen, ycen, tmp;
double angle, radius;
Fw32f *cx,*cy;
xcen = p->bor_width / 2.0 ;
ycen = p->bor_height / 2.0 ;
Fw32f *xx, *yy ;
xx = (float*)malloc(4);
yy = (float*)malloc(4);
cx = (float*)malloc(4);
cy = (float*)malloc(4);
for (int j=0 ; j < p->bor_height ; j++)
{
for (int i=0 ; i < p->bor_width ; i++)
{
p->srcStep = 1 ;
cx[0] = (i - xcen) / fscale ;
cy[0] = (j - ycen) / fscale ;
tmp = 3.14159265 / (double)p->field ;
angle = floor (atan2(cy[0],cx[0]) / 2.0 / tmp) * 2.0 * tmp + tmp ;
/*--------------------------------------------------------------------------------*/
/* Calling API "fwiSqr_32f_C1IR" : */
/* */
/* This functions steps through an ROI in a source buffer and calculates */
/* the square of the source data. Result is written back to the source location */
/* */
/*--------------------------------------------------------------------------------*/
api_return_val = fwiSqr_32f_C1IR ( cx , p->srcStep, p->spare_roiSize );
if (api_return_val<0)
throw api_return_val ;
api_return_val = fwiSqr_32f_C1IR ( cy , p->srcStep, p->spare_roiSize );
if (api_return_val<0)
throw api_return_val ;
/*--------------------------------------------------------------------------------*/
/* Calling API "fwiAdd_32f_C1IR" : */
/* */
/* This functions steps through an ROI in two source buffers and add the */
/* data in buffer 2 to the data in buffer 1. Result is written back to the */
/* destination location */
/* */
/*--------------------------------------------------------------------------------*/
api_return_val = fwiAdd_32f_C1IR ( cx , p->srcStep , cy , p->srcStep ,p->spare_roiSize );
if (api_return_val<0)
throw api_return_val ;
/*--------------------------------------------------------------------------------*/
/* Calling API "fwiSqrt_32f_C1IR" : */
/* */
/* This functions steps through an ROI in a source buffer and calculates */
/* the square root of the source data. Result is written back to the source */
/* location */
/* */
/*--------------------------------------------------------------------------------*/
api_return_val = fwiSqrt_32f_C1IR( cy , p->srcStep , p->spare_roiSize );
if (api_return_val<0)
throw api_return_val ;
radius = cy[0] ;
xx[0] = (Fw32f)((int)(i - foffset * cos (angle)) );
yy[0] = (Fw32f)((int)(j - foffset * sin (angle)) );
/*--------------------------------------------------------------------------------*/
/* Calling API "fwiThreshold_GT_32f_C1IR" : */
/* */
/* This functions steps through an ROI in a source buffer and compares */
/* source data to a specified threshold value. When the source data is */
/* greater than the threshold value, the output data is set to the threshold */
/* value. */
/* */
/*--------------------------------------------------------------------------------*/
threshold = (Fw32f)(p->bor_width - 1) ;
api_return_val = fwiThreshold_GT_32f_C1IR ( xx , p->srcStep, p->spare_roiSize , threshold );
if (api_return_val<0)
throw api_return_val ;
/*--------------------------------------------------------------------------------*/
/* Calling API "fwiThreshold_LT_32f_C1IR" : */
/* */
/* This functions steps through an ROI in a source buffer and compares */
/* source data to a specified threshold value. When the source data is */
/* lesser than the threshold value, the output data is set to the threshold */
/* value. */
/* */
/*--------------------------------------------------------------------------------*/
threshold = 0;
api_return_val = fwiThreshold_LT_32f_C1IR ( xx , p->srcStep, p->spare_roiSize , threshold );
if (api_return_val<0)
throw api_return_val ;
/*--------------------------------------------------------------------------------*/
/* Calling API "fwiThreshold_GT_32f_C1IR" : */
/* */
/* This functions steps through an ROI in a source buffer and compares */
/* source data to a specified threshold value. When the source data is */
/* greater than the threshold value, the output data is set to the threshold */
/* value. */
/* */
/*--------------------------------------------------------------------------------*/
threshold = (Fw32f)(p->bor_height - 1) ;
api_return_val = fwiThreshold_GT_32f_C1IR ( yy , p->srcStep, p->spare_roiSize , threshold );
if (api_return_val<0)
throw api_return_val ;
/*--------------------------------------------------------------------------------*/
/* Calling API "fwiThreshold_LT_32f_C1IR" : */
/* */
/* This functions steps through an ROI in a source buffer and compares */
/* source data to a specified threshold value. When the source data is */
/* lesser than the threshold value, the output data is set to the threshold */
/* value. */
/* */
/*--------------------------------------------------------------------------------*/
threshold = 0;
api_return_val = fwiThreshold_LT_32f_C1IR ( yy , p->srcStep, p->spare_roiSize , threshold );
if (api_return_val<0)
throw api_return_val ;
int a = (int)((yy[0] * p->bor_width * 3 ) + (xx[0] - 1) * 3) ;
p->pSrcDst[k] = p->pSrcDst[k] + (int)(radius * (p->pSrc[a] - p->pSrcDst[k]));
p->pSrcDst[k+1] = p->pSrcDst[k+1] + (int)(radius * (p->pSrc[a+1] - p->pSrcDst[k+1]));
p->pSrcDst[k+2] = p->pSrcDst[k+2] + (int)(radius * (p->pSrc[a+2] - p->pSrcDst[k+2]));
p->srcStep = 3 ;
/*--------------------------------------------------------------------------------*/
/* Calling API "fwiThreshold_GT_8u_C3IR" : */
/* */
/* This functions steps through an ROI in a source buffer and compares */
/* source data to a specified threshold value. When the source data is */
/* greater than the threshold value, the output data is set to the threshold */
/* value. */
/* */
/*--------------------------------------------------------------------------------*/
p->value[2] = 255 ;
p->value[1] = 255 ;
p->value[0] = 255 ;
api_return_val = fwiThreshold_GT_8u_C3IR ( &p->pSrcDst[0] + k ,p->srcStep , p->spare_roiSize , p->value );
if (api_return_val<0)
throw api_return_val ;
/*--------------------------------------------------------------------------------*/
/* Calling API "fwiThreshold_LT_8u_C3IR" : */
/* */
/* This functions steps through an ROI in a source buffer and compares */
/* source data to a specified threshold value. When the source data is */
/* lesser than the threshold value, the output data is set to the threshold */
/* value. */
/* */
/*--------------------------------------------------------------------------------*/
p->value[0] = 0 ;
p->value[1] = 0 ;
p->value[2] = 0 ;
api_return_val = fwiThreshold_LT_8u_C3IR( &p->pSrcDst[0] + k ,p->srcStep , p->spare_roiSize , p->value );
if (api_return_val<0)
throw api_return_val ;
k = k + 3 ;
}
}
free(sqrwidth) ;
free(sqrheight) ;
free(xx) ;
free(yy) ;
free(cx) ;
free(cy) ;
TIME_FINISH(p) /* Stop Timer */
}
| [
"dudochkin.victor@gmail.com"
] | dudochkin.victor@gmail.com |
7a70b79bc7ba204ba14e5ca81af4cf3f076c9600 | f44b145f9b39b2da7ac5b8191fb2999ffad8154d | /contSampler.cpp | 660a907667823d2ac272793123d349898e15080d | [] | no_license | JSchallert/E80Spring2018 | fd394a41cbad762102de6797c5e55c24636ba60f | 8927f3c7c4b6e92b4bc61ff1dab13f835a2c299c | refs/heads/master | 2021-04-26T22:12:06.666581 | 2018-04-25T02:26:56 | 2018-04-25T02:26:56 | 124,038,190 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,488 | cpp |
#include "contSampler.h"
#include <math.h>
#include <stdio.h>
#include "Printer.h"
extern Printer printer;
String message;
contSampler::contSampler(void){
//Nothing to do?
}
void contSampler::updateSamples(void)
{
for (int i=0; i<NUM_SAMPS; i++){
samps[i] = analogRead(ENCODER_PIN);
}
}
String contSampler::printSample(void)
{
String printString = "ENCODER:";
for (int i=0; i<NUM_SAMPS; i++) {
printString += " ";
printString += String(samps[i]);
}
return printString; //printer.printValue(0, printString);
}
size_t contSampler::writeDataBytes(unsigned char * buffer, size_t idx)
{
int * data_slot = (int *) &buffer[idx];
for (int i=0; i<NUM_SAMPS; i++) {
data_slot[i] = samps[i];
}
return idx + NUM_SAMPS*sizeof(int);
}
void contSampler::padding(int number, byte width, String & str) {
int currentMax = 10;
for (byte i = 1; i < width; i++) {
if (number < currentMax) {
str.concat("0");
}
currentMax *= 10;
}
str.concat(number);
}
void contSampler::init(void) {
Serial.print("Initializing SD Card for contSampler... ");
if (!SD.begin()) {
Serial.println("failed!");
return;
}
Serial.println("done!");
unsigned int number = 0;
String numstr = "";
padding(number, 3, numstr);
String finalname = SMP_FILENAME_BASE + numstr + ".bin";
finalname.toCharArray(logfilename, SMP_FILENAME_BUFFERLEN);
while(SD.exists(logfilename)) {
number++;
numstr = "";
padding(number, 3, numstr);
finalname = SMP_FILENAME_BASE + numstr + ".bin";
finalname.toCharArray(logfilename, SMP_FILENAME_BUFFERLEN);
}
finalname = HEADINGS_FILENAME_BASE + numstr + ".txt";
finalname.toCharArray(headingfilename, SMP_FILENAME_BUFFERLEN);
message = "contSampler: Using log file name " + String(logfilename);
printer.printMessage(message,30);
String headingStr = "Analog Encoder";
String dataTypeStr = "int";
headingStr += "\n"+dataTypeStr;
file = SD.open(headingfilename, FILE_WRITE);
// if the file exists, use it:
if (file) {
file.println(headingStr);
file.close();
}
printer.printMessage("Creating log file",10);
file = SD.open(logfilename, FILE_WRITE);
if(!file) {
message = "Logger: error creating " + String(logfilename);
printer.printMessage(message,0);
} else {
file.close();
}
// if exiting without error
keepLogging = true;
}
bool contSampler::log(void){
// record data from sources
size_t idx = 0;
unsigned char buffer[BYTES_PER_BLOCK];
for(size_t i = 0; i < num_samples; ++i) {
if (idx >= BYTES_PER_BLOCK) {
printer.printMessage("Too much data per log. Increase BYTES_PER_BLOCK or reduce data", 2);
}
}
// write data to SD
if (writtenBlocks >= FILE_BLOCK_COUNT) {
printer.printMessage("Current file size limit reached. Change FILE_BLOCK_COUNT to fix. Stopping logging for now.",0);
keepLogging = false;
}
file = SD.open(logfilename, FILE_WRITE);
if (file) {
int bytes = file.write(&buffer[0],BYTES_PER_BLOCK);
if (!bytes) {
printer.printMessage("Logger: Error printing to SD",0);
}
}
file.close();
writtenBlocks++;
keepLogging = true;
}
String contSampler::printState(void){
String printString = "Logger: ";
if(keepLogging) {
printString += "Just logged buffer " + String(writtenBlocks) + " to SD.";
} else {
printString += "LOGGING ERROR, LOGGING HAS STOPPED";
}
return printString;
}
| [
"noreply@github.com"
] | JSchallert.noreply@github.com |
18876fe03a64def267d7b7738551819f55ffe337 | b9873d80f8adcf5435fdaaf2cd3f99cb781974ff | /include/ops/declarable/LegacyTransformOp.h | 218d7ad2fa0b4aa56e29bfb52f95af46184bbc1c | [
"Apache-2.0"
] | permissive | gluonhq/libnd4j | 73b7a0484f31a5ad79cc721274ac48368669f5b7 | 6be4678caf6f820f5b0fd1a5392c0941936f2e43 | refs/heads/master | 2021-05-05T21:51:10.024782 | 2018-01-04T11:45:38 | 2018-01-04T11:45:38 | 116,035,267 | 0 | 1 | null | 2018-01-02T16:33:38 | 2018-01-02T16:33:38 | null | UTF-8 | C++ | false | false | 763 | h | //
// Created by raver119 on 16.10.2017.
//
#ifndef LIBND4J_LEGACYTRANSFORMOP_H
#define LIBND4J_LEGACYTRANSFORMOP_H
#include <ops/declarable/LegacyOp.h>
namespace nd4j {
namespace ops {
/**
* This class provides wrapper for Transform operations (i.e. Pow or OneMinus)
*/
template <typename T>
class LegacyTransformOp : public LegacyOp<T> {
protected:
Nd4jStatus validateAndExecute(Context<T>& block);
public:
LegacyTransformOp();
LegacyTransformOp(int opNum);
ShapeList* calculateOutputShape(ShapeList* inputShape, nd4j::graph::Context<T>& block);
virtual LegacyOp<T>* clone();
};
}
}
#endif //LIBND4J_LEGACYTRANSFORMOP_H
| [
"noreply@github.com"
] | gluonhq.noreply@github.com |
caa938368b9860650ac50bd06ea2536aa1e1e5cf | 8134cacd6e7c604a56d854727a68fc95797358de | /src/main/sdl2/rendersurface.hpp | 090300a4edde9aaa18d1622b4255dea3e2e691e2 | [] | no_license | lopespm/cannonball | 03d3d0febc09f9c0e3ea64679d45af8e6bea4f98 | 80d95e88daa82df7a77b615ae3fd1cf7584877f2 | refs/heads/master | 2021-01-21T01:20:23.606677 | 2016-10-03T22:10:18 | 2016-10-03T22:10:18 | 51,142,793 | 11 | 12 | null | 2016-02-05T11:26:58 | 2016-02-05T11:26:58 | null | UTF-8 | C++ | false | false | 1,194 | hpp | /***************************************************************************
SDL2 Hardware Surface Video Rendering.
Known Bugs:
- Software scanlines not implemented because we do hardware post-scaling
using the SDL_RenderCopy() rects from the original bitmap, so would not
look good at all because they would be ruined by magnifying.
Copyright Manuel Alfayate and Chris White.
See license.txt for more details.
***************************************************************************/
#pragma once
#include "renderbase.hpp"
class RenderSurface : public RenderBase
{
public:
RenderSurface();
~RenderSurface();
bool init(int src_width, int src_height,
int scale,
int video_mode,
int scanlines);
void disable();
bool start_frame();
bool finalize_frame();
void draw_frame(uint16_t* pixels);
private:
// SDL2 window
SDL_Window *window;
// SDL2 renderer
SDL_Renderer *renderer;
// SDL2 texture
SDL_Texture *texture;
// SDL2 blitting rects for hw scaling
// ratio correction using SDL_RenderCopy()
SDL_Rect src_rect;
SDL_Rect dst_rect;
};
| [
"redwindwanderer@gmail.com"
] | redwindwanderer@gmail.com |
3f4a54b90b8649a932d081461242e2748111de42 | 902c38753580796b38443a48c807db531eb18d60 | /My practice in c++/adapter design pattern.cpp | 0d372209f65725da5051f6bab8cd7eaf732225d9 | [] | no_license | ibadeeCodes/All-About-C-plus | b6b189f4f2fb09b6ca85e2789de8da4a93997d39 | fe286f4cf93ea8a6c091baba8fba7d226e312c25 | refs/heads/master | 2020-04-14T13:29:40.232570 | 2019-01-02T18:32:27 | 2019-01-02T18:32:27 | 163,870,040 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 801 | cpp | #include <iostream>
using namespace std;
class Circle
{
public:
virtual void draw() = 0;
};
class StandardCircle
{
public:
StandardCircle(double radius)
{
radius_ = radius;
cout << "StandardCircle: create. radius = "<< radius_ << endl;
}
void oldDraw()
{
cout << "StandardCircle: oldDraw. " << radius_ << endl;
}
private:
double radius_ ;
};
class CAdapter : public Circle, private StandardCircle //Adapter Class
{
public:
CAdapter( double diameter)
: StandardCircle(diameter/2)
{
cout << "CAdapter: create. diameter = " << diameter << endl;
}
virtual void draw()
{
cout << "CAdapter: draw." << endl;
oldDraw();
}
};
int main()
{
Circle* c = new CAdapter(14);
c->draw();
}
| [
"ibadeeshaikh@gmail.com"
] | ibadeeshaikh@gmail.com |
c45beac7cf232d27d0c5124673b2c58c0d4a8d00 | ecb3b5552115c0228239a1bf7edb7a127de57482 | /mytimer.cpp | 575fbf0d8379ac51383b550c5885eb83c49f3478 | [] | no_license | yyyly/l110 | e8edfbab9600e1e154c8cec6d8220ed5ecbf5978 | 3361876192994b5a3ad906c5c0753ddbf19a0362 | refs/heads/master | 2020-09-28T01:58:41.569957 | 2020-08-22T02:16:54 | 2020-08-22T02:16:54 | 226,661,326 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 268 | cpp | #include"mytimer.h"
myTimer::myTimer(QObject *parent)
:QTimer(parent)
{
}
myTimer::myTimer(LONG h, QObject *parent)
:QTimer(parent),handle(h)
{
connect(this,SIGNAL(timeout()),this,SLOT(finish()));
}
void myTimer::finish()
{
emit timeOut(handle);
}
| [
"1305892681@qq.com"
] | 1305892681@qq.com |
1ae9d895ac0f2b8db1d7f6e4159935369237400b | f8b92dc59e8e7216a31cc7b74714d079d5b4a6a5 | /Rendering/OpenGL2/vtkTextureObject.cxx | 619017bada40ef78c96cc24e6f0855a06bbdb0fc | [
"BSD-3-Clause"
] | permissive | vejmarie/vtk-7 | 6dfef52b090bb4cd34ac80b1b6ff88b2b3ebdb54 | 32025222cd631e758292e28ab72b3655be554dac | refs/heads/master | 2016-09-14T13:39:55.362280 | 2016-05-13T06:42:26 | 2016-05-13T06:42:26 | 58,708,076 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 58,674 | cxx | /*=========================================================================
Program: Visualization Toolkit
Module: vtkTextureObject.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkTextureObject.h"
#include "vtk_glew.h"
#include "vtkObjectFactory.h"
#if GL_ES_VERSION_2_0 != 1 || GL_ES_VERSION_3_0 == 1
#include "vtkPixelBufferObject.h"
#endif
#include "vtkNew.h"
#include "vtkOpenGLBufferObject.h"
#include "vtkOpenGLError.h"
#include "vtkOpenGLRenderUtilities.h"
#include "vtkOpenGLRenderWindow.h"
#include "vtkOpenGLShaderCache.h"
#include "vtkOpenGLTexture.h"
#include "vtkOpenGLVertexArrayObject.h"
#include "vtkRenderer.h"
#include "vtkShaderProgram.h"
#include "vtkOpenGLHelper.h"
#include <cassert>
//#define VTK_TO_DEBUG
//#define VTK_TO_TIMING
#ifdef VTK_TO_TIMING
#include "vtkTimerLog.h"
#endif
#include "vtkTextureObjectFS.h"
#include "vtkTextureObjectVS.h" // a pass through shader
#define BUFFER_OFFSET(i) (static_cast<char *>(NULL) + (i))
// Mapping from DepthTextureCompareFunction values to OpenGL values.
//----------------------------------------------------------------------------
static GLint OpenGLDepthTextureCompareFunction[8]=
{
GL_LEQUAL,
GL_GEQUAL,
GL_LESS,
GL_GREATER,
GL_EQUAL,
GL_NOTEQUAL,
GL_ALWAYS,
GL_NEVER
};
//----------------------------------------------------------------------------
static const char *DepthTextureCompareFunctionAsString[8]=
{
"Lequal",
"Gequal",
"Less",
"Greater",
"Equal",
"NotEqual",
"AlwaysTrue",
"Never"
};
// Mapping from Wrap values to OpenGL values
#if GL_ES_VERSION_2_0 != 1
//--------------------------------------------------------------------------
static GLint OpenGLWrap[4]=
{
GL_CLAMP_TO_EDGE,
GL_REPEAT,
GL_MIRRORED_REPEAT,
GL_CLAMP_TO_BORDER
};
//--------------------------------------------------------------------------
static const char *WrapAsString[4]=
{
"ClampToEdge",
"Repeat",
"MirroredRepeat",
"ClampToBorder"
};
//----------------------------------------------------------------------------
static GLenum OpenGLAlphaInternalFormat[5]=
{
GL_R8,
GL_R8,
GL_R16,
GL_R16F,
GL_R32F
};
#else
//--------------------------------------------------------------------------
static GLint OpenGLWrap[3]=
{
GL_CLAMP_TO_EDGE,
GL_REPEAT,
GL_MIRRORED_REPEAT
};
//--------------------------------------------------------------------------
static const char *WrapAsString[3]=
{
"ClampToEdge",
"Repeat",
"MirroredRepeat"
};
//----------------------------------------------------------------------------
// Should be GL_RED but that requires an extension for ES 2.0
static GLenum OpenGLAlphaInternalFormat[5]=
{
GL_LUMINANCE,
GL_LUMINANCE,
GL_LUMINANCE,
GL_LUMINANCE,
GL_LUMINANCE
};
#endif
// Mapping MinificationFilter values to OpenGL values.
//----------------------------------------------------------------------------
static GLint OpenGLMinFilter[6]=
{
GL_NEAREST,
GL_LINEAR,
GL_NEAREST_MIPMAP_NEAREST,
GL_NEAREST_MIPMAP_LINEAR,
GL_LINEAR_MIPMAP_NEAREST,
GL_LINEAR_MIPMAP_LINEAR
};
// Mapping MagnificationFilter values to OpenGL values.
//----------------------------------------------------------------------------
static GLint OpenGLMagFilter[6]=
{
GL_NEAREST,
GL_LINEAR
};
//----------------------------------------------------------------------------
static const char *MinMagFilterAsString[6]=
{
"Nearest",
"Linear",
"NearestMipmapNearest",
"NearestMipmapLinear",
"LinearMipmapNearest",
"LinearMipmapLinear"
};
//----------------------------------------------------------------------------
static GLenum OpenGLDepthInternalFormat[5]=
{
GL_DEPTH_COMPONENT,
GL_DEPTH_COMPONENT16,
#ifdef GL_DEPTH_COMPONENT24
GL_DEPTH_COMPONENT24,
#else
GL_DEPTH_COMPONENT16,
#endif
#ifdef GL_DEPTH_COMPONENT32
GL_DEPTH_COMPONENT32,
#else
GL_DEPTH_COMPONENT16,
#endif
#ifdef GL_DEPTH_COMPONENT32F
GL_DEPTH_COMPONENT32F
#else
GL_DEPTH_COMPONENT16
#endif
};
//----------------------------------------------------------------------------
static GLenum OpenGLDepthInternalFormatType[5]=
{
GL_UNSIGNED_INT,
GL_UNSIGNED_INT,
GL_UNSIGNED_INT,
GL_UNSIGNED_INT,
#ifdef GL_DEPTH_COMPONENT32F
GL_FLOAT
#else
GL_UNSIGNED_INT
#endif
};
/*
static const char *DepthInternalFormatFilterAsString[6]=
{
"Native",
"Fixed16",
"Fixed24",
"Fixed32",
"Float32"
};
*/
//----------------------------------------------------------------------------
vtkStandardNewMacro(vtkTextureObject);
//----------------------------------------------------------------------------
vtkTextureObject::vtkTextureObject()
{
this->Context = NULL;
this->Handle = 0;
this->NumberOfDimensions = 0;
this->Target = 0;
this->Components = 0;
this->Width = 0;
this->Height = 0;
this->Depth = 0;
this->RequireTextureInteger = false;
this->SupportsTextureInteger = false;
this->RequireTextureFloat = false;
this->SupportsTextureFloat = false;
this->RequireDepthBufferFloat = false;
this->SupportsDepthBufferFloat = false;
this->AutoParameters = 1;
this->WrapS = Repeat;
this->WrapT = Repeat;
this->WrapR = Repeat;
this->MinificationFilter = Nearest;
this->MagnificationFilter = Nearest;
this->MinLOD = -1000.0f;
this->MaxLOD = 1000.0f;
this->BaseLevel = 0;
this->MaxLevel = 0;
this->DepthTextureCompare = false;
this->DepthTextureCompareFunction = Lequal;
this->GenerateMipmap = false;
this->ShaderProgram = NULL;
this->BorderColor[0] = 0.0f;
this->BorderColor[1] = 0.0f;
this->BorderColor[2] = 0.0f;
this->BorderColor[3] = 0.0f;
this->BufferObject = 0;
this->ResetFormatAndType();
}
//----------------------------------------------------------------------------
vtkTextureObject::~vtkTextureObject()
{
this->DestroyTexture();
if (this->ShaderProgram)
{
delete this->ShaderProgram;
this->ShaderProgram = NULL;
}
}
//----------------------------------------------------------------------------
bool vtkTextureObject::IsSupported(vtkOpenGLRenderWindow* vtkNotUsed(win),
bool requireTexFloat,
bool requireDepthFloat,
bool requireTexInt)
{
#if GL_ES_VERSION_2_0 != 1
if (vtkOpenGLRenderWindow::GetContextSupportsOpenGL32())
{
return true;
}
bool texFloat = true;
if (requireTexFloat)
{
texFloat = (glewIsSupported("GL_ARB_texture_float") != 0
&& glewIsSupported("GL_ARB_texture_rg") != 0);
}
bool depthFloat = true;
if (requireDepthFloat)
{
depthFloat = (glewIsSupported("GL_ARB_depth_buffer_float") != 0);
}
bool texInt = true;
if (requireTexInt)
{
texInt = (glewIsSupported("GL_EXT_texture_integer") != 0);
}
#else
bool texFloat = true;
bool depthFloat = !requireDepthFloat;
bool texInt = !requireTexInt;
#if GL_ES_VERSION_3_0 == 1
texFloat = true;
depthFloat = true; // I think this is the case
texInt = true;
#endif
#endif
return texFloat && depthFloat && texInt;
}
//----------------------------------------------------------------------------
bool vtkTextureObject::LoadRequiredExtensions(vtkOpenGLRenderWindow *renWin)
{
#if GL_ES_VERSION_2_0 != 1
if (vtkOpenGLRenderWindow::GetContextSupportsOpenGL32())
{
this->SupportsTextureInteger = true;
this->SupportsTextureFloat = true;
this->SupportsDepthBufferFloat = true;
}
else
{
this->SupportsTextureInteger =
(glewIsSupported("GL_EXT_texture_integer") != 0);
this->SupportsTextureFloat =
(glewIsSupported("GL_ARB_texture_float") != 0 &&
glewIsSupported("GL_ARB_texture_rg") != 0);
this->SupportsDepthBufferFloat =
(glewIsSupported("GL_ARB_depth_buffer_float") != 0);
}
#else
// some of these may have extensions etc for ES 2.0
// setting to false right now as I do not know
this->SupportsTextureInteger = false;
this->SupportsTextureFloat = true;
this->SupportsDepthBufferFloat = false;
#if GL_ES_VERSION_3_0 == 1
this->SupportsTextureInteger = true;
this->SupportsTextureFloat = true;
this->SupportsDepthBufferFloat = true;
#endif
#endif
return this->IsSupported(renWin,
this->RequireTextureFloat,
this->RequireDepthBufferFloat,
this->RequireTextureInteger);
}
//----------------------------------------------------------------------------
void vtkTextureObject::SetContext(vtkOpenGLRenderWindow* renWin)
{
// avoid pointless reassignment
if (this->Context == renWin)
{
return;
}
// free previous resources
this->DestroyTexture();
this->Context = NULL;
this->Modified();
// all done if assigned null
if (!renWin)
{
return;
}
if (!this->LoadRequiredExtensions(renWin) )
{
vtkErrorMacro("Required OpenGL extensions not supported by the context.");
return;
}
// initialize
this->Context = renWin;
this->Context->MakeCurrent();
}
//----------------------------------------------------------------------------
vtkOpenGLRenderWindow* vtkTextureObject::GetContext()
{
return this->Context;
}
//----------------------------------------------------------------------------
void vtkTextureObject::DestroyTexture()
{
// deactivate it first
this->Deactivate();
// because we don't hold a reference to the render
// context we don't have any control on when it is
// destroyed. In fact it may be destroyed before
// we are(eg smart pointers), in which case we should
// do nothing.
if (this->Context && this->Handle)
{
GLuint tex = this->Handle;
glDeleteTextures(1, &tex);
vtkOpenGLCheckErrorMacro("failed at glDeleteTexture");
}
this->Handle = 0;
this->NumberOfDimensions = 0;
this->Target = 0;
this->Components = 0;
this->Width = this->Height = this->Depth = 0;
this->ResetFormatAndType();
}
//----------------------------------------------------------------------------
void vtkTextureObject::CreateTexture()
{
assert(this->Context);
// reuse the existing handle if we have one
if (!this->Handle)
{
GLuint tex=0;
glGenTextures(1, &tex);
vtkOpenGLCheckErrorMacro("failed at glGenTextures");
this->Handle=tex;
#if defined(GL_TEXTURE_BUFFER)
if (this->Target && this->Target != GL_TEXTURE_BUFFER)
#else
if (this->Target)
#endif
{
glBindTexture(this->Target, this->Handle);
vtkOpenGLCheckErrorMacro("failed at glBindTexture");
// See: http://www.opengl.org/wiki/Common_Mistakes#Creating_a_complete_texture
// turn off mip map filter or set the base and max level correctly. here
// both are done.
glTexParameteri(this->Target, GL_TEXTURE_MIN_FILTER,
this->GetMinificationFilterMode(this->MinificationFilter));
glTexParameteri(this->Target, GL_TEXTURE_MAG_FILTER,
this->GetMagnificationFilterMode(this->MagnificationFilter));
glTexParameteri(this->Target, GL_TEXTURE_WRAP_S,
this->GetWrapSMode(this->WrapS));
glTexParameteri(this->Target, GL_TEXTURE_WRAP_T,
this->GetWrapTMode(this->WrapT));
#if defined(GL_TEXTURE_3D)
if (this->Target == GL_TEXTURE_3D)
{
glTexParameteri(this->Target, GL_TEXTURE_WRAP_R,
this->GetWrapRMode(this->WrapR));
}
#endif
#ifdef GL_TEXTURE_BASE_LEVEL
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
#endif
#ifdef GL_TEXTURE_MAX_LEVEL
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
#endif
glBindTexture(this->Target, 0);
}
}
}
//---------------------------------------------------------------------------
int vtkTextureObject::GetTextureUnit()
{
if (this->Context)
{
return this->Context->GetTextureUnitForTexture(this);
}
return -1;
}
//---------------------------------------------------------------------------
void vtkTextureObject::Activate()
{
// activate a free texture unit for this texture
this->Context->ActivateTexture(this);
this->Bind();
}
//---------------------------------------------------------------------------
void vtkTextureObject::Deactivate()
{
if (this->Context)
{
this->Context->ActivateTexture(this);
this->UnBind();
this->Context->DeactivateTexture(this);
}
}
//---------------------------------------------------------------------------
void vtkTextureObject::ReleaseGraphicsResources(vtkWindow *win)
{
vtkOpenGLRenderWindow *rwin =
vtkOpenGLRenderWindow::SafeDownCast(win);
if (rwin && this->Handle)
{
rwin->MakeCurrent();
rwin->ActivateTexture(this);
this->UnBind();
rwin->DeactivateTexture(this);
GLuint tex = this->Handle;
glDeleteTextures(1, &tex);
this->Handle = 0;
this->NumberOfDimensions = 0;
this->Target =0;
this->InternalFormat = 0;
this->Format = 0;
this->Type = 0;
this->Components = 0;
this->Width = this->Height = this->Depth = 0;
}
if (this->ShaderProgram)
{
this->ShaderProgram->ReleaseGraphicsResources(win);
delete this->ShaderProgram;
this->ShaderProgram = NULL;
}
}
//----------------------------------------------------------------------------
void vtkTextureObject::Bind()
{
assert(this->Context);
assert(this->Handle);
glBindTexture(this->Target, this->Handle);
vtkOpenGLCheckErrorMacro("failed at glBindTexture");
if (this->AutoParameters && (this->GetMTime() > this->SendParametersTime))
{
this->SendParameters();
}
}
//----------------------------------------------------------------------------
void vtkTextureObject::UnBind()
{
if (this->Target)
{
glBindTexture(this->Target, 0);
vtkOpenGLCheckErrorMacro("failed at glBindTexture(0)");
}
}
//----------------------------------------------------------------------------
bool vtkTextureObject::IsBound()
{
bool result=false;
if(this->Context && this->Handle)
{
GLenum target=0; // to avoid warnings.
switch(this->Target)
{
#if defined(GL_TEXTURE_1D) && defined(GL_TEXTURE_BINDING_1D)
case GL_TEXTURE_1D:
target=GL_TEXTURE_BINDING_1D;
break;
#endif
case GL_TEXTURE_2D:
target=GL_TEXTURE_BINDING_2D;
break;
#if defined(GL_TEXTURE_3D) && defined(GL_TEXTURE_BINDING_3D)
case GL_TEXTURE_3D:
target=GL_TEXTURE_BINDING_3D;
break;
#endif
#if defined(GL_TEXTURE_BUFFER) && defined(GL_TEXTURE_BINDING_BUFFER)
case GL_TEXTURE_BUFFER:
target=GL_TEXTURE_BINDING_BUFFER;
break;
#endif
default:
assert("check: impossible case" && 0);
break;
}
GLint objectId;
glGetIntegerv(target,&objectId);
result=static_cast<GLuint>(objectId)==this->Handle;
}
return result;
}
//----------------------------------------------------------------------------
void vtkTextureObject::SendParameters()
{
assert("pre: is_bound" && this->IsBound());
#if defined(GL_TEXTURE_BUFFER)
if (this->Target == GL_TEXTURE_BUFFER)
{
return;
}
#endif
glTexParameteri(this->Target,GL_TEXTURE_WRAP_S, OpenGLWrap[this->WrapS]);
glTexParameteri(this->Target,GL_TEXTURE_WRAP_T, OpenGLWrap[this->WrapT]);
#ifdef GL_TEXTURE_WRAP_R
glTexParameteri(
this->Target,
GL_TEXTURE_WRAP_R,
OpenGLWrap[this->WrapR]);
#endif
glTexParameteri(
this->Target,
GL_TEXTURE_MIN_FILTER,
OpenGLMinFilter[this->MinificationFilter]);
glTexParameteri(
this->Target,
GL_TEXTURE_MAG_FILTER,
OpenGLMagFilter[this->MagnificationFilter]);
#if GL_ES_VERSION_2_0 != 1 || GL_ES_VERSION_3_0 == 1
#if GL_ES_VERSION_3_0 != 1
glTexParameterfv(this->Target, GL_TEXTURE_BORDER_COLOR, this->BorderColor);
if(this->DepthTextureCompare)
{
glTexParameteri(
this->Target,
GL_TEXTURE_COMPARE_MODE,
GL_COMPARE_REF_TO_TEXTURE);
}
else
{
glTexParameteri(
this->Target,
GL_TEXTURE_COMPARE_MODE,
GL_NONE);
}
#endif
glTexParameterf(this->Target, GL_TEXTURE_MIN_LOD, this->MinLOD);
glTexParameterf(this->Target, GL_TEXTURE_MAX_LOD, this->MaxLOD);
glTexParameteri(this->Target, GL_TEXTURE_BASE_LEVEL, this->BaseLevel);
glTexParameteri(this->Target, GL_TEXTURE_MAX_LEVEL, this->MaxLevel);
glTexParameteri(
this->Target,
GL_TEXTURE_COMPARE_FUNC,
OpenGLDepthTextureCompareFunction[this->DepthTextureCompareFunction]);
#endif
vtkOpenGLCheckErrorMacro("failed after SendParameters");
this->SendParametersTime.Modified();
}
//----------------------------------------------------------------------------
unsigned int vtkTextureObject::GetInternalFormat(int vtktype, int numComps,
bool shaderSupportsTextureInt)
{
if (this->InternalFormat)
{
return this->InternalFormat;
}
// pre-condition
if(vtktype == VTK_VOID && numComps != 1)
{
vtkErrorMacro("Depth component texture must have 1 component only (" <<
numComps << " requested");
this->InternalFormat = 0;
return this->InternalFormat;
}
this->InternalFormat =
this->GetDefaultInternalFormat(vtktype, numComps, shaderSupportsTextureInt);
if (!this->InternalFormat)
{
vtkDebugMacro("Unable to find suitable internal format for T="
<< vtktype << " NC=" << numComps << " SSTI="
<< shaderSupportsTextureInt);
}
return this->InternalFormat;
}
//----------------------------------------------------------------------------
unsigned int vtkTextureObject::GetDefaultInternalFormat(
int vtktype, int numComps,
bool shaderSupportsTextureInt)
{
GLenum result = 0;
// if shader supports int textures try that first
if (shaderSupportsTextureInt)
{
result = this->Context->GetDefaultTextureInternalFormat(
vtktype,numComps,true,false);
if (!result)
{
vtkDebugMacro("Unsupported internal texture type!");
}
return result;
}
// try default next
result = this->Context->GetDefaultTextureInternalFormat(
vtktype,numComps,false,false);
if (result)
{
return result;
}
// try floating point
result = this->Context->GetDefaultTextureInternalFormat(
vtktype,numComps,false,true);
if (!result)
{
vtkDebugMacro("Unsupported internal texture type!");
vtkDebugMacro("Unable to find suitable internal format for T="
<< vtktype << " NC=" << numComps << " SSTI=" << shaderSupportsTextureInt);
}
return result;
}
//----------------------------------------------------------------------------
void vtkTextureObject::SetInternalFormat(unsigned int glInternalFormat)
{
if (this->InternalFormat != glInternalFormat)
{
this->InternalFormat = glInternalFormat;
this->Modified();
}
}
//----------------------------------------------------------------------------
unsigned int vtkTextureObject::GetFormat(int vtktype, int numComps,
bool shaderSupportsTextureInt)
{
if (!this->Format)
{
this->Format = this->GetDefaultFormat(vtktype,
numComps, shaderSupportsTextureInt);
}
return this->Format;
}
//----------------------------------------------------------------------------
unsigned int vtkTextureObject::GetDefaultFormat(int vtktype, int numComps,
bool shaderSupportsTextureInt)
{
if (vtktype == VTK_VOID)
{
return GL_DEPTH_COMPONENT;
}
#if GL_ES_VERSION_2_0 != 1
if(this->SupportsTextureInteger && shaderSupportsTextureInt
&& (vtktype==VTK_SIGNED_CHAR||vtktype==VTK_UNSIGNED_CHAR||
vtktype==VTK_SHORT||vtktype==VTK_UNSIGNED_SHORT||vtktype==VTK_INT||
vtktype==VTK_UNSIGNED_INT))
{
switch (numComps)
{
case 1:
return GL_RED_INTEGER;
case 2:
return GL_RG_INTEGER;
case 3:
return GL_RGB_INTEGER_EXT;
case 4:
return GL_RGBA_INTEGER_EXT;
}
}
else
{
switch (numComps)
{
case 1:
return GL_RED;
case 2:
return GL_RG;
case 3:
return GL_RGB;
case 4:
return GL_RGBA;
}
#else
{
switch (numComps)
{
#ifdef GL_RED
case 1:
return GL_RED;
case 2:
return GL_RG;
#else
case 1:
return GL_LUMINANCE;
case 2:
return GL_LUMINANCE_ALPHA;
#endif
case 3:
return GL_RGB;
case 4:
return GL_RGBA;
}
#endif
}
return GL_RGB;
}
//----------------------------------------------------------------------------
void vtkTextureObject::SetFormat(unsigned int glFormat)
{
if (this->Format != glFormat)
{
this->Format = glFormat;
this->Modified();
}
}
//----------------------------------------------------------------------------
void vtkTextureObject::ResetFormatAndType()
{
this->Format = 0;
this->InternalFormat = 0;
this->Type = 0;
}
//----------------------------------------------------------------------------
int vtkTextureObject::GetDefaultDataType(int vtk_scalar_type)
{
// DON'T DEAL with VTK_CHAR as this is platform dependent.
switch (vtk_scalar_type)
{
case VTK_SIGNED_CHAR:
return GL_BYTE;
case VTK_UNSIGNED_CHAR:
return GL_UNSIGNED_BYTE;
case VTK_SHORT:
return GL_SHORT;
case VTK_UNSIGNED_SHORT:
return GL_UNSIGNED_SHORT;
case VTK_INT:
return GL_INT;
case VTK_UNSIGNED_INT:
return GL_UNSIGNED_INT;
case VTK_FLOAT:
case VTK_VOID: // used for depth component textures.
return GL_FLOAT;
}
return 0;
}
//----------------------------------------------------------------------------
static int vtkGetVTKType(GLenum gltype)
{
// DON'T DEAL with VTK_CHAR as this is platform dependent.
switch (gltype)
{
case GL_BYTE:
return VTK_SIGNED_CHAR;
case GL_UNSIGNED_BYTE:
return VTK_UNSIGNED_CHAR;
case GL_SHORT:
return VTK_SHORT;
case GL_UNSIGNED_SHORT:
return VTK_UNSIGNED_SHORT;
case GL_INT:
return VTK_INT;
case GL_UNSIGNED_INT:
return VTK_UNSIGNED_INT;
case GL_FLOAT:
return VTK_FLOAT;
}
return 0;
}
//----------------------------------------------------------------------------
int vtkTextureObject::GetVTKDataType()
{
return ::vtkGetVTKType(this->Type);
}
//----------------------------------------------------------------------------
int vtkTextureObject::GetDataType(int vtk_scalar_type)
{
if (!this->Type)
{
this->Type = this->GetDefaultDataType(vtk_scalar_type);
}
return this->Type;
}
//----------------------------------------------------------------------------
void vtkTextureObject::SetDataType(unsigned int glType)
{
if (this->Type != glType)
{
this->Type = glType;
this->Modified();
}
}
//----------------------------------------------------------------------------
unsigned int vtkTextureObject::GetMinificationFilterMode(int vtktype)
{
switch(vtktype)
{
case Nearest:
return GL_NEAREST;
case Linear:
return GL_LINEAR;
case NearestMipmapNearest:
return GL_NEAREST_MIPMAP_NEAREST;
case NearestMipmapLinear:
return GL_NEAREST_MIPMAP_LINEAR;
case LinearMipmapNearest:
return GL_LINEAR_MIPMAP_NEAREST;
case LinearMipmapLinear:
return GL_LINEAR_MIPMAP_LINEAR;
default:
return GL_NEAREST;
}
}
//----------------------------------------------------------------------------
unsigned int vtkTextureObject::GetMagnificationFilterMode(int vtktype)
{
switch(vtktype)
{
case Nearest:
return GL_NEAREST;
case Linear:
return GL_LINEAR;
default:
return GL_NEAREST;
}
}
//----------------------------------------------------------------------------
unsigned int vtkTextureObject::GetWrapSMode(int vtktype)
{
switch(vtktype)
{
case ClampToEdge:
return GL_CLAMP_TO_EDGE;
case Repeat:
return GL_REPEAT;
#ifdef GL_CLAMP_TO_BORDER
case ClampToBorder:
return GL_CLAMP_TO_BORDER;
#endif
case MirroredRepeat:
return GL_MIRRORED_REPEAT;
default:
return GL_CLAMP_TO_EDGE;
}
}
//----------------------------------------------------------------------------
unsigned int vtkTextureObject::GetWrapTMode(int vtktype)
{
return this->GetWrapSMode(vtktype);
}
//----------------------------------------------------------------------------
unsigned int vtkTextureObject::GetWrapRMode(int vtktype)
{
return this->GetWrapSMode(vtktype);
}
// 1D textures are not supported in ES 2.0 or 3.0
#if GL_ES_VERSION_2_0 != 1
//----------------------------------------------------------------------------
bool vtkTextureObject::Create1D(int numComps,
vtkPixelBufferObject* pbo,
bool shaderSupportsTextureInt)
{
assert(this->Context);
assert(pbo->GetContext() == this->Context.GetPointer());
GLenum target = GL_TEXTURE_1D;
// Now, detemine texture parameters using the information from the pbo.
// * internalFormat depends on number of components and the data type.
GLenum internalFormat = this->GetInternalFormat(pbo->GetType(), numComps,
shaderSupportsTextureInt);
// * format depends on the number of components.
GLenum format = this->GetFormat(pbo->GetType(), numComps,
shaderSupportsTextureInt);
// * type if the data type in the pbo
GLenum type = this->GetDefaultDataType(pbo->GetType());
if (!internalFormat || !format || !type)
{
vtkErrorMacro("Failed to detemine texture parameters.");
return false;
}
this->Target = target;
this->Context->ActivateTexture(this);
this->CreateTexture();
this->Bind();
pbo->Bind(vtkPixelBufferObject::UNPACKED_BUFFER);
// Source texture data from the PBO.
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage1D(target, 0, static_cast<GLint>(internalFormat),
static_cast<GLsizei>(pbo->GetSize()/
static_cast<unsigned int>(numComps)),
0, format,
type, BUFFER_OFFSET(0));
vtkOpenGLCheckErrorMacro("failed at glTexImage1D");
pbo->UnBind();
this->Deactivate();
this->Target = target;
this->Format = format;
this->Type = type;
this->Components = numComps;
this->Width = pbo->GetSize();
this->Height = 1;
this->Depth =1;
this->NumberOfDimensions=1;
return true;
}
//----------------------------------------------------------------------------
bool vtkTextureObject::Create1DFromRaw(unsigned int width, int numComps,
int dataType, void *data)
{
assert(this->Context);
// Now determine the texture parameters using the arguments.
this->GetDataType(dataType);
this->GetInternalFormat(dataType, numComps, false);
this->GetFormat(dataType, numComps, false);
if (!this->InternalFormat || !this->Format || !this->Type)
{
vtkErrorMacro("Failed to determine texture parameters.");
return false;
}
GLenum target = GL_TEXTURE_1D;
this->Target = target;
this->Components = numComps;
this->Width = width;
this->Height = 1;
this->Depth = 1;
this->NumberOfDimensions = 1;
this->Context->ActivateTexture(this);
this->CreateTexture();
this->Bind();
glTexImage1D(this->Target,
0,
this->InternalFormat,
static_cast<GLsizei> (this->Width),
0,
this->Format,
this->Type,
static_cast<const GLvoid *> (data));
vtkOpenGLCheckErrorMacro("failed at glTexImage1D");
this->Deactivate();
return true;
}
// ----------------------------------------------------------------------------
// Description:
// Create a 1D alpha texture using a raw pointer.
// This is a blocking call. If you can, use PBO instead.
bool vtkTextureObject::CreateAlphaFromRaw(unsigned int width,
int internalFormat,
int rawType,
void* raw)
{
assert("pre: context_exists" && this->GetContext()!=0);
assert("pre: raw_exists" && raw!=0);
assert("pre: valid_internalFormat" && internalFormat>=0
&& internalFormat<NumberOfAlphaFormats);
// Now, detemine texture parameters using the arguments.
this->GetDataType(rawType);
if (!this->InternalFormat)
{
this->InternalFormat
= OpenGLAlphaInternalFormat[internalFormat];
}
if (!this->InternalFormat || !this->Type)
{
vtkErrorMacro("Failed to detemine texture parameters.");
return false;
}
this->Target = GL_TEXTURE_1D;
this->Format = GL_RED;
this->Width = width;
this->Height = 1;
this->Depth = 1;
this->NumberOfDimensions = 1;
this->Components = 1;
this->Context->ActivateTexture(this);
this->CreateTexture();
this->Bind();
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage1D(this->Target, 0, static_cast<GLint>(this->InternalFormat),
static_cast<GLsizei>(this->Width), 0,
this->Format, this->Type, raw);
vtkOpenGLCheckErrorMacro("failed at glTexImage1D");
this->Deactivate();
return true;
}
// Description:
// Create a texture buffer basically a 1D texture that can be
// very large for passing data into the fragment shader
bool vtkTextureObject::CreateTextureBuffer(unsigned int numValues, int numComps,
int dataType, vtkOpenGLBufferObject *bo)
{
assert(this->Context);
// Now, detemine texture parameters using the arguments.
this->GetDataType(dataType);
this->GetInternalFormat(dataType, numComps, false);
this->GetFormat(dataType, numComps, false);
if (!this->InternalFormat || !this->Format || !this->Type)
{
vtkErrorMacro("Failed to detemine texture parameters.");
return false;
}
this->Target = GL_TEXTURE_BUFFER;
this->Components = numComps;
this->Width = numValues;
this->Height = 1;
this->Depth = 1;
this->NumberOfDimensions = 1;
this->BufferObject = bo;
this->Context->ActivateTexture(this);
this->CreateTexture();
this->Bind();
// Source texture data from the PBO.
glTexBuffer(
this->Target,
this->InternalFormat,
this->BufferObject->GetHandle());
vtkOpenGLCheckErrorMacro("failed at glTexBuffer");
this->Deactivate();
return true;
}
#else
// Description:
// Create a texture buffer basically a 1D texture that can be
// very large for passing data into the fragment shader
bool vtkTextureObject::CreateTextureBuffer(unsigned int numValues, int numComps,
int dataType, vtkOpenGLBufferObject *bo)
{
assert(this->Context);
vtkErrorMacro("TextureBuffers not supported in OPenGL ES");
// TODO: implement 1D and Texture buffers using 2D textures
return false;
}
#endif // not ES 2.0 or 3.0
#if GL_ES_VERSION_2_0 != 1 || GL_ES_VERSION_3_0 == 1
//----------------------------------------------------------------------------
bool vtkTextureObject::Create2D(unsigned int width, unsigned int height,
int numComps, vtkPixelBufferObject* pbo,
bool shaderSupportsTextureInt)
{
assert(this->Context);
assert(pbo->GetContext() == this->Context.GetPointer());
if (pbo->GetSize() < width*height*static_cast<unsigned int>(numComps))
{
vtkErrorMacro("PBO size must match texture size.");
return false;
}
// Now, detemine texture parameters using the information from the pbo.
// * internalFormat depends on number of components and the data type.
// * format depends on the number of components.
// * type if the data type in the pbo
int vtktype = pbo->GetType();
GLenum type = this->GetDefaultDataType(vtktype);
GLenum internalFormat
= this->GetInternalFormat(vtktype, numComps, shaderSupportsTextureInt);
GLenum format
= this->GetFormat(vtktype, numComps, shaderSupportsTextureInt);
if (!internalFormat || !format || !type)
{
vtkErrorMacro("Failed to detemine texture parameters.");
return false;
}
GLenum target = GL_TEXTURE_2D;
this->Target = target;
this->Context->ActivateTexture(this);
this->CreateTexture();
this->Bind();
// Source texture data from the PBO.
pbo->Bind(vtkPixelBufferObject::UNPACKED_BUFFER);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(
target,
0,
internalFormat,
static_cast<GLsizei>(width),
static_cast<GLsizei>(height),
0,
format,
type,
BUFFER_OFFSET(0));
vtkOpenGLCheckErrorMacro("failed at glTexImage2D");
pbo->UnBind();
this->Deactivate();
this->Target = target;
this->Format = format;
this->Type = type;
this->Components = numComps;
this->Width = width;
this->Height = height;
this->Depth = 1;
this->NumberOfDimensions = 2;
return true;
}
// ----------------------------------------------------------------------------
// Description:
// Create a 2D depth texture using a PBO.
bool vtkTextureObject::CreateDepth(unsigned int width,
unsigned int height,
int internalFormat,
vtkPixelBufferObject *pbo)
{
assert("pre: context_exists" && this->GetContext()!=0);
assert("pre: pbo_context_exists" && pbo->GetContext()!=0);
assert("pre: context_match" && this->GetContext()==pbo->GetContext());
assert("pre: sizes_match" && pbo->GetSize()==width*height);
assert("pre: valid_internalFormat" && internalFormat>=0
&& internalFormat<NumberOfDepthFormats);
GLenum inFormat=OpenGLDepthInternalFormat[internalFormat];
GLenum type = this->GetDefaultDataType(pbo->GetType());
this->Target=GL_TEXTURE_2D;
this->Format=GL_DEPTH_COMPONENT;
this->Type=type;
this->Width=width;
this->Height=height;
this->Depth=1;
this->NumberOfDimensions=2;
this->Components=1;
this->Context->ActivateTexture(this);
this->CreateTexture();
this->Bind();
pbo->Bind(vtkPixelBufferObject::UNPACKED_BUFFER);
// Source texture data from the PBO.
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(this->Target, 0, static_cast<GLint>(inFormat),
static_cast<GLsizei>(width), static_cast<GLsizei>(height), 0,
this->Format, this->Type, BUFFER_OFFSET(0));
vtkOpenGLCheckErrorMacro("failed at glTexImage2D");
pbo->UnBind();
this->Deactivate();
return true;
}
//----------------------------------------------------------------------------
bool vtkTextureObject::Create3D(unsigned int width, unsigned int height,
unsigned int depth, int numComps,
vtkPixelBufferObject* pbo,
bool shaderSupportsTextureInt)
{
#ifdef GL_TEXTURE_3D
assert(this->Context);
assert(this->Context.GetPointer() == pbo->GetContext());
if (pbo->GetSize() != width*height*depth*static_cast<unsigned int>(numComps))
{
vtkErrorMacro("PBO size must match texture size.");
return false;
}
GLenum target = GL_TEXTURE_3D;
// Now, detemine texture parameters using the information from the pbo.
// * internalFormat depends on number of components and the data type.
GLenum internalFormat = this->GetInternalFormat(pbo->GetType(), numComps,
shaderSupportsTextureInt);
// * format depends on the number of components.
GLenum format = this->GetFormat(pbo->GetType(), numComps,
shaderSupportsTextureInt);
// * type if the data type in the pbo
GLenum type = this->GetDefaultDataType(pbo->GetType());
if (!internalFormat || !format || !type)
{
vtkErrorMacro("Failed to detemine texture parameters.");
return false;
}
this->Target = target;
this->Context->ActivateTexture(this);
this->CreateTexture();
this->Bind();
pbo->Bind(vtkPixelBufferObject::UNPACKED_BUFFER);
// Source texture data from the PBO.
glTexImage3D(target, 0, static_cast<GLint>(internalFormat),
static_cast<GLsizei>(width), static_cast<GLsizei>(height),
static_cast<GLsizei>(depth), 0, format, type,
BUFFER_OFFSET(0));
vtkOpenGLCheckErrorMacro("failed at glTexImage3D");
pbo->UnBind();
this->Deactivate();
this->Target = target;
this->Format = format;
this->Type = type;
this->Components = numComps;
this->Width = width;
this->Height = height;
this->Depth = depth;
this->NumberOfDimensions = 3;
return true;
#else
return false;
#endif
}
//----------------------------------------------------------------------------
vtkPixelBufferObject* vtkTextureObject::Download()
{
assert(this->Context);
assert(this->Handle);
vtkPixelBufferObject* pbo = vtkPixelBufferObject::New();
pbo->SetContext(this->Context);
int vtktype = ::vtkGetVTKType(this->Type);
if (vtktype == 0)
{
vtkErrorMacro("Failed to determine type.");
return 0;
}
unsigned int size = this->Width* this->Height* this->Depth;
// doesn't matter which Upload*D method we use since we are not really
// uploading any data, simply allocating GPU space.
if (!pbo->Upload1D(vtktype, NULL, size, this->Components, 0))
{
vtkErrorMacro("Could not allocate memory for PBO.");
pbo->Delete();
return 0;
}
pbo->Bind(vtkPixelBufferObject::PACKED_BUFFER);
this->Bind();
#if GL_ES_VERSION_2_0 != 1
glGetTexImage(this->Target, 0, this->Format, this->Type, BUFFER_OFFSET(0));
#else
// you can do something with glReadPixels and binding a texture as a FBO
// I believe for ES 2.0
#endif
vtkOpenGLCheckErrorMacro("failed at glGetTexImage");
this->Deactivate();
pbo->UnBind();
pbo->SetComponents(this->Components);
return pbo;
}
//----------------------------------------------------------------------------
bool vtkTextureObject::Create3DFromRaw(unsigned int width, unsigned int height,
unsigned int depth, int numComps,
int dataType, void *data)
{
assert(this->Context);
// Now, detemine texture parameters using the arguments.
this->GetDataType(dataType);
this->GetInternalFormat(dataType, numComps, false);
this->GetFormat(dataType, numComps, false);
if (!this->InternalFormat || !this->Format || !this->Type)
{
vtkErrorMacro("Failed to detemine texture parameters.");
return false;
}
this->Target = GL_TEXTURE_3D;
this->Components = numComps;
this->Width = width;
this->Height = height;
this->Depth = depth;
this->NumberOfDimensions = 3;
this->Context->ActivateTexture(this);
this->CreateTexture();
this->Bind();
// Source texture data from the PBO.
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage3D(
this->Target,
0,
this->InternalFormat,
static_cast<GLsizei>(this->Width),
static_cast<GLsizei>(this->Height),
static_cast<GLsizei>(this->Depth),
0,
this->Format,
this->Type,
static_cast<const GLvoid *>(data));
vtkOpenGLCheckErrorMacro("failed at glTexImage2D");
this->Deactivate();
return true;
}
#endif
//----------------------------------------------------------------------------
bool vtkTextureObject::Create2DFromRaw(unsigned int width, unsigned int height,
int numComps, int dataType, void *data)
{
assert(this->Context);
// Now determine the texture parameters using the arguments.
this->GetDataType(dataType);
this->GetInternalFormat(dataType, numComps, false);
this->GetFormat(dataType, numComps, false);
if (!this->InternalFormat || !this->Format || !this->Type)
{
vtkErrorMacro("Failed to determine texture parameters. IF="
<< this->InternalFormat << " F=" << this->Format << " T=" << this->Type);
return false;
}
GLenum target = GL_TEXTURE_2D;
this->Target = target;
this->Components = numComps;
this->Width = width;
this->Height = height;
this->Depth = 1;
this->NumberOfDimensions = 2;
this->Context->ActivateTexture(this);
this->CreateTexture();
this->Bind();
// Source texture data from the PBO.
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(
this->Target,
0,
this->InternalFormat,
static_cast<GLsizei>(this->Width),
static_cast<GLsizei>(this->Height),
0,
this->Format,
this->Type,
static_cast<const GLvoid *>(data));
vtkOpenGLCheckErrorMacro("failed at glTexImage2D");
this->Deactivate();
return true;
}
// ----------------------------------------------------------------------------
// Description:
// Create a 2D depth texture using a raw pointer.
// This is a blocking call. If you can, use PBO instead.
bool vtkTextureObject::CreateDepthFromRaw(unsigned int width,
unsigned int height,
int internalFormat,
int rawType,
void *raw)
{
assert("pre: context_exists" && this->GetContext()!=0);
assert("pre: raw_exists" && raw!=0);
assert("pre: valid_internalFormat" && internalFormat>=0
&& internalFormat<NumberOfDepthFormats);
// Now, detemine texture parameters using the arguments.
this->GetDataType(rawType);
if (!this->InternalFormat)
{
this->InternalFormat
= OpenGLDepthInternalFormat[internalFormat];;
}
if (!this->InternalFormat || !this->Type)
{
vtkErrorMacro("Failed to detemine texture parameters.");
return false;
}
this->Target = GL_TEXTURE_2D;
this->Format = GL_DEPTH_COMPONENT;
this->Width = width;
this->Height = height;
this->Depth = 1;
this->NumberOfDimensions = 2;
this->Components = 1;
this->Context->ActivateTexture(this);
this->CreateTexture();
this->Bind();
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(this->Target, 0, static_cast<GLint>(this->InternalFormat),
static_cast<GLsizei>(this->Width),
static_cast<GLsizei>(this->Height), 0,
this->Format, this->Type,raw);
vtkOpenGLCheckErrorMacro("failed at glTexImage2D");
this->Deactivate();
return true;
}
// ----------------------------------------------------------------------------
bool vtkTextureObject::AllocateDepth(unsigned int width, unsigned int height,
int internalFormat)
{
assert("pre: context_exists" && this->GetContext()!=0);
assert("pre: valid_internalFormat" && internalFormat>=0
&& internalFormat<NumberOfDepthFormats);
this->Target = GL_TEXTURE_2D;
this->Format = GL_DEPTH_COMPONENT;
// Try to match vtk type to internal fmt
if (!this->Type)
{
this->Type = OpenGLDepthInternalFormatType[internalFormat];
}
if (!this->InternalFormat)
{
this->InternalFormat = OpenGLDepthInternalFormat[internalFormat];
}
this->Width = width;
this->Height = height;
this->Depth = 1;
this->NumberOfDimensions = 2;
this->Components = 1;
this->Context->ActivateTexture(this);
this->CreateTexture();
this->Bind();
glTexImage2D(
this->Target,
0,
static_cast<GLint>(this->InternalFormat),
static_cast<GLsizei>(this->Width),
static_cast<GLsizei>(this->Height),
0,
this->Format,
this->Type,
0);
vtkOpenGLCheckErrorMacro("failed at glTexImage2D");
this->Deactivate();
return true;
}
// ----------------------------------------------------------------------------
bool vtkTextureObject::Allocate1D(unsigned int width, int numComps,
int vtkType)
{
#ifdef GL_TEXTURE_1D
assert(this->Context);
this->Target = GL_TEXTURE_1D;
this->GetDataType(vtkType);
this->GetInternalFormat(vtkType, numComps, false);
this->GetFormat(vtkType, numComps, false);
this->Components = numComps;
this->Width = width;
this->Height = 1;
this->Depth = 1;
this->NumberOfDimensions = 1;
this->Context->ActivateTexture(this);
this->CreateTexture();
this->Bind();
glTexImage1D(this->Target, 0, static_cast<GLint>(this->InternalFormat),
static_cast<GLsizei>(this->Width), 0, this->Format,
this->Type,0);
vtkOpenGLCheckErrorMacro("failed at glTexImage1D");
this->Deactivate();
return true;
#else
return false;
#endif
}
// ----------------------------------------------------------------------------
// Description:
// Create a 2D color texture but does not initialize its values.
// Internal format is deduced from numComps and vtkType.
bool vtkTextureObject::Allocate2D(unsigned int width,unsigned int height,
int numComps, int vtkType)
{
assert(this->Context);
this->Target = GL_TEXTURE_2D;
this->GetDataType(vtkType);
this->GetInternalFormat(vtkType, numComps, false);
this->GetFormat(vtkType, numComps,false);
this->Components = numComps;
this->Width = width;
this->Height = height;
this->Depth =1;
this->NumberOfDimensions=2;
this->Context->ActivateTexture(this);
this->CreateTexture();
this->Bind();
glTexImage2D(this->Target, 0, static_cast<GLint>(this->InternalFormat),
static_cast<GLsizei>(this->Width),
static_cast<GLsizei>(this->Height),
0, this->Format, this->Type, 0);
vtkOpenGLCheckErrorMacro("failed at glTexImage2D");
this->Deactivate();
return true;
}
// ----------------------------------------------------------------------------
// Description:
// Create a 3D color texture but does not initialize its values.
// Internal format is deduced from numComps and vtkType.
bool vtkTextureObject::Allocate3D(unsigned int width,unsigned int height,
unsigned int depth, int numComps,
int vtkType)
{
#ifdef GL_TEXTURE_3D
this->Target=GL_TEXTURE_3D;
if(this->Context==0)
{
vtkErrorMacro("No context specified. Cannot create texture.");
return false;
}
this->GetInternalFormat(vtkType, numComps, false);
this->GetFormat(vtkType, numComps, false);
this->GetDataType(vtkType);
this->Components = numComps;
this->Width = width;
this->Height = height;
this->Depth = depth;
this->NumberOfDimensions = 3;
this->Context->ActivateTexture(this);
this->CreateTexture();
this->Bind();
glTexImage3D(this->Target, 0,
static_cast<GLint>(this->InternalFormat),
static_cast<GLsizei>(this->Width),
static_cast<GLsizei>(this->Height),
static_cast<GLsizei>(this->Depth), 0,
this->Format, this->Type, 0);
vtkOpenGLCheckErrorMacro("failed at glTexImage3D");
this->Deactivate();
return true;
#else
return false;
#endif
}
//----------------------------------------------------------------------------
bool vtkTextureObject::Create2D(unsigned int width, unsigned int height,
int numComps, int vtktype,
bool shaderSupportsTextureInt)
{
assert(this->Context);
GLenum target = GL_TEXTURE_2D;
// Now, detemine texture parameters using the information provided.
this->GetDataType(vtktype);
this->GetInternalFormat(vtktype, numComps, shaderSupportsTextureInt);
this->GetFormat(vtktype, numComps, shaderSupportsTextureInt);
if (!this->InternalFormat || !this->Format || !this->Type)
{
vtkErrorMacro("Failed to detemine texture parameters.");
return false;
}
this->Target = target;
this->Components = numComps;
this->Width = width;
this->Height = height;
this->Depth = 1;
this->NumberOfDimensions = 2;
this->Context->ActivateTexture(this);
this->CreateTexture();
this->Bind();
// Allocate space for texture, don't upload any data.
glTexImage2D(target, 0,
static_cast<GLint>(this->InternalFormat),
static_cast<GLsizei>(this->Width),
static_cast<GLsizei>(this->Height),
0, this->Format, this->Type, NULL);
vtkOpenGLCheckErrorMacro("failed at glTexImage2D");
this->Deactivate();
return true;
}
//----------------------------------------------------------------------------
bool vtkTextureObject::Create3D(unsigned int width, unsigned int height,
unsigned int depth,
int numComps, int vtktype,
bool shaderSupportsTextureInt)
{
#ifdef GL_TEXTURE_3D
assert(this->Context);
GLenum target = GL_TEXTURE_3D;
// Now, detemine texture parameters using the information provided.
this->GetInternalFormat(vtktype, numComps, shaderSupportsTextureInt);
this->GetFormat(vtktype, numComps, shaderSupportsTextureInt);
this->GetDataType(vtktype);
if (!this->InternalFormat || !this->Format || !this->Type)
{
vtkErrorMacro("Failed to detemine texture parameters.");
return false;
}
this->Target = target;
this->Components = numComps;
this->Width = width;
this->Height = height;
this->Depth = depth;
this->NumberOfDimensions = 3;
this->Context->ActivateTexture(this);
this->CreateTexture();
this->Bind();
// Allocate space for texture, don't upload any data.
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage3D(this->Target, 0,
static_cast<GLint>(this->InternalFormat),
static_cast<GLsizei>(this->Width),
static_cast<GLsizei>(this->Height),
static_cast<GLsizei>(this->Depth), 0,
this->Format, this->Type, NULL);
vtkOpenGLCheckErrorMacro("falied at glTexImage3D");
this->Deactivate();
return true;
#else
return false;
#endif
}
// ----------------------------------------------------------------------------
void vtkTextureObject::CopyToFrameBuffer(
vtkShaderProgram *program, vtkOpenGLVertexArrayObject *vao)
{
// the following math really only works when texture
// and viewport are of the same dimensions
float minXTexCoord=static_cast<float>(
static_cast<double>(0.5)/this->Width);
float minYTexCoord=static_cast<float>(
static_cast<double>(0.5)/this->Height);
float maxXTexCoord=static_cast<float>(
static_cast<double>(this->Width-0.5)/this->Width);
float maxYTexCoord=static_cast<float>(
static_cast<double>(this->Height-0.5)/this->Height);
float tcoords[] = {
minXTexCoord, minYTexCoord,
maxXTexCoord, minYTexCoord,
maxXTexCoord, maxYTexCoord,
minXTexCoord, maxYTexCoord};
float verts[] = {
-1.0f, -1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
1.0f, 1.0f, 0.0f,
-1.0f, 1.0f, 0.0f};
this->CopyToFrameBuffer(tcoords, verts, program, vao);
}
// ----------------------------------------------------------------------------
void vtkTextureObject::CopyToFrameBuffer(
int srcXmin, int srcYmin,
int srcXmax, int srcYmax,
int dstXmin, int dstYmin,
int dstSizeX, int dstSizeY,
vtkShaderProgram *program, vtkOpenGLVertexArrayObject *vao)
{
float dstXmax = static_cast<float>(dstXmin+srcXmax-srcXmin);
float dstYmax = static_cast<float>(dstYmin+srcYmax-srcYmin);
this->CopyToFrameBuffer(srcXmin, srcYmin, srcXmax, srcYmax,
dstXmin, dstYmin, dstXmax, dstYmax, dstSizeX, dstSizeY,
program, vao);
}
// ----------------------------------------------------------------------------
void vtkTextureObject::CopyToFrameBuffer(
int srcXmin, int srcYmin,
int srcXmax, int srcYmax,
int dstXmin, int dstYmin,
int dstXmax, int dstYmax,
int dstSizeX, int dstSizeY,
vtkShaderProgram *program, vtkOpenGLVertexArrayObject *vao)
{
assert("pre: positive_srcXmin" && srcXmin>=0);
assert("pre: max_srcXmax" &&
static_cast<unsigned int>(srcXmax)<this->GetWidth());
assert("pre: increasing_x" && srcXmin<=srcXmax);
assert("pre: positive_srcYmin" && srcYmin>=0);
assert("pre: max_srcYmax" &&
static_cast<unsigned int>(srcYmax)<this->GetHeight());
assert("pre: increasing_y" && srcYmin<=srcYmax);
assert("pre: positive_dstXmin" && dstXmin>=0);
assert("pre: positive_dstYmin" && dstYmin>=0);
float minXTexCoord=static_cast<float>(
static_cast<double>(srcXmin+0.5)/this->Width);
float minYTexCoord=static_cast<float>(
static_cast<double>(srcYmin+0.5)/this->Height);
float maxXTexCoord=static_cast<float>(
static_cast<double>(srcXmax+0.5)/this->Width);
float maxYTexCoord=static_cast<float>(
static_cast<double>(srcYmax+0.5)/this->Height);
GLint saved_viewport[4];
glGetIntegerv(GL_VIEWPORT, saved_viewport);
glViewport(0,0,dstSizeX,dstSizeY);
float tcoords[] = {
minXTexCoord, minYTexCoord,
maxXTexCoord, minYTexCoord,
maxXTexCoord, maxYTexCoord,
minXTexCoord, maxYTexCoord};
float verts[] = {
2.0f*dstXmin/dstSizeX-1.0f, 2.0f*dstYmin/dstSizeY-1.0f, 0.0f,
2.0f*(dstXmax+1.0f)/dstSizeX-1.0f, 2.0f*dstYmin/dstSizeY-1.0f, 0.0f,
2.0f*(dstXmax+1.0f)/dstSizeX-1.0f, 2.0f*(dstYmax+1.0f)/dstSizeY-1.0f, 0.0f,
2.0f*dstXmin/dstSizeX-1.0f, 2.0f*(dstYmax+1.0f)/dstSizeY-1.0f, 0.0f};
this->CopyToFrameBuffer(tcoords, verts, program, vao);
glViewport(saved_viewport[0], saved_viewport[1], saved_viewport[2],
saved_viewport[3]);
}
void vtkTextureObject::CopyToFrameBuffer(float *tcoords, float *verts,
vtkShaderProgram *program, vtkOpenGLVertexArrayObject *vao)
{
vtkOpenGLClearErrorMacro();
// if no program or VAO was provided, then use
// a simple pass through program and bind this
// texture to it
if (!program || !vao)
{
if (!this->ShaderProgram)
{
this->ShaderProgram = new vtkOpenGLHelper;
// build the shader source code
std::string VSSource = vtkTextureObjectVS;
std::string FSSource = vtkTextureObjectFS;
std::string GSSource;
// compile and bind it if needed
vtkShaderProgram *newShader =
this->Context->GetShaderCache()->ReadyShaderProgram(
VSSource.c_str(),
FSSource.c_str(),
GSSource.c_str());
// if the shader changed reinitialize the VAO
if (newShader != this->ShaderProgram->Program)
{
this->ShaderProgram->Program = newShader;
this->ShaderProgram->VAO->ShaderProgramChanged(); // reset the VAO as the shader has changed
}
this->ShaderProgram->ShaderSourceTime.Modified();
}
else
{
this->Context->GetShaderCache()->ReadyShaderProgram(
this->ShaderProgram->Program);
}
// bind and activate this texture
this->Activate();
int sourceId = this->GetTextureUnit();
this->ShaderProgram->Program->SetUniformi("source",sourceId);
vtkOpenGLRenderUtilities::RenderQuad(verts, tcoords, this->ShaderProgram->Program,
this->ShaderProgram->VAO);
this->Deactivate();
}
else
{
vtkOpenGLRenderUtilities::RenderQuad(verts, tcoords, program, vao);
}
vtkOpenGLCheckErrorMacro("failed after CopyToFrameBuffer")
}
//----------------------------------------------------------------------------
// Description:
// Copy a sub-part of a logical buffer of the framebuffer (color or depth)
// to the texture object. src is the framebuffer, dst is the texture.
// (srcXmin,srcYmin) is the location of the lower left corner of the
// rectangle in the framebuffer. (dstXmin,dstYmin) is the location of the
// lower left corner of the rectangle in the texture. width and height
// specifies the size of the rectangle in pixels.
// If the logical buffer is a color buffer, it has to be selected first with
// glReadBuffer().
// \pre is2D: GetNumberOfDimensions()==2
void vtkTextureObject::CopyFromFrameBuffer(int srcXmin,
int srcYmin,
int vtkNotUsed(dstXmin),
int vtkNotUsed(dstYmin),
int width,
int height)
{
assert("pre: is2D" && this->GetNumberOfDimensions()==2);
this->Activate();
glCopyTexImage2D(this->Target,0,this->Format,srcXmin,srcYmin,width,height,0);
vtkOpenGLCheckErrorMacro("failed at glCopyTexImage2D " << this->Format);
}
//----------------------------------------------------------------------------
void vtkTextureObject::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "Width: " << this->Width << endl;
os << indent << "Height: " << this->Height << endl;
os << indent << "Depth: " << this->Depth << endl;
os << indent << "Components: " << this->Components << endl;
os << indent << "Handle: " << this->Handle << endl;
os << indent << "Target: ";
switch(this->Target)
{
#ifdef GL_TEXTURE_1D
case GL_TEXTURE_1D:
os << "GL_TEXTURE_1D" << endl;
break;
#endif
case GL_TEXTURE_2D:
os << "GL_TEXTURE_2D" << endl;
break;
#ifdef GL_TEXTURE_3D
case GL_TEXTURE_3D:
os << "GL_TEXTURE_3D" << endl;
break;
#endif
default:
os << "unknown value: 0x" << hex << this->Target << dec <<endl;
break;
}
os << indent << "NumberOfDimensions: " << this->NumberOfDimensions << endl;
os << indent << "WrapS: " << WrapAsString[this->WrapS] << endl;
os << indent << "WrapT: " << WrapAsString[this->WrapT] << endl;
os << indent << "WrapR: " << WrapAsString[this->WrapR] << endl;
os << indent << "MinificationFilter: "
<< MinMagFilterAsString[this->MinificationFilter] << endl;
os << indent << "MagnificationFilter: "
<< MinMagFilterAsString[this->MagnificationFilter] << endl;
os << indent << "MinLOD: " << this->MinLOD << endl;
os << indent << "MaxLOD: " << this->MaxLOD << endl;
os << indent << "BaseLevel: " << this->BaseLevel << endl;
os << indent << "MaxLevel: " << this->MaxLevel << endl;
os << indent << "DepthTextureCompare: " << this->DepthTextureCompare
<< endl;
os << indent << "DepthTextureCompareFunction: "
<< DepthTextureCompareFunctionAsString[this->DepthTextureCompareFunction]
<< endl;
os << indent << "GenerateMipmap: " << this->GenerateMipmap << endl;
}
| [
"vejmarie@ruggedpod.qyshare.com"
] | vejmarie@ruggedpod.qyshare.com |
5677ab9a459a08f8541cbe2719a4cc51c212215c | 04edd07877771af42f66847baaefda410c265767 | /src/Object/Light.h | 2c05e6ef7a2aaabbe11250a187968bc5c7c4e506 | [] | no_license | aljox/Ray-Tracer | f59fae7b7bc4a53a7d7eb1ed0813773265e09ec7 | 6bfa61d9c9d365e764d520f37ddc3d508b6928cd | refs/heads/master | 2021-04-01T07:01:12.803758 | 2020-03-18T08:17:08 | 2020-03-18T08:17:08 | 248,166,339 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,752 | h | #pragma once
#include "./Object.h"
#include <string>
class Light : public Object
{
protected:
std::string m_type;
Vec3f m_albedo;
float m_intensity;
float m_ambientConst;
float m_diffuseConst;
float m_speculatConst;
public:
Light() {};
~Light() {};
Light(Vec3f albedo)
{
m_type = "Light";
m_albedo = albedo;
m_intensity = 1.0;
m_ambientConst = 0.1f;
m_diffuseConst = 0.8f;
m_speculatConst = 0.8f;
}
Light(Vec3f albedo, float intensity)
{
m_type = "Light";
m_albedo = albedo;
m_intensity = intensity;
m_ambientConst = 0.1f;
m_diffuseConst = 0.8f;
m_speculatConst = 0.8f;
}
Light(Vec3f albedo, float intensity, float ambientConst, float diffuseConst, float specularConst)
{
m_type = "Light";
m_albedo = albedo;
m_intensity = intensity;
m_ambientConst = ambientConst;
m_diffuseConst = diffuseConst;
m_speculatConst = specularConst;
}
virtual Vec3f generateShadowRayDir(Vec3f hitPoint) { return Vec3f(0.0f, 0.0f, 0.0f); }
void setAlbedo(Vec3f albedo) { m_albedo = albedo; }
void setIntensity(float intensity) { m_intensity = intensity; }
void setAmbientConst(float ambientConst) { m_ambientConst = ambientConst; }
void setDiffuseConst(float diffuseConst) { m_diffuseConst = diffuseConst; }
void setSpecularConst(float speculatConst) { m_speculatConst = speculatConst; }
std::string getType() { return m_type; }
Vec3f getAlbedo() { return m_albedo; }
float getIntensity() { return m_intensity; }
float getAmbientConst() { return m_ambientConst; }
float getDiffuseConst() { return m_diffuseConst; }
float getSpecularConst() { return m_speculatConst; }
}; | [
"noreply@github.com"
] | aljox.noreply@github.com |
db16bc2a02b455eb7d7156bb1a70fda0525593eb | eda7f1e5c79682bf55cfa09582a82ce071ee6cee | /aspects/thermal/network/test/UtThermFileParser.cpp | 11a06931118b688a6e47857b70de4263dea2eee2 | [
"LicenseRef-scancode-us-govt-public-domain",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | nasa/gunns | 923f4f7218e2ecd0a18213fe5494c2d79a566bb3 | d5455e3eaa8b50599bdb16e4867a880705298f62 | refs/heads/master | 2023-08-30T06:39:08.984844 | 2023-07-27T12:18:42 | 2023-07-27T12:18:42 | 235,422,976 | 34 | 11 | NOASSERTION | 2023-08-30T15:11:41 | 2020-01-21T19:21:16 | C++ | UTF-8 | C++ | false | false | 28,542 | cpp | /************************** TRICK HEADER ***********************************************************
@copyright Copyright 2019 United States Government as represented by the Administrator of the
National Aeronautics and Space Administration. All Rights Reserved.
LIBRARY DEPENDENCY:
((aspects/thermal/network/ThermFileParser.o))
***************************************************************************************************/
#include "UtThermFileParser.hh"
#include "software/exceptions/TsParseException.hh"
#include "software/exceptions/TsOutOfBoundsException.hh"
#include <iostream>
#include <string>
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details This is the default constructor for the UtThermFileParser class.
////////////////////////////////////////////////////////////////////////////////////////////////////
UtThermFileParser::UtThermFileParser()
:
tTimeStep(),
tTol(),
tNameError(),
tArticle(),
tNodeFile(),
tCondFile(),
tRadFile(),
tHtrFile(),
tPanFile(),
tEtcFile(),
tThermInputFile(),
tNumNodes(),
tNode(),
tNodeName(),
tSpaceNode(),
tNumLinksCap(),
tCap(),
tCapName(),
tCapTemperature(),
tCapCapacitance(),
tCapGroup(),
tNumLinksCond(),
tCond(),
tCondName(),
tCondNode0(),
tCondNode1(),
tCondConductivity(),
tCond2(),
tCond2Name(),
tNumLinksRad(),
tRad(),
tRadName(),
tRadNode0(),
tRadNode1(),
tRadCoefficient(),
tNumLinksHtr(),
tHtrA(),
tHtrAName(),
tHtrAScalar(),
tHtrAPorts(),
tHtrANode0(),
tHtrANode1(),
tHtrANode2(),
tHtrANode3(),
tHtrANode4(),
tHtrANode5(),
tHtrAFrac0(),
tHtrAFrac1(),
tHtrAFrac2(),
tHtrAFrac3(),
tHtrAFrac4(),
tHtrAFrac5(),
tHtrB(),
tHtrBName(),
tHtrBScalar(),
tHtrBPorts(),
tHtrBNode0(),
tHtrBNode1(),
tHtrBNode2(),
tHtrBNode3(),
tHtrBNode4(),
tHtrBNode5(),
tHtrBFrac0(),
tHtrBFrac1(),
tHtrBFrac2(),
tHtrBFrac3(),
tHtrBFrac4(),
tHtrBFrac5(),
tNumLinksPan(),
tPan(),
tPanName(),
tPanPorts(),
tPanNode0(),
tPanNode1(),
tPanArea(),
tPanAbsorptivity(),
tNumLinksPot(),
tPot(),
tPotName(),
tPotNode(),
tPotTemperature(),
tPotConductivity(),
tNumLinksSrc(),
tSrc(),
tSrcName(),
tSrcNode0(),
tSrcNode1(),
tSrcNode2(),
tSrcNode3(),
tSrcFrac0(),
tSrcFrac1(),
tSrcFrac2(),
tSrcFrac3(),
tSrcFlux()
{
//do nothing
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details This is the default destructor for the UtThermFileParser class.
////////////////////////////////////////////////////////////////////////////////////////////////////
UtThermFileParser::~UtThermFileParser()
{
//do nothing
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Executed after each unit test.
////////////////////////////////////////////////////////////////////////////////////////////////////
void UtThermFileParser::tearDown()
{
/// - Deletes for news in setUp
delete tArticle;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Executed before each unit test.
////////////////////////////////////////////////////////////////////////////////////////////////////
void UtThermFileParser::setUp()
{
/// - test technical data
tTol = 0.0001;
tTimeStep = 0.1;
tNameError = "(error setting name)";
/// - Declare the config-files.
tNodeFile = "ThermNodes_base.xml";
tCondFile = "ThermLinksCond_base.xml";
tRadFile = "ThermLinksRad_base.xml";
tHtrFile = "HtrRegistry_base.xml";
tPanFile = "ThermLinksPan_base.xml";
tEtcFile = "ThermLinksEtc_base.xml";
/// - Declare the input-files.
tThermInputFile = "ThermInput_base.xml";
/// - nominal node data from the test case
tNumNodes = 22;
tNode = 15;
tNodeName = "CMRCSNR1_20";
tSpaceNode = "SPACE_1";
/// - nominal capacitance link data from the test case
tNumLinksCap = 21;
tCap = 6;
tCapName = "cap_CMBCKSHL_13330";
tCapTemperature = 455;
tCapCapacitance = 4722.05;
tCapGroup = 1;
/// - nominal conduction link data from the test case
tNumLinksCond = 8;
tCond = 5;
tCondNode0 = "CMPRPHYT_2";
tCondNode1 = "CMPRPHYT_20";
tCondName = "cond " + tCondNode0 + " to " + tCondNode1;
tCondConductivity = 0.40;
tCond2 = 6;
tCond2Name = "hydrazine tank bracket";
/// - nominal radiation link data from the test case
tNumLinksRad = 17;
tRad = 7;
tRadNode0 = "CMBCKSHL_13330";
tRadNode1 = "CMHS_62803";
tRadName = "rad " + tRadNode0 + " to " + tRadNode1;
tRadCoefficient = 53.1;
/// - nominal ThermalPanel data from the test case
tNumLinksPan = 3;
tPan = 0;
tPanName = "shell";
tPanPorts = 2;
tPanNode0 = "CMBCKSHL_13330";
tPanNode1 = "CMHS_48233";
tPanArea = 14.531;
tPanAbsorptivity = 0.43;
/// - nominal heater A data from the test case
tNumLinksHtr = 3;
tHtrA = 0;
tHtrAName = "eclss heater";
tHtrAScalar = 0.93;
tHtrAPorts = 3;
tHtrANode0 = "CECLSS_46";
tHtrANode1 = "CECLSS_26";
tHtrANode2 = "CECLSS_161";
tHtrAFrac0 = 0.46;
tHtrAFrac1 = 0.46;
tHtrAFrac2 = 0.08;
/// - nominal heater B data from the test case
tHtrB = 2;
tHtrBName = "tank heater";
tHtrBScalar = 0.99;
tHtrBPorts = 2;
tHtrBNode0 = "CMPRPHET_1";
tHtrBNode1 = "CMPRPHET_100";
tHtrBFrac0 = 0.5;
tHtrBFrac1 = 0.5;
/// - nominal potential link data from the test case
tNumLinksPot = 2;
tPot = 1;
tPotName = "pressure vessel";
tPotNode = "CPV_5380";
tPotTemperature = 318;
tPotConductivity = 1e12;
/// - nominal source link data from the test case
tNumLinksSrc = 2;
tSrc = 1;
tSrcName = "multi-node source";
tSrcNode0 = "CMAFTGUS_30";
tSrcNode1 = "CMAFTGUS_31";
tSrcNode2 = "CRRMECH_200";
tSrcNode3 = "CRRMECH_300";
tSrcFrac0 = 0.3;
tSrcFrac1 = 0.3;
tSrcFrac2 = 0.2;
tSrcFrac3 = 0.2;
tSrcFlux = 100;
/// - Create the test article.
tArticle = new FriendlyThermFileParser();
/// - Simulate the setting of config-files by ThermalNetwork.
tArticle->mNodeFile = tNodeFile;
tArticle->mCondFile = tCondFile;
tArticle->mRadFile = tRadFile;
tArticle->mHtrFile = tHtrFile;
tArticle->mPanFile = tPanFile;
tArticle->mEtcFile = tEtcFile;
/// - Read files!
tArticle->initialize("article_nominal");
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Tests for appropriate construction.
////////////////////////////////////////////////////////////////////////////////////////////////////
void UtThermFileParser::testConstruction()
{
std::cout << "\n -----------------------------------------------------------------------------";
std::cout << "\n ThermFileParser 01: Testing default construction ..............";
/// - Default construct an un-initialized test article.
FriendlyThermFileParser article;
/// @test Logistic data
CPPUNIT_ASSERT_EQUAL_MESSAGE("NOT_FOUND", -99, article.NOT_FOUND );
CPPUNIT_ASSERT_EQUAL_MESSAGE("areNodesRegistered", false, article.areNodesRegistered );
CPPUNIT_ASSERT_MESSAGE("mName", "" == article.mName );
/// @test Node data
CPPUNIT_ASSERT_EQUAL_MESSAGE("numNodes", 0, article.numNodes );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vNodeNames", 0, static_cast<int>(article.vNodeNames.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("mNodeMap", 0, static_cast<int>(article.mNodeMap.size()) );
/// @test Capacitance link data
CPPUNIT_ASSERT_EQUAL_MESSAGE("numLinksCap", 0, article.numLinksCap );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vCapNames", 0, static_cast<int>(article.vCapNames.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vCapTemperatures", 0, static_cast<int>(article.vCapTemperatures.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vCapCapacitances", 0, static_cast<int>(article.vCapCapacitances.size()) );
/// @test Conduction link data
CPPUNIT_ASSERT_EQUAL_MESSAGE("numLinksCond", 0, article.numLinksCond );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vCondNames", 0, static_cast<int>(article.vCondNames.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vCondPorts0", 0, static_cast<int>(article.vCondPorts0.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vCondPorts1", 0, static_cast<int>(article.vCondPorts1.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vCondConductivities", 0, static_cast<int>(article.vCondConductivities.size()) );
/// @test Radiation link data
CPPUNIT_ASSERT_EQUAL_MESSAGE("numLinksRad", 0, article.numLinksRad );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vRadNames", 0, static_cast<int>(article.vRadNames.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vRadPorts0", 0, static_cast<int>(article.vRadPorts0.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vRadPorts1", 0, static_cast<int>(article.vRadPorts1.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vRadCoefficients", 0, static_cast<int>(article.vRadCoefficients.size()) );
/// @test Heater link data
CPPUNIT_ASSERT_EQUAL_MESSAGE("numLinksHtr", 0, article.numLinksHtr );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vHtrNames", 0, static_cast<int>(article.vHtrNames.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vHtrScalars", 0, static_cast<int>(article.vHtrScalars.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vHtrPorts", 0, static_cast<int>(article.vHtrPorts.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vHtrFracs", 0, static_cast<int>(article.vHtrFracs.size()) );
/// @test Panel data
CPPUNIT_ASSERT_EQUAL_MESSAGE("numLinksPan", 0, article.numLinksPan );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vPanNames", 0, static_cast<int>(article.vPanNames.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vPanAbsorptivities", 0, static_cast<int>(article.vPanAbsorptivities.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vPanPorts", 0, static_cast<int>(article.vPanPorts.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vPanFracs", 0, static_cast<int>(article.vPanFracs.size()) );
/// @test Potential link data
CPPUNIT_ASSERT_EQUAL_MESSAGE("numLinksPot", 0, article.numLinksPot );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vPotNames", 0, static_cast<int>(article.vPotNames.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vPotPorts", 0, static_cast<int>(article.vPotPorts.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vPotTemperatures", 0, static_cast<int>(article.vPotTemperatures.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vPotConductivities", 0, static_cast<int>(article.vPotConductivities.size()) );
/// @test Source link data
CPPUNIT_ASSERT_EQUAL_MESSAGE("numLinksSrc", 0, article.numLinksSrc );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vSrcNames", 0, static_cast<int>(article.vSrcNames.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vSrcInits", 0, static_cast<int>(article.vSrcInits.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vSrcPorts", 0, static_cast<int>(article.vSrcPorts.size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("vSrcFracs", 0, static_cast<int>(article.vSrcFracs.size()) );
std::cout << " Pass";
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Tests for appropriate handling of off-nominal file parsing.
////////////////////////////////////////////////////////////////////////////////////////////////////
void UtThermFileParser::testParseErrorHandling()
{
std::cout << "\n ThermFileParser 02: Testing off-nominal file parsing...........";
/// - Default construct an un-initialized test article.
FriendlyThermFileParser article;
/// - Create a dummy TiXmlDocument.
TiXmlDocument doc;
std::string noFile = "no_file.net";
std::string nonXmlFile = "main.cpp";
std::string illFormedXml = "ThermNodes_illformed.xml";
/// @test Exception thrown on attempt to build links before nodes.
CPPUNIT_ASSERT_THROW_MESSAGE("file doesn't exist", article.openFile(doc, noFile), TsParseException);
/// @test Exception thrown on article given a random file that has no thermal link info.
CPPUNIT_ASSERT_THROW_MESSAGE("non-XML file", article.openFile(doc, nonXmlFile), TsParseException);
/// @test Exception thrown on article with ill-formed XML
CPPUNIT_ASSERT_THROW_MESSAGE("ill-formed XML", article.openFile(doc, illFormedXml), TsParseException);
/// @test Exception thrown on article with invalid tags
article.mNodeFile = "ThermNodes_nolist.xml";
CPPUNIT_ASSERT_THROW_MESSAGE("no <list>", article.readNodeFile(), TsParseException);
article.mNodeFile = "ThermLinksCond_base.xml";
CPPUNIT_ASSERT_THROW_MESSAGE("no <node>", article.readNodeFile(), TsParseException);
/// @test Exception NOT thrown on article with empty <name> tag
article.mNodeFile = "ThermNodes_blankname.xml";
CPPUNIT_ASSERT_NO_THROW_MESSAGE("empty <name> tag", article.readNodeFile() );
/// @test Exception NOT thrown on article with no space node (just a warning).
article.mNodeFile = "ThermNodes_nospace.xml";
CPPUNIT_ASSERT_NO_THROW_MESSAGE("no space node", article.readNodeFile() );
/// @test Exception NOT thrown on article with non-numerical info where needed (just warning).
article.mNodeFile = "ThermNodes_nonnumeric.xml";
CPPUNIT_ASSERT_NO_THROW_MESSAGE("non-numerical info", article.readNodeFile() );
/// @test Capacitance link #0 had a string in the <capacitance> tag, so its
/// value should default to 0.0.
CPPUNIT_ASSERT_DOUBLES_EQUAL(0.0, article.vCapCapacitances.at(0), tTol);
/// - Successfully read node-file first before executing remaining tests.
article.mNodeFile = tNodeFile;
article.readNodeFile();
/// @test Exception thrown on article given the wrong file by accident.
article.mCondFile = "ThermLinksRad_base.xml";
CPPUNIT_ASSERT_THROW_MESSAGE("cond-file with no links", article.readCondFile(), TsParseException);
article.mRadFile = "ThermLinksCond_base.xml";
CPPUNIT_ASSERT_THROW_MESSAGE("rad-file with no links", article.readRadFile(), TsParseException);
article.mHtrFile = "ThermLinksPan_base.xml";
CPPUNIT_ASSERT_THROW_MESSAGE("htr-file with no links", article.readHtrFile(), TsParseException);
article.mPanFile = "ThermLinksHtr_base.xml";
CPPUNIT_ASSERT_THROW_MESSAGE("pan-file with no links", article.readPanFile(), TsParseException);
article.mEtcFile = "ThermLinksHtr_base.xml";
CPPUNIT_ASSERT_THROW_MESSAGE("etc-file with no links", article.readEtcFile(), TsParseException);
/// @test Exception thrown on article initialized without config set in default data.
CPPUNIT_ASSERT_THROW_MESSAGE("initialize without config set", article.initialize(tNameError), TsParseException);
/// - Default construct an un-initialized test article.
FriendlyThermFileParser article1;
/// - Set NodeFile only.
article1.mNodeFile = tNodeFile;
/// @test Exception NOT thrown on article with all files null except for the NodeFile.
CPPUNIT_ASSERT_NO_THROW_MESSAGE("all files null except nodes", article1.initialize(tNameError) );
std::cout << " Pass";
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Tests for correct build of Node data from node-file.
////////////////////////////////////////////////////////////////////////////////////////////////////
void UtThermFileParser::testNode()
{
std::cout << "\n ThermFileParser 03: Testing node data read from config-file....";
/// @test Node data from the test case was built correctly.
CPPUNIT_ASSERT_EQUAL_MESSAGE("Node amount", tNumNodes, tArticle->numNodes);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Node name", tNodeName, tArticle->vNodeNames.at(tNode) );
/// @test Node map was constructed correctly.
CPPUNIT_ASSERT_EQUAL( 0, tArticle->getMapLocation(tHtrANode1) );
CPPUNIT_ASSERT_EQUAL( 6, tArticle->getMapLocation(tPanNode0) );
CPPUNIT_ASSERT_EQUAL(21, tArticle->getMapLocation(tSpaceNode) );
/// - Declare an invalid node string.
std::string fakeName = "FAKE_123";
/// @test An invalid node name should return NOT_FOUND.
CPPUNIT_ASSERT_EQUAL(ThermFileParser::NOT_FOUND, tArticle->getMapLocation(fakeName));
std::cout << " Pass";
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Tests for correct build of Capacitance link data from node-file.
////////////////////////////////////////////////////////////////////////////////////////////////////
void UtThermFileParser::testCap()
{
std::cout << "\n ThermFileParser 04: Testing capacitance link, index " << tCap
<< " .........";
/// @test capacitance link data from the test case
CPPUNIT_ASSERT_EQUAL_MESSAGE("Cap amount", tNumLinksCap, tArticle->numLinksCap);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Cap name", tCapName, tArticle->vCapNames.at(tCap) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("Cap Port", tCap, tArticle->vCapPorts.at(tCap));
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Cap capacitance", tCapCapacitance, tArticle->vCapCapacitances.at(tCap), tTol);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Cap temperature", tCapTemperature, tArticle->vCapTemperatures.at(tCap), tTol);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Cap group id", tCapGroup, tArticle->vCapEditGroupIdentifiers.at(tCap) );
std::cout << " Pass";
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Tests for correct build of Conduction link data from cond-file.
////////////////////////////////////////////////////////////////////////////////////////////////////
void UtThermFileParser::testCond()
{
std::cout << "\n ThermFileParser 05: Testing conduction link, index " << tCond
<< " ..........";
/// @test conduction link data from the test case
CPPUNIT_ASSERT_EQUAL_MESSAGE("Conduction amount", tNumLinksCond, tArticle->numLinksCond);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Cond given name", tCondName, tArticle->vCondNames.at(tCond) );
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Cond conductivity", tCondConductivity, tArticle->vCondConductivities.at(tCond), tTol);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Cond Port 0", tArticle->getMapLocation(tCondNode0), tArticle->vCondPorts0.at(tCond));
CPPUNIT_ASSERT_EQUAL_MESSAGE("Cond Port 1", tArticle->getMapLocation(tCondNode1), tArticle->vCondPorts1.at(tCond));
CPPUNIT_ASSERT_EQUAL_MESSAGE("Cond generic name", tCond2Name, tArticle->vCondNames.at(tCond2) );
std::cout << " Pass";
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Tests for correct build of Radiation link data from rad-file.
////////////////////////////////////////////////////////////////////////////////////////////////////
void UtThermFileParser::testRad()
{
std::cout << "\n ThermFileParser 06: Testing radiation link, index " << tRad
<< " ...........";
/// @test radiation link data from the test case
CPPUNIT_ASSERT_EQUAL_MESSAGE("Rad amount", tNumLinksRad, tArticle->numLinksRad);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Rad name", tRadName, tArticle->vRadNames.at(tRad) );
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Rad coefficient", tRadCoefficient, tArticle->vRadCoefficients.at(tRad), tTol);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Rad port 0", tArticle->getMapLocation(tRadNode0), tArticle->vRadPorts0.at(tRad));
CPPUNIT_ASSERT_EQUAL_MESSAGE("Rad port 1", tArticle->getMapLocation(tRadNode1), tArticle->vRadPorts1.at(tRad));
std::cout << " Pass";
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Tests for correct build of Heater data from htr-file.
////////////////////////////////////////////////////////////////////////////////////////////////////
void UtThermFileParser::testHtr()
{
std::cout << "\n ThermFileParser 07: Testing heaters, index "
<< tHtrA << " and "<< tHtrB << " ............";
/// @test heater data from the test case
CPPUNIT_ASSERT_EQUAL_MESSAGE("Htr amount", tNumLinksHtr, tArticle->numLinksHtr);
/// @test heater A name
CPPUNIT_ASSERT_EQUAL_MESSAGE("HtrA name", tHtrAName, tArticle->vHtrNames.at(tHtrA) );
/// @test heater A tuning scalar
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("HtrA scalar", tHtrAScalar, tArticle->vHtrScalars[tHtrA], tTol);
/// @test heater A ports
CPPUNIT_ASSERT_EQUAL_MESSAGE("HtrA ports", tHtrAPorts, static_cast<int>(tArticle->vHtrFracs.at(tHtrA).size()) );
/// @test heater A port numbers
CPPUNIT_ASSERT_EQUAL_MESSAGE("HtrA port0 node", tArticle->getMapLocation(tHtrANode0), tArticle->vHtrPorts.at(tHtrA).at(0) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("HtrA port1 node", tArticle->getMapLocation(tHtrANode1), tArticle->vHtrPorts.at(tHtrA).at(1) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("HtrA port2 node", tArticle->getMapLocation(tHtrANode2), tArticle->vHtrPorts.at(tHtrA).at(2) );
/// @test heater A power-draw fractions
CPPUNIT_ASSERT_EQUAL_MESSAGE("HtrA port0 frac", tHtrAFrac0, tArticle->vHtrFracs.at(tHtrA).at(0) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("HtrA port1 frac", tHtrAFrac1, tArticle->vHtrFracs.at(tHtrA).at(1) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("HtrA port2 frac", tHtrAFrac2, tArticle->vHtrFracs.at(tHtrA).at(2) );
CPPUNIT_ASSERT_THROW_MESSAGE("HtrA port3 frac", tArticle->vHtrFracs.at(tHtrA).at(3), std::out_of_range );
/// @test heater B name
CPPUNIT_ASSERT_EQUAL_MESSAGE("HtrB name", tHtrBName, tArticle->vHtrNames.at(tHtrB) );
/// @test heater B tuning scalar
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("HtrB scalar", tHtrBScalar, tArticle->vHtrScalars[tHtrB], tTol);
/// @test heater B ports
CPPUNIT_ASSERT_EQUAL_MESSAGE("HtrB ports", tHtrBPorts, static_cast<int>(tArticle->vHtrFracs.at(tHtrB).size()) );
/// @test heater B port numbers
CPPUNIT_ASSERT_EQUAL_MESSAGE("HtrB port0 node", tArticle->getMapLocation(tHtrBNode0), tArticle->vHtrPorts.at(tHtrB).at(0) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("HtrB port1 node", tArticle->getMapLocation(tHtrBNode1), tArticle->vHtrPorts.at(tHtrB).at(1) );
/// @test heater B power-draw fractions
CPPUNIT_ASSERT_EQUAL_MESSAGE("HtrB port0 frac", tHtrBFrac0, tArticle->vHtrFracs.at(tHtrB).at(0) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("HtrB port1 frac", tHtrBFrac1, tArticle->vHtrFracs.at(tHtrB).at(1) );
CPPUNIT_ASSERT_THROW_MESSAGE("HtrB port2 frac", tArticle->vHtrFracs.at(tHtrB).at(2), std::out_of_range );
std::cout << " Pass";
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Tests for correct build of ThermalPanel data from pan-file.
////////////////////////////////////////////////////////////////////////////////////////////////////
void UtThermFileParser::testPan()
{
std::cout << "\n ThermFileParser 08: Testing thermal panel, index " << tPan
<< " ............";
/// @test heater data from the test case
CPPUNIT_ASSERT_EQUAL_MESSAGE("Pan amount", tNumLinksPan, tArticle->numLinksPan);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Pan name", tNameError, tArticle->vPanNames.at(2) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("Pan name", tPanName, tArticle->vPanNames.at(tPan) );
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Pan absorptivity", tPanAbsorptivity, tArticle->vPanAbsorptivities.at(tPan), tTol);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Pan area", tPanArea, tArticle->vPanAreas.at(tPan), tTol);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Pan ports", tPanPorts, static_cast<int>(tArticle->vPanFracs.at(tPan).size()) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("Pan port0", tArticle->getMapLocation(tPanNode0), tArticle->vPanPorts.at(tPan).at(0));
CPPUNIT_ASSERT_EQUAL_MESSAGE("Pan port1", tArticle->getMapLocation(tPanNode1), tArticle->vPanPorts.at(tPan).at(1));
std::cout << " Pass";
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Tests for correct build of Potential link data from etc-file.
////////////////////////////////////////////////////////////////////////////////////////////////////
void UtThermFileParser::testPot()
{
std::cout << "\n ThermFileParser 10: Testing potential link, index " << tPot
<< " ...........";
/// @test Potential link data from the test case
CPPUNIT_ASSERT_EQUAL_MESSAGE("Pot amount", tNumLinksPot, tArticle->numLinksPot);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Pot name", tPotName, tArticle->vPotNames.at(tPot) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("Pot node", tArticle->getMapLocation(tPotNode), tArticle->vPotPorts.at(tPot));
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Pot temperature", tPotTemperature, tArticle->vPotTemperatures.at(tPot), tTol);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Pot conductivity", tPotConductivity, tArticle->vPotConductivities.at(tPot) );
std::cout << " Pass";
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Tests for correct build of Source link data from etc-file.
////////////////////////////////////////////////////////////////////////////////////////////////////
void UtThermFileParser::testSrc()
{
std::cout << "\n ThermFileParser 11: Testing source link, index " << tSrc
<< " ..............";
/// @test Sources data from the test case
CPPUNIT_ASSERT_EQUAL_MESSAGE("Src amount", tNumLinksSrc, tArticle->numLinksSrc);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Src port0", tArticle->getMapLocation(tSrcNode0), tArticle->vSrcPorts.at(tSrc).at(0));
CPPUNIT_ASSERT_EQUAL_MESSAGE("Src port1", tArticle->getMapLocation(tSrcNode1), tArticle->vSrcPorts.at(tSrc).at(1));
CPPUNIT_ASSERT_EQUAL_MESSAGE("Src port2", tArticle->getMapLocation(tSrcNode2), tArticle->vSrcPorts.at(tSrc).at(2));
CPPUNIT_ASSERT_EQUAL_MESSAGE("Src port3", tArticle->getMapLocation(tSrcNode3), tArticle->vSrcPorts.at(tSrc).at(3));
CPPUNIT_ASSERT_EQUAL_MESSAGE("Src port0 frac", tSrcFrac0, tArticle->vSrcFracs.at(tSrc).at(0) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("Src port1 frac", tSrcFrac1, tArticle->vSrcFracs.at(tSrc).at(1) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("Src port2 frac", tSrcFrac2, tArticle->vSrcFracs.at(tSrc).at(2) );
CPPUNIT_ASSERT_EQUAL_MESSAGE("Src port3 frac", tSrcFrac3, tArticle->vSrcFracs.at(tSrc).at(3) );
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Src flux", tSrcFlux, tArticle->vSrcInits.at(tSrc), tTol);
CPPUNIT_ASSERT_EQUAL_MESSAGE("Src name", tSrcName, tArticle->vSrcNames.at(tSrc) );
std::cout << " Pass";
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/// @details Tests for correct edit of data by reading of ThermInput file.
////////////////////////////////////////////////////////////////////////////////////////////////////
void UtThermFileParser::testThermInput()
{
std::cout << "\n ThermFileParser 12: Testing read of ThermInput file............";
/// @test Exception NOT thrown on article with null input file.
CPPUNIT_ASSERT_NO_THROW_MESSAGE("null input file", tArticle->readThermInputFile() );
/// - Set input file to invalid path.
tArticle->mThermInputFile = "calabria.xml";
/// @test Read invalid input file.
CPPUNIT_ASSERT_NO_THROW_MESSAGE("invalid input file", tArticle->readThermInputFile() );
/// - Set input file to valid path.
tArticle->mThermInputFile = tThermInputFile;
/// @test Read valid input file.
CPPUNIT_ASSERT_NO_THROW_MESSAGE("read valid input file", tArticle->readThermInputFile() );
/// @test Temperature overwrites.
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Temp override 0", 12.34, tArticle->vCapTemperatures.at(0), tTol);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Temp override 1", 56.78, tArticle->vCapTemperatures.at(1), tTol);
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Temp override 2", 910.0, tArticle->vCapTemperatures.at(2), tTol);
/// @test Do nothing if no override provided.
CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Should maintain original temperature",
tCapTemperature, tArticle->vCapTemperatures.at(tCap), tTol);
std::cout << " Pass";
}
| [
"jason.l.harvey@nasa.gov"
] | jason.l.harvey@nasa.gov |
fdec1fe99af01d7e9050729f9deb1c1d8125932e | b71f6e948c3a74a6cb9713e61cf4035fb3f6cc79 | /CleanSFML/mission.h | 57c4496870f5114924e6ba3dd9f73d4465a86054 | [] | no_license | LowColor/myfight | 14a10dd30b1bbd38c7aa2e9cfcd4758ea077d1d2 | 9337fb09d8a40b97a377747e59264613a7839c81 | refs/heads/master | 2020-03-19T22:09:51.467400 | 2018-06-11T17:43:51 | 2018-06-11T17:43:51 | 136,961,112 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 1,750 | h |
///////////////////////////////////НОМЕР МИССИИ//////////////////////////////////
int getCurrentMission(int x)//ф-ция номера миссия, которая меняет номер миссии, в зависимости от координаты игрока Х (сюда будем передавать эту координату)
{
int mission = 0;
if ((x>0) && (x<400)) { mission = 0; } //знакомим игрока с игрой
if (x>400) { mission = 1; } //игрок на первой миссии
if (x>700) { mission = 2; }//2ой
if (x>2200) { mission = 3; }//и тд
return mission;//ф-ция возвращает номер миссии
}
/////////////////////////////////////ТЕКСТ МИССИИ/////////////////////////////////
std::string getTextMission(int currentMission) {
std::string missionText = "";//текст миссии и его инициализация
switch (currentMission)//принимается номер миссии и в зависимости от него переменной missionText присваивается различный текст
{
case 0: missionText = "\nНачальный этап и \nинструкции к игре"; break;
case 1: missionText = "\nMission 1\n\nВот твоя первая\n миссия, на\n этом уровне \nтебе стоит опасаться\n ... бла-бла-бла ..."; break;
case 2: missionText = "\nMission 2\n Необходимо решить\n логическую задачку,\n чтобы пройти дальше "; break;
case 3: missionText = "\nИ так далее \nи тому подобное....."; break;
}
return missionText;//ф-ция возвращает текст
}; | [
"desir7777@gmail.com"
] | desir7777@gmail.com |
d8e06d05484dba9cd164fa3c6b5f69d43bb0d83e | be3167504c0e32d7708e7d13725c2dbc9232f2cb | /mameppk/src/emu/bus/a2bus/a2estd80col.h | 0d85af21a8d022ab032bb36e75fc4a2f1a04ea8e | [] | no_license | sysfce2/MAME-Plus-Plus-Kaillera | 83b52085dda65045d9f5e8a0b6f3977d75179e78 | 9692743849af5a808e217470abc46e813c9068a5 | refs/heads/master | 2023-08-10T06:12:47.451039 | 2016-08-01T09:44:21 | 2016-08-01T09:44:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,439 | h | // license:BSD-3-Clause
// copyright-holders:R. Belmont
/*********************************************************************
a2estd80col.c
Apple IIe Standard 80 Column Card
*********************************************************************/
#ifndef __A2EAUX_STD80COL__
#define __A2EAUX_STD80COL__
#include "emu.h"
#include "a2eauxslot.h"
//**************************************************************************
// TYPE DEFINITIONS
//**************************************************************************
class a2eaux_std80col_device:
public device_t,
public device_a2eauxslot_card_interface
{
public:
// construction/destruction
a2eaux_std80col_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock);
a2eaux_std80col_device(const machine_config &mconfig, device_type type, const char *name, const char *tag, device_t *owner, UINT32 clock, const char *shortname, const char *source);
protected:
virtual void device_start();
virtual void device_reset();
virtual UINT8 read_auxram(UINT16 offset);
virtual void write_auxram(UINT16 offset, UINT8 data);
virtual UINT8 *get_vram_ptr();
virtual UINT8 *get_auxbank_ptr();
virtual bool allow_dhr() { return false; } // we don't allow DHR
private:
UINT8 m_ram[2*1024];
};
// device type definition
extern const device_type A2EAUX_STD80COL;
#endif /* __A2EAUX_STD80COL__ */
| [
"mameppk@199a702f-54f1-4ac0-8451-560dfe28270b"
] | mameppk@199a702f-54f1-4ac0-8451-560dfe28270b |
85bc6e3e72cad629b2cdcc65e17293a9f5072cf3 | 320660851dc9a8c7a230db6d5388ba0d737572f6 | /win32/include/pthread.h | 0172cb1a3083722319c6b64845fabe30e96629ed | [] | no_license | Vadiza/sage-3.5b | 0e9fb033324c4efd86aa0801c8ab2bd8d3a62ff9 | 5e2af1d1a9838933fe0e60673d74a54408fdb61e | refs/heads/master | 2020-04-09T15:16:17.571400 | 2014-05-09T15:27:17 | 2014-05-09T15:27:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 44,226 | h | /* This is an implementation of the threads API of POSIX 1003.1-2001.
*
* --------------------------------------------------------------------------
*
* Pthreads-win32 - POSIX Threads Library for Win32
* Copyright(C) 1998 John E. Bossom
* Copyright(C) 1999,2005 Pthreads-win32 contributors
*
* Contact Email: rpj@callisto.canberra.edu.au
*
* The current list of contributors is contained
* in the file CONTRIBUTORS included with the source
* code distribution. The list can also be seen at the
* following World Wide Web location:
* http://sources.redhat.com/pthreads-win32/contributors.html
*
* 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 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 in the file COPYING.LIB;
* if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
#if !defined( PTHREAD_H )
#define PTHREAD_H
/*
* See the README file for an explanation of the pthreads-win32 version
* numbering scheme and how the DLL is named etc.
*/
#define PTW32_VERSION 2,7,0,0
#define PTW32_VERSION_STRING "2, 7, 0, 0\0"
/* There are three implementations of cancel cleanup.
* Note that pthread.h is included in both application
* compilation units and also internally for the library.
* The code here and within the library aims to work
* for all reasonable combinations of environments.
*
* The three implementations are:
*
* WIN32 SEH
* C
* C++
*
* Please note that exiting a push/pop block via
* "return", "exit", "break", or "continue" will
* lead to different behaviour amongst applications
* depending upon whether the library was built
* using SEH, C++, or C. For example, a library built
* with SEH will call the cleanup routine, while both
* C++ and C built versions will not.
*/
/*
* Define defaults for cleanup code.
* Note: Unless the build explicitly defines one of the following, then
* we default to standard C style cleanup. This style uses setjmp/longjmp
* in the cancelation and thread exit implementations and therefore won't
* do stack unwinding if linked to applications that have it (e.g.
* C++ apps). This is currently consistent with most/all commercial Unix
* POSIX threads implementations.
*/
#if !defined( __CLEANUP_SEH ) && !defined( __CLEANUP_CXX ) && !defined( __CLEANUP_C )
# define __CLEANUP_C
#endif
#if defined( __CLEANUP_SEH ) && ( !defined( _MSC_VER ) && !defined(PTW32_RC_MSC))
#error ERROR [__FILE__, line __LINE__]: SEH is not supported for this compiler.
#endif
/*
* Stop here if we are being included by the resource compiler.
*/
#ifndef RC_INVOKED
#undef PTW32_LEVEL
#if defined(_POSIX_SOURCE)
#define PTW32_LEVEL 0
/* Early POSIX */
#endif
#if defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199309
#undef PTW32_LEVEL
#define PTW32_LEVEL 1
/* Include 1b, 1c and 1d */
#endif
#if defined(INCLUDE_NP)
#undef PTW32_LEVEL
#define PTW32_LEVEL 2
/* Include Non-Portable extensions */
#endif
#define PTW32_LEVEL_MAX 3
#if !defined(PTW32_LEVEL)
#define PTW32_LEVEL PTW32_LEVEL_MAX
/* Include everything */
#endif
#ifdef _UWIN
# define HAVE_STRUCT_TIMESPEC 1
# define HAVE_SIGNAL_H 1
# undef HAVE_CONFIG_H
# pragma comment(lib, "pthread")
#endif
/*
* -------------------------------------------------------------
*
*
* Module: pthread.h
*
* Purpose:
* Provides an implementation of PThreads based upon the
* standard:
*
* POSIX 1003.1-2001
* and
* The Single Unix Specification version 3
*
* (these two are equivalent)
*
* in order to enhance code portability between Windows,
* various commercial Unix implementations, and Linux.
*
* See the ANNOUNCE file for a full list of conforming
* routines and defined constants, and a list of missing
* routines and constants not defined in this implementation.
*
* Authors:
* There have been many contributors to this library.
* The initial implementation was contributed by
* John Bossom, and several others have provided major
* sections or revisions of parts of the implementation.
* Often significant effort has been contributed to
* find and fix important bugs and other problems to
* improve the reliability of the library, which sometimes
* is not reflected in the amount of code which changed as
* result.
* As much as possible, the contributors are acknowledged
* in the ChangeLog file in the source code distribution
* where their changes are noted in detail.
*
* Contributors are listed in the CONTRIBUTORS file.
*
* As usual, all bouquets go to the contributors, and all
* brickbats go to the project maintainer.
*
* Maintainer:
* The code base for this project is coordinated and
* eventually pre-tested, packaged, and made available by
*
* Ross Johnson <rpj@callisto.canberra.edu.au>
*
* QA Testers:
* Ultimately, the library is tested in the real world by
* a host of competent and demanding scientists and
* engineers who report bugs and/or provide solutions
* which are then fixed or incorporated into subsequent
* versions of the library. Each time a bug is fixed, a
* test case is written to prove the fix and ensure
* that later changes to the code don't reintroduce the
* same error. The number of test cases is slowly growing
* and therefore so is the code reliability.
*
* Compliance:
* See the file ANNOUNCE for the list of implemented
* and not-implemented routines and defined options.
* Of course, these are all defined is this file as well.
*
* Web site:
* The source code and other information about this library
* are available from
*
* http://sources.redhat.com/pthreads-win32/
*
* -------------------------------------------------------------
*/
/* Try to avoid including windows.h */
#if defined(__MINGW32__) && defined(__cplusplus)
#define PTW32_INCLUDE_WINDOWS_H
#endif
#ifdef PTW32_INCLUDE_WINDOWS_H
#include <windows.h>
#endif
#if defined(_MSC_VER) && _MSC_VER < 1300 || defined(__DMC__)
/*
* VC++6.0 or early compiler's header has no DWORD_PTR type.
*/
typedef unsigned long DWORD_PTR;
#endif
/*
* -----------------
* autoconf switches
* -----------------
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif /* HAVE_CONFIG_H */
#ifndef NEED_FTIME
#include <time.h>
#else /* NEED_FTIME */
/* use native WIN32 time API */
#endif /* NEED_FTIME */
#if HAVE_SIGNAL_H
#include <signal.h>
#endif /* HAVE_SIGNAL_H */
#include <setjmp.h>
#include <limits.h>
/*
* Boolean values to make us independent of system includes.
*/
enum {
PTW32_FALSE = 0,
PTW32_TRUE = (! PTW32_FALSE)
};
/*
* This is a duplicate of what is in the autoconf config.h,
* which is only used when building the pthread-win32 libraries.
*/
#ifndef PTW32_CONFIG_H
# if defined(WINCE)
# define NEED_ERRNO
# define NEED_SEM
# endif
# if defined(_UWIN) || defined(__MINGW32__)
# define HAVE_MODE_T
# endif
#endif
/*
*
*/
#if PTW32_LEVEL >= PTW32_LEVEL_MAX
#ifdef NEED_ERRNO
#include "need_errno.h"
#else
#include <errno.h>
#endif
#endif /* PTW32_LEVEL >= PTW32_LEVEL_MAX */
/*
* Several systems don't define some error numbers.
*/
#ifndef ENOTSUP
# define ENOTSUP 48 /* This is the value in Solaris. */
#endif
#ifndef ETIMEDOUT
# define ETIMEDOUT 10060 /* This is the value in winsock.h. */
#endif
#ifndef ENOSYS
# define ENOSYS 140 /* Semi-arbitrary value */
#endif
#ifndef EDEADLK
# ifdef EDEADLOCK
# define EDEADLK EDEADLOCK
# else
# define EDEADLK 36 /* This is the value in MSVC. */
# endif
#endif
#include <sched.h>
/*
* To avoid including windows.h we define only those things that we
* actually need from it.
*/
#ifndef PTW32_INCLUDE_WINDOWS_H
#ifndef HANDLE
# define PTW32__HANDLE_DEF
# define HANDLE void *
#endif
#ifndef DWORD
# define PTW32__DWORD_DEF
# define DWORD unsigned long
#endif
#endif
#ifndef HAVE_STRUCT_TIMESPEC
#define HAVE_STRUCT_TIMESPEC 1
struct timespec {
long tv_sec;
long tv_nsec;
};
#endif /* HAVE_STRUCT_TIMESPEC */
#ifndef SIG_BLOCK
#define SIG_BLOCK 0
#endif /* SIG_BLOCK */
#ifndef SIG_UNBLOCK
#define SIG_UNBLOCK 1
#endif /* SIG_UNBLOCK */
#ifndef SIG_SETMASK
#define SIG_SETMASK 2
#endif /* SIG_SETMASK */
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
/*
* -------------------------------------------------------------
*
* POSIX 1003.1-2001 Options
* =========================
*
* Options are normally set in <unistd.h>, which is not provided
* with pthreads-win32.
*
* For conformance with the Single Unix Specification (version 3), all of the
* options below are defined, and have a value of either -1 (not supported)
* or 200112L (supported).
*
* These options can neither be left undefined nor have a value of 0, because
* either indicates that sysconf(), which is not implemented, may be used at
* runtime to check the status of the option.
*
* _POSIX_THREADS (== 200112L)
* If == 200112L, you can use threads
*
* _POSIX_THREAD_ATTR_STACKSIZE (== 200112L)
* If == 200112L, you can control the size of a thread's
* stack
* pthread_attr_getstacksize
* pthread_attr_setstacksize
*
* _POSIX_THREAD_ATTR_STACKADDR (== -1)
* If == 200112L, you can allocate and control a thread's
* stack. If not supported, the following functions
* will return ENOSYS, indicating they are not
* supported:
* pthread_attr_getstackaddr
* pthread_attr_setstackaddr
*
* _POSIX_THREAD_PRIORITY_SCHEDULING (== -1)
* If == 200112L, you can use realtime scheduling.
* This option indicates that the behaviour of some
* implemented functions conforms to the additional TPS
* requirements in the standard. E.g. rwlocks favour
* writers over readers when threads have equal priority.
*
* _POSIX_THREAD_PRIO_INHERIT (== -1)
* If == 200112L, you can create priority inheritance
* mutexes.
* pthread_mutexattr_getprotocol +
* pthread_mutexattr_setprotocol +
*
* _POSIX_THREAD_PRIO_PROTECT (== -1)
* If == 200112L, you can create priority ceiling mutexes
* Indicates the availability of:
* pthread_mutex_getprioceiling
* pthread_mutex_setprioceiling
* pthread_mutexattr_getprioceiling
* pthread_mutexattr_getprotocol +
* pthread_mutexattr_setprioceiling
* pthread_mutexattr_setprotocol +
*
* _POSIX_THREAD_PROCESS_SHARED (== -1)
* If set, you can create mutexes and condition
* variables that can be shared with another
* process.If set, indicates the availability
* of:
* pthread_mutexattr_getpshared
* pthread_mutexattr_setpshared
* pthread_condattr_getpshared
* pthread_condattr_setpshared
*
* _POSIX_THREAD_SAFE_FUNCTIONS (== 200112L)
* If == 200112L you can use the special *_r library
* functions that provide thread-safe behaviour
*
* _POSIX_READER_WRITER_LOCKS (== 200112L)
* If == 200112L, you can use read/write locks
*
* _POSIX_SPIN_LOCKS (== 200112L)
* If == 200112L, you can use spin locks
*
* _POSIX_BARRIERS (== 200112L)
* If == 200112L, you can use barriers
*
* + These functions provide both 'inherit' and/or
* 'protect' protocol, based upon these macro
* settings.
*
* -------------------------------------------------------------
*/
/*
* POSIX Options
*/
#undef _POSIX_THREADS
#define _POSIX_THREADS 200112L
#undef _POSIX_READER_WRITER_LOCKS
#define _POSIX_READER_WRITER_LOCKS 200112L
#undef _POSIX_SPIN_LOCKS
#define _POSIX_SPIN_LOCKS 200112L
#undef _POSIX_BARRIERS
#define _POSIX_BARRIERS 200112L
#undef _POSIX_THREAD_SAFE_FUNCTIONS
#define _POSIX_THREAD_SAFE_FUNCTIONS 200112L
#undef _POSIX_THREAD_ATTR_STACKSIZE
#define _POSIX_THREAD_ATTR_STACKSIZE 200112L
/*
* The following options are not supported
*/
#undef _POSIX_THREAD_ATTR_STACKADDR
#define _POSIX_THREAD_ATTR_STACKADDR -1
#undef _POSIX_THREAD_PRIO_INHERIT
#define _POSIX_THREAD_PRIO_INHERIT -1
#undef _POSIX_THREAD_PRIO_PROTECT
#define _POSIX_THREAD_PRIO_PROTECT -1
/* TPS is not fully supported. */
#undef _POSIX_THREAD_PRIORITY_SCHEDULING
#define _POSIX_THREAD_PRIORITY_SCHEDULING -1
#undef _POSIX_THREAD_PROCESS_SHARED
#define _POSIX_THREAD_PROCESS_SHARED -1
/*
* POSIX 1003.1-2001 Limits
* ===========================
*
* These limits are normally set in <limits.h>, which is not provided with
* pthreads-win32.
*
* PTHREAD_DESTRUCTOR_ITERATIONS
* Maximum number of attempts to destroy
* a thread's thread-specific data on
* termination (must be at least 4)
*
* PTHREAD_KEYS_MAX
* Maximum number of thread-specific data keys
* available per process (must be at least 128)
*
* PTHREAD_STACK_MIN
* Minimum supported stack size for a thread
*
* PTHREAD_THREADS_MAX
* Maximum number of threads supported per
* process (must be at least 64).
*
* SEM_NSEMS_MAX
* The maximum number of semaphores a process can have.
* (must be at least 256)
*
* SEM_VALUE_MAX
* The maximum value a semaphore can have.
* (must be at least 32767)
*
*/
#undef _POSIX_THREAD_DESTRUCTOR_ITERATIONS
#define _POSIX_THREAD_DESTRUCTOR_ITERATIONS 4
#undef PTHREAD_DESTRUCTOR_ITERATIONS
#define PTHREAD_DESTRUCTOR_ITERATIONS _POSIX_THREAD_DESTRUCTOR_ITERATIONS
#undef _POSIX_THREAD_KEYS_MAX
#define _POSIX_THREAD_KEYS_MAX 128
#undef PTHREAD_KEYS_MAX
#define PTHREAD_KEYS_MAX _POSIX_THREAD_KEYS_MAX
#undef PTHREAD_STACK_MIN
#define PTHREAD_STACK_MIN 0
#undef _POSIX_THREAD_THREADS_MAX
#define _POSIX_THREAD_THREADS_MAX 64
/* Arbitrary value */
#undef PTHREAD_THREADS_MAX
#define PTHREAD_THREADS_MAX 2019
#undef _POSIX_SEM_NSEMS_MAX
#define _POSIX_SEM_NSEMS_MAX 256
/* Arbitrary value */
#undef SEM_NSEMS_MAX
#define SEM_NSEMS_MAX 1024
#undef _POSIX_SEM_VALUE_MAX
#define _POSIX_SEM_VALUE_MAX 32767
#undef SEM_VALUE_MAX
#define SEM_VALUE_MAX INT_MAX
#if __GNUC__ && ! defined (__declspec)
# error Please upgrade your GNU compiler to one that supports __declspec.
#endif
/*
* When building the DLL code, you should define PTW32_BUILD so that
* the variables/functions are exported correctly. When using the DLL,
* do NOT define PTW32_BUILD, and then the variables/functions will
* be imported correctly.
*/
#ifndef PTW32_STATIC_LIB
# ifdef PTW32_BUILD
# define PTW32_DLLPORT __declspec (dllexport)
# else
# define PTW32_DLLPORT __declspec (dllimport)
# endif
#else
# define PTW32_DLLPORT
#endif
/*
* The Open Watcom C/C++ compiler uses a non-standard calling convention
* that passes function args in registers unless __cdecl is explicitly specified
* in exposed function prototypes.
*
* We force all calls to cdecl even though this could slow Watcom code down
* slightly. If you know that the Watcom compiler will be used to build both
* the DLL and application, then you can probably define this as a null string.
* Remember that pthread.h (this file) is used for both the DLL and application builds.
*/
#define PTW32_CDECL __cdecl
#if defined(_UWIN) && PTW32_LEVEL >= PTW32_LEVEL_MAX
# include <sys/types.h>
#else
/*
* Generic handle type - intended to extend uniqueness beyond
* that available with a simple pointer. It should scale for either
* IA-32 or IA-64.
*/
typedef struct {
void * p; /* Pointer to actual object */
unsigned int x; /* Extra information - reuse count etc */
} ptw32_handle_t;
typedef ptw32_handle_t pthread_t;
typedef struct pthread_attr_t_ * pthread_attr_t;
typedef struct pthread_once_t_ pthread_once_t;
typedef struct pthread_key_t_ * pthread_key_t;
typedef struct pthread_mutex_t_ * pthread_mutex_t;
typedef struct pthread_mutexattr_t_ * pthread_mutexattr_t;
typedef struct pthread_cond_t_ * pthread_cond_t;
typedef struct pthread_condattr_t_ * pthread_condattr_t;
#endif
typedef struct pthread_rwlock_t_ * pthread_rwlock_t;
typedef struct pthread_rwlockattr_t_ * pthread_rwlockattr_t;
typedef struct pthread_spinlock_t_ * pthread_spinlock_t;
typedef struct pthread_barrier_t_ * pthread_barrier_t;
typedef struct pthread_barrierattr_t_ * pthread_barrierattr_t;
/*
* ====================
* ====================
* POSIX Threads
* ====================
* ====================
*/
enum {
/*
* pthread_attr_{get,set}detachstate
*/
PTHREAD_CREATE_JOINABLE = 0, /* Default */
PTHREAD_CREATE_DETACHED = 1,
/*
* pthread_attr_{get,set}inheritsched
*/
PTHREAD_INHERIT_SCHED = 0,
PTHREAD_EXPLICIT_SCHED = 1, /* Default */
/*
* pthread_{get,set}scope
*/
PTHREAD_SCOPE_PROCESS = 0,
PTHREAD_SCOPE_SYSTEM = 1, /* Default */
/*
* pthread_setcancelstate paramters
*/
PTHREAD_CANCEL_ENABLE = 0, /* Default */
PTHREAD_CANCEL_DISABLE = 1,
/*
* pthread_setcanceltype parameters
*/
PTHREAD_CANCEL_ASYNCHRONOUS = 0,
PTHREAD_CANCEL_DEFERRED = 1, /* Default */
/*
* pthread_mutexattr_{get,set}pshared
* pthread_condattr_{get,set}pshared
*/
PTHREAD_PROCESS_PRIVATE = 0,
PTHREAD_PROCESS_SHARED = 1,
/*
* pthread_barrier_wait
*/
PTHREAD_BARRIER_SERIAL_THREAD = -1
};
/*
* ====================
* ====================
* Cancelation
* ====================
* ====================
*/
#define PTHREAD_CANCELED ((void *) -1)
/*
* ====================
* ====================
* Once Key
* ====================
* ====================
*/
#define PTHREAD_ONCE_INIT { PTW32_FALSE, 0, 0, 0}
struct pthread_once_t_
{
int done; /* indicates if user function has been executed */
void * lock;
int reserved1;
int reserved2;
};
/*
* ====================
* ====================
* Object initialisers
* ====================
* ====================
*/
#define PTHREAD_MUTEX_INITIALIZER ((pthread_mutex_t) -1)
#define PTHREAD_RECURSIVE_MUTEX_INITIALIZER ((pthread_mutex_t) -2)
#define PTHREAD_ERRORCHECK_MUTEX_INITIALIZER ((pthread_mutex_t) -3)
/*
* Compatibility with LinuxThreads
*/
#define PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP PTHREAD_RECURSIVE_MUTEX_INITIALIZER
#define PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP PTHREAD_ERRORCHECK_MUTEX_INITIALIZER
#define PTHREAD_COND_INITIALIZER ((pthread_cond_t) -1)
#define PTHREAD_RWLOCK_INITIALIZER ((pthread_rwlock_t) -1)
#define PTHREAD_SPINLOCK_INITIALIZER ((pthread_spinlock_t) -1)
/*
* Mutex types.
*/
enum
{
/* Compatibility with LinuxThreads */
PTHREAD_MUTEX_FAST_NP,
PTHREAD_MUTEX_RECURSIVE_NP,
PTHREAD_MUTEX_ERRORCHECK_NP,
PTHREAD_MUTEX_TIMED_NP = PTHREAD_MUTEX_FAST_NP,
PTHREAD_MUTEX_ADAPTIVE_NP = PTHREAD_MUTEX_FAST_NP,
/* For compatibility with POSIX */
PTHREAD_MUTEX_NORMAL = PTHREAD_MUTEX_FAST_NP,
PTHREAD_MUTEX_RECURSIVE = PTHREAD_MUTEX_RECURSIVE_NP,
PTHREAD_MUTEX_ERRORCHECK = PTHREAD_MUTEX_ERRORCHECK_NP,
PTHREAD_MUTEX_DEFAULT = PTHREAD_MUTEX_NORMAL
};
typedef struct ptw32_cleanup_t ptw32_cleanup_t;
#if defined(_MSC_VER)
/* Disable MSVC 'anachronism used' warning */
#pragma warning( disable : 4229 )
#endif
typedef void (* PTW32_CDECL ptw32_cleanup_callback_t)(void *);
#if defined(_MSC_VER)
#pragma warning( default : 4229 )
#endif
struct ptw32_cleanup_t
{
ptw32_cleanup_callback_t routine;
void *arg;
struct ptw32_cleanup_t *prev;
};
#ifdef __CLEANUP_SEH
/*
* WIN32 SEH version of cancel cleanup.
*/
#define pthread_cleanup_push( _rout, _arg ) \
{ \
ptw32_cleanup_t _cleanup; \
\
_cleanup.routine = (ptw32_cleanup_callback_t)(_rout); \
_cleanup.arg = (_arg); \
__try \
{ \
#define pthread_cleanup_pop( _execute ) \
} \
__finally \
{ \
if( _execute || AbnormalTermination()) \
{ \
(*(_cleanup.routine))( _cleanup.arg ); \
} \
} \
}
#else /* __CLEANUP_SEH */
#ifdef __CLEANUP_C
/*
* C implementation of PThreads cancel cleanup
*/
#define pthread_cleanup_push( _rout, _arg ) \
{ \
ptw32_cleanup_t _cleanup; \
\
ptw32_push_cleanup( &_cleanup, (ptw32_cleanup_callback_t) (_rout), (_arg) ); \
#define pthread_cleanup_pop( _execute ) \
(void) ptw32_pop_cleanup( _execute ); \
}
#else /* __CLEANUP_C */
#ifdef __CLEANUP_CXX
/*
* C++ version of cancel cleanup.
* - John E. Bossom.
*/
class PThreadCleanup {
/*
* PThreadCleanup
*
* Purpose
* This class is a C++ helper class that is
* used to implement pthread_cleanup_push/
* pthread_cleanup_pop.
* The destructor of this class automatically
* pops the pushed cleanup routine regardless
* of how the code exits the scope
* (i.e. such as by an exception)
*/
ptw32_cleanup_callback_t cleanUpRout;
void * obj;
int executeIt;
public:
PThreadCleanup() :
cleanUpRout( 0 ),
obj( 0 ),
executeIt( 0 )
/*
* No cleanup performed
*/
{
}
PThreadCleanup(
ptw32_cleanup_callback_t routine,
void * arg ) :
cleanUpRout( routine ),
obj( arg ),
executeIt( 1 )
/*
* Registers a cleanup routine for 'arg'
*/
{
}
~PThreadCleanup()
{
if ( executeIt && ((void *) cleanUpRout != (void *) 0) )
{
(void) (*cleanUpRout)( obj );
}
}
void execute( int exec )
{
executeIt = exec;
}
};
/*
* C++ implementation of PThreads cancel cleanup;
* This implementation takes advantage of a helper
* class who's destructor automatically calls the
* cleanup routine if we exit our scope weirdly
*/
#define pthread_cleanup_push( _rout, _arg ) \
{ \
PThreadCleanup cleanup((ptw32_cleanup_callback_t)(_rout), \
(void *) (_arg) );
#define pthread_cleanup_pop( _execute ) \
cleanup.execute( _execute ); \
}
#else
#error ERROR [__FILE__, line __LINE__]: Cleanup type undefined.
#endif /* __CLEANUP_CXX */
#endif /* __CLEANUP_C */
#endif /* __CLEANUP_SEH */
/*
* ===============
* ===============
* Methods
* ===============
* ===============
*/
/*
* PThread Attribute Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_attr_init (pthread_attr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_destroy (pthread_attr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_getdetachstate (const pthread_attr_t * attr,
int *detachstate);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_getstackaddr (const pthread_attr_t * attr,
void **stackaddr);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_getstacksize (const pthread_attr_t * attr,
size_t * stacksize);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_setdetachstate (pthread_attr_t * attr,
int detachstate);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_setstackaddr (pthread_attr_t * attr,
void *stackaddr);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_setstacksize (pthread_attr_t * attr,
size_t stacksize);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_getschedparam (const pthread_attr_t *attr,
struct sched_param *param);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_setschedparam (pthread_attr_t *attr,
const struct sched_param *param);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_setschedpolicy (pthread_attr_t *,
int);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_getschedpolicy (pthread_attr_t *,
int *);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_setinheritsched(pthread_attr_t * attr,
int inheritsched);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_getinheritsched(pthread_attr_t * attr,
int * inheritsched);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_setscope (pthread_attr_t *,
int);
PTW32_DLLPORT int PTW32_CDECL pthread_attr_getscope (const pthread_attr_t *,
int *);
/*
* PThread Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_create (pthread_t * tid,
const pthread_attr_t * attr,
void *(*start) (void *),
void *arg);
PTW32_DLLPORT int PTW32_CDECL pthread_detach (pthread_t tid);
PTW32_DLLPORT int PTW32_CDECL pthread_equal (pthread_t t1,
pthread_t t2);
PTW32_DLLPORT void PTW32_CDECL pthread_exit (void *value_ptr);
PTW32_DLLPORT int PTW32_CDECL pthread_join (pthread_t thread,
void **value_ptr);
PTW32_DLLPORT pthread_t PTW32_CDECL pthread_self (void);
PTW32_DLLPORT int PTW32_CDECL pthread_cancel (pthread_t thread);
PTW32_DLLPORT int PTW32_CDECL pthread_setcancelstate (int state,
int *oldstate);
PTW32_DLLPORT int PTW32_CDECL pthread_setcanceltype (int type,
int *oldtype);
PTW32_DLLPORT void PTW32_CDECL pthread_testcancel (void);
PTW32_DLLPORT int PTW32_CDECL pthread_once (pthread_once_t * once_control,
void (*init_routine) (void));
#if PTW32_LEVEL >= PTW32_LEVEL_MAX
PTW32_DLLPORT ptw32_cleanup_t * PTW32_CDECL ptw32_pop_cleanup (int execute);
PTW32_DLLPORT void PTW32_CDECL ptw32_push_cleanup (ptw32_cleanup_t * cleanup,
void (*routine) (void *),
void *arg);
#endif /* PTW32_LEVEL >= PTW32_LEVEL_MAX */
/*
* Thread Specific Data Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_key_create (pthread_key_t * key,
void (*destructor) (void *));
PTW32_DLLPORT int PTW32_CDECL pthread_key_delete (pthread_key_t key);
PTW32_DLLPORT int PTW32_CDECL pthread_setspecific (pthread_key_t key,
const void *value);
PTW32_DLLPORT void * PTW32_CDECL pthread_getspecific (pthread_key_t key);
/*
* Mutex Attribute Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_init (pthread_mutexattr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_destroy (pthread_mutexattr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_getpshared (const pthread_mutexattr_t
* attr,
int *pshared);
PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_setpshared (pthread_mutexattr_t * attr,
int pshared);
PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_settype (pthread_mutexattr_t * attr, int kind);
PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_gettype (pthread_mutexattr_t * attr, int *kind);
/*
* Barrier Attribute Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_barrierattr_init (pthread_barrierattr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_barrierattr_destroy (pthread_barrierattr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_barrierattr_getpshared (const pthread_barrierattr_t
* attr,
int *pshared);
PTW32_DLLPORT int PTW32_CDECL pthread_barrierattr_setpshared (pthread_barrierattr_t * attr,
int pshared);
/*
* Mutex Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_mutex_init (pthread_mutex_t * mutex,
const pthread_mutexattr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_mutex_destroy (pthread_mutex_t * mutex);
PTW32_DLLPORT int PTW32_CDECL pthread_mutex_lock (pthread_mutex_t * mutex);
PTW32_DLLPORT int PTW32_CDECL pthread_mutex_timedlock(pthread_mutex_t *mutex,
const struct timespec *abstime);
PTW32_DLLPORT int PTW32_CDECL pthread_mutex_trylock (pthread_mutex_t * mutex);
PTW32_DLLPORT int PTW32_CDECL pthread_mutex_unlock (pthread_mutex_t * mutex);
/*
* Spinlock Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_spin_init (pthread_spinlock_t * lock, int pshared);
PTW32_DLLPORT int PTW32_CDECL pthread_spin_destroy (pthread_spinlock_t * lock);
PTW32_DLLPORT int PTW32_CDECL pthread_spin_lock (pthread_spinlock_t * lock);
PTW32_DLLPORT int PTW32_CDECL pthread_spin_trylock (pthread_spinlock_t * lock);
PTW32_DLLPORT int PTW32_CDECL pthread_spin_unlock (pthread_spinlock_t * lock);
/*
* Barrier Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_barrier_init (pthread_barrier_t * barrier,
const pthread_barrierattr_t * attr,
unsigned int count);
PTW32_DLLPORT int PTW32_CDECL pthread_barrier_destroy (pthread_barrier_t * barrier);
PTW32_DLLPORT int PTW32_CDECL pthread_barrier_wait (pthread_barrier_t * barrier);
/*
* Condition Variable Attribute Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_condattr_init (pthread_condattr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_condattr_destroy (pthread_condattr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_condattr_getpshared (const pthread_condattr_t * attr,
int *pshared);
PTW32_DLLPORT int PTW32_CDECL pthread_condattr_setpshared (pthread_condattr_t * attr,
int pshared);
/*
* Condition Variable Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_cond_init (pthread_cond_t * cond,
const pthread_condattr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_cond_destroy (pthread_cond_t * cond);
PTW32_DLLPORT int PTW32_CDECL pthread_cond_wait (pthread_cond_t * cond,
pthread_mutex_t * mutex);
PTW32_DLLPORT int PTW32_CDECL pthread_cond_timedwait (pthread_cond_t * cond,
pthread_mutex_t * mutex,
const struct timespec *abstime);
PTW32_DLLPORT int PTW32_CDECL pthread_cond_signal (pthread_cond_t * cond);
PTW32_DLLPORT int PTW32_CDECL pthread_cond_broadcast (pthread_cond_t * cond);
/*
* Scheduling
*/
PTW32_DLLPORT int PTW32_CDECL pthread_setschedparam (pthread_t thread,
int policy,
const struct sched_param *param);
PTW32_DLLPORT int PTW32_CDECL pthread_getschedparam (pthread_t thread,
int *policy,
struct sched_param *param);
PTW32_DLLPORT int PTW32_CDECL pthread_setconcurrency (int);
PTW32_DLLPORT int PTW32_CDECL pthread_getconcurrency (void);
/*
* Read-Write Lock Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_init(pthread_rwlock_t *lock,
const pthread_rwlockattr_t *attr);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_destroy(pthread_rwlock_t *lock);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_tryrdlock(pthread_rwlock_t *);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_trywrlock(pthread_rwlock_t *);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_rdlock(pthread_rwlock_t *lock);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_timedrdlock(pthread_rwlock_t *lock,
const struct timespec *abstime);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_wrlock(pthread_rwlock_t *lock);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_timedwrlock(pthread_rwlock_t *lock,
const struct timespec *abstime);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlock_unlock(pthread_rwlock_t *lock);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlockattr_init (pthread_rwlockattr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlockattr_destroy (pthread_rwlockattr_t * attr);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlockattr_getpshared (const pthread_rwlockattr_t * attr,
int *pshared);
PTW32_DLLPORT int PTW32_CDECL pthread_rwlockattr_setpshared (pthread_rwlockattr_t * attr,
int pshared);
#if PTW32_LEVEL >= PTW32_LEVEL_MAX - 1
/*
* Signal Functions. Should be defined in <signal.h> but MSVC and MinGW32
* already have signal.h that don't define these.
*/
PTW32_DLLPORT int PTW32_CDECL pthread_kill(pthread_t thread, int sig);
/*
* Non-portable functions
*/
/*
* Compatibility with Linux.
*/
PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_setkind_np(pthread_mutexattr_t * attr,
int kind);
PTW32_DLLPORT int PTW32_CDECL pthread_mutexattr_getkind_np(pthread_mutexattr_t * attr,
int *kind);
/*
* Possibly supported by other POSIX threads implementations
*/
PTW32_DLLPORT int PTW32_CDECL pthread_delay_np (struct timespec * interval);
PTW32_DLLPORT int PTW32_CDECL pthread_num_processors_np(void);
/*
* Useful if an application wants to statically link
* the lib rather than load the DLL at run-time.
*/
PTW32_DLLPORT int PTW32_CDECL pthread_win32_process_attach_np(void);
PTW32_DLLPORT int PTW32_CDECL pthread_win32_process_detach_np(void);
PTW32_DLLPORT int PTW32_CDECL pthread_win32_thread_attach_np(void);
PTW32_DLLPORT int PTW32_CDECL pthread_win32_thread_detach_np(void);
/*
* Features that are auto-detected at load/run time.
*/
PTW32_DLLPORT int PTW32_CDECL pthread_win32_test_features_np(int);
enum ptw32_features {
PTW32_SYSTEM_INTERLOCKED_COMPARE_EXCHANGE = 0x0001, /* System provides it. */
PTW32_ALERTABLE_ASYNC_CANCEL = 0x0002 /* Can cancel blocked threads. */
};
/*
* Register a system time change with the library.
* Causes the library to perform various functions
* in response to the change. Should be called whenever
* the application's top level window receives a
* WM_TIMECHANGE message. It can be passed directly to
* pthread_create() as a new thread if desired.
*/
PTW32_DLLPORT void * PTW32_CDECL pthread_timechange_handler_np(void *);
#endif /*PTW32_LEVEL >= PTW32_LEVEL_MAX - 1 */
#if PTW32_LEVEL >= PTW32_LEVEL_MAX
/*
* Returns the Win32 HANDLE for the POSIX thread.
*/
PTW32_DLLPORT HANDLE PTW32_CDECL pthread_getw32threadhandle_np(pthread_t thread);
/*
* Protected Methods
*
* This function blocks until the given WIN32 handle
* is signaled or pthread_cancel had been called.
* This function allows the caller to hook into the
* PThreads cancel mechanism. It is implemented using
*
* WaitForMultipleObjects
*
* on 'waitHandle' and a manually reset WIN32 Event
* used to implement pthread_cancel. The 'timeout'
* argument to TimedWait is simply passed to
* WaitForMultipleObjects.
*/
PTW32_DLLPORT int PTW32_CDECL pthreadCancelableWait (HANDLE waitHandle);
PTW32_DLLPORT int PTW32_CDECL pthreadCancelableTimedWait (HANDLE waitHandle,
DWORD timeout);
#endif /* PTW32_LEVEL >= PTW32_LEVEL_MAX */
/*
* Thread-Safe C Runtime Library Mappings.
*/
#ifndef _UWIN
# if defined(NEED_ERRNO)
PTW32_DLLPORT int * PTW32_CDECL _errno( void );
# else
# ifndef errno
# if (defined(_MT) || defined(_DLL))
__declspec(dllimport) extern int * __cdecl _errno(void);
# define errno (*_errno())
# endif
# endif
# endif
#endif
/*
* WIN32 C runtime library had been made thread-safe
* without affecting the user interface. Provide
* mappings from the UNIX thread-safe versions to
* the standard C runtime library calls.
* Only provide function mappings for functions that
* actually exist on WIN32.
*/
#if !defined(__MINGW32__)
#define strtok_r( _s, _sep, _lasts ) \
( *(_lasts) = strtok( (_s), (_sep) ) )
#endif /* !__MINGW32__ */
#define asctime_r( _tm, _buf ) \
( strcpy( (_buf), asctime( (_tm) ) ), \
(_buf) )
#define ctime_r( _clock, _buf ) \
( strcpy( (_buf), ctime( (_clock) ) ), \
(_buf) )
#define gmtime_r( _clock, _result ) \
( *(_result) = *gmtime( (_clock) ), \
(_result) )
#define localtime_r( _clock, _result ) \
( *(_result) = *localtime( (_clock) ), \
(_result) )
#define rand_r( _seed ) \
( _seed == _seed? rand() : rand() )
/*
* Some compiler environments don't define some things.
*/
#if defined(__BORLANDC__)
# define _ftime ftime
# define _timeb timeb
#endif
#ifdef __cplusplus
/*
* Internal exceptions
*/
class ptw32_exception {};
class ptw32_exception_cancel : public ptw32_exception {};
class ptw32_exception_exit : public ptw32_exception {};
#endif
#if PTW32_LEVEL >= PTW32_LEVEL_MAX
/* FIXME: This is only required if the library was built using SEH */
/*
* Get internal SEH tag
*/
PTW32_DLLPORT DWORD PTW32_CDECL ptw32_get_exception_services_code(void);
#endif /* PTW32_LEVEL >= PTW32_LEVEL_MAX */
#ifndef PTW32_BUILD
#ifdef __CLEANUP_SEH
/*
* Redefine the SEH __except keyword to ensure that applications
* propagate our internal exceptions up to the library's internal handlers.
*/
#define __except( E ) \
__except( ( GetExceptionCode() == ptw32_get_exception_services_code() ) \
? EXCEPTION_CONTINUE_SEARCH : ( E ) )
#endif /* __CLEANUP_SEH */
#ifdef __CLEANUP_CXX
/*
* Redefine the C++ catch keyword to ensure that applications
* propagate our internal exceptions up to the library's internal handlers.
*/
#ifdef _MSC_VER
/*
* WARNING: Replace any 'catch( ... )' with 'PtW32CatchAll'
* if you want Pthread-Win32 cancelation and pthread_exit to work.
*/
#ifndef PtW32NoCatchWarn
#pragma message("Specify \"/DPtW32NoCatchWarn\" compiler flag to skip this message.")
#pragma message("------------------------------------------------------------------")
#pragma message("When compiling applications with MSVC++ and C++ exception handling:")
#pragma message(" Replace any 'catch( ... )' in routines called from POSIX threads")
#pragma message(" with 'PtW32CatchAll' or 'CATCHALL' if you want POSIX thread")
#pragma message(" cancelation and pthread_exit to work. For example:")
#pragma message("")
#pragma message(" #ifdef PtW32CatchAll")
#pragma message(" PtW32CatchAll")
#pragma message(" #else")
#pragma message(" catch(...)")
#pragma message(" #endif")
#pragma message(" {")
#pragma message(" /* Catchall block processing */")
#pragma message(" }")
#pragma message("------------------------------------------------------------------")
#endif
#define PtW32CatchAll \
catch( ptw32_exception & ) { throw; } \
catch( ... )
#else /* _MSC_VER */
#define catch( E ) \
catch( ptw32_exception & ) { throw; } \
catch( E )
#endif /* _MSC_VER */
#endif /* __CLEANUP_CXX */
#endif /* ! PTW32_BUILD */
#ifdef __cplusplus
} /* End of extern "C" */
#endif /* __cplusplus */
#ifdef PTW32__HANDLE_DEF
# undef HANDLE
#endif
#ifdef PTW32__DWORD_DEF
# undef DWORD
#endif
#undef PTW32_LEVEL
#undef PTW32_LEVEL_MAX
#endif /* ! RC_INVOKED */
#endif /* PTHREAD_H */
| [
"matt@doeringtech.com"
] | matt@doeringtech.com |
2db79d5ef74797f0c90c48b039a7aaa4c365dda8 | cb6b0770bd3e01f888fc36bb658d8e5a40279408 | /bazel/google_cloud_cpp/generated/bigtable_mock.grpc.pb.h | 12dabc8ca6a3e74d43e7054d52552d4282eb79ee | [] | no_license | cschuet/tfs | 8f572dd49935ca47a05b7c78133198f24ee00b99 | 28bb8b273e6a5d0e07e475b5ff5ba338122b6aca | refs/heads/master | 2020-03-11T11:01:22.236629 | 2018-04-17T20:30:09 | 2018-04-17T20:30:09 | 129,958,588 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 4,797 | h | // Generated by the gRPC C++ plugin.
// If you make any local change, they will be lost.
// source: google/bigtable/v2/bigtable.proto
#include "google/bigtable/v2/bigtable.pb.h"
#include "google/bigtable/v2/bigtable.grpc.pb.h"
#include <grpcpp/impl/codegen/async_stream.h>
#include <grpcpp/impl/codegen/sync_stream.h>
#include <gmock/gmock.h>
namespace google {
namespace bigtable {
namespace v2 {
class MockBigtableStub : public Bigtable::StubInterface {
public:
MOCK_METHOD2(ReadRowsRaw, ::grpc::ClientReaderInterface< ::google::bigtable::v2::ReadRowsResponse>*(::grpc::ClientContext* context, const ::google::bigtable::v2::ReadRowsRequest& request));
MOCK_METHOD4(AsyncReadRowsRaw, ::grpc::ClientAsyncReaderInterface< ::google::bigtable::v2::ReadRowsResponse>*(::grpc::ClientContext* context, const ::google::bigtable::v2::ReadRowsRequest& request, ::grpc::CompletionQueue* cq, void* tag));
MOCK_METHOD3(PrepareAsyncReadRowsRaw, ::grpc::ClientAsyncReaderInterface< ::google::bigtable::v2::ReadRowsResponse>*(::grpc::ClientContext* context, const ::google::bigtable::v2::ReadRowsRequest& request, ::grpc::CompletionQueue* cq));
MOCK_METHOD2(SampleRowKeysRaw, ::grpc::ClientReaderInterface< ::google::bigtable::v2::SampleRowKeysResponse>*(::grpc::ClientContext* context, const ::google::bigtable::v2::SampleRowKeysRequest& request));
MOCK_METHOD4(AsyncSampleRowKeysRaw, ::grpc::ClientAsyncReaderInterface< ::google::bigtable::v2::SampleRowKeysResponse>*(::grpc::ClientContext* context, const ::google::bigtable::v2::SampleRowKeysRequest& request, ::grpc::CompletionQueue* cq, void* tag));
MOCK_METHOD3(PrepareAsyncSampleRowKeysRaw, ::grpc::ClientAsyncReaderInterface< ::google::bigtable::v2::SampleRowKeysResponse>*(::grpc::ClientContext* context, const ::google::bigtable::v2::SampleRowKeysRequest& request, ::grpc::CompletionQueue* cq));
MOCK_METHOD3(MutateRow, ::grpc::Status(::grpc::ClientContext* context, const ::google::bigtable::v2::MutateRowRequest& request, ::google::bigtable::v2::MutateRowResponse* response));
MOCK_METHOD3(AsyncMutateRowRaw, ::grpc::ClientAsyncResponseReaderInterface< ::google::bigtable::v2::MutateRowResponse>*(::grpc::ClientContext* context, const ::google::bigtable::v2::MutateRowRequest& request, ::grpc::CompletionQueue* cq));
MOCK_METHOD3(PrepareAsyncMutateRowRaw, ::grpc::ClientAsyncResponseReaderInterface< ::google::bigtable::v2::MutateRowResponse>*(::grpc::ClientContext* context, const ::google::bigtable::v2::MutateRowRequest& request, ::grpc::CompletionQueue* cq));
MOCK_METHOD2(MutateRowsRaw, ::grpc::ClientReaderInterface< ::google::bigtable::v2::MutateRowsResponse>*(::grpc::ClientContext* context, const ::google::bigtable::v2::MutateRowsRequest& request));
MOCK_METHOD4(AsyncMutateRowsRaw, ::grpc::ClientAsyncReaderInterface< ::google::bigtable::v2::MutateRowsResponse>*(::grpc::ClientContext* context, const ::google::bigtable::v2::MutateRowsRequest& request, ::grpc::CompletionQueue* cq, void* tag));
MOCK_METHOD3(PrepareAsyncMutateRowsRaw, ::grpc::ClientAsyncReaderInterface< ::google::bigtable::v2::MutateRowsResponse>*(::grpc::ClientContext* context, const ::google::bigtable::v2::MutateRowsRequest& request, ::grpc::CompletionQueue* cq));
MOCK_METHOD3(CheckAndMutateRow, ::grpc::Status(::grpc::ClientContext* context, const ::google::bigtable::v2::CheckAndMutateRowRequest& request, ::google::bigtable::v2::CheckAndMutateRowResponse* response));
MOCK_METHOD3(AsyncCheckAndMutateRowRaw, ::grpc::ClientAsyncResponseReaderInterface< ::google::bigtable::v2::CheckAndMutateRowResponse>*(::grpc::ClientContext* context, const ::google::bigtable::v2::CheckAndMutateRowRequest& request, ::grpc::CompletionQueue* cq));
MOCK_METHOD3(PrepareAsyncCheckAndMutateRowRaw, ::grpc::ClientAsyncResponseReaderInterface< ::google::bigtable::v2::CheckAndMutateRowResponse>*(::grpc::ClientContext* context, const ::google::bigtable::v2::CheckAndMutateRowRequest& request, ::grpc::CompletionQueue* cq));
MOCK_METHOD3(ReadModifyWriteRow, ::grpc::Status(::grpc::ClientContext* context, const ::google::bigtable::v2::ReadModifyWriteRowRequest& request, ::google::bigtable::v2::ReadModifyWriteRowResponse* response));
MOCK_METHOD3(AsyncReadModifyWriteRowRaw, ::grpc::ClientAsyncResponseReaderInterface< ::google::bigtable::v2::ReadModifyWriteRowResponse>*(::grpc::ClientContext* context, const ::google::bigtable::v2::ReadModifyWriteRowRequest& request, ::grpc::CompletionQueue* cq));
MOCK_METHOD3(PrepareAsyncReadModifyWriteRowRaw, ::grpc::ClientAsyncResponseReaderInterface< ::google::bigtable::v2::ReadModifyWriteRowResponse>*(::grpc::ClientContext* context, const ::google::bigtable::v2::ReadModifyWriteRowRequest& request, ::grpc::CompletionQueue* cq));
};
} // namespace google
} // namespace bigtable
} // namespace v2
| [
"cschuet@google.com"
] | cschuet@google.com |
1b38ea63dfdec4dfc200ea79bebe28e655fbb299 | d4edd187959684ffb592510847833f2365f254c8 | /includes/Shapes.h | 1402d76c7c6c1eaa97d4405666712998f8aa9e91 | [] | no_license | costashatz/SimpleRaytracer | 8463d6eb193a408a5fa7892ab34f3afdd50c7f6e | b8f882d635017779989c5fd49e19971f98c3d11e | refs/heads/master | 2021-01-13T02:11:47.620915 | 2014-02-05T09:10:11 | 2014-02-05T09:10:11 | 16,525,856 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,249 | h | #pragma once
#include "LocalGeo.h"
#include "Ray.h"
//Shape class
class Shape
{
public:
virtual bool intersect(Ray& ray, float* thit, LocalGeo* local) { return false; }
virtual bool intersectP(Ray& ray)
{
float temp;
LocalGeo l;
return intersect(ray,&temp,&l);
}
};
//Triangle
class Triangle : public Shape
{
private:
Point p0,p1,p2;
public:
Triangle() {}
Triangle(Point _p0, Point _p1, Point _p2)
{
p0 = _p0;
p1 = _p1;
p2 = _p2;
}
bool intersect(Ray& ray, float* thit, LocalGeo* local)
{
vec3 e1 = p1-p0, e2 = p2-p0, p, s, q;
float tmp, t, u, v, epsilon = 0.000001;
p = glm::cross(ray.Direction(),e2);
tmp = glm::dot(p,e1);
if(tmp>-epsilon && tmp < epsilon)
return false;
tmp = 1.f/tmp;
s = ray.Position()-p0;
u = tmp*glm::dot(s,p);
if(u<0.0 || u>1.0)
return false;
q = glm::cross(s,e1);
v = tmp*glm::dot(ray.Direction(),q);
if(v<0.0 || u+v>1.0)
return false;
t = tmp*glm::dot(e2,q);
Point P = ray.Position()+t*ray.Direction();
vec3 n = glm::normalize(glm::cross(e1,e2));
if(t<ray.Min() || t>ray.Max())
return false;
*thit = t;
*local = LocalGeo(P, n);
return true;
}
};
//Sphere
class Sphere : public Shape
{
private:
Point center;
float radius;
public:
Sphere():center(Point()),radius(0.0) {}
Sphere(Point c, float r):center(c),radius(r) {}
bool intersect(Ray& ray, float* thit, LocalGeo* local)
{
float a,b,c, discrm, t;
vec3 pMinusC = ray.Position()-center;
a = glm::dot(ray.Direction(),ray.Direction());
b = 2.0*glm::dot(ray.Direction(),pMinusC);
c = glm::dot(pMinusC,pMinusC)-radius*radius;
discrm = b*b-4*a*c;
if(discrm<0.f)
return false;
float t1 = (-b+sqrt(discrm))/(2*a);
float t2 = (-b-sqrt(discrm))/(2*a);
if(t1>=0.0&&t2>=0.0)
{
t = t1;
if(t2<t1)
t = t2;
}
else
{
if(t1>=0.0)
t = t1;
else if(t2>=0.0)
t = t2;
else
return false;
}
if(t<ray.Min() || t>ray.Max())
return false;
Point temp = ray.Position()+t*ray.Direction();
vec3 n = glm::normalize(temp-center);
*thit = t;
*local = LocalGeo(temp, n);
return true;
}
};
//TriangleNormal
class TriangleNormal : public Shape
{
private:
Point p0,p1,p2;
vec3 n0,n1,n2;
public:
TriangleNormal() {}
TriangleNormal(Point _p0, Point _p1, Point _p2, vec3 _n0, vec3 _n1, vec3 _n2)
{
p0 = _p0;
p1 = _p1;
p2 = _p2;
n0 = _n0;
n1 = _n1;
n2 = _n2;
}
bool intersect(Ray& ray, float* thit, LocalGeo* local)
{
vec3 e1 = p1-p0, e2 = p2-p0, p, s, q;
float tmp, t, u, v, epsilon = 0.000001;
p = glm::cross(ray.Direction(),e2);
tmp = glm::dot(p,e1);
if(tmp>-epsilon && tmp < epsilon)
return false;
tmp = 1.f/tmp;
s = ray.Position()-p0;
u = tmp*glm::dot(s,p);
if(u<0.0 || u>1.0)
return false;
q = glm::cross(s,e1);
v = tmp*glm::dot(ray.Direction(),q);
if(v<0.0 || u+v>1.0)
return false;
t = tmp*glm::dot(e2,q);
Point P = ray.Position()+t*ray.Direction();
float w = 1-u-v;
vec3 n = glm::normalize(w*n0+u*n1+v*n2);
if(t<ray.Min() || t>ray.Max())
return false;
*thit = t;
*local = LocalGeo(P, n);
return true;
}
}; | [
"costas@costas-Xubuntu.(none)"
] | costas@costas-Xubuntu.(none) |
31fba71ecd1ee951cb358026f5fa3049042714cc | bee6ac60b1de3e20e3c88631a0139447ed3bb446 | /Hello-World.cpp | 2dda5546959bd42680f614d579ae04e458c4e2ae | [] | no_license | zs-co/upgraded-memory | 06bbe5b6a40b82877bf3fa9940e47b6548cd5ba8 | a6610be6b1f35c1a0baa6b88372d9f0b5472fead | refs/heads/master | 2022-10-25T02:45:51.262022 | 2020-06-10T06:50:56 | 2020-06-10T06:50:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 139 | cpp | #include <iostream>
using namespace std;
int main(){
cout << "Hello-World\n";
return 0;
}
| [
"noreply@github.com"
] | zs-co.noreply@github.com |
7a09b88a2e2987bbdf05305b6da0b6dd4151b388 | 29948885a97f946dd46d25dcce1ae08247affb8a | /Examen2/proxy.cpp | 25e70dd14a2a925f42b5ecbf2751c9f25517e412 | [] | no_license | osanseviero/Software_Engineering | 8c9d573fd8793601d8ee25f827f7295c940a9174 | 396244b0de12275115959ce11c008a1bb08a7db2 | refs/heads/master | 2020-04-12T05:42:19.118305 | 2016-12-08T02:54:55 | 2016-12-08T02:54:58 | 65,292,647 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 369 | cpp | class Proxy
{
private:
int id;
News* news;
static int next;
public:
Proxy() {
id = next++;
news = NULL;
}
void publish(std::string pub) {
if(!news) {
news = new News(id);
}
news->publish(pub);
}
};
int Proxy::next = 1; | [
"osanseviero@gmail.com"
] | osanseviero@gmail.com |
1c41c93368cf4e8549e571023bed070aab5d5727 | 04f7112bb9f33921cd39c027621c612b1c60f9cc | /Dali/dali-core/dali/internal/event/animation/linear-constrainer-impl.cpp | a1b586a34aa1b0c39a3b31b1b7e8dc8d93869b5d | [] | no_license | zg2nets/windows-backend | c5cf568a3f865405a0b47c1208c9720fe00f0d02 | 8af57e6a295a810b51654d70af2e3e10b5a771bb | refs/heads/release | 2020-09-10T01:54:58.611433 | 2020-02-21T04:29:24 | 2020-02-21T04:29:24 | 221,619,486 | 0 | 0 | null | 2020-02-21T04:29:25 | 2019-11-14T05:32:57 | C++ | UTF-8 | C++ | false | false | 4,674 | cpp | /*
* Copyright (c) 2018 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// CLASS HEADER
#include <dali/internal/event/animation/linear-constrainer-impl.h>
//EXTRENAL INCLUDES
#include <cstring> // for strcmp
// INTERNAL INCLUDES
#include <dali/public-api/animation/constraint.h>
#include <dali/public-api/object/property-array.h>
#include <dali/public-api/object/type-registry.h>
#include <dali/internal/event/common/property-helper.h>
namespace Dali
{
namespace Internal
{
namespace
{
// Properties
// Name Type writable animatable constraint-input enum for index-checking
DALI_PROPERTY_TABLE_BEGIN
DALI_PROPERTY( "value", ARRAY, true, false, false, Dali::LinearConstrainer::Property::VALUE )
DALI_PROPERTY( "progress", ARRAY, true, false, false, Dali::LinearConstrainer::Property::PROGRESS )
DALI_PROPERTY_TABLE_END( DEFAULT_OBJECT_PROPERTY_START_INDEX, LinearConstrainerDefaultProperties )
BaseHandle Create()
{
return Dali::LinearConstrainer::New();
}
TypeRegistration mType( typeid( Dali::LinearConstrainer ), typeid( Dali::Handle ), Create, LinearConstrainerDefaultProperties );
} //Unnamed namespace
LinearConstrainer* LinearConstrainer::New()
{
return new LinearConstrainer();
}
LinearConstrainer::LinearConstrainer()
: Constrainer()
{
}
LinearConstrainer::~LinearConstrainer()
{
}
Property::Value LinearConstrainer::GetDefaultProperty( Property::Index index ) const
{
if( index == Dali::LinearConstrainer::Property::VALUE )
{
Property::Value value( Property::ARRAY );
Property::Array* array = value.GetArray();
uint32_t count = static_cast<uint32_t>( mValue.Size() );
if( array )
{
array->Reserve( count );
for( uint32_t i( 0 ); i != count; ++i )
{
array->PushBack( mValue[i] );
}
}
return value;
}
else if( index == Dali::LinearConstrainer::Property::PROGRESS )
{
Property::Value value( Property::ARRAY );
Property::Array* array = value.GetArray();
uint32_t count = static_cast<uint32_t>( mProgress.Size() );
if( array )
{
array->Reserve( count );
for( uint32_t i( 0 ); i != count; ++i )
{
array->PushBack( mProgress[i] );
}
}
return value;
}
return Property::Value();
}
Property::Value LinearConstrainer::GetDefaultPropertyCurrentValue( Property::Index index ) const
{
return GetDefaultProperty( index ); // Event-side only properties
}
void LinearConstrainer::SetDefaultProperty( Property::Index index, const Property::Value& propertyValue )
{
const Property::Array* array = propertyValue.GetArray();
if( array )
{
uint32_t propertyArrayCount = static_cast<uint32_t>( array->Count() );
if( index == Dali::LinearConstrainer::Property::VALUE )
{
mValue.Clear(); // remove old values
mValue.Resize( propertyArrayCount );
for( uint32_t i(0); i != propertyArrayCount; ++i )
{
array->GetElementAt( i ).Get( mValue[ i ] );
}
}
else if( index == Dali::LinearConstrainer::Property::PROGRESS )
{
mProgress.Clear(); // remove old values
mProgress.Resize( propertyArrayCount );
for( uint32_t i(0); i != propertyArrayCount; ++i )
{
array->GetElementAt( i ).Get( mProgress[ i ] );
}
}
}
}
void LinearConstrainer::Apply( Property target, Property source, const Vector2& range, const Vector2& wrap)
{
Dali::Constraint constraint = Dali::Constraint::New<float>( target.object, target.propertyIndex, LinearConstraintFunctor( mValue, mProgress, range, wrap ) );
constraint.AddSource( Dali::Source(source.object, source.propertyIndex ) );
constraint.SetTag( static_cast<uint32_t>( reinterpret_cast<uintptr_t>( this ) ) ); // taking 32bits of this as tag
constraint.SetRemoveAction( Dali::Constraint::Discard );
constraint.Apply();
//Start observing the object
Observe( target.object );
}
} // Internal
} // Dali
| [
"noreply@github.com"
] | zg2nets.noreply@github.com |
3faf9d7ffa9e8a101c506b48c02ef669fe615bda | c7bcd0590f52975d3a832e9dfb00763e8702c7ec | /src/IOE/IOEExceptions/IOEExceptionsPCH.cpp | 33b3ed2a9c6c209ffd8b0dc78431a12a3791246f | [] | no_license | stevenhartin/IOE | 656075f502b1e4f39525ec93564ba05c158215fe | d070a2f583aa26632625fe5b8115460d82349ca9 | refs/heads/master | 2020-05-23T09:47:56.408122 | 2019-05-15T22:03:38 | 2019-05-15T22:03:38 | 186,713,691 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 29 | cpp | #include "IOEExceptionsPCH.h" | [
"steven.hartin@googlemail.com"
] | steven.hartin@googlemail.com |
7d059e592d9abd6c393d2fdd4ffbe1f7db4f86e8 | fdb63867d49dcc1e9d83e55197ca8a05baf7484b | /PMBRender/shaders/TriangleFragment0.cpp | 0ea4cd58f24c806783dca1e0ff9ac2e4570ee791 | [
"MIT"
] | permissive | LRLVEC/MarchingCubes | 3ae52235cc248aea4704016ef4bff354492ea724 | 6bcfdf36a057e22aea7a906330d074eb961e2f50 | refs/heads/master | 2023-08-21T13:40:57.600602 | 2021-09-23T15:48:25 | 2021-09-23T15:48:25 | 283,292,748 | 10 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 90 | cpp | #version 450 core
in vec4 in_color;
out vec4 o_color;
void main()
{
o_color = in_color;
} | [
"mjdyx@outlook.com"
] | mjdyx@outlook.com |
d5e1d0f3219703add4574c51bc6f4a5708d618f6 | 8085f16eaf5133bebb45aeeabb9b172ae3db4176 | /hdoj/hdu2222/hdu2222/main.cpp | 4e6a6c94d5ba9791803ba6f783690dbbbe160883 | [] | no_license | EyciaZhou/acm | ff0dd40971424f338369eca8507e8c339497f946 | 50121929dc658be717b8fa6076ec28dea915ce97 | refs/heads/master | 2020-05-01T08:57:48.118961 | 2015-06-09T06:48:53 | 2015-06-09T06:48:53 | 35,026,832 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,141 | cpp | //
// main.cpp
// poj3080
//
// Created by eycia on 14/12/5.
// Copyright (c) 2014年 eycia. All rights reserved.
//
#include <cstdio>
#include <cstring>
#include <queue>
#include <iostream>
using namespace std;
char s[1000005];
typedef struct node {
int n[26];
int f; //fall
int d; //date
int fa; //fa
int b; //iis
} NODE;
int n;
NODE trie[600000];
int list[600000];
void dof() {
int i, j;
int h = -1, t = 0;
for (i = 0; i <= n; i++) {
if (trie[0].n[i] >= 0) {
trie[trie[0].n[i]].f = 0;
for (j = 0; j <= n; j++) {
if (trie[trie[0].n[i]].n[j] >= 0) {
h = (h + 1) % 600000;
list[h] = trie[trie[0].n[i]].n[j];
}
}
}
}
while ((h + 1) % 600000 != t) {
int p = list[t];
//cout << p << endl;
t = (t + 1) % 600000;
for (i = 0; i <= n; i++) {
if (trie[p].n[i] >= 0) {
h = (h + 1) % 600000;
list[h] = trie[p].n[i];
}
}
int n = trie[p].d;
int q = trie[trie[p].fa].f;
while (true) {
if (trie[q].n[n] >= 0) {
trie[p].f = trie[q].n[n];
//if (trie[trie[q].n[n]].b > 0) {
//trie[p].b += trie[trie[q].n[n]].b;
//trie[trie[q].n[n]].b += trie[p].b;
//}
break;
}else{
if (q == 0) {
trie[p].f = 0;
break;
}
}
q = trie[q].f;
}
}
}
int getnext(int f, int n) {
while (true) {
if (trie[f].n[n] >= 0) {
return trie[f].n[n];
}
if (f == 0) {
return 0;
}
f = trie[f].f;
}
}
void flf(int f, int k) {
while (true) {
if (f == 0) {
return ;
}
trie[f].b -= k;
//cout << trie[f].b << endl;
f = trie[f].f;
}
}
void up(int f) {
cout << "aa" << f << endl;
int k = 0;
while (true) {
if (f == 0) {
return ;
}
k += trie[f].b;
trie[f].b = k;
//cout << trie[f].b << endl;
f = trie[f].f;
}
}
char key[100];
int main(int argc, const char * argv[]) {
int ff;
scanf("%d", &ff);
n = 25;
while (ff--) {
int mem = 0;
memset(trie[0].n, -1, sizeof(trie[0].n));
trie[0].f = -1;
trie[0].fa = -1;
trie[0].d = -1;
trie[0].b = false;
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%s", key);
int sl = strlen(key);
int now = 0;
for (int j = 0; j < sl; j++) {
if (trie[now].n[key[j]-'a'] < 0) {
mem++;
memset(trie[mem].n, -1, sizeof(trie[mem].n));
trie[mem].f = -1;
trie[mem].fa = now;
trie[mem].d = key[j] - 'a';
trie[mem].b = 0;
trie[now].n[key[j]-'a'] = mem;
}
now = trie[now].n[key[j]-'a'];
}
trie[now].b++;
}
dof();
for (int i = 1; i <= mem; i++) {
if (trie[i].n[trie[i].d] < 0) {
up(i);
}
}
scanf("%s", s);
int sl = strlen(s);
int now = 0, ans = 0, re = 0;
for (int i = 0; i < sl; i++) {
re = getnext(now, s[i] - 'a');
ans += trie[re].b;
//trie[re].b = 0;
if (trie[re].b > 0) {
//flf(re, trie[re].b);
cout << endl;
}
now = re;
}
printf("%d\n", ans);
}
}
/*
2
2
sher
he
she
2
sher
he
sher
1
6
she
he
he
say
shr
her
yasherhe
1
6
she
he
he
say
shr
her
yasherhs
10
2
abcdef
bcd
abcdef
1
h
hhhhh
5
bhea
her
he
h
ha
bhera
5
bhea
her
he
h
ha
bhera
*/ | [
"zhou.eycia@gmail.com"
] | zhou.eycia@gmail.com |
5ac91959ff9ba14f2f069715b94ef51f866c6ca6 | 27ef6b50e8d2d388ab0f745e5c402117baedf983 | /03Decorator/DarkRoast.cpp | a54946dc9d1a2cd908eb4ab2ef333f0049f29b4a | [] | no_license | sanqima/HeadFirstDesignPatternsCPP | c7decb6d4af5165ba5ada99e22cd4fe095e4bff3 | 1d8e20d9745610d69fbce92a600125a7ba5e1386 | refs/heads/master | 2023-03-16T18:45:04.567965 | 2020-09-28T13:48:37 | 2020-09-28T13:48:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 194 | cpp | #include "DarkRoast.h"
namespace decorator
{
double DarkRoast::cost()
{
return 0.99f;
}
DarkRoast::DarkRoast()
{
description = "Dark Roast Coffee";
}
}
| [
"knapecz.adam@gmail.com"
] | knapecz.adam@gmail.com |
dd2233b2887285734ea8172b079447d56de89279 | fa8bc6a9c08210def6028f124a746da50b16c162 | /Source/Accelerate/AIManager.h | 7f1af4727626aee985d79d5637c68e840933ae2b | [] | no_license | arorabharat144/Accelerate | 661fe183c355a605817fd294c0260d610ce6a440 | 3c2791d093412ea69fa85b69cbe42598b94023b2 | refs/heads/master | 2022-01-05T06:35:47.832941 | 2019-05-11T18:44:38 | 2019-05-11T18:44:38 | 186,170,047 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,646 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "AICheckpoint.h"
#include <vector>
#include "AIManager.generated.h"
constexpr int MAX_AI = 11;
UENUM()
enum class AIPlayerActions
{
Left UMETA(DisplayName = "Left"),
Right UMETA(DisplayName = "Right"),
Nothing UMETA(DisplayName = "Nothing"),
};
UENUM()
enum class BattleAIStates
{
Patrol UMETA(DisplayName = "Patrol"),
Attack UMETA(DisplayName = "Attack"),
};
class AAcceleratePlayer;
UCLASS()
class ACCELERATE_API AAIManager : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AAIManager();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
void Init();
// Race AI Functions
AAICheckpoint* RaceUpdate(FVector playerLocation, AAICheckpoint* currentCheckpoint);
AAICheckpoint* GetCheckpoint(uint32 path, uint32 checkpoint);
// Battle AI Functions
AAICheckpoint* BattleUpdate(AAICheckpoint* currentCheckpoint, FVector currentLocation, int& iterate);
AAcceleratePlayer* GetTarget(FVector currentLocation, float heightDifference);
// Functions for Race and Battle AI
AIPlayerActions GetAction(FVector direction, FVector location, FVector targetLocation) const;
//UPROPERTY(EditAnywhere, Category = "Designer Tools")
float checkpointCollideDistance{ 1500.0f };
private:
bool mInit{ false };
std::vector<std::vector<AAICheckpoint*>> mCheckpoints;
TArray<AAcceleratePlayer*> mPlayers;
};
| [
"arorabharat144@gmail.com"
] | arorabharat144@gmail.com |
d035dda6ffbd237ccfc4d367d22cf5a17e14541f | 2e87e774d607afbe4f16582b0ade36324835a186 | /src/main.cpp | 3da2e2ca8e101cd669c936c80992188afabf8bd2 | [] | no_license | mateopolancec/CppND-Route-Planning-Project | 896ba6278832bacd5906dce69ed37d83e436c70e | f2d527a5a0dc0aaf6461f2c46d8a0f523304a5d2 | refs/heads/master | 2022-10-09T07:25:31.016430 | 2020-05-31T21:53:01 | 2020-05-31T21:53:01 | 263,146,262 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,758 | cpp | #include <optional>
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
#include <io2d.h>
#include "route_model.h"
#include "render.h"
#include "route_planner.h"
using namespace std::experimental;
static std::optional<std::vector<std::byte>> ReadFile(const std::string &path)
{
std::ifstream is{path, std::ios::binary | std::ios::ate};
if( !is )
return std::nullopt;
auto size = is.tellg();
std::vector<std::byte> contents(size);
is.seekg(0);
is.read((char*)contents.data(), size);
if( contents.empty() )
return std::nullopt;
return std::move(contents);
}
int main(int argc, const char **argv)
{
std::string osm_data_file = "";
if( argc > 1 ) {
for( int i = 1; i < argc; ++i )
if( std::string_view{argv[i]} == "-f" && ++i < argc )
osm_data_file = argv[i];
}
else {
std::cout << "To specify a map file use the following format: " << std::endl;
std::cout << "Usage: [executable] [-f filename.osm]" << std::endl;
osm_data_file = "../map.osm";
}
std::vector<std::byte> osm_data;
if( osm_data.empty() && !osm_data_file.empty() ) {
std::cout << "Reading OpenStreetMap data from the following file: " << osm_data_file << std::endl;
auto data = ReadFile(osm_data_file);
if( !data )
std::cout << "Failed to read." << std::endl;
else
osm_data = std::move(*data);
}
// TODO 1: Declare floats `start_x`, `start_y`, `end_x`, and `end_y` and get
// user input for these values using std::cin. Pass the user input to the
// RoutePlanner object below in place of 10, 10, 90, 90.
float start_x, start_y, end_x, end_y;
std::cout << "Enter start_x: ";
std::cin >> start_x;
std::cout << "Enter start_y: ";
std::cin >> start_y;
std::cout << "Enter end_x: ";
std::cin >> end_x;
std::cout << "Enter end_y: ";
std::cin >> end_y;
// Build Model.
RouteModel model{osm_data};
// Create RoutePlanner object and perform A* search.
RoutePlanner route_planner{model, start_x, start_y, end_x, end_y};
route_planner.AStarSearch();
std::cout << "Distance: " << route_planner.GetDistance() << " meters. \n";
// Render results of search.
Render render{model};
auto display = io2d::output_surface{400, 400, io2d::format::argb32, io2d::scaling::none, io2d::refresh_style::fixed, 30};
display.size_change_callback([](io2d::output_surface& surface){
surface.dimensions(surface.display_dimensions());
});
display.draw_callback([&](io2d::output_surface& surface){
render.Display(surface);
});
display.begin_show();
}
| [
"noreply@github.com"
] | mateopolancec.noreply@github.com |
111555f53c33fdf0713762f962e723c85f73e200 | b7f1b4df5d350e0edf55521172091c81f02f639e | /device/gamepad/gamepad_pad_state_provider.h | 62a8ccacf4a56b98b01e9e7bce2ef1744901eacd | [
"BSD-3-Clause"
] | permissive | blusno1/chromium-1 | f13b84547474da4d2702341228167328d8cd3083 | 9dd22fe142b48f14765a36f69344ed4dbc289eb3 | refs/heads/master | 2023-05-17T23:50:16.605396 | 2018-01-12T19:39:49 | 2018-01-12T19:39:49 | 117,339,342 | 4 | 2 | NOASSERTION | 2020-07-17T07:35:37 | 2018-01-13T11:48:57 | null | UTF-8 | C++ | false | false | 3,259 | h | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef DEVICE_GAMEPAD_GAMEPAD_PAD_STATE_PROVIDER_H_
#define DEVICE_GAMEPAD_GAMEPAD_PAD_STATE_PROVIDER_H_
#include <stdint.h>
#include <limits>
#include <memory>
#include "device/gamepad/gamepad_export.h"
#include "device/gamepad/gamepad_standard_mappings.h"
#include "device/gamepad/public/cpp/gamepad.h"
namespace device {
class GamepadDataFetcher;
enum GamepadSource {
GAMEPAD_SOURCE_NONE = 0,
GAMEPAD_SOURCE_ANDROID,
GAMEPAD_SOURCE_GVR,
GAMEPAD_SOURCE_CARDBOARD,
GAMEPAD_SOURCE_LINUX_UDEV,
GAMEPAD_SOURCE_MAC_GC,
GAMEPAD_SOURCE_MAC_HID,
GAMEPAD_SOURCE_MAC_XBOX,
GAMEPAD_SOURCE_OCULUS,
GAMEPAD_SOURCE_OPENVR,
GAMEPAD_SOURCE_TEST,
GAMEPAD_SOURCE_WIN_XINPUT,
GAMEPAD_SOURCE_WIN_RAW,
};
enum GamepadActiveState {
GAMEPAD_INACTIVE = 0,
GAMEPAD_ACTIVE,
GAMEPAD_NEWLY_ACTIVE,
};
struct PadState {
// Which data fetcher provided this gamepad's data.
GamepadSource source;
// Data fetcher-specific identifier for this gamepad.
int source_id;
// Indicates whether or not the gamepad is actively being updated
GamepadActiveState active_state;
// Gamepad data, unmapped.
Gamepad data;
// Functions to map from device data to standard layout, if available. May
// be null if no mapping is available or needed.
GamepadStandardMappingFunction mapper;
// Sanitization masks
// axis_mask and button_mask are bitfields that represent the reset state of
// each input. If a button or axis has ever reported 0 in the past the
// corresponding bit will be set to 1.
// If we ever increase the max axis count this will need to be updated.
static_assert(Gamepad::kAxesLengthCap <=
std::numeric_limits<uint32_t>::digits,
"axis_mask is not large enough");
uint32_t axis_mask;
// If we ever increase the max button count this will need to be updated.
static_assert(Gamepad::kButtonsLengthCap <=
std::numeric_limits<uint32_t>::digits,
"button_mask is not large enough");
uint32_t button_mask;
};
class DEVICE_GAMEPAD_EXPORT GamepadPadStateProvider {
public:
GamepadPadStateProvider();
virtual ~GamepadPadStateProvider();
// Gets a PadState object for the given source and id. If the device hasn't
// been encountered before one of the remaining slots will be reserved for it.
// If no slots are available will return NULL.
PadState* GetPadState(GamepadSource source, int source_id);
// Gets a PadState object for a connected gamepad by specifying its index in
// the pad_states_ array. Returns NULL if there is no connected gamepad at
// that index.
PadState* GetConnectedPadState(int pad_index);
protected:
void ClearPadState(PadState& state);
void InitializeDataFetcher(GamepadDataFetcher* fetcher);
void MapAndSanitizeGamepadData(PadState* pad_state,
Gamepad* pad,
bool sanitize);
// Tracks the state of each gamepad slot.
std::unique_ptr<PadState[]> pad_states_;
};
} // namespace device
#endif // DEVICE_GAMEPAD_GAMEPAD_PAD_STATE_PROVIDER_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
16c624c4e95a5c9a7ef025958af29b3c79285fee | 5390eac0ac54d2c3c1c664ae525881fa988e2cf9 | /include/Pothos/serialization/impl/mpl/vector/vector50_c.hpp | 698d13da92b1addf3d0d5ed3f1313146128e23cf | [
"BSL-1.0"
] | permissive | pothosware/pothos-serialization | 2935b8ab1fe51299a6beba2a3e11611928186849 | c59130f916a3e5b833a32ba415063f9cb306a8dd | refs/heads/master | 2021-08-16T15:22:12.642058 | 2015-12-10T03:32:04 | 2015-12-10T03:32:04 | 19,961,886 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,478 | hpp |
#ifndef POTHOS_MPL_VECTOR_VECTOR50_C_HPP_INCLUDED
#define POTHOS_MPL_VECTOR_VECTOR50_C_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2000-2004
//
// 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/mpl for documentation.
// $Id: vector50_c.hpp 49267 2008-10-11 06:19:02Z agurtovoy $
// $Date: 2008-10-10 23:19:02 -0700 (Fri, 10 Oct 2008) $
// $Revision: 49267 $
#if !defined(POTHOS_MPL_PREPROCESSING_MODE)
# include <Pothos/serialization/impl/mpl/vector/vector40_c.hpp>
# include <Pothos/serialization/impl/mpl/vector/vector50.hpp>
#endif
#include <Pothos/serialization/impl/mpl/aux_/config/use_preprocessed.hpp>
#if !defined(POTHOS_MPL_CFG_NO_PREPROCESSED_HEADERS) \
&& !defined(POTHOS_MPL_PREPROCESSING_MODE)
# define POTHOS_MPL_PREPROCESSED_HEADER vector50_c.hpp
# include <Pothos/serialization/impl/mpl/vector/aux_/include_preprocessed.hpp>
#else
# include <Pothos/serialization/impl/mpl/aux_/config/typeof.hpp>
# include <Pothos/serialization/impl/mpl/aux_/config/ctps.hpp>
# include <Pothos/serialization/impl/preprocessor/iterate.hpp>
namespace Pothos { namespace mpl {
# define POTHOS_PP_ITERATION_PARAMS_1 \
(3,(41, 50, <boost/mpl/vector/aux_/numbered_c.hpp>))
# include POTHOS_PP_ITERATE()
}}
#endif // BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS
#endif // BOOST_MPL_VECTOR_VECTOR50_C_HPP_INCLUDED
| [
"josh@joshknows.com"
] | josh@joshknows.com |
d672d244bb65a3d379955d8f7bad5aee00262a84 | 5a8fafefd7712b3730b27c5907ca8f54b567e328 | /neb/inc/com/centreon/engine/logging/broker.hh | f90ee9e3eb2d7bdfe489848db50a01accaad16e1 | [
"Apache-2.0"
] | permissive | joe4568/centreon-broker | 672d831389c17f92f09948704437c4bc9026998d | daf454371520989573c810be1f6dfca40979a75d | refs/heads/master | 2020-04-13T05:11:03.126655 | 2018-12-24T14:53:34 | 2018-12-24T14:53:34 | 162,984,149 | 0 | 0 | Apache-2.0 | 2018-12-24T11:33:05 | 2018-12-24T11:33:04 | null | UTF-8 | C++ | false | false | 2,143 | hh | /*
** Copyright 2011-2013 Merethis
**
** This file is part of Centreon Engine.
**
** Centreon Engine 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.
**
** Centreon Engine 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 Centreon Engine. If not, see
** <http://www.gnu.org/licenses/>.
*/
#ifndef CCE_LOGGING_BROKER_HH
# define CCE_LOGGING_BROKER_HH
# include "com/centreon/concurrency/thread.hh"
# include "com/centreon/engine/namespace.hh"
# include "com/centreon/logging/backend.hh"
CCE_BEGIN()
namespace logging {
/**
* @class broker broker.hh
* @brief Call broker for all logging message.
*
* Call broker for all logging message without debug.
*/
class broker
: public com::centreon::logging::backend {
public:
broker();
broker(broker const& right);
~broker() throw ();
broker& operator=(broker const& right);
void close() throw ();
void log(
unsigned long long types,
unsigned int verbose,
char const* msg,
unsigned int size) throw ();
void open();
void reopen();
void show_pid(bool enable);
void show_timestamp(com::centreon::logging::time_precision val);
void show_thread_id(bool enable);
private:
bool _enable;
concurrency::thread_id _thread;
};
}
CCE_END()
#endif // !CCE_LOGGING_BROKER_HH
| [
"mkermagoret@centreon.com"
] | mkermagoret@centreon.com |
275ebe4d2029b9075693c5dcdf75c7c949d309f5 | c5e1991cee008b77104916da81197ea07c3911d6 | /Problems/EEGSpatioTemporal/Data/DataForEEGSpatioTemporal.cpp | 3c7c7e4ec304fbe0c0f6914c2299195934fae953 | [] | no_license | torms3/hypernetwork | 1be59ae5d077094586a6389a73e85048bac37b29 | 0d30bbcb48373d219fc4a598a79abae2338b246c | refs/heads/master | 2020-08-07T06:36:20.224433 | 2015-03-13T02:40:42 | 2015-03-13T02:40:42 | 32,121,237 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 361 | cpp | //
// Copyright 2011 by
// kslee@bi.snu.ac.kr
// hmlee@bi.snu.ac.kr
//
#include "DataForEEGSpatioTemporal.h"
#include <algorithm>
namespace HN
{
//
// Implementation for Data class
//
EEGData::EEGData(int signal_size, int time_size)
{
m_signal_size = signal_size;
m_time_size = time_size;
}
EEGData::~EEGData()
{
}
} | [
"kisuklee@mit.edu"
] | kisuklee@mit.edu |
1b03d3111889304a9f2629cf71c39fc48334c88d | 04b1803adb6653ecb7cb827c4f4aa616afacf629 | /third_party/skia/gm/fontmgr.cpp | 9290825e1d9ad60fe48d5433af938bd0b37ab7c7 | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0"
] | permissive | Samsung/Castanets | 240d9338e097b75b3f669604315b06f7cf129d64 | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | refs/heads/castanets_76_dev | 2023-08-31T09:01:04.744346 | 2021-07-30T04:56:25 | 2021-08-11T05:45:21 | 125,484,161 | 58 | 49 | BSD-3-Clause | 2022-10-16T19:31:26 | 2018-03-16T08:07:37 | null | UTF-8 | C++ | false | false | 13,435 | cpp | /*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm/gm.h"
#include "include/core/SkCanvas.h"
#include "include/core/SkColor.h"
#include "include/core/SkFont.h"
#include "include/core/SkFontMetrics.h"
#include "include/core/SkFontMgr.h"
#include "include/core/SkFontStyle.h"
#include "include/core/SkFontTypes.h"
#include "include/core/SkGraphics.h"
#include "include/core/SkPaint.h"
#include "include/core/SkPath.h"
#include "include/core/SkPoint.h"
#include "include/core/SkRect.h"
#include "include/core/SkRefCnt.h"
#include "include/core/SkScalar.h"
#include "include/core/SkSize.h"
#include "include/core/SkString.h"
#include "include/core/SkTypeface.h"
#include "include/core/SkTypes.h"
#include "src/core/SkFontPriv.h"
#include "src/utils/SkMetaData.h"
#include "tools/ToolUtils.h"
#include <utility>
// limit this just so we don't take too long to draw
#define MAX_FAMILIES 30
static SkScalar drawString(SkCanvas* canvas, const SkString& text, SkScalar x,
SkScalar y, const SkFont& font) {
canvas->drawString(text, x, y, font, SkPaint());
return x + font.measureText(text.c_str(), text.size(), SkTextEncoding::kUTF8);
}
static SkScalar drawCharacter(SkCanvas* canvas, uint32_t character, SkScalar x,
SkScalar y, const SkFont& origFont, SkFontMgr* fm,
const char* fontName, const char* bcp47[], int bcp47Count,
const SkFontStyle& fontStyle) {
SkFont font = origFont;
// find typeface containing the requested character and draw it
SkString ch;
ch.appendUnichar(character);
sk_sp<SkTypeface> typeface(fm->matchFamilyStyleCharacter(fontName, fontStyle,
bcp47, bcp47Count, character));
font.setTypeface(typeface);
x = drawString(canvas, ch, x, y, font) + 20;
if (nullptr == typeface) {
return x;
}
// repeat the process, but this time use the family name of the typeface
// from the first pass. This emulates the behavior in Blink where it
// it expects to get the same glyph when following this pattern.
SkString familyName;
typeface->getFamilyName(&familyName);
font.setTypeface(fm->legacyMakeTypeface(familyName.c_str(), typeface->fontStyle()));
return drawString(canvas, ch, x, y, font) + 20;
}
static const char* zh = "zh";
static const char* ja = "ja";
class FontMgrGM : public skiagm::GM {
public:
FontMgrGM() {
SkGraphics::SetFontCacheLimit(16 * 1024 * 1024);
fName.set("fontmgr_iter");
fFM = SkFontMgr::RefDefault();
}
protected:
SkString onShortName() override {
return fName;
}
SkISize onISize() override {
return SkISize::Make(1536, 768);
}
void onDraw(SkCanvas* canvas) override {
SkScalar y = 20;
SkFont font;
font.setEdging(SkFont::Edging::kSubpixelAntiAlias);
font.setSubpixel(true);
font.setSize(17);
SkFontMgr* fm = fFM.get();
int count = SkMin32(fm->countFamilies(), MAX_FAMILIES);
for (int i = 0; i < count; ++i) {
SkString familyName;
fm->getFamilyName(i, &familyName);
font.setTypeface(nullptr);
(void)drawString(canvas, familyName, 20, y, font);
SkScalar x = 220;
sk_sp<SkFontStyleSet> set(fm->createStyleSet(i));
for (int j = 0; j < set->count(); ++j) {
SkString sname;
SkFontStyle fs;
set->getStyle(j, &fs, &sname);
sname.appendf(" [%d %d %d]", fs.weight(), fs.width(), fs.slant());
font.setTypeface(sk_sp<SkTypeface>(set->createTypeface(j)));
x = drawString(canvas, sname, x, y, font) + 20;
// check to see that we get different glyphs in japanese and chinese
x = drawCharacter(canvas, 0x5203, x, y, font, fm, familyName.c_str(), &zh, 1, fs);
x = drawCharacter(canvas, 0x5203, x, y, font, fm, familyName.c_str(), &ja, 1, fs);
// check that emoji characters are found
x = drawCharacter(canvas, 0x1f601, x, y, font, fm, familyName.c_str(), nullptr,0, fs);
}
y += 24;
}
}
private:
sk_sp<SkFontMgr> fFM;
SkString fName;
typedef GM INHERITED;
};
class FontMgrMatchGM : public skiagm::GM {
sk_sp<SkFontMgr> fFM;
public:
FontMgrMatchGM() : fFM(SkFontMgr::RefDefault()) {
SkGraphics::SetFontCacheLimit(16 * 1024 * 1024);
}
protected:
SkString onShortName() override {
return SkString("fontmgr_match");
}
SkISize onISize() override {
return SkISize::Make(640, 1024);
}
void iterateFamily(SkCanvas* canvas, const SkFont& font, SkFontStyleSet* fset) {
SkFont f(font);
SkScalar y = 0;
for (int j = 0; j < fset->count(); ++j) {
SkString sname;
SkFontStyle fs;
fset->getStyle(j, &fs, &sname);
sname.appendf(" [%d %d]", fs.weight(), fs.width());
f.setTypeface(sk_sp<SkTypeface>(fset->createTypeface(j)));
(void)drawString(canvas, sname, 0, y, f);
y += 24;
}
}
void exploreFamily(SkCanvas* canvas, const SkFont& font, SkFontStyleSet* fset) {
SkFont f(font);
SkScalar y = 0;
for (int weight = 100; weight <= 900; weight += 200) {
for (int width = 1; width <= 9; width += 2) {
SkFontStyle fs(weight, width, SkFontStyle::kUpright_Slant);
sk_sp<SkTypeface> face(fset->matchStyle(fs));
if (face) {
SkString str;
str.printf("request [%d %d]", fs.weight(), fs.width());
f.setTypeface(std::move(face));
(void)drawString(canvas, str, 0, y, f);
y += 24;
}
}
}
}
DrawResult onDraw(SkCanvas* canvas, SkString* errorMsg) override {
SkFont font;
font.setEdging(SkFont::Edging::kSubpixelAntiAlias);
font.setSubpixel(true);
font.setSize(17);
const char* gNames[] = {
"Helvetica Neue", "Arial", "sans"
};
sk_sp<SkFontStyleSet> fset;
for (size_t i = 0; i < SK_ARRAY_COUNT(gNames); ++i) {
fset.reset(fFM->matchFamily(gNames[i]));
if (fset->count() > 0) {
break;
}
}
if (nullptr == fset.get()) {
*errorMsg = "No SkFontStyleSet";
return DrawResult::kFail;
}
canvas->translate(20, 40);
this->exploreFamily(canvas, font, fset.get());
canvas->translate(150, 0);
this->iterateFamily(canvas, font, fset.get());
return DrawResult::kOk;
}
private:
typedef GM INHERITED;
};
class FontMgrBoundsGM : public skiagm::GM {
public:
FontMgrBoundsGM(double scale, double skew)
: fFM(SkFontMgr::RefDefault())
, fName("fontmgr_bounds")
, fScaleX(SkDoubleToScalar(scale))
, fSkewX(SkDoubleToScalar(skew))
, fLabelBounds(false)
{
if (scale != 1 || skew != 0) {
fName.appendf("_%g_%g", scale, skew);
}
}
bool onGetControls(SkMetaData* controls) override {
controls->setBool("Label Bounds", fLabelBounds);
return true;
}
void onSetControls(const SkMetaData& controls) override {
controls.findBool("Label Bounds", &fLabelBounds);
}
static void show_bounds(SkCanvas* canvas, const SkFont& font, SkScalar x, SkScalar y,
SkColor boundsColor, bool labelBounds)
{
SkRect fontBounds = SkFontPriv::GetFontBounds(font).makeOffset(x, y);
SkPaint boundsPaint;
boundsPaint.setAntiAlias(true);
boundsPaint.setColor(boundsColor);
boundsPaint.setStyle(SkPaint::kStroke_Style);
canvas->drawRect(fontBounds, boundsPaint);
SkFontMetrics fm;
font.getMetrics(&fm);
SkPaint metricsPaint(boundsPaint);
metricsPaint.setStyle(SkPaint::kFill_Style);
metricsPaint.setAlphaf(0.25f);
if ((fm.fFlags & SkFontMetrics::kUnderlinePositionIsValid_Flag) &&
(fm.fFlags & SkFontMetrics::kUnderlineThicknessIsValid_Flag))
{
SkRect underline{ fontBounds.fLeft, fm.fUnderlinePosition+y,
fontBounds.fRight, fm.fUnderlinePosition+y + fm.fUnderlineThickness };
canvas->drawRect(underline, metricsPaint);
}
if ((fm.fFlags & SkFontMetrics::kStrikeoutPositionIsValid_Flag) &&
(fm.fFlags & SkFontMetrics::kStrikeoutThicknessIsValid_Flag))
{
SkRect strikeout{ fontBounds.fLeft, fm.fStrikeoutPosition+y - fm.fStrikeoutThickness,
fontBounds.fRight, fm.fStrikeoutPosition+y };
canvas->drawRect(strikeout, metricsPaint);
}
SkGlyphID left = 0, right = 0, top = 0, bottom = 0;
{
int numGlyphs = font.getTypefaceOrDefault()->countGlyphs();
SkRect min = {0, 0, 0, 0};
for (int i = 0; i < numGlyphs; ++i) {
SkGlyphID glyphId = i;
SkRect cur;
font.getBounds(&glyphId, 1, &cur, nullptr);
if (cur.fLeft < min.fLeft ) { min.fLeft = cur.fLeft; left = i; }
if (cur.fTop < min.fTop ) { min.fTop = cur.fTop ; top = i; }
if (min.fRight < cur.fRight ) { min.fRight = cur.fRight; right = i; }
if (min.fBottom < cur.fBottom) { min.fBottom = cur.fBottom; bottom = i; }
}
}
SkGlyphID str[] = { left, right, top, bottom };
SkPoint location[] = {
{fontBounds.left(), fontBounds.centerY()},
{fontBounds.right(), fontBounds.centerY()},
{fontBounds.centerX(), fontBounds.top()},
{fontBounds.centerX(), fontBounds.bottom()}
};
SkFont labelFont;
labelFont.setEdging(SkFont::Edging::kAntiAlias);
labelFont.setTypeface(ToolUtils::create_portable_typeface());
if (labelBounds) {
SkString name;
font.getTypefaceOrDefault()->getFamilyName(&name);
canvas->drawString(name, fontBounds.fLeft, fontBounds.fBottom, labelFont, SkPaint());
}
for (size_t i = 0; i < SK_ARRAY_COUNT(str); ++i) {
SkPath path;
font.getPath(str[i], &path);
path.offset(x, y);
SkPaint::Style style = path.isEmpty() ? SkPaint::kFill_Style : SkPaint::kStroke_Style;
SkPaint glyphPaint;
glyphPaint.setStyle(style);
canvas->drawSimpleText(&str[i], sizeof(str[0]), SkTextEncoding::kGlyphID, x, y, font, glyphPaint);
if (labelBounds) {
SkString glyphStr;
glyphStr.appendS32(str[i]);
canvas->drawString(glyphStr, location[i].fX, location[i].fY, labelFont, SkPaint());
}
}
}
protected:
SkString onShortName() override {
return fName;
}
SkISize onISize() override {
return SkISize::Make(1024, 850);
}
void onDraw(SkCanvas* canvas) override {
SkFont font;
font.setEdging(SkFont::Edging::kAntiAlias);
font.setSubpixel(true);
font.setSize(100);
font.setScaleX(fScaleX);
font.setSkewX(fSkewX);
const SkColor boundsColors[2] = { SK_ColorRED, SK_ColorBLUE };
SkFontMgr* fm = fFM.get();
int count = SkMin32(fm->countFamilies(), 32);
int index = 0;
SkScalar x = 0, y = 0;
canvas->translate(10, 120);
for (int i = 0; i < count; ++i) {
sk_sp<SkFontStyleSet> set(fm->createStyleSet(i));
for (int j = 0; j < set->count() && j < 3; ++j) {
font.setTypeface(sk_sp<SkTypeface>(set->createTypeface(j)));
// Fonts with lots of glyphs are interesting, but can take a long time to find
// the glyphs which make up the maximum extent.
if (font.getTypefaceOrDefault() && font.getTypefaceOrDefault()->countGlyphs() < 1000) {
SkRect fontBounds = SkFontPriv::GetFontBounds(font);
x -= fontBounds.fLeft;
show_bounds(canvas, font, x, y, boundsColors[index & 1], fLabelBounds);
x += fontBounds.fRight + 20;
index += 1;
if (x > 900) {
x = 0;
y += 160;
}
if (y >= 700) {
return;
}
}
}
}
}
private:
const sk_sp<SkFontMgr> fFM;
SkString fName;
const SkScalar fScaleX;
const SkScalar fSkewX;
bool fLabelBounds;
typedef GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
DEF_GM(return new FontMgrGM;)
DEF_GM(return new FontMgrMatchGM;)
DEF_GM(return new FontMgrBoundsGM(1.0, 0);)
DEF_GM(return new FontMgrBoundsGM(0.75, 0);)
DEF_GM(return new FontMgrBoundsGM(1.0, -0.25);)
| [
"42931768+uzair-jaleel@users.noreply.github.com"
] | 42931768+uzair-jaleel@users.noreply.github.com |
9273677cb3cdf6c409910c6fc784c896e48a9a38 | dd1385ee93b0135f53c705f9d89f7936390a8fd8 | /src/glresource/glresource.h | a69df981c54a22482b40926dc953a57ed3b2f99d | [] | no_license | catompiler/celestial-battle | fcceff6d1551398bda97a62930295986d1217281 | 1998c50867317d71326caec54ecbc47749f71445 | refs/heads/master | 2016-09-05T09:51:32.493447 | 2015-05-09T16:47:44 | 2015-05-09T16:47:44 | 35,336,270 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 338 | h | #ifndef _GLRESOURCE_H
#define _GLRESOURCE_H
#include "opengl/opengl.h"
OPENGL_NAMESPACE_BEGIN
class Resource
{
public:
Resource();
Resource(GLuint id_);
virtual ~Resource();
GLuint id();
operator GLuint();
protected:
GLuint _id;
};
OPENGL_NAMESPACE_END
#endif //_GLRESOURCE_H
| [
"artem.lab@localhost"
] | artem.lab@localhost |
e8bc2b1daa02c06f828018656c5c6fa73dc51912 | 3b27aa7866471739819670d91142e99031e8db59 | /eater.cpp | 33618a601f6e62a4a7b810c6ed8060ad39f2e068 | [] | no_license | krejgo/game-eater | 36260a40449ccf1e890cd0d49924df93b35ad571 | 8a96b17056d579a25eedf76909f7992695c08560 | refs/heads/master | 2021-07-23T01:31:51.461628 | 2017-11-01T00:34:48 | 2017-11-01T00:34:48 | 109,066,821 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,321 | cpp | #include <iostream>
#include <unistd.h>
#include <conio.h>
#include <windows.h>
#include <vector>
using namespace std;
const int border = GetPrivateProfileInt("Settings", "border", 78, "./settings.ini");
const int dropdown = GetPrivateProfileInt("Settings", "dropRange", 60, "./settings.ini");
int ph1L = GetPrivateProfileInt("Settings", "ph1L", 4, "./settings.ini");
int ph2L = GetPrivateProfileInt("Settings", "ph2L", 2, "./settings.ini");
const int K_UP = 72;
const int K_DOWN = 107;
const int K_LEFT = 106;
const int K_RIGHT = 108;
//==============CLASSES============//
#include "player.h"
#include "level.h"
//===========-SUBPROGRAMS==========//
void display (int space);
//===========MAIN PROGRAM==========//
int main() {
int input;
level game;
cout << "Insert snake's length : ";
cin >> input;
player snake(input);
game.setPlayer(&snake);
while(1) {
if (kbhit()) {
switch (getch()) {
case K_RIGHT :
cKey = 1; break;
case K_DOWN :
cKey = 0; break;
case K_LEFT :
cKey = -1; break;
}
}
game.updateFrame();
snake.updatePos();
usleep(25000); // 40 fps
}
return 0;
}
//===========SUBPROGRAMS SOURCE==========//
void display (int space) {
cout << string(space, ' ') << '*' << endl;
}
| [
"noreply@github.com"
] | krejgo.noreply@github.com |
f3499e735b65ef62103804675740a1e10e4a1995 | cf8ddfc720bf6451c4ef4fa01684327431db1919 | /SDK/ARKSurvivalEvolved_DinoCharacterStatusComponent_BP_Shapeshifter_Small_functions.cpp | 622a18ac32fa8eb5064273bee990bc3c764a5ffe | [
"MIT"
] | permissive | git-Charlie/ARK-SDK | 75337684b11e7b9f668da1f15e8054052a3b600f | c38ca9925309516b2093ad8c3a70ed9489e1d573 | refs/heads/master | 2023-06-20T06:30:33.550123 | 2021-07-11T13:41:45 | 2021-07-11T13:41:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,379 | cpp | // ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_DinoCharacterStatusComponent_BP_Shapeshifter_Small_parameters.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function DinoCharacterStatusComponent_BP_Shapeshifter_Small.DinoCharacterStatusComponent_BP_Shapeshifter_Small_C.ExecuteUbergraph_DinoCharacterStatusComponent_BP_Shapeshifter_Small
// ()
// Parameters:
// int EntryPoint (Parm, ZeroConstructor, IsPlainOldData)
void UDinoCharacterStatusComponent_BP_Shapeshifter_Small_C::ExecuteUbergraph_DinoCharacterStatusComponent_BP_Shapeshifter_Small(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function DinoCharacterStatusComponent_BP_Shapeshifter_Small.DinoCharacterStatusComponent_BP_Shapeshifter_Small_C.ExecuteUbergraph_DinoCharacterStatusComponent_BP_Shapeshifter_Small");
UDinoCharacterStatusComponent_BP_Shapeshifter_Small_C_ExecuteUbergraph_DinoCharacterStatusComponent_BP_Shapeshifter_Small_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"sergey.2bite@gmail.com"
] | sergey.2bite@gmail.com |
1e820c8a4fc99de24769b8907d28453a22f1601d | 0f46bca9176f453ea28be8a7c91adfdeee4af3e5 | /src/gui/CameraGUI.cpp | 1f9e6fe51ff53bcbd5d70a4577df1de62e9e693b | [] | no_license | PeterZs/RIM | 3181baf1b668c719ae55dbc0448228d233083cd4 | 81639c2f06b969c668f6d187f6cccf5d97a71ba7 | refs/heads/master | 2022-12-01T04:35:23.344641 | 2020-08-06T07:29:16 | 2020-08-06T07:29:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,365 | cpp | #include "common.h"
#include "gui/CameraGUI.h"
#include "managers/TextureManager.h"
#include <imgui.h>
#include <imgui_impl_glfw.h>
#include <imgui_impl_opengl3.h>
#include <glm/gtc/type_ptr.hpp>
CameraGUI::CameraGUI(CameraFPS* cam)
{
setCamera(cam);
visible = true;
displayname = "Camera options";
}
CameraGUI::~CameraGUI()
{}
void CameraGUI::setCamera(CameraFPS* cam)
{
this->camptr = cam;
}
void CameraGUI::draw(GLFWwindow* window, int order)
{
if (!camptr) return;
ImVec2 outerSize = ImGui::GetItemRectSize();
bool dirty = false;
if (ImGui::DragFloat3("Position", glm::value_ptr(camptr->position), 0.01f + abs(glm::length(camptr->position) / 100.f ) )) dirty = true;
//if (ImGui::DragFloat3("Orientation", glm::value_ptr(m.gl.diffuse), 0.01f, 0.0f, 1e12f)) dirty = true;
if (ImGui::DragFloat("Vertical FOV", &camptr->verticalFov_deg, 0.05f, 0.0f, 180.f)) dirty = true;
if (ImGui::DragFloat("Near", &camptr->nearplane, 0.0001f + camptr->nearplane / 100.f, 0.00001f, camptr->farplane - 0.0001f)) dirty = true;
if (ImGui::DragFloat("Far", &camptr->farplane, 0.0001f + camptr->farplane / 100.f, camptr->nearplane + 0.0001f, 1e12f)) dirty = true;
if (ImGui::DragFloat("Rotation speed", &camptr->rot_speed, 0.001f, 0.0f, 100.f)) dirty = true;
if (ImGui::DragFloat("Motion speed", &camptr->mov_speed, 0.001f, 0.0f, 100.f)) dirty = true;
} | [
"RotateMe@gmail.com"
] | RotateMe@gmail.com |
4ec7c7b6244f59d63d37e435501164d9184e9b21 | fd094d2a03926ec1b5901cc2b54544aa1126d324 | /AOIS6/AOIS6/main.cpp | 3a8726a6553aaf5fba34594f5ac6759e643e009d | [] | no_license | LastStranger0/AOIS | 154a2574d567853fefd963174d95dc3737658f98 | 7b6953e6a987d996557ecce122a59376561adb55 | refs/heads/master | 2020-08-02T07:14:22.712938 | 2019-12-24T14:51:49 | 2019-12-24T14:51:49 | 211,273,251 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 7,561 | cpp | #include <iostream>
#include <vector>
#include <string>
#include <forward_list>
using namespace std;
struct hesh
{
string id;
int value;
int hesh_code;
bool collision;
bool unaval;
bool terminal;
bool delining;
hesh* next;
string data;
};
int alpha(char);
int get_value(string);
int get_hesh(int, int);
void add_el(vector <hesh>&, string, string);
void del_el(vector <hesh>&, string);
void print_search_el(vector <hesh>, string);
void print_table(vector <hesh>);
int main()
{
setlocale(LC_ALL, "Russian");
vector <hesh> table;
add_el(table, "Самолёт", "Воздушный");
add_el(table, "Лодка", "Водный");
add_el(table, "Караван", "Наземный");
add_el(table, "Дирижабль", "Воздушный");
add_el(table, "Автомобиль", "Наземный");
add_el(table, "Катер", "Водный");
add_el(table, "Труба", "Трубопроводный");
add_el(table, "Челнок", "Космический");
add_el(table, "Яхта", "Водный");
add_el(table, "Поезд", "Наземный");
add_el(table, "Вертолёт", "Воздушный");
add_el(table, "Электричка", "Наземный");
add_el(table, "Воздушный шар", "Воздушный");
add_el(table, "Велосипед", "Наземный");
add_el(table, "Судно", "Водный");
add_el(table, "Лифт", "Наземный");
add_el(table, "Лошадь", "Наземный");
add_el(table, "Автобус", "Наземный");
add_el(table, "Парусник", "Водный");
add_el(table, "Эскалатор", "Наземный");
add_el(table, "Тут уже", "Воздушный");
add_el(table, "Заканчивается фантазия", "Водный");
add_el(table, "Квадракоптер", "Воздушный");
add_el(table, "Лошадь", "Наземный");
print_table(table);
del_el(table, "Поезд");
cout << endl << endl;
print_table(table);
cout << endl;
print_search_el(table, "Самолёт");
cout << endl;
system("pause");
return 0;
}
int alpha(char symb)
{
if (symb == 'а' || symb == 'А')
{
return 1;
}
else if (symb == 'б' || symb == 'Б')
{
return 2;
}
else if (symb == 'в' || symb == 'В')
{
return 3;
}
else if (symb == 'г' || symb == 'Г')
{
return 4;
}
else if (symb == 'д' || symb == 'Д')
{
return 5;
}
else if (symb == 'е' || symb == 'Е')
{
return 6;
}
else if (symb == 'ё' || symb == 'Ё')
{
return 7;
}
else if (symb == 'ж' || symb == 'Ж')
{
return 8;
}
else if (symb == 'з' || symb == 'З')
{
return 9;
}
else if (symb == 'и' || symb == 'И')
{
return 10;
}
else if (symb == 'й' || symb == 'Й')
{
return 11;
}
else if (symb == 'к' || symb == 'К')
{
return 12;
}
else if (symb == 'л' || symb == 'Л')
{
return 13;
}
else if (symb == 'м' || symb == 'М')
{
return 14;
}
else if (symb == 'н' || symb == 'Н')
{
return 15;
}
else if (symb == 'о' || symb == 'О')
{
return 16;
}
else if (symb == 'п' || symb == 'П')
{
return 17;
}
else if (symb == 'р' || symb == 'Р')
{
return 18;
}
else if (symb == 'с' || symb == 'С')
{
return 19;
}
else if (symb == 'т' || symb == 'Т')
{
return 20;
}
else if (symb == 'у' || symb == 'у')
{
return 21;
}
else if (symb == 'ф' || symb == 'Ф')
{
return 22;
}
else if (symb == 'х' || symb == 'Х')
{
return 23;
}
else if (symb == 'ц' || symb == 'Ц')
{
return 24;
}
else if (symb == 'ч' || symb == 'Ч')
{
return 25;
}
else if (symb == 'ш' || symb == 'Ш')
{
return 26;
}
else if (symb == 'щ' || symb == 'Щ')
{
return 27;
}
else if (symb == 'ь' || symb == 'Ь')
{
return 28;
}
else if (symb == 'ъ' || symb == 'Ъ')
{
return 29;
}
else if (symb == 'ы' || symb == 'Ы')
{
return 30;
}
else if (symb == 'э' || symb == 'Э')
{
return 31;
}
else if (symb == 'ю' || symb == 'Ю')
{
return 32;
}
else if (symb == 'я' || symb == 'Я')
{
return 33;
}
else
{
return -9999999999;
}
}
int get_value(string str)
{
int value = 0;
int range;
if (str.size() >= 3)
{
range = 3;
}
else
{
range = str.size();
}
for (size_t i = 0; i < range; i++)
{
value += 33 * alpha(str[i]);
}
return value;
}
int get_hesh(int V, int B)
{
int val = V % 10 + B;
return val;
}
void add_el(vector <hesh>& ref, string id, string data)
{
int val = get_value(id);
int hsh = get_hesh(val, ref.size());
hesh boof;
bool is = false;
for (size_t i = 0; i < ref.size(); i++)
{
if (hsh == ref[i].hesh_code)
{
ref[i].collision = true;
hesh* ptr = &ref[i];
while (ptr->next != NULL)
{
ptr = ptr->next;
}
ptr->next = new hesh;
ptr = ptr->next;
ptr->data = data;
ptr->next = NULL;
ptr->id = id;
ptr->value = val;
ptr->hesh_code = hsh;
ptr->collision = true;
ptr->unaval = true;
ptr->terminal = 0;
ptr->delining = false;
is = true;
}
}
if (!is)
{
boof.data = data;
boof.next = NULL;
boof.id = id;
boof.value = val;
boof.hesh_code = hsh;
boof.collision = false;
boof.unaval = true;
boof.terminal = 0;
boof.delining = false;
ref.push_back(boof);
}
}
void del_el(vector <hesh>& ref, string id)
{
for (int i = 0; i < ref.size(); i++)
{
if (ref[i].collision == 1)
{
hesh* ptr = &ref[i];
while (ptr->next != NULL)
{
if (ptr->next->id == id && ptr->next->next == NULL)
{
ptr->next = NULL;
}
else if (ptr->next->id == id && ptr->next->next != NULL)
{
ptr->next = ptr->next->next;
}
else
{
ptr = ptr->next;
}
}
}
else if (ref[i].id == id)
{
ref.erase(ref.begin() + i);
}
}
}
void print_search_el(vector <hesh> ref, string id)
{
hesh srch;
for (int i = 0; i < ref.size(); i++)
{
if (ref[i].collision == 1)
{
hesh* ptr = &ref[i];
while (id != ptr->id && ptr->next != NULL)
{
ptr = ptr->next;
}
if (id == ptr->id)
{
cout << ptr->data;
}
}
else if (ref[i].id == id)
{
cout << ref[i].data;
}
}
}
void print_table(vector <hesh> ref)
{
cout << "id" <<
", " << "value" <<
", " << "hesh_code" <<
", " << "collision" <<
", " << "unaval" <<
", " << "terminal" <<
", " << "delining" <<
", " << "next" <<
", " << "data" << endl << endl;
for (size_t i = 0; i < ref.size(); i++)
{
cout << ref[i].id <<
'\t' << ref[i].value <<
'\t' << ref[i].hesh_code <<
'\t' << ref[i].collision <<
'\t' << ref[i].unaval <<
'\t' << ref[i].terminal <<
'\t' << ref[i].delining <<
'\t' << ref[i].next <<
'\t' << ref[i].data << endl;
if (ref[i].next != NULL)
{
cout << endl <<
"******************COLLISION SECTOR*******************" << endl;
hesh* ptr;
ptr = ref[i].next;
while (ptr != NULL)
{
cout << ptr->id <<
'\t' << ptr->value <<
'\t' << ptr->hesh_code <<
'\t' << ptr->collision <<
'\t' << ptr->unaval <<
'\t' << ptr->terminal <<
'\t' << ptr->delining <<
'\t' << ptr->next <<
'\t' << ptr->data << endl;
ptr = ptr->next;
}
cout << endl <<
"*****************************************************" << endl;
}
}
}
| [
"noreply@github.com"
] | LastStranger0.noreply@github.com |
49cc94b37ba61f252668bd58e8ab83adf3fac01c | 0c1da14e754ea8f2c558262e7ae920dca6c0dd9c | /matrix_object/main.cpp | 7399b9f8da150221ab42cf93562eac2f30aff50b | [] | no_license | risentveber/Old-code | 02d10bd3eb041f4ebc300b97732dfa78461e0d74 | 11fae95894891903bf261db7cdf7d8b8e7489880 | refs/heads/master | 2021-01-10T05:14:42.868148 | 2019-11-23T12:16:50 | 2019-11-23T12:16:50 | 45,670,454 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 120 | cpp | #include "matrix.h"
int main(){
matrix one;
matrix two;
one.input();
two.input();
one = one*3;
one.output();
}
| [
"risentveber@gmail.com"
] | risentveber@gmail.com |
fbbfaad6e91852e5b5490df04523b0f1282547e2 | 754cc9e0424740907af49075f7c1eb6c7cbdcf91 | /common/Table/Table_NpcOptionalSkill.h | 6a6b6eabfb5d2ec449f1f20d32e4426fc5407b66 | [] | no_license | zhaojinwei0124/Project-RC_Server | 2d0906bed6406ef02e83cb9260746ccd23c0996e | b9ccb3e0476d7c562a4affb25d247e87c8aed1be | refs/heads/master | 2021-01-21T15:38:14.408311 | 2017-01-26T03:16:29 | 2017-01-26T03:16:29 | 81,521,050 | 0 | 2 | null | 2017-02-10T03:12:07 | 2017-02-10T03:12:07 | null | UTF-8 | C++ | false | false | 1,401 | h | //This code create by CodeEngine,don't modify
#ifndef _NpcOptionalSkillTABLE_H
#define _NpcOptionalSkillTABLE_H
#include "DBCTable.h"
class Table_NpcOptionalSkill:public DBC_Recorder_Loader<Table_NpcOptionalSkill,99999,500>
{
public:
enum _ID
{
INVLAID_INDEX=-1,
ID_SKILLID,
ID_SELETARGETLOGIC=2,
ID_ACTIVATELOGIC,
ID_ACTIVATEPARAM1,
ID_ACTIVATEPARAM2,
ID_TAB_CURCOL_COUNT,
MAX_ID=99999,
MAX_RECORD=500
};
public:
bool __Load(DBC_Loader &loader);
private:
tint32 m_ActivateLogic;
public:
tint32 GetActivateLogic() const { return m_ActivateLogic; }
public:
tint32 getActivateParamCount() const { return 2; }
private:
tint32 m_ActivateParam[2];
public:
tint32 GetActivateParambyIndex(tint32 idx) const
{
if(idx>=0 && idx<2) return m_ActivateParam[idx];
return -1;
}
private:
tint32 m_SeleTargetLogic;
public:
tint32 GetSeleTargetLogic() const { return m_SeleTargetLogic; }
private:
tint32 m_SkillId;
public:
tint32 GetSkillId() const { return m_SkillId; }
};
DECL_TABLE_FUNCTIONS(Table_NpcOptionalSkill);
//bool InitTable_NpcOptionalSkillTable( const tchar* szFileName );
//bool InitTable_NpcOptionalSkillTableFromMemory( const DBCFile& rDB );
//const Table_NpcOptionalSkill* GetTable_NpcOptionalSkillByID(tint32 id);
//const Table_NpcOptionalSkill* GetTable_NpcOptionalSkillByIndex(tint32 index);
//tint32 GetTable_NpcOptionalSkillCount(void);
#endif
| [
"bu213200@gmail.com"
] | bu213200@gmail.com |
68192a75cf30157f16d1880680a85b52c4f9a021 | 5f3ba1affc395e24a762fe488b72bf9ae219e145 | /ScoreManager.h | ef26d7f65f72953907163f2fa0ec0ffa8f5b9aa0 | [] | no_license | Kawazuini/PurPose | a9e01acc35b6a64e82809d5235dc0c9d58807721 | d019887fc19cb22136dc6c16b14ced2461fa7aa1 | refs/heads/master | 2020-06-22T03:24:03.679572 | 2017-08-21T10:27:48 | 2017-08-21T10:27:48 | 74,759,709 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,753 | h | /**
* @file ScoreManager.h
* @brief ScoreManager
* @author Maeda Takumi
*/
#ifndef SCOREMANAGER_H
#define SCOREMANAGER_H
#include "GameState.h"
/**
* @brief \~english management of game score
* @brief \~japanese ゲームスコア管理
* @author \~ Maeda Takumi
*/
class ScoreManager final {
private:
/* ランキングファイル名 */ static const String RANK_FILE_NAME;
/* ランキングファイル */ KFile mFile;
/* 得点情報 */
struct Score {
/* 得点 */ int mScore;
/* 名前 */ String mName;
/* 詳細 */ String mBrief;
};
/* スコアランキング */ Vector<Score> mRanking;
public:
ScoreManager();
~ScoreManager() = default;
/**
* \~english
* @brief draw score.
* @param aUI drawing target
* @param aRank rank information
* \~japanese
* @brief 得点を描画します。
* @param aUI 描画対象
* @param aRank 順位情報
*/
void draw(KGLUI& aUI,const int& aRank) const;
/**
* \~english
* @brief add new score
* @param aState game state
* @param aClear clear flag
* @return score rank
* \~japanese
* @brief 新しいスコアを追加します。
* @param aState ゲーム状態
* @param aClear クリアフラグ
* @return 順位
*/
int newScore(const GameState& aState, const bool& aClear = false);
/**
* \~english
* @brief calc score
* @param aState game state
* @return score
* \~japanese
* @brief スコアを計算します。
* @param aState ゲーム状態
* @return スコア
*/
static int calcScore(const GameState& aState);
};
#endif /* SCOREMANAGER_H */
| [
"kawazuini@gmail.com"
] | kawazuini@gmail.com |
4f99c2ea1f2375f0d354ec7714cee924c54371b9 | e983a641073f855fc613e5dc799f83104bd11663 | /binarySortTree/二叉排序树.cpp | f0cbfae4b3beeccf26f16a4ef90e3c9c3749ff85 | [] | no_license | AlbertMP/BinarySortTree | 4c79cea89e8688f7c98f8d0f1ea42d1a5ff627bc | 319f171ef394355a3469c051f6b75301f565fd4d | refs/heads/master | 2020-05-26T12:57:56.107585 | 2019-05-23T14:10:50 | 2019-05-23T14:10:50 | 188,239,609 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,549 | cpp | //
// main.cpp
// binarySortTree
//
// Created by 苗芃 on 2019/3/23.
// Copyright © 2019 苗芃. All rights reserved.
//
//【选做内容】
// (1) 创建一棵二叉排序树;
// (2) 查找二叉排序树中一个指定结点;
// (3) 输出查找指定结点过程中所需比较的次数。
#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define TRUE 1
#define OVERFLOW -2
#define FALSE 0
#define ERROR 0
#define MAXSIZE 100
typedef bool Status;
typedef int KeyType;
typedef struct{
KeyType key; // 用于存放编码
}ElemType;
typedef struct BiTNode{
ElemType data; // 结点的数据域
struct BiTNode *lchild, *rchild; // 左右孩子指针
}BiTNode, *BiTree;
int count=0;
BiTree SearchBST(BiTree T, KeyType key){
if ((!T)||(key==T->data.key)){
count++;
printf("查找成功!\n");
printf("查找次数:%d\n",count);
printf("要查找的节点及其后续子节点为:\n");
return T;
}
else if (key<T->data.key){
count++;
return SearchBST(T->lchild, key);
}
else{
count++;
return SearchBST(T->rchild, key);
}
}
Status RSearchBST(BiTree T, KeyType key, BiTree f, BiTree &p){
// 返回插入位置的二叉排序树查找算法
if (!T) {p = f; return FALSE;} // 查找不成功
else if (key == T->data.key){ p=T; return TRUE;} // 查找成功
else if (key < T->data.key) return RSearchBST(T->lchild, key, T, p); // 在左子树中继续查找
else return RSearchBST(T->rchild, key, T, p); // 在右子树中继续查找
}
Status InsertBST(BiTree &T, ElemType e){
// 在二叉排序树中插入关键字值为key, 记录为e的新结点
// 若成功,则返回TRUE;否则返回FAISE
BiTree p,s;
if (!RSearchBST(T, e.key, NULL, p)) {
s=(BiTree)malloc(sizeof(BiTNode));
s->data=e;
s->lchild=s->rchild=NULL;
if (!p) T=s;
else if (e.key<p->data.key) p->lchild=s;
else p->rchild=s;
return TRUE;
}
else
return FALSE;
}
Status CreateBST(BiTree &T, ElemType items[], int n){
for (int i=0; i<n; i++) {
InsertBST(T, items[i]); // 调用二叉排序树的插入算法
}
printf("创建完成!\n");
return OK;
}
void PreRootTraverse(BiTree T){
// 先序遍历
if (T!=NULL) {
printf("%d ",T->data.key);
PreRootTraverse(T->lchild);
PreRootTraverse(T->rchild);
}
}
void InRootTraverse(BiTree T){
// 中序遍历
if (T!=NULL) {
InRootTraverse(T->lchild);
printf("%d ", T->data.key);
InRootTraverse(T->rchild);
}
}
Status IsSame(ElemType array[], int count){
for (int i=0; i<count; i++) {
int temp = array[i].key;
for (int j=i+1; j<count; j++) {
if (temp==array[j].key) {
return TRUE;
}
}
}
return FALSE;
}
int levelOfNode(BiTree T, KeyType key){
int n = 1;
BiTree q;
q=T;
if (T==NULL)
return 0; // 空树
while (q) {
if (key==q->data.key) {
return n;
}else{
if (key<q->data.key)
q=q->lchild;
else
q=q->rchild;
n++;
}
}
return -1; // 不存在,未查询到
}
void Menu(){
printf("-----二叉排序树的操作-----\n");
printf("请选择要进行的操作:(1-5)\n");
printf("1. 生成二叉树\n");
printf("2. 中序遍历二叉树\n");
printf("3. 先序遍历二叉树\n");
printf("4. 查找节点\n");
printf("5. 退出进程\n");
printf("-----------------------\n");
}
int main() {
Menu();
int operation;
while (true) {
BiTree T;
printf("选择你的操作:");
scanf("%d",&operation);
switch (operation) {
case 1:
int count, n;
printf("-----------------------\n");
printf("创建开始,请输入元素个数:");
scanf("%d", &count);
printf("输入元素:\n");
ElemType items[count];
for (int i=0; i<count; i++) {
scanf("%d",&n);
items[i].key=n;
}
if (IsSame(items, count)) {
printf("输入的元素不允许重复!\n");
printf("-----------------------\n");
break;
}
// ElemType items[7]={2,4,1,3,6,7,5};
CreateBST(T, items, count);
printf("-----------------------\n");
break;
case 2:
// if (T==NULL) {
// printf("请先建立二叉排序树!\n");
// printf("-----------------------\n");
// break;
// }
printf("-----------------------\n");
printf("中序遍历:\n");
InRootTraverse(T);
printf("\n");
printf("-----------------------\n");
break;
case 3:
// if (T==NULL) {
// printf("请先建立二叉排序树!\n");
// printf("-----------------------\n");
// break;
// }
printf("-----------------------\n");
printf("先序遍历:\n");
PreRootTraverse(T);
printf("\n");
printf("-----------------------\n");
break;
case 4:
// if (T==NULL) {
// printf("请先建立二叉排序树!\n");
// printf("-----------------------\n");
// break;
// }
printf("-----------------------\n");
printf("请输入要查找的节点:");
int findnum;
scanf("%d",&findnum);
PreRootTraverse(SearchBST(T, findnum));
printf("\n");
printf("该节点位于第%d层。\n",levelOfNode(T, findnum));
printf("-----------------------\n");
break;
case 5:
printf("再会!\n");
return 0;
default:
printf("请输入正确的操作码!\n");
printf("-----------------------\n");
printf("选择你的操作:");
break;
}
}
}
| [
"2570869891@qq.com"
] | 2570869891@qq.com |
8d9c9edfdd27cc93dd576f4d4e628a5dffa4f71a | 55863c34d5ad8f893fd8506babb775bd5af7f4a0 | /BeatmapConvert/Mania.Pattern.cpp | a0d17e509c3899b081d04cd5aa1ac9bb2b64175e | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | HO-COOH/Osu12Jumper | bb401b01a7d3ce59bd5d1a6c5879941a1f832437 | 5f4ae438edda4a559d7844faf003918937ffe53f | refs/heads/master | 2023-09-04T12:07:11.775763 | 2021-11-11T09:30:27 | 2021-11-11T09:30:27 | 282,067,933 | 0 | 0 | null | 2021-11-11T09:30:28 | 2020-07-23T22:19:56 | HTML | UTF-8 | C++ | false | false | 2,261 | cpp | #include "include/Mania.Pattern.hpp"
#include <unordered_set>
#include <algorithm>
bool Mania::Pattern::colunmHasObject(int column) const
{
return std::any_of(hitObjects.cbegin(), hitObjects.cend(), [column, this](auto const& objPtr) { return objPtr->getColumnIndex(totalColumn) == column; });
}
int Mania::Pattern::numColumnWithObject() const
{
std::unordered_set<int> column;
for (auto const& hitObject : hitObjects)
column.insert(hitObject->getColumnIndex(totalColumn));
return static_cast<int>(column.size());
}
Mania::Pattern& Mania::Pattern::operator+=(std::unique_ptr<HitObject>&& hitObject)
{
hitObjects.emplace_back(std::move(hitObject));
return *this;
}
Mania::Pattern& Mania::Pattern::operator+=(Pattern&& pattern)
{
hitObjects.reserve(hitObjects.size() + pattern.hitObjects.size());
//hitObjects.insert(hitObjects.end(), pattern.hitObjects.begin(), pattern.hitObjects.end());
std::move(pattern.hitObjects.begin(), pattern.hitObjects.end(), std::back_inserter(hitObjects));
pattern.hitObjects.clear();
return *this;
}
std::ostream& Mania::operator<<(std::ostream& os, Pattern::Type type)
{
if (type == Pattern::Type::None)
{
os << "None";
return os;
}
Pattern::Type const copy = type;
for (int i = 1; i < sizeof(type) * 8; ++i)
{
reinterpret_cast<unsigned&>(type) &= (1 << (i - 1));
if (type & Pattern::Type::ForceStack)
os << "ForceStack, ";
else if (type & Pattern::Type::ForceNotStack)
os << "ForceNotStack, ";
else if (type & Pattern::Type::KeepSingle)
os << "KeepSingle, ";
else if (type & Pattern::Type::LowProbability)
os << "LowProbability, ";
else if (type & Pattern::Type::Alternate)
os << "Alternate, ";
else if (type & Pattern::Type::ForceSigSlider)
os << "ForceSigSlider, ";
else if (type & Pattern::Type::ForceNotSlider)
os << "ForceNotSlider, ";
else if (type & Pattern::Type::Gathered)
os << "Gathered, ";
else if (type & Pattern::Type::Mirror)
os << "Mirror, ";
else if (type & Pattern::Type::Reverse)
os << "Reverse, ";
else if (type & Pattern::Type::Cycle)
os << "Cycle, ";
else if (type & Pattern::Type::Stair)
os << "Stair, ";
else if (type & Pattern::Type::ReverseStair)
os << "ReverseStair, ";
type = copy;
}
return os;
}
| [
"noreply@github.com"
] | HO-COOH.noreply@github.com |
5379fec7b306c6831cf2023d1ad04783bf42cadc | 44846a44741833c1887f73b0a0b809f8f327e3d6 | /Greg/MIDIUtils.h | 8762eae40e876a641e9969236f771eafd709224b | [] | no_license | bmelts/greg | 296084da2bedc19f3420a2eb70e3edb91af44756 | a946523f5f5140f8911e6cdc593c5266aef457d2 | refs/heads/master | 2020-05-17T08:02:34.242736 | 2012-05-02T08:48:25 | 2012-05-02T08:48:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,184 | h | /*
* Greg/MIDIUtils.h
*
* Copyright (c) 2011-2012 Bill Meltsner
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the author be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#ifndef Greg_MIDIUtils_h
#define Greg_MIDIUtils_h
#include <string>
struct Note {
uint8_t midiNote;
uint8_t velocity;
uint8_t channel;
double timestamp;
std::string pitch();
Note * copy();
};
double getNoteLength(std::string code);
#endif
| [
"bill@meltsner.com"
] | bill@meltsner.com |
234bea3778dfc2444e01cc32cc0f7c7bb32a1940 | 711e5c8b643dd2a93fbcbada982d7ad489fb0169 | /XPSP1/NT/inetsrv/iis/iisrearc/iisplus/ulatq/wprecycler.cxx | d9486d58044eb0775d21bf592f24263fdd77245e | [] | no_license | aurantst/windows-XP-SP1 | 629a7763c082fd04d3b881e0d32a1cfbd523b5ce | d521b6360fcff4294ae6c5651c539f1b9a6cbb49 | refs/heads/master | 2023-03-21T01:08:39.870106 | 2020-09-28T08:10:11 | 2020-09-28T08:10:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,609 | cxx | /*++
Copyright (c) 1998 Microsoft Corporation
Module Name :
wprecycler.cxx
Abstract:
Implementation of WP_RECYCLER. Object handles worker process recycling
- Memory based recycling
- Schedule based recycling
- Elapsed Time based recycling
- Processed Request Count based recycling
Dependencies:
g_pwpContext is used by WP_RECYCLER to be able to send messages
Author:
Jaroslav Dunajsky (JaroslaD) 07-Dec-2000
Environment:
Win32 - User Mode
Project:
W3DT.DLL
--*/
#include "precomp.hxx"
#include "wprecycler.hxx"
#define ONE_DAY_IN_MILLISECONDS (1000 * 60 * 60 * 24)
//
// Static variables
//
CRITICAL_SECTION WP_RECYCLER::sm_CritSec;
//
// Static variables for Memory based recycling
//
HANDLE WP_RECYCLER::sm_hTimerForMemoryBased = NULL;
BOOL WP_RECYCLER::sm_fIsStartedMemoryBased = FALSE;
SIZE_T WP_RECYCLER::sm_MaxValueForMemoryBased = 0;
HANDLE WP_RECYCLER::sm_hCurrentProcess = NULL;
//
// Static variables for Time based recycling
//
HANDLE WP_RECYCLER::sm_hTimerForTimeBased = NULL;
BOOL WP_RECYCLER::sm_fIsStartedTimeBased = FALSE;
//
// Static variables for Schedule based recycling
//
HANDLE WP_RECYCLER::sm_hTimerQueueForScheduleBased = NULL;
BOOL WP_RECYCLER::sm_fIsStartedScheduleBased = FALSE;
//
// Static variables for Request based recycling
//
BOOL WP_RECYCLER::sm_fIsStartedRequestBased = FALSE;
DWORD WP_RECYCLER::sm_dwMaxValueForRequestBased = 0;
LONG WP_RECYCLER::sm_RecyclingMsgSent = 0;
BOOL WP_RECYCLER::sm_fCritSecInit = FALSE;
//
// Static methods for Schedule based recycling
//
//static
HRESULT
WP_RECYCLER::StartScheduleBased(
IN const WCHAR * pwszScheduleTimes
)
/*++
Routine Description:
Start schedule based recycling
Arguments:
pwszScheduleTimes - MULTISZ array of time information
<time>\0<time>\0\0
time is of military format hh:mm
(hh>=0 && hh<=23)
(mm>=0 && hh<=59)
Return Value:
HRESULT
--*/
{
HRESULT hr = E_FAIL;
BOOL fRet = FALSE;
const WCHAR * pwszCurrentChar = pwszScheduleTimes;
HANDLE hTimer;
WORD wHours = 0;
WORD wMinutes = 0;
WORD wDigitCount = 0;
SYSTEMTIME SystemTime;
FILETIME FileTime;
FILETIME CurrentFileTime;
ULARGE_INTEGER largeintCurrentTime;
ULARGE_INTEGER largeintTime;
DWORD dwDueTime = 0;
DBG_ASSERT(TRUE == sm_fCritSecInit);
EnterCriticalSection( &WP_RECYCLER::sm_CritSec );
IF_DEBUG( WPRECYCLER )
{
DBGPRINTF(( DBG_CONTEXT,
"WP_RECYCLER::StartScheduleBased()\n"));
}
DBG_ASSERT( pwszScheduleTimes != NULL );
//
// If scheduler based recycling has been running already
// terminate it before restarting with new settings
//
if ( WP_RECYCLER::sm_fIsStartedScheduleBased )
{
WP_RECYCLER::TerminateScheduleBased();
}
WP_RECYCLER::sm_hTimerQueueForScheduleBased = CreateTimerQueue();
if ( WP_RECYCLER::sm_hTimerQueueForScheduleBased == NULL )
{
hr = HRESULT_FROM_WIN32( GetLastError() );
goto Failed;
}
//
// Gets current time
//
GetLocalTime( &SystemTime );
SystemTimeToFileTime( &SystemTime,
&CurrentFileTime );
memcpy( &largeintCurrentTime,
&CurrentFileTime,
sizeof( ULARGE_INTEGER ) );
//
// empty string in MULTISZ indicates the end of MULTISZ
//
while ( *pwszCurrentChar != '\0' )
{
//
// Skip white spaces
//
while ( iswspace( (wint_t) *pwszCurrentChar ) )
{
pwszCurrentChar++;
}
//
// Start of the time info
// Expect military format hh:mm
//
//
// Process hours (up to 2 digits is valid)
//
wHours = 0;
wDigitCount = 0;
while ( iswdigit( *pwszCurrentChar ) )
{
wDigitCount++;
wHours = 10 * wHours + (*pwszCurrentChar - '0');
pwszCurrentChar++;
}
if ( wDigitCount > 2 ||
( wHours > 23 ) )
{
hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER );
goto Failed;
}
//
// Hours - minutes separator
// Be liberal - any character that is not a digit or '\0' is OK
//
if ( *pwszCurrentChar == '\0' )
{
hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER );
goto Failed;
}
pwszCurrentChar++;
//
// Process minutes (must be exactly 2 digits)
//
wMinutes = 0;
wDigitCount = 0;
while ( iswdigit( (wint_t) *pwszCurrentChar ) )
{
wDigitCount++;
wMinutes = 10 * wMinutes + (*pwszCurrentChar - '0');
pwszCurrentChar++;
}
if ( ( wDigitCount != 2 ) ||
( wMinutes > 59 ) )
{
hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER );
goto Failed;
}
//
// Skip white spaces
//
while ( iswspace( (wint_t)*pwszCurrentChar ) )
{
pwszCurrentChar++;
}
//
// Check for terminating zero
//
if ( *pwszCurrentChar != '\0' )
{
//
// Extra characters in the time string
//
hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER );
goto Failed;
}
pwszCurrentChar++;
//
// Convert Hours and Minutes info
//
SystemTime.wHour = wHours;
SystemTime.wMinute = wMinutes;
SystemTime.wSecond = 0;
SystemTime.wMilliseconds = 0;
SystemTimeToFileTime( &SystemTime,
&FileTime );
memcpy( &largeintTime,
&FileTime,
sizeof(ULARGE_INTEGER) );
//
// Issue 12/21/2000 jaroslad:
// This method of setting absolute time with CreateTimerQueueTimer
// is bad since instead of setting absolute time the relative time is
// calculated and used for timer.
// This approach fails badly if someone changes machine
// time. Other Api that enables setting abolute time must be used for proper
// implementation
//
// Get Due Time in milliseconds
//
dwDueTime = static_cast<DWORD>(
( largeintTime.QuadPart - largeintCurrentTime.QuadPart )/ 10000);
if ( largeintTime.QuadPart < largeintCurrentTime.QuadPart)
{
dwDueTime = ONE_DAY_IN_MILLISECONDS - static_cast<DWORD>(
( largeintCurrentTime.QuadPart - largeintTime.QuadPart )/ 10000);
}
else
{
dwDueTime = static_cast<DWORD>(
( largeintTime.QuadPart - largeintCurrentTime.QuadPart )/ 10000);
}
if ( dwDueTime == 0 )
{
//
// this event is to be scheduled for the next day
// one day has 1000 * 60 * 60 * 24 of (100-nanosecond intervals)
//
dwDueTime += ONE_DAY_IN_MILLISECONDS;
}
//
// Schedule event for specified time, repeating once a day
//
IF_DEBUG( WPRECYCLER )
{
DBGPRINTF(( DBG_CONTEXT,
"Schedule recycling for %d:%d (in %d milliseconds)\n",
(int) wHours,
(int) wMinutes,
dwDueTime));
}
fRet = CreateTimerQueueTimer(
&hTimer,
WP_RECYCLER::sm_hTimerQueueForScheduleBased,
WP_RECYCLER::TimerCallbackForScheduleBased,
NULL,
dwDueTime,
// repeat daily (interval in milliseconds)
ONE_DAY_IN_MILLISECONDS,
WT_EXECUTELONGFUNCTION );
if ( !fRet )
{
hr = HRESULT_FROM_WIN32( GetLastError() );
goto Failed;
}
//
// hTimer will not be stored
// sm_hTimerQueueForScheduleBased is going to be used for cleanup
// DeleteTimerQueueEx() should be able to correctly delete all timers
// in the queue
//
}
WP_RECYCLER::sm_fIsStartedScheduleBased = TRUE;
LeaveCriticalSection( &WP_RECYCLER::sm_CritSec );
return S_OK;
Failed:
WP_RECYCLER::TerminateScheduleBased();
DBG_ASSERT( FAILED( hr ) );
IF_DEBUG( WPRECYCLER )
{
DBGPRINTF(( DBG_CONTEXT,
"WP_RECYCLER::StartScheduleBased() failed with error hr=0x%x\n",
hr ));
}
LeaveCriticalSection( &WP_RECYCLER::sm_CritSec );
return hr;
}
//static
VOID
WP_RECYCLER::TerminateScheduleBased(
VOID
)
/*++
Routine Description:
Stops schedule based recycling
Performs cleanup
Note:
It is safe to call this method for cleanup if Start failed
Arguments:
NONE
Return Value:
VOID
--*/
{
HRESULT hr = E_FAIL;
DBG_ASSERT(TRUE == sm_fCritSecInit);
EnterCriticalSection( &WP_RECYCLER::sm_CritSec );
if( WP_RECYCLER::sm_hTimerQueueForScheduleBased != NULL )
{
if ( !DeleteTimerQueueEx(
WP_RECYCLER::sm_hTimerQueueForScheduleBased,
INVALID_HANDLE_VALUE /* wait for callbacks to complete */
) )
{
DBGPRINTF(( DBG_CONTEXT,
"failed to call DeleteTimerQueueEx(): hr=0x%x\n",
HRESULT_FROM_WIN32(GetLastError()) ));
}
WP_RECYCLER::sm_hTimerQueueForScheduleBased = NULL;
}
WP_RECYCLER::sm_fIsStartedScheduleBased = FALSE;
LeaveCriticalSection( &WP_RECYCLER::sm_CritSec );
return;
}
//static
VOID
WINAPI
WP_RECYCLER::TimerCallbackForScheduleBased(
PVOID pParam,
BOOLEAN TimerOrWaitFired
)
/*++
Routine Description:
Timer callback for Schedule based recycling
It is passed to CreateTimerQueueTimer()
Routine will inform WAS that process is ready to be recycled
because scheduled time has been reached
Arguments:
see the description of WAITORTIMERCALLBACK type in MSDN
Return Value:
none
--*/
{
DBG_ASSERT( WP_RECYCLER::sm_fIsStartedScheduleBased );
IF_DEBUG( WPRECYCLER )
{
DBGPRINTF(( DBG_CONTEXT,
"WP_RECYCLER::TimerCallbackForScheduleBased()"
" - tell WAS to recycle\n" ));
}
//
// Indicate to WAS that we are ready for recycling
//
WP_RECYCLER::SendRecyclingMsg( IPM_WP_RESTART_SCHEDULED_TIME_REACHED );
}
//
// Static methods for Memory based recycling
//
//static
HRESULT
WP_RECYCLER::StartMemoryBased(
IN DWORD dwMaxVirtualMemoryUsageInKB
)
/*++
Routine Description:
Start virtual memory usage based recycling.
Arguments:
dwMaxVirtualMemoryUsageInKB - If usage of virtual memory reaches this value
worker process is ready for recycling
Note:
VM usage will be checked periodically. See the value of internal constant
CHECK_MEMORY_TIME_PERIOD
Return Value:
HRESULT
--*/
{
HRESULT hr = E_FAIL;
BOOL fRet = FALSE;
DBG_ASSERT(TRUE == sm_fCritSecInit);
EnterCriticalSection( &WP_RECYCLER::sm_CritSec );
IF_DEBUG( WPRECYCLER )
{
DBGPRINTF(( DBG_CONTEXT,
"WP_RECYCLER::StartMemoryBased(%d kB)\n",
dwMaxVirtualMemoryUsageInKB ));
}
//
// If time based recycling has been running already
// terminate it before restarting with new settings
//
if ( WP_RECYCLER::sm_fIsStartedMemoryBased == TRUE )
{
WP_RECYCLER::TerminateMemoryBased();
}
if ( dwMaxVirtualMemoryUsageInKB == 0 )
{
//
// 0 means not to run memory recycling
//
hr = S_OK;
goto succeeded;
}
fRet = CreateTimerQueueTimer( &WP_RECYCLER::sm_hTimerForMemoryBased,
NULL,
WP_RECYCLER::TimerCallbackForMemoryBased,
NULL,
CHECK_MEMORY_TIME_PERIOD,
CHECK_MEMORY_TIME_PERIOD,
WT_EXECUTELONGFUNCTION );
if ( !fRet )
{
WP_RECYCLER::sm_hTimerForMemoryBased = NULL;
hr = HRESULT_FROM_WIN32( GetLastError() );
goto failed;
}
//
// Get current process handle
// It will be used for NtQueryInformationProcess()
// in the timer callback
// there is no error to check for and handle doesn't need to be closed
// on cleanup
//
sm_hCurrentProcess = GetCurrentProcess();
sm_MaxValueForMemoryBased = 1024 * dwMaxVirtualMemoryUsageInKB;
WP_RECYCLER::sm_fIsStartedMemoryBased = TRUE;
succeeded:
LeaveCriticalSection( &WP_RECYCLER::sm_CritSec );
return S_OK;
failed:
DBG_ASSERT( FAILED( hr ) );
WP_RECYCLER::TerminateMemoryBased();
IF_DEBUG( WPRECYCLER )
{
DBGPRINTF(( DBG_CONTEXT,
"WP_RECYCLER::StartMemoryBased() failed with error hr=0x%x\n",
hr ));
}
LeaveCriticalSection( &WP_RECYCLER::sm_CritSec );
return hr;
}
//static
VOID
WP_RECYCLER::TerminateMemoryBased(
VOID
)
/*++
Routine Description:
Stops virtual memory usage based recycling
Performs cleanup
Note:
It is safe to call this method for cleanup if Start failed
Arguments:
NONE
Return Value:
VOID
--*/
{
HRESULT hr = E_FAIL;
DBG_ASSERT(TRUE == sm_fCritSecInit);
EnterCriticalSection( &WP_RECYCLER::sm_CritSec );
if ( WP_RECYCLER::sm_hTimerForMemoryBased != NULL )
{
if ( !DeleteTimerQueueTimer(
NULL,
WP_RECYCLER::sm_hTimerForMemoryBased,
INVALID_HANDLE_VALUE /* wait for callbacks to complete */
) )
{
DBGPRINTF(( DBG_CONTEXT,
"failed to call DeleteTimerQueueTimer(): hr=0x%x\n",
HRESULT_FROM_WIN32(GetLastError()) ));
}
WP_RECYCLER::sm_hTimerForMemoryBased = NULL;
}
WP_RECYCLER::sm_fIsStartedMemoryBased = FALSE;
LeaveCriticalSection( &WP_RECYCLER::sm_CritSec );
return;
}
//static
VOID
WINAPI
WP_RECYCLER::TimerCallbackForMemoryBased(
PVOID pParam,
BOOLEAN TimerOrWaitFired
)
/*++
Routine Description:
Timer callback for Elapsed time based recycling
This Callback is passed to CreateTimerQueueTimer()
Virtual memory usage will be checked and if limit has been reached
then routine will inform WAS that process is ready to be recycled
Arguments:
see description of WAITORTIMERCALLBACK type in MSDN
Return Value:
none
--*/
{
NTSTATUS Status = 0;
VM_COUNTERS VmCounters;
DBG_ASSERT( WP_RECYCLER::sm_fIsStartedMemoryBased );
Status = NtQueryInformationProcess( sm_hCurrentProcess,
ProcessVmCounters,
&VmCounters,
sizeof(VM_COUNTERS),
NULL );
if ( ! NT_SUCCESS ( Status ) )
{
IF_DEBUG( WPRECYCLER )
{
DBGPRINTF(( DBG_CONTEXT,
"NtQueryInformationProcess failed with Status: %d\n",
Status ));
}
return;
}
if ( VmCounters.VirtualSize >= sm_MaxValueForMemoryBased )
{
IF_DEBUG( WPRECYCLER )
{
DBGPRINTF(( DBG_CONTEXT,
"WP_RECYCLER::TimerCallbackForMemoryBased()"
" - current VM:%ld kB, configured max VM:%ld kB"
" - tell WAS to recycle\n",
VmCounters.VirtualSize/1024 ,
sm_MaxValueForMemoryBased/1024 ));
}
//
// we reached Virtual Memory Usage limit
//
WP_RECYCLER::SendRecyclingMsg( IPM_WP_RESTART_MEMORY_LIMIT_REACHED );
}
}
//
// Static methods for Time based recycling
//
//static
HRESULT
WP_RECYCLER::StartTimeBased(
IN DWORD dwPeriodicRestartTimeInMinutes
)
/*++
Routine Description:
Start elapsed time based recycling
Arguments:
dwPeriodicRestartTimeInMinutes - how often to restart (in minutes)
Return Value:
HRESULT
--*/
{
HRESULT hr = E_FAIL;
BOOL fRet = FALSE;
DBG_ASSERT(TRUE == sm_fCritSecInit);
EnterCriticalSection( &WP_RECYCLER::sm_CritSec );
IF_DEBUG( WPRECYCLER )
{
DBGPRINTF(( DBG_CONTEXT,
"WP_RECYCLER::StartTimeBased(%d min)\n" ,
dwPeriodicRestartTimeInMinutes ));
}
//
// If time based recycling has been running already
// terminate it before restarting with new settings
//
if ( WP_RECYCLER::sm_fIsStartedTimeBased == TRUE )
{
WP_RECYCLER::TerminateTimeBased();
}
if ( dwPeriodicRestartTimeInMinutes == 0 )
{
//
// 0 means not to run time based recycling
//
hr = S_OK;
goto succeeded;
}
fRet = CreateTimerQueueTimer( &WP_RECYCLER::sm_hTimerForTimeBased,
NULL,
WP_RECYCLER::TimerCallbackForTimeBased,
NULL,
dwPeriodicRestartTimeInMinutes * 60000,
// convert to msec
dwPeriodicRestartTimeInMinutes * 60000,
// convert to msec
WT_EXECUTELONGFUNCTION );
if ( !fRet )
{
WP_RECYCLER::sm_hTimerForTimeBased = NULL;
hr = HRESULT_FROM_WIN32( GetLastError() );
goto failed;
}
WP_RECYCLER::sm_fIsStartedTimeBased = TRUE;
succeeded:
LeaveCriticalSection( &WP_RECYCLER::sm_CritSec );
return S_OK;
failed:
DBG_ASSERT( FAILED( hr ) );
WP_RECYCLER::TerminateTimeBased();
IF_DEBUG( WPRECYCLER )
{
DBGPRINTF(( DBG_CONTEXT,
"WP_RECYCLER::StartTimeBased() failed with error hr=0x%x\n",
hr));
}
LeaveCriticalSection( &WP_RECYCLER::sm_CritSec );
return hr;
}
//static
VOID
WP_RECYCLER::TerminateTimeBased(
VOID
)
/*++
Routine Description:
Stops elapsed time based recycling
Performs cleanup
Note:
It is safe to call this method for cleanup if Start failed
Arguments:
NONE
Return Value:
HRESULT
--*/
{
HRESULT hr = E_FAIL;
DBG_ASSERT(TRUE == sm_fCritSecInit);
EnterCriticalSection( &WP_RECYCLER::sm_CritSec );
if ( WP_RECYCLER::sm_hTimerForTimeBased != NULL )
{
if ( !DeleteTimerQueueTimer(
NULL,
WP_RECYCLER::sm_hTimerForTimeBased,
INVALID_HANDLE_VALUE /* wait for callbacks to complete */
) )
{
DBGPRINTF(( DBG_CONTEXT,
"failed to call DeleteTimerQueueTimer(): hr=0x%x\n",
HRESULT_FROM_WIN32(GetLastError()) ));
}
WP_RECYCLER::sm_hTimerForTimeBased = NULL;
}
WP_RECYCLER::sm_fIsStartedTimeBased = FALSE;
LeaveCriticalSection( &WP_RECYCLER::sm_CritSec );
return;
}
//static
VOID
WINAPI
WP_RECYCLER::TimerCallbackForTimeBased(
PVOID pParam,
BOOLEAN TimerOrWaitFired
)
/*++
Routine Description:
Timer callback for Elapsed time based recycling
This Callback is passed to CreateTimerQueueTimer()
Routine will inform WAS that process is ready to be recycled
because required elapsed time has been reached
Arguments:
see description of WAITORTIMERCALLBACK type in MSDN
Return Value:
none
--*/
{
DBG_ASSERT( WP_RECYCLER::sm_fIsStartedTimeBased );
IF_DEBUG( WPRECYCLER )
{
DBGPRINTF(( DBG_CONTEXT,
"WP_RECYCLER::TimerCallbackForTimeBased"
" - tell WAS to recycle\n" ));
}
WP_RECYCLER::SendRecyclingMsg( IPM_WP_RESTART_ELAPSED_TIME_REACHED );
}
//
// Static methods for Request based recycling
//
//static
HRESULT
WP_RECYCLER::StartRequestBased(
IN DWORD dwRequests
)
/*++
Routine Description:
Start request based recycling.
Arguments:
dwRequests - If number of requests processed by worker process reaches this value
recycling will be required
Return Value:
HRESULT
--*/
{
HRESULT hr = E_FAIL;
DBG_ASSERT(TRUE == sm_fCritSecInit);
EnterCriticalSection( &WP_RECYCLER::sm_CritSec );
IF_DEBUG( WPRECYCLER )
{
DBGPRINTF(( DBG_CONTEXT,
"WP_RECYCLER::StartRequestBased(%d kB)\n" ,
dwRequests ));
}
//
// If time based recycling has been running already
// terminate it before restarting with new settings
//
if ( WP_RECYCLER::sm_fIsStartedRequestBased == TRUE )
{
WP_RECYCLER::TerminateRequestBased();
}
if ( dwRequests == 0 )
{
//
// 0 means not to run request based recycling
//
hr = S_OK;
goto succeeded;
}
InterlockedExchange(
reinterpret_cast<LONG *>(&sm_dwMaxValueForRequestBased),
dwRequests );
InterlockedExchange(
reinterpret_cast<LONG *>(&WP_RECYCLER::sm_fIsStartedTimeBased),
TRUE );
hr = S_OK;
succeeded:
LeaveCriticalSection( &WP_RECYCLER::sm_CritSec );
return hr;
}
//static
VOID
WP_RECYCLER::TerminateRequestBased(
VOID
)
/*++
Routine Description:
Stops request based recycling
Performs cleanup
Note:
It is safe to call this method for cleanup if Start failed
Arguments:
NONE
Return Value:
HRESULT
--*/
{
DBG_ASSERT(TRUE == sm_fCritSecInit);
EnterCriticalSection( &WP_RECYCLER::sm_CritSec );
//
// InterlockedExchange is used because Request Based recycling callback
// IsRequestCountLimitReached() is called for each request
// and we don't synchronize it with &WP_RECYCLER::sm_CritSec
//
InterlockedExchange(
reinterpret_cast<LONG *>(&WP_RECYCLER::sm_fIsStartedTimeBased),
FALSE );
LeaveCriticalSection( &WP_RECYCLER::sm_CritSec );
return;
}
| [
"112426112@qq.com"
] | 112426112@qq.com |
de82b35c95021f3a2978cd09ae9882f2bd507c0f | 0250600efb84f9f324602934c3fe42e62e67f8f6 | /topcoder/SRM_523/BricksN.cpp | 6fe792a2a7de8803ba1a95d5a41a8b5a378672ef | [] | no_license | bloops/solved | 987b43a4e8b9a2276bf81588a694ed77724fc633 | 2be75bb735b2edc13ba55826fbc9982e403ef8ce | refs/heads/master | 2021-01-01T18:02:40.019170 | 2012-01-19T16:18:38 | 2012-01-19T16:18:38 | 3,089,147 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,612 | cpp | #include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
typedef long long int lli;
const lli MOD = 1000000007;
class BricksN {
public:
int partitions[55]; // partitions[i][k] = no of ways to make contiguous blocks of length i using 1..k
int count[55][55]; // count[w][h] = # of ways to structures on a base of length w
// with height atmost h (not including base w)
int countStructures(int w, int h, int k) {
partitions[0] = 1;
for (int i = 1; i <= w; i++){
for (int j = 1; j <= k; j++){
if(i-j >= 0){
partitions[i] += partitions[i-j];
partitions[i] %= MOD;
}
}
}
for (int hi = 0; hi <= h; hi++){
for (int wi = 0; wi <= w; wi++){
// find count[wi][hi]
count[wi][hi] = 1; // no blocks at all
for (int i = 1; i <= wi; i++){
for (int j = i; j <= wi; j++){
// put the last block [i..j]
int last = j-i+1;
int multterm = (partitions[last] * (lli)count[last][hi-1]) % MOD;
if( i >= 2 )
multterm = (multterm * (lli)count[i-2][hi]) % MOD;
count[wi][hi] += multterm;
count[wi][hi] %= MOD;
}
}
}
}
return count[w][h];
}
};
// BEGIN KAWIGIEDIT TESTING
// Generated by KawigiEdit 2.1.4 (beta) modified by pivanof
bool KawigiEdit_RunTest(int testNum, int p0, int p1, int p2, bool hasAnswer, int p3) {
cout << "Test " << testNum << ": [" << p0 << "," << p1 << "," << p2;
cout << "]" << endl;
BricksN *obj;
int answer;
obj = new BricksN();
clock_t startTime = clock();
answer = obj->countStructures(p0, p1, p2);
clock_t endTime = clock();
delete obj;
bool res;
res = true;
cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl;
if (hasAnswer) {
cout << "Desired answer:" << endl;
cout << "\t" << p3 << endl;
}
cout << "Your answer:" << endl;
cout << "\t" << answer << endl;
if (hasAnswer) {
res = answer == p3;
}
if (!res) {
cout << "DOESN'T MATCH!!!!" << endl;
} else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) {
cout << "FAIL the timeout" << endl;
res = false;
} else if (hasAnswer) {
cout << "Match :-)" << endl;
} else {
cout << "OK, but is it right?" << endl;
}
cout << "" << endl;
return res;
}
int main() {
bool all_right;
all_right = true;
int p0;
int p1;
int p2;
int p3;
{
// ----- test 0 -----
p0 = 3;
p1 = 1;
p2 = 3;
p3 = 13;
all_right = KawigiEdit_RunTest(0, p0, p1, p2, true, p3) && all_right;
// ------------------
}
{
// ----- test 1 -----
p0 = 3;
p1 = 2;
p2 = 3;
p3 = 83;
all_right = KawigiEdit_RunTest(1, p0, p1, p2, true, p3) && all_right;
// ------------------
}
{
// ----- test 2 -----
p0 = 1;
p1 = 5;
p2 = 1;
p3 = 6;
all_right = KawigiEdit_RunTest(2, p0, p1, p2, true, p3) && all_right;
// ------------------
}
{
// ----- test 3 -----
p0 = 10;
p1 = 10;
p2 = 3;
p3 = 288535435;
all_right = KawigiEdit_RunTest(3, p0, p1, p2, true, p3) && all_right;
// ------------------
}
if (all_right) {
cout << "You're a stud (at least on the example cases)!" << endl;
} else {
cout << "Some of the test cases had errors." << endl;
}
return 0;
}
// END KAWIGIEDIT TESTING
//Powered by KawigiEdit 2.1.4 (beta) modified by pivanof!
| [
"bloopsie@gmail.com"
] | bloopsie@gmail.com |
974fe86b534d4567f685ad4c15dfaad7b9b047f5 | 3b70cb095b5bc18cdb35d1affa5f78235b164dac | /draw/debug/moc_wumian.cpp | 870b3efbd8bbfee840d494dd6c87346aab9b5429 | [] | no_license | GaoYifanGHB/qtP | 2e96ad690e2d1844622847aa705db4fc3880e739 | 60f71804e6899301309e9de5e169d90609cbe000 | refs/heads/master | 2021-04-26T01:31:51.137849 | 2017-11-02T08:53:33 | 2017-11-02T08:53:33 | 107,406,674 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,008 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'wumian.h'
**
** Created: Sun Aug 13 16:22:49 2017
** by: The Qt Meta Object Compiler version 62 (Qt 4.7.3)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../model/wumian.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'wumian.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 62
#error "This file was generated using the moc from 4.7.3. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_wumian[] = {
// content:
5, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
static const char qt_meta_stringdata_wumian[] = {
"wumian\0"
};
const QMetaObject wumian::staticMetaObject = {
{ &QGLWidget::staticMetaObject, qt_meta_stringdata_wumian,
qt_meta_data_wumian, 0 }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &wumian::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *wumian::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *wumian::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_wumian))
return static_cast<void*>(const_cast< wumian*>(this));
return QGLWidget::qt_metacast(_clname);
}
int wumian::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QGLWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
QT_END_MOC_NAMESPACE
| [
"gao_yifan@163.com"
] | gao_yifan@163.com |
7221349c9d3ad45499f97bfe605a3557673ab89c | 6956e203caf857ca4e1a64ff4248a5824951a314 | /common_src/Unirse.cpp | c84e1eb1c1418e1763a35847c45f42ecc5a484a9 | [] | no_license | psdimartino/TallerDeProgramacion_TP3 | 431f1bc48bd9ce26aaf8897938edff330125933f | 5ac9f7f1c031fbd74189a337a4396e43238b255e | refs/heads/main | 2023-05-29T01:07:56.307625 | 2021-06-15T20:21:16 | 2021-06-15T20:21:16 | 374,215,694 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 568 | cpp | #include "../common_src/Unirse.h"
Unirse::Unirse(std::string const nombre) : nombre(nombre) {}
std::string const& Unirse::getNombre() const {
return nombre;
}
void Unirse::ejecutar(MapaDePartidas &partidas,
std::string &nombrePartida, char &jugador) {
if (!partidas.unirse(nombre)) {
result << "La partida no existe o esta llena" << std::endl;
return;
}
jugador = CRUZ;
nombrePartida = std::move(nombre);
partidas[nombrePartida].esperarElTurnoDe(jugador);
result << partidas[nombrePartida];
}
| [
"pdimartino@fi.uba.ar"
] | pdimartino@fi.uba.ar |
56a6abb096668ae7d14e1647b55bc424fdd76710 | 92a9f837503a591161330d39d061ce290c996f0e | /SiNDY-u/DiffImportRoad/stdafx.h | 2babcb550a5e057680929941afc0f8313214614b | [] | no_license | AntLJ/TestUploadFolder | 53a7dae537071d2b1e3bab55e925c8782f3daa0f | 31f9837abbd6968fc3a0be7610560370c4431217 | refs/heads/master | 2020-12-15T21:56:47.756829 | 2020-01-23T07:33:23 | 2020-01-23T07:33:23 | 235,260,509 | 1 | 1 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,272 | h | /*
* Copyright (C) INCREMENT P CORP. All Rights Reserved.
*
* THIS SOFTWARE IS PROVIDED BY INCREMENT P CORP., WITHOUT WARRANTY OF
* ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* AND NONINFRINGEMENT.
*
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDER BE LIABLE FOR ANY
* CLAIM, DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
* OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
*/
// stdafx.h : 標準のシステム インクルード ファイルのインクルード ファイル、または
// 参照回数が多く、かつあまり変更されない、プロジェクト専用のインクルード ファイル
// を記述します。
//
#pragma once
#include "targetver.h"
#include <atlbase.h>
#include <atlcom.h>
#include <atlstr.h>
#include <conio.h>
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <fstream>
#include <string>
#include <atlbase.h>
#include <TDC/useful_headers/tstring.h>
#include <set>
#include <list>
#include <map>
#include <vector>
#include <assert.h>
#pragma warning(push)
#pragma warning(disable: 4192)
#pragma warning(disable: 4278)
#pragma warning(pop)
| [
"noreply@github.com"
] | AntLJ.noreply@github.com |
6070b13c45099e983645c086e468fc7ccc75d9a1 | 4054a250ae5db77119bfc5fd54de94675a3231ca | /test/block_cipher/test_aes_cbc.cpp | 8189a8662fa59a9a3d29070e35bb15eca85dc45d | [
"MIT"
] | permissive | hocktide/v-c-crypto | 21c937421534191e29d152f1e173e7e2dbd40bd0 | 4f3d5f21cc62f4a92c7987abdbcaee2d652781ca | refs/heads/master | 2022-09-10T13:13:25.771967 | 2020-05-14T03:26:13 | 2020-05-29T19:37:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,037 | cpp | /**
* \file test_aes_cbc.cpp
*
* Unit tests for AES CBC Mode.
*
* \copyright 2018 Velo Payments, Inc. All rights reserved.
*/
#include <gtest/gtest.h>
#include <vccrypt/block_cipher.h>
#include <vpr/allocator/malloc_allocator.h>
using namespace std;
class aes_cbc_test : public ::testing::Test {
protected:
void SetUp() override
{
/* register all AES block ciphers. */
vccrypt_block_register_AES_256_CBC_FIPS();
vccrypt_block_register_AES_256_2X_CBC();
vccrypt_block_register_AES_256_3X_CBC();
vccrypt_block_register_AES_256_4X_CBC();
/* set up allocator */
malloc_allocator_options_init(&alloc_opts);
/* set up options for each variant. */
fips_options_init_result =
vccrypt_block_options_init(
&fips_options, &alloc_opts,
VCCRYPT_BLOCK_ALGORITHM_AES_256_CBC_FIPS);
x2_options_init_result =
vccrypt_block_options_init(
&x2_options, &alloc_opts,
VCCRYPT_BLOCK_ALGORITHM_AES_256_2X_CBC);
x3_options_init_result =
vccrypt_block_options_init(
&x3_options, &alloc_opts,
VCCRYPT_BLOCK_ALGORITHM_AES_256_3X_CBC);
x4_options_init_result =
vccrypt_block_options_init(
&x4_options, &alloc_opts,
VCCRYPT_BLOCK_ALGORITHM_AES_256_4X_CBC);
}
void TearDown() override
{
/* tear down options for each variant. */
if (0 == fips_options_init_result)
{
dispose((disposable_t*)&fips_options);
}
if (0 == x2_options_init_result)
{
dispose((disposable_t*)&x2_options);
}
if (0 == x3_options_init_result)
{
dispose((disposable_t*)&x3_options);
}
if (0 == x4_options_init_result)
{
dispose((disposable_t*)&x4_options);
}
dispose((disposable_t*)&alloc_opts);
}
allocator_options_t alloc_opts;
vccrypt_block_options_t fips_options;
vccrypt_block_options_t x2_options;
vccrypt_block_options_t x3_options;
vccrypt_block_options_t x4_options;
int fips_options_init_result;
int x2_options_init_result;
int x3_options_init_result;
int x4_options_init_result;
};
/**
* We should be able to create an options structure for each of the supported
* CBC mode ciphers.
*/
TEST_F(aes_cbc_test, register_options)
{
/* Test FIPS AES-256-CBC options init. */
ASSERT_EQ(0, fips_options_init_result);
EXPECT_NE(nullptr, fips_options.hdr.dispose);
EXPECT_EQ(&alloc_opts, fips_options.alloc_opts);
EXPECT_EQ(32U, fips_options.key_size);
EXPECT_EQ(16U, fips_options.IV_size);
EXPECT_EQ(UINT64_MAX, fips_options.maximum_message_size);
EXPECT_NE(nullptr, fips_options.vccrypt_block_alg_init);
EXPECT_NE(nullptr, fips_options.vccrypt_block_alg_encrypt);
EXPECT_NE(nullptr, fips_options.vccrypt_block_alg_decrypt);
/* Test AES-256-2X-CBC options init. */
ASSERT_EQ(0, x2_options_init_result);
EXPECT_NE(nullptr, x2_options.hdr.dispose);
EXPECT_EQ(&alloc_opts, x2_options.alloc_opts);
EXPECT_EQ(32U, x2_options.key_size);
EXPECT_EQ(16U, x2_options.IV_size);
EXPECT_EQ(UINT64_MAX, x2_options.maximum_message_size);
EXPECT_NE(nullptr, x2_options.vccrypt_block_alg_init);
EXPECT_NE(nullptr, x2_options.vccrypt_block_alg_encrypt);
EXPECT_NE(nullptr, x2_options.vccrypt_block_alg_decrypt);
/* Test AES-256-3X-CBC options init. */
ASSERT_EQ(0, x3_options_init_result);
EXPECT_NE(nullptr, x3_options.hdr.dispose);
EXPECT_EQ(&alloc_opts, x3_options.alloc_opts);
EXPECT_EQ(32U, x3_options.key_size);
EXPECT_EQ(16U, x3_options.IV_size);
EXPECT_EQ(UINT64_MAX, x3_options.maximum_message_size);
EXPECT_NE(nullptr, x3_options.vccrypt_block_alg_init);
EXPECT_NE(nullptr, x3_options.vccrypt_block_alg_encrypt);
EXPECT_NE(nullptr, x3_options.vccrypt_block_alg_decrypt);
/* Test AES-256-4X-CBC options init. */
ASSERT_EQ(0, x4_options_init_result);
EXPECT_NE(nullptr, x4_options.hdr.dispose);
EXPECT_EQ(&alloc_opts, x4_options.alloc_opts);
EXPECT_EQ(32U, x4_options.key_size);
EXPECT_EQ(16U, x4_options.IV_size);
EXPECT_EQ(UINT64_MAX, x4_options.maximum_message_size);
EXPECT_NE(nullptr, x4_options.vccrypt_block_alg_init);
EXPECT_NE(nullptr, x4_options.vccrypt_block_alg_encrypt);
EXPECT_NE(nullptr, x4_options.vccrypt_block_alg_decrypt);
}
/**
* We should be able to initialize, encrypt, and decrypt using a FIPS compatible
* block cipher. TEST from FIPS-800-38a (F.2.5).
*/
TEST_F(aes_cbc_test, aes_256_cbc_fips_f25)
{
vccrypt_block_context_t ctx;
vccrypt_buffer_t key;
const uint8_t KEY[32] = {
0x60, 0x3d, 0xeb, 0x10, 0x15, 0xca, 0x71, 0xbe,
0x2b, 0x73, 0xae, 0xf0, 0x85, 0x7d, 0x77, 0x81,
0x1f, 0x35, 0x2c, 0x07, 0x3b, 0x61, 0x08, 0xd7,
0x2d, 0x98, 0x10, 0xa3, 0x09, 0x14, 0xdf, 0xf4
};
const uint8_t IV[16] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f
};
const uint8_t PLAINTEXT[64] = {
0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96,
0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a,
0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c,
0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51,
0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11,
0xe5, 0xfb, 0xc1, 0x19, 0x1a, 0x0a, 0x52, 0xef,
0xf6, 0x9f, 0x24, 0x45, 0xdf, 0x4f, 0x9b, 0x17,
0xad, 0x2b, 0x41, 0x7b, 0xe6, 0x6c, 0x37, 0x10
};
const uint8_t CIPHERTEXT[64] = {
0xf5, 0x8c, 0x4c, 0x04, 0xd6, 0xe5, 0xf1, 0xba,
0x77, 0x9e, 0xab, 0xfb, 0x5f, 0x7b, 0xfb, 0xd6,
0x9c, 0xfc, 0x4e, 0x96, 0x7e, 0xdb, 0x80, 0x8d,
0x67, 0x9f, 0x77, 0x7b, 0xc6, 0x70, 0x2c, 0x7d,
0x39, 0xf2, 0x33, 0x69, 0xa9, 0xd9, 0xba, 0xcf,
0xa5, 0x30, 0xe2, 0x63, 0x04, 0x23, 0x14, 0x61,
0xb2, 0xeb, 0x05, 0xe2, 0xc3, 0x9b, 0xe9, 0xfc,
0xda, 0x6c, 0x19, 0x07, 0x8c, 0x6a, 0x9d, 0x1b
};
uint8_t output[64];
uint8_t poutput[64];
/* write junk to the output buffers */
memset(output, 0xFC, sizeof(output));
memset(poutput, 0xFC, sizeof(poutput));
/* create a buffer for the key data. */
ASSERT_EQ(0, vccrypt_buffer_init(&key, &alloc_opts, sizeof(KEY)));
/* read the key into the buffer. */
ASSERT_EQ(0, vccrypt_buffer_read_data(&key, KEY, sizeof(KEY)));
/* create a new block cipher with the given key. */
ASSERT_EQ(0, vccrypt_block_init(&fips_options, &ctx, &key, true));
/* encrypt each plaintext block, writing to output. */
ASSERT_EQ(0, vccrypt_block_encrypt(&ctx, IV, PLAINTEXT, output));
ASSERT_EQ(0, vccrypt_block_encrypt(&ctx, output, PLAINTEXT + 16, output + 16));
ASSERT_EQ(0, vccrypt_block_encrypt(&ctx, output + 16, PLAINTEXT + 32, output + 32));
ASSERT_EQ(0, vccrypt_block_encrypt(&ctx, output + 32, PLAINTEXT + 48, output + 48));
/* the encrypted data should match our ciphertext */
ASSERT_EQ(0, memcmp(output, CIPHERTEXT, sizeof(output)));
/* clean up encryption context */
dispose((disposable_t*)&ctx);
/* create a new block cipher with the given key. */
ASSERT_EQ(0, vccrypt_block_init(&fips_options, &ctx, &key, false));
/* decrypt each ciphertext block, writing it to poutput. */
ASSERT_EQ(0, vccrypt_block_decrypt(&ctx, IV, CIPHERTEXT, poutput));
ASSERT_EQ(0, vccrypt_block_decrypt(&ctx, CIPHERTEXT, CIPHERTEXT + 16, poutput + 16));
ASSERT_EQ(0, vccrypt_block_decrypt(&ctx, CIPHERTEXT + 16, CIPHERTEXT + 32, poutput + 32));
ASSERT_EQ(0, vccrypt_block_decrypt(&ctx, CIPHERTEXT + 32, CIPHERTEXT + 48, poutput + 48));
/* the decrypted data should match our plaintext */
ASSERT_EQ(0, memcmp(poutput, PLAINTEXT, sizeof(poutput)));
dispose((disposable_t*)&ctx);
dispose((disposable_t*)&key);
}
| [
"nanolith@gmail.com"
] | nanolith@gmail.com |
fb5ac67e56adc3ef9d0c7122e919436c200c7ac9 | a14badc58bc6b5871cbd85e91cd8bf636824acec | /Binary Search/WoodCuttingMadeEasy.cpp | bd37fbb5fe60c54130ce295e0a2230af64635d9f | [] | no_license | prashant97sikarwar/Interview-Bit | 693b37c15e70de346c58debfd18e22541aaf7452 | 4b3bf032e30e16b8033e1a47c840fcaa434be429 | refs/heads/master | 2023-07-16T17:02:58.297411 | 2021-08-31T11:35:39 | 2021-08-31T11:35:39 | 353,809,557 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 742 | cpp | //Problem Link:- https://www.interviewbit.com/problems/woodcutting-made-easy/
#include<bits/stdc++.h>
using namespace std;
bool helper(vector<int> &nums,int k,int h){
long long sm = 0;
for(int i=0;i<nums.size();i++){
if (nums[i] > h){
sm += nums[i]-h;
}
}
if (sm >= k){
return true;
}
return false;
}
int solve(vector<int> &nums, int k) {
int left = 0;
int right = *max_element(nums.begin(),nums.end());
int res = INT_MIN;
while (left <= right){
int mid = left + (right-left)/2;
if (helper(nums,k,mid)){
res = max(res,mid);
left = mid+1;
}
else{
right = mid-1;
}
}
return res;
}
| [
"prashant97sikarwar@gmail.com"
] | prashant97sikarwar@gmail.com |
6b835908aa7e9b9632807ddaca04d4acc4f0b3e8 | 9d8bd24d59ad0fafc84748ca3d74153ee118b41f | /sandbox/planar-arma/include/planar-utils.h | b1049ce52b46a5cf745aafeba65b9398aac94b7e | [] | no_license | ColleyLi/bsp | 2e990254ede7144f88c976e2f69a43258d5a632f | d920b6e687e6167b574cc3716acfebe9b725b5cc | refs/heads/master | 2021-05-27T22:15:25.940929 | 2014-09-14T17:33:31 | 2014-09-14T17:33:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,014 | h | #ifndef __PLANAR_UTILS_H__
#define __PLANAR_UTILS_H__
#include <Python.h>
#include <map>
#include <boost/python.hpp>
#include <boost/python/numeric.hpp>
#include <boost/python/tuple.hpp>
#include <boost/numpy.hpp>
#include <boost/filesystem.hpp>
namespace py = boost::python;
namespace np = boost::numpy;
#include <armadillo>
using namespace arma;
#include "../../util/Timer.h"
#include "../../util/logging.h"
/**
* Wrapper that tracks multiple timers
*/
class TimerCollection {
public:
void start(const std::string& timer_name);
void stop(const std::string& timer_name);
void print_elapsed(const std::string& timer_name);
void print_all_elapsed();
void clear_all();
private:
std::map<std::string,util::Timer> timer_dict;
std::map<std::string,double> timer_elapsed;
std::map<std::string,bool> timer_running;
};
namespace planar_utils {
inline double uniform(double low, double high) {
return (high - low)*(rand() / double(RAND_MAX)) + low;
}
np::ndarray arma_to_ndarray(mat& m);
}
#endif
| [
"gkahn13@gmail.com"
] | gkahn13@gmail.com |
40d7dd3c139d08041ecd5d951952635959c3166e | 5be61bc794c26850ed6ad39e959d73c8e89975c7 | /Tugas SD Modul 6.cpp | 14c40df95e90688dad58efc486c7f1921c1ee96d | [] | no_license | MBaihaqqiPP/Tugas-Prak.-Struktur-Data | 85abce4963d878c0cbf378a7290c6c3e077127b6 | b6aa2e0cd7ccc4571d471c38d6ab39b224b76e6a | refs/heads/master | 2022-04-26T00:17:23.506323 | 2020-04-27T14:04:33 | 2020-04-27T14:04:33 | 241,255,485 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 630 | cpp | #include<stdio.h>
#include<conio.h>
#include<string.h>
char balik(char K[50]);
char cek(char O[50],char P[50]);
int main()
{
char K[50],L[50];
printf("Masukkan kalimat : "); gets(m);
strcpy(K,L);
balik(K);
cek(K,L);
getch();
printf("Masukkan kalimat : "); gets(m);
strcpy(L,K);
balik(L);
cek(K,L);
getch();
}
char balik(char x[50])
{
strrev(x);
}
char cek(char O[50],char P[50])
{
if(strcmp(O,P)==0)
{
printf("\nKalimat tersebut adalah palindrom\n\n");
}
else
{
printf("\nKalimat tersebut bukan palindrom\n\n");
}
}
| [
"noreply@github.com"
] | MBaihaqqiPP.noreply@github.com |
d121214d0f4181d2d594c81fa5a527e281adbaff | 6ec2b24683e532193107f1b68f8e648893174dbc | /eos/10/docker/oasis/contracts/Marketplace/Marketplace.cpp | c8c420098ea4f81306ee3adbbf59b9bb49c9417c | [
"Apache-2.0"
] | permissive | AaronZgl/blockchain | dde3f51d520d2b474d2e90f54cc3b90b572751b8 | 7c1b75a5870c13dfbaf11c943a02ff6074604796 | refs/heads/master | 2020-03-27T17:41:53.808466 | 2018-08-31T09:32:36 | 2018-08-31T09:32:36 | 146,867,528 | 0 | 0 | Apache-2.0 | 2018-08-31T08:58:19 | 2018-08-31T08:58:19 | null | UTF-8 | C++ | false | false | 3,796 | cpp | #include "Marketplace.hpp"
#include <eosiolib/asset.hpp>
namespace Oasis {
void Marketplace::buy(account_name buyer, uint64_t productId) {
productIndex products(_self, _self);
print("buy function,self is: ", name{ _self });
auto iterator = products.find(productId);
eosio_assert(iterator != products.end(), "The product not found");
auto product = products.get(productId);
eosio_assert(product.quantity > 0, "The product is out of stock");
print(" | Id: ", product.product_id);
print(" | Name: ", product.name.c_str());
print(" | Power: ", product.power);
print(" | Health: ", product.health);
print(" | Ability: ", product.ability.c_str());
print(" | Level up: ", product.level_up);
print(" | Quantity: ", product.quantity);
print(" | Price: ", product.price);
asset productPrice = asset(product.price, string_to_symbol(4, "OAS"));
action(
permission_level{ buyer, N(active) },
N(token), N(transfer),
std::make_tuple(buyer, _self, productPrice, string("buyTest"))
).send();
action(
permission_level{ buyer, N(active) },
N(player), N(additem),
std::make_tuple(buyer,
product.product_id,
product.name,
product.power,
product.health,
product.ability,
product.level_up
)).send();
update(buyer, product.product_id, -1);
}
void Marketplace::getbyid(uint64_t productId) {
productIndex products(_self, _self);
auto iterator = products.find(productId);
eosio_assert(iterator != products.end(), "Product not found");
auto product = products.get(productId);
print("Id: ", product.product_id);
print(" | Name: ", product.name.c_str());
print(" | Power: ", product.power);
print(" | Health: ", product.health);
print(" | Ability: ", product.ability.c_str());
print(" | Level up: ", product.level_up);
print(" | Quantity: ", product.quantity);
print(" | Price: ", product.price);
}
void Marketplace::add(account_name account, product newProduct) {
require_auth(account);
productIndex products(_self, _self);
auto iterator = products.find(newProduct.product_id);
eosio_assert(iterator == products.end(), "Product for this ID already exists");
products.emplace(account, [&](auto& product) {
product.product_id = newProduct.product_id;
product.name = newProduct.name;
product.power = newProduct.power;
product.health = newProduct.health;
product.ability = newProduct.ability;
product.level_up = newProduct.level_up;
product.quantity = newProduct.quantity;
product.price = newProduct.price;
});
}
void Marketplace::update(account_name account, uint64_t product_id, uint64_t quantity) {
require_auth(account);
productIndex products(_self, _self);
auto iterator = products.find(product_id);
eosio_assert(iterator != products.end(), "Product not found");
//TODO: check the 'product.quantity + quantity > 0'
products.modify(iterator, account, [&](auto& product) {
product.quantity += quantity;
});
}
void Marketplace::remove(account_name account, uint64_t productId) {
require_auth(account);
productIndex products(_self, _self);
auto iterator = products.find(productId);
eosio_assert(iterator != products.end(), "Product not found");
products.erase(iterator);
}
}
| [
"shanlusun@gmail.com"
] | shanlusun@gmail.com |
c95faa0483328b0d7e87ca8493590f4e994e7039 | c07c34c92e255583fb4d0e5318a47e04db66b0a2 | /sorting_algorithms/sorting_algorithms/Sort.hpp | fc10c36e1fcc984710e773c16ca9e82c19095d8d | [] | no_license | abyesses/calidad_software | 84e246e5ed6e86f2ebb77ebff41e69cd768f99d0 | 4ef352019bf61d2795a02ab8cd42557001a06db2 | refs/heads/master | 2021-01-11T23:02:07.554737 | 2017-02-10T16:04:40 | 2017-02-10T16:04:40 | 78,536,543 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 444 | hpp | //
// Sort.hpp
// sorting_algorithms
//
// Created by Abraham Esses on 1/24/17.
// Copyright © 2017 Abraham Esses. All rights reserved.
//
#ifndef Sort_hpp
#define Sort_hpp
#define vect_tam 20
#include <stdio.h>
#include <vector>
#include <time.h>
using namespace std;
class Sort{
protected:
//vector<int> * unsorted = new vector<int>(vect_tam);
public:
virtual vector<int>* sort(vector<int>*,int)=0;
};
#endif /* Sort_hpp */
| [
"abraham@Abrahams-MacBook-Pro.local"
] | abraham@Abrahams-MacBook-Pro.local |
c48126c2316e1ea6740a8e324283cbc4bbf6918f | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/squid/gumtree/squid_repos_function_3730_squid-3.5.27.cpp | 1027a95beb16649c8344a86d0b8ecf909e7ffc17 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 203 | cpp | HttpHdrRangeSpec *
HttpHdrRangeSpec::Create(const char *field, int flen)
{
HttpHdrRangeSpec spec;
if (!spec.parseInit(field, flen))
return NULL;
return new HttpHdrRangeSpec(spec);
} | [
"993273596@qq.com"
] | 993273596@qq.com |
84cb8f7a20954b011a38fb0337d0b547327465a5 | 21ede326b6cfcf5347ca6772d392d3acca80cfa0 | /content/renderer/input/input_event_prediction.cc | 72f91539214b2b2c8ee9c893714e4de287f5b3cb | [
"BSD-3-Clause"
] | permissive | csagan5/kiwi | 6eaab0ab4db60468358291956506ad6f889401f8 | eb2015c28925be91b4a3130b3c2bee2f5edc91de | refs/heads/master | 2020-04-04T17:06:54.003121 | 2018-10-24T08:20:01 | 2018-10-24T08:20:01 | 156,107,399 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,915 | cc | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/input/input_event_prediction.h"
#include "base/feature_list.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/field_trial_params.h"
#include "content/public/common/content_features.h"
#include "ui/events/blink/prediction/empty_predictor.h"
#include "ui/events/blink/prediction/least_squares_predictor.h"
using blink::WebInputEvent;
using blink::WebMouseEvent;
using blink::WebPointerEvent;
using blink::WebPointerProperties;
using blink::WebTouchEvent;
namespace content {
namespace {
constexpr char kPredictor[] = "predictor";
constexpr char kInputEventPredictorTypeLsq[] = "lsq";
} // namespace
InputEventPrediction::InputEventPrediction() {
std::string predictor_type_ = GetFieldTrialParamValueByFeature(
features::kResamplingInputEvents, kPredictor);
if (predictor_type_ == kInputEventPredictorTypeLsq)
selected_predictor_type_ = PredictorType::kLsq;
else
selected_predictor_type_ = PredictorType::kEmpty;
mouse_predictor_ = CreatePredictor();
}
InputEventPrediction::~InputEventPrediction() {}
void InputEventPrediction::HandleEvents(
const blink::WebCoalescedInputEvent& coalesced_event,
base::TimeTicks frame_time,
blink::WebInputEvent* event) {
switch (event->GetType()) {
case WebInputEvent::kMouseMove:
case WebInputEvent::kTouchMove:
case WebInputEvent::kPointerMove: {
size_t coalesced_size = coalesced_event.CoalescedEventSize();
for (size_t i = 0; i < coalesced_size; i++)
UpdatePrediction(coalesced_event.CoalescedEvent(i));
ApplyResampling(frame_time, event);
break;
}
case WebInputEvent::kTouchScrollStarted:
case WebInputEvent::kPointerCausedUaAction:
pointer_id_predictor_map_.clear();
break;
default:
ResetPredictor(*event);
}
}
std::unique_ptr<ui::InputPredictor> InputEventPrediction::CreatePredictor()
const {
switch (selected_predictor_type_) {
case PredictorType::kEmpty:
return std::make_unique<ui::EmptyPredictor>();
case PredictorType::kLsq:
return std::make_unique<ui::LeastSquaresPredictor>();
}
}
void InputEventPrediction::UpdatePrediction(const WebInputEvent& event) {
if (WebInputEvent::IsTouchEventType(event.GetType())) {
DCHECK(event.GetType() == WebInputEvent::kTouchMove);
const WebTouchEvent& touch_event = static_cast<const WebTouchEvent&>(event);
for (unsigned i = 0; i < touch_event.touches_length; ++i) {
if (touch_event.touches[i].state == blink::WebTouchPoint::kStateMoved) {
UpdateSinglePointer(touch_event.touches[i], touch_event.TimeStamp());
}
}
} else if (WebInputEvent::IsMouseEventType(event.GetType())) {
DCHECK(event.GetType() == WebInputEvent::kMouseMove);
UpdateSinglePointer(static_cast<const WebMouseEvent&>(event),
event.TimeStamp());
} else if (WebInputEvent::IsPointerEventType(event.GetType())) {
DCHECK(event.GetType() == WebInputEvent::kPointerMove);
UpdateSinglePointer(static_cast<const WebPointerEvent&>(event),
event.TimeStamp());
}
}
void InputEventPrediction::ApplyResampling(base::TimeTicks frame_time,
WebInputEvent* event) {
if (event->GetType() == WebInputEvent::kTouchMove) {
WebTouchEvent* touch_event = static_cast<WebTouchEvent*>(event);
for (unsigned i = 0; i < touch_event->touches_length; ++i) {
if (ResampleSinglePointer(frame_time, &touch_event->touches[i]))
event->SetTimeStamp(frame_time);
}
} else if (event->GetType() == WebInputEvent::kMouseMove) {
if (ResampleSinglePointer(frame_time, static_cast<WebMouseEvent*>(event)))
event->SetTimeStamp(frame_time);
} else if (event->GetType() == WebInputEvent::kPointerMove) {
if (ResampleSinglePointer(frame_time, static_cast<WebPointerEvent*>(event)))
event->SetTimeStamp(frame_time);
}
}
void InputEventPrediction::ResetPredictor(const WebInputEvent& event) {
if (WebInputEvent::IsTouchEventType(event.GetType())) {
const WebTouchEvent& touch_event = static_cast<const WebTouchEvent&>(event);
for (unsigned i = 0; i < touch_event.touches_length; ++i) {
if (touch_event.touches[i].state != blink::WebTouchPoint::kStateMoved &&
touch_event.touches[i].state !=
blink::WebTouchPoint::kStateStationary)
pointer_id_predictor_map_.erase(touch_event.touches[i].id);
}
} else if (WebInputEvent::IsMouseEventType(event.GetType())) {
ResetSinglePredictor(static_cast<const WebMouseEvent&>(event));
} else if (WebInputEvent::IsPointerEventType(event.GetType())) {
ResetSinglePredictor(static_cast<const WebPointerEvent&>(event));
}
}
void InputEventPrediction::UpdateSinglePointer(
const WebPointerProperties& event,
base::TimeTicks event_time) {
ui::InputPredictor::InputData data = {event.PositionInWidget(), event_time};
if (event.pointer_type == WebPointerProperties::PointerType::kMouse)
mouse_predictor_->Update(data);
else {
auto predictor = pointer_id_predictor_map_.find(event.id);
if (predictor != pointer_id_predictor_map_.end()) {
predictor->second->Update(data);
} else {
// Workaround for GLIBC C++ < 7.3 that fails to insert with braces
// See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82522
auto pair = std::make_pair(event.id, CreatePredictor());
pointer_id_predictor_map_.insert(std::move(pair));
pointer_id_predictor_map_[event.id]->Update(data);
}
}
}
bool InputEventPrediction::ResampleSinglePointer(base::TimeTicks frame_time,
WebPointerProperties* event) {
ui::InputPredictor::InputData predict_result;
if (event->pointer_type == WebPointerProperties::PointerType::kMouse) {
if (mouse_predictor_->HasPrediction() &&
mouse_predictor_->GeneratePrediction(frame_time, &predict_result)) {
event->SetPositionInWidget(predict_result.pos);
return true;
}
} else {
// Reset mouse predictor if pointer type is touch or stylus
mouse_predictor_->Reset();
auto predictor = pointer_id_predictor_map_.find(event->id);
if (predictor != pointer_id_predictor_map_.end() &&
predictor->second->HasPrediction() &&
predictor->second->GeneratePrediction(frame_time, &predict_result)) {
event->SetPositionInWidget(predict_result.pos);
return true;
}
}
return false;
}
void InputEventPrediction::ResetSinglePredictor(
const WebPointerProperties& event) {
if (event.pointer_type == WebPointerProperties::PointerType::kMouse)
mouse_predictor_->Reset();
else
pointer_id_predictor_map_.erase(event.id);
}
} // namespace content
| [
"team@geometry.ee"
] | team@geometry.ee |
7161a782338bbd493a0f853fe7ad69bf828fd956 | 9cb1727433c8da111f08ba139402761ad4169e57 | /SFML Wave function collapse/main.cpp | 028a71a5d8a6469719f435179877c766b4a4e539 | [] | no_license | Diemoonn/SFML-Wave-function-collapse-ESTM- | 661eab7795b85712fc505a25648e6e17404e93d0 | 8c3e2a01e75b2547990ec923236239356947dbd1 | refs/heads/master | 2023-07-14T15:55:06.749909 | 2021-08-10T08:52:11 | 2021-08-10T08:52:11 | 391,181,353 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 10,873 | cpp | #include <SFML/Graphics.hpp>
#include <vector>
#include <algorithm>
using namespace sf;
using namespace std;
struct Tile
{
string name;
Color color;
vector<string> compatible;
float probability;
};
class Cell
{
public:
vector<Tile> domain;
Tile tile;
Cell() {}
Cell(Vector2f position, vector<Tile> tiles)
{
cell.setPosition(position);
cell.setSize(Vector2f(16, 16));
cell.setFillColor(color);
for (unsigned int i = 0; i < tiles.size(); i++) // заполняем домен возможными вариантами тайлов
{
domain.push_back(tiles[i]);
entropia++;
}
decided = false;
}
void decideRandom()
{
int randIndex, randKoef;
float result;
do {
randIndex = rand() % domain.size() + 0;
randKoef = rand() % 10 + 1;
result = randKoef * domain[randIndex].probability;
} while (result < 1);
tile = domain[randIndex];
color = tile.color;
cell.setFillColor(color);
decided = true;
}
void setTile(Tile newTile)
{
tile = newTile;
color = tile.color;
cell.setFillColor(color);
}
bool isDecided() const
{
return decided;
}
int getEntropia() const
{
return entropia;
}
vector<string> getCompatible() const
{
return tile.compatible;
}
void drawCell(RenderWindow &window) const
{
window.draw(cell);
}
private:
RectangleShape cell;
int entropia = 0;
bool decided;
Color color = Color::Green;
};
void initCells(vector<Cell> &map, vector<Tile> tiles)
{
// заполняет карту клетками в суперпозиции
for (int y = 0; y < 256; y += 16)
{
for (int x = 0; x < 256; x += 16)
{
Cell newCell(Vector2f(x, y), tiles);
map.push_back(newCell);
}
}
}
void setNewState(vector<Cell> &map, int index)
{
// выбирает новое состояние для клетки
map[index].decideRandom();
}
/*
void initTiles(int tilesetWidth, int tilesetHeight)
{
// читает данные их config-file и на их основе создаёт тайлы
Texture tileset;
tileset.loadFromFile("resourses/tiles textures/tileset.png");
for (int y = 0; y < tilesetHeight; y+=16)
{
for (int x = 0; x < tilesetWidth; x+=16)
{
Tile newTile;
}
}
}
*/
void findNeighboors(int (&near)[4], int index)
{
// записывает в принимаемый массив индексы смежных с данной клеток
int leftSide[14] = { 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224 };
int rightSide[14] = { 31, 47, 63, 79, 95, 111, 127, 143, 159, 175, 191, 207, 223, 239 };
// проверяем, находится ли элемент с индексом index в углах
switch (index)
{
case 0: // левый верхний
near[0] = index + 1;
near[1] = index + 16; // 16 в данном случае и дальше в функции - кол-во клеток по вертикали и горизонтали. Это изменяемый параметр
break;
case 15: // правый верхний
near[0] = index - 1;
near[1] = index + 16;
break;
case 240: // левый нижний
near[0] = index - 16;
near[1] = index + 1;
break;
case 255: // правый нижний
near[0] = index - 16;
near[1] = index - 1;
}
// проверяем, находится ли клетка в верхнем ряду
if (index >= 1 && index <= 14)
{
near[0] = index - 1;
near[1] = index + 1;
near[2] = index + 16;
}
else if (index >= 241 && index <= 254) // проверяем, находится ли клетка в нижнем ряду
{
near[0] = index - 1;
near[1] = index + 1;
near[2] = index - 16;
}
// проверяем, находится ли клетка на левой стороне
for (int i = 0; i <= 13; i++)
{
if (leftSide[i] == index)
{
near[0] = index - 16;
near[1] = index + 1;
near[2] = index + 16;
}
}
if (near[0] == -1)
{
near[0] = index - 1;
near[1] = index + 1;
near[2] = index - 16;
near[3] = index + 16;
}
// проверяем, находится ли клетка на правой стороне
for (int i = 0; i <= 13; i++)
{
if (rightSide[i] == index)
{
near[0] = index - 16;
near[1] = index - 1;
near[2] = index + 16;
}
}
// проверяем, находится ли клетка во внутреннем квадрате
if (near[0] == -1)
{
near[0] = index - 1;
near[1] = index + 1;
near[2] = index - 16;
near[3] = index + 16;
}
}
void extend(vector<Cell> &map, int index)
{
// распространяет ограничения
/*
алгоритм распространения ограничений
взять последнюю решённую клетку
вычислить её соседей
для каждой соседней нерешённой клетки
сравнить домен соседней и возможные варианты текущей
выкинуть из домена соседней клетки, не входящие в варианты текущей
*/
int near[4] = { -1, -1, -1, -1 };
findNeighboors(near, index);
int neighboor;
for (int i = 0; i < 4; i++)
{
if (near[i] == -1)
continue;
neighboor = near[i];
vector<string>::iterator startSearch = map[index].tile.compatible.begin();
vector<string>::iterator finishSearch = map[index].tile.compatible.end();
if (map[neighboor].isDecided() == false) // обрабатываем только нерешённые смежные тайлы
{
/*Для каждого варианта в домене нерешённой ищем соответствующий в вариантах решённой. Если ничего
не нашли - удаляем вариант из домена*/
for (unsigned int i = 0; i < map[neighboor].domain.size(); i++) /*проходим по домену нерешённой клетки*/
{
bool found = false;
/*поиск текущего элемента из домена в возможных вариантах клетки.*/
string searchString = map[neighboor].domain[i].name;
vector<string>::const_iterator tileIter = find(startSearch, finishSearch, searchString);
if (tileIter != map[index].tile.compatible.end())
found = true;
if (found == false)
map[neighboor].domain.erase(map[neighboor].domain.begin() + i);
}
}
}
}
void sandFilter(vector<Cell> &map, Tile filterTile)
{
// заменяет песок на землю, если клетка, содержащая песок, не граничит с водой
int neighboors[4] = { -1, -1, -1, -1 };
int currentNeighboor;
bool hasWater;
for (unsigned int i = 0; i < map.size(); i++) // перебор всей карты
{
if (map[i].tile.name == "sand") // если нашли песок
{
neighboors[0] = -1;
neighboors[1] = -1;
neighboors[2] = -1;
neighboors[3] = -1;
hasWater = false;
findNeighboors(neighboors, i); // ищем соседей
for (int j = 0; j < 4; j++) // перебор соседей
{
currentNeighboor = neighboors[j];
if (currentNeighboor != -1)
{
if (map[currentNeighboor].tile.name == "water") // если сосед - вода
hasWater = true;
}
}
if (hasWater == false)
map[i].setTile(filterTile);
}
}
}
void drawMap(RenderWindow &window, vector<Cell> map)
{
// рисует готовую карту
for (unsigned int i = 0; i < map.size(); i++)
map[i].drawCell(window);
}
int main()
{
RenderWindow window(sf::VideoMode(256, 256), "SFML Wave function collapse");
srand(static_cast<unsigned int> (time(0)));
Tile water, sand, ground;
water.name = "water";
sand.name = "sand";
ground.name = "ground";
water.probability = 0.5;
sand.probability = 0.1;
ground.probability = 0.5;
water.color = Color::Blue;
sand.color = Color::Yellow;
ground.color = Color::Green;
water.compatible.push_back("water");
water.compatible.push_back("sand");
sand.compatible.push_back("water");
sand.compatible.push_back("sand");
sand.compatible.push_back("ground");
ground.compatible.push_back("sand");
ground.compatible.push_back("ground");
vector<Tile> tiles;
tiles.push_back(water);
tiles.push_back(sand);
tiles.push_back(ground);
vector<Cell> map;
// заполнить поверхность клетками в суперпозиции
initCells(map, tiles);
int lastDecided = 0;
for (int i = 0; i < 256; i++)
{
// локально распространить ограничения
extend(map, lastDecided);
// выбор клетки с наименьшей энтропией
int minEntropia = 4;
int minIndex = 0;
for (unsigned int j = 0; j < map.size(); j++)
{
if ((map[j].getEntropia() < minEntropia) && (map[j].isDecided() == false))
{
minEntropia = map[j].getEntropia();
minIndex = j;
}
}
// решение клетки с наименьшей энтропией
setNewState(map, minIndex);
lastDecided = minIndex;
}
sandFilter(map, ground);
while (window.isOpen())
{
Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
// drawing;
drawMap(window, map);
window.display();
}
return 0;
} | [
"gordienko.gordienkodima2004@yandex.ru"
] | gordienko.gordienkodima2004@yandex.ru |
cb7d2fab916674aca8dd89c4db34bfdbf9808538 | 714405f5edf52445771d680083c6d891b20f02b4 | /ClothApp/UserInteraction.cpp | 8958031318dd65c04c9973d25b81ecdbfcfc0a3e | [] | no_license | PeterZs/FastMassSpring-1 | 5fad64c8ad1d501705e1f69a9d08125a60fea8ab | 180015bdf09d1b70445b0835b4f9da0b485f33b5 | refs/heads/master | 2020-04-11T20:42:09.041378 | 2018-12-16T16:31:58 | 2018-12-16T16:31:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 869 | cpp | #include "UserInteraction.h"
#include <GL/glew.h>
#include <iostream>
#include <cmath>
UserInteraction::UserInteraction(float* vbuff, int n)
: vbuff(vbuff), fixer(vbuff, 3 * n * n), n(n), i(-1) {}
int UserInteraction::colorToIndex(color c) {
if (c[2] != 51) return -1;
int vx = std::round((n - 1) * c[0] / 255.0);
int vy = std::round((n - 1) * c[1] / 255.0);
return 3 * n * vy + 3 * vx;
}
void UserInteraction::grabPoint(int mouse_x, int mouse_y){
// read color
color c(3);
glReadPixels(mouse_x, mouse_y, 1, 1, GL_RGB, GL_UNSIGNED_BYTE, &c[0]);
i = colorToIndex(c);
fixer.addPoint(i);
}
void UserInteraction::releasePoint() { fixer.removePoint(i); i = -1; }
void UserInteraction::movePoint(vec3 v) {
fixer.removePoint(i);
for(int j = 0; j < 3; j++)
vbuff[i + j] += v[j];
fixer.addPoint(i);
}
void UserInteraction::fixPoints() { fixer.fixPoints(); } | [
"24758349+sam007961@users.noreply.github.com"
] | 24758349+sam007961@users.noreply.github.com |
f8ab8ba26831a6a0c93fff95d7cdf3da714b8860 | 6d90e332ed3e630429e959578df1181967c4bcaa | /AC-Submissions/problems/longest_uploaded_prefix/solution.cpp | 5dcaf09661a35bdae6eefa44d15dddd06ca52fdd | [] | no_license | amir-hosen7/LeetCode | fe27cca877b5ee8c73c00b6553b682b94351e16d | ee13b162c098276abd2f01b0ae4ea6bbe527bfa1 | refs/heads/master | 2023-02-23T04:15:52.250303 | 2023-02-13T12:57:46 | 2023-02-13T12:57:46 | 234,529,205 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,095 | cpp | class LUPrefix {
public:
int bit[200050], N;
void update(int idx, int n) {
while(idx<=n) {
bit[idx]++;
idx+=(idx&-idx);
}
}
int getSum(int idx) {
int sum=0;
while(idx>0) {
sum+=bit[idx];
idx-=(idx&-idx);
}
return sum;
}
LUPrefix(int n) {
N=n;
for(int i=0; i<=N; i++){
bit[i]=0;
}
}
int res;
void upload(int video) {
update(video, N);
//cout<<video<<" "<<getSum(10)<<"\n";
int l=0, r=N;
while(l<=r){
int mid=l+(r-l)/2;
//cout<<mid<<" "<<getSum(mid)<<"\n";
if(mid==getSum(mid)){
res=mid, l=mid+1;
}
else{
r=mid-1;
}
}
}
int longest() {
//cout<<"fahim\n";
return res;
}
};
/**
* Your LUPrefix object will be instantiated and called as such:
* LUPrefix* obj = new LUPrefix(n);
* obj->upload(video);
* int param_2 = obj->longest();
*/ | [
"42311923+amantuamir@users.noreply.github.com"
] | 42311923+amantuamir@users.noreply.github.com |
b5203eaf4da139e149a5a63d2aef8ed929676ec4 | 31589435071cbff4c5e95b357d8f3fa258f43269 | /PPTVForWin8/ppbox_1.2.0/src/p2p/server_mod/natcheck/base/AppBuffer.h | bac1bf86523aaa1dd272e51f86b151073c928397 | [] | no_license | huangyt/MyProjects | 8d94656f41f6fac9ae30f089230f7c4bfb5448ac | cd17f4b0092d19bc752d949737c6ed3a3ef00a86 | refs/heads/master | 2021-01-17T20:19:35.691882 | 2013-05-03T07:19:31 | 2013-05-03T07:19:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,273 | h | #ifndef _BUFFER_H_
#define _BUFFER_H_
#include "Common.h"
typedef boost::uint8_t byte;
namespace base
{
struct AppBuffer
{
public:
enum { BUF_NORMAL, BUF_SUBPIECE };
private:
boost::shared_array<byte> data_;
protocol::SubPieceContent::pointer subpiece_;
size_t length_;
size_t offset_;
size_t type_;
public:
AppBuffer() :
length_(0), offset_(0), type_(BUF_NORMAL)
{
}
AppBuffer(const AppBuffer& buffer)
{
if (this != &buffer)
{
data_ = buffer.data_;
subpiece_ = buffer.subpiece_;
length_ = buffer.length_;
offset_ = buffer.offset_;
type_ = buffer.type_;
}
}
AppBuffer& operator =(const AppBuffer& buffer)
{
if (this != &buffer)
{
data_ = buffer.data_;
subpiece_ = buffer.subpiece_;
length_ = buffer.length_;
offset_ = buffer.offset_;
type_ = buffer.type_;
}
return *this;
}
explicit AppBuffer(const protocol::SubPieceBuffer& buffer)
{
length_ = buffer.Length();
offset_ = buffer.Offset();
subpiece_ = buffer.GetSubPieceBuffer();
type_ = BUF_SUBPIECE;
}
explicit AppBuffer(size_t length) :
data_(new byte[length]), length_(length), offset_(0), type_(BUF_NORMAL)
{
}
explicit AppBuffer(size_t length, int val) :
data_(new byte[length]), length_(length), offset_(0), type_(BUF_NORMAL)
{
memset((void*)data_.get(), val, length);
}
explicit AppBuffer(const string& str)
: data_(new byte[str.length()]), length_(str.length()), offset_(0), type_(BUF_NORMAL)
{
memcpy(data_.get(), str.c_str(), length_);
}
AppBuffer(const char* data, size_t length) :
data_(new byte[length]), length_(length), offset_(0), type_(BUF_NORMAL)
{
memcpy(data_.get(), data, length);
}
AppBuffer(const byte* data, size_t length) :
data_(new byte[length]), length_(length), offset_(0), type_(BUF_NORMAL)
{
memcpy(data_.get(), data, length);
}
AppBuffer(boost::shared_array<byte> data, size_t length) :
data_(new byte[length]), length_(length), offset_(0), type_(BUF_NORMAL)
{
memcpy(data_.get(), data.get(), length);
}
bool Add(const byte* data, size_t length)
{
if (offset_ + length >= length_)
{
return false;
}
memcpy(data_.get()+offset_, data, length);
}
inline byte* Data() const
{
if (BUF_NORMAL == type_) {
return &data_[offset_];
}
else if (BUF_SUBPIECE == type_) {
return *subpiece_;
}
return NULL;
}
inline byte* Data(size_t offset) const
{
byte* base_ptr = Data();
if (base_ptr != NULL) {
return base_ptr + offset;
}
return NULL;
}
inline size_t Length() const
{
return length_;
}
size_t Type() const
{
return type_;
}
size_t Offset() const
{
return offset_;
}
void Data(boost::shared_array<byte> data)
{
data_ = data;
type_ = BUF_NORMAL;
}
void Length(size_t length)
{
length_ = length;
}
void Offset(size_t offset)
{
offset_ = offset;
}
AppBuffer SubBuffer(size_t offset) const
{
AppBuffer buffer;
if (offset < length_)
{
buffer.offset_ = offset_ + offset;
buffer.length_ = length_ - offset;
buffer.data_ = data_;
buffer.subpiece_ = subpiece_;
buffer.type_ = type_;
}
return buffer;
}
AppBuffer SubBuffer(size_t offset, size_t length) const
{
AppBuffer buffer;
if (offset + length <= length_)
{
buffer.offset_ = offset_ + offset;
buffer.length_ = length;
buffer.data_ = data_;
buffer.subpiece_ = subpiece_;
buffer.type_ = type_;
}
return buffer;
}
void Malloc(size_t length)
{
length_ = length;
data_ = boost::shared_array<byte>(new byte[length_]);
offset_ = 0;
type_ = BUF_NORMAL;
}
AppBuffer Clone() const
{
return AppBuffer(Data(), length_);
}
void Clear(byte padding = 0)
{
if (length_ > 0)
{
memset(Data(), padding, length_);
}
}
bool operator !() const
{
return length_ == 0;
}
operator bool() const
{
return length_ != 0;
}
bool operator ==(const AppBuffer& buffer) const
{
return data_.get() == buffer.data_.get() && length_ == buffer.length_
&& offset_ == buffer.offset_ && type_ == buffer.type_;
}
bool operator <(const AppBuffer& b2) const
{
if (type_ != b2.type_)
{
return type_ < b2.type_;
}
else if (data_.get() != b2.data_.get())
{
return data_.get() < b2.data_.get();
}
else if (offset_ != b2.offset_)
{
return offset_ < b2.offset_;
}
else
{
return length_ < b2.length_;
}
}
};
struct TempBuffer
{
AppBuffer buffer_;
byte* data_;
size_t length_;
TempBuffer(const AppBuffer& buffer, byte* data, size_t length) :
buffer_(buffer), data_(data), length_(length)
{
assert(buffer);
assert(data >= buffer.Data());
assert(data < buffer.Data() + buffer.Length());
}
TempBuffer(const AppBuffer& buffer, size_t offset, size_t length) :
buffer_(buffer), data_(buffer_.Data() + offset), length_(length)
{
assert(buffer);
assert(offset >= 0);
assert(offset < buffer_.Length());
}
TempBuffer(const AppBuffer& buffer, byte* data) :
buffer_(buffer), data_(data)
{
assert(buffer);
assert(data >= buffer.Data());
assert(data < buffer.Data() + buffer.Length());
length_ = buffer.Length() - (data - buffer.Data());
}
TempBuffer(const AppBuffer& buffer, size_t offset) :
buffer_(buffer), data_(buffer_.Data() + offset), length_(buffer_.Length() - offset)
{
assert(buffer);
assert(offset >= 0);
assert(offset < buffer_.Length());
}
inline byte* Get() const
{
return data_;
}
inline size_t GetLength() const
{
return length_;
}
inline bool operator ==(const TempBuffer& buffer)
{
return buffer_ == buffer.buffer_ && Get() == buffer.Get() && GetLength() == buffer.GetLength();
}
inline AppBuffer ToBuffer()
{
return AppBuffer(Get(), GetLength());
}
};
inline bool operator <(const TempBuffer& b1, const TempBuffer& b2)
{
if (b1.buffer_ == b2.buffer_)
{
if (b1.Get() != b2.Get())
return b1.Get() < b2.Get();
else
return b1.GetLength() < b2.GetLength();
}
else
{
return b1.buffer_ < b2.buffer_;
}
}
}
#endif // _BUFFER_H_
| [
"penneryu@outlook.com"
] | penneryu@outlook.com |
caa6d824924cce0c0fb30f7f346ca226c69781cd | ce87d9968abead1aaa084a343f9f18379d666922 | /src/actor/actor_actions/use_skill_action.cpp | a60b22bb73bb57af8e579854e022e7360d19590b | [] | no_license | lonski/amarlon | eec7cbf6da257bbc4d2385e1b3f64631c970536d | fd9abe327f98bd7050aef193803f5d9cba0bf5f1 | refs/heads/master | 2022-01-14T21:32:12.203539 | 2021-12-30T10:28:04 | 2021-12-30T10:28:04 | 24,822,534 | 7 | 3 | null | 2015-05-17T12:08:49 | 2014-10-05T18:18:47 | C++ | UTF-8 | C++ | false | false | 693 | cpp | #include "use_skill_action.h"
#include <skill.h>
namespace amarlon {
UseSkillAction::UseSkillAction(SkillPtr skill, Target target)
: _skill(skill)
, _target(target)
{
}
UseSkillAction::~UseSkillAction()
{
}
ActorActionResult UseSkillAction::perform(ActorPtr user)
{
_user = user;
ActorActionResult r = ActorActionResult::Nok;
if ( _user && _skill )
{
r = _skill->use(_user, _target) ? ActorActionResult::Ok
: ActorActionResult::Nok;
}
return r;
}
ActorActionUPtr UseSkillAction::clone()
{
UseSkillActionUPtr cloned = std::make_unique<UseSkillAction>(_skill, _target);
cloned->_user = _user;
return std::move(cloned);
}
}
| [
"michal@lonski.pl"
] | michal@lonski.pl |
59a2f96238c3ef4c78e821e4cf02189378c9d291 | 7b36063fb05909c9bca723e677b083fb7349ef04 | /algorithm/0258-add-digits/solution.cc | 7d3e0da57a6d997ae199b646c91c356060719171 | [] | no_license | Liam0205/leetcode | c3dff919fbd596ed3bcea514c599c18c66b4a388 | 64c668a8f47a8e649e90a5881a884559c31a1a1c | refs/heads/master | 2022-02-20T19:37:38.492782 | 2022-02-08T10:07:10 | 2022-02-08T10:19:02 | 49,959,125 | 7 | 4 | null | 2018-11-26T01:34:55 | 2016-01-19T14:46:23 | C++ | UTF-8 | C++ | false | false | 120 | cc | class Solution {
public:
int addDigits(int num) {
return (num - (int) (9 * floor((num - 1) / 9)));
}
};
| [
"liamhuang0205@gmail.com"
] | liamhuang0205@gmail.com |
583bf96fcdb0de09d9bf5c85e9072c65e81c4f6f | 91721cafcc790673eb39c99be05bad570aedef74 | /Leetcode practice/260. Single Number III.cpp | 52ea46751904be465f9befb8519d0f87e0ead1f5 | [] | no_license | olee12/Leetcode-practice | 6631d559377d926c480b3115c75b1348be5c55fe | ea4649601af66193da036c4cce6032a22b1a673b | refs/heads/master | 2022-07-09T09:04:26.542487 | 2022-07-02T05:16:10 | 2022-07-02T05:16:10 | 81,569,221 | 0 | 0 | null | 2020-10-13T10:30:13 | 2017-02-10T13:45:44 | C++ | UTF-8 | C++ | false | false | 575 | cpp | #include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
long long mask = 0;
for(auto n:nums) mask ^= n;
long long diff = mask & (-mask);
long long x = 0;
for(auto n:nums) if(diff & n) x^=n;
return {(int)x, (int)(x^mask)};
}
};
int main(int argc, char const *argv[])
{
vector<int> t1 = {1,2,1,3,2,5};
Solution sol;
for(auto it:sol.singleNumber(t1)) {
cout << it << " ";
}
cout << endl;
return 0;
}
| [
"tahmid.hossain@shopee.com"
] | tahmid.hossain@shopee.com |
573dd44f707a3e83a1cc3827ac3e2c2b49dfc963 | 759ec1fd0308bcb3471dcddffb3a665a9e9c1479 | /src/Camera_I.hpp | f3c534a70f866fcd6272bb359f6ccdf8502a8722 | [] | no_license | pfriesch/makingOfMoon | 8787644a560d817b10bc7663afd7caac0b445264 | b0916525b81bb0453911559c46f9944df61d4892 | refs/heads/master | 2021-09-04T00:36:53.951178 | 2018-01-11T22:59:02 | 2018-01-11T22:59:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 188 | hpp | #pragma once
#include "common.hpp"
#include "WindowManager.hpp"
class Camera_I : public WindowEventListener {
public:
virtual void onWindowSizeChanged(int width, int height) = 0;
};
| [
"p.friesch@posteo.de"
] | p.friesch@posteo.de |
9242fa7fc26623e3a845dd9eef457bcaf56392c3 | 76f79c8242b5e68f3fba1afdb134608482aced6d | /DogsMustDie/Classes/BuyScene.h | 6c0c35455862a89101e82b66037b00a561d368c4 | [] | no_license | daoduchai/DogsMustDie | 92a66d978bbcc349b45a635d96c576cad02c8e03 | f07d7cd33d4a66fc4c952ac5d4d3e10d8ae0e644 | refs/heads/master | 2021-01-22T08:40:00.115080 | 2013-05-16T16:00:27 | 2013-05-16T16:00:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 360 | h |
#ifndef BuyScene_h__
#define BuyScene_h__
#include "cocos2d.h"
#include "Box2D/Box2D.h"
#include "SimpleAudioEngine.h"
#include "BuyLayer.h"
class BuyScene : public cocos2d::CCScene
{
public:
BuyScene(void);
~BuyScene(void);
virtual bool init();
CREATE_FUNC(BuyScene);
CC_SYNTHESIZE(BuyLayer*, m_pBuyLayer, BuyLayer);
};
#endif // BuyScene_h__ | [
"25331812a"
] | 25331812a |
7f225e4572a4b77fd2886bd069462abad2baa9c0 | e7428bcf823db625cdd988f9a2a57e146f3b74d8 | /src/amount.cpp | dd572cd103ba5a82edde7bee51dec9225d304f2c | [
"MIT"
] | permissive | 4XT-Forex-Trading/4xt | bf8ddcc7df0d76f7def4531a3e37b8c16ee0ca50 | ab8d27b4e760281e8e4d974044e1ddca4ae626f0 | refs/heads/master | 2021-05-17T01:32:43.492049 | 2020-03-27T14:34:59 | 2020-03-27T14:34:59 | 250,557,908 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 860 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2015-2019 The PIVX developers
// Copyright (c) 2020 The Forex Trading developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "amount.h"
#include "tinyformat.h"
CFeeRate::CFeeRate(const CAmount& nFeePaid, size_t nSize)
{
if (nSize > 0)
nSatoshisPerK = nFeePaid * 1000 / nSize;
else
nSatoshisPerK = 0;
}
CAmount CFeeRate::GetFee(size_t nSize) const
{
CAmount nFee = nSatoshisPerK * nSize / 1000;
if (nFee == 0 && nSatoshisPerK > 0)
nFee = nSatoshisPerK;
return nFee;
}
std::string CFeeRate::ToString() const
{
return strprintf("%d.%08d 4XT/kB", nSatoshisPerK / COIN, nSatoshisPerK % COIN);
}
| [
"4XT-Forex-Trading@users.noreply.github.com"
] | 4XT-Forex-Trading@users.noreply.github.com |
40ca0d843b7924ab3c0e8d30880f0d9df6d0a20c | ec68c973b7cd3821dd70ed6787497a0f808e18e1 | /Cpp/SDK/Character_RiftWalker_Clone_Male_AnimBP_parameters.h | 8ea0b46479436b3c7d4fbe63ef233f98784de803 | [] | no_license | Hengle/zRemnant-SDK | 05be5801567a8cf67e8b03c50010f590d4e2599d | be2d99fb54f44a09ca52abc5f898e665964a24cb | refs/heads/main | 2023-07-16T04:44:43.113226 | 2021-08-27T14:26:40 | 2021-08-27T14:26:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 653 | h | #pragma once
// Name: Remnant, Version: 1.0
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Parameters
//---------------------------------------------------------------------------
// Function Character_RiftWalker_Clone_Male_AnimBP.Character_RiftWalker_Clone_Male_AnimBP_C.ExecuteUbergraph_Character_RiftWalker_Clone_Male_AnimBP
struct UCharacter_RiftWalker_Clone_Male_AnimBP_C_ExecuteUbergraph_Character_RiftWalker_Clone_Male_AnimBP_Params
{
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"zp2kshield@gmail.com"
] | zp2kshield@gmail.com |
610098b47f76932e4c841d8d53c9f64079c81a84 | ac62c3107b48aab1267c1e0e75653e9f3ded6e49 | /_COISA/exemplo_console/mysocket.h | b72b10f2323722f8b53c0aed0c798a6af441edb3 | [] | no_license | lariskelmer/programacao-avancada | e61bfd62902efea407f3c44f315ef1da306e2857 | 15c5129d998ff949c3ea0926ee2f5de3fa15c752 | refs/heads/master | 2020-08-30T12:26:37.924282 | 2019-10-30T19:18:44 | 2019-10-30T19:18:44 | 218,379,914 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,148 | h | #ifndef _MYSOCKET_H_
#define _MYSOCKET_H_
#include <iostream>
#include <string>
#include <stdint.h>
/* #############################################################
## ATENCAO: VOCE DEVE DESCOMENTAR UMA DAS LINHAS ABAIXO ##
## PARA PODER COMPILAR NO WINDOWS OU NO LINUX ##
############################################################# */
#define _SOP_WINDOWS_
//#define _SOP_LINUX_
// As linhas necessarias para compilar no Windows
#ifdef _SOP_WINDOWS_
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x501
#endif // _WIN32_WINNT
#include <winsock2.h>
#include <ws2tcpip.h>
#endif // _SOP_WINDOWS_
// As linhas necessarias para compilar no Linux
#ifdef _SOP_LINUX_
typedef int SOCKET;
#define SOCKET_ERROR -1
#define INVALID_SOCKET -1
#include <sys/socket.h>
#endif // _SOP_LINUX_
typedef int MYSOCKET_STATUS;
#define SOCKET_OK 0
// Valor de retorno quando o outro socket encerrou a conexao corretamente
#define SOCKET_DISCONNECTED -666
// Valor de retorno em caso de timeout
#define SOCKET_TIMEOUT -999
#define TAM_MAX_MSG_STRING 256
// Predefinicao das classes
class mysocket_queue;
class tcp_mysocket;
class tcp_mysocket_server;
/* #############################################################
## A classe base dos sockets ##
############################################################# */
class mysocket
{
private:
SOCKET id;
public:
/// Construtor por default
inline mysocket(): id(INVALID_SOCKET) {}
/// Permuta dois sockets
/// Geralmente, deve ser utilizado ao inves do operador de atribuicao
void swap(mysocket &S);
/// Fecha (caso esteja aberto) um socket
void close();
/// Testa se um socket eh "virgem" ou foi fechado
inline bool closed() const {return id==INVALID_SOCKET;}
/// Testa se um socket estah aberto (aceitando conexoes)
inline bool accepting() const {return !closed();}
/// Testa se um socket estah conectado (pronto para ler e escrever)
inline bool connected() const {return !closed();}
/// Imprime um socket
friend std::ostream& operator<<(std::ostream& os, const mysocket &);
/// As classes amigas
friend class tcp_mysocket;
friend class tcp_mysocket_server;
friend class mysocket_queue;
};
/* #############################################################
## As classes dos sockets orientados a conexao (TCP) ##
############################################################# */
class tcp_mysocket: public mysocket
{
public:
/// Construtor default
inline tcp_mysocket(): mysocket() {}
/// Se conecta a um socket aberto
/// Soh pode ser usado em sockets "virgens" ou explicitamente fechados
/// Retorna SOCKET_OK, se tudo deu certo, ou outro valor, em caso de erro
MYSOCKET_STATUS connect(const char *name, const char *port);
/// Leh de um socket conectado
/// Soh pode ser usado em socket para o qual tenha sido feito um "connect" antes
/// Ou entao em um socket retornado pelo "accept" de um socket servidor
/// O ultimo parametro eh o tempo maximo (em milisegundos) para esperar
/// por dados; se for <0, que eh o default, espera indefinidamente.
/// Retorna:
/// - o numero de bytes lidos (ou seja, len, >0), em caso de sucesso;
/// - SOCKET_TIMEOUT, se retornou por timeout;
/// - SOCKET_DISCONNECTED, se a conexao foi fechada corretamente; ou
/// - SOCKET_ERRO, em caso de erro
MYSOCKET_STATUS read(char *dado, size_t len, long milisec=-1) const;
/// Escreve em um socket conectado
/// Soh pode ser usado em socket para o qual tenha sido feito um "connect" antes
/// Ou entao em um socket retornado pelo "accept" de um socket servidor
/// Retorna:
/// - o numero de bytes enviados (ou seja, len), em caso de sucesso; ou
/// - SOCKET_ERRO, em caso de erro
MYSOCKET_STATUS write(const char* dado, size_t len) const;
/// Leh um int32_t de um socket conectado
/// O ultimo parametro eh o tempo maximo (em milisegundos) para esperar
/// por dados; se for <0, que eh o default, espera indefinidamente.
/// Retorna:
/// - o numero de bytes lidos (ou seja, 4), em caso de sucesso;
/// - SOCKET_TIMEOUT, se retornou por timeout;
/// - SOCKET_DISCONNECTED, se a conexao foi fechada corretamente; ou
/// - SOCKET_ERRO, em caso de erro
MYSOCKET_STATUS read_int(int32_t &num, long milisec=-1) const;
/// Escreve um int32_t em um socket conectado
/// Retorna o numero de bytes enviados (ou seja, 4), em caso de sucesso,
/// ou SOCKET_ERRO
MYSOCKET_STATUS write_int(const int32_t num) const;
/// Leh uma string de um socket conectado
/// Primeiro leh o numero de bytes da string (int32_T), depois os caracteres
/// O ultimo parametro eh o tempo maximo (em milisegundos) para esperar
/// por dados; se for <0, que eh o default, espera indefinidamente.
/// Retorna:
/// - o numero de bytes lidos (ou seja, msg.size()), em caso de sucesso;
/// - SOCKET_TIMEOUT, se retornou por timeout;
/// - SOCKET_DISCONNECTED, se a conexao foi fechada corretamente; ou
/// - SOCKET_ERRO, em caso de erro
MYSOCKET_STATUS read_string(std::string &msg, long milisec=-1) const;
/// Escreve uma string em um socket conectado
/// Primeiro escreve o numero de bytes da string (int32_T), depois os caracteres
/// Retorna o numero de bytes enviados (ou seja, msg.size()), em caso de sucesso,
/// ou SOCKET_ERRO
MYSOCKET_STATUS write_string(const std::string &msg) const;
};
class tcp_mysocket_server: public mysocket
{
public:
/// Construtor default
inline tcp_mysocket_server(): mysocket() {}
/// Abre um novo socket para esperar conexoes
/// Soh pode ser usado em sockets "virgens" ou explicitamente fechados
/// Retorna SOCKET_OK ou SOCKET_ERRO
MYSOCKET_STATUS listen(const char *port, int nconex=1);
/// Aceita uma conexao que chegou em um socket aberto
/// Soh pode ser usado em socket para o qual tenha sido feito um "listen" antes
/// O socket "a" passado como parametro, em caso de sucesso, estarah conectado
/// (nao-conectado em caso de erro)
/// Retorna SOCKET_OK ou SOCKET_ERRO
MYSOCKET_STATUS accept(tcp_mysocket &a) const;
};
/* #############################################################
## A fila de sockets ##
############################################################# */
class mysocket_queue
{
private:
fd_set set;
/// Construtor por copia
/// NUNCA DEVE SER CHAMADO OU UTILIZADO
mysocket_queue(const mysocket_queue &S);
/// Operador de atribuicao
/// NUNCA DEVE SER CHAMADO OU UTILIZADO
void operator=(const mysocket_queue &S);
public:
/// Limpa a lista de sockets
inline void clean() {FD_ZERO(&set);};
/// Construtor e destrutor
inline mysocket_queue() {clean();}
inline ~mysocket_queue() {clean();}
/// Adiciona um socket a uma fila de sockets
/// Retorna SOCKET_OK ou SOCKET_ERRO
MYSOCKET_STATUS include(const mysocket &a);
/// Retira um socket de uma fila de sockets
/// Retorna SOCKET_OK ou SOCKET_ERRO
MYSOCKET_STATUS exclude(const mysocket &a);
/// Bloqueia ateh haver alguma atividade de leitura em socket da fila
/// Retorna:
/// - o numero de sockets (>0) que tem dados a serem lidos em caso de sucesso;
/// - SOCKET_TIMEOUT, se retornou por timeout; ou
/// - SOCKET_ERRO, em caso de erro
MYSOCKET_STATUS wait_read(long milisec=-1);
/// Bloqueia ateh haver alguma atividade de conexao em socket da fila
/// Retorna:
/// - o numero de sockets (>0) que tem dados a serem lidos em caso de sucesso;
/// - SOCKET_TIMEOUT, se retornou por timeout; ou
/// - SOCKET_ERRO, em caso de erro
inline MYSOCKET_STATUS wait_connect(long milisec=-1) {return wait_read(milisec);}
/// Bloqueia ateh haver alguma atividade de escrita em socket da fila
/// Retorna:
/// - o numero de sockets (>0) que tem dados a serem lidos em caso de sucesso;
/// - SOCKET_TIMEOUT, se retornou por timeout; ou
/// - SOCKET_ERRO, em caso de erro
MYSOCKET_STATUS wait_write(long milisec=-1);
/// Testa se houve atividade em um socket especifico da fila
bool had_activity(const mysocket &a);
};
#endif
| [
"amc.marcelino.cordeiro@gmail.com"
] | amc.marcelino.cordeiro@gmail.com |
9735167e3e5593c888fab2841b95e89e72fdb211 | e53518a04b26c3019d9a3940726c29a1b3bb6c82 | /VC_USB_GPIO_Test/USB_GPIO_Test/USB_GPIO_Test/USB_GPIO_Test.cpp | c3edcf87d113947cdb176718dcf3376218745672 | [] | no_license | viewtool/SPI_Adapter | f4aab07d1617cac9abf9604803b9267df1f01d15 | e8229060805759bee4dd6f974a24251596510b57 | refs/heads/master | 2021-01-21T06:39:24.612496 | 2020-07-06T06:52:43 | 2020-07-06T06:52:43 | 83,263,145 | 6 | 1 | null | null | null | null | GB18030 | C++ | false | false | 3,921 | cpp | /*
******************************************************************************
* @file : USB_GPIO_Test.cpp
* @Copyright: ViewTool
* @Revision : ver 1.0
* @Date : 2014/12/19 11:53
* @brief : USB_GPIO_Test demo
******************************************************************************
* @attention
*
* Copyright 2009-2014, ViewTool
* http://www.viewtool.com/
* All Rights Reserved
*
******************************************************************************
*/
#include "stdafx.h"
#include "ControlGPIO.h"
int _tmain(int argc, _TCHAR* argv[])
{
int ret;
// Scan connected device
ret = VGI_ScanDevice(1);
if (ret <= 0)
{
printf("No device connect!\n");
return ret;
}
// Open device
ret = VGI_OpenDevice(VGI_USBGPIO, 0, 0);
if (ret != ERR_SUCCESS)
{
printf("Open device error!\n");
return ret;
}
// Set GPIO_7 and GPIO_8 to output
ret = VGI_SetOutput(VGI_USBGPIO, 0, VGI_GPIO_PIN7 | VGI_GPIO_PIN8);
if (ret != ERR_SUCCESS)
{
printf("Set pin output error!\n");
return ret;
}
// Set GPIO_7 and GPIO_8
ret = VGI_SetPins(VGI_USBGPIO, 0, VGI_GPIO_PIN7 | VGI_GPIO_PIN8);
if (ret != ERR_SUCCESS)
{
printf("Set pin high error!\n");
return ret;
}
// Reset GPIO_7 and GPIO_8
ret = VGI_ResetPins(VGI_USBGPIO, 0, VGI_GPIO_PIN7 | VGI_GPIO_PIN8);
if (ret != ERR_SUCCESS)
{
printf("Set pin low error!\n");
return ret;
}
// Set GPIO_4 and GPIO_5 to input
ret = VGI_SetInput(VGI_USBGPIO, 0, VGI_GPIO_PIN4 | VGI_GPIO_PIN5);
if (ret != ERR_SUCCESS)
{
printf("Set pin input error!\n");
return ret;
}
// Get GPIO_4 and GPIO_5 status
uint16_t pin_value = 0;
ret = VGI_ReadDatas(VGI_USBGPIO, 0, VGI_GPIO_PIN4 | VGI_GPIO_PIN5, &pin_value);
if (ret != ERR_SUCCESS)
{
printf("Get pin data error!\n");
return ret;
}
else
{
if ((pin_value & VGI_GPIO_PIN4) != 0)
{
printf("GPIO_4 is high-level!\n");
}
else
{
printf("GPIO_4 is low-level!\n");
}
if ((pin_value & VGI_GPIO_PIN5) != 0)
{
printf("GPIO_5 is high-level!\n");
}
else
{
printf("GPIO_5 is low-level!\n");
}
}
//将GPIO_4和GPIO_5引脚设置成开漏模式(需加上拉电阻,可当双向口)
ret = VGI_SetOpenDrain(VGI_USBGPIO, 0, VGI_GPIO_PIN4 | VGI_GPIO_PIN5);
if (ret != ERR_SUCCESS)
{
printf("Set pin open drain error!\n");
return ret;
}
//将GPIO_4和GPIO_5输出高电平
ret = VGI_SetPins(VGI_USBGPIO, 0, VGI_GPIO_PIN4 | VGI_GPIO_PIN5);
if (ret != ERR_SUCCESS)
{
printf("Set pin high error!\n");
return ret;
}
//将GPIO_4和GPIO_5输出低电平
ret = VGI_ResetPins(VGI_USBGPIO, 0, VGI_GPIO_PIN4 | VGI_GPIO_PIN5);
if (ret != ERR_SUCCESS)
{
printf("Set pin high error!\n");
return ret;
}
//获取GPIO_4和GPIO_5引脚状态
ret = VGI_ReadDatas(VGI_USBGPIO, 0, VGI_GPIO_PIN4 | VGI_GPIO_PIN5, &pin_value);
if (ret != ERR_SUCCESS)
{
printf("Get pin data error!\n");
return ret;
}
else
{
if ((pin_value & VGI_GPIO_PIN4) != 0)
{
printf("GPIO_4 is high-level!\n");
}
else
{
printf("GPIO_4 is low-level!\n");
}
if ((pin_value & VGI_GPIO_PIN5) != 0)
{
printf("GPIO_5 is high-level!\n");
}
else
{
printf("GPIO_5 is low-level!\n");
}
}
//关闭设备
ret = VGI_CloseDevice(VGI_USBGPIO, 0);
if (ret != ERR_SUCCESS)
{
printf("Close device error!\n");
return ret;
}
return 0;
}
| [
"792499568@qq.com"
] | 792499568@qq.com |
9189c35d07bc49c3ba7ac85d1ef74c16ffd8691e | 1c21ea7d49d4d1a6dc96f40bc910496373c0190d | /Valdemar/Metaprogramming/FunctionalProgramming/typelists.cpp | 1e0c85fca7678dbf900f90f43af7d3b766136ceb | [] | no_license | tmoller96/APK | 5fcbc1677e15f6e6a3797a5e15fe72ea7e510e9b | 75d0cfd97b35b874d21656972d40c904900743e7 | refs/heads/master | 2023-02-11T16:05:31.901177 | 2021-01-08T13:27:17 | 2021-01-08T13:27:17 | 292,011,987 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,188 | cpp | #include "at_index.hpp"
#include "contains.hpp"
#include "is_same.hpp"
#include <iostream>
// #define TYPELIST1(T1) TypeList<T1, NullType>;
// #define TYPELIST2(T1, T2) TypeList<T1, T2>;
// #define TYPELIST3(T1, T2, T3) TypeList<T1, TypeList<T2, T3>>;
int main()
{
std::cout << "IsSame <int , int >:: value=" << IsSame<int, int>::value
<< std::endl;
std::cout << "IsSame <int , char >:: value=" << IsSame<int, char>::value
<< std ::endl;
typedef TypeList<int, TypeList<char, TypeList<long, NullType>>> TL;
std::cout << "Contains <TL , int >:: value=" << Contains<TL, int>::value
<< std::endl;
/* Must be false */
std::cout << "Contains <TL , std::string >:: value="
<< Contains<TL, std::string>::value << std::endl;
typedef TypeList<long, TypeList<char, TypeList<int, NullType>>> TL2;
/* Must be true */
std::cout << "IsSame <typename AtIndex <TL , 2>::type , int >:: value"
<< IsSame<typename AtIndex<TL2, 2>::type, int>::value << std::endl;
std::cout << "IsSame <typename AtIndex <TL , 2>::type , char >:: value"
<< IsSame<typename AtIndex<TL2, 2>::type, char>::value << std::endl;
}
| [
"valdemar-tang@hotmail.com"
] | valdemar-tang@hotmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.