blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
146
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
7
| license_type
stringclasses 2
values | repo_name
stringlengths 6
79
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 4
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.07k
426M
⌀ | star_events_count
int64 0
27
| fork_events_count
int64 0
12
| gha_license_id
stringclasses 3
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 6
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 1
class | length_bytes
int64 20
6.28M
| extension
stringclasses 20
values | content
stringlengths 20
6.28M
| authors
listlengths 1
16
| author_lines
listlengths 1
16
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b78fa163e0752a88c1a7f899d7aba01ef47573c8 | 1eb441701fc977785b13ea70bc590234f4a45705 | /nukak3d/include/nkToolBar.h | 0a228d7ca981079afeb413fe900dfd057a5f8ab9 | []
| no_license | svn2github/Nukak3D | 942947dc37c56fc54245bbc489e61923c7623933 | ec461c40431c6f2a04d112b265e184d260f929b8 | refs/heads/master | 2021-01-10T03:13:54.715360 | 2011-01-18T22:16:52 | 2011-01-18T22:16:52 | 47,416,318 | 1 | 2 | null | null | null | null | ISO-8859-2 | C++ | false | false | 6,013 | h | /**
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* The Original Code is Copyright (C) 2007-2010 by Bioingenium Research Group.
* Bogota - Colombia
* All rights reserved.
*
* Author(s): Alexander Pinzón Fernández.
*
* ***** END GPL LICENSE BLOCK *****
*/
/**
* @file nkToolBar.h
* @brief Toolbar of nukak3d.
* @author Alexander Pinzon Fernandez.
* @version 0.1
* @date 18/10/2007 02:50 p.m.
*/
#ifndef _NKTOOLBAR_H_
#define _NKTOOLBAR_H_
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include "wx/intl.h"
/**
* @brief Item of menu.
* @details Class for generate item for toolbar.
*/
class nkTool{
public:
/**
* @brief Class constructor.
*/
nkTool(int toolId,
const wxString& label,
const wxBitmap& bitmap1,
const wxString& shortHelpString = "",
wxItemKind kind = wxITEM_NORMAL);
/**
* @brief Class destructor.
*/
~nkTool();
/**
* @brief Generation and insertion of tool in wxToolBar.
* @param un_tool wxToolBar to insert.
*/
wxToolBarToolBase* getTool(wxToolBar * un_tool);
/**
* @brief Size: Widh and Height of item of menu.
*/
static wxSize LARGO_X_ANCHO_ICONO;
private:
/** ID of his control.*/
int prv_toolId;
/** Label for this control.*/
wxString prv_label;
/** Icon.*/
wxBitmap prv_bitmap1;
/** Help text for this control.*/
wxString prv_shortHelpString;
/** Configuration of this item (Normal, Toogle, Radio) .*/
wxItemKind prv_kind;
};
/**
* List of nkTool declaration.
*/
WX_DECLARE_LIST(nkTool, nkListaTool);
/**
* @brief Menu of items.
* @details Class for creation menu in Toolbar.
*/
class nkMenuTool: public wxPanel{
public:
/**
* @brief Id for mouse event in this menu.
*/
enum{
ID_CLICKMENU = wxID_HIGHEST + 1000
};
/**
* @brief Class constructor.
*/
nkMenuTool(wxWindow* parent,
wxWindowID id,
const wxString& nombreMenu = "Menu",
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
long style = wxNO_BORDER);
/**
* @brief Class destructor.
* @details Delete list.
*/
~nkMenuTool();
/** Widht of menu*/
static int ANCHO_TOOLBAR;
/**
* @brief Make menu.
*/
void crearMenu(void);
/**
* @brief Insert item in menu.
*/
void insertarTool(nkTool* un_tool);
/**
* @brief get nkTool of list.
* @param un_indice Position of nkTool in list.
*/
nkTool* obtenerTool(size_t un_indice);
/**
* @brief Return list len.
*/
size_t longitudLista(void);
/**
* @brief Return actual size of Menu.
*/
wxSize obtenerTamanio(void);
/**
* @brief Is display menu.
*/
bool estaDeplegado(void);
/**
* @brief Function for dropdown menu.
*/
void desplegarMenu(void);
/**
* @brief Function for hide tools in menu.
*/
void replegarMenu(void);
/**
* @brief Function for paint content of wxPanel
* @details Function for paint items in menu.
*/
void repintar(void);
/**
* @brief Function for dropdown menu or hide items in this menu.
*/
void evtClick(wxCommandEvent & WXUNUSED(evt));
/**
* @brief Call Refresh() function of wxPanel.
*/
void evtRedimensionar(wxSizeEvent & WXUNUSED(evt));
/**
* @brief Function for event EVT_PAINT.
*/
void evtRepintar(wxPaintEvent& WXUNUSED(evt));
private:
/** Label for this menu.*/
wxString prv_nombreMenu;
/** Toolbar for inset this menu.*/
wxToolBar* prv_toolbar;
/** List with items of this menu.*/
nkListaTool prv_listaTool;
/** State of menu.*/
bool prv_desplegado;
/**
* @brief call Macro for events fo this menu.
*/
DECLARE_EVENT_TABLE()
};
/**
* Declaration of list of nkMenuTool.
*/
WX_DECLARE_LIST(nkMenuTool, nkListaMenu);
/**
* @brief Toolbar for Menus.
*/
class nkToolBar: public wxScrolledWindow{
public:
/** Margins size for this control.*/
static int ALINEACION;
/**
* @brief Class constructor.
*/
nkToolBar(wxWindow* parent,
wxWindowID id = -1,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
long style = wxHSCROLL | wxVSCROLL,
const wxString& name = "scrolledWindow");
/**
* @brief Class destructor.
*/
~nkToolBar(void);
/**
* @brief Procedure for create menu.
* @param id for this control.
* @param nombreMenu label for this control.
*/
nkMenuTool* insertarMenu(long id, const wxString& nombreMenu = "Menu");
/**
* @brief Function that return nkMenuTool item of list.
* @param id key identifier in the list.
*/
nkMenuTool* obtenerMenu(long id);
/**
* @brief Function for dropdown menu.
* @param un_menu for dropdown.
*/
void desplegarMenu(nkMenuTool* un_menu);
/**
* @brief Function for hide items of menu.
* @param un_menu to hide.
*/
void replegarMenu(nkMenuTool* un_menu);
/**
* @brief Func for hide all items of all menus.
*/
void replegarMenus(void);
/**
* @brief Function to calc height of this toolbar.
*/
int alto(void);
/**
* @brief Function manager for event EVT_SIZE.
*/
void evtRedimensionar(wxSizeEvent & p_Event);
/**
* @brief Function for paint all menus.
* @details Function that paint and put menus.
*/
void evtRepintar(wxPaintEvent& WXUNUSED(evt));
private:
/** List of nkMenu.*/
nkListaMenu prv_listaMenus;
/**
* @brief Macro for manage events.
*/
DECLARE_EVENT_TABLE()
};
#endif //_NKTOOLBAR_H_ | [
"apinzonf@4b68e429-1748-0410-913f-c2fc311d3372"
]
| [
[
[
1,
266
]
]
]
|
626e156e4f719cb8cf05cae0d0ad868de097629f | 7b4e708809905ae003d0cb355bf53e4d16c9cbbc | /JuceLibraryCode/modules/juce_audio_processors/scanning/juce_PluginListComponent.cpp | 6d2ecd045de03bcc6b277813f828e94c47af5466 | []
| no_license | sonic59/JulesText | ce6507014e4cba7fb0b67597600d1cee48a973a5 | 986cbea68447ace080bf34ac2b94ac3ab46faca4 | refs/heads/master | 2016-09-06T06:10:01.815928 | 2011-11-18T01:19:26 | 2011-11-18T01:19:26 | 2,796,827 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,342 | cpp | /*
==============================================================================
This file is part of the JUCE library - "Jules' Utility Class Extensions"
Copyright 2004-11 by Raw Material Software Ltd.
------------------------------------------------------------------------------
JUCE can be redistributed and/or modified under the terms of the GNU General
Public License (Version 2), as published by the Free Software Foundation.
A copy of the license is included in the JUCE distribution, or can be found
online at www.gnu.org/licenses.
JUCE 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.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.rawmaterialsoftware.com/juce for more information.
==============================================================================
*/
BEGIN_JUCE_NAMESPACE
//==============================================================================
PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
const File& deadMansPedalFile_,
PropertiesFile* const propertiesToUse_)
: list (listToEdit),
deadMansPedalFile (deadMansPedalFile_),
optionsButton ("Options..."),
propertiesToUse (propertiesToUse_)
{
listBox.setModel (this);
addAndMakeVisible (&listBox);
addAndMakeVisible (&optionsButton);
optionsButton.addListener (this);
optionsButton.setTriggeredOnMouseDown (true);
setSize (400, 600);
list.addChangeListener (this);
updateList();
}
PluginListComponent::~PluginListComponent()
{
list.removeChangeListener (this);
}
void PluginListComponent::resized()
{
listBox.setBounds (0, 0, getWidth(), getHeight() - 30);
optionsButton.changeWidthToFitText (24);
optionsButton.setTopLeftPosition (8, getHeight() - 28);
}
void PluginListComponent::changeListenerCallback (ChangeBroadcaster*)
{
updateList();
}
void PluginListComponent::updateList()
{
listBox.updateContent();
listBox.repaint();
}
int PluginListComponent::getNumRows()
{
return list.getNumTypes();
}
void PluginListComponent::paintListBoxItem (int row,
Graphics& g,
int width, int height,
bool rowIsSelected)
{
if (rowIsSelected)
g.fillAll (findColour (TextEditor::highlightColourId));
const PluginDescription* const pd = list.getType (row);
if (pd != nullptr)
{
GlyphArrangement ga;
ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
g.setColour (Colours::black);
ga.draw (g);
const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
String desc;
desc << pd->pluginFormatName
<< (pd->isInstrument ? " instrument" : " effect")
<< " - "
<< pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
<< " / "
<< pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
if (pd->manufacturerName.isNotEmpty())
desc << " - " << pd->manufacturerName;
if (pd->version.isNotEmpty())
desc << " - " << pd->version;
if (pd->category.isNotEmpty())
desc << " - category: '" << pd->category << '\'';
g.setColour (Colours::grey);
ga.clear();
ga.addCurtailedLineOfText (Font (height * 0.6f), desc, bb.getRight() + 10.0f, height * 0.8f, width - bb.getRight() - 12.0f, true);
ga.draw (g);
}
}
void PluginListComponent::deleteKeyPressed (int lastRowSelected)
{
list.removeType (lastRowSelected);
}
void PluginListComponent::optionsMenuCallback (int result)
{
switch (result)
{
case 1:
list.clear();
break;
case 2:
list.sort (KnownPluginList::sortAlphabetically);
break;
case 3:
list.sort (KnownPluginList::sortByCategory);
break;
case 4:
list.sort (KnownPluginList::sortByManufacturer);
break;
case 5:
{
const SparseSet <int> selected (listBox.getSelectedRows());
for (int i = list.getNumTypes(); --i >= 0;)
if (selected.contains (i))
list.removeType (i);
break;
}
case 6:
{
const PluginDescription* const desc = list.getType (listBox.getSelectedRow());
if (desc != nullptr)
{
if (File (desc->fileOrIdentifier).existsAsFile())
File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
}
break;
}
case 7:
for (int i = list.getNumTypes(); --i >= 0;)
if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
list.removeType (i);
break;
default:
if (result != 0)
{
typeToScan = result - 10;
startTimer (1);
}
break;
}
}
void PluginListComponent::optionsMenuStaticCallback (int result, PluginListComponent* pluginList)
{
if (pluginList != nullptr)
pluginList->optionsMenuCallback (result);
}
void PluginListComponent::buttonClicked (Button* button)
{
if (button == &optionsButton)
{
PopupMenu menu;
menu.addItem (1, TRANS("Clear list"));
menu.addItem (5, TRANS("Remove selected plugin from list"), listBox.getNumSelectedRows() > 0);
menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox.getNumSelectedRows() > 0);
menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
menu.addSeparator();
menu.addItem (2, TRANS("Sort alphabetically"));
menu.addItem (3, TRANS("Sort by category"));
menu.addItem (4, TRANS("Sort by manufacturer"));
menu.addSeparator();
for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
{
AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
}
menu.showMenuAsync (PopupMenu::Options().withTargetComponent (&optionsButton),
ModalCallbackFunction::forComponent (optionsMenuStaticCallback, this));
}
}
void PluginListComponent::timerCallback()
{
stopTimer();
scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
}
bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
{
return true;
}
void PluginListComponent::filesDropped (const StringArray& files, int, int)
{
OwnedArray <PluginDescription> typesFound;
list.scanAndAddDragAndDroppedFiles (files, typesFound);
}
void PluginListComponent::scanFor (AudioPluginFormat* format)
{
#if JUCE_MODAL_LOOPS_PERMITTED
if (format == nullptr)
return;
FileSearchPath path (format->getDefaultLocationsToSearch());
if (propertiesToUse != nullptr)
path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
{
AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
FileSearchPathListComponent pathList;
pathList.setSize (500, 300);
pathList.setPath (path);
aw.addCustomComponent (&pathList);
aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
aw.addButton (TRANS("Cancel"), 0, KeyPress::escapeKey);
if (aw.runModalLoop() == 0)
return;
path = pathList.getPath();
}
if (propertiesToUse != nullptr)
{
propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
propertiesToUse->saveIfNeeded();
}
double progress = 0.0;
AlertWindow aw (TRANS("Scanning for plugins..."),
TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
aw.addButton (TRANS("Cancel"), 0, KeyPress::escapeKey);
aw.addProgressBarComponent (progress);
aw.enterModalState();
MessageManager::getInstance()->runDispatchLoopUntil (300);
PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
for (;;)
{
aw.setMessage (TRANS("Testing:\n\n")
+ scanner.getNextPluginFileThatWillBeScanned());
MessageManager::getInstance()->runDispatchLoopUntil (100);
if (! scanner.scanNextFile (true))
break;
if (! aw.isCurrentlyModal())
break;
progress = scanner.getProgress();
}
if (scanner.getFailedFiles().size() > 0)
{
StringArray shortNames;
for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
AlertWindow::showMessageBox (AlertWindow::InfoIcon,
TRANS("Scan complete"),
TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
+ shortNames.joinIntoString (", "));
}
#else
jassertfalse; // this method needs refactoring to work without modal loops..
#endif
}
END_JUCE_NAMESPACE
| [
"[email protected]"
]
| [
[
[
1,
320
]
]
]
|
03c9341c8646074da6d18f65bdec034b8d4a0bcd | 2d4221efb0beb3d28118d065261791d431f4518a | /OIDE源代码/OLIDE/Controls/scintilla/scintilla/src/ScintillaBase.cxx | c95d87138066e036c0393ad61aef5999def25097 | [
"LicenseRef-scancode-scintilla"
]
| permissive | ophyos/olanguage | 3ea9304da44f54110297a5abe31b051a13330db3 | 38d89352e48c2e687fd9410ffc59636f2431f006 | refs/heads/master | 2021-01-10T05:54:10.604301 | 2010-03-23T11:38:51 | 2010-03-23T11:38:51 | 48,682,489 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,561 | cxx | // Scintilla source code edit control
/** @file ScintillaBase.cxx
** An enhanced subclass of Editor with calltips, autocomplete and context menu.
**/
// Copyright 1998-2003 by Neil Hodgson <[email protected]>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include "Platform.h"
#include "Scintilla.h"
#include "PropSet.h"
#ifdef SCI_LEXER
#include "SciLexer.h"
#include "Accessor.h"
#include "DocumentAccessor.h"
#include "KeyWords.h"
#endif
#include "SplitVector.h"
#include "Partitioning.h"
#include "RunStyles.h"
#include "ContractionState.h"
#include "CellBuffer.h"
#include "CallTip.h"
#include "KeyMap.h"
#include "Indicator.h"
#include "XPM.h"
#include "LineMarker.h"
#include "Style.h"
#include "ViewStyle.h"
#include "AutoComplete.h"
#include "CharClassify.h"
#include "Decoration.h"
#include "Document.h"
#include "PositionCache.h"
#include "Editor.h"
#include "ScintillaBase.h"
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
ScintillaBase::ScintillaBase() {
displayPopupMenu = true;
listType = 0;
maxListWidth = 0;
#ifdef SCI_LEXER
lexLanguage = SCLEX_CONTAINER;
performingStyle = false;
lexCurrent = 0;
for (int wl = 0;wl < numWordLists;wl++)
keyWordLists[wl] = new WordList;
keyWordLists[numWordLists] = 0;
#endif
}
ScintillaBase::~ScintillaBase() {
#ifdef SCI_LEXER
for (int wl = 0;wl < numWordLists;wl++)
delete keyWordLists[wl];
#endif
}
void ScintillaBase::Finalise() {
Editor::Finalise();
popup.Destroy();
}
void ScintillaBase::RefreshColourPalette(Palette &pal, bool want) {
Editor::RefreshColourPalette(pal, want);
ct.RefreshColourPalette(pal, want);
}
void ScintillaBase::AddCharUTF(char *s, unsigned int len, bool treatAsDBCS) {
bool isFillUp = ac.Active() && ac.IsFillUpChar(*s);
if (!isFillUp) {
Editor::AddCharUTF(s, len, treatAsDBCS);
}
if (ac.Active()) {
AutoCompleteCharacterAdded(s[0]);
// For fill ups add the character after the autocompletion has
// triggered so containers see the key so can display a calltip.
if (isFillUp) {
Editor::AddCharUTF(s, len, treatAsDBCS);
}
}
}
void ScintillaBase::Command(int cmdId) {
switch (cmdId) {
case idAutoComplete: // Nothing to do
break;
case idCallTip: // Nothing to do
break;
case idcmdUndo:
WndProc(SCI_UNDO, 0, 0);
break;
case idcmdRedo:
WndProc(SCI_REDO, 0, 0);
break;
case idcmdCut:
WndProc(SCI_CUT, 0, 0);
break;
case idcmdCopy:
WndProc(SCI_COPY, 0, 0);
break;
case idcmdPaste:
WndProc(SCI_PASTE, 0, 0);
break;
case idcmdDelete:
WndProc(SCI_CLEAR, 0, 0);
break;
case idcmdSelectAll:
WndProc(SCI_SELECTALL, 0, 0);
break;
}
}
int ScintillaBase::KeyCommand(unsigned int iMessage) {
// Most key commands cancel autocompletion mode
if (ac.Active()) {
switch (iMessage) {
// Except for these
case SCI_LINEDOWN:
AutoCompleteMove(1);
return 0;
case SCI_LINEUP:
AutoCompleteMove( -1);
return 0;
case SCI_PAGEDOWN:
AutoCompleteMove(5);
return 0;
case SCI_PAGEUP:
AutoCompleteMove( -5);
return 0;
case SCI_VCHOME:
AutoCompleteMove( -5000);
return 0;
case SCI_LINEEND:
AutoCompleteMove(5000);
return 0;
case SCI_DELETEBACK:
DelCharBack(true);
AutoCompleteCharacterDeleted();
EnsureCaretVisible();
return 0;
case SCI_DELETEBACKNOTLINE:
DelCharBack(false);
AutoCompleteCharacterDeleted();
EnsureCaretVisible();
return 0;
case SCI_TAB:
AutoCompleteCompleted();
return 0;
case SCI_NEWLINE:
AutoCompleteCompleted();
return 0;
default:
ac.Cancel();
}
}
if (ct.inCallTipMode) {
if (
(iMessage != SCI_CHARLEFT) &&
(iMessage != SCI_CHARLEFTEXTEND) &&
(iMessage != SCI_CHARRIGHT) &&
(iMessage != SCI_CHARRIGHTEXTEND) &&
(iMessage != SCI_EDITTOGGLEOVERTYPE) &&
(iMessage != SCI_DELETEBACK) &&
(iMessage != SCI_DELETEBACKNOTLINE)
) {
ct.CallTipCancel();
}
if ((iMessage == SCI_DELETEBACK) || (iMessage == SCI_DELETEBACKNOTLINE)) {
if (currentPos <= ct.posStartCallTip) {
ct.CallTipCancel();
}
}
}
return Editor::KeyCommand(iMessage);
}
void ScintillaBase::AutoCompleteDoubleClick(void* p) {
ScintillaBase* sci = reinterpret_cast<ScintillaBase*>(p);
sci->AutoCompleteCompleted();
}
void ScintillaBase::AutoCompleteStart(int lenEntered, const char *list,bool show) {
//Platform::DebugPrintf("AutoComplete %s\n", list);
ct.CallTipCancel();
if (ac.chooseSingle && (listType == 0)) {
if (list && !strchr(list, ac.GetSeparator())) {
const char *typeSep = strchr(list, ac.GetTypesep());
size_t lenInsert = (typeSep) ? (typeSep-list) : strlen(list);
if (ac.ignoreCase) {
SetEmptySelection(currentPos - lenEntered);
pdoc->DeleteChars(currentPos, lenEntered);
SetEmptySelection(currentPos);
pdoc->InsertString(currentPos, list, lenInsert);
SetEmptySelection(currentPos + lenInsert);
} else {
SetEmptySelection(currentPos);
pdoc->InsertString(currentPos, list + lenEntered, lenInsert - lenEntered);
SetEmptySelection(currentPos + lenInsert - lenEntered);
}
return;
}
}
ac.Start(wMain, idAutoComplete, currentPos, LocationFromPosition(currentPos),
lenEntered, vs.lineHeight, IsUnicodeMode());
PRectangle rcClient = GetClientRectangle();
Point pt = LocationFromPosition(currentPos - lenEntered);
PRectangle rcPopupBounds = wMain.GetMonitorRect(pt);
if (rcPopupBounds.Height() == 0)
rcPopupBounds = rcClient;
int heightLB = 100;
int widthLB = 100;
if (pt.x >= rcClient.right - widthLB) {
HorizontalScrollTo(xOffset + pt.x - rcClient.right + widthLB);
Redraw();
pt = LocationFromPosition(currentPos);
}
PRectangle rcac;
rcac.left = pt.x - ac.lb->CaretFromEdge();
if (pt.y >= rcPopupBounds.bottom - heightLB && // Wont fit below.
pt.y >= (rcPopupBounds.bottom + rcPopupBounds.top) / 2) { // and there is more room above.
rcac.top = pt.y - heightLB;
if (rcac.top < rcPopupBounds.top) {
heightLB -= (rcPopupBounds.top - rcac.top);
rcac.top = rcPopupBounds.top;
}
} else {
rcac.top = pt.y + vs.lineHeight;
}
rcac.right = rcac.left + widthLB;
rcac.bottom = Platform::Minimum(rcac.top + heightLB, rcPopupBounds.bottom);
ac.lb->SetPositionRelative(rcac, wMain);
ac.lb->SetFont(vs.styles[STYLE_DEFAULT].font);
unsigned int aveCharWidth = vs.styles[STYLE_DEFAULT].aveCharWidth;
ac.lb->SetAverageCharWidth(aveCharWidth);
ac.lb->SetDoubleClickAction(AutoCompleteDoubleClick, this);
ac.SetList(list);
// Fiddle the position of the list so it is right next to the target and wide enough for all its strings
PRectangle rcList = ac.lb->GetDesiredRect();
int heightAlloced = rcList.bottom - rcList.top;
widthLB = Platform::Maximum(widthLB, rcList.right - rcList.left);
if (maxListWidth != 0)
widthLB = Platform::Minimum(widthLB, aveCharWidth*maxListWidth);
// Make an allowance for large strings in list
rcList.left = pt.x - ac.lb->CaretFromEdge();
rcList.right = rcList.left + widthLB;
if (((pt.y + vs.lineHeight) >= (rcPopupBounds.bottom - heightAlloced)) && // Wont fit below.
((pt.y + vs.lineHeight / 2) >= (rcPopupBounds.bottom + rcPopupBounds.top) / 2)) { // and there is more room above.
rcList.top = pt.y - heightAlloced;
} else {
rcList.top = pt.y + vs.lineHeight;
}
rcList.bottom = rcList.top + heightAlloced;
ac.lb->SetPositionRelative(rcList, wMain);
ac.Show(show);
if (lenEntered != 0) {
AutoCompleteMoveToCurrentWord();
}
}
void ScintillaBase::AutoCompleteCancel() {
ac.Cancel();
}
void ScintillaBase::AutoCompleteMove(int delta) {
ac.Move(delta);
}
void ScintillaBase::AutoCompleteMoveToCurrentWord() {
char wordCurrent[1000];
int i;
int startWord = ac.posStart - ac.startLen;
for (i = startWord; i < currentPos && i - startWord < 1000; i++)
wordCurrent[i - startWord] = pdoc->CharAt(i);
wordCurrent[Platform::Minimum(i - startWord, 999)] = '\0';
ac.Select(wordCurrent);
}
void ScintillaBase::AutoCompleteCharacterAdded(char ch) {
if (ac.IsFillUpChar(ch)) {
AutoCompleteCompleted();
} else if (ac.IsStopChar(ch)) {
ac.Cancel();
} else {
AutoCompleteMoveToCurrentWord();
}
}
void ScintillaBase::AutoCompleteCharacterDeleted() {
if (currentPos < ac.posStart - ac.startLen) {
ac.Cancel();
} else if (ac.cancelAtStartPos && (currentPos <= ac.posStart)) {
ac.Cancel();
} else {
AutoCompleteMoveToCurrentWord();
}
}
void ScintillaBase::AutoCompleteCompleted() {
int item = ac.lb->GetSelection();
char selected[1000];
selected[0] = '\0';
if (item != -1) {
ac.lb->GetValue(item, selected, sizeof(selected));
} else {
ac.Cancel();
return;
}
ac.Show(false);
listSelected = selected;
SCNotification scn = {0};
scn.nmhdr.code = listType > 0 ? SCN_USERLISTSELECTION : SCN_AUTOCSELECTION;
scn.message = 0;
scn.wParam = listType;
scn.listType = listType;
Position firstPos = ac.posStart - ac.startLen;
scn.lParam = firstPos;
scn.text = listSelected.c_str();
NotifyParent(scn);
if (!ac.Active())
return;
ac.Cancel();
if (listType > 0)
return;
Position endPos = currentPos;
if (ac.dropRestOfWord)
endPos = pdoc->ExtendWordSelect(endPos, 1, true);
if (endPos < firstPos)
return;
pdoc->BeginUndoAction();
if (endPos != firstPos) {
pdoc->DeleteChars(firstPos, endPos - firstPos);
}
SetEmptySelection(ac.posStart);
if (item != -1) {
SString piece = selected;
pdoc->InsertCString(firstPos, piece.c_str());
SetEmptySelection(firstPos + static_cast<int>(piece.length()));
}
pdoc->EndUndoAction();
}
int ScintillaBase::AutoCompleteGetCurrent() {
return ac.lb->GetSelection();
}
void ScintillaBase::CallTipShow(Point pt, const char *defn) {
AutoCompleteCancel();
pt.y += vs.lineHeight;
// If container knows about STYLE_CALLTIP then use it in place of the
// STYLE_DEFAULT for the face name, size and character set. Also use it
// for the foreground and background colour.
int ctStyle = ct.UseStyleCallTip() ? STYLE_CALLTIP : STYLE_DEFAULT;
if (ct.UseStyleCallTip()) {
ct.SetForeBack(vs.styles[STYLE_CALLTIP].fore, vs.styles[STYLE_CALLTIP].back);
}
PRectangle rc = ct.CallTipStart(currentPos, pt,
defn,
vs.styles[ctStyle].fontName,
vs.styles[ctStyle].sizeZoomed,
CodePage(),
vs.styles[ctStyle].characterSet,
wMain);
// If the call-tip window would be out of the client
// space, adjust so it displays above the text.
PRectangle rcClient = GetClientRectangle();
if (rc.bottom > rcClient.bottom) {
int offset = vs.lineHeight + rc.Height();
rc.top -= offset;
rc.bottom -= offset;
}
// Now display the window.
CreateCallTipWindow(rc);
ct.wCallTip.SetPositionRelative(rc, wMain);
ct.wCallTip.Show();
}
void ScintillaBase::CallTipClick() {
SCNotification scn = {0};
scn.nmhdr.code = SCN_CALLTIPCLICK;
scn.position = ct.clickPlace;
NotifyParent(scn);
}
void ScintillaBase::ContextMenu(Point pt) {
if (displayPopupMenu) {
bool writable = !WndProc(SCI_GETREADONLY, 0, 0);
popup.CreatePopUp();
AddToPopUp("Undo", idcmdUndo, writable && pdoc->CanUndo());
AddToPopUp("Redo", idcmdRedo, writable && pdoc->CanRedo());
AddToPopUp("");
AddToPopUp("Cut", idcmdCut, writable && currentPos != anchor);
AddToPopUp("Copy", idcmdCopy, currentPos != anchor);
AddToPopUp("Paste", idcmdPaste, writable && WndProc(SCI_CANPASTE, 0, 0));
AddToPopUp("Delete", idcmdDelete, writable && currentPos != anchor);
AddToPopUp("");
AddToPopUp("Select All", idcmdSelectAll);
popup.Show(pt, wMain);
}
}
void ScintillaBase::CancelModes() {
AutoCompleteCancel();
ct.CallTipCancel();
Editor::CancelModes();
}
void ScintillaBase::ButtonDown(Point pt, unsigned int curTime, bool shift, bool ctrl, bool alt) {
CancelModes();
Editor::ButtonDown(pt, curTime, shift, ctrl, alt);
}
#ifdef SCI_LEXER
void ScintillaBase::SetLexer(uptr_t wParam) {
lexLanguage = wParam;
lexCurrent = LexerModule::Find(lexLanguage);
if (!lexCurrent)
lexCurrent = LexerModule::Find(SCLEX_NULL);
}
void ScintillaBase::SetLexerLanguage(const char *languageName) {
lexLanguage = SCLEX_CONTAINER;
lexCurrent = LexerModule::Find(languageName);
if (!lexCurrent)
lexCurrent = LexerModule::Find(SCLEX_NULL);
if (lexCurrent)
lexLanguage = lexCurrent->GetLanguage();
}
void ScintillaBase::Colourise(int start, int end) {
if (!performingStyle) {
// Protect against reentrance, which may occur, for example, when
// fold points are discovered while performing styling and the folding
// code looks for child lines which may trigger styling.
performingStyle = true;
int lengthDoc = pdoc->Length();
if (end == -1)
end = lengthDoc;
int len = end - start;
PLATFORM_ASSERT(len >= 0);
PLATFORM_ASSERT(start + len <= lengthDoc);
//WindowAccessor styler(wMain.GetID(), props);
DocumentAccessor styler(pdoc, props, wMain.GetID());
int styleStart = 0;
if (start > 0)
styleStart = styler.StyleAt(start - 1) & pdoc->stylingBitsMask;
styler.SetCodePage(pdoc->dbcsCodePage);
if (lexCurrent && (len > 0)) { // Should always succeed as null lexer should always be available
lexCurrent->Lex(start, len, styleStart, keyWordLists, styler);
styler.Flush();
if (styler.GetPropertyInt("fold")) {
lexCurrent->Fold(start, len, styleStart, keyWordLists, styler);
styler.Flush();
}
}
performingStyle = false;
}
}
#endif
void ScintillaBase::NotifyStyleToNeeded(int endStyleNeeded) {
#ifdef SCI_LEXER
if (lexLanguage != SCLEX_CONTAINER) {
int endStyled = WndProc(SCI_GETENDSTYLED, 0, 0);
int lineEndStyled = WndProc(SCI_LINEFROMPOSITION, endStyled, 0);
endStyled = WndProc(SCI_POSITIONFROMLINE, lineEndStyled, 0);
Colourise(endStyled, endStyleNeeded);
return;
}
#endif
Editor::NotifyStyleToNeeded(endStyleNeeded);
}
sptr_t ScintillaBase::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) {
switch (iMessage) {
case SCI_AUTOCSHOW:
listType = 0;
AutoCompleteStart(wParam, reinterpret_cast<const char *>(lParam));
break;
case SCI_AUTOCSHOWEX:
listType = 0;
AutoCompleteStart(wParam, reinterpret_cast<const char *>(lParam),false);
break;
case SCI_AUTOCCANCEL:
AutoCompleteCancel();
break;
case SCI_AUTOCACTIVE:
return ac.Active();
case SCI_AUTOCPOSSTART:
return ac.posStart;
case SCI_AUTOCCOMPLETE:
AutoCompleteCompleted();
break;
case SCI_AUTOCSETSEPARATOR:
ac.SetSeparator(static_cast<char>(wParam));
break;
case SCI_AUTOCGETSEPARATOR:
return ac.GetSeparator();
case SCI_AUTOCSTOPS:
ac.SetStopChars(reinterpret_cast<char *>(lParam));
break;
case SCI_AUTOCSELECT:
if(lParam == 0){
ac.Select((int)wParam);
}
else{
ac.Select(reinterpret_cast<char *>(lParam));
}
break;
case SCI_AUTOCGETCURRENT:
return AutoCompleteGetCurrent();
case SCI_AUTOCSETCANCELATSTART:
ac.cancelAtStartPos = wParam != 0;
break;
case SCI_AUTOCGETCANCELATSTART:
return ac.cancelAtStartPos;
case SCI_AUTOCSETFILLUPS:
ac.SetFillUpChars(reinterpret_cast<char *>(lParam));
break;
case SCI_AUTOCSETCHOOSESINGLE:
ac.chooseSingle = wParam != 0;
break;
case SCI_AUTOCGETCHOOSESINGLE:
return ac.chooseSingle;
case SCI_AUTOCSETIGNORECASE:
ac.ignoreCase = wParam != 0;
break;
case SCI_AUTOCGETIGNORECASE:
return ac.ignoreCase;
case SCI_USERLISTSHOW:
listType = wParam;
AutoCompleteStart(0, reinterpret_cast<const char *>(lParam));
break;
case SCI_AUTOCSETAUTOHIDE:
ac.autoHide = wParam != 0;
break;
case SCI_AUTOCGETAUTOHIDE:
return ac.autoHide;
case SCI_AUTOCSETDROPRESTOFWORD:
ac.dropRestOfWord = wParam != 0;
break;
case SCI_AUTOCGETDROPRESTOFWORD:
return ac.dropRestOfWord;
case SCI_AUTOCSETMAXHEIGHT:
ac.lb->SetVisibleRows(wParam);
break;
case SCI_AUTOCGETMAXHEIGHT:
return ac.lb->GetVisibleRows();
case SCI_AUTOCSETMAXWIDTH:
maxListWidth = wParam;
break;
case SCI_AUTOCGETMAXWIDTH:
return maxListWidth;
case SCI_REGISTERIMAGE:
ac.lb->RegisterImage(wParam, reinterpret_cast<const char *>(lParam));
break;
case SCI_CLEARREGISTEREDIMAGES:
ac.lb->ClearRegisteredImages();
break;
case SCI_AUTOCSETTYPESEPARATOR:
ac.SetTypesep(static_cast<char>(wParam));
break;
case SCI_AUTOCGETTYPESEPARATOR:
return ac.GetTypesep();
case SCI_CALLTIPSHOW:
CallTipShow(LocationFromPosition(wParam),
reinterpret_cast<const char *>(lParam));
break;
case SCI_CALLTIPCANCEL:
ct.CallTipCancel();
break;
case SCI_CALLTIPACTIVE:
return ct.inCallTipMode;
case SCI_CALLTIPPOSSTART:
return ct.posStartCallTip;
case SCI_CALLTIPSETHLT:
ct.SetHighlight(wParam, lParam);
break;
case SCI_CALLTIPSETBACK:
ct.colourBG = ColourDesired(wParam);
vs.styles[STYLE_CALLTIP].back = ct.colourBG;
InvalidateStyleRedraw();
break;
case SCI_CALLTIPSETFORE:
ct.colourUnSel = ColourDesired(wParam);
vs.styles[STYLE_CALLTIP].fore = ct.colourUnSel;
InvalidateStyleRedraw();
break;
case SCI_CALLTIPSETFOREHLT:
ct.colourSel = ColourDesired(wParam);
InvalidateStyleRedraw();
break;
case SCI_CALLTIPUSESTYLE:
ct.SetTabSize((int)wParam);
InvalidateStyleRedraw();
break;
case SCI_USEPOPUP:
displayPopupMenu = wParam != 0;
break;
#ifdef SCI_LEXER
case SCI_SETLEXER:
SetLexer(wParam);
lexLanguage = wParam;
break;
case SCI_GETLEXER:
return lexLanguage;
case SCI_COLOURISE:
if (lexLanguage == SCLEX_CONTAINER) {
pdoc->ModifiedAt(wParam);
NotifyStyleToNeeded((lParam == -1) ? pdoc->Length() : lParam);
} else {
Colourise(wParam, lParam);
}
Redraw();
break;
case SCI_SETPROPERTY:
props.Set(reinterpret_cast<const char *>(wParam),
reinterpret_cast<const char *>(lParam));
break;
case SCI_GETPROPERTY: {
SString val = props.Get(reinterpret_cast<const char *>(wParam));
const int n = val.length();
if (lParam != 0) {
char *ptr = reinterpret_cast<char *>(lParam);
memcpy(ptr, val.c_str(), n);
ptr[n] = '\0'; // terminate
}
return n; // Not including NUL
}
case SCI_GETPROPERTYEXPANDED: {
SString val = props.GetExpanded(reinterpret_cast<const char *>(wParam));
const int n = val.length();
if (lParam != 0) {
char *ptr = reinterpret_cast<char *>(lParam);
memcpy(ptr, val.c_str(), n);
ptr[n] = '\0'; // terminate
}
return n; // Not including NUL
}
case SCI_GETPROPERTYINT:
return props.GetInt(reinterpret_cast<const char *>(wParam), lParam);
case SCI_SETKEYWORDS:
if (wParam < numWordLists) {
keyWordLists[wParam]->Clear();
keyWordLists[wParam]->Set(reinterpret_cast<const char *>(lParam));
}
break;
case SCI_SETLEXERLANGUAGE:
SetLexerLanguage(reinterpret_cast<const char *>(lParam));
break;
case SCI_GETSTYLEBITSNEEDED:
return lexCurrent ? lexCurrent->GetStyleBitsNeeded() : 5;
#endif
default:
return Editor::WndProc(iMessage, wParam, lParam);
}
return 0l;
}
| [
"[email protected]"
]
| [
[
[
1,
747
]
]
]
|
72ed387c3323599662fd3cef01c9a45721c89f6f | 36d0ddb69764f39c440089ecebd10d7df14f75f3 | /プログラム/Game/Manager/Scene/Option/XMLLoader.h | 5a1b4df7588586ffcec7decc4e8694caf4b3e995 | []
| no_license | weimingtom/tanuki-mo-issyo | 3f57518b4e59f684db642bf064a30fc5cc4715b3 | ab57362f3228354179927f58b14fa76b3d334472 | refs/heads/master | 2021-01-10T01:36:32.162752 | 2009-04-19T10:37:37 | 2009-04-19T10:37:37 | 48,733,344 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,385 | h | /*******************************************************************************/
/**
* @file XMLLoader.h.
*
* @brief XML読み込み補助クラス.
*
* @date 2009/01/13.
*
* @version 1.00.
*
* @author Kenji Iwata.
*/
/*******************************************************************************/
#ifndef _XMLLOADER_H_
#define _XMLLOADER_H_
/*===== インクルード ==========================================================*/
#include "Define/SpriteInfo.h"
/*===== 定数宣言 ==============================================================*/
/**
* @brief クラス名.
*/
class XMLLoader
{
public:
/*=========================================================================*/
/**
* @brief コンストラクタ.
*
* @param[in] 引数名 引数説明.
*/
XMLLoader();
/*=========================================================================*/
/**
* @brief デストラクタ.
*
*/
~XMLLoader();
/*=========================================================================*/
/**
* @brief 関数説明.
*
* @param[in] 引数名 引数説明.
* @return 戻り値説明.
*/
SpriteInfo LoadSpriteInfo( std::string name );
protected:
private:
/** 変数の説明 */
};
#endif
/*===== EOF ===================================================================*/ | [
"rs.drip@aa49b5b2-a402-11dd-98aa-2b35b7097d33"
]
| [
[
[
1,
63
]
]
]
|
2493d76fa27e727f8604979739588647b0d49693 | ff5313a6e6c9f9353f7505a37a57255c367ff6af | /xrzie/webbrowser2.h | d88468cc9856ad74636a56c073400ba45a273805 | []
| no_license | badcodes/vc6 | 467d6d513549ac4d435e947927d619abf93ee399 | 0c11d7a81197793e1106c8dd3e7ec6b097a68248 | refs/heads/master | 2016-08-07T19:14:15.611418 | 2011-07-09T18:05:18 | 2011-07-09T18:05:18 | 1,220,419 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,759 | h | #if !defined(AFX_WEBBROWSER2_H__49C4D2AE_B726_4356_868F_CE850239E592__INCLUDED_)
#define AFX_WEBBROWSER2_H__49C4D2AE_B726_4356_868F_CE850239E592__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// Machine generated IDispatch wrapper class(es) created by Microsoft Visual C++
// NOTE: Do not modify the contents of this file. If this class is regenerated by
// Microsoft Visual C++, your modifications will be overwritten.
/////////////////////////////////////////////////////////////////////////////
// CWebBrowser2 wrapper class
class CWebBrowser2 : public CWnd
{
protected:
DECLARE_DYNCREATE(CWebBrowser2)
public:
CLSID const& GetClsid()
{
static CLSID const clsid
= { 0x8856f961, 0x340a, 0x11d0, { 0xa9, 0x6b, 0x0, 0xc0, 0x4f, 0xd7, 0x5, 0xa2 } };
return clsid;
}
virtual BOOL Create(LPCTSTR lpszClassName,
LPCTSTR lpszWindowName, DWORD dwStyle,
const RECT& rect,
CWnd* pParentWnd, UINT nID,
CCreateContext* pContext = NULL)
{ return CreateControl(GetClsid(), lpszWindowName, dwStyle, rect, pParentWnd, nID); }
BOOL Create(LPCTSTR lpszWindowName, DWORD dwStyle,
const RECT& rect, CWnd* pParentWnd, UINT nID,
CFile* pPersist = NULL, BOOL bStorage = FALSE,
BSTR bstrLicKey = NULL)
{ return CreateControl(GetClsid(), lpszWindowName, dwStyle, rect, pParentWnd, nID,
pPersist, bStorage, bstrLicKey); }
// Attributes
public:
// Operations
public:
void GoBack();
void GoForward();
void GoHome();
void GoSearch();
void Navigate(LPCTSTR URL, VARIANT* Flags, VARIANT* TargetFrameName, VARIANT* PostData, VARIANT* Headers);
void Refresh();
void Refresh2(VARIANT* Level);
void Stop();
LPDISPATCH GetApplication();
LPDISPATCH GetParent();
LPDISPATCH GetContainer();
LPDISPATCH GetDocument();
BOOL GetTopLevelContainer();
CString GetType();
long GetLeft();
void SetLeft(long nNewValue);
long GetTop();
void SetTop(long nNewValue);
long GetWidth();
void SetWidth(long nNewValue);
long GetHeight();
void SetHeight(long nNewValue);
CString GetLocationName();
CString GetLocationURL();
BOOL GetBusy();
void Quit();
void ClientToWindow(long* pcx, long* pcy);
void PutProperty(LPCTSTR Property_, const VARIANT& vtValue);
VARIANT GetProperty_(LPCTSTR Property_);
CString GetName();
long GetHwnd();
CString GetFullName();
CString GetPath();
BOOL GetVisible();
void SetVisible(BOOL bNewValue);
BOOL GetStatusBar();
void SetStatusBar(BOOL bNewValue);
CString GetStatusText();
void SetStatusText(LPCTSTR lpszNewValue);
long GetToolBar();
void SetToolBar(long nNewValue);
BOOL GetMenuBar();
void SetMenuBar(BOOL bNewValue);
BOOL GetFullScreen();
void SetFullScreen(BOOL bNewValue);
void Navigate2(VARIANT* URL, VARIANT* Flags, VARIANT* TargetFrameName, VARIANT* PostData, VARIANT* Headers);
long QueryStatusWB(long cmdID);
void ExecWB(long cmdID, long cmdexecopt, VARIANT* pvaIn, VARIANT* pvaOut);
void ShowBrowserBar(VARIANT* pvaClsid, VARIANT* pvarShow, VARIANT* pvarSize);
long GetReadyState();
BOOL GetOffline();
void SetOffline(BOOL bNewValue);
BOOL GetSilent();
void SetSilent(BOOL bNewValue);
BOOL GetRegisterAsBrowser();
void SetRegisterAsBrowser(BOOL bNewValue);
BOOL GetRegisterAsDropTarget();
void SetRegisterAsDropTarget(BOOL bNewValue);
BOOL GetTheaterMode();
void SetTheaterMode(BOOL bNewValue);
BOOL GetAddressBar();
void SetAddressBar(BOOL bNewValue);
BOOL GetResizable();
void SetResizable(BOOL bNewValue);
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_WEBBROWSER2_H__49C4D2AE_B726_4356_868F_CE850239E592__INCLUDED_)
| [
"[email protected]"
]
| [
[
[
1,
114
]
]
]
|
494c2eaca3742e692b9adeebc08b56dce9d7ec0f | fa609a5b5a0e7de3344988a135b923a0f655f59e | /Tests/Source/TestTokenInclude.cpp | 60c992af975115505bfd155fe6433fca5639dc4e | [
"MIT"
]
| permissive | Sija/swift | 3edfd70e1c8d9d54556862307c02d1de7d400a7e | dddedc0612c0d434ebc2322fc5ebded10505792e | refs/heads/master | 2016-09-06T09:59:35.416041 | 2007-08-30T02:29:30 | 2007-08-30T02:29:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,401 | cpp | #include "stdafx.h"
#include <cppunit/extensions/HelperMacros.h>
#include "../../Source/stdafx.h"
#include "../../Source/tokens/Include.h"
#include "../../Source/values/String.h"
#include "../../Source/TextTemplate.h"
#include "../../Source/Factory.h"
#include "../../Source/Globals.h"
#include "../../Source/Parser.h"
using namespace Swift;
class TestTokenInclude : public CPPUNIT_NS::TestFixture {
public:
CPPUNIT_TEST_SUITE(TestTokenInclude);
CPPUNIT_TEST(testOutput);
CPPUNIT_TEST_SUITE_END();
public:
void setUp() {
Factory::get()->bind("include", &Tokens::Include::getInstance);
}
void tearDown() { }
protected:
void testOutput() {
oTemplate tpl;
Parser parser;
parser.parse(tpl = new TextTemplate(L"{include file='test.tpl'}"));
tpl->addVariable("ab", "bc");
Globals::get()->addVariable("de", "fh");
try {
tpl->output();
CPPUNIT_ASSERT("file exist?");
} catch (Stamina::Exception& e) {
}
{
wofstream o("test.tpl");
o << L"{'hello'}";
o.close();
}
Sleep(10);
CPPUNIT_ASSERT(tpl->output() == L"hello");
{
wofstream o("test.tpl");
o << L"{'hi'}";
o.close();
}
Sleep(10);
CPPUNIT_ASSERT(tpl->output() == L"hi");
{
wofstream o("test.tpl");
o << L"{$de}{$ab}";
o.close();
}
Sleep(10);
CPPUNIT_ASSERT(tpl->output() == L"fhbc");
parser.parse(tpl = new TextTemplate(L"{$no = 'two'}{include file='test.tpl', arg='argument', inherit=false}"));
tpl->addVariable("ab", "bc");
{
wofstream o("test.tpl");
o << L"{$de}{$ab} {$arg}{$no}";
o.close();
}
Sleep(10);
String s = tpl->output();
CPPUNIT_ASSERT(tpl->output() == L"fh argument");
parser.parse(tpl = new TextTemplate(L"{$no = 'two'}{include file='test.tpl', arg='argument', inherit=true}"));
tpl->addVariable("ab", "bc");
s = tpl->output();
CPPUNIT_ASSERT(tpl->output() == L"fhbc argumenttwo");
{
wofstream o("test.tpl");
o << L"{/7}";
o.close();
}
Sleep(10);
try {
tpl->output();
CPPUNIT_ASSERT(!"good syntax?");
} catch (Stamina::Exception& e) {
}
Globals::get()->clearVariables();
}
};
CPPUNIT_TEST_SUITE_REGISTRATION(TestTokenInclude); | [
"[email protected]"
]
| [
[
[
1,
106
]
]
]
|
b196a25546502f2a3dab7f8dcc4361a4fb07fad0 | fac8de123987842827a68da1b580f1361926ab67 | /inc/math/HMMatrix4.h | 156538c934f7261fd21d6df355189c4d429cb437 | []
| no_license | blockspacer/transporter-game | 23496e1651b3c19f6727712a5652f8e49c45c076 | 083ae2ee48fcab2c7d8a68670a71be4d09954428 | refs/heads/master | 2021-05-31T04:06:07.101459 | 2009-02-19T20:59:59 | 2009-02-19T20:59:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,486 | h | #ifndef HYPERMATH_M4
#define HYPERMATH_M4
#include "math/HMath.h"
using namespace hmath;
namespace hmath
{
class m4
{
public:
union {
f64 val[4][4];
f64 _val[16];
};
m4();
m4( f64 m00, f64 m01, f64 m02, f64 m03,
f64 m10, f64 m11, f64 m12, f64 m13,
f64 m20, f64 m21, f64 m22, f64 m23,
f64 m30, f64 m31, f64 m32, f64 m33 );
m4(const m3& m3x3);
m4(const quat& rot);
void set( f64 m00, f64 m01, f64 m02, f64 m03,
f64 m10, f64 m11, f64 m12, f64 m13,
f64 m20, f64 m21, f64 m22, f64 m23,
f64 m30, f64 m31, f64 m32, f64 m33 );
f64* operator [] ( size_t iRow );
const f64 *const operator [] ( size_t iRow ) const;
m4 concatenate(const m4 &m2) const;
m4 operator * ( const m4 &m2 ) const;
v3 operator * ( const v3 &v ) const;
v4 operator * (const v4& v) const;
m4 operator + ( const m4 &m2 ) const;
m4 operator - ( const m4 &m2 ) const;
bit operator == ( const m4& m2 ) const;
bit operator != ( const m4& m2 ) const;
void operator = ( const m3& mat3 );
m4 transpose(void) const;
void setTrans( const v3& v );
v3 getTrans() const;
void makeTrans( const v3& v );
void makeTrans( f64 tx, f64 ty, f64 tz );
static m4 getTrans( const v3& v );
static m4 getTrans( f64 t_x, f64 t_y, f64 t_z );
void setScale( const v3& v );
static m4 getScale( const v3& v );
static m4 getScale( f64 s_x, f64 s_y, f64 s_z );
void extract3x3Matrix(m3& m3x3) const;
quat extractQuaternion() const;
static const m4 ZERO;
static const m4 IDENTITY;
static const m4 CLIPSPACE2DTOIMAGESPACE;
m4 operator*(f64 scalar) const;
m4 adjoint() const;
f64 determinant() const;
m4 inverse() const;
void makeTransform(const v3& position, const v3& scale, const quat& orientation);
void makeInverseTransform(const v3& position, const v3& scale, const quat& orientation);
bit isAffine(void) const;
m4 inverseAffine(void) const;
m4 concatenateAffine(const m4 &m2) const;
v3 transformAffine(const v3& v) const;
v4 transformAffine(const v4& v) const;
};
extern v4 operator * (const v4& v, const m4& mat);
}
#endif
| [
"uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4"
]
| [
[
[
1,
70
]
]
]
|
6ed55ff78b4e7ecf8f45c8cffe12b2620dcfa62d | b799c972367cd014a1ffed4288a9deb72f590bec | /project/NetServices/if/ppp/PPPNetIf.cpp | a2a7c7c6835f9f4f863ce508219582073d673fbf | []
| no_license | intervigilium/csm213a-embedded | 647087de8f831e3c69e05d847d09f5fa12b468e6 | ae4622be1eef8eb6e4d1677a9b2904921be19a9e | refs/heads/master | 2021-01-13T02:22:42.397072 | 2011-12-11T22:50:37 | 2011-12-11T22:50:37 | 2,832,079 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,170 | cpp |
/*
Copyright (c) 2010 Donatien Garnier (donatiengar [at] gmail [dot] com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "PPPNetIf.h"
#include "mbed.h"
#include "ppp/ppp.h"
#include "lwip/init.h"
#include "lwip/sio.h"
#define __DEBUG
#include "dbg/dbg.h"
#include "netCfg.h"
#if NET_PPP
#define PPP_TIMEOUT 60000
#define BUF_SIZE 256
PPPNetIf::PPPNetIf(GPRSModem* pIf) : LwipNetIf(), m_pIf(pIf),/* m_open(false),*/ m_connected(false), m_status(PPP_DISCONNECTED), m_fd(0) //, m_id(0)
{
//FIXME: Check static refcount
m_buf = new uint8_t[BUF_SIZE];
}
PPPNetIf::~PPPNetIf()
{
delete[] m_buf;
}
#if 0
PPPErr PPPNetIf::open(Serial* pSerial)
{
GPRSErr err = m_pIf->open(pSerial);
if(err)
return PPP_MODEM;
m_open = true;
#if 0
m_id = sioMgr::registerSerialIf(this);
if(!m_id)
{
close();
return PPP_CLOSED;
}
#endif
return PPP_OK;
}
#endif
PPPErr PPPNetIf::GPRSConnect(const char* apn, const char* userId, const char* password) //Connect using GPRS
{
LwipNetIf::init();
pppInit();
//TODO: Tell ATIf that we get ownership of the serial port
GPRSErr gprsErr;
gprsErr = m_pIf->connect(apn);
if(gprsErr)
return PPP_NETWORK;
DBG("PPPNetIf: If Connected.\n");
if( userId == NULL )
pppSetAuth(PPPAUTHTYPE_NONE, NULL, NULL);
else
pppSetAuth(PPPAUTHTYPE_PAP, userId, password); //TODO: Allow CHAP as well
DBG("PPPNetIf: Set Auth.\n");
//wait(1.);
//m_pIf->flushBuffer(); //Flush buffer before passing serial port to PPP
m_status = PPP_CONNECTING;
DBG("m_pIf = %p\n", m_pIf);
int res = pppOverSerialOpen((void*)m_pIf, sPppCallback, (void*)this);
DBG("PPP connected\n");
if(res<0)
{
disconnect();
return PPP_PROTOCOL;
}
DBG("PPPNetIf: PPP Started with res = %d.\n", res);
m_fd = res;
m_connected = true;
Timer t;
t.start();
while( m_status == PPP_CONNECTING ) //Wait for callback
{
poll();
if(t.read_ms()>PPP_TIMEOUT)
{
DBG("PPPNetIf: Timeout.\n");
disconnect();
return PPP_PROTOCOL;
}
}
DBG("PPPNetIf: Callback returned.\n");
if( m_status == PPP_DISCONNECTED )
{
disconnect();
return PPP_PROTOCOL;
}
return PPP_OK;
}
PPPErr PPPNetIf::ATConnect(const char* number) //Connect using a "classic" voice modem or GSM
{
//TODO: IMPL
return PPP_MODEM;
}
PPPErr PPPNetIf::disconnect()
{
if(m_fd)
pppClose(m_fd); //0 if ok, else should gen a WARN
m_connected = false;
m_pIf->flushBuffer();
m_pIf->printf("+++\r\n");
wait(.5);
m_pIf->flushBuffer();
GPRSErr gprsErr;
gprsErr = m_pIf->disconnect();
if(gprsErr)
return PPP_NETWORK;
return PPP_OK;
}
#if 0
PPPErr PPPNetIf::close()
{
GPRSErr err = m_pIf->close();
if(err)
return PPP_MODEM;
m_open = false;
return PPP_OK;
}
#endif
#if 0
//We have to use :
/** Pass received raw characters to PPPoS to be decoded. This function is
* thread-safe and can be called from a dedicated RX-thread or from a main-loop.
*
* @param pd PPP descriptor index, returned by pppOpen()
* @param data received data
* @param len length of received data
*/
void
pppos_input(int pd, u_char* data, int len)
{
pppInProc(&pppControl[pd].rx, data, len);
}
#endif
void PPPNetIf::poll()
{
if(!m_connected)
return;
LwipNetIf::poll();
//static u8_t buf[128];
int len;
do
{
len = sio_tryread((sio_fd_t) m_pIf, m_buf, BUF_SIZE);
if(len > 0)
pppos_input(m_fd, m_buf, len);
} while(len>0);
}
//Link Callback
void PPPNetIf::pppCallback(int errCode, void *arg)
{
switch ( errCode )
{
//No error
case PPPERR_NONE:
{
struct ppp_addrs* addrs = (struct ppp_addrs*) arg;
m_ip = IpAddr(&(addrs->our_ipaddr)); //Set IP
}
m_status = PPP_CONNECTED;
break;
default:
//Disconnected
DBG("PPPNetIf: Callback errCode = %d.\n", errCode);
m_status = PPP_DISCONNECTED;
break;
}
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
224
]
]
]
|
00cc2de539e73838b5e7829bb6e796010f125643 | 96fefafdfbb413a56e0a2444fcc1a7056afef757 | /MQ2Center/ISXEQCenter.cpp | 7962e764842287c4cdd4fa5f79153bf1f66ae8b3 | []
| no_license | kevrgithub/peqtgc-mq2-sod | ffc105aedbfef16060769bb7a6fa6609d775b1fa | d0b7ec010bc64c3f0ac9dc32129a62277b8d42c0 | refs/heads/master | 2021-01-18T18:57:16.627137 | 2011-03-06T13:05:41 | 2011-03-06T13:05:41 | 32,849,784 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 11,996 | cpp | //
// ISXEQCenter
//
#pragma warning(disable:4996)
#include "../ISXEQClient.h"
#include "ISXEQCenter.h"
// The mandatory pre-setup function. Our name is "ISXEQCenter", and the class is ISXEQCenter.
// This sets up a "ModulePath" variable which contains the path to this module in case we want it,
// and a "PluginLog" variable, which contains the path and filename of what we should use for our
// debug logging if we need it. It also sets up a variable "pExtension" which is the pointer to
// our instanced class.
ISXPreSetup("ISXEQCenter",ISXEQCenter);
// Basic LavishScript datatypes, these get retrieved on startup by our initialize function, so we can
// use them in our Top-Level Objects or custom datatypes
LSType *pStringType=0;
LSType *pIntType=0;
LSType *pBoolType=0;
LSType *pFloatType=0;
LSType *pTimeType=0;
LSType *pByteType=0;
ISInterface *pISInterface=0;
HISXSERVICE hPulseService=0;
HISXSERVICE hMemoryService=0;
HISXSERVICE hServicesService=0;
HISXSERVICE hEQChatService=0;
HISXSERVICE hEQUIService=0;
HISXSERVICE hEQGamestateService=0;
HISXSERVICE hEQSpawnService=0;
HISXSERVICE hEQZoneService=0;
unsigned int ISXEQCenterXML=0;
// Forward declarations of callbacks
void __cdecl PulseService(bool Broadcast, unsigned int MSG, void *lpData);
void __cdecl MemoryService(bool Broadcast, unsigned int MSG, void *lpData);
void __cdecl ServicesService(bool Broadcast, unsigned int MSG, void *lpData);
// Initialize is called by Inner Space when the extension should initialize.
bool ISXEQCenter::Initialize(ISInterface *p_ISInterface)
{ pISInterface=p_ISInterface;
// retrieve basic ISData types
pStringType=pISInterface->FindLSType("string");
pIntType=pISInterface->FindLSType("int");
pBoolType=pISInterface->FindLSType("bool");
pFloatType=pISInterface->FindLSType("float");
pTimeType=pISInterface->FindLSType("time");
pByteType=pISInterface->FindLSType("byte");
pISInterface->OpenSettings(XMLFileName);
LoadSettings();
ConnectServices();
RegisterCommands();
RegisterAliases();
RegisterDataTypes();
RegisterTopLevelObjects();
RegisterServices();
WriteChatf("ISXEQCenter Loaded");
return true;
}
// shutdown sequence
void ISXEQCenter::Shutdown()
{
// save settings, if you changed them and want to save them now. You should normally save
// changes immediately.
//pISInterface->ExportSet(ISXEQCenterXML,XMLFileName);
pISInterface->UnloadSet(ISXEQCenterXML);
DisconnectServices();
UnRegisterServices();
UnRegisterTopLevelObjects();
UnRegisterDataTypes();
UnRegisterAliases();
UnRegisterCommands();
}
void ISXEQCenter::ConnectServices()
{
// connect to any services. Here we connect to "Pulse" which receives a
// message every frame (after the frame is displayed) and "Memory" which
// wraps "detours" and memory modifications
hPulseService=pISInterface->ConnectService(this,"Pulse",PulseService);
hMemoryService=pISInterface->ConnectService(this,"Memory",MemoryService);
hServicesService=pISInterface->ConnectService(this,"Services",ServicesService);
}
void ISXEQCenter::RegisterCommands()
{
// add any commands
// pISInterface->AddCommand("MyCommand",MyCommand,true,false);
}
void ISXEQCenter::RegisterAliases()
{
// add any aliases
}
void ISXEQCenter::RegisterDataTypes()
{
// add any datatypes
// pMyType = new MyType;
// pISInterface->AddLSType(*pMyType);
}
void ISXEQCenter::RegisterTopLevelObjects()
{
// add any Top-Level Objects
// pISInterface->AddTopLevelObject("MapSpawn",tloMapSpawn);
}
void ISXEQCenter::RegisterServices()
{
// register any services. Here we demonstrate a service that does not use a
// callback
// set up a 1-way service (broadcast only)
// hISXEQCenterService=pISInterface->RegisterService(this,"ISXEQCenter Service",0);
// broadcast a message, which is worthless at this point because nobody will receive it
// (nobody has had a chance to connect)
// pISInterface->ServiceBroadcast(this,hISXEQCenterService,ISXSERVICE_MSG+1,0);
}
void ISXEQCenter::DisconnectServices()
{
// gracefully disconnect from services
if (hPulseService)
pISInterface->DisconnectService(this,hPulseService);
if (hMemoryService)
{
pISInterface->DisconnectService(this,hMemoryService);
// memory modifications are automatically undone when disconnecting
// also, since this service accepts messages from clients we should reset our handle to
// 0 to make sure we dont try to continue using it
hMemoryService=0;
}
if (hServicesService)
pISInterface->DisconnectService(this,hServicesService);
}
void ISXEQCenter::UnRegisterCommands()
{
// remove commands
// pISInterface->RemoveCommand("MyCommand");
}
void ISXEQCenter::UnRegisterAliases()
{
// remove aliases
}
void ISXEQCenter::UnRegisterDataTypes()
{
// remove data types
//if (pMyType)
//{
// pISInterface->RemoveLSType(*pMyType);
// delete pMyType;
//}
}
void ISXEQCenter::UnRegisterTopLevelObjects()
{
// remove Top-Level Objects
// pISInterface->RemoveTopLevelObject("MapSpawn");
}
void ISXEQCenter::UnRegisterServices()
{
// shutdown our own services
// if (hISXEQCenterService)
// pISInterface->ShutdownService(this,hISXEQCenterService);
}
void ISXEQCenter::LoadSettings()
{
bool bChanged=false;
// open the settings file, and store the ID number in ISXEQCenterXML
ISXEQCenterXML=pISInterface->OpenSettings(XMLFileName);
// This ID is used to refer to the base set of the loaded settings
/*
Here is an example settings hierarchy:
base set
..settings
.."General" set
.."Characters" set
...."Server A" set
......"Character A" set
........settings
......"Character B" set
........settings
...."Server B" set
......"Character A" set
........settings
...."Server C" set
......"Character A" set
........settings
......"Character B" set
........settings
......"Character C" set
........settings
As you can see, there can be any number of nested sets, which can contain sets, settings, and comments.
Any set can be referred to by its ID. The base set is stored in ISXEQCenterXML. Note that the settings
are NOT "xml" after loading them, they are simply settings stored in memory!
*/
// Get General set ID, which can be a child of the base set
if (unsigned int GeneralGUID=pISInterface->FindSet(ISXEQCenterXML,"General"))
{
// retrieve a text setting from the General set
char Text[512];
if (pISInterface->GetSetting(GeneralGUID,"Name of setting",Text,512))
{
// success
}
unsigned int IntSetting;
if (pISInterface->GetSetting(GeneralGUID,"Name of int setting",IntSetting))
{
// success
}
}
/*
Deeper sets and settings are accessed in exactly the same way. If a sub-set of General was to be used,
accessing it would work like so:
if (unsigned int SubSetGUID=pISInterface->FindSet(GeneralGUID,"Sub-set name"))
{
// got the sub-set
}
*/
// save settings if we changed them
if (bChanged)
pISInterface->ExportSet(ISXEQCenterXML,XMLFileName);
// Note: ExportSet can save ANY set and its settings, sets, and comments as ANY filename. The "General" set
// could be stored as "General.XML" simply by doing pISInterface->ExportSet(GeneralGUID,"General.XML");
}
void __cdecl PulseService(bool Broadcast, unsigned int MSG, void *lpData)
{
if (MSG==PULSE_PULSE)
{
// Same as OnPulse
}
}
void __cdecl MemoryService(bool Broadcast, unsigned int MSG, void *lpData)
{
// no messages are currently associated with this service (other than
// system messages such as client disconnect), so do nothing.
}
void __cdecl EQUIService(bool Broadcast, unsigned int MSG, void *lpData)
{
switch(MSG)
{
case UISERVICE_CLEANUP:
// same as OnCleanUI
break;
case UISERVICE_RELOAD:
// same as OnReloadUI
break;
}
}
void __cdecl EQGamestateService(bool Broadcast, unsigned int MSG, void *lpData)
{
#define GameState ((unsigned int)lpData)
if (MSG==GAMESTATESERVICE_CHANGED)
{
// same as SetGameState
}
#undef GameState
}
void __cdecl EQSpawnService(bool Broadcast, unsigned int MSG, void *lpData)
{
switch(MSG)
{
#define pSpawn ((PSPAWNINFO)lpData)
case SPAWNSERVICE_ADDSPAWN:
// same as OnAddSpawn
break;
case SPAWNSERVICE_REMOVESPAWN:
// same as OnRemoveSpawn
break;
#undef pSpawn
#define pGroundItem ((PGROUNDITEM)lpData)
case SPAWNSERVICE_ADDITEM:
// same as OnAddGroundItem
break;
case SPAWNSERVICE_REMOVEITEM:
// same as OnRemoveGroundItem
break;
#undef pGroundItem
}
}
void __cdecl EQZoneService(bool Broadcast, unsigned int MSG, void *lpData)
{
switch(MSG)
{
case ZONESERVICE_BEGINZONE:
// same as OnBeginZone
break;
case ZONESERVICE_ENDZONE:
// same as OnEndZone
break;
case ZONESERVICE_ZONED:
// same as OnZoned
break;
}
}
void __cdecl EQChatService(bool Broadcast, unsigned int MSG, void *lpData)
{
#define pChat ((_EQChat*)lpData)
switch(MSG)
{
case CHATSERVICE_OUTGOING:
// same as OnWriteChatColor
break;
case CHATSERVICE_INCOMING:
// same as OnIncomingChat
break;
}
#undef pChat
}
// This uses the Services service to connect to ISXEQ services
void __cdecl ServicesService(bool Broadcast, unsigned int MSG, void *lpData)
{
#define Name ((char*)lpData)
switch(MSG)
{
case SERVICES_ADDED:
if (!stricmp(Name,"EQ UI Service"))
{
hEQUIService=pISInterface->ConnectService(pExtension,Name,EQUIService);
}
else if (!stricmp(Name,"EQ Gamestate Service"))
{
hEQGamestateService=pISInterface->ConnectService(pExtension,Name,EQGamestateService);
}
else if (!stricmp(Name,"EQ Spawn Service"))
{
hEQSpawnService=pISInterface->ConnectService(pExtension,Name,EQSpawnService);
}
else if (!stricmp(Name,"EQ Zone Service"))
{
hEQZoneService=pISInterface->ConnectService(pExtension,Name,EQZoneService);
}
else if (!stricmp(Name,"EQ Chat Service"))
{
hEQChatService=pISInterface->ConnectService(pExtension,Name,EQChatService);
}
break;
case SERVICES_REMOVED:
if (!stricmp(Name,"EQ UI Service"))
{
if (hEQUIService)
{
pISInterface->DisconnectService(pExtension,hEQUIService);
hEQUIService=0;
}
}
else if (!stricmp(Name,"EQ Gamestate Service"))
{
if (hEQGamestateService)
{
pISInterface->DisconnectService(pExtension,hEQGamestateService);
hEQGamestateService=0;
}
}
else if (!stricmp(Name,"EQ Spawn Service"))
{
if (hEQSpawnService)
{
pISInterface->DisconnectService(pExtension,hEQSpawnService);
hEQSpawnService=0;
}
}
else if (!stricmp(Name,"EQ Zone Service"))
{
if (hEQZoneService)
{
pISInterface->DisconnectService(pExtension,hEQZoneService);
hEQZoneService=0;
}
}
else if (!stricmp(Name,"EQ Chat Service"))
{
if (hEQChatService)
{
pISInterface->DisconnectService(pExtension,hEQChatService);
hEQChatService=0;
}
}
break;
}
#undef Name
}
int MyCommand(int argc, char *argv[])
{
// IS Commands work just like console programs. argc is the argument (aka parameter) count,
// argv is an array containing them. The name of the command is always the first argument.
if (argc<2)
{
// This command requires arguments
WriteChatf("Syntax: %s <text>",argv[0]);
return 0;
}
char FullText[8192]={0};
pISInterface->GetArgs(1,argc,argv,FullText); // this gets the rest of the arguments, from 1 to argc
WriteChatf("You passed the following text to the command:");
WriteChatf("%s",FullText);
// For most commands, you need to deal with only one argument at a time, instead of the entire line.
for (int i = 1 ; i < argc ; i++)
{
WriteChatf("argv[%d]=\"%s\"",i,argv[i]);
}
// return 0 or greater for normal conditions, or return -1 for an error that should stop
// a script.
return 0;
}
| [
"[email protected]@39408780-f958-9dab-a28b-4b240efc9052"
]
| [
[
[
1,
440
]
]
]
|
01fad5b8b01981a18e8ecf6f5823163c41a71abd | f90b1358325d5a4cfbc25fa6cccea56cbc40410c | /src/GUI/proRataResidueComposition.cpp | 2a512badd2239619e3bd2ec302ba6f9c44baec3c | []
| no_license | ipodyaco/prorata | bd52105499c3fad25781d91952def89a9079b864 | 1f17015d304f204bd5f72b92d711a02490527fe6 | refs/heads/master | 2021-01-10T09:48:25.454887 | 2010-05-11T19:19:40 | 2010-05-11T19:19:40 | 48,766,766 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,528 | cpp |
#include "proRataResidueComposition.h"
ProRataResidueComposition::ProRataResidueComposition( QWidget* qwParent, Qt::WFlags qwfFl )
: QWidget( qwParent, qwfFl )
{
priTreatment = NULL;
priReference = NULL;
buildUI();
setValues();
}
ProRataResidueComposition::~ProRataResidueComposition()
{
}
void ProRataResidueComposition::buildUI()
{
qgMainLayout = new QGridLayout;
priTreatment = new ProRataIsotopologue;
priTreatment->setName( "treatment" );
priReference = new ProRataIsotopologue;
priReference->setName( "reference" );
qgMainLayout->addWidget( priTreatment, 0, 0 );
qgMainLayout->addWidget( priReference, 1, 0 );
setLayout( qgMainLayout );
}
void ProRataResidueComposition::setValues()
{
QStringList qslTableData;
qslTableData << "NTerm" << "CTerm" << "L" << "A" << "S" << "G" << "V"
<< "E" << "K" << "I" << "T" << "D" << "R" << "P"
<< "N" << "F" << "Q" << "Y" << "M" << "H" << "C" << "W";
priTreatment->setData( 0, qslTableData );
priReference->setData( 0, qslTableData );
qslTableData.clear();
qslTableData << "0" << "0" << "6" << "3" << "3" << "2" << "5" << "5" << "6" << "6" << "4" << "4" << "6" << "5" << "4" << "9" << "5" << "9" << "5" << "6" << "3" << "11";
priTreatment->setData( 1, qslTableData );
priReference->setData( 1, qslTableData );
qslTableData.clear();
qslTableData << "1" << "1" << "11" << "5" << "5" << "3" << "9" << "7" << "12" << "11" << "7" << "5" << "12" << "7" << "6" << "9" << "8" << "9" << "9" << "7" << "5" << "10";
priTreatment->setData( 2, qslTableData );
priReference->setData( 2, qslTableData );
qslTableData.clear();
qslTableData << "0" << "1" << "1" << "1" << "2" << "1" << "1" << "3" << "1" << "1" << "2" << "3" << "1" << "1" << "2" << "1" << "2" << "2" << "1" << "1" << "1" << "1";
priTreatment->setData( 3, qslTableData );
priReference->setData( 3, qslTableData );
qslTableData.clear();
qslTableData << "0" << "0" << "1" << "1" << "1" << "1" << "1" << "1" << "2" << "1" << "1" << "1" << "4" << "1" << "2" << "1" << "2" << "1" << "1" << "3" << "1" << "2";
priTreatment->setData( 4, qslTableData );
priReference->setData( 4, qslTableData );
qslTableData.clear();
qslTableData << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0";
priTreatment->setData( 5, qslTableData );
priReference->setData( 5, qslTableData );
qslTableData.clear();
qslTableData << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "1" << "0" << "1" << "0";
priTreatment->setData( 6, qslTableData );
priReference->setData( 6, qslTableData );
qslTableData.clear();
qslTableData << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0";
priTreatment->setData( 7, qslTableData );
priReference->setData( 7, qslTableData );
qslTableData.clear();
qslTableData << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0";
priTreatment->setData( 8, qslTableData );
priReference->setData( 8, qslTableData );
qslTableData.clear();
qslTableData << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0";
priTreatment->setData( 9, qslTableData );
priReference->setData( 9, qslTableData );
qslTableData.clear();
qslTableData << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0";
priTreatment->setData( 10, qslTableData );
priReference->setData( 10, qslTableData );
qslTableData.clear();
qslTableData << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0";
priTreatment->setData( 11, qslTableData );
priReference->setData( 11, qslTableData );
qslTableData.clear();
qslTableData << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0" << "0";
priTreatment->setData( 12, qslTableData );
priReference->setData( 12, qslTableData );
qslTableData.clear();
}
| [
"chongle.pan@c58cc1ec-c975-bb1e-ac29-6983d7497d3a"
]
| [
[
[
1,
105
]
]
]
|
c3c5b6740595b67cd7a1687f526e07a62833744f | ef23e388061a637f82b815d32f7af8cb60c5bb1f | /src/mame/includes/angelkds.h | 492d1fd1d0b4b2a14e0e13562fbb764ded02ed19 | []
| no_license | marcellodash/psmame | 76fd877a210d50d34f23e50d338e65a17deff066 | 09f52313bd3b06311b910ed67a0e7c70c2dd2535 | refs/heads/master | 2021-05-29T23:57:23.333706 | 2011-06-23T20:11:22 | 2011-06-23T20:11:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,387 | h | /*************************************************************************
Angel Kids
*************************************************************************/
class angelkds_state : public driver_device
{
public:
angelkds_state(running_machine &machine, const driver_device_config_base &config)
: driver_device(machine, config) { }
/* memory pointers */
UINT8 * m_paletteram;
UINT8 * m_spriteram;
UINT8 * m_txvideoram;
UINT8 * m_bgtopvideoram;
UINT8 * m_bgbotvideoram;
tilemap_t *m_tx_tilemap;
tilemap_t *m_bgbot_tilemap;
tilemap_t *m_bgtop_tilemap;
int m_txbank;
int m_bgbotbank;
int m_bgtopbank;
UINT8 m_sound[4];
UINT8 m_sound2[4];
UINT8 m_layer_ctrl;
/* devices */
device_t *m_subcpu;
};
/*----------- defined in video/angelkds.c -----------*/
WRITE8_HANDLER( angelkds_bgtopvideoram_w );
WRITE8_HANDLER( angelkds_bgbotvideoram_w );
WRITE8_HANDLER( angelkds_txvideoram_w );
WRITE8_HANDLER( angelkds_bgtopbank_write );
WRITE8_HANDLER( angelkds_bgtopscroll_write );
WRITE8_HANDLER( angelkds_bgbotbank_write );
WRITE8_HANDLER( angelkds_bgbotscroll_write );
WRITE8_HANDLER( angelkds_txbank_write );
WRITE8_HANDLER( angelkds_paletteram_w );
WRITE8_HANDLER( angelkds_layer_ctrl_write );
VIDEO_START( angelkds );
SCREEN_UPDATE( angelkds );
| [
"Mike@localhost"
]
| [
[
[
1,
52
]
]
]
|
18747d8fff346ebbb9206e2b5208e1b8d025678c | 3e69b159d352a57a48bc483cb8ca802b49679d65 | /branches/bokeoa-scons/eeschema/dialog_build_BOM.h | 1805849b86f2eed31299a66ef8b2fb8ac32a40f9 | []
| no_license | BackupTheBerlios/kicad-svn | 4b79bc0af39d6e5cb0f07556eb781a83e8a464b9 | 4c97bbde4b1b12ec5616a57c17298c77a9790398 | refs/heads/master | 2021-01-01T19:38:40.000652 | 2006-06-19T20:01:24 | 2006-06-19T20:01:24 | 40,799,911 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,785 | h | /////////////////////////////////////////////////////////////////////////////
// Name: dialog_build_BOM.h
// Purpose:
// Author: jean-pieere Charras
// Modified by:
// Created: 01/15/06 18:18:44
// RCS-ID:
// Copyright: GNU license
// Licence:
/////////////////////////////////////////////////////////////////////////////
// Generated by DialogBlocks (unregistered), 01/15/06 18:18:44
#ifndef _DIALOG_BUILD_BOM_H_
#define _DIALOG_BUILD_BOM_H_
#if defined(__GNUG__) && !defined(__APPLE__)
#pragma interface "dialog_build_BOM.cpp"
#endif
/*!
* Includes
*/
////@begin includes
#include "wx/valgen.h"
////@end includes
/*!
* Forward declarations
*/
////@begin forward declarations
////@end forward declarations
/*!
* Control identifiers
*/
////@begin control identifiers
#define ID_DIALOG 10000
#define SYMBOL_WINEDA_BUILD_BOM_FRAME_STYLE wxDEFAULT_DIALOG_STYLE|wxCAPTION|wxRESIZE_BORDER|wxSYSTEM_MENU|wxSTAY_ON_TOP|wxCLOSE_BOX
#define SYMBOL_WINEDA_BUILD_BOM_FRAME_TITLE _("List of Material")
#define SYMBOL_WINEDA_BUILD_BOM_FRAME_IDNAME ID_DIALOG
#define SYMBOL_WINEDA_BUILD_BOM_FRAME_SIZE wxSize(400, 300)
#define SYMBOL_WINEDA_BUILD_BOM_FRAME_POSITION wxDefaultPosition
#define ID_CHECKBOX 10001
#define ID_CHECKBOX1 10003
#define ID_CHECKBOX2 10004
#define ID_CHECKBOX3 10005
#define ID_CHECKBOX4 10006
#define ID_CHECKBOX5 10002
////@end control identifiers
/*!
* Compatibility
*/
#ifndef wxCLOSE_BOX
#define wxCLOSE_BOX 0x1000
#endif
#ifndef wxFIXED_MINSIZE
#define wxFIXED_MINSIZE 0
#endif
/*!
* WinEDA_Build_BOM_Frame class declaration
*/
class WinEDA_Build_BOM_Frame: public wxDialog
{
DECLARE_DYNAMIC_CLASS( WinEDA_Build_BOM_Frame )
DECLARE_EVENT_TABLE()
public:
/// Constructors
WinEDA_Build_BOM_Frame( );
WinEDA_Build_BOM_Frame( WinEDA_DrawFrame* parent,
wxWindowID id = SYMBOL_WINEDA_BUILD_BOM_FRAME_IDNAME,
const wxString& caption = SYMBOL_WINEDA_BUILD_BOM_FRAME_TITLE,
const wxPoint& pos = SYMBOL_WINEDA_BUILD_BOM_FRAME_POSITION,
const wxSize& size = SYMBOL_WINEDA_BUILD_BOM_FRAME_SIZE,
long style = SYMBOL_WINEDA_BUILD_BOM_FRAME_STYLE );
/// Creation
bool Create( wxWindow* parent, wxWindowID id = SYMBOL_WINEDA_BUILD_BOM_FRAME_IDNAME, const wxString& caption = SYMBOL_WINEDA_BUILD_BOM_FRAME_TITLE, const wxPoint& pos = SYMBOL_WINEDA_BUILD_BOM_FRAME_POSITION, const wxSize& size = SYMBOL_WINEDA_BUILD_BOM_FRAME_SIZE, long style = SYMBOL_WINEDA_BUILD_BOM_FRAME_STYLE );
/// Creates the controls and sizers
void CreateControls();
////@begin WinEDA_Build_BOM_Frame event handler declarations
/// wxEVT_COMMAND_BUTTON_CLICKED event handler for wxID_OK
void OnOkClick( wxCommandEvent& event );
/// wxEVT_COMMAND_BUTTON_CLICKED event handler for wxID_EXIT
void OnExitClick( wxCommandEvent& event );
////@end WinEDA_Build_BOM_Frame event handler declarations
void GenList(void);
////@begin WinEDA_Build_BOM_Frame member function declarations
/// Retrieves bitmap resources
wxBitmap GetBitmapResource( const wxString& name );
/// Retrieves icon resources
wxIcon GetIconResource( const wxString& name );
////@end WinEDA_Build_BOM_Frame member function declarations
/// Should we show tooltips?
static bool ShowToolTips();
////@begin WinEDA_Build_BOM_Frame member variables
wxCheckBox* m_ListCmpbyRefItems;
wxCheckBox* m_ListCmpbyValItems;
wxCheckBox* m_ListSubCmpItems;
wxCheckBox* m_GenListLabelsbyVal;
wxCheckBox* m_GenListLabelsbySheet;
wxCheckBox* m_GetListBrowser;
////@end WinEDA_Build_BOM_Frame member variables
WinEDA_DrawFrame * m_Parent;
wxString m_LibArchiveFileName;
wxString m_ListFileName;
};
#endif
// _DIALOG_BUILD_BOM_H_
| [
"bokeoa@244deca0-f506-0410-ab94-f4f3571dea26"
]
| [
[
[
1,
130
]
]
]
|
7ee93f3824fd12d7a774fbdc7c957e8eedb56f2f | 8c54d89af1800c4c06959a3b7b62d04f883a11c0 | /cs752/iPhone/firstapp/Untitled/Classes/.svn/text-base/Sphere.cpp.svn-base | 264a51c45647031dd9e9a59f5236b1100e61cc30 | []
| no_license | dknutsen/dokray | 567c79e7a69c80a97cd73bead151a12ad2d34f23 | 92acd2967542865963462aaf2299ab2427b89f31 | refs/heads/master | 2020-12-24T13:29:01.740250 | 2011-10-23T23:09:49 | 2011-10-23T23:09:49 | 2,639,353 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,685 |
#include "Sphere.h"
#include <iostream>
using std::cout;
Sphere::Sphere(){
material = NULL;
p = RPoint(0,0,0);
rad = 1.f;
}
Sphere::Sphere(Material* material, const RPoint& c, float radius){
this->material = material;
p = c;
rad = radius;
}
RPoint Sphere::c()const{ return p; }
float Sphere::r()const{ return rad; }
RPoint& Sphere::c(){ return p; }
float& Sphere::r(){ return rad; }
float Sphere::r2()const{ return rad*rad; }
void Sphere::preprocess(){
material->preprocess();
}
Vector Sphere::normal(const RPoint& point)const{
return (point-p).normal();
}
void Sphere::intersect(HitRecord& hit, const RenderContext& rc, const Ray& ray)const{
/*float a = dot(ray.d(), ray.d());
Vector v = ray.p()-p;/*Vector(ray.p().x(), ray.p().y(), ray.p().z());*/
/*float b = 2 * dot(ray.d(), v);
float c = dot(v, v) - r2();
float disc = b * b - 4 * a * c;
if (disc < 0.f){
hit.hit(std::numeric_limits<float>::infinity(), this, material);
return;
}
float distSqrt = sqrtf(disc);
float q;
if (b < 0) q = (-b - distSqrt)/2.0f;
else q = (-b + distSqrt)/2.0f;
float t0 = q / a;
float t1 = c / q;
if (t0 > t1){
float temp = t0;
t0 = t1;
t1 = temp;
}
if (t1 < 0) hit.hit(std::numeric_limits<float>::infinity(), this, material);
if (t0 < 0) hit.hit(t1, this, material);
else hit.hit(t0, this, material);*/
Vector dist = ray.p() - p;
float b = dot(dist, ray.d());
float c = dot(dist, dist) - r2();
float d = b*b - c;
float t = d > 0 ? -b - sqrt(d) : std::numeric_limits<float>::infinity();
hit.hit(t, this, this->material);
} | [
"[email protected]"
]
| [
[
[
1,
66
]
]
]
|
|
284413138f5db5198775bbddce98d3a56ea05469 | b8fbe9079ce8996e739b476d226e73d4ec8e255c | /src/engine/rb_texture/export.cpp | 0ba61e98957365811fe1efcd0b908c77f39cb814 | []
| no_license | dtbinh/rush | 4294f84de1b6e6cc286aaa1dd48cf12b12a467d0 | ad75072777438c564ccaa29af43e2a9fd2c51266 | refs/heads/master | 2021-01-15T17:14:48.417847 | 2011-06-16T17:41:20 | 2011-06-16T17:41:20 | 41,476,633 | 1 | 0 | null | 2015-08-27T09:03:44 | 2015-08-27T09:03:44 | null | UTF-8 | C++ | false | false | 103 | cpp | #include "stdafx.h"
#include "JReflect.h"
export(rb_texture)
{
link_class( JProcTexture );
} | [
"[email protected]"
]
| [
[
[
1,
7
]
]
]
|
d993b1382d80f25b442c10b4bcf56dbfade332a4 | b14d5833a79518a40d302e5eb40ed5da193cf1b2 | /cpp/extern/xercesc++/2.6.0/src/xercesc/util/NetAccessors/libWWW/LibWWWNetAccessor.cpp | d55ba24c7bdcaa54b584d64c58939870be4499a3 | [
"Apache-2.0"
]
| permissive | andyburke/bitflood | dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf | fca6c0b635d07da4e6c7fbfa032921c827a981d6 | refs/heads/master | 2016-09-10T02:14:35.564530 | 2011-11-17T09:51:49 | 2011-11-17T09:51:49 | 2,794,411 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,097 | cpp | /*
* Copyright 1999-2000,2004 The Apache Software Foundation.
*
* 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.
*/
/**
* $Id: LibWWWNetAccessor.cpp,v 1.7 2004/09/08 13:56:36 peiyongz Exp $
*/
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/util/XMLUni.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/NetAccessors/libWWW/BinURLInputStream.hpp>
#include <xercesc/util/NetAccessors/libWWW/LibWWWNetAccessor.hpp>
#include <WWWInit.h>
XERCES_CPP_NAMESPACE_BEGIN
const XMLCh LibWWWNetAccessor::fgMyName[] =
{
chLatin_l, chLatin_i, chLatin_b, chLatin_W, chLatin_W, chLatin_W,
chLatin_N, chLatin_e, chLatin_t, chLatin_A, chLatin_c, chLatin_c,
chLatin_e, chLatin_s, chLatin_s, chLatin_o, chLatin_r, chNull
};
LibWWWNetAccessor::LibWWWNetAccessor()
{
//
// Initialize the libWWW library here.
//
HTProfile_newPreemptiveClient("XercesC", gXercesFullVersionStr);
HTConversion_add(HTFormat_conversion(), "text/xml", "*/*", HTThroughLine, 1.0, 0.0, 0.0);
HTConversion_add(HTFormat_conversion(), "application/xml", "*/*", HTThroughLine, 1.0, 0.0, 0.0);
#ifdef XML_DEBUG
HTSetTraceMessageMask("sop");
#endif
HTAlert_setInteractive(NO);
HTHost_setEventTimeout(5000);
}
LibWWWNetAccessor::~LibWWWNetAccessor()
{
// Cleanup the libWWW library here.
/* Quote from http://www.w3.org/Library/src/HTProfil.html#Client:
*
* This call also supersedes the termination function for the
* Library core, HTLibTerminate() so that you don't have to call
* that after calling this function.
*/
HTProfile_delete();
}
BinInputStream* LibWWWNetAccessor::makeNew(const XMLURL& urlSource, const XMLNetHTTPInfo* httpInfo/*=0*/)
{
XMLURL::Protocols protocol = urlSource.getProtocol();
switch(protocol)
{
case XMLURL::HTTP:
{
if(httpInfo!=0 && httpInfo->fHTTPMethod!=XMLNetHTTPInfo::GET)
ThrowXML(NetAccessorException, XMLExcepts::NetAcc_UnsupportedMethod);
BinURLInputStream* retStrm =
new (urlSource.getMemoryManager()) BinURLInputStream(urlSource);
return retStrm;
}
//
// These are the only protocols we support now. So throw and
// unsupported protocol exception for the others.
//
default :
ThrowXMLwithMemMgr(MalformedURLException, XMLExcepts::URL_UnsupportedProto, urlSource.getMemoryManager());
}
}
XERCES_CPP_NAMESPACE_END
| [
"[email protected]"
]
| [
[
[
1,
92
]
]
]
|
09a81f9e0996ecaa8e32a9ea47775937523280cd | ad80c85f09a98b1bfc47191c0e99f3d4559b10d4 | /code/src/odephysics/nodesphereshape.cc | ed9752df9a0f83b2f589832b6afe0ef8ea08c524 | []
| no_license | DSPNerd/m-nebula | 76a4578f5504f6902e054ddd365b42672024de6d | 52a32902773c10cf1c6bc3dabefd2fd1587d83b3 | refs/heads/master | 2021-12-07T18:23:07.272880 | 2009-07-07T09:47:09 | 2009-07-07T09:47:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,606 | cc | #define N_IMPLEMENTS nOdeSphereShape
//------------------------------------------------------------------------------
// nodesphereshape.cc
//
// (c) 2003 Vadim Macagon
//
// nOdeSphereShape is licensed under the terms of the Nebula License.
//------------------------------------------------------------------------------
#include "odephysics/nodesphereshape.h"
#ifndef N_PRIMITIVESERVER_H
#include "gfx/nprimitiveserver.h"
#endif
#ifndef N_ODE_H
#define N_ODE_H
#include <ode/ode.h>
#endif
//------------------------------------------------------------------------------
/**
*/
nOdeSphereShape::nOdeSphereShape()
{
// create sphere with default radius = 1
this->geomId = dCreateSphere( 0, 1 );
dGeomSetData( this->geomId, (void*)this );
this->shapeType = nOdeCollideShape::OST_SPHERE;
}
//------------------------------------------------------------------------------
/**
*/
nOdeSphereShape::~nOdeSphereShape()
{
dGeomDestroy( this->geomId );
}
//------------------------------------------------------------------------------
/**
*/
void nOdeSphereShape::SetRadius( float rad )
{
dGeomSphereSetRadius( this->geomId, rad );
}
//------------------------------------------------------------------------------
/**
*/
float nOdeSphereShape::GetRadius()
{
return dGeomSphereGetRadius( this->geomId );
}
//------------------------------------------------------------------------------
/**
*/
void nOdeSphereShape::VisualizeLocal( nGfxServer* gs, nPrimitiveServer* prim )
{
prim->SolidSphere( this->GetRadius(), 16, 16 );
}
| [
"plushe@411252de-2431-11de-b186-ef1da62b6547"
]
| [
[
[
1,
61
]
]
]
|
f7aaee6a2120bb3575ccae94336876fa680b8467 | cd0987589d3815de1dea8529a7705caac479e7e9 | /webkit/WebKit2/Platform/qt/SharedMemoryQt.cpp | 148104f01a81bf7efb1cd9b221eb8f732bfa098f | []
| no_license | azrul2202/WebKit-Smartphone | 0aab1ff641d74f15c0623f00c56806dbc9b59fc1 | 023d6fe819445369134dee793b69de36748e71d7 | refs/heads/master | 2021-01-15T09:24:31.288774 | 2011-07-11T11:12:44 | 2011-07-11T11:12:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,400 | cpp | /*
* Copyright (C) 2010 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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 "SharedMemory.h"
#include "NotImplemented.h"
namespace WebKit {
SharedMemory::Handle::Handle()
{
notImplemented();
}
SharedMemory::Handle::~Handle()
{
notImplemented();
}
void SharedMemory::Handle::encode(CoreIPC::ArgumentEncoder* encoder) const
{
notImplemented();
}
bool SharedMemory::Handle::decode(CoreIPC::ArgumentDecoder* decoder, Handle& handle)
{
notImplemented();
return false;
}
PassRefPtr<SharedMemory> SharedMemory::create(size_t size)
{
notImplemented();
return 0;
}
PassRefPtr<SharedMemory> SharedMemory::create(const Handle& handle, Protection protection)
{
notImplemented();
return 0;
}
SharedMemory::~SharedMemory()
{
notImplemented();
}
bool SharedMemory::createHandle(Handle& handle, Protection protection)
{
notImplemented();
return false;
}
unsigned SharedMemory::systemPageSize()
{
static unsigned pageSize = 0;
return pageSize;
}
} // namespace WebKit
| [
"[email protected]"
]
| [
[
[
1,
83
]
]
]
|
00112038012604fdeea0ea2d347c16c356501ccb | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Targets/MapLib/Shared/include/InterpolationCallback.h | f65348c6c04dd72807e5adc660f8508be3ff021e | [
"BSD-3-Clause"
]
| permissive | ravustaja/Wayfinder-S60-Navigator | ef506c418b8c2e6498ece6dcae67e583fb8a4a95 | 14d1b729b2cea52f726874687e78f17492949585 | refs/heads/master | 2021-01-16T20:53:37.630909 | 2010-06-28T09:51:10 | 2010-06-28T09:51:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,225 | h | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Vodafone Group Services Ltd 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.
*/
#ifndef _INTERPOLATIONCALLBACK_H_
#define _INTERPOLATIONCALLBACK_H_
#include "MC2Coordinate.h"
class InterpolationCallback {
public:
/**
* Callback function that is called whenever a
* new position has been interpolated. The distinction
* between normal position updates and these are that
* these are calculated, and not necessarily corresponding
* to the actual point in time.
*/
virtual void positionInterpolated( MC2Coordinate newPosition,
double velocityMPS,
double headingDegrees ) = 0;
};
#endif /* _INTERPOLATIONCALLBACK_H_ */
| [
"[email protected]"
]
| [
[
[
1,
35
]
]
]
|
688f191da0bb47270ab049c6dd348fab3fae4660 | 0bab4267636e3b06cb0e73fe9d31b0edd76260c2 | /freewar-alpha/lib/sdlgfx/SDL_gfxPrimitives.cpp | 414c6973029c08387ec7766efff0ae6a1d28e1c3 | []
| no_license | BackupTheBerlios/freewar-svn | 15fafedeed3ea1d374500d3430ff16b412b2f223 | aa1a28f19610dbce12be463d5ccd98f712631bc3 | refs/heads/master | 2021-01-10T19:54:11.599797 | 2006-12-10T21:45:11 | 2006-12-10T21:45:11 | 40,725,388 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 83,410 | cpp | /*
SDL_gfxPrimitives - Graphics primitives for SDL surfaces
LGPL (c) A. Schiffler
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include "freewar.h"
#include "SDL_gfxPrimitives.h"
#include "SDL_gfxPrimitives_font.h"
/* -===================- */
/* ----- Defines for pixel clipping tests */
#define clip_xmin(surface) surface->clip_rect.x
#define clip_xmax(surface) surface->clip_rect.x+surface->clip_rect.w-1
#define clip_ymin(surface) surface->clip_rect.y
#define clip_ymax(surface) surface->clip_rect.y+surface->clip_rect.h-1
/* ----- Pixel - fast, no blending, no locking, clipping */
int fastPixelColorNolock(SDL_Surface * dst, Sint16 x, Sint16 y, Uint32 color)
{
int bpp;
Uint8 *p;
/*
* Honor clipping setup at pixel level
*/
if ((x >= clip_xmin(dst)) && (x <= clip_xmax(dst)) && (y >= clip_ymin(dst)) && (y <= clip_ymax(dst))) {
/*
* Get destination format
*/
bpp = dst->format->BytesPerPixel;
p = (Uint8 *) dst->pixels + y * dst->pitch + x * bpp;
switch (bpp) {
case 1:
*p = color;
break;
case 2:
*(Uint16 *) p = color;
break;
case 3:
if (SDL_BYTEORDER == SDL_BIG_ENDIAN) {
p[0] = (color >> 16) & 0xff;
p[1] = (color >> 8) & 0xff;
p[2] = color & 0xff;
} else {
p[0] = color & 0xff;
p[1] = (color >> 8) & 0xff;
p[2] = (color >> 16) & 0xff;
}
break;
case 4:
*(Uint32 *) p = color;
break;
} /* switch */
}
return (0);
}
/* ----- Pixel - fast, no blending, no locking, no clipping */
/* (faster but dangerous, make sure we stay in surface bounds) */
int fastPixelColorNolockNoclip(SDL_Surface * dst, Sint16 x, Sint16 y, Uint32 color)
{
int bpp;
Uint8 *p;
/*
* Get destination format
*/
bpp = dst->format->BytesPerPixel;
p = (Uint8 *) dst->pixels + y * dst->pitch + x * bpp;
switch (bpp) {
case 1:
*p = color;
break;
case 2:
*(Uint16 *) p = color;
break;
case 3:
if (SDL_BYTEORDER == SDL_BIG_ENDIAN) {
p[0] = (color >> 16) & 0xff;
p[1] = (color >> 8) & 0xff;
p[2] = color & 0xff;
} else {
p[0] = color & 0xff;
p[1] = (color >> 8) & 0xff;
p[2] = (color >> 16) & 0xff;
}
break;
case 4:
*(Uint32 *) p = color;
break;
} /* switch */
return (0);
}
/* ----- Pixel - fast, no blending, locking, clipping */
int fastPixelColor(SDL_Surface * dst, Sint16 x, Sint16 y, Uint32 color)
{
int result;
/*
* Lock the surface
*/
if (SDL_MUSTLOCK(dst)) {
if (SDL_LockSurface(dst) < 0) {
return (-1);
}
}
result = fastPixelColorNolock(dst, x, y, color);
/*
* Unlock surface
*/
if (SDL_MUSTLOCK(dst)) {
SDL_UnlockSurface(dst);
}
return (result);
}
/* ----- Pixel - fast, no blending, locking, RGB input */
int fastPixelRGBA(SDL_Surface * dst, Sint16 x, Sint16 y, Uint8 r, Uint8 g, Uint8 b, Uint8 a)
{
Uint32 color;
/*
* Setup color
*/
color = SDL_MapRGBA(dst->format, r, g, b, a);
/*
* Draw
*/
return (fastPixelColor(dst, x, y, color));
}
/* ----- Pixel - fast, no blending, no locking RGB input */
int fastPixelRGBANolock(SDL_Surface * dst, Sint16 x, Sint16 y, Uint8 r, Uint8 g, Uint8 b, Uint8 a)
{
Uint32 color;
/*
* Setup color
*/
color = SDL_MapRGBA(dst->format, r, g, b, a);
/*
* Draw
*/
return (fastPixelColorNolock(dst, x, y, color));
}
/* PutPixel routine with alpha blending, input color in destination format */
/* New, faster routine - default blending pixel */
int _putPixelAlpha(SDL_Surface * surface, Sint16 x, Sint16 y, Uint32 color, Uint8 alpha)
{
Uint32 Rmask = surface->format->Rmask, Gmask =
surface->format->Gmask, Bmask = surface->format->Bmask, Amask = surface->format->Amask;
Uint32 R, G, B, A = 0;
if (x >= clip_xmin(surface) && x <= clip_xmax(surface)
&& y >= clip_ymin(surface) && y <= clip_ymax(surface)) {
switch (surface->format->BytesPerPixel) {
case 1:{ /* Assuming 8-bpp */
if (alpha == 255) {
*((Uint8 *) surface->pixels + y * surface->pitch + x) = color;
} else {
Uint8 *pixel = (Uint8 *) surface->pixels + y * surface->pitch + x;
Uint8 dR = surface->format->palette->colors[*pixel].r;
Uint8 dG = surface->format->palette->colors[*pixel].g;
Uint8 dB = surface->format->palette->colors[*pixel].b;
Uint8 sR = surface->format->palette->colors[color].r;
Uint8 sG = surface->format->palette->colors[color].g;
Uint8 sB = surface->format->palette->colors[color].b;
dR = dR + ((sR - dR) * alpha >> 8);
dG = dG + ((sG - dG) * alpha >> 8);
dB = dB + ((sB - dB) * alpha >> 8);
*pixel = SDL_MapRGB(surface->format, dR, dG, dB);
}
}
break;
case 2:{ /* Probably 15-bpp or 16-bpp */
if (alpha == 255) {
*((Uint16 *) surface->pixels + y * surface->pitch / 2 + x) = color;
} else {
Uint16 *pixel = (Uint16 *) surface->pixels + y * surface->pitch / 2 + x;
Uint32 dc = *pixel;
R = ((dc & Rmask) + (((color & Rmask) - (dc & Rmask)) * alpha >> 8)) & Rmask;
G = ((dc & Gmask) + (((color & Gmask) - (dc & Gmask)) * alpha >> 8)) & Gmask;
B = ((dc & Bmask) + (((color & Bmask) - (dc & Bmask)) * alpha >> 8)) & Bmask;
if (Amask)
A = ((dc & Amask) + (((color & Amask) - (dc & Amask)) * alpha >> 8)) & Amask;
*pixel = R | G | B | A;
}
}
break;
case 3:{ /* Slow 24-bpp mode, usually not used */
Uint8 *pix = (Uint8 *) surface->pixels + y * surface->pitch + x * 3;
Uint8 rshift8 = surface->format->Rshift / 8;
Uint8 gshift8 = surface->format->Gshift / 8;
Uint8 bshift8 = surface->format->Bshift / 8;
Uint8 ashift8 = surface->format->Ashift / 8;
if (alpha == 255) {
*(pix + rshift8) = color >> surface->format->Rshift;
*(pix + gshift8) = color >> surface->format->Gshift;
*(pix + bshift8) = color >> surface->format->Bshift;
*(pix + ashift8) = color >> surface->format->Ashift;
} else {
Uint8 dR, dG, dB, dA = 0;
Uint8 sR, sG, sB, sA = 0;
pix = (Uint8 *) surface->pixels + y * surface->pitch + x * 3;
dR = *((pix) + rshift8);
dG = *((pix) + gshift8);
dB = *((pix) + bshift8);
dA = *((pix) + ashift8);
sR = (color >> surface->format->Rshift) & 0xff;
sG = (color >> surface->format->Gshift) & 0xff;
sB = (color >> surface->format->Bshift) & 0xff;
sA = (color >> surface->format->Ashift) & 0xff;
dR = dR + ((sR - dR) * alpha >> 8);
dG = dG + ((sG - dG) * alpha >> 8);
dB = dB + ((sB - dB) * alpha >> 8);
dA = dA + ((sA - dA) * alpha >> 8);
*((pix) + rshift8) = dR;
*((pix) + gshift8) = dG;
*((pix) + bshift8) = dB;
*((pix) + ashift8) = dA;
}
}
break;
case 4:{ /* Probably 32-bpp */
if (alpha == 255) {
*((Uint32 *) surface->pixels + y * surface->pitch / 4 + x) = color;
} else {
Uint32 *pixel = (Uint32 *) surface->pixels + y * surface->pitch / 4 + x;
Uint32 dc = *pixel;
R = ((dc & Rmask) + (((color & Rmask) - (dc & Rmask)) * alpha >> 8)) & Rmask;
G = ((dc & Gmask) + (((color & Gmask) - (dc & Gmask)) * alpha >> 8)) & Gmask;
B = ((dc & Bmask) + (((color & Bmask) - (dc & Bmask)) * alpha >> 8)) & Bmask;
if (Amask)
A = ((dc & Amask) + (((color & Amask) - (dc & Amask)) * alpha >> 8)) & Amask;
*pixel = R | G | B | A;
}
}
break;
}
}
return (0);
}
/* ----- Pixel - pixel draw with blending enabled if a<255 */
int pixelColor(SDL_Surface * dst, Sint16 x, Sint16 y, Uint32 color)
{
Uint8 alpha;
Uint32 mcolor;
int result = 0;
/*
* Lock the surface
*/
if (SDL_MUSTLOCK(dst)) {
if (SDL_LockSurface(dst) < 0) {
return (-1);
}
}
/*
* Setup color
*/
alpha = color & 0x000000ff;
mcolor =
SDL_MapRGBA(dst->format, (color & 0xff000000) >> 24,
(color & 0x00ff0000) >> 16, (color & 0x0000ff00) >> 8, alpha);
/*
* Draw
*/
result = _putPixelAlpha(dst, x, y, mcolor, alpha);
/*
* Unlock the surface
*/
if (SDL_MUSTLOCK(dst)) {
SDL_UnlockSurface(dst);
}
return (result);
}
int pixelColorNolock(SDL_Surface * dst, Sint16 x, Sint16 y, Uint32 color)
{
Uint8 alpha;
Uint32 mcolor;
int result = 0;
/*
* Setup color
*/
alpha = color & 0x000000ff;
mcolor =
SDL_MapRGBA(dst->format, (color & 0xff000000) >> 24,
(color & 0x00ff0000) >> 16, (color & 0x0000ff00) >> 8, alpha);
/*
* Draw
*/
result = _putPixelAlpha(dst, x, y, mcolor, alpha);
return (result);
}
/* Filled rectangle with alpha blending, color in destination format */
int _filledRectAlpha(SDL_Surface * surface, Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Uint32 color, Uint8 alpha)
{
Uint32 Rmask = surface->format->Rmask, Gmask =
surface->format->Gmask, Bmask = surface->format->Bmask, Amask = surface->format->Amask;
Uint32 R, G, B, A = 0;
Sint16 x, y;
switch (surface->format->BytesPerPixel) {
case 1:{ /* Assuming 8-bpp */
Uint8 *row, *pixel;
Uint8 dR, dG, dB;
Uint8 sR = surface->format->palette->colors[color].r;
Uint8 sG = surface->format->palette->colors[color].g;
Uint8 sB = surface->format->palette->colors[color].b;
for (y = y1; y <= y2; y++) {
row = (Uint8 *) surface->pixels + y * surface->pitch;
for (x = x1; x <= x2; x++) {
pixel = row + x;
dR = surface->format->palette->colors[*pixel].r;
dG = surface->format->palette->colors[*pixel].g;
dB = surface->format->palette->colors[*pixel].b;
dR = dR + ((sR - dR) * alpha >> 8);
dG = dG + ((sG - dG) * alpha >> 8);
dB = dB + ((sB - dB) * alpha >> 8);
*pixel = SDL_MapRGB(surface->format, dR, dG, dB);
}
}
}
break;
case 2:{ /* Probably 15-bpp or 16-bpp */
Uint16 *row, *pixel;
Uint32 dR = (color & Rmask), dG = (color & Gmask), dB = (color & Bmask), dA = (color & Amask);
for (y = y1; y <= y2; y++) {
row = (Uint16 *) surface->pixels + y * surface->pitch / 2;
for (x = x1; x <= x2; x++) {
pixel = row + x;
R = ((*pixel & Rmask) + ((dR - (*pixel & Rmask)) * alpha >> 8)) & Rmask;
G = ((*pixel & Gmask) + ((dG - (*pixel & Gmask)) * alpha >> 8)) & Gmask;
B = ((*pixel & Bmask) + ((dB - (*pixel & Bmask)) * alpha >> 8)) & Bmask;
if (Amask)
A = ((*pixel & Amask) + ((dA - (*pixel & Amask)) * alpha >> 8)) & Amask;
*pixel = R | G | B | A;
}
}
}
break;
case 3:{ /* Slow 24-bpp mode, usually not used */
Uint8 *row, *pix;
Uint8 dR, dG, dB, dA;
Uint8 rshift8 = surface->format->Rshift / 8;
Uint8 gshift8 = surface->format->Gshift / 8;
Uint8 bshift8 = surface->format->Bshift / 8;
Uint8 ashift8 = surface->format->Ashift / 8;
Uint8 sR = (color >> surface->format->Rshift) & 0xff;
Uint8 sG = (color >> surface->format->Gshift) & 0xff;
Uint8 sB = (color >> surface->format->Bshift) & 0xff;
Uint8 sA = (color >> surface->format->Ashift) & 0xff;
for (y = y1; y <= y2; y++) {
row = (Uint8 *) surface->pixels + y * surface->pitch;
for (x = x1; x <= x2; x++) {
pix = row + x * 3;
dR = *((pix) + rshift8);
dG = *((pix) + gshift8);
dB = *((pix) + bshift8);
dA = *((pix) + ashift8);
dR = dR + ((sR - dR) * alpha >> 8);
dG = dG + ((sG - dG) * alpha >> 8);
dB = dB + ((sB - dB) * alpha >> 8);
dA = dA + ((sA - dA) * alpha >> 8);
*((pix) + rshift8) = dR;
*((pix) + gshift8) = dG;
*((pix) + bshift8) = dB;
*((pix) + ashift8) = dA;
}
}
}
break;
case 4:{ /* Probably 32-bpp */
Uint32 *row, *pixel;
Uint32 dR = (color & Rmask), dG = (color & Gmask), dB = (color & Bmask), dA = (color & Amask);
for (y = y1; y <= y2; y++) {
row = (Uint32 *) surface->pixels + y * surface->pitch / 4;
for (x = x1; x <= x2; x++) {
pixel = row + x;
R = ((*pixel & Rmask) + ((dR - (*pixel & Rmask)) * alpha >> 8)) & Rmask;
G = ((*pixel & Gmask) + ((dG - (*pixel & Gmask)) * alpha >> 8)) & Gmask;
B = ((*pixel & Bmask) + ((dB - (*pixel & Bmask)) * alpha >> 8)) & Bmask;
if (Amask)
A = ((*pixel & Amask) + ((dA - (*pixel & Amask)) * alpha >> 8)) & Amask;
*pixel = R | G | B | A;
}
}
}
break;
}
return (0);
}
/* Draw rectangle with alpha enabled from RGBA color. */
int filledRectAlpha(SDL_Surface * dst, Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Uint32 color)
{
Uint8 alpha;
Uint32 mcolor;
int result = 0;
/*
* Lock the surface
*/
if (SDL_MUSTLOCK(dst)) {
if (SDL_LockSurface(dst) < 0) {
return (-1);
}
}
/*
* Setup color
*/
alpha = color & 0x000000ff;
mcolor =
SDL_MapRGBA(dst->format, (color & 0xff000000) >> 24,
(color & 0x00ff0000) >> 16, (color & 0x0000ff00) >> 8, alpha);
/*
* Draw
*/
result = _filledRectAlpha(dst, x1, y1, x2, y2, mcolor, alpha);
/*
* Unlock the surface
*/
if (SDL_MUSTLOCK(dst)) {
SDL_UnlockSurface(dst);
}
return (result);
}
/* Draw horizontal line with alpha enabled from RGBA color */
int HLineAlpha(SDL_Surface * dst, Sint16 x1, Sint16 x2, Sint16 y, Uint32 color)
{
return (filledRectAlpha(dst, x1, y, x2, y, color));
}
/* Draw vertical line with alpha enabled from RGBA color */
int VLineAlpha(SDL_Surface * dst, Sint16 x, Sint16 y1, Sint16 y2, Uint32 color)
{
return (filledRectAlpha(dst, x, y1, x, y2, color));
}
/* Pixel - using alpha weight on color for AA-drawing */
int pixelColorWeight(SDL_Surface * dst, Sint16 x, Sint16 y, Uint32 color, Uint32 weight)
{
Uint32 a;
/*
* Get alpha
*/
a = (color & (Uint32) 0x000000ff);
/*
* Modify Alpha by weight
*/
a = ((a * weight) >> 8);
return (pixelColor(dst, x, y, (color & (Uint32) 0xffffff00) | (Uint32) a));
}
/* Pixel - using alpha weight on color for AA-drawing - no locking */
int pixelColorWeightNolock(SDL_Surface * dst, Sint16 x, Sint16 y, Uint32 color, Uint32 weight)
{
Uint32 a;
/*
* Get alpha
*/
a = (color & (Uint32) 0x000000ff);
/*
* Modify Alpha by weight
*/
a = ((a * weight) >> 8);
return (pixelColorNolock(dst, x, y, (color & (Uint32) 0xffffff00) | (Uint32) a));
}
int pixelRGBA(SDL_Surface * dst, Sint16 x, Sint16 y, Uint8 r, Uint8 g, Uint8 b, Uint8 a)
{
Uint32 color;
/*
* Check Alpha
*/
if (a == 255) {
/*
* No alpha blending required
*/
/*
* Setup color
*/
color = SDL_MapRGBA(dst->format, r, g, b, a);
/*
* Draw
*/
return (fastPixelColor(dst, x, y, color));
} else {
/*
* Alpha blending required
*/
/*
* Draw
*/
return (pixelColor(dst, x, y, ((Uint32) r << 24) | ((Uint32) g << 16) | ((Uint32) b << 8) | (Uint32) a));
}
}
/* ----- Horizontal line */
/* Just store color including alpha, no blending */
int hlineColorStore(SDL_Surface * dst, Sint16 x1, Sint16 x2, Sint16 y, Uint32 color)
{
Sint16 left, right, top, bottom;
Uint8 *pixel, *pixellast;
int dx;
int pixx, pixy;
Sint16 w;
Sint16 xtmp;
int result = -1;
/*
* Get clipping boundary
*/
left = dst->clip_rect.x;
right = dst->clip_rect.x + dst->clip_rect.w - 1;
top = dst->clip_rect.y;
bottom = dst->clip_rect.y + dst->clip_rect.h - 1;
/*
* Check visibility of hline
*/
if ((x1<left) && (x2<left)) {
return(0);
}
if ((x1>right) && (x2>right)) {
return(0);
}
if ((y<top) || (y>bottom)) {
return (0);
}
/*
* Clip x
*/
if (x1 < left) {
x1 = left;
}
if (x2 > right) {
x2 = right;
}
/*
* Swap x1, x2 if required
*/
if (x1 > x2) {
xtmp = x1;
x1 = x2;
x2 = xtmp;
}
/*
* Calculate width
*/
w = x2 - x1;
/*
* Sanity check on width
*/
if (w < 0) {
return (0);
}
/*
* Lock surface
*/
SDL_LockSurface(dst);
/*
* More variable setup
*/
dx = w;
pixx = dst->format->BytesPerPixel;
pixy = dst->pitch;
pixel = ((Uint8 *) dst->pixels) + pixx * (int) x1 + pixy * (int) y;
/*
* Draw
*/
switch (dst->format->BytesPerPixel) {
case 1:
memset(pixel, color, dx);
break;
case 2:
pixellast = pixel + dx + dx;
for (; pixel <= pixellast; pixel += pixx) {
*(Uint16 *) pixel = color;
}
break;
case 3:
pixellast = pixel + dx + dx + dx;
for (; pixel <= pixellast; pixel += pixx) {
if (SDL_BYTEORDER == SDL_BIG_ENDIAN) {
pixel[0] = (color >> 16) & 0xff;
pixel[1] = (color >> 8) & 0xff;
pixel[2] = color & 0xff;
} else {
pixel[0] = color & 0xff;
pixel[1] = (color >> 8) & 0xff;
pixel[2] = (color >> 16) & 0xff;
}
}
break;
default: /* case 4 */
dx = dx + dx;
pixellast = pixel + dx + dx;
for (; pixel <= pixellast; pixel += pixx) {
*(Uint32 *) pixel = color;
}
break;
}
/*
* Unlock surface
*/
SDL_UnlockSurface(dst);
/*
* Set result code
*/
result = 0;
return (result);
}
int hlineRGBAStore(SDL_Surface * dst, Sint16 x1, Sint16 x2, Sint16 y, Uint8 r, Uint8 g, Uint8 b, Uint8 a)
{
/*
* Draw
*/
return (hlineColorStore(dst, x1, x2, y, ((Uint32) r << 24) | ((Uint32) g << 16) | ((Uint32) b << 8) | (Uint32) a));
}
int hlineColor(SDL_Surface * dst, Sint16 x1, Sint16 x2, Sint16 y, Uint32 color)
{
Sint16 left, right, top, bottom;
Uint8 *pixel, *pixellast;
int dx;
int pixx, pixy;
Sint16 w;
Sint16 xtmp;
int result = -1;
Uint8 *colorptr;
/*
* Get clipping boundary
*/
left = dst->clip_rect.x;
right = dst->clip_rect.x + dst->clip_rect.w - 1;
top = dst->clip_rect.y;
bottom = dst->clip_rect.y + dst->clip_rect.h - 1;
/*
* Check visibility of hline
*/
if ((x1<left) && (x2<left)) {
return(0);
}
if ((x1>right) && (x2>right)) {
return(0);
}
if ((y<top) || (y>bottom)) {
return (0);
}
/*
* Clip x
*/
if (x1 < left) {
x1 = left;
}
if (x2 > right) {
x2 = right;
}
/*
* Swap x1, x2 if required
*/
if (x1 > x2) {
xtmp = x1;
x1 = x2;
x2 = xtmp;
}
/*
* Calculate width
*/
w = x2 - x1;
/*
* Sanity check on width
*/
if (w < 0) {
return (0);
}
/*
* Alpha check
*/
if ((color & 255) == 255) {
/*
* No alpha-blending required
*/
/*
* Setup color
*/
colorptr = (Uint8 *) & color;
if (SDL_BYTEORDER == SDL_BIG_ENDIAN) {
color = SDL_MapRGBA(dst->format, colorptr[0], colorptr[1], colorptr[2], colorptr[3]);
} else {
color = SDL_MapRGBA(dst->format, colorptr[3], colorptr[2], colorptr[1], colorptr[0]);
}
/*
* Lock surface
*/
SDL_LockSurface(dst);
/*
* More variable setup
*/
dx = w;
pixx = dst->format->BytesPerPixel;
pixy = dst->pitch;
pixel = ((Uint8 *) dst->pixels) + pixx * (int) x1 + pixy * (int) y;
/*
* Draw
*/
switch (dst->format->BytesPerPixel) {
case 1:
memset(pixel, color, dx);
break;
case 2:
pixellast = pixel + dx + dx;
for (; pixel <= pixellast; pixel += pixx) {
*(Uint16 *) pixel = color;
}
break;
case 3:
pixellast = pixel + dx + dx + dx;
for (; pixel <= pixellast; pixel += pixx) {
if (SDL_BYTEORDER == SDL_BIG_ENDIAN) {
pixel[0] = (color >> 16) & 0xff;
pixel[1] = (color >> 8) & 0xff;
pixel[2] = color & 0xff;
} else {
pixel[0] = color & 0xff;
pixel[1] = (color >> 8) & 0xff;
pixel[2] = (color >> 16) & 0xff;
}
}
break;
default: /* case 4 */
dx = dx + dx;
pixellast = pixel + dx + dx;
for (; pixel <= pixellast; pixel += pixx) {
*(Uint32 *) pixel = color;
}
break;
}
/*
* Unlock surface
*/
SDL_UnlockSurface(dst);
/*
* Set result code
*/
result = 0;
} else {
/*
* Alpha blending blit
*/
result = HLineAlpha(dst, x1, x1 + w, y, color);
}
return (result);
}
int hlineRGBA(SDL_Surface * dst, Sint16 x1, Sint16 x2, Sint16 y, Uint8 r, Uint8 g, Uint8 b, Uint8 a)
{
/*
* Draw
*/
return (hlineColor(dst, x1, x2, y, ((Uint32) r << 24) | ((Uint32) g << 16) | ((Uint32) b << 8) | (Uint32) a));
}
/* ----- Vertical line */
int vlineColor(SDL_Surface * dst, Sint16 x, Sint16 y1, Sint16 y2, Uint32 color)
{
Sint16 left, right, top, bottom;
Uint8 *pixel, *pixellast;
int dy;
int pixx, pixy;
Sint16 h;
Sint16 ytmp;
int result = -1;
Uint8 *colorptr;
/*
* Get clipping boundary
*/
left = dst->clip_rect.x;
right = dst->clip_rect.x + dst->clip_rect.w - 1;
top = dst->clip_rect.y;
bottom = dst->clip_rect.y + dst->clip_rect.h - 1;
/*
* Check visibility of vline
*/
if ((x<left) || (x>right)) {
return (0);
}
if ((y1<top) && (y2<top)) {
return(0);
}
if ((y1>bottom) && (y2>bottom)) {
return(0);
}
/*
* Clip y
*/
if (y1 < top) {
y1 = top;
}
if (y2 > bottom) {
y2 = bottom;
}
/*
* Swap y1, y2 if required
*/
if (y1 > y2) {
ytmp = y1;
y1 = y2;
y2 = ytmp;
}
/*
* Calculate height
*/
h = y2 - y1;
/*
* Sanity check on height
*/
if (h < 0) {
return (0);
}
/*
* Alpha check
*/
if ((color & 255) == 255) {
/*
* No alpha-blending required
*/
/*
* Setup color
*/
colorptr = (Uint8 *) & color;
if (SDL_BYTEORDER == SDL_BIG_ENDIAN) {
color = SDL_MapRGBA(dst->format, colorptr[0], colorptr[1], colorptr[2], colorptr[3]);
} else {
color = SDL_MapRGBA(dst->format, colorptr[3], colorptr[2], colorptr[1], colorptr[0]);
}
/*
* Lock surface
*/
SDL_LockSurface(dst);
/*
* More variable setup
*/
dy = h;
pixx = dst->format->BytesPerPixel;
pixy = dst->pitch;
pixel = ((Uint8 *) dst->pixels) + pixx * (int) x + pixy * (int) y1;
pixellast = pixel + pixy * dy;
/*
* Draw
*/
switch (dst->format->BytesPerPixel) {
case 1:
for (; pixel <= pixellast; pixel += pixy) {
*(Uint8 *) pixel = color;
}
break;
case 2:
for (; pixel <= pixellast; pixel += pixy) {
*(Uint16 *) pixel = color;
}
break;
case 3:
for (; pixel <= pixellast; pixel += pixy) {
if (SDL_BYTEORDER == SDL_BIG_ENDIAN) {
pixel[0] = (color >> 16) & 0xff;
pixel[1] = (color >> 8) & 0xff;
pixel[2] = color & 0xff;
} else {
pixel[0] = color & 0xff;
pixel[1] = (color >> 8) & 0xff;
pixel[2] = (color >> 16) & 0xff;
}
}
break;
default: /* case 4 */
for (; pixel <= pixellast; pixel += pixy) {
*(Uint32 *) pixel = color;
}
break;
}
/*
* Unlock surface
*/
SDL_UnlockSurface(dst);
/*
* Set result code
*/
result = 0;
} else {
/*
* Alpha blending blit
*/
result = VLineAlpha(dst, x, y1, y1 + h, color);
}
return (result);
}
int vlineRGBA(SDL_Surface * dst, Sint16 x, Sint16 y1, Sint16 y2, Uint8 r, Uint8 g, Uint8 b, Uint8 a)
{
/*
* Draw
*/
return (vlineColor(dst, x, y1, y2, ((Uint32) r << 24) | ((Uint32) g << 16) | ((Uint32) b << 8) | (Uint32) a));
}
/* ----- Rectangle */
int rectangleColor(SDL_Surface * dst, Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Uint32 color)
{
int result;
Sint16 w, h, xtmp, ytmp;
/*
* Swap x1, x2 if required
*/
if (x1 > x2) {
xtmp = x1;
x1 = x2;
x2 = xtmp;
}
/*
* Swap y1, y2 if required
*/
if (y1 > y2) {
ytmp = y1;
y1 = y2;
y2 = ytmp;
}
/*
* Calculate width&height
*/
w = x2 - x1;
h = y2 - y1;
/*
* Sanity check
*/
if ((w < 0) || (h < 0)) {
return (0);
}
/*
* Test for special cases of straight lines or single point
*/
if (x1 == x2) {
if (y1 == y2) {
return (pixelColor(dst, x1, y1, color));
} else {
return (vlineColor(dst, x1, y1, y2, color));
}
} else {
if (y1 == y2) {
return (hlineColor(dst, x1, x2, y1, color));
}
}
/*
* Draw rectangle
*/
result = 0;
result |= hlineColor(dst, x1, x2, y1, color);
result |= hlineColor(dst, x1, x2, y2, color);
y1 += 1;
y2 -= 1;
if (y1<=y2) {
result |= vlineColor(dst, x1, y1, y2, color);
result |= vlineColor(dst, x2, y1, y2, color);
}
return (result);
}
int rectangleRGBA(SDL_Surface * dst, Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Uint8 r, Uint8 g, Uint8 b, Uint8 a)
{
/*
* Draw
*/
return (rectangleColor
(dst, x1, y1, x2, y2, ((Uint32) r << 24) | ((Uint32) g << 16) | ((Uint32) b << 8) | (Uint32) a));
}
/* --------- Clipping routines for line */
/* Clipping based heavily on code from */
/* http://www.ncsa.uiuc.edu/Vis/Graphics/src/clipCohSuth.c */
#define CLIP_LEFT_EDGE 0x1
#define CLIP_RIGHT_EDGE 0x2
#define CLIP_BOTTOM_EDGE 0x4
#define CLIP_TOP_EDGE 0x8
#define CLIP_INSIDE(a) (!a)
#define CLIP_REJECT(a,b) (a&b)
#define CLIP_ACCEPT(a,b) (!(a|b))
static int clipEncode(Sint16 x, Sint16 y, Sint16 left, Sint16 top, Sint16 right, Sint16 bottom)
{
int code = 0;
if (x < left) {
code |= CLIP_LEFT_EDGE;
} else if (x > right) {
code |= CLIP_RIGHT_EDGE;
}
if (y < top) {
code |= CLIP_TOP_EDGE;
} else if (y > bottom) {
code |= CLIP_BOTTOM_EDGE;
}
return code;
}
static int clipLine(SDL_Surface * dst, Sint16 * x1, Sint16 * y1, Sint16 * x2, Sint16 * y2)
{
Sint16 left, right, top, bottom;
int code1, code2;
int draw = 0;
Sint16 swaptmp;
float m;
/*
* Get clipping boundary
*/
left = dst->clip_rect.x;
right = dst->clip_rect.x + dst->clip_rect.w - 1;
top = dst->clip_rect.y;
bottom = dst->clip_rect.y + dst->clip_rect.h - 1;
while (1) {
code1 = clipEncode(*x1, *y1, left, top, right, bottom);
code2 = clipEncode(*x2, *y2, left, top, right, bottom);
if (CLIP_ACCEPT(code1, code2)) {
draw = 1;
break;
} else if (CLIP_REJECT(code1, code2))
break;
else {
if (CLIP_INSIDE(code1)) {
swaptmp = *x2;
*x2 = *x1;
*x1 = swaptmp;
swaptmp = *y2;
*y2 = *y1;
*y1 = swaptmp;
swaptmp = code2;
code2 = code1;
code1 = swaptmp;
}
if (*x2 != *x1) {
m = (*y2 - *y1) / (float) (*x2 - *x1);
} else {
m = 1.0f;
}
if (code1 & CLIP_LEFT_EDGE) {
*y1 += (Sint16) ((left - *x1) * m);
*x1 = left;
} else if (code1 & CLIP_RIGHT_EDGE) {
*y1 += (Sint16) ((right - *x1) * m);
*x1 = right;
} else if (code1 & CLIP_BOTTOM_EDGE) {
if (*x2 != *x1) {
*x1 += (Sint16) ((bottom - *y1) / m);
}
*y1 = bottom;
} else if (code1 & CLIP_TOP_EDGE) {
if (*x2 != *x1) {
*x1 += (Sint16) ((top - *y1) / m);
}
*y1 = top;
}
}
}
return draw;
}
/* ----- Filled rectangle (Box) */
int boxColor(SDL_Surface * dst, Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Uint32 color)
{
Sint16 left, right, top, bottom;
Uint8 *pixel, *pixellast;
int x, dx;
int dy;
int pixx, pixy;
Sint16 w, h, tmp;
int result;
Uint8 *colorptr;
/*
* Get clipping boundary
*/
left = dst->clip_rect.x;
right = dst->clip_rect.x + dst->clip_rect.w - 1;
top = dst->clip_rect.y;
bottom = dst->clip_rect.y + dst->clip_rect.h - 1;
/* Check visibility */
if ((x1<left) && (x2<left)) {
return(0);
}
if ((x1>right) && (x2>right)) {
return(0);
}
if ((y1<top) && (y2<top)) {
return(0);
}
if ((y1>bottom) && (y2>bottom)) {
return(0);
}
/* Clip all points */
if (x1<left) {
x1=left;
} else if (x1>right) {
x1=right;
}
if (x2<left) {
x2=left;
} else if (x2>right) {
x2=right;
}
if (y1<top) {
y1=top;
} else if (y1>bottom) {
y1=bottom;
}
if (y2<top) {
y2=top;
} else if (y2>bottom) {
y2=bottom;
}
/*
* Order coordinates
*/
if (x1 > x2) {
tmp = x1;
x1 = x2;
x2 = tmp;
}
if (y1 > y2) {
tmp = y1;
y1 = y2;
y2 = tmp;
}
/*
* Test for special cases of straight line or single point
*/
if (x1 == x2) {
if (y1 == y2) {
return (pixelColor(dst, x1, y1, color));
} else {
return (vlineColor(dst, x1, y1, y2, color));
}
}
if (y1 == y2) {
return (hlineColor(dst, x1, x2, y1, color));
}
/*
* Calculate width&height
*/
w = x2 - x1;
h = y2 - y1;
/*
* Alpha check
*/
if ((color & 255) == 255) {
/*
* No alpha-blending required
*/
/*
* Setup color
*/
colorptr = (Uint8 *) & color;
if (SDL_BYTEORDER == SDL_BIG_ENDIAN) {
color = SDL_MapRGBA(dst->format, colorptr[0], colorptr[1], colorptr[2], colorptr[3]);
} else {
color = SDL_MapRGBA(dst->format, colorptr[3], colorptr[2], colorptr[1], colorptr[0]);
}
/*
* Lock surface
*/
SDL_LockSurface(dst);
/*
* More variable setup
*/
dx = w;
dy = h;
pixx = dst->format->BytesPerPixel;
pixy = dst->pitch;
pixel = ((Uint8 *) dst->pixels) + pixx * (int) x1 + pixy * (int) y1;
pixellast = pixel + pixx * dx + pixy * dy;
dx++;
/*
* Draw
*/
switch (dst->format->BytesPerPixel) {
case 1:
for (; pixel <= pixellast; pixel += pixy) {
memset(pixel, (Uint8) color, dx);
}
break;
case 2:
pixy -= (pixx * dx);
for (; pixel <= pixellast; pixel += pixy) {
for (x = 0; x < dx; x++) {
*(Uint16 *) pixel = color;
pixel += pixx;
}
}
break;
case 3:
pixy -= (pixx * dx);
for (; pixel <= pixellast; pixel += pixy) {
for (x = 0; x < dx; x++) {
if (SDL_BYTEORDER == SDL_BIG_ENDIAN) {
pixel[0] = (color >> 16) & 0xff;
pixel[1] = (color >> 8) & 0xff;
pixel[2] = color & 0xff;
} else {
pixel[0] = color & 0xff;
pixel[1] = (color >> 8) & 0xff;
pixel[2] = (color >> 16) & 0xff;
}
pixel += pixx;
}
}
break;
default: /* case 4 */
pixy -= (pixx * dx);
for (; pixel <= pixellast; pixel += pixy) {
for (x = 0; x < dx; x++) {
*(Uint32 *) pixel = color;
pixel += pixx;
}
}
break;
}
/*
* Unlock surface
*/
SDL_UnlockSurface(dst);
result = 0;
} else {
result = filledRectAlpha(dst, x1, y1, x1 + w, y1 + h, color);
}
return (result);
}
int boxRGBA(SDL_Surface * dst, Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Uint8 r, Uint8 g, Uint8 b, Uint8 a)
{
/*
* Draw
*/
return (boxColor(dst, x1, y1, x2, y2, ((Uint32) r << 24) | ((Uint32) g << 16) | ((Uint32) b << 8) | (Uint32) a));
}
/* ----- Line */
/* Non-alpha line drawing code adapted from routine */
/* by Pete Shinners, [email protected] */
/* Originally from pygame, http://pygame.seul.org */
#define ABS(a) (((a)<0) ? -(a) : (a))
int lineColor(SDL_Surface * dst, Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Uint32 color)
{
int pixx, pixy;
int x, y;
int dx, dy;
int ax, ay;
int sx, sy;
int swaptmp;
Uint8 *pixel;
Uint8 *colorptr;
/*
* Clip line and test if we have to draw
*/
if (!(clipLine(dst, &x1, &y1, &x2, &y2))) {
return (0);
}
/*
* Test for special cases of straight lines or single point
*/
if (x1 == x2) {
if (y1 < y2) {
return (vlineColor(dst, x1, y1, y2, color));
} else if (y1 > y2) {
return (vlineColor(dst, x1, y2, y1, color));
} else {
return (pixelColor(dst, x1, y1, color));
}
}
if (y1 == y2) {
if (x1 < x2) {
return (hlineColor(dst, x1, x2, y1, color));
} else if (x1 > x2) {
return (hlineColor(dst, x2, x1, y1, color));
}
}
/*
* Variable setup
*/
dx = x2 - x1;
dy = y2 - y1;
sx = (dx >= 0) ? 1 : -1;
sy = (dy >= 0) ? 1 : -1;
/* Lock surface */
if (SDL_MUSTLOCK(dst)) {
if (SDL_LockSurface(dst) < 0) {
return (-1);
}
}
/*
* Check for alpha blending
*/
if ((color & 255) == 255) {
/*
* No alpha blending - use fast pixel routines
*/
/*
* Setup color
*/
colorptr = (Uint8 *) & color;
if (SDL_BYTEORDER == SDL_BIG_ENDIAN) {
color = SDL_MapRGBA(dst->format, colorptr[0], colorptr[1], colorptr[2], colorptr[3]);
} else {
color = SDL_MapRGBA(dst->format, colorptr[3], colorptr[2], colorptr[1], colorptr[0]);
}
/*
* More variable setup
*/
dx = sx * dx + 1;
dy = sy * dy + 1;
pixx = dst->format->BytesPerPixel;
pixy = dst->pitch;
pixel = ((Uint8 *) dst->pixels) + pixx * (int) x1 + pixy * (int) y1;
pixx *= sx;
pixy *= sy;
if (dx < dy) {
swaptmp = dx;
dx = dy;
dy = swaptmp;
swaptmp = pixx;
pixx = pixy;
pixy = swaptmp;
}
/*
* Draw
*/
x = 0;
y = 0;
switch (dst->format->BytesPerPixel) {
case 1:
for (; x < dx; x++, pixel += pixx) {
*pixel = color;
y += dy;
if (y >= dx) {
y -= dx;
pixel += pixy;
}
}
break;
case 2:
for (; x < dx; x++, pixel += pixx) {
*(Uint16 *) pixel = color;
y += dy;
if (y >= dx) {
y -= dx;
pixel += pixy;
}
}
break;
case 3:
for (; x < dx; x++, pixel += pixx) {
if (SDL_BYTEORDER == SDL_BIG_ENDIAN) {
pixel[0] = (color >> 16) & 0xff;
pixel[1] = (color >> 8) & 0xff;
pixel[2] = color & 0xff;
} else {
pixel[0] = color & 0xff;
pixel[1] = (color >> 8) & 0xff;
pixel[2] = (color >> 16) & 0xff;
}
y += dy;
if (y >= dx) {
y -= dx;
pixel += pixy;
}
}
break;
default: /* case 4 */
for (; x < dx; x++, pixel += pixx) {
*(Uint32 *) pixel = color;
y += dy;
if (y >= dx) {
y -= dx;
pixel += pixy;
}
}
break;
}
} else {
/*
* Alpha blending required - use single-pixel blits
*/
ax = ABS(dx) << 1;
ay = ABS(dy) << 1;
x = x1;
y = y1;
if (ax > ay) {
int d = ay - (ax >> 1);
while (x != x2) {
pixelColorNolock (dst, x, y, color);
if (d > 0 || (d == 0 && sx == 1)) {
y += sy;
d -= ax;
}
x += sx;
d += ay;
}
} else {
int d = ax - (ay >> 1);
while (y != y2) {
pixelColorNolock (dst, x, y, color);
if (d > 0 || ((d == 0) && (sy == 1))) {
x += sx;
d -= ay;
}
y += sy;
d += ax;
}
}
pixelColorNolock (dst, x, y, color);
}
/* Unlock surface */
if (SDL_MUSTLOCK(dst)) {
SDL_UnlockSurface(dst);
}
return (0);
}
int lineRGBA(SDL_Surface * dst, Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Uint8 r, Uint8 g, Uint8 b, Uint8 a)
{
/*
* Draw
*/
return (lineColor(dst, x1, y1, x2, y2, ((Uint32) r << 24) | ((Uint32) g << 16) | ((Uint32) b << 8) | (Uint32) a));
}
/* AA Line */
#define AAlevels 256
#define AAbits 8
/*
This implementation of the Wu antialiasing code is based on Mike Abrash's
DDJ article which was reprinted as Chapter 42 of his Graphics Programming
Black Book, but has been optimized to work with SDL and utilizes 32-bit
fixed-point arithmetic. (A. Schiffler).
*/
int aalineColorInt(SDL_Surface * dst, Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Uint32 color, int draw_endpoint)
{
Sint32 xx0, yy0, xx1, yy1;
int result;
Uint32 intshift, erracc, erradj;
Uint32 erracctmp, wgt, wgtcompmask;
int dx, dy, tmp, xdir, y0p1, x0pxdir;
/*
* Clip line and test if we have to draw
*/
if (!(clipLine(dst, &x1, &y1, &x2, &y2))) {
return (0);
}
/*
* Keep on working with 32bit numbers
*/
xx0 = x1;
yy0 = y1;
xx1 = x2;
yy1 = y2;
/*
* Reorder points if required
*/
if (yy0 > yy1) {
tmp = yy0;
yy0 = yy1;
yy1 = tmp;
tmp = xx0;
xx0 = xx1;
xx1 = tmp;
}
/*
* Calculate distance
*/
dx = xx1 - xx0;
dy = yy1 - yy0;
/*
* Adjust for negative dx and set xdir
*/
if (dx >= 0) {
xdir = 1;
} else {
xdir = -1;
dx = (-dx);
}
/*
* Check for special cases
*/
if (dx == 0) {
/*
* Vertical line
*/
return (vlineColor(dst, x1, y1, y2, color));
} else if (dy == 0) {
/*
* Horizontal line
*/
return (hlineColor(dst, x1, x2, y1, color));
} else if (dx == dy) {
/*
* Diagonal line
*/
return (lineColor(dst, x1, y1, x2, y2, color));
}
/*
* Line is not horizontal, vertical or diagonal
*/
result = 0;
/*
* Zero accumulator
*/
erracc = 0;
/*
* # of bits by which to shift erracc to get intensity level
*/
intshift = 32 - AAbits;
/*
* Mask used to flip all bits in an intensity weighting
*/
wgtcompmask = AAlevels - 1;
/* Lock surface */
if (SDL_MUSTLOCK(dst)) {
if (SDL_LockSurface(dst) < 0) {
return (-1);
}
}
/*
* Draw the initial pixel in the foreground color
*/
result |= pixelColorNolock(dst, x1, y1, color);
/*
* x-major or y-major?
*/
if (dy > dx) {
/*
* y-major. Calculate 16-bit fixed point fractional part of a pixel that
* X advances every time Y advances 1 pixel, truncating the result so that
* we won't overrun the endpoint along the X axis
*/
/*
* Not-so-portable version: erradj = ((Uint64)dx << 32) / (Uint64)dy;
*/
erradj = ((dx << 16) / dy) << 16;
/*
* draw all pixels other than the first and last
*/
x0pxdir = xx0 + xdir;
while (--dy) {
erracctmp = erracc;
erracc += erradj;
if (erracc <= erracctmp) {
/*
* rollover in error accumulator, x coord advances
*/
xx0 = x0pxdir;
x0pxdir += xdir;
}
yy0++; /* y-major so always advance Y */
/*
* the AAbits most significant bits of erracc give us the intensity
* weighting for this pixel, and the complement of the weighting for
* the paired pixel.
*/
wgt = (erracc >> intshift) & 255;
result |= pixelColorWeightNolock (dst, xx0, yy0, color, 255 - wgt);
result |= pixelColorWeightNolock (dst, x0pxdir, yy0, color, wgt);
}
} else {
/*
* x-major line. Calculate 16-bit fixed-point fractional part of a pixel
* that Y advances each time X advances 1 pixel, truncating the result so
* that we won't overrun the endpoint along the X axis.
*/
/*
* Not-so-portable version: erradj = ((Uint64)dy << 32) / (Uint64)dx;
*/
erradj = ((dy << 16) / dx) << 16;
/*
* draw all pixels other than the first and last
*/
y0p1 = yy0 + 1;
while (--dx) {
erracctmp = erracc;
erracc += erradj;
if (erracc <= erracctmp) {
/*
* Accumulator turned over, advance y
*/
yy0 = y0p1;
y0p1++;
}
xx0 += xdir; /* x-major so always advance X */
/*
* the AAbits most significant bits of erracc give us the intensity
* weighting for this pixel, and the complement of the weighting for
* the paired pixel.
*/
wgt = (erracc >> intshift) & 255;
result |= pixelColorWeightNolock (dst, xx0, yy0, color, 255 - wgt);
result |= pixelColorWeightNolock (dst, xx0, y0p1, color, wgt);
}
}
/*
* Do we have to draw the endpoint
*/
if (draw_endpoint) {
/*
* Draw final pixel, always exactly intersected by the line and doesn't
* need to be weighted.
*/
result |= pixelColorNolock (dst, x2, y2, color);
}
/* Unlock surface */
if (SDL_MUSTLOCK(dst)) {
SDL_UnlockSurface(dst);
}
return (result);
}
int aalineColor(SDL_Surface * dst, Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Uint32 color)
{
return (aalineColorInt(dst, x1, y1, x2, y2, color, 1));
}
int aalineRGBA(SDL_Surface * dst, Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Uint8 r, Uint8 g, Uint8 b, Uint8 a)
{
return (aalineColorInt
(dst, x1, y1, x2, y2, ((Uint32) r << 24) | ((Uint32) g << 16) | ((Uint32) b << 8) | (Uint32) a, 1));
}
/* ----- Circle */
/* Note: Based on algorithm from sge library, modified by A. Schiffler */
/* with multiple pixel-draw removal and other minor speedup changes. */
int circleColor(SDL_Surface * dst, Sint16 x, Sint16 y, Sint16 r, Uint32 color)
{
Sint16 left, right, top, bottom;
int result;
Sint16 x1, y1, x2, y2;
Sint16 cx = 0;
Sint16 cy = r;
Sint16 ocx = (Sint16) 0xffff;
Sint16 ocy = (Sint16) 0xffff;
Sint16 df = 1 - r;
Sint16 d_e = 3;
Sint16 d_se = -2 * r + 5;
Sint16 xpcx, xmcx, xpcy, xmcy;
Sint16 ypcy, ymcy, ypcx, ymcx;
Uint8 *colorptr;
/*
* Sanity check radius
*/
if (r < 0) {
return (-1);
}
/*
* Special case for r=0 - draw a point
*/
if (r == 0) {
return (pixelColor(dst, x, y, color));
}
/*
* Get clipping boundary
*/
left = dst->clip_rect.x;
right = dst->clip_rect.x + dst->clip_rect.w - 1;
top = dst->clip_rect.y;
bottom = dst->clip_rect.y + dst->clip_rect.h - 1;
/*
* Test if bounding box of circle is visible
*/
x1 = x - r;
x2 = x + r;
y1 = y - r;
y2 = y + r;
if ((x1<left) && (x2<left)) {
return(0);
}
if ((x1>right) && (x2>right)) {
return(0);
}
if ((y1<top) && (y2<top)) {
return(0);
}
if ((y1>bottom) && (y2>bottom)) {
return(0);
}
/*
* Draw circle
*/
result = 0;
/* Lock surface */
if (SDL_MUSTLOCK(dst)) {
if (SDL_LockSurface(dst) < 0) {
return (-1);
}
}
/*
* Alpha Check
*/
if ((color & 255) == 255) {
/*
* No Alpha - direct memory writes
*/
/*
* Setup color
*/
colorptr = (Uint8 *) & color;
if (SDL_BYTEORDER == SDL_BIG_ENDIAN) {
color = SDL_MapRGBA(dst->format, colorptr[0], colorptr[1], colorptr[2], colorptr[3]);
} else {
color = SDL_MapRGBA(dst->format, colorptr[3], colorptr[2], colorptr[1], colorptr[0]);
}
/*
* Draw
*/
do {
if ((ocy != cy) || (ocx != cx)) {
xpcx = x + cx;
xmcx = x - cx;
if (cy > 0) {
ypcy = y + cy;
ymcy = y - cy;
result |= fastPixelColorNolock(dst, xmcx, ypcy, color);
result |= fastPixelColorNolock(dst, xpcx, ypcy, color);
result |= fastPixelColorNolock(dst, xmcx, ymcy, color);
result |= fastPixelColorNolock(dst, xpcx, ymcy, color);
} else {
result |= fastPixelColorNolock(dst, xmcx, y, color);
result |= fastPixelColorNolock(dst, xpcx, y, color);
}
ocy = cy;
xpcy = x + cy;
xmcy = x - cy;
if (cx > 0) {
ypcx = y + cx;
ymcx = y - cx;
result |= fastPixelColorNolock(dst, xmcy, ypcx, color);
result |= fastPixelColorNolock(dst, xpcy, ypcx, color);
result |= fastPixelColorNolock(dst, xmcy, ymcx, color);
result |= fastPixelColorNolock(dst, xpcy, ymcx, color);
} else {
result |= fastPixelColorNolock(dst, xmcy, y, color);
result |= fastPixelColorNolock(dst, xpcy, y, color);
}
ocx = cx;
}
/*
* Update
*/
if (df < 0) {
df += d_e;
d_e += 2;
d_se += 2;
} else {
df += d_se;
d_e += 2;
d_se += 4;
cy--;
}
cx++;
} while (cx <= cy);
/*
* Unlock surface
*/
SDL_UnlockSurface(dst);
} else {
/*
* Using Alpha - blended pixel blits
*/
do {
/*
* Draw
*/
if ((ocy != cy) || (ocx != cx)) {
xpcx = x + cx;
xmcx = x - cx;
if (cy > 0) {
ypcy = y + cy;
ymcy = y - cy;
result |= pixelColorNolock (dst, xmcx, ypcy, color);
result |= pixelColorNolock (dst, xpcx, ypcy, color);
result |= pixelColorNolock (dst, xmcx, ymcy, color);
result |= pixelColorNolock (dst, xpcx, ymcy, color);
} else {
result |= pixelColorNolock (dst, xmcx, y, color);
result |= pixelColorNolock (dst, xpcx, y, color);
}
ocy = cy;
xpcy = x + cy;
xmcy = x - cy;
if (cx > 0) {
ypcx = y + cx;
ymcx = y - cx;
result |= pixelColorNolock (dst, xmcy, ypcx, color);
result |= pixelColorNolock (dst, xpcy, ypcx, color);
result |= pixelColorNolock (dst, xmcy, ymcx, color);
result |= pixelColorNolock (dst, xpcy, ymcx, color);
} else {
result |= pixelColorNolock (dst, xmcy, y, color);
result |= pixelColorNolock (dst, xpcy, y, color);
}
ocx = cx;
}
/*
* Update
*/
if (df < 0) {
df += d_e;
d_e += 2;
d_se += 2;
} else {
df += d_se;
d_e += 2;
d_se += 4;
cy--;
}
cx++;
} while (cx <= cy);
} /* Alpha check */
/* Unlock surface */
if (SDL_MUSTLOCK(dst)) {
SDL_UnlockSurface(dst);
}
return (result);
}
int circleRGBA(SDL_Surface * dst, Sint16 x, Sint16 y, Sint16 rad, Uint8 r, Uint8 g, Uint8 b, Uint8 a)
{
/*
* Draw
*/
return (circleColor(dst, x, y, rad, ((Uint32) r << 24) | ((Uint32) g << 16) | ((Uint32) b << 8) | (Uint32) a));
}
/* ----- AA Circle */
/* AA circle is based on AAellipse */
#ifndef WIN32
int aacircleColor(SDL_Surface * dst, Sint16 x, Sint16 y, Sint16 r, Uint32 color)
{
return (aaellipseColor(dst, x, y, r, r, color));
}
int aacircleRGBA(SDL_Surface * dst, Sint16 x, Sint16 y, Sint16 rad, Uint8 r, Uint8 g, Uint8 b, Uint8 a)
{
/*
* Draw
*/
return (aaellipseColor
(dst, x, y, rad, rad, ((Uint32) r << 24) | ((Uint32) g << 16) | ((Uint32) b << 8) | (Uint32) a));
}
#endif
/* ----- Filled Circle */
/* Note: Based on algorithm from sge library with multiple-hline draw removal */
/* and other speedup changes. */
int filledCircleColor(SDL_Surface * dst, Sint16 x, Sint16 y, Sint16 r, Uint32 color)
{
Sint16 left, right, top, bottom;
int result;
Sint16 x1, y1, x2, y2;
Sint16 cx = 0;
Sint16 cy = r;
Sint16 ocx = (Sint16) 0xffff;
Sint16 ocy = (Sint16) 0xffff;
Sint16 df = 1 - r;
Sint16 d_e = 3;
Sint16 d_se = -2 * r + 5;
Sint16 xpcx, xmcx, xpcy, xmcy;
Sint16 ypcy, ymcy, ypcx, ymcx;
/*
* Sanity check radius
*/
if (r < 0) {
return (-1);
}
/*
* Special case for r=0 - draw a point
*/
if (r == 0) {
return (pixelColor(dst, x, y, color));
}
/*
* Get clipping boundary
*/
left = dst->clip_rect.x;
right = dst->clip_rect.x + dst->clip_rect.w - 1;
top = dst->clip_rect.y;
bottom = dst->clip_rect.y + dst->clip_rect.h - 1;
/*
* Test if bounding box of circle is visible
*/
x1 = x - r;
x2 = x + r;
y1 = y - r;
y2 = y + r;
if ((x1<left) && (x2<left)) {
return(0);
}
if ((x1>right) && (x2>right)) {
return(0);
}
if ((y1<top) && (y2<top)) {
return(0);
}
if ((y1>bottom) && (y2>bottom)) {
return(0);
}
/*
* Draw
*/
result = 0;
do {
xpcx = x + cx;
xmcx = x - cx;
xpcy = x + cy;
xmcy = x - cy;
if (ocy != cy) {
if (cy > 0) {
ypcy = y + cy;
ymcy = y - cy;
result |= hlineColor(dst, xmcx, xpcx, ypcy, color);
result |= hlineColor(dst, xmcx, xpcx, ymcy, color);
} else {
result |= hlineColor(dst, xmcx, xpcx, y, color);
}
ocy = cy;
}
if (ocx != cx) {
if (cx != cy) {
if (cx > 0) {
ypcx = y + cx;
ymcx = y - cx;
result |= hlineColor(dst, xmcy, xpcy, ymcx, color);
result |= hlineColor(dst, xmcy, xpcy, ypcx, color);
} else {
result |= hlineColor(dst, xmcy, xpcy, y, color);
}
}
ocx = cx;
}
/*
* Update
*/
if (df < 0) {
df += d_e;
d_e += 2;
d_se += 2;
} else {
df += d_se;
d_e += 2;
d_se += 4;
cy--;
}
cx++;
} while (cx <= cy);
return (result);
}
int filledCircleRGBA(SDL_Surface * dst, Sint16 x, Sint16 y, Sint16 rad, Uint8 r, Uint8 g, Uint8 b, Uint8 a)
{
/*
* Draw
*/
return (filledCircleColor
(dst, x, y, rad, ((Uint32) r << 24) | ((Uint32) g << 16) | ((Uint32) b << 8) | (Uint32) a));
}
/* ----- Ellipse */
/* Note: Based on algorithm from sge library with multiple-hline draw removal */
/* and other speedup changes. */
int ellipseColor(SDL_Surface * dst, Sint16 x, Sint16 y, Sint16 rx, Sint16 ry, Uint32 color)
{
Sint16 left, right, top, bottom;
int result;
Sint16 x1, y1, x2, y2;
int ix, iy;
int h, i, j, k;
int oh, oi, oj, ok;
int xmh, xph, ypk, ymk;
int xmi, xpi, ymj, ypj;
int xmj, xpj, ymi, ypi;
int xmk, xpk, ymh, yph;
Uint8 *colorptr;
/*
* Sanity check radii
*/
if ((rx < 0) || (ry < 0)) {
return (-1);
}
/*
* Special case for rx=0 - draw a vline
*/
if (rx == 0) {
return (vlineColor(dst, x, y - ry, y + ry, color));
}
/*
* Special case for ry=0 - draw a hline
*/
if (ry == 0) {
return (hlineColor(dst, x - rx, x + rx, y, color));
}
/*
* Get clipping boundary
*/
left = dst->clip_rect.x;
right = dst->clip_rect.x + dst->clip_rect.w - 1;
top = dst->clip_rect.y;
bottom = dst->clip_rect.y + dst->clip_rect.h - 1;
/*
* Test if bounding box of ellipse is visible
*/
x1 = x - rx;
x2 = x + rx;
y1 = y - ry;
y2 = y + ry;
if ((x1<left) && (x2<left)) {
return(0);
}
if ((x1>right) && (x2>right)) {
return(0);
}
if ((y1<top) && (y2<top)) {
return(0);
}
if ((y1>bottom) && (y2>bottom)) {
return(0);
}
/*
* Init vars
*/
oh = oi = oj = ok = 0xFFFF;
/*
* Draw
*/
result = 0;
/* Lock surface */
if (SDL_MUSTLOCK(dst)) {
if (SDL_LockSurface(dst) < 0) {
return (-1);
}
}
/*
* Check alpha
*/
if ((color & 255) == 255) {
/*
* No Alpha - direct memory writes
*/
/*
* Setup color
*/
colorptr = (Uint8 *) & color;
if (SDL_BYTEORDER == SDL_BIG_ENDIAN) {
color = SDL_MapRGBA(dst->format, colorptr[0], colorptr[1], colorptr[2], colorptr[3]);
} else {
color = SDL_MapRGBA(dst->format, colorptr[3], colorptr[2], colorptr[1], colorptr[0]);
}
if (rx > ry) {
ix = 0;
iy = rx * 64;
do {
h = (ix + 32) >> 6;
i = (iy + 32) >> 6;
j = (h * ry) / rx;
k = (i * ry) / rx;
if (((ok != k) && (oj != k)) || ((oj != j) && (ok != j)) || (k != j)) {
xph = x + h;
xmh = x - h;
if (k > 0) {
ypk = y + k;
ymk = y - k;
result |= fastPixelColorNolock(dst, xmh, ypk, color);
result |= fastPixelColorNolock(dst, xph, ypk, color);
result |= fastPixelColorNolock(dst, xmh, ymk, color);
result |= fastPixelColorNolock(dst, xph, ymk, color);
} else {
result |= fastPixelColorNolock(dst, xmh, y, color);
result |= fastPixelColorNolock(dst, xph, y, color);
}
ok = k;
xpi = x + i;
xmi = x - i;
if (j > 0) {
ypj = y + j;
ymj = y - j;
result |= fastPixelColorNolock(dst, xmi, ypj, color);
result |= fastPixelColorNolock(dst, xpi, ypj, color);
result |= fastPixelColorNolock(dst, xmi, ymj, color);
result |= fastPixelColorNolock(dst, xpi, ymj, color);
} else {
result |= fastPixelColorNolock(dst, xmi, y, color);
result |= fastPixelColorNolock(dst, xpi, y, color);
}
oj = j;
}
ix = ix + iy / rx;
iy = iy - ix / rx;
} while (i > h);
} else {
ix = 0;
iy = ry * 64;
do {
h = (ix + 32) >> 6;
i = (iy + 32) >> 6;
j = (h * rx) / ry;
k = (i * rx) / ry;
if (((oi != i) && (oh != i)) || ((oh != h) && (oi != h) && (i != h))) {
xmj = x - j;
xpj = x + j;
if (i > 0) {
ypi = y + i;
ymi = y - i;
result |= fastPixelColorNolock(dst, xmj, ypi, color);
result |= fastPixelColorNolock(dst, xpj, ypi, color);
result |= fastPixelColorNolock(dst, xmj, ymi, color);
result |= fastPixelColorNolock(dst, xpj, ymi, color);
} else {
result |= fastPixelColorNolock(dst, xmj, y, color);
result |= fastPixelColorNolock(dst, xpj, y, color);
}
oi = i;
xmk = x - k;
xpk = x + k;
if (h > 0) {
yph = y + h;
ymh = y - h;
result |= fastPixelColorNolock(dst, xmk, yph, color);
result |= fastPixelColorNolock(dst, xpk, yph, color);
result |= fastPixelColorNolock(dst, xmk, ymh, color);
result |= fastPixelColorNolock(dst, xpk, ymh, color);
} else {
result |= fastPixelColorNolock(dst, xmk, y, color);
result |= fastPixelColorNolock(dst, xpk, y, color);
}
oh = h;
}
ix = ix + iy / ry;
iy = iy - ix / ry;
} while (i > h);
}
} else {
if (rx > ry) {
ix = 0;
iy = rx * 64;
do {
h = (ix + 32) >> 6;
i = (iy + 32) >> 6;
j = (h * ry) / rx;
k = (i * ry) / rx;
if (((ok != k) && (oj != k)) || ((oj != j) && (ok != j)) || (k != j)) {
xph = x + h;
xmh = x - h;
if (k > 0) {
ypk = y + k;
ymk = y - k;
result |= pixelColorNolock (dst, xmh, ypk, color);
result |= pixelColorNolock (dst, xph, ypk, color);
result |= pixelColorNolock (dst, xmh, ymk, color);
result |= pixelColorNolock (dst, xph, ymk, color);
} else {
result |= pixelColorNolock (dst, xmh, y, color);
result |= pixelColorNolock (dst, xph, y, color);
}
ok = k;
xpi = x + i;
xmi = x - i;
if (j > 0) {
ypj = y + j;
ymj = y - j;
result |= pixelColorNolock (dst, xmi, ypj, color);
result |= pixelColorNolock (dst, xpi, ypj, color);
result |= pixelColorNolock (dst, xmi, ymj, color);
result |= pixelColor(dst, xpi, ymj, color);
} else {
result |= pixelColorNolock (dst, xmi, y, color);
result |= pixelColorNolock (dst, xpi, y, color);
}
oj = j;
}
ix = ix + iy / rx;
iy = iy - ix / rx;
} while (i > h);
} else {
ix = 0;
iy = ry * 64;
do {
h = (ix + 32) >> 6;
i = (iy + 32) >> 6;
j = (h * rx) / ry;
k = (i * rx) / ry;
if (((oi != i) && (oh != i)) || ((oh != h) && (oi != h) && (i != h))) {
xmj = x - j;
xpj = x + j;
if (i > 0) {
ypi = y + i;
ymi = y - i;
result |= pixelColorNolock (dst, xmj, ypi, color);
result |= pixelColorNolock (dst, xpj, ypi, color);
result |= pixelColorNolock (dst, xmj, ymi, color);
result |= pixelColorNolock (dst, xpj, ymi, color);
} else {
result |= pixelColorNolock (dst, xmj, y, color);
result |= pixelColorNolock (dst, xpj, y, color);
}
oi = i;
xmk = x - k;
xpk = x + k;
if (h > 0) {
yph = y + h;
ymh = y - h;
result |= pixelColorNolock (dst, xmk, yph, color);
result |= pixelColorNolock (dst, xpk, yph, color);
result |= pixelColorNolock (dst, xmk, ymh, color);
result |= pixelColorNolock (dst, xpk, ymh, color);
} else {
result |= pixelColorNolock (dst, xmk, y, color);
result |= pixelColorNolock (dst, xpk, y, color);
}
oh = h;
}
ix = ix + iy / ry;
iy = iy - ix / ry;
} while (i > h);
}
} /* Alpha check */
/* Unlock surface */
if (SDL_MUSTLOCK(dst)) {
SDL_UnlockSurface(dst);
}
return (result);
}
int ellipseRGBA(SDL_Surface * dst, Sint16 x, Sint16 y, Sint16 rx, Sint16 ry, Uint8 r, Uint8 g, Uint8 b, Uint8 a)
{
/*
* Draw
*/
return (ellipseColor(dst, x, y, rx, ry, ((Uint32) r << 24) | ((Uint32) g << 16) | ((Uint32) b << 8) | (Uint32) a));
}
/* ----- AA Ellipse */
/* Based on code from Anders Lindstroem, based on code from SGE, based on code from TwinLib */
#ifndef WIN32
int aaellipseColor(SDL_Surface * dst, Sint16 xc, Sint16 yc, Sint16 rx, Sint16 ry, Uint32 color)
{
Sint16 left, right, top, bottom;
Sint16 x1,y1,x2,y2;
int i;
int a2, b2, ds, dt, dxt, t, s, d;
Sint16 x, y, xs, ys, dyt, xx, yy, xc2, yc2;
float cp;
Uint8 weight, iweight;
int result;
/*
* Sanity check radii
*/
if ((rx < 0) || (ry < 0)) {
return (-1);
}
/*
* Special case for rx=0 - draw a vline
*/
if (rx == 0) {
return (vlineColor(dst, xc, yc - ry, yc + ry, color));
}
/*
* Special case for ry=0 - draw a hline
*/
if (ry == 0) {
return (hlineColor(dst, xc - rx, xc + rx, yc, color));
}
/*
* Get clipping boundary
*/
left = dst->clip_rect.x;
right = dst->clip_rect.x + dst->clip_rect.w - 1;
top = dst->clip_rect.y;
bottom = dst->clip_rect.y + dst->clip_rect.h - 1;
/*
* Test if bounding box of ellipse is visible
*/
x1 = xc - rx;
x2 = xc + rx;
y1 = yc - ry;
y2 = yc + ry;
if ((x1<left) && (x2<left)) {
return(0);
}
if ((x1>right) && (x2>right)) {
return(0);
}
if ((y1<top) && (y2<top)) {
return(0);
}
if ((y1>bottom) && (y2>bottom)) {
return(0);
}
/* Variable setup */
a2 = rx * rx;
b2 = ry * ry;
ds = 2 * a2;
dt = 2 * b2;
xc2 = 2 * xc;
yc2 = 2 * yc;
dxt = (int) (a2 / sqrt(a2 + b2));
t = 0;
s = -2 * a2 * ry;
d = 0;
x = xc;
y = yc - ry;
/* Draw */
result = 0;
/* Lock surface */
if (SDL_MUSTLOCK(dst)) {
if (SDL_LockSurface(dst) < 0) {
return (-1);
}
}
/* "End points" */
result |= pixelColorNolock(dst, x, y, color);
result |= pixelColorNolock(dst, xc2 - x, y, color);
result |= pixelColorNolock(dst, x, yc2 - y, color);
result |= pixelColorNolock(dst, xc2 - x, yc2 - y, color);
for (i = 1; i <= dxt; i++) {
x--;
d += t - b2;
if (d >= 0)
ys = y - 1;
else if ((d - s - a2) > 0) {
if ((2 * d - s - a2) >= 0)
ys = y + 1;
else {
ys = y;
y++;
d -= s + a2;
s += ds;
}
} else {
y++;
ys = y + 1;
d -= s + a2;
s += ds;
}
t -= dt;
/* Calculate alpha */
if (s != 0.0) {
cp = (float) abs(d) / (float) abs(s);
if (cp > 1.0) {
cp = 1.0;
}
} else {
cp = 1.0;
}
/* Calculate weights */
weight = (Uint8) (cp * 255);
iweight = 255 - weight;
/* Upper half */
xx = xc2 - x;
result |= pixelColorWeightNolock(dst, x, y, color, iweight);
result |= pixelColorWeightNolock(dst, xx, y, color, iweight);
result |= pixelColorWeightNolock(dst, x, ys, color, weight);
result |= pixelColorWeightNolock(dst, xx, ys, color, weight);
/* Lower half */
yy = yc2 - y;
result |= pixelColorWeightNolock(dst, x, yy, color, iweight);
result |= pixelColorWeightNolock(dst, xx, yy, color, iweight);
yy = yc2 - ys;
result |= pixelColorWeightNolock(dst, x, yy, color, weight);
result |= pixelColorWeightNolock(dst, xx, yy, color, weight);
}
dyt = abs(y - yc);
for (i = 1; i <= dyt; i++) {
y++;
d -= s + a2;
if (d <= 0)
xs = x + 1;
else if ((d + t - b2) < 0) {
if ((2 * d + t - b2) <= 0)
xs = x - 1;
else {
xs = x;
x--;
d += t - b2;
t -= dt;
}
} else {
x--;
xs = x - 1;
d += t - b2;
t -= dt;
}
s += ds;
/* Calculate alpha */
if (t != 0.0) {
cp = (float) abs(d) / (float) abs(t);
if (cp > 1.0) {
cp = 1.0;
}
} else {
cp = 1.0;
}
/* Calculate weight */
weight = (Uint8) (cp * 255);
iweight = 255 - weight;
/* Left half */
xx = xc2 - x;
yy = yc2 - y;
result |= pixelColorWeightNolock(dst, x, y, color, iweight);
result |= pixelColorWeightNolock(dst, xx, y, color, iweight);
result |= pixelColorWeightNolock(dst, x, yy, color, iweight);
result |= pixelColorWeightNolock(dst, xx, yy, color, iweight);
/* Right half */
xx = 2 * xc - xs;
result |= pixelColorWeightNolock(dst, xs, y, color, weight);
result |= pixelColorWeightNolock(dst, xx, y, color, weight);
result |= pixelColorWeightNolock(dst, xs, yy, color, weight);
result |= pixelColorWeightNolock(dst, xx, yy, color, weight);
}
/* Unlock surface */
if (SDL_MUSTLOCK(dst)) {
SDL_UnlockSurface(dst);
}
return (result);
}
int aaellipseRGBA(SDL_Surface * dst, Sint16 x, Sint16 y, Sint16 rx, Sint16 ry, Uint8 r, Uint8 g, Uint8 b, Uint8 a)
{
/*
* Draw
*/
return (aaellipseColor
(dst, x, y, rx, ry, ((Uint32) r << 24) | ((Uint32) g << 16) | ((Uint32) b << 8) | (Uint32) a));
}
#endif
/* ---- Filled Ellipse */
/* Note: */
/* Based on algorithm from sge library with multiple-hline draw removal */
/* and other speedup changes. */
int filledEllipseColor(SDL_Surface * dst, Sint16 x, Sint16 y, Sint16 rx, Sint16 ry, Uint32 color)
{
Sint16 left, right, top, bottom;
int result;
Sint16 x1, y1, x2, y2;
int ix, iy;
int h, i, j, k;
int oh, oi, oj, ok;
int xmh, xph;
int xmi, xpi;
int xmj, xpj;
int xmk, xpk;
/*
* Sanity check radii
*/
if ((rx < 0) || (ry < 0)) {
return (-1);
}
/*
* Special case for rx=0 - draw a vline
*/
if (rx == 0) {
return (vlineColor(dst, x, y - ry, y + ry, color));
}
/*
* Special case for ry=0 - draw a hline
*/
if (ry == 0) {
return (hlineColor(dst, x - rx, x + rx, y, color));
}
/*
* Get clipping boundary
*/
left = dst->clip_rect.x;
right = dst->clip_rect.x + dst->clip_rect.w - 1;
top = dst->clip_rect.y;
bottom = dst->clip_rect.y + dst->clip_rect.h - 1;
/*
* Test if bounding box of ellipse is visible
*/
x1 = x - rx;
x2 = x + rx;
y1 = y - ry;
y2 = y + ry;
if ((x1<left) && (x2<left)) {
return(0);
}
if ((x1>right) && (x2>right)) {
return(0);
}
if ((y1<top) && (y2<top)) {
return(0);
}
if ((y1>bottom) && (y2>bottom)) {
return(0);
}
/*
* Init vars
*/
oh = oi = oj = ok = 0xFFFF;
/*
* Draw
*/
result = 0;
if (rx > ry) {
ix = 0;
iy = rx * 64;
do {
h = (ix + 32) >> 6;
i = (iy + 32) >> 6;
j = (h * ry) / rx;
k = (i * ry) / rx;
if ((ok != k) && (oj != k)) {
xph = x + h;
xmh = x - h;
if (k > 0) {
result |= hlineColor(dst, xmh, xph, y + k, color);
result |= hlineColor(dst, xmh, xph, y - k, color);
} else {
result |= hlineColor(dst, xmh, xph, y, color);
}
ok = k;
}
if ((oj != j) && (ok != j) && (k != j)) {
xmi = x - i;
xpi = x + i;
if (j > 0) {
result |= hlineColor(dst, xmi, xpi, y + j, color);
result |= hlineColor(dst, xmi, xpi, y - j, color);
} else {
result |= hlineColor(dst, xmi, xpi, y, color);
}
oj = j;
}
ix = ix + iy / rx;
iy = iy - ix / rx;
} while (i > h);
} else {
ix = 0;
iy = ry * 64;
do {
h = (ix + 32) >> 6;
i = (iy + 32) >> 6;
j = (h * rx) / ry;
k = (i * rx) / ry;
if ((oi != i) && (oh != i)) {
xmj = x - j;
xpj = x + j;
if (i > 0) {
result |= hlineColor(dst, xmj, xpj, y + i, color);
result |= hlineColor(dst, xmj, xpj, y - i, color);
} else {
result |= hlineColor(dst, xmj, xpj, y, color);
}
oi = i;
}
if ((oh != h) && (oi != h) && (i != h)) {
xmk = x - k;
xpk = x + k;
if (h > 0) {
result |= hlineColor(dst, xmk, xpk, y + h, color);
result |= hlineColor(dst, xmk, xpk, y - h, color);
} else {
result |= hlineColor(dst, xmk, xpk, y, color);
}
oh = h;
}
ix = ix + iy / ry;
iy = iy - ix / ry;
} while (i > h);
}
return (result);
}
int filledEllipseRGBA(SDL_Surface * dst, Sint16 x, Sint16 y, Sint16 rx, Sint16 ry, Uint8 r, Uint8 g, Uint8 b, Uint8 a)
{
/*
* Draw
*/
return (filledEllipseColor
(dst, x, y, rx, ry, ((Uint32) r << 24) | ((Uint32) g << 16) | ((Uint32) b << 8) | (Uint32) a));
}
/* ----- filled pie */
/* Low-speed float pie-calc implementation by drawing polygons/lines. */
int doPieColor(SDL_Surface * dst, Sint16 x, Sint16 y, Sint16 rad, Sint16 start, Sint16 end, Uint32 color, Uint8 filled)
{
Sint16 left, right, top, bottom;
Sint16 x1, y1, x2, y2;
int result;
double angle, start_angle, end_angle;
double deltaAngle;
double dr;
int posX, posY;
int numpoints, i;
Sint16 *vx, *vy;
/*
* Sanity check radii
*/
if (rad < 0) {
return (-1);
}
/*
* Fixup angles
*/
start = start % 360;
end = end % 360;
/*
* Special case for rad=0 - draw a point
*/
if (rad == 0) {
return (pixelColor(dst, x, y, color));
}
/*
* Get clipping boundary
*/
left = dst->clip_rect.x;
right = dst->clip_rect.x + dst->clip_rect.w - 1;
top = dst->clip_rect.y;
bottom = dst->clip_rect.y + dst->clip_rect.h - 1;
/*
* Test if bounding box of pie's circle is visible
*/
x1 = x - rad;
x2 = x + rad;
y1 = y - rad;
y2 = y + rad;
if ((x1<left) && (x2<left)) {
return(0);
}
if ((x1>right) && (x2>right)) {
return(0);
}
if ((y1<top) && (y2<top)) {
return(0);
}
if ((y1>bottom) && (y2>bottom)) {
return(0);
}
/*
* Variable setup
*/
dr = (double) rad;
deltaAngle = 3.0 / dr;
start_angle = (double) start *(2.0 * M_PI / 360.0);
end_angle = (double) end *(2.0 * M_PI / 360.0);
if (start > end) {
end_angle += (2.0 * M_PI);
}
/* Count points (rather than calculate it) */
numpoints = 1;
angle = start_angle;
while (angle <= end_angle) {
angle += deltaAngle;
numpoints++;
}
/* Check size of array */
if (numpoints == 1) {
return (pixelColor(dst, x, y, color));
} else if (numpoints == 2) {
posX = x + (int) (dr * cos(start_angle));
posY = y + (int) (dr * sin(start_angle));
return (lineColor(dst, x, y, posX, posY, color));
}
/* Allocate vertex array */
vx = vy = (Sint16 *) malloc(2 * sizeof(Uint16) * numpoints);
if (vx == NULL) {
return (-1);
}
vy += numpoints;
/* Center */
vx[0] = x;
vy[0] = y;
/* Calculate and store vertices */
i = 1;
angle = start_angle;
while (angle <= end_angle) {
vx[i] = x + (int) (dr * cos(angle));
vy[i] = y + (int) (dr * sin(angle));
angle += deltaAngle;
i++;
}
/* Draw */
if (filled) {
result = filledPolygonColor(dst, vx, vy, numpoints, color);
} else {
result = polygonColor(dst, vx, vy, numpoints, color);
}
/* Free vertex array */
free(vx);
return (result);
}
int pieColor(SDL_Surface * dst, Sint16 x, Sint16 y, Sint16 rad,
Sint16 start, Sint16 end, Uint32 color)
{
return (doPieColor(dst, x, y, rad, start, end, color, 0));
}
int pieRGBA(SDL_Surface * dst, Sint16 x, Sint16 y, Sint16 rad,
Sint16 start, Sint16 end, Uint8 r, Uint8 g, Uint8 b, Uint8 a)
{
return (doPieColor(dst, x, y, rad, start, end,
((Uint32) r << 24) | ((Uint32) g << 16) | ((Uint32) b << 8) | (Uint32) a, 0));
}
int fillepieColor(SDL_Surface * dst, Sint16 x, Sint16 y, Sint16 rad, Sint16 start, Sint16 end, Uint32 color)
{
return (doPieColor(dst, x, y, rad, start, end, color, 1));
}
int filledpieRGBA(SDL_Surface * dst, Sint16 x, Sint16 y, Sint16 rad,
Sint16 start, Sint16 end, Uint8 r, Uint8 g, Uint8 b, Uint8 a)
{
return (doPieColor(dst, x, y, rad, start, end,
((Uint32) r << 24) | ((Uint32) g << 16) | ((Uint32) b << 8) | (Uint32) a, 1));
}
/* Trigon */
int trigonColor(SDL_Surface * dst, Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Sint16 x3, Sint16 y3, Uint32 color)
{
Sint16 vx[3];
Sint16 vy[3];
vx[0]=x1;
vx[1]=x2;
vx[2]=x3;
vy[0]=y1;
vy[1]=y2;
vy[2]=y3;
return(polygonColor(dst,vx,vy,3,color));
}
int trigonRGBA(SDL_Surface * dst, Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Sint16 x3, Sint16 y3,
Uint8 r, Uint8 g, Uint8 b, Uint8 a)
{
Sint16 vx[3];
Sint16 vy[3];
vx[0]=x1;
vx[1]=x2;
vx[2]=x3;
vy[0]=y1;
vy[1]=y2;
vy[2]=y3;
return(polygonRGBA(dst,vx,vy,3,r,g,b,a));
}
/* AA-Trigon */
int aatrigonColor(SDL_Surface * dst, Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Sint16 x3, Sint16 y3, Uint32 color)
{
Sint16 vx[3];
Sint16 vy[3];
vx[0]=x1;
vx[1]=x2;
vx[2]=x3;
vy[0]=y1;
vy[1]=y2;
vy[2]=y3;
return(aapolygonColor(dst,vx,vy,3,color));
}
int aatrigonRGBA(SDL_Surface * dst, Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Sint16 x3, Sint16 y3,
Uint8 r, Uint8 g, Uint8 b, Uint8 a)
{
Sint16 vx[3];
Sint16 vy[3];
vx[0]=x1;
vx[1]=x2;
vx[2]=x3;
vy[0]=y1;
vy[1]=y2;
vy[2]=y3;
return(aapolygonRGBA(dst,vx,vy,3,r,g,b,a));
}
/* Filled Trigon */
int filledTrigonColor(SDL_Surface * dst, Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Sint16 x3, Sint16 y3, int color)
{
Sint16 vx[3];
Sint16 vy[3];
vx[0]=x1;
vx[1]=x2;
vx[2]=x3;
vy[0]=y1;
vy[1]=y2;
vy[2]=y3;
return(filledPolygonColor(dst,vx,vy,3,color));
}
int filledTrigonRGBA(SDL_Surface * dst, Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Sint16 x3, Sint16 y3,
Uint8 r, Uint8 g, Uint8 b, Uint8 a)
{
Sint16 vx[3];
Sint16 vy[3];
vx[0]=x1;
vx[1]=x2;
vx[2]=x3;
vy[0]=y1;
vy[1]=y2;
vy[2]=y3;
return(filledPolygonRGBA(dst,vx,vy,3,r,g,b,a));
}
/* ---- Polygon */
int polygonColor(SDL_Surface * dst, Sint16 * vx, Sint16 * vy, int n, Uint32 color)
{
int result;
int i;
Sint16 *x1, *y1, *x2, *y2;
/*
* Sanity check
*/
if (n < 3) {
return (-1);
}
/*
* Pointer setup
*/
x1 = x2 = vx;
y1 = y2 = vy;
x2++;
y2++;
/*
* Draw
*/
result = 0;
for (i = 1; i < n; i++) {
result |= lineColor(dst, *x1, *y1, *x2, *y2, color);
x1 = x2;
y1 = y2;
x2++;
y2++;
}
result |= lineColor(dst, *x1, *y1, *vx, *vy, color);
return (result);
}
int polygonRGBA(SDL_Surface * dst, Sint16 * vx, Sint16 * vy, int n, Uint8 r, Uint8 g, Uint8 b, Uint8 a)
{
/*
* Draw
*/
return (polygonColor(dst, vx, vy, n, ((Uint32) r << 24) | ((Uint32) g << 16) | ((Uint32) b << 8) | (Uint32) a));
}
/* ---- AA-Polygon */
int aapolygonColor(SDL_Surface * dst, Sint16 * vx, Sint16 * vy, int n, Uint32 color)
{
int result;
int i;
Sint16 *x1, *y1, *x2, *y2;
/*
* Sanity check
*/
if (n < 3) {
return (-1);
}
/*
* Pointer setup
*/
x1 = x2 = vx;
y1 = y2 = vy;
x2++;
y2++;
/*
* Draw
*/
result = 0;
for (i = 1; i < n; i++) {
result |= aalineColorInt(dst, *x1, *y1, *x2, *y2, color, 0);
x1 = x2;
y1 = y2;
x2++;
y2++;
}
result |= aalineColorInt(dst, *x1, *y1, *vx, *vy, color, 0);
return (result);
}
int aapolygonRGBA(SDL_Surface * dst, Sint16 * vx, Sint16 * vy, int n, Uint8 r, Uint8 g, Uint8 b, Uint8 a)
{
/*
* Draw
*/
return (aapolygonColor(dst, vx, vy, n, ((Uint32) r << 24) | ((Uint32) g << 16) | ((Uint32) b << 8) | (Uint32) a));
}
/* ---- Filled Polygon */
int gfxPrimitivesCompareInt(const void *a, const void *b);
static int *gfxPrimitivesPolyInts = NULL;
static int gfxPrimitivesPolyAllocated = 0;
int filledPolygonColor(SDL_Surface * dst, Sint16 * vx, Sint16 * vy, int n, int color)
{
int result;
int i;
int x, y, xa, xb;
int miny, maxy;
int x1, y1;
int x2, y2;
int ind1, ind2;
int ints;
/*
* Sanity check
*/
if (n < 3) {
return -1;
}
/*
* Allocate temp array, only grow array
*/
if (!gfxPrimitivesPolyAllocated) {
gfxPrimitivesPolyInts = (int *) malloc(sizeof(int) * n);
gfxPrimitivesPolyAllocated = n;
} else {
if (gfxPrimitivesPolyAllocated < n) {
gfxPrimitivesPolyInts = (int *) realloc(gfxPrimitivesPolyInts, sizeof(int) * n);
gfxPrimitivesPolyAllocated = n;
}
}
/*
* Determine Y maxima
*/
miny = vy[0];
maxy = vy[0];
for (i = 1; (i < n); i++) {
if (vy[i] < miny) {
miny = vy[i];
} else if (vy[i] > maxy) {
maxy = vy[i];
}
}
/*
* Draw, scanning y
*/
result = 0;
for (y = miny; (y <= maxy); y++) {
ints = 0;
for (i = 0; (i < n); i++) {
if (!i) {
ind1 = n - 1;
ind2 = 0;
} else {
ind1 = i - 1;
ind2 = i;
}
y1 = vy[ind1];
y2 = vy[ind2];
if (y1 < y2) {
x1 = vx[ind1];
x2 = vx[ind2];
} else if (y1 > y2) {
y2 = vy[ind1];
y1 = vy[ind2];
x2 = vx[ind1];
x1 = vx[ind2];
} else {
continue;
}
if ( ((y >= y1) && (y < y2)) || ((y == maxy) && (y > y1) && (y <= y2)) ) {
gfxPrimitivesPolyInts[ints++] = ((65536 * (y - y1)) / (y2 - y1)) * (x2 - x1) + (65536 * x1);
}
}
qsort(gfxPrimitivesPolyInts, ints, sizeof(int), gfxPrimitivesCompareInt);
for (i = 0; (i < ints); i += 2) {
xa = gfxPrimitivesPolyInts[i] + 1;
xa = (xa >> 16) + ((xa & 32768) >> 15);
xb = gfxPrimitivesPolyInts[i+1] - 1;
xb = (xb >> 16) + ((xb & 32768) >> 15);
result |= hlineColor(dst, xa, xb, y, color);
}
}
return (result);
}
int filledPolygonRGBA(SDL_Surface * dst, Sint16 * vx, Sint16 * vy, int n, Uint8 r, Uint8 g, Uint8 b, Uint8 a)
{
/*
* Draw
*/
return (filledPolygonColor
(dst, vx, vy, n, ((Uint32) r << 24) | ((Uint32) g << 16) | ((Uint32) b << 8) | (Uint32) a));
}
int gfxPrimitivesCompareInt(const void *a, const void *b)
{
return (*(const int *) a) - (*(const int *) b);
}
/* ---- Character */
static SDL_Surface *gfxPrimitivesFont[256];
static Uint32 gfxPrimitivesFontColor[256];
/* Default is to use 8x8 internal font */
static unsigned char *currentFontdata = gfxPrimitivesFontdata;
static int charWidth = 8, charHeight = 8;
static int charPitch = 1;
static int charSize = 8; /* character data size in bytes */
void gfxPrimitivesSetFont(unsigned char *fontdata, int cw, int ch)
{
int i;
if (fontdata) {
currentFontdata = fontdata;
charWidth = cw;
charHeight = ch;
} else {
currentFontdata = gfxPrimitivesFontdata;
charWidth = 8;
charHeight = 8;
}
charPitch = (charWidth+7)/8;
charSize = charPitch * charHeight;
for (i = 0; i < 256; i++) {
if (gfxPrimitivesFont[i]) {
SDL_FreeSurface(gfxPrimitivesFont[i]);
gfxPrimitivesFont[i] = NULL;
}
}
}
int characterColor(SDL_Surface * dst, Sint16 x, Sint16 y, char c, Uint32 color)
{
Sint16 left, right, top, bottom;
Sint16 x1, y1, x2, y2;
SDL_Rect srect;
SDL_Rect drect;
int result;
int ix, iy;
unsigned char *charpos;
unsigned char *bitpos;
Uint8 *curpos;
int forced_redraw;
Uint8 patt, mask;
/*
* Get clipping boundary
*/
left = dst->clip_rect.x;
right = dst->clip_rect.x + dst->clip_rect.w - 1;
top = dst->clip_rect.y;
bottom = dst->clip_rect.y + dst->clip_rect.h - 1;
/*
* Test if bounding box of character is visible
*/
x1 = x;
x2 = x + charWidth;
y1 = y;
y2 = y + charHeight;
if ((x1<left) && (x2<left)) {
return(0);
}
if ((x1>right) && (x2>right)) {
return(0);
}
if ((y1<top) && (y2<top)) {
return(0);
}
if ((y1>bottom) && (y2>bottom)) {
return(0);
}
/*
* Setup source rectangle
*/
srect.x = 0;
srect.y = 0;
srect.w = charWidth;
srect.h = charHeight;
/*
* Setup destination rectangle
*/
drect.x = x;
drect.y = y;
drect.w = charWidth;
drect.h = charHeight;
/*
* Create new charWidth x charHeight bitmap surface if not already present
*/
if (gfxPrimitivesFont[(unsigned char) c] == NULL) {
gfxPrimitivesFont[(unsigned char) c] =
SDL_CreateRGBSurface(SDL_SWSURFACE | SDL_HWSURFACE | SDL_SRCALPHA,
charWidth, charHeight, 32,
0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF);
/*
* Check pointer
*/
if (gfxPrimitivesFont[(unsigned char) c] == NULL) {
return (-1);
}
/*
* Definitely redraw
*/
forced_redraw = 1;
} else {
forced_redraw = 0;
}
/*
* Check if color has changed
*/
if ((gfxPrimitivesFontColor[(unsigned char) c] != color) || (forced_redraw)) {
/*
* Redraw character
*/
SDL_SetAlpha(gfxPrimitivesFont[(unsigned char) c], SDL_SRCALPHA, 255);
gfxPrimitivesFontColor[(unsigned char) c] = color;
/*
* Variable setup
*/
charpos = currentFontdata + (unsigned char) c * charSize;
curpos = (Uint8 *) gfxPrimitivesFont[(unsigned char) c]->pixels;
/*
* Drawing loop
*/
patt = 0;
for (iy = 0; iy < charHeight; iy++) {
mask = 0x00;
for (ix = 0; ix < charWidth; ix++) {
if (!(mask >>= 1)) {
patt = *charpos++;
mask = 0x80;
}
if (patt & mask)
*(Uint32 *)curpos = color;
else
*(Uint32 *)curpos = 0;
curpos += 4;;
}
}
}
/*
* Draw bitmap onto destination surface
*/
result = SDL_BlitSurface(gfxPrimitivesFont[(unsigned char) c], &srect, dst, &drect);
return (result);
}
int characterRGBA(SDL_Surface * dst, Sint16 x, Sint16 y, char c, Uint8 r, Uint8 g, Uint8 b, Uint8 a)
{
/*
* Draw
*/
return (characterColor(dst, x, y, c, ((Uint32) r << 24) | ((Uint32) g << 16) | ((Uint32) b << 8) | (Uint32) a));
}
int stringColor(SDL_Surface * dst, Sint16 x, Sint16 y, const char *c, Uint32 color)
{
int result = 0;
int curx = x;
const char *curchar = c;
while (*curchar) {
result |= characterColor(dst, curx, y, *curchar, color);
curx += charWidth;
curchar++;
}
return (result);
}
int stringRGBA(SDL_Surface * dst, Sint16 x, Sint16 y, const char *c, Uint8 r, Uint8 g, Uint8 b, Uint8 a)
{
/*
* Draw
*/
return (stringColor(dst, x, y, c, ((Uint32) r << 24) | ((Uint32) g << 16) | ((Uint32) b << 8) | (Uint32) a));
}
/* ---- Bezier curve */
/*
Calculate bezier interpolator of data array with ndata values at position 't'
*/
double evaluateBezier (double *data, int ndata, double t)
{
double mu, result;
int n,k,kn,nn,nkn;
double blend,muk,munk;
/* Sanity check bounds */
if (t<0.0) {
return(data[0]);
}
if (t>=(double)ndata) {
return(data[ndata-1]);
}
/* Adjust t to the range 0.0 to 1.0 */
mu=t/(double)ndata;
/* Calculate interpolate */
n=ndata-1;
result=0.0;
muk = 1;
munk = pow(1-mu,(double)n);
for (k=0;k<=n;k++) {
nn = n;
kn = k;
nkn = n - k;
blend = muk * munk;
muk *= mu;
munk /= (1-mu);
while (nn >= 1) {
blend *= nn;
nn--;
if (kn > 1) {
blend /= (double)kn;
kn--;
}
if (nkn > 1) {
blend /= (double)nkn;
nkn--;
}
}
result += data[k] * blend;
}
return(result);
}
int bezierColor(SDL_Surface * dst, Sint16 * vx, Sint16 * vy, int n, int s, Uint32 color)
{
return (0);
// int result;
// int i;
// double *x, *y, t, stepsize;
// Sint16 x1, y1, x2, y2;
// /*
// * Sanity check
// */
// if (n < 3) {
// return (-1);
// }
// if (s < 2) {
// return (-1);
// }
// /*
// * Variable setup
// */
// stepsize=(double)1.0/(double)s;
// /* Transfer vertices into float arrays */
// if ((x=(double *)malloc(sizeof(double)*(n+1)))==NULL) {
// return(-1);
// }
// if ((y=(double *)malloc(sizeof(double)*(n+1)))==NULL) {
// free(x);
// return(-1);
// }
// for (i=0; i<n; i++) {
// x[i]=vx[i];
// y[i]=vy[i];
// }
// x[n]=vx[0];
// y[n]=vy[0];
// /*
// * Draw
// */
// result = 0;
// t=0.0;
// x1=evaluateBezier(x,n+1,t);
// y1=evaluateBezier(y,n+1,t);
// for (i = 0; i <= (n*s); i++) {
// t += stepsize;
// x2=(Sint16)evaluateBezier(x,n,t);
// y2=(Sint16)evaluateBezier(y,n,t);
// result |= lineColor(dst, x1, y1, x2, y2, color);
// x1 = x2;
// y1 = y2;
// }
// /* Clean up temporary array */
// free(x);
// free(y);
// return (result);
}
int bezierRGBA(SDL_Surface * dst, Sint16 * vx, Sint16 * vy, int n, int s, Uint8 r, Uint8 g, Uint8 b, Uint8 a)
{
/*
* Draw
*/
return (bezierColor(dst, vx, vy, n, s, ((Uint32) r << 24) | ((Uint32) g << 16) | ((Uint32) b << 8) | (Uint32) a));
}
| [
"doomsday@b2c3ed95-53e8-0310-b220-efb193137011"
]
| [
[
[
1,
3712
]
]
]
|
57c58f174ac4f3240050dc0e18724cc468edff76 | 1d415fdfabd9db522a4c3bca4ba66877ec5b8ef4 | /gui/ttcutpreview.cpp | 182427ace988b61094b021b85621c1a0ffda2d3d | []
| no_license | panjinan333/ttcut | 61b160c0c38c2ea6c8785ba258c2fa4b6d18ae1a | fc13ec3289ae4dbce6a888d83c25fbc9c3d21c1a | refs/heads/master | 2022-03-23T21:55:36.535233 | 2010-12-23T20:58:13 | 2010-12-23T20:58:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,906 | cpp | /*----------------------------------------------------------------------------*/
/* COPYRIGHT: TriTime (c) 2003/2010 / www.tritime.org */
/*----------------------------------------------------------------------------*/
/* PROJEKT : TTCUT 2008 */
/* FILE : ttcutpreview.cpp */
/*----------------------------------------------------------------------------*/
/* AUTHOR : b. altendorf (E-Mail: [email protected]) DATE: 03/13/2005 */
/*----------------------------------------------------------------------------*/
// ----------------------------------------------------------------------------
// TTCUTPREVIEW
// ----------------------------------------------------------------------------
/*----------------------------------------------------------------------------*/
/* This program is free software; you can redistribute it and/or modify it */
/* under the terms of the GNU General Public License as published by the Free */
/* Software Foundation; */
/* either version 2 of the License, or (at your option) any later version. */
/* */
/* This program is distributed in the hope that it will be useful, but WITHOUT*/
/* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or */
/* FITNESS FOR A PARTICULAR PURPOSE. */
/* See the GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License along */
/* with this program; if not, write to the Free Software Foundation, */
/* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */
/*----------------------------------------------------------------------------*/
#include "../common/ttexception.h"
#include "ttcutpreview.h"
#include "../avstream/ttavstream.h"
#include "../data/ttavdata.h"
#include "../data/ttavlist.h"
#include "../data/ttcutpreviewtask.h"
#include "ttmplayerwidget.h"
#include "ttphononwidget.h"
#include <QApplication>
#include <QDir>
/* /////////////////////////////////////////////////////////////////////////////
* TTCutPreview constructor
*/
TTCutPreview::TTCutPreview(QWidget* parent, int prevW, int prevH)
: QDialog(parent)
{
setupUi(this);
videoPlayer = new TTPhononWidget(videoFrame);
setObjectName("TTCutPreview");
// set desired video width x height
previewWidth = prevW;
previewHeight = prevH;
cbCutPreview->setEditable( false );
cbCutPreview->setMinimumSize( 160, 20 );
cbCutPreview->setInsertPolicy( QComboBox::InsertAfterCurrent );
connect(videoPlayer, SIGNAL(optimalSizeChanged()), SLOT(onOptimalSizeChanged()));
connect(videoPlayer, SIGNAL(playerPlaying()), SLOT(onPlayerPlaying()));
connect(videoPlayer, SIGNAL(playerFinished()), SLOT(onPlayerFinished()));
connect(cbCutPreview, SIGNAL(currentIndexChanged(int)), SLOT(onCutSelectionChanged(int)));
connect(pbPlay, SIGNAL(clicked()), SLOT(onPlayPreview()));
connect(pbExit, SIGNAL(clicked()), SLOT(onExitPreview()));
}
/* /////////////////////////////////////////////////////////////////////////////
* Destroys the object and frees any allocated resources
*/
TTCutPreview::~TTCutPreview()
{
}
/* /////////////////////////////////////////////////////////////////////////////
* resizeEvent
*/
void TTCutPreview::resizeEvent(QResizeEvent*)
{
videoPlayer->resize(videoFrame->width()-2, videoFrame->height()-2);
}
void TTCutPreview::onOptimalSizeChanged()
{
}
/* /////////////////////////////////////////////////////////////////////////////
* Event handler to receive widgets close events
*/
void TTCutPreview::closeEvent(QCloseEvent* event)
{
cleanUp();
event->accept();
}
/* /////////////////////////////////////////////////////////////////////////////
* Initialize preview parameter
*/
void TTCutPreview::initPreview(TTCutList* cutList)
{
int iPos;
QString preview_video_name;
QFileInfo preview_video_info;
QString selectionString;
int numPreview = cutList->count()/2+1;
// Create video and audio preview clips
for (int i = 0; i < numPreview; i++ ) {
// first cut-in
if (i == 0) {
TTCutItem item = cutList->at(i);
selectionString = QString("Start: %1").arg(item.cutInTime().toString("hh:mm:ss"));
cbCutPreview->addItem( selectionString );
}
// cut i-i
if (numPreview > 1 && i > 0 && i < numPreview-1) {
iPos = (i-1)*2+1;
TTCutItem item1 = cutList->at(iPos);
TTCutItem item2 = cutList->at(iPos+1);
selectionString.sprintf( "Cut %d-%d: %s - %s",i,i+1,
qPrintable(item1.cutInTime().toString("hh:mm:ss")),
qPrintable(item2.cutOutTime().toString("hh:mm:ss")));
cbCutPreview->addItem( selectionString );
}
//last cut out
if (i == numPreview-1) {
iPos = (i-1)*2+1;
TTCutItem item = cutList->at(iPos);
selectionString.sprintf( "End: %s", qPrintable(item.cutOutTime().toString("hh:mm:ss")));
cbCutPreview->addItem( selectionString );
}
}
// set the current cut preview to the first cut clip
preview_video_name.sprintf("preview_001.mpg");
preview_video_info.setFile(QDir(TTCut::tempDirPath), preview_video_name);
current_video_file = preview_video_info.absoluteFilePath();
onCutSelectionChanged(0);
}
/* /////////////////////////////////////////////////////////////////////////////
* ComboBox selectionChanged event handler: load the selected movie
*/
void TTCutPreview::onCutSelectionChanged( int iCut )
{
QString preview_video_name;
QFileInfo preview_video_info;
preview_video_name.sprintf("preview_%03d.mpg",iCut+1);
preview_video_info.setFile( QDir(TTCut::tempDirPath), preview_video_name );
current_video_file = preview_video_info.absoluteFilePath();
qDebug("load preview %s", qPrintable(current_video_file));
videoPlayer->load(current_video_file);
pbPlay->setText(tr("Play"));
pbPlay->setIcon(QIcon(":/pixmaps/pixmaps/play_18.xpm"));
}
/* /////////////////////////////////////////////////////////////////////////////
* Play/Pause the selected preview clip
*/
void TTCutPreview::onPlayPreview()
{
if (videoPlayer->isPlaying()) {
videoPlayer->stop();
pbPlay->setText(tr("Play"));
pbPlay->setIcon(QIcon(":/pixmaps/pixmaps/play_18.xpm"));
return;
}
pbPlay->setText(tr("Stop"));
pbPlay->setIcon(QIcon(":/pixmaps/pixmaps/stop_18.xpm"));
videoPlayer->play();
}
void TTCutPreview::onPlayerPlaying()
{
onPlayPreview();
}
void TTCutPreview::onPlayerFinished()
{
videoPlayer->load(current_video_file);
pbPlay->setText(tr("Play"));
pbPlay->setIcon(QIcon(":/pixmaps/pixmaps/play_18.xpm"));
}
/* /////////////////////////////////////////////////////////////////////////////
* Exit the preview window
*/
void TTCutPreview::onExitPreview()
{
close();
}
/* /////////////////////////////////////////////////////////////////////////////
* Housekeeping: Remove the temporary created preview clips
*/
void TTCutPreview::cleanUp()
{
QString rmCommand = "rm ";
QString fileName = "preview*";
QFileInfo fileInfo;
videoPlayer->cleanUp();
// clean up preview* files in temp directory
fileInfo.setFile(QDir(TTCut::tempDirPath), fileName);
rmCommand += fileInfo.absoluteFilePath();
rmCommand += " 2>/dev/null";
//system(rmCommand.toAscii().data());
}
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
160
],
[
162,
219
],
[
221,
221
]
],
[
[
161,
161
],
[
220,
220
]
]
]
|
1f8a964d35c4b38099b6a7262a4dc8b40856f6c6 | 58496be10ead81e2531e995f7d66017ffdfc6897 | /Sources/System/Win/SystemUtilsImpl.cpp | 9b23079a36977217e645bfaedaed4518491284b6 | []
| no_license | Diego160289/cross-fw | ba36fc6c3e3402b2fff940342315596e0365d9dd | 532286667b0fd05c9b7f990945f42279bac74543 | refs/heads/master | 2021-01-10T19:23:43.622578 | 2011-01-09T14:54:12 | 2011-01-09T14:54:12 | 38,457,864 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,305 | cpp | //============================================================================
// Date : 22.12.2010
// Author : Tkachenko Dmitry
// Copyright : (c) Tkachenko Dmitry ([email protected])
//============================================================================
#include "SystemUtilsImpl.h"
#include <vector>
#include <windows.h>
namespace System
{
std::wstring AStringToWStringImpl(const std::string &str, bool fromUTF8)
{
size_t Len = str.length() + 1;
Len = ::MultiByteToWideChar(fromUTF8 ? CP_UTF8 : CP_ACP, 0, str.c_str(),
static_cast<int>(str.length()), 0, 0);
std::vector<wchar_t> Buffer(Len + 1, 0);
Len = ::MultiByteToWideChar(fromUTF8 ? CP_UTF8 : CP_ACP, 0, str.c_str(),
static_cast<int>(str.length()), &Buffer.front(), static_cast<int>(Len));
return &Buffer.front();
}
std::string WStringToAStringImpl(const std::wstring &str, bool toUTF8)
{
size_t Len = str.length() + 1;
Len = ::WideCharToMultiByte(toUTF8 ? CP_UTF8 : CP_ACP, 0, str.c_str(), -1, 0, 0, NULL, NULL);
std::vector<char> Buffer(Len, 0);
::WideCharToMultiByte(toUTF8 ? CP_UTF8 : CP_ACP, 0, str.c_str(), -1, &Buffer.front(),
static_cast<int>(Len), NULL, NULL);
return &Buffer.front();
}
}
| [
"TkachenkoDmitryV@d548627a-540d-11de-936b-e9512c4d2277"
]
| [
[
[
1,
39
]
]
]
|
370d4c3ee99b44f895e7bddc605a716127b7ff62 | 7acbb1c1941bd6edae0a4217eb5d3513929324c0 | /GLibrary-CPP/sources/GExecutionTime.h | 034d10a8c2cc3a714de2dc597888b036bc27f088 | []
| no_license | hungconcon/geofreylibrary | a5bfc96e0602298b5a7b53d4afe7395a993498f1 | 3abf3e1c31a245a79fa26b4bcf2e6e86fa258e4d | refs/heads/master | 2021-01-10T10:11:51.535513 | 2009-11-30T15:29:34 | 2009-11-30T15:29:34 | 46,771,895 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 393 | h | #ifndef __GEXECUTIONTIME_H__
# define __GEXECUTIONTIME_H__
# include "GExport.h"
# include "GPrecisionTime.h"
class GEXPORTED GExecutionTime
{
public:
GExecutionTime(void);
~GExecutionTime(void);
void Start(void);
GPrecisionTime Now(void);
GPrecisionTime Stop(void);
GPrecisionTime Restart(void);
private:
bool _started;
GPrecisionTime _begin;
};
#endif
| [
"mvoirgard@34e8d5ee-a372-11de-889f-a79cef5dd62c"
]
| [
[
[
1,
22
]
]
]
|
bdc72460ace661972d68437a7c2c3de142b7bf57 | 6c8c4728e608a4badd88de181910a294be56953a | /RexQtScriptModule/QtScriptModule.h | 02b53552651936a2e988636cbf1895f26ee42926 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | caocao/naali | 29c544e121703221fe9c90b5c20b3480442875ef | 67c5aa85fa357f7aae9869215f840af4b0e58897 | refs/heads/master | 2021-01-21T00:25:27.447991 | 2010-03-22T15:04:19 | 2010-03-22T15:04:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,334 | h | #ifndef incl_RexQtScriptModule_h
#define incl_RexQtScriptModule_h
#include "Foundation.h"
#include "StableHeaders.h"
#include "ModuleInterface.h"
#include "ComponentRegistrarInterface.h"
#include <QtScript>
namespace RexQtScript
{
//hack to have a ref to framework so can get the module in api funcs
static Foundation::Framework *staticframework;
class MODULE_API RexQtScriptModule : public Foundation::ModuleInterfaceImpl
{
public:
RexQtScriptModule();
virtual ~RexQtScriptModule();
//the module interface
virtual void Load();
virtual void Unload();
virtual void Initialize();
virtual void PostInitialize();
virtual void Uninitialize();
virtual void Update(Core::f64 frametime);
MODULE_LOGGING_FUNCTIONS;
//! returns name of this module. Needed for logging.
static const std::string &NameStatic() { return Foundation::Module::NameFromType(type_static_); }
static const Foundation::Module::Type type_static_ = Foundation::Module::MT_QtScript;
//QScriptValue test(QScriptContext *context, QScriptEngine *engine);
private:
QScriptEngine engine;
};
//api stuff
QScriptValue LoadUI(QScriptContext *context, QScriptEngine *engine);
QScriptValue Print(QScriptContext *context, QScriptEngine *engine);
}
#endif
| [
"aura@5b2332b8-efa3-11de-8684-7d64432d61a3"
]
| [
[
[
1,
46
]
]
]
|
f320770da992d9e32daf23d5d5417299cefd3d13 | 25fd79ea3a1f2c552388420c5a02433d9cdf855d | /Pool/Billiards/PrecompiledHeaders.cpp | e1074c289059bf3f5504d74192238890d6d721c6 | []
| no_license | k-l-lambda/klspool | 084cbe99a1dc3b9703233fccea3f2f6570df9d63 | b57703169828f9d406e7d0a6cd326063832b12c6 | refs/heads/master | 2021-01-23T07:03:59.086914 | 2009-09-06T09:14:51 | 2009-09-06T09:14:51 | 32,123,777 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 489 | cpp | /*
** This source file is part of Pool.
**
** Copyright (c) 2009 K.L.<[email protected]>, Lazy<[email protected]>
** This program is free software without any warranty.
*/
// PrecompiledHeaders.cpp : 只包括标准包含文件的源文件
// Tetra.pch 将成为预编译头
// PrecompiledHeaders.obj 将包含预编译类型信息
#include "StableHeaders.h"
// TODO: 在 StableHeaders.h 中
//引用任何所需的附加头文件,而不是在此文件中引用
| [
"xxxK.L.xxx@64c72148-2b1e-11de-874f-bb9810f3bc79"
]
| [
[
[
1,
15
]
]
]
|
7da638328ab58a7e0c699e61572590b6f0b7806a | cc07062d1084b4ee88e5f33585fa5aeffc8bb994 | /linalg.cpp | a75937ef8cbdf2bebb4e3096d6642391f52ba4eb | []
| no_license | aloschilov/ComputerGraphics | db5016dd83c8d498790cb9aa674a9426bfaae65b | 46a7a7af151ecbb4c51fb776f0aa4777cf0e45ae | refs/heads/master | 2016-09-05T09:05:38.477800 | 2011-08-03T13:19:33 | 2011-08-03T13:19:33 | 2,148,486 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 31,547 | cpp | ///////////////////////////////////////////////////////////////////////////////
/// @file linalg.cpp
/// @brief This file contains implementation of linear algebra modules
///
/// Related Files: The definitions are in linalg.h
///
/// Maintained by: NSTU
///
/// Copyright c 2007 aloschil. All right reserved.
///
/// CONFIDENTIALLY AND LIMITED USE
///
/// This software, including any software of third parties embodied herein,
/// contains information and concepts wich are confidential to Alexander
/// Loschilov and such third parties. This software is licensed for use
/// solely in accordance with the terms and conditions of the applicable
/// license agreement with Alexander Loschilov or his authorized distributor.
///////////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include "linalg.h"
#include "matrix.h"
using namespace std;
namespace Aloschil
{
//----------------------------------------------------------------------------
// This is a public API. Refer to linalg.h for details.
//----------------------------------------------------------------------------
double ang(const Matrix &v,const Matrix &omega)
{
if(fabs((v.getTransposed() *v).getDeterminant()) <EPSILON ||
fabs((omega.getTransposed()*omega).getDeterminant())<EPSILON)
return 0.0;
Matrix d = augment(v,omega);
double cosValue = (v.getTransposed()*omega).getDeterminant()
/(
sqrt((v.getTransposed()*v).getDeterminant())
*sqrt((omega.getTransposed()*omega).getDeterminant()));
if(cosValue < -1) cosValue = -1;
if(cosValue > 1) cosValue = 1;
return (d.getDeterminant()>=0 ? 1 : -1)*acos(
cosValue
);
}
//----------------------------------------------------------------------------
// This is a public API. Refer to linalg.h for details.
//----------------------------------------------------------------------------
double atan(const Matrix &p)
{
return atan2(p.at(1,0),p.at(0,0));
}
//----------------------------------------------------------------------------
// This is a public API. Refer to linalg.h for details.
//----------------------------------------------------------------------------
Matrix
getCrossingParameters(
const Matrix &A,
const Matrix &B,
const Matrix &C,
const Matrix &D)
{
return !augment(B-A,-(D-C))*(C-A);
}
//----------------------------------------------------------------------------
// This is a public API. Refer to linalg.h for details.
//----------------------------------------------------------------------------
Matrix
getCrossPoint(const Matrix &A,const Matrix &B,
const Matrix &C,const Matrix &D)
{
Matrix T = getCrossingParameters(A,B,C,D);
return A + T[0]*(B-A);
}
//----------------------------------------------------------------------------
// This is a public API. Refer to linalg.h for details.
//----------------------------------------------------------------------------
Matrix
getSectionsCrossPoint(const Matrix &A,const Matrix &B,
const Matrix &C,const Matrix &D)
{
Matrix T = getCrossingParameters(A,B,C,D);
if(!(T[0]>0 && T[0]<1 && T[1]>0 && T[1]<1)) throw NoCrossPoint();
return A + T[0]*(B-A);
}
//----------------------------------------------------------------------------
// This is a public API. Refer to linalg.h for details.
//----------------------------------------------------------------------------
double
getDistance(const Matrix &A, const Matrix &B)
{
return sqrt(((B-A).getTransposed()*(B-A)).getDeterminant());
}
//----------------------------------------------------------------------------
// This is a public API. Refer to linalg.h for details.
//----------------------------------------------------------------------------
SectionsPositionalRelationship
getPositionalRelationship( const Matrix &A,const Matrix &B,
const Matrix &C,const Matrix &D,
double rangeOfEquivalence,
double rangeOfCollinearity)
{
if( fabs(ang(B-A,D-C)/deg)<rangeOfCollinearity ||
fabs(fabs(ang(B-A,D-C)/deg)-180.0)<rangeOfCollinearity)
{
return COLLINEAR;
}
else
{
Matrix E = getCrossPoint(A,B,C,D);
char DCBA=0;
if(getDistance(E,A)<rangeOfEquivalence) DCBA = DCBA | 0x01;
if(getDistance(E,B)<rangeOfEquivalence) DCBA = DCBA | 0x02;
if(getDistance(E,C)<rangeOfEquivalence) DCBA = DCBA | 0x04;
if(getDistance(E,D)<rangeOfEquivalence) DCBA = DCBA | 0x08;
Matrix T = getCrossingParameters(A,B,C,D);
if(DCBA==0)
{// No points are considered to be equal to cross point
if(!(T[0]<0 || T[0]>1 || T[1] <0 || T[1]>1))
return CROSSING_OR_CROSSED;
}
else
{
if(!((DCBA & 0x03) && (DCBA & 0x0C)))
{ // non-adjacent and non-crossed one
if((DCBA & 0x03) && (T[1]>0 && T[1]<1))
{//touched one
return TOUCHED;
}
if((DCBA & 0x0C) && (T[0]>0 && T[0]<1))
{//touching one
return TOUCHING;
}
}
else
{// Adjacent by meaning
return ADJACENT;
}
}
}
return NONINTERSECTING;
}
//----------------------------------------------------------------------------
// This is a public API. Refer to linalg.h for details.
//----------------------------------------------------------------------------
int
random(int max)
{
int number;
number = rand();
return number % max;
}
//----------------------------------------------------------------------------
// This is a public API. Refer to linalg.h for details.
//----------------------------------------------------------------------------
vector<Matrix>
getRandomPolygon( const Matrix &T,
double a, double b,
double teta)
{
vector<Matrix> resultVector;
int phi;
for(phi=0;phi<360;phi+=random(teta))
resultVector.push_back(T + (a + random(b-a))*Vector(cos(phi*deg),sin(phi*deg)));
return resultVector;
}
//----------------------------------------------------------------------------
// This is a public API. Refer to linalg.h for details.
//----------------------------------------------------------------------------
vector<Matrix> getRound(
const Matrix &a,
const Matrix &b,
const Matrix &c,
double r,
double rho,
int numberOfSegments,
double rangeOfCollinearity)
{
if(getPositionalRelationship(a,b,b,c,EPSILON,rangeOfCollinearity)==
COLLINEAR)
{
vector<Matrix> result;
result.push_back(b);
return result;
}
Matrix V = normalize(b-a);
Matrix W = normalize(c-b);
double phi = 0.5*ang(V,W);
double rCandidateAB = rho*getDistance(a,b)/tan(fabs(phi));
double rCandidateBC = rho*getDistance(b,c)/tan(fabs(phi));
if(rCandidateAB>=r)
{
if(rCandidateBC<r)
{
r = rCandidateBC;
}
}
else
{
if(rCandidateAB<rCandidateBC)
{
r = rCandidateAB;
}
else
{
r = rCandidateBC;
}
}
Matrix B = sign(phi)* Lrot(V+W);
Matrix o = b + r/cos(phi)*normalize(B);
double alfa = atan(sign(phi)*Rrot(V));
return getArc(o,r,alfa,2*phi,numberOfSegments);
}
//----------------------------------------------------------------------------
// This is a public API. Refer to linalg.h for details.
//----------------------------------------------------------------------------
vector<Matrix> getArc( const Matrix ¢er,
double radius,
double startAngle,
double sweepLength,
int numberOfSegments)
{
vector<Matrix> result;
if(sweepLength>=0)
{
if(numberOfSegments<=0) return result;
double step = sweepLength/numberOfSegments;
double endAngle = startAngle + sweepLength;
for(double angle=startAngle;angle<endAngle + EPSILON;angle+=step)
{
double x = radius*cos(angle);
double y = radius*sin(angle);
Matrix matrixToPush = Vector(x,y)+center;
result.push_back(matrixToPush);
}
}else
{
if(numberOfSegments<=0) return result;
double step = sweepLength/numberOfSegments;
double endAngle = startAngle + sweepLength;
for(double angle=startAngle;angle>=endAngle - EPSILON;angle+=step)
{
double x = radius*cos(angle);
double y = radius*sin(angle);
Matrix matrixToPush = Vector(x,y)+center;
result.push_back(matrixToPush);
}
}
return result;
}
//----------------------------------------------------------------------------
// This is a public API. Refer to linalg.h for details.
//----------------------------------------------------------------------------
Matrix Lrot(const Matrix &vectorToRotate)
{
Matrix result;
result.setSize(2,1);
result[0] = -vectorToRotate.at(1,0);
result[1] = vectorToRotate.at(0,0);
return result;
}
//----------------------------------------------------------------------------
// This is a public API. Refer to linalg.h for details.
//----------------------------------------------------------------------------
Matrix Rrot(const Matrix &vectorToRotate)
{
Matrix result;
result.setSize(2,1);
result[0] = vectorToRotate.at(1,0);
result[1] = -vectorToRotate.at(0,0);
return result;
}
//----------------------------------------------------------------------------
// This is a public API. Refer to linalg.h for details.
//----------------------------------------------------------------------------
Matrix normalize(const Matrix &vectorToNormalize)
{
double length =sqrt( (vectorToNormalize.getTransposed()*vectorToNormalize).
getDeterminant());
return (1/length)*vectorToNormalize;
}
//----------------------------------------------------------------------------
// This is a public API. Refer to linalg.h for details.
//----------------------------------------------------------------------------
double sign(double x)
{
if(x==0) return 0;
if(x>0) return 1;
return -1;
}
//----------------------------------------------------------------------------
// This is a public API. Refer to linalg.h for details.
//----------------------------------------------------------------------------
std::vector<std::vector<Matrix> > getClosedCircuits(
std::vector<std::vector<Matrix> > listOfSegments,
double rangeOfEquivalence)
{
size_t numberOfSegments = listOfSegments.size();
vector<vector<Matrix> > emptyVectorOfPolygons;
vector<vector<Matrix> > result;
vector<Matrix> ab;
vector<Matrix > curCircuit;
size_t currentCircuitSize = 0;
bool newCircuitJustStarted = true;
bool lastCircuitJustClosed = true;
if(listOfSegments.size()<3)
return emptyVectorOfPolygons;
vector<bool> notUsed(listOfSegments.size(),true);
bool thereAreChanges = true;
while(true)
{
if(!thereAreChanges) return emptyVectorOfPolygons;
thereAreChanges = false;
for(size_t i=0;i<numberOfSegments;++i)
{
if(find(notUsed.begin(),notUsed.end(),true)==notUsed.end())
{
if(lastCircuitJustClosed)
return result;
else
return emptyVectorOfPolygons;
}
lastCircuitJustClosed = false;
if(notUsed[i])
{
ab = listOfSegments[i];
if(newCircuitJustStarted)
{
curCircuit.clear();
curCircuit.push_back(ab[0]);
curCircuit.push_back(ab[1]);
currentCircuitSize = 2;
newCircuitJustStarted = false;
notUsed[i] = false;
thereAreChanges = true;
}
else
{
if(getDistance(
curCircuit[currentCircuitSize-1],
ab[0])<rangeOfEquivalence)
{
curCircuit.push_back(ab[1]);
++currentCircuitSize;
notUsed[i] = false;
thereAreChanges = true;
}
else
{
if(getDistance(
curCircuit[currentCircuitSize-1],
ab[1])<rangeOfEquivalence)
{
curCircuit.push_back(ab[0]);
++currentCircuitSize;
notUsed[i] = false;
thereAreChanges = true;
}
else
{
continue;
}
}
if(getDistance(curCircuit[currentCircuitSize-1],
curCircuit[0])<rangeOfEquivalence && currentCircuitSize>3)
{
result.push_back(curCircuit);
newCircuitJustStarted = true;
lastCircuitJustClosed = true;
}
else
{
continue;
}
}
}
else
{
continue;
}
}
}
}
//----------------------------------------------------------------------------
// This is a public API. Refer to linalg.h for details.
//----------------------------------------------------------------------------
Matrix getCrossProduct(const Matrix &u, const Matrix&v)
{
Matrix result;
result.setSize(3,1);
result[0]=u.at(1,0)*v.at(2,0) - v.at(1,0)*u.at(2,0);
result[1]=-(u.at(0,0)*v.at(2,0) - v.at(0,0)*u.at(2,0));
result[2]=u.at(0,0)*v.at(1,0) - v.at(0,0)*u.at(1,0);
return result;
}
//----------------------------------------------------------------------------
// This is a public API. Refer to linalg.h for details.
//----------------------------------------------------------------------------
list<list<Matrix> > cont(list<list<Matrix> > Ls,double epsilon)
{
list<list<Matrix> > LP;
list<list<Matrix> > S;
list<Matrix> ab;
list<Matrix> C;
printListOfLists("Ls.list",Ls);
size_Ls:
if(!Ls.empty())
{
S = Ls;
printListOfLists("S.list",S);
ab_Ls:
ab = (*Ls.begin());
printList("ab.list",ab);
if(C.empty())
{
C=ab;
printList("C.list",C);
goto Ls_Ls_ab;
}
else
{
if(getDistance(C.back(),ab.front())<=epsilon)
{
C.push_back(ab.back());
goto Ls_Ls_ab;
}
else
{
if(getDistance(C.back(),ab.back())<=epsilon)
{
C.push_back(ab.front());
goto Ls_Ls_ab;
}
else
{
list<Matrix> tmp = Ls.front();
Ls.erase(Ls.begin());
Ls.push_back(tmp);
printListOfLists("Ls.list",Ls);
// ���� �������� �������������� ����, ��� ����� ������� {Ls=S}
if(equal(S.begin(),S.end(),Ls.begin()))
{
list<Matrix>::iterator endSegment = C.end();
--endSegment;
C.erase(endSegment);
goto size_Ls;
}
else
{
goto ab_Ls;
}
}
}
}
Ls_Ls_ab:
// �������� ������� �� ������
list<list<Matrix> >::iterator curSegment = Ls.begin();
list<list<Matrix> >::iterator endSegment = Ls.end();
// ����� ���� �������� � ������
for(;curSegment!=endSegment;++curSegment)
{
if( (*curSegment).front()==ab.front() &&
(*curSegment).back()==ab.back())
{
Ls.erase(curSegment);
break;
}
}
printListOfLists("Ls.list",Ls);
if(C.size()<4) goto size_Ls;
printList("C.list",C);
list<Matrix>::iterator curVertex = C.begin();
list<Matrix>::iterator endVertex = C.end();
list<Matrix>::iterator C_m = C.end();--C_m;
--endVertex;
--endVertex;
--endVertex;
for(;curVertex!=endVertex;++curVertex)
{
if(getDistance(*curVertex,*C_m)>epsilon)
continue;
if(curVertex!=C.begin())
{
list<Matrix>::iterator k = C.begin();
for(;k!=curVertex;++k)
{
list<Matrix > c1c2;
c1c2.push_back(C.front());
C.erase(C.begin());
c1c2.push_back(C.front());
Ls.push_back(c1c2);
}
}
printList("C.list",C);
LP.push_back(min_poly(C));
printListOfLists("LP.list",LP);
printListOfLists("Ls.list",Ls);
goto size_Ls;
}
goto size_Ls;
}
printListOfLists("LP.list",LP);
return LP;
}
//----------------------------------------------------------------------------
// This is a public API. Refer to linalg.h for details.
//----------------------------------------------------------------------------
list<Matrix> min_poly(list<Matrix> P,double epsilon)
{
list<Matrix>::iterator pm = P.begin();
list<Matrix>::iterator i = P.begin();
list<Matrix>::iterator pEnd = P.end();
double t;
for(++i;i!=pEnd;++i)
{
Matrix V = (*i) - (*pm);
//double abs = sqrt((V.getTransposed()*V).getDeterminant());
if(sqrt((V.getTransposed()*V).getDeterminant())>epsilon)
{
if(pm!=P.begin())
{
list<Matrix>::iterator pmM1 = pm;
--pmM1;
Matrix W = (*pm) - (*pmM1);
t = (W.getTransposed()*(V + W)).getDeterminant() / (W.getTransposed()*W).getDeterminant();
if(fabs(((normalize(W).getTransposed())*normalize(V)).getDeterminant())>=1)
{
if(t>1)
{//(1,inf)
(*pm) = (*i);
}
else
{
if(t<=0)
{// (-inf,0]
(*pmM1)=(*pm);
(*pm) = (*i);
}
else
{// (0,1]
continue;
}
}
}
else
{
++pm;
(*pm) = (*i);
}
}
else
{
++pm;
(*pm) = (*i);
}
}
}
list<Matrix>::iterator pmM1=pm;
--pmM1;
list<Matrix>::iterator pmP1=pm;
++pmP1;
list<Matrix>::iterator p2 = P.begin();
++p2;
if(fabs((normalize(P.front() - (*pmM1))*normalize((*p2) - P.front()).getTransposed()).getDeterminant())<1)
{
P.erase(pmP1,P.end());
}
else
{
P.erase(P.begin());
P.erase(pm,P.end());
P.push_back(P.front());
}
return P;
}
//----------------------------------------------------------------------------
// This is a public API. Refer to linalg.h for details.
//----------------------------------------------------------------------------
void printList(const char *fileName,list<Matrix> listToPrint)
{
FILE *file;
if((file=fopen(fileName,"w"))==NULL)
{
return;
}
list<Matrix>::iterator curMatrix = listToPrint.begin();
list<Matrix>::iterator endMatrix = listToPrint.end();
for(;curMatrix!=endMatrix;++curMatrix)
{
for(unsigned int i=0;i<(*curMatrix).y;i++)
{
for(unsigned int j=0;j<(*curMatrix).x;j++)
{
fprintf(file,"|%10.3g",
(*curMatrix).field[i*(*curMatrix).x+j]);
}
fprintf(file,"\n");
}
fprintf(file,"\n");
}
fclose(file);
}
//----------------------------------------------------------------------------
// This is a public API. Refer to linalg.h for details.
//----------------------------------------------------------------------------
void printListOfLists(const char *fileName,list<list<Matrix> >listToPrint)
{
FILE *file;
if((file=fopen(fileName,"w"))==NULL)
{
return;
}
list<list<Matrix> >::iterator curList = listToPrint.begin();
list<list<Matrix> >::iterator endList = listToPrint.end();
for(;curList!=endList;++curList)
{
list<Matrix>::iterator curMatrix = (*curList).begin();
list<Matrix>::iterator endMatrix = (*curList).end();
for(;curMatrix!=endMatrix;++curMatrix)
{
for(unsigned int i=0;i<(*curMatrix).y;i++)
{
for(unsigned int j=0;j<(*curMatrix).x;j++)
{
fprintf(file,"|%10.3g",
(*curMatrix).field[i*(*curMatrix).x+j]);
}
fprintf(file,"\n");
}
fprintf(file,"\n");
}
}
fclose(file);
}
//----------------------------------------------------------------------------
// This is a public API. Refer to linalg.h for details.
//----------------------------------------------------------------------------
Matrix rotateX(double angle)
{
Matrix tmp;
tmp.setSize(4, 4);
tmp.at(0,0) = 1.0;
tmp.at(1,1) = cos(angle);
tmp.at(1,2) = sin(angle);
tmp.at(2,1) = -sin(angle);
tmp.at(2,2) = cos(angle);
tmp.at(3,3) = 1.0;
return tmp.getTransposed();
}
//----------------------------------------------------------------------------
// This is a public API. Refer to linalg.h for details.
//----------------------------------------------------------------------------
Matrix rotateY(double angle)
{
Matrix tmp;
tmp.setSize(4, 4);
tmp.at(0,0) = cos(angle);
tmp.at(0,2) = -sin(angle);
tmp.at(1,1) = 1.0;
tmp.at(2,0) = sin(angle);
tmp.at(2,2) = cos(angle);
tmp.at(3,3) = 1.0;
return tmp.getTransposed();
}
//----------------------------------------------------------------------------
// This is a public API. Refer to linalg.h for details.
//----------------------------------------------------------------------------
Matrix rotateZ(double angle)
{
Matrix tmp;
tmp.setSize(4, 4);
tmp.at(0,0) = cos(angle);
tmp.at(0,1) = sin(angle);
tmp.at(1,0) = -sin(angle);
tmp.at(1,1) = cos(angle);
tmp.at(2,2) = 1.0;
tmp.at(3,3) = 1.0;
return tmp.getTransposed();
}
//----------------------------------------------------------------------------
// This is a public API. Refer to linalg.h for details.
//----------------------------------------------------------------------------
Matrix scale(double x,double y,double z)
{
Matrix tmp;
tmp.setSize(4,4);
tmp.at(0,0)=x;
tmp.at(1,1)=y;
tmp.at(2,2)=z;
tmp.at(3,3)=1.0;
return tmp.getTransposed();
}
//----------------------------------------------------------------------------
// This is a public API. Refer to linalg.h for details.
//----------------------------------------------------------------------------
Matrix translate(double x,double y,double z)
{
Matrix tmp;
tmp.setSize(4,4);
tmp.at(0,0)=1.0;
tmp.at(1,1)=1.0;
tmp.at(2,2)=1.0;
tmp.at(3,3)=1.0;
tmp.at(3,0)=x;
tmp.at(3,1)=y;
tmp.at(3,2)=z;
return tmp.getTransposed();
}
double _M_PI = 3.141592654;
double const deg = _M_PI/180.0;
//----------------------------------------------------------------------------
// This is a public API. Refer to linalg.h for details.
//----------------------------------------------------------------------------
int point_is_in_polygon(const Matrix &point, const std::vector<Matrix> &polygon) {
int r = 0;
int l = 0;
int e = 0;
size_t segments_count = polygon.size();
for(size_t current_segment=0; current_segment<segments_count; ++current_segment) {
double point_test_result = line_to_point_test(
polygon[current_segment],
polygon[(current_segment+1)%segments_count],
point);
if(point_test_result<0) {
l = 1;
} else if (point_test_result>0) {
r = 1;
} else {
e = 1;
}
if(l*r != 0) {
return -1;
}
}
return -(e-1);
}
//----------------------------------------------------------------------------
// This is a public API. Refer to linalg.h for details.
//----------------------------------------------------------------------------
double line_to_point_test(const Matrix &A, const Matrix &B, const Matrix&P) {
Matrix M;
M.setSize(2, 2);
M.at(0, 0) = (P - A)[0];
M.at(1, 0) = (P - A)[1];
M.at(0, 1) = (B - A)[0];
M.at(1, 1) = (B - A)[1];
return M.getDeterminant();
}
} // namespace Aloschil
| [
"[email protected]"
]
| [
[
[
1,
804
]
]
]
|
02306b8eace91eff237447673df128888c1e3a70 | 63fc6506b8e438484a013b3c341a1f07f121686b | /apps/examples/_emptyExample/src/testApp.h | aa7dd8868d8493c3eaceaefaa4d06b0f41ecc57e | []
| no_license | progen/ofx-dev | c5a54d3d588d8fd7318e35e9b57bf04c62cda5a8 | 45125fcab657715abffc7e84819f8097d594e28c | refs/heads/master | 2021-01-20T07:15:39.755316 | 2009-03-03T22:33:37 | 2009-03-03T22:33:37 | 140,479 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 436 | h | #ifndef _TEST_APP
#define _TEST_APP
#include "ofMain.h"
#include "ofAddons.h"
class testApp : public ofBaseApp {
public:
void setup();
void update();
void draw();
void keyPressed(int key);
void keyReleased(int key);
void mouseMoved(int x, int y );
void mouseDragged(int x, int y, int button);
void mousePressed(int x, int y, int button);
void mouseReleased();
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
27
]
]
]
|
e65eba172b68b64b71207dbb907f219c1ea3c791 | 00c36cc82b03bbf1af30606706891373d01b8dca | /OpenGUI/OpenGUI_PluginManager.cpp | 401cd89ef4c7ebd68ffd5867b8f8680e1658ea4a | [
"BSD-3-Clause"
]
| permissive | VB6Hobbyst7/opengui | 8fb84206b419399153e03223e59625757180702f | 640be732a25129a1709873bd528866787476fa1a | refs/heads/master | 2021-12-24T01:29:10.296596 | 2007-01-22T08:00:22 | 2007-01-22T08:00:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,736 | cpp | // OpenGUI (http://opengui.sourceforge.net)
// This source code is released under the BSD License
// See LICENSE.TXT for details
#include "tinyxml.h"
#include "OpenGUI_PluginManager.h"
#include "OpenGUI_DynamicLib.h"
#include "OpenGUI_LogSystem.h"
#include "OpenGUI_Exception.h"
#include "OpenGUI_System.h"
#include "OpenGUI_ResourceProvider.h"
#include "OpenGUI_Resource.h"
#include "OpenGUI_XMLParser.h"
typedef void( *PLUGIN_START_FUNC )( void );
typedef void( *PLUGIN_STOP_FUNC )( void );
namespace OpenGUI {
//############################################################################
template<> PluginManager* Singleton<PluginManager>::mptr_Singleton = 0;
//############################################################################
PluginManager& PluginManager::getSingleton( void ) {
assert( mptr_Singleton );
return ( *mptr_Singleton );
}
//############################################################################
PluginManager* PluginManager::getSingletonPtr( void ) {
return mptr_Singleton;
}
//############################################################################
//############################################################################
//############################################################################
PluginManager::PluginManager() {
LogManager::SlogMsg( "INIT", OGLL_INFO2 ) << "Created PluginManager" << Log::endlog;
XMLParser::getSingleton().RegisterLoadHandler( "Plugin", &PluginManager::_Plugin_XMLNode_Load );
XMLParser::getSingleton().RegisterUnloadHandler( "Plugin", &PluginManager::_Plugin_XMLNode_Unload );
}
//############################################################################
PluginManager::~PluginManager() {
LogManager::SlogMsg( "SHUTDOWN", OGLL_INFO2 ) << "Destroying PluginManager" << Log::endlog;
PluginManager::unloadAllPlugins();
XMLParser::getSingleton().UnregisterLoadHandler( "Plugin", &PluginManager::_Plugin_XMLNode_Load );
XMLParser::getSingleton().UnregisterUnloadHandler( "Plugin", &PluginManager::_Plugin_XMLNode_Unload );
}
//############################################################################
void PluginManager::loadPlugin( String filename ) {
LogManager::SlogMsg( "PluginManager", OGLL_INFO2 ) << "LoadPlugin: " << filename << Log::endlog;
PluginMap::iterator iter = mPluginMap.find( filename );
if ( iter != mPluginMap.end() ) {
OG_THROW( Exception::ERR_DUPLICATE_ITEM, "Plugin already loaded: " + filename, "PluginManager::loadPlugin" );
}
//attach the module
DynamicLib* lib = new DynamicLib( filename );
if ( !lib )
return;
try {
lib->load();
} catch ( Exception e ) {
delete lib;
throw e;
return;
}
mPluginMap[filename] = lib;
//run start plugin
firePluginStart( lib );
}
//############################################################################
void PluginManager::unloadPlugin( String filename ) {
LogManager::SlogMsg( "PluginManager", OGLL_INFO2 ) << "UnloadPlugin: " << filename << Log::endlog;
DynamicLib* lib;
PluginMap::iterator iter = mPluginMap.find( filename );
if ( iter == mPluginMap.end() ) {
OG_THROW( Exception::ERR_ITEM_NOT_FOUND, "Plugin not found in list of loaded plugins: " + filename, "PluginManager::unloadPlugin" );
}
lib = iter->second;
mPluginMap.erase( iter );
//run stop plugin
firePluginStop( lib );
//detach the module
lib->unload();
delete lib;
}
//############################################################################
void PluginManager::unloadAllPlugins() {
LogManager::SlogMsg( "PluginManager", OGLL_INFO2 ) << "UnloadAllPlugins..." << Log::endlog;
DynamicLib* lib;
PluginMap::iterator iter = mPluginMap.begin();
while ( iter != mPluginMap.end() ) {
lib = iter->second;
//run stop plugin
firePluginStop( lib );
//detach the module
lib->unload();
delete lib;
iter++;
}
mPluginMap.clear();
}
//############################################################################
void PluginManager::firePluginStart( DynamicLib* lib ) {
LogManager::SlogMsg( "PluginManager", OGLL_INFO3 ) << "firePluginStart: " << lib->getName() << Log::endlog;
PLUGIN_START_FUNC func;
func = ( PLUGIN_START_FUNC ) lib->getSymbol( "pluginStart" );
if ( func )
func();
}
//############################################################################
void PluginManager::firePluginStop( DynamicLib* lib ) {
LogManager::SlogMsg( "PluginManager", OGLL_INFO3 ) << "firePluginStop: " << lib->getName() << Log::endlog;
PLUGIN_STOP_FUNC func;
func = ( PLUGIN_STOP_FUNC ) lib->getSymbol( "pluginStop" );
if ( func )
func();
}
//############################################################################
bool PluginManager::_Plugin_XMLNode_Load( const XMLNode& node, const String& nodePath ) {
PluginManager& manager = PluginManager::getSingleton();
// we only handle these tags within <OpenGUI>
if ( nodePath != "/OpenGUI/" )
return false;
const String file = node.getAttribute( "File" );
manager.loadPlugin( file );
return true;
}
//############################################################################
bool PluginManager::_Plugin_XMLNode_Unload( const XMLNode& node, const String& nodePath ) {
PluginManager& manager = PluginManager::getSingleton();
// we only handle these tags within <OpenGUI>
if ( nodePath != "/OpenGUI/" )
return false;
const String file = node.getAttribute( "File" );
manager.unloadPlugin( file );
return true;
}
//############################################################################
};
| [
"zeroskill@2828181b-9a0d-0410-a8fe-e25cbdd05f59"
]
| [
[
[
1,
157
]
]
]
|
ba37241f27e29597bbcb59da57d453960c036d76 | c94aa08b9f0574e67a04f6f4213665e35219ab8d | /DSound/HttpServer.cpp | e29a469129419057f24a49ae11f47d77b5285a90 | []
| no_license | xzlinux/dsbridge | 47f2e2c80abc5313b756c22aa9ae0bd9624ac207 | bc7cb0413a554b07b9d2894b9ea9734a03835ce3 | refs/heads/master | 2021-12-10T04:47:47.540806 | 2009-07-31T16:16:34 | 2009-07-31T16:16:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,688 | cpp | /*
Copyright 2009 Jesper Svennevid
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR 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 "HttpServer.h"
#include "Notify.h"
#include "ExceptionHandler.h"
#include "Configuration.h"
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
namespace dsbridge
{
volatile bool HttpServer::s_isStreaming = false;
HttpServer::HttpServer()
: m_thread(0)
, m_socket(-1)
, m_clients(0)
, m_clientCount(0)
, m_running(false)
, m_lastAnnounce(time(0))
, m_port(0)
{}
HttpServer::~HttpServer()
{
}
bool HttpServer::create()
{
InitializeCriticalSection(&m_cs);
if (!m_buffer.create(100 * 1024))
{
Notify::update(Notify::HttpServer, Notify::Error, "Could not create ringbuffer");
return false;
}
m_thread = CreateThread(0, 0, threadEntry, this, CREATE_SUSPENDED, 0);
if (!m_thread)
{
Notify::update(Notify::HttpServer, Notify::Error, "Could not create thread");
return false;
}
m_running = true;
ResumeThread(m_thread);
return true;
}
void HttpServer::destroy()
{
m_running = false;
SleepEx(10, FALSE);
m_thread = 0;
}
void HttpServer::write(const void* buffer, size_t count)
{
EnterCriticalSection(&m_cs);
do
{
if (m_buffer.left() < count)
{
m_buffer.seek((m_buffer.left() + m_buffer.written()) / 2);
}
m_buffer.write(buffer, count);
}
while (0);
LeaveCriticalSection(&m_cs);
}
DWORD WINAPI HttpServer::threadEntry(LPVOID parameters)
{
__try
{
HttpServer* server = static_cast<HttpServer*>(parameters);
if (!server->initialize())
{
return 0;
}
while (server->run())
{
SleepEx(1, TRUE);
}
server->shutdown();
Notify::update(Notify::HttpServer, Notify::Info, "Stopped");
}
__except(ExceptionHandler::filter("HttpServer", GetExceptionInformation()))
{
}
return 0;
}
bool HttpServer::initialize()
{
int delayNetworking = Configuration::getInteger("DelayNetworking");
if (delayNetworking > 0)
{
SleepEx(delayNetworking, FALSE);
}
int initializeNetworking = Configuration::getInteger("InitializeNetworking");
if (initializeNetworking)
{
WSADATA data;
if (WSAStartup(MAKEWORD(2,2), &data))
{
Notify::update(Notify::HttpServer, Notify::Error, "Could not initialize networking");
return false;
}
}
m_socket = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (m_socket < 0)
{
Notify::update(Notify::HttpServer, Notify::Error, "Could not create socket");
return false;
}
SOCKADDR_IN saddr;
saddr.sin_family = AF_INET;
saddr.sin_addr.S_un.S_addr = INADDR_ANY;
saddr.sin_port = htons(m_port = Configuration::getInteger("HTTPPort", 8124));
if (::bind(m_socket, reinterpret_cast<SOCKADDR*>(&saddr), sizeof(saddr)) < 0)
{
Notify::update(Notify::HttpServer, Notify::Error, "Could not bind to port %d", m_port);
return false;
}
BOOL reuse = TRUE;
if (::setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<const char*>(&reuse), sizeof(reuse)) < 0)
{
Notify::update(Notify::HttpServer, Notify::Error, "Could not set SO_REUSEADDR");
return false;
}
ULONG nonblock = 1;
if (::ioctlsocket(m_socket, FIONBIO, &nonblock) < 0)
{
Notify::update(Notify::HttpServer, Notify::Error, "Could not set server to non-blocking");
return false;
}
if (::listen(m_socket, 1) < 0)
{
Notify::update(Notify::HttpServer, Notify::Error, "Could not start listening to port");
return false;
}
Notify::update(Notify::HttpServer, Notify::Info, "Listening on port %d", m_port);
return true;
}
bool HttpServer::run()
{
fd_set rfds;
fd_set wfds;
FD_ZERO(&rfds);
FD_ZERO(&wfds);
FD_SET(m_socket, &rfds);
time_t newAnnounce = time(0);
if ((newAnnounce - m_lastAnnounce) > 5)
{
Notify::setConnected(m_clientCount > 0);
Notify::update(Notify::HttpServer, Notify::Info, "http://localhost:%d/", m_port);
m_lastAnnounce = newAnnounce;
}
for (unsigned int i = 0; i < m_clientCount; ++i)
{
Client& client = m_clients[i];
switch (client.m_state)
{
case Header:
{
FD_SET(client.m_socket, &rfds);
}
break;
case Close:
case Streaming:
case Cover:
{
FD_SET(client.m_socket, &wfds);
}
break;
}
}
timeval timeout = {0};
int fd = ::select(0, &rfds, &wfds, 0, &timeout);
if (fd < 0)
{
Notify::update(Notify::HttpServer, Notify::Error, "select() failed - %d", fd);
return false;
}
else if (!fd)
{
return m_running;
}
bool isStreaming = false;
for (unsigned int i = 0; i < m_clientCount; ++i)
{
Client& client = m_clients[i];
switch (client.m_state)
{
case Header:
{
if (!FD_ISSET(client.m_socket, &rfds))
{
break;
}
int result = ::recv(client.m_socket, client.m_buffer + client.m_bufferSize, int(sizeof(client.m_buffer) - client.m_bufferSize), 0);
if (result <= 0)
{
client.m_state = Close;
client.m_bufferSize = client.m_bufferOffset = 0;
break;
}
client.m_bufferSize += result;
processHeader(client);
}
break;
case Close:
{
if (!FD_ISSET(client.m_socket, &wfds))
{
break;
}
int result = ::send(client.m_socket, client.m_buffer + client.m_bufferOffset, int(client.m_bufferSize - client.m_bufferOffset), 0);
if (result == SOCKET_ERROR)
{
client.m_state = Close;
client.m_bufferSize = client.m_bufferOffset = 0;
break;
}
client.m_bufferOffset += result;
}
break;
case Streaming:
{
isStreaming = true;
if (!FD_ISSET(client.m_socket, &wfds))
{
break;
}
processStreaming(client);
int result = ::send(client.m_socket, client.m_buffer + client.m_bufferOffset, int(client.m_bufferSize - client.m_bufferOffset), 0);
if (result == SOCKET_ERROR)
{
client.m_state = Close;
client.m_bufferSize = client.m_bufferOffset = 0;
break;
}
client.m_bufferOffset += result;
}
break;
case Cover:
{
if (!FD_ISSET(client.m_socket, &wfds))
{
break;
}
processCover(client);
int result = ::send(client.m_socket, client.m_buffer + client.m_bufferOffset, int(client.m_bufferSize - client.m_bufferOffset), 0);
if (result == SOCKET_ERROR)
{
client.m_state = Close;
client.m_bufferSize = client.m_bufferOffset = 0;
break;
}
client.m_bufferOffset += result;
}
break;
}
}
for (unsigned int i = 0; i < m_clientCount;)
{
Client& client = m_clients[i];
if ((client.m_state != Close) || (client.m_bufferSize != client.m_bufferOffset))
{
++i;
continue;
}
delete client.m_cover;
::closesocket(client.m_socket);
::memmove(&client, &client + 1, sizeof(Client) * (m_clientCount - (i+1)));
--m_clientCount;
}
s_isStreaming = isStreaming && (m_clientCount > 0);
if (FD_ISSET(m_socket, &rfds))
{
SOCKADDR_IN saddr;
int saddrlen = sizeof(saddr);
SOCKET clientSocket = ::accept(m_socket, reinterpret_cast<SOCKADDR*>(&saddr), &saddrlen);
if (clientSocket != INVALID_SOCKET)
{
Client* clients = new Client[m_clientCount + 1];
if (m_clientCount > 0)
{
memcpy(clients, m_clients, m_clientCount * sizeof(Client));
delete [] m_clients;
}
clients[m_clientCount].m_socket = clientSocket;
clients[m_clientCount].m_state = Header;
m_clients = clients;
++ m_clientCount;
}
}
return m_running;
}
void HttpServer::shutdown()
{
::closesocket(m_socket);
m_socket = -1;
}
void HttpServer::processHeader(Client& client)
{
enum State
{
ParseRequest,
ParseHeader
} state = ParseRequest;
ClientState clientState = Close;
for (const char* begin = client.m_buffer, *end = client.m_buffer + client.m_bufferSize; (begin != end) && (client.m_state == Header);)
{
const char* eol = begin;
while ((eol != end) && (*eol != '\r') && (*eol != '\n')) ++eol;
if (eol == end)
{
break;
}
switch (state)
{
case ParseRequest:
{
const char* curr = begin;
const char* methodBegin = curr;
const char* methodEnd = methodBegin;
while ((methodEnd != eol) && (*methodEnd != ' ')) ++methodEnd;
if ((methodEnd == eol) || ((methodEnd-methodBegin) != 3) || ::_strnicmp(methodBegin, "GET", 3))
{
client.m_state = Close;
sprintf_s(client.m_buffer, sizeof(client.m_buffer), "HTTP/1.0 405 Method Not Allowed\r\nAllow: GET\r\n\r\n");
client.m_bufferSize = static_cast<int>(::strlen(client.m_buffer));
client.m_bufferOffset = 0;
break;
}
curr = methodEnd + 1;
const char* uriBegin = curr;
const char* uriEnd = uriBegin;
while ((uriEnd != eol) && (*uriEnd != ' ')) ++uriEnd;
static int coverArtEnabled = Configuration::getInteger("CoverArt");
if ((uriEnd != eol) && ((uriEnd-uriBegin) == 1) && !::_strnicmp(uriBegin, "/", 1))
{
clientState = Streaming;
}
else if ((uriEnd != eol) && ((uriEnd-uriBegin) >= 6) && !::_strnicmp(uriBegin, "/cover", 6) && coverArtEnabled)
{
clientState = Cover;
}
else
{
client.m_state = Close;
sprintf_s(client.m_buffer, sizeof(client.m_buffer), "HTTP/1.0 404 Not Found\r\n\r\n");
client.m_bufferSize = static_cast<int>(::strlen(client.m_buffer));
client.m_bufferOffset = 0;
break;
}
curr = uriEnd + 1;
if (((eol-curr) != 8) || (::_strnicmp(curr,"HTTP/1.0",8) && ::_strnicmp(curr,"HTTP/1.1",8)))
{
client.m_state = Close;
sprintf_s(client.m_buffer, sizeof(client.m_buffer), "HTTP/1.0 505 HTTP Version Not Supported\r\n\r\n");
client.m_bufferSize = static_cast<int>(::strlen(client.m_buffer));
client.m_bufferOffset = 0;
break;
}
state = ParseHeader;
}
break;
case ParseHeader:
{
if (begin == eol)
{
client.m_state = clientState;
sprintf_s(client.m_buffer, sizeof(client.m_buffer), "HTTP/1.0 200 OK\r\n");
if (client.m_metaData)
{
sprintf_s(client.m_buffer, sizeof(client.m_buffer), "%sicy-metaint: %d\r\n", client.m_buffer, s_metaSize);
}
if (client.m_state == Cover)
{
sprintf_s(client.m_buffer, sizeof(client.m_buffer), "%sContent-Type: image/png\r\n", client.m_buffer);
}
else if (client.m_state == Streaming)
{
sprintf_s(client.m_buffer, sizeof(client.m_buffer), "%sContent-Type: audio/mpeg\r\n", client.m_buffer);
}
sprintf_s(client.m_buffer, sizeof(client.m_buffer), "%s\r\n", client.m_buffer);
client.m_bufferSize = static_cast<int>(::strlen(client.m_buffer));
client.m_metaOffset = s_metaSize;
break;
}
const char* headerEnd = begin;
while ((headerEnd != eol) && (*headerEnd != ':')) ++headerEnd;
if (headerEnd == eol)
{
break;
}
const char* valueBegin = headerEnd + 1;
while ((valueBegin != eol) && (*valueBegin == ' ')) ++valueBegin;
if (((headerEnd - begin) == 12) && !::_strnicmp(begin, "Icy-MetaData", 12))
{
const char* value = begin;
while ((eol != end) && (*eol == ' ')) ++eol;
if (::strtoul(begin + 13, 0, 10) > 0)
{
client.m_metaData = true;
}
}
if (((headerEnd - begin) == 4) && !::_strnicmp(begin, "Host", 4))
{
::memset(client.m_host, 0, sizeof(client.m_host));
::strncpy_s(client.m_host, sizeof(client.m_host), valueBegin, eol - valueBegin);
}
}
break;
}
while ((eol != end) && (*eol == '\r')) ++eol;
while ((eol != end) && (*eol == '\n')) ++eol;
begin = eol;
}
if ((client.m_bufferSize == sizeof(client.m_buffer)) && (client.m_state == Header))
{
client.m_state = Close;
client.m_bufferSize = client.m_bufferOffset = 0;
}
}
void HttpServer::processStreaming(Client& client)
{
do
{
if (client.m_bufferOffset != client.m_bufferSize)
{
break;
}
client.m_bufferOffset = client.m_bufferSize = 0;
if (client.m_metaOffset > 0)
{
break;
}
client.m_metaOffset = s_metaSize;
if (!client.m_metaData)
{
break;
}
char windowTitle[256];
if (!GetWindowText(Notify::window(), windowTitle, sizeof(windowTitle)))
{
windowTitle[0] = '\0';
}
unsigned int newHash = hash(windowTitle, ::strlen(windowTitle));
if (newHash == client.m_titleHash && !client.m_sendCover)
{
client.m_buffer[0] = '\0';
client.m_bufferSize = 1;
break;
}
char* buf = client.m_buffer+1;
size_t bufsize = sizeof(client.m_buffer)-1;
static int coverArtEnabled = Configuration::getInteger("CoverArt");
if (newHash != client.m_titleHash)
{
char* activeTitle = windowTitle;
static const char* titlePrefix = Configuration::getString("TitlePrefix");
if (!::_strnicmp(activeTitle, titlePrefix, ::strlen(titlePrefix)))
{
activeTitle += ::strlen(titlePrefix);
}
for (size_t i = 0, n = ::strlen(activeTitle); i < n; ++i)
{
char& c = activeTitle[i];
switch (c)
{
case -106: c = '-'; break;
case -107: c = '-'; break;
}
}
sprintf_s(buf, bufsize, "StreamTitle='%s';", activeTitle);
client.m_sendCover = Notify::window() && (::strlen(client.m_host) > 0) && coverArtEnabled;
}
else if (client.m_sendCover)
{
sprintf_s(buf, bufsize, "StreamUrl='http://%s/cover/%d.png';", client.m_host, time(0));
client.m_sendCover = false;
}
size_t length = ::strlen(buf) + 1;
size_t fill = ((length + 15) & ~15) - length;
size_t packetLength = length + fill;
memset(buf + length, 0, fill);
client.m_buffer[0] = char(packetLength / 16);
client.m_bufferSize = packetLength + 1;
client.m_titleHash = newHash;
}
while (0);
size_t maxRead = client.m_metaOffset < (sizeof(client.m_buffer) - client.m_bufferSize) ? client.m_metaOffset : sizeof(client.m_buffer) - client.m_bufferSize;
if (!maxRead)
{
return;
}
EnterCriticalSection(&m_cs);
do
{
size_t actual = m_buffer.read(client.m_buffer + client.m_bufferSize, maxRead);
client.m_bufferSize += actual;
client.m_metaOffset -= actual;
}
while (0);
LeaveCriticalSection(&m_cs);
}
unsigned int HttpServer::hash(const char* str, size_t length)
{
unsigned int hash = 0;
for(unsigned int i = 0; i < length; ++str, ++i)
{
unsigned int x;
hash = (hash << 4) + (*str);
if((x = hash & 0xF0000000L) != 0)
{
hash ^= (x >> 24);
}
hash &= ~x;
}
return hash;
}
void HttpServer::processCover(Client& client)
{
int i = 0;
if (!client.m_cover)
{
client.m_cover = CoverExtractor::getCoverImage(Notify::window());
if (!client.m_cover)
{
client.m_state = Close;
}
}
do
{
if (client.m_bufferOffset != client.m_bufferSize)
{
break;
}
if (client.m_coverOffset == client.m_cover->length)
{
client.m_state = Close;
break;
}
size_t maxCopy = (client.m_cover->length - client.m_coverOffset) > sizeof(client.m_buffer) ? sizeof(client.m_buffer) : (client.m_cover->length - client.m_coverOffset);
::memcpy_s(client.m_buffer, sizeof(client.m_buffer), client.m_cover->image + client.m_coverOffset, maxCopy);
client.m_bufferOffset = 0;
client.m_bufferSize = maxCopy;
client.m_coverOffset += maxCopy;
}
while (0);
}
}
| [
"[email protected]"
]
| [
[
[
1,
686
]
]
]
|
3c388fde4e2c051782ee74a2d8a93d5ded1b05bf | cc97070bb192c613fae05f301713a9ed47e89278 | /entities.h | eac2c3263fc1c3d8f1680473ed7645a20515e147 | []
| no_license | username0x0a/facebook-protocol | 257f39264ad801b3108d5d97c6ec7216d34053e3 | a97982e0187330326f1c40c709cba5eef60ceea9 | refs/heads/master | 2021-06-15T06:45:42.371823 | 2011-04-20T02:16:48 | 2011-04-20T02:16:48 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 2,556 | h | /*
Facebook plugin for Miranda Instant Messenger
_____________________________________________
Copyright © 2009-11 Michal Zelinka
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
File name : $HeadURL: https://[email protected]/svn/trunk/facebook/entities.h $
Revision : $Revision: 91 $
Last change by : $Author: n3weRm0re.ewer $
Last change on : $Date: 2011-01-08 11:10:34 +0100 (Sat, 08 Jan 2011) $
*/
#pragma once
struct facebook_user
{
HANDLE handle;
std::string user_id;
std::string real_name;
unsigned int status_id;
std::string status;
bool is_idle;
std::string image_url;
time_t last_update;
facebook_user( )
{
this->handle = NULL;
this->user_id = this->real_name = this->status = this->image_url = "";
this->is_idle = false;
this->status_id = ID_STATUS_OFFLINE;
this->last_update = 0;
}
facebook_user( facebook_user* fu )
{
this->handle = fu->handle;
this->image_url = fu->image_url;
this->is_idle = fu->is_idle;
this->last_update = fu->last_update;
this->real_name = fu->real_name;
this->status = fu->status;
this->status_id = fu->status_id;
this->user_id = fu->user_id;
}
};
struct facebook_message
{
std::string user_id;
std::string message_text;
time_t time;
facebook_message( )
{
this->user_id = this->message_text = "";
this->time = 0;
}
facebook_message( const facebook_message& msg )
{
this->user_id = msg.user_id;
this->message_text = msg.message_text;
this->time = msg.time;
}
};
struct facebook_notification
{
std::string user_id;
std::string text;
std::string link;
facebook_notification( ) {
this->user_id = this->text = this->link = ""; }
};
struct facebook_newsfeed
{
std::string user_id;
std::string title;
std::string text;
std::string link;
facebook_newsfeed( ) {
this->user_id = this->title = this->text = this->link = ""; }
};
| [
"[email protected]"
]
| [
[
[
1,
106
]
]
]
|
3725d1cdbd17935e378963f83c4a6720116f9fc5 | f978424f35fd0fb95bc8cd17466cb2b86ce7d04c | /GraphicsProject/src/graphics/graphics_camera.h | 0e5ae63bec41ed2d48f387cc64d8db20db11f8aa | []
| no_license | omegahm/FoundationOfGraphics | 9efadf3bc2a228c6867d71640858daf87efa98fc | a221589c38ff6d8b4c97c4fe182599046c0d8087 | refs/heads/master | 2021-01-22T02:34:50.483751 | 2010-03-08T19:47:00 | 2010-03-08T19:47:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,359 | h | #ifndef GRAPHICS_CAMERA_H
#define GRAPHICS_CAMERA_H
//
// Graphics Framework.
// Copyright (C) 2008 Department of Computer Science, University of Copenhagen
//
namespace graphics
{
/**
* A virtual pin-hole camera.
* The camera class produces the matrices necessary for the virtual world
* to be rasterized.
*/
template<typename math_types>
class Camera
{
public:
/// The actual type of the elements of vectors and matrices.
typedef typename math_types::real_type real_type;
/// The actual type of a vector2.
typedef typename math_types::vector2_type vector2_type;
/// The actual type of a vector3.
typedef typename math_types::vector3_type vector3_type;
/// The actual type of a matrix4x4.
typedef typename math_types::matrix4x4_type matrix4x4_type;
public:
/**
* Creates a Camera with a default (empty) state.
*/
Camera() : m_state(0)
{}
/**
* Destroys the Camera.
*/
virtual ~Camera()
{}
/**
* Initialize the Camera with a RenderPipeline.
*/
void init( RenderPipeline<math_types>& R ) {
m_state = &(R.state());
}
/**
* Set the projection matrix.
*
* @param vrp View reference point
* @param vpn View-plane normal
* @param vup View up vector
* @param prp Projection reference point
* @param lower_left Lower left corner of the view-plane
* @param upper_right Upper right corner of the view-plane
* @param front_plane Distance to front clipping plane
* @param back_plane Distance to back clipping plane
*/
void set_projection(vector3_type const& vrp, vector3_type const& vpn,
vector3_type const& vup, vector3_type const& prp,
vector2_type const& lower_left,
vector2_type const& upper_right,
real_type const& front_plane,
real_type const& back_plane)
{
this->m_state->view_orientation() = this->compute_view_orientation_matrix(vrp, vpn, vup);
this->m_state->view_projection() = this->compute_view_projection_matrix(prp,
lower_left,
upper_right,
front_plane,
back_plane);
this->m_state->window_viewport() = this->compute_window_viewport();
matrix4x4_type M;
M = this->m_state->window_viewport() * this->m_state->view_projection() * this->m_state->view_orientation();
this->m_state->projection() = M;
}
/**
* Get the projection matrix.
* @return The current projection matrix from world to screen.
*/
matrix4x4_type get_projection() const
{
return this->m_state->projection();
}
/**
* Get View-Orientation.
* @return The transformation matrix which transforms from the world-coordinate system to the eye-coordinate system.
*/
matrix4x4_type get_view_orientation() const
{
return this->m_state->view_orientation();
}
/**
* Get View-Projection.
* @return The transformation matrix which transforms from the eye-coordinate system to the canonical view-volume.
*/
matrix4x4_type get_view_projection() const
{
return this->m_state->view_projection();
}
/**
* Get window-viewport transformation.
* @return The transformation matrix which transforms from the canonical view-volume to the screen-coordinate system.
*/
matrix4x4_type get_window_viewport() const
{
return this->m_state->window_viewport();
}
/**
* Set model-view matrix.
*
*@param M Model-View matrix.
*/
void set_model_view(matrix4x4_type const& M)
{
this->m_state->model() = M;
}
protected:
/**
* Computes a matrix which transforms coordinates from the World-coordinate system to the Eye-coordinate system.
* Foley et al. (p.229-284; 2nd edition)
* @param vrp The View Reference Point.
* @param vpn The View Plane Normal.
* @param vup The View Up Vector.
* @return The view_orientation matrix.
*/
virtual matrix4x4_type compute_view_orientation_matrix(vector3_type const& vrp,
vector3_type const& vpn,
vector3_type const& vup) = 0;
/**
* Computes a matrix which transforms from the Eye-coordinate system to the Canonical View Volume.
* Foley et al. (p.229-284; 2nd edition)
* @param prp The Projection Reference Point in Eye-coordinates.
* @param lower_left The lower left corner of the window in Eye-coordinates.
* @param upper_right The upper right corner of the window in Eye-coordinates.
* @param front_plane The closest distance from the origin in Eye-coordinates.
* @param back_plane The farthest distance from the origin in Eye-coordinates.
* @return The view_projection matrix.
*/
virtual matrix4x4_type compute_view_projection_matrix(vector3_type const& prp,
vector2_type const& lower_left,
vector2_type const& upper_right,
real_type const& front_plane,
real_type const& back_plane) = 0;
/**
* Computes a projection matrix using the parameters for a perspective camera
* given by Foley et al. (p.229-284; 2nd edition)
* The projection matrix should transforms from world coordinates to
* normalized projection coordinates
*
* @param vrp View reference point
* @param vpn View-plane normal
* @param vup View up vector
* @param prp Projection reference point
* @param lower_left Lower left corner of the view-plane
* @param upper_right Upper right corner of the view-plane
* @param front_plane Distance to front clipping plane
* @param back_plane Distance to back clipping plane
*/
virtual matrix4x4_type compute_projection_matrix(vector3_type const& vrp,
vector3_type const& vpn,
vector3_type const& vup,
vector3_type const& prp,
vector2_type const& lower_left,
vector2_type const& upper_right,
real_type const& front_plane,
real_type const& back_plane) = 0;
virtual matrix4x4_type compute_window_viewport() = 0;
protected:
/**
* Stores a pointer to the state of the graphics pipeline.
*/
GraphicsState<math_types>* m_state;
};
}// end namespace graphics
// GRAPHICS_CAMERA_H
#endif
| [
"[email protected]"
]
| [
[
[
1,
202
]
]
]
|
69f1c3e25c9422aba312f8eed402222654cadfb5 | eb039fcb8dccfef9cec68dd97bdc3fa63d420845 | /kifaru.old/primitives.h | a405c1da5ec922fc54dd24e0d29c0752d039b172 | []
| no_license | BackupTheBerlios/kifaru | 8fead5b2de6a838aee9cfb0c3c869caaffc35038 | b694dffbd4e85c07689d35af5198f1ed1c415f5f | refs/heads/master | 2020-12-02T16:00:17.331679 | 2006-06-28T18:22:20 | 2006-06-28T18:22:20 | 40,044,599 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 342 | h | #include <SDL/SDL.h>
namespace ephidrena
{
void PutPixel(SDL_Surface *screen,Uint32 x, Uint32 y, Uint8 R, Uint8 G, Uint8 B);
void Plasma(SDL_Surface *screen);
void WriteNextPixel(SDL_Surface *screen, Uint32 offset, Uint8 R, Uint8 G, Uint8 B);
void Slock(SDL_Surface *screen);
void Sulock(SDL_Surface *screen);
};
| [
"nerve-"
]
| [
[
[
1,
13
]
]
]
|
05db903f71414f705bacb8bb97afe2952eb7f951 | bef7d0477a5cac485b4b3921a718394d5c2cf700 | /nanobots/src/demo/map/Turbulence.h | 2f2e47fd05a39cadee56eac19ceb1613cfd5c6fb | [
"MIT"
]
| permissive | TomLeeLive/aras-p-dingus | ed91127790a604e0813cd4704acba742d3485400 | 22ef90c2bf01afd53c0b5b045f4dd0b59fe83009 | refs/heads/master | 2023-04-19T20:45:14.410448 | 2011-10-04T10:51:13 | 2011-10-04T10:51:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 363 | h | #ifndef __TURBULENCE_H
#define __TURBULENCE_H
class CGameMap;
class CTurbulence : public boost::noncopyable {
public:
struct SCell {
float vx;
float vy;
};
public:
CTurbulence( const CGameMap& gmap );
~CTurbulence();
void update();
private:
const CGameMap* mMap;
// turbulence cells array
SCell* mCells;
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
28
]
]
]
|
ba9002ed58414acbe71b2ad20df0a8e092af0457 | 1c80a726376d6134744d82eec3129456b0ab0cbf | /Project/C++/POJ/1947/1947.cpp | 77d2cad25f5a9c700b72845a46a5d453d0ebaa9d | []
| no_license | dabaopku/project_pku | 338a8971586b6c4cdc52bf82cdd301d398ad909f | b97f3f15cdc3f85a9407e6bf35587116b5129334 | refs/heads/master | 2021-01-19T11:35:53.500533 | 2010-09-01T03:42:40 | 2010-09-01T03:42:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,305 | cpp | /*
#include "stdio.h"
#include "iostream"
#include "string"
using namespace std;
struct tree
{
int sons;
tree *son[152],*parent;
};
tree data[152];
int num[152][152]={0};
int n;
int count(int start,int barns,tree *head)
{
if(start<1 || start > n || barns<=0 ) return 0;
if(num[start][barns]!=-1) return num[start][barns];
int i,min=200;
for()
}
int main()
{
int p,i,j;
int father,son;
cin>>n>>p;
for(i=0;i<152;i++){
data[i].parent=NULL;
data->sons=1;
}
while(cin>>father>>son){
data[father].sons++;
data[father].son[data[father].sons-1]=&data[son];
data[son].parent=&data[father];
}
tree *head=&data[1];
while(head->parent)
head=head->parent;
memset(num,-1,sizeof(num));
father = count(1,p,head);
return 0;
}*/
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#define MAXN 200
#define MAX 100000
struct Node
{
int first,next,parent,count;
};
Node node[MAXN];
int a[MAXN][MAXN],b[MAXN][MAXN];
void count(int root,int num)
{
if(root==0)
return;
int i,min;
count(node[root].first,num);
count(node[root].next,num);
if(node[root].next==0)
a[root][num]=b[root][num];
else
{
min=a[node[root].next][num]+1;
for(i=0;i<=num;i++)
if(a[node[root].next][i]+b[root][num-i]<min)
min=a[node[root].next][i]+b[root][num-i];
a[root][num]=min;
}
if(num+1>node[root].count)
b[root][num+1]=MAX;
else
b[root][num+1]=a[node[root].first][num];
}
void visit(int root)
{
if(root==0)
return;
int r;
visit(node[root].first);
visit(node[root].next);
r=node[root].first;
node[root].count=1;
while(r){
node[root].count+=node[r].count;
r=node[r].next; }
}
int main()
{
int i,n,p,s1,s2,root,min;
while(scanf("%d%d",&n,&p)!=EOF){
memset(node,0,sizeof(node));
for(i=0;i<n-1;i++){
scanf("%d%d",&s1,&s2);
node[s2].next=node[s1].first;
node[s1].first=s2;
node[s2].parent=s1;
}
for(i=1;i<=n;i++)
if(node[i].parent==0)
{
root=i;
break;
}
visit(root);
for(i=0;i<=n;i++)
b[i][0]=1;
for(i=0;i<p;i++)
count(root,i);
min=b[1][p];
for(i=2;i<=n;i++)
{
if(i!=root)
b[i][p]++;
if(b[i][p]<min)
min=b[i][p];
}
printf("%d\n",min);
}
return 0;
} | [
"[email protected]@592586dc-1302-11df-8689-7786f20063ad"
]
| [
[
[
1,
126
]
]
]
|
97ce5a78a655ee82601a7ffef9320bf70c85a4b1 | bef7d0477a5cac485b4b3921a718394d5c2cf700 | /testSoftShadows/src/system/Globals.h | 980830900baa56a7438cf653384b011fe7a69af2 | [
"MIT"
]
| permissive | TomLeeLive/aras-p-dingus | ed91127790a604e0813cd4704acba742d3485400 | 22ef90c2bf01afd53c0b5b045f4dd0b59fe83009 | refs/heads/master | 2023-04-19T20:45:14.410448 | 2011-10-04T10:51:13 | 2011-10-04T10:51:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 674 | h | #ifndef __GLOBALS_H
#define __GLOBALS_H
#include <dingus/renderer/RenderContext.h>
#include <dingus/kernel/D3DDevice.h>
#include <dingus/input/InputContext.h>
#include <dingus/resource/EffectBundle.h>
#include <dingus/resource/IndexBufferBundle.h>
#include <dingus/resource/MeshBundle.h>
#include <dingus/resource/SharedTextureBundle.h>
#include <dingus/resource/SharedSurfaceBundle.h>
#include <dingus/resource/TextureBundle.h>
#include <dingus/resource/VertexDeclBundle.h>
using namespace dingus;
extern dingus::CRenderContext* G_RENDERCTX;
extern dingus::CInputContext* G_INPUTCTX;
const int GUI_X = 640;
const int GUI_Y = 480;
#endif
| [
"[email protected]"
]
| [
[
[
1,
27
]
]
]
|
7f20005751fd4073465d6987ef802e3bf89df7be | 593b85562f3e570a5a6e75666d8cd1c535daf3b6 | /Source/ObjectManager2.cpp | 9f582de59c5af2725355fd642d858af4a08a53fd | []
| no_license | rayjohannessen/songofalbion | fc62c317d829ceb7c215b805fed4276788a22154 | 83d7e87719bfb3ade14096d4969aa32c524c1902 | refs/heads/master | 2021-01-23T13:18:10.028635 | 2011-02-13T00:23:37 | 2011-02-13T00:23:37 | 32,121,693 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,151 | cpp | ////////////////////////////////////////////////////////
// File Name : "ObjectManager.cpp"
//
// Author : Matthew Di Matteo (MD)
//
// Purpose : Manages all objects in the game
////////////////////////////////////////////////////////
#include "ObjectManager.h"
#include "BattleMap.h"
#include "CSGD_DirectInput.h"
#include "Tile.h"
#include "Base.h"
#include "CodeProfiler.h"
#include "MessageSystem.h"
#include "Assets.h"
#include <queue>
using namespace std;
struct cmp
{
bool operator() (const CBase * a, const CBase * b)
{
return (a->GetPosY()+a->GetHeight() > b->GetPosY()+b->GetHeight());
}
};
ObjectManager::ObjectManager(void)
{
}
ObjectManager::~ObjectManager(void)
{
RemoveAll();
}
ObjectManager* ObjectManager::GetInstance()
{
static ObjectManager instance;
return &instance;
}
void ObjectManager::UpdateObjects(float fElapsedTime)
{
CBattleMap* bm = CBattleMap::GetInstance();
for (unsigned int i=0; i < m_vObjects.size(); i++)
{
m_vObjects[i]->Update(fElapsedTime);
}
}
void ObjectManager::RenderObjects(void)
{
static CCodeProfiler cp("ObjMainRender");
cp.Start();
//Z-Sorted ... seems to be a small problem with ninjas rendering on top of another
// (perhaps when they're being put in front when they need to be in front of a map object?)
priority_queue<CBase *, vector<CBase *>, cmp> objects;
for (unsigned int i=0; i < m_vObjects.size(); i++)
{
m_vObjects[i]->SetPosZ(GetZdepthDraw(m_vObjects[i]->GetAnchor().x, m_vObjects[i]->GetAnchor().y, m_vObjects[i]->GetCurrTile() ) );
objects.push(m_vObjects[i]);
}
while (objects.size())
{
objects.top()->Render();
objects.pop();
}
cp.End();
}
void ObjectManager::Add(CBase* pObj)
{
if (pObj != NULL)
m_vObjects.push_back(pObj);
}
void ObjectManager::Remove(CBase* pObj)
{
if (pObj != NULL)
{
vector<CBase*>::iterator iter = m_vObjects.begin();
int count = 0;
while(iter != m_vObjects.end())
{
if ((*iter) == pObj)
{
if ((*iter)->GetType() == OBJECT_BOSS)
{
for(int j = 0; j < (int)(*iter)->GetAnimations().size(); j++)
(*iter)->GetAnimations()[j].Unload();
}
CBase* temp = m_vObjects[count];
delete temp;
iter = m_vObjects.erase(iter);
break;
}
++count;
++iter;
}
}
}
void ObjectManager::RemoveAll(void)
{
for (unsigned int i=0; i < m_vObjects.size(); i++)
{
CBase* temp = m_vObjects[i];
delete temp;
}
m_vObjects.clear();
}
bool ObjectManager::CheckObjectsToAlpha(RECT* mapObjectRect)
{
if (CSGD_DirectInput::GetInstance()->KeyPressed(DIK_D))
int i = 0;
for (unsigned int i=0; i < m_vObjects.size(); i++)
{
if (m_vObjects[i]->GetAnchor().x >= mapObjectRect->left &&
m_vObjects[i]->GetAnchor().x <= mapObjectRect->right &&
m_vObjects[i]->GetAnchor().y >= mapObjectRect->top &&
m_vObjects[i]->GetAnchor().y <= mapObjectRect->bottom)
{
return true;
}
}
return false;
}
float ObjectManager::GetZdepthDraw(int xAnchor, int yAnchor, int currTileID)
{
// if (CSGD_DirectInput::GetInstance()->KeyPressed(DIK_D)) // if need to do debugging
// int i = 0;
// for the character to be ahead of the object,
// it must be directly below, to the southeast, or
// to the southwest of an edge tile...
// otherwise it is behind the object.
CBattleMap* bMap = CBattleMap::GetInstance();
CTile* tiles = bMap->GetTiles();
int numCols = bMap->GetNumCols();
if (currTileID != -1)
{
if (tiles[currTileID-1].Flag() == FLAG_OBJECT_EDGE || // NW
tiles[currTileID-numCols].Flag() == FLAG_OBJECT_EDGE || // NE
tiles[currTileID-(numCols+1)].Flag() == FLAG_OBJECT_EDGE || // N
tiles[currTileID-((numCols+1)<<1)].Flag() == FLAG_OBJECT_EDGE || //
tiles[currTileID-(numCols+2)].Flag() == FLAG_OBJECT_EDGE ||
tiles[currTileID-(((numCols+1)<<1)-1)].Flag() == FLAG_OBJECT_EDGE )
{
return depth.CHARACTER_AHEAD;
}
else
return depth.CHARACTER_BEHIND;
}
else // shouldn't let it get here...
{
MessageBox(0, "Current Tile ID = -1", "Incorrect version.", MB_OK);
return 0;
}
}
void ObjectManager::CheckCollisions(void)
{
for(unsigned int i = 0; i < m_vObjects.size(); i++)
{
for(unsigned int j = 0; j < m_vObjects.size(); j++)
{
if((m_vObjects[i]->GetType()== OBJECT_TURTLE && (m_vObjects[j]->GetType()==OBJECT_BATTLEITEM || m_vObjects[j]->GetType()==OBJECT_WEAPON))
|| (m_vObjects[j]->GetType()== OBJECT_TURTLE && (m_vObjects[i]->GetType()==OBJECT_BATTLEITEM || m_vObjects[i]->GetType()==OBJECT_WEAPON)))
{
RECT rCollision;
RECT rCollisionRect1 = {(LONG)m_vObjects[i]->GetPosX(), (LONG)m_vObjects[i]->GetPosY(),
(LONG)(m_vObjects[i]->GetWidth() + m_vObjects[i]->GetPosX()), (LONG)(m_vObjects[i]->GetHeight() + m_vObjects[i]->GetPosY())};
RECT rCollisionRect2 = {(LONG)m_vObjects[j]->GetPosX(), (LONG)m_vObjects[j]->GetPosY(),
(LONG)(m_vObjects[j]->GetWidth() + m_vObjects[j]->GetPosX()), (LONG)(m_vObjects[j]->GetHeight() + m_vObjects[j]->GetPosY())};
if (IntersectRect(&rCollision, &rCollisionRect1, &rCollisionRect2))
{
if(m_vObjects[j]->GetType()== OBJECT_BATTLEITEM)
{
MessageSystem::GetInstance()->SendMsg( new CDestroyItem((CBattleItem*)m_vObjects[j]));
CBattleMap::GetInstance()->PlaySFX(CAssets::GetInstance()->aBMpickupSnd);
if (m_vObjects[j]->GetName()== "Pizza")
{
CBattleMap::GetInstance()->PlaySFX(CAssets::GetInstance()->aBMninjaPizzaSnd);
}
return;
}
else if(m_vObjects[i]->GetType() == OBJECT_BATTLEITEM)
{
MessageSystem::GetInstance()->SendMsg( new CDestroyItem((CBattleItem*)m_vObjects[i]));
CBattleMap::GetInstance()->PlaySFX(CAssets::GetInstance()->aBMpickupSnd);
if (m_vObjects[j]->GetName()== "Pizza")
{
CBattleMap::GetInstance()->PlaySFX(CAssets::GetInstance()->aBMninjaPizzaSnd);
}
return;
}
else if(m_vObjects[j]->GetType() == OBJECT_WEAPON)
{
MessageSystem::GetInstance()->SendMsg( new CDestroyWeapon(m_vObjects[j]));
CBattleMap::GetInstance()->PlaySFX(CAssets::GetInstance()->aBMpickupSnd);
CBattleMap::GetInstance()->SetWpnPickedUp();
return;
}
else if(m_vObjects[i]->GetType() == OBJECT_WEAPON)
{
MessageSystem::GetInstance()->SendMsg( new CDestroyWeapon(m_vObjects[i]));
CBattleMap::GetInstance()->PlaySFX(CAssets::GetInstance()->aBMpickupSnd);
CBattleMap::GetInstance()->SetWpnPickedUp();
return;
}
}
}
}
}
}
void ObjectManager::ClearEnemies()
{
vector<CBase*>::iterator iter = m_vObjects.begin();
int count = 0;
while(iter != m_vObjects.end())
{
if ((*iter)->GetType() != OBJECT_TURTLE)
{
if ((*iter)->GetType() == OBJECT_BOSS)
{
for(int j = 0; j < (int)(*iter)->GetAnimations().size(); j++)
(*iter)->GetAnimations()[j].Unload();
}
CBase* temp = m_vObjects[count--];
delete temp;
iter = m_vObjects.erase(iter);
}
else
++iter;
++count;
}
} | [
"AllThingsCandid@cb80bfb0-ca38-a83e-6856-ee7c686669b9"
]
| [
[
[
1,
241
]
]
]
|
879bb939644b1ab471a9da9b52ee9683fdd01c6f | 5236606f2e6fb870fa7c41492327f3f8b0fa38dc | /nsrpc/test/nsrpcTest/ProactorSessionAcceptorTest.cpp | 62323bbfea5e54487221e4ed1cba10acdc144e18 | []
| no_license | jcloudpld/srpc | aa8ecf4ffc5391b7183b19d217f49fb2b1a67c88 | f2483c8177d03834552053e8ecbe788e15b92ac0 | refs/heads/master | 2021-01-10T08:54:57.140800 | 2010-02-08T07:03:00 | 2010-02-08T07:03:00 | 44,454,693 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,923 | cpp | #include "stdafx.h"
#include "ProactorSessionTestFixture.h"
#if defined(NSRPC_HAS_PROACTOR)
#include "TestClient.h"
#include <nsrpc/utility/SystemUtil.h>
using namespace nsrpc;
/**
* @class ProactorSessionAcceptorTest
*
* ProactorSessionAcceptor Test
*/
class ProactorSessionAcceptorTest : public ProactorSessionTestFixture
{
private:
virtual void SetUp() {
ProactorSessionTestFixture::SetUp();
client_ = new TestClient;
(void)client_->connect(1, getTestAddress());
}
virtual void TearDown() {
client_->close();
delete client_;
ProactorSessionTestFixture::TearDown();
}
protected:
TestProactorSessionManager* getSessionManager() {
return static_cast<TestProactorSessionManager*>(sessionManager_);
}
protected:
TestClient* client_;
};
TEST_F(ProactorSessionAcceptorTest, testAccept)
{
pause(1);
EXPECT_EQ(1, getSessionManager()->getSessionCount());
}
TEST_F(ProactorSessionAcceptorTest, testMultipleAccept)
{
const int connectionCount = 5;
TestClient client[connectionCount];
for (int i = 0; i < connectionCount; ++i) {
EXPECT_TRUE(client[i].connect(1, getTestAddress()));
}
pause(5);
EXPECT_EQ(1 + connectionCount, getSessionManager()->getSessionCount());
}
TEST_F(ProactorSessionAcceptorTest, testStopToAccept)
{
acceptor_->close();
TestClient client;
EXPECT_FALSE(client.connect(1, getTestAddress())) << "can't connect";
EXPECT_FALSE(acceptor_->open(getTestAddress())) << "can't restart";
}
TEST_F(ProactorSessionAcceptorTest, testDisconnected)
{
pause(1);
EXPECT_TRUE(getSessionManager()->getSession().isConnected());
client_->close();
pause(1);
EXPECT_EQ(0, getSessionManager()->getSessionCount());
}
#endif // #if defined(NSRPC_HAS_PROACTOR)
| [
"kcando@6d7ccee0-1a3b-0410-bfa1-83648d9ec9a4"
]
| [
[
[
1,
89
]
]
]
|
6f8873177eb93b02f2588eacae51764b3adfef8a | b5ab57edece8c14a67cc98e745c7d51449defcff | /Captain's Log/MainGame/Source/Managers/CWorldManager.cpp | 5587a837570a1a7f72b4d199cd323826e9048dcb | []
| no_license | tabu34/tht-captainslog | c648c6515424a6fcdb628320bc28fc7e5f23baba | 72d72a45e7ea44bdb8c1ffc5c960a0a3845557a2 | refs/heads/master | 2020-05-30T15:09:24.514919 | 2010-07-30T17:05:11 | 2010-07-30T17:05:11 | 32,187,254 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,383 | cpp | #include "precompiled_header.h"
#include "CWorldManager.h"
#include "../SGD Wrappers/CSGD_Direct3D.h"
#include "../SGD Wrappers/CSGD_TextureManager.h"
#include "../CGame.h"
#include "CPathManager.h"
#include "../States/CLoadLevelState.h"
#include <fstream>
using namespace std;
CWorldManager::CWorldManager()
{
}
CWorldManager::~CWorldManager()
{
for (int l = 0; l < m_nWorldDepth; l++)
{
for (int i = 0; i < m_nWorldWidth; i++)
{
delete[] m_World[l][i];
}
delete[] m_World[l];
}
delete[] m_World;
}
CWorldManager* CWorldManager::GetInstance()
{
static CWorldManager instance;
return &instance;
}
void CWorldManager::Load(string sFileName)
{
CLoadLevelState::GetInstance()->SetPercentage(0.0f);
CLoadLevelState::GetInstance()->Render();
ifstream fin(sFileName.c_str(), ios::in | ios::binary);
fin.read((char*)&m_fVersionNumber, sizeof(float));
int nFileNameSize = 0;
fin.read((char*)&nFileNameSize, sizeof(int));
m_szFileName = new char[nFileNameSize];
fin.read((char*)m_szFileName, nFileNameSize);
m_szFileName[nFileNameSize] = '\0';
m_nTilesetImageID = CSGD_TextureManager::GetInstance()->LoadTexture(m_szFileName);
fin.read((char*)&m_nTilesetHeight, sizeof(int));
fin.read((char*)&m_nTilesetWidth, sizeof(int));
fin.read((char*)&m_nWorldWidth, sizeof(int));
fin.read((char*)&m_nWorldHeight, sizeof(int));
fin.read((char*)&m_nWorldDepth, sizeof(int));
m_World = new Tile**[m_nWorldDepth];
for (int l = 0; l < m_nWorldDepth; l++)
{
m_World[l] = new Tile*[m_nWorldWidth];
for (int i = 0; i < m_nWorldWidth; i++)
{
m_World[l][i] = new Tile[m_nWorldHeight];
for (int j = 0; j < m_nWorldHeight; j++)
{
Tile tempTile;
fin.read((char*)&tempTile.m_nWidth, sizeof(int));
fin.read((char*)&tempTile.m_nHeight, sizeof(int));
fin.read((char*)&tempTile.m_nTileNumber, sizeof(int));
fin.read((char*)&tempTile.m_nTop, sizeof(int));
fin.read((char*)&tempTile.m_nLeft, sizeof(int));
m_World[l][i][j] = tempTile;
}
}
CLoadLevelState::GetInstance()->SetPercentage(2.5f + (l / (m_nWorldDepth)) * 2.5f);
CLoadLevelState::GetInstance()->Render();
}
CLoadLevelState::GetInstance()->SetPercentage(5.0f);
CLoadLevelState::GetInstance()->Render();
int numHelperNodes;
fin.read((char*)&numHelperNodes, sizeof(int));
for (int b = 0; b < numHelperNodes; b++)
{
POINT tempPoint;
fin.read((char*)&tempPoint.x, sizeof(int));
fin.read((char*)&tempPoint.y, sizeof(int));
m_HelperNodes.push_back(tempPoint);
}
fin.read((char*)&m_nNumBlockers, sizeof(int));
m_Blockers = new Blocker[m_nNumBlockers];
for (int b = 0; b < m_nNumBlockers; b++)
{
fin.read((char*)&m_Blockers[b].m_nNumPoints, sizeof(int));
m_Blockers[b].m_Points = new Blocker::Point[m_Blockers[b].m_nNumPoints];
for (int p = 0; p < m_Blockers[b].m_nNumPoints; p++)
{
fin.read((char*)&m_Blockers[b].m_Points[p].x, sizeof(int));
fin.read((char*)&m_Blockers[b].m_Points[p].y, sizeof(int));
}
}
fin.close();
//DEBUG:: hard-coded blocker to test pathing
// m_nNumBlockers=1;
// m_Blockers = new Blocker;
// m_Blockers->m_nNumPoints=5;
// m_Blockers->m_Points = new Blocker::Point[5];
// m_Blockers->m_Points[0].x = 516;
// m_Blockers->m_Points[0].y = 325;
// m_Blockers->m_Points[1].x = 910;
// m_Blockers->m_Points[1].y = 325;
// m_Blockers->m_Points[2].x = 910;
// m_Blockers->m_Points[2].y = 550;
// m_Blockers->m_Points[3].x = 516;
// m_Blockers->m_Points[3].y = 550;
// m_Blockers->m_Points[4].x = 516;
// m_Blockers->m_Points[4].y = 325;
//create pathing
CPathManager::GetInstance()->GenerateMap();
}
void CWorldManager::Render()
{
for (int l = 0; l < m_nWorldDepth; l++)
{
int tileHeight, tileWidth;
tileHeight = 16;//m_World[l][0][0].m_nHeight;
tileWidth = 16;//m_World[l][0][0].m_nWidth;
int startCulledRow = ((int)CGame::GetInstance()->GetCamera()->GetY()) / tileHeight;
int endCulledRow = ((int)CGame::GetInstance()->GetCamera()->GetY() + CGame::GetInstance()->GetScreenHeight()) / tileHeight;
int startCulledCol = ((int)CGame::GetInstance()->GetCamera()->GetX()) / tileWidth;
int endCulledCol = ((int)CGame::GetInstance()->GetCamera()->GetX() + CGame::GetInstance()->GetScreenWidth()) / tileWidth;
endCulledRow = min(endCulledRow * (tileHeight / 16) + 1, (WorldHeight()/16));
endCulledCol = min(endCulledCol * (tileWidth / 16) + 1, (WorldWidth()/16));
for (int i = startCulledCol; i < endCulledCol; i++)
{
for (int j = startCulledRow; j < endCulledRow; j++)
{
Tile tempTile = m_World[l][i][j];
if (tempTile.m_nTileNumber != -1)
{
RECT src = {tempTile.m_nTileNumber % (m_nTilesetWidth) * tempTile.m_nWidth,
tempTile.m_nTileNumber / (m_nTilesetWidth) * tempTile.m_nHeight,
0, 0};
src.left += tempTile.m_nTileNumber % (m_nTilesetWidth);
src.top += tempTile.m_nTileNumber / (m_nTilesetWidth);
src.bottom = src.top + tempTile.m_nHeight;
src.right = src.left + tempTile.m_nWidth;
CSGD_TextureManager::GetInstance()->Draw(m_nTilesetImageID, tempTile.m_nLeft - (int)CGame::GetInstance()->GetCamera()->GetX(), tempTile.m_nTop - (int)CGame::GetInstance()->GetCamera()->GetY(), 1.0f, 1.0f, &src);
}
}
}
}
} | [
"notserp007@34577012-8437-c882-6fb8-056151eb068d",
"[email protected]@34577012-8437-c882-6fb8-056151eb068d",
"tabu34@34577012-8437-c882-6fb8-056151eb068d"
]
| [
[
[
1,
5
],
[
7,
99
],
[
118,
118
],
[
139,
177
]
],
[
[
6,
6
],
[
119,
120
],
[
135,
138
]
],
[
[
100,
117
],
[
121,
134
]
]
]
|
7aa5b56634b9f1155eb13eba77542cebee353fa0 | 14447604061a3ded605cd609b44fec3979d9b1cc | /slowtest/SlowHttpTest.cpp | 65e893be395db4ceabd8a07f41214922ea2801db | []
| no_license | sinsoku/cacoon | 459e441aacf4dc01311a6b5cd7eae2425fbf4c3f | 36e81b689b53505c2d8117ff60ce8e4012d6eae6 | refs/heads/master | 2020-05-30T23:34:08.361671 | 2010-12-03T17:44:20 | 2010-12-03T17:44:20 | 809,470 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,239 | cpp | #include "stdafx.h"
#include "HttpClient.h"
#include "HeaderMap.h"
// 簡易接続のテスト
TEST( HttpConnectionTest, EasyRequest )
{
Response resp = HttpClient::Connect( Method::Get, "http://cacoo.com/" );
EXPECT_EQ( 200, resp.StatusCode() );
}
// 複数回のレスポンスのテスト
TEST( HttpConnectionTest, MultiRequest )
{
EXPECT_NO_THROW(
{
try
{
Connection c = HttpClient::CreateHttpConnection( "cacoo.com" );
Response res1st = c.Request( Method::Get, "/" );
Response res2nd = c.Request( Method::Get, "/features" );
EXPECT_EQ( 200, res1st.StatusCode() );
EXPECT_EQ( 200, res2nd.StatusCode() );
Connection c2 = c;
Response res3rd = c2.Request( Method::Get, "/" );
EXPECT_EQ( 200, res3rd.StatusCode() );
}
catch( const CacoonException & ex )
{
std::cout << ex.Info() << std::endl;
throw;
}
} );
}
// 実際に HTTP 通信をしてみる
TEST( HttpConnectionTest, RealConnection )
{
Connection c = HttpClient::CreateHttpConnection( "www.google.co.jp" );
Response res = c.Request( Method::Get, "/index.html" );
//std::cout << res.Header().ToString() << "\r\n" << res.Body() << std::endl;
EXPECT_EQ( 200, res.StatusCode() );
} | [
"[email protected]"
]
| [
[
[
1,
47
]
]
]
|
3ed03ebfa1f635b85222639add90074d79a95f34 | ce262ae496ab3eeebfcbb337da86d34eb689c07b | /SEFoundation/SEDistance/SEDistVector3Triangle3.cpp | c6d8a6e70ce88603843baad0ac9f5bb8439d46b6 | []
| no_license | pizibing/swingengine | d8d9208c00ec2944817e1aab51287a3c38103bea | e7109d7b3e28c4421c173712eaf872771550669e | refs/heads/master | 2021-01-16T18:29:10.689858 | 2011-06-23T04:27:46 | 2011-06-23T04:27:46 | 33,969,301 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,533 | cpp | // Swing Engine Version 1 Source Code
// Most of techniques in the engine are mainly based on David Eberly's
// Wild Magic 4 open-source code.The author of Swing Engine learned a lot
// from Eberly's experience of architecture and algorithm.
// Several sub-systems are totally new,and others are re-implimented or
// re-organized based on Wild Magic 4's sub-systems.
// Copyright (c) 2007-2010. All Rights Reserved
//
// Eberly's permission:
// Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or (at
// your option) any later version. The license is available for reading at
// the location:
// http://www.gnu.org/copyleft/lgpl.html
#include "SEFoundationPCH.h"
#include "SEDistVector3Triangle3.h"
using namespace Swing;
//----------------------------------------------------------------------------
SEDistVector3Triangle3f::SEDistVector3Triangle3f(const SEVector3f& rVector,
const SETriangle3f& rTriangle)
:
m_pVector(&rVector),
m_pTriangle(&rTriangle)
{
}
//----------------------------------------------------------------------------
const SEVector3f& SEDistVector3Triangle3f::GetVector() const
{
return *m_pVector;
}
//----------------------------------------------------------------------------
const SETriangle3f& SEDistVector3Triangle3f::GetTriangle() const
{
return *m_pTriangle;
}
//----------------------------------------------------------------------------
float SEDistVector3Triangle3f::Get()
{
float fSqrDist = GetSquared();
return SEMath<float>::Sqrt(fSqrDist);
}
//----------------------------------------------------------------------------
float SEDistVector3Triangle3f::GetSquared()
{
SEVector3f vec3fDiff = m_pTriangle->V[0] - *m_pVector;
SEVector3f vec3fEdge0 = m_pTriangle->V[1] - m_pTriangle->V[0];
SEVector3f vec3fEdge1 = m_pTriangle->V[2] - m_pTriangle->V[0];
float fA00 = vec3fEdge0.GetSquaredLength();
float fA01 = vec3fEdge0.Dot(vec3fEdge1);
float fA11 = vec3fEdge1.GetSquaredLength();
float fB0 = vec3fDiff.Dot(vec3fEdge0);
float fB1 = vec3fDiff.Dot(vec3fEdge1);
float fC = vec3fDiff.GetSquaredLength();
float fDet = SEMath<float>::FAbs(fA00*fA11 - fA01*fA01);
float fS = fA01*fB1 - fA11*fB0;
float fT = fA01*fB0 - fA00*fB1;
float fSqrDistance;
if( fS + fT <= fDet )
{
if( fS < 0.0f )
{
if( fT < 0.0f ) // region 4
{
if( fB0 < 0.0f )
{
fT = 0.0f;
if( -fB0 >= fA00 )
{
fS = 1.0f;
fSqrDistance = fA00 + 2.0f*fB0 + fC;
}
else
{
fS = -fB0/fA00;
fSqrDistance = fB0*fS + fC;
}
}
else
{
fS = 0.0f;
if( fB1 >= 0.0f )
{
fT = 0.0f;
fSqrDistance = fC;
}
else if( -fB1 >= fA11 )
{
fT = 1.0f;
fSqrDistance = fA11 + 2.0f*fB1 + fC;
}
else
{
fT = -fB1/fA11;
fSqrDistance = fB1*fT + fC;
}
}
}
else // region 3
{
fS = 0.0f;
if( fB1 >= 0.0f )
{
fT = 0.0f;
fSqrDistance = fC;
}
else if( -fB1 >= fA11 )
{
fT = 1.0f;
fSqrDistance = fA11 + 2.0f*fB1 + fC;
}
else
{
fT = -fB1/fA11;
fSqrDistance = fB1*fT + fC;
}
}
}
else if( fT < 0.0f ) // region 5
{
fT = 0.0f;
if( fB0 >= 0.0f )
{
fS = 0.0f;
fSqrDistance = fC;
}
else if( -fB0 >= fA00 )
{
fS = 1.0f;
fSqrDistance = fA00 + 2.0f*fB0 + fC;
}
else
{
fS = -fB0/fA00;
fSqrDistance = fB0*fS + fC;
}
}
else // region 0
{
// minimum at interior point
float fInvDet = 1.0f / fDet;
fS *= fInvDet;
fT *= fInvDet;
fSqrDistance = fS*(fA00*fS + fA01*fT + 2.0f*fB0) +
fT*(fA01*fS + fA11*fT + 2.0f*fB1) + fC;
}
}
else
{
float fTmp0, fTmp1, fNumer, fDenom;
if( fS < 0.0f ) // region 2
{
fTmp0 = fA01 + fB0;
fTmp1 = fA11 + fB1;
if( fTmp1 > fTmp0 )
{
fNumer = fTmp1 - fTmp0;
fDenom = fA00 - 2.0f*fA01 + fA11;
if( fNumer >= fDenom )
{
fS = 1.0f;
fT = 0.0f;
fSqrDistance = fA00 + 2.0f*fB0 + fC;
}
else
{
fS = fNumer/fDenom;
fT = 1.0f - fS;
fSqrDistance = fS*(fA00*fS + fA01*fT + 2.0f*fB0) +
fT*(fA01*fS + fA11*fT + 2.0f*fB1) + fC;
}
}
else
{
fS = 0.0f;
if( fTmp1 <= 0.0f )
{
fT = 1.0f;
fSqrDistance = fA11 + 2.0f*fB1 + fC;
}
else if( fB1 >= 0.0f )
{
fT = 0.0f;
fSqrDistance = fC;
}
else
{
fT = -fB1/fA11;
fSqrDistance = fB1*fT + fC;
}
}
}
else if( fT < 0.0f ) // region 6
{
fTmp0 = fA01 + fB1;
fTmp1 = fA00 + fB0;
if( fTmp1 > fTmp0 )
{
fNumer = fTmp1 - fTmp0;
fDenom = fA00 - 2.0f*fA01 + fA11;
if( fNumer >= fDenom )
{
fT = 1.0f;
fS = 0.0f;
fSqrDistance = fA11 + 2.0f*fB1 + fC;
}
else
{
fT = fNumer/fDenom;
fS = 1.0f - fT;
fSqrDistance = fS*(fA00*fS + fA01*fT + 2.0f*fB0) +
fT*(fA01*fS + fA11*fT + 2.0f*fB1) + fC;
}
}
else
{
fT = 0.0f;
if( fTmp1 <= 0.0f )
{
fS = 1.0f;
fSqrDistance = fA00 + 2.0f*fB0 + fC;
}
else if( fB0 >= 0.0f )
{
fS = 0.0f;
fSqrDistance = fC;
}
else
{
fS = -fB0/fA00;
fSqrDistance = fB0*fS + fC;
}
}
}
else // region 1
{
fNumer = fA11 + fB1 - fA01 - fB0;
if( fNumer <= 0.0f )
{
fS = 0.0f;
fT = 1.0f;
fSqrDistance = fA11 + 2.0f*fB1 + fC;
}
else
{
fDenom = fA00 - 2.0f*fA01 + fA11;
if( fNumer >= fDenom )
{
fS = 1.0f;
fT = 0.0f;
fSqrDistance = fA00 + 2.0f*fB0 + fC;
}
else
{
fS = fNumer/fDenom;
fT = 1.0f - fS;
fSqrDistance = fS*(fA00*fS + fA01*fT + 2.0f*fB0) +
fT*(fA01*fS + fA11*fT + 2.0f*fB1) + fC;
}
}
}
}
// account for numerical round-off error
if( fSqrDistance < 0.0f )
{
fSqrDistance = 0.0f;
}
m_ClosestPoint0 = *m_pVector;
m_ClosestPoint1 = m_pTriangle->V[0] + fS*vec3fEdge0 + fT*vec3fEdge1;
m_afTriangleBary[1] = fS;
m_afTriangleBary[2] = fT;
m_afTriangleBary[0] = 1.0f - fS - fT;
return fSqrDistance;
}
//----------------------------------------------------------------------------
float SEDistVector3Triangle3f::Get(float fT, const SEVector3f& rVelocity0,
const SEVector3f& rVelocity1)
{
SEVector3f vec3fMVector = *m_pVector + fT*rVelocity0;
SEVector3f vec3fMV0 = m_pTriangle->V[0] + fT*rVelocity1;
SEVector3f vec3fMV1 = m_pTriangle->V[1] + fT*rVelocity1;
SEVector3f vec3fMV2 = m_pTriangle->V[2] + fT*rVelocity1;
SETriangle3f tempMTriangle(vec3fMV0, vec3fMV1, vec3fMV2);
return SEDistVector3Triangle3f(vec3fMVector, tempMTriangle).Get();
}
//----------------------------------------------------------------------------
float SEDistVector3Triangle3f::GetSquared(float fT, const SEVector3f&
rVelocity0, const SEVector3f& rVelocity1)
{
SEVector3f vec3fMVector = *m_pVector + fT*rVelocity0;
SEVector3f vec3fMV0 = m_pTriangle->V[0] + fT*rVelocity1;
SEVector3f vec3fMV1 = m_pTriangle->V[1] + fT*rVelocity1;
SEVector3f vec3fMV2 = m_pTriangle->V[2] + fT*rVelocity1;
SETriangle3f tempMTriangle(vec3fMV0, vec3fMV1, vec3fMV2);
return SEDistVector3Triangle3f(vec3fMVector, tempMTriangle).GetSquared();
}
//----------------------------------------------------------------------------
float SEDistVector3Triangle3f::GetTriangleBary(int i) const
{
SE_ASSERT( 0 <= i && i < 3 );
return m_afTriangleBary[i];
}
//----------------------------------------------------------------------------
| [
"[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac"
]
| [
[
[
1,
319
]
]
]
|
d872f4473e4af0097ef1995879cf9bdf8468ee8a | 1e976ee65d326c2d9ed11c3235a9f4e2693557cf | /Database/SQLManager.h | a71217679a0da81da8a19ddee8436a796d7871b0 | []
| no_license | outcast1000/Jaangle | 062c7d8d06e058186cb65bdade68a2ad8d5e7e65 | 18feb537068f1f3be6ecaa8a4b663b917c429e3d | refs/heads/master | 2020-04-08T20:04:56.875651 | 2010-12-25T10:44:38 | 2010-12-25T10:44:38 | 19,334,292 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,012 | h | // /*
// *
// * Copyright (C) 2003-2010 Alexandros Economou
// *
// * This file is part of Jaangle (http://www.jaangle.com)
// *
// * This Program is free software; you can redistribute it and/or modify
// * it under the terms of the GNU General Public License as published by
// * the Free Software Foundation; either version 2, or (at your option)
// * any later version.
// *
// * This Program is distributed in the hope that it will be useful,
// * but WITHOUT ANY WARRANTY; without even the implied warranty of
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// * GNU General Public License for more details.
// *
// * You should have received a copy of the GNU General Public License
// * along with GNU Make; see the file COPYING. If not, write to
// * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
// * http://www.gnu.org/copyleft/gpl.html
// *
// */
#ifndef _SQLManager_h_
#define _SQLManager_h_
#include "DataRecords.h"
#include "TracksFilter.h"
#include "TagInfo.h"
class ADODatabase;
class ADORecordset;
static const TCHAR* const TS_UnknownString = _T("[Unknown]");
class SQLManager
{
public:
#ifdef _UNITTESTING
static BOOL UnitTest();
#endif
public:
SQLManager():m_pDB(NULL) {}
virtual ~SQLManager();
BOOL Init(LPCTSTR DatabasePath);
//BOOL TrackRecordCollectionByCollectionID(TrackRecordCollection& col, UINT collectionID);
//=======================Public Utilities
INT AddNewTrackFromTagInfo(UINT collectionID, LPCTSTR location, TagInfo& info);
BOOL UpdateTrackFromTagInfo(UINT ID, UINT collectionID, LPCTSTR location, TagInfo& info);
//===============AddNew-Xxx-Record: Adds a new Xxx record
//REQUIRE: xxx with ID==0 && name != "" && foreign keys valid
//RETURN: FALSE if xxx exists || failure
// TRUE on success. Modifies ID with the new ID
BOOL AddNewTrackRecord(TrackRecord& rec);
BOOL AddNewAlbumRecord(AlbumRecord& rec);
BOOL AddNewArtistRecord(ArtistRecord& rec);
BOOL AddNewGenreRecord(GenreRecord& rec);
//BOOL AddNewInfoRecord(InfoRecord& rec);
BOOL AddNewCollectionRecord(CollectionRecord& rec);
BOOL AddNewHistTrackRecord(HistTrackRecord& rec);
BOOL AddNewHistLogRecord(HistLogRecord& rec);
BOOL AddNewHistArtistRecord(HistArtistRecord& rec);
//===============Update-Xxx-Record: Updates a Xxx record
//REQUIRE: xxx with ID!=0 && name != "" && foreign keys valid
//RETURN: FALSE on failure
// TRUE on success.
BOOL UpdateTrackRecord(TrackRecord& rec);
BOOL UpdateAlbumRecord(AlbumRecord& rec, BOOL bForce);
BOOL UpdateArtistRecord(ArtistRecord& rec, BOOL bForce);
BOOL UpdateGenreRecord(GenreRecord& rec, BOOL bForce);
//BOOL UpdateInfoRecord(InfoRecord& rec);
BOOL UpdateCollectionRecord(CollectionRecord& rec);
BOOL UpdateHistTrackRecord(HistTrackRecord& rec);
BOOL UpdateHistLogRecord(HistLogRecord& rec);
BOOL UpdateHistArtistRecord(HistArtistRecord& rec);
//Add/Update/Deletes automatically. It may modify the rec.ID
//BOOL AdjustInfoRecord(InfoRecord& rec);
//===============Get-Xxx-Record: Gets a record from ID
//REQUIRE: ID!=0
//RETURN: FALSE if xxx does not exists || failure
// TRUE on success.
BOOL GetTrackRecord(UINT ID, TrackRecord& rec);
BOOL GetAlbumRecord(UINT ID, AlbumRecord& rec);
BOOL GetArtistRecord(UINT ID, ArtistRecord& rec);
BOOL GetGenreRecord(UINT ID, GenreRecord& rec);
//BOOL GetInfoRecord(UINT ID, InfoRecord& rec);
BOOL GetCollectionRecord(UINT ID, CollectionRecord& rec);
BOOL GetHistTrackRecord(UINT ID, HistTrackRecord& rec);
BOOL GetHistArtistRecord(UINT ID, HistArtistRecord& rec);
BOOL GetHistLogRecord(UINT ID, HistLogRecord& rec);
//BOOL GetInfoRecordRequestRecord(InfoRecordRequest& rec);//rec.parID && rec.infoType
BOOL GetPicRecord(PicRecord& rec);
BOOL AddOrUpdatePicRecord(PicRecord& rec);
BOOL DeletePicRecord(InfoItemTypeEnum infoType, UINT parID);
BOOL DeleteInfoRequestsOlderThan(UINT timeStampLimit);
BOOL GetInfoRequests(std::set<UINT>& requestSet);
BOOL AddInfoRequest(UINT timeStamp, UINT hash);
//BOOL DeleteInfoRecordResult(UINT ID, InfoItemTypeEnum iit);
BOOL GetFullTrackRecordByID(FullTrackRecordSP& rec, UINT id);
BOOL GetFullAlbumRecordByID(FullAlbumRecordSP& rec, UINT id);
BOOL GetFullArtistRecordByID(FullArtistRecordSP& rec, UINT id);
//===============Get-Xxx-RecordUnique: Gets a record from ID
//REQUIRE: ID!=0
//RETURN: FALSE if xxx does not exists || failure
// TRUE on success.
BOOL GetTrackRecordUnique(UINT colID, LPCTSTR location, TrackRecord& rec);
BOOL GetAlbumRecordUnique(UINT artID, LPCTSTR name, AlbumRecord& rec);
BOOL GetArtistRecordUnique(LPCTSTR name, ArtistRecord& rec);
BOOL GetGenreRecordUnique(LPCTSTR name, GenreRecord& rec);
BOOL GetCollectionRecordUnique(UINT serial, LPCTSTR location, CollectionRecord& rec);
BOOL GetHistTrackRecordUnique(UINT artID, LPCTSTR name, HistTrackRecord& rec);
BOOL GetHistArtistRecordUnique(LPCTSTR name, HistArtistRecord& rec);
//===============Get-Xxx-UD: Gets the ID
//REQUIRE: ...
//RETURN: 0 if xxx does not exists || failure
// Database ID on success.
UINT GetTrackID(UINT colID, LPCTSTR location);
UINT GetAlbumID(UINT artID, LPCTSTR name);
UINT GetArtistID(LPCTSTR name);
UINT GetGenreID(LPCTSTR name);
UINT GetCollectionID(UINT serial, LPCTSTR location);
UINT GetHistTrackID(UINT artID, LPCTSTR name);
UINT GetHistArtistID(LPCTSTR name);
//===============Xxx-RecordExists: Test if a record exist
//REQUIRE: ID!=0
//RETURN: FALSE if xxx does not exists || failure
// TRUE on success.
BOOL TrackRecordExists(UINT ID);
BOOL AlbumRecordExists(UINT ID);
BOOL ArtistRecordExists(UINT ID);
BOOL GenreRecordExists(UINT ID);
//BOOL InfoRecordExists(UINT ID);
BOOL CollectionRecordExists(UINT ID);
BOOL HistTrackRecordExists(UINT ID);
BOOL HistArtistRecordExists(UINT ID);
BOOL HistLogRecordExists(UINT ID);
//===============Delete-Xxx-Record: Deletes
//REQUIRE: ID!=0
//RETURN: FALSE if xxx does not exists || failure
// TRUE on success.
BOOL DeleteTrackRecord(UINT ID);
BOOL DeleteAlbumRecord(UINT ID);
BOOL DeleteArtistRecord(UINT ID);
BOOL DeleteGenreRecord(UINT ID);
//===DeleteInfoRecord Force will also delete the associated Tracks
BOOL DeleteCollectionRecord(UINT ID, BOOL bForce);
//===DeleteCollectionRecord Force will also reset the Tracks/Albums/Artists info flags
//BOOL DeleteInfoRecord(UINT ID);
BOOL DeleteHistLogRecord(UINT ID);
//====CONTRACTS for Updates
//1. WHEN artist.ID = 0;
// REQUEST: "Add the record (if does not exist)"
// POSSIBLE RESULTS: (UR_Error)"Failure" ---record is not modified
// (UR_DataAdded)"Added OK" ---record is not modified
// (UR_DataMerged)"Same name (unique) exists." ---Record.ID gets the value of the existing record
// * "Other Record fields has been ignored"
//2. When artist.ID > 0;
// REQUEST: "Update the record with ID to the new fields"
// POSSIBLE RESULTS: (UR_Error)"Failure" ---record is not modified
// (UR_DataUpdated)"Updated OK" ---record is not modified
// (UR_DataMerged)"Name (unique) has changed && New Name exists." ---Record.ID gets the value of the existing record.
// * "Other Record fields has been ignored"
//UpdateResult UpdateArtistRecord(ArtistRecord& artist);
//UpdateResult UpdateAlbumRecord(AlbumRecord& artist);
//UpdateResult UpdateGenreRecord(GenreRecord& genre);
//UpdateResult UpdateCollectionRecord(CollectionRecord& collection);
struct ChangeStyle
{
ChangeStyle():additions(0),removals(0),updates(0){}
INT additions;
INT removals;
INT updates;
};
struct Changes
{
ChangeStyle tracks;
ChangeStyle albums;
ChangeStyle artists;
ChangeStyle genres;
ChangeStyle collections;
ChangeStyle info;
};
const Changes& GetChanges() {return m_changes;}
void ResetChanges() {m_changes = Changes();}
//UpdateFullArtistRecord: May Modify the genreID || the artist ID
BOOL UpdateFullArtistRecord(FullArtistRecord& artist, BOOL bForce);
//UpdateFullAlbumRecord: May Modify the albumID || the artist ID
BOOL UpdateFullAlbumRecord(FullAlbumRecord& album, BOOL bForce);
//UpdateFullTrackRecord: May Modify ALL the foreign keys
BOOL UpdateFullTrackRecord(FullTrackRecord& track);
//BOOL InfoRecordByID(InfoRecordSP& rec, UINT id);
//BOOL GetFullTrackRecordByID(FullTrackRecordSP& rec, UINT id);
BOOL GetFullTrackRecordByLocation(FullTrackRecordSP& rec, LPCTSTR Location, UINT CollectionID = 0);
//BOOL GetFullAlbumRecordByID(FullAlbumRecordSP& rec, UINT id);
//BOOL GetFullArtistRecordByID(FullArtistRecordSP& rec, UINT id);
//====================Retrieve Collections By SQL
BOOL GetTrackRecordCollectionBySQL(TrackRecordCollection& col, LPCTSTR sql, INT limitResults = 0);
BOOL GetGenreRecordCollectionBySQL(GenreRecordCollection& col, LPCTSTR SQL);
BOOL GetCollectionRecordCollectionBySQL(CollectionRecordCollection& col, LPCTSTR SQL);
BOOL GetYearRecordCollectionBySQL(YearRecordCollection& col, LPCTSTR SQL);
BOOL GetFullTrackRecordCollectionBySQL(FullTrackRecordCollection& col, LPCTSTR SQL, INT limitResults = 0);
BOOL GetFullAlbumRecordCollectionBySQL(FullAlbumRecordCollection& col, LPCTSTR SQL);
BOOL GetFullArtistRecordCollectionBySQL(FullArtistRecordCollection& col, LPCTSTR SQL);
BOOL GetMonthAddedRecordCollectionBySQL(MonthAddedRecordCollection& col, LPCTSTR sql);
//====================Retrieve Collections By TracksFilter
BOOL GetTrackRecordCollectionByTracksFilter(TrackRecordCollection& col, TracksFilter& Filter);
BOOL GetGenreRecordCollectionByTracksFilter(GenreRecordCollection& col, TracksFilter& Filter, BOOL bCountTracks);
BOOL GetCollectionRecordCollectionByTracksFilter(CollectionRecordCollection& col, TracksFilter& Filter, BOOL bCountTracks);
BOOL GetYearRecordCollectionByTracksFilter(YearRecordCollection& col, TracksFilter& Filter, BOOL bCountTracks);
BOOL GetFullTrackRecordCollectionByTracksFilter(FullTrackRecordCollection& col, TracksFilter& Filter, INT limitResults = 0);
BOOL GetFullAlbumRecordCollectionByTracksFilter(FullAlbumRecordCollection& col, TracksFilter& Filter);
BOOL GetFullArtistRecordCollectionByTracksFilter(FullArtistRecordCollection& col, TracksFilter& Filter);
BOOL GetFullAlbumGPNRecordCollectionByTracksFilter(FullAlbumRecordCollection& col, TracksFilter& Filter);
BOOL GetMonthAddedRecordCollectionByTracksFilter(MonthAddedRecordCollection& col, TracksFilter& Filter, BOOL bCountTracks);
//====================Retrieve Collections [Special]
BOOL GetFullTrackRecordCollectionBySimpleSearch(FullTrackRecordCollection& col, LPCTSTR searchStr, INT limitResults = 0);
BOOL GetFullTrackRecordCollectionBySmartSearch(FullTrackRecordCollection& col, LPCTSTR searchStr, INT limitResults = 0);
BOOL GetFullTrackRecordCollectionByInfoLikeness(FullTrackRecordCollection& col, InfoItemTypeEnum iit, LPCTSTR searchString);
BOOL GetFullTrackRecordCollectionByLocation(FullTrackRecordCollection& col, LPCTSTR Location);
BOOL GetFullAlbumRecordCollectionByTracksFilterForCollections(FullAlbumRecordCollection& col, TracksFilter& Filter);
BOOL GetCollectionRecordCollectionByTypeID(CollectionRecordCollection& col, CollectionTypesEnum type);
//=====================Get/Set Info
//UINT GetTrackInfoID(UINT trackID, InfoItemTypeEnum iit);
//UINT GetAlbumInfoID(UINT albID, InfoItemTypeEnum iit);
//UINT GetArtistInfoID(UINT artID, InfoItemTypeEnum iit);
BOOL AddNewTrackInfo(UINT trackID, InfoItemTypeEnum iit, LPCTSTR info);
BOOL AddNewAlbumInfo(UINT albID, InfoItemTypeEnum iit, LPCTSTR info);
BOOL AddNewArtistInfo(UINT artID, InfoItemTypeEnum iit, LPCTSTR info);
BOOL UpdateTrackInfo(UINT trackID, InfoItemTypeEnum iit, LPCTSTR info);
BOOL UpdateAlbumInfo(UINT albID, InfoItemTypeEnum iit, LPCTSTR info);
BOOL UpdateArtistInfo(UINT artID, InfoItemTypeEnum iit, LPCTSTR info);
BOOL DeleteTrackInfo(UINT trackID, InfoItemTypeEnum iit);
BOOL DeleteAlbumInfo(UINT albID, InfoItemTypeEnum iit);
BOOL DeleteArtistInfo(UINT artID, InfoItemTypeEnum iit);
BOOL DeleteAllTrackInfo(UINT trackID);
BOOL DeleteAllAlbumInfo(UINT albID);
BOOL DeleteAllArtistInfo(UINT artID);
BOOL AdjustTrackInfo(UINT trackID, InfoItemTypeEnum iit, LPCTSTR info);
BOOL AdjustAlbumInfo(UINT albID, InfoItemTypeEnum iit, LPCTSTR info);
BOOL AdjustArtistInfo(UINT artID, InfoItemTypeEnum iit, LPCTSTR info);
BOOL GetTrackInfoRecord(UINT trackID, InfoItemTypeEnum iit, InfoRecord& ir);
BOOL GetAlbumInfoRecord(UINT albID, InfoItemTypeEnum iit, InfoRecord& ir);
BOOL GetArtistInfoRecord(UINT artID, InfoItemTypeEnum iit, InfoRecord& ir);
UINT GetTrackInfoFlags(UINT trackID);
//Other Statistical Info
UINT GetTrackCount(TracksFilter& tf);
BOOL GetTrackIDList(TracksFilter& tf, std::vector<UINT>& idList);
//enum RandomTrackModeEnum
//{
// RTM_All,
// RTM_Artist,
// RTM_Album,
// RTM_Genre,
// RTM_Year,
// RTM_Collection,
// RTM_Newest,
// RTM_Last
//};
//BOOL GetRandomTrackIDList(std::vector<UINT>& idList, UINT numItems, RandomTrackModeEnum rtm, UINT rtmHelperID, UINT avoidID, UINT minRating);
BOOL GetFullLogRecordCollection(FullHistLogRecordCollection& col,
SYSTEMTIME* startDate/* = NULL*/,
SYSTEMTIME* endDate /*= NULL*/,
TCHAR* ArtistFilter /*= NULL*/,
TCHAR* TrackFilter /*= NULL*/,
HistoryLogActionsEnum actID,
UINT limitResults /*= 0*/);
BOOL GetFullHistTrackRecordCollection(FullHistTrackRecordCollection& col,
SYSTEMTIME* startDate/* = NULL*/,
SYSTEMTIME* endDate /*= NULL*/,
TCHAR* ArtistFilter /*= NULL*/,
TCHAR* TrackFilter /*= NULL*/,
HistoryLogActionsEnum actID,
UINT limitResults /*= 0*/);
BOOL GetFullHistArtistRecordCollection(FullHistArtistRecordCollection& col,
SYSTEMTIME* startDate/* = NULL*/,
SYSTEMTIME* endDate /*= NULL*/,
TCHAR* ArtistFilter /*= NULL*/,
TCHAR* TrackFilter /*= NULL*/,
HistoryLogActionsEnum actID,
UINT limitResults /*= 0*/);
struct Rank
{
UINT Hits;
UINT HitsCount;
};
BOOL GetHistTrackRankCollection(std::vector<Rank>& col);
BOOL GetHistArtistRankCollection(std::vector<Rank>& col);
BOOL LogTrackInHistory(LPCTSTR Artist, LPCTSTR Track, HistoryLogActionsEnum actID, SYSTEMTIME& localTime);
struct HistoryLogStats
{
HistoryLogStats():actions(0),plays(0)
{
memset(&firstTime, 0, sizeof(SYSTEMTIME));
memset(&lastTime, 0, sizeof(SYSTEMTIME));
}
UINT actions;
UINT plays;
SYSTEMTIME firstTime;
SYSTEMTIME lastTime;
};
BOOL GetHistoryLogStats(HistoryLogStats& stats);
struct HistoryTrackStats
{
HistoryTrackStats():rank(0),hits(0)
{
memset(&firstTime, 0, sizeof(SYSTEMTIME));
memset(&lastTime, 0, sizeof(SYSTEMTIME));
}
UINT rank;
UINT hits;
SYSTEMTIME firstTime;
SYSTEMTIME lastTime;
};
BOOL GetHistoryTrackStats(LPCTSTR Artist, LPCTSTR Track, SYSTEMTIME* startDate, SYSTEMTIME* endDate,//IN
HistoryTrackStats& stats);//OUT
BOOL GetVirtualTrackCollectionRecord(CollectionRecord& cr);
struct ValuedID
{
ValuedID(UINT artid, DOUBLE val):ID(artid),value(val),appearanceCount(1){}
UINT ID;
DOUBLE value;
UINT appearanceCount;
};
BOOL GetSimilarArtists(std::vector<ValuedID>& col, UINT artistID, INT maxTagsToExamine = 5, INT maxArtistsPerGenreToExamine = 5);
//BOOL UpdateTrack(FullTrackRecordSP track);
private:
//BOOL GetInfo(LPCTSTR fldName, LPCTSTR tblName, InfoItemTypeEnum iit, UINT ID, InfoRecord& rec);
//BOOL SetInfo(LPCTSTR fldName, LPCTSTR tblName, InfoItemTypeEnum iit, UINT ID, LPCTSTR info);
BOOL RecordExists(LPCTSTR sql, UINT ID);
void AddSQLStrParameter(CString& ret, TextMatch tm, LPCTSTR str);
void AddSQLNumParameter(CString& ret, NumericMatch nm, LPCTSTR str);
void AddSQLCountParameter(CString& ret, NumericMatch nm, LPCTSTR fieldName);
void AddSQLDateParameter(CString& ret, DateMatch dm, LPCTSTR str);
CString GetWhereSQL(TracksFilter& Filter);
CString GetHavingSQL(NumericMatch nm);
static UINT FixStringField(LPCTSTR source, LPTSTR dest, UINT destLen);
static void GetSQLDateForQueries(SYSTEMTIME& input, LPTSTR bf, UINT bfLen);
//Appends the data from the current recordset (current position) to rec.
//Requests recordset fields using their index starting from fieldID
void GetTrackRecordFields(TrackRecord& rec, ADORecordset& rs, short& startIdx);
BOOL SetTrackRecordFields(TrackRecord& rec, ADORecordset& rs);
void GetAlbumRecordFields(AlbumRecord& rec, ADORecordset& rs, short& startIdx);
BOOL SetAlbumRecordFields(AlbumRecord& rec, ADORecordset& rs);
void GetArtistRecordFields(ArtistRecord& rec, ADORecordset& rs, short& startIdx);
BOOL SetArtistRecordFields(ArtistRecord& rec, ADORecordset& rs);
void GetGenreRecordFields(GenreRecord& rec, ADORecordset& rs, short& startIdx);
BOOL SetGenreRecordFields(GenreRecord& rec, ADORecordset& rs);
void GetCollectionRecordFields(CollectionRecord& rec, ADORecordset& rs, short& startIdx);
BOOL SetCollectionRecordFields(CollectionRecord& rec, ADORecordset& rs);
//void GetInfoRecordFields(InfoRecord& rec, ADORecordset& rs, short& startIdx);
//BOOL SetInfoRecordFields(InfoRecord& rec, ADORecordset& rs);
void GetHistArtistRecordFields(HistArtistRecord& rec, ADORecordset& rs, short& startIdx);
void GetHistLogRecordFields(HistLogRecord& rec, ADORecordset& rs, short& startIdx);
void GetHistTrackRecordFields(HistTrackRecord& rec, ADORecordset& rs, short& startIdx);
BOOL GetFirstVal(LPCTSTR sql, INT& val);
void AddSmartSearchCondition(std::tstring& SQL, LPCTSTR condition);
BOOL EvaluateTrackInfo(InfoItemTypeEnum iit);
BOOL EvaluateAlbumInfo(InfoItemTypeEnum iit);
BOOL EvaluateArtistInfo(InfoItemTypeEnum iit);
//UINT GetInfoID(LPCTSTR tblName, LPCTSTR fldName, UINT ID, InfoItemTypeEnum iit);
BOOL AddNewInfo(LPCTSTR tblName, LPCTSTR fldName, UINT ID, InfoItemTypeEnum iit, LPCTSTR info);
//===================================COLLECTIONS
//BOOL GetCollectionRecord(CollectionRecord& collection, UINT ID);
//BOOL GetCollectionRecordUnique(CollectionRecord& genre, LPCTSTR location, UINT serial);
//===================================GENRES
//BOOL GetGenreRecord(GenreRecord& genre, UINT ID);
//BOOL GetGenreRecordUnique(GenreRecord& genre, LPCTSTR name);
//===================================ARTISTS
//BOOL GetArtistRecordUnique(ArtistRecord& artist, LPCTSTR name);
//===================================ALBUMS
//BOOL AddNewAlbumRecord(AlbumRecord& album);
//BOOL GetAlbumRecordUnique(AlbumRecord& album, LPCTSTR name, UINT artID);
//BOOL SetCollectionRecordFields(CollectionRecord& collection, ADORecordset& rs);
private:
ADODatabase* m_pDB;
Changes m_changes;
};
#endif
| [
"outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678"
]
| [
[
[
1,
472
]
]
]
|
d9b4e7df2ca55cf0e5374f2842e70525b6cd2ee3 | f2cbdee1dfdcad7b77c597e1af5f40ad83bad4aa | /MyJava/JRex/src/native/jni/dom/html2/org_mozilla_jrex_dom_html2_JRexHTMLScriptElementImpl.cpp | 3e9ef825bcc81bbd9fa7e543ad731a4d01a996d4 | []
| no_license | jdouglas71/Examples | d03d9effc414965991ca5b46fbcf808a9dd6fe6d | b7829b131581ea3a62cebb2ae35571ec8263fd61 | refs/heads/master | 2021-01-18T14:23:56.900005 | 2011-04-07T19:34:04 | 2011-04-07T19:34:04 | 1,578,581 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 12,626 | cpp | /* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Contributor(s):
* C.N Medappa <[email protected]><>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the NPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "org_mozilla_jrex_dom_html2_JRexHTMLScriptElementImpl.h"
#include "JRexDOMGlobals.h"
//event types for JRexHTMLScriptElement
enum JRexHTMLScriptElementEventTypes{ JREX_GET_TEXT=0U,
JREX_SET_TEXT,
JREX_GET_HTML_FOR,
JREX_SET_HTML_FOR,
JREX_GET_EVENT,
JREX_SET_EVENT,
JREX_GET_CHARSET,
JREX_SET_CHARSET,
JREX_GET_DEFER,
JREX_SET_DEFER,
JREX_GET_SRC,
JREX_SET_SRC,
JREX_GET_TYPE,
JREX_SET_TYPE };
static void* PR_CALLBACK HandleJRexHTMLScriptElementEvent(PLEvent* aEvent);
static void PR_CALLBACK DestroyJRexHTMLScriptElementEvent(PLEvent* aEvent);
/*
* Class: org_mozilla_jrex_dom_html2_JRexHTMLScriptElementImpl
* Method: GetText
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_org_mozilla_jrex_dom_html2_JRexHTMLScriptElementImpl_GetText
(JNIEnv *env, jobject jhtmlEle){
GET_DOM_STRING_JNI(env , jhtmlEle, HTMLScriptElement, GetText, JREX_GET_TEXT, JRexDOMGlobals::nodePeerID, PR_FALSE)
}
/*
* Class: org_mozilla_jrex_dom_html2_JRexHTMLScriptElementImpl
* Method: SetText
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_org_mozilla_jrex_dom_html2_JRexHTMLScriptElementImpl_SetText
(JNIEnv *env, jobject jhtmlEle, jstring jvalue){
SET_DOM_STRING_JNI(env , jhtmlEle, jvalue, HTMLScriptElement, SetText, JREX_SET_TEXT, JRexDOMGlobals::nodePeerID, PR_FALSE)
}
/*
* Class: org_mozilla_jrex_dom_html2_JRexHTMLScriptElementImpl
* Method: GetHtmlFor
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_org_mozilla_jrex_dom_html2_JRexHTMLScriptElementImpl_GetHtmlFor
(JNIEnv *env, jobject jhtmlEle){
GET_DOM_STRING_JNI(env , jhtmlEle, HTMLScriptElement, GetHtmlFor, JREX_GET_HTML_FOR, JRexDOMGlobals::nodePeerID, PR_FALSE)
}
/*
* Class: org_mozilla_jrex_dom_html2_JRexHTMLScriptElementImpl
* Method: SetHtmlFor
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_org_mozilla_jrex_dom_html2_JRexHTMLScriptElementImpl_SetHtmlFor
(JNIEnv *env, jobject jhtmlEle, jstring jvalue){
SET_DOM_STRING_JNI(env , jhtmlEle, jvalue, HTMLScriptElement, SetHtmlFor, JREX_SET_HTML_FOR, JRexDOMGlobals::nodePeerID, PR_FALSE)
}
/*
* Class: org_mozilla_jrex_dom_html2_JRexHTMLScriptElementImpl
* Method: GetEvent
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_org_mozilla_jrex_dom_html2_JRexHTMLScriptElementImpl_GetEvent
(JNIEnv *env, jobject jhtmlEle){
GET_DOM_STRING_JNI(env , jhtmlEle, HTMLScriptElement, GetEvent, JREX_GET_EVENT, JRexDOMGlobals::nodePeerID, PR_FALSE)
}
/*
* Class: org_mozilla_jrex_dom_html2_JRexHTMLScriptElementImpl
* Method: SetEvent
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_org_mozilla_jrex_dom_html2_JRexHTMLScriptElementImpl_SetEvent
(JNIEnv *env, jobject jhtmlEle, jstring jvalue){
SET_DOM_STRING_JNI(env , jhtmlEle, jvalue, HTMLScriptElement, SetEvent, JREX_SET_EVENT, JRexDOMGlobals::nodePeerID, PR_FALSE)
}
/*
* Class: org_mozilla_jrex_dom_html2_JRexHTMLScriptElementImpl
* Method: GetCharset
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_org_mozilla_jrex_dom_html2_JRexHTMLScriptElementImpl_GetCharset
(JNIEnv *env, jobject jhtmlEle){
GET_DOM_STRING_JNI(env , jhtmlEle, HTMLScriptElement, GetCharset, JREX_GET_CHARSET, JRexDOMGlobals::nodePeerID, PR_FALSE)
}
/*
* Class: org_mozilla_jrex_dom_html2_JRexHTMLScriptElementImpl
* Method: SetCharset
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_org_mozilla_jrex_dom_html2_JRexHTMLScriptElementImpl_SetCharset
(JNIEnv *env, jobject jhtmlEle, jstring jvalue){
SET_DOM_STRING_JNI(env , jhtmlEle, jvalue, HTMLScriptElement, SetCharset, JREX_SET_CHARSET, JRexDOMGlobals::nodePeerID, PR_FALSE)
}
/*
* Class: org_mozilla_jrex_dom_html2_JRexHTMLScriptElementImpl
* Method: GetDefer
* Signature: ()Z
*/
JNIEXPORT jboolean JNICALL Java_org_mozilla_jrex_dom_html2_JRexHTMLScriptElementImpl_GetDefer
(JNIEnv *env, jobject jhtmlEle){
GET_DOM_BOOL_JNI(env , jhtmlEle, HTMLScriptElement, GetDefer, JREX_GET_DEFER, JRexDOMGlobals::nodePeerID, PR_FALSE)
}
/*
* Class: org_mozilla_jrex_dom_html2_JRexHTMLScriptElementImpl
* Method: SetDefer
* Signature: (Z)V
*/
JNIEXPORT void JNICALL Java_org_mozilla_jrex_dom_html2_JRexHTMLScriptElementImpl_SetDefer
(JNIEnv *env, jobject jhtmlEle, jboolean jvalue){
SET_DOM_BOOL_JNI(env , jhtmlEle, jvalue, HTMLScriptElement, SetDefer, JREX_SET_DEFER, JRexDOMGlobals::nodePeerID, PR_FALSE)
}
/*
* Class: org_mozilla_jrex_dom_html2_JRexHTMLScriptElementImpl
* Method: GetSrc
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_org_mozilla_jrex_dom_html2_JRexHTMLScriptElementImpl_GetSrc
(JNIEnv *env, jobject jhtmlEle){
GET_DOM_STRING_JNI(env , jhtmlEle, HTMLScriptElement, GetSrc, JREX_GET_SRC, JRexDOMGlobals::nodePeerID, PR_FALSE)
}
/*
* Class: org_mozilla_jrex_dom_html2_JRexHTMLScriptElementImpl
* Method: SetSrc
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_org_mozilla_jrex_dom_html2_JRexHTMLScriptElementImpl_SetSrc
(JNIEnv *env, jobject jhtmlEle, jstring jvalue){
SET_DOM_STRING_JNI(env , jhtmlEle, jvalue, HTMLScriptElement, SetSrc, JREX_SET_SRC, JRexDOMGlobals::nodePeerID, PR_FALSE)
}
/*
* Class: org_mozilla_jrex_dom_html2_JRexHTMLScriptElementImpl
* Method: GetType
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_org_mozilla_jrex_dom_html2_JRexHTMLScriptElementImpl_GetType
(JNIEnv *env, jobject jhtmlEle){
GET_DOM_STRING_JNI(env , jhtmlEle, HTMLScriptElement, GetType, JREX_GET_TYPE, JRexDOMGlobals::nodePeerID, PR_FALSE)
}
/*
* Class: org_mozilla_jrex_dom_html2_JRexHTMLScriptElementImpl
* Method: SetType
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_org_mozilla_jrex_dom_html2_JRexHTMLScriptElementImpl_SetType
(JNIEnv *env, jobject jhtmlEle, jstring jvalue){
SET_DOM_STRING_JNI(env , jhtmlEle, jvalue, HTMLScriptElement, SetType, JREX_SET_TYPE, JRexDOMGlobals::nodePeerID, PR_FALSE)
}
void* PR_CALLBACK HandleJRexHTMLScriptElementEvent(PLEvent* aEvent){
if(!JRexDOMGlobals::sIntialized)return nsnull;
JRexBasicEvent* event = NS_REINTERPRET_CAST(JRexBasicEvent*, aEvent);
nsresult rv=NS_OK;
JREX_LOGLN("HandleJRexHTMLScriptElementEvent()--> **** target <"<<event->target<<"> ****")
nsCOMPtr<nsIDOMHTMLScriptElement> ele(do_QueryInterface(NS_REINTERPRET_CAST(nsISupports*, event->target)));
switch(event->eventType){
case JREX_GET_TEXT:
{
JREX_LOGLN("HandleJRexHTMLScriptElementEvent JREX_GET_TEXT EVENT!!!****")
JREX_JNI_UTIL::JRexCommonJRV *jrv=NULL;
GET_DOM_STRING_EQT(NULL, ele.get(), GetText, jrv)
return (void*)jrv;
}
case JREX_SET_TEXT:
{
JREX_LOGLN("HandleJRexHTMLScriptElementEvent JREX_SET_TEXT EVENT!!!****")
JREX_JNI_UTIL::JRexCommonJRV *jrv=NULL;
PRUnichar* value = NS_REINTERPRET_CAST(PRUnichar*, event->eventData);
SET_DOM_STRING_EQT(value, ele.get(), SetText, jrv)
return (void*)jrv;
}
case JREX_GET_HTML_FOR:
{
JREX_LOGLN("HandleJRexHTMLScriptElementEvent JREX_GET_HTML_FOR EVENT!!!****")
JREX_JNI_UTIL::JRexCommonJRV *jrv=NULL;
GET_DOM_STRING_EQT(NULL, ele.get(), GetHtmlFor, jrv)
return (void*)jrv;
}
case JREX_SET_HTML_FOR:
{
JREX_LOGLN("HandleJRexHTMLScriptElementEvent JREX_SET_HTML_FOR EVENT!!!****")
JREX_JNI_UTIL::JRexCommonJRV *jrv=NULL;
PRUnichar* value = NS_REINTERPRET_CAST(PRUnichar*, event->eventData);
SET_DOM_STRING_EQT(value, ele.get(), SetHtmlFor, jrv)
return (void*)jrv;
}
case JREX_GET_EVENT:
{
JREX_LOGLN("HandleJRexHTMLScriptElementEvent JREX_GET_EVENT EVENT!!!****")
JREX_JNI_UTIL::JRexCommonJRV *jrv=NULL;
GET_DOM_STRING_EQT(NULL, ele.get(), GetHtmlFor, jrv)
return (void*)jrv;
}
case JREX_SET_EVENT:
{
JREX_LOGLN("HandleJRexHTMLScriptElementEvent JREX_SET_EVENT EVENT!!!****")
JREX_JNI_UTIL::JRexCommonJRV *jrv=NULL;
PRUnichar* value = NS_REINTERPRET_CAST(PRUnichar*, event->eventData);
SET_DOM_STRING_EQT(value, ele.get(), SetEvent, jrv)
return (void*)jrv;
}
case JREX_GET_CHARSET:
{
JREX_LOGLN("HandleJRexHTMLScriptElementEvent JREX_GET_CHARSET EVENT!!!****")
JREX_JNI_UTIL::JRexCommonJRV *jrv=NULL;
GET_DOM_STRING_EQT(NULL, ele.get(), GetCharset, jrv)
return (void*)jrv;
}
case JREX_SET_CHARSET:
{
JREX_LOGLN("HandleJRexHTMLScriptElementEvent JREX_SET_CHARSET EVENT!!!****")
JREX_JNI_UTIL::JRexCommonJRV *jrv=NULL;
PRUnichar* value = NS_REINTERPRET_CAST(PRUnichar*, event->eventData);
SET_DOM_STRING_EQT(value, ele.get(), SetCharset, jrv)
return (void*)jrv;
}
case JREX_GET_DEFER:
{
JREX_LOGLN("HandleJRexHTMLScriptElementEvent JREX_GET_DEFER EVENT!!!****")
JREX_JNI_UTIL::JRexCommonJRV *jrv=NULL;
GET_DOM_BOOL_EQT(NULL, ele.get(), GetDefer, jrv)
return (void*)jrv;
}
case JREX_SET_DEFER:
{
JREX_LOGLN("HandleJRexHTMLScriptElementEvent JREX_SET_DEFER EVENT!!!****")
JREX_JNI_UTIL::JRexCommonJRV *jrv=NULL;
PRBool value = NS_REINTERPRET_CAST(PRBool, event->eventData);
SET_DOM_BOOL_EQT(value, ele.get(), SetDefer, jrv)
return (void*)jrv;
}
case JREX_GET_SRC:
{
JREX_LOGLN("HandleJRexHTMLScriptElementEvent JREX_GET_SRC EVENT!!!****")
JREX_JNI_UTIL::JRexCommonJRV *jrv=NULL;
GET_DOM_STRING_EQT(NULL, ele.get(), GetSrc, jrv)
return (void*)jrv;
}
case JREX_SET_SRC:
{
JREX_LOGLN("HandleJRexHTMLScriptElementEvent JREX_SET_SRC EVENT!!!****")
JREX_JNI_UTIL::JRexCommonJRV *jrv=NULL;
PRUnichar* value = NS_REINTERPRET_CAST(PRUnichar*, event->eventData);
SET_DOM_STRING_EQT(value, ele.get(), SetSrc, jrv)
return (void*)jrv;
}
case JREX_GET_TYPE:
{
JREX_LOGLN("HandleJRexHTMLScriptElementEvent JREX_GET_TYPE EVENT!!!****")
JREX_JNI_UTIL::JRexCommonJRV *jrv=NULL;
GET_DOM_STRING_EQT(NULL, ele.get(), GetType, jrv)
return (void*)jrv;
}
case JREX_SET_TYPE:
{
JREX_LOGLN("HandleJRexHTMLScriptElementEvent JREX_SET_TYPE EVENT!!!****")
JREX_JNI_UTIL::JRexCommonJRV *jrv=NULL;
PRUnichar* value = NS_REINTERPRET_CAST(PRUnichar*, event->eventData);
SET_DOM_STRING_EQT(value, ele.get(), SetType, jrv)
return (void*)jrv;
}
default:
{
JREX_LOGLN("HandleJRexHTMLScriptElementEvent()--> **** EVENT TYPE<"<<event->eventType<<"> not handled!!! ****")
}
}
JREX_LOGLN("HandleJRexHTMLScriptElementEvent()--> **** returning rv<"<<rv<<"> ****")
return (void*)rv;
}
void PR_CALLBACK DestroyJRexHTMLScriptElementEvent(PLEvent* aEvent){
JRexBasicEvent* event = NS_REINTERPRET_CAST( JRexBasicEvent*, aEvent);
JREX_LOGLN("DestroyJRexHTMLScriptElementEvent()--> **** target <"<<event->target<<"> ****")
delete event;
} | [
"[email protected]"
]
| [
[
[
1,
347
]
]
]
|
df69923032b6c1116c0999ace674b0e802b4e3fc | 550e17ad61efc7bea2066db5844663c8b5835e4f | /Examples/Tutorial/Physics/08LoadFromXML.cpp | 4ac2b6d75e44402502758117555f369747c2eac3 | []
| no_license | danguilliams/OpenSGToolbox | 9287424c66c9c4b38856cf749a311f15d8aac4f0 | 102a9fb02ad1ceeaf5784e6611c2862c4ba84d61 | refs/heads/master | 2021-01-17T23:02:36.528911 | 2010-11-01T16:56:31 | 2010-11-01T16:56:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,231 | cpp | // General OpenSG configuration, needed everywhere
#include "OSGConfig.h"
// Methods to create simple geometry: boxes, spheres, tori etc.
#include "OSGSimpleGeometry.h"
// A little helper to simplify rootNode management and interaction
#include "OSGSimpleSceneManager.h"
#include "OSGSimpleMaterial.h"
#include "OSGComponentTransform.h"
#include "OSGTransform.h"
#include "OSGTypeFactory.h"
#include "OSGFieldContainerFactory.h"
#include "OSGNameAttachment.h"
#include "OSGSceneFileHandler.h"
#include "OSGSimpleStatisticsForeground.h"
#include "OSGFCFileHandler.h"
#include "OSGContainerUtils.h"
// Input
#include "OSGKeyListener.h"
#include "OSGWindowUtils.h"
//Physics
#include "OSGPhysics.h"
// Activate the OpenSG namespace
// This is not strictly necessary, you can also prefix all OpenSG symbols
// with OSG::, but that would be a bit tedious for this example
OSG_USING_NAMESPACE
// forward declaration so we can have the interesting stuff upfront
void display(void);
void reshape(Vec2f Size);
void buildCar();
void buildTriMesh(void);
void buildSphere(void);
void buildBox(void);
// The SimpleSceneManager to manage simple applications
SimpleSceneManager *mgr;
WindowEventProducerUnrecPtr TutorialWindow;
NodeUnrecPtr TriGeometryBase;
PhysicsHandlerUnrecPtr physHandler;
PhysicsWorldUnrecPtr physicsWorld;
PhysicsSpaceUnrecPtr physicsSpace;
//just for hierarchy
NodeUnrecPtr spaceGroupNode;
NodeUnrecPtr rootNode;
// Create a class to allow for the use of the Ctrl+q
class TutorialKeyListener : public KeyListener
{
public:
virtual void keyPressed(const KeyEventUnrecPtr e)
{
if(e->getKey() == KeyEvent::KEY_Q && e->getModifiers() & KeyEvent::KEY_MODIFIER_COMMAND)
{
TutorialWindow->closeWindow();
}
switch(e->getKey())
{
case KeyEvent::KEY_S:
{
buildSphere();
}
break;
case KeyEvent::KEY_B:
{
buildBox();
}
break;
case KeyEvent::KEY_Z:
{
//SceneFileHandler::the().write(rootNode, "scene.osb");
}
break;
case KeyEvent::KEY_T:
{
buildTriMesh();
}
break;
}
}
virtual void keyReleased(const KeyEventUnrecPtr e)
{
}
virtual void keyTyped(const KeyEventUnrecPtr e)
{
}
};
class TutorialMouseListener : public MouseListener
{
public:
virtual void mouseClicked(const MouseEventUnrecPtr e)
{
}
virtual void mouseEntered(const MouseEventUnrecPtr e)
{
}
virtual void mouseExited(const MouseEventUnrecPtr e)
{
}
virtual void mousePressed(const MouseEventUnrecPtr e)
{
mgr->mouseButtonPress(e->getButton(), e->getLocation().x(), e->getLocation().y());
}
virtual void mouseReleased(const MouseEventUnrecPtr e)
{
mgr->mouseButtonRelease(e->getButton(), e->getLocation().x(), e->getLocation().y());
}
};
class TutorialMouseMotionListener : public MouseMotionListener
{
public:
virtual void mouseMoved(const MouseEventUnrecPtr e)
{
mgr->mouseMove(e->getLocation().x(), e->getLocation().y());
}
virtual void mouseDragged(const MouseEventUnrecPtr e)
{
mgr->mouseMove(e->getLocation().x(), e->getLocation().y());
}
};
// Initialize GLUT & OpenSG and set up the rootNode
int main(int argc, char **argv)
{
// OSG init
osgInit(argc,argv);
// Set up Window
TutorialWindow = createNativeWindow();
TutorialWindow->initWindow();
TutorialWindow->setDisplayCallback(display);
TutorialWindow->setReshapeCallback(reshape);
TutorialKeyListener TheKeyListener;
TutorialWindow->addKeyListener(&TheKeyListener);
TutorialMouseListener TheTutorialMouseListener;
TutorialMouseMotionListener TheTutorialMouseMotionListener;
TutorialWindow->addMouseListener(&TheTutorialMouseListener);
TutorialWindow->addMouseMotionListener(&TheTutorialMouseMotionListener);
// Create the SimpleSceneManager helper
mgr = new SimpleSceneManager;
// Tell the Manager what to manage
mgr->setWindow(TutorialWindow);
//Make Base Geometry Node
TriGeometryBase = makeTorus(0.5, 1.0, 24, 24);
//Setup Physics Scene
FCFileType::FCPtrStore NewContainers;
NewContainers = FCFileHandler::the()->read(BoostPath("Data/08PhysicsData.xml"));
FCFileType::FCPtrStore::iterator Itor;
for(Itor = NewContainers.begin() ; Itor != NewContainers.end() ; ++Itor)
{
//Get Physics Handler
if( (*Itor)->getType() == PhysicsHandler::getClassType())
{
physHandler = dynamic_pointer_cast<PhysicsHandler>(*Itor);
}
//Get Physics World
if( (*Itor)->getType() == PhysicsWorld::getClassType())
{
physicsWorld=dynamic_pointer_cast<PhysicsWorld>(*Itor);
}
//Get Physics World
if( (*Itor)->getType().isDerivedFrom(PhysicsSpace::getClassType()))
{
physicsSpace = dynamic_pointer_cast<PhysicsSpace>(*Itor);
}
//Get Root Node
if( (*Itor)->getType() == Node::getClassType() &&
dynamic_pointer_cast<Node>(*Itor)->getParent() == NULL)
{
rootNode = dynamic_pointer_cast<Node>(*Itor);
}
}
commitChanges();
FCFileType::FCPtrStore SaveContainers;
SaveContainers.insert(rootNode);
FCFileHandler::the()->write(SaveContainers, BoostPath("08Output.xml"));
//Find the Physics Space Node
spaceGroupNode = dynamic_pointer_cast<Node>(getFieldContainer("Physics Space Group Node"));
std::cout << "spaceGroupNode " << spaceGroupNode << std::endl;
physHandler->attachUpdateProducer(TutorialWindow->editEventProducer());
//Create Statistics Foreground
SimpleStatisticsForegroundUnrecPtr PhysicsStatForeground = SimpleStatisticsForeground::create();
PhysicsStatForeground->setSize(25);
PhysicsStatForeground->setColor(Color4f(0,1,0,0.7));
PhysicsStatForeground->addElement(PhysicsHandler::statPhysicsTime,
"Physics time: %.3f s");
PhysicsStatForeground->addElement(PhysicsHandler::statCollisionTime,
"Collision time: %.3f s");
PhysicsStatForeground->addElement(PhysicsHandler::statSimulationTime,
"Simulation time: %.3f s");
PhysicsStatForeground->addElement(PhysicsHandler::statNCollisions,
"%d collisions");
PhysicsStatForeground->addElement(PhysicsHandler::statNCollisionTests,
"%d collision tests");
PhysicsStatForeground->addElement(PhysicsHandler::statNPhysicsSteps,
"%d simulation steps per frame");
PhysicsStatForeground->setVerticalAlign(SimpleStatisticsForeground::Center);
SimpleStatisticsForegroundUnrecPtr RenderStatForeground = SimpleStatisticsForeground::create();
RenderStatForeground->setSize(25);
RenderStatForeground->setColor(Color4f(0,1,0,0.7));
RenderStatForeground->addElement(RenderAction::statDrawTime, "Draw FPS: %r.3f");
RenderStatForeground->addElement(RenderAction::statNGeometries,
"%d Nodes drawn");
// tell the manager what to manage
mgr->setRoot (rootNode);
mgr->getWindow()->getPort(0)->addForeground(PhysicsStatForeground);
mgr->getWindow()->getPort(0)->addForeground(RenderStatForeground);
physHandler->setStatistics(PhysicsStatForeground->getCollector());
mgr->getRenderAction()->setStatCollector(RenderStatForeground->getCollector());
// show the whole rootNode
mgr->showAll();
Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f);
Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5);
TutorialWindow->openWindow(WinPos,
WinSize,
"08LoadFromXML");
//Enter main Loop
TutorialWindow->mainLoop();
osgExit();
return 0;
}
// Redraw the window
void display(void)
{
mgr->redraw();
}
// React to size changes
void reshape(Vec2f Size)
{
mgr->resize(Size.x(), Size.y());
}
//////////////////////////////////////////////////////////////////////////
//! build a box
//////////////////////////////////////////////////////////////////////////
void buildBox(void)
{
Vec3f Lengths((Real32)(rand()%2)+1.0, (Real32)(rand()%2)+1.0, (Real32)(rand()%2)+1.0);
Matrix m;
//create OpenSG mesh
GeometryUnrecPtr box;
NodeUnrecPtr boxNode = makeBox(Lengths.x(), Lengths.y(), Lengths.z(), 1, 1, 1);
box = dynamic_cast<Geometry*>(boxNode->getCore());
SimpleMaterialUnrecPtr box_mat = SimpleMaterial::create();
box_mat->setAmbient(Color3f(0.0,0.0,0.0));
box_mat->setDiffuse(Color3f(0.0,1.0 ,0.0));
box->setMaterial(box_mat);
TransformUnrecPtr boxTrans;
NodeUnrecPtr boxTransNode = makeCoredNode<Transform>(&boxTrans);
m.setIdentity();
Real32 randX = (Real32)(rand()%10)-5.0;
Real32 randY = (Real32)(rand()%10)-5.0;
m.setTranslate(randX, randY, 10.0);
boxTrans->setMatrix(m);
//create ODE data
PhysicsBodyUnrecPtr boxBody = PhysicsBody::create(physicsWorld);
boxBody->setPosition(Vec3f(randX, randY, 10.0));
boxBody->setBoxMass(1.0, Lengths.x(), Lengths.y(), Lengths.z());
PhysicsBoxGeomUnrecPtr boxGeom = PhysicsBoxGeom::create();
boxGeom->setBody(boxBody);
boxGeom->setSpace(physicsSpace);
boxGeom->setLengths(Lengths);
//add attachments
boxNode->addAttachment(boxGeom);
boxTransNode->addAttachment(boxBody);
boxTransNode->addChild(boxNode);
//add to SceneGraph
spaceGroupNode->addChild(boxTransNode);
commitChanges();
}
//////////////////////////////////////////////////////////////////////////
//! build a sphere
//////////////////////////////////////////////////////////////////////////
void buildSphere(void)
{
Real32 Radius((Real32)(rand()%2)*0.5+0.5);
Matrix m;
//create OpenSG mesh
GeometryUnrecPtr sphere;
NodeUnrecPtr sphereNode = makeSphere(2, Radius);
sphere = dynamic_cast<Geometry*>(sphereNode->getCore());
SimpleMaterialUnrecPtr sphere_mat = SimpleMaterial::create();
sphere_mat->setAmbient(Color3f(0.0,0.0,0.0));
sphere_mat->setDiffuse(Color3f(0.0,0.0,1.0));
sphere->setMaterial(sphere_mat);
TransformUnrecPtr sphereTrans;
NodeUnrecPtr sphereTransNode = makeCoredNode<Transform>(&sphereTrans);
m.setIdentity();
Real32 randX = (Real32)(rand()%10)-5.0;
Real32 randY = (Real32)(rand()%10)-5.0;
m.setTranslate(randX, randY, 10.0);
sphereTrans->setMatrix(m);
//create ODE data
PhysicsBodyUnrecPtr sphereBody = PhysicsBody::create(physicsWorld);
sphereBody->setPosition(Vec3f(randX, randY, 10.0));
sphereBody->setAngularDamping(0.0001);
sphereBody->setSphereMass(1.0,Radius);
PhysicsSphereGeomUnrecPtr sphereGeom = PhysicsSphereGeom::create();
sphereGeom->setBody(sphereBody);
sphereGeom->setSpace(physicsSpace);
sphereGeom->setRadius(Radius);
//add attachments
sphereNode->addAttachment(sphereGeom);
sphereTransNode->addAttachment(sphereBody);
sphereTransNode->addChild(sphereNode);
//add to SceneGraph
spaceGroupNode->addChild(sphereTransNode);
commitChanges();
}
//////////////////////////////////////////////////////////////////////////
//! trimesh defined by filenode will be loaded
//////////////////////////////////////////////////////////////////////////
void buildTriMesh(void)
{
//NodeUnrecPtr tri = makeTorus(0.5, 1.0, 24, 12);
//NodeUnrecPtr tri = makeBox(10.0, 10.0, 10.0, 1, 1, 1);
NodeRefPtr tri = cloneTree(TriGeometryBase);
if(tri!=NULL)
{
GeometryUnrecPtr triGeo = dynamic_cast<Geometry*>(tri->getCore());
Matrix m;
SimpleMaterialUnrecPtr tri_mat = SimpleMaterial::create();
tri_mat->setAmbient(Color3f(0.1,0.1,0.2));
tri_mat->setDiffuse(Color3f(1.0,0.1,0.7));
triGeo->setMaterial(tri_mat);
TransformUnrecPtr triTrans;
NodeUnrecPtr triTransNode = makeCoredNode<Transform>(&triTrans);
m.setIdentity();
Real32 randX = (Real32)(rand()%10)-5.0;
Real32 randY = (Real32)(rand()%10)-5.0;
m.setTranslate(randX, randY, 18.0);
triTrans->setMatrix(m);
//create ODE data
Vec3f GeometryBounds(calcMinGeometryBounds(triGeo));
PhysicsBodyUnrecPtr triBody = PhysicsBody::create(physicsWorld);
triBody->setPosition(Vec3f(randX, randY, 18.0));
triBody->setLinearDamping(0.0001);
triBody->setAngularDamping(0.0001);
triBody->setBoxMass(1.0,GeometryBounds.x(), GeometryBounds.y(), GeometryBounds.z());
PhysicsGeomUnrecPtr triGeom;
if(true)
{
triGeom = PhysicsTriMeshGeom::create();
triGeom->setBody(triBody);
//add geom to space for collision
triGeom->setSpace(physicsSpace);
//set the geometryNode to fill the ode-triMesh
NodeUnrecPtr TorusGeomNode(makeTorus(0.5, 1.0, 10, 10));
dynamic_pointer_cast<PhysicsTriMeshGeom>(triGeom)->setGeometryNode(TorusGeomNode);
}
else
{
triGeom = PhysicsBoxGeom::create();
triGeom->setBody(triBody);
triGeom->setSpace(physicsSpace);
dynamic_pointer_cast<PhysicsBoxGeom>(triGeom)->setLengths(GeometryBounds);
}
//add attachments
tri->addAttachment(triGeom);
triTransNode->addAttachment(triBody);
//add to SceneGraph
triTransNode->addChild(tri);
spaceGroupNode->addChild(triTransNode);
}
else
{
SLOG << "Could not read MeshData!" << endLog;
}
commitChanges();
}
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
67
],
[
69,
432
]
],
[
[
68,
68
]
]
]
|
9552438c4fc19a9d5552b177792c0d30aeda5ff5 | 6d9c58ba709bace54d85a9d8665288c81fd57aac | /riskyBsns/playerai.h | 8495c420a616da7dd5097e8042f18f45234ecc59 | []
| no_license | pandademonlord/gsp360midtermrisk4-28-2010 | 3136db1767285eb812a97bc9f3bbc4c4b645ea52 | f44fe4c87a41adb7216d6775f1bf67569c81e691 | refs/heads/master | 2021-01-10T20:38:19.707191 | 2010-06-26T21:14:47 | 2010-06-26T21:14:47 | 32,240,040 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,193 | h | #pragma once
#include "player.h"
#include "random.h"
class PlayerAI : public Player
{
public:
PlayerAI(short t,short id) : Player(t, id)
{}
bool isAI(){return true;}
//decide whether or not to continue to randomly attack
bool continueAttack()
{
const short maxAtkSize = 100;
const float atkRatio = .75;
short a_toAttack = random() % maxAtkSize;
if(a_toAttack < (maxAtkSize * atkRatio))
return true;
else
return false;
}
//returns ID of randomly selected un-owned territory to claim
short getClaimID(TemplateArray<Territory*> a_board)
{
short numOfValidOptions = 0;
for(int i = 0; i < a_board.size(); ++i)
{
if(a_board.get(i)->getOwner() == OWNER_NONE)
numOfValidOptions++;
}
short randTer = random() % numOfValidOptions;
short counter = 0;
for(int i = 0; i < a_board.size(); ++i)
{
if(a_board.get(i)->getOwner() == OWNER_NONE)
{
if(randTer == counter)
return a_board.get(i)->getID();
else
counter++;
}
}
}
//returns ID of randomly selected self-owned territory to add 1 troop to
short getPlaceID(TemplateArray<Territory*> a_board)
{
short numOfValidOptions = 0;
for(int i = 0; i < a_board.size(); ++i)
{
if(this->ifOwns(a_board.get(i)) && a_board.get(i)->isConnectedToEnemy())
numOfValidOptions++;
}
short randTer = random() % numOfValidOptions;
short counter = 0;
for(int i = 0; i < a_board.size(); ++i)
{
if(this->ifOwns(a_board.get(i)) && a_board.get(i)->isConnectedToEnemy())
{
if(randTer == counter)
return a_board.get(i)->getID();
else
counter++;
}
}
}
//randomly pick a territory to attack with, pass the board and the AI's ID
short getAtkOriginID(TemplateArray<Territory*> a_board)
{
short numLoneEnemy = 0;
for(int i = 0; i < a_board.size(); ++i)
{
if(this->ifOwns(a_board.get(i)) && a_board.get(i)->haveTroopsToAttackFority() && a_board.get(i)->connectedToLoneEnemy())
numLoneEnemy++;
}
if(numLoneEnemy > 0)
{
short randAlly = random() % numLoneEnemy;
short counter = 0;
for(int i = 0; i < a_board.size(); ++i)
{
if(this->ifOwns(a_board.get(i)) && a_board.get(i)->haveTroopsToAttackFority() && a_board.get(i)->connectedToLoneEnemy())
{
if(randAlly == counter)
return a_board.get(i)->getID();
else
counter++;
}
}
}
else
{
short numOfValidOptions = 0;
for(int i = 0; i < a_board.size(); ++i)
{
if(this->ifOwns(a_board.get(i)) && a_board.get(i)->haveTroopsToAttackFority() && a_board.get(i)->isConnectedToEnemy())
numOfValidOptions++;
}
short randAlly = random() % numOfValidOptions;
short counter = 0;
for(int i = 0; i < a_board.size(); ++i)
{
if(this->ifOwns(a_board.get(i)) && a_board.get(i)->haveTroopsToAttackFority() && a_board.get(i)->isConnectedToEnemy())
{
if(randAlly == counter)
return a_board.get(i)->getID();
else
counter++;
}
}
}
}
//pick a territory to attack by passing it the board and the result pickAttackingTer()
short getAtkTargetID(TemplateArray<Territory*> a_board, short a_attackingTerID)
{
return a_board.get(a_attackingTerID)->getRandEnemyTerritoryID();
}
//returns ID of randomly selected ally-owned ter connected to enemy
short getFortOriginID(TemplateArray<Territory*> a_board)
{
short validNoEnemy = 0;
for(int i = 0; i < a_board.size(); ++i)
{
if(this->ifOwns(a_board.get(i)) && a_board.get(i)->haveTroopsToAttackFority() && a_board.get(i)->isConnectedToAlly()
& a_board.get(i)->connectedToLoneAlly())
validNoEnemy++;
}
if(validNoEnemy > 0)
{
short randAlly = random() % validNoEnemy;
short counter = 0;
for(int i = 0; i < a_board.size(); ++i)
{
if(this->ifOwns(a_board.get(i)) && a_board.get(i)->haveTroopsToAttackFority() && a_board.get(i)->isConnectedToAlly()
& a_board.get(i)->connectedToLoneAlly())
{
if(randAlly == counter)
return a_board.get(i)->getID();
else
counter++;
}
}
}
else
{
short numOfValidOptions = 0;
for(int i = 0; i < a_board.size(); ++i)
{
if(this->ifOwns(a_board.get(i)) && a_board.get(i)->haveTroopsToAttackFority() && a_board.get(i)->isConnectedToAlly())
numOfValidOptions++;
}
short randAlly = random() % numOfValidOptions;
short counter = 0;
for(int i = 0; i < a_board.size(); ++i)
{
if(this->ifOwns(a_board.get(i)) && a_board.get(i)->haveTroopsToAttackFority() && a_board.get(i)->isConnectedToAlly())
{
if(randAlly == counter)
return a_board.get(i)->getID();
else
counter++;
}
}
}
}
//returns ID of randomly selected ally-owned ter connected to ter with a_ID
short getFortTargetID(TemplateArray<Territory*> a_board, short a_ID)
{
return a_board.get(a_ID)->getRandAllyTerritoryID();
}
//returns radomly selected # of troops to take from ter with ID of a_ID
short getFortTroops(TemplateArray<Territory*> a_board, short a_ID)
{
return random() % (a_board.get(a_ID)->getTroops() - 1);
}
};
| [
"jparks.gsp@01c8a8da-d48b-78e0-b892-dcd36b50181e"
]
| [
[
[
1,
176
]
]
]
|
3b24ad7ac0bc8760439a8fb5144848b1c64ceb05 | b03c23324d8f048840ecf50875b05835dedc8566 | /engin3d/src/Graphics/Fonts/acgfx_font.cpp | 484ed4fb385919667d1427c786389369951ebc3c | []
| no_license | carlixyz/engin3d | 901dc61adda54e6098a3ac6637029efd28dd768e | f0b671b1e75a02eb58a2c200268e539154cd2349 | refs/heads/master | 2018-01-08T16:49:50.439617 | 2011-06-16T00:13:26 | 2011-06-16T00:13:26 | 36,534,616 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 30,491 | cpp | /*
AngelCode Tool Box Library
Copyright (c) 2007-2008 Andreas Jonsson
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you
must not claim that you wrote the original software. If you use
this software in a product, an 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.
Andreas Jonsson
[email protected]
*/
// THIS VERSION IS NOT THE ORIGINAL VERSION OF THE LIBRARY!
#include <stdio.h>
//#include "../GLHeaders.h"
#include "acgfx_font.h"
#include <windows.h>
#include <gl/gl.h>
#include "acutil_unicode.h"
// This is a modification of the original code <
#include "../Textures/TextureManager.h"
#include "../Textures/Texture.h"
#include <cassert>
#pragma warning( disable : 4996 )
//#include "..\..\Utility\Debug.h" // Remember to Build a Debug.h and .cpp (or stole the one from David)
// > This is a modification of the original code
#define LOG(X) printf X
using namespace std;
// Implement private helper classes for loading the bitmap font files
class CFontLoader
{
public:
CFontLoader(FILE *f, cFont *font, const char *fontFile);
virtual int Load() = 0; // Must be implemented by derived class
protected:
void LoadPage(int id, const char *pageFile, const char *fontFile);
void SetFontInfo(int outlineThickness);
void SetCommonInfo(int fontHeight, int base, int scaleW, int scaleH, int pages, bool isPacked);
void AddChar(int id, int x, int y, int w, int h, int xoffset, int yoffset, int xadvance, int page, int chnl);
void AddKerningPair(int first, int second, int amount);
FILE *f;
cFont *font;
const char *fontFile;
int outlineThickness;
};
class CFontLoaderTextFormat : public CFontLoader
{
public:
CFontLoaderTextFormat(FILE *f, cFont *font, const char *fontFile);
int Load();
int SkipWhiteSpace(std::string &str, int start);
int FindEndOfToken(std::string &str, int start);
void InterpretInfo(std::string &str, int start);
void InterpretCommon(std::string &str, int start);
void InterpretChar(std::string &str, int start);
void InterpretSpacing(std::string &str, int start);
void InterpretKerning(std::string &str, int start);
void InterpretPage(std::string &str, int start, const char *fontFile);
};
class CFontLoaderBinaryFormat : public CFontLoader
{
public:
CFontLoaderBinaryFormat(FILE *f, cFont *font, const char *fontFile);
int Load();
void ReadInfoBlock(int size);
void ReadCommonBlock(int size);
void ReadPagesBlock(int size);
void ReadCharsBlock(int size);
void ReadKerningPairsBlock(int size);
};
//=============================================================================
// cFont
//
// This is the cFont class that is used to write text with bitmap fonts.
//=============================================================================
cFont::cFont()
{
fontHeight = 0;
base = 0;
scaleW = 0;
scaleH = 0;
scale = 1.0f;
hasOutline = false;
encoding = NONE;
SetColour(1.0f, 1.0f, 1.0f);
}
void cFont::Deinit()
{
std::map<int, SCharDescr*>::iterator it = chars.begin();
while( it != chars.end() )
{
delete it->second;
it++;
}
// This is a modification of the original code <
for( unsigned n = 0; n < pages.size(); n++ )
{
cTextureManager::Get().UnloadResource( &pages[n] );
}
// > This is a modification of the original code
}
int cFont::Init(const char *fontFile)
{
// Load the font
FILE *f = fopen(fontFile, "rb");
// Determine format by reading the first bytes of the file
char str[4] = {0};
fread(str, 3, 1, f);
fseek(f, 0, SEEK_SET);
CFontLoader *loader = 0;
if( strcmp(str, "BMF") == 0 )
loader = new CFontLoaderBinaryFormat(f, this, fontFile);
else
loader = new CFontLoaderTextFormat(f, this, fontFile);
int r = loader->Load();
delete loader;
return r;
}
void cFont::SetTextEncoding(EFontTextEncoding encoding)
{
this->encoding = encoding;
}
// Internal
SCharDescr *cFont::GetChar(int id)
{
std::map<int, SCharDescr*>::iterator it = chars.find(id);
if( it == chars.end() ) return 0;
return it->second;
}
// Internal
float cFont::AdjustForKerningPairs(int first, int second)
{
SCharDescr *ch = GetChar(first);
if( ch == 0 ) return 0;
for( unsigned n = 0; n < ch->kerningPairs.size(); n += 2 )
{
if( ch->kerningPairs[n] == second )
return ch->kerningPairs[n+1] * scale;
}
return 0;
}
float cFont::GetTextWidth(const char *text, int count)
{
if( count <= 0 )
count = GetTextLength(text);
float x = 0;
for( int n = 0; n < count; )
{
int charId = GetTextChar(text,n,&n);
SCharDescr *ch = GetChar(charId);
if( ch == 0 ) ch = &defChar;
x += scale * (ch->xAdv);
if( n < count )
x += AdjustForKerningPairs(charId, GetTextChar(text,n));
}
return x;
}
void cFont::SetHeight(float h)
{
scale = h / float(fontHeight);
}
float cFont::GetHeight()
{
return scale * float(fontHeight);
}
float cFont::GetBottomOffset()
{
return scale * (base - fontHeight);
}
float cFont::GetTopOffset()
{
return scale * (base - 0);
}
// Internal
// Returns the number of bytes in the string until the null char
int cFont::GetTextLength(const char *text)
{
if( encoding == UTF16 )
{
int textLen = 0;
for(;;)
{
unsigned int len;
int r = acUtility::DecodeUTF16(&text[textLen], &len);
if( r > 0 )
textLen += len;
else if( r < 0 )
textLen++;
else
return textLen;
}
}
// Both UTF8 and standard ASCII strings can use strlen
return (int)strlen(text);
}
// Internal
int cFont::GetTextChar(const char *text, int pos, int *nextPos)
{
int ch;
unsigned int len;
if( encoding == UTF8 )
{
ch = acUtility::DecodeUTF8(&text[pos], &len);
if( ch == -1 ) len = 1;
}
else if( encoding == UTF16 )
{
ch = acUtility::DecodeUTF16(&text[pos], &len);
if( ch == -1 ) len = 2;
}
else
{
len = 1;
ch = (unsigned char)text[pos];
}
if( nextPos ) *nextPos = pos + len;
return ch;
}
// Internal
int cFont::FindTextChar(const char *text, int start, int length, int ch)
{
int pos = start;
int nextPos;
int currChar = -1;
while( pos < length )
{
currChar = GetTextChar(text, pos, &nextPos);
if( currChar == ch )
return pos;
pos = nextPos;
}
return -1;
}
void cFont::InternalWrite(float x, float y, float z, const char *text, int count, float spacing)
{
// This is a modification of the original code <
int page = -1;
glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
glBegin(GL_QUADS);
y += scale * float(base);
for( int n = 0; n < count; )
{
int charId = GetTextChar(text, n, &n);
SCharDescr *ch = GetChar(charId);
if( ch == 0 ) ch = &defChar;
// Map the center of the texel to the corners
// in order to get pixel perfect mapping
float u = (float(ch->srcX)+0.5f) / scaleW;
float v = (float(ch->srcY)+0.5f) / scaleH;
float u2 = u + float(ch->srcW) / scaleW;
float v2 = v + float(ch->srcH) / scaleH;
float a = scale * float(ch->xAdv);
float w = scale * float(ch->srcW);
float h = scale * float(ch->srcH);
float ox = scale * float(ch->xOff);
float oy = scale * float(ch->yOff);
if( ch->page != page )
{
glEnd();
page = ch->page;
cResource * lpResource = pages[page].GetResource();
assert(lpResource);
cTexture * lpTexture = (cTexture*)lpResource;
unsigned luiTextureHandle = lpTexture->GetTextureHandle();
glBindTexture( GL_TEXTURE_2D, luiTextureHandle );
glBegin(GL_QUADS);
}
glColor4f (mfR, mfG, mfB, mfA);
glTexCoord2f( u, v );
glVertex3f (x+ox, y-oy, z);
glTexCoord2f( u2, v );
glVertex3f (x+w+ox, y-oy, z);
glTexCoord2f( u2, v2 );
glVertex3f (x+w+ox, y-h-oy, z);
glTexCoord2f( u, v2 );
glVertex3f (x+ox, y-h-oy, z);
x += a;
if( charId == ' ' )
x += spacing;
if( n < count )
x += AdjustForKerningPairs(charId, GetTextChar(text,n));
}
glEnd();
// > This is a modification of the original code
}
void cFont::Write(float x, float y, float z, const char *text, int count, unsigned int mode)
{
if( count <= 0 )
count = GetTextLength(text);
if( mode == FONT_ALIGN_CENTER )
{
float w = GetTextWidth(text, count);
x -= w/2;
}
else if( mode == FONT_ALIGN_RIGHT )
{
float w = GetTextWidth(text, count);
x -= w;
}
InternalWrite(x, y, z, text, count);
}
void cFont::WriteML(float x, float y, float z, const char *text, int count, unsigned int mode)
{
if( count <= 0 )
count = GetTextLength(text);
// Get first line
int pos = 0;
int len = FindTextChar(text, pos, count, '\n');
if( len == -1 ) len = count;
while( pos < count )
{
float cx = x;
if( mode == FONT_ALIGN_CENTER )
{
float w = GetTextWidth(&text[pos], len);
cx -= w/2;
}
else if( mode == FONT_ALIGN_RIGHT )
{
float w = GetTextWidth(&text[pos], len);
cx -= w;
}
InternalWrite(cx, y, z, &text[pos], len);
y -= scale * float(fontHeight);
// Get next line
pos += len;
int ch = GetTextChar(text, pos, &pos);
if( ch == '\n' )
{
len = FindTextChar(text, pos, count, '\n');
if( len == -1 )
len = count - pos;
else
len = len - pos;
}
}
}
void cFont::WriteBox(float x, float y, float z, float width, const char *text, int count, unsigned int mode)
{
if( count <= 0 )
count = GetTextLength(text);
float currWidth = 0, wordWidth;
int lineS = 0, lineE = 0, wordS = 0, wordE = 0;
int wordCount = 0;
const char *s = " ";
float spaceWidth = GetTextWidth(s, 1);
bool softBreak = false;
for(; lineS < count;)
{
// Determine the extent of the line
for(;;)
{
// Determine the number of characters in the word
while( wordE < count &&
GetTextChar(text,wordE) != ' ' &&
GetTextChar(text,wordE) != '\n' )
// Advance the cursor to the next character
GetTextChar(text,wordE,&wordE);
// Determine the width of the word
if( wordE > wordS )
{
wordCount++;
wordWidth = GetTextWidth(&text[wordS], wordE-wordS);
}
else
wordWidth = 0;
// Does the word fit on the line? The first word is always accepted.
if( wordCount == 1 || currWidth + (wordCount > 1 ? spaceWidth : 0) + wordWidth <= width )
{
// Increase the line extent to the end of the word
lineE = wordE;
currWidth += (wordCount > 1 ? spaceWidth : 0) + wordWidth;
// Did we reach the end of the line?
if( wordE == count || GetTextChar(text,wordE) == '\n' )
{
softBreak = false;
// Skip the newline character
if( wordE < count )
// Advance the cursor to the next character
GetTextChar(text,wordE,&wordE);
break;
}
// Skip the trailing space
if( wordE < count && GetTextChar(text,wordE) == ' ' )
// Advance the cursor to the next character
GetTextChar(text,wordE,&wordE);
// Move to next word
wordS = wordE;
}
else
{
softBreak = true;
// Skip the trailing space
if( wordE < count && GetTextChar(text,wordE) == ' ' )
// Advance the cursor to the next character
GetTextChar(text,wordE,&wordE);
break;
}
}
// Write the line
if( mode == FONT_ALIGN_JUSTIFY )
{
float spacing = 0;
if( softBreak )
{
if( wordCount > 2 )
spacing = (width - currWidth) / (wordCount-2);
else
spacing = (width - currWidth);
}
InternalWrite(x, y, z, &text[lineS], lineE - lineS, spacing);
}
else
{
float cx = x;
if( mode == FONT_ALIGN_RIGHT )
cx = x + width - currWidth;
else if( mode == FONT_ALIGN_CENTER )
cx = x + 0.5f*(width - currWidth);
InternalWrite(cx, y, z, &text[lineS], lineE - lineS);
}
if( softBreak )
{
// Skip the trailing space
if( lineE < count && GetTextChar(text,lineE) == ' ' )
// Advance the cursor to the next character
GetTextChar(text,lineE,&lineE);
// We've already counted the first word on the next line
currWidth = wordWidth;
wordCount = 1;
}
else
{
// Skip the line break
if( lineE < count && GetTextChar(text,lineE) == '\n' )
// Advance the cursor to the next character
GetTextChar(text,lineE,&lineE);
currWidth = 0;
wordCount = 0;
}
// Move to next line
lineS = lineE;
wordS = wordE;
y -= scale * float(fontHeight);
}
}
// This is a modification of the original code <
/*
void cFont::PrepareEffect()
{
CGraphics *gfx = render->GetGraphics();
gfx->SetEffect(fxFile.c_str());
if( hasOutline )
gfx->SetEffectTechnique("RenderWithOutline");
else
gfx->SetEffectTechnique("RenderWithoutOutline");
}
void cFont::PreparePixelPerfectOutput()
{
IDirect3DDevice9 *dev = render->GetDevice();
CGraphics *gfx = render->GetGraphics();
// Determine size of view port
D3DVIEWPORT9 vp;
dev->GetViewport(&vp);
// Clear world matrix
D3DXMATRIX mtx;
D3DXMatrixIdentity(&mtx);
gfx->SetMatrix(D3DTS_WORLD, &mtx);
// Setup orthogonal view
// Origin is in lower-left corner
D3DXMatrixOrthoOffCenterLH(&mtx, 0, (float)vp.Width, 0, (float)vp.Height, vp.MinZ, vp.MaxZ);
gfx->SetMatrix(D3DTS_VIEW, &mtx);
D3DXMatrixIdentity(&mtx);
gfx->SetMatrix(D3DTS_PROJECTION, &mtx);
// Adjust the scale of the font so that the
// resolution of texture is the same as the screen
scale = 1.0f;
}*/
// > This is a modification of the original code
//=============================================================================
// CFontLoader
//
// This is the base class for all loader classes. This is the only class
// that has access to and knows how to set the cFont members.
//=============================================================================
CFontLoader::CFontLoader(FILE *f, cFont *font, const char *fontFile)
{
this->f = f;
this->font = font;
this->fontFile = fontFile;
outlineThickness = 0;
}
void CFontLoader::LoadPage(int id, const char *pageFile, const char *fontFile)
{
string str;
// Load the texture from the same directory as the font descriptor file
// Find the directory
str = fontFile;
for( size_t n = 0; (n = str.find('/', n)) != string::npos; ) str.replace(n, 1, "\\");
size_t i = str.rfind('\\');
if( i != string::npos )
str = str.substr(0, i+1);
else
str = "";
// Load the font textures
str += pageFile;
// This is a modification of the original code <
cResourceHandle lHandle = cTextureManager::Get().LoadResource(str.c_str(),str.c_str());
font->pages[id] = lHandle;
// > This is a modification of the original code
}
void CFontLoader::SetFontInfo(int outlineThickness)
{
this->outlineThickness = outlineThickness;
}
void CFontLoader::SetCommonInfo(int fontHeight, int base, int scaleW, int scaleH, int pages, bool isPacked)
{
font->fontHeight = fontHeight;
font->base = base;
font->scaleW = scaleW;
font->scaleH = scaleH;
font->pages.resize(pages);
// This is a modification of the original code <
/* for( int n = 0; n < pages; n++ )
font->pages[n] = 0; */
// > This is a modification of the original code
if( isPacked && outlineThickness )
font->hasOutline = true;
}
void CFontLoader::AddChar(int id, int x, int y, int w, int h, int xoffset, int yoffset, int xadvance, int page, int chnl)
{
// Convert to a 4 element vector
// TO DO: Does this depend on hardware? It probably does
if ( chnl == 1 ) chnl = 0x00010000; // Blue channel
else if( chnl == 2 ) chnl = 0x00000100; // Green channel
else if( chnl == 4 ) chnl = 0x00000001; // Red channel
else if( chnl == 8 ) chnl = 0x01000000; // Alpha channel
else chnl = 0;
if( id >= 0 )
{
SCharDescr *ch = new SCharDescr;
ch->srcX = x;
ch->srcY = y;
ch->srcW = w;
ch->srcH = h;
ch->xOff = xoffset;
ch->yOff = yoffset;
ch->xAdv = xadvance;
ch->page = page;
ch->chnl = chnl;
font->chars.insert(std::map<int, SCharDescr*>::value_type(id, ch));
}
if( id == -1 )
{
font->defChar.srcX = x;
font->defChar.srcY = y;
font->defChar.srcW = w;
font->defChar.srcH = h;
font->defChar.xOff = xoffset;
font->defChar.yOff = yoffset;
font->defChar.xAdv = xadvance;
font->defChar.page = page;
font->defChar.chnl = chnl;
}
}
void CFontLoader::AddKerningPair(int first, int second, int amount)
{
if( first >= 0 && first < 256 && font->chars[first] )
{
font->chars[first]->kerningPairs.push_back(second);
font->chars[first]->kerningPairs.push_back(amount);
}
}
//=============================================================================
// CFontLoaderTextFormat
//
// This class implements the logic for loading a BMFont file in text format
//=============================================================================
CFontLoaderTextFormat::CFontLoaderTextFormat(FILE *f, cFont *font, const char *fontFile) : CFontLoader(f, font, fontFile)
{
}
int CFontLoaderTextFormat::Load()
{
string line;
while( !feof(f) )
{
// Read until line feed (or EOF)
line = "";
line.reserve(256);
while( !feof(f) )
{
char ch;
if( fread(&ch, 1, 1, f) )
{
if( ch != '\n' )
line += ch;
else
break;
}
}
if (line == "") break; //Yorman y José Manuel (añadido)
// Skip white spaces
int pos = SkipWhiteSpace(line, 0);
// Read token
int pos2 = FindEndOfToken(line, pos);
string token = line.substr(pos, pos2-pos);
//DEBUG_MSG("%d - %s", ++i, token.c_str());
// Interpret line
if( token == "info" )
InterpretInfo(line, pos2);
else if( token == "common" )
InterpretCommon(line, pos2);
else if( token == "char" )
InterpretChar(line, pos2);
else if( token == "kerning" )
InterpretKerning(line, pos2);
else if( token == "page" )
InterpretPage(line, pos2, fontFile);
}
fclose(f);
// Success
return 0;
}
int CFontLoaderTextFormat::SkipWhiteSpace(string &str, int start)
{
unsigned n = start;
while( n < str.size() )
{
char ch = str[n];
if( ch != ' ' && ch != '\t' && ch != '\r' && ch != '\n' )
break;
++n;
}
return n;
}
int CFontLoaderTextFormat::FindEndOfToken(string &str, int start)
{
unsigned n = start;
if( str[n] == '"' )
{
n++;
while( n < str.size() )
{
char ch = str[n];
if( ch == '"' )
{
// Include the last quote char in the token
++n;
break;
}
++n;
}
}
else
{
while( n < str.size() )
{
char ch = str[n];
if( ch == ' ' ||
ch == '\t' ||
ch == '\r' ||
ch == '\n' ||
ch == '=' )
break;
++n;
}
}
return n;
}
void CFontLoaderTextFormat::InterpretKerning(string &str, int start)
{
// Read the attributes
int first = 0;
int second = 0;
int amount = 0;
int pos, pos2 = start;
while( true )
{
pos = SkipWhiteSpace(str, pos2);
pos2 = FindEndOfToken(str, pos);
string token = str.substr(pos, pos2-pos);
pos = SkipWhiteSpace(str, pos2);
if( pos == str.size() || str[pos] != '=' ) break;
pos = SkipWhiteSpace(str, pos+1);
pos2 = FindEndOfToken(str, pos);
string value = str.substr(pos, pos2-pos);
if( token == "first" )
first = strtol(value.c_str(), 0, 10);
else if( token == "second" )
second = strtol(value.c_str(), 0, 10);
else if( token == "amount" )
amount = strtol(value.c_str(), 0, 10);
//if( pos == str.size() ) break; //orig Jesús
if( pos2 == str.size() -1 ) break; //Yorman y José Manuel (añadido)
}
// Store the attributes
AddKerningPair(first, second, amount);
}
void CFontLoaderTextFormat::InterpretChar(string &str, int start)
{
// Read all attributes
int id = 0;
int x = 0;
int y = 0;
int width = 0;
int height = 0;
int xoffset = 0;
int yoffset = 0;
int xadvance = 0;
int page = 0;
int chnl = 0;
int pos, pos2 = start;
while( true )
{
pos = SkipWhiteSpace(str, pos2);
pos2 = FindEndOfToken(str, pos);
string token = str.substr(pos, pos2-pos);
pos = SkipWhiteSpace(str, pos2);
if( pos == str.size() || str[pos] != '=' ) break;
pos = SkipWhiteSpace(str, pos+1);
pos2 = FindEndOfToken(str, pos);
string value = str.substr(pos, pos2-pos);
if( token == "id" )
id = strtol(value.c_str(), 0, 10);
else if( token == "x" )
x = strtol(value.c_str(), 0, 10);
else if( token == "y" )
y = strtol(value.c_str(), 0, 10);
else if( token == "width" )
width = strtol(value.c_str(), 0, 10);
else if( token == "height" )
height = strtol(value.c_str(), 0, 10);
else if( token == "xoffset" )
xoffset = strtol(value.c_str(), 0, 10);
else if( token == "yoffset" )
yoffset = strtol(value.c_str(), 0, 10);
else if( token == "xadvance" )
xadvance = strtol(value.c_str(), 0, 10);
else if( token == "page" )
page = strtol(value.c_str(), 0, 10);
else if( token == "chnl" )
chnl = strtol(value.c_str(), 0, 10);
if( pos == str.size() ) break; //orig Jesús
//if( pos2 >= str.size() -1 ) break; //Yorman y José Manuel (añadido)
}
// Store the attributes
AddChar(id, x, y, width, height, xoffset, yoffset, xadvance, page, chnl);
}
void CFontLoaderTextFormat::InterpretCommon(string &str, int start)
{
int fontHeight;
int base;
int scaleW;
int scaleH;
int pages;
int packed;
// Read all attributes
int pos, pos2 = start;
while( true )
{
pos = SkipWhiteSpace(str, pos2);
pos2 = FindEndOfToken(str, pos);
string token = str.substr(pos, pos2-pos);
pos = SkipWhiteSpace(str, pos2);
if( pos == str.size() || str[pos] != '=' ) break;
pos = SkipWhiteSpace(str, pos+1);
pos2 = FindEndOfToken(str, pos);
string value = str.substr(pos, pos2-pos);
if( token == "lineHeight" )
fontHeight = (short)strtol(value.c_str(), 0, 10);
else if( token == "base" )
base = (short)strtol(value.c_str(), 0, 10);
else if( token == "scaleW" )
scaleW = (short)strtol(value.c_str(), 0, 10);
else if( token == "scaleH" )
scaleH = (short)strtol(value.c_str(), 0, 10);
else if( token == "pages" )
pages = strtol(value.c_str(), 0, 10);
else if( token == "packed" )
packed = strtol(value.c_str(), 0, 10);
//if( pos == str.size() ) break; //orig Jesús
if( pos2 == str.size() - 1) break; //Yorman y José Manuel (añadido)
}
SetCommonInfo(fontHeight, base, scaleW, scaleH, pages, packed ? true : false);
}
void CFontLoaderTextFormat::InterpretInfo(string &str, int start)
{
int outlineThickness;
// Read all attributes
int pos, pos2 = start;
while( true )
{
pos = SkipWhiteSpace(str, pos2);
pos2 = FindEndOfToken(str, pos);
string token = str.substr(pos, pos2-pos);
pos = SkipWhiteSpace(str, pos2);
if( pos == str.size() || str[pos] != '=' )
break;
pos = SkipWhiteSpace(str, pos+1);
pos2 = FindEndOfToken(str, pos);
string value = str.substr(pos, pos2-pos);
if( token == "outline" )
outlineThickness = (short)strtol(value.c_str(), 0, 10);
if( pos == str.size() ) break; //orig Jesús
//if( pos2 >= str.size() -1) break; //Yorman y José Manuel (añadido)
}
SetFontInfo(outlineThickness);
}
void CFontLoaderTextFormat::InterpretPage(string &str, int start, const char *fontFile)
{
int id = 0;
string file;
// Read all attributes
int pos, pos2 = start;
while( true )
{
pos = SkipWhiteSpace(str, pos2);
pos2 = FindEndOfToken(str, pos);
string token = str.substr(pos, pos2-pos);
pos = SkipWhiteSpace(str, pos2);
if( pos == str.size() || str[pos] != '=' ) break;
pos = SkipWhiteSpace(str, pos+1);
pos2 = FindEndOfToken(str, pos);
string value = str.substr(pos, pos2-pos);
if( token == "id" )
id = strtol(value.c_str(), 0, 10);
else if( token == "file" )
file = value.substr(1, value.length()-2);
if( pos == str.size() ) break; //orig Jesús
//if( pos2 >= str.size() - 1) break; //Yorman y José Manuel (añadido)
}
LoadPage(id, file.c_str(), fontFile);
}
//=============================================================================
// CFontLoaderBinaryFormat
//
// This class implements the logic for loading a BMFont file in binary format
//=============================================================================
CFontLoaderBinaryFormat::CFontLoaderBinaryFormat(FILE *f, cFont *font, const char *fontFile) : CFontLoader(f, font, fontFile)
{
}
int CFontLoaderBinaryFormat::Load()
{
// Read and validate the tag. It should be 66, 77, 70, 2,
// or 'BMF' and 2 where the number is the file version.
char magicString[4];
fread(magicString, 4, 1, f);
if( strncmp(magicString, "BMF\003", 4) != 0 )
{
LOG(("Unrecognized format for '%s'", fontFile));
fclose(f);
return -1;
}
// Read each block
char blockType;
int blockSize;
while( fread(&blockType, 1, 1, f) )
{
// Read the blockSize
fread(&blockSize, 4, 1, f);
switch( blockType )
{
case 1: // info
ReadInfoBlock(blockSize);
break;
case 2: // common
ReadCommonBlock(blockSize);
break;
case 3: // pages
ReadPagesBlock(blockSize);
break;
case 4: // chars
ReadCharsBlock(blockSize);
break;
case 5: // kerning pairs
ReadKerningPairsBlock(blockSize);
break;
default:
LOG(("Unexpected block type (%d)", blockType));
fclose(f);
return -1;
}
}
fclose(f);
// Success
return 0;
}
void CFontLoaderBinaryFormat::ReadInfoBlock(int size)
{
#pragma pack(push)
#pragma pack(1)
struct infoBlock
{
unsigned short fontSize;
unsigned char reserved:4;
unsigned char bold :1;
unsigned char italic :1;
unsigned char unicode :1;
unsigned char smooth :1;
unsigned char charSet;
unsigned short stretchH;
unsigned char aa;
unsigned char paddingUp;
unsigned char paddingRight;
unsigned char paddingDown;
unsigned char paddingLeft;
unsigned char spacingHoriz;
unsigned char spacingVert;
unsigned char outline; // Added with version 2
char fontName[1];
};
#pragma pack(pop)
char *buffer = new char[size];
fread(buffer, size, 1, f);
// We're only interested in the outline thickness
infoBlock *blk = (infoBlock*)buffer;
SetFontInfo(blk->outline);
delete[] buffer;
}
void CFontLoaderBinaryFormat::ReadCommonBlock(int size)
{
#pragma pack(push)
#pragma pack(1)
struct commonBlock
{
unsigned short lineHeight;
unsigned short base;
unsigned short scaleW;
unsigned short scaleH;
unsigned short pages;
unsigned char packed :1;
unsigned char reserved:7;
unsigned char alphaChnl;
unsigned char redChnl;
unsigned char greenChnl;
unsigned char blueChnl;
};
#pragma pack(pop)
char *buffer = new char[size];
fread(buffer, size, 1, f);
commonBlock *blk = (commonBlock*)buffer;
SetCommonInfo(blk->lineHeight, blk->base, blk->scaleW, blk->scaleH, blk->pages, blk->packed ? true : false);
delete[] buffer;
}
void CFontLoaderBinaryFormat::ReadPagesBlock(int size)
{
#pragma pack(push)
#pragma pack(1)
struct pagesBlock
{
char pageNames[1];
};
#pragma pack(pop)
char *buffer = new char[size];
fread(buffer, size, 1, f);
pagesBlock *blk = (pagesBlock*)buffer;
for( int id = 0, pos = 0; pos < size; id++ )
{
LoadPage(id, &blk->pageNames[pos], fontFile);
pos += 1 + (int)strlen(&blk->pageNames[pos]);
}
delete[] buffer;
}
void CFontLoaderBinaryFormat::ReadCharsBlock(int size)
{
#pragma pack(push)
#pragma pack(1)
struct charsBlock
{
struct charInfo
{
unsigned id;
unsigned short x;
unsigned short y;
unsigned short width;
unsigned short height;
short xoffset;
short yoffset;
short xadvance;
unsigned char page;
unsigned char chnl;
} chars[1];
};
#pragma pack(pop)
char *buffer = new char[size];
fread(buffer, size, 1, f);
charsBlock *blk = (charsBlock*)buffer;
for( int n = 0; int(n*sizeof(charsBlock::charInfo)) < size; n++ )
{
AddChar(blk->chars[n].id,
blk->chars[n].x,
blk->chars[n].y,
blk->chars[n].width,
blk->chars[n].height,
blk->chars[n].xoffset,
blk->chars[n].yoffset,
blk->chars[n].xadvance,
blk->chars[n].page,
blk->chars[n].chnl);
}
delete[] buffer;
}
void CFontLoaderBinaryFormat::ReadKerningPairsBlock(int size)
{
#pragma pack(push)
#pragma pack(1)
struct kerningPairsBlock
{
struct kerningPair
{
unsigned first;
unsigned second;
short amount;
} kerningPairs[1];
};
#pragma pack(pop)
char *buffer = new char[size];
fread(buffer, size, 1, f);
kerningPairsBlock *blk = (kerningPairsBlock*)buffer;
for( int n = 0; int(n*sizeof(kerningPairsBlock::kerningPair)) < size; n++ )
{
AddKerningPair(blk->kerningPairs[n].first,
blk->kerningPairs[n].second,
blk->kerningPairs[n].amount);
}
delete[] buffer;
}
// This is a modification of the original code <
#pragma warning( default : 4996 )
// > This is a modification of the original code
// 2008-05-11 Storing the characters in a map instead of an array
// 2008-05-11 Loading the new binary format for BMFont v1.10
// 2008-05-17 Added support for writing text with UTF8 and UTF16 encoding
| [
"[email protected]"
]
| [
[
[
1,
1261
]
]
]
|
5998b8fc4ab3a5f43bc7fe959b7e2f5c84d8916e | 01b123189b5d09a0088721da1c5f11892d9d3ad0 | /mapcontroller.cpp | e9a22c045834eaf8200919263fc104f76eb44a5f | []
| no_license | love-rollercoaster/comp3004 | 0cc624c4200641237c2e10412c885363f72e582b | 2aeb48860fd4a35ff25923455c8d92efe41e8032 | refs/heads/master | 2021-01-25T12:19:48.641948 | 2011-03-02T08:01:32 | 2011-03-08T00:51:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 915 | cpp |
#include "mapcontroller.h"
#include "mapform.h"
#include "mapview.h"
#include "facilitymapnode.h"
MapController::MapController()
{
MapForm *mapForm = new MapForm();
mapForm->show();
mapView = mapForm->mapView();
}
MapController::~MapController()
{
}
void MapController::addFacility(Facility *facility)
{
// FacilityMapNode *node = new FacilityMapNode(map, facility->getOccupancyRate(), facility->getType());
FacilityMapNode *node = new FacilityMapNode(
mapView,
FacilityMapNode::LOW, // Needs to be determined by facility's
// occupancy rate.
facility->type
);
// node->setPos(
// convertFacilityCoordinatesToPixel(facility->coordinates)
// );
node->setPos(facility->coordinates);
facilityMapNodes.append(node);
mapView->addFacilityMapNode(node);
}
| [
"[email protected]"
]
| [
[
[
1,
37
]
]
]
|
e4744fe05d8b6730396102fe275aa48338b64405 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.0/bctestmisccontrol/src/bctestsubeikcaptionedcontrol.cpp | d72a27a14a79deae463c285a5b7e6fb4d3f29327 | []
| no_license | SymbianSource/oss.FCL.sftools.ana.compatanamdw | a6a8abf9ef7ad71021d43b7f2b2076b504d4445e | 1169475bbf82ebb763de36686d144336fcf9d93b | refs/heads/master | 2020-12-24T12:29:44.646072 | 2010-11-11T14:03:20 | 2010-11-11T14:03:20 | 72,994,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,227 | cpp | /*
* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description: Invoke eik captioned control's protected APIs.
*
*/
#include "bctestsubeikcaptionedcontrol.h"
#include "bctestmisccontrol.hrh"
#include "autotestcommands.h"
// ======== MEMBER FUNCTIONS ========
// ---------------------------------------------------------------------------
// C++ default constructor
// ---------------------------------------------------------------------------
//
CBCTestSubEikCaptionedControl::CBCTestSubEikCaptionedControl()
{
}
// ---------------------------------------------------------------------------
// Destructor
// ---------------------------------------------------------------------------
//
CBCTestSubEikCaptionedControl::~CBCTestSubEikCaptionedControl()
{
}
| [
"none@none"
]
| [
[
[
1,
51
]
]
]
|
fe4905d8fa88d30f5baeb7bdeed15748124d5013 | fd518ed0226c6a044d5e168ab50a0e4a37f8efa9 | /iAuthor/Author/Volume/VolumeInXXX.cpp | 0031928f65417d24ef62f59aa8b62bd875dfddf5 | []
| no_license | shilinxu/iprojects | e2e2394df9882afaacfb9852332f83cbef6a8c93 | 79bc8e45596577948c45cf2afcff331bc71ab026 | refs/heads/master | 2020-05-17T19:15:43.197685 | 2010-04-02T15:58:11 | 2010-04-02T15:58:11 | 41,959,151 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,987 | cpp | // VolumeInXXX.cpp : Module interface implementation.
// Developer : Alex Chmut
// Created : 8/11/98
#include "StdAfx.h"
#include "VolumeInXXX.h"
/////////////////////////////////////////////////////////////////////////////
// Defines
#define BAD_DWORD (DWORD)-1
#define WND_CLASS_NAME "Input Volume Msg Wnd Class"
#define WND_NAME "Input Volume Msg Wnd"
/////////////////////////////////////////////////////////////////////////////
// Globals
PCVolumeInXXX g_pThis = NULL;
////////////////////////////////////////////////////////////
//{{{ Audio specific functions
#define AUDFREQ 22050 // Frequency
#define AUDCHANNELS 1 // Number of channels
#define AUDBITSMPL 16 // Number of bits per sample
inline
void SetDeviceType( WAVEFORMATEX* pwfe )
{
memset( pwfe, 0, sizeof(WAVEFORMATEX) );
WORD nBlockAlign = (AUDCHANNELS*AUDBITSMPL)/8;
DWORD nSamplesPerSec = AUDFREQ;
pwfe->wFormatTag = WAVE_FORMAT_PCM;
pwfe->nChannels = AUDCHANNELS;
pwfe->nBlockAlign = nBlockAlign;
pwfe->nSamplesPerSec = nSamplesPerSec;
pwfe->wBitsPerSample = AUDBITSMPL;
pwfe->nAvgBytesPerSec = nSamplesPerSec*nBlockAlign;
}
//}}} Audio specific functions
/////////////////////////////////////////////////////////////////////////////
// Implementation
//////////////
CVolumeInXXX::CVolumeInXXX( UINT uLineIndex )
: m_bOK(false),
m_bInitialized(false),
m_bAvailable(false),
m_uMixerID(0L),
m_dwMixerHandle(0L),
m_hWnd(NULL),
m_uMicrophoneSourceLineIndex(BAD_DWORD),
m_dwMinimalVolume(BAD_DWORD),
m_dwMaximalVolume(BAD_DWORD),
m_pfUserSink(NULL),
m_dwUserValue(0L)
{
if ( m_bOK = Init() )
{
g_pThis = this;
if ( !Initialize( uLineIndex ) )
{
Done();
g_pThis = NULL;
}
}
}
//////////////
CVolumeInXXX::~CVolumeInXXX()
{
if ( m_bOK )
Done();
g_pThis = NULL;
}
//////////////
bool CVolumeInXXX::Init()
{
if ( !mixerGetNumDevs() )
return false;
// Getting Mixer ID
HWAVEIN hwaveIn;
MMRESULT mmResult;
WAVEFORMATEX WaveFmt;
SetDeviceType( &WaveFmt );
mmResult = waveInOpen( &hwaveIn, WAVE_MAPPER, &WaveFmt, 0L, 0L, CALLBACK_NULL );
if ( mmResult != MMSYSERR_NOERROR )
{
TRACE(".InputXxxVolume: FAILURE: Could not open WaveIn Mapper. mmResult=%d\n", mmResult );
return false;
} else {
mmResult = mixerGetID( (HMIXEROBJ)hwaveIn, &m_uMixerID, MIXER_OBJECTF_HWAVEIN );
waveInClose( hwaveIn );
if ( mmResult != MMSYSERR_NOERROR )
{
TRACE(".InputXxxVolume: FAILURE: WaveIn Mapper in Mixer is not available. mmResult=%d\n", mmResult );
return false;
}
}
// Exposing Window to Mixer
WNDCLASSEX wcx;
memset( &wcx, 0, sizeof(WNDCLASSEX) );
wcx.cbSize = sizeof(WNDCLASSEX);
wcx.lpszClassName = WND_CLASS_NAME;
wcx.lpfnWndProc = (WNDPROC)MixerWndProc;
::RegisterClassEx(&wcx);
m_hWnd = CreateWindow( WND_CLASS_NAME,
WND_NAME,
WS_POPUP | WS_DISABLED,
0, 0, 0, 0,
NULL, NULL, NULL, NULL );
if ( !m_hWnd )
{
TRACE(".InputXxxVolume: FAILURE: Could not create internal window.\n" );
return false;
}
::ShowWindow(m_hWnd, SW_HIDE);
mmResult = mixerOpen( (LPHMIXER)&m_dwMixerHandle, m_uMixerID, (DWORD)m_hWnd, 0L, CALLBACK_WINDOW );
if ( mmResult != MMSYSERR_NOERROR )
{
TRACE(".InputXxxVolume: FAILURE: Could not open Mixer. mmResult=%d\n", mmResult );
::DestroyWindow( m_hWnd );
return false;
}
return true;
}
//////////////
void CVolumeInXXX::Done()
{
if ( mixerClose( (HMIXER)m_dwMixerHandle ) != MMSYSERR_NOERROR )
{
TRACE(".InputXxxVolume: WARNING: Could not close Mixer.\n" );
}
::DestroyWindow( m_hWnd );
m_bInitialized = false;
m_bOK = false;
}
//////////////
void CVolumeInXXX::OnControlChanged( DWORD dwControlID )
{
if ( m_dwVolumeControlID == dwControlID )
{
DWORD dwVolume = GetCurrentVolume();
if ( (dwVolume!=BAD_DWORD) && (m_pfUserSink) )
{
(*m_pfUserSink)( dwVolume, m_dwUserValue );
}
}
}
//////////////
bool CVolumeInXXX::Initialize( UINT uLineIndex )
{
MMRESULT mmResult;
if ( !m_bOK )
return false;
TRACE(".InputXxxVolume: Initializing for the Source Line (%d) ..\n", uLineIndex );
MIXERLINE MixerLine;
memset( &MixerLine, 0, sizeof(MIXERLINE) );
MixerLine.cbStruct = sizeof(MIXERLINE);
MixerLine.dwComponentType = MIXERLINE_COMPONENTTYPE_DST_WAVEIN;
mmResult = mixerGetLineInfo( (HMIXEROBJ)m_dwMixerHandle, &MixerLine, MIXER_GETLINEINFOF_COMPONENTTYPE );
if ( mmResult != MMSYSERR_NOERROR )
{
TRACE(".InputXxxVolume: FAILURE: Could not get WaveIn Destionation Line for the requested source while initilaizing. mmResult=%d\n", mmResult );
return false;
}
MIXERCONTROL Control;
memset( &Control, 0, sizeof(MIXERCONTROL) );
Control.cbStruct = sizeof(MIXERCONTROL);
MIXERLINECONTROLS LineControls;
memset( &LineControls, 0, sizeof(MIXERLINECONTROLS) );
LineControls.cbStruct = sizeof(MIXERLINECONTROLS);
MIXERLINE Line;
memset( &Line, 0, sizeof(MIXERLINE) );
Line.cbStruct = sizeof(MIXERLINE);
if ( ( uLineIndex < MixerLine.cConnections ) )
{
Line.dwDestination = MixerLine.dwDestination;
Line.dwSource = uLineIndex;
mmResult = mixerGetLineInfo( (HMIXEROBJ)m_dwMixerHandle, &Line, MIXER_GETLINEINFOF_SOURCE );
if ( mmResult != MMSYSERR_NOERROR )
{
TRACE(".InputXxxVolume: FAILURE: Could not get the requested Source Line while initilaizing. mmResult=%d\n", mmResult );
return false;
}
TRACE(".InputXxxVolume: \"%s\" Source Line adopted.\n", Line.szShortName );
LineControls.dwControlType = MIXERCONTROL_CONTROLTYPE_VOLUME;
LineControls.dwLineID = Line.dwLineID;
LineControls.cControls = 1;
LineControls.cbmxctrl = sizeof(MIXERCONTROL);
LineControls.pamxctrl = &Control;
mmResult = mixerGetLineControls( (HMIXEROBJ)m_dwMixerHandle, &LineControls, MIXER_GETLINECONTROLSF_ONEBYTYPE );
if ( mmResult == MMSYSERR_NOERROR )
{
if ( !(Control.fdwControl & MIXERCONTROL_CONTROLF_DISABLED) )
{
m_bAvailable = true;
TRACE(".InputXxxVolume: \"%s\" Volume control for the Source Line adopted\n", Control.szShortName );
} else {
TRACE(".InputXxxVolume: WARNING: The Volume Control is disabled.\n" );
}
} else {
TRACE(".InputXxxVolume: WARNING: Could not get the requested Source Line Volume Control for the requested line while initilaizing. mmResult=%d\n", mmResult );
}
} else {
TRACE(".InputXxxVolume: FAILURE: Invalid Source Line index passed.\n" );
return false;
}
// Retrieving Microphone Source Line
for ( UINT uLine = 0; uLine < MixerLine.cConnections; uLine++ )
{
MIXERLINE MicrophoneLine;
memset( &MicrophoneLine, 0, sizeof(MIXERLINE) );
MicrophoneLine.cbStruct = sizeof(MIXERLINE);
MicrophoneLine.dwDestination = MixerLine.dwDestination;
MicrophoneLine.dwSource = uLine;
mmResult = mixerGetLineInfo( (HMIXEROBJ)m_dwMixerHandle, &MicrophoneLine, MIXER_GETLINEINFOF_SOURCE );
if ( mmResult == MMSYSERR_NOERROR )
{
if ( MicrophoneLine.dwComponentType == MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE )
{
m_uMicrophoneSourceLineIndex = MicrophoneLine.dwSource;
TRACE(".InputXxxVolume: Microphone Source Line \"%s\" has been found.\n", MicrophoneLine.szShortName );
break;
}
}
}
if ( m_uMicrophoneSourceLineIndex == BAD_DWORD )
{
TRACE(".InputXxxVolume: WARNING: Could not retrieve Microphone Source Line.\n" );
}
m_uSourceLineIndex = uLineIndex;
m_nChannelCount = Line.cChannels;
m_dwLineID = LineControls.dwLineID;
m_dwVolumeControlID = Control.dwControlID;
m_dwMinimalVolume = Control.Bounds.dwMinimum;
m_dwMaximalVolume = Control.Bounds.dwMaximum;
m_dwVolumeStep = Control.Metrics.cSteps;
m_bInitialized = true;
return true;
}
//////////////////////////////////////////////
bool CVolumeInXXX::GetMicrophoneSourceLineIndex( UINT* puLineIndex )
{
if ( !puLineIndex || !m_bInitialized || (m_uMicrophoneSourceLineIndex==BAD_DWORD) )
return false;
*puLineIndex = m_uMicrophoneSourceLineIndex;
return true;
}
//////////////////////////////////////////////
// IVolume interface
//////////////
bool CVolumeInXXX::IsAvailable()
{
return m_bAvailable;
}
//////////////
void CVolumeInXXX::Enable()
{
if ( !m_bInitialized )
return;
bool bAnyEnabled = false;
MMRESULT mmResult;
MIXERLINE lineDestination;
memset( &lineDestination, 0, sizeof(MIXERLINE) );
lineDestination.cbStruct = sizeof(MIXERLINE);
lineDestination.dwComponentType = MIXERLINE_COMPONENTTYPE_DST_WAVEIN;
mmResult = mixerGetLineInfo( (HMIXEROBJ)m_dwMixerHandle, &lineDestination, MIXER_GETLINEINFOF_COMPONENTTYPE );
if ( mmResult != MMSYSERR_NOERROR )
{
TRACE(".InputXxxVolume: FAILURE: Could not get the Destination Line while enabling. mmResult=%d\n", mmResult );
return;
}
// Getting all line's controls
int nControlCount = lineDestination.cControls;
int nChannelCount = lineDestination.cChannels;
MIXERLINECONTROLS LineControls;
memset( &LineControls, 0, sizeof(MIXERLINECONTROLS) );
MIXERCONTROL* aControls = (MIXERCONTROL*)malloc( nControlCount * sizeof(MIXERCONTROL) );
if ( !aControls )
{
TRACE(".InputXxxVolume: FAILURE: Out of memory while enabling the line.\n" );
return;
}
memset( &aControls[0], 0, sizeof(nControlCount * sizeof(MIXERCONTROL)) );
for ( int i = 0; i < nControlCount; i++ )
{
aControls[i].cbStruct = sizeof(MIXERCONTROL);
}
LineControls.cbStruct = sizeof(MIXERLINECONTROLS);
LineControls.dwLineID = lineDestination.dwLineID;
LineControls.cControls = nControlCount;
LineControls.cbmxctrl = sizeof(MIXERCONTROL);
LineControls.pamxctrl = &aControls[0];
mmResult = mixerGetLineControls( (HMIXEROBJ)m_dwMixerHandle, &LineControls, MIXER_GETLINECONTROLSF_ALL );
if ( mmResult == MMSYSERR_NOERROR )
{
for (int i = 0; i < nControlCount; i++ )
{
if ( aControls[i].dwControlType & MIXERCONTROL_CT_UNITS_BOOLEAN )
{
MIXERCONTROLDETAILS_BOOLEAN* aDetails = NULL;
int nMultipleItems = aControls[i].cMultipleItems;
int nChannels = nChannelCount;
// MIXERCONTROLDETAILS
MIXERCONTROLDETAILS ControlDetails;
memset( &ControlDetails, 0, sizeof(MIXERCONTROLDETAILS) );
ControlDetails.cbStruct = sizeof(MIXERCONTROLDETAILS);
ControlDetails.dwControlID = aControls[i].dwControlID;
if ( aControls[i].fdwControl & MIXERCONTROL_CONTROLF_UNIFORM )
{
nChannels = 1;
}
if ( aControls[i].fdwControl & MIXERCONTROL_CONTROLF_MULTIPLE )
{
nMultipleItems = aControls[i].cMultipleItems;
aDetails = (MIXERCONTROLDETAILS_BOOLEAN*)malloc(nMultipleItems*nChannels*sizeof(MIXERCONTROLDETAILS_BOOLEAN));
if ( !aDetails )
{
TRACE(".InputXxxVolume: FAILURE: Out of memory while enabling the line.\n" );
continue;
}
for ( int nItem = 0; nItem < nMultipleItems; nItem++ )
{
LONG lValue = FALSE;
if ( nItem == (int)m_uSourceLineIndex )
lValue = TRUE;
for ( int nChannel = 0; nChannel < nChannels; nChannel++ )
{
aDetails[nItem+nChannel].fValue = lValue;
}
}
} else {
nMultipleItems = 0;
aDetails = (MIXERCONTROLDETAILS_BOOLEAN*)malloc(nChannels*sizeof(MIXERCONTROLDETAILS_BOOLEAN));
if ( !aDetails )
{
TRACE(".InputXxxVolume: FAILURE: Out of memory while enabling the line.\n" );
continue;
}
for ( int nChannel = 0; nChannel < nChannels; nChannel++ )
{
aDetails[nChannel].fValue = (LONG)TRUE;
}
}
ControlDetails.cChannels = nChannels;
ControlDetails.cMultipleItems = nMultipleItems;
ControlDetails.cbDetails = sizeof(MIXERCONTROLDETAILS_BOOLEAN);
ControlDetails.paDetails = &aDetails[0];
mmResult = mixerSetControlDetails( (HMIXEROBJ)m_dwMixerHandle, &ControlDetails, 0L );
if ( mmResult == MMSYSERR_NOERROR )
{
TRACE(".InputXxxVolume: Enabling Line: Line control \"%s\" has been enabled.\n", aControls[i].szShortName );
bAnyEnabled = true;
}
free( aDetails );
}
}
} else {
TRACE(".InputXxxVolume: FAILURE: Could not get the line's controls while enabling. mmResult=%d\n", mmResult );
}
free( aControls );
if ( !bAnyEnabled )
{
TRACE(".InputXxxVolume: WARNING: No controls were found for enabling the line.\n" );
}
}
//////////////
void CVolumeInXXX::Disable()
{
TRACE(".InputXxxVolume: WARNING: Disable line has no sense. The function not implemented.\n" );
}
//////////////
DWORD CVolumeInXXX::GetVolumeMetric()
{
if ( !m_bAvailable )
return BAD_DWORD;
return m_dwVolumeStep;
}
//////////////
DWORD CVolumeInXXX::GetMinimalVolume()
{
if ( !m_bAvailable )
return BAD_DWORD;
return m_dwMinimalVolume;
}
//////////////
DWORD CVolumeInXXX::GetMaximalVolume()
{
if ( !m_bAvailable )
return BAD_DWORD;
return m_dwMaximalVolume;
}
//////////////
DWORD CVolumeInXXX::GetCurrentVolume()
{
if ( !m_bAvailable )
return BAD_DWORD;
MIXERCONTROLDETAILS_UNSIGNED* aDetails = (MIXERCONTROLDETAILS_UNSIGNED*)malloc(m_nChannelCount*sizeof(MIXERCONTROLDETAILS_UNSIGNED));
if ( !aDetails )
return BAD_DWORD;
MIXERCONTROLDETAILS ControlDetails;
memset( &ControlDetails, 0, sizeof(MIXERCONTROLDETAILS) );
ControlDetails.cbStruct = sizeof(MIXERCONTROLDETAILS);
ControlDetails.dwControlID = m_dwVolumeControlID;
ControlDetails.cChannels = m_nChannelCount;
ControlDetails.cMultipleItems = 0;
ControlDetails.cbDetails = sizeof(MIXERCONTROLDETAILS_UNSIGNED);
ControlDetails.paDetails = &aDetails[0];
MMRESULT mmResult = mixerGetControlDetails( (HMIXEROBJ)m_dwMixerHandle, &ControlDetails, MIXER_GETCONTROLDETAILSF_VALUE );
DWORD dw = aDetails[0].dwValue;
free( aDetails );
if ( mmResult != MMSYSERR_NOERROR )
{
TRACE(".InputXxxVolume: FAILURE: Could not get volume. mmResult=%d\n", mmResult );
return BAD_DWORD;
}
return dw;
}
//////////////
void CVolumeInXXX::SetCurrentVolume( DWORD dwValue )
{
if ( !m_bAvailable || (dwValue<m_dwMinimalVolume) || (dwValue>m_dwMaximalVolume) )
return;
MIXERCONTROLDETAILS_UNSIGNED* aDetails = (MIXERCONTROLDETAILS_UNSIGNED*)malloc(m_nChannelCount*sizeof(MIXERCONTROLDETAILS_UNSIGNED));
if ( !aDetails )
return;
for ( int i = 0; i < m_nChannelCount; i++ )
{
aDetails[i].dwValue = dwValue;
}
MIXERCONTROLDETAILS ControlDetails;
memset( &ControlDetails, 0, sizeof(MIXERCONTROLDETAILS) );
ControlDetails.cbStruct = sizeof(MIXERCONTROLDETAILS);
ControlDetails.dwControlID = m_dwVolumeControlID;
ControlDetails.cChannels = m_nChannelCount;
ControlDetails.cMultipleItems = 0;
ControlDetails.cbDetails = sizeof(MIXERCONTROLDETAILS_UNSIGNED);
ControlDetails.paDetails = &aDetails[0];
MMRESULT mmResult = mixerSetControlDetails( (HMIXEROBJ)m_dwMixerHandle, &ControlDetails, MIXER_SETCONTROLDETAILSF_VALUE );
free( aDetails );
if ( mmResult != MMSYSERR_NOERROR )
{
TRACE(".InputXxxVolume: FAILURE: Could not set volume(%d) mmResult=%d\n", dwValue, mmResult );
}
}
//////////////
void CVolumeInXXX::RegisterNotificationSink( PONMICVOULUMECHANGE pfUserSink, DWORD dwUserValue )
{
m_pfUserSink = pfUserSink;
m_dwUserValue = dwUserValue;
}
////////////////////////////////////////////////////////////////////////
LRESULT CALLBACK CVolumeInXXX::MixerWndProc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
if ( uMsg == MM_MIXM_CONTROL_CHANGE )
{
if ( g_pThis )
{
g_pThis->OnControlChanged( (DWORD)lParam );
}
}
return ::DefWindowProc( hwnd, uMsg, wParam, lParam);
}
////////////////////////////////////////////////////////////////////////
bool CVolumeInXXX::EnumerateInputLines( PINPUTLINEPROC pUserCallback, DWORD dwUserValue )
{
if ( !pUserCallback )
return false;
MMRESULT mmResult;
HWAVEIN hwaveIn;
WAVEFORMATEX WaveFmt;
SetDeviceType( &WaveFmt );
mmResult = waveInOpen( &hwaveIn, WAVE_MAPPER, &WaveFmt, 0L, 0L, CALLBACK_NULL );
if ( mmResult != MMSYSERR_NOERROR )
{
TRACE(".InputXxxVolume: FAILURE: Could not open WaveIn Mapper. mmResult=%d\n", mmResult );
return false;
}
UINT uMixerID;
DWORD dwMixerHandle;
mmResult = mixerGetID( (HMIXEROBJ)hwaveIn, &uMixerID, MIXER_OBJECTF_HWAVEIN );
waveInClose( hwaveIn );
if ( mmResult != MMSYSERR_NOERROR )
{
TRACE(".InputXxxVolume: FAILURE: WaveIn Mapper in Mixer is not available. mmResult=%d\n", mmResult );
return false;
}
mmResult = mixerOpen( (LPHMIXER)&dwMixerHandle, uMixerID, 0L, 0L, 0L );
if ( mmResult != MMSYSERR_NOERROR )
{
mixerClose( (HMIXER)dwMixerHandle );
TRACE(".InputXxxVolume: FAILURE: Could not open Mixer. mmResult=%d\n", mmResult );
return false;
}
MIXERLINE MixerLine;
memset( &MixerLine, 0, sizeof(MIXERLINE) );
MixerLine.cbStruct = sizeof(MIXERLINE);
MixerLine.dwComponentType = MIXERLINE_COMPONENTTYPE_DST_WAVEIN;
mmResult = mixerGetLineInfo( (HMIXEROBJ)dwMixerHandle, &MixerLine, MIXER_GETLINEINFOF_COMPONENTTYPE );
if ( mmResult != MMSYSERR_NOERROR )
{
mixerClose( (HMIXER)dwMixerHandle );
TRACE(".InputXxxVolume: FAILURE: Could not get WaveIn Destionation Line for the requested source while enumerating. mmResult=%d\n", mmResult );
return false;
}
MIXERLINE Line;
for ( UINT uLineIndex = 0; uLineIndex < MixerLine.cConnections; uLineIndex++ )
{
memset( &Line, 0, sizeof(MIXERLINE) );
Line.cbStruct = sizeof(MIXERLINE);
Line.dwDestination = MixerLine.dwDestination;
Line.dwSource = uLineIndex;
mmResult = mixerGetLineInfo( (HMIXEROBJ)dwMixerHandle, &Line, MIXER_GETLINEINFOF_SOURCE );
if ( mmResult != MMSYSERR_NOERROR )
{
mixerClose( (HMIXER)dwMixerHandle );
TRACE(".InputXxxVolume: FAILURE: Could not get the interated Source Line while enumerating. mmResult=%d\n", mmResult );
return false;
}
if ( !((*pUserCallback)( uLineIndex, &Line, dwUserValue )) )
{
break;
}
}
mixerClose( (HMIXER)dwMixerHandle );
return true;
}
| [
"[email protected]"
]
| [
[
[
1,
535
]
]
]
|
cff625501255958c98aa80ba3b4943b61054d30b | b2d46af9c6152323ce240374afc998c1574db71f | /cursovideojuegos/theflostiproject/3rdParty/boost/libs/mpl/test/set_c.cpp | 1b1adbcd79eeb1d8d62569ff5d7ef2baf13ee513 | []
| no_license | bugbit/cipsaoscar | 601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4 | 52aa8b4b67d48f59e46cb43527480f8b3552e96d | refs/heads/master | 2021-01-10T21:31:18.653163 | 2011-09-28T16:39:12 | 2011-09-28T16:39:12 | 33,032,640 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,707 | cpp |
// 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.
// $Source: /cvsroot/boost/boost/libs/mpl/test/Attic/set_c.cpp,v $
// $Date: 2004/11/10 23:51:34 $
// $Revision: 1.1.2.1 $
#include <boost/mpl/set_c.hpp>
#include <boost/mpl/at.hpp>
#include <boost/mpl/size.hpp>
#include <boost/mpl/aux_/test.hpp>
namespace test { namespace {
#if !BOOST_WORKAROUND(BOOST_MSVC, <= 1300)
template< typename S, typename S::value_type k >
struct at_c
: at< S, integral_c<typename S::value_type,k> >::type
{
};
#else
template< typename S, long k >
struct at_c
: aux::msvc_eti_base<
at< S, integral_c<typename S::value_type,k> >
>
{
};
#endif
}}
#if !BOOST_WORKAROUND(BOOST_MSVC, <= 1200)
MPL_TEST_CASE()
{
typedef set_c<bool,true>::type s1;
typedef set_c<bool,false>::type s2;
typedef set_c<bool,true,false>::type s3;
MPL_ASSERT_RELATION( size<s1>::value, ==, 1 );
MPL_ASSERT_RELATION( size<s2>::value, ==, 1 );
MPL_ASSERT_RELATION( size<s3>::value, ==, 2 );
MPL_ASSERT(( is_same< s1::value_type, bool > ));
MPL_ASSERT(( is_same< s3::value_type, bool > ));
MPL_ASSERT(( is_same< s2::value_type, bool > ));
#if !BOOST_WORKAROUND(BOOST_MSVC, <= 1300)
MPL_ASSERT_RELATION( ( test::at_c<s1,true>::value ), ==, true );
MPL_ASSERT_RELATION( ( test::at_c<s2,false>::value ), ==, false );
MPL_ASSERT_RELATION( ( test::at_c<s3,true>::value ), ==, true );
MPL_ASSERT_RELATION( ( test::at_c<s3,false>::value ), ==, false );
MPL_ASSERT(( is_same< test::at_c<s1,false>::type, void_ > ));
MPL_ASSERT(( is_same< test::at_c<s2,true>::type, void_ > ));
#endif
}
#endif
MPL_TEST_CASE()
{
typedef set_c<char,'a'>::type s1;
typedef set_c<char,'a','b','c','d','e','f','g','h'>::type s2;
MPL_ASSERT_RELATION( size<s1>::value, ==, 1 );
MPL_ASSERT_RELATION( size<s2>::value, ==, 8 );
MPL_ASSERT(( is_same< s1::value_type, char > ));
MPL_ASSERT(( is_same< s2::value_type, char > ));
#if !BOOST_WORKAROUND(BOOST_MSVC, <= 1300)
MPL_ASSERT_RELATION( ( test::at_c<s1,'a'>::value ), ==, 'a' );
MPL_ASSERT_RELATION( ( test::at_c<s2,'a'>::value ), ==, 'a' );
MPL_ASSERT_RELATION( ( test::at_c<s2,'d'>::value ), ==, 'd' );
MPL_ASSERT_RELATION( ( test::at_c<s2,'h'>::value ), ==, 'h' );
MPL_ASSERT(( is_same< test::at_c<s1,'z'>::type, void_ > ));
MPL_ASSERT(( is_same< test::at_c<s2,'k'>::type, void_ > ));
#endif
}
| [
"ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a"
]
| [
[
[
1,
85
]
]
]
|
68197783cdd5bda57b7e6c786a688fe062f475e4 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/mpl/example/tuple_from_list.cpp | 43e41f42a0280ff3f90039e2c6bf969034895d15 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,064 | cpp |
// Copyright Aleksey Gurtovoy 2002-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.
// $Source: /cvsroot/boost/boost/libs/mpl/example/tuple_from_list.cpp,v $
// $Date: 2004/09/02 15:41:29 $
// $Revision: 1.3 $
#include <boost/mpl/reverse_fold.hpp>
#include <boost/mpl/list.hpp>
#include <boost/tuple/tuple.hpp>
#include <iostream>
using namespace boost::mpl;
template< typename Types > struct tuple_gen
: reverse_fold<
Types
, boost::tuples::null_type
, boost::tuples::cons<_2,_1>
>
{
};
int main()
{
tuple_gen< list<int,char const*,bool> >::type t;
boost::get<0>(t) = -1;
boost::get<1>(t) = "text";
boost::get<2>(t) = false;
std::cout
<< boost::get<0>(t) << '\n'
<< boost::get<1>(t) << '\n'
<< boost::get<2>(t) << '\n'
;
return 0;
}
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
]
| [
[
[
1,
46
]
]
]
|
d29e5e66c0caa51e17f9910368c555e6ddf089a9 | 38664d844d9fad34e88160f6ebf86c043db9f1c5 | /branches/initialize/infostudio/InfoStudio/commonctl/ListViewTrackTip.h | 1d39f765d7880b7c693e540f421b758fff1c4af8 | []
| no_license | cnsuhao/jezzitest | 84074b938b3e06ae820842dac62dae116d5fdaba | 9b5f6cf40750511350e5456349ead8346cabb56e | refs/heads/master | 2021-05-28T23:08:59.663581 | 2010-11-25T13:44:57 | 2010-11-25T13:44:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,361 | h | #if !defined(AFX_LISTVIEWTRACKTIP_H__20030113_F7A2_CF82_8F7F_0080AD509054__INCLUDED_)
#define AFX_LISTVIEWTRACKTIP_H__20030113_F7A2_CF82_8F7F_0080AD509054__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#pragma once
/////////////////////////////////////////////////////////////////////////////
// ListViewTrackTip - Tracking ToolTip for a ListView control
//
// Written by Bjarke Viksoe ([email protected])
// Copyright (c) 2003 Bjarke Viksoe.
//
// Add a member to the parent window:
// CListViewTrackTip m_Tip;
// Add the following macro to the parent's message map:
// CHAIN_MSG_MAP_MEMBER( m_Tip )
// Attach the tracking tip to the ListView:
// m_Tip.Attach(m_hWnd, m_ctrlList);
//
// This code may be used in compiled form in any way you desire. This
// file may be redistributed by any means PROVIDING it is
// not sold for profit without the authors written consent, and
// providing that this notice and the authors name is included.
//
// This file is provided "as is" with no expressed or implied warranty.
// The author accepts no liability if it causes any damage to you or your
// computer whatsoever. It's free, so don't hassle me about it.
//
// Beware of bugs.
//
#ifndef __cplusplus
#error WTL requires C++ compilation (use a .cpp suffix)
#endif
#ifndef __ATLCTRLS_H__
#error ListViewTrackTip.h requires atlctrls.h to be included first
#endif
class CListViewTrackTip : public CMessageMap
{
public:
enum
{
TIMER_ID = 438,
X_OFFSET = 15,
Y_OFFSET = 15,
};
CContainedWindowT<CListViewCtrl> m_ctrlList;
CToolTipCtrl m_ctrlTip;
CWindow m_wndOwner;
TOOLINFO m_ti;
int m_iCurItem;
bool m_bTrackingMouseLeave;
BEGIN_MSG_MAP(CListViewTrackTip)
MESSAGE_HANDLER(WM_TIMER, OnTimer)
NOTIFY_CODE_HANDLER(TTN_GETDISPINFO, OnGetDispInfo);
ALT_MSG_MAP(1)
MESSAGE_HANDLER(WM_MOUSEMOVE, OnMouseMove)
MESSAGE_HANDLER(WM_MOUSEWHEEL, OnMouseMove)
MESSAGE_HANDLER(WM_MOUSELEAVE, OnMouseLeave)
END_MSG_MAP()
public:
CListViewTrackTip() :
m_ctrlList(this, 1), m_iCurItem(-1), m_bTrackingMouseLeave(false)
{
}
~CListViewTrackTip()
{
if( m_ctrlTip.IsWindow() )
/* scary */ m_ctrlTip.DestroyWindow();
if( m_ctrlList.IsWindow() )
/* scary */ m_ctrlList.UnsubclassWindow();
}
int GetCurItem()
{
return m_iCurItem;
}
void Attach(HWND hwndOwner, HWND hwndList)
{
ATLASSERT(::IsWindow(hwndOwner));
ATLASSERT(::IsWindow(hwndList));
ATLASSERT(!m_ctrlList.IsWindow()); // Only attach once
m_wndOwner = hwndOwner;
m_ctrlList.SubclassWindow(hwndList);
// Create the tooltip
DWORD dwStyle = WS_POPUP | TTS_NOPREFIX | TTS_ALWAYSTIP;
m_ctrlTip.Create(NULL, CWindow::rcDefault, NULL, dwStyle, WS_EX_TOPMOST);
ATLASSERT(m_ctrlTip.IsWindow());
m_ctrlTip.SetWindowPos(HWND_TOPMOST, 0,0,0,0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
// Add the ListView as a ToolTip tool...
::ZeroMemory(&m_ti, sizeof(m_ti));
m_ti.cbSize = sizeof(TOOLINFO);
m_ti.uFlags = TTF_IDISHWND | TTF_TRACK | TTF_ABSOLUTE;
m_ti.hwnd = hwndOwner;
m_ti.hinst = _Module.GetResourceInstance();
m_ti.uId = (UINT) (HWND) m_ctrlList;
m_ti.lpszText = LPSTR_TEXTCALLBACK;
m_ctrlTip.AddTool(&m_ti);
m_ctrlTip.TrackActivate(&m_ti, FALSE);
}
// Message handlers
LRESULT OnMouseLeave(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
ATLASSERT(m_ctrlList.IsWindow());
ATLASSERT(m_ctrlTip.IsWindow());
m_bTrackingMouseLeave = false;
m_wndOwner.KillTimer(TIMER_ID);
m_ctrlTip.TrackActivate(&m_ti, FALSE);
bHandled = FALSE;
return 0;
}
LRESULT OnMouseMove(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
{
ATLASSERT(m_ctrlList.IsWindow());
ATLASSERT(m_ctrlTip.IsWindow());
bHandled = FALSE;
m_wndOwner.KillTimer(TIMER_ID);
if( !m_bTrackingMouseLeave ) {
TRACKMOUSEEVENT tme = { 0 };
tme.cbSize = sizeof(TRACKMOUSEEVENT);
tme.dwFlags = TME_LEAVE;
tme.hwndTrack = m_ctrlList;
::_TrackMouseEvent(&tme);
m_bTrackingMouseLeave = true;
}
POINT pt = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
UINT iFlags = 0;
int item = m_ctrlList.HitTest(pt, &iFlags);
int nWidth = m_ctrlList.GetColumnWidth(0);
if( item == -1 || pt.x > nWidth) {
// Not hovering over any list item? Turn ToolTip off.
m_ctrlTip.TrackActivate(&m_ti, FALSE);
}
else {
bool bTipVisible = m_ctrlTip.GetCurrentTool(NULL) != 0;
if( !bTipVisible )
{
// Start a timer. If it triggers, the ToolTip has hovered over
// the same item for some time...
m_ctrlList.ClientToScreen(&pt);
m_ctrlTip.TrackPosition(pt.x + X_OFFSET, pt.y + Y_OFFSET);
m_wndOwner.SetTimer(TIMER_ID, m_ctrlTip.GetDelayTime(TTDT_INITIAL));
m_iCurItem = item;
}
else
{
// Already visible! If we're hovering over a new
// item, change tip text...
m_ctrlList.ClientToScreen(&pt);
m_ctrlTip.TrackPosition(pt.x + X_OFFSET, pt.y + Y_OFFSET);
if( m_iCurItem != item )
{
m_iCurItem = item;
m_ctrlTip.TrackActivate(&m_ti, FALSE);
m_wndOwner.SetTimer(TIMER_ID, m_ctrlTip.GetDelayTime(TTDT_INITIAL));
}
}
}
return 0;
}
LRESULT OnTimer(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
{
bHandled = FALSE;
if( wParam != TIMER_ID ) return 0;
m_ctrlTip.TrackActivate(&m_ti, TRUE);
return 0;
}
LRESULT OnGetDispInfo(int /*idCtrl*/, LPNMHDR pnmh, BOOL& bHandled)
{
if( pnmh->hwndFrom != m_ctrlTip ) {
bHandled = FALSE;
return 0;
}
//::wsprintf(lpnmtdi->szText, "Item %d", m_iCurItem);
return 0;
}
};
#endif // !defined(AFX_LISTVIEWTRACKTIP_H__20030113_F7A2_CF82_8F7F_0080AD509054__INCLUDED_)
| [
"ken.shao@ba8f1dc9-3c1c-0410-9eed-0f8a660c14bd"
]
| [
[
[
1,
203
]
]
]
|
728a317040aa5da15f97a51aeadcc8ae80351ae6 | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/Dependencies/Xerces/include/xercesc/util/HashPtr.cpp | 236e6553dac4e86ae126f5d2a899ad83e234fba3 | []
| no_license | svn2github/ngene | b2cddacf7ec035aa681d5b8989feab3383dac012 | 61850134a354816161859fe86c2907c8e73dc113 | refs/heads/master | 2023-09-03T12:34:18.944872 | 2011-07-27T19:26:04 | 2011-07-27T19:26:04 | 78,163,390 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,084 | cpp | /*
* Copyright 1999-2000,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <xercesc/util/HashPtr.hpp>
XERCES_CPP_NAMESPACE_BEGIN
HashPtr::HashPtr()
{
}
HashPtr::~HashPtr()
{
}
unsigned int HashPtr::getHashVal(const void *const key, unsigned int mod
, MemoryManager* const)
{
return ((long)key % (unsigned long)mod);
}
bool HashPtr::equals(const void *const key1, const void *const key2)
{
return (key1 == key2);
}
XERCES_CPP_NAMESPACE_END
| [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
]
| [
[
[
1,
40
]
]
]
|
ebf6e90e390f77bdef36abdf2513386fe284e066 | 709cd826da3ae55945fd7036ecf872ee7cdbd82a | /Term/WildMagic2/Source/Numerics/WmlOdeEuler.h | 74e25121d979da9de3ced18d2f6403cca2b23ab0 | []
| no_license | argapratama/kucgbowling | 20dbaefe1596358156691e81ccceb9151b15efb0 | 65e40b6f33c5511bddf0fa350c1eefc647ace48a | refs/heads/master | 2018-01-08T15:27:44.784437 | 2011-06-19T15:23:39 | 2011-06-19T15:23:39 | 36,738,655 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 913 | h | // Magic Software, Inc.
// http://www.magic-software.com
// http://www.wild-magic.com
// Copyright (c) 2003. All Rights Reserved
//
// The Wild Magic Library (WML) source code is supplied under the terms of
// the license agreement http://www.magic-software.com/License/WildMagic.pdf
// and may not be copied or disclosed except in accordance with the terms of
// that agreement.
#ifndef WMLODEEULER_H
#define WMLODEEULER_H
#include "WmlOdeSolver.h"
namespace Wml
{
template <class Real>
class WML_ITEM OdeEuler : public OdeSolver<Real>
{
public:
OdeEuler (int iDim, Real fStep, typename OdeSolver<Real>::Function* aoF,
void* pvData = NULL);
virtual void Update (Real fTIn, Real* afXIn, Real& rfTOut,
Real* afXOut);
virtual void SetStepSize (Real fStep);
};
typedef OdeEuler<float> OdeEulerf;
typedef OdeEuler<double> OdeEulerd;
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
37
]
]
]
|
2b1b2e64ae1b5b54efbc174ccc537d52f8f644b9 | 5e72c94a4ea92b1037217e31a66e9bfee67f71dd | /older/tptest5/src/ToolsPanel.cpp | 76a1fe71f5ec52f4210ee1522a563482a1c5c2ce | []
| no_license | stein1/bbk | 1070d2c145e43af02a6df14b6d06d9e8ed85fc8a | 2380fc7a2f5bcc9cb2b54f61e38411468e1a1aa8 | refs/heads/master | 2021-01-17T23:57:37.689787 | 2011-05-04T14:50:01 | 2011-05-04T14:50:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,171 | cpp | #include "ToolsPanel.h"
enum {
wxID_TOOLS_BOOK
};
ToolsPanel::ToolsPanel( wxWindow *parent )
:wxPanel( parent, wxID_ANY )
{
// Create the sizer for the main frame and the pages
m_SizerMain = new wxBoxSizer( wxVERTICAL );
// Create Notebook
m_BookMain = new wxNotebook( this, wxID_TOOLS_BOOK, wxDefaultPosition, wxDefaultSize, wxNB_TOP );
// Create and add the pages to book
m_PageTPTest = new TPTestPanel( m_BookMain );
m_PageIFConfig = new IFConfigPanel( m_BookMain );
m_PageNetStat = new NetstatPanel( m_BookMain );
m_PagePing = new PingPanel( m_BookMain );
m_PageTraceroute = new TraceroutePanel( m_BookMain );
m_BookMain->AddPage( m_PageTPTest, wxT("TPTEST 3") );
m_BookMain->AddPage( m_PageIFConfig, wxT("IFConfig") );
m_BookMain->AddPage( m_PageNetStat, wxT("NetStat") );
m_BookMain->AddPage( m_PagePing, wxT("Ping") );
m_BookMain->AddPage( m_PageTraceroute, wxT("Traceroute") );
// Add book to main sizer
m_SizerMain->Add( m_BookMain,
1,
wxEXPAND |
wxALL,
0 );
this->SetSizer( m_SizerMain );
//m_SizerMain->SetSizeHints( this );
}
ToolsPanel::~ToolsPanel(void)
{
}
| [
"[email protected]"
]
| [
[
[
1,
43
]
]
]
|
b9eec53c73f5e0d144e9abac9a802ce125978b92 | bfcc0f6ef5b3ec68365971fd2e7d32f4abd054ed | /kguicookies.h | 61f1b5e4af9b52d2e6ad2d742818105809a1545f | []
| no_license | cnsuhao/kgui-1 | d0a7d1e11cc5c15d098114051fabf6218f26fb96 | ea304953c7f5579487769258b55f34a1c680e3ed | refs/heads/master | 2021-05-28T22:52:18.733717 | 2011-03-10T03:10:47 | 2011-03-10T03:10:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,702 | h | #ifndef __KGUICOOKIES__
#define __KGUICOOKIES__
#include "kguixml.h"
/*! @class kGUICookie
@brief this class is for holding cookies
@ingroup Online */
class kGUICookie : public Links<kGUICookie>
{
public:
kGUICookie();
~kGUICookie();
void SetAttribute(unsigned int att,kGUIString *value,kGUIString *domain,kGUIString *subdomain,kGUIString *url);
void SetName(kGUIString *name) {m_name.SetString(name);}
kGUIString *GetName(void) {return &m_name;}
void SetValue(kGUIString *value) {m_value.SetString(value);}
kGUIString *GetValue(void) {return &m_value;}
void SetDomain(kGUIString *domain) {m_domain.SetString(domain);}
kGUIString *GetDomain(void) {return &m_domain;}
void SetPath(kGUIString *path) {m_path.SetString(path);}
kGUIString *GetPath(void) {return &m_path;}
void SetExpiry(kGUIString *expiry) {m_expiry.Set(expiry->GetString());}
kGUIDate *GetExpiry(void) {return &m_expiry;}
void SetPort(int port) {m_port=port;}
int GetPort(void) {return m_port;}
void SetRemove(bool r) {m_remove=r;}
bool GetRemove(void) {return m_remove;}
void SetSecure(bool s) {m_secure=s;}
bool GetSecure(void) {return m_secure;}
void SetPermanent(bool p) {m_permanent=p;}
bool GetPermanent(void) {return m_permanent;}
bool GetError(void) {return m_error;}
private:
bool Set(kGUIString *line);
kGUIString m_name;
kGUIString m_value;
kGUIString m_domain;
int m_port;
kGUIString m_path;
bool m_secure:1;
bool m_remove:1;
bool m_permanent:1;
bool m_error:1;
kGUIDate m_expiry;
};
/*! @class kGUICookieDomain
@brief this class is for handling a domains cookies
@ingroup Online */
class kGUICookieDomain
{
public:
kGUICookieDomain() {}
~kGUICookieDomain();
kGUICookie *GetFirst(void) {return m_links.GetFirst();}
kGUICookie *GetTail(void) {return m_links.GetTail();}
private:
//linked list of cookies attached to this domain, sorted so longer paths are first
LinkEnds<kGUICookie,kGUICookie> m_links;
};
/*! @class kGUICookieJar
@brief this class is for handling all the domains and their cookies
@ingroup Online */
class kGUICookieJar
{
public:
kGUICookieJar();
~kGUICookieJar();
void Load(kGUIXMLItem *root);
void Save(kGUIXMLItem *root);
void SetCookie(kGUIString *s,kGUIString *domain,kGUIString *url);
void UpdateCookie(kGUICookie *cookie);
void GetCookies(kGUIString *s,kGUIString *domain,kGUIString *url,bool issecure);
unsigned int GetCookieList(Array<kGUICookie *>*cookielist);
private:
void GetSubDomain(kGUIString *domain,kGUIString *subdomain);
Hash m_atthash;
Hash m_domainhash;
Hash m_cookiehash;
kGUIMutex m_busymutex;
};
#endif
| [
"[email protected]@4b35e2fd-144d-0410-91a6-811dcd9ab31d"
]
| [
[
[
1,
97
]
]
]
|
7164cdf72264a694163e9836e9d147c96a77ae29 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/regex/v4/regex_replace.hpp | 38dac520f77b96afeddf7c9c31ed8d0172ee0a41 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,676 | hpp | /*
*
* Copyright (c) 1998-2002
* John Maddock
*
* Use, modification and distribution are subject to 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)
*
*/
/*
* LOCATION: see http://www.boost.org for most recent version.
* FILE regex_format.hpp
* VERSION see <boost/version.hpp>
* DESCRIPTION: Provides formatting output routines for search and replace
* operations. Note this is an internal header file included
* by regex.hpp, do not include on its own.
*/
#ifndef BOOST_REGEX_V4_REGEX_REPLACE_HPP
#define BOOST_REGEX_V4_REGEX_REPLACE_HPP
namespace boost{
#ifdef BOOST_HAS_ABI_HEADERS
# include BOOST_ABI_PREFIX
#endif
template <class OutputIterator, class BidirectionalIterator, class traits, class charT>
OutputIterator regex_replace(OutputIterator out,
BidirectionalIterator first,
BidirectionalIterator last,
const basic_regex<charT, traits>& e,
const charT* fmt,
match_flag_type flags = match_default)
{
regex_iterator<BidirectionalIterator, charT, traits> i(first, last, e, flags);
regex_iterator<BidirectionalIterator, charT, traits> j;
if(i == j)
{
if(!(flags & regex_constants::format_no_copy))
out = re_detail::copy(first, last, out);
}
else
{
BidirectionalIterator last_m(first);
while(i != j)
{
if(!(flags & regex_constants::format_no_copy))
out = re_detail::copy(i->prefix().first, i->prefix().second, out);
out = i->format(out, fmt, flags, e);
last_m = (*i)[0].second;
if(flags & regex_constants::format_first_only)
break;
++i;
}
if(!(flags & regex_constants::format_no_copy))
out = re_detail::copy(last_m, last, out);
}
return out;
}
template <class OutputIterator, class Iterator, class traits, class charT>
inline OutputIterator regex_replace(OutputIterator out,
Iterator first,
Iterator last,
const basic_regex<charT, traits>& e,
const std::basic_string<charT>& fmt,
match_flag_type flags = match_default)
{
return regex_replace(out, first, last, e, fmt.c_str(), flags);
}
template <class traits, class charT>
std::basic_string<charT> regex_replace(const std::basic_string<charT>& s,
const basic_regex<charT, traits>& e,
const charT* fmt,
match_flag_type flags = match_default)
{
std::basic_string<charT> result;
re_detail::string_out_iterator<std::basic_string<charT> > i(result);
regex_replace(i, s.begin(), s.end(), e, fmt, flags);
return result;
}
template <class traits, class charT>
std::basic_string<charT> regex_replace(const std::basic_string<charT>& s,
const basic_regex<charT, traits>& e,
const std::basic_string<charT>& fmt,
match_flag_type flags = match_default)
{
std::basic_string<charT> result;
re_detail::string_out_iterator<std::basic_string<charT> > i(result);
regex_replace(i, s.begin(), s.end(), e, fmt.c_str(), flags);
return result;
}
#ifdef BOOST_HAS_ABI_HEADERS
# include BOOST_ABI_SUFFIX
#endif
} // namespace boost
#endif // BOOST_REGEX_V4_REGEX_REPLACE_HPP
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
]
| [
[
[
1,
108
]
]
]
|
13f5d691d8a4c626449fff0e3233a46c637ea089 | dca366f7f7597c87e3b7936c5f4f8dbc612a7fec | /BotNet/client/CrazyUncleBurton/c/chains/AttackChain.h | bdd3048637c4a36de9234b7880a7017ccfc8f083 | []
| no_license | mojomojomojo/MegaMinerAI | 6e0183b45f20e57af90e31a412c303f9b3e508d7 | 4457c8255583c10da3ed683ec352f32e1b35295a | refs/heads/master | 2020-05-18T10:44:16.037341 | 2011-12-12T17:13:46 | 2011-12-12T17:13:46 | 2,779,888 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 227 | h | #ifndef ATTACKCHAINH_H
#define ATTACKCHAINH_H
#include "ChainH.h"
class AttackChain : public Chain_base
{
public:
AttackChain(AI* ai);
bool spawnMore();
bool advance();
bool kidnap(int virusID);
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
15
]
]
]
|
aff6716fff3df82f94ceb2690355c25ac144303e | e2e49023f5a82922cb9b134e93ae926ed69675a1 | /tools/aoslcpp/source/aosl/resource_id.cpp | 8c8291c25f16e8dc8f8b37b67cb22611a6efef01 | []
| no_license | invy/mjklaim-freewindows | c93c867e93f0e2fe1d33f207306c0b9538ac61d6 | 30de8e3dfcde4e81a57e9059dfaf54c98cc1135b | refs/heads/master | 2021-01-10T10:21:51.579762 | 2011-12-12T18:56:43 | 2011-12-12T18:56:43 | 54,794,395 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,420 | cpp | // Copyright (C) 2005-2010 Code Synthesis Tools CC
//
// This program was generated by CodeSynthesis XSD, an XML Schema
// to C++ data binding compiler, in the Proprietary License mode.
// You should have received a proprietary license from Code Synthesis
// Tools CC prior to generating this code. See the license text for
// conditions.
//
// Begin prologue.
//
#define AOSLCPP_SOURCE
//
// End prologue.
#include <xsd/cxx/pre.hxx>
#include "aosl/resource_id.hpp"
#include <xsd/cxx/xml/dom/wildcard-source.hxx>
#include <xsd/cxx/xml/dom/parsing-source.hxx>
#include <xsd/cxx/tree/type-factory-map.hxx>
#include <xsd/cxx/tree/comparison-map.hxx>
namespace _xsd
{
static
const ::xsd::cxx::tree::type_factory_plate< 0, char >
type_factory_plate_init;
static
const ::xsd::cxx::tree::comparison_plate< 0, char >
comparison_plate_init;
}
namespace aosl
{
// Resource_id
//
Resource_id::
Resource_id (const ::xml_schema::Id& _xsd_Id_base)
: ::aosl::Unique_id (_xsd_Id_base)
{
}
Resource_id::
Resource_id (const Resource_id& x,
::xml_schema::Flags f,
::xml_schema::Container* c)
: ::aosl::Unique_id (x, f, c)
{
}
Resource_id::
Resource_id (const ::xercesc::DOMElement& e,
::xml_schema::Flags f,
::xml_schema::Container* c)
: ::aosl::Unique_id (e, f, c)
{
}
Resource_id::
Resource_id (const ::xercesc::DOMAttr& a,
::xml_schema::Flags f,
::xml_schema::Container* c)
: ::aosl::Unique_id (a, f, c)
{
}
Resource_id::
Resource_id (const ::std::string& s,
const ::xercesc::DOMElement* e,
::xml_schema::Flags f,
::xml_schema::Container* c)
: ::aosl::Unique_id (s, e, f, c)
{
}
Resource_id* Resource_id::
_clone (::xml_schema::Flags f,
::xml_schema::Container* c) const
{
return new class Resource_id (*this, f, c);
}
Resource_id::
~Resource_id ()
{
}
}
#include <ostream>
#include <xsd/cxx/tree/std-ostream-map.hxx>
namespace _xsd
{
static
const ::xsd::cxx::tree::std_ostream_plate< 0, char >
std_ostream_plate_init;
}
namespace aosl
{
::std::ostream&
operator<< (::std::ostream& o, const Resource_id& i)
{
o << static_cast< const ::aosl::Unique_id& > (i);
return o;
}
}
#include <istream>
#include <xsd/cxx/xml/sax/std-input-source.hxx>
#include <xsd/cxx/tree/error-handler.hxx>
namespace aosl
{
}
#include <ostream>
#include <xsd/cxx/tree/error-handler.hxx>
#include <xsd/cxx/xml/dom/serialization-source.hxx>
#include <xsd/cxx/tree/type-serializer-map.hxx>
namespace _xsd
{
static
const ::xsd::cxx::tree::type_serializer_plate< 0, char >
type_serializer_plate_init;
}
namespace aosl
{
void
operator<< (::xercesc::DOMElement& e, const Resource_id& i)
{
e << static_cast< const ::aosl::Unique_id& > (i);
}
void
operator<< (::xercesc::DOMAttr& a, const Resource_id& i)
{
a << static_cast< const ::aosl::Unique_id& > (i);
}
void
operator<< (::xml_schema::ListStream& l,
const Resource_id& i)
{
l << static_cast< const ::aosl::Unique_id& > (i);
}
}
#include <xsd/cxx/post.hxx>
// Begin epilogue.
//
//
// End epilogue.
| [
"klaim@localhost"
]
| [
[
[
1,
169
]
]
]
|
78a1307685df951e67ccf9ef6b6eda09ae15357f | 4ecb7e18f351ee920a6847c7ebd9010b6a5d34ce | /HD/trunk/HuntingDragon/gametutor/header/CVSView.h | 5a1620ba6d649bf28d25b83ab14067eb0eaf5fcb | []
| no_license | dogtwelve/bkiter08-gameloft-internship-2011 | 505141ea314c234d99652600db5165a22cf041c3 | 0efc9f009bf12fe4ed36e1abfeb34f346a8c4198 | refs/heads/master | 2021-01-10T12:16:51.540936 | 2011-10-27T13:30:50 | 2011-10-27T13:30:50 | 46,549,117 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,256 | h | #ifndef __CVSVIEW_H__
#define __CVSVIEW_H__
#include "Header.h"
#include "CSingleton.h"
#if (CONFIG_PLATFORM==PLATFORM_WIN32_VS)
namespace GameTutor
{
class CVSView: public CAbsSingleton<CVSView>
{
public:
CVSView(__INT32 w, __INT32 h, bool fullscreen = false, const char*name = 0);
virtual ~CVSView();
void Update();
void UpdateView();
static void Render(ESContext* esContext);
static void OnTouchDown(ESContext* esContext, int x, int y);
static void OnTouchUp(ESContext* esContext, int x, int y);
static void OnTouchMove(ESContext* esContext, WPARAM wparam, int x, int y);
static void KeyFunc(ESContext* esContext, unsigned char key, int x, int y);
static void KeyUpFunc(ESContext* esContext, unsigned char key);
__INT32 GetWidth() {return m_iWidth;}
__INT32 GetHeight() {return m_iHeight;}
__INT32 IsFullScreen() {return m_isFullScreen;}
void SetContext(ESContext* esContext);
void RefreshOpenGL();
void StartMainLoop();
private:
ESContext* esContext;
__INT32 m_iWidth;
__INT32 m_iHeight;
bool m_isFullScreen;
char *m_strTitle;
void Destroy();
bool m_isLeftMouseDown;
bool m_isKeyDown;
};
}
#endif //(CONFIG_PLATFORM==PLATFORM_WIN32_VS)
#endif | [
"[email protected]"
]
| [
[
[
1,
46
]
]
]
|
99e0652be1f52f1532ae79d8e65a81c63e987705 | 0b66a94448cb545504692eafa3a32f435cdf92fa | /tags/0.8/cbear.berlios.de/base/noncreatable.hpp | 18025ad66773ca5f39c8f1afb721b1854e95a7ca | [
"MIT"
]
| permissive | BackupTheBerlios/cbear-svn | e6629dfa5175776fbc41510e2f46ff4ff4280f08 | 0109296039b505d71dc215a0b256f73b1a60b3af | refs/heads/master | 2021-03-12T22:51:43.491728 | 2007-09-28T01:13:48 | 2007-09-28T01:13:48 | 40,608,034 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 411 | hpp | #ifndef CBEAR_BERLIOS_DE_BASE_NONCREATABLE_HPP_INCLUDED
#define CBEAR_BERLIOS_DE_BASE_NONCREATABLE_HPP_INCLUDED
// boost::mpl::bool_
#include <boost/mpl/bool.hpp>
namespace cbear_berlios_de
{
namespace base
{
class noncreatable
{
private:
noncreatable() {}
noncreatable(const noncreatable &) {}
noncreatable &operator=(const noncreatable &) {}
~noncreatable() {}
};
}
}
#endif
| [
"sergey_shandar@e6e9985e-9100-0410-869a-e199dc1b6838"
]
| [
[
[
1,
24
]
]
]
|
3a414d5fe55d4cfdbd81b8447adf3cd62d167de8 | ef23e388061a637f82b815d32f7af8cb60c5bb1f | /src/mame/includes/sprcros2.h | 91267571f488f1c3a5bbb39ac1e0b7c4f8282c08 | []
| no_license | marcellodash/psmame | 76fd877a210d50d34f23e50d338e65a17deff066 | 09f52313bd3b06311b910ed67a0e7c70c2dd2535 | refs/heads/master | 2021-05-29T23:57:23.333706 | 2011-06-23T20:11:22 | 2011-06-23T20:11:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 682 | h | class sprcros2_state : public driver_device
{
public:
sprcros2_state(running_machine &machine, const driver_device_config_base &config)
: driver_device(machine, config) { }
UINT8 m_s_port3;
UINT8 m_port7;
tilemap_t *m_bgtilemap;
tilemap_t *m_fgtilemap;
UINT8 *m_fgvideoram;
UINT8 *m_bgvideoram;
UINT8 *m_spriteram;
size_t m_spriteram_size;
};
/*----------- defined in video/sprcros2.c -----------*/
WRITE8_HANDLER( sprcros2_fgvideoram_w );
WRITE8_HANDLER( sprcros2_bgvideoram_w );
WRITE8_HANDLER( sprcros2_bgscrollx_w );
WRITE8_HANDLER( sprcros2_bgscrolly_w );
PALETTE_INIT( sprcros2 );
VIDEO_START( sprcros2 );
SCREEN_UPDATE( sprcros2 );
| [
"Mike@localhost"
]
| [
[
[
1,
27
]
]
]
|
d397c1c13bd24d12931b9410550f1029581b99df | 52dd8bdffaa5d7e450477b7f3955dbe0d26b7473 | /sort/merge-sort/merge-sort.cpp | ac3e7df6d21ef41901bda334fb3689d415f4ace2 | []
| no_license | xhbang/algorithms | 7475a4f3ed1a6877a0950eb3534edaeb2a6921a1 | 226229bc77e2926246617aa4a9db308096183a8c | refs/heads/master | 2021-01-25T04:57:53.425634 | 2011-12-05T09:57:09 | 2011-12-05T09:57:09 | 2,352,910 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 909 | cpp | #include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
const int d[5]={8,6,4,2,1}; //最后一个增量必须是1,相当于直接插入排序
const int times=200000;
const int maxSize=20;
typedef struct Node{
int key;
int data;
}Node;
class Order{
Node my[maxSize]; //0号元素temp
Node help[maxSize]; //辅助空间
int size;
// clock_t start,finish; //计算时间
public:
Order(int i=0):size(i){}
void display(ostream &out);
void init();
};
void Order::init(){
srand(time(NULL));
for(int i=1;i<=size;i++){
my[i].data=rand()%100;
my[i].key=i;
}
}
void Order::display(ostream &out){
for(int i=1;i<=size;i++)
out<<my[i].key<<" ";
out<<endl;
for(int i=1;i<=size;i++)
out<<my[i].data<<" ";
out<<endl;
}
int main(){
Order order(19); //最多19
order.init();
order.display(cout);
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
51
]
]
]
|
b56efdd25e321884084b0c0c05c9d37bac905ec2 | 6b83c731acb331c4f7ddd167ab5bb562b450d0f2 | /ScriptEngine/src/GM_Save.cpp | 8b91408a22384b879c167069f2a8526dfae2a64c | []
| no_license | weimingtom/toheart2p | fbfb96f6ca8d3102b462ba53d3c9cff16ca509e7 | 560e99c42fdff23e65f16df6d14df9a9f1868d8e | refs/heads/master | 2021-01-10T01:36:31.515707 | 2007-12-20T15:13:51 | 2007-12-20T15:13:51 | 44,464,730 | 2 | 0 | null | null | null | null | GB18030 | C++ | false | false | 7,198 | cpp |
#include <mm_std.h>
#include "main.h"
#include "Escript.h"
#include "GM_Avg.h"
#include "GM_Save.h"
#include "disp.h"
typedef struct
{
int ver_no;
int sin_no;
SYSTEMTIME sys_time; //系统时间
char message[32]; //读存档时显示的简单略语
RGB24 thumbnail[80*60]; //缩略图
}SAVE_HEADER; //存档文件头
typedef struct
{
SAVE_HEADER save_head; //存档文件头
EXEC_DATA EXEC_ScriptInfo;
char NowScriptFileName[64]; //保存时的脚本文件名
int RunScriptBlockNo;
int PrevRunScriptBlockNo;
int ESC_FlagBuf[ ESC_FLAG_MAX ];
AVG_SAVE_DATA sdata;
}SAVE_STRUCT; //存档文件结构体
SAVE_STRUCT SaveStruct; //游戏存档文件结构体
void SAV_CreateSaveHead(void)
{
int _times = ESC_GetFlag( _TIME );
int _days = ESC_GetFlag( _DAY );
int _month = ESC_GetFlag( _MONTH );
SaveStruct.save_head.ver_no = 1;
SaveStruct.save_head.sin_no = (_month<<16) | (_days<<8) | _times;
GetLocalTime( &SaveStruct.save_head.sys_time );
DSP_SetGraph( GRP_WORK, BMP_CAP, 0, ON, CHK_HOKAN );
DSP_SetGraphPosZoom( GRP_WORK, 0, 0, 80, 60, 0, 0, 800, 600 );
DSP_CreateBmp( BMP_WORK, BMP_FULL, 80, 60 );
DSP_SetGraphTarget( GRP_WORK, BMP_WORK, MainWindow.draw_mode2 );
BMP_F *bmp_f = (BMP_F *)DSP_GetBmp( BMP_WORK );
CopyMemory( SaveStruct.save_head.thumbnail, bmp_f->buf, 80*60*sizeof(RGB24) );
DSP_ResetGraph( GRP_WORK );
DSP_ReleaseBmp( BMP_WORK );
char *buf = SaveStruct.save_head.message;
char buf2[1024];
int k=0;
int j=0;
ZeroMemory( &SaveStruct.save_head.message, 32 );
ZeroMemory( buf2, 1024 );
DSP_GetTextDispStr( TXT_WINDOW, buf2 );
if(MapStep)
{
strcpy( buf, " MAP選択" );
}
else
{
strncpy( buf, buf2, 18 );
}
while( buf[k] && buf[k]!='\n' )
{
if( (0x00<=buf[k] && buf[k]<0x80) || (0xa0<=buf[k] && buf[k]<0xe0) )
{
if(k>=28)
{
j=1;
break;
}
else
{
k++;
}
}
else
{
if(k>=27)
{
j=1;
break;
}
else
{
k+=2;
}
}
}
if(j)
{
buf[k ]=0xA5;
buf[k+1]=0xA5;
buf[k+2]='\0';
}
else
buf[k]='\0';
}
//-------------------------------------------------------------------------
//函数名: SAV_LoadHeadTime
//功能: 读取存档时间文件头
//
//输入参数:
// 类型 参数名 意义
// int load_no 存档Shot
// SYSTEMTIME *sys_time(输出)读出的时间数据
//返回值:
// BOOL 成功返回TRUE;否则FALSE
BOOL SAV_LoadHeadTime( int load_no, SYSTEMTIME *sys_time )
{
char fname[256];
wsprintf( fname, "save_%02d.sav", load_no );
if( !STD_ReadFile( fname, (char*)&SaveStruct.save_head, sizeof(SYSTEMTIME)+8 ) )
return FALSE;
else
{
*sys_time = SaveStruct.save_head.sys_time;
return TRUE;
}
}
//-------------------------------------------------------------------------
//函数名: SAV_LoadHead
//功能: 读取存档文件头
//
//输入参数:
// 类型 参数名 意义
// int load_no 存档Shot
// char * mes(输出) 当前存档的简单提示内容
// SYSTEMTIME *sys_time(输出) 读出的时间数据
// BMP_SET *bmp_set(输出)
// int *game_time(输出)
//返回值:
// BOOL 成功返回TRUE
BOOL SAV_LoadHead( int load_no, char *mes, SYSTEMTIME *sys_time, BMP_SET *bmp_set, int *game_time )
{
char fname[256];
//初始化位图集结构
if(bmp_set)
{
ZeroMemory( bmp_set, sizeof(BMP_SET) );
bmp_set->flag=1;
bmp_set->bmp_bit=BMP_FULL;
bmp_set->alp_flag=0;
bmp_set->pos.x=0;
bmp_set->pos.y=0;
bmp_set->size.x=80;
bmp_set->size.y=60;
}
wsprintf( fname, "save_%02d.sav", load_no );
//根据生成的存档文件名,读取存档
if( !STD_ReadFile( fname, (char*)&SaveStruct.save_head, sizeof(SaveStruct.save_head)) )
return FALSE;
else
{
if(mes)
{ //缩略信息加载
wsprintf( mes, "%s", SaveStruct.save_head.message );
}
if(bmp_set)
{ //缩略图加载
bmp_set->bmp_f.buf = SaveStruct.save_head.thumbnail;
bmp_set->bmp_f.sx=80;
bmp_set->bmp_f.sy=60;
}
//获得存档的时间
if(sys_time)
*sys_time = SaveStruct.save_head.sys_time;
//获得游戏时间
if(game_time)
*game_time = SaveStruct.save_head.sin_no;
return TRUE;
}
}
void SAV_SaveScript(void)
{
CopyMemory( SaveStruct.NowScriptFileName, NowLangFileName, 64 );
SaveStruct.EXEC_ScriptInfo = *EXEC_LangInfo;
SaveStruct.RunScriptBlockNo = RunLangBlockNo;
SaveStruct.PrevRunScriptBlockNo = PrevRunLangBlockNo;
}
//-------------------------------------------------------------------------
//函数名: SAV_LoadScript
//功能: 从存档中读取存档结构到内存
//
//输入参数:无
// 类型 参数名 意义
//返回值:
// 无
void SAV_LoadScript(void)
{
int digit=0;
ESC_InitEOprFlag( );
CopyMemory( NowLangFileName, SaveStruct.NowScriptFileName, 64 );
*EXEC_LangInfo = SaveStruct.EXEC_ScriptInfo;
EXEC_LangInfo->LangBuf=NULL;
RunLangBlockNo = SaveStruct.RunScriptBlockNo;
PrevRunLangBlockNo = SaveStruct.PrevRunScriptBlockNo;
EXEC_ReadLang( NowLangFileName, EXEC_LangInfo );
EXEC_LangInfo->BusyFlg = SaveStruct.EXEC_ScriptInfo.BusyFlg;
AVG_SetScenarioNo( GetScenarioNo(NowLangFileName) );
}
void SAV_ErrSave( char *buf )
{
char fname[256];
SAV_CreateSaveHead();
SAV_SaveScript();
CopyMemory( SaveStruct.ESC_FlagBuf, ESC_FlagBuf, sizeof(int)*ESC_FLAG_MAX );
AVG_SetSaveData( &SaveStruct.sdata );
wsprintf( fname, "err\\%s.sav", buf );
if( !STD_WriteFile( fname, (char*)&SaveStruct, sizeof(SaveStruct)) )
DebugPrintf( "ファイルが開けないにょ[%s]", fname );
}
void SAV_Save( int save_no )
{
char fname[256];
SAV_CreateSaveHead();
SAV_SaveScript();
CopyMemory( SaveStruct.ESC_FlagBuf, ESC_FlagBuf, sizeof(int)*ESC_FLAG_MAX );
AVG_SetSaveData( &SaveStruct.sdata );
if(save_no>=0)
{
wsprintf( fname, "save_%02d.sav", save_no );
}
else
{
wsprintf( fname, "save___.sav" );
}
if( !STD_WriteFile( fname, (char*)&SaveStruct, sizeof(SaveStruct)) )
{
DebugBox( NULL, "ファイルが開けないにょ[%s]", fname );
}
}
//-------------------------------------------------------------------------
//函数名: SAV_Load
//功能: 读入存档操作
//
//输入参数:
// 类型 参数名 意义
// int load_no 存档的Shot号
//返回值:
// 无
void SAV_Load( int load_no )
{
char fname[256];
if(load_no>=0)
wsprintf( fname, "save_%02d.sav", load_no );
else
wsprintf( fname, "save___.sav" );
if( !STD_ReadFile( fname, (char*)&SaveStruct, sizeof(SaveStruct)) )
DebugBox( NULL, "ファイルが開けないにょ[%s]", fname );
//存档把数据读入内存
SAV_LoadScript();
CopyMemory( ESC_FlagBuf, SaveStruct.ESC_FlagBuf, sizeof(int)*ESC_FLAG_MAX );
DefaultCharName = ESC_GetFlag( _DEFAULT_NAME );
AVG_SetLoadData( SaveStruct.sdata );
AVG_LoadWindow();
}
| [
"pspbter@13f3a943-b841-0410-bae6-1b2c8ac2799f"
]
| [
[
[
1,
301
]
]
]
|
5f3d20eea192999640c4d42b775a5bdefb6eb776 | 9ac7606c5aa3e851a597cca2cd64682d79940ed1 | /labpro-sdk/LabPro_console_src/LabPro_consoleDoc.h | ee63c0c428d73773f251a05117ec02460cc4c701 | []
| no_license | concord-consortium/labpro-usb | 18422f703f43d672cceb32eb7dae208a0b137274 | ad87bd11d3b574f51ac59b128db86aee9f449200 | HEAD | 2016-09-06T14:22:35.102192 | 2011-11-01T22:24:12 | 2011-11-01T22:24:12 | 2,369,348 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,779 | h | // LabPro_consoleDoc.h : interface of the CLabPro_consoleDoc class
//
/////////////////////////////////////////////////////////////////////////////
#if !defined(AFX_LABPRO_CONSOLEDOC_H__76256924_B0C2_470C_8D31_E8174588B9AF__INCLUDED_)
#define AFX_LABPRO_CONSOLEDOC_H__76256924_B0C2_470C_8D31_E8174588B9AF__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#define MAX_INPUT_BUFLEN 4000
class CLabPro_consoleDoc : public CDocument
{
protected: // create from serialization only
CLabPro_consoleDoc();
DECLARE_DYNCREATE(CLabPro_consoleDoc)
// Attributes
public:
//LabPro parms:
int m_LabPro_nNumChannels;
short m_LabPro_bBinaryMode;
short m_LabPro_bRealTime;
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CLabPro_consoleDoc)
public:
virtual BOOL OnNewDocument();
virtual void Serialize(CArchive& ar);
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CLabPro_consoleDoc();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
char m_input_buffer[MAX_INPUT_BUFLEN];
int m_input_buffer_next_byte_index;
protected:
// Generated message map functions
protected:
//{{AFX_MSG(CLabPro_consoleDoc)
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_LABPRO_CONSOLEDOC_H__76256924_B0C2_470C_8D31_E8174588B9AF__INCLUDED_)
| [
"scytacki@6e01202a-0783-4428-890a-84243c50cc2b"
]
| [
[
[
1,
65
]
]
]
|
122ec0a017f2f908acf6bb08881d9137ea32ad41 | fac8de123987842827a68da1b580f1361926ab67 | /inc/physics/Physics/Utilities/Serialize/hkpHavokSnapshot.h | 47aac65574f06287b5d847ef09aa72a995542e75 | []
| no_license | blockspacer/transporter-game | 23496e1651b3c19f6727712a5652f8e49c45c076 | 083ae2ee48fcab2c7d8a68670a71be4d09954428 | refs/heads/master | 2021-05-31T04:06:07.101459 | 2009-02-19T20:59:59 | 2009-02-19T20:59:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,933 | h | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
#ifndef HK_HAVOKSNAPSHOTPACKFILE_H
#define HK_HAVOKSNAPSHOTPACKFILE_H
#include <Common/Serialize/Packfile/hkPackfileReader.h>
#include <Common/Serialize/Util/hkStructureLayout.h>
#include <Common/Serialize/Packfile/hkPackfileWriter.h>
/// This is a simple way to snapshot (serialize) the whole scene into a file.
/// This can be useful for debugging purposes.
class hkpHavokSnapshot
{
public:
/// Converts some objects to different types for snapshots.
class ConvertListener : public hkPackfileWriter::AddObjectListener
{
public:
~ConvertListener();
virtual void addObjectCallback( ObjectPointer& p, ClassPointer& k );
hkArray<hkReferencedObject*> m_objects;
};
/// Save a snapshot of the world to filename in packfile form (binary).
/// Returns true on success
/// If you don't provide a target layout then the current host layout is assumed.
/// NOTE: some objects are inherently not serializable because they point to
/// external memory. i.e. The vertex and index arrays of an hkpMeshShape. When these objects
/// are encountered, we convert them before saving. i.e hkpMeshShape -> hkpStorageMeshShape.
static hkBool HK_CALL save(const class hkpWorld* world, hkStreamWriter* writer, hkBool binaryFormat = true, const hkStructureLayout::LayoutRules* targetLayout = HK_NULL, bool saveContactPoints = false );
/// Save a snapshot of a hkpPhysicsData to filename.
static hkBool HK_CALL save( const class hkpPhysicsData* data, hkStreamWriter* writer, hkBool binaryFormat = true, const hkStructureLayout::LayoutRules* targetLayout = HK_NULL );
/// Save a snapshot of a given object under a RootLevelContainer to the given stream
static hkBool HK_CALL saveUnderRootLevel( const void* data, const hkClass& dataClass, hkStreamWriter* writer, hkBool binaryFormat = true, const hkStructureLayout::LayoutRules* targetLayout = HK_NULL );
/// Save a snapshot of a given object to filename.
static hkBool HK_CALL save( const void* data, const hkClass& dataClass, hkStreamWriter* writer, hkBool binaryFormat = true, const hkStructureLayout::LayoutRules* targetLayout = HK_NULL, hkPackfileWriter::AddObjectListener* userListener = HK_NULL );
/// Load a snapshot from a filename in packfile form. It will search
/// the root level container in the file for a hkpPhysicsData class. It will autodetect
/// if the stream is a binary packfile or not (then assumed to be XML).
/// NOTE: remember to remove the reference from allocatedData once you are finished using the loaded data.
static class hkpPhysicsData* HK_CALL load(class hkStreamReader* reader, hkPackfileReader::AllocatedData** allocatedData);
};
#endif // HK_HAVOKSNAPSHOTSESSION_H
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529)
*
* Confidential Information of Havok. (C) Copyright 1999-2008
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at
* www.havok.com/tryhavok
*
*/
| [
"uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4"
]
| [
[
[
1,
72
]
]
]
|
2a9ed2a555656b3f241eddbe9f44bee441bf07ea | 33cdd09e352529963fe8b28b04e0d2e33483777b | /trunk/word_plugin/ReportAsistent/MainObject.h | da300b9fef22596cd79cecec8632122fb162057c | []
| no_license | BackupTheBerlios/reportasistent-svn | 20e386c86b6990abafb679eeb9205f2aef1af1ac | 209650c8cbb0c72a6e8489b0346327374356b57c | refs/heads/master | 2020-06-04T16:28:21.972009 | 2010-05-18T12:06:48 | 2010-05-18T12:06:48 | 40,804,982 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 837 | h | // MainObject.h : Declaration of the CMainObject
#ifndef __MAINOBJECT_H_
#define __MAINOBJECT_H_
#include "resource.h" // main symbols
/////////////////////////////////////////////////////////////////////////////
// CMainObject
class ATL_NO_VTABLE CMainObject :
public CComObjectRootEx<CComSingleThreadModel>,
public CComCoClass<CMainObject, &CLSID_MainObject>,
public IDispatchImpl<IMainObject, &IID_IMainObject, &LIBID_REPORTASISTENTLib>
{
public:
CMainObject()
{
}
DECLARE_REGISTRY_RESOURCEID(IDR_MAINOBJECT)
DECLARE_PROTECT_FINAL_CONSTRUCT()
BEGIN_COM_MAP(CMainObject)
COM_INTERFACE_ENTRY(IMainObject)
COM_INTERFACE_ENTRY(IDispatch)
END_COM_MAP()
// IMainObject
public:
STDMETHOD(get_GetNextInsertElement)(/*[out, retval]*/ InsertElement* *pVal);
};
#endif //__MAINOBJECT_H_
| [
"dedej1am@fded5620-0c03-0410-a24c-85322fa64ba0"
]
| [
[
[
1,
34
]
]
]
|
a07c26204f06f4ac44f80d5dfe71d502d9acd62e | 8bbbcc2bd210d5608613c5c591a4c0025ac1f06b | /nes/mapper/112.cpp | 2eac2fd3fcfecb8cdb1a90e81b17d4f3257165bc | []
| no_license | PSP-Archive/NesterJ-takka | 140786083b1676aaf91d608882e5f3aaa4d2c53d | 41c90388a777c63c731beb185e924820ffd05f93 | refs/heads/master | 2023-04-16T11:36:56.127438 | 2008-12-07T01:39:17 | 2008-12-07T01:39:17 | 357,617,280 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,109 | cpp |
/////////////////////////////////////////////////////////////////////
// Mapper 112
void NES_mapper112_Init()
{
g_NESmapper.Reset = NES_mapper112_Reset;
g_NESmapper.MemoryWrite = NES_mapper112_MemoryWrite;
g_NESmapper.HSync = NES_mapper112_HSync;
}
void NES_mapper112_Reset()
{
// clear registers FIRST!!!
int i;
for(i = 0; i < 8; i++) g_NESmapper.Mapper112.regs[i] = 0x00;
// set CPU bank pointers
g_NESmapper.Mapper112.prg0 = 0;
g_NESmapper.Mapper112.prg1 = 1;
NES_mapper112_MMC3_set_CPU_banks();
// set VROM banks
if(g_NESmapper.num_1k_VROM_banks)
{
g_NESmapper.Mapper112.chr01 = 0;
g_NESmapper.Mapper112.chr23 = 2;
g_NESmapper.Mapper112.chr4 = 4;
g_NESmapper.Mapper112.chr5 = 5;
g_NESmapper.Mapper112.chr6 = 6;
g_NESmapper.Mapper112.chr7 = 7;
NES_mapper112_MMC3_set_PPU_banks();
}
else
{
g_NESmapper.Mapper112.chr01 = g_NESmapper.Mapper112.chr23 = g_NESmapper.Mapper112.chr4 = g_NESmapper.Mapper112.chr5 = g_NESmapper.Mapper112.chr6 = g_NESmapper.Mapper112.chr7 = 0;
}
g_NESmapper.Mapper112.irq_enabled = 0;
g_NESmapper.Mapper112.irq_counter = 0;
g_NESmapper.Mapper112.irq_latch = 0;
}
void NES_mapper112_MemoryWrite(uint32 addr, uint8 data)
{
switch(addr & 0xE001)
{
case 0x8000:
{
g_NESmapper.Mapper112.regs[0] = data;
NES_mapper112_MMC3_set_PPU_banks();
NES_mapper112_MMC3_set_CPU_banks();
}
break;
case 0xA000:
{
uint32 bank_num;
g_NESmapper.Mapper112.regs[1] = data;
bank_num = g_NESmapper.Mapper112.regs[1];
switch(g_NESmapper.Mapper112.regs[0] & 0x07)
{
case 0x02:
{
if(g_NESmapper.num_1k_VROM_banks)
{
bank_num &= 0xfe;
g_NESmapper.Mapper112.chr01 = bank_num;
NES_mapper112_MMC3_set_PPU_banks();
}
}
break;
case 0x03:
{
if(g_NESmapper.num_1k_VROM_banks)
{
bank_num &= 0xfe;
g_NESmapper.Mapper112.chr23 = bank_num;
NES_mapper112_MMC3_set_PPU_banks();
}
}
break;
case 0x04:
{
if(g_NESmapper.num_1k_VROM_banks)
{
g_NESmapper.Mapper112.chr4 = bank_num;
NES_mapper112_MMC3_set_PPU_banks();
}
}
break;
case 0x05:
{
if(g_NESmapper.num_1k_VROM_banks)
{
g_NESmapper.Mapper112.chr5 = bank_num;
NES_mapper112_MMC3_set_PPU_banks();
}
}
break;
case 0x06:
{
if(g_NESmapper.num_1k_VROM_banks)
{
g_NESmapper.Mapper112.chr6 = bank_num;
NES_mapper112_MMC3_set_PPU_banks();
}
}
break;
case 0x07:
{
if(g_NESmapper.num_1k_VROM_banks)
{
g_NESmapper.Mapper112.chr7 = bank_num;
NES_mapper112_MMC3_set_PPU_banks();
}
}
break;
case 0x00:
{
g_NESmapper.Mapper112.prg0 = bank_num;
NES_mapper112_MMC3_set_CPU_banks();
}
break;
case 0x01:
{
g_NESmapper.Mapper112.prg1 = bank_num;
NES_mapper112_MMC3_set_CPU_banks();
}
break;
}
}
break;
case 0x8001:
{
g_NESmapper.Mapper112.regs[2] = data;
if(NES_ROM_get_mirroring() != NES_PPU_MIRROR_FOUR_SCREEN)
{
if(data & 0x01)
{
g_NESmapper.set_mirroring2(NES_PPU_MIRROR_VERT);
}
else
{
g_NESmapper.set_mirroring2(NES_PPU_MIRROR_HORIZ);
}
}
}
break;
case 0xA001:
{
g_NESmapper.Mapper112.regs[3] = data;
}
break;
case 0xC000:
{
g_NESmapper.Mapper112.regs[4] = data;
g_NESmapper.Mapper112.irq_counter = g_NESmapper.Mapper112.regs[4];
}
break;
case 0xC001:
{
g_NESmapper.Mapper112.regs[5] = data;
g_NESmapper.Mapper112.irq_latch = g_NESmapper.Mapper112.regs[5];
}
break;
case 0xE000:
{
g_NESmapper.Mapper112.regs[6] = data;
g_NESmapper.Mapper112.irq_enabled = 0;
if(data)
{
g_NESmapper.set_mirroring2(NES_PPU_MIRROR_HORIZ);
}
else
{
g_NESmapper.set_mirroring2(NES_PPU_MIRROR_VERT);
}
}
break;
case 0xE001:
{
g_NESmapper.Mapper112.regs[7] = data;
g_NESmapper.Mapper112.irq_enabled = 1;
}
break;
}
}
void NES_mapper112_HSync(uint32 scanline)
{
if(g_NESmapper.Mapper112.irq_enabled)
{
if((scanline >= 0) && (scanline <= 239))
{
if(NES_PPU_spr_enabled() || NES_PPU_bg_enabled())
{
if(!(g_NESmapper.Mapper112.irq_counter--))
{
g_NESmapper.Mapper112.irq_counter = g_NESmapper.Mapper112.irq_latch;
NES6502_DoIRQ();
}
}
}
}
}
void NES_mapper112_MMC3_set_CPU_banks()
{
if(g_NESmapper.Mapper112.regs[0] & 0x40)
{
g_NESmapper.set_CPU_banks4(g_NESmapper.num_8k_ROM_banks-2,g_NESmapper.Mapper112.prg1,g_NESmapper.Mapper112.prg0,g_NESmapper.num_8k_ROM_banks-1);
}
else
{
g_NESmapper.set_CPU_banks4(g_NESmapper.Mapper112.prg0,g_NESmapper.Mapper112.prg1,g_NESmapper.num_8k_ROM_banks-2,g_NESmapper.num_8k_ROM_banks-1);
}
}
void NES_mapper112_MMC3_set_PPU_banks()
{
if(g_NESmapper.num_1k_VROM_banks)
{
if(g_NESmapper.Mapper112.regs[0] & 0x80)
{
g_NESmapper.set_PPU_banks8(g_NESmapper.Mapper112.chr4,g_NESmapper.Mapper112.chr5,g_NESmapper.Mapper112.chr6,g_NESmapper.Mapper112.chr7,g_NESmapper.Mapper112.chr01,g_NESmapper.Mapper112.chr01+1,g_NESmapper.Mapper112.chr23,g_NESmapper.Mapper112.chr23+1);
}
else
{
g_NESmapper.set_PPU_banks8(g_NESmapper.Mapper112.chr01,g_NESmapper.Mapper112.chr01+1,g_NESmapper.Mapper112.chr23,g_NESmapper.Mapper112.chr23+1,g_NESmapper.Mapper112.chr4,g_NESmapper.Mapper112.chr5,g_NESmapper.Mapper112.chr6,g_NESmapper.Mapper112.chr7);
}
}
}
#define MAP112_ROM(ptr) (((ptr)-NES_ROM_get_ROM_banks()) >> 13)
#define MAP112_VROM(ptr) (((ptr)-NES_ROM_get_VROM_banks()) >> 10)
void NES_mapper112_SNSS_fixup()
{
nes6502_context context;
NES6502_GetContext(&context);
g_NESmapper.Mapper112.prg0 = MAP112_ROM(context.mem_page[(g_NESmapper.Mapper112.regs[0] & 0x40) ? 6 : 4]);
g_NESmapper.Mapper112.prg1 = MAP112_ROM(context.mem_page[5]);
if(g_NESmapper.num_1k_VROM_banks)
{
if(g_NESmapper.Mapper112.regs[0] & 0x80)
{
g_NESmapper.Mapper112.chr01 = MAP112_VROM(g_PPU.PPU_VRAM_banks[4]);
g_NESmapper.Mapper112.chr23 = MAP112_VROM(g_PPU.PPU_VRAM_banks[6]);
g_NESmapper.Mapper112.chr4 = MAP112_VROM(g_PPU.PPU_VRAM_banks[0]);
g_NESmapper.Mapper112.chr5 = MAP112_VROM(g_PPU.PPU_VRAM_banks[1]);
g_NESmapper.Mapper112.chr6 = MAP112_VROM(g_PPU.PPU_VRAM_banks[2]);
g_NESmapper.Mapper112.chr7 = MAP112_VROM(g_PPU.PPU_VRAM_banks[3]);
}
else
{
g_NESmapper.Mapper112.chr01 = MAP112_VROM(g_PPU.PPU_VRAM_banks[0]);
g_NESmapper.Mapper112.chr23 = MAP112_VROM(g_PPU.PPU_VRAM_banks[2]);
g_NESmapper.Mapper112.chr4 = MAP112_VROM(g_PPU.PPU_VRAM_banks[4]);
g_NESmapper.Mapper112.chr5 = MAP112_VROM(g_PPU.PPU_VRAM_banks[5]);
g_NESmapper.Mapper112.chr6 = MAP112_VROM(g_PPU.PPU_VRAM_banks[6]);
g_NESmapper.Mapper112.chr7 = MAP112_VROM(g_PPU.PPU_VRAM_banks[7]);
}
}
}
/////////////////////////////////////////////////////////////////////
| [
"takka@e750ed6d-7236-0410-a570-cc313d6b6496"
]
| [
[
[
1,
281
]
]
]
|
ed271d3a75a6c63032c7ad971b58e87e2b860e2c | a0bc9908be9d42d58af7a1a8f8398c2f7dcfa561 | /SlonEngine/slon/Scene/LookAtCamera.h | 2acc9405bd72bdd23dfcc7b03a2930c4b5211b81 | []
| no_license | BackupTheBerlios/slon | e0ca1137a84e8415798b5323bc7fd8f71fe1a9c6 | dc10b00c8499b5b3966492e3d2260fa658fee2f3 | refs/heads/master | 2016-08-05T09:45:23.467442 | 2011-10-28T16:19:31 | 2011-10-28T16:19:31 | 39,895,039 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,687 | h | #ifndef __SLON_ENGINE_CAMERA_LOOK_AT_CAMERA__
#define __SLON_ENGINE_CAMERA_LOOK_AT_CAMERA__
#include "../Utility/cached_value.hpp"
#include "CommonCamera.h"
namespace slon {
namespace scene {
/** Coommon camera with several functions to manipulate camera position
* in the space.
*/
class SLON_PUBLIC LookAtCamera :
public CommonCamera
{
public:
LookAtCamera();
/** Set position of the camera */
void setPosition(const math::Vector3f& _position);
/** Set direction(z-axis) of the camera */
void setDirection(const math::Vector3f& _direction);
/** Set up vector(y-axis) of the camera */
void setUp(const math::Vector3f& _up);
/** Set projection matrix */
void setProjectionMatrix(const math::Matrix4f& _projectionMatrix);
/** Rotate camera around camera right vector */
void turnPitch(float angle);
/** Rotate camera around camera up vector */
void turnYaw(float angle);
/** Rotate camera around camera direction */
void turnRoll(float angle);
/** Rotate camera around arbitrary axis */
void turnAroundAxis(float angle, const math::Vector3f& axis);
/** Move camera along camera axises */
void move(float x, float y, float z);
/** Move camera along the direction vector */
void moveForward(float length);
/** Move camera along the up vector */
void moveUp(float length);
/** Move camera along the right vector */
void moveRight(float length);
// Override camera
math::Vector3f getPosition() const { return position; }
math::Vector3f getDirection() const { return direction; }
math::Vector3f getUp() const { return up; }
math::Vector3f getRight() const { return cross(up, direction); }
const math::Frustumf& getFrustum() const;
const math::Matrix4f& getProjectionMatrix() const { return projectionMatrix; }
const math::Matrix4f& getViewMatrix() const;
const math::Matrix4f& getInverseViewMatrix() const;
const math::Matrix3f& getNormalMatrix() const;
private:
void dirtyViewMatrix();
private:
mutable CachedMatrix4f viewMatrix;
mutable CachedMatrix4f invViewMatrix;
mutable CachedMatrix3f normalMatrix;
mutable CachedFrustumf frustum;
math::Matrix4f projectionMatrix;
math::Vector3f position;
math::Vector3f direction;
math::Vector3f up;
};
typedef boost::intrusive_ptr<LookAtCamera> look_at_camera_ptr;
typedef boost::intrusive_ptr<const LookAtCamera> const_look_at_camera_ptr;
} // namespace scene
} // namespace slon
#endif // __SLON_ENGINE_CAMERA_LOOK_AT_CAMERA__
| [
"devnull@localhost"
]
| [
[
[
1,
88
]
]
]
|
b6b309be504a0a42279bd14b1ba41728688b8150 | 841e58a0ee1393ddd5053245793319c0069655ef | /Karma/Headers/NPC.h | 653554c2547d0b1799711672dbd6a24fb4ce2813 | []
| no_license | dremerbuik/projectkarma | 425169d06dc00f867187839618c2d45865da8aaa | faf42e22b855fc76ed15347501dd817c57ec3630 | refs/heads/master | 2016-08-11T10:02:06.537467 | 2010-06-09T07:06:59 | 2010-06-09T07:06:59 | 35,989,873 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,739 | h | /*---------------------------------------------------------------------------------*/
/* File: NPC.h */
/* Author: Per Karlsson, [email protected] */
/* */
/* Description: NPC is the class between the Character and the derived NPC */
/* classes (i.e NPCAimer). It involves some standard functions for reseting */
/* the NPC. */
/*---------------------------------------------------------------------------------*/
#ifndef NPC_H
#define NPC_H
#include "Character.h"
/* */
class NPC : public Character
{
public:
NPC(Ogre::SceneManager* sceneMgr,NxOgre::Scene* physScene,OGRE3DRenderSystem* renderSystem, Ogre::String filename,
Ogre::String name, Ogre::Vector3 spawnPoint , float scale, float hp , float walkSpeed);
/* Returns true if NPC is currently resetting */
bool isReseting(){return mtReseting;};
/* Instead of moving normally (often towards the Player), the NPC walks to its spawn point. */
bool moveReset(const double& timeSinceLastFrame);
/* Resets the character. Used when it is no longer in the active chunk area. */
void reset();
/* Static function to set the scene node that the player is attached to. */
static void setPlayerNode(Ogre::SceneNode* s){playerNode = s;};
/* Abstract function. All NPC subclasses need their own way of updating. */
virtual void update(const double& timeSinceLastFrame) = 0;
protected:
GridData mtChunk;
float mtUpdateTimer;
static Ogre::SceneNode* playerNode;
bool mtReseting;
/* Common method for dying that can be used for any NPC subclass. Is virtual in the superclass and can still be overwritten. */
void die();
};
#endif | [
"perkarlsson89@0a7da93c-2c89-6d21-fed9-0a9a637d9411"
]
| [
[
[
1,
46
]
]
]
|
3074ceeb0bb3e3222e7ec5146f2b9b5cff7dd50e | 80a71182c4b0b6e3ccf400bc8755a0f8b309612f | /OpenGL_CV/OpenGL_CV/OpenGL_CV.cpp | a12438b303646048c6812bf7fd22958f6210ec2f | []
| no_license | shubham-pachori/hlibrary | 19338c790049cb0e3e7e2f17b35f2d6529e87f0a | 840897bc2f706263a46145fdfb3a5612d14d9985 | refs/heads/master | 2020-05-18T04:20:23.105777 | 2011-07-14T08:56:25 | 2011-07-14T08:56:25 | 40,962,765 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,779 | cpp | // OpenGL_CV.cpp : Defines the entry point for the application.
//
// Start @ 2011-07-13.
// Reference from http://www.vislab.usyd.edu.au/moinwiki/OpenCV/OpenCV%20and%20OpenGL
//
#include "stdafx.h"
#include "OpenGL_CV.h"
// HLib
#include "HGLManager.hpp"
#include "HRenderer2D.hpp"
#include "HSystem.hpp"
// Standard
#include <iostream>
#include "shellapi.h"
// OpenGL
#include "glext.h"
#define MAX_LOADSTRING 100
// Global Variables:
HINSTANCE hInst; // current instance
TCHAR szTitle[MAX_LOADSTRING]; // The title bar text
TCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name
// Forward declarations of functions included in this code module:
ATOM MyRegisterClass(HINSTANCE hInstance);
HWND InitInstance(HINSTANCE, int); /// Hyon modified
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
// HLib
CHGLManager* p_hglmgr;
CHRenderer2D* p_renderer;
CHSystem* p_system;
using namespace std;
int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
int argc;
WCHAR** argv = CommandLineToArgvW(GetCommandLine(), &argc);
AllocConsole();
freopen("conout$","wt",stdout);
/// HGLMGR
p_hglmgr = new CHGLManager(hInstance);
p_renderer = new CHRenderer2D();
p_system = new CHSystem();
if (argc == 2)
{
p_system->ReadSequenceFromFolder(argv[1]);
}
else if (argc == 1)
{
// Open camera
}
// TODO: Place code here.
MSG msg;
HACCEL hAccelTable;
// Initialize global strings
LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadString(hInstance, IDC_OPENGL_CV, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
HWND hWnd;
// Perform application initialization: Hyon Modified.
if ((hWnd =InitInstance (hInstance, nCmdShow)) == NULL)
{
return FALSE;
}
hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_OPENGL_CV));
//-----------------------------------------------------------
// HLib allocation
//-----------------------------------------------------------
p_hglmgr->setHWindow(hWnd);
p_hglmgr->setRenderer(p_renderer);
if(p_hglmgr->enableOpenGL() != true)
{
cout << "Failed to init GL context" << endl;
return -1;
}
else
{
initGlExtensions();
cout << "OpenGL initialization success" << endl;
p_hglmgr->display();
}
//-----------------------------------------------------------
// Main message loop:
#if 0
/// Does not work!
while (GetMessage(&msg, NULL, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
// HGL
p_hglmgr->idle();
}
#else
bool quit = false;
while(!quit)
{
if(PeekMessage(&msg,NULL,0,0,PM_REMOVE))
{
if(msg.message == WM_QUIT)
{
quit = TRUE;
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
else
{
// HGL
p_hglmgr->idle();
}
}
#endif
//HGL
p_hglmgr->disableOpenGL();
return (int) msg.wParam;
}
//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
// COMMENTS:
//
// This function and its usage are only necessary if you want this code
// to be compatible with Win32 systems prior to the 'RegisterClassEx'
// function that was added to Windows 95. It is important to call this function
// so that the application will get 'well formed' small icons associated
// with it.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_OPENGL_CV));
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCE(IDC_OPENGL_CV);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassEx(&wcex);
}
//
// FUNCTION: InitInstance(HINSTANCE, int)
//
// PURPOSE: Saves instance handle and creates main window
//
// COMMENTS:
//
// In this function, we save the instance handle in a global variable and
// create and display the main program window.
//
// Hyon Modified
HWND InitInstance(HINSTANCE hInstance, int nCmdShow)
{
HWND hWnd;
hInst = hInstance; // Store instance handle in our global variable
hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return hWnd;
}
//
// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// PURPOSE: Processes messages for the main window.
//
// WM_COMMAND - process the application menu
// WM_PAINT - Paint the main window
// WM_DESTROY - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
int wmId, wmEvent;
PAINTSTRUCT ps;
HDC hdc;
// Sanity check
if(p_hglmgr == NULL)
return 0;
switch (message)
{
case WM_COMMAND:
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
break;
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
// TODO: Add any drawing code here...
p_hglmgr->postRedisplay();
EndPaint(hWnd, &ps);
break;
case WM_SIZE:
// Hyon
p_hglmgr->reshape(LOWORD(lParam),HIWORD(lParam));
p_hglmgr->postRedisplay();
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
| [
"[email protected]"
]
| [
[
[
1,
298
]
]
]
|
36fdbb33b7c57b92793acc0649a84cf50598b4e1 | 2f72d621e6ec03b9ea243a96e8dd947a952da087 | /src/DecalCursor.cpp | 4d54c9cbbcd15c452ad59f1291e9ed3569f1503a | []
| no_license | gspu/lol4fg | 752358c3c3431026ed025e8cb8777e4807eed7a0 | 12a08f3ef1126ce679ea05293fe35525065ab253 | refs/heads/master | 2023-04-30T05:32:03.826238 | 2011-07-23T23:35:14 | 2011-07-23T23:35:14 | 364,193,504 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,726 | cpp | /**
* @file DecalCursor.cpp
* @author Jesse Wright - www.cutthroatstudios.com
* @date Created on 12/25/2007
* @date Last modified 5/19/2007
* @note Modified from Brocan's example on the Ogre forums
*/
#include "OgreSceneManager.h"
#include "OgreTextureManager.h"
#include "OgreSceneNode.h"
#include "OgreFrustum.h"
#include "OgreTextureUnitState.h"
#include "OgrePass.h"
#include "DecalCursor.h"
/**
* @brief The length of one meter in ogre units
* @todo Set this to something meaningful for your project!
*/
static const float METER_SCALE = 1.0f;
DecalCursor::DecalCursor(Ogre::SceneManager* man, Ogre::MaterialPtr terrainMat, const Ogre::Vector2& size,
const std::string& tex)
: m_bVisible ( false ), m_nodeProj(0), m_pass(0), m_frustProj(0), m_texState(0), m_sceneMgr(man),
m_terrainMat( terrainMat ), m_pos ( Ogre::Vector3::ZERO ), m_size ( Ogre::Vector2::ZERO )
{
init(size, tex);
}
DecalCursor::~DecalCursor()
{
hide();
// remove the decal pass
if ( m_pass )
{
m_terrainMat->getTechnique(0)->removePass( m_pass->getIndex() );
m_pass = 0;
}
// delete frustum
m_nodeProj->detachAllObjects();
delete m_frustProj;
// destroy node
m_nodeProj->getParentSceneNode()->removeAndDestroyChild(m_nodeProj->getName());
}
void DecalCursor::init(const Ogre::Vector2& size, const std::string& tex )
{
// create a new pass in the material to render the decal
m_pass = m_terrainMat->getTechnique(0)->getPass("Decal");
if (!m_pass)
{
Ogre::Technique* techPref = m_terrainMat->getTechnique(0);
m_pass = techPref->createPass();
m_pass->setName("Decal");
m_pass->setLightingEnabled(false);
m_pass->setSceneBlending(Ogre::SBT_TRANSPARENT_ALPHA);
m_pass->setDepthBias(2.5, 2.5);
m_pass->setFog(true);
m_pass->createTextureUnitState("decalBase.png");
}
// init projective decal
// set up the main decal projection frustum
m_frustProj = new Ogre::Frustum();
m_nodeProj = m_sceneMgr->getRootSceneNode()->createChildSceneNode();
m_nodeProj->attachObject(m_frustProj);
m_frustProj->setProjectionType(Ogre::PT_ORTHOGRAPHIC);
m_nodeProj->setOrientation(Ogre::Quaternion(Ogre::Degree(90), Ogre::Vector3::UNIT_X));
/* Commented out for general use. If you are using mouse picking in your scene, set this to an unselectable flag otherwise you may find the frustum in your ray queries. */
//m_frustProj->setQueryFlags(Sanguis::UNSELECTABLE);
// set given values
setSize(size);
m_sTexName = tex; // texture to apply
// load the images for the decal and the filter
Ogre::TextureManager::getSingleton().load(m_sTexName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D, 1);
m_bVisible = false;
}
Ogre::Vector3 DecalCursor::getPosition() const
{
return m_pos;
}
void DecalCursor::show()
{
if(!m_bVisible)
{
m_bVisible = true;
showTerrainDecal();
setPosition(m_pos);
}
}
void DecalCursor::hide()
{
if (m_bVisible)
{
m_bVisible = false;
hideTerrainDecal();
}
}
void DecalCursor::setPosition(const Ogre::Vector3& pos)
{
m_pos = pos;
// Set the projection coming from some distance above the current position.
m_nodeProj->setPosition(pos.x, pos.y + (10.0 * METER_SCALE), pos.z);
}
void DecalCursor::setSize(const Ogre::Vector2& size)
{
if (m_size != size)
{
m_size = size;
// update aspect ratio
#if OGRE_VERSION_MAJOR == 1 && OGRE_VERSION_MINOR <= 4
m_frustProj->setAspectRatio(m_size.x / m_size.y);
#else
m_frustProj->setOrthoWindow ( m_size.x, m_size.y );
#endif
// set fovy so that tan = 1, so 45 degrees
m_frustProj->setFOVy(Ogre::Degree(45));
// set near clip plane according to fovy:
m_frustProj->setNearClipDistance(m_size.y);
}
}
// Protected
void DecalCursor::showTerrainDecal()
{
if (!m_texState)
{
// set up the decal's texture unit
m_texState = m_pass->createTextureUnitState(m_sTexName);
m_texState->setProjectiveTexturing(true, m_frustProj);
m_texState->setTextureAddressingMode(Ogre::TextureUnitState::TAM_CLAMP);
m_texState->setTextureFiltering(Ogre::FO_POINT, Ogre::FO_LINEAR, Ogre::FO_NONE);
m_texState->setAlphaOperation(Ogre::LBX_ADD);
}
}
void DecalCursor::hideTerrainDecal()
{
if (m_texState)
{
m_pass->removeTextureUnitState(m_pass->getTextureUnitStateIndex(m_texState));
m_texState = 0;
}
} | [
"praecipitator@bd7a9385-7eed-4fd6-88b1-0096df50a1ac"
]
| [
[
[
1,
164
]
]
]
|
45ed6866345308c5c51922c7461ddeeb84f104d9 | 2112057af069a78e75adfd244a3f5b224fbab321 | /branches/ref1/src-root/src/ireon_rs/accounts/general_character_info.cpp | 938c6d34dd2b24dc61aae543ae7c0b4e8c477fe1 | []
| no_license | blockspacer/ireon | 120bde79e39fb107c961697985a1fe4cb309bd81 | a89fa30b369a0b21661c992da2c4ec1087aac312 | refs/heads/master | 2023-04-15T00:22:02.905112 | 2010-01-07T20:31:07 | 2010-01-07T20:31:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,331 | cpp | /**
* @file ireon_rs/accounts/character_info.cpp
* character info class
*/
/* Copyright (C) 2005 ireon.org developers council
* $Id$
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#include "ireon_rs/accounts/general_character_info.h"
#include "common/db/mysql_db.h"
#include <mysql++.h>
CGeneralCharacterInfo::CGeneralCharacterInfo(uint id, String name):
m_id(id),
m_name(name)
{
}
// --------------------------------------------------------------------
bool CGeneralCharacterInfo::getCharactersForAccount(uint accountId, std::map<uint,CharacterInfoPointer> &charMap)
{
assert(accountId);
CharacterInfoPointer *charInfo;
mysqlpp::Query query = CMySQLConnection::instance()->getQuery();
query << "select * from `" << CMySQLConnection::instance()->getTableNamesPrefix() <<
"characters` where `owner`=" << accountId;
mysqlpp::Result result = query.store();
if (result) {
mysqlpp::Row row;
mysqlpp::Row::size_type i;
for (i = 0; row = result.at(i); ++i) {
charInfo = new CharacterInfoPointer(new CGeneralCharacterInfo(row["id"], String(row["name"])));
charMap.insert(std::pair<uint,CharacterInfoPointer>((uint) row["id"],*charInfo));
}
return true;
}
return false;
}
// --------------------------------------------------------------------
bool CGeneralCharacterInfo::removeFromDB()
{
assert(m_id);
mysqlpp::Query query = CMySQLConnection::instance()->getQuery();
query << "delete from `" << CMySQLConnection::instance()->getTableNamesPrefix() <<
"characters` where `id`=" << m_id;
return query.exec(query.str());
}
| [
"[email protected]"
]
| [
[
[
1,
77
]
]
]
|
72b9bd1ecdf7fd6e8c105f09728be142ffdebd65 | 14b3d57ed3d60b8934dad450a1edf96c573c9e40 | /renamer/Source/ruleset.cpp | 3817c01a79e15b1fc29ef1f65bc97829d11682d5 | []
| no_license | arturh85/Renamer.NET | 02f251f7c41a3f15397faa9bbc63dcb14fa10b67 | e883f8558cdddaa9b88a13261611e9ae429e70aa | refs/heads/master | 2020-08-27T02:29:29.137558 | 2009-06-24T15:34:49 | 2009-06-24T15:34:49 | 3,036,515 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,387 | cpp | /************************************************************************
Copyright (c) 2008, Artur H., Lennart W.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the authors nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE. */
/************************************************************************/
#include "stdafx.h"
#include "ruleset.h"
#include "sqlTools.h"
#include "stlUtility.h"
#include "error.h"
using namespace boost::filesystem;
using boost::regex;
using boost::smatch;
Ruleset::Ruleset() {
mDb = NULL;
mBeforeReplacementsPtr = NULL;
mAfterReplacementsPtr = NULL;
mFilename = "";
mName = "memory database";
if(sqlite3_open(":memory:", &mDb)) {
sqlite3_close(mDb);
throw std::runtime_error("could not open database file in memory");
}
initDb(mDb);
mBeforeReplacementsPtr = new Replacements(mDb, "rulesetBefore", MAGIC_OWNER_ID);
mAfterReplacementsPtr = new Replacements(mDb, "rulesetAfter", MAGIC_OWNER_ID);
loadDb();
}
Ruleset::Ruleset(string filename) {
mDb = NULL;
mBeforeReplacementsPtr = NULL;
mAfterReplacementsPtr = NULL;
mFilename = filename;
loadDb(boost::filesystem::path(filename));
};
Ruleset::Ruleset(wstring filename) {
mDb = NULL;
mBeforeReplacementsPtr = NULL;
mAfterReplacementsPtr = NULL;
mFilename = toStlString(filename);
loadDb(boost::filesystem::path(toStlString(filename)));
};
Ruleset::Ruleset(boost::filesystem::path filename) {
mDb = NULL;
mBeforeReplacementsPtr = NULL;
mAfterReplacementsPtr = NULL;
mFilename = filename.file_string();
loadDb(filename);
};
Ruleset::~Ruleset() {
// save database back to file
if(mFilename != "") {
/*sqlite3* database = NULL;
if(sqlite3_open(mFilename.c_str(), &database)) {
sqlite3_close(database);
throw exDbError();
}
copyDb(mDb, database);
sqlite3_close(database);*/
}
sqlite3_close(mDb);
if(mBeforeReplacementsPtr)
delete mBeforeReplacementsPtr;
if(mAfterReplacementsPtr)
delete mAfterReplacementsPtr;
for (map<sqlite_int64, OutputFormat*>::iterator it = mChildren.begin();
it!=mChildren.end() ; it++) {
delete it->second;
}
}
void Ruleset::loadDb(path dbFile) {
static const regex getNameRegex("^.*\\\\(.*)\\.(.*)$");
boost::smatch nameMatch;
if(!regex_match(mFilename,nameMatch,getNameRegex)) {
//! \todo catch this exception
// throw exBadName();
}
mName = nameMatch[1];
// open database file
if(sqlite3_open(dbFile.file_string().c_str(), &mDb)) {
sqlite3_close(mDb);
throw exDbError();
}
// initialise tables
try {
initDb(mDb);
} catch(...) {} // ignore exception thrown if tables already exist
// load object model from database to memory representation
loadDb();
}
void Ruleset::loadDb() {
if(mBeforeReplacementsPtr)
delete mBeforeReplacementsPtr;
if(mAfterReplacementsPtr)
delete mAfterReplacementsPtr;
mBeforeReplacementsPtr = new Replacements(mDb, "rulesetBefore", MAGIC_OWNER_ID);
mAfterReplacementsPtr = new Replacements(mDb, "rulesetAfter", MAGIC_OWNER_ID);
for(map<sqlite_int64, OutputFormat*>::iterator it = mChildren.begin(); it != mChildren.end(); it++) {
delete it->second;
}
mChildren.clear();
//get outputFormats
vector<string> rowids;
stringstream strSql;
strSql << "SELECT rowid FROM outputFormats";
exec(strSql, mDb, onAppendFirstColumnToVector, &rowids);
for (vector<string>::iterator it = rowids.begin();
it != rowids.end(); it++) {
sqlite_int64 rowid = cSqlInFormated<sqlite_int64>(*it);
OutputFormat* newFormatPtr = new OutputFormat(mDb, rowid);
mChildren[newFormatPtr->getRowId()] = newFormatPtr;
}
}
void Ruleset::initDb(sqlite3* database) {
string sSql;
InputRule::createTables(database);
Replacement::createTables(database);
Replacements::createTables(database);
Gem::createTables(database);
OutputFormat::createTables(database);
}
void Ruleset::removeOutputFormat(sqlite_int64 outputFormatId) {
OutputFormat* outputFormat = mChildren[outputFormatId];
vector<InputRule*> rules = outputFormat->getInputRules();
for (vector<InputRule*>::iterator it = rules.begin();
it != rules.end(); it++) {
outputFormat->removeInputRule((*it)->getRowId());
}
stringstream strSql;
strSql << "DELETE FROM outputFormats WHERE rowid = "
<< cSqlOutFormated(outputFormatId);
exec(strSql, mDb);
mChildren.erase(outputFormatId);
delete outputFormat;
return;
}
//string Ruleset::getName() const {
// return mName;
//}
string Ruleset::getFilename() const {
return mFilename;
}
//vector<string> stripVarNames(string sString) {
// static const regex varRegex("\\$(\\w+)\\$");
// smatch what;
// vector<string> retVal;
//
// std::string::const_iterator start, end;
// start = sString.begin();
// end = sString.end();
// boost::match_flag_type flags = boost::match_default;
// while(regex_search(start, end, what, varRegex, flags)) {
//
// retVal.push_back(what[1]);
//
// // update search position:
// start = what[0].second;
// // update flags:
// flags |= boost::match_prev_avail;
// flags |= boost::match_not_bob;
// }
//
// return retVal;
//}
vector<OutputFormat*> Ruleset::getOutputFormats() {
vector<OutputFormat*> retVal;
for (map<sqlite_int64, OutputFormat*>::iterator it = mChildren.begin();
it!=mChildren.end(); it++) {
retVal.push_back(it->second);
}
return retVal;
}
bool Ruleset::applyTo(string fileName, string& outputFileName, bool updateHistory) {
const regex getFilename("^(.*\\\\)?([^/\\\\:?*\"<>|]+)$");
smatch what, what2;
if (!regex_match(fileName, what, getFilename)) {
throw runtime_error("bad filename2");
}
string path = what[1];
string baseName = what[2];
string sExtension;
string baseName2 = what[2];
//if the filename has an extension extract it, and re-add it later
const regex getExtension("([^/\\\\:?*\"<>|]+)(\\.\\w+)$");
if (regex_match(baseName, what2, getExtension)) {
exAssert(what2.size() == 3);
baseName2 = what2[1];
sExtension = what2[2];
}
//apply replacements
baseName2 = mBeforeReplacementsPtr->replace(baseName2);
vector<OutputFormat*> rules = getOutputFormats();
for (vector<OutputFormat*>::iterator it = rules.begin();
it != rules.end(); it++) {
if ((*it)->applyTo(baseName2, outputFileName, updateHistory)) {
outputFileName = path + outputFileName + sExtension;
return true;
}
}
return false;
}
OutputFormat& Ruleset::addOutputFormat() {
OutputFormat* formatPtr = new OutputFormat (mDb);
mChildren[formatPtr->getRowId()] = formatPtr;
return *formatPtr;
}
bool Ruleset::rename(string fileName) {
// path test("/");
// cout << fileName << endl;
if (!exists(fileName)) {
throw runtime_error("file does not exist");
}
string newFilename;
if (!applyTo(fileName, newFilename, true)) {
return false;
}
//create directories out of the outputformat
vector<string> dirParts;
using namespace boost::algorithm;
split( dirParts, newFilename, is_any_of("\\") );
if (dirParts.size() > 1) {
string sSubDir = "";
vector<string>::iterator itLast = --dirParts.end();
for (vector<string>::iterator it = dirParts.begin(); it!=itLast ; it++) {
sSubDir += *it+"\\";
if (!exists(sSubDir)) {
create_directory(sSubDir);
}
}
}
// cout << ">>" << path+newFilename+sExtension << endl;
boost::filesystem::rename(fileName, newFilename);
return true;
}
InputRule& Ruleset::getInputRule(sqlite_int64 rowid) {
for (map<sqlite_int64, OutputFormat*>::iterator it=mChildren.begin();
it!=mChildren.end(); it++) {
InputRule* rulePtr = it->second->getInputRule(rowid);
if (rulePtr) {
return *rulePtr;
}
}
throw exNoSuchId();
}
Gem& Ruleset::getGem(sqlite_int64 rowid) {
for (map<sqlite_int64, OutputFormat*>::iterator it=mChildren.begin();
it!=mChildren.end(); it++) {
Gem* gemPtr = it->second->getGem(rowid);
if (gemPtr) {
return *gemPtr;
}
}
throw exNoSuchId();
}
void Ruleset::save() {
for (map<sqlite_int64, OutputFormat*>::iterator it = mChildren.begin();
it!=mChildren.end(); it++) {
it->second->save();
}
if(mBeforeReplacementsPtr)
mBeforeReplacementsPtr->save();
if(mAfterReplacementsPtr)
mAfterReplacementsPtr->save();
}
Replacement& Ruleset::getReplacement(sqlite_int64 rowid) {
vector<Replacement*> replacements = mBeforeReplacementsPtr->getReplacements();
for (vector<Replacement*>::iterator it = replacements.begin();
it != replacements.end(); it++) {
if ((*it)->getRowId() == rowid) {
return *(*it);
}
}
throw exNoSuchId();
}
void Ruleset::copyDb(sqlite3* source, sqlite3* target) {
char* tables[] = { "gems", "history", "options", "outputFormats", "regexes", "replacementGroups", "replacements" };
const int tableCount = 7; // importent! set this MANUALLY each time you update the tables var
// Step1: Drop all tables of target
for(int i=0; i<tableCount; i++) {
stringstream strSql;
strSql << "DROP TABLE " << tables[i];
sqlite3_exec(target, strSql.str().c_str(), NULL, NULL, NULL);
}
// Step2: Create tables on target
initDb(target);
// Step3: iterate through all tables of this Ruleset and write them to target
for(int i=0; i<tableCount; i++) {
stringstream strSql;
strSql << "SELECT * FROM " << tables[i];
vector<map<string,string> > resultset;
try {
exec(strSql.str(), source, onAppendAllColumnsToMapVector, &resultset );
}
catch(...) {
}
for(unsigned int j=0; j<resultset.size(); j++) {
map<string,string>& columns = resultset[j];
stringstream strColumns;
stringstream strValues;
for(map<string,string>::iterator it = columns.begin(); it != columns.end(); it++) {
strColumns << it->first;
strValues << "'" << it->second << "'";
map<string,string>::iterator nextit = it;
nextit ++;
if(nextit != columns.end()) {
strColumns << ",";
strValues << ",";
}
}
strSql.str("");
strSql << "INSERT INTO " << tables[i] << " (" << strColumns.str() << ") VALUES (" << strValues.str() << ")";
sqlite3_exec(target, strSql.str().c_str(), NULL, NULL, NULL);
}
}
}
#ifdef RENAMER_UNIT_TEST
#include <boost/test/test_tools.hpp>
void testName(string name) {
BOOST_CHECK_NO_THROW(Ruleset(name));
if(exists(name))
remove(name);
}
void testNewRuleset(path dbFileName);
void testSavedRuleset(path dbFileName);
void Ruleset::unitTest() {
//The.Unit.S02E20.HDTV.XviD-LOL.avi
//The.Unit.S02E21.HDTV.XviD-XOR.avi
path dbFileName = initial_path<path>()/"unitTest.db3";
testNewRuleset(dbFileName);
testSavedRuleset(dbFileName);
remove_all("The Unit");
}
void testSavedRuleset(path dbFileName) {
Ruleset myRules(dbFileName);
system("echo > The.Unit.S02E18.HDTV.XviD-NoTV.avi");
BOOST_CHECK(myRules.rename("The.Unit.S02E18.HDTV.XviD-NoTV.avi"));
BOOST_CHECK(exists("The Unit\\02\\18.avi")); //whole directory will be removed at the end
}
void testNewRuleset(path dbFileName) {
BOOST_CHECKPOINT("begin");
// // test global functions
// vector<string> tmpVector;
// tmpVector = stripVarNames("Atlantis $staffel$x$folge$");
// BOOST_REQUIRE(tmpVector.size() == 2);
// BOOST_CHECK(tmpVector[0] == "staffel");
// BOOST_CHECK(tmpVector[1] == "folge");
if (exists(dbFileName))
boost::filesystem::remove(dbFileName);
Ruleset myRules(dbFileName);
// Ruleset myRules;
OutputFormat& simpleFormat = myRules.addOutputFormat();
BOOST_REQUIRE(myRules.getOutputFormats().size() == 1);
BOOST_REQUIRE_EQUAL(myRules.getOutputFormats()[0] , &simpleFormat);
simpleFormat.setFormat("$series$ - $season$x$episode$");
simpleFormat.addInputRule("^(Stargate Atlantis|The Simpsons) S(\\d+)E(\\d+)([ -]\\w{0,7})*");
myRules.getBeforeReplacements().addReplacement("\\.", " ");
//these should work
string sNewFileName;
BOOST_CHECK(myRules.applyTo("Stargate.Atlantis.S03E17.HR.HDTV.AC3.2.0.XviD-NBS", sNewFileName ));
BOOST_CHECK_EQUAL(sNewFileName, "Stargate Atlantis - 03x17");
BOOST_CHECK(myRules.applyTo("Stargate.Atlantis.S03E18.READ.NFO.DSR.XviD-NXSPR0N", sNewFileName ));
BOOST_CHECK_EQUAL(sNewFileName, "Stargate Atlantis - 03x18");
BOOST_CHECK(myRules.applyTo("Stargate.Atlantis.S03E19.HDTV.XviD-MiNT", sNewFileName ));
BOOST_CHECK_EQUAL(sNewFileName, "Stargate Atlantis - 03x19");
BOOST_CHECKPOINT("ruleSimpsons");
BOOST_CHECK(myRules.applyTo("The.Simpsons.S18E10.PDTV.XviD-NoTV", sNewFileName ));
BOOST_CHECK(sNewFileName == "The Simpsons - 18x10");
BOOST_CHECK(myRules.applyTo("The.Simpsons.S18E12.PDTV.XviD-LOL", sNewFileName ));
BOOST_CHECK(sNewFileName == "The Simpsons - 18x12");
BOOST_CHECK(myRules.applyTo("The.Simpsons.S18E13.PDTV.XviD-2HD", sNewFileName ));
BOOST_CHECK(sNewFileName == "The Simpsons - 18x13");
BOOST_CHECK(myRules.applyTo("The.Simpsons.S18E14.PDTV.XviD-LOL", sNewFileName ));
BOOST_CHECK(sNewFileName == "The Simpsons - 18x14");
BOOST_CHECK(myRules.applyTo("The.Simpsons.S18E16.PDTV.XviD-LOL", sNewFileName ));
BOOST_CHECK(sNewFileName == "The Simpsons - 18x16");
OutputFormat& formatAtlantis = myRules.addOutputFormat();
formatAtlantis.setFormat("Atlantis $staffel$x$folge$");
BOOST_CHECKPOINT("myRules.applyTo");
string sDummy;
//these should work
BOOST_CHECK(myRules.applyTo("Stargate.Atlantis.S03E17.HR.HDTV.AC3.2.0.XviD-NBS", sDummy ));
BOOST_CHECK(myRules.applyTo("Stargate.Atlantis.S03E18.READ.NFO.DSR.XviD-NXSPR0N", sDummy ));
BOOST_CHECK(myRules.applyTo("Stargate.Atlantis.S03E19.HDTV.XviD-MiNT", sDummy ));
//these lines are intentionally the same
BOOST_CHECKPOINT("myRules.applyTo (doubles check)");
BOOST_CHECK(myRules.applyTo("Stargate.Atlantis.S03E20.HR.HDTV.AC3.2.0.XviD-NBS2", sDummy ));
BOOST_CHECK(myRules.applyTo("Stargate.Atlantis.S03E20.HR.HDTV.AC3.2.0.XviD-NBS2", sDummy ));
// these are expected the be false
BOOST_CHECKPOINT("myRules.applyTo (failures)");
BOOST_CHECK(!myRules.applyTo("Notice the ! left", sDummy ));
BOOST_CHECK(!myRules.applyTo("blah", sDummy ));
BOOST_CHECK(!myRules.applyTo("D:\\Daten\\Develop\\Renamer\\testFiles\\14Dr.House.S02E14.Sex.wird.unterschaetzt.German.Dubbed.DVDRIP.WS.XviD-TvR.avi", sDummy ));
BOOST_CHECKPOINT("check allowed Names");
// BOOST_CHECK_THROW(Ruleset(string("Stargate Atlantis")), exBadName);
// BOOST_CHECK_THROW(Ruleset(string("24")), exBadName);
// BOOST_CHECK_THROW(Ruleset(string("z:\\The Simpsons")), exBadName);
BOOST_CHECK_THROW(Ruleset(string("x:\\strangeDir\\The Simpsons.db3")),exDbError);
BOOST_CHECK_THROW(Ruleset(string("c:\\myDir\\xyz\\24.RULESET")),exDbError);
BOOST_CHECK_THROW(Ruleset(string("x:\\The Simpsons.ruleset")),exDbError);
testName(".\\Stargate Atlantis.ruleSet");
testName(".\\Stargate Atlantis.db3");
testName("c:\\24.db3");
BOOST_CHECKPOINT("rename");
system("echo > The.Simpsons.S18E10.PDTV.XviD-NoTV.avi");
BOOST_CHECK(myRules.rename("The.Simpsons.S18E10.PDTV.XviD-NoTV.avi"));
BOOST_CHECK(exists("The Simpsons - 18x10.avi"));
remove("The Simpsons - 18x10.avi");
system("echo > The.Simpsons.S18E12.PDTV.XviD-LOL.avi");
BOOST_CHECK(myRules.rename("The.Simpsons.S18E12.PDTV.XviD-LOL.avi"));
BOOST_CHECK(exists("The Simpsons - 18x12.avi"));
remove("The Simpsons - 18x12.avi");
string tmpDir(getenv("TMP"));
system(string("echo > ") + tmpDir + "\\The.Simpsons.S18E12.PDTV.XviD-LOL.avi");
BOOST_CHECK(myRules.rename(tmpDir + "\\The.Simpsons.S18E12.PDTV.XviD-LOL.avi"));
BOOST_CHECK(exists(tmpDir + "\\The Simpsons - 18x12.avi"));
remove(tmpDir + "\\The Simpsons - 18x12.avi");
BOOST_CHECKPOINT("subDirs");
OutputFormat& unitFormat = myRules.addOutputFormat();
unitFormat.setFormat("The Unit\\$season$\\$episode$");
InputRule& ruleUnit = unitFormat.addInputRule("The Unit S(\\d+)E(\\d+) HDTV XviD-(NoTV|XOR|LOL)");
// InputRule& ruleUnit = unitFormat.addInputRule("The\\.Unit\\.S(\\d+)E(\\d+)\\.HDTV\\.XviD-(NoTV|XOR|LOL)");
ruleUnit.updateGems("$season$x$episode$");
system("echo > The.Unit.S02E16.HDTV.XviD-NoTV.avi");
BOOST_CHECK(myRules.rename("The.Unit.S02E16.HDTV.XviD-NoTV.avi"));
BOOST_CHECK(exists("The Unit\\02\\16.avi")); //whole directory will be removed at the end
BOOST_CHECKPOINT("BeforeReplacements");
myRules.getBeforeReplacements().addReplacement(" JUNK","");
system("echo > The.Unit.S02E17.HDTV.JUNK.XviD-XOR.avi");
BOOST_CHECK(myRules.rename("The.Unit.S02E17.HDTV.JUNK.XviD-XOR.avi"));
BOOST_CHECK(exists("The Unit\\02\\17.avi")); //whole directory will be removed at the end
myRules.save();
}
#endif
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
230
],
[
232,
315
],
[
317,
318
],
[
320,
340
],
[
342,
356
],
[
358,
575
]
],
[
[
231,
231
],
[
316,
316
],
[
319,
319
],
[
341,
341
],
[
357,
357
]
]
]
|
7ca3a89aa7cdcb690c24cd38a9a074b4c153d4cc | 08c7de4d101008cb44841fa781c94f5bc17d8e20 | /src/configuration.h | 64e6db0c7d0c351688cf4bf4c740383b46f3d90e | []
| no_license | CowboyCoders/cow_player | 1a661067b070b18b377db136e35aefa3bc035149 | ac0f5ba408459fb509105ddac99424e5afeefd22 | refs/heads/master | 2020-05-20T05:30:34.968270 | 2010-08-28T12:49:10 | 2010-08-28T12:49:10 | 868,351 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,284 | h | /*
Copyright 2010 CowboyCoders. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are
permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list
of conditions and the following disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY COWBOYCODERS ``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 COWBOYCODERS 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.
The views and conclusions contained in the software and documentation are those of the
authors and should not be interpreted as representing official policies, either expressed
or implied, of CowboyCoders.
*/
#ifndef ___configuration_h___
#define ___configuration_h___
#include <boost/lexical_cast.hpp>
#include <string>
#include <map>
#include <sstream>
#include <stdexcept>
#include "cow_player_types.h"
namespace cow_player {
namespace configuration {
namespace exceptions {
/**
* Load config error that can be thrown when it's not possible
* to load the configuration from file.
*/
class load_config_error : public std::runtime_error
{
public:
/**
* Throws the load config error.
*/
load_config_error(const std::string& msg) : std::runtime_error(msg) {}
};
/**
* Save config error that can be thrown when it's not possible
* to save the configuration to file.
*/
class save_config_error : public std::runtime_error
{
public:
/**
* Throws the save config error.
*/
save_config_error(const std::string& msg) : std::runtime_error(msg) {}
};
/**
* Conversion error that can be thrown when a property can't
* be converted.
*/
class conversion_error : public std::runtime_error
{
public:
/**
* Throws the conversion error.
*/
conversion_error(const std::string& msg) : std::runtime_error(msg) {}
};
}
/**
* This class is responsible for generating and retrieving a storable representation
* for a value of type T.
*/
template <typename T>
class serializer
{
public:
/**
* When we try to serialize a value of unknown type, we will throw an error.
* @param value The value to try to serialize.
* @return A pair variable that stores the original value.
*/
static cow_player::property_value serialize(T value) {
throw exceptions::conversion_error("Missing serializer for the specified type.");
}
/**
* When we try to deserialize a value of unknown type, we will throw an error.
* @param prop_value The value to try to deserialize.
* @return The original value of type T.
*/
static T deserialize(const std::string& prop_value) {
throw exceptions::conversion_error("Missing deserializer for the specified type.");
}
};
/**
* This class is responsible for generating and retrieving a storable representation
* for a value of type string.
*/
template <>
class serializer<std::string>
{
public:
/**
* Stores the specified value in a property_value representation.
* @param value The value to serialize.
* @return A pair variable that stores the original value.
*/
static cow_player::property_value serialize(const std::string& value)
{
return std::make_pair("string", value);
}
/**
* Retrieves the original value for the specified prop_value.
* @param prop_value The value to try to deserialize.
* @return The original value of type string.
*/
static std::string deserialize(const std::string& prop_value)
{
return prop_value;
}
};
/**
* This class is responsible for generating and retrieving a storable representation
* for a value of type int.
*/
template <>
class serializer<int>
{
public:
/**
* Stores the specified value in a property_value representation.
* @param value The value to serialize.
* @return A pair variable that stores the original value.
*/
static cow_player::property_value serialize(int value)
{
return std::make_pair("int", boost::lexical_cast<std::string>(value));
}
/**
* Retrieves the original value for the specified prop_value.
* @param prop_value The value to try to deserialize.
* @return The original value of type int.
*/
static int deserialize(const std::string& prop_value)
{
try {
return boost::lexical_cast<int>(prop_value);
} catch (boost::bad_lexical_cast&) {
throw exceptions::conversion_error("Failed to convert data to a integer value.");
}
}
};
/**
* This class is responsible for generating and retrieving a storable representation
* for a value of type bool.
*/
template <>
class serializer<bool>
{
public:
/**
* Stores the specified value in a property_value representation.
* @param value The value to serialize.
* @return A pair variable that stores the original value.
*/
static cow_player::property_value serialize(bool value)
{
return std::make_pair("bool", boost::lexical_cast<std::string>(value));
}
/**
* Retrieves the original value for the specified prop_value.
* @param prop_value The value to try to deserialize.
* @return The original value of type bool.
*/
static bool deserialize(const std::string& prop_value)
{
try {
return boost::lexical_cast<bool>(prop_value);
} catch (boost::bad_lexical_cast&) {
throw exceptions::conversion_error("Failed to convert data to a boolean value.");
}
}
};
#define CONFIGURATION_PROPERTY(name, type, default_value) \
void set_##name(type value) { set_property(#name, value); } \
type get_##name() const { return get_property<type>(#name, default_value); }
/**
* This class is a general configuration class that loads
* and saves configurations.
*/
class base_configuration
{
public:
base_configuration();
/**
* Creates a new cowplayer::configuration::base_configuration object
* and loads settings from the specified file.
* @param fileName The file to load settings from.
*/
base_configuration(const std::string& fileName);
virtual ~base_configuration() {}
/**
* Load a configuration from a file.
* @param fileName The file to load settings from.
*/
void load(const std::string& fileName);
/**
* Save the current configuration to file.
* @param fileName The file to save settings to.
*/
void save(const std::string& fileName) const;
/**
* Sets a property in the configuration.
* @param name The name of the property to set.
* @param value The value of the property to set.
*/
template <typename T>
void set_property(const std::string& name, T value)
{
property_map_[name] = serializer<T>::serialize(value);
}
/**
* Tries to retrieve the value for the specified property name.
* If no value is found, default_value will be returned instead.
* @param name The name of the property to retrive.
* @param default_value The default value to return if the property isn't found.
* @return A value of type T.
*/
template <typename T>
T get_property(const std::string& name, T default_value) const
{
cow_player::property_map::const_iterator item = property_map_.find(name);
if (item == property_map_.end())
return default_value;
try {
return serializer<T>::deserialize(item->second.second);
} catch (exceptions::conversion_error&) {
return default_value;
}
}
/**
* Returns the property_map (a key,value) map containing
* all the settings and their values
*
* @return A property_map with all the read settings
*/
cow_player::property_map settings() const {
return property_map_;
}
/**
* Sets the property_map (a key,value) map containing
* all the settings and their values
*
* @param A property_map with all the settings
*/
void settings(cow_player::property_map map){
property_map_ = map;
}
private:
cow_player::property_map property_map_;
};
}
}
#endif // ___configuration_h___
| [
"[email protected]",
"[email protected]",
"devnull@localhost"
]
| [
[
[
1,
28
],
[
45,
48
],
[
52,
54
],
[
58,
61
],
[
65,
67
],
[
71,
74
],
[
78,
80
],
[
86,
89
],
[
94,
98
],
[
103,
107
],
[
113,
116
],
[
121,
125
],
[
131,
135
],
[
142,
145
],
[
150,
154
],
[
160,
164
],
[
175,
178
],
[
183,
187
],
[
193,
197
],
[
215,
218
],
[
224,
229
],
[
234,
237
],
[
239,
242
],
[
245,
249
],
[
256,
262
]
],
[
[
29,
44
],
[
49,
51
],
[
55,
57
],
[
62,
64
],
[
68,
70
],
[
75,
77
],
[
81,
85
],
[
90,
93
],
[
99,
102
],
[
108,
112
],
[
117,
120
],
[
126,
130
],
[
136,
141
],
[
146,
149
],
[
155,
159
],
[
165,
168
],
[
170,
174
],
[
179,
182
],
[
188,
192
],
[
198,
201
],
[
203,
207
],
[
209,
214
],
[
219,
223
],
[
230,
231
],
[
238,
238
],
[
243,
244
],
[
250,
255
],
[
263,
269
],
[
275,
305
]
],
[
[
169,
169
],
[
202,
202
],
[
208,
208
],
[
232,
233
],
[
270,
274
]
]
]
|
b688a81209a36300da5ec938b001bd5e3e769c3f | d57f646dc96686ef496054d073d4d495b6036b9b | /NetPipe/ServiceManager.cpp | b6241a9292734542e412fefabcc95a6312be826d | [
"BSD-2-Clause"
]
| permissive | limura/netpipe | 00d65fd542d3bab833acf24a1a27ac7fd767503a | 1e363a21e299bc2bab4f902c8e70c66786ea8e5b | refs/heads/master | 2021-01-19T13:50:41.041736 | 2007-10-02T10:25:13 | 2007-10-02T10:25:13 | 32,438,427 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,795 | cpp | /*
* Copyright (c) 2007 IIMURA Takuji. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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.
*
* $Id: ServiceManager.cpp 69 2007-07-04 08:49:24Z $
*/
#include "config.h"
#include "ServiceManager.h"
#include "net.h"
#include "PipeManager.h"
#include "tools.h"
#define NETPIPE_HEADER_BUFFER_LENGTH (1024)
namespace NetPipe {
ServiceManager::ServiceManager(char *name){
if(name == NULL)
throw "undefined service name. ";
serviceName = strdup(name);
if(serviceName == NULL)
throw "no more memory. ";
creator = NULL;
creatorUserData = NULL;
}
ServiceManager::~ServiceManager(){
if(serviceName != NULL){
free(serviceName);
serviceName = NULL;
}
}
char *ServiceManager::getServiceName(){
return serviceName;
}
void ServiceManager::addReadPort(char *portName, char *description){
ReadPort *rp = new ReadPort();
if(rp == NULL)
throw "no more memory";
rp->portName = strdup(portName);
if(rp->portName == NULL){
delete rp;
throw "no more memory";
}
rp->description = strdup(description);
if(rp->description == NULL){
free(rp->portName);
delete rp;
throw "no more memory";
}
readPortMap[portName] = rp;
}
void ServiceManager::addWritePort(char *portName, char *description){
WritePort *wp = new WritePort();
if(wp == NULL)
throw "no more memory";
wp->portName = strdup(portName);
if(wp->portName == NULL){
delete wp;
throw "no more memory";
}
wp->description = strdup(description);
if(wp->description == NULL){
free(wp->portName);
delete wp;
throw "no more memory";
}
writePortMap[portName] = wp;
}
void ServiceManager::addReadFD(int fd, char *description, size_t bufsize){
FDInput *fdi = fdInputMap[fd];
if(fdi == NULL){
fdi = new FDInput();
fdInputMap[fd] = fdi;
}
fdi->fd = fd;
fdi->description = strdup(description);
if(fdi->description == NULL){
delete fdi;
throw "no more memory";
}
fdi->bufSize = bufsize;
}
void ServiceManager::addTimer(int usec, char *description){
}
void ServiceManager::addServiceCreator(ServiceCreator *serviceCreator, void *userdata){
creator = serviceCreator;
creatorUserData = userdata;
}
Service *ServiceManager::createNewService(){
if(creator == NULL)
return NULL;
return creator->createNewService(creatorUserData);
}
void ServiceManager::registReadFDInput(PipeManager *pm){
for(FDInputMap::iterator i = fdInputMap.begin(); i != fdInputMap.end(); i++){
pm->addReadFD(i->second->fd, i->second->bufSize);
}
}
void ServiceManager::registerServiceDB(char *IPaddr, char *TCPPort){
char ServiceString[10240];
/*
* i\tServiceName\tInputPortName\tInputPortName\tInputPortName...
* o\tServiceName\tOutputPortName\tOutputPortName\tOutputPortName...
* p\tInputPortName:ServiceName\tIPAddr\tTCPPortString
*/
if(IPaddr == NULL || TCPPort == NULL)
throw "IPAddr == NULL || TCPPort == NULL";
ServiceString[0] = '\0';
if(readPortMap.size() > 0){
strncat(ServiceString, "i\t", sizeof(ServiceString));
strncat(ServiceString, serviceName, sizeof(ServiceString));
for(ReadPortMap::iterator i = readPortMap.begin(); i != readPortMap.end(); i++){
strncat(ServiceString, "\t", sizeof(ServiceString));
strncat(ServiceString, i->second->portName, sizeof(ServiceString));
}
strncat(ServiceString, "\n", sizeof(ServiceString));
}
if(writePortMap.size() > 0){
strncat(ServiceString, "o\t", sizeof(ServiceString));
strncat(ServiceString, serviceName, sizeof(ServiceString));
for(WritePortMap::iterator i = writePortMap.begin(); i != writePortMap.end(); i++){
strncat(ServiceString, "\t", sizeof(ServiceString));
strncat(ServiceString, i->second->portName, sizeof(ServiceString));
}
strncat(ServiceString, "\n", sizeof(ServiceString));
}
strncat(ServiceString, "p\t", sizeof(ServiceString));
strncat(ServiceString, serviceName, sizeof(ServiceString));
strncat(ServiceString, "\t", sizeof(ServiceString));
strncat(ServiceString, IPaddr, sizeof(ServiceString));
strncat(ServiceString, "\t", sizeof(ServiceString));
strncat(ServiceString, TCPPort, sizeof(ServiceString));
strncat(ServiceString, "\n", sizeof(ServiceString));
if(ServiceString[0] != '\0')
ServiceDB::getInstance()->Regist(ServiceString);
}
}; /* namespace NetPipe */
| [
"uirou.j@b085bb30-bf34-0410-99c5-0750ab6b8f60"
]
| [
[
[
1,
166
]
]
]
|
c12b788fd7f051e7e2a1cc67f9dcb4369fb242eb | 1eb0e6d7119d33fa76bdad32363483d0c9ace9b2 | /PointCloud/trunk/PointCloud/FtpMesh.h | f9a4cbc1d8658f82cef11804281954ac5345078f | []
| no_license | kbdacaa/point-clouds-mesh | 90f174a534eddb373a1ac6f5481ee7a80b05f806 | 73b6bc17aa5c597192ace1a3356bff4880ca062f | refs/heads/master | 2016-09-08T00:22:30.593144 | 2011-06-04T01:54:24 | 2011-06-04T01:54:24 | 41,203,780 | 0 | 2 | null | null | null | null | GB18030 | C++ | false | false | 11,579 | h | #ifndef FTPMESH
#define FTPMESH
#include "Mesh.h"
#include <algorithm>
#include <iterator>
//#include "Common/KdTree.h"
using namespace std;
#define FrontEdgeList list<CFrontEdge>
#define FrontListIterator list<CFrontList>::iterator
//! 波前环类:包含波前边链表和波前点链表及为外环否?
class CFrontList{
public:
list<CFrontEdge> m_frontEdges; // 波前边链表
list<int> m_frontVertexs; // 波前顶点链表
bool m_bOutRing; // 当前链表为外环?
public:
CFrontList():m_bOutRing(true){}
// CFrontList(const CTriangle* pFace):m_bOutRing(true){
// CFrontEdge a(pFace->getA(), pFace->getB()),
// b(pFace->getB(), pFace->getC()),
// c(pFace->getC(), pFace->getA());
// a.setPreTriangle(pFace);
// b.setPreTriangle(pFace);
// c.setPreTriangle(pFace);
// m_frontEdges.push_back(a);
// m_frontEdges.push_back(b);
// m_frontEdges.push_back(c);
// m_frontVertexs.push_back(pFace->getA());
// m_frontVertexs.push_back(pFace->getB());
// m_frontVertexs.push_back(pFace->getC());
// }
CFrontList(const CFrontList& src){
m_frontVertexs.resize(src.frontVertexsSize());
m_frontEdges.resize(src.frontVertexsSize());
std::copy(src.m_frontVertexs.begin(), src.m_frontVertexs.end(), m_frontVertexs.begin());
std::copy(src.m_frontEdges.begin(), src.m_frontEdges.end(), m_frontEdges.begin());
m_bOutRing = src.bOutRing();
}
CFrontList(FrontListIterator& frontList, FrontEdgeIterator& from, FrontEdgeIterator& to, bool bOutRing = false)
: m_bOutRing(bOutRing){
m_frontEdges.splice(m_frontEdges.end(), frontList->frontEdges(), from, to);
constructVertex();
}
CFrontList& operator=(const CFrontList& src){
if (this == &src) return *this;
m_frontVertexs.resize(src.frontVertexsSize());
m_frontEdges.resize(src.frontVertexsSize());
std::copy(src.m_frontEdges.begin(), src.m_frontEdges.end(), m_frontEdges.begin());
std::copy(src.m_frontVertexs.begin(), src.m_frontVertexs.end(), m_frontVertexs.begin());
m_bOutRing = src.bOutRing();
return *this;
}
//@ 根据波前边链表生成顶点链表集
void constructVertex(){
m_frontVertexs.clear();
for (FrontEdgeIterator it = m_frontEdges.begin(); it != m_frontEdges.end(); ++it)
{
m_frontVertexs.push_back(it->getA());
}
}
public:
int frontVertexsSize()const { return m_frontVertexs.size(); }
int frontEdgesSize() const { return m_frontEdges.size(); }
list<CFrontEdge>& frontEdges() { return m_frontEdges; }
list<int>& frontVertexs() { return m_frontVertexs; }
//@ 判断当前环是否为外环
bool bOutRing() const { return m_bOutRing; }
void addVertex(const int vIdx) { m_frontVertexs.push_back(vIdx); }
//@ 向边界环上添加一个三角形(第一步)
void addFace(CTriangle* pFace){
CFrontEdge a(pFace->getA(), pFace->getB(), pFace->getC(), pFace),
b(pFace->getB(), pFace->getC(), pFace->getA(), pFace),
c(pFace->getC(), pFace->getA(), pFace->getB(), pFace);
m_frontEdges.push_back(a);
m_frontEdges.push_back(b);
m_frontEdges.push_back(c);
addVertex(pFace->getA());
addVertex(pFace->getB());
addVertex(pFace->getC());
}
//@ 查找itEdge的前一个iterator
FrontEdgeIterator preEdge(const FrontEdgeIterator& itEdge){
FrontEdgeIterator it = itEdge;
if (it == m_frontEdges.begin()){
it = m_frontEdges.end();
}
-- it;
return it;
}
//@ 查找itEdge的后一个iterator (! 保证itEdge不为end() !)
FrontEdgeIterator nextEdge(const FrontEdgeIterator& itEdge){
FrontEdgeIterator it = itEdge;
++ it;
if ( it == m_frontEdges.end() ){
it = m_frontEdges.begin();
}
return it;
}
// bool join(FrontEdgeIterator& itEdge, int vIdx, CTriangle* face);
// //@ 将一个波前边链表分裂为两个
// bool split(FrontEdgeList& nFEList);
// //@ 将两个波前边链表合并为一个
// bool merge(FrontEdgeList& anthFEList);
// //@ 判断点vIdx在波前边上否?
bool isPtOn(const int vIdx){
for (list<CFrontEdge>::iterator it = m_frontEdges.begin(); it != m_frontEdges.end() ; it++)
{
if (it->getA() == vIdx) return true;
}
return false;
}
//@ 查找点vIdx在波前环上的位置
bool findVertex(FrontEdgeIterator& itEdge, const int vIdx){
for (FrontEdgeIterator it = m_frontEdges.begin();
it != m_frontEdges.end(); ++it){
if (it->getA() == vIdx){
itEdge = it;
return true;
}
}
return false;
}
};
bool frontListCompare(const CFrontList& a, const CFrontList& b);
//! 当前边或者点在波前环集上的位置
struct FrontIter{
FrontEdgeIterator itEdge; // 波前边迭代器
FrontListIterator itList; // 波前环迭代器
};
//! 波前环集合
class CFrontSet{
public:
list<CFrontList> m_frontLists; // 波前环链表
std::vector<short>& m_sPointStatus; // 当前点状态
list<CFrontList> m_boundaryLists; // 边界环链表
public:
CFrontSet(vector<short>& sPointStatus):m_sPointStatus(sPointStatus){}
public:
size_t frontListSize() const { return m_frontLists.size();}
void addFrontList(const CFrontList& frontList){ m_frontLists.push_back(frontList); }
//@ 对波前环链表按照环中边的个数进行排序
void sortFrontLists(){
//sort(m_frontLists.begin(), m_frontLists.end(), frontListCompare);
}
//@ 设置顶点的状态
void setPointStatus(int vIdx, short status = INPOINT){
m_sPointStatus[vIdx] = status;
}
//@ 设置边和其两个端点是为边界边和点
void setBoundary(FrontIter& itFront){
itFront.itEdge->setBoundary();
int A = itFront.itEdge->getA(), B = itFront.itEdge->getB();
FrontEdgeIterator pre = itFront.itList->preEdge(itFront.itEdge),
next = itFront.itList->nextEdge(itFront.itEdge);
if (pre->bBoundary())
setPointStatus(A, BOUNDARYPOINT);
if (next->bBoundary())
setPointStatus(B, BOUNDARYPOINT);
}
//@ 如果当前波前环只有4条边或3条边直接生成三角形
void toFace(FrontListIterator& itList, vector<CTriangle*>& faceVector){
int size = itList->frontEdgesSize();
if (size == 3){
FrontEdgeIterator it = itList->frontEdges().begin(), itNext = it;
itNext++;
CTriangle* pFace = new CTriangle(it->getA(), it->getB(), itNext->getB());
// it->getPreTriangle()->setNeighbor(it, pFace);
// pFace->setNeighbor(it->getA(), itNext->getPreTriangle());
// itNext->getPreTriangle()->setNeighbor(itNext, pFace);
// pFace->setNeighbor(itNext->getB(), it->getPreTriangle());
// itNext++;
// itNext->getPreTriangle()->setNeighbor(itNext, pFace);
// pFace->setNeighbor(it->getB(), itNext->getPreTriangle());
faceVector.push_back(pFace);
m_frontLists.erase(itList);
}else if(size == 4){
FrontEdgeIterator itE = itList->frontEdges().begin(),
it = itE++, itN = itE++, itNN = it++;
CTriangle* pF1 = new CTriangle(it->getA(), it->getB(), itNN->getA()),
* pF2 = new CTriangle(itNN->getA(), itNN->getB(), it->getA());
// pF1->setNeighbor(itNN->getA(), it->getPreTriangle());
// pF1->setNeighbor(it->getA(), itN->getPreTriangle());
// pF1->setNeighbor(it->getB(), pF2);
// it->getPreTriangle()->setNeighbor(it, pF1);
// itN->getPreTriangle()->setNeighbor(itN, pF1);
//
// pF2->setNeighbor(itNN->getB(), pF1);
// pF2->setNeighbor(itNN->getA(), itE->getPreTriangle());
// pF2->setNeighbor(it->getA(), itNN->getPreTriangle());
// itE->getPreTriangle()->setNeighbor(itE, pF2);
// itNN->getPreTriangle()->setNeighbor(itNN, pF2);
faceVector.push_back(pF1);
faceVector.push_back(pF2);
m_frontLists.erase(itList);
}
}
void toFace(CFrontList& frontList, vector<CTriangle*>& faceVector){
int size = frontList.frontEdgesSize();
if (size == 3){
FrontEdgeIterator it = frontList.frontEdges().begin(), itNext = it;
itNext++;
CTriangle* pFace = new CTriangle(it->getA(), it->getB(), itNext->getB());
// it->getPreTriangle()->setNeighbor(it, pFace);
// pFace->setNeighbor(it->getA(), itNext->getPreTriangle());
// itNext->getPreTriangle()->setNeighbor(itNext, pFace);
// pFace->setNeighbor(itNext->getB(), it->getPreTriangle());
// itNext++;
// itNext->getPreTriangle()->setNeighbor(itNext, pFace);
// pFace->setNeighbor(it->getB(), itNext->getPreTriangle());
faceVector.push_back(pFace);
}else if(size == 4){
FrontEdgeIterator itE = frontList.frontEdges().begin(),
it = itE++, itN = itE++, itNN = it++;
CTriangle* pF1 = new CTriangle(it->getA(), it->getB(), itNN->getA()),
* pF2 = new CTriangle(itNN->getA(), itNN->getB(), it->getA());
// pF1->setNeighbor(itNN->getA(), it->getPreTriangle());
// pF1->setNeighbor(it->getA(), itN->getPreTriangle());
// pF1->setNeighbor(it->getB(), pF2);
// it->getPreTriangle()->setNeighbor(it, pF1);
// itN->getPreTriangle()->setNeighbor(itN, pF1);
//
// pF2->setNeighbor(itNN->getB(), pF1);
// pF2->setNeighbor(itNN->getA(), itE->getPreTriangle());
// pF2->setNeighbor(it->getA(), itNN->getPreTriangle());
// itE->getPreTriangle()->setNeighbor(itE, pF2);
// itNN->getPreTriangle()->setNeighbor(itNN, pF2);
faceVector.push_back(pF1);
faceVector.push_back(pF2);
}
}
//@ 向波前环集合中添加一个三角形环
void addFace(CTriangle* pFace){
CFrontList newList;
newList.addFace(pFace);
addFrontList(newList);
}
//@ 获得当前边的上一条边
FrontIter preEdge(const FrontIter& itFront){
FrontIter it;
it.itList = itFront.itList;
it.itEdge = itFront.itList->preEdge(itFront.itEdge);
return it;
}
//@ 获得当前边的下一条边
FrontIter nextEdge(const FrontIter& itFront){
FrontIter it;
it.itList = itFront.itList;
it.itEdge = itFront.itList->nextEdge(itFront.itEdge);
return it;
}
//@ 从波前边链表集中获取一条活动边
bool getActiveEdge(FrontIter& itFront){
FrontListIterator itL = m_frontLists.begin();
while (itL != m_frontLists.end())
{
FrontEdgeIterator itE = itL->frontEdges().begin();
while (itE != itL->frontEdges().end())
{
if (itE->getStatus() == ACTIVE){
itFront.itEdge = itE;
itFront.itList = itL;
return true;
}
itE ++;
}
//TODO 将全是边界边的FrontList 移动到 m_boundaryLists 中
itL ++;
}
return false;
}
//@ 在波前环链表中查找点vIdx所在的环和边 (边的起点为vIdx)
bool findVertex(FrontIter& itV, int vIdx){
for (FrontListIterator itL = m_frontLists.begin(); itL != m_frontLists.end() ; itL++)
{
for (FrontEdgeIterator itE = itL->frontEdges().begin(); itE != itL->frontEdges().end() ; itE++)
{
if (itE->getA() == vIdx){
itV.itList = itL;
itV.itEdge = itE;
return true;
}
}
}
return false;
}
//@ 将一个扩展点加入进来形成新三角形
bool join(FrontIter& itEdge, int vIdx, bool bFront, vector<CTriangle*>& faceList);
};
class CPointCloudView;
class CFTPMesh : public CMesh{
public:
CFrontSet m_front;
//KdTree* kdTree;
CPointCloudView* m_pView;
public:
CFTPMesh(CPointSet* ps, CPointCloudView* pView):CMesh(ps), m_front(m_bPointUsed), m_pView(pView){ /*kdTree = new KdTree(ps); */}
~CFTPMesh(){ /*if (kdTree != NULL) delete kdTree;*/ }
public:
void start();
bool findSeedTriangle(CTriangle*& pFace, int K =10);
bool getCandidatePoint(const FrontIter& itFront, int& vIdx, bool& bFrontVertex );
//=============Mesh 权值计算方法=============//
public:
};
#endif | [
"huangchunkuangke@e87e5053-baee-b2b1-302d-3646b6e6cf75"
]
| [
[
[
1,
328
]
]
]
|
cac2ac7de9ecbe58115bdbcec58adca9ce426ea1 | 1d6dcdeddc2066f451338361dc25196157b8b45c | /tp2/Visualizacion/Camara.cpp | 9c915cc718baf53b58bcd3e462aa77bdeb237653 | []
| no_license | nicohen/ssgg2009 | 1c105811837f82aaa3dd1f55987acaf8f62f16bb | 467e4f475ef04d59740fa162ac10ee51f1f95f83 | refs/heads/master | 2020-12-24T08:16:36.476182 | 2009-08-15T00:43:57 | 2009-08-15T00:43:57 | 34,405,608 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 328 | cpp | #include "Camara.h"
Camara::Camara(){
this->eye[0] = 15.0;
this->eye[1] = 15.0;
this->eye[2] = 5.0;
this->at[0] = 0.0;
this->at[1] = 0.0;
this->at[2] = 0.0;
this->up[0] = 0.0;
this->up[1] = 0.0;
this->up[2] = 1.0;
this->zoom = 30.0;
}
Camara::~Camara()
{
//dtor
}
| [
"rodvar@6da81292-15a5-11de-a4db-e31d5fa7c4f0"
]
| [
[
[
1,
19
]
]
]
|
9f8bb7e32d03efed6bf491a9f428aece7a588b60 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/WORLDSERVER/WorldDialog.cpp | 2ba1281d73060046c97ae6be3a8890824097f0be | []
| no_license | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,728 | cpp | #include "stdafx.h"
#if defined(__REMOVE_SCIRPT_060712)
#include "WorldDialog.h"
extern void InitDialogFunctions();
CWorldDialog& CWorldDialog::GetInstance()
{
static CWorldDialog obj;
return obj;
}
CWorldDialog::CWorldDialog()
{
m_hDLL = NULL;
m_pfnRunDialog = NULL;
m_pfnFindScriptKey = NULL;
m_pfnInitWorldDialog = NULL;
}
CWorldDialog::~CWorldDialog()
{
Free();
}
BOOL CWorldDialog::Reload()
{
Free();
return Load();
}
BOOL CWorldDialog::Load()
{
HINSTANCE hModule = LoadLibrary( "WorldDialog.dll" );
if( hModule )
{
m_hDLL = hModule;
m_pfnRunDialog = (PFRUNDIALOG)GetProcAddress( m_hDLL, "RunDialog" );
m_pfnFindScriptKey = (PFFINDSCIRPTKEY)GetProcAddress( m_hDLL, "FindScriptKey" );
m_pfnInitWorldDialog = (PFINITWORLDDIALOG)GetProcAddress( m_hDLL, "InitWorldDialog" );
PFSETLANGUAGE pfSetLanguage = (PFSETLANGUAGE)GetProcAddress( m_hDLL, "SetLanguage" );
if( m_pfnRunDialog && m_pfnFindScriptKey && m_pfnInitWorldDialog && pfSetLanguage )
{
pfSetLanguage(::GetLanguage());
if(m_pfnInitWorldDialog())
return TRUE;
else
return FALSE;
}
}
return FALSE;
}
void CWorldDialog::Free()
{
if( m_hDLL )
{
::FreeLibrary( m_hDLL );
m_hDLL = NULL;
}
}
BOOL CWorldDialog::Init()
{
InitDialogFunctions();
return Load();
}
BOOL CWorldDialog::Find( LPCTSTR szName, LPCTSTR szKey )
{
if( m_hDLL )
return m_pfnFindScriptKey( szName, szKey );
else
return FALSE;
}
int CWorldDialog::Run( LPCTSTR szName, LPCTSTR szKey, NPCDIALOG_INFO* pInfo )
{
if( m_hDLL )
return m_pfnRunDialog( szName, szKey, pInfo );
else
return 0;
}
#endif // #if defined(__REMOVE_SCIRPT_060712)
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
]
| [
[
[
1,
88
]
]
]
|
93f965fa485ff17864717245bff239c800b159f5 | 6e563096253fe45a51956dde69e96c73c5ed3c18 | /dhnetsdk/Demo/AlarmCtrlDlg.cpp | 1030b8ddc01d92bfb676b409cbf2802099158832 | []
| no_license | 15831944/phoebemail | 0931b76a5c52324669f902176c8477e3bd69f9b1 | e10140c36153aa00d0251f94bde576c16cab61bd | refs/heads/master | 2023-03-16T00:47:40.484758 | 2010-10-11T02:31:02 | 2010-10-11T02:31:02 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 5,651 | cpp | // AlarmCtrlDlg.cpp : implementation file
//
#include "stdafx.h"
#include "netsdkdemo.h"
#include "AlarmCtrlDlg.h"
#include "NetSDKDemoDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CAlarmCtrlDlg dialog
CAlarmCtrlDlg::CAlarmCtrlDlg(CWnd* pParent /*=NULL*/)
: CDialog(CAlarmCtrlDlg::IDD, pParent)
{
m_DeviceId = 0;
m_inNum = 0;
m_outNum = 0;
//{{AFX_DATA_INIT(CAlarmCtrlDlg)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
}
void CAlarmCtrlDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAlarmCtrlDlg)
// NOTE: the ClassWizard will add DDX and DDV calls here
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAlarmCtrlDlg, CDialog)
//{{AFX_MSG_MAP(CAlarmCtrlDlg)
ON_BN_CLICKED(IDC_SAVE_IO, OnSaveIo)
ON_BN_CLICKED(IDC_CANCEL, OnCancel)
ON_BN_CLICKED(IDC_TRIGGER, OnTrigger)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CAlarmCtrlDlg message handlers
void CAlarmCtrlDlg::SetDeviceId(LONG nDeviceId)
{
m_DeviceId = nDeviceId;
}
void CAlarmCtrlDlg::OnSaveIo()
{
int i;
BOOL nRet = FALSE;
if(m_DeviceId)
{
for(i = 0; i < m_inNum; i++)
{
if(((CButton *)GetDlgItem(IDC_CTRLIN1 + i))->GetCheck())
{
m_inState[i].state = 1;
}
else
{
m_inState[i].state = 0;
}
}
if(m_inNum)
{
nRet = CLIENT_IOControl(m_DeviceId, IOTYPE_ALARMINPUT, m_inState, sizeof(ALARM_CONTROL) *m_inNum );
if (!nRet)
{
((CNetSDKDemoDlg *)GetParent())->LastError();//Peng Dongfeng 06.11.24
}
}
if(!nRet)
{
MessageBox(ConvertString(MSG_ERROR_IOCTRL_IN));
return;
}
for(int i = 0; i < m_outNum; i++)
{
if(((CButton *)GetDlgItem(IDC_CTRLOUT1 + i))->GetCheck())
{
m_outState[i].state = 1;
}
else
{
m_outState[i].state = 0;
}
}
if(m_outNum)
{
nRet = CLIENT_IOControl(m_DeviceId, IOTYPE_ALARMOUTPUT, m_outState, sizeof(ALARM_CONTROL) *m_outNum );
if (!nRet)
{
((CNetSDKDemoDlg *)GetParent())->LastError();//Peng Dongfeng 06.11.24
}
}
if(!nRet)
{
MessageBox(ConvertString(MSG_ERROR_IOCTRL_OUT));
return;
}
}
CDialog::OnOK();
// TODO: Add your control notification handler code here
}
void CAlarmCtrlDlg::OnCancel()
{
// TODO: Add your control notification handler code here
CDialog::OnCancel();
}
BOOL CAlarmCtrlDlg::OnInitDialog()
{
g_SetWndStaticText(this);
BOOL nRet;
int i, j;
WORD nState;
CDialog::OnInitDialog();
if(m_DeviceId)
{
nRet = CLIENT_QueryIOControlState(m_DeviceId,IOTYPE_ALARMINPUT,NULL,0,&m_inNum);
if(nRet)
{
if(m_inNum > MAX_IO_NUM)
{
MessageBox(ConvertString(MSG_ERROR_ALARMCHL_OVERMAX));
goto e_close;
}
nRet = CLIENT_QueryIOControlState(m_DeviceId,IOTYPE_ALARMINPUT,m_inState,sizeof(ALARM_CONTROL)*m_inNum,&m_inNum);
if (!nRet)
{
((CNetSDKDemoDlg *)GetParent())->LastError();//Peng Dongfeng 06.11.24
}
}
if(!nRet || !m_inNum)
{
MessageBox(ConvertString(MSG_ERROR_ALARM_STATUS));
goto e_close;
}
if(m_inNum > MAX_IO_NUM)
{
m_inNum = MAX_IO_NUM;
}
for(i = 0; i < m_inNum; i++)
{
nState = m_inState[i].state;
if(nState)
{
((CButton *)GetDlgItem(IDC_CTRLIN1 + i))->SetCheck(1);
}
else
{
((CButton *)GetDlgItem(IDC_CTRLIN1 + i))->SetCheck(0);
}
}
for(j = m_inNum; j < MAX_IO_NUM; j++)
{
((CButton *)GetDlgItem(IDC_CTRLIN1 + j))->EnableWindow(false);
((CButton *)GetDlgItem(IDC_CTRLIN17 + j))->EnableWindow(false);
}
//Êä³ö
nRet = CLIENT_QueryIOControlState(m_DeviceId,IOTYPE_ALARMOUTPUT,NULL,0,&m_outNum);
if(nRet)
{
if(m_outNum > MAX_IO_NUM)
{
MessageBox(ConvertString(MSG_ERROR_ALARMCHL_OVERMAX));
goto e_close;
}
nRet = CLIENT_QueryIOControlState(m_DeviceId,IOTYPE_ALARMOUTPUT,m_outState,sizeof(ALARM_CONTROL)*m_outNum,&m_outNum);
if (!nRet)
{
((CNetSDKDemoDlg *)GetParent())->LastError();//Peng Dongfeng 06.11.24
}
}
if(!nRet || !m_outNum)
{
MessageBox(ConvertString(MSG_ERROR_ALARM_STATUS));
goto e_close;
}
if(m_outNum > MAX_IO_NUM)
{
m_outNum = MAX_IO_NUM;
}
for(i = 0; i < m_outNum; i++)
{
nState = m_outState[i].state;
if(nState)
{
((CButton *)GetDlgItem(IDC_CTRLOUT1 + i))->SetCheck(1);
}
else
{
((CButton *)GetDlgItem(IDC_CTRLOUT1 + i))->SetCheck(0);
}
}
for(j = m_outNum; j < MAX_IO_NUM; j++)
{
((CButton *)GetDlgItem(IDC_CTRLOUT1 + j))->EnableWindow(false);
}
}
memset(m_triggerIn, 0, sizeof(ALARMCTRL_PARAM)*MAX_IO_NUM);
return TRUE;
e_close:
((CButton *)GetDlgItem(IDC_SAVE_IO))->EnableWindow(FALSE);
return TRUE;
}
void CAlarmCtrlDlg::OnTrigger()
{
//½â·¢ÍøÂ籨¾¯
for(int i = 0; i < m_inNum; i++)
{
m_triggerIn[i].dwSize = sizeof(ALARMCTRL_PARAM);
m_triggerIn[i].nAlarmNo = i;
if(((CButton *)GetDlgItem(IDC_CTRLIN17 + i))->GetCheck())
{
m_triggerIn[i].nAction = 1;
}
else
{
m_triggerIn[i].nAction = 0;
}
BOOL b = CLIENT_ControlDevice(m_DeviceId, CTRL_TYPE_TRIGGER_ALARM_IN, &m_triggerIn[i], 1000);
if (!b)
{
MessageBox("trigger failed!");
((CNetSDKDemoDlg *)GetParent())->LastError();//Peng Dongfeng 06.11.24
break;
}
}
}
| [
"guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd"
]
| [
[
[
1,
257
]
]
]
|
b470f7dad60cf141a4ebc28bd84f13b060a36666 | 28aa23d9cb8f5f4e8c2239c70ef0f8f6ec6d17bc | /mytesgnikrow --username hotga2801/Project/Adaboost/SFaceDetection/FaceDetectionDlg.cpp | b4615f3fa838e19e26b4d2b8a01ef6a1ca29d66b | []
| no_license | taicent/mytesgnikrow | 09aed8836e1297a24bef0f18dadd9e9a78ec8e8b | 9264faa662454484ade7137ee8a0794e00bf762f | refs/heads/master | 2020-04-06T04:25:30.075548 | 2011-02-17T13:37:16 | 2011-02-17T13:37:16 | 34,991,750 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,521 | cpp | /*
---- Author : Binh Nguyen - Bioz
---- Last Update : 21 Oct 2008
---- License : Free
---- Official site : www.sectic.com
---- Description : detect face by using haar model supplied by OpenCV lib.
*/
// FaceDetectionDlg.cpp : implementation file
//
#include "stdafx.h"
#include "FaceDetection.h"
#include "FaceDetectionDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()
// CFaceDetectionDlg dialog
CFaceDetectionDlg::CFaceDetectionDlg(CWnd* pParent /*=NULL*/)
: CDialog(CFaceDetectionDlg::IDD, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CFaceDetectionDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CFaceDetectionDlg, CDialog)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
//}}AFX_MSG_MAP
ON_BN_CLICKED(IDOK, &CFaceDetectionDlg::OnBnClickedOk)
ON_BN_CLICKED(IDCANCEL, &CFaceDetectionDlg::OnBnClickedCancel)
ON_BN_CLICKED(IDC_BUTTON_CASCADE_OPEN, &CFaceDetectionDlg::OnBnClickedButtonCascadeOpen)
ON_LBN_SELCHANGE(IDC_LIST_IMAGE, &CFaceDetectionDlg::OnLbnSelchangeListImage)
ON_LBN_SELCHANGE(IDC_LIST_CASCADE, &CFaceDetectionDlg::OnLbnSelchangeListCascade)
ON_BN_CLICKED(IDC_BUTTON_IMAGE_OPEN, &CFaceDetectionDlg::OnBnClickedButtonImageOpen)
END_MESSAGE_MAP()
// CFaceDetectionDlg message handlers
BOOL CFaceDetectionDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
//-------- Set default cascade ------------
char strPathName[_MAX_PATH];
::GetModuleFileName(NULL, strPathName, _MAX_PATH);
// The following code will allow you to get the path.
CString temp_path(strPathName);
int fpos = temp_path.ReverseFind('\\');
if (fpos != -1)
{
cascade_root = temp_path.Left(fpos + 1);
image_path = cascade_root + "face_default.jpg";
cascade_path = cascade_root + "haarcascade_frontalface_default.xml";
}
GetDlgItem(IDC_EDIT_SCALE)->SetWindowText("1");
//----------------------------------------------------
return TRUE; // return TRUE unless you set the focus to a control
}
void CFaceDetectionDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CFaceDetectionDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
// The system calls this function to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CFaceDetectionDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void CFaceDetectionDlg::OnBnClickedOk()
{
// TODO: Add your control notification handler code here
OpenCVFaceDetection *detector;
int status;
double time; // time to run algorithm
CvSeq* faces = NULL; // Storage for found face coordinates.
status = detector->init_cascade(cascade_path);
if(status < 0){
fprintf(stderr, "Initializing cascade failed.\n");
exit(1);
}
//--------- Get Value of Scale from Textbox ------------
CString strTextBoxValue;
CWnd* txtScale=GetDlgItem(IDC_EDIT_SCALE);
txtScale->GetWindowText(strTextBoxValue);
if(strTextBoxValue.IsEmpty())
{
strTextBoxValue.Format(_T("%f"),SCALE);
}
double scale;
try{
scale = atof(strTextBoxValue);
}catch(CException* e)
{
AfxMessageBox("Please input a number for scale!",MB_OK,0);
GetDlgItem(IDC_EDIT_SCALE)->SetWindowText("1");
}
//------------------------------------------------------
IplImage *output; // This is the image pointer (output)
output= cvCreateImage(cvSize(image->width,image->height), image->depth, image->nChannels); // output image memory allocation
cvCopyImage(image, output); // create a copy of origin image
faces = detector->detect_face(output, atof(strTextBoxValue), time);
CString temp;
temp.Format(_T("Num of Face: %d"), faces->total);
GetDlgItem(IDC_STATIC_STATISTIC_LABEL)->SetWindowText(temp);
temp.Format(_T("Time to run: %f ms"), time);
GetDlgItem(IDC_STATIC_STATISTIC_LABEL2)->SetWindowText(temp);
cvNamedWindow( "Original Image"); // Create window for image show by OpenCV
cvShowImage("Original Image", output); // Show image in the window
cvReleaseImage(&output);
}
void CFaceDetectionDlg::OnBnClickedCancel()
{
// TODO: Add your control notification handler code here
cvDestroyAllWindows();
OnCancel();
}
void CFaceDetectionDlg::OnBnClickedButtonCascadeOpen()
{
//TODO: Add your control notification handler code here
BROWSEINFO bi;
ZeroMemory(&bi, sizeof(bi));
TCHAR szDisplayName[MAX_PATH];
szDisplayName[0] = ' ';
bi.hwndOwner = NULL;
bi.pidlRoot = NULL;
bi.pszDisplayName = szDisplayName;
bi.lpszTitle = _T("Please select a folder that stored cascade files :");
bi.ulFlags = BIF_RETURNONLYFSDIRS;
bi.lParam = NULL;
bi.iImage = 0;
LPITEMIDLIST pidl = SHBrowseForFolder(&bi);
TCHAR szPathName[MAX_PATH];
if (NULL != pidl)
{
BOOL bRet = SHGetPathFromIDList(pidl,szPathName);
if(FALSE == bRet)
{
return;
}
cascade_root = strcat(szPathName,"\\");
LoadFileListToListBox(IDC_LIST_CASCADE,cascade_root, "*.xml");
}
}
void CFaceDetectionDlg::LoadFileListToListBox(int id_list, CString root, CString extFile)
{
CListBox * pList;
pList = (CListBox *)GetDlgItem(id_list);
pList->ResetContent();
CFileFind finder;
BOOL finding = finder.FindFile (root + extFile);
//iterate the results
int count=0;
while (finding)
{
finding = finder.FindNextFile();
pList->AddString(finder.GetFileName());
count++;
}
if(count <= 0)
{
pList->AddString("no files found");
}
finder.Close ();
}
CString CFaceDetectionDlg::GetFileNameFromListBox(int id_list)
{
CListBox * pList;
pList = (CListBox *)GetDlgItem(id_list);
CString result="";
int nIndex = pList->GetCurSel();
pList->GetText(nIndex, result);
return result;
}
void CFaceDetectionDlg::OnLbnSelchangeListImage()
{
// TODO: Add your control notification handler code here
CString path = image_path + GetFileNameFromListBox(IDC_LIST_IMAGE);
image= cvLoadImage(path); // load the image
cvNamedWindow( "Original Image"); // Create window for image show by OpenCV
cvShowImage("Original Image", image); // display it
}
void CFaceDetectionDlg::OnLbnSelchangeListCascade()
{
// TODO: Add your control notification handler code here
cascade_path = cascade_root + GetFileNameFromListBox(IDC_LIST_CASCADE);
}
void CFaceDetectionDlg::OnBnClickedButtonImageOpen()
{
// TODO: Add your control notification handler code here
BROWSEINFO bi;
ZeroMemory(&bi, sizeof(bi));
TCHAR szDisplayName[MAX_PATH];
szDisplayName[0] = ' ';
bi.hwndOwner = NULL;
bi.pidlRoot = NULL;
bi.pszDisplayName = szDisplayName;
bi.lpszTitle = _T("Please select a folder that stored image files :");
bi.ulFlags = BIF_RETURNONLYFSDIRS;
bi.lParam = NULL;
bi.iImage = 0;
LPITEMIDLIST pidl = SHBrowseForFolder(&bi);
TCHAR szPathName[MAX_PATH];
if (NULL != pidl)
{
BOOL bRet = SHGetPathFromIDList(pidl,szPathName);
if(FALSE == bRet)
{
return;
}
image_path = strcat(szPathName,"\\");
LoadFileListToListBox(IDC_LIST_IMAGE,image_path, "*.jpg");
}
}
| [
"hotga2801@ecd9aaca-b8df-3bf4-dfa7-576663c5f076"
]
| [
[
[
1,
372
]
]
]
|
bcbb47cace524cb21ace8d854fda16af4393c846 | bef7d0477a5cac485b4b3921a718394d5c2cf700 | /ic2005/src/extern/ode/src/opcode/IceRevisitedRadix.h | 896637ec9a8fe040d2dbd1951f88db219552c57f | [
"MIT"
]
| permissive | TomLeeLive/aras-p-dingus | ed91127790a604e0813cd4704acba742d3485400 | 22ef90c2bf01afd53c0b5b045f4dd0b59fe83009 | refs/heads/master | 2023-04-19T20:45:14.410448 | 2011-10-04T10:51:13 | 2011-10-04T10:51:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,679 | h | ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Contains source code from the article "Radix Sort Revisited".
* \file IceRevisitedRadix.h
* \author Pierre Terdiman
* \date April, 4, 2000
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Include Guard
#ifndef __ICERADIXSORT_H__
#define __ICERADIXSORT_H__
#include "OPC_IceHook.h"
//! Allocate histograms & offsets locally
#define RADIX_LOCAL_RAM
enum RadixHint
{
RADIX_SIGNED, //!< Input values are signed
RADIX_UNSIGNED, //!< Input values are unsigned
RADIX_FORCE_DWORD = 0x7fffffff
};
class ICECORE_API RadixSort
{
public:
// Constructor/Destructor
RadixSort();
~RadixSort();
// Sorting methods
RadixSort& Sort(const udword* input, udword nb, RadixHint hint=RADIX_SIGNED);
RadixSort& Sort(const float* input, udword nb);
//! Access to results. mRanks is a list of indices in sorted order, i.e. in the order you may further process your data
inline_ const udword* GetRanks() const { return mRanks; }
//! mIndices2 gets trashed on calling the sort routine, but otherwise you can recycle it the way you want.
inline_ udword* GetRecyclable() const { return mRanks2; }
// Stats
udword GetUsedRam() const;
//! Returns the total number of calls to the radix sorter.
inline_ udword GetNbTotalCalls() const { return mTotalCalls; }
//! Returns the number of eraly exits due to temporal coherence.
inline_ udword GetNbHits() const { return mNbHits; }
private:
#ifndef RADIX_LOCAL_RAM
udword* mHistogram; //!< Counters for each byte
udword* mOffset; //!< Offsets (nearly a cumulative distribution function)
#endif
udword mCurrentSize; //!< Current size of the indices list
udword* mRanks; //!< Two lists, swapped each pass
udword* mRanks2;
// Stats
udword mTotalCalls; //!< Total number of calls to the sort routine
udword mNbHits; //!< Number of early exits due to coherence
// Internal methods
void CheckResize(udword nb);
bool Resize(udword nb);
};
#endif // __ICERADIXSORT_H__
| [
"[email protected]"
]
| [
[
[
1,
67
]
]
]
|
8b0eba0f15aee126ff23831ac1e3cde4059f83fb | dc4f8d571e2ed32f9489bafb00b420ca278121c6 | /mojo_engine/cKeyboardStateEx.h | 628b54a1897836fba9a66560e3df9a0d4f6a9eda | []
| no_license | mwiemarc/mojoware | a65eaa4ec5f6130425d2a1e489e8bda4f6f88ec0 | 168a2d3a9f87e6c585bde4a69b97db53f72deb7f | refs/heads/master | 2021-01-11T20:11:30.945122 | 2010-01-25T00:27:47 | 2010-01-25T00:27:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,488 | h | /***********************************************************************************************************************
/*
/* cKeyboardStateEx.h
/*
/* Stores EXTENDED virtual key codes, i.e., virtual key code + (if extended) 0x100.
/* Used by keyboard hook handler to set the previous keystate bit.
/*
/* Copyright 2009 Robert Sacks. See end of file for more info.
/*
/**********************************************************************************************************************/
#pragma once
#include "cTrigger.h"
//======================================================================================================================
// DATA
//======================================================================================================================
//======================================================================================================================
// CLASS
//======================================================================================================================
class cKeyboardStateEx
{
public:
cKeyboardStateEx ();
void get_key_state_as_trigger ( mojo::cTrigger * pRet );
static WORD ex_vk ( const KBDLLHOOKSTRUCT * p ) { return (WORD) p->vkCode + ( p->flags & LLKHF_EXTENDED ? 0x100 : 0 ); }
DWORD mod_state () const;
void receive ( const KBDLLHOOKSTRUCT * p );
bool is_down ( unsigned uExVK ) { return down == ayTable[uExVK]; };
friend mojo::cTrigger::cTrigger ( const cKeyboardStateEx * );
WORD wMostRecentPressedExVK;
WORD wMostRecentExVK;
enum eEvent { up, down };
eEvent eMostRecentEvent;
private:
unsigned char ayTable [ 512 ];
HWND hNotificand;
};
//----------------------------------------------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------------------------------------------
/***********************************************************************************************************************
/*
/* This file is part of Mojo. For more information, see http://mojoware.org.
/*
/* You may redistribute and/or modify Mojo under the terms of the GNU General Public License, version 3, as
/* published by the Free Software Foundation. You should have received a copy of the license with Mojo. If you
/* did not, go to http://www.gnu.org.
/*
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "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 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.
/*
/***********************************************************************************************************************/ | [
"[email protected]"
]
| [
[
[
1,
76
]
]
]
|
1fb5503b8e72105daa0bd12189ef1d427f27b4f7 | 9176b0fd29516d34cfd0b143e1c5c0f9e665c0ed | /CS_153_Data_Structures/assignment6/bst.hpp | 6efc153362b205dc366197cc7c19156c7ff839a6 | []
| no_license | Mr-Anderson/james_mst_hw | 70dbde80838e299f9fa9c5fcc16f4a41eec8263a | 83db5f100c56e5bb72fe34d994c83a669218c962 | refs/heads/master | 2020-05-04T13:15:25.694979 | 2011-11-30T20:10:15 | 2011-11-30T20:10:15 | 2,639,602 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,340 | hpp | //////////////////////////////////////////////////////////////////////
/// @file bst.hpp
/// @author James Anderson CS 153 Section A
/// @brief Template implemintation file for
/// the bst class for assignment 6
//////////////////////////////////////////////////////////////////////
template <class generic>
void Bst<generic>::insert (generic x)
{
m_size++ ;
if (m_root == NULL)
{
m_root = new Btn<generic>;
m_root->data = new generic;
m_root->instance = new int;
*(m_root->instance) = 1;
*(m_root->data) = x ;
m_root->parent = NULL;
m_root->left = NULL;
m_root->right = NULL;
}
else
{
Btn<generic> * temp = m_root;
do
{
if(*(temp->data) > x )
{
if (temp->left == NULL )
{
temp->left = new Btn<generic>;
temp->left->data = new generic;
temp->left->instance = new int;
*(temp->left->instance) = 1;
*(temp->left->data) = x ;
temp->left->parent = temp;
temp->left->left = NULL;
temp->left->right = NULL;
temp = NULL;
}
else
{
temp = temp->left;
}
}
else if(*(temp->data) < x )
{
if (temp->right == NULL )
{
temp->right = new Btn<generic>;
temp->right->data = new generic;
temp->right->instance = new int;
*(temp->right->instance) = 1;
*(temp->right->data) = x ;
temp->right->parent = temp;
temp->right->left = NULL;
temp->right->right = NULL;
temp = NULL;
}
else
{
temp = temp->right;
}
}
else if(*(temp->data) = x )
{
*(temp->instance)++;
temp = NULL;
}
}while (temp != NULL) ;
}
}
template <class generic>
void Bst<generic>::remove (generic x)
{
Btn<generic> * temp ;
//throw exception if empty
if (m_root == NULL)
{
throw Exception
(
CONTAINER_EMPTY,
"The container is empty. You canot make it smaller."
);
}
//find node with data were looking for
temp = p_search (x);
//if the item to be deleted exists
if (temp != NULL)
{
//node to delete has no children
if (temp->left == NULL && temp->right == NULL )
{
delete_leaf (temp);
}
//node to delete has two children
else if (temp->left != NULL && temp->right != NULL )
{
//move temp2 down to left right most
Btn<generic> * temp2 ;
temp2 = temp;
if (temp2->left !=NULL)
temp2 = temp2->left;
while ( temp2->right != NULL )
{
temp2 = temp2->right ;
}
//swap data in node to delete
swap(temp , temp2);
//node to delete has no children
if (temp2->left == NULL && temp2->right == NULL )
{
delete_leaf ( temp2 ) ;
}
//node to delete has one child
else
{
//cerr << temp2 << endl;
delete_link ( temp2 ) ;
}
}
//node to delete has one child
else
{
delete_link ( temp ) ;
}
}
}
template <class generic>
BTPreorderIterator<generic> Bst<generic>::pre_search (generic x)
{
return PreOrder (p_search(x));
}
template <class generic>
BTInorderIterator<generic> Bst<generic>::in_search (generic x)
{
return InOrder (p_search(x));
}
template <class generic>
BTPostorderIterator<generic> Bst<generic>::post_search (generic x)
{
return PostOrder (p_search(x));
}
template <class generic>
void Bst<generic>::swap (Btn<generic> * temp1, Btn<generic> * temp2)
{
generic * temp3 = NULL;
temp3 = temp1->data;
temp1->data = temp2->data;
temp2->data = temp3;
temp3 = NULL;
int * temp4 = NULL;
temp4 = temp1->instance;
temp1->instance = temp2->instance;
temp2->instance = temp4;
temp4 = NULL;
}
template <class generic>
void Bst<generic>::delete_leaf (Btn<generic> *temp1)
{
if (temp1->parent != NULL)
{
if (temp1->parent->right == temp1)
{
temp1->parent->right = NULL;
}
else if (temp1->parent->left == temp1)
{
temp1->parent->left = NULL;
}
}
else
{
m_root = NULL;
}
m_size = m_size - *(temp1->instance) ;
delete temp1->instance;
delete temp1->data;
delete temp1;
}
template <class generic>
void Bst<generic>::delete_link (Btn<generic> * temp1)
{
//cerr << "fuck my life" << endl;
//child to right
if (temp1->right != NULL)
{
//point parent to child
if ( temp1->parent != NULL)
{
if (temp1->parent->right == temp1)
{
temp1->parent->right = temp1->right;
}
else if (temp1->parent->left == temp1)
{
temp1->parent->left = temp1->right;
}
}
else
{
m_root = temp1->right;
}
//point child to parent
temp1->right->parent = temp1->parent;
//delete node
}
//child to left
else
{
//point parent to child
if ( temp1->parent != NULL)
{
if (temp1->parent->right == temp1)
{
temp1->parent->right = temp1->left;
}
else if (temp1->parent->left == temp1)
{
temp1->parent->left = temp1->left;
}
}
else
{
m_root = temp1->left;
}
//point child to parent
temp1->left->parent = temp1->parent;
//delete node
}
m_size = m_size - *(temp1->instance) ;
delete temp1->instance;
delete temp1->data;
delete temp1;
}
template <class generic>
Btn<generic> * Bst<generic>::p_insert (generic x)
{
Btn<generic> * temp ;
temp = m_root;
bool loop = true ;
//set temp to the x wher looking for
while ( loop )
{
//cerr << "searching for" << x << endl;
if (temp->right == NULL || temp->left == NULL)
{
loop = 0 ;
}
else if(*(temp->data) > x )
{
temp = temp->left;
}
else if(*(temp->data) < x )
{
temp = temp->right;
}
else if (*(temp->data) == x)
{
temp = temp->parent;
loop = 0 ;
}
}
//cerr << "found" << *(temp->data) << endl;
return temp ;
}
template <class generic>
Btn<generic> * Bst<generic>::p_remove (generic x)
{
Btn<generic> * temp ;
temp = m_root;
bool loop = true ;
//set temp to the x wher looking for
while ( loop )
{
//cerr << "searching for" << x << endl;
if (temp == NULL)
{
loop = 0 ;
}
else if(*(temp->data) > x )
{
temp = temp->left;
}
else if(*(temp->data) < x )
{
temp = temp->right;
}
else if (*(temp->data) == x)
{
loop = 0 ;
}
}
//cerr << "found" << *(temp->data) << endl;
return temp->parent ;
}
template <class generic>
Btn<generic> * Bst<generic>::p_search (generic x)
{
Btn<generic> * temp ;
temp = m_root;
bool loop = true ;
//set temp to the x wher looking for
while ( loop )
{
//cerr << "searching for" << x << endl;
if (temp == NULL)
{
loop = 0 ;
}
else if(*(temp->data) > x )
{
temp = temp->left;
}
else if(*(temp->data) < x )
{
temp = temp->right;
}
else if (*(temp->data) == x)
{
loop = 0 ;
}
}
//cerr << "found" << *(temp->data) << endl;
if ( temp == NULL)
{
throw Exception
(
NOT_FOUND,
"Im sorry dave, I canot return that value."
);
}
return temp ;
}
| [
"[email protected]"
]
| [
[
[
1,
432
]
]
]
|
0a0813615fecaa256cb1d23f088c16321e0ca70b | 8020ee737f9d88efac93bba3b9ff4e03bb96ff2a | /src/tetris.h | f15e221b6aed8e56d56d400f3f942e5ce4cc4db9 | [
"WTFPL"
]
| permissive | osgcc/osgcc2-OMGWTFADD | f4169c06436ae0357e9143015ccf671041925154 | 2ec7d0de5deea28980c5d4e66501406e71f36205 | refs/heads/master | 2020-08-23T16:28:06.086903 | 2010-03-11T22:14:47 | 2010-03-11T22:14:47 | 823,620 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,750 | h |
#ifndef TETRIS_INCLUDED
#define TETRIS_INCLUDED
#include "game.h"
class Tetris : public Game
{
public:
// conventions:
void Update(game_info* gi, float deltatime);
void Draw(game_info* gi);
void DrawOrtho(game_info* gi);
void KeyDown(game_info* gi, Uint32 key);
void KeyUp(game_info* gi, Uint32 key);
void KeyRepeat(game_info* gi);
void Attack(game_info* gi, int severity);
void MouseMovement(game_info* gi, Uint32 x, Uint32 y);
void MouseDown(game_info* gi);
void InitGame(game_info* gi);
// stuffs:
void GetNewPiece(game_info* gi);
void DrawBoard(game_info* gi);
void DrawPiece(game_info* gi, double x, double y);
void DrawBlock(int type, game_info* gi, double x, double y);
void AddPiece(game_info* gi);
void AddPiece(game_info* gi, int start_x, int start_y);
void AddBlock(game_info* gi, int i, int j, int type);
void DropPiece(game_info* gi);
int ClearLines(game_info* gi);
void PushUp(game_info* gi, int num);
void DropLine(game_info* gi, int lineIndex);
bool TestGameOver(game_info* gi);
bool TestCollisionBlock(game_info* gi, double x, double y);
bool TestCollision(game_info* gi);
bool TestCollision(game_info* gi, double x, double y);
double TestSideCollision(game_info* gi, double x, double y);
// materials:
// board posts:
static GLfloat board_piece_amb[4];
static GLfloat board_piece_diff[4];
static GLfloat board_piece_spec[4];
static GLfloat board_piece_shine;
static GLfloat board_piece_emi[4];
// block materials
static GLfloat tet_piece_amb[4];
static GLfloat tet_piece_diff[6][4];
static GLfloat tet_piece_spec[4];
static GLfloat tet_piece_emi[4];
static GLfloat tet_piece_shine;
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
73
]
]
]
|
9496014e4f88c366cce33c8ca1126031bd0310cd | b84a38aad619acf34c22ed6e6caa0f7b00ebfa0a | /Code/TootleGui/TLGui.h | 429387ac55519e7edf9a620d643b3d424916ad05 | []
| no_license | SoylentGraham/Tootle | 4ae4e8352f3e778e3743e9167e9b59664d83b9cb | 17002da0936a7af1f9b8d1699d6f3e41bab05137 | refs/heads/master | 2021-01-24T22:44:04.484538 | 2010-11-03T22:53:17 | 2010-11-03T22:53:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,161 | h | /*------------------------------------------------------
The GUI library is a generic interface to the OS's windows
and controls. For the Mac and PC this goes through wxWidgets
(via our own wrapper)
-------------------------------------------------------*/
#pragma once
#include <TootleCore/TLTypes.h>
#include <TootleCore/TRef.h>
#include <TootleCore/TPtr.h>
namespace TLMessaging
{
class TPublisher;
}
namespace TLGui
{
// generic types
class TControl; // an OS control inside a window
class TWindow; // a OS window.
class TMenuWrapper; // manages link between a menu controller and a menu attached to a window (not OS specialised)
class TMenuHandler; // OS menu handler - try and merge menu wrapper and handler?
// control types
class TOpenglCanvas; // opengl area - maybe rename this to "RenderCanvas" to cope with directx's requirements etc
class TTree; // Multi-columned tree
class TTreeItem; // item in a tree (not a control)
SyncBool Init(); // lib init
SyncBool Shutdown(); // lib init
DEPRECATED TString GetAppExe();
const TString& GetAppPath();
void SetAppPath(const TString& Path);
bool OnCommandLine(const TString& CommandLine,int& Result); // handle command line params - if true is returned, return Result from main
// factory style wrappers. Temporary implementation until I decide how data/factory driven I want this to be
TPtr<TWindow> CreateGuiWindow(TRefRef Ref);
TPtr<TOpenglCanvas> CreateOpenglCanvas(TWindow& Parent,TRefRef Ref);
TPtr<TTree> CreateTree(TWindow& Parent,TRefRef Ref,TPtr<TTreeItem>& pRootItem,const TArray<TRef>& Columns); // render[0] = ItemData[ column[0] ]
// some hacky global functions
DEPRECATED int2 GetDefaultScreenMousePosition(); // get the cursor position in the default screen's client space
namespace Platform
{
SyncBool Init();
SyncBool Shutdown();
void GetDesktopSize(Type4<s32>& DesktopSize); // get the desktop dimensions. note: need a window so we can decide which desktop?
#if defined(TL_TARGET_PC)
extern void* g_HInstance; // HINSTANCE
#endif
}
};
| [
"[email protected]"
]
| [
[
[
1,
60
]
]
]
|
ed3af05709680d0262bb4d1404cc91a803da33ca | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/serialization/test/test_cyclic_ptrs.cpp | 3fa8b481df8f60b667fb1ad3fd0d01bc069e8860 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,419 | cpp | /////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// test_cyclic_ptrs.cpp
// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com .
// Use, modification and distribution is subject to 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)
// should pass compilation and execution
#include <fstream>
#include <cstdio> // remove
#include <boost/config.hpp>
#if defined(BOOST_NO_STDC_NAMESPACE)
namespace std{
using ::remove;
}
#endif
#include "test_tools.hpp"
#include <boost/preprocessor/stringize.hpp>
#include BOOST_PP_STRINGIZE(BOOST_ARCHIVE_TEST)
#include <boost/detail/no_exceptions_support.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/version.hpp>
#include <boost/serialization/base_object.hpp>
#include "A.hpp"
///////////////////////////////////////////////////////
// class with a member which refers to itself
class J : public A
{
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive &ar, const unsigned int /* file_version */){
ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(A);
ar & BOOST_SERIALIZATION_NVP(j);
}
public:
bool operator==(const J &rhs) const;
J *j;
J(J *_j) : j(_j) {}
J() : j(NULL){}
};
BOOST_CLASS_VERSION(J, 6)
bool J::operator==(const J &rhs) const
{
return static_cast<const A &>(*this) == static_cast<const A &>(rhs);
}
///////////////////////////////////////////////////////
// class with members that refer to each other
// this is an example of a class that, as written, cannot
// be serialized with this system. The problem is that the
// serialization of the first member - j1 , provokes serialization
// of those objects which it points to either directly or indirectly.
// When those objects are subsequently serialized, it is discovered
// that have already been serialized through pointers. This is
// detected by the system and an exception - pointer_conflict -
// is thrown. Permiting this to go undetected would result in the
// creation of multiple equal objects rather than the original
// structure.
class K
{
J j1;
J j2;
J j3;
friend class boost::serialization::access;
template<class Archive>
void serialize(
Archive &ar,
const unsigned int /* file_version */
){
ar & BOOST_SERIALIZATION_NVP(j1);
ar & BOOST_SERIALIZATION_NVP(j2);
ar & BOOST_SERIALIZATION_NVP(j3);
}
public:
bool operator==(const K &rhs) const;
K();
};
K::K()
: j1(&j2), j2(&j3), j3(&j1)
{
}
bool K::operator==(const K &rhs) const
{
return
j1.j == & j2
&& j2.j == & j3
&& j3.j == & j1
&& j1 == rhs.j1
&& j2 == rhs.j2
&& j3 == rhs.j3
;
}
int test_main( int /* argc */, char* /* argv */[] )
{
const char * testfile = boost::archive::tmpnam(NULL);
BOOST_REQUIRE(NULL != testfile);
K k;
boost::archive::archive_exception exception(
boost::archive::archive_exception::no_exception
);
{
test_ostream os(testfile, TEST_STREAM_FLAGS);
test_oarchive oa(os);
BOOST_TRY {
oa << BOOST_SERIALIZATION_NVP(k);
}
BOOST_CATCH (boost::archive::archive_exception ae){
exception = ae;
}
BOOST_CATCH_END
BOOST_CHECK(
exception.code == boost::archive::archive_exception::pointer_conflict
);
}
// if exception wasn't invoked
if(exception.code == boost::archive::archive_exception::no_exception){
// try to read the archive
test_istream is(testfile, TEST_STREAM_FLAGS);
test_iarchive ia(is);
exception = boost::archive::archive_exception(
boost::archive::archive_exception::no_exception
);
BOOST_TRY {
ia >> BOOST_SERIALIZATION_NVP(k);
}
BOOST_CATCH (boost::archive::archive_exception ae){
exception = ae;
}
BOOST_CATCH_END
BOOST_CHECK(
exception.code == boost::archive::archive_exception::pointer_conflict
);
}
std::remove(testfile);
return EXIT_SUCCESS;
}
// EOF
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
]
| [
[
[
1,
153
]
]
]
|
973bcc9a5fe129e9d3419500340992df80ed2122 | d94c6cce730a771c18a6d84c7991464129ed3556 | /safeFatPrinter/branch/src/net_agent.cpp | 9c550c0c34b243339fc0f1adb2022634a2f96a32 | []
| no_license | S1aNT/cupsfilter | 09afbcedb4f011744e670fae74d71fce4cebdd25 | 26ecc1e76eefecde2b00173dff9f91ebd92fb349 | refs/heads/master | 2021-01-02T09:26:27.015991 | 2011-03-15T06:43:47 | 2011-03-15T06:43:47 | 32,496,994 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,502 | cpp | #include "net_agent.h"
// format is: [/me|/cmd|/sql];:;command_type;:;uid;:;command
net_agent::net_agent(QObject *parent)
{
socket = new QTcpSocket(this);
connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()));
connect(socket, SIGNAL(connected()), this, SLOT(connected()));
}
void net_agent::do_connect(QString &host,int port,QString &sid)
{
qDebug() << "connecting to server " <<host <<port << sid;
client_sid=sid;
if (host.isEmpty()){
emit error_signal(HOSTNAME_EMPTY_ERR,QObject::trUtf8("Ошибка в файле конфигурации. Имя сервера не может быть пустым."));
}else if (port<1024 or port >65536){
emit error_signal (INVALID_PORT_RANGE_ERR,QObject::trUtf8("Ошибка в файле конфигурации. Порт %1 вне допустимого диапазона.").arg(port));
}else{
socket->connectToHost(host, port);
if( !socket->waitForConnected(5000) ){
emit error_signal(socket->error(), socket->errorString());
qDebug() << QObject::trUtf8("failed to connect %1 port %2").arg(host,port);
return;
}
}
}
void net_agent::send2Server(commands_t cmd,QString &body)
{
qDebug() << Q_FUNC_INFO << socket->state();
if (socket->state()==QAbstractSocket::ConnectedState){
QString message;
message =QString("/cmd;:;%1;:;%2;:;%3").arg(cmd,0,10).arg(client_sid).arg(body);
qDebug() << Q_FUNC_INFO << "Write to socket " << message;
socket->write(QString(message + "\n").toUtf8());
}
}
void net_agent::execQuery(QString &query)
{
/*
select documents.Stamp , documents.mb , documents.punkt ,documents.inv_number
documents.number_ex, documents.doc_des, documents.print_last_page_stamp,
documents.print_overside_stamp, users.FIO as executor_fio,users.phone, users.FIO pressman_id integer
*/
}
void net_agent::connected()
{
QString message =QString("/me;:;%1;:;%2").arg(REGISTER_CMD,0,10).arg(client_sid);
qDebug() << Q_FUNC_INFO << "write to socket" << message;
socket->write(QString(message + "\n").toUtf8());
}
void net_agent::readyRead()
{
while(socket->canReadLine()){
// Here's the line the of text the server sent use UTF-8
QString line = QString::fromUtf8(socket->readLine()).trimmed();
qDebug() << Q_FUNC_INFO <<"Read from socket" <<line;
if (!line.isEmpty()){
emit serverSay(line);
}
}
}
| [
"[email protected]"
]
| [
[
[
1,
69
]
]
]
|
b5fecae2a14644105f7f3b4640052ca42bb7c3e3 | cd787383f4b4ffad1c6a1d45899ed16a8d12a18a | /CBackupState.h | ddc1875c631a6ec31a6bc85194bdc981454f5712 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
]
| permissive | brianly/hobocopy | f6d6277203422d0a757459bafa4856e47dab118d | 0450f1551a4df300829723048db0924b69ec7d96 | refs/heads/master | 2020-12-25T13:08:22.457084 | 2011-01-22T00:55:01 | 2011-01-22T00:55:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,836 | h | /*
Copyright (c) 2006 Wangdera Corporation ([email protected])
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include "CComException.h"
#include "OutputWriter.h"
class CBackupState
{
private:
bool _hasLastFullBackup;
bool _hasLastIncrementalBackup;
SYSTEMTIME _lastFullBackup;
SYSTEMTIME _lastIncrementalBackup;
void AppendAttribute(CComPtr<IXMLDOMDocument> document, CComPtr<IXMLDOMElement> parent,
LPCTSTR name, LPCTSTR value)
{
CString message;
message.AppendFormat(TEXT("Creating attribute %s"), name);
OutputWriter::WriteLine(message);
CComPtr<IXMLDOMAttribute> pAttribute;
CHECK_HRESULT(document->createAttribute(CComBSTR(name), &pAttribute));
OutputWriter::WriteLine(TEXT("Setting value of attribute."));
CHECK_HRESULT(pAttribute->put_text(CComBSTR(value)));
OutputWriter::WriteLine(TEXT("Retrieving attributes from parent element."));
CComPtr<IXMLDOMNamedNodeMap> pAttributes;
CHECK_HRESULT(parent->get_attributes(&pAttributes));
OutputWriter::WriteLine(TEXT("Adding attribute to parent."));
CComPtr<IXMLDOMNode> pThrowawayNode;
CHECK_HRESULT(pAttributes->setNamedItem(pAttribute, &pThrowawayNode));
}
bool SelectDateTimeValue(CComPtr<IXMLDOMDocument> document,
LPCTSTR xpath, LPSYSTEMTIME pTime)
{
CString message(TEXT("Selecting node for xpath "));
message.Append(xpath);
OutputWriter::WriteLine(message);
CComPtr<IXMLDOMNode> pNode;
HRESULT hr = document->selectSingleNode(CComBSTR(xpath), &pNode);
if (hr == S_FALSE)
{
OutputWriter::WriteLine(TEXT("Unable to find matching node."));
return FALSE;
}
else
{
// Cheap way of throwing an exception with the details filled in
CHECK_HRESULT(hr);
}
OutputWriter::WriteLine(TEXT("Retrieving text value of node"));
CComBSTR bstrLastFullBackup;
CHECK_HRESULT(pNode->get_text(&bstrLastFullBackup));
CString lastFullBackup(bstrLastFullBackup);
Utilities::ParseDateTime(lastFullBackup, TEXT("T"), pTime);
CString message2(TEXT("Time value was: "));
CString dateTime;
Utilities::FormatDateTime(pTime, TEXT(" "), false, dateTime);
message2.Append(dateTime);
OutputWriter::WriteLine(message2);
return true;
}
public:
CBackupState::CBackupState(void)
{
_hasLastFullBackup = false;
_hasLastIncrementalBackup = false;
}
LPSYSTEMTIME get_LastFullBackupTime()
{
if (_hasLastFullBackup)
{
return &_lastFullBackup;
}
else
{
return NULL;
}
}
void set_LastFullBackupTime(LPSYSTEMTIME value)
{
_hasLastFullBackup = true;
_lastFullBackup = *value;
}
LPSYSTEMTIME get_LastIncrementalBackupTime()
{
if (_hasLastIncrementalBackup)
{
return &_lastIncrementalBackup;
}
else
{
return NULL;
}
}
void set_LastIncrementalBackupTime(LPSYSTEMTIME value)
{
_hasLastIncrementalBackup = true;
_lastIncrementalBackup = *value;
}
void Load(LPCTSTR path)
{
_hasLastFullBackup = false;
_hasLastIncrementalBackup = false;
OutputWriter::WriteLine(TEXT("Creating DOM document object."));
CComPtr<IXMLDOMDocument> stateDocument;
CHECK_HRESULT(stateDocument.CoCreateInstance(__uuidof(DOMDocument30)));
CString message;
message.AppendFormat(TEXT("Loading state file from %s."), path);
OutputWriter::WriteLine(message);
OutputWriter::WriteLine(TEXT("Turning off validation"));
CHECK_HRESULT(stateDocument->put_validateOnParse(VARIANT_FALSE));
VARIANT_BOOL isSuccessful;
HRESULT hr = stateDocument->load(CComVariant(path), &isSuccessful);
if (FAILED(hr))
{
// A cheap way of throwing an exception with the details filled in
CHECK_HRESULT(hr);
}
else if (hr == S_FALSE || isSuccessful == VARIANT_FALSE)
{
CComPtr<IXMLDOMParseError> pError;
CHECK_HRESULT(stateDocument->get_parseError(&pError));
CComBSTR bstrReason;
CHECK_HRESULT(pError->get_reason(&bstrReason));
CString reason(bstrReason);
CString message;
message.AppendFormat(TEXT("Failed to load state file from %s. Reason: %s."), path, (LPCTSTR) reason);
throw new CHoboCopyException(message);
}
_hasLastFullBackup = SelectDateTimeValue(stateDocument, TEXT("/hoboCopyState/@lastFullBackup"), &_lastFullBackup);
if (_hasLastFullBackup)
{
CString message;
CString dateTime;
Utilities::FormatDateTime(&_lastFullBackup, TEXT(" "), false, dateTime);
message.AppendFormat(TEXT("Last full backup time read as %s"), dateTime);
OutputWriter::WriteLine(message);
}
else
{
OutputWriter::WriteLine(TEXT("Backup file did not have last full backup time recorded."));
}
_hasLastIncrementalBackup = SelectDateTimeValue(stateDocument, TEXT("/hoboCopyState/@lastIncrementalBackup"), &_lastIncrementalBackup);
if (_hasLastIncrementalBackup)
{
CString message;
CString dateTime;
Utilities::FormatDateTime(&_lastIncrementalBackup, TEXT(" "), false, dateTime);
message.AppendFormat(TEXT("Last incremental backup time read as %s"), dateTime);
OutputWriter::WriteLine(message);
}
else
{
OutputWriter::WriteLine(TEXT("Backup file did not have last incremental backup time recorded."));
}
}
void Save(LPCTSTR path, BSTR backupDocument)
{
if (!_hasLastFullBackup)
{
throw new CHoboCopyException(TEXT("Could not locate last full backup time."));
}
CString message;
message.AppendFormat(TEXT("Saving backup document to state file %s"), path);
OutputWriter::WriteLine(message, VERBOSITY_THRESHOLD_NORMAL);
OutputWriter::WriteLine(TEXT("Backup document:"));
OutputWriter::WriteLine(backupDocument);
OutputWriter::WriteLine(TEXT("Creating DOM document object."));
CComPtr<IXMLDOMDocument> backupDocumentDom;
//IXMLDOMDocument* backupDocumentDom;
//CHECK_HRESULT(::CoCreateInstance(CLSID_DOMDocument30, NULL, CLSCTX_INPROC, IID_IXMLDOMDocument, (LPVOID*) &backupDocumentDom)
CHECK_HRESULT(backupDocumentDom.CoCreateInstance(__uuidof(DOMDocument30)));
OutputWriter::WriteLine(TEXT("Turning off validation"));
CHECK_HRESULT(backupDocumentDom->put_validateOnParse(VARIANT_FALSE));
OutputWriter::WriteLine(TEXT("Loading backup document into DOM."));
VARIANT_BOOL worked;
HRESULT hr = backupDocumentDom->loadXML(backupDocument, &worked);
if (FAILED(hr))
{
CString message;
message.Format(TEXT("loadXML failed with HRESULT 0x%x"), hr);
throw new CHoboCopyException(message);
}
else if (hr == S_FALSE)
{
CComPtr<IXMLDOMParseError> parseError;
OutputWriter::WriteLine(TEXT("Retrieving parse error"));
CHECK_HRESULT(backupDocumentDom->get_parseError(&parseError));
CComBSTR bstrReason;
OutputWriter::WriteLine(TEXT("Retrieving reason"));
CHECK_HRESULT(parseError->get_reason(&bstrReason));
CString message;
message.Format(TEXT("loadXML failed to parse: %s"), bstrReason);
throw new CHoboCopyException(message);
}
if (worked == VARIANT_FALSE)
{
throw new CHoboCopyException(TEXT("IXMLDOMDocument::loadXML() failed"));
}
OutputWriter::WriteLine(TEXT("Creating state element."));
CComPtr<IXMLDOMElement> pStateElement;
CHECK_HRESULT(backupDocumentDom->createElement(CComBSTR(TEXT("hoboCopyState")),
&pStateElement));
if (_hasLastFullBackup)
{
OutputWriter::WriteLine(TEXT("Creating lastFullBackup attribute"));
CString dateTime;
Utilities::FormatDateTime(&_lastFullBackup, TEXT("T"), false, dateTime);
AppendAttribute(backupDocumentDom, pStateElement, TEXT("lastFullBackup"), dateTime);
}
else
{
OutputWriter::WriteLine(TEXT("No last full backup time was present."));
}
if (_hasLastIncrementalBackup)
{
OutputWriter::WriteLine(TEXT("Creating lastIncrementalBackup attribute"));
CString dateTime;
Utilities::FormatDateTime(&_lastIncrementalBackup, TEXT("T"), false, dateTime);
AppendAttribute(backupDocumentDom, pStateElement, TEXT("lastIncrementalBackup"), dateTime);
}
else
{
OutputWriter::WriteLine(TEXT("No last incremental backup time was present."));
}
OutputWriter::WriteLine(TEXT("Retrieving reference to backup document element."));
CComPtr<IXMLDOMElement> pBackupDocumentElement;
CHECK_HRESULT(backupDocumentDom->get_documentElement(&pBackupDocumentElement));
CComPtr<IXMLDOMNode> pThrowawayNode;
OutputWriter::WriteLine(TEXT("Removing backup document element."));
CHECK_HRESULT(backupDocumentDom->removeChild(pBackupDocumentElement, &pThrowawayNode));
pThrowawayNode.Release();
OutputWriter::WriteLine(TEXT("Adding backup document element as child of state element."));
CHECK_HRESULT(pStateElement->appendChild(pBackupDocumentElement, &pThrowawayNode));
pThrowawayNode.Release();
OutputWriter::WriteLine(TEXT("Adding state element as document element."));
CHECK_HRESULT(backupDocumentDom->appendChild(pStateElement, &pThrowawayNode));
pThrowawayNode.Release();
OutputWriter::WriteLine(TEXT("Saving backup document."));
CHECK_HRESULT(backupDocumentDom->save(CComVariant(path)));
OutputWriter::WriteLine(TEXT("Successfully wrote state file"), VERBOSITY_THRESHOLD_NORMAL);
}
}; | [
"[email protected]"
]
| [
[
[
1,
309
]
]
]
|
8ada3cdcf2ebca131c78b7747e228c69c2007ee5 | 91802b64e63029acba16947be3ee33c3a8f67980 | /Enregistrement.cpp | 0466b6fa5795a2deb984b85afdf1d25c42431675 | []
| no_license | clementdubois/SIMUL | 7b5671dfe0a02f6a499bb6f1393cd6acf04fc66f | 547bc206f3dda3005239384a48a39a260a838b7c | refs/heads/master | 2021-03-12T23:44:10.160625 | 2011-12-03T14:51:43 | 2011-12-03T14:51:43 | 2,783,409 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 543 | cpp | #include "Enregistrement.h"
#include <string.h>
#include <iostream>
using namespace std;
void Enregistrement::afficher(ostream &out) const{
//On afffiche l'enregistrement
out << m_a << "::" << m_b;
}
ostream& operator<<(ostream& out, Enregistrement const& enregistrement){
enregistrement.afficher(out);
return out;
}
Enregistrement::Enregistrement(){
m_a = 0;
strcpy(m_b, "");
}
Enregistrement::Enregistrement(int a, char* b){
m_a = a;
strcpy(m_b, b);
}
//Destructor
Enregistrement::~Enregistrement(){
}
| [
"[email protected]"
]
| [
[
[
1,
29
]
]
]
|
6bb120a3e6e97e4506e61eaab78d9a77c790e376 | a802460dc0bad0ddb19dca16913edd8df7e5930d | /boost/include/boost/version.hpp | ef07cdc694d4eeab7d619e021c9168c9a714389d | []
| no_license | tangyin025/llgen | e24ffddc8e8fb85e2e7570239b8e68514832e29f | bd3e7eba3e02191d526ecaf03ccfbd77d21c11f3 | refs/heads/master | 2023-03-19T06:54:28.578812 | 2011-02-01T09:34:57 | 2011-02-01T09:34:57 | 127,590,866 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,159 | hpp | // Boost version.hpp configuration header file ------------------------------//
// (C) Copyright John maddock 1999. 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/config for documentation
#ifndef BOOST_VERSION_HPP
#define BOOST_VERSION_HPP
//
// Caution, this is the only boost header that is guarenteed
// to change with every boost release, including this header
// will cause a recompile every time a new boost version is
// released.
//
// BOOST_VERSION % 100 is the patch level
// BOOST_VERSION / 100 % 1000 is the minor version
// BOOST_VERSION / 100000 is the major version
#define BOOST_VERSION 104300
//
// BOOST_LIB_VERSION must be defined to be the same as BOOST_VERSION
// but as a *string* in the form "x_y[_z]" where x is the major version
// number, y is the minor version number, and z is the patch level if not 0.
// This is used by <config/auto_link.hpp> to select which library version to link to.
#define BOOST_LIB_VERSION "1_43"
#endif
| [
"tang@b4afd296-5ef5-d945-9884-b277f1a201ea"
]
| [
[
[
1,
35
]
]
]
|
32cde41553eb589b730cb85b6405bfdc6a0f5d4e | a30b091525dc3f07cd7e12c80b8d168a0ee4f808 | /EngineAll/Graphics Devices/SoftwareGraphicsDevice.h | 548218acd966bc16f9f819d0ff26c76877191961 | []
| no_license | ghsoftco/basecode14 | f50dc049b8f2f8d284fece4ee72f9d2f3f59a700 | 57de2a24c01cec6dc3312cbfe200f2b15d923419 | refs/heads/master | 2021-01-10T11:18:29.585561 | 2011-01-23T02:25:21 | 2011-01-23T02:25:21 | 47,255,927 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,900 | h | /*
SoftwareGraphicsDevice.h
Written by Matthew Fisher
a software instance of GraphicsDevice. Contains no new functionality over GraphicsDevice.
Doesn't support several things, like textures or lighting.
*/
#pragma once
class SoftwareGraphicsDevice : public GraphicsDevice
{
public:
SoftwareGraphicsDevice();
~SoftwareGraphicsDevice();
void FreeMemory();
void Init3D(WindowObjects &O, const GraphicsDeviceParameters &Parameters);
void ReSize(WindowObjects &O, AppInterface &App);
void ReSizeFullScreen(WindowObjects &O, AppInterface &App);
void StartRender(WindowObjects &O);
void FinishRender(WindowObjects &O, AppInterface &App);
void DrawStringFloat(const String &Text, float x, float y, RGBColor c);
void LoadViewport(Viewport &V)
{
}
void LoadMatrix(MatrixController &MC);
void RenderLineStrip(const Mesh &M);
void Render(const Mesh &M);
BaseTexture* CreateTexture(); //textures are not supported in software
void CaptureScreen(WindowManager &WM, Bitmap &B);
void SetWireframe();
void DisableWireframe();
void ToggleWireframe();
void ClearTexture(UINT Index);
void SetZState(ZState NewState);
void RenderSolidWireframe(BaseMesh *BM)
{
}
void LoadNewBmp(const Bitmap &_Bmp)
{
Bmp = _Bmp;
}
private:
bool _Wireframe;
Bitmap Bmp; //the rendering target
ZBuffer Z; //the depth buffer
BITMAPINFO Info; //information about the screen
HDC hDC; //the device context
HWND hWnd; //the window handle
Matrix4 Total,Viewport; //Total is the World*View*Perspective transform; Viewport is the NDC -> screen Matrix4
AliasRender PR; //the interface used for rendering primitives
};
| [
"zhaodongmpii@7e7f00ea-7cf8-66b5-cf80-f378872134d2"
]
| [
[
[
1,
66
]
]
]
|
77f5c84143bdc41c435487b79ffd2de02d5d5466 | ef23e388061a637f82b815d32f7af8cb60c5bb1f | /src/mame/includes/snowbros.h | 2f891e25a2b601b869bdf6c021670fbdc0c08fbe | []
| no_license | marcellodash/psmame | 76fd877a210d50d34f23e50d338e65a17deff066 | 09f52313bd3b06311b910ed67a0e7c70c2dd2535 | refs/heads/master | 2021-05-29T23:57:23.333706 | 2011-06-23T20:11:22 | 2011-06-23T20:11:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 397 | h | #include "emu.h"
class snowbros_state : public driver_device
{
public:
snowbros_state(running_machine &machine, const driver_device_config_base &config)
: driver_device(machine, config) { }
UINT16 *m_hyperpac_ram;
int m_sb3_music_is_playing;
int m_sb3_music;
UINT8 m_semicom_prot_offset;
UINT8 *m_spriteram;
UINT16 *m_bootleg_spriteram16;
size_t m_spriteram_size;
};
| [
"Mike@localhost"
]
| [
[
[
1,
17
]
]
]
|
9b631e0c6eff99bab6885880736d02343f94a6e4 | c5ecda551cefa7aaa54b787850b55a2d8fd12387 | /src/UILayer/FileHashKey.h | 2ec5e025a458d7342a733129253aeeec050694aa | []
| no_license | firespeed79/easymule | b2520bfc44977c4e0643064bbc7211c0ce30cf66 | 3f890fa7ed2526c782cfcfabb5aac08c1e70e033 | refs/heads/master | 2021-05-28T20:52:15.983758 | 2007-12-05T09:41:56 | 2007-12-05T09:41:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 345 | h | #pragma once
class CFileHashKey
{
public:
CFileHashKey(void);
~CFileHashKey(void);
CFileHashKey& operator=(const unsigned char acFileHash[16]);
bool operator<(const CFileHashKey& right) const;
BOOL operator==(const CFileHashKey& right) const;
protected:
enum {HASH_SIZE = 16};
unsigned char m_acFileHash[HASH_SIZE];
};
| [
"LanceFong@4a627187-453b-0410-a94d-992500ef832d"
]
| [
[
[
1,
16
]
]
]
|
01ab2a18cced4ba937aa4c21c7ff1e8adbe42f68 | 55c675d13726d1ce015f0193654593e3b6b0f269 | /WizardGeometrySheet.cpp | b8c298dcd7605421c57ba8cb576942c1b6b0c6c3 | []
| no_license | fourier/Geometry2d | c4e0e9eaa16375f675fddecaab01f75b9b99dbf0 | 2f84511e06ae012d6c9052796e70015d5f81acc6 | refs/heads/master | 2020-12-24T14:10:07.238982 | 2009-05-26T06:57:15 | 2009-05-26T06:57:15 | 12,709,941 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,612 | cpp | // WizardGeometrySheet.cpp : implementation file
//
#include "stdafx.h"
#include "Geometry2d.h"
#include ".\wizardgeometrysheet.h"
#include ".\Geometry2dView.h"
//class CGeometry2dView;
// CWizardGeometrySheet
IMPLEMENT_DYNAMIC(CWizardGeometrySheet, CExtResizablePropertySheet )
CWizardGeometrySheet::CWizardGeometrySheet(UINT nIDCaption, CWnd* pParentWnd, UINT iSelectPage)
:CExtResizablePropertySheet (nIDCaption, pParentWnd, iSelectPage)
{
}
CWizardGeometrySheet::CWizardGeometrySheet(LPCTSTR pszCaption, CWnd* pParentWnd, UINT iSelectPage)
:CExtResizablePropertySheet (pszCaption, pParentWnd, iSelectPage)
{
}
CWizardGeometrySheet::~CWizardGeometrySheet()
{
for ( int i = 0; i < GetPageCount(); i++ )
if ( GetPage(i) )
delete GetPage(i);
}
BEGIN_MESSAGE_MAP(CWizardGeometrySheet, CExtResizablePropertySheet )
END_MESSAGE_MAP()
// CWizardGeometrySheet message handlers
BOOL CWizardGeometrySheet::OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo)
{
switch(nID)
{
case ID_WIZFINISH:
{
GetView()->OnGeometryTriangulate();
}
case IDCANCEL:
GetView()->SetMode(CGeometry2dView::ENone);
DestroyWindow();
break;
case ID_WIZBACK:
case ID_WIZNEXT:
break;
default:
TRACE0("CWizardGeometrySheet::OnCmdMsg : Unknown case");
// ASSERT(FALSE);
break;
}
return CExtResizablePropertySheet ::OnCmdMsg(nID, nCode, pExtra, pHandlerInfo);
}
BOOL CWizardGeometrySheet::DestroyWindow()
{
m_pView->PostMessage(WM_FLUSHWIZARD);
return CExtResizablePropertySheet ::DestroyWindow();
}
| [
"[email protected]"
]
| [
[
[
1,
67
]
]
]
|
529373d26b47830ac1ad0434fd1dcc34f0fd210c | 677f7dc99f7c3f2c6aed68f41c50fd31f90c1a1f | /SolidSBCNetLib/SolidSBCPacketResultRequest.cpp | 6686e1cadf32635df6d639c6bc9f1be163465ad6 | []
| no_license | M0WA/SolidSBC | 0d743c71ec7c6f8cfe78bd201d0eb59c2a8fc419 | 3e9682e90a22650e12338785c368ed69a9cac18b | refs/heads/master | 2020-04-19T14:40:36.625222 | 2011-12-02T01:50:05 | 2011-12-02T01:50:05 | 168,250,374 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,108 | cpp | #include "StdAfx.h"
#include "SolidSBCPacketResultRequest.h"
CSolidSBCPacketResultRequest::CSolidSBCPacketResultRequest(const CString& strComputerName,const CString& strClientUUID)
: CSolidSBCPacket()
, m_sClientUUID(strClientUUID)
, m_sComputerName(strComputerName)
{
CString sPacketXml;
sPacketXml.Format (
_T("<ResultRequest>\n")
_T("\t<ClientUUID>\n")
_T("\t\t%s\n")
_T("\t</ClientUUID>\n")
_T("\t<ComputerName>\n")
_T("\t\t%s\n")
_T("\t</ComputerName>\n")
_T("</ResultRequest>")
, m_sClientUUID
, m_sComputerName
);
ParseXml(sPacketXml);
}
CSolidSBCPacketResultRequest::CSolidSBCPacketResultRequest(const PBYTE pPacket)
: CSolidSBCPacket(pPacket)
{
USES_CONVERSION;
std::string sClientUUID, sComputerName;
m_sClientUUID = A2T(GetNodeValue<std::string>(_T("ResultRequest/ClientUUID[1]") , sClientUUID ) ? sClientUUID.c_str() : "" );
m_sComputerName = A2T(GetNodeValue<std::string>(_T("ResultRequest/ComputerName[1]"), sComputerName ) ? sComputerName.c_str() : "" );
}
CSolidSBCPacketResultRequest::~CSolidSBCPacketResultRequest(void)
{
} | [
"admin@bd7e3521-35e9-406e-9279-390287f868d3"
]
| [
[
[
1,
37
]
]
]
|
7a2dde06d9c22769257a3f81ea6122f03a40c6da | fac8de123987842827a68da1b580f1361926ab67 | /inc/physics/Animation/Animation/Deform/Morphing/Simd/hkaSimdMorphingDeformer.h | a6487bea4611d6ec7c4972e62087e5a59a49d047 | []
| no_license | blockspacer/transporter-game | 23496e1651b3c19f6727712a5652f8e49c45c076 | 083ae2ee48fcab2c7d8a68670a71be4d09954428 | refs/heads/master | 2021-05-31T04:06:07.101459 | 2009-02-19T20:59:59 | 2009-02-19T20:59:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,787 | h | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
#ifndef HK_SIMD_MORPHING_DEFORMER_H
#define HK_SIMD_MORPHING_DEFORMER_H
#include <Animation/Animation/Deform/Morphing/hkaMorphingDeformer.h>
/// The derived reference counted class for a SIMD based implementation of weighted vertex deformation.
/// This deformer requires that the input buffers' deformable
/// members (pos, normals) be aligned as a hkVector4 (16byte aligned as it is 128bit)
/// and for faster operation make sure that the outputs are aligned as well.
/// N.B. It is important to note that these deformers are here to be used by Havok's demos but are not production quality.
/// It is assumed that deforming will be done most commonly by your graphics engine, usually in hardware on GPUs or VUs.
/// That hardware deformation is usually performed at the same time as per vertex lighting operations, so Havok cannot
/// provide optimized deformers for all such game specific usage.
class hkaSimdMorphingDeformer : public hkReferencedObject, public hkaMorphingDeformer
{
public:
/// Initializes to an unbound deformer
hkaSimdMorphingDeformer();
/// Bind the buffers
/// The output buffer should be preallocated.
/// Returns false if the deformer does not support the input or output buffer format.
/// The input and output buffers must be appropriately aligned (16 byte)
hkBool bind( const hkaVertexDeformerInput& input, const hkxVertexBuffer* inputBuffer1, const hkxVertexBuffer* inputBuffer2, hkxVertexBuffer* outputBuffer );
/// Interpolate the input buffers into the output buffer.
/// The deformer must first be bound and the output buffer locked before deforming.
virtual void deform ( hkReal delta );
private:
void deformAligned( hkReal delta );
void deformAlignedInput( hkReal delta );
struct hkaSimdBinding
{
HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_ANIM_RUNTIME, hkaSimdMorphingDeformer::hkaSimdBinding );
// Input buffer 1
const hkVector4* m_i1PosBase;
const hkVector4* m_i1NormBase;
const hkVector4* m_i1BinormBase;
const hkVector4* m_i1TangentBase;
hkUint8 m_i1Stride;
// Input Buffer 2
const hkVector4* m_i2PosBase;
const hkVector4* m_i2NormBase;
const hkVector4* m_i2BinormBase;
const hkVector4* m_i2TangentBase;
hkUint8 m_i2Stride;
// Output Buffer
hkReal* m_oPosBase;
hkReal* m_oNormBase;
hkReal* m_oBinormBase;
hkReal* m_oTangentBase;
hkUint8 m_oStride;
hkUint32 m_numVerts;
};
struct hkaSimdBinding m_binding;
hkBool m_outputAligned;
};
#endif // HK_SIMD_MORPHING_DEFORMER_H
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529)
*
* Confidential Information of Havok. (C) Copyright 1999-2008
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at
* www.havok.com/tryhavok
*
*/
| [
"uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4"
]
| [
[
[
1,
92
]
]
]
|
fce71139103697bfaccfd985749c446f1f56fd75 | 6c8c4728e608a4badd88de181910a294be56953a | /OgreAssetEditorModule/OgreMaterialProperties.h | 4dbe7311a0f71320364bfc5c10f6a1a9512c0c4d | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | caocao/naali | 29c544e121703221fe9c90b5c20b3480442875ef | 67c5aa85fa357f7aae9869215f840af4b0e58897 | refs/heads/master | 2021-01-21T00:25:27.447991 | 2010-03-22T15:04:19 | 2010-03-22T15:04:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,641 | h | // For conditions of distribution and use, see copyright notice in license.txt
/**
* @file OgreMaterialProperties.h
* @brief Dynamically created QProperties for OGRE material scripts.
*/
#ifndef incl_OgreAssetEditorModule_OgreMaterialProperties_h
#define incl_OgreAssetEditorModule_OgreMaterialProperties_h
#include <boost/shared_ptr.hpp>
#include <OgreTexture.h>
#include <OgreGpuProgram.h>
#include <QObject>
#include <QMap>
#include <QString>
namespace Foundation
{
class Framework;
class AssetInterface;
typedef boost::shared_ptr<AssetInterface> AssetPtr;
}
namespace OgreRenderer
{
class OgreMaterialResource;
}
namespace Naali
{
typedef QMap<QString, QVariant> PropertyMap;
typedef QMap<QString, QVariant> TypeValuePair;
typedef QMapIterator<QString, QVariant> PropertyMapIter;
class OgreMaterialProperties : public QObject
{
Q_OBJECT
public:
/// Constructor.
/// @param asset Asset pointer to the material binary data.
explicit OgreMaterialProperties(const QString &name, Foundation::AssetPtr asset);
/// Destructor.
~OgreMaterialProperties();
/// Convenience function returning map of property names, their type and values.
/// Provides easier access to the properties than iterating dynamic properties by hand.
/// @return Property map QMap[QString(name), QVariant[QMap[QString(type), QVariant(value)]]].
PropertyMap GetPropertyMap();
/// @return Does this material have valid properties.
bool HasProperties();
/// @return Material script as an OgreMaterialPtr.
Ogre::MaterialPtr ToOgreMaterial();
/// @return Material script as a string.
QString ToString();
/// Utility function for converting Ogre::GpuConstantType enum to type string.
/// @param type Ogre::GpuConstantType enum.
/// @return Type as string.
static QString GpuConstantTypeToString(const Ogre::GpuConstantType &type);
/// Utility function for converting Ogre::GpuConstantType enum to type string.
/// @param type Ogre::GpuConstantType enum.
/// @return Type as string.
static QString TextureTypeToString(const Ogre::TextureType &type);
private:
/// Creates the QProperties dynamically for this material.
/// @True if creation was succesful, false otherwise.
bool CreateProperties();
/// Material resource pointer.
OgreRenderer::OgreMaterialResource *material_;
};
}
#endif
| [
"jaakkoallander@5b2332b8-efa3-11de-8684-7d64432d61a3",
"Stinkfist0@5b2332b8-efa3-11de-8684-7d64432d61a3"
]
| [
[
[
1,
31
],
[
33,
84
]
],
[
[
32,
32
]
]
]
|
53855ff970a86516bd67dc5c671dcd23d753178e | 6c8c4728e608a4badd88de181910a294be56953a | /ProtocolUtilities/NetworkMessages/NetMessageManager.cpp | 7f5850c0d0de4f568154a8d3acbac4ac84dce068 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | caocao/naali | 29c544e121703221fe9c90b5c20b3480442875ef | 67c5aa85fa357f7aae9869215f840af4b0e58897 | refs/heads/master | 2021-01-21T00:25:27.447991 | 2010-03-22T15:04:19 | 2010-03-22T15:04:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,836 | cpp | // For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include <iomanip>
#include <iostream>
#include <sstream>
#include <vector>
#include <cstring>
#include <boost/timer.hpp>
#include "DebugOperatorNew.h"
#include "Poco/Net/NetException.h"
#include "Poco/Net/DatagramSocket.h" // To get htons etc.
#include "NetMessageManager.h"
#include "ZeroCode.h"
#include "RealXtend/RexProtocolMsgIDs.h"
#include "Profiler.h"
using namespace std;
//#define PROTOCOL_STRESS_TEST
namespace ProtocolUtilities
{
/* For reference, here's how an SLUDP packet frame looks like:
struct UDPMessagePacket
{
uint8_t flags;
uint32_t sequenceNumber;
uint8_t extraHeaderSize;
byte extraHeaderData[extraHeaderSize]; // Not currently parsed at all.
// Message body. (possibly zerocoded)
// Appended acks.
// The format for message body:
// u8/u16/u32 messageNumber; // Variable-length -encoded.
// Message content. // Serialized data, the format is described by the SLUDP message_template.msg
};
*/
/// This function skips the message header from the given data packet.
/// @param data A pointer to the message data.
/// @param numBytes The size of data, in bytes.
/// @param messageLength [out] The remaining length of the buffer is returned here, in bytes.
/// @return A pointer to the start of the message body, or 0 if the size of the body is 0 bytes or if the message was malformed.
static uint8_t *ComputeMessageBodyStartAddrAndLength(uint8_t *data, size_t numBytes, size_t *messageLength)
{
// Too small buffer, no body existing at all.
if (numBytes < 6)
{
if (messageLength)
*messageLength = 0;
return 0;
}
// There's a variable-sized extra header we need to skip. How many bytes is it?
const uint8_t extraHeaderSize = data[5];
if (messageLength)
{
*messageLength = numBytes - 6 - extraHeaderSize;
// If there's pending acks, remove them from message length
if (data[0] & NetFlagAck)
{
size_t acksize = 1 + data[numBytes-1] * 4;
// Malformed?
if (*messageLength < acksize)
{
*messageLength = 0;
return 0;
}
*messageLength -= acksize;
}
}
return data + 6 + extraHeaderSize;
}
/// Returns a list of appended acks from packet
/// @param data A pointer to the message data.
/// @param numBytes The size of data, in bytes.
static std::vector<uint32_t> GetAppendedAckList(uint8_t *data, size_t numBytes)
{
std::vector<uint32_t> acks;
if ((data[0] & NetFlagAck) && (numBytes > 6))
{
if (numBytes > 6)
{
size_t num_acks = data[numBytes-1];
acks.resize(num_acks);
int idx = numBytes - 1 - num_acks * 4;
if (idx < 6) return acks;
for (size_t i = 0; i < num_acks; ++i)
{
acks.push_back((uint32_t)ntohl(*(u_long*)&data[idx]));
}
}
}
return acks;
}
/// const version of above.
/*
static const uint8_t *ComputeMessageBodyStartAddrAndLength(const uint8_t *data, size_t numBytes, size_t *messageLength)
{
return ComputeMessageBodyStartAddrAndLength(const_cast<uint8_t *>(data), numBytes, messageLength);
}
*/
/// Reads the packet sequence number from the given byte stream that represents an SLUDP packet.
/// @param data Pointer to the start of the message data (to first byte of header).
/// @param numBytes The size of the message (including headers).
/// @return The message sequence number, or 0 to denote an error occurred.
static uint32_t ExtractNetworkMessageSequenceNumber(const uint8_t *data, size_t numBytes)
{
assert(data || numBytes == 0);
if (numBytes < 6)
return 0;
return (uint32_t)ntohl(*(u_long*)&data[1]);//((data[1] << 24) + (data[2] << 16) + (data[3] << 8) + data[4]);
}
const char *VariableTypeToStr(NetVariableType type)
{
const char *data[] = { "Invalid", "U8", "U16", "U32", "U64", "S8", "S16", "S32", "S64", "F32", "F64", "LLVector3", "LLVector3d", "LLVector4",
"LLQuaternion", "UUID", "BOOL", "IPADDR", "IPPORT", "Fixed", "Variable", "BufferByte", "Buffer2Bytes", "Buffer4Bytes" };
if (type < 0 || type >= NUMELEMS(data))
return data[0];
return data[type];
}
NetMessageManager::NetMessageManager(const char *messageListFilename)
:messageList(boost::shared_ptr<NetMessageList>(new NetMessageList(messageListFilename)))
,messageListener(0),
sequenceNumber(1), // Note here: We always start outbound communication with PacketID==1.
lastReceivedSequenceNumber(0)
#ifdef PROFILING
,sentDatagrams(65536)
,sentDatabytes(65536)
,receivedDatagrams(65536)
,receivedDatabytes(65536)
,resentPackets(65536)
,lostPackets(65536)
,duplicatesReceived(65536)
#endif
{
receivedSequenceNumbers.clear();
}
NetMessageManager::~NetMessageManager()
{
ClearMessagePoolMemory();
receivedSequenceNumbers.clear();
}
void NetMessageManager::DumpNetworkMessage(NetMsgID id, NetInMessage *msg)
{
const NetMessageInfo *info = msg->GetMessageInfo();
if (!info)
{
std::cout << "Packet with invalid ID received: 0x" << std::hex << id << "." << std::endl;
return;
}
size_t dataSize = msg->GetDataSize();
std::cout << "\"" << info->name << "\" length " << dataSize << " bytes:" << std::endl;
int prevBlock = msg->GetCurrentBlock();
while(msg->GetCurrentBlock() < msg->GetBlockCount())
{
int curBlock = msg->GetCurrentBlock();
const NetMessageBlock &block = info->blocks[curBlock];
size_t blockInstanceCount = msg->ReadCurrentBlockInstanceCount();
const NetMessageVariable &var = block.variables[msg->GetCurrentVariable()];
if (curBlock != prevBlock || (curBlock == 0 && prevBlock == 0))
std::cout << " Block \"" << block.name << "\":" << std::endl;
prevBlock = curBlock;
NetVariableType varType = msg->CheckNextVariableType();
size_t varSize = msg->ReadVariableSize();
const uint8_t* data = (const uint8_t*)msg->ReadBytesUnchecked(varSize);
msg->SkipToNextVariable(true);
stringstream varData;
bool bMalformed = false;
if (data && varSize > 0)
for(size_t k = 0; k < varSize && k < 15; ++k) // Print only first 15 bytes of data.
varData << hex << (int)data[k] << " ";
else
{
varData << "Size: " << varSize << " but packet was malformed!";
bMalformed = true;
}
std::cout << " Var \"" << var.name << "\"(" << VariableTypeToStr(varType)<< "):" << varData.str() << std::endl;
if(bMalformed) return;
}
}
const NetMessageInfo *NetMessageManager::GetMessageInfoByID(NetMsgID id) const
{
return messageList->GetMessageInfoByID(id);
}
void NetMessageManager::HandleInboundBytes(std::vector<uint8_t> &data)
{
const size_t numBytes = data.size();
#ifdef PROFILING
receivedDatagrams.InsertRecord(1.0);
receivedDatabytes.InsertRecord(numBytes);
#endif
if (!messageListener)
{
cout << "No UDP message listener set! Dropping incoming packet as unhandled:" << endl;
// DumpNetworkMessage(&data[0], numBytes);
return;
}
uint32_t seqNum = ExtractNetworkMessageSequenceNumber(&data[0], numBytes);
#ifdef PROFILING
if (receivedSequenceNumbers.size() > 0 && seqNum - lastReceivedSequenceNumber < 16)
{
for(int i = lastReceivedSequenceNumber+1; i < seqNum; ++i)
if (receivedSequenceNumbers.find(i) == receivedSequenceNumbers.end())
lostPackets.InsertRecord(1.0);
}
#endif
lastReceivedSequenceNumber = seqNum;
// Send ACK for reliable messages.
if ((data[0] & NetFlagReliable) != 0)
QueuePacketACK(seqNum);
// We need to do pruning of inbound duplicates, so add the sequence number to the set of received sequence numbers,
// and check if we've seen this packet before.
pair<set<uint32_t>::iterator, bool> ret = receivedSequenceNumbers.insert(seqNum);
if (ret.second == false)
{
#ifdef PROFILING
duplicatesReceived.InsertRecord(1.0);
#endif
return; // A message with this sequence number has already been given to the application for processing. Drop it this time.
}
// NetMsgID id = ExtractNetworkMessageNumber(&data[0], numBytes);
size_t messageLength = 0;
const uint8_t *message = ComputeMessageBodyStartAddrAndLength(&data[0], numBytes, &messageLength);
if (!message)
{
cout << "Malformed packet received, could not determine message size" << endl;
return;
}
std::vector<uint32_t> appended_acks = GetAppendedAckList(&data[0], numBytes);
try
{
NetInMessage msg(seqNum, &message[0], messageLength, (data[0] & NetFlagZeroCode) != 0);
const NetMessageInfo *messageInfo = messageList->GetMessageInfoByID(msg.GetMessageID());
if (!messageInfo)
{
cout << "Unknown message received with Message ID " << msg.GetMessageID() << "!" << endl;
return;
}
msg.SetMessageInfo(messageInfo);
// Process appended acks
if (appended_acks.size() > 0)
{
for(unsigned i = 0; i < appended_acks.size(); ++i)
ProcessPacketACK(appended_acks[i]);
}
// NetMessageManager handles all Acks and Pings. Those are not passed to the application.
switch(msg.GetMessageID())
{
case RexNetMsgPacketAck:
ProcessPacketACK(&msg);
break;
case RexNetMsgStartPingCheck:
SendCompletePingCheck(msg.ReadU8());
break;
default:
// Pass the message to the listener(s).
messageListener->OnNetworkMessageReceived(msg.GetMessageID(), &msg);
break;
}
}
catch (Exception &e)
{
cout << "Parsing inbound bytes to a network message failed: " << e.what() << endl;
return;
}
}
static void FlipBits(std::vector<uint8_t> &data, int numBitsToFlip)
{
while(numBitsToFlip-- > 0)
{
int idx = rand() % data.size();
uint8_t bit = 1 << (rand() % 8);
data[idx] ^= bit;
}
}
/// Polls the inbound socket until the message queue is empty. Also resends any timed out reliable messages.
void NetMessageManager::ProcessMessages()
{
PROFILE (NetMessageManager_ProcessMessages);
if (!connection)
return;
if (!ResendQueueIsEmpty())
ProcessResendQueue();
// Process network messages for max. 0.1 seconds, to prevent lack of rendering/mainloop execution during heavy processing
static const double MAX_PROCESS_TIME = 0.1;
boost::timer timer;
PROFILE(NetMessageManager_WhilePacketsAvailable);
while(connection->PacketsAvailable() && timer.elapsed() < MAX_PROCESS_TIME)
{
const int cMaxPayload = 2048;
std::vector<uint8_t> data(cMaxPayload, 0);
int numBytes = connection->ReceiveBytes(&data[0], cMaxPayload);
if (numBytes == 0)
break;
data.resize(numBytes);
#ifdef PROTOCOL_STRESS_TEST
const int numDuplications = 10;
const double bitErrorRate = 0.05;
for(int i = 0; i < numDuplications; ++i)
{
#endif
HandleInboundBytes(data);
#ifdef PROTOCOL_STRESS_TEST
FlipBits(data, (int)ceil(data.size() * bitErrorRate));
}
#endif
}
if (!connection->Open())
connection.reset();
// To keep memory footprint down and to defend against memory attacks, keep the list of seen sequence numbers to a fixed size.
const size_t cMaxSeqNumMemorySize = 300;
while(receivedSequenceNumbers.size() > cMaxSeqNumMemorySize)
receivedSequenceNumbers.erase(receivedSequenceNumbers.begin()); // We remove from the front to guarantee the smallest(oldest) are removed first.
// Acknowledge all the new accumulated packets that the server sent as reliable.
SendPendingACKs();
}
bool NetMessageManager::ConnectTo(const char *serverAddress, int port)
{
try
{
connection = boost::shared_ptr<NetworkConnection>(new NetworkConnection(serverAddress, port));
return true;
} catch(Poco::Net::NetException &e)
{
std::cout << "Failed to connect to " << serverAddress << ":" << port << ". Error: " << e.message() << std::endl;
return false;
}
}
void NetMessageManager::Disconnect()
{
connection->Close();
ClearMessagePoolMemory();
receivedSequenceNumbers.clear();
}
NetOutMessage *NetMessageManager::StartNewMessage(NetMsgID id)
{
// There should exist a message 'template' with the given ID in the message info list. If not,
// we can't start crafting a new message and must fail. See message_template.msg file for a list
// of all the protocol messages supported by the system.
const NetMessageInfo *info = messageList->GetMessageInfoByID(id);
if (!info)
return 0;
NetOutMessage *newMsg = 0;
// Find if we have an old message struct in the unused pool that we can use.
if (unusedMessagePool.size() > 0)
{
newMsg = unusedMessagePool.front();
unusedMessagePool.pop_front();
newMsg->ResetWriting();
}
else
newMsg = new NetOutMessage();
newMsg->SetMessageInfo(info);
newMsg->AddMessageHeader();
usedMessagePool.push_back(newMsg);
return newMsg;
}
void NetMessageManager::FinishMessage(NetOutMessage *message)
{
assert(message);
message->SetSequenceNumber(GetNewSequenceNumber());
std::vector<uint8_t> &data = message->GetData();
if (data.size() == 0)
{
unusedMessagePool.push_back(message);
return;
}
assert(data.size() >= message->BytesFilled());
data.resize(message->BytesFilled());
// Find and remove the given message from the usedMessagePool list, it has to be there.
#ifdef _DEBUG
const size_t usedMessagePoolSize = usedMessagePool.size();
#endif
std::list<NetOutMessage*>::iterator newEnd = std::remove(usedMessagePool.begin(), usedMessagePool.end(), message);
usedMessagePool.erase(newEnd, usedMessagePool.end());
#ifdef _DEBUG
assert(usedMessagePoolSize == usedMessagePool.size() + 1);
#endif
// Try to Zero-encode the message if that is desired. If encoding worsens the size, we'll send unencoded.
if (message->GetMessageInfo()->encoding == NetZeroEncoded)
{
size_t bodyLength = 0;
const uint8_t *bodyData = ComputeMessageBodyStartAddrAndLength(&data[0], message->BytesFilled(), &bodyLength);
assert(bodyLength < message->BytesFilled());
size_t headerLength = message->BytesFilled() - bodyLength;
size_t encodedBodyLength = CountZeroEncodedLength(bodyData, bodyLength);
// If the encoded message would take more space than the non-coded, just send non-coded.
if (headerLength + encodedBodyLength >= message->BytesFilled())
{
data[0] &= ~NetFlagZeroCode;
}
else // Send out zerocoded, it's actually compressed something.
{
data[0] |= NetFlagZeroCode;
std::vector<uint8_t> zeroCodedData;
zeroCodedData.resize(headerLength + encodedBodyLength, 0);
memcpy(&zeroCodedData[0], &data[0], headerLength);
ZeroEncode(&zeroCodedData[headerLength], encodedBodyLength, bodyData, bodyLength);
data = zeroCodedData;
}
}
SendProcessedMessage(message);
// Push reliable messages to queue to wait ACK from the server.
if (message->IsReliable())
AddMessageToResendQueue(message);
else
unusedMessagePool.push_back(message);
}
void NetMessageManager::SendProcessedMessage(NetOutMessage *msg)
{
assert(msg);
std::vector<uint8_t> &data = msg->GetData();
assert(data.size() > 0);
connection->SendBytes(&data[0], data.size());
#ifdef PROFILING
sentDatagrams.InsertRecord(1.0);
sentDatabytes.InsertRecord(data.size());
#endif
if (messageListener)
messageListener->OnNetworkMessageSent(msg);
}
void NetMessageManager::QueuePacketACK(uint32_t packetID)
{
pendingACKs.insert(packetID);
}
void NetMessageManager::ClearMessagePoolMemory()
{
for(std::list<NetOutMessage*>::iterator iter = unusedMessagePool.begin(); iter != unusedMessagePool.end(); ++iter)
delete *iter;
// We're supposed to free up all of our memory, but someone's using it!
assert(usedMessagePool.size() == 0 && "Warning! Unsafe teardown of NetMessageManager detected!");
for(std::list<NetOutMessage*>::iterator iter = usedMessagePool.begin(); iter != usedMessagePool.end(); ++iter)
delete *iter;
for(MessageResendList::iterator iter = messageResendQueue.begin(); iter != messageResendQueue.end(); ++iter)
delete iter->second;
unusedMessagePool.clear();
usedMessagePool.clear();
messageResendQueue.clear();
}
///\todo Have better delay method for pending ACKs, currently sends everything accumulated just over one frame
void NetMessageManager::SendPendingACKs()
{
PROFILE(NetMessageManager_SendPendingACKs);
// If we aren't even connected (or not connected anymore), clear any old pending ACKs and return.
if (!connection.get())
{
pendingACKs.clear();
return;
}
static const size_t max_acks_in_msg = 100;
while (pendingACKs.size() > 0)
{
size_t acks_to_send = pendingACKs.size();
if (acks_to_send > max_acks_in_msg)
acks_to_send = max_acks_in_msg;
NetOutMessage *m = StartNewMessage(RexNetMsgPacketAck);
assert(m);
m->SetVariableBlockCount(acks_to_send);
std::set<uint32_t>::iterator i = pendingACKs.begin();
size_t added_acks = 0;
while (added_acks < acks_to_send)
{
// Note! Horrible protocol design issue! The sequence numbers that both
// server and client use are sent in big endian, but in the ACK packets
// they need to be transferred in little endian. !! So, no conversion to
// big endian here.
m->AddU32(*i);
++added_acks;
++i;
}
FinishMessage(m);
pendingACKs.erase(pendingACKs.begin(), i);
}
}
void NetMessageManager::ProcessPacketACK(NetInMessage *msg)
{
size_t blockCount = msg->ReadCurrentBlockInstanceCount();
for(size_t i = 0; i < blockCount; ++i)
ProcessPacketACK(msg->ReadU32());
}
void NetMessageManager::ProcessPacketACK(uint32_t id)
{
//std::cout << "Received ACK for packet " << id << std::endl;
RemoveMessageFromResendQueue(id);
}
void NetMessageManager::SendCompletePingCheck(uint8_t pingID)
{
NetOutMessage *m = StartNewMessage(RexNetMsgCompletePingCheck);
assert(m);
m->AddU8(pingID);
FinishMessage(m);
}
/// A unary find predicate that looks for a NetOutMessage that has the given desired sequence number in a resendqueue container.
class MsgSeqNumMatchPred
{
public:
MsgSeqNumMatchPred(uint32_t seqNum_):seqNum(seqNum_) {}
bool operator()(const std::pair<time_t, NetOutMessage*> &elem) const { return elem.second && elem.second->GetSequenceNumber() == seqNum; }
private:
uint32_t seqNum;
};
void NetMessageManager::AddMessageToResendQueue(NetOutMessage *msg)
{
// Don't add this message to the queue, if it already exists in the queue, i.e. it has already been resent once due to a timeout.
MessageResendList::iterator it = std::find_if(messageResendQueue.begin(), messageResendQueue.end(), MsgSeqNumMatchPred(msg->GetSequenceNumber()));
if (it != messageResendQueue.end())
{
// If the sequence numbers matched but these are different message structs, add the message to unusedMessagePool, it's extraneous.
if (it->second != msg)
unusedMessagePool.push_back(msg);
return;
}
messageResendQueue.push_back(std::make_pair(time(0), msg));
}
void NetMessageManager::RemoveMessageFromResendQueue(uint32_t packetID)
{
MessageResendList::iterator it = std::find_if(messageResendQueue.begin(), messageResendQueue.end(), MsgSeqNumMatchPred(packetID));
if (it != messageResendQueue.end())
{
unusedMessagePool.push_back(it->second);
messageResendQueue.erase(it);
}
}
void NetMessageManager::ProcessResendQueue()
{
PROFILE(NetMessageManager_ProcessResendQueue);
const int cTimeoutSeconds = 5;
const time_t timeNow = time(0);
for(MessageResendList::iterator it = messageResendQueue.begin(); it != messageResendQueue.end(); ++it)
{
if (timeNow - it->first >= cTimeoutSeconds)
{
it->first = timeNow;
it->second->MarkResend();
SendProcessedMessage(it->second);
//std::cout << "Resending packet " << it->second->GetSequenceNumber() << std::endl;
#ifdef PROFILING
resentPackets.InsertRecord(1.0);
#endif
}
}
}
#ifndef RELEASE
void NetMessageManager::DebugSendHardcodedTestPacket()
{
const uint8_t data[] =
{ 0x40, 0x00, 0x00, 0x00, 0x01, 0x00, 0xff, 0xff, 0x00, 0x03, 0x37, 0x2d, 0x5e, 0x0d, 0xde, 0xc9, 0x50,
0xb7, 0x40, 0x2d, 0xa2, 0x23, 0xc1, 0xae, 0xe0, 0x7e, 0x35, 0xe6, 0x8e, 0x5b, 0x78, 0x42, 0xac, 0x6d,
0x11, 0x67, 0x47, 0xde, 0x91, 0xf3, 0x58, 0xa9, 0x65, 0x49, 0xb0, 0xf0 };
connection->SendBytes(data, NUMELEMS(data));
}
void NetMessageManager::DebugSendHardcodedRandomPacket(size_t numBytes)
{
if (numBytes == 0)
return;
std::vector<uint8_t> data(numBytes, 0);
for(size_t i = 0; i < numBytes; ++i)
data[i] = rand() & 0xFF;
connection->SendBytes(&data[0], numBytes);
}
#endif
}
| [
"jonnenau@5b2332b8-efa3-11de-8684-7d64432d61a3",
"jujjyl@5b2332b8-efa3-11de-8684-7d64432d61a3",
"jjj@5b2332b8-efa3-11de-8684-7d64432d61a3",
"jaakkoallander@5b2332b8-efa3-11de-8684-7d64432d61a3",
"loorni@5b2332b8-efa3-11de-8684-7d64432d61a3"
]
| [
[
[
1,
1
],
[
4,
8
],
[
10,
10
],
[
13,
22
],
[
25,
27
],
[
665,
665
],
[
668,
669
]
],
[
[
2,
3
],
[
9,
9
],
[
23,
24
],
[
141,
154
],
[
211,
216
],
[
218,
229
],
[
231,
231
],
[
233,
245
],
[
247,
256
],
[
258,
258
],
[
260,
271
],
[
273,
280
],
[
285,
285
],
[
304,
358
],
[
485,
485
],
[
488,
492
],
[
635,
637
],
[
642,
642
],
[
666,
667
]
],
[
[
11,
12
],
[
402,
403
],
[
427,
428
],
[
430,
430
],
[
435,
437
],
[
440,
442
],
[
471,
472
],
[
597,
597
],
[
600,
603
],
[
605,
605
],
[
615,
616
],
[
618,
618
]
],
[
[
28,
140
],
[
155,
210
],
[
217,
217
],
[
230,
230
],
[
232,
232
],
[
246,
246
],
[
257,
257
],
[
259,
259
],
[
272,
272
],
[
281,
284
],
[
286,
303
],
[
359,
401
],
[
404,
426
],
[
429,
429
],
[
431,
434
],
[
438,
439
],
[
443,
470
],
[
473,
484
],
[
486,
487
],
[
493,
596
],
[
598,
599
],
[
604,
604
],
[
606,
614
],
[
617,
617
],
[
619,
631
],
[
633,
633
],
[
638,
641
],
[
643,
664
]
],
[
[
632,
632
],
[
634,
634
]
]
]
|
cdfc12faddb8774783f6fc559e5b43aecbd6328a | 5fb9b06a4bf002fc851502717a020362b7d9d042 | /developertools/MapRenderer/src/SDLEvent.cpp | 68fd947248269c2415aa568174dd010e518db4c2 | []
| no_license | bravesoftdz/iris-svn | 8f30b28773cf55ecf8951b982370854536d78870 | c03438fcf59d9c788f6cb66b6cb9cf7235fbcbd4 | refs/heads/master | 2021-12-05T18:32:54.525624 | 2006-08-21T13:10:54 | 2006-08-21T13:10:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,282 | cpp | //
// File: SDLEvent.h
// Created by: Gustav Nylander - [email protected]
//
#include <iostream>
#include "SDLEvent.h"
#include "renderer/SDLScreen.h"
#include "renderer/Renderer.h"
//#include "renderer/Camera.h"
#include "Debug.h"
#include <math.h>
#include "Config.h"
#include "Game.h"
using namespace std;
extern SDLScreen *SDLscreen;
SDLEvent::SDLEvent()
{
lasttick = 0;
last_click = 0;
lastx = 0;
lasty = 0;
lastbutton = 0;
quit = 0;
clickdown_x = 0;
clickdown_y = 0;
dragging = false;
}
SDLEvent::~SDLEvent()
{
// TODO: put destructor code here
}
void
SDLEvent::PollEvent()
{
/* handle the events in the queue */
//SDL_WarpMouse( 320, 240 );
unsigned int currenttime = SDL_GetTicks();
if(last_click)
if((currenttime - last_click) >= CLICK_TIME) {
pGame.HandleClick(lastx, lasty, lastbutton, false);
// printf("Single Click!\n");
last_click = 0;
}
while (SDL_PollEvent(&event)) {
HandleEvent(event, currenttime);
}
HandleMovement();
}
void
SDLEvent::WaitEvent()
{
unsigned int currenttime = SDL_GetTicks();
while (!quit && SDL_WaitEvent(&event)) {
HandleEvent(event, currenttime);
}
}
void SDLEvent::HandleEvent(SDL_Event event, unsigned int currenttime)
{
switch (event.type) {
case SDL_ACTIVEEVENT:
/* Something's happend with our focus
* If we lost focus or we are iconified, we
* shouldn't draw the screen
*/
//if ( event.active.gain == 0 )
//isActive = false;
//else
//isActive = TRUE;
break;
case SDL_VIDEORESIZE:
/* handle resize event */
break;
case SDL_KEYDOWN:
/* handle key presses */
break;
case SDL_MOUSEMOTION:
/* handle mouse movements */
break;
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP:
case SDL_QUIT:
/* handle quit requests */
quit = true;
break;
default:
break;
}
}
/* function to handle key press events */
void SDLEvent::HandleKeyPress(SDL_keysym * keysym)
{
}
void SDLEvent::HandleMovement(void)
{
}
void SDLEvent::HandleMouseMotion(SDL_MouseMotionEvent * event)
{
}
| [
"sience@a725d9c3-d2eb-0310-b856-fa980ef11a19"
]
| [
[
[
1,
121
]
]
]
|
45c3619eab953149734af89e861c930513c0951b | 3dca0a6382ea348a8617be05e1bfa6f4ed70d77c | /include/PgeMath.h | 0078c63e7b14c91db875ff9eaa32d68c5da9f7fb | []
| no_license | David-Haim-zz/pharaoh-game-engine | 9c766916559f9c74667e981b9b3f03b43920bc4e | b71db3fd99ebad0ab40a0888360d560748f63131 | refs/heads/master | 2021-05-29T15:17:23.043407 | 2011-01-23T17:53:39 | 2011-01-23T17:53:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,892 | h |
/*! $Id$
* @file PgeMath.h
* @author Chad M. Draper
* @date May 7, 2008
* @brief Some useful mathematical routines and constants.
*
*/
#ifndef PGEMATH_H
#define PGEMATH_H
#include "PgeTypes.h"
#include <limits>
#include <math.h>
namespace PGE
{
class _PgeExport Math
{
public:
static const Real pi;
static const Real half_pi;
static const Real two_pi;
static const Real rad_2_deg;
static const Real deg_2_rad;
static const Real epsilon;
/** Compare Real values for equality */
static inline bool RealEqual( Real r1, Real r2 )
{
return ( static_cast< Real >( fabs( r1 - r2 ) ) <= epsilon );
}
/** Get the absolute value of a number */
static Real Abs( Real n );
/** Get the absolute value of a number */
static Int IAbs( Int n );
/** Get the sign of a number */
static Real Sign( Real n );
/** Get the sign of a number */
static Int ISign( Int n );
/** Get the floor of a number */
static Real Floor( Real n );
/** Get the floor of a number */
static Int IFloor( Int n );
/** Get the ceiling of a number */
static Real Ceil( Real n );
/** Get the ceiling of a number */
static Int ICeil( Int n );
/** Round a number */
static Real Round( Real n );
/** Round a number to a given decimal position */
static Real RoundTo( Real n, Int numDigits );
/** Linear interpolation between two numbers */
static Real Lerp( Real n1, Real n2, Real ratio );
/** Cosine interpolation using an ease in/out ratio
@param ratio Interpolation ratio
@param low Lower bounds of the range
@param high Upper bounds of the range
@param easeInOut Amount to ease in and out
*/
static Real InterpCosine( Real ratio, Real low, Real high, Real easeInOut );
/** Perform step interpolation, where the minimum value is
returned for ratios less than 1, and the maximum value is
returned for ratios >= 1.
@param ratio Interpolation ratio
@param low Lower bounds of the range
@param high Upper bounds of the range
*/
static Real InterpStep( Real ratio, Real low, Real high );
/** Perform cubic interpolation. Cubic interpolation requires
4 parameters: the value before the minimum, the minimum, the
maximum, and the value after the maximum.
*/
static Real InterpCubic( Real ratio, Real v0, Real v1, Real v2, Real v3 );
/** Perform quadratic interpolation */
static Real InterpQuadratic( Real v1, Real v2, Real v3, Real ratio );
/** Calculate the square root of a number */
static Real Sqrt( Real n );
/** Calculate the square of a number */
static Real Sqr( Real n );
/** Cube a number */
static Real Cube( Real n );
/** Swap two numbers */
template< typename T >
static void Swap( T& n1, T& n2 )
{
T temp = n1;
n1 = n2;
n2 = temp;
}
/** Cosine */
static Real Cos( Real n );
/** ArcCosine */
static Real ACos( Real n );
/** Sine */
static Real Sin( Real n );
/** ArcSine */
static Real ASin( Real n );
/** Tangent */
static Real Tan( Real n );
/** ArcTangent */
static Real ATan( Real n );
/** ArcTangent2 */
static Real ATan2( Real n, Real y );
/** Logarithm */
static Real Log( Real n );
/** Exponential */
static Real Exp( Real n );
/** Calculate n^y */
static Real Pow( Real n, Real y );
/** Take the minimum of two numbers */
static Real Min( Real n1, Real n2 );
/** Take the maximum of two numbers */
static Real Max( Real n1, Real n2 );
/** Take the minimum of two numbers */
static Int IMin( Int n1, Int n2 );
/** Take the maximum of two numbers */
static Int IMax( Int n1, Int n2 );
/** Select a random number within a range */
static Real RangeRandom( Real low, Real high );
/** Select a random number within a range */
static Int IRangeRandom( Int low, Int high );
/** Select a random number within +/- a value */
static Real SymmetricRandom( Real n );
/** Select a random number within +/- a value */
static Int ISymmetricRandom( Int n );
/** Select a random number between 0 and 1 (inclusive) */
static Real UnitRandom();
/** Clamp a value to a range */
static Real Clamp( Real val, Real low, Real high );
/** Clamp a value to a range */
static Int IClamp( Int val, Int low, Int high );
/** Calculate the modulus of two numbers */
static Real Mod( Real n1, Real n2 );
/** Calculate the modulus of a number within a range */
static Real ModRange( Real n, Real low, Real high );
/** Calculate the modulus of a number within a range (inclusive) */
static Real ModRangeInclusive( Real n, Real low, Real high );
/** Calculate the modulus of two numbers */
static Int IMod( Int n1, Int n2 );
/** Calculate the modulus of a number within a range */
static Int IModRange( Int n, Int low, Int high );
/** Calculate the modulus of a number within a range (inclusive) */
static Int IModRangeInclusive( Int n, Int low, Int high );
/** Convert a value from radians to degrees */
static Real RadiansToDegrees( Real angle );
/** Convert a value from degrees to radian */
static Real DegreesToRadians( Real angle );
/**
Reflect a value about a specfied pivot.
@remarks
The value is mirrored about the pivot so that the new value equals
the pivot plus the pivot minus the original value. There is no
additional bounds checking. For example, reflect( 3, 4 ) = 5,
reflect( 10, 3 ) = -4.
*/
static Int IReflect( int val, int pivot );
static Real Reflect( Real val, Real pivot );
/**
Keep a value within a range, by reflecting it about the boundaries.
@remarks
If the value is less than the minimum of the range, reflect about
the minimum. If the value is greater than the range maximum,
reflect about the maximum. If the value is within the range, do
nothing.
*/
static Int IReflectRange( Int val, Int minVal, Int maxVal );
static Real ReflectRange( Real val, Real minVal, Real maxVal );
/** Reflect a value the boundaries of a range, using a sine curve. This
will result in a smoother reflection than ReflectRange.
*/
static Real ReflectSine( Real val, Real minVal, Real maxVal );
/** Convert a base 10 integer value to a hexadecimal string */
static String Int2Hex( UInt32 intVal );
/** Convert an hexadecimal string to base 10 integer */
static UInt32 Hex2Int( String hexVal );
/** Calculate the sawtooth sine of an angle:
@param angle Angle in radians
*/
static Real SawtoothSin( Real angle );
/** Calculate the step sine of an angle:
@param angle Angle in radians
*/
static Real StepSin( Real angle );
/** Convert rectancular coordinates to polar coordinates */
static void RectToPolar( Real* ang, Real* dist, Int x, Int y, Int centerX, Int centerY, Real scaleX = 1.0, Real scaleY = 1.0 );
static void RectToPolar( Real* ang, Real* dist, Real x, Real y, Real centerX, Real centerY, Real scaleX = 1.0, Real scaleY = 1.0 );
/** Convert polar coordinates to rectangular coordinates */
static void PolarToRect( Real ang, Real dist, Int* x, Int* y, Int centerX, Int centerY );
static void PolarToRect( Real ang, Real dist, Real* x, Real* y, Real centerX, Real centerY );
/** Find the most significant bit of a number */
static UInt32 FindMSB( UInt32 val );
/** Test whether a number is a power of 2 */
static bool IsPowerOf2( UInt32 val );
/** Get the next value, after a given number, that is a power of 2 */
static UInt32 FindNextPowerOf2( UInt32 start );
}; // class Math
/** @class RandomString
Generates a random string of characters.
@remarks
By default, legal characters in the random string are alphanumeric,
upper and lowercase. If a custom set of characters are desired,
use the <code>SetLegalChars</code> method to set the string of
characters to select from. Then, use the <code>GetCustomString</code>
to get a random string using the custom characters.
@note
Only the default characters will be returned when using the static
method <code>GetRandomString</code>. To get a string using custom
characters, the class must be instantiated.
*/
class _PgeExport RandomString
{
private:
static const String DefaultChars;
String CustomChars;
public:
/** Constructor
@remarks
The class is instantiated, and the custom characters is set to
the default characters. Use <code>SetLegalChars</code> to set
a custom set of characters.
*/
RandomString();
/** Initialization constructor
@param legalChars String of characters to use for a custom random string
*/
RandomString( const String& legalChars );
/** Set the custom set of characters */
void SetLegalChars( const String& legalChars );
/** Get a random string of characters using the custom characters
@param length Length of the returned string
*/
String GetCustomString( size_t length ) const;
/** Get a random string of characters using the default characters
@param length Length of the returned string
*/
static String GetRandomString( size_t length );
};
} // namespace PGE
#endif // PGEMATH_H
| [
"pharaohgameengine@555db735-7c4c-0410-acd0-0358cc0c1ac3"
]
| [
[
[
1,
279
]
]
]
|
cb2e221d890ba0f7149a22e6f3ff9172f1ddd6b1 | 8bdca3c7a80b5e92000f5a49af50c3565df210bf | /MarioBros/MarioBros/Sign.h | 4ffba2fd174e6f8438d54b40ec6b27df4636ff1d | []
| no_license | NguyenMinhTri/mario-directx-laptringgame2d | d8e5bffd78ea321a0d51980ea4e72675390ce0c1 | 28becda2fbfb13a8c04358a50ce2f1f7b23db247 | refs/heads/master | 2021-01-10T15:52:48.275384 | 2011-11-29T03:34:06 | 2011-11-29T03:34:06 | 44,036,200 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 286 | h | #pragma once
#include "Animation.h"
#include "Sprite.h"
#include "Object.h"
#include <list>
using namespace std;
class Sign:public Object
{
public:
Sign();
Sign(float _x, float _y,float width,float height,int _ID);
void Save(fstream *fs);
void Load(fstream *fs);
}; | [
"[email protected]"
]
| [
[
[
1,
16
]
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.