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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7d3fea6763fbd1c0cbecc0fda4ff01494ac97142 | 74f42e5510324185af098e47bdb4891cd4a29470 | /FieldStripper.h | c4365fdbacce50671a1fc36e15614e8c00d412c8 | []
| no_license | SecondReality/FieldStripper | 9f8a2a7937474778f6702d673cbcf1bccf68c6e2 | 7b5b60f416216349b55fa9ed854abaa5996dc500 | refs/heads/master | 2016-09-05T21:09:07.904948 | 2011-07-24T16:39:55 | 2011-07-24T16:39:55 | 2,011,882 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 710 | h | // datamine, LIS
#ifndef FIELDSTRIPPER_H
#define FIELDSTRIPPER_H
#include <QString>
#include <QList>
#include <QObject>
#include <QPair>
#include "SearchFields.h"
// Produces a grid of records.
// Also emits a signal for each field found.
class FieldStripper : public QObject
{
Q_OBJECT
public:
FieldStripper();
typedef QPair<QString, int> FoundText; // Contains the found text, and the location it was found in the original document.
typedef QList<QList<FoundText> > StringTable;
void strip(const SearchFields& sf, const QString &searchText, StringTable& table);
signals:
void foundField(SearchField, int location);
};
#endif // FIELDSTRIPPER_H
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
24
],
[
26,
31
]
],
[
[
25,
25
]
]
]
|
9d0accd0db1220763e439f34293fb8aec2f9dcf4 | 5ac13fa1746046451f1989b5b8734f40d6445322 | /minimangalore/Nebula2/code/nebula2/src/tools/nresourcecompiler.cc | 3f705cbe7fdca02ecab4da0d68892c4449de2c83 | []
| no_license | moltenguy1/minimangalore | 9f2edf7901e7392490cc22486a7cf13c1790008d | 4d849672a6f25d8e441245d374b6bde4b59cbd48 | refs/heads/master | 2020-04-23T08:57:16.492734 | 2009-08-01T09:13:33 | 2009-08-01T09:13:33 | 35,933,330 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,537 | cc | //------------------------------------------------------------------------------
// nresourcecompiler.cc
// (C) 2003 RadonLabs GmbH
//------------------------------------------------------------------------------
#include "tools/nresourcecompiler.h"
#include "kernel/nfileserver2.h"
#include "scene/nshapenode.h"
#include "scene/nskinanimator.h"
#include "kernel/npersistserver.h"
#include "tools/nmeshbuilder.h"
#include "tools/nanimbuilder.h"
#include "tools/napplauncher.h"
//------------------------------------------------------------------------------
/**
*/
nResourceCompiler::nResourceCompiler() :
kernelServer(0),
refResourceServer("/sys/servers/resource"),
isOpen(false),
rootNode(0),
shapeNodeClass(0),
shaderNodeClass(0),
skinAnimatorClass(0),
binaryFlag(false),
dataFile(0)
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
nResourceCompiler::~nResourceCompiler()
{
if (this->isOpen)
{
this->Close();
}
}
//------------------------------------------------------------------------------
/**
*/
bool
nResourceCompiler::Open(nKernelServer* ks)
{
n_assert(!this->isOpen);
n_assert(0 != ks);
n_assert(0 == this->kernelServer);
n_assert(this->meshes.Empty());
n_assert(this->textures.Empty());
n_assert(this->anims.Empty());
n_assert(0 == this->rootNode);
n_assert(0 == this->dataFile);
// initialize Nebula runtime
this->kernelServer = ks;
// initialize proj assign
nFileServer2* fileServer = kernelServer->GetFileServer();
fileServer->SetAssign("proj", this->GetPath(ProjectDirectory));
// create resource root node
this->rootNode = kernelServer->New("nroot", "/rsrc");
// lookup Nebula classes
this->shaderNodeClass = kernelServer->FindClass("nabstractshadernode");
this->shapeNodeClass = kernelServer->FindClass("nshapenode");
this->skinAnimatorClass = kernelServer->FindClass("nskinanimator");
n_assert(this->shaderNodeClass);
n_assert(this->shapeNodeClass);
n_assert(this->skinAnimatorClass);
this->isOpen = true;
return true;
}
//------------------------------------------------------------------------------
/**
*/
void
nResourceCompiler::Close()
{
n_assert(this->isOpen);
n_assert(this->rootNode);
if (this->dataFile)
{
this->dataFile->Release();
this->dataFile = 0;
}
this->meshes.Clear();
this->textures.Clear();
this->anims.Clear();
this->rootNode->Release();
this->rootNode = 0;
this->kernelServer = 0;
this->isOpen = false;
}
//------------------------------------------------------------------------------
/**
*/
bool
nResourceCompiler::Compile(const nArray<nString>& objs)
{
n_assert(this->isOpen);
nFileServer2* fileServer = kernelServer->GetFileServer();
// open temporary data file
this->dataFilePath = this->GetPath(ScratchDirectory);
this->dataFilePath.Append("/nrb_data.tmp");
this->dataFile = fileServer->NewFileObject();
if (!this->dataFile->Open(this->dataFilePath.Get(), "wb"))
{
this->SetError("nResourceCompiler::Open(): could not open tmp file '%s'\n", this->dataFilePath.Get());
this->Close();
return false;
}
// step 1: load Nebula objects
n_printf("\n* LOADING OBJECTS:\n");
n_printf("==================\n");
if (!this->LoadObjects(objs))
{
return false;
}
// step 2: extract resource names from Nebula objects
this->ExtractResourceAttrs(this->rootNode);
// step 3: process meshes
n_printf("\n* PROCESSING MESHES:\n");
n_printf("====================\n");
if (!this->ProcessMeshes())
{
return false;
}
// step 4: process anims
n_printf("\n* PROCESSING ANIMS:\n");
n_printf("===================\n");
if (!this->ProcessAnims())
{
return false;
}
// step 5: process textures
n_printf("\n* PROCESSING TEXTURES:\n");
n_printf("======================\n");
if (!this->ProcessTextures())
{
return false;
}
// close temporary data file
this->dataFile->Close();
// step 6: save Nebula objects
if (!this->SaveObjectHierarchy())
{
this->SetError("Error: Failed to save Nebula2 object to %s.n2\n", this->GetPath(BaseFilename));
return false;
}
// step 7: save resource bundle
n_printf("\n* Creating resource file '%s.nrb'...\n\n", this->GetPath(BaseFilename));
if (!this->SaveResourceBundle())
{
this->SetError("Error: Failed to write resource bundle file to %s.nrb\n", this->GetPath(BaseFilename));
return false;
}
// delete tmp files
fileServer->DeleteFile(this->dataFilePath);
return true;
}
//------------------------------------------------------------------------------
/**
*/
int
nResourceCompiler::GetMeshDataSize() const
{
int size = 0;
int i;
for (i = 0; i < this->meshes.Size(); i++)
{
size += this->meshes[i].GetDataLength();
}
return size;
}
//------------------------------------------------------------------------------
/**
*/
int
nResourceCompiler::GetAnimDataSize() const
{
int size = 0;
int i;
for (i = 0; i < this->anims.Size(); i++)
{
size += this->anims[i].GetDataLength();
}
return size;
}
//------------------------------------------------------------------------------
/**
*/
int
nResourceCompiler::GetTextureDataSize() const
{
int size = 0;
int i;
for (i = 0; i < this->textures.Size(); i++)
{
size += this->textures[i].GetDataLength();
}
return size;
}
//------------------------------------------------------------------------------
/**
This loads all Nebula objects.
*/
bool
nResourceCompiler::LoadObjects(const nArray<nString>& objs)
{
n_assert(this->isOpen);
n_assert(this->kernelServer);
n_assert(this->rootNode);
kernelServer->PushCwd(this->rootNode);
int i;
int num = objs.Size();
for (i = 0; i < num; i++)
{
n_printf("-> loading '%s'\n", objs[i].Get());
if (0 == kernelServer->Load(objs[i].Get()))
{
this->SetError("ERROR: Failed to load object '%s'\n", objs[i].Get());
return false;
}
}
kernelServer->PopCwd();
return true;
}
//------------------------------------------------------------------------------
/**
Recursively extract resource attributes from Nebula2 object hierarchy.
*/
void
nResourceCompiler::ExtractResourceAttrs(nRoot* curNode)
{
// meshes
if (curNode->IsA(this->shapeNodeClass))
{
nShapeNode* shapeNode = (nShapeNode*)curNode;
ResEntry entry(nResource::Mesh, shapeNode->GetMesh().Get());
entry.SetFlags(shapeNode->GetMeshUsage());
if (!this->meshes.Find(entry))
{
this->meshes.Append(entry);
}
}
// textures
if (curNode->IsA(this->shaderNodeClass))
{
nAbstractShaderNode* shdNode = (nAbstractShaderNode*) curNode;
int num = shdNode->GetNumTextures();
int i;
for (i = 0; i < num; i++)
{
ResEntry entry(nResource::Texture, shdNode->GetTextureAt(i));
if (!this->textures.Find(entry))
{
this->textures.Append(entry);
}
}
}
// animations
if (curNode->IsA(this->skinAnimatorClass))
{
nSkinAnimator* skinAnimator = (nSkinAnimator*) curNode;
ResEntry entry(nResource::Animation, skinAnimator->GetAnim().Get());
if (!this->anims.Find(entry))
{
this->anims.Append(entry);
}
}
// recurse
nRoot* curChild;
for (curChild = curNode->GetHead(); curChild; curChild = curChild->GetSucc())
{
this->ExtractResourceAttrs(curChild);
}
}
//------------------------------------------------------------------------------
/**
Save the Nebula object hierarchy.
*/
bool
nResourceCompiler::SaveObjectHierarchy()
{
nPersistServer* persistServer = kernelServer->GetPersistServer();
if (this->GetBinaryFlag())
{
persistServer->SetSaverClass("nbinscriptserver");
}
else
{
persistServer->SetSaverClass("ntclserver");
}
return this->rootNode->SaveAs(this->GetPath(BaseFilename));
}
//------------------------------------------------------------------------------
/**
Load each mesh, append it as binary nvx2 file to the temporary
data file, and record its start offset and length.
FIXME: small meshes should be combined into optimally sized
meshes.
*/
bool
nResourceCompiler::ProcessMeshes()
{
n_assert(this->dataFile);
n_assert(this->kernelServer);
int i;
int num = this->meshes.Size();
for (i = 0; i < num; i++)
{
ResEntry& resEntry = this->meshes[i];
nMeshBuilder meshBuilder;
const char* name = resEntry.GetName();
n_assert(name);
n_printf("-> %s\n", name);
// load mesh
if (!meshBuilder.Load(kernelServer->GetFileServer(), name))
{
this->SetError("Error: Failed to load mesh '%s'\n", name);
return false;
}
// record start offset in temp data file
resEntry.SetDataOffset(this->dataFile->GetSize());
// append mesh data to temp data file
if (!meshBuilder.SaveNvx2(this->dataFile))
{
this->SetError("Error: Writing data of mesh '%s' failed!\n", resEntry.GetName());
return false;
}
// record length of mesh data
resEntry.SetDataLength(this->dataFile->GetSize() - resEntry.GetDataOffset());
}
return true;
}
//------------------------------------------------------------------------------
/**
Load each animation, and append it to the temporary data file.
*/
bool
nResourceCompiler::ProcessAnims()
{
n_assert(this->dataFile);
n_assert(this->kernelServer);
int i;
int num = this->anims.Size();
for (i = 0; i < num; i++)
{
ResEntry& resEntry = this->anims[i];
nAnimBuilder animBuilder;
const char* name = resEntry.GetName();
n_assert(name);
n_printf("-> %s\n", name);
// load anim
if (!animBuilder.Load(kernelServer->GetFileServer(), name))
{
this->SetError("Error: Failed to load anim '%s'\n", name);
return false;
}
// record start offset in temp data file
resEntry.SetDataOffset(this->dataFile->GetSize());
// append anim data to temp data file
if (!animBuilder.SaveNax2(this->dataFile))
{
this->SetError("Error: Writing data of animation '%s' failed!\n", resEntry.GetName());
return false;
}
// record length of anim data
resEntry.SetDataLength(this->dataFile->GetSize() - resEntry.GetDataOffset());
}
return true;
}
//------------------------------------------------------------------------------
/**
Append the texture file (assumed to be dds) to the data file and
record its start offset and length.
*/
bool
nResourceCompiler::ProcessTextures()
{
n_assert(this->kernelServer);
nFileServer2* fileServer = this->kernelServer->GetFileServer();
int i;
int num = this->textures.Size();
for (i = 0; i < num; i++)
{
ResEntry& resEntry = this->textures[i];
const char* name = resEntry.GetName();
n_assert(name);
n_printf("-> %s\n", name);
// record start offset in temp data file
resEntry.SetDataOffset(this->dataFile->GetSize());
// append image file to temp data file
nFile* srcFile = fileServer->NewFileObject();
if (srcFile->Open(name, "rb"))
{
this->dataFile->AppendFile(srcFile);
srcFile->Close();
}
else
{
this->SetError("Error: Failed to file '%s'!\n", name);
srcFile->Release();
return false;
}
srcFile->Release();
// record length of data
resEntry.SetDataLength(this->dataFile->GetSize() - resEntry.GetDataOffset());
}
return true;
}
//------------------------------------------------------------------------------
/**
Write a single resource entry to a file.
*/
bool
nResourceCompiler::WriteResEntry(nFile* file, const ResEntry& resEntry, int dataBlockOffset)
{
n_assert(file);
// write type
switch (resEntry.GetType())
{
case nResource::Mesh:
file->PutInt('MESH');
break;
case nResource::Animation:
file->PutInt('MANI'); // a memory-animation vs. streamed animation
break;
case nResource::Texture:
file->PutInt('TXTR');
break;
default:
n_error("nResourceCompiler::WriteResEntry(): Unsupported resource type!");
break;
}
// convert filename to resource identifier
nString resId = this->refResourceServer->GetResourceId(resEntry.GetName());
// write resource identifier
file->Write(resId.Get(), resId.Length());
// write data offset and data length
file->PutInt(resEntry.GetDataOffset() + dataBlockOffset);
file->PutInt(resEntry.GetDataLength());
file->PutInt(resEntry.GetFlags());
return true;
}
//------------------------------------------------------------------------------
/**
Write the resource bundle file consisting of header and data block.
*/
bool
nResourceCompiler::SaveResourceBundle()
{
n_assert(this->isOpen);
nFileServer2* fileServer = kernelServer->GetFileServer();
nFile* dstFile = fileServer->NewFileObject();
// open destination file
nString dstFileName = this->GetPath(BaseFilename);
dstFileName.Append(".nrb");
if (!dstFile->Open(dstFileName.Get(), "wb"))
{
dstFile->Release();
return false;
}
// write header
int numTocEntries = this->meshes.Size() + this->anims.Size() + this->textures.Size();
dstFile->PutInt('NRB0');
dstFile->PutInt(numTocEntries);
// compute offset of datablock (header + numTocEntries * sizeof(tocEntry))
int dataOffset = 2 * sizeof(int) + numTocEntries * (3 * sizeof(int) + 32);
// write toc entries
int i;
for (i = 0; i < this->meshes.Size(); i++)
{
this->WriteResEntry(dstFile, this->meshes[i], dataOffset);
}
for (i = 0; i < this->anims.Size(); i++)
{
this->WriteResEntry(dstFile, this->anims[i], dataOffset);
}
for (i = 0; i < this->textures.Size(); i++)
{
this->WriteResEntry(dstFile, this->textures[i], dataOffset);
}
// append the data block to the nrb file
bool success = this->dataFile->Open(this->dataFilePath, "rb");
n_assert(success);
dstFile->AppendFile(this->dataFile);
this->dataFile->Close();
// cleanup
dstFile->Close();
dstFile->Release();
return true;
}
| [
"BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c"
]
| [
[
[
1,
559
]
]
]
|
e83f1548986cf5025deaf99e3f9f607971ed834b | fbe2cbeb947664ba278ba30ce713810676a2c412 | /iptv_root/iptv_appsharing/include/ASModuleWin.h | 5c4c0943ddf737908e9131283a518dc27bbee43b | []
| no_license | abhipr1/multitv | 0b3b863bfb61b83c30053b15688b070d4149ca0b | 6a93bf9122ddbcc1971dead3ab3be8faea5e53d8 | refs/heads/master | 2020-12-24T15:13:44.511555 | 2009-06-04T17:11:02 | 2009-06-04T17:11:02 | 41,107,043 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,214 | h | ///////////////////////////////////////////////////////////////////////////////
#pragma once
#ifndef __ASMODULE__
#define __ASMODULE__
///////////////////////////////////////////////////////////////////////////////
#include "ASModuleDll.h"
#include "ASFlags.h"
#include "ASListener.h"
///////////////////////////////////////////////////////////////////////////////
#define AS_RECV_STRETCH 0x00000001
#define AS_RECV_STRETCH_PROPORTIONAL 0x00000002
#define AS_RECV_SCROLLBAR 0x00000100
#define ID_RECEIVE_CHILDWIN (1021)
///////////////////////////////////////////////////////////////////////////////
class ISockBuff;
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
ASMODULE_API_WIN bool Initialize( ISockBuff *pSockBuff, int flMode, long nMediaID,
CxAppSharingListener *pListener = NULL,
HWND p_hWnd = NULL, int p_BitDepth = 16,
RECT *p_Bounds = NULL, int p_RefreshTime = 1000,
int p_CaptureMode = AS_GDI );
ASMODULE_API_WIN bool End( void );
ASMODULE_API_WIN bool SetParent( HWND hWndParent );
ASMODULE_API_WIN bool SetWindowPos( int x, int y, int cx, int cy );
ASMODULE_API_WIN bool UpdateWindowPos( void );
ASMODULE_API_WIN bool SetReceiveStyle( long nStyle );
ASMODULE_API_WIN long GetReceiveStyle( void );
ASMODULE_API_WIN long SendKeyFrame( void );
ASMODULE_API_WIN long SetCaptureTimeWindow( unsigned long nmsTime );
// Mouse and Keyboard
// Receive
ASMODULE_API_WIN long EnableKM( bool flEnable );
ASMODULE_API_WIN long EnablePen( bool flEnable );
//Capture
ASMODULE_API_WIN long ProcessKM( char *psKM, unsigned long nSize );
ASMODULE_API_WIN long ResetKM( void );
ASMODULE_API_WIN long Send_CTRL_ALT_DEL( void );
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
#endif /* __ASMODULE__ */
| [
"heineck@c016ff2c-3db2-11de-a81c-fde7d73ceb89"
]
| [
[
[
1,
46
]
]
]
|
425fff2a83c0d38612cfe8c40f1d2e6e164935cc | f69b9ae8d4c17d3bed264cefc5a82a0d64046b1c | /src/evaluator/ChartParametersEditor.cxx | f8911ce0ca58b39c9bd5dae851b687084f905e86 | []
| no_license | lssgufeng/proteintracer | 611501cf8001ff9d4bf5e7aa645c24069cce675f | 055cc953d6bf62d17eb9435117f44b3f3d9b8f3f | refs/heads/master | 2016-08-09T22:20:40.978584 | 2009-06-07T22:08:14 | 2009-06-07T22:08:14 | 55,025,270 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,546 | cxx | /*==============================================================================
Copyright (c) 2009, André Homeyer
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
==============================================================================*/
#include <evaluator/ChartParametersEditor.h>
#include <FL/Fl_Button.H>
#include <FL/Fl_Return_Button.H>
#include <FL/fl_ask.H>
#include <gui/common.h>
static const int WINDOW_WIDTH = 400;
static const int WINDOW_HEIGHT = 500;
ChartParametersEditor::ChartParametersEditor(const PT::Analysis* analysis) :
analysis_(analysis),
Fl_Double_Window(WINDOW_WIDTH, WINDOW_HEIGHT, "Edit Chart Parameters")
{
static const int BIG_MARGIN = 15;
static const int BUTTON_HEIGHT = 25;
static const int BUTTON_WIDTH = 85;
static const int INPUT_HEIGHT = 25;
static const int LABEL_HEIGHT = 14;
static const int MEDIUM_MARGIN = 10;
static const int BUTTONS_HEIGHT = BUTTON_HEIGHT + MEDIUM_MARGIN * 2;
this->set_modal();
chartTypeChoice_ = new Fl_Choice(
this->x() + MEDIUM_MARGIN,
this->y() + BIG_MARGIN + LABEL_HEIGHT,
this->w() - 2 * MEDIUM_MARGIN,
INPUT_HEIGHT);
chartTypeChoice_->label("Chart Type");
chartTypeChoice_->align(FL_ALIGN_LEFT | FL_ALIGN_TOP);
chartTypeChoice_->callback(fltk_member_cb<ChartParametersEditor, &ChartParametersEditor::selectChartType>, this);
// fill chartTypeChoice_
{
Fl_Menu_Item* menuItems = new Fl_Menu_Item[CHART_TYPE_NAMES.size() + 1];
std::vector<std::string>::const_iterator it = CHART_TYPE_NAMES.begin();
std::vector<std::string>::const_iterator end = CHART_TYPE_NAMES.end();
for (int i = 0; it != end; ++i, ++it)
{
const std::string& name = *it;
menuItems[i].text = name.c_str();
menuItems[i].shortcut_ = 0;
menuItems[i].callback_ = 0;
menuItems[i].user_data_ = 0;
menuItems[i].flags = FL_MENU_VALUE;
menuItems[i].labeltype_ = FL_NORMAL_LABEL;
menuItems[i].labelfont_ = FL_HELVETICA;
menuItems[i].labelsize_ = 14;
menuItems[i].labelcolor_ = FL_BLACK;
}
// add closing item
menuItems[CHART_TYPE_NAMES.size()].text = 0;
chartTypeChoice_->menu(menuItems);
}
int pty = chartTypeChoice_->y() + chartTypeChoice_->h() + MEDIUM_MARGIN;
parameterTable_ = new ParameterTable(
chartTypeChoice_->x(),
pty,
chartTypeChoice_->w(),
this->y() + this->h() - pty - BUTTONS_HEIGHT);
this->resizable(parameterTable_);
Fl_Return_Button* okButton = new Fl_Return_Button(
parameterTable_->x() + parameterTable_->w() - MEDIUM_MARGIN - 2 * BUTTON_WIDTH,
this->y() + this->h() - BUTTONS_HEIGHT + MEDIUM_MARGIN,
BUTTON_WIDTH,
BUTTON_HEIGHT);
okButton->label("&OK");
okButton->callback(fltk_member_cb<ChartParametersEditor, &ChartParametersEditor::handleOkButtonClick>, this);
Fl_Button* cancelButton = new Fl_Button(
okButton->x() + okButton->w() + MEDIUM_MARGIN,
okButton->y(),
BUTTON_WIDTH,
BUTTON_HEIGHT);
cancelButton->label("&Cancel");
cancelButton->callback(fltk_member_cb<ChartParametersEditor, &ChartParametersEditor::handleCancelButtonClick>, this);
this->end();
}
void ChartParametersEditor::selectChartType()
{
ChartType chartTypeIndex = (ChartType) chartTypeChoice_->value();
std::auto_ptr<ChartParameters> chartParameters = ChartParameters::createParameters(chartTypeIndex, analysis_);
setChartParameters(chartParameters);
}
void ChartParametersEditor::setChartParameters(std::auto_ptr<ChartParameters> chartParameters)
{
assert(chartParameters.get() != 0);
parameters_ = chartParameters;
int chartType = parameters_->getChartType();
chartTypeChoice_->value(chartType);
parameterTable_->setParameterSet(parameters_.get());
}
void ChartParametersEditor::handleOkButtonClick()
{
std::string errorMessage = parameters_->validate();
if (errorMessage.size() > 0)
fl_message(errorMessage.c_str());
else
this->hide();
}
void ChartParametersEditor::handleCancelButtonClick()
{
parameters_.reset();
this->hide();
}
std::auto_ptr<ChartParameters> ChartParametersEditor::showEditor(
const PT::Analysis* analysis,
const ChartParameters* chartParameters)
{
assert(analysis != 0);
ChartParametersEditor chartParametersEditor(analysis);
if (chartParameters != 0)
{
std::auto_ptr<ChartParameters> newChartParamters(new ChartParameters(*chartParameters));
chartParametersEditor.setChartParameters(newChartParamters);
}
else
{
std::auto_ptr<ChartParameters> newChartParamters =
ChartParameters::createParameters(CHART_TYPE_SCATTERPLOT, analysis);
chartParametersEditor.setChartParameters(newChartParamters);
}
chartParametersEditor.show();
while (chartParametersEditor.shown())
Fl::wait();
return chartParametersEditor.parameters_;
}
| [
"andre.homeyer@localhost"
]
| [
[
[
1,
173
]
]
]
|
d39ee3ee85f1d61e4c72d3a78974301a92f5e76b | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/_Interface/WndGuildTabApp.h | fdc2a93930071914d1f82ab40164b3871f93ae4f | []
| 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,574 | h | #ifndef __WNDGUILD_TAB_APP__H
#define __WNDGUILD_TAB_APP__H
#include "guild.h"
extern CGuildMng g_GuildMng;
class CWndGuildPayConfirm : public CWndNeuz
{
public:
DWORD m_dwAppellation;
CWndGuildPayConfirm();
~CWndGuildPayConfirm();
virtual BOOL Initialize( CWndBase* pWndParent );
virtual BOOL OnChildNotify( UINT message, UINT nID, LRESULT* pLResult );
virtual void OnDraw( C2DRender* p2DRender );
virtual void OnInitialUpdate();
virtual BOOL OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase );
virtual void OnSize( UINT nType, int cx, int cy );
virtual void OnLButtonUp( UINT nFlags, CPoint point );
virtual void OnLButtonDown( UINT nFlags, CPoint point );
};
class CWndGuildTabApp : public CWndNeuz
{
public:
void UpdateData();
void EnableButton( BOOL bEnable );
CWndGuildTabApp();
~CWndGuildTabApp();
DWORD m_adwPower[MAX_GM_LEVEL];
CWndGuildPayConfirm* m_pWndGuildPayConfirm;
CWndStatic* m_pWndPenya[MAX_GM_LEVEL];
void SetData( DWORD dwPower[] );
void SetPenya( void );
virtual BOOL Initialize( CWndBase* pWndParent = NULL, DWORD nType = MB_OK );
virtual BOOL OnChildNotify( UINT message, UINT nID, LRESULT* pLResult );
virtual void OnDraw( C2DRender* p2DRender );
virtual void OnInitialUpdate();
virtual BOOL OnCommand( UINT nID, DWORD dwMessage, CWndBase* pWndBase );
virtual void OnSize( UINT nType, int cx, int cy );
virtual void OnLButtonUp( UINT nFlags, CPoint point );
virtual void OnLButtonDown( UINT nFlags, CPoint point );
};
#endif | [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
]
| [
[
[
1,
48
]
]
]
|
cd081237fc4ac01393445779312142d2d4de278c | 990e19b7ae3d9bd694ebeae175c50be589abc815 | /src/VRG3D.lib/include/VRG3D.H | f6f3b11d81aa8cb538e75d9cc953bd88bf006f37 | []
| no_license | shadoof/CW2 | 566b43cc2bdea2c86bd1ccd1e7b7e7cd85b8f4f5 | a3986cb28270a702402c197cdb16373bf74b9d03 | refs/heads/master | 2020-05-16T23:39:56.007788 | 2011-12-08T06:10:22 | 2011-12-08T06:10:22 | 2,389,647 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 664 | h | /**
* \author Daniel Keefe (dfk)
*
* \file VRG3D.H
*
*/
#ifndef VRG3D_H
#define VRG3D_H
// Include all of G3D
#include <G3D/G3DAll.h>
// Include all of the VRG3D library here
#include "ConfigMap.H"
#include "DisplayTile.H"
#include "Event.H"
#include "EventNet.H"
#include "G3DOperators.H"
#include "InputDevice.H"
#include "MouseToTracker.H"
#include "ProjectionVRCamera.H"
#include "SynchedSystem.H"
#include "VRApp.H"
#include "VRPNAnalogDevice.H"
#include "VRPNButtonDevice.H"
#include "VRPNTrackerDevice.H"
//using namespace VRG3D;
#include <iostream>
using namespace std;
#include "PlatformDefs.h"
#endif
| [
"[email protected]"
]
| [
[
[
1,
38
]
]
]
|
cce2c5f5e147e75e430da754398983e61fe4db1e | 5f616e16acb97ce895552f6f0e00ae53d3a5fc19 | /SimpleHashing/stdafx.cpp | 8ab5ede0d50758f84683410cae51780f1f6173a5 | []
| no_license | webstorage119/CryptoPP_Testing | bb56dfb457b1e838b904d54319c52a2e89b25c52 | de8843782aff9e5f53eb0b1d7248e0dbd608ffe9 | refs/heads/master | 2021-05-30T02:03:00.695362 | 2011-01-07T18:30:52 | 2011-01-07T18:30:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 300 | cpp | // stdafx.cpp : source file that includes just the standard includes
// SimpleHashing.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"none@none"
]
| [
[
[
1,
8
]
]
]
|
e7aaee0d3e84aa8749794ab931728739dc73e091 | c1a2953285f2a6ac7d903059b7ea6480a7e2228e | /deitel/ch10/Fig10_07_09/Increment.h | c593fad60b6aeaa21b88d4da5ff1da4aa61ffc3d | []
| no_license | tecmilenio/computacion2 | 728ac47299c1a4066b6140cebc9668bf1121053a | a1387e0f7f11c767574fcba608d94e5d61b7f36c | refs/heads/master | 2016-09-06T19:17:29.842053 | 2008-09-28T04:27:56 | 2008-09-28T04:27:56 | 50,540 | 4 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,580 | h | // Fig. 10.7: Increment.h
// Definition of class Increment.
#ifndef INCREMENT_H
#define INCREMENT_H
class Increment
{
public:
Increment( int c = 0, int i = 1 ); // default constructor
// function addIncrement definition
void addIncrement()
{
count += increment;
} // end function addIncrement
void print() const; // prints count and increment
private:
int count;
const int increment; // const data member
}; // end class Increment
#endif
/**************************************************************************
* (C) Copyright 1992-2008 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
**************************************************************************/
| [
"[email protected]"
]
| [
[
[
1,
38
]
]
]
|
023566ef6e75c8ff862e7d50c313498458655eda | 8be41f8425a39f7edc92efb3b73b6a8ca91150f3 | /MFCOpenGLTest/MyRect.cpp | 740126193d9bfe206eba0d98e0a1ce62c5c64aa6 | []
| no_license | SysMa/msq-summer-project | b497a061feef25cac1c892fe4dd19ebb30ae9a56 | 0ef171aa62ad584259913377eabded14f9f09e4b | refs/heads/master | 2021-01-23T09:28:34.696908 | 2011-09-16T06:39:52 | 2011-09-16T06:39:52 | 34,208,886 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,390 | cpp | // MyRect.cpp: implementation of the CMyRect class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "MFCOpenGLTest.h"
#include "MyRect.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CMyRect::CMyRect()
{
m_first = 0;
}
CMyRect::~CMyRect()
{
}
void CMyRect::Draw()
{
glLogicOp(GL_COPY);
glColor3f(color.r,color.g,color.b);
glLineWidth(this->Width);
glBegin(GL_LINES);
glVertex2f(xmin, ymin);
glVertex2f(xmin, ymax);
glVertex2f(xmin, ymin);
glVertex2f(xmax, ymin);
glVertex2f(xmin, ymax);
glVertex2f(xmax, ymax);
glVertex2f(xmax, ymin);
glVertex2f(xmax, ymax);
glEnd();
}
void CMyRect::DrawCurrentOperation()
{
glEnable(GL_COLOR_LOGIC_OP);
glLogicOp(GL_XOR);
glColor3f(0,1,0);
// glColor3f(color.r,color.g,color.b);
glLineWidth(this->Width);
if (m_first == 1)
{
glBegin(GL_LINES);
glVertex2f(xmin, ymin);
glVertex2f(xmin, ymax);
glVertex2f(xmin, ymin);
glVertex2f(xmax, ymin);
glVertex2f(xmin, ymax);
glVertex2f(xmax, ymax);
glVertex2f(xmax, ymin);
glVertex2f(xmax, ymax);
glEnd();
m_lastx = xmax, m_lasty = ymax;
m_first = 2;
}
else if (m_first == 2)
{
glBegin(GL_LINES);
glVertex2f(xmin, ymin);
glVertex2f(xmin, m_lasty);
glVertex2f(xmin, ymin);
glVertex2f(m_lastx, ymin);
glVertex2f(xmin, m_lasty);
glVertex2f(m_lastx, m_lasty);
glVertex2f(m_lastx, ymin);
glVertex2f(m_lastx, m_lasty);
glEnd();
glBegin(GL_LINES);
glVertex2f(xmin, ymin);
glVertex2f(xmin, ymax);
glVertex2f(xmin, ymin);
glVertex2f(xmax, ymin);
glVertex2f(xmin, ymax);
glVertex2f(xmax, ymax);
glVertex2f(xmax, ymin);
glVertex2f(xmax, ymax);
glEnd();
}
glDisable(GL_COLOR_LOGIC_OP);
}
bool CMyRect::OnLButtonUp(float x,float y)
{
if (!m_first)
{
xmin = x;
ymin = y;
xmax = x;
ymax = y;
m_first =1;
return false;
}
xmax = x;
ymax = y;
float x0 = min(xmin,xmax);
float x1 = max(xmin,xmax);
float y0 = min(ymin,ymax);
float y1 = max(ymin,ymax);
xmin = x0, ymin = y0, xmax = x1, ymax = y1;
return true;
}
void CMyRect::OnMouseMove(float x,float y)
{
if (m_first==2)
{
xmax = x;
ymax = y;
}
}
bool CMyRect::Pick(float x,float y)
{
if ((x>Field.TopLeft().x&&x<Field.BottomRight().x)&&(y>Field.TopLeft().y&&y<Field.BottomRight().y))
return true;
return false;
}
bool CMyRect::GetTheFeildCrect()
{
Field.SetRect(min(xmax,xmin),min(ymax,ymin),max(xmax,xmin),max(ymax,ymin));
return true;
}
void CMyRect::GetPos(float& x, float& y)
{
}
void CMyRect::OnKeyMove(UINT nChar)
{
glEnable(GL_COLOR_LOGIC_OP);
glLogicOp(GL_XOR);
// glColor3f(0,1,0);
glColor3f(color.r,color.g,color.b);
glLineWidth(this->Width);
glBegin(GL_LINES);
glVertex2f(xmin, ymin);
glVertex2f(xmin, ymax);
glVertex2f(xmin, ymin);
glVertex2f(xmax, ymin);
glVertex2f(xmin, ymax);
glVertex2f(xmax, ymax);
glVertex2f(xmax, ymin);
glVertex2f(xmax, ymax);
glEnd();
glDisable(GL_COLOR_LOGIC_OP);
switch(nChar)
{
case 'W':
ymin=ymin-1;
ymax=ymax-1;
break;
case 'S':
ymin=ymin+1;
ymax=ymax+1;
break;
case 'A':
xmin=xmin-1;
xmax=xmax-1;
break;
case 'D':
xmin=xmin+1;
xmax=xmax+1;
break;
default:
break;
}
}
bool CMyRect:: Read(CString str)
{
int pos=0;
float para[8];
int i=0;
while (i<8)
{
pos=str.Find(' ');
para[i]=atof(str.Left(pos));
str=str.Mid(pos+1,str.GetLength());
i++;
}
this->color.r=para[0];
this->color.g=para[1];
this->color.b=para[2];
this->Width=para[3];
this->xmin=para[4];
this->ymin=para[5];
this->xmax=para[6];
this->ymax=para[7];
return true;
}
CString CMyRect::Save()
{
CString test="";
CString str;
str.Format(" %f %f %f %f %f %f %f %f ",this->color.r,this->color.g,this->color.b,this->Width,this->xmin,this->ymin,this->xmax,this->ymax);
test=test+str;
return test;
} | [
"[email protected]@551f4f89-5e81-c284-84fc-d916aa359411"
]
| [
[
[
1,
251
]
]
]
|
b2b58b4dcee64a820a21e8875b29204399563b83 | 3d9e738c19a8796aad3195fd229cdacf00c80f90 | /src/gui/gl_widget_3/GL_cutting_plane_layer_3.h | f464d9863cfe709ec990d0dd7a615af7924da987 | []
| no_license | mrG7/mesecina | 0cd16eb5340c72b3e8db5feda362b6353b5cefda | d34135836d686a60b6f59fa0849015fb99164ab4 | refs/heads/master | 2021-01-17T10:02:04.124541 | 2011-03-05T17:29:40 | 2011-03-05T17:29:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 891 | h | /* This source file is part of mesecina, a software for visualization and studying of
* the medial axis and related computational geometry structures.
* More info at http://www.agg.ethz.ch/~miklosb/mesecina
* Copyright Balint Miklos, Applied Geometry Group, ETH Zurich
*
* $Id: GL_cutting_plane_layer_3.h 93 2007-04-06 22:00:48Z miklosb $
*/
#ifndef MESECINA_CUTTING_PLANE_LAYER_3_H
#define MESECINA_CUTTING_PLANE_LAYER_3_H
#include <gui/gl_widget_3/GL_draw_layer_3.h>
class qglviewer::ManipulatedFrame;
class W_API GL_cutting_plane_layer_3 : public GL_draw_layer_3 {
public:
GL_cutting_plane_layer_3(const QString& name);
virtual void set_active(bool a);
virtual void attach(GL_widget_3 *w);
virtual void draw();
virtual bool has_property(Layer_property prop);
qglviewer::ManipulatedFrame* fr;
};
#endif //MESECINA_CUTTING_PLANE_LAYER_3_H
| [
"balint.miklos@localhost"
]
| [
[
[
1,
30
]
]
]
|
6d019a916e2bc6189a1fe9f4bd3535857b777b3d | 4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61 | /CleanProject/MyGUI/include/MyGUI_ScrollView.h | 25bcc1b169164b77d2f42ace7cf3609d1a0b7537 | []
| no_license | bahao247/apeengine2 | 56560dbf6d262364fbc0f9f96ba4231e5e4ed301 | f2617b2a42bdf2907c6d56e334c0d027fb62062d | refs/heads/master | 2021-01-10T14:04:02.319337 | 2009-08-26T08:23:33 | 2009-08-26T08:23:33 | 45,979,392 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,770 | h | /*!
@file
@author Albert Semenov
@date 08/2008
@module
*//*
This file is part of MyGUI.
MyGUI 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 3 of the License, or
(at your option) any later version.
MyGUI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with MyGUI. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __MYGUI_SCROLL_VIEW_H__
#define __MYGUI_SCROLL_VIEW_H__
#include "MyGUI_Prerequest.h"
#include "MyGUI_Widget.h"
namespace MyGUI
{
class MYGUI_EXPORT ScrollView : public Widget
{
// для вызова закрытого конструктора
friend class factory::BaseWidgetFactory<ScrollView>;
MYGUI_RTTI_CHILD_HEADER( ScrollView, Widget );
public:
//! @copydoc Widget::setAlign
//virtual void setAlign(Align _align);
//! @copydoc Widget::setPosition(const IntPoint & _point)
virtual void setPosition(const IntPoint & _point);
//! @copydoc Widget::setSize(const IntSize& _size)
virtual void setSize(const IntSize & _size);
//! @copydoc Widget::setCoord(const IntCoord & _coord)
virtual void setCoord(const IntCoord & _coord);
/** @copydoc Widget::setPosition(int _left, int _top) */
void setPosition(int _left, int _top) { setPosition(IntPoint(_left, _top)); }
/** @copydoc Widget::setSize(int _width, int _height) */
void setSize(int _width, int _height) { setSize(IntSize(_width, _height)); }
/** @copydoc Widget::setCoord(int _left, int _top, int _width, int _height) */
void setCoord(int _left, int _top, int _width, int _height) { setCoord(IntCoord(_left, _top, _width, _height)); }
/** Show VScroll when text size larger than Edit */
void setVisibleVScroll(bool _visible) { mShowVScroll = _visible; updateView(); }
/** Get Show VScroll flag */
bool isVisibleVScroll() { return mShowVScroll; }
/** Show HScroll when text size larger than Edit */
void setVisibleHScroll(bool _visible) { mShowHScroll = _visible; updateView(); }
/** Get Show HScroll flag */
bool isVisibleHScroll() { return mShowHScroll; }
/** Get canvas align */
Align getCanvasAlign() { return mAlignCanvas; }
/** Set canvas align */
void setCanvasAlign(Align _align) { mAlignCanvas = _align; updateView(); }
/** Get canvas size */
IntSize getCanvasSize() { return mWidgetClient->getSize(); }
/** Set canvas size */
void setCanvasSize(const IntSize & _size) { mWidgetClient->setSize(_size); updateView(); }
/** Set canvas size */
void setCanvasSize(int _width, int _height) { setCanvasSize(IntSize(_width, _height)); }
/** Get rect where child widgets placed */
const IntCoord& getClientCoord() { return mClient->getCoord(); }
/*obsolete:*/
#ifndef MYGUI_DONT_USE_OBSOLETE
MYGUI_OBSOLETE("use : void Widget::setCoord(const IntCoord& _coord)")
void setPosition(const IntCoord & _coord) { setCoord(_coord); }
MYGUI_OBSOLETE("use : void Widget::setCoord(int _left, int _top, int _width, int _height)")
void setPosition(int _left, int _top, int _width, int _height) { setCoord(_left, _top, _width, _height); }
MYGUI_OBSOLETE("use : void ScrollView::setVisibleVScroll(bool _visible)")
void showVScroll(bool _visible) { setVisibleVScroll(_visible); }
MYGUI_OBSOLETE("use : bool ScrollView::isVisibleVScroll()")
bool isShowVScroll() { return isVisibleVScroll(); }
MYGUI_OBSOLETE("use : void ScrollView::setVisibleHScroll(bool _visible)")
void showHScroll(bool _visible) { setVisibleHScroll(_visible); }
MYGUI_OBSOLETE("use : bool ScrollView::isVisibleHScroll()")
bool isShowHScroll() { return isVisibleHScroll(); }
#endif // MYGUI_DONT_USE_OBSOLETE
protected:
ScrollView(WidgetStyle _style, const IntCoord& _coord, Align _align, const WidgetSkinInfoPtr _info, WidgetPtr _parent, ICroppedRectangle * _croppedParent, IWidgetCreator * _creator, const std::string & _name);
virtual ~ScrollView();
void baseChangeWidgetSkin(WidgetSkinInfoPtr _info);
// переопределяем для присвоению холста
virtual WidgetPtr baseCreateWidget(WidgetStyle _style, const std::string & _type, const std::string & _skin, const IntCoord& _coord, Align _align, const std::string & _layer, const std::string & _name);
void notifyMouseSetFocus(WidgetPtr _sender, WidgetPtr _old);
void notifyMouseLostFocus(WidgetPtr _sender, WidgetPtr _new);
void notifyMousePressed(WidgetPtr _sender, int _left, int _top, MouseButton _id);
void notifyMouseReleased(WidgetPtr _sender, int _left, int _top, MouseButton _id);
void notifyScrollChangePosition(VScrollPtr _sender, size_t _position);
void notifyMouseWheel(WidgetPtr _sender, int _rel);
virtual void onKeyLostFocus(WidgetPtr _new);
virtual void onKeySetFocus(WidgetPtr _old);
void updateScrollViewState();
// обновление представления
void updateView();
void updateScroll();
private:
void initialiseWidgetSkin(WidgetSkinInfoPtr _info);
void shutdownWidgetSkin();
protected:
bool mIsFocus;
bool mIsPressed;
VScrollPtr mVScroll;
HScrollPtr mHScroll;
bool mShowHScroll;
bool mShowVScroll;
size_t mVRange;
size_t mHRange;
WidgetPtr mClient;
Align mAlignCanvas;
}; // class ScrollView : public Widget
} // namespace MyGUI
#endif // __MYGUI_SCROLL_VIEW_H__
| [
"pablosn@06488772-1f9a-11de-8b5c-13accb87f508"
]
| [
[
[
1,
152
]
]
]
|
5a15212625317c915908e1bdd8e3e30eb0daae1d | 335783c9e5837a1b626073d1288b492f9f6b057f | /source/fbxcmd/daolib/Model/Common/matrix44.cpp | 06ddf1b5d132f2546ff77c568d68d7b8b79aca6c | [
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause"
]
| permissive | code-google-com/fbx4eclipse | 110766ee9760029d5017536847e9f3dc09e6ebd2 | cc494db4261d7d636f8c4d0313db3953b781e295 | refs/heads/master | 2016-09-08T01:55:57.195874 | 2009-12-03T20:35:48 | 2009-12-03T20:35:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,247 | cpp | /* Copyright (c) 2006, NIF File Format Library and Tools
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 NIF File Format Library and Tools
project 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 "DAOFormat.h"
#include "vector2f.h"
#include "vector3f.h"
#include "vector4f.h"
#include "color4.h"
#include "quaternion.h"
#include "matrix33.h"
#include "matrix43.h"
#include "matrix44.h"
const Matrix44 Matrix44::IDENTITY( 1.0f, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f );
Matrix44::Matrix44() {
*this = Matrix44::IDENTITY;
}
Matrix44::Matrix44( const Matrix33 & r ) {
//Set this matrix with rotate and translate information
Matrix44 & m = *this;
m[0][0] = r[0][0]; m[0][1] = r[0][1]; m[0][2] = r[0][2]; m[0][3] = 0.0f;
m[1][0] = r[1][0]; m[1][1] = r[1][1]; m[1][2] = r[1][2]; m[1][3] = 0.0f;
m[2][0] = r[2][0]; m[2][1] = r[2][1]; m[2][2] = r[2][2]; m[2][3] = 0.0f;
m[3][0] = 0.0f; m[3][1] = 0.0f; m[3][2] = 0.0f; m[3][3] = 1.0f;
}
Matrix44::Matrix44( const Vector3f & t, const Matrix33 & r, float scale ) {
//Set up a matrix with rotate and translate information
Matrix44 rt;
rt[0][0] = r[0][0]; rt[0][1] = r[0][1]; rt[0][2] = r[0][2]; rt[0][3] = 0.0f;
rt[1][0] = r[1][0]; rt[1][1] = r[1][1]; rt[1][2] = r[1][2]; rt[1][3] = 0.0f;
rt[2][0] = r[2][0]; rt[2][1] = r[2][1]; rt[2][2] = r[2][2]; rt[2][3] = 0.0f;
rt[3][0] = t.x; rt[3][1] = t.y; rt[3][2] = t.z; rt[3][3] = 1.0f;
//Set up another matrix with the scale information
Matrix44 s;
s[0][0] = scale; s[0][1] = 0.0f; s[0][2] = 0.0f; s[0][3] = 0.0f;
s[1][0] = 0.0f; s[1][1] = scale; s[1][2] = 0.0f; s[1][3] = 0.0f;
s[2][0] = 0.0f; s[2][1] = 0.0f; s[2][2] = scale; s[2][3] = 0.0f;
s[3][0] = 0.0f; s[3][1] = 0.0f; s[3][2] = 0.0f; s[3][3] = 1.0f;
//Multiply the two for the combined transform
*this = s * rt;
}
Matrix44::Matrix44( float m11, float m12, float m13, float m14
, float m21, float m22, float m23, float m24
, float m31, float m32, float m33, float m34
, float m41, float m42, float m43, float m44 )
{
m[0][0] = m11; m[0][1] = m12; m[0][2] = m13; m[0][3] = m14;
m[1][0] = m21; m[1][1] = m22; m[1][2] = m23; m[1][3] = m24;
m[2][0] = m31; m[2][1] = m32; m[2][2] = m33; m[2][3] = m34;
m[3][0] = m41; m[3][1] = m42; m[3][2] = m43; m[3][3] = m44;
}
Matrix44::Matrix44( const Vector3f& pos, const Quaternion& rot, float scale )
{
Set(pos, rot, scale);
}
Matrix44::Matrix44( const Vector3f& pos, const Quaternion& rot, const Vector3f& scale )
{
Set(pos, rot, scale);
}
Matrix44::Matrix44( const Vector4f& pos, const Quaternion& rot, float scale )
{
Set(pos, rot, scale);
}
Matrix44::Matrix44( const Vector4f& pos, const Quaternion& rot, const Vector3f& scale )
{
Set(pos, rot, scale);
}
Matrix33 Matrix44::GetRotation() const {
const Matrix44 & t = *this;
Matrix33 m( t[0][0], t[0][1], t[0][2],
t[1][0], t[1][1], t[1][2],
t[2][0], t[2][1], t[2][2]
);
//--Extract Scale from first 3 a--//
float scale[3];
for (int r = 0; r < 3; ++r) {
//Get scale for this row
scale[r] = Vector3f( m[r][0], m[r][1], m[r][2] ).Length();
//Normalize the row by dividing each factor by scale
m[r][0] /= scale[r];
m[r][1] /= scale[r];
m[r][2] /= scale[r];
}
//Return result
return m;
}
float Matrix44::GetScale() const {
const Matrix44 & m = *this;
float scale[3];
for (int r = 0; r < 3; ++r) {
//Get scale for this row
scale[r] = Vector3f( m[r][0], m[r][1], m[r][2] ).Length();
}
//averate the scale since NIF doesn't support discreet scaling
return (scale[0] + scale[1] + scale[2]) / 3.0f;
}
Vector3f Matrix44::GetTranslation() const {
const Matrix44 & m = *this;
return Vector3f( m[3][0], m[3][1], m[3][2] );
}
Matrix44 Matrix44::operator*( const Matrix44 & rh ) const {
return Matrix44(*this) *= rh;
}
Matrix44 & Matrix44::operator*=( const Matrix44 & rh ) {
Matrix44 r;
Matrix44 & lh = *this;
float t;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
t = 0.0f;
for (int k = 0; k < 4; k++) {
t += lh[i][k] * rh[k][j];
}
r[i][j] = t;
}
}
*this = r;
return *this;
}
Matrix44 Matrix44::operator*( float rh ) const {
return Matrix44(*this) *= rh;
}
Matrix44 & Matrix44::operator*=( float rh ) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
(*this)[i][j] *= rh;
}
}
return *this;
}
Vector3f Matrix44::operator*( const Vector3f & rh ) const {
const Matrix44 & t = *this;
Vector3f v;
//Multiply, ignoring w
v.x = rh.x * t[0][0] + rh.y * t[1][0] + rh.z * t[2][0] + t[3][0];
v.y = rh.x * t[0][1] + rh.y * t[1][1] + rh.z * t[2][1] + t[3][1];
v.z = rh.x * t[0][2] + rh.y * t[1][2] + rh.z * t[2][2] + t[3][2];
//answer[3] = rh[0] * t(0,3) + rh[1] * t(1,3) + rh[2] * t(2,3) + t(3,3);
return v;
}
Matrix44 Matrix44::operator+( const Matrix44 & rh ) const {
return Matrix44(*this) += rh;
}
Matrix44 & Matrix44::operator+=( const Matrix44 & rh ) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
(*this)[i][j] += rh[i][j];
}
}
return *this;
}
Matrix44 Matrix44::operator-( const Matrix44 & rh ) const {
return Matrix44(*this) -= rh;
}
Matrix44 & Matrix44::operator-=( const Matrix44 & rh ) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
(*this)[i][j] -= rh[i][j];
}
}
return *this;
}
Matrix44 & Matrix44::operator=( const Matrix44 & rh ) {
memcpy(m, rh.m, sizeof(float) * 4 * 4);
return *this;
}
bool Matrix44::operator==( const Matrix44 & rh ) const {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if ( (*this)[i][j] != rh[i][j] )
return false;
}
}
return true;
}
bool Matrix44::operator!=( const Matrix44 & rh ) const {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if ( (*this)[i][j] != rh[i][j] )
return true;
}
}
return false;
}
Matrix44 Matrix44::Transpose() const {
const Matrix44 & t = *this;
return Matrix44( t[0][0], t[1][0], t[2][0], t[3][0],
t[0][1], t[1][1], t[2][1], t[3][1],
t[0][2], t[1][2], t[2][2], t[3][2],
t[0][3], t[1][3], t[2][3], t[3][3] );
}
Matrix33 Matrix44::Submatrix( int skip_r, int skip_c ) const {
Matrix33 sub;
int i = 0, j = 0;
for (int r = 0; r < 4; r++) {
if (r == skip_r)
continue;
for (int c = 0; c < 4; c++) {
if (c == skip_c)
continue;
sub[i][j] = (*this)[r][c];
j++;
}
i++;
j = 0;
}
return sub;
}
float Matrix44::Adjoint( int skip_r, int skip_c ) const {
Matrix33 sub = Submatrix( skip_r, skip_c );
return pow(-1.0f, float(skip_r + skip_c)) * sub.Determinant();
}
Matrix44 Matrix44::Inverse() const {
Matrix44 result;
float det = Determinant();
for (int r = 0; r < 4; r++) {
for (int c = 0; c < 4; c++) {
result[c][r] = Adjoint(r, c) / det;
}
}
return result;
}
float Matrix44::Determinant() const {
const Matrix44 & t = *this;
return t[0][0] * Submatrix(0, 0).Determinant()
- t[0][1] * Submatrix(0, 1).Determinant()
+ t[0][2] * Submatrix(0, 2).Determinant()
- t[0][3] * Submatrix(0, 3).Determinant();
}
void Matrix44::Decompose( Vector3f & translate, Matrix33 & rotation, Vector3f & scale ) const
{
translate = Vector3f( (*this)[3][0], (*this)[3][1], (*this)[3][2] );
Matrix33 rotT;
for ( int i = 0; i < 3; i++ ){
for ( int j = 0; j < 3; j++ ){
rotation[i][j] = (*this)[i][j];
rotT[j][i] = (*this)[i][j];
}
}
Matrix33 mtx = rotation * rotT;
scale.Set( sqrt(mtx[0][0]), sqrt(mtx[1][1]), sqrt(mtx[2][2]) );
for ( int i = 0; i < 3; i++ ){
for ( int j = 0; j < 3; j++ ){
rotation[i][j] /= scale[i];
}
}
}
void Matrix44::Decompose( Vector3f & translate, Matrix33 & rotation, float & scale ) const {
Vector3f scale3;
Decompose(translate, rotation, scale3);
scale = (scale3[0] + scale3[1] + scale3[2]) / 3.0f;
}
void Matrix44::Decompose( Vector3f & translate, Quaternion & rotation, float & scale ) const {
Matrix33 m3;
Vector3f scale3;
Decompose(translate, m3, scale3);
rotation = m3.AsQuaternion();
scale = (scale3[0] + scale3[1] + scale3[2]) / 3.0f;
}
void Matrix44::Decompose( Vector3f & translate, Quaternion & rotation, Vector3f & scale ) const {
Matrix33 m3;
Decompose(translate, m3, scale);
rotation = m3.AsQuaternion();
}
Matrix44& Matrix44::Set(const Vector3f& pos, const Quaternion& rot, float scale)
{
Matrix44 rt;
rot.MakeMatrix(rt);
rt.SetRow(3, pos);
if (scale == 1.0)
{
*this = rt;
}
else
{
Matrix44 s(true);
s[0][0] = s[1][1] = s[2][2] = s[3][3] = 1.0;
*this = s * rt;
}
return *this;
}
Matrix44& Matrix44::Set(const Vector3f& pos, const Quaternion& rot, const Vector3f& scale)
{
Matrix44 rt;
rot.MakeMatrix(rt);
rt.SetRow(3, pos);
if (scale[0] == 1.0 && scale[1] == 1.0 && scale[2] == 1.0)
{
*this = rt;
}
else
{
Matrix44 s(true);
s[0][0] = scale.x;
s[1][1] = scale.y;
s[2][2] = scale.z;
*this = s * rt;
}
return *this;
}
Matrix44& Matrix44::Set(const Vector4f& pos, const Quaternion& rot, float scale)
{
Matrix44 rt;
rot.MakeMatrix(rt);
rt.SetRow(3, pos);
if (scale == 1.0)
{
*this = rt;
}
else
{
Matrix44 s(true);
s[0][0] = s[1][1] = s[2][2] = 1.0;
*this = s * rt;
}
return *this;
}
Matrix44& Matrix44::Set(const Vector4f& pos, const Quaternion& rot, const Vector3f& scale)
{
Matrix44 rt;
rot.MakeMatrix(rt);
rt.SetRow(3, pos);
if (scale[0] == 1.0 && scale[1] == 1.0 && scale[2] == 1.0)
{
*this = rt;
}
else
{
Matrix44 s(true);
s[0][0] = scale.x;
s[1][1] = scale.y;
s[2][2] = scale.z;
*this = s * rt;
}
return *this;
}
Quaternion Matrix44::GetRot() const
{
Quaternion quat;
float tr, s, q[4];
int i, j, k;
int nxt[3] = {1, 2, 0};
// compute the trace of the matrix
tr = m[0][0] + m[1][1] + m[2][2];
// check if the trace is positive or negative
if (tr > 0.0) {
s = sqrt (tr + 1.0f);
quat.w = s / 2.0f;
s = 0.5f / s;
quat.x = (m[1][2] - m[2][1]) * s;
quat.y = (m[2][0] - m[0][2]) * s;
quat.z = (m[0][1] - m[1][0]) * s;
}
else {
// trace is negative
i = 0;
if ( m[1][1] > m[0][0])
i = 1;
if ( m[2][2] > m[i][i] )
i = 2;
j = nxt[i];
k = nxt[j];
s = sqrt( ( m[i][i] - (m[j][j] + m[k][k]) ) + 1.0f );
q[i] = s * 0.5f;
if (s != 0.0f) s = 0.5f / s;
q[3] = (m[j][k] - m[k][j]) * s;
q[j] = (m[i][j] + m[j][i]) * s;
q[k] = (m[i][k] + m[k][i]) * s;
quat.x = q[0];
quat.y= q[1];
quat.z = q[2];
quat.w = q[3];
}
return quat;
}
| [
"tazpn314@ccf8930c-dfc1-11de-9043-17b7bd24f792"
]
| [
[
[
1,
466
]
]
]
|
19700faae41439d0aea21df110e83c8d67b00a2a | 3925963306e021f1635cf8958b4027179bc791f8 | /importpts.cpp | 93275ee29fb615936a945627feaad8ba08017a8c | []
| no_license | liuxinren456852/point-cloud-tools | 5141e02117815e291138fb83274ee8c231c9262b | 9ae029f568cc355e8226467f21c6067b1f659e4b | refs/heads/master | 2016-09-06T05:46:41.859699 | 2010-04-09T04:25:07 | 2010-04-09T04:25:07 | 32,194,185 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,513 | cpp | #include "stdafx.h"
#include "define.h"
#include "pctools.h"
#include "mmfini.h"
/*
struct file_closer {
void operator()(FILE* f) const { if (f) std::fclose(f); }
};
typedef unique_ptr<FILE,file_closer> file_handle;
*/
struct scope_guard_file_closer {
FILE* f;
scope_guard_file_closer(FILE* fin) : f(fin) {}
~scope_guard_file_closer() { if (f) fclose(f); }
};
/*
inline void KahanAdd(double3 &sum, double3 p) {
T reduceCPU(T *data, int size)
{
double3 sum = data[0];
double3 c = {0,0,0};
for (int i = 1; i < size; i++)
{
T y = data[i] - c;
T t = sum + y;
c = (t - sum) - y;
sum = t;
}
return sum;
}
*/
//int importpts(const _TCHAR* from_ascii, const _TCHAR* mmf, PCDESCR & descr)
int importpts(const _TCHAR* from_ascii, const _TCHAR* mmf)
{
time_t start = time(NULL);
uint64 nl = std::numeric_limits<uint64>::max();
FILE *xyz_text = _tfopen(from_ascii, _T("rtS"));
scope_guard_file_closer sgfc1(xyz_text);
FILE *xyz_binary = _tfopen(mmf, _T("wbS"));
scope_guard_file_closer sgfc2(xyz_binary);
if(xyz_text == NULL || xyz_binary == NULL) {
cerr << "Problem opening file\n";
return 1;
}
uint64 l = 0,
npoints = 0; // number of valid points
char line[512];
fgets(line, sizeof(line), xyz_text);// Always skipping the first line
printf("skippping line #%llu: %s", l, line);
l++;
double3 p0 = {0,0,0};
fpos_t pos;
if(fgetpos(xyz_text,&pos)) {
cerr << "fgetpos error\n";
return 1;
}
while(l < nl) {
char*str = fgets(line, sizeof(line), xyz_text);
if(str == NULL || *str == 0) {//ferror(xyz_text) || feof(xyz_text))
cerr << "Empty or Corrupted file\n";
return 1;
}
l++;
double3 p;
int nfields = sscanf(line, "%lf %lf %lf", &p.x, &p.y, &p.z);
if(nfields != 3) {
fprintf(stderr, "skippping line #%llu: %s", l, line);
} else {
p0 = p;
p-=p0;
fwrite(as_array(p), sizeof(p), 1, xyz_binary);
break; // exit
}
}
//double3 pmin = {DBL_MAX,DBL_MAX,DBL_MAX}, pmax={-DBL_MAX,-DBL_MAX,-DBL_MAX}, pcom = {0,0,0};
npoints = 1;
double3 pmin = {0,0,0}, pmax = {0,0,0};
double xx = 0, xy = 0, xz = 0, yy = 0, yz = 0, zz = 0;
FPSUM(xx);
FPSUM(xy);
FPSUM(xz);
FPSUM(yy);
FPSUM(yz);
FPSUM(zz);
double3 pcom = {0,0,0};
FPSUM(pcom);
// if(!fsetpos(xyz_text,&pos)) {
// cerr << "fsetpos error\n";
// return 1;
// }
//auto &sum = pcom;
//FPADDINIT(pcom);
//KahanSum<decltype(pcom)> pcom_ks(pcom);
// FPADDINIT(pcom);
//FPSimpleAdd<decltype(pcom)> pcom_add(pcom);
while(l < nl) {
char*str = fgets(line, sizeof(line), xyz_text);
if(str == NULL) //ferror(xyz_text) || feof(xyz_text))
break; //assuming EOF
if(*str == 0) {//ferror(xyz_text) || feof(xyz_text))
cerr << "Corrupted file, binary 0 at the line # " << l << endl;
return 1;
}
l++;
double3 p;
int nfields = sscanf(line, "%lf %lf %lf", &p.x, &p.y, &p.z);
if(nfields != 3) {
fprintf(stderr, "skippping line #%llu: %s", l, line);
continue;
}
p-=p0;
auto update_limits_along = [&p, &pmin, &pmax](int coord) {
auto& x = as_array(p)[coord]; auto& xmin = as_array(pmin)[coord]; auto& xmax = as_array(pmax)[coord];
if(x < xmin) xmin = x;
if(x > xmax) xmax = x;
};
update_limits_along(X);
update_limits_along(Y);
update_limits_along(Z);
const double x = p.x;
const double y = p.y;
const double z = p.z;
xx_add(x*x);
xy_add(x*y);
xz_add(x*z);
yy_add(y*y);
yz_add(y*z);
zz_add(z*z);
pcom_add(p);
fwrite(as_array(p), sizeof(p), 1, xyz_binary);
npoints++;
if(l%(1000000)==0)
printf("\r%llu", l);
}
//fclose(xyz_binary);
//fclose(xyz_text);
pcom /= npoints;
auto const x = pcom.x, y = pcom.y, z = pcom.z;
xx -= x*x * npoints;
xy -= x*y * npoints;
xz -= x*z * npoints;
yy -= y*y * npoints;
yz -= y*z * npoints;
zz -= z*z * npoints;
Wm4::Matrix3d const A(
xx,xy,xz,
xy,yy,yz,
xz,yz,zz);
//clog << "A = \n" << A << endl;
// Bounded-time eigensolver.
Wm4::NoniterativeEigen3x3d const eigen(A);
// clog << "eigen values: \n";
// clog << eigen.GetEigenvalue(0) << " ";
// clog << eigen.GetEigenvalue(1) << " ";
// clog << eigen.GetEigenvalue(2) << "\n";
// clog << "eigen values: \n";
// clog << eigen.GetEigenvector(0) << "\n";
// clog << eigen.GetEigenvector(1) << "\n";
// clog << eigen.GetEigenvector(2) << "\n";
// Wm4::Vector3d const
// normal = eigen.GetEigenvector(0),
// ez(0,0,1),
// ey(0,1,0);
//
// Wm4::Quaterniond q1,q2;
// q1.Align(normal, ez);
//
// Wm4::Vector3d slope = q1.Rotate(-ez + normal*normal.Z());
// slope.Normalize();
// q2.Align(slope, -ey);
//
// Wm4::Quaterniond const q = q2*q1;
// clog << "q = " << q << endl;
//
// Wm4::Vector3d const
// normal_new = q.Rotate(normal),
// slope_new = q.Rotate(-ez + normal*normal.Z());
// min and max must encompass all the points, even for the truncated floating point precision
// pmin.x = min<double>(pmin.x, float(pmin.x));
// pmin.y = min<double>(pmin.y, float(pmin.y));
// pmin.z = min<double>(pmin.z, float(pmin.z));
// pmax.x = max<double>(pmax.x, float(pmax.x));
// pmax.y = max<double>(pmax.y, float(pmax.y));
// pmax.z = max<double>(pmax.z, float(pmax.z));
mmfini::pc ini;
uint32 floatnbits = sizeof(double)*8;
double3 const eigen_values = {eigen.GetEigenvalue(0), eigen.GetEigenvalue(1), eigen.GetEigenvalue(2)};
double3 const
eigen_vec0 = convert(eigen.GetEigenvector(0)),
eigen_vec1 = convert(eigen.GetEigenvector(1)),
eigen_vec2 = convert(eigen.GetEigenvector(2));
#define ASSIGN(field) bf::at_key<mmfini::field>(ini) = field
ASSIGN(npoints);
ASSIGN(floatnbits);
ASSIGN(pmin);
ASSIGN(pmax);
ASSIGN(pcom);
ASSIGN(p0);
ASSIGN(eigen_values);
ASSIGN(eigen_vec0);
ASSIGN(eigen_vec1);
ASSIGN(eigen_vec2);
#undef ASSIGN
const wstring filename_ext(mmf);
const wstring::size_type beginext = filename_ext.rfind('.');
const wstring filename(filename_ext, 0, beginext);
// const wstring ext(filename_ext, beginext);
if(!mmfini::save(ini, mmfini::filename(filename).c_str())) {
cerr << "Cannot save description file";
return 1;
}
// PCDESCR descr1 = {npoints, 64, pmin, pmax, pcom, p0, {0,0,0}};
// descr = descr1;
clog << "\r" << l << "lines (" << npoints << " points) in " << time(NULL) - start << "sec \n";
return 0;
} | [
"rychphd@84adf23a-ec51-11de-a5fe-b7516cc0fd57"
]
| [
[
[
1,
253
]
]
]
|
ed21e23fd551d3195da6af7710a19b86b6555fc0 | 4a266d6931aa06a2343154cab99d8d5cfdac6684 | /csci3081/project-phase3/test/WaterHeaterTest.h | b7b57ef929a0aad4b3abb40518279002c5b632c1 | []
| no_license | Magneticmagnum/robotikdude-school | f0185feb6839ad5c5324756fc86f984fce7abdc1 | cb39138b500c8bbc533e796225588439dcfa6555 | refs/heads/master | 2021-01-10T19:01:39.479621 | 2011-05-17T04:44:47 | 2011-05-17T04:44:47 | 35,382,573 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,541 | h | #ifndef WATERHEATERTEST_H_
#define WATERHEATERTEST_H_
#include "WaterHeater.h"
#include "MockScheduler.h"
#include <cxxtest/TestSuite.h>
class WaterHeaterTest: public CxxTest::TestSuite
{
public:
void test_constructor()
{
log4cxx::LoggerPtr log(log4cxx::Logger::getLogger("WaterHeaterTest"));
LOG4CXX_DEBUG(log, "--> WaterHeaterTest::test_constructors()");
MockScheduler* scheduler = new MockScheduler();
WaterHeater wh1 = WaterHeater(0, scheduler);
TS_ASSERT_EQUALS(wh1.getWaterTemperature(), 50);
delete (scheduler);
LOG4CXX_DEBUG(log, "<-- WaterHeaterTest::test_constructors()");
}
void test_configuration()
{
log4cxx::LoggerPtr log(log4cxx::Logger::getLogger("WaterHeaterTest"));
LOG4CXX_DEBUG(log, "--> WaterHeaterTest::test_configuration()");
MockScheduler* scheduler = new MockScheduler();
ConfigMap* config = Model::parseConfiguration("unittest.config",
WATERHEATER, "waterheater");
WaterHeater wh = WaterHeater(config, scheduler);
TS_ASSERT(!wh.isRunning());
TS_ASSERT_EQUALS(wh.getPower(), 0.0);
for (int i = 0; i < 300; i++) {
wh.tick();
TS_ASSERT(!wh.isRunning());
TS_ASSERT_EQUALS(wh.getPower(), 0.0);
}
for (int i = 0; i < 31; i++) {
wh.tick();
TS_ASSERT(wh.isRunning());
TS_ASSERT_EQUALS(wh.getPower(), 6000.0);
}
wh.tick();
TS_ASSERT(!wh.isRunning());
TS_ASSERT_EQUALS(wh.getPower(), 0.0);
Model::deleteConfiguration(config);
config = Model::parseConfiguration("unittest.config", WATERHEATER,
"fail-heater1");
wh = WaterHeater(config, scheduler);
TS_ASSERT(!wh.isRunning());
TS_ASSERT_EQUALS(wh.getPower(), 0.0);
for (int i = 0; i < 345; i++) {
wh.tick();
TS_ASSERT(!wh.isRunning());
TS_ASSERT_EQUALS(wh.getPower(), 0.0);
}
for (int i = 0; i < 5; i++) {
wh.tick();
TS_ASSERT(wh.isRunning());
TS_ASSERT_EQUALS(wh.getPower(), 4500.0);
}
wh.tick();
TS_ASSERT(!wh.isRunning());
TS_ASSERT_EQUALS(wh.getPower(), 0.0);
Model::deleteConfiguration(config);
config = Model::parseConfiguration("unittest.config", WATERHEATER,
"fail-heater2");
wh = WaterHeater(config, scheduler);
TS_ASSERT(!wh.isRunning());
TS_ASSERT_EQUALS(wh.getPower(), 0.0);
for (int i = 0; i < 345; i++) {
wh.tick();
TS_ASSERT(!wh.isRunning());
TS_ASSERT_EQUALS(wh.getPower(), 0.0);
}
for (int i = 0; i < 5; i++) {
wh.tick();
TS_ASSERT(wh.isRunning());
TS_ASSERT_EQUALS(wh.getPower(), 4500.0);
}
wh.tick();
TS_ASSERT(!wh.isRunning());
TS_ASSERT_EQUALS(wh.getPower(), 0.0);
Model::deleteConfiguration(config);
delete (scheduler);
LOG4CXX_DEBUG(log, "<-- RefrigeratorTest::test_configuration()");
}
void test_action()
{
log4cxx::LoggerPtr log(log4cxx::Logger::getLogger("RefrigeratorTest"));
LOG4CXX_DEBUG(log, "--> RefrigeratorTest::action()");
MockScheduler* scheduler = new MockScheduler();
WaterHeater wh = WaterHeater(0, scheduler);
TS_ASSERT_EQUALS(wh.action("start"), true);
TS_ASSERT_EQUALS(wh.action("stop blah blah blah kajsd;lkfja;slkdjfl;"), true);
TS_ASSERT_EQUALS(wh.action(""), true);
delete (scheduler);
LOG4CXX_DEBUG(log, "<-- RefrigeratorTest::action()");
}
void test_getPower()
{
log4cxx::LoggerPtr log(log4cxx::Logger::getLogger("WaterHeaterTest"));
LOG4CXX_DEBUG(log, "--> WaterHeaterTest::test_getPower()");
MockScheduler* scheduler = new MockScheduler();
WaterHeater wh = WaterHeater(0, scheduler);
TS_ASSERT_EQUALS(wh.getPower(), 0);
for (int i = 0; i < 346; i++) {
wh.tick();
}
TS_ASSERT_EQUALS(wh.getPower(), 4500);
delete (scheduler);
LOG4CXX_DEBUG(log, "<-- WaterHeaterTest::test_getPower()");
}
void test_getEnergy()
{
log4cxx::LoggerPtr log(log4cxx::Logger::getLogger("WaterHeaterTest"));
LOG4CXX_DEBUG(log, "--> WaterHeaterTest::test_getEnergy()");
MockScheduler* scheduler = new MockScheduler();
WaterHeater wh = WaterHeater(0, scheduler);
// double waterHeat = WATERHEATER_TEMP_OFF;
TS_ASSERT_EQUALS(wh.getEnergy(), 0);
for (int i = 0; i < 345; i++) {
wh.tick();
// waterHeat -= WATERHEATER_HEAT_LOSS;
TS_ASSERT_EQUALS(wh.getEnergy(), 0);
}
wh.tick();
TS_ASSERT_DELTA(wh.getEnergy(), 270000.0, 0.1);
wh.tick();
TS_ASSERT_DELTA(wh.getEnergy(), 540000.0, 0.1);
wh.tick();
TS_ASSERT_DELTA(wh.getEnergy(), 810000.0, 0.1);
delete (scheduler);
LOG4CXX_DEBUG(log, "<-- WaterHeaterTest::test_getEnergy()");
}
void test_getWater()
{
log4cxx::LoggerPtr log(log4cxx::Logger::getLogger("WaterHeaterTest"));
LOG4CXX_DEBUG(log, "--> WaterHeaterTest::test_getWater()");
MockScheduler* scheduler = new MockScheduler();
WaterHeater wh = WaterHeater(0, scheduler);
TS_ASSERT_EQUALS(wh.getWater(100.0, 40.0), 40.0);
wh = WaterHeater(0, scheduler);
TS_ASSERT_EQUALS(wh.getWater(100.0, 50.0), 50.0);
wh = WaterHeater(0, scheduler);
TS_ASSERT_EQUALS(wh.getWater(100.0, 60.0), 50.0);
wh = WaterHeater(0, scheduler);
TS_ASSERT_EQUALS(wh.getWater(200.0, 50.0), 50.0);
wh = WaterHeater(0, scheduler);
TS_ASSERT_EQUALS(wh.getWater(300.0, 50.0), (200.0 * 50.0 + 100.0 * 7.0) / 300.0);
delete (scheduler);
LOG4CXX_DEBUG(log, "<-- WaterHeaterTest::test_getWater()");
}
void test_getWaterTemperature()
{
log4cxx::LoggerPtr log(log4cxx::Logger::getLogger("WaterHeaterTest"));
LOG4CXX_DEBUG(log, "--> WaterHeaterTest::test_getWaterTemperature()");
MockScheduler* scheduler = new MockScheduler();
WaterHeater wh = WaterHeater(0, scheduler);
double waterTemp = WATERHEATER_DEFAULT_TEMP_OFF;
TS_ASSERT_EQUALS(wh.getEnergy(), 0);
for (int i = 0; i < 345; i++) {
wh.tick();
waterTemp -= WATERHEATER_DEFAULT_HEAT_LOSS;
TS_ASSERT_EQUALS(wh.getWaterTemperature(), waterTemp);
}
wh.tick();
waterTemp += WATERHEATER_DEFAULT_HEAT_GAIN;
TS_ASSERT_EQUALS(wh.getWaterTemperature(), waterTemp);
wh.tick();
waterTemp += WATERHEATER_DEFAULT_HEAT_GAIN;
TS_ASSERT_EQUALS(wh.getWaterTemperature(), waterTemp);
wh.tick();
waterTemp += WATERHEATER_DEFAULT_HEAT_GAIN;
TS_ASSERT_EQUALS(wh.getWaterTemperature(), waterTemp);
wh.tick();
waterTemp += WATERHEATER_DEFAULT_HEAT_GAIN;
TS_ASSERT_EQUALS(wh.getWaterTemperature(), waterTemp);
wh.tick();
waterTemp += WATERHEATER_DEFAULT_HEAT_GAIN;
TS_ASSERT_EQUALS(wh.getWaterTemperature(), waterTemp);
for (int i = 0; i < 100; i++) {
wh.tick();
waterTemp -= WATERHEATER_DEFAULT_HEAT_LOSS;
TS_ASSERT_EQUALS(wh.getWaterTemperature(), waterTemp);
}
delete (scheduler);
LOG4CXX_DEBUG(log, "<-- WaterHeaterTest::test_getWaterTemperature()");
}
void test_isRunning()
{
log4cxx::LoggerPtr log(log4cxx::Logger::getLogger("WaterHeaterTest"));
LOG4CXX_DEBUG(log, "--> WaterHeaterTest::test_isRunning()");
MockScheduler* scheduler = new MockScheduler();
WaterHeater wh = WaterHeater(0, scheduler);
TS_ASSERT(!wh.isRunning());
for (int i = 0; i < 345; i++) {
wh.tick();
TS_ASSERT(!wh.isRunning());
}
wh.tick();
TS_ASSERT(wh.isRunning());
wh.tick();
TS_ASSERT(wh.isRunning());
wh.tick();
TS_ASSERT(wh.isRunning());
wh.tick();
TS_ASSERT(wh.isRunning());
wh.tick();
TS_ASSERT(wh.isRunning());
for (int i = 0; i < 100; i++) {
wh.tick();
TS_ASSERT(!wh.isRunning());
}
delete (scheduler);
LOG4CXX_DEBUG(log, "<-- WaterHeaterTest::test_isRunning()");
}
};
#endif /* WATERHEATERTEST_H_ */
| [
"robotikdude@e80761d0-8fc2-79d0-c9d0-3546e327c268"
]
| [
[
[
1,
265
]
]
]
|
7baf0679d5073a2ba9a0452b57a4da86804b1083 | c93cd6cba98fe123f99b62168bf3e7c5ca988b8a | /pvmi/pvmf/src/pvmf_pmem_buffer_alloc.cpp | 8428e83ea40ca6e67ab14804ab3f8e4d137c4211 | [
"MIT",
"LicenseRef-scancode-other-permissive",
"Artistic-2.0",
"LicenseRef-scancode-philippe-de-muyter",
"Apache-2.0",
"LicenseRef-scancode-mpeg-iso",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | pulse-android-dev/caf_platform_external_opencore | 66faaed3563cc48a109c3b3d54b7cacbc99c5d20 | ea5a81547a9bb3b104a72d6f255071c53292fd7c | refs/heads/master | 2020-03-29T23:12:28.742734 | 2010-08-05T23:14:50 | 2010-08-05T23:14:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,352 | cpp | /* ------------------------------------------------------------------
* Copyright (C) 1998-2009 PacketVideo
* Copyright (c) 2010, Code Aurora Forum. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied.
* See the License for the specific language governing permissions
* and limitations under the License.
* -------------------------------------------------------------------
*/
#include "pvmf_pmem_buffer_alloc.h"
#include "pvlogger.h"
//#define LOG_NDEBUG 0
//#define LOG_TAG "PMEMBufferAlloc"
#include <utils/Log.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
PVMFPMemBufferAlloc::PVMFPMemBufferAlloc() :
nNumBufferAllocated(0)
{
iBuffersAllocQueueLock.Create();
}
PVMFPMemBufferAlloc::~PVMFPMemBufferAlloc()
{
LOGE("PVMFPMemBufferAlloc::~PVMFPMemBufferAlloc with the num buff as %d", nNumBufferAllocated);
// Not all the buffers is properly cleaned.
if ( nNumBufferAllocated != 0 ) {
// cleanup all the memory
cleanup();
}
iBuffersAllocQueueLock.Close();
}
OsclAny* PVMFPMemBufferAlloc::allocate(int32 nSize, int32 *pmem_fd)
{
int32 pmemfd = -1;
void *pmem_buf = NULL;
LOGE("PVMFPMemBufferAlloc::allocate calling with required size %d", nSize);
// 1. Open the pmem_audio
pmemfd = open("/dev/pmem_audio", O_RDWR);
if ( pmemfd < 0 ) {
LOGE("PVMFPMemBufferAlloc::allocate failed to open pmem_audio");
*pmem_fd = -1;
return pmem_buf;
}
// 2. MMAP to get the virtual address
pmem_buf = mmap(0, nSize, PROT_READ | PROT_WRITE, MAP_SHARED, pmemfd, 0);
if ( NULL == pmem_buf ) {
LOGE("PVMFPMemBufferAlloc::allocate failed to mmap");
*pmem_fd = -1;
return pmem_buf;
}
// 3. Store this information for internal mapping / maintanence
BuffersAllocated buf((OsclAny*) pmem_buf, nSize, pmemfd);
// 4. Lock the queue, insert the item , update the count and unlock
iBuffersAllocQueueLock.Lock();
iBuffersAllocQueue.push_back(buf);
nNumBufferAllocated++;
iBuffersAllocQueueLock.Unlock();
// 5. Send the pmem fd information
*pmem_fd = pmemfd;
LOGE("The PMEM that is allocated is %d and buffer is %x", pmemfd, pmem_buf);
LOGE("The queue size is %d and num buff allocated is %d", iBuffersAllocQueue.size(), nNumBufferAllocated);
// 6. Return the virtual address
return(OsclAny*)pmem_buf;
}
void PVMFPMemBufferAlloc::deallocate(OsclAny *ptr, int32 pmem_fd)
{
iBuffersAllocQueueLock.Lock();
for ( int32 i = (iBuffersAllocQueue.size() - 1); i >= 0; i-- ) {
// 1. if the buffer address match, delete from the queue
if ( (iBuffersAllocQueue[i].iPMem_buf == ptr) ||
(iBuffersAllocQueue[i].iPMem_fd == pmem_fd) ) {
munmap(iBuffersAllocQueue[i].iPMem_buf, iBuffersAllocQueue[i].iPMem_bufsize);
// Close the PMEM fd
close(iBuffersAllocQueue[i].iPMem_fd);
// Remove the pmem info from the queue
iBuffersAllocQueue.erase(&iBuffersAllocQueue[i]);
nNumBufferAllocated--;
}
}
LOGE("Inside deallocate and the queue size is set to %d with numbuf as %d", iBuffersAllocQueue.size(), nNumBufferAllocated);
iBuffersAllocQueueLock.Unlock();
}
void PVMFPMemBufferAlloc::cleanup()
{
iBuffersAllocQueueLock.Lock();
for ( int32 i = (iBuffersAllocQueue.size() - 1); i >= 0; i-- ) {
munmap(iBuffersAllocQueue[i].iPMem_buf, iBuffersAllocQueue[i].iPMem_bufsize);
// Close the PMEM fd
close(iBuffersAllocQueue[i].iPMem_fd);
// Remove the pmem info from the queue
iBuffersAllocQueue.erase(&iBuffersAllocQueue[i]);
nNumBufferAllocated--;
}
iBuffersAllocQueueLock.Unlock();
}
| [
"[email protected]"
]
| [
[
[
1,
141
]
]
]
|
59287e5759adc4302fd3c4ac1cb2504a01218da1 | 580738f96494d426d6e5973c5b3493026caf8b6a | /Include/Vcl/dbcommon.hpp | ec3569c1e08ab1e276cf09daea3dfc3307054a68 | []
| no_license | bravesoftdz/cbuilder-vcl | 6b460b4d535d17c309560352479b437d99383d4b | 7b91ef1602681e094a6a7769ebb65ffd6f291c59 | refs/heads/master | 2021-01-10T14:21:03.726693 | 2010-01-11T11:23:45 | 2010-01-11T11:23:45 | 48,485,606 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 8,299 | hpp | // Borland C++ Builder
// Copyright (c) 1995, 2002 by Borland Software Corporation
// All rights reserved
// (DO NOT EDIT: machine generated header) 'DBCommon.pas' rev: 6.00
#ifndef DBCommonHPP
#define DBCommonHPP
#pragma delphiheader begin
#pragma option push -w-
#pragma option push -Vx
#include <SqlTimSt.hpp> // Pascal unit
#include <DB.hpp> // Pascal unit
#include <Classes.hpp> // Pascal unit
#include <Variants.hpp> // Pascal unit
#include <Windows.hpp> // Pascal unit
#include <SysInit.hpp> // Pascal unit
#include <System.hpp> // Pascal unit
//-- user supplied -----------------------------------------------------------
namespace Dbcommon
{
//-- type declarations -------------------------------------------------------
#pragma option push -b-
enum TCANOperator { coNOTDEFINED, coISBLANK, coNOTBLANK, coEQ, coNE, coGT, coLT, coGE, coLE, coNOT, coAND, coOR, coTUPLE2, coFIELD2, coCONST2, coMINUS, coADD, coSUB, coMUL, coDIV, coMOD, coREM, coSUM, coCOUNT, coMIN, coMAX, coAVG, coCONT, coUDF2, coCONTINUE2, coLIKE, coIN, coLIST2, coUPPER, coLOWER, coFUNC2, coLISTELEM2, coASSIGN };
#pragma option pop
#pragma option push -b-
enum NODEClass { nodeNULL, nodeUNARY, nodeBINARY, nodeCOMPARE, nodeFIELD, nodeCONST, nodeTUPLE, nodeCONTINUE, nodeUDF, nodeLIST, nodeFUNC, nodeLISTELEM };
#pragma option pop
typedef DynamicArray<Byte > TExprData;
typedef Byte TFieldMap[38];
#pragma option push -b-
enum TParserOption { poExtSyntax, poAggregate, poDefaultExpr, poUseOrigNames, poFieldNameGiven, poFieldDepend };
#pragma option pop
typedef Set<TParserOption, poExtSyntax, poFieldDepend> TParserOptions;
#pragma option push -b-
enum TExprNodeKind { enField, enConst, enOperator, enFunc };
#pragma option pop
#pragma option push -b-
enum TExprScopeKind { skField, skAgg, skConst };
#pragma option pop
struct TExprNode;
typedef TExprNode *PExprNode;
struct TExprNode
{
TExprNode *FNext;
TExprNodeKind FKind;
bool FPartial;
TCANOperator FOperator;
Variant FData;
TExprNode *FLeft;
TExprNode *FRight;
Db::TFieldType FDataType;
int FDataSize;
Classes::TList* FArgs;
TExprScopeKind FScopeKind;
} ;
class DELPHICLASS TFilterExpr;
class PASCALIMPLEMENTATION TFilterExpr : public System::TObject
{
typedef System::TObject inherited;
private:
Db::TDataSet* FDataSet;
Byte FFieldMap[38];
Db::TFilterOptions FOptions;
TParserOptions FParserOptions;
TExprNode *FNodes;
DynamicArray<Byte > FExprBuffer;
int FExprBufSize;
int FExprNodeSize;
int FExprDataSize;
AnsiString FFieldName;
Classes::TBits* FDependentFields;
Db::TField* __fastcall FieldFromNode(PExprNode Node);
char * __fastcall GetExprData(int Pos, int Size);
int __fastcall PutConstBCD(const Variant &Value, int Decimals);
int __fastcall PutConstFMTBCD(const Variant &Value, int Decimals);
int __fastcall PutConstBool(const Variant &Value);
int __fastcall PutConstDate(const Variant &Value);
int __fastcall PutConstDateTime(const Variant &Value);
int __fastcall PutConstSQLTimeStamp(const Variant &Value);
int __fastcall PutConstFloat(const Variant &Value);
int __fastcall PutConstInt(Db::TFieldType DataType, const Variant &Value);
int __fastcall PutConstNode(Db::TFieldType DataType, char * Data, int Size);
int __fastcall PutConstStr(const AnsiString Value);
int __fastcall PutConstTime(const Variant &Value);
int __fastcall PutData(char * Data, int Size);
int __fastcall PutExprNode(PExprNode Node, TCANOperator ParentOp);
int __fastcall PutFieldNode(Db::TField* Field, PExprNode Node);
int __fastcall PutNode(NODEClass NodeType, TCANOperator OpType, int OpCount);
void __fastcall SetNodeOp(int Node, int Index, int Data);
int __fastcall PutConstant(PExprNode Node);
Db::TField* __fastcall GetFieldByName(AnsiString Name);
public:
__fastcall TFilterExpr(Db::TDataSet* DataSet, Db::TFilterOptions Options, TParserOptions ParseOptions, const AnsiString FieldName, Classes::TBits* DepFields, const Byte * FieldMap);
__fastcall virtual ~TFilterExpr(void);
PExprNode __fastcall NewCompareNode(Db::TField* Field, TCANOperator Operator, const Variant &Value);
PExprNode __fastcall NewNode(TExprNodeKind Kind, TCANOperator Operator, const Variant &Data, PExprNode Left, PExprNode Right);
TExprData __fastcall GetFilterData(PExprNode Root);
__property Db::TDataSet* DataSet = {write=FDataSet};
};
#pragma option push -b-
enum TExprToken { etEnd, etSymbol, etName, etLiteral, etLParen, etRParen, etEQ, etNE, etGE, etLE, etGT, etLT, etADD, etSUB, etMUL, etDIV, etComma, etLIKE, etISNULL, etISNOTNULL, etIN };
#pragma option pop
class DELPHICLASS TExprParser;
class PASCALIMPLEMENTATION TExprParser : public System::TObject
{
typedef System::TObject inherited;
private:
char FDecimalSeparator;
TFilterExpr* FFilter;
Byte FFieldMap[38];
AnsiString FText;
char *FSourcePtr;
char *FTokenPtr;
AnsiString FTokenString;
AnsiString FStrTrue;
AnsiString FStrFalse;
TExprToken FToken;
TExprToken FPrevToken;
DynamicArray<Byte > FFilterData;
bool FNumericLit;
int FDataSize;
TParserOptions FParserOptions;
AnsiString FFieldName;
Db::TDataSet* FDataSet;
Classes::TBits* FDependentFields;
void __fastcall NextToken(void);
bool __fastcall NextTokenIsLParen(void);
PExprNode __fastcall ParseExpr(void);
PExprNode __fastcall ParseExpr2(void);
PExprNode __fastcall ParseExpr3(void);
PExprNode __fastcall ParseExpr4(void);
PExprNode __fastcall ParseExpr5(void);
PExprNode __fastcall ParseExpr6(void);
PExprNode __fastcall ParseExpr7(void);
AnsiString __fastcall TokenName();
bool __fastcall TokenSymbolIs(const AnsiString S);
bool __fastcall TokenSymbolIsFunc(const AnsiString S);
void __fastcall GetFuncResultInfo(PExprNode Node);
void __fastcall TypeCheckArithOp(PExprNode Node);
void __fastcall GetScopeKind(PExprNode Root, PExprNode Left, PExprNode Right);
public:
__fastcall TExprParser(Db::TDataSet* DataSet, const AnsiString Text, Db::TFilterOptions Options, TParserOptions ParserOptions, const AnsiString FieldName, Classes::TBits* DepFields, const Byte * FieldMap);
__fastcall virtual ~TExprParser(void);
void __fastcall SetExprParams(const AnsiString Text, Db::TFilterOptions Options, TParserOptions ParserOptions, const AnsiString FieldName);
__property TExprData FilterData = {read=FFilterData};
__property int DataSize = {read=FDataSize, nodefault};
};
#pragma pack(push, 4)
struct TFieldInfo
{
AnsiString DatabaseName;
AnsiString TableName;
AnsiString OriginalFieldName;
} ;
#pragma pack(pop)
#pragma option push -b-
enum TSQLToken { stUnknown, stTableName, stFieldName, stAscending, stDescending, stSelect, stFrom, stWhere, stGroupBy, stHaving, stUnion, stPlan, stOrderBy, stForUpdate, stEnd, stPredicate, stValue, stIsNull, stIsNotNull, stLike, stAnd, stOr, stNumber, stAllFields, stComment, stDistinct };
#pragma option pop
//-- var, const, procedure ---------------------------------------------------
static const Shortint CANEXPRSIZE = 0xa;
static const Shortint CANHDRSIZE = 0x8;
static const Shortint CANEXPRVERSION = 0x2;
#define SQLSections (System::Set<TSQLToken, stUnknown, stDistinct> () << TSQLToken(5) << TSQLToken(6) << TSQLToken(7) << TSQLToken(8) << TSQLToken(9) << TSQLToken(10) << TSQLToken(11) << TSQLToken(12) << TSQLToken(13) )
extern PACKAGE TSQLToken __fastcall NextSQLToken(char * &p, /* out */ AnsiString &Token, TSQLToken CurSection);
extern PACKAGE AnsiString __fastcall AddParamSQLForDetail(Db::TParams* Params, AnsiString SQL, bool Native);
extern PACKAGE AnsiString __fastcall GetTableNameFromQuery(const AnsiString SQL);
extern PACKAGE AnsiString __fastcall GetTableNameFromSQL(const AnsiString SQL);
extern PACKAGE bool __fastcall IsMultiTableQuery(const AnsiString SQL);
extern PACKAGE Db::TIndexDef* __fastcall GetIndexForOrderBy(const AnsiString SQL, Db::TDataSet* DataSet);
extern PACKAGE bool __fastcall GetFieldInfo(const AnsiString Origin, TFieldInfo &FieldInfo);
} /* namespace Dbcommon */
using namespace Dbcommon;
#pragma option pop // -w-
#pragma option pop // -Vx
#pragma delphiheader end.
//-- end unit ----------------------------------------------------------------
#endif // DBCommon
| [
"bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b"
]
| [
[
[
1,
204
]
]
]
|
819e2c883aa63f1fc248ebd1bf1276c9c2339979 | 7476d2c710c9a48373ce77f8e0113cb6fcc4c93b | /Reference.h | 4e183fad0ae38b990c11fbdebc98dfc9aa6d795b | []
| no_license | CmaThomas/Vault-Tec-Multiplayer-Mod | af23777ef39237df28545ee82aa852d687c75bc9 | 5c1294dad16edd00f796635edaf5348227c33933 | refs/heads/master | 2021-01-16T21:13:29.029937 | 2011-10-30T21:58:41 | 2011-10-30T22:00:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,644 | h | #ifndef REFERENCE_H
#define REFERENCE_H
#include "Data.h"
#include "Utils.h"
#include "Value.h"
#include "Network.h"
#include "CriticalSection.h"
#include "VaultFunctor.h"
#include "RakNet/NetworkIDObject.h"
using namespace std;
using namespace RakNet;
using namespace Data;
/**
* \brief The base class for all in-game types
*
* Data specific to References are a reference ID, a base ID and a NetworkID
*/
class Reference : public CriticalSection, public NetworkIDObject
{
friend class GameFactory;
private:
Value<unsigned int> refID;
Value<unsigned int> baseID;
static IndexLookup Mods;
Reference( const Reference& );
Reference& operator=( const Reference& );
protected:
static unsigned int ResolveIndex( unsigned int baseID );
Reference( unsigned int refID, unsigned int baseID );
virtual ~Reference();
public:
/**
* \brief Retrieves the Reference's reference ID
*/
unsigned int GetReference() const;
/**
* \brief Retrieves the Reference's base ID
*/
unsigned int GetBase() const;
/**
* \brief Sets the Reference's reference ID
*/
Lockable* SetReference( unsigned int refID );
/**
* \brief Sets the Reference's base ID
*/
Lockable* SetBase( unsigned int baseID );
/**
* \brief Returns a constant Parameter used to pass the reference ID of this Reference to the Interface
*/
const Parameter GetReferenceParam() const;
/**
* \brief Returns a constant Parameter used to pass the base ID of this Reference to the Interface
*/
const Parameter GetBaseParam() const;
};
#endif
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
23
],
[
25,
25
],
[
29,
29
],
[
31,
31
],
[
34,
34
],
[
37,
37
],
[
40,
40
],
[
42,
42
],
[
51,
51
],
[
60,
60
],
[
69,
72
]
],
[
[
24,
24
],
[
26,
28
],
[
30,
30
],
[
32,
33
],
[
35,
36
],
[
38,
39
],
[
41,
41
],
[
43,
50
],
[
52,
59
],
[
61,
68
]
]
]
|
d7d00cd81da0cd417c5b52327fec3f4885b889ab | 06ff805f168597297a87642c951867b453e401f7 | /Algorithm/src/test/BreadthFirstSearchTest.cpp | 557fef09f4d26bb5e78e2ca75c6e071634ad3bf7 | []
| no_license | fredska/algorithms | 58459720295f8cf36edc88f68e4b37962235e533 | 10538d9677894b450f359db9301108b459b604ca | refs/heads/master | 2021-01-02T09:38:34.466733 | 2011-11-09T17:32:57 | 2011-11-09T17:32:57 | 2,652,603 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,339 | cpp | /*
* BreadthFirstSearchTest.cpp
*
* Created on: Oct 27, 2011
* Author: Work
*/
#include "cute.h"
#include "ide_listener.h"
#include "cute_runner.h"
#include <vector>
#include <set>
#include <iostream>
#include <Graph.h>
#include <BreadthFirstSearchTest.h>
using namespace std;
Graph bfsGraph(WIDTH * HEIGHT);
/**
* Use a queue structure to generate the edges
* the edges will be immediately Above, Below, Left and Right of the source point
* so.. (d is for pointing down)
* 1 <- 2 -> 3
* ^ ^ ^
* 4 <- 5 -> 6
* d d d
* 7 <- 8 -> 9
*/
bool verifyValidLocation(int vertex, int MAX_SIZE)
{
set<int> i;
return (vertex < 0 || vertex >= (MAX_SIZE));
}
Graph generateGraphFromSource(Graph graph, int source)
{
queue<int> q;
q.push(source);
int MAX_SIZE;
MAX_SIZE = WIDTH * HEIGHT;
bool *nodeState = new bool[MAX_SIZE]; // For Visited Nodes;
for(int i = 0;i<MAX_SIZE;i++)
nodeState[i] = 0;
while(!q.empty())
{
int vertex = q.front();
q.pop();
if(verifyValidLocation(vertex,MAX_SIZE) || nodeState[vertex])
{
continue;
}
nodeState[vertex] = true;
int above, below, left, right;
above = vertex + WIDTH;
below = vertex - WIDTH;
left = vertex - 1;
right = vertex + 1;
if((vertex >= (WIDTH) && !nodeState[below]) && !verifyValidLocation(below, MAX_SIZE))
{
graph.addEdge(vertex, below);
q.push(below);
}
if((vertex <= (MAX_SIZE - WIDTH) && !nodeState[above]) && !verifyValidLocation(above, MAX_SIZE))
{
graph.addEdge(vertex, above);
q.push(above);
}
if(((vertex % WIDTH) != 0 && !nodeState[left]) && !verifyValidLocation(left, MAX_SIZE))
{
graph.addEdge(vertex, left);
q.push(left);
}
if(((vertex % WIDTH) != (WIDTH-1) && !nodeState[right]) && !verifyValidLocation(right, MAX_SIZE))
{
graph.addEdge(vertex, right);
q.push(right);
}
}
return graph;
}
void setupBreadthFirstSearchTest()
{
bfsGraph = generateGraphFromSource(bfsGraph, 4);
}
void checkEdgeValuesValid()
{
typedef set<int> EDGES;
EDGES getEdges;
getEdges = bfsGraph.verticies.at(13);
EDGES::iterator getEdgesIter;
std::cout << "Checking the node paths: " << endl;
for(getEdgesIter=getEdges.begin(); getEdgesIter!=getEdges.end();getEdgesIter++)
{
std::cout << "13," << *getEdgesIter << endl;
}
getEdgesIter = getEdges.find(12);
ASSERT(getEdgesIter!=getEdges.end());
//Check edges 17,22 & 17,16
getEdges = bfsGraph.verticies.at(17);
std::cout << "Checking the node paths: " << endl;
for(getEdgesIter=getEdges.begin(); getEdgesIter!=getEdges.end();getEdgesIter++)
{
std::cout << "17," << *getEdgesIter << endl;
}
getEdgesIter = getEdges.find(16);
ASSERT(getEdgesIter!=getEdges.end());
}
void validateDistanceToDestinationFromSource(int source, int dest, int gridWidth, int gridHeight)
{
Graph thisGraph(gridWidth * gridHeight);
thisGraph = generateGraphFromSource(thisGraph, source);
}
void BreadthFirstSearchTest::runBFSSuite(){
cute::suite s;
//TODO add your test here
setupBreadthFirstSearchTest();
s.push_back(CUTE(checkEdgeValuesValid));
cute::ide_listener lis;
cute::makeRunner(lis)(s, "BreadthFirstSearch Suite");
}
BreadthFirstSearchTest::BreadthFirstSearchTest()
{
;
}
| [
"[email protected]"
]
| [
[
[
1,
143
]
]
]
|
fe31ada9aba7bdc01810893f7bc0daaf57bce989 | 7e6387a7495e89ec42acc99ea6d8736a69d96d72 | /guiCode/guiVisualizePage.cpp | a97a7716c8a49194de8139e16780865856596cba | []
| no_license | erkg/virtualflowlab | 2a491d71fdf8e7db6dab243560fadbb8cd731943 | a540d4ecd076327f98cb7e3044422e7b4d33efbb | refs/heads/master | 2016-08-11T07:12:51.924920 | 2010-07-22T14:40:24 | 2010-07-22T14:40:24 | 55,049,199 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,446 | cpp | #include <QtGui>
#include <math.h>
#include <iomanip>
#include <fstream>
#include "mainWindow.h"
#include "glwidget.h"
#include "guiConvergencePlot.h"
#include "guiTypedefs.h"
#include "guiProblem.h"
#include "../guiCode/guiSolverThread.h"
extern Problem *problem;
void mainWindow::postProcessTabSelection (QWidget * w)
{
int i;
i = postProcessTab->currentIndex();
if (i == 0) { // Contour Page
visualizeContourButton->setChecked(true);
problem->setvisualizeState(SELECT);
} else if (i == 1) { // Streamline Page
visualizeStreamlineButton->setChecked(true);
problem->setvisualizeState(ADDSTREAMLINE);
} else if (i == 2) { // Probe Page
visualizeProbeButton->setChecked(true);
problem->setvisualizeState(PROBE);
}
} // End of postProcessTabSelection
void mainWindow::openResultFile()
{
int i, j, dummyNstreamlines;
float **firstPointCoor;
if (problem->getCfdFileName() == "") { // Do not open any result file if the problem is not saved.
appendMessage(tr("WARNING: First you need to save the problem you are working on or open a previously created problem."), Qt::black);
return;
}
QString dir = QString(problem->getDir().c_str());
QString fileName = QFileDialog::getOpenFileName(this, tr("Open Result File"), dir, tr("Problem Files (*.dat)"));
if (!fileName.isEmpty()){
QFileInfo file( fileName );
string dir = file.absolutePath().toStdString();
string baseName = file.completeBaseName().toStdString();
problem->setResultFileName(dir + "/" + baseName + ".dat"); // e.g. C:\VFL\Problems\MyProblem_100.dat
appendMessage(tr("Result file is opened."), Qt::black);
readResultFile();
if (retainStyleCheck->isChecked() ) {
// Recreate all the existing streamlines. This can be done in a separate function
// Copy the starting points of the streamlines
firstPointCoor = new float*[problem->nStreamlines];
for(i=0; i<problem->nStreamlines; i++) firstPointCoor[i] = new float[2];
for(i=0; i<problem->nStreamlines; i++) {
firstPointCoor[i][0] = problem->streamlines[i].coor[0][0];
firstPointCoor[i][1] = problem->streamlines[i].coor[0][1];
}
dummyNstreamlines = problem->nStreamlines;
clearAllStreamlinesButtonClicked();
// Redraw the streamlines
for(i=0; i<dummyNstreamlines; i++) {
addStreamline(firstPointCoor[i][0], firstPointCoor[i][1]);
}
for(j=0; j<problem->nStreamlines; j++) delete[] firstPointCoor[j];
delete[] firstPointCoor;
} else {
boundaryCheckBox->setChecked(TRUE);
meshCheckBox->setChecked(FALSE);
contourCheckBox->setChecked(TRUE);
streamlineCheckBox->setChecked(FALSE);
problem->showBoundary = TRUE;
problem->showMesh = FALSE;
problem->showContour = TRUE;
problem->showStreamline = FALSE;
clearAllStreamlinesButtonClicked();
}
}
glWidget->update();
} // End of function openResultFile()
void mainWindow::readResultFile()
{
// Cuneyt: No multi-block support.
// This creates the .DAT file generated by the solver.
// .DAT file is written in Tecplot format. It has the following variables
// x, y, u, v, p, u_res, v_res, p_res, vorticity
int i, j, nX, nY;
double d1, d2;
ifstream outFile;
nX = problem->mesh->blocks[0].getnXpoints();
nY = problem->mesh->blocks[0].getnYpoints();
// Deallocate and allocate necessary matrices
if (problem->uResult != NULL) {
for(i=0; i<nX; i++) delete[] problem->uResult[i];
delete[] problem->uResult;
problem->uResult = NULL;
for(i=0; i<nX; i++) delete[] problem->vResult[i];
delete[] problem->vResult;
problem->vResult = NULL;
for(i=0; i<nX; i++) delete[] problem->pResult[i];
delete[] problem->pResult;
problem->pResult = NULL;
}
problem->uResult = new double*[nX];
for(i=0; i<nX; i++) problem->uResult[i] = new double[nY];
problem->vResult = new double*[nX];
for(i=0; i<nX; i++) problem->vResult[i] = new double[nY];
problem->pResult = new double*[nX];
for(i=0; i<nX; i++) problem->pResult[i] = new double[nY];
// Start reading the .DAT file
outFile.open(problem->getResultFileName().c_str(), ios::in);
// Read and ignore the file header
outFile.ignore(256, '\n');
outFile.ignore(256, '\n');
outFile.ignore(256, '\n');
for (j = 0; j < nY; j++) {
for (i = 0; i < nX; i++) {
outFile >> d1 >> d2 >> problem->uResult[i][j] >> problem->vResult[i][j] >> problem->pResult[i][j];
outFile.ignore(256, '\n');
}
}
} // End of function readResultFile()
void mainWindow::showContoursButtonClicked()
{
contourCheckBox->setChecked(true);
glWidget->update();
}
void mainWindow::visualizeChecksToggled()
{
problem->showBoundary = boundaryCheckBox->isChecked();
problem->showMesh = meshCheckBox->isChecked();
problem->showContour = contourCheckBox->isChecked();
problem->showStreamline = streamlineCheckBox->isChecked();
glWidget->update();
}
void mainWindow::contourVarChanged(int i)
{
problem->contourVar = i;
glWidget->update();
}
void mainWindow::contourStyleChanged(int i)
{
problem->contourStyle = i;
glWidget->update();
}
void mainWindow::colorMapChanged(int i)
{
problem->colorMap = i;
glWidget->update();
}
void mainWindow::contourLevelChanged(const QString & str)
{
problem->nContourLevels = str.toInt();
}
void mainWindow::visualizeButtonsClicked()
{
// Shows the corresponding page of the postProcessTab when a button is pressed.
// Sets the visualizeState variable.
if (visualizeContourButton->isChecked()) {
postProcessTab->setCurrentIndex(0);
problem->setvisualizeState(SELECT);
} else if (visualizeStreamlineButton->isChecked()) {
postProcessTab->setCurrentIndex(1);
problem->setvisualizeState(ADDSTREAMLINE);
} else if (visualizeProbeButton->isChecked()) {
postProcessTab->setCurrentIndex(2);
problem->setvisualizeState(PROBE);
//} else if (visualizeDataExtractButton->isChecked()) {
// // ...
// // problem->setvisualizeState(DATAEXTRACT);
} else if (visualizeSelectButton->isChecked()) {
problem->setvisualizeState(SELECT);
} else {
visualizeSelectButton->setChecked(TRUE);
problem->setvisualizeState(SELECT);
}
} // End of function visualizeButtonsClicked()
void mainWindow::probeButtonClicked()
{
float x, y;
int b, c1, I, J, nX, nY;
if (problem->getResultFileName() == "") // Do nothing if a result file is not opened.
return;
if (probeX->text().isEmpty() || probeY->text().isEmpty() )
return;
if (probeXYradio->isChecked()) { // Probe at given (x,y) coordinates
x = probeX->text().toFloat();
y = probeY->text().toFloat();
probeAtPosition(x, y);
} else { // Probe at given (I,J) indices
I = probeX->text().toInt();
J = probeY->text().toInt();
b = 0; // Cuneyt: No multi-block support.
nX = problem->mesh->blocks[b].getnXpoints();
nY = problem->mesh->blocks[b].getnYpoints();
if (I<1 || I>nX || J<1 || J>nY) { // I, J indices are outside the range
// Cuneyt: A warning message can be provided to remind nX and nY.
probeResultX->setText("");
probeResultY->setText("");
probeResultU->setText("");
probeResultV->setText("");
probeResultP->setText("");
return;
} else {
// Find the corresponding x and y
c1 = (J-1) * nX + (I-1);
x = problem->mesh->blocks[b].coordinates[2*c1];
y = problem->mesh->blocks[b].coordinates[2*c1+1];
probeAtPosition(x, y);
}
}
} // End of function probeButtonClicked()
void mainWindow::probeAtPosition(float x, float y)
{
int b, cell, i, iCell, jCell, nX, nY;
double var[3][4]; // u, v, p values at the 4 corners of a cell.
double interpolation[3]; // u, v, p interpolation at point (x,y).
float **cornerCoor; // Corner coordinates of a cell
// First find in which cell the point (x,y) lies in
b = 0; // Cuneyt: No multi-block support
nX = problem->mesh->blocks[b].getnXpoints();
nY = problem->mesh->blocks[b].getnYpoints();
cornerCoor = new float*[4];
for(i=0; i<4; i++) cornerCoor[i] = new float[2];
// Find in which cell the point (x,y) lies in
cell = problem->mesh->blocks[b].findCellAtXY(x, y, iCell, jCell, cornerCoor);
// Cuneyt: isCellFound can be set to FALSE if point (x,y) is inside ablcoked cell.
if (cell > -1 && !problem->mesh->blocks[b].isCellBlocked[cell]) { // If a non-blocked cell is found
// Now we can interpolate for the variables at (x,y). Perform bi-linear interpolation.
// Get the variables at the 4 corners of this cell
var[0][0] = problem->uResult[iCell][jCell];
var[0][1] = problem->uResult[iCell+1][jCell];
var[0][2] = problem->uResult[iCell+1][jCell+1];
var[0][3] = problem->uResult[iCell][jCell+1];
var[1][0] = problem->vResult[iCell][jCell];
var[1][1] = problem->vResult[iCell+1][jCell];
var[1][2] = problem->vResult[iCell+1][jCell+1];
var[1][3] = problem->vResult[iCell][jCell+1];
var[2][0] = problem->vResult[iCell][jCell];
var[2][1] = problem->vResult[iCell+1][jCell];
var[2][2] = problem->vResult[iCell+1][jCell+1];
var[2][3] = problem->vResult[iCell][jCell+1];
// Cuneyt: All the cells are assumed to be Cartesian.
// First interpolate in the x direction
for (i=0; i<3; i++) {
// double fR1 = ( (cornerCoor[1][0]-x)*var[i][0] + (x-cornerCoor[0][0])*var[i][1] ) / (cornerCoor[1][0]-cornerCoor[0][0]);
// double fR2 = ( (cornerCoor[1][0]-x)*var[i][3] + (x-cornerCoor[0][0])*var[i][2] ) / (cornerCoor[1][0]-cornerCoor[0][0]);
// Now interpolate in the y direction
//double fP = ( (cornerCoor[2][1]-y)*fR1 + (y-cornerCoor[0][1])*fR2 ) / (cornerCoor[2][1]-cornerCoor[0][1]);
// Now calculate the interpolated value.
interpolation[i] = (var[i][0]*(cornerCoor[1][0]-x)*(cornerCoor[2][1]-y) + var[i][1]*(x-cornerCoor[0][0])*(cornerCoor[2][1]-y) +
var[i][3]*(cornerCoor[1][0]-x)*(y-cornerCoor[0][1]) + var[i][2]*(x-cornerCoor[0][0])*(y-cornerCoor[0][1])) /
((cornerCoor[1][0]-cornerCoor[0][0])*(cornerCoor[2][1]-cornerCoor[0][1]));
}
// Now show the results of probing inside the proper text boxes.
probeResultX->setText(QString("%1").arg(x));
probeResultY->setText(QString("%1").arg(y));
probeResultU->setText(QString("%1").arg(interpolation[0]));
probeResultV->setText(QString("%1").arg(interpolation[1]));
probeResultP->setText(QString("%1").arg(interpolation[2]));
} else {
// Probed point is not inside the problem domain.
probeResultX->setText(QString("%1").arg(x));
probeResultY->setText(QString("%1").arg(y));
probeResultU->setText("");
probeResultV->setText("");
probeResultP->setText("");
}
} // End of function probeAtPosition()
void mainWindow::probeRadioButtonsToggled(bool flag)
{
if (flag) {
probeXlabel->setText("x");
probeYlabel->setText("y");
} else {
probeXlabel->setText("I");
probeYlabel->setText("J");
}
}
void mainWindow::addStreamline(float x, float y)
{
int b, i, k, nS, nX, nY;
int cell, iCell, jCell, neighborCells[9], pointCounter;
double dx, dy, theta, distance;
double var[2][4]; // u, v values at the 4 corners of a cell.
double speed[2]; // u, v interpolation at point (x,y).
float **dummyCoor;
float **cornerCoor; // Corner coordinates of a cell
nS = problem->nStreamlines; // Shortcut
if (nS == MAX_STREAMLINES) return; // No more streamline can be added.
double stepSize = streamlineStepSizeEdit->text().toDouble(); // Step size for integration (% of the cell size)
int nMaxSteps = streamlineMaxStepsEdit->text().toInt(); // Upper limit of integration steps
pointCounter = 0;
b = 0; // Cuneyt: No multi-block support
nX = problem->mesh->blocks[b].getnXpoints();
nY = problem->mesh->blocks[b].getnYpoints();
dummyCoor = new float*[nMaxSteps];
for(i=0; i<nMaxSteps; i++) dummyCoor[i] = new float[2];
dummyCoor[0][0] = x;
dummyCoor[0][1] = y;
cornerCoor = new float*[4];
for(i=0; i<4; i++) {
cornerCoor[i] = new float[2];
}
for(i=0; i<9; i++) {
neighborCells[i] = -1;
}
for (k=1; k<nMaxSteps; k++) {
// First find in which cell the point (x,y) lies in
cell = problem->mesh->blocks[b].isXYinNeighbors(x, y, iCell, jCell, cornerCoor, neighborCells);
if (cell == -1)
cell = problem->mesh->blocks[b].findCellAtXY(x, y, iCell, jCell, cornerCoor);
if (cell == -1) { // If no cell was found, it means the streamline reached to a point outside the problem domain. STOP.
break; // Exit the k loop
} else if (problem->mesh->blocks[b].isCellBlocked[cell]) { // If cell is a blocked cell STOP.
break; // Exit k loop
}
// Now we can interpolate for the variables at (x,y). Perform bi-linear interpolation.
// Get the variables at the 4 corners of this cell
var[0][0] = problem->uResult[iCell][jCell];
var[0][1] = problem->uResult[iCell+1][jCell];
var[0][2] = problem->uResult[iCell+1][jCell+1];
var[0][3] = problem->uResult[iCell][jCell+1];
var[1][0] = problem->vResult[iCell][jCell];
var[1][1] = problem->vResult[iCell+1][jCell];
var[1][2] = problem->vResult[iCell+1][jCell+1];
var[1][3] = problem->vResult[iCell][jCell+1];
// Cuneyt: All the cells are assumed to be Cartesian.
// First interpolate in the x direction
for (i=0; i<2; i++) {
// double fR1 = ( (cornerCoor[1][0]-x)*var[i][0] + (x-cornerCoor[0][0])*var[i][1] ) / (cornerCoor[1][0]-cornerCoor[0][0]);
// double fR2 = ( (cornerCoor[1][0]-x)*var[i][3] + (x-cornerCoor[0][0])*var[i][2] ) / (cornerCoor[1][0]-cornerCoor[0][0]);
// Now interpolate in the y direction
//double fP = ( (cornerCoor[2][1]-y)*fR1 + (y-cornerCoor[0][1])*fR2 ) / (cornerCoor[2][1]-cornerCoor[0][1]);
// Now calculate the interpolated value.
speed[i] = (var[i][0]*(cornerCoor[1][0]-x)*(cornerCoor[2][1]-y) + var[i][1]*(x-cornerCoor[0][0])*(cornerCoor[2][1]-y) +
var[i][3]*(cornerCoor[1][0]-x)*(y-cornerCoor[0][1]) + var[i][2]*(x-cornerCoor[0][0])*(y-cornerCoor[0][1])) /
((cornerCoor[1][0]-cornerCoor[0][0])*(cornerCoor[2][1]-cornerCoor[0][1]));
}
// if (speed[0] == 0.0 && speed[1] == 0.0) {
// break; // Streamline reached to a wall. Stop.
// }
// Let's find the location of the next point of the streamline.
// We know that next point is stepSize*cellSize away from point(x,y).
// Cuneyt: Cells are assumed to be Cartesian.
distance = stepSize * min(fabs(cornerCoor[1][0]-cornerCoor[0][0]), fabs(cornerCoor[2][1]-cornerCoor[0][1]));
// Its exact location is found from the direction of the speed vector.
theta = atan2(fabs(speed[1]), fabs(speed[0]));
dx = distance / sqrt(1 + tan(theta)*tan(theta));
dy = dx * tan(theta);
if (speed[0] >= 0) x = x + dx;
else x = x - dx;
if (speed[1] >= 0) y = y + dy;
else y = y - dy;
pointCounter = pointCounter + 1;
dummyCoor[pointCounter][0] = x;
dummyCoor[pointCounter][1] = y;
// Let's find the neighbors of the "cell". Most probably the next point of the streamline is located in one these neighbors.
// Note that for convenience cell itself is considered to be one of the neighbors.
// If a neighbor is -1, it means it is either outside the problem domain or it is a blocked cell.
neighborCells[0] = cell;
neighborCells[1] = cell + 1; // Right neighbor
neighborCells[2] = cell - 1; // Left neighbor
neighborCells[3] = cell + nX; // Top neighbor
neighborCells[4] = cell - nX; // Bottom neighbor
neighborCells[5] = cell + nX + 1; // Top-right neighbor
neighborCells[6] = cell + nX - 1; // Top-left neighbor
neighborCells[7] = cell - nX + 1; // Bottom-right neighbor
neighborCells[8] = cell - nX - 1; // Bottom-left neighbor
// Correct the neighbors that should actually fall outside the problem domain
if (cell < nX-1) { // cell is located at the bottom boundary
neighborCells[4] = -1;
neighborCells[7] = -1;
neighborCells[8] = -1;
}
if (cell > (nX-1)*(nY-1)-nX) { // cell is located at the top boundary
neighborCells[3] = -1;
neighborCells[5] = -1;
neighborCells[6] = -1;
}
if (cell % (nX-1) == 0) { // cell is located at the left boundary
neighborCells[2] = -1;
neighborCells[6] = -1;
neighborCells[8] = -1;
}
if ((cell+1) % (nX-1) == 0) { // cell is located at the right boundary
neighborCells[1] = -1;
neighborCells[5] = -1;
neighborCells[7] = -1;
}
}
if (pointCounter > 0) { // Add this streamline
// Allocate space for the streamline coordinates
problem->streamlines[nS].coor = new float*[pointCounter];
for(i=0; i<pointCounter; i++) problem->streamlines[nS].coor[i] = new float[2];
// Copy dummyCoor to streamline coordinates
for(i=0; i<pointCounter; i++) {
problem->streamlines[nS].coor[i][0] = dummyCoor[i][0];
problem->streamlines[nS].coor[i][1] = dummyCoor[i][1];
}
problem->streamlines[nS].nPoints = pointCounter;
problem->nStreamlines = problem->nStreamlines + 1;
if (!streamlineCheckBox->isChecked()) emit streamlineCheckBox->click();
}
// Deallocate dummyCoor
for(i=0; i<nMaxSteps; i++) delete[] dummyCoor[i];
delete[] dummyCoor;
for(i=0; i<4; i++) delete[] cornerCoor[i];
delete[] cornerCoor;
} // End of function addStreamline()
void mainWindow::placeStreamlineRadioButtonsToggled(bool flag)
{
if (placeStreamlineXYradio->isChecked()) {
streamlineXlabel->setText("x");
streamlineYlabel->setText("y");
} else {
streamlineXlabel->setText("I");
streamlineYlabel->setText("J");
}
}
void mainWindow::clearAllStreamlinesButtonClicked()
{
int i, j;
// Delete streamline coordinates
for(i=0; i<problem->nStreamlines; i++) {
for(j=0; j<problem->streamlines[i].nPoints; j++) delete[] problem->streamlines[i].coor[j];
delete[] problem->streamlines[i].coor;
}
problem->nStreamlines = 0;
glWidget->update();
}
void mainWindow::clearTheLastStreamlineButtonClicked()
{
int i, j;
if (problem->nStreamlines == 0) return; // There is no streamline to erase.
// Delete the streamline coordinates
i = problem->nStreamlines - 1;
for(j=0; j<problem->streamlines[i].nPoints; j++) delete[] problem->streamlines[i].coor[j];
delete[] problem->streamlines[i].coor;
problem->nStreamlines = problem->nStreamlines - 1;
glWidget->update();
}
void mainWindow::placeStreamlineButtonClicked()
{
float x, y;
int b, c1, I, J, nX, nY;
if (problem->getResultFileName() == "") // Do nothing if a result file is not opened.
return;
if (placeStreamlineXedit->text().isEmpty() || placeStreamlineYedit->text().isEmpty() )
return;
if (placeStreamlineXYradio->isChecked()) { // Place the streamline at given (x,y) coordinates
x = placeStreamlineXedit->text().toFloat();
y = placeStreamlineYedit->text().toFloat();
addStreamline(x, y);
} else { // Place the streamline at given (I,J) indices
I = placeStreamlineXedit->text().toInt();
J = placeStreamlineYedit->text().toInt();
b = 0; // cuneyt: Multi-block destegi yok.
nX = problem->mesh->blocks[b].getnXpoints();
nY = problem->mesh->blocks[b].getnYpoints();
if (I<1 || I>nX || J<1 || J>nY) { // I, J indices are outside the range
// cuneyt: nX ve nY'yi hatirlatan bir uyari vermek gerek.
return;
} else {
// Find the corresponding x and y
c1 = (J-1) * nX + (I-1);
x = problem->mesh->blocks[b].coordinates[2*c1];
y = problem->mesh->blocks[b].coordinates[2*c1+1];
addStreamline(x, y);
}
}
streamlineCheckBox->setChecked(true);
glWidget->update();
} // End of function placeStreamlineButtonClicked()
| [
"cuneytsert@76eae623-603d-0410-ac33-4f885805322a"
]
| [
[
[
1,
630
]
]
]
|
0b250058d07f5705e7fda61f022cac7d365d58bb | 854780006deb64b27d25ea852114c7def4d29dc4 | /rapidjson/test/perftest/perftest.h | 1790a7a5c8be7ff18cece6ecccbfab1a8178d620 | [
"MIT"
]
| permissive | lloyd/yajl_vs_rapidjson | 30b705ee9eab0cad3f87816efb66f729f96a54e4 | 1f7014157099a98f0a732d13c7ce39e21ee25c3a | refs/heads/master | 2023-08-19T18:03:10.315441 | 2011-11-20T04:10:47 | 2011-11-20T04:10:47 | 2,811,884 | 6 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,712 | h | #ifndef PERFTEST_H_
#define PERFTEST_H_
#define TEST_RAPIDJSON 1
#define TEST_JSONCPP 1
#define TEST_YAJL 1
#if TEST_RAPIDJSON
//#define RAPIDJSON_SSE2
//#define RAPIDJSON_SSE42
#endif
#if TEST_YAJL
#include "yajl/yajl_common.h"
#undef YAJL_MAX_DEPTH
#define YAJL_MAX_DEPTH 1024
#endif
////////////////////////////////////////////////////////////////////////////////
// Google Test
#ifdef __cplusplus
#include "gtest/gtest.h"
#ifdef _MSC_VER
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#pragma warning(disable : 4996) // 'function': was declared deprecated
#endif
//! Base class for all performance tests
class PerfTest : public ::testing::Test {
public:
virtual void SetUp() {
FILE *fp = fopen("data/sample.json", "rb");
if (!fp)
fp = fopen("../../bin/data/sample.json", "rb");
ASSERT_TRUE(fp != 0);
fseek(fp, 0, SEEK_END);
length_ = (size_t)ftell(fp);
fseek(fp, 0, SEEK_SET);
json_ = (char*)malloc(length_ + 1);
fread(json_, 1, length_, fp);
json_[length_] = '\0';
length_++; // include the null terminator
fclose(fp);
// whitespace test
whitespace_length_ = 1024 * 1024;
whitespace_ = (char *)malloc(whitespace_length_ + 4);
char *p = whitespace_;
for (size_t i = 0; i < whitespace_length_; i += 4) {
*p++ = ' ';
*p++ = '\n';
*p++ = '\r';
*p++ = '\t';
}
*p++ = '[';
*p++ = '0';
*p++ = ']';
*p++ = '\0';
}
virtual void TearDown() {
free(json_);
free(whitespace_);
}
protected:
char *json_;
size_t length_;
char *whitespace_;
size_t whitespace_length_;
static const size_t kTrialCount = 1000;
};
#endif // __cplusplus
#endif // PERFTEST_H_
| [
"[email protected]"
]
| [
[
[
1,
82
]
]
]
|
2429670078da01957eda28954629f283cdb9c056 | 2b32433353652d705e5558e7c2d5de8b9fbf8fc3 | /Dm_new_idz/Mlita/Graph.cpp | 94846b704ee08679cd88d583b9fc87a7b6dbff5d | []
| no_license | smarthaert/d-edit | 70865143db2946dd29a4ff52cb36e85d18965be3 | 41d069236748c6e77a5a457280846a300d38e080 | refs/heads/master | 2020-04-23T12:21:51.180517 | 2011-01-30T00:37:18 | 2011-01-30T00:37:18 | 35,532,200 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 2,381 | cpp | // Graph.cpp: implementation of the CGraph class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
//#include "Exam.h"
#include "Graph.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
int Random(int n)
{
return rand() % n +1;
}
CGraph::CGraph()
{
m_V = 0;
m_E = 0;
m_Style = 0;
}
CGraph::CGraph(int Tops,int Edges, int Style )
{
m_V = Tops;
m_E = 0;
m_Style = Style;
Init();
Generate(Tops,Edges);
}
CGraph::~CGraph()
{
// DestroyGraph();
}
//DEL void CGraph::DestroyGraph()
//DEL {
//DEL }
int CGraph::Generate(int VC, int EC)
{ // Graph must be initialized!!! no checking!
if (m_Style & Gr_Bounds) // связанный
{
int r,d;
bool been[MaxTops];
for (int i=0; i<MaxTops; i++) been[i] = false;
int Start=r=Random(VC);
for (i=0; i<VC-1; i++)
{
do
{
d=Random(VC);
}
while ( d==Start || been[d]);
been[d] = true;
AddEdge(r,d);
r=d;
}
AddEdge(d,Start);
}
while (m_E != EC)
{
int r=Random(VC);
int s=Random(VC);
if (!(m_Style & Gr_HasCycles) && !IsCycleForm(r,s)) if (!IsLinked(r,s) && r!=s) AddEdge(r,s);
}
return 0;
}
void CGraph::Init()
{
// DeInit();
for (int i=0; i<=m_V*m_V; i++)
for (int j=0; j<=m_V; j++) M[i][j]=C[i][j]=0;
}
//DEL void CGraph::DeInit()
//DEL {
//DEL // if (C) free(C);
//DEL // if (H) free(H);
//DEL // if (M) free(M);
//DEL }
bool CGraph::IsLinked(int i, int j)
{
if (i==j) return 1;
if (m_Style & Gr_Oriented)
return M[i][j];
else
return M[i][j]||M[j][i];
}
int CGraph::AddEdge(int i, int j)
{
int Ret = 0;
Ret = M[i][j]+M[j][i];
E[m_E].i=i;
E[m_E].j=j;
M[i][j] = 1;
if (m_Style & Gr_Oriented) ; else M[j][i] = 1;
if (m_Style & Gr_Fluidized)
{
C[i][j] = Random(MAXCOST);
if (!(m_Style & Gr_Positive)) C[i][j] =C[i][j] - MAXCOST /2;
if (m_Style & Gr_Oriented) C[j][i] = LARGECOST; else C[j][i] = C[i][j];
}
if (!Ret) m_E++;
return Ret;
}
Edge CGraph::GetEdge(int i)
{
return E[i];
}
bool CGraph::IsCycleForm(int r, int s)
{
return false;
}
| [
"[email protected]"
]
| [
[
[
1,
133
]
]
]
|
46278891f37f2d35b9a8743f219086f28b9f3a4e | 0cc80cab288248cd9c3a2cc922487ac2afd5148c | /tu_quoque/tu_quoque/BasicTypes.hpp | 6aa19b9bcb58c412aa9dd471d742c969a1370193 | []
| no_license | WestleyArgentum/tu-quoque | a3fbdb37dfebe9e9f0b00254144a48fdee89e946 | 38f661a145916768727b1a6fb7df5aa37072b6d2 | refs/heads/master | 2021-01-02T08:57:39.513862 | 2011-02-20T05:56:36 | 2011-02-20T05:56:36 | 33,832,399 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,230 | hpp | /******************************************************************************/
/*!
\file BasicTypes.hpp
\author Chris Barrett
\brief
BasicTypes declarations.
Copyright (C) 2009 DigiPen Institute of Technology.
Reproduction or disclosure of this file or its contents without the
prior written consent of DigiPen Institute of Technology is prohibited.
*/
/******************************************************************************/
#pragma once
#ifndef BASIC_TYPES_HPP_
#define BASIC_TYPES_HPP_
//#include "MFCoreConfig.hpp"
//#ifdef MFCORE_BASIC_TYPES_INCLUDES_STRING_
#include <string>
//#endif
namespace MFCore
{
typedef bool B8;// 8 bits under Microsoft
typedef signed char I8;
typedef unsigned char U8;
typedef short I16;
typedef unsigned short U16;
typedef int I32;
typedef unsigned int U32;
typedef long long I64;
typedef unsigned long long U64;
typedef float F32;
typedef double F64;
#ifdef MFCORE_BASIC_TYPES_INCLUDES_STRING_
typedef std::string STRING;
#endif
}
using namespace MFCore;
#endif // ndef BASIC_TYPES_HPP_
| [
"westleyargentum@259acd2b-3792-e4e4-6ce2-44c093ac8a23"
]
| [
[
[
1,
52
]
]
]
|
081416fafc6fbdba0504a92f3a30f4fa56c99b10 | a30b091525dc3f07cd7e12c80b8d168a0ee4f808 | /EngineAll/Victor/GMRES.cpp | 1790b76b8112c688b7a93d1d7c79076febd6b892 | []
| 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 | 4,613 | cpp | #include <cstddef>
#include <cmath>
#include <complex>
#include <iostream>
#include "TBLAS.h"
#include "TLASupport.h"
#include "LinearSolve.h"
#include "IterativeLinearSolvers.h"
// Implementation of GMRES - Generalized Minimum Residual
void RNP::GMRES_alloc(size_t n, const GMRES_params ¶ms, LinearSolverWorkspace *workspace){
if(NULL == workspace){ return; }
const size_t m = params.m;
workspace->zwork = new std::complex<double>[(2+m+n)*(m+1)+m];
workspace->rwork = new double[m];
}
void RNP::GMRES_free(size_t n, const GMRES_params ¶ms, LinearSolverWorkspace *workspace){
if(NULL == workspace){ return; }
if(NULL != workspace->zwork){ delete [] workspace->zwork; workspace->zwork = NULL; }
if(NULL != workspace->rwork){ delete [] workspace->rwork; workspace->rwork = NULL; }
}
int RNP::GMRES(
const size_t n,
// A is a function which multiplies the matrix by the first argument
// and returns the result in the second. The second argument must
// be manually cleared. The third parameter is user data, passed in
// through Adata.
void (*A)(const std::complex<double>*, std::complex<double>*, void*),
std::complex<double>* b,
std::complex<double>* x,
RNP::LinearSolverParams &ls_params,
const RNP::GMRES_params ¶ms,
// Optional parameters
RNP::LinearSolverWorkspace *workspace,
//std::complex<double> *work, // if not null, should be length (2+m+n)*(m+1)+m, m = params.m
//double *rwork, // if not null, should be length params.m
void *Adata,
// P is a precondition which simply solves P*x' = x,
// where x i the first argument. The second parameter is user data,
// which is passed in through Pdata.
void (*P)(std::complex<double>*, void*),
void *Pdata
){
const size_t mxm = params.m;
// Set initial x
if(!ls_params.x_initialized){
for(size_t i = 0; i < n; ++i){ x[i] = 0; }
}
if(NULL != P){ P(b, Pdata); }
RNP::LinearSolverWorkspace *_work = workspace;
if(NULL == workspace){
_work = new RNP::LinearSolverWorkspace();
RNP::GMRES_alloc(n, params, _work);
}
double *cs = _work->rwork;
std::complex<double> *sn = _work->zwork; // length mxm
std::complex<double> *rs = sn + mxm; // length mxm+1
std::complex<double> *y = rs + mxm+1; // length mxm+1
std::complex<double> *v = y + mxm+1; // length n*(mxm+1)
std::complex<double> *hh = v + n*(mxm+1); // length mxm*(mxm+1)
double rnrm0 = RNP::TBLAS::Norm2(n, b, 1);
double rnrm = rnrm0;
double eps1 = ls_params.tol * rnrm;
RNP::TBLAS::Copy(n, b, 1, &v[0+0*n], 1);
size_t iter = 0;
size_t num_multmv = 0;
size_t maxit = ls_params.max_iterations;
if(0 == maxit){
maxit = 2*n;
if(1000 < maxit){ maxit = 1000; }
}
if(0 == ls_params.max_mult){ ls_params.max_mult = (size_t)-1; }
// iteration
while(num_multmv <= ls_params.max_mult && iter <= maxit && rnrm > eps1){
RNP::TBLAS::Scale(n, 1./rnrm, &v[0+0*n], 1);
rs[0] = rnrm;
size_t m = 0;
while(m < mxm && rnrm > eps1 && num_multmv <= ls_params.max_mult){
A(&v[0+m*n], &v[0+(m+1)*n], Adata); ++num_multmv;
if(NULL != P){ P(&v[0+(m+1)*n], Pdata); }
for(size_t i = 0; i <= m; ++i){
hh[i+m*(mxm+1)] = RNP::TBLAS::ConjugateDot(n, &v[0+i*n], 1, &v[0+(m+1)*n], 1);
RNP::TBLAS::Axpy(n, -hh[i+m*(mxm+1)], &v[0+i*n], 1, &v[0+(m+1)*n], 1);
}
hh[m+1+m*(mxm+1)] = RNP::TBLAS::Norm2(n, &v[0+(m+1)*n], 1);
RNP::TBLAS::Scale(n, 1./hh[m+1+m*(mxm+1)], &v[0+(m+1)*n], 1);
for(size_t i = 0; i < m; ++i){
RNP::TLASupport::ApplyPlaneRotation(1, &hh[i+m*(mxm+1)], 1, &hh[i+1+m*(mxm+1)], 1, cs[i], sn[i]);
}
std::complex<double> rcs;
RNP::TLASupport::GeneratePlaneRotation(hh[m+m*(mxm+1)], hh[m+1+m*(mxm+1)], &cs[m], &sn[m], &rcs);
hh[m+m*(mxm+1)] = rcs;
hh[m+1+m*(mxm+1)] = 0;
rs[m+1] = 0;
RNP::TLASupport::ApplyPlaneRotation(1, &rs[m], 1, &rs[m+1], 1, cs[m], sn[m]);
rnrm = std::abs(rs[m+1]);
++m;
}
// compute approximate solution x
RNP::TBLAS::Copy(m, rs, 1, y, 1);
RNP::TBLAS::SolveTrV<'U','N','N'>(m, hh, mxm+1, y, 1);
RNP::TBLAS::MultMV<'N'>(n, m, 1., v, n, y, 1, 1., x, 1);
// compute residual for restart
A(x, &v[0+1*n], Adata);
if(NULL != P){ P(&v[0+1*n], Pdata); }
RNP::TBLAS::Copy(n, b, 1, &v[0+0*n], 1);
RNP::TBLAS::Axpy(n, -1., &v[0+1*n], 1, &v[0+0*n], 1);
rnrm = RNP::TBLAS::Norm2(n, &v[0+0*n], 1);
++iter;
}
ls_params.max_iterations = iter;
ls_params.tol = rnrm / rnrm0;
ls_params.max_mult = num_multmv;
if(NULL == workspace){
RNP::GMRES_free(n, params, _work);
delete _work;
}
return 0;
}
| [
"zhaodongmpii@7e7f00ea-7cf8-66b5-cf80-f378872134d2"
]
| [
[
[
1,
133
]
]
]
|
8a5b608066ef211ea3eb2c63c3537731dbbd34a0 | 57855d23617d6a65298c2ae3485ba611c51809eb | /Zen/plugins/ZOgre/src/ResourceServiceFactory.cpp | 4cd90e560635a45f44896e559ba6fc7731f51928 | []
| no_license | Azaezel/quillus-daemos | 7ff4261320c29e0125843b7da39b7b53db685cd5 | 8ee6eac886d831eec3acfc02f03c3ecf78cc841f | refs/heads/master | 2021-01-01T20:35:04.863253 | 2011-04-08T13:46:40 | 2011-04-08T13:46:40 | 32,132,616 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,497 | cpp | //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
// Zen Game Engine Framework
//
// Copyright (C) 2001 - 2008 Tony Richards
//
// 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.
//
// Tony Richards [email protected]
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
#include "ResourceServiceFactory.hpp"
#include "ResourceService.hpp"
#include <Zen/Core/Memory/managed_weak_ptr.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <stddef.h>
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
namespace Zen {
namespace ZOgre {
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
ResourceServiceFactory::ResourceServiceFactory()
{
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
ResourceServiceFactory::~ResourceServiceFactory()
{
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
static ResourceServiceFactory sm_resourceServiceFactory;
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
ResourceServiceFactory&
ResourceServiceFactory::instance()
{
return sm_resourceServiceFactory;
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
Engine::Resource::I_ResourceServiceFactory::pResourceService_type
ResourceServiceFactory::create(const std::string& _type)
{
// TODO Verify that _type is "ogre"
// TODO Guard
if (m_pResourceService == NULL)
{
ResourceService* pRawService = new ResourceService();
pResourceService_type pService(pRawService, boost::bind(&ResourceServiceFactory::destroy, this, _1));
wpResourceService_type pWeakPtr(pService);
pRawService->setSelfReference(pWeakPtr);
m_pResourceService = pService;
}
return m_pResourceService;
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
void
ResourceServiceFactory::destroy(wpResourceService_type _pService)
{
/// Fire the service's onDestroyEvent.
_pService->onDestroyEvent(_pService);
/// Delete the service
ResourceService* pService = dynamic_cast<ResourceService*>(_pService.get());
if (pService != NULL)
{
delete pService;
}
else
{
// TODO Error!
}
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
} // namespace ZOgre
} // namespace Zen
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
| [
"sgtflame@Sullivan"
]
| [
[
[
1,
104
]
]
]
|
889becc57f954025c94ce1c7abd5429a31837732 | 580738f96494d426d6e5973c5b3493026caf8b6a | /Include/Vcl/qforms.hpp | d5c961c49cc1e780bfe3bad8e06994c5411f2543 | []
| no_license | bravesoftdz/cbuilder-vcl | 6b460b4d535d17c309560352479b437d99383d4b | 7b91ef1602681e094a6a7769ebb65ffd6f291c59 | refs/heads/master | 2021-01-10T14:21:03.726693 | 2010-01-11T11:23:45 | 2010-01-11T11:23:45 | 48,485,606 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 43,257 | hpp | // Borland C++ Builder
// Copyright (c) 1995, 2002 by Borland Software Corporation
// All rights reserved
// (DO NOT EDIT: machine generated header) 'QForms.pas' rev: 6.00
#ifndef QFormsHPP
#define QFormsHPP
#pragma delphiheader begin
#pragma option push -w-
#pragma option push -Vx
#include <HelpIntfs.hpp> // Pascal unit
#include <QStyle.hpp> // Pascal unit
#include <QActnList.hpp> // Pascal unit
#include <QMenus.hpp> // Pascal unit
#include <QControls.hpp> // Pascal unit
#include <QGraphics.hpp> // Pascal unit
#include <Types.hpp> // Pascal unit
#include <Classes.hpp> // Pascal unit
#include <SysUtils.hpp> // Pascal unit
#include <QTypes.hpp> // Pascal unit
#include <Qt.hpp> // Pascal unit
#include <Messages.hpp> // Pascal unit
#include <Windows.hpp> // Pascal unit
#include <SysInit.hpp> // Pascal unit
#include <System.hpp> // Pascal unit
//-- user supplied -----------------------------------------------------------
namespace Qforms
{
//-- type declarations -------------------------------------------------------
#pragma option push -b-
enum TScrollBarKind { sbHorizontal, sbVertical };
#pragma option pop
typedef Word TScrollBarInc;
class DELPHICLASS TControlScrollBar;
class DELPHICLASS TScrollingWidget;
class PASCALIMPLEMENTATION TScrollingWidget : public Qcontrols::TFrameControl
{
typedef Qcontrols::TFrameControl inherited;
private:
TControlScrollBar* FHorzScrollBar;
TControlScrollBar* FVertScrollBar;
bool FAutoScroll;
bool FIgnoreMoves;
int FAutoRangeCount;
#pragma pack(push, 1)
tagSIZE FOldScrollPos;
#pragma pack(pop)
bool FUpdatingScrollBars;
Qt::QWidgetH* FViewportHandle;
Qt::QWidget_hookH* FViewportHook;
tagSIZE __fastcall CalcAutoRange();
void __cdecl ContentsMovingHook(int x, int y);
void __fastcall ScaleScrollBars(int MV, int DV, int MH, int DH);
void __cdecl ScrollBarGeometryHook(Qt::QScrollBarH* sb, int &x, int &y, int &w, int &h);
void __fastcall SetAutoScroll(const bool Value);
void __fastcall SetHorzScrollBar(const TControlScrollBar* Value);
void __fastcall SetVertScrollBar(const TControlScrollBar* Value);
void __fastcall UpdateScrollBars(void);
HIDESBASE Qt::QOpenScrollViewH* __fastcall GetHandle(void);
protected:
virtual void __fastcall AdjustScrollRange(TScrollBarKind Kind, int &ARange);
virtual void __fastcall AdjustClientRect(Types::TRect &Rect);
virtual void __fastcall AlignControls(Qcontrols::TControl* AControl, Types::TRect &ARect);
virtual bool __fastcall AutoScrollEnabled(void);
virtual void __fastcall AutoScrollInView(Qcontrols::TControl* AControl);
DYNAMIC void __fastcall ChangeScale(int MV, int DV, int MH, int DH);
DYNAMIC void __fastcall ColorChanged(void);
DYNAMIC void __fastcall ControlsListChanging(Qcontrols::TControl* Control, bool Inserting);
virtual void __fastcall CreateWidget(void);
virtual bool __fastcall EventFilter(Qt::QObjectH* Sender, Qt::QEventH* Event);
virtual Qt::QPaintDeviceH* __fastcall GetAlignedPaintDevice(void);
virtual Qt::QWidgetH* __fastcall GetChildHandle(void);
virtual Types::TPoint __fastcall GetClientOrigin();
virtual Types::TRect __fastcall GetClientRect();
virtual Qt::QPaintDeviceH* __fastcall GetPaintDevice(void);
virtual void __fastcall HookEvents(void);
virtual void __fastcall InitWidget(void);
DYNAMIC void __fastcall PaletteChanged(System::TObject* Sender);
DYNAMIC void __fastcall Resize(void);
virtual void __fastcall ScrollBarSize(TControlScrollBar* ScrollBar, int &Position, int &Extent);
virtual void __fastcall ScrollBarVisibleChanged(TControlScrollBar* Sender);
Qt::QWidgetH* __fastcall ViewportHandle(void);
virtual Types::TRect __fastcall ViewportRect();
DYNAMIC void __fastcall WidgetDestroyed(void);
virtual int __fastcall WidgetFlags(void);
__property bool AutoScroll = {read=FAutoScroll, write=SetAutoScroll, default=1};
public:
__fastcall virtual TScrollingWidget(Classes::TComponent* AOwner);
__fastcall virtual ~TScrollingWidget(void);
void __fastcall DisableAutoRange(void);
void __fastcall EnableAutoRange(void);
virtual void __fastcall ScrollBy(int DeltaX, int DeltaY);
void __fastcall ScrollInView(Qcontrols::TControl* AControl);
__property BorderStyle = {default=4};
__property Qt::QOpenScrollViewH* Handle = {read=GetHandle};
__published:
__property TControlScrollBar* VertScrollBar = {read=FVertScrollBar, write=SetVertScrollBar};
__property TControlScrollBar* HorzScrollBar = {read=FHorzScrollBar, write=SetHorzScrollBar};
public:
#pragma option push -w-inl
/* TWidgetControl.CreateParented */ inline __fastcall TScrollingWidget(Qt::QWidgetH* ParentWidget) : Qcontrols::TFrameControl(ParentWidget) { }
#pragma option pop
};
class PASCALIMPLEMENTATION TControlScrollBar : public Classes::TPersistent
{
typedef Classes::TPersistent inherited;
private:
TScrollingWidget* FControl;
TScrollBarInc FIncrement;
TScrollBarInc FPageIncrement;
int FPosition;
int FRange;
TScrollBarKind FKind;
Word FMargin;
bool FVisible;
bool FTracking;
bool FScaled;
Qgraphics::TColor FColor;
bool FParentColor;
bool FUpdateNeeded;
Qt::QScrollBarH* FHandle;
Qt::QScrollBar_hookH* FHooks;
__fastcall TControlScrollBar(TScrollingWidget* AControl, TScrollBarKind AKind);
int __fastcall CalcAutoRange(void);
void __fastcall DoSetRange(int Value);
int __fastcall GetScrollPos(void);
bool __fastcall HandleAllocated(void);
void __fastcall SetColor(Qgraphics::TColor Value);
void __fastcall SetParentColor(bool Value);
void __fastcall SetPosition(const int Value);
void __fastcall SetRange(const int Value);
void __fastcall SetVisible(const bool Value);
bool __fastcall IsRangeStored(void);
void __fastcall Update(void);
void __fastcall SetIncrement(const TScrollBarInc Value);
void __fastcall SetMargin(const Word Value);
void __fastcall SetHandle(const Qt::QScrollBarH* Value);
void __fastcall SetTracking(const bool Value);
protected:
bool __cdecl EventFilter(Qt::QObjectH* Sender, Qt::QEventH* Event);
public:
virtual void __fastcall Assign(Classes::TPersistent* Source);
bool __fastcall IsScrollBarVisible(void);
__property TScrollBarKind Kind = {read=FKind, nodefault};
__property Qt::QScrollBarH* Handle = {read=FHandle, write=SetHandle};
__property int ScrollPos = {read=GetScrollPos, nodefault};
__published:
__property Qgraphics::TColor Color = {read=FColor, write=SetColor, default=-10};
__property TScrollBarInc Increment = {read=FIncrement, write=SetIncrement, default=8};
__property Word Margin = {read=FMargin, write=SetMargin, default=0};
__property bool ParentColor = {read=FParentColor, write=SetParentColor, default=1};
__property int Range = {read=FRange, write=SetRange, stored=IsRangeStored, default=0};
__property int Position = {read=FPosition, write=SetPosition, default=0};
__property bool Tracking = {read=FTracking, write=SetTracking, default=1};
__property bool Visible = {read=FVisible, write=SetVisible, default=1};
public:
#pragma option push -w-inl
/* TPersistent.Destroy */ inline __fastcall virtual ~TControlScrollBar(void) { }
#pragma option pop
public:
#pragma option push -w-inl
/* TObject.Create */ inline __fastcall TControlScrollBar(void) : Classes::TPersistent() { }
#pragma option pop
};
typedef TScrollingWidget TScrollingWinControl;
;
class DELPHICLASS TScrollBox;
class PASCALIMPLEMENTATION TScrollBox : public TScrollingWidget
{
typedef TScrollingWidget inherited;
public:
__fastcall virtual TScrollBox(Classes::TComponent* AOwner);
__published:
__property Align = {default=0};
__property Anchors = {default=3};
__property AutoScroll = {default=1};
__property BorderStyle = {default=6};
__property Color ;
__property Constraints ;
__property DragMode = {default=0};
__property Enabled = {default=1};
__property Font ;
__property ParentColor = {default=1};
__property ParentFont = {default=1};
__property ParentShowHint = {default=1};
__property ShowHint ;
__property TabOrder = {default=-1};
__property TabStop = {default=0};
__property Visible = {default=1};
__property OnClick ;
__property OnConstrainedResize ;
__property OnContextPopup ;
__property OnDblClick ;
__property OnDragDrop ;
__property OnDragOver ;
__property OnEndDrag ;
__property OnEnter ;
__property OnExit ;
__property OnMouseDown ;
__property OnMouseMove ;
__property OnMouseUp ;
__property OnMouseWheel ;
__property OnMouseWheelDown ;
__property OnMouseWheelUp ;
__property OnResize ;
__property OnStartDrag ;
public:
#pragma option push -w-inl
/* TScrollingWidget.Destroy */ inline __fastcall virtual ~TScrollBox(void) { }
#pragma option pop
public:
#pragma option push -w-inl
/* TWidgetControl.CreateParented */ inline __fastcall TScrollBox(Qt::QWidgetH* ParentWidget) : TScrollingWidget(ParentWidget) { }
#pragma option pop
};
class DELPHICLASS TCustomFrame;
class PASCALIMPLEMENTATION TCustomFrame : public TScrollingWidget
{
typedef TScrollingWidget inherited;
private:
void __fastcall AddActionList(Qactnlist::TCustomActionList* ActionList);
void __fastcall RemoveActionList(Qactnlist::TCustomActionList* ActionList);
protected:
DYNAMIC void __fastcall GetChildren(Classes::TGetChildProc Proc, Classes::TComponent* Root);
virtual void __fastcall InitWidget(void);
virtual void __fastcall Notification(Classes::TComponent* AComponent, Classes::TOperation Operation);
__property BorderStyle = {default=0};
public:
__fastcall virtual TCustomFrame(Classes::TComponent* AOwner);
public:
#pragma option push -w-inl
/* TScrollingWidget.Destroy */ inline __fastcall virtual ~TCustomFrame(void) { }
#pragma option pop
public:
#pragma option push -w-inl
/* TWidgetControl.CreateParented */ inline __fastcall TCustomFrame(Qt::QWidgetH* ParentWidget) : TScrollingWidget(ParentWidget) { }
#pragma option pop
};
typedef TMetaClass*TCustomFrameClass;
class DELPHICLASS TFrame;
class PASCALIMPLEMENTATION TFrame : public TCustomFrame
{
typedef TCustomFrame inherited;
__published:
__property Align = {default=0};
__property Anchors = {default=3};
__property AutoScroll = {default=1};
__property BorderStyle = {default=0};
__property Color ;
__property Constraints ;
__property DragMode = {default=0};
__property Enabled = {default=1};
__property Font ;
__property ParentColor = {default=1};
__property ParentFont = {default=1};
__property ParentShowHint = {default=1};
__property PopupMenu ;
__property ShowHint ;
__property TabOrder = {default=-1};
__property TabStop = {default=0};
__property Visible = {default=1};
__property OnClick ;
__property OnConstrainedResize ;
__property OnContextPopup ;
__property OnDblClick ;
__property OnDragDrop ;
__property OnDragOver ;
__property OnEndDrag ;
__property OnEnter ;
__property OnExit ;
__property OnMouseDown ;
__property OnMouseMove ;
__property OnMouseUp ;
__property OnMouseWheel ;
__property OnMouseWheelDown ;
__property OnMouseWheelUp ;
__property OnResize ;
__property OnStartDrag ;
public:
#pragma option push -w-inl
/* TCustomFrame.Create */ inline __fastcall virtual TFrame(Classes::TComponent* AOwner) : TCustomFrame(AOwner) { }
#pragma option pop
public:
#pragma option push -w-inl
/* TScrollingWidget.Destroy */ inline __fastcall virtual ~TFrame(void) { }
#pragma option pop
public:
#pragma option push -w-inl
/* TWidgetControl.CreateParented */ inline __fastcall TFrame(Qt::QWidgetH* ParentWidget) : TCustomFrame(ParentWidget) { }
#pragma option pop
};
__interface IDesignerHook;
typedef System::DelphiInterface<IDesignerHook> _di_IDesignerHook;
class DELPHICLASS TCustomForm;
__interface INTERFACE_UUID("{ABBE7256-5495-11D1-9FB5-0020AF3D82DA}") IDesignerHook : public IDesignerNotify
{
public:
virtual Classes::TComponent* __fastcall GetRoot(void) = 0 ;
virtual TCustomForm* __fastcall GetCustomForm(void) = 0 ;
virtual bool __fastcall IsDesignEvent(Qcontrols::TWidgetControl* Sender, Qt::QObjectH* SenderHandle, Qt::QEventH* Event) = 0 ;
virtual void __fastcall ControlPaintRequest(Qcontrols::TControl* Control) = 0 ;
virtual void __fastcall PaintGrid(void) = 0 ;
virtual void __fastcall ValidateRename(Classes::TComponent* AComponent, const AnsiString CurName, const AnsiString NewName) = 0 ;
virtual AnsiString __fastcall UniqueName(const AnsiString BaseName) = 0 ;
__property TCustomForm* Form = {read=GetCustomForm};
__property Classes::TComponent* Root = {read=GetRoot};
};
#pragma option push -b-
enum TBorderIcon { biSystemMenu, biMinimize, biMaximize, biHelp };
#pragma option pop
typedef Set<TBorderIcon, biSystemMenu, biHelp> TBorderIcons;
#pragma option push -b-
enum TFormBorderStyle { fbsNone, fbsSingle, fbsSizeable, fbsDialog, fbsToolWindow, fbsSizeToolWin };
#pragma option pop
#pragma option push -b-
enum TFormStyle { fsNormal, fsMDIChild, fsMDIForm, fsStayOnTop };
#pragma option pop
#pragma option push -b-
enum TPosition { poDesigned, poDefault, poDefaultPosOnly, poDefaultSizeOnly, poScreenCenter, poDesktopCenter, poMainFormCenter, poOwnerFormCenter };
#pragma option pop
#pragma option push -b-
enum TWindowState { wsNormal, wsMinimized, wsMaximized };
#pragma option pop
#pragma option push -b-
enum TCloseAction { caNone, caHide, caFree, caMinimize };
#pragma option pop
#pragma option push -b-
enum TShowAction { saIgnore, saRestore, saMinimize, saMaximize };
#pragma option pop
typedef void __fastcall (__closure *TCloseEvent)(System::TObject* Sender, TCloseAction &Action);
typedef void __fastcall (__closure *TCloseQueryEvent)(System::TObject* Sender, bool &CanClose);
typedef int TModalResult;
#pragma option push -b-
enum QForms__6 { fsCreating, fsVisible, fsShowing, fsModal, fsActivated };
#pragma option pop
typedef Set<QForms__6, fsCreating, fsActivated> TFormState;
typedef void __fastcall (__closure *TShortCutEvent)(int Key, Classes::TShiftState Shift, bool &Handled);
typedef bool __fastcall (__closure *THelpEvent)(Classes::THelpType HelpType, Classes::THelpContext HelpContext, const AnsiString HelpKeyword, const AnsiString HelpFile, bool &Handled);
class DELPHICLASS TForm;
class PASCALIMPLEMENTATION TCustomForm : public TScrollingWidget
{
typedef TScrollingWidget inherited;
private:
Qcontrols::TWidgetControl* FActiveControl;
Qcontrols::TWidgetControl* FFocusedControl;
TBorderIcons FBorderIcons;
bool FActive;
bool FKeyPreview;
bool FDropTarget;
bool FShown;
_di_IDesignerHook FDesignerHook;
Qmenus::TMainMenu* FMenu;
TModalResult FModalResult;
TFormBorderStyle FBorderStyle;
Qcontrols::TControlCanvas* FCanvas;
int FClientHeight;
int FClientWidth;
int FPixelsPerInch;
int FTextHeight;
int FTextWidth;
TCloseEvent FOnClose;
TCloseQueryEvent FOnCloseQuery;
THelpEvent FOnHelp;
Classes::TNotifyEvent FOnCreate;
Classes::TNotifyEvent FOnLoaded;
Classes::TNotifyEvent FOnPaint;
Classes::TNotifyEvent FOnActivate;
TShortCutEvent FOnShortCut;
Classes::TNotifyEvent FOnShow;
Classes::TNotifyEvent FOnDeactivate;
Classes::TNotifyEvent FOnHide;
Classes::TNotifyEvent FOnDestroy;
TFormStyle FFormStyle;
TPosition FPosition;
TWindowState FWindowState;
bool FSizeGrip;
Qt::QSizeGripH* FGripper;
int FMenuHeight;
Qt::QWorkspaceH* FClientHandle;
Qt::QWorkspace_hookH* FClientHooks;
TForm* FMDIParent;
Classes::TList* FMDIChildList;
Qgraphics::TIcon* FIcon;
void __fastcall CheckGripper(void);
Qgraphics::TCanvas* __fastcall GetCanvas(void);
int __fastcall GetPixelsPerInch(void);
bool __fastcall GetScaled(void);
bool __fastcall IsClientSizeStored(void);
bool __fastcall IsFormSizeStored(void);
void __fastcall SetActiveControl(const Qcontrols::TWidgetControl* Control);
HIDESBASE void __fastcall SetClientHeight(int Value);
HIDESBASE void __fastcall SetClientWidth(int Value);
void __fastcall SetDesignerHook(const _di_IDesignerHook Value);
void __fastcall SetMenu(const Qmenus::TMainMenu* Value);
void __fastcall SetPixelsPerInch(const int Value);
void __fastcall SetScaled(const bool Value);
HIDESBASE void __fastcall SetVisible(bool Value);
void __fastcall SetWidgetFocus(void);
bool __fastcall IsForm(void);
HIDESBASE void __fastcall SetBorderStyle(const TFormBorderStyle Value);
void __fastcall SetBorderIcons(const TBorderIcons Value);
void __fastcall SetFormStyle(const TFormStyle Value);
void __fastcall IgnoreIdent(Classes::TReader* Reader);
void __fastcall SetPosition(const TPosition Value);
void __fastcall SetModalResult(const TModalResult Value);
void __fastcall SetWindowState(const TWindowState Value);
void __fastcall ShowWindowState(void);
void __fastcall SetMDIParent(const TForm* Value);
Classes::TList* __fastcall MDIChildList(void);
void __fastcall WorkspaceNeeded(void);
int __fastcall GetMDIChildCount(void);
TForm* __fastcall GetMDIChildren(int I);
void __fastcall RemoveMDIChild(TCustomForm* AForm);
void __fastcall AppendMDIChild(TCustomForm* AForm);
Qt::QWorkspaceH* __fastcall GetClientHandle(void);
TForm* __fastcall GetActiveMDIChild(void);
void __fastcall SetIcon(const Qgraphics::TIcon* Value);
void __fastcall MergeMenu(bool MergeState);
int __fastcall GetTextHeight(void);
int __fastcall GetTextWidth(void);
void __fastcall ReadTextHeight(Classes::TReader* Reader);
void __fastcall ReadTextWidth(Classes::TReader* Reader);
void __fastcall WriteTextHeight(Classes::TWriter* Writer);
void __fastcall WriteTextWidth(Classes::TWriter* Writer);
void __fastcall WritePixelsPerInch(Classes::TWriter* Writer);
void __cdecl MDIChildActivated(Qt::QWidgetH* w);
protected:
Classes::TList* FActionLists;
TFormState FFormState;
DYNAMIC bool __fastcall ActionExecute(Classes::TBasicAction* &BasicAction);
DYNAMIC bool __fastcall ActionUpdate(Classes::TBasicAction* &BasicAction);
DYNAMIC void __fastcall Activate(void);
DYNAMIC void __fastcall ActiveChanged(void);
virtual void __fastcall AlignControls(Qcontrols::TControl* AControl, Types::TRect &Rect);
DYNAMIC void __fastcall BeginAutoDrag(void);
DYNAMIC void __fastcall ChangeScale(int MV, int DV, int MH, int DH);
DYNAMIC void __fastcall ColorChanged(void);
DYNAMIC void __fastcall ControlsListChanging(Qcontrols::TControl* Control, bool Inserting);
virtual void __fastcall CreateWidget(void);
DYNAMIC void __fastcall Deactivate(void);
virtual void __fastcall DefineProperties(Classes::TFiler* Filer);
DYNAMIC void __fastcall DoClose(TCloseAction &Action);
virtual void __fastcall DoCreate(void);
virtual void __fastcall DoDestroy(void);
DYNAMIC void __fastcall DoHide(void);
DYNAMIC void __fastcall DoLoaded(void);
DYNAMIC void __fastcall DoShow(void);
virtual bool __fastcall EventFilter(Qt::QObjectH* Sender, Qt::QEventH* Event);
DYNAMIC void __fastcall FontChanged(void);
DYNAMIC void __fastcall GetChildren(Classes::TGetChildProc Proc, Classes::TComponent* Root);
virtual Types::TRect __fastcall GetClientRect();
virtual Types::TPoint __fastcall GetClientOrigin();
virtual Qt::QPaintDeviceH* __fastcall GetPaintDevice(void);
virtual Qt::QWidgetH* __fastcall GetParentWidget(void);
DYNAMIC bool __fastcall HandleCreateException(void);
virtual void __fastcall IconChanged(System::TObject* Sender);
virtual void __fastcall InitWidget(void);
virtual void __fastcall Loaded(void);
int __fastcall MDIChildTop(void);
int __fastcall MDIChildLeft(void);
virtual void __fastcall Notification(Classes::TComponent* AComponent, Classes::TOperation Operation);
virtual void __fastcall Painting(Qt::QObjectH* Sender, Qt::QRegionH* EventRegion);
DYNAMIC void __fastcall Paint(void);
DYNAMIC void __fastcall ParentFontChanged(void);
virtual HRESULT __stdcall QueryInterface(const GUID &IID, /* out */ void *Obj);
virtual void __fastcall ReadState(Classes::TReader* Reader);
DYNAMIC void __fastcall Resize(void);
DYNAMIC void __fastcall SetChildOrder(Classes::TComponent* Child, int Order);
virtual void __fastcall SetInitialBounds(void);
virtual void __fastcall SetParent(const Qcontrols::TWidgetControl* AParent);
DYNAMIC void __fastcall ShowingChanged(void);
virtual void __fastcall UpdateActions(void);
virtual void __fastcall ValidateRename(Classes::TComponent* AComponent, const AnsiString CurName, const AnsiString NewName);
virtual Types::TRect __fastcall ViewportRect();
DYNAMIC void __fastcall VisibleChanging(void);
DYNAMIC bool __fastcall WantKey(int Key, Classes::TShiftState Shift, const WideString KeyText);
DYNAMIC void __fastcall WidgetDestroyed(void);
virtual int __fastcall WidgetFlags(void);
__property TForm* ActiveMDIChild = {read=GetActiveMDIChild};
__property TBorderIcons BorderIcons = {read=FBorderIcons, write=SetBorderIcons, stored=IsForm, default=7};
__property TFormBorderStyle BorderStyle = {read=FBorderStyle, write=SetBorderStyle, stored=IsForm, default=2};
__property Qt::QWorkspaceH* ClientHandle = {read=GetClientHandle};
__property ClientHeight = {write=SetClientHeight, stored=IsClientSizeStored};
__property ClientWidth = {write=SetClientWidth, stored=IsClientSizeStored};
__property TFormStyle FormStyle = {read=FFormStyle, write=SetFormStyle, stored=IsForm, default=0};
__property Height = {stored=IsFormSizeStored};
__property Qgraphics::TIcon* Icon = {read=FIcon, write=SetIcon};
__property int MDIChildCount = {read=GetMDIChildCount, nodefault};
__property TForm* MDIChildren[int I] = {read=GetMDIChildren};
__property TForm* MDIParent = {read=FMDIParent, write=SetMDIParent};
__property int PixelsPerInch = {read=GetPixelsPerInch, write=SetPixelsPerInch, stored=false, nodefault};
__property TPosition Position = {read=FPosition, write=SetPosition, default=0};
__property bool Scaled = {read=GetScaled, write=SetScaled, default=1};
__property bool SizeGrip = {read=FSizeGrip, write=FSizeGrip, default=1};
__property Visible = {write=SetVisible, default=0};
__property Width = {stored=IsFormSizeStored};
__property Classes::TNotifyEvent OnActivate = {read=FOnActivate, write=FOnActivate};
__property TCloseEvent OnClose = {read=FOnClose, write=FOnClose};
__property TCloseQueryEvent OnCloseQuery = {read=FOnCloseQuery, write=FOnCloseQuery};
__property Classes::TNotifyEvent OnCreate = {read=FOnCreate, write=FOnCreate};
__property Classes::TNotifyEvent OnDeactivate = {read=FOnDeactivate, write=FOnDeactivate};
__property Classes::TNotifyEvent OnDestroy = {read=FOnDestroy, write=FOnDestroy};
__property THelpEvent OnHelp = {read=FOnHelp, write=FOnHelp};
__property Classes::TNotifyEvent OnHide = {read=FOnHide, write=FOnHide};
__property Classes::TNotifyEvent OnLoaded = {read=FOnLoaded, write=FOnLoaded};
__property Classes::TNotifyEvent OnPaint = {read=FOnPaint, write=FOnPaint};
__property TShortCutEvent OnShortCut = {read=FOnShortCut, write=FOnShortCut};
__property Classes::TNotifyEvent OnShow = {read=FOnShow, write=FOnShow};
public:
__fastcall virtual TCustomForm(Classes::TComponent* AOwner);
__fastcall virtual TCustomForm(Classes::TComponent* AOwner, int Dummy);
__fastcall virtual ~TCustomForm(void);
virtual void __fastcall AfterConstruction(void);
virtual void __fastcall BeforeDestruction(void);
void __fastcall Close(void);
virtual bool __fastcall CloseQuery(void);
void __fastcall DefocusControl(Qcontrols::TWidgetControl* Control, bool Removing);
void __fastcall FocusControl(Qcontrols::TWidgetControl* Control);
HIDESBASE void __fastcall Hide(void);
virtual void __fastcall InvokeHelp(void);
DYNAMIC bool __fastcall IsShortCut(int Key, Classes::TShiftState Shift, const WideString KeyText);
void __fastcall Release(void);
virtual void __fastcall SetFocus(void);
virtual bool __fastcall SetFocusedControl(Qcontrols::TWidgetControl* Control);
HIDESBASE void __fastcall Show(void);
virtual int __fastcall ShowModal(void);
__property Action ;
__property bool Active = {read=FActive, default=1};
__property Qcontrols::TWidgetControl* ActiveControl = {read=FActiveControl, write=SetActiveControl};
__property Qgraphics::TCanvas* Canvas = {read=GetCanvas};
__property Caption ;
__property Color ;
__property _di_IDesignerHook DesignerHook = {read=FDesignerHook, write=SetDesignerHook};
__property bool DropTarget = {read=FDropTarget, write=FDropTarget, nodefault};
__property Qcontrols::TWidgetControl* FocusedControl = {read=FFocusedControl};
__property Font ;
__property TFormState FormState = {read=FFormState, nodefault};
__property HelpFile ;
__property bool KeyPreview = {read=FKeyPreview, write=FKeyPreview, default=0};
__property Qmenus::TMainMenu* Menu = {read=FMenu, write=SetMenu};
__property TModalResult ModalResult = {read=FModalResult, write=SetModalResult, nodefault};
__property TWindowState WindowState = {read=FWindowState, write=SetWindowState, stored=IsForm, default=0};
public:
#pragma option push -w-inl
/* TWidgetControl.CreateParented */ inline __fastcall TCustomForm(Qt::QWidgetH* ParentWidget) : TScrollingWidget(ParentWidget) { }
#pragma option pop
};
class PASCALIMPLEMENTATION TForm : public TCustomForm
{
typedef TCustomForm inherited;
public:
void __fastcall Cascade(void);
void __fastcall Next(void);
void __fastcall Previous(void);
void __fastcall Tile(void);
__property ActiveMDIChild ;
__property ClientHandle ;
__property MDIChildCount ;
__property MDIChildren ;
__published:
__property Action ;
__property ActiveControl ;
__property Anchors = {default=3};
__property AutoScroll = {default=1};
__property Bitmap ;
__property BorderIcons = {default=7};
__property BorderStyle = {default=2};
__property Caption ;
__property ClientHeight ;
__property ClientWidth ;
__property Color ;
__property Constraints ;
__property DragMode = {default=0};
__property Enabled = {default=1};
__property Font ;
__property FormStyle = {default=0};
__property Height ;
__property HelpFile ;
__property HelpKeyword ;
__property HorzScrollBar ;
__property Icon ;
__property KeyPreview = {default=0};
__property Menu ;
__property ParentFont = {default=1};
__property PixelsPerInch ;
__property PopupMenu ;
__property Position = {default=0};
__property Scaled = {default=1};
__property ShowHint ;
__property VertScrollBar ;
__property Visible = {default=0};
__property Width ;
__property WindowState = {default=0};
__property OnActivate ;
__property OnClick ;
__property OnClose ;
__property OnCloseQuery ;
__property OnConstrainedResize ;
__property OnContextPopup ;
__property OnCreate ;
__property OnDblClick ;
__property OnDragDrop ;
__property OnDragOver ;
__property OnDeactivate ;
__property OnDestroy ;
__property OnHelp ;
__property OnHide ;
__property OnKeyDown ;
__property OnKeyPress ;
__property OnKeyString ;
__property OnKeyUp ;
__property OnLoaded ;
__property OnMouseDown ;
__property OnMouseMove ;
__property OnMouseUp ;
__property OnMouseWheel ;
__property OnMouseWheelDown ;
__property OnMouseWheelUp ;
__property OnPaint ;
__property OnResize ;
__property OnShow ;
__property OnShortCut ;
public:
#pragma option push -w-inl
/* TCustomForm.Create */ inline __fastcall virtual TForm(Classes::TComponent* AOwner) : TCustomForm(AOwner) { }
#pragma option pop
#pragma option push -w-inl
/* TCustomForm.CreateNew */ inline __fastcall virtual TForm(Classes::TComponent* AOwner, int Dummy) : TCustomForm(AOwner, Dummy) { }
#pragma option pop
#pragma option push -w-inl
/* TCustomForm.Destroy */ inline __fastcall virtual ~TForm(void) { }
#pragma option pop
public:
#pragma option push -w-inl
/* TWidgetControl.CreateParented */ inline __fastcall TForm(Qt::QWidgetH* ParentWidget) : TCustomForm(ParentWidget) { }
#pragma option pop
};
typedef TMetaClass*TCustomFormClass;
typedef TMetaClass*TFormClass;
struct TCursorRec;
typedef TCursorRec *PCursorRec;
#pragma pack(push, 4)
struct TCursorRec
{
TCursorRec *Next;
int Index;
Qt::QCursorH* Handle;
} ;
#pragma pack(pop)
class DELPHICLASS TScreen;
class PASCALIMPLEMENTATION TScreen : public Classes::TComponent
{
typedef Classes::TComponent inherited;
private:
TCursorRec *FCursorList;
int FPixelsPerInch;
Qcontrols::TCursor FCursor;
int FCursorCount;
Classes::TNotifyEvent FOnActiveControlChange;
Classes::TNotifyEvent FOnActiveFormChange;
Qcontrols::TWidgetControl* FActiveControl;
Classes::TList* FSaveFocusedList;
Classes::TList* FForms;
Classes::TList* FCustomForms;
Classes::TList* FDataModules;
TCustomForm* FActiveCustomForm;
TForm* FActiveForm;
Qcontrols::TWidgetControl* FLastActiveControl;
TCustomForm* FLastActiveCustomForm;
TCustomForm* FFocusedForm;
Qgraphics::TFont* FHintFont;
Qt::QCursorH* FDefaultCursor;
Classes::TStrings* FFonts;
void __fastcall AddDataModule(Classes::TDataModule* DataModule);
void __fastcall AddForm(TCustomForm* AForm);
void __fastcall CreateCursors(void);
void __fastcall DeleteCursor(int Index);
Qt::QCursorH* __fastcall GetCursors(int Index);
int __fastcall GetCustomFormCount(void);
TCustomForm* __fastcall GetCustomForms(int Index);
Classes::TDataModule* __fastcall GetDataModule(int Index);
int __fastcall GetDataModuleCount(void);
Classes::TStrings* __fastcall GetFonts(void);
TForm* __fastcall GetForm(int Index);
int __fastcall GetFormCount(void);
int __fastcall GetPixelsPerInch(void);
Qgraphics::TFont* __fastcall GetHintFont(void);
void __fastcall InternalHintFontChanged(System::TObject* Sender);
void __fastcall InsertCursor(int Index, Qt::QCursorH* Handle);
void __fastcall RemoveDataModule(Classes::TDataModule* DataModule);
void __fastcall RemoveForm(TCustomForm* AForm);
void __fastcall SetCursor(const Qcontrols::TCursor Value);
void __fastcall SetCursors(int Index, const Qt::QCursorH* Value);
void __fastcall SetHintFont(Qgraphics::TFont* Value);
void __fastcall UpdateLastActive(void);
int __fastcall GetHeight(void);
int __fastcall GetWidth(void);
Qt::QWidgetH* __fastcall GetActiveWidget(void);
public:
__fastcall virtual TScreen(Classes::TComponent* AOwner);
__fastcall virtual ~TScreen(void);
__property Qcontrols::TWidgetControl* ActiveControl = {read=FActiveControl};
__property TCustomForm* ActiveCustomForm = {read=FActiveCustomForm};
__property TForm* ActiveForm = {read=FActiveForm};
__property Qt::QWidgetH* ActiveWidget = {read=GetActiveWidget};
__property Qcontrols::TCursor Cursor = {read=FCursor, write=SetCursor, nodefault};
__property Qt::QCursorH* Cursors[int Index] = {read=GetCursors, write=SetCursors};
__property int CustomFormCount = {read=GetCustomFormCount, nodefault};
__property TCustomForm* CustomForms[int Index] = {read=GetCustomForms};
__property int DataModuleCount = {read=GetDataModuleCount, nodefault};
__property Classes::TDataModule* DataModules[int Index] = {read=GetDataModule};
__property Classes::TStrings* Fonts = {read=GetFonts};
__property int FormCount = {read=GetFormCount, nodefault};
__property TForm* Forms[int Index] = {read=GetForm};
__property int Height = {read=GetHeight, nodefault};
__property Qgraphics::TFont* HintFont = {read=GetHintFont, write=SetHintFont};
__property int PixelsPerInch = {read=GetPixelsPerInch, nodefault};
__property int Width = {read=GetWidth, nodefault};
__property Classes::TNotifyEvent OnActiveControlChange = {read=FOnActiveControlChange, write=FOnActiveControlChange};
__property Classes::TNotifyEvent OnActiveFormChange = {read=FOnActiveFormChange, write=FOnActiveFormChange};
};
#pragma option push -b-
enum TTimerMode { tmShow, tmHide };
#pragma option pop
typedef void __fastcall (__closure *TEventEvent)(Qt::QObjectH* Sender, Qt::QEventH* Event, bool &Handled);
typedef void __fastcall (__closure *TExceptionEvent)(System::TObject* Sender, Sysutils::Exception* E);
typedef void __fastcall (__closure *TIdleEvent)(System::TObject* Sender, bool &Done);
#pragma option push -b-
enum TMessageButton { smbOK, smbCancel, smbYes, smbNo, smbAbort, smbRetry, smbIgnore };
#pragma option pop
typedef Set<TMessageButton, smbOK, smbIgnore> TMessageButtons;
#pragma option push -b-
enum TMessageStyle { smsInformation, smsWarning, smsCritical };
#pragma option pop
typedef void __fastcall (__closure *TOnHelpEvent)(System::TObject* Sender);
class DELPHICLASS TApplication;
class PASCALIMPLEMENTATION TApplication : public Classes::TComponent
{
typedef Classes::TComponent inherited;
private:
Helpintfs::_di_IHelpSystem FHelpSystem;
char * *FArgv;
bool FTerminated;
bool FActive;
bool FShowMainForm;
Qt::QApplicationH* FHandle;
bool FHintShortCuts;
Qt::QObject_hookH* FHooks;
TExceptionEvent FOnException;
TCustomForm* FMainForm;
Qt::QWidgetH* FAppWidget;
bool FQtAccels;
WideString FTitle;
WideString FHint;
Qgraphics::TColor FHintColor;
Qcontrols::TControl* FHintControl;
#pragma pack(push, 1)
Types::TRect FHintCursorRect;
#pragma pack(pop)
int FHintHidePause;
int FHintPause;
int FHintShortPause;
Classes::TComponent* FHintTimer;
TTimerMode FTimerMode;
Qcontrols::THintWindow* FHintWindow;
Classes::TComponent* FIdleTimer;
Qcontrols::TControl* FMouseControl;
Qgraphics::TPalette* FPalette;
Qstyle::TApplicationStyle* FStyle;
Qgraphics::TFont* FFont;
TIdleEvent FOnIdle;
Classes::TNotifyEvent FOnHint;
Classes::TNotifyEvent FOnDeactivate;
Classes::TNotifyEvent FOnActivate;
TEventEvent FOnEvent;
Qactnlist::TActionEvent FOnActionExecute;
Qactnlist::TActionEvent FOnActionUpdate;
TShortCutEvent FOnShortCut;
Qcontrols::TShowHintEvent FOnShowHint;
Classes::TNotifyEvent FOnModalBegin;
Classes::TNotifyEvent FOnModalEnd;
Qcontrols::TCursor FOldCursor;
AnsiString FHelpFile;
int FHelpKey;
AnsiString FHelpKeyword;
Classes::THelpContext FHelpContext;
Classes::THelpType FHelpType;
THelpEvent FOnHelp;
Classes::TNotifyEvent FOnMinimize;
Classes::TNotifyEvent FOnRestore;
Classes::TList* FTopMostList;
Qgraphics::TIcon* FIcon;
int FTopMostLevel;
int FModalLevel;
bool FHintActive;
bool FShowHint;
bool FMinimized;
bool FMainFormSet;
Classes::TShiftState FKeyState;
bool __fastcall ExecuteActionNotification(Classes::TBasicAction* Action);
bool __fastcall UpdateActionNotification(Classes::TBasicAction* Action);
Qcontrols::TControl* __fastcall DoMouseIdle(void);
void __fastcall DoActionIdle(void);
void __fastcall DoDeactivate(void);
void __fastcall DoActivate(void);
void __fastcall StyleChanged(System::TObject* Sender);
void __fastcall PaletteChanged(System::TObject* Sender);
void __fastcall SetHandle(const Qt::QApplicationH* Value);
bool __cdecl EventFilter(Qt::QObjectH* Sender, Qt::QEventH* Event);
Qt::QWidgetH* __fastcall GetDesktop(void);
Qgraphics::TFont* __fastcall GetFont(void);
void __fastcall SetFont(Qgraphics::TFont* Value);
void __fastcall InternalFontChanged(System::TObject* Sender);
void __fastcall HintTimerExpired(void);
void __fastcall LoadTranslator(void);
void __fastcall SetTitle(const WideString Value);
void __fastcall SetHint(const WideString Value);
void __fastcall SetHintColor(Qgraphics::TColor Value);
void __fastcall SetShowHint(bool Value);
void __fastcall StartHintTimer(int Value, TTimerMode TimerMode);
void __fastcall StopHintTimer(void);
void __fastcall HintTimerProc(System::TObject* Sender);
Qstyle::TApplicationStyle* __fastcall GetStyle(void);
void __fastcall SetStyle(const Qstyle::TApplicationStyle* Value);
void __fastcall Quit(void);
void __fastcall UpdateVisible(void);
AnsiString __fastcall GetCurrentHelpFile();
AnsiString __fastcall GetExeName();
void __fastcall SetIcon(const Qgraphics::TIcon* Value);
Classes::TList* __fastcall GetTopMostList(void);
bool __fastcall GetActiveState(void);
Qt::QWidgetH* __fastcall GetAppWidget(void);
void __fastcall WakeMainThread(System::TObject* Sender);
protected:
__property Qt::QWidgetH* AppWidget = {read=GetAppWidget};
void __fastcall CreateHandle(void);
__property Qt::QObject_hookH* Hooks = {read=FHooks};
virtual void __fastcall IconChanged(System::TObject* Sender);
DYNAMIC void __fastcall Idle(System::TObject* Sender);
void __fastcall SetHelpContext(const Classes::THelpContext Value);
void __fastcall SetHelpKeyword(const AnsiString Value);
bool __fastcall ValidateHelpSystem(void);
__property Classes::TList* TopMostList = {read=GetTopMostList};
public:
__fastcall virtual TApplication(Classes::TComponent* AOwner);
__fastcall virtual ~TApplication(void);
void __fastcall ActivateHint(const Types::TPoint &CursorPos);
void __fastcall BringToFront(void);
void __fastcall CancelHint(void);
void __fastcall ControlDestroyed(Qcontrols::TControl* Control);
void __fastcall CreateForm(TMetaClass* InstanceClass, void *Reference);
DYNAMIC bool __fastcall ExecuteAction(Classes::TBasicAction* Action);
void __fastcall HandleException(System::TObject* Sender);
void __fastcall HandleMessage(void);
void __fastcall HideHint(void);
void __fastcall HintMouseMessage(Qcontrols::TControl* Control, Classes::TShiftState Shift, int X, int Y);
void __fastcall HookSynchronizeWakeup(void);
void __fastcall Initialize(void);
bool __fastcall IsShortCut(int Key, Classes::TShiftState Shift, const WideString KeyText);
void __fastcall InvokeHelp(void);
bool __fastcall ContextHelp(const Classes::THelpContext HelpContext);
bool __fastcall KeywordHelp(const AnsiString HelpKeyword);
TMessageButton __fastcall MessageBox(const WideString Text, const WideString Caption = L"", TMessageButtons Buttons = (System::Set<TMessageButton, smbOK, smbIgnore> () << TMessageButton(0) ), TMessageStyle Style = (TMessageStyle)(0x0), TMessageButton Default = (TMessageButton)(0x0), TMessageButton Escape = (TMessageButton)(0x1));
void __fastcall Minimize(void);
void __fastcall ModalStarted(System::TObject* Sender);
void __fastcall ModalFinished(System::TObject* Sender);
void __fastcall NormalizeTopMosts(void);
void __fastcall ProcessMessages(void);
void __fastcall Restore(void);
void __fastcall RestoreTopMosts(void);
void __fastcall Run(void);
void __fastcall ShowException(Sysutils::Exception* E);
void __fastcall Terminate(void);
void __fastcall UnhookSynchronizeWakeup(void);
DYNAMIC bool __fastcall UpdateAction(Classes::TBasicAction* Action);
__property bool Active = {read=FActive, nodefault};
__property AnsiString CurrentHelpFile = {read=GetCurrentHelpFile};
__property Qt::QWidgetH* Desktop = {read=GetDesktop};
__property bool EnableQtAccelerators = {read=FQtAccels, write=FQtAccels, nodefault};
__property AnsiString ExeName = {read=GetExeName};
__property Qgraphics::TFont* Font = {read=GetFont, write=SetFont};
__property Qt::QApplicationH* Handle = {read=FHandle, write=SetHandle};
__property AnsiString HelpFile = {read=FHelpFile, write=FHelpFile};
__property int HelpKey = {read=FHelpKey, write=FHelpKey, default=4144};
__property Helpintfs::_di_IHelpSystem HelpSystem = {read=FHelpSystem};
__property AnsiString HelpWord = {read=FHelpKeyword, write=SetHelpKeyword};
__property Classes::THelpContext HelpContext = {read=FHelpContext, write=SetHelpContext, nodefault};
__property Classes::THelpType HelpType = {read=FHelpType, write=FHelpType, nodefault};
__property WideString Hint = {read=FHint, write=SetHint};
__property Qgraphics::TColor HintColor = {read=FHintColor, write=SetHintColor, nodefault};
__property int HintHidePause = {read=FHintHidePause, write=FHintHidePause, nodefault};
__property int HintPause = {read=FHintPause, write=FHintPause, nodefault};
__property bool HintShortCuts = {read=FHintShortCuts, write=FHintShortCuts, nodefault};
__property int HintShortPause = {read=FHintShortPause, write=FHintShortPause, nodefault};
__property Qgraphics::TIcon* Icon = {read=FIcon, write=SetIcon};
__property Classes::TShiftState KeyState = {read=FKeyState, nodefault};
__property TCustomForm* MainForm = {read=FMainForm};
__property Qgraphics::TPalette* Palette = {read=FPalette};
__property bool ShowHint = {read=FShowHint, write=SetShowHint, default=1};
__property bool ShowMainForm = {read=FShowMainForm, write=FShowMainForm, nodefault};
__property Qstyle::TApplicationStyle* Style = {read=GetStyle, write=SetStyle};
__property bool Terminated = {read=FTerminated, nodefault};
__property WideString Title = {read=FTitle, write=SetTitle};
__property Qactnlist::TActionEvent OnActionExecute = {read=FOnActionExecute, write=FOnActionExecute};
__property Qactnlist::TActionEvent OnActionUpdate = {read=FOnActionUpdate, write=FOnActionUpdate};
__property Classes::TNotifyEvent OnActivate = {read=FOnActivate, write=FOnActivate};
__property Classes::TNotifyEvent OnDeactivate = {read=FOnDeactivate, write=FOnDeactivate};
__property TEventEvent OnEvent = {read=FOnEvent, write=FOnEvent};
__property TExceptionEvent OnException = {read=FOnException, write=FOnException};
__property THelpEvent OnHelp = {read=FOnHelp, write=FOnHelp};
__property Classes::TNotifyEvent OnHint = {read=FOnHint, write=FOnHint};
__property TIdleEvent OnIdle = {read=FOnIdle, write=FOnIdle};
__property Classes::TNotifyEvent OnMinimize = {read=FOnMinimize, write=FOnMinimize};
__property Classes::TNotifyEvent OnModalBegin = {read=FOnModalBegin, write=FOnModalBegin};
__property Classes::TNotifyEvent OnModalEnd = {read=FOnModalEnd, write=FOnModalEnd};
__property Classes::TNotifyEvent OnRestore = {read=FOnRestore, write=FOnRestore};
__property Qcontrols::TShowHintEvent OnShowHint = {read=FOnShowHint, write=FOnShowHint};
__property TShortCutEvent OnShortCut = {read=FOnShortCut, write=FOnShortCut};
};
typedef void __fastcall (*TFormWidgetCreatedHook)(TCustomForm* Form);
//-- var, const, procedure ---------------------------------------------------
#define QEventType_CMDestroyWidget (Qt::QEventType)(1001)
#define QEventType_CMQuit (Qt::QEventType)(1002)
#define QEventType_CMRelease (Qt::QEventType)(1003)
#define QEventType_CMScrolled (Qt::QEventType)(1004)
extern PACKAGE TApplication* Application;
extern PACKAGE TScreen* Screen;
extern PACKAGE Qcontrols::TMouse* Mouse;
extern PACKAGE TMetaClass*HintWindowClass;
extern PACKAGE TFormWidgetCreatedHook FormWidgetCreatedHook;
extern PACKAGE TCustomForm* __fastcall GetParentForm(Qcontrols::TControl* Control);
extern PACKAGE TCustomForm* __fastcall ValidParentForm(Qcontrols::TControl* Control);
extern PACKAGE bool __fastcall IsAccel(Word VK, const WideString Str);
} /* namespace Qforms */
using namespace Qforms;
#pragma option pop // -w-
#pragma option pop // -Vx
#pragma delphiheader end.
//-- end unit ----------------------------------------------------------------
#endif // QForms
| [
"bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b"
]
| [
[
[
1,
1038
]
]
]
|
4a65202f031c2bceaaebbad70b28c065d023fa84 | 3bf3c2da2fd334599a80aa09420dbe4c187e71a0 | /MyVector.h | 8bcbd7807455fc80a1a2323c8ddeb826401d42d1 | []
| no_license | xiongchiamiov/virus-td | 31b88f6a5d156a7b7ee076df55ddce4e1c65ca4f | a7b24ce50d07388018f82d00469cb331275f429b | refs/heads/master | 2020-12-24T16:50:11.991795 | 2010-06-10T05:05:48 | 2010-06-10T05:05:48 | 668,821 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,057 | h | #pragma once
class MyVector
{
public:
MyVector(void);
MyVector(float in_i, float in_j, float in_k, float in_x, float in_y, float in_z);
MyVector(float in_i, float in_j, float in_k);
~MyVector(void);
void setVector(float in_i, float in_j, float in_k);
void setPosition(float in_x, float in_y, float in_z);
float dotProduct(MyVector other);
void crossProduct(MyVector other, MyVector& newVector);
float getLength();
float getI();
float setI(float newI);
float getJ();
float setJ(float newJ);
float getK();
float setK(float newK);
float getX();
float setX(float newX);
float getY();
float setY(float newY);
float getZ();
float setZ(float newZ);
void normalize();
MyVector& operator=(const MyVector& other);
MyVector& operator+=(const MyVector& other);
MyVector& operator-=(const MyVector& other);
MyVector& operator+(const MyVector& other);
MyVector& operator-(const MyVector& other);
private:
float i;
float j;
float k;
float x;
float y;
float z;
};
| [
"agonza40@05766cc9-4f33-4ba7-801d-bd015708efd9"
]
| [
[
[
1,
41
]
]
]
|
8cbdbbe2a176954e7c26429c840c026cad4da993 | b2155efef00dbb04ae7a23e749955f5ec47afb5a | /tools/MatrixCalc/DlgMatrixCalc.h | 7cf875f7f85368a8ce1d66412f30a38f92c86439 | []
| no_license | zjhlogo/originengine | 00c0bd3c38a634b4c96394e3f8eece86f2fe8351 | a35a83ed3f49f6aeeab5c3651ce12b5c5a43058f | refs/heads/master | 2021-01-20T13:48:48.015940 | 2011-04-21T04:10:54 | 2011-04-21T04:10:54 | 32,371,356 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 850 | h | /*!
* \file DlgMatrixCalc.h
* \date 27-2-2010 9:16:06
*
*
* \author zjhlogo ([email protected])
*/
#ifndef __DLGMATRIXCALC_H__
#define __DLGMATRIXCALC_H__
#include <wx/dialog.h>
#include "MatrixElement.h"
class CDlgMatrixCalc : public wxDialog
{
DECLARE_EVENT_TABLE()
public:
enum CONST_DEFINE
{
MATRIX_ROW = 4,
MATRIX_COL = 4,
MATRIX_ELEMENT_SIZE = MATRIX_ROW*MATRIX_COL,
};
public:
CDlgMatrixCalc();
virtual ~CDlgMatrixCalc();
private:
void OnBtnCalculateClick(wxCommandEvent& event);
void OnBtnCloseClick(wxCommandEvent& event);
void ResetMatrixElement();
void SetupMatrixElement();
private:
CMatrixElement m_MatrixA[MATRIX_ELEMENT_SIZE];
CMatrixElement m_MatrixB[MATRIX_ELEMENT_SIZE];
CMatrixElement m_MatrixResult[MATRIX_ELEMENT_SIZE];
};
#endif // __DLGMATRIXCALC_H__
| [
"zjhlogo@fdcc8808-487c-11de-a4f5-9d9bc3506571"
]
| [
[
[
1,
43
]
]
]
|
36ffd688e18f5b778a9af3de7d94cdb1bf374427 | f78d9c67f1785c436050d3c1ca40bf4253501717 | /Mesh.cpp | 9fb14bc8ecf0044a503cbba6173098cff5b9cbcf | []
| no_license | elcerdo/pixelcity | 0cdafbd013994475cd1db5919807f4e537d58b4c | aafecd6bd344ec79298d8aaf0c08426934fc2049 | refs/heads/master | 2021-01-10T22:06:18.964202 | 2009-05-13T19:15:40 | 2009-05-13T19:15:40 | 194,478 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,796 | cpp | /*-----------------------------------------------------------------------------
Mesh.cpp
2009 Shamus Young
-------------------------------------------------------------------------------
This class is used to make constructing objects easier. It handles
allocating vertex lists, polygon lists, and suchlike.
If you were going to implement vertex buffers, this would be the place to
do it. Take away the _vertex member variable and store verts for ALL meshes
in a common list, which could then be unloaded onto the good 'ol GPU.
-----------------------------------------------------------------------------*/
#include <cstdlib>
#include <cstring>
#include <GL/gl.h>
#include <GL/glu.h>
#include "glTypes.h"
#include "Mesh.h"
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
CMesh::CMesh ()
{
_vertex_count = 0;
_triangle_count = 0;
_quad_strip_count = 0;
_fan_count = 0;
_cube_count = 0;
_polycount = 0;
_list = glGenLists(1);
_compiled = false;
_vertex = NULL;
_normal = NULL;
_triangle = NULL;
_cube = NULL;
_quad_strip = NULL;
_fan = NULL;
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
CMesh::~CMesh ()
{
unsigned i;
if (_vertex)
free (_vertex);
if (_normal)
free (_normal);
if (_triangle)
free (_triangle);
if (_cube)
free (_cube);
for (i = 0; i < _quad_strip_count; i++)
delete _quad_strip[i].index_list;
if (_quad_strip)
delete _quad_strip;
for (i = 0; i < _fan_count; i++)
delete _fan[i].index_list;
if (_fan)
delete _fan;
if (_list)
glDeleteLists (_list, 1);
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
void CMesh::VertexAdd (GLvertex v)
{
_vertex = (GLvertex*)realloc (_vertex, sizeof (GLvertex) * (_vertex_count + 1));
_vertex[_vertex_count] = v;
_vertex_count++;
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
void CMesh::CubeAdd (int* index)
{
_cube = (cube*)realloc (_cube, sizeof (cube) * (_cube_count + 1));
memcpy (&_cube[_cube_count].index_list[0], index, sizeof (int) * 10);
_cube_count++;
_polycount += 5;
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
void CMesh::QuadStripAdd (int* index, int count)
{
_quad_strip = (quad_strip*)realloc (_quad_strip, sizeof (quad_strip) * (_quad_strip_count + 1));
_quad_strip[_quad_strip_count].index_list = (int*)malloc (sizeof (int) * count);
_quad_strip[_quad_strip_count].count = count;
memcpy (&_quad_strip[_quad_strip_count].index_list[0], &index[0], sizeof (int) * count);
_quad_strip_count++;
_polycount += (count - 2) / 2;
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
void CMesh::FanAdd (int* index, int count)
{
_fan = (fan*)realloc (_fan, sizeof (fan) * (_fan_count + 1));
_fan[_fan_count].index_list = (int*)malloc (sizeof (int) * count);
_fan[_fan_count].count = count;
memcpy (&_fan[_fan_count].index_list[0], &index[0], sizeof (int) * count);
_fan_count++;
_polycount += count - 2;
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
void CMesh::Render ()
{
unsigned i, n;
int* index;
if (_compiled) {
glCallList (_list);
return;
}
for (i = 0; i < _quad_strip_count; i++) {
index = &_quad_strip[i].index_list[0];
glBegin (GL_QUAD_STRIP);
for (n = 0; n < _quad_strip[i].count; n++) {
glTexCoord2fv (&_vertex[index[n]].uv.x);
glVertex3fv (&_vertex[index[n]].position.x);
}
glEnd ();
}
for (i = 0; i < _cube_count; i++) {
index = &_cube[i].index_list[0];
glBegin (GL_QUAD_STRIP);
for (n = 0; n < 10; n++) {
glTexCoord2fv (&_vertex[index[n]].uv.x);
glVertex3fv (&_vertex[index[n]].position.x);
}
glEnd ();
glBegin (GL_QUADS);
glTexCoord2fv (&_vertex[index[7]].uv.x);
glVertex3fv (&_vertex[index[7]].position.x);
glVertex3fv (&_vertex[index[5]].position.x);
glVertex3fv (&_vertex[index[3]].position.x);
glVertex3fv (&_vertex[index[1]].position.x);
glEnd ();
glBegin (GL_QUADS);
glTexCoord2fv (&_vertex[index[6]].uv.x);
glVertex3fv (&_vertex[index[0]].position.x);
glVertex3fv (&_vertex[index[2]].position.x);
glVertex3fv (&_vertex[index[4]].position.x);
glVertex3fv (&_vertex[index[6]].position.x);
glEnd ();
}
for (i = 0; i < _fan_count; i++) {
index = &_fan[i].index_list[0];
glBegin (GL_TRIANGLE_FAN);
for (n = 0; n < _fan[i].count; n++) {
glTexCoord2fv (&_vertex[index[n]].uv.x);
glVertex3fv (&_vertex[index[n]].position.x);
}
glEnd ();
}
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
void CMesh::Compile ()
{
glNewList (_list, GL_COMPILE);
Render ();
glEndList();
_compiled = true;
}
| [
"youngshamus@c6164f88-37c5-11de-9d05-31133e6853b1",
"[email protected]"
]
| [
[
[
1,
17
],
[
22,
22
],
[
25,
215
]
],
[
[
18,
21
],
[
23,
24
],
[
216,
216
]
]
]
|
a4a8c062edd7574ee84b139c96e303e8f2d5845b | a0bc9908be9d42d58af7a1a8f8398c2f7dcfa561 | /SlonEngine/slon/Database/Storage.h | 2062c0e5e799b12c5f83875bbde55790eab2b642 | []
| 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,930 | h | #ifndef __SLON_ENGINE_DATABASE_STORAGE_H__
#define __SLON_ENGINE_DATABASE_STORAGE_H__
#include <boost/function.hpp>
#include <map>
namespace slon {
namespace database {
/** Storage stores items in associative container */
template<typename Key, typename StorageItem>
class Storage
{
public:
typedef Key key_type;
typedef StorageItem item_type;
typedef boost::function<item_type ()> loader_type;
typedef std::map<Key, StorageItem> container_type;
typedef typename container_type::value_type value_type;
typedef typename container_type::iterator item_iterator;
typedef typename container_type::const_iterator const_item_iterator;
public:
/** Search for item in the storage */
item_iterator find(const key_type& key)
{
item_iterator iter = container.find(key);
return iter;
}
/** Search for item in the storage. If not found, then load it and add to storage */
item_iterator load(const key_type& key, const loader_type& func)
{
item_iterator iter = container.find(key);
if ( iter != container.end() ) {
return iter;
}
return container.insert( value_type(key, func()) ).first;
}
/** Get iterator addressing item after last item */
item_iterator end() { return container.end(); }
/** Remove single item from the storage */
void remove(const item_iterator& iterator) { container.erase(iterator); }
/** Remove all items from the storage */
void clear() { container.clear(); }
private:
container_type container;
};
/** Storage stores items in associative container. Singleton */
template<typename Key, typename StorageItem>
class SingletonStorage :
public Storage<Key, StorageItem>
{
public:
/** Get instance */
static SingletonStorage* Instance()
{
if ( !instance.get() ) {
instance.reset(new SingletonStorage);
}
return instance.get();
}
private:
static std::auto_ptr<SingletonStorage> instance;
};
// static decl
template<typename Key, typename StorageItem>
std::auto_ptr< SingletonStorage<Key, StorageItem> > SingletonStorage<Key, StorageItem>::instance;
/** Look for item in the storage. If not found then call
* loader and add item to the storage.
* @param storage - storage where to look for item.
* @param key - key of the item.
* @param func - item loader functor.
*/
template<typename Key, typename StorageItem>
StorageItem load( Storage<Key, StorageItem>& storage,
const Key& key,
const typename Storage<Key, StorageItem>::loader_type& func )
{
return storage.load(key, func)->second;
}
} // namespace database
} // namespace slon
#endif // __SLON_ENGINE_DATABASE_STORAGE_H__
| [
"devnull@localhost"
]
| [
[
[
1,
97
]
]
]
|
5c34462318c4bf3d347d7109f7182729cd4ad974 | 4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61 | /CleanProject/MyGUI/include/MyGUI_Plugin.h | 483f7ae6827ecbf89c116e3b484e6c465017d6ab | []
| no_license | bahao247/apeengine2 | 56560dbf6d262364fbc0f9f96ba4231e5e4ed301 | f2617b2a42bdf2907c6d56e334c0d027fb62062d | refs/heads/master | 2021-01-10T14:04:02.319337 | 2009-08-26T08:23:33 | 2009-08-26T08:23:33 | 45,979,392 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,663 | h | /*!
@file
@author Denis Koronchik
@date 09/2007
@module
*//*
This file is part of MyGUI.
MyGUI 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 3 of the License, or
(at your option) any later version.
MyGUI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with MyGUI. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __MYGUI_PLUGIN_H__
#define __MYGUI_PLUGIN_H__
#include "MyGUI_Prerequest.h"
namespace MyGUI
{
/*! \brief Base plugin class
*/
class MYGUI_EXPORT IPlugin
{
public:
IPlugin() { }
virtual ~IPlugin() { }
/*! Get the name of the plugin.
@remarks An implementation must be supplied for this method to uniquely
identify the plugin
*/
virtual const std::string& getName() const = 0;
/*! Perform the plugin initial installation sequence
*/
virtual void install() = 0;
/*! Perform any tasks the plugin needs to perform on full system
initialisation.
*/
virtual void initialize() = 0;
/*! Perform any tasks the plugin needs to perform when the system is shut down
*/
virtual void shutdown() = 0;
/*! Perform the final plugin uninstallation sequence
*/
virtual void uninstall() = 0;
};
}
#endif // __MYGUI_PLUGIN_H__
| [
"pablosn@06488772-1f9a-11de-8b5c-13accb87f508"
]
| [
[
[
1,
65
]
]
]
|
a4780e05469064fe959828b5f63b397abb28fca5 | b7c505dcef43c0675fd89d428e45f3c2850b124f | /Src/ControllerQt/LogPlayer.cpp | 3c9ace9340697238880bb43c66619740da5ef344 | [
"BSD-2-Clause"
]
| permissive | pranet/bhuman2009fork | 14e473bd6e5d30af9f1745311d689723bfc5cfdb | 82c1bd4485ae24043aa720a3aa7cb3e605b1a329 | refs/heads/master | 2021-01-15T17:55:37.058289 | 2010-02-28T13:52:56 | 2010-02-28T13:52:56 | null | 0 | 0 | null | null | null | null | ISO-8859-2 | C++ | false | false | 9,014 | cpp | /**
* @file ControllerQt/LogPlayer.cpp
*
* Implementation of class LogPlayer
*
* @author Martin Lötzsch
*/
#include "LogPlayer.h"
#include "Representations/Perception/JPEGImage.h"
#include "Platform/SystemCall.h"
#include "Platform/GTAssert.h"
LogPlayer::LogPlayer(MessageQueue& targetQueue) :
targetQueue(targetQueue)
{
init();
}
void LogPlayer::init()
{
clear();
stop();
numberOfFrames = 0;
numberOfMessagesWithinCompleteFrames = 0;
state = initial;
loop = true; //default: loop enabled
}
bool LogPlayer::open(const char* fileName)
{
InBinaryFile file(fileName);
if(file.exists())
{
clear();
file >> *this;
stop();
countFrames();
return true;
}
return false;
}
void LogPlayer::play()
{
state = playing;
}
void LogPlayer::stop()
{
if (state == recording)
{
recordStop();
return;
}
currentMessageNumber = -1;
currentFrameNumber = -1;
state = initial;
}
void LogPlayer::pause()
{
if(getNumberOfMessages() == 0)
state = initial;
else
state = paused;
}
void LogPlayer::stepBackward()
{
pause();
if(state == paused && currentFrameNumber > 0)
{
do
queue.setSelectedMessageForReading(--currentMessageNumber);
while(currentMessageNumber > 0 && queue.getMessageID() != idProcessFinished);
--currentFrameNumber;
stepRepeat();
}
}
void LogPlayer::stepForward()
{
pause();
if(state == paused && currentFrameNumber < numberOfFrames - 1)
{
do
copyMessage(++currentMessageNumber, targetQueue);
while(queue.getMessageID() != idProcessFinished);
++currentFrameNumber;
}
}
void LogPlayer::stepRepeat()
{
pause();
if(state == paused && currentFrameNumber >= 0)
{
do
queue.setSelectedMessageForReading(--currentMessageNumber);
while(currentMessageNumber > 0 && queue.getMessageID() != idProcessFinished);
--currentFrameNumber;
stepForward();
}
}
void LogPlayer::gotoFrame(int frame)
{
pause();
if(state == paused && frame < numberOfFrames)
{
currentFrameNumber = -1;
currentMessageNumber = -1;
while(++currentMessageNumber < getNumberOfMessages() && frame > currentFrameNumber + 1)
{
queue.setSelectedMessageForReading(currentMessageNumber);
if(queue.getMessageID() == idProcessFinished)
++currentFrameNumber;
}
stepForward();
}
}
bool LogPlayer::save(const char* fileName)
{
if(state == recording)
recordStop();
if(!getNumberOfMessages())
return false;
OutBinaryFile file(fileName);
if(file.exists())
{
file << *this;
return true;
}
return false;
}
bool LogPlayer::saveImages(const bool raw, const char* fileName)
{
struct BmpHeader{
unsigned long k0,k1,k2;
unsigned long ofs1,ofs2;
unsigned long xsiz,ysiz;
unsigned long modbit;
unsigned long z1;
unsigned long len;
unsigned long z2,z3,z4,z5;
} bmpHeader;
char name[512];
char fname[512];
strcpy(name,fileName);
if ((strlen(name)>4)&&((strncmp(name+strlen(name)-4,".bmp",4)==0)||(strncmp(name+strlen(name)-4,".jpg",4)==0)))
{
*(name+strlen(name)-4) = 0;
}
if ((strlen(name)>4)&&((strncmp(name+strlen(name)-4,"_000",4)==0)||(strncmp(name+strlen(name)-4,"_001",4)==0)))
{
*(name+strlen(name)-4) = 0;
}
int i=0;
for (currentMessageNumber=0; currentMessageNumber<getNumberOfMessages();currentMessageNumber++)
{
queue.setSelectedMessageForReading(currentMessageNumber);
Image image;
if(queue.getMessageID() == idImage)
{
in.bin >> image;
}
else if(queue.getMessageID() == idJPEGImage)
{
JPEGImage jpegImage;
in.bin >> jpegImage;
jpegImage.toImage(image);
}
else
continue;
Image rgbImage;
if(!raw)
rgbImage.convertFromYCbCrToRGB(image);
sprintf(fname,"%s_%03i.bmp",name,i++);
OutBinaryFile file(fname);
if (file.exists())
{
long truelinelength=(3*rgbImage.cameraInfo.resolutionWidth+3) & 0xfffffc;
char line[3*320+4];
memset(line,0,truelinelength);
bmpHeader.k0=0x4d420000; //2 dummy bytes 4 alignment, then "BM"
bmpHeader.k1=rgbImage.cameraInfo.resolutionHeight*truelinelength+0x36;
bmpHeader.k2=0;
bmpHeader.ofs1=0x36;
bmpHeader.ofs2=0x28;
bmpHeader.xsiz=rgbImage.cameraInfo.resolutionWidth;
bmpHeader.ysiz=rgbImage.cameraInfo.resolutionHeight;
bmpHeader.modbit=0x00180001;
bmpHeader.z1=0;
bmpHeader.len=truelinelength*rgbImage.cameraInfo.resolutionHeight;
bmpHeader.z2=0;
bmpHeader.z3=0;
bmpHeader.z4=0;
bmpHeader.z5=0;
file.write(2+(char*)&bmpHeader,sizeof(bmpHeader)-2);
for (int i=rgbImage.cameraInfo.resolutionHeight-1; i>=0; i--)
{
int ofs=0;
if(raw)
{
for (int j=0;j<image.cameraInfo.resolutionWidth;j++)
{
line[ofs++]=image.image[i][j].cr;
line[ofs++]=image.image[i][j].cb;
line[ofs++]=image.image[i][j].y;
}
}
else
{
for (int j=0;j<rgbImage.cameraInfo.resolutionWidth;j++)
{
line[ofs++]=rgbImage.image[i][j].b;
line[ofs++]=rgbImage.image[i][j].g;
line[ofs++]=rgbImage.image[i][j].r;
}
}
file.write(line,truelinelength);
}
}
else
{
stop();
return false;
}
}
stop();
return true;
}
void LogPlayer::recordStart()
{
state = recording;
}
void LogPlayer::recordStop()
{
while(getNumberOfMessages() > numberOfMessagesWithinCompleteFrames)
removeLastMessage();
currentMessageNumber = -1;
currentFrameNumber = -1;
state = initial;
}
void LogPlayer::setLoop(bool loop_)
{
loop = loop_;
}
void LogPlayer::handleMessage(InMessage& message)
{
if(state == recording)
{
message >> *this;
if(message.getMessageID() == idProcessFinished)
{
numberOfMessagesWithinCompleteFrames = getNumberOfMessages();
++numberOfFrames;
}
}
}
bool LogPlayer::replay()
{
if(state == playing)
{
if(currentFrameNumber < numberOfFrames - 1)
{
do
copyMessage(++currentMessageNumber, targetQueue);
while(queue.getMessageID() != idProcessFinished);
++currentFrameNumber;
if(currentFrameNumber == numberOfFrames - 1)
{
if (loop) //restart in loop mode
{
gotoFrame(0);
play();
}
else
stop();
}
return true;
}
else
{
if (loop) //restart in loop mode
{
gotoFrame(0);
play();
}
else
stop();
}
}
return false;
}
void LogPlayer::keep(MessageID* messageIDs)
{
LogPlayer temp((MessageQueue&) *this);
moveAllMessages(temp);
for(temp.currentMessageNumber = 0; temp.currentMessageNumber < temp.getNumberOfMessages(); ++temp.currentMessageNumber)
{
temp.queue.setSelectedMessageForReading(temp.currentMessageNumber);
MessageID* m = messageIDs;
while(*m)
{
if(temp.queue.getMessageID() == *m ||
temp.queue.getMessageID() == idProcessBegin ||
temp.queue.getMessageID() == idProcessFinished)
{
temp.copyMessage(temp.currentMessageNumber, *this);
break;
}
++m;
}
}
}
void LogPlayer::remove(MessageID* messageIDs)
{
LogPlayer temp((MessageQueue&) *this);
moveAllMessages(temp);
for(temp.currentMessageNumber = 0; temp.currentMessageNumber < temp.getNumberOfMessages(); ++temp.currentMessageNumber)
{
temp.queue.setSelectedMessageForReading(temp.currentMessageNumber);
MessageID* m = messageIDs;
while(*m)
{
if(temp.queue.getMessageID() == *m ||
temp.queue.getMessageID() == idProcessBegin ||
temp.queue.getMessageID() == idProcessFinished)
break;
++m;
}
if(!*m)
temp.copyMessage(temp.currentMessageNumber, *this);
}
}
void LogPlayer::statistics(int frequency[numOfDataMessageIDs])
{
for(int i = 0; i < numOfDataMessageIDs; ++i)
frequency[i] = 0;
int current = queue.getSelectedMessageForReading();
for(int i = 0; i < getNumberOfMessages(); ++i)
{
queue.setSelectedMessageForReading(i);
ASSERT(queue.getMessageID() < numOfDataMessageIDs);
++frequency[queue.getMessageID()];
}
queue.setSelectedMessageForReading(current);
}
void LogPlayer::countFrames()
{
numberOfFrames = 0;
for(int i = 0; i < getNumberOfMessages(); ++i)
{
queue.setSelectedMessageForReading(i);
if(queue.getMessageID() == idProcessFinished)
{
++numberOfFrames;
numberOfMessagesWithinCompleteFrames = i + 1;
}
}
}
| [
"alon@rogue.(none)"
]
| [
[
[
1,
381
]
]
]
|
d2655b661b9c136f2c5d3771573012cd51fb96df | dcd98d0a6f194aebcfcea02461e59bf62146a454 | /commonimlib/src/chatimplfactory.cpp | d632f234b2a991ee84257d0cd3630e4d44099702 | []
| no_license | lcsouzamenezes/oss.FCL.sf.incubator.rcschat | 736afc3b76e74baab4fd96dc4b59aed59e2b5eec | c353084f4328e7e3cce4d6d16800aae51d75ad6c | refs/heads/master | 2021-06-05T03:33:21.262762 | 2010-10-11T06:36:54 | 2010-10-11T06:36:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,813 | cpp | /*
* Copyright (c) 2009-2010 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:
* RCS IM Library - Initial version
*
*/
#include "chatinterfaces.h"
#include "immanagerfactory.h"
#include "chatimplfactory.h"
#include <QtPlugin>
#include <QDir>
#include <QLibraryInfo>
#include <QPluginLoader>
#include <QCoreApplication>
RcsIMLib::MChatContactManagerIntf* ChatImplFactory::createIMManager(QString protocol)
{
#ifdef Q_OS_SYMBIAN
QDir pluginsDir = QLibraryInfo::location(QLibraryInfo::PluginsPath) + "/IMLIB";
#else
QDir pluginsDir = QCoreApplication::applicationDirPath() + "/resource/qt/plugins/IMLIB";
#endif
/* Now doing a dirty implementation.
* The real thing to do is parse manifests and compare each plugin for
* the protocol string
*/
IMManagerFactory* imManagerFact=0;
foreach (QString fileName, pluginsDir.entryList(QDir::Files))
{
QPluginLoader pluginLoader(pluginsDir.absoluteFilePath(fileName));
QObject *plugin = pluginLoader.instance();
if (plugin)
{
imManagerFact = qobject_cast<IMManagerFactory *>(plugin);
if (imManagerFact && imManagerFact->protocol()==protocol)
{
RcsIMLib::MChatContactManagerIntf* imManager = imManagerFact->createIMManager();
//delete imManagerFact;
return imManager;
}
//delete imManagerFact;
imManagerFact = 0;
}
}
return 0;
}
| [
"none@none"
]
| [
[
[
1,
58
]
]
]
|
8e6f2ebb98ffba13f622a83c43dc964157863b83 | 8aa65aef3daa1a52966b287ffa33a3155e48cc84 | /Source/Math/Path.h | e88df3c8a5f2e487f4cd1219394b8a68e2d7fc61 | []
| no_license | jitrc/p3d | da2e63ef4c52ccb70023d64316cbd473f3bd77d9 | b9943c5ee533ddc3a5afa6b92bad15a864e40e1e | refs/heads/master | 2020-04-15T09:09:16.192788 | 2009-06-29T04:45:02 | 2009-06-29T04:45:02 | 37,063,569 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,706 | h | #pragma once
#include "Range.h"
namespace P3D
{
/*
Default operations over path point.
Implement your explicit template to override.
*/
template<class T>
struct PathPointTypeTraits
{
static T Multiply(Scalar t, const T& val)
{
return t * val;
}
static T Add(const T& val1, const T& val2)
{
return val1 + val2;
}
};
/*
Traits for QTransform.
*/
template<>
struct PathPointTypeTraits<QTransform>
{
static QTransform Multiply(Scalar t, const QTransform& val)
{
return QTransform(val.Translation * t, Quaternion(
val.Rotation.x * t,
val.Rotation.y * t,
val.Rotation.z * t,
val.Rotation.w * t));
}
static QTransform Add(const QTransform& val1, const QTransform& val2)
{
return QTransform(val1.Translation + val2.Translation, Quaternion(
val1.Rotation.x + val2.Rotation.x,
val1.Rotation.y + val2.Rotation.y,
val1.Rotation.z + val2.Rotation.z,
val1.Rotation.w + val2.Rotation.w));
}
};
/*
A set of elements (vectors, quaternions, whatever) with time values.
*/
template<class T>
class Path : public Object
{
typedef typename PathPointTypeTraits<T> Traits;
public:
mathinline Path()
{
MinT = MaxT = 0;
}
/*
Add point to the list.
*/
mathinline void AppendPoint(Scalar time, const T& position)
{
if (time < MinT) MinT = time;
if (time > MaxT) MaxT = time;
PointsList::iterator it = Points.end();
while (it != Points.begin())
{
--it;
if (time >= it->Time)
{
Points.insert(++it, Point(position, time));
//PointAdded(this, time, position);
return;
}
}
Points.push_back(Point(position, time));
//PointAdded(this, time, position);
}
/*
Clears the path.
*/
mathinline void Clear()
{
MinT = MaxT = 0;
Points.clear();
}
/*
Returns interpolated path position.
*/
mathinline void Interpolate(Scalar time, T& outputPos) const
{
if (Points.size() == 0) return;
if (Points.size() == 1)
{
outputPos = Points[0].Position;
return;
}
if (time <= Points[0].Time)
{
outputPos = Points[0].Position;
return;
}
if (time >= Points.back().Time)
{
outputPos = Points.back().Position;
return;
}
int left = 0, right = Points.size();
while ((right - left) != 1)
{
int middle = (left + right) / 2;
Scalar middleVal = Points[middle].Time;
if (time >= middleVal)
left = middle;
else
right = middle;
}
if (Points[left].Time == Points[right].Time) return;
Scalar t = (time - Points[left].Time) / (Points[right].Time - Points[left].Time);
outputPos = Traits::Add(Traits::Multiply((1.0f - t), Points[left].Position),
Traits::Multiply(t, Points[right].Position));
}
/*
Called when point added to the Path.
*/
//signal3<const Path<T>*, Scalar, const T&> PointAdded;
public:
/*
One path element.
*/
struct Point
{
Point()
{}
Point(const T& position, Scalar time)
: Position(position), Time(time)
{ }
Scalar Time;
T Position;
};
typedef std::vector<Point> PointsList;
/*
List of all path points.
*/
PointsList Points;
/*
Minimal value of the parameter.
*/
Scalar MinT;
/*
Maximal value of the parameter.
*/
Scalar MaxT;
};
} | [
"vadun87@6320d0be-1f75-11de-b650-e715bd6d7cf1"
]
| [
[
[
1,
178
]
]
]
|
bd6d688099c47098ec9bb1415542215607eb3751 | ef94f24815a7d85a62b6ce2ddb9ce4a75043e6b6 | /tree.cpp | a56357fde94dca6c6306d702ff737ed93b0ae7b0 | []
| no_license | qartis/djayan | 65a52e5aa666aad52a2b905b61d612f6517d0c08 | 056ae84950b81739d7f3d07e7ad45958c586db78 | refs/heads/master | 2020-06-01T13:19:02.432114 | 2011-11-08T00:23:25 | 2011-11-08T00:23:25 | 2,730,435 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,420 | cpp | #include <FL/Fl.H>
#include <iconv.h>
#include <errno.h>
#include <FL/Fl_Pixmap.H>
#include <FL/Fl_Widget.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Double_Window.H>
#include <FL/Fl_Tree.H>
#include <curl/curl.h>
#include <stdio.h>
#include <regex.h>
#include <vector>
#include "Fl_GIF.H"
#include "folder_open_small.xpm"
#include "folder_closed_small.xpm"
#include "icons.h"
#include "plus.h"
enum types {
CATEGORIES,
ALBUM,
SONG
};
struct xferinfo {
char *buf;
int len;
enum types type;
Fl_Tree *tree;
Fl_Tree_Item *item;
const char *url;
};
struct urlinfo {
char *name;
int name_len;
char *url;
int url_len;
};
static Fl_Pixmap folder_open(folder_open_small_xpm);
static Fl_Pixmap folder_closed(folder_closed_small_xpm);
static Fl_Pixmap document(document_xpm);
static Fl_GIF *spinner = new Fl_GIF("ajax.gif");
void Button_CB(Fl_Widget*w, void*data) {
fprintf(stderr, "'%s' button pushed\n", w->label());
}
const char* reason_as_name(Fl_Tree_Reason reason) {
switch ( reason ) {
case FL_TREE_REASON_NONE: return("none");
case FL_TREE_REASON_SELECTED: return("selected");
case FL_TREE_REASON_DESELECTED: return("deselected");
case FL_TREE_REASON_OPENED: return("opened");
case FL_TREE_REASON_CLOSED: return("closed");
default: return("???");
}
}
void fix_icons(Fl_Tree *tree){
for (Fl_Tree_Item *item = tree->first(); item; item=item->next()){
if (item->has_children()){
if (item->is_open()){
item->usericon(&folder_open);
} else {
item->usericon(&folder_closed);
}
} else {
item->usericon(&document);
}
}
}
void remove_spinner(Fl_Tree_Item *item){
struct xferinfo *info = (struct xferinfo *)item->user_data();
spinner->animating(false);
if (info){
info->tree->redraw();
}
}
static void cb_tree(Fl_Tree *tree, void *data){
Fl_Tree_Item *item = tree->callback_item();
if (!item){
return;
}
struct xferinfo *info = (struct xferinfo *)item->user_data();
printf("label %s reason %s\n", item->label(), reason_as_name(tree->callback_reason()));
if (tree->callback_reason() == FL_TREE_REASON_SELECTED || tree->callback_reason() == FL_TREE_REASON_DESELECTED){
tree->open_toggle(item, 0);
} else
if (item->has_children()){
if (item->is_open()){
item->usericon(&folder_open);
} else {
item->usericon(&folder_closed);
}
} else if (tree->callback_reason() == FL_TREE_REASON_SELECTED){
item->usericon(spinner);
spinner->animating(true);
spinner->parent(tree);
Fl::add_timeout(2.0, (Fl_Timeout_Handler)remove_spinner, (void *)item);
}
}
struct urlinfo grab_url(regex_t *preg, char **pos){
struct urlinfo info = {0};
regmatch_t pmatch[3];
size_t rm;
rm = regexec (preg, *pos, 3, pmatch, 0);
if (rm != REG_NOMATCH){
info.name = *pos + pmatch[1].rm_so;
info.url = *pos + pmatch[2].rm_so;
info.name_len = pmatch[1].rm_eo - pmatch[1].rm_so;
info.url_len = pmatch[2].rm_eo - pmatch[2].rm_so;
*pos = *pos + pmatch[2].rm_eo;
}
return info;
}
int substr_count(const char *haystack, const char *needle) {
const char *p;
int count = 0;
size_t len = strlen(needle);
while ((p = strstr(haystack, needle))) {
count++;
haystack = p + len;
}
return count;
}
char* str_replace(char *from, char *to, char *str){
int count = substr_count(str, from);
if (count < 1) return str;
int width_change = strlen(to) - strlen(from);
char *res = (char *)malloc(strlen(str) + count * width_change + 1);
res[0] = '\0';
char *pos = str;
char *p;
while((p = strcasestr(pos, from))){
strncat(res,pos,p-pos);
strcat(res,to);
pos = p + strlen(from);
}
strcat(res,pos);
free(str);
return res;
}
void look_for_categories(char *buf, Fl_Tree *tree){
regex_t preg;
char *pos = buf;
struct urlinfo info;
regcomp (&preg, "<a [^>]*title=\"([^\"]+)[^>]*href=\"([^\"]+)\">", REG_EXTENDED);
while ((info = grab_url(&preg, &pos)), info.name_len){
char *name = strndup(info.name, info.name_len);
name = str_replace("【","/",name);
name = str_replace("】","/",name);
name = str_replace("专辑","/",name);
Fl_Tree_Item *item = tree->add(name);
free(name);
struct xferinfo *xinfo = (struct xferinfo *)malloc(sizeof(struct xferinfo));
xinfo->tree = tree;
xinfo->url = strndup(info.url, info.url_len);
xinfo->buf = NULL;
xinfo->len = 0;
xinfo->type = ALBUM;
xinfo->item = item;
item->user_data(xinfo);
}
regfree(&preg);
int skip = 2; /* don't close the root or the first category */
for(Fl_Tree_Item *item = tree->first(); item; item=item->next()){
if (skip){
skip--;
} else {
tree->close(item, 0);
}
}
fix_icons(tree);
tree->redraw();
regfree (&preg);
}
char* to_utf8(char *src, size_t srclen){
char *dest = (char *)malloc(srclen * 2);
size_t destlen = srclen * 2;
char * pIn = src;
char * pOut = dest;
iconv_t conv = iconv_open("utf8", "gb2312");
iconv(conv, &pIn, &srclen, &pOut, &destlen);
iconv_close(conv);
free(src);
return dest;
}
void handle_completed_transfer(CURLM *multi){
CURLMsg *msg;
CURL *easy;
int num;
while ((msg = curl_multi_info_read(multi, &num))){
if (msg->msg == CURLMSG_DONE){
struct xferinfo *info;
easy = msg->easy_handle;
curl_easy_getinfo(easy, CURLINFO_PRIVATE, (char **)&info);
if (info->type == CATEGORIES){
info->buf = to_utf8(info->buf, info->len);
look_for_categories(info->buf, info->tree);
free(info->buf);
}
free(info);
curl_multi_remove_handle(multi, easy);
curl_easy_cleanup(easy);
}
}
}
size_t writefunc(char *ptr, size_t size, size_t nmemb, void *userdata){
struct xferinfo *info = (struct xferinfo *)userdata;
info->buf = (char *)realloc(info->buf, info->len + size * nmemb);
memcpy(info->buf + info->len, ptr, size * nmemb);
info->len += size * nmemb;
return size * nmemb;
}
void do_xfer(CURLM *multi){
int still_running;
curl_multi_perform(multi, &still_running);
if (still_running){
Fl::repeat_timeout(0.1, (Fl_Timeout_Handler)do_xfer, (void *)multi);
} else {
handle_completed_transfer(multi);
}
}
void load_categories(CURLM *multi, Fl_Tree *tree){
CURL *easy = curl_easy_init();
struct xferinfo *info = (struct xferinfo *)malloc(sizeof(struct xferinfo));
info->type = CATEGORIES;
info->buf = NULL;
info->len = 0;
info->tree = tree;
info->url = NULL;
curl_easy_setopt(easy, CURLOPT_URL, "localhost/djayan/List_1.html");
curl_easy_setopt(easy, CURLOPT_WRITEDATA, (void *)info);
curl_easy_setopt(easy, CURLOPT_WRITEFUNCTION, writefunc);
curl_easy_setopt(easy, CURLOPT_PRIVATE, (void *)info);
curl_easy_setopt(easy, CURLOPT_VERBOSE, 0L);
curl_easy_setopt(easy, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)");
curl_multi_add_handle(multi, easy);
Fl::add_timeout(0.1, (Fl_Timeout_Handler)do_xfer, (void *)multi);
}
int main(int argc, char **argv) {
Fl::set_font(FL_HELVETICA, "Droid Sans Fallback");
Fl_Double_Window *window = new Fl_Double_Window(550, 450, "tree");
Fl_Tree *tree = new Fl_Tree(5, 5, 550-10, 450-10, "Tree");
tree->end();
window->end();
tree->showroot(0);
tree->callback((Fl_Callback *)cb_tree, (void *)NULL);
CURLM *multi = curl_multi_init();
load_categories(multi, tree);
window->resizable(tree);
window->end();
window->show(argc, argv);
return Fl::run();
}
| [
"[email protected]"
]
| [
[
[
1,
297
]
]
]
|
6e03dd7fff38ba09f0c1f376f1dcb591efa51e0a | d6eba554d0c3db3b2252ad34ffce74669fa49c58 | /Source/States/GameStates/CCreditsState.cpp | 28679981ff0c59f2d96957d36e19a9eb25c44df1 | []
| no_license | nbucciarelli/Polarity-Shift | e7246af9b8c3eb4aa0e6aaa41b17f0914f9d0b10 | 8b9c982f2938d7d1e5bd1eb8de0bdf10505ed017 | refs/heads/master | 2016-09-11T00:24:32.906933 | 2008-09-26T18:01:01 | 2008-09-26T18:01:01 | 3,408,115 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,514 | cpp | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// File: "CCreditsState.cpp"
// Author: Jared Hamby (JH)
// Purpose: Handles the credits state
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "CCreditsState.h"
#include <windows.h>
#include "..\..\EventSystem\eventManager.h"
#include "..\..\EventSystem\globalEvents.h"
#include "..\..\Wrappers\viewManager.h"
#include "../../Helpers/SGD_Math.h"
#include "..\..\game.h"
#include "..\..\Helpers\bitFont.h"
#include "..\..\Wrappers\CSGD_FModManager.h"
#define TEXTSIZE .45f
CCreditsState::CCreditsState(void)
{
foregroundID = viewManager::getInstance()->loadTexture("Resource/Images/PS_Menu.png");
menuItemString = new char*[TOTAL];
menuItemString[BACK] = "Back";
menuLast = BACK;
}
CCreditsState::~CCreditsState(void)
{
viewManager::getInstance()->releaseTexture(foregroundID);
}
CCreditsState* CCreditsState::getInstance()
{
static CCreditsState Elgoog;
return &Elgoog;
}
void CCreditsState::enter(void)
{
m_fSoundLerp = 100;
m_fXLerp = 1024;
m_bMainMenu = false;
m_bIsMoving = true;
m_bIsExiting = false;
m_bIsExited = false;
menuState::enter();
}
void CCreditsState::exit(void)
{
m_bIsMoving = true;
m_fXLerp = 1024;
m_fSoundLerp = 100;
menuState::exit();
}
void CCreditsState::update(float dt)
{
if(!entered)
return;
m_fTime += dt;
if(m_bIsMoving == true)
{
if (dt >= .016f)
{
m_fXPer += .1f;
m_fXLerp = Lerp(1024, 0, m_fXPer);
m_fSoundPer -= .2f;
m_fSoundLerp = Lerp(100, 0, m_fXPer);
m_fSoundLerp *= -1;
// SET PAN FROM RIGHT TO CENTER WITH SOUND LERP
if(!CSGD_FModManager::GetInstance()->IsSoundPlaying(game::GetInstance()->GetSZSCHHHSound()))
CSGD_FModManager::GetInstance()->SetPan(game::GetInstance()->GetSZSCHHHSound(), m_fSoundLerp);
// PLAY SOUND HERE
CSGD_FModManager::GetInstance()->PlaySound(game::GetInstance()->GetSZSCHHHSound());
if(m_fXPer >= 1)
{
m_fXPer = 1;
// STOP SOUND HERE
CSGD_FModManager::GetInstance()->StopSound(game::GetInstance()->GetSZSCHHHSound());
m_bIsMoving = false;
}
}
}
else if(m_bIsExiting == true)
{
if (dt >= .016f)
{
m_fXPer -= .1f;
m_fXLerp = Lerp(1024, 0, m_fXPer);
m_fSoundPer -= .2f;
m_fSoundLerp = Lerp(0, 100, m_fSoundPer);
m_fSoundLerp *= -1;
// SET PAN FROM CENTER TO RIGHT WITH SOUND LERP
CSGD_FModManager::GetInstance()->SetPan(game::GetInstance()->GetSZSCHHHSound(), m_fSoundLerp);
// PLAY SOUND HERE
if(!CSGD_FModManager::GetInstance()->IsSoundPlaying(game::GetInstance()->GetSZSCHHHSound()))
CSGD_FModManager::GetInstance()->PlaySound(game::GetInstance()->GetSZSCHHHSound());
if(m_fXPer <= 0)
{
m_fXPer = 0;
// STOP SOUND HERE
CSGD_FModManager::GetInstance()->StopSound(game::GetInstance()->GetSZSCHHHSound());
m_bIsExiting = false;
m_bIsExited = true;
}
}
}
if(m_bIsExited == true)
{
if(m_bMainMenu == true)
EM->sendGlobalEvent(GE_STATE_CHANGETO, new int(STATE_MAINMENU));
}
}
void CCreditsState::menuHandler()
{
switch(menuPos)
{
case BACK:
m_bIsExiting = true;
m_bMainMenu = true;
break;
}
}
void CCreditsState::render(void) const
{
if(!entered)
return;
viewManager::getInstance()->drawTexture(foregroundID, &vector3(20 + m_fXLerp, 0, 0));
theFont->drawText("Credits", (int)(373 + m_fXLerp), 65, textColor, 1);
//Draw menu items
theFont->drawText("Nick Bucciarelli - Project Officer", (int)(200 + m_fXLerp + xPos), 440, textColor, TEXTSIZE);
theFont->drawText("Jared Hamby - Interface Officer/Art", (int)(200 + m_fXLerp + xPos), 480, textColor, TEXTSIZE);
theFont->drawText("Lee Nyman - Gameplay Officer", (int)(200 + m_fXLerp + xPos), 520, textColor, TEXTSIZE);
theFont->drawText("Scott Smallback - Technical Officer", (int)(200 + m_fXLerp + xPos), 560, textColor, TEXTSIZE);
theFont->drawText("Dustin Clingman - Executive Producer", (int)(200 + m_fXLerp + xPos), 640, textColor, TEXTSIZE);
theFont->drawText("Ronald Powell - Associate Producer", (int)(200 + m_fXLerp + xPos), 680, textColor, TEXTSIZE);
theFont->drawText("Chris Jahosky - Art", (int)(200 + m_fXLerp + xPos), 760, textColor, TEXTSIZE);
theFont->drawText(menuItemString[BACK], (int)(20 + m_fXLerp + xPos), 675, highlightColor);
} | [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
6
],
[
8,
8
],
[
11,
15
],
[
17,
18
],
[
21,
22
],
[
25,
26
],
[
31,
31
],
[
36,
37
],
[
42,
47
],
[
50,
50
],
[
53,
55
],
[
58,
58
],
[
60,
64
],
[
66,
109
],
[
112,
116
],
[
123,
125
],
[
128,
149
]
],
[
[
7,
7
],
[
9,
10
],
[
16,
16
],
[
19,
20
],
[
23,
24
],
[
27,
30
],
[
32,
35
],
[
38,
41
],
[
48,
49
],
[
51,
52
],
[
56,
57
],
[
59,
59
],
[
65,
65
],
[
110,
111
],
[
117,
122
],
[
126,
127
],
[
150,
150
]
]
]
|
47dd9a139bb478b86fe9e41169fcfbe6c988850e | 55196303f36aa20da255031a8f115b6af83e7d11 | /private/external/gameswf/net/http_server.cpp | 37639ecd7f49e50263fd8d0001c25141b7af59fe | []
| no_license | Heartbroken/bikini | 3f5447647d39587ffe15a7ae5badab3300d2a2ff | fe74f51a3a5d281c671d303632ff38be84d23dd7 | refs/heads/master | 2021-01-10T19:48:40.851837 | 2010-05-25T19:58:52 | 2010-05-25T19:58:52 | 37,190,932 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,829 | cpp | // http_server.cpp -- Thatcher Ulrich http://tulrich.com 2005
// This source code has been donated to the Public Domain. Do
// whatever you want with it.
// Very simple HTTP server. Intended for embedding in games or other
// apps, for monitoring/tweaking.
//
// HTTP 1.1 protocol defined here:
// http://www.w3.org/Protocols/rfc2616/rfc2616.html
//
// "EHS - Embedded HTTP Server" http://xaxxon.slackworks.com/EHS.html
// has very similar goals. Unfortunately it's LGPL.
#include "net/http_server.h"
#include "net/net_interface.h"
#include "base/tu_timer.h"
#include "base/logger.h"
void http_request::dump_html(tu_string* outptr)
// Debug helper.
//
// Append our contents into the given string, in HTML format.
{
tu_string& out = *outptr;
out += "Request info:<br>\n";
out += "status: ";
char buf[200];
sprintf(buf, "%d<br>\n", int(m_status));
out += buf;
out += "method: ";
out += m_method;
out += "<br>\n";
out += "uri: ";
out += m_uri;
out += "<br>\n";
out += "path: ";
out += m_path;
out += "<br>\n";
out += "file: ";
out += m_file;
out += "<br>\n";
out += "params:<br><ul>\n";
for (string_hash<array<tu_string>* >::iterator it = m_param.begin(); it != m_param.end(); ++it)
{
for (int i = 0, n = it->second->size(); i < n; i++) {
out += "<li><b>";
out += it->first;
out += "</b> - ";
out += (*it->second)[i];
out += "</li>\n";
}
}
out += "</ul><br>\n";
out += "headers:<br><ul>\n";
for (string_hash<tu_string>::iterator it = m_header.begin(); it != m_header.end(); ++it)
{
out += "<li><b>";
out += it->first;
out += "</b> - ";
out += it->second;
out += "</li>\n";
}
out += "</ul><br>\n";
out += "body: <br><pre>";
out += m_body;
out += "\n</pre><br>";
}
http_server::http_server(net_interface* net)
:
m_net(net)
{
}
http_server::~http_server()
{
for (int i = 0; i < m_state.size(); i++) {
delete m_state[i];
}
m_state.resize(0);
if (m_net)
{
delete m_net;
m_net = NULL;
}
}
bool http_server::add_handler(const char* path, http_handler* handler)
// Hook a handler, return true on success.
{
if (m_handlers.get(path, NULL))
{
// Already linked this one!
return false;
}
m_handlers.add(path, handler);
return true;
}
void http_server::update()
// Call this periodically to serve pending requests.
{
// if (active sockets < 10 or so)
// Check for new connections.
net_socket* sock = m_net->accept();
if (sock) {
// Find or create a state for this socket.
int use_state = -1;
for (int i = 0; i < m_state.size(); i++) {
if (!m_state[i]->is_alive()) {
// Re-use this state.
use_state = i;
break;
}
}
if (use_state == -1) {
use_state = m_state.size();
m_state.push_back(new http_request_state);
}
m_state[use_state]->activate(sock);
printf("accepted new socket on state %d\n", use_state);//xxxxxx
}
// Update any active requests.
static const float UPDATE_TIMEOUT_SECONDS = 0.100f;
uint64 start = tu_timer::get_ticks();
uint64 last_activity_ticks = start;
for (;;) {
int active_requests = 0;
for (int i = 0; i < m_state.size(); i++) {
if (!m_state[i]->is_alive()) {
continue;
}
m_state[i]->update(this);
if (m_state[i]->is_alive() == false || m_state[i]->is_pending() == false) {
continue;
}
active_requests++;
last_activity_ticks = tu_timer::get_ticks();
}
if (!active_requests) {
break;
}
// Even when there are pending requests, don't block
// for very long.
uint64 now = tu_timer::get_ticks();
if (tu_timer::ticks_to_seconds(now - start) >= UPDATE_TIMEOUT_SECONDS)
{
printf("state long timed out ****\n");//xxxxxx
break;
}
tu_timer::sleep(0);
}
}
void http_server::send_response(http_request* req, const char* content_type, const void* data, int len)
// Send a known-length response.
{
tu_string header = string_printf(
"HTTP/1.1 %d %s\r\nContent-length: %d\r\n"
"Content-type: %s\r\n"
"\r\n"
,
int(req->m_status),
req->m_status >= 400 ? "ERROR" : "OK",
len,
content_type);
req->m_sock->write(header.c_str(), header.length(), 0.010f);
req->m_sock->write(data, len, 0.010f);
VLOG("send_response: \n%s\n", header.c_str());
}
void http_server::dispatch_request(http_request* req)
// Return a response for the given request.
{
assert(req);
assert(req->m_sock);
VLOG("dispatch_request: \n%s\n", req);
if (! req->m_sock->is_open())
{
// Can't respond, just ignore the request.
return;
}
if (req->m_status >= 400)
{
// Minimal error response.
tu_string error_body = string_printf(
"<html><head><title>Error %d</title></head><body>Error %d</body></html>", req->m_status, req->m_status);
send_html_response(req, error_body);
return;
}
// Look at the request, and dispatch it to the appropriate
// handler.
// Try the paths to see if there's a corresponding handler, in
// order from most specific to least specific.
const char* path = req->m_path.c_str();
const char* last_slash = path + req->m_path.length();
for (;;)
{
// Key is a subset of the path.
tu_string key(path, last_slash - path);
http_handler* handler(NULL);
if (m_handlers.get(key, &handler))
{
// Dispatch.
handler->handle_request(this, key, req);
return;
}
// Shrink the key.
const char* next_last_slash_in_key = strrchr(key.c_str(), '/');
if (next_last_slash_in_key == NULL)
{
// Done checking subkeys of this path.
break;
}
int slash_index = next_last_slash_in_key - key.c_str();
last_slash = path + slash_index;
}
// No handler found for this request, return error.
req->m_status = HTTP_NOT_FOUND;
tu_string error_string = "<html><head><title>Error 404</title></head>"
"<body>Error 404 - No handler for object</body></html>";
send_html_response(req, error_string);
}
void http_server::http_request_state::update(http_server* server)
// Continues processing the request. Deactivates our state when the
// request is finished.
{
if (! is_alive()) {
return;
}
int bytes_in;
static const int MAX_LINE_BYTES = 32768; // very generous, but not insane, max line size.
static const float CONNECTION_TIMEOUT = 300.0f; // How long to leave the socket open.
if (m_request_state == IDLE) {
// Watch for the start of a new request.
if (m_req.m_sock->is_readable() == false) {
uint64 now = tu_timer::get_ticks();
if (tu_timer::ticks_to_seconds(now - m_last_activity) > CONNECTION_TIMEOUT) {
// Timed out; close the socket.
deactivate();
printf("socket timed out, deactivating.\n");//xxxxxx
}
// Idle.
return;
} else {
// We have some data on the socket; start
// parsing it.
m_request_state = PARSE_START_LINE;
m_last_activity = tu_timer::get_ticks();
// Fall through and start processing.
//printf("socket is now readable\n");//xxxx
}
}
if (m_req.m_sock->is_open() == false) {
// The connection closed on us -- abort the current request!
deactivate();
printf("socket closed, deactivating.\n");//xxxxxx
return;
}
switch (m_request_state)
{
default:
// Invalid state.
assert(0);
deactivate();
break;
case PARSE_START_LINE:
case PARSE_HEADER:
// wait for a whole line, parse it.
bytes_in = m_req.m_sock->read_line(&m_line_buffer, MAX_LINE_BYTES - m_line_buffer.length(), 0.010f);
if (m_line_buffer.length() >= 2 && m_line_buffer[m_line_buffer.length() - 1] == '\n')
{
//printf("req got header line: %s", m_line_buffer.c_str());//xxxxxx
// We have the whole line. Parse and continue.
m_req.m_status = parse_message_line(m_line_buffer.c_str());
if (m_req.m_status >= 400)
{
m_line_buffer.clear();
m_request_state = PARSE_DONE;
}
// else we're either still in the header, or
// process_header changed our parse state.
m_line_buffer.clear();
}
else if (m_line_buffer.length() >= MAX_LINE_BYTES)
{
printf("req invalid header line length\n");//xxxxxx
// Invalid line.
m_line_buffer.clear();
m_req.m_status = HTTP_BAD_REQUEST;
m_request_state = PARSE_DONE;
}
break;
case PARSE_BODY_IDENTITY:
case PARSE_BODY_CHUNKED_CHUNK:
case PARSE_BODY_CHUNKED_TRAILER:
m_req.m_status = parse_body();
if (m_req.m_status >= 400)
{
// Something bad happened.
m_request_state = PARSE_DONE;
}
break;
case PARSE_DONE:
// Respond to the request.
server->dispatch_request(&m_req);
// Leave the connection open, but go idle, waiting for
// another request.
m_request_state = IDLE;
m_last_activity = tu_timer::get_ticks();
clear();
break;
}
}
void http_server::http_request_state::activate(net_socket* sock)
// Initialize to handle a request coming in on the given socket.
{
VLOG("hrs::activate(%x)", sock);
deactivate();
// Adopt the given socket.
assert(m_req.m_sock == NULL);
m_req.m_sock = sock;
m_last_activity = tu_timer::get_ticks();
}
void http_server::http_request_state::deactivate()
// Clear request state & close the socket.
{
VLOG("hrs::deactivate(), sock = %x\n", m_req.m_sock);
clear();
m_req.deactivate();
}
void http_server::http_request_state::clear()
// Clear out request state, but don't mess with our socket.
{
VLOG("hrs::clear(), sock = %x\n", m_req.m_sock);
m_req.clear();
m_line_buffer.clear();
m_parse_key.clear();
m_parse_value.clear();
m_request_state = IDLE;
m_content_length = -1;
}
bool is_linear_whitepace(char c)
{
return c == ' ' || c == '\t';
}
bool is_whitespace(char c)
{
return is_linear_whitepace(c) || c == '\r' || c == '\n';
}
tu_string trim_whitespace(const char* buf)
// Return the arg with whitespace at either end trimmed off.
{
const char* c = buf;
while (is_whitespace(c[0]))
{
c++;
}
int end = strlen(c);
while (end > 0 && is_whitespace(c[end - 1]))
{
end--;
}
return tu_string(c, end);
}
http_status http_server::http_request_state::parse_message_line(const char* line)
// Parse the next line.
{
VLOG("parse_message_line: '%s'\n", line);
http_status status = HTTP_BAD_REQUEST;
switch (m_request_state)
{
default:
case PARSE_DONE:
assert(0);
break;
case PARSE_START_LINE:
status = parse_request_line(line);
if (status < 400)
{
// Move on to the rest of the header.
m_request_state = PARSE_HEADER;
}
break;
case PARSE_HEADER:
status = parse_header_line(line);
break;
}
return status;
}
http_status http_server::http_request_state::parse_request_line(const char* reqline)
// Parses the first line of an HTTP request. Fills in fields in m_req
// appropriately. Returns HTTP result code, 400+ if we detected an
// error, HTTP_OK if the parse is OK.
{
VLOG("parse_request_line(), sock = %x: %s\n", m_req.m_sock, reqline);
// Method.
const char* first_space = strchr(reqline, ' ');
if (first_space == NULL || first_space == reqline)
{
// No method.
return HTTP_BAD_REQUEST;
}
m_req.m_method = tu_string(reqline, first_space - reqline);
// URI.
const char* second_space = strchr(first_space + 1, ' ');
if (second_space == NULL || second_space == first_space + 1)
{
// No URI.
return HTTP_BAD_REQUEST;
}
m_req.m_uri = tu_string(first_space + 1, second_space - first_space - 1);
// HTTP version.
const char* version = second_space + 1;
if (strncmp(version, "HTTP/1.0", 8) == 0)
{
m_req.m_http_version_x256 = 0x0100;
}
else if (strncmp(version, "HTTP/1.1", 8) == 0)
{
m_req.m_http_version_x256 = 0x0101;
}
else
{
return HTTP_HTTP_VERSION_NOT_SUPPORTED;
}
return HTTP_OK; // OK so far.
}
http_status http_server::http_request_state::parse_header_line(const char* hline)
// Parse a header line. Call this multiple lines, once with each
// header line, to build up m_req.
//
// Sets m_request_state to PARSE_BODY if hline is the last header line.
//
// Returns an error code >= 400 on error; < 400 on success.
{
assert(m_request_state == PARSE_HEADER);
if (hline[0] == '\r' && hline[1] == '\n')
{
// End of the header.
// Finish the previous key.
if (m_parse_key.length())
{
m_req.m_header.set(m_parse_key, m_parse_value);
}
return process_header();
}
if (is_linear_whitepace(hline[0]))
{
// Looks like a continuation.
if (m_parse_key.length())
{
m_parse_value += " ";
m_parse_value += trim_whitespace(hline);
return HTTP_OK;
}
else
{
// Non-continuation line starts with whitespace.
return HTTP_BAD_REQUEST;
}
}
// Finish any previous key.
if (m_parse_key.length())
{
m_req.m_header.set(m_parse_key, m_parse_value);
m_parse_key = "";
m_parse_value = "";
}
const char* first_colon = strchr(hline, ':');
if (first_colon == NULL || first_colon == hline)
{
return HTTP_BAD_REQUEST;
}
// Start a key/value pair.
m_parse_key = tu_string(hline, first_colon - hline).utf8_to_lower();
// Fill in any value-so-far from an earlier occurrence of this header.
assert(m_parse_value.length() == 0);
m_req.m_header.get(m_parse_key, &m_parse_value);
if (m_parse_value.length())
{
m_parse_value += ",";
}
m_parse_value += trim_whitespace(first_colon + 1);
return HTTP_OK;
}
static const int MAX_CONTENT_LENGTH_ACCEPTED = 32768;
int hex_to_int(char c)
// Convert a hex digit ([0-9] or [a-fA-F]) to an integer [0,15].
// Return -1 if the character is not a hex digit.
{
if (c >= '0' && c <= '9') {
return c - '0';
} else if (c >= 'a' && c <= 'f') {
return 10 + (c - 'a');
} else if (c >= 'A' && c <= 'F') {
return 10 + (c - 'A');
}
return -1;
}
static void unescape_url_component(tu_string* str)
// Do URL unescaping on a URL component. I.e. convert the hex code
// "%xx" to the corresponding byte, and change '+' to ' '.
{
tu_string out;
for (int i = 0; i < str->length(); i++) {
char c = (*str)[i];
if (c == '%'
&& i + 2 < str->length()) {
// Interpret the next two chars as hex digits.
char digit_hi = (*str)[i + 1];
char digit_lo = (*str)[i + 2];
int val_hi = hex_to_int(digit_hi);
int val_lo = hex_to_int(digit_lo);
if (val_hi < 0 || val_lo < 0) {
// Invalid hex digits. Pass the '%'
// straight through and don't consume the
// two following chars.
out += c;
} else {
char encoded = (val_hi << 4) | (val_lo);
if (encoded > 0) {
out += encoded;
}
i += 2;
}
} else if (c == '+') {
// '+' is turned into a space.
out += ' ';
} else {
// Pass this character straight through.
out += c;
}
}
*str = out;
}
void http_server::http_request_state::parse_query_string(const char* query)
// Parses a URL-encoded query string. Puts decoded param/value pairs
// into m_req.m_params.
{
while (query) {
const char* equals = strchr(query, '=');
tu_string param;
tu_string value;
if (equals) {
param = tu_string(query, equals - query);
// Find the end of the value and update the query.
query = strchr(query, '&');
if (query) {
value = tu_string(equals + 1, query - (equals + 1));
query++; // Skip the '&'
} else {
value = equals + 1;
}
} else {
const char* next_query = strchr(query, '&');
if (next_query) {
param = tu_string(query, next_query - query);
next_query++; // Skip the '&'
} else {
param = query;
}
query = next_query;
}
unescape_url_component(¶m);
unescape_url_component(&value);
if (param.length()) {
m_req.add_param(param, value);
}
}
}
http_status http_server::http_request_state::process_header()
// Call this after finishing parsing the header. Sets the following
// parse state. Returns an HTTP status code.
{
assert(m_request_state == PARSE_HEADER);
assert(m_req.m_body.length() == 0);
// Set up path/file vars.
const char* pathend = strchr(m_req.m_uri.c_str(), '?');
const char* query = NULL;
if (pathend) {
query = pathend + 1;
} else {
pathend = m_req.m_uri.c_str() + m_req.m_uri.length();
}
m_req.m_path = tu_string(m_req.m_uri.c_str(), pathend - m_req.m_uri.c_str());
unescape_url_component(&m_req.m_path);
const char* filestart = strrchr(m_req.m_path.c_str(), '/');
if (filestart)
{
m_req.m_file = (filestart + 1);
unescape_url_component(&m_req.m_file);
}
// Parse params in the request string.
parse_query_string(query);
m_content_length = -1;
tu_string content_length_str;
if (m_req.m_header.get("content-length", &content_length_str))
{
m_content_length = atol(content_length_str.c_str());
if (m_content_length > MAX_CONTENT_LENGTH_ACCEPTED)
{
m_request_state = PARSE_DONE;
return HTTP_REQUEST_ENTITY_TOO_LARGE;
}
}
tu_string transfer_encoding;
if (m_req.m_header.get("transfer-encoding", &transfer_encoding))
{
if (transfer_encoding.to_tu_stringi() == "chunked")
{
// We're required to ignore the content-length
// header.
m_content_length = -1;
m_request_state = PARSE_BODY_CHUNKED_CHUNK;
return parse_body();
}
else if (transfer_encoding.to_tu_stringi() == "identity")
{
// This is OK; basically a no-op.
}
else
{
// A transfer encoding we don't know how to handle.
// Reject it.
m_request_state = PARSE_DONE;
return HTTP_NOT_IMPLEMENTED;
}
}
// If there's a body section, then we need to read it & parse it.
if (m_content_length >= 0)
{
m_request_state = PARSE_BODY_IDENTITY;
return parse_body();
}
else
{
m_request_state = PARSE_DONE;
}
return HTTP_OK;
}
http_status http_server::http_request_state::parse_body()
// Read the body section from the socket and fills m_req.m_body.
//
// Sets m_request_state to PARSE_DONE.
//
// Returns an error code >= 400 on error; < 400 on success.
{
assert(m_req.m_body.length() == 0);
// Get the body data and stash it in m_req.m_body.
switch (m_request_state)
{
default:
assert(0);
break;
case PARSE_BODY_IDENTITY:
m_request_state = PARSE_DONE;
// We assume we can get the whole body within 100 ms.
m_req.m_body.resize(m_content_length);
int bytes_read = m_req.m_sock->read(&(m_req.m_body[0]), m_content_length, 0.100f);
if (bytes_read < m_content_length)
{
return HTTP_BAD_REQUEST;
}
break;
#if 0
case PARSE_BODY_CHUNKED_CHUNK:
read a line;
get chunk size;
while (chunk_size > 0)
{
read chunk data and CRLF;
m_body += chunk data;
read a line;
get chunk size;
}
read entity_header;
while (entity_header.length() > 0)
{
parse entity_header;
read entity_header;
}
m_request_state = PARSE_DONE;
break;
#endif // 0
}
// Parse the body data if necessary.
tu_string type_str;
if (m_req.m_method == "POST" && m_req.m_header.get("content-type", &type_str)) {
if (type_str == "application/x-www-form-urlencoded") {
// Parse "Content-type: application/x-www-form-urlencoded" in the body
//
// Basically this is a long string that looks like:
//
// key1=value1&key2=value2&key3=value3 [...]
//
// I.e. just like in the URL.
//
// http://www.w3.org/TR/REC-html40/interact/forms.html says
// it's "the default content type". Quote from that doc:
//
// 1. Control names and values are escaped. Space
// characters are replaced by `+', and then reserved
// characters are escaped as described in [RFC1738],
// section 2.2: Non-alphanumeric characters are replaced by
// `%HH', a percent sign and two hexadecimal digits
// representing the ASCII code of the character. Line
// breaks are represented as "CR LF" pairs (i.e.,
// `%0D%0A').
//
// 2. The control names/values are listed in the order they
// appear in the document. The name is separated from the
// value by `=' and name/value pairs are separated from
// each other by `&'.
parse_query_string(m_req.m_body.c_str());
} else if (type_str == "multipart/form-data") {
// Parse "Content-type: multipart/form-data" in the body
// (i.e. file uploads, non-ASCII fields, ... -- what else?)
// etc...
// // each part has a header like: Content-disposition: form-data; name="something"
// // each part optionally has a Content-type: header. The default is "text/plain".
// // each part may have a Content-transfer-encoding:, if it differs from the body
//
// // http://www.faqs.org/rfcs/rfc2388.html covers multipart/form-data for HTTP 1.1
// // http://www.faqs.org/rfcs/rfc2046.html covers MIME multipart encoding generically
return HTTP_UNSUPPORTED_MEDIA_TYPE;
} else {
return HTTP_UNSUPPORTED_MEDIA_TYPE;
}
}
return HTTP_OK;
}
#ifdef HTTP_SERVER_TEST
// Compile with e.g.:
//
// cl http_server.cpp -Fehttp_server_test.exe -DHTTP_SERVER_TEST -I.. -Od -Zi -MD ../base/base.lib /link /NODEFAULTLIB:msvcprt.lib
/*static*/ void http_server::parse_test()
{
// Test the parsing of the request line (first line).
static struct reqline_test_vector
{
const char* reqline;
http_status status;
const char* method;
const char* uri;
int version_x256;
}
tests[] =
{
{ "GET http://tulrich.com/index.html HTTP/1.1", HTTP_OK, "GET", "http://tulrich.com/index.html", 0x0101 },
{ "POST /index.html HTTP/1.1", HTTP_OK, "POST", "/index.html", 0x0101 },
{ "PUT * HTTP/1.0", HTTP_OK, "PUT", "*", 0x0100 },
{ "OPTIONS http://localhost/ HTTP/1.1", HTTP_OK, "OPTIONS", "http://tulrich.com/", 0x0101 },
{ "HEAD * HTTP/1.2", HTTP_HTTP_VERSION_NOT_SUPPORTED, "HEAD", "*", 0x0102 },
{ "nospaces", HTTP_BAD_REQUEST, "", "", 0 },
{ "one spaces", HTTP_BAD_REQUEST, "", "", 0 },
{ "too many spaces", HTTP_BAD_REQUEST, "", "", 0 },
{ "too many spaces", HTTP_HTTP_VERSION_NOT_SUPPORTED, "", "", 0 },
};
for (int i = 0; i < ARRAYSIZE(tests); i++)
{
http_server::http_request_state state;
int status = state.parse_request_line(tests[i].reqline);
if (status >= 400)
{
// Make sure test is expected to fail.
assert(tests[i].status >= 400);
printf("status = %d, expected = %d\n", status, int(tests[i].status));
}
else
{
assert(state.m_req.m_method == tests[i].method);
assert(state.m_req.m_uri == tests[i].uri);
assert(state.m_req.m_http_version_x256 == tests[i].version_x256);
printf("reqline = %s\n", tests[i].reqline);
printf("Req method = %s\n", state.m_req.m_method.c_str());
printf("Req URI = %s\n", state.m_req.m_uri.c_str());
printf("Req version = 0x%X\n", state.m_req.m_http_version_x256);
}
printf("\n");
}
// Test parsing of whole header.
static struct header_test_vector
{
const char* headertext;
http_status status;
const char* path;
const char* file;
const char* arg_list;
const char* argval_list;
}
tests2[] =
{
{ "GET http://127.0.0.1/path/to/SomeJunk.html?a=1&b=2 HTTP/1.1\r\n"
"Host: 127.0.0.1\r\n"
"User-Agent: something or other\r\n"
"\r\n"
"" // Message body
,
HTTP_OK,
"path/to",
"SomeJunk.html",
"a,b",
"1,2"
};
}
int main()
{
http_server::parse_test();
return 0;
}
#endif // HTTP_SERVER_TEST
// Local Variables:
// mode: C++
// c-basic-offset: 8
// tab-width: 8
// indent-tabs-mode: t
// End:
| [
"viktor.reutskyy@68c2588f-494f-0410-aecb-65da31d84587"
]
| [
[
[
1,
958
]
]
]
|
95632828ee9bb0cc3619dfa207390dbb74b686b6 | 6e016fa119b56ecf0ce40625a651ebba74418b2e | /misc/WindowsMonitor/CommonMisc.h | dbf79f0ae63c88f683c28d8ef980b373cb7d9762 | []
| no_license | smartdj/multi-desktop-manager | 3d382b2b4105d6666a0bfcbebba9e4540868b86f | 98d79b423389b75223affdbd514ea3a45fe42898 | refs/heads/master | 2016-09-05T12:11:27.996006 | 2010-08-01T14:42:39 | 2010-08-01T14:42:39 | 37,246,600 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 924 | h | //CommonMisc.h
#pragma once
//--------------------------------------------------------------------
// Constant variable
//--------------------------------------------------------------------
//--------------------------------------------------------------------
// Type define
//--------------------------------------------------------------------
//--------------------------------------------------------------------
// Inline function
//--------------------------------------------------------------------
template<class T> inline unsigned int NumOfArray(T t)
{
return sizeof( T )/sizeof( T[ 0 ] );
}
template<class T> inline void Safe_Release(T t)
{
if ( t )
{
t->Release();
t = 0;
}
}
template<class T> inline void Safe_Delete(T t)
{
if ( t )
{
delete t;
t = 0;
}
}
template<class T> inline void Safe_Delete_Array(T t)
{
if ( t )
{
delete [] t;
t = 0;
}
} | [
"angelipin@7ff612aa-105e-4e35-adfd-5cdac6c44c12"
]
| [
[
[
1,
41
]
]
]
|
59b654b495849dc6d4635be3dbebcc7d7d92977b | b22c254d7670522ec2caa61c998f8741b1da9388 | /dependencies/OpenSceneGraph/include/osg/Array | d3cace7902b9633df00fa9d5866486b856422669 | []
| no_license | ldaehler/lbanet | 341ddc4b62ef2df0a167caff46c2075fdfc85f5c | ecb54fc6fd691f1be3bae03681e355a225f92418 | refs/heads/master | 2021-01-23T13:17:19.963262 | 2011-03-22T21:49:52 | 2011-03-22T21:49:52 | 39,529,945 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 18,968 | /* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details.
*/
#ifndef OSG_ARRAY
#define OSG_ARRAY 1
#include <osg/MixinVector>
#include <osg/Vec2>
#include <osg/Vec3>
#include <osg/Vec4>
#include <osg/Vec2d>
#include <osg/Vec3d>
#include <osg/Vec4d>
#include <osg/Vec4ub>
#include <osg/Vec2s>
#include <osg/Vec3s>
#include <osg/Vec4s>
#include <osg/Vec2b>
#include <osg/Vec3b>
#include <osg/Vec4b>
#include <osg/Matrix>
#include <osg/BufferObject>
#include <osg/Object>
#include <osg/GL>
namespace osg {
class ArrayVisitor;
class ConstArrayVisitor;
class ValueVisitor;
class ConstValueVisitor;
class OSG_EXPORT Array : public BufferData
{
public:
enum Type
{
ArrayType = 0,
ByteArrayType = 1,
ShortArrayType = 2,
IntArrayType = 3,
UByteArrayType = 4,
UShortArrayType = 5,
UIntArrayType = 6,
Vec4ubArrayType = 7,
FloatArrayType = 8,
Vec2ArrayType = 9,
Vec3ArrayType = 10,
Vec4ArrayType = 11,
Vec2sArrayType = 12,
Vec3sArrayType = 13,
Vec4sArrayType = 14,
Vec2bArrayType = 15,
Vec3bArrayType = 16,
Vec4bArrayType = 17,
DoubleArrayType = 18,
Vec2dArrayType = 19,
Vec3dArrayType = 20,
Vec4dArrayType = 21,
MatrixArrayType = 22
};
Array(Type arrayType=ArrayType,GLint dataSize=0,GLenum dataType=0):
_arrayType(arrayType),
_dataSize(dataSize),
_dataType(dataType) {}
Array(const Array& array,const CopyOp& copyop=CopyOp::SHALLOW_COPY):
BufferData(array,copyop),
_arrayType(array._arrayType),
_dataSize(array._dataSize),
_dataType(array._dataType) {}
virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const Array*>(obj)!=NULL; }
virtual const char* libraryName() const { return "osg"; }
virtual const char* className() const;
virtual void accept(ArrayVisitor&) = 0;
virtual void accept(ConstArrayVisitor&) const = 0;
virtual void accept(unsigned int index,ValueVisitor&) = 0;
virtual void accept(unsigned int index,ConstValueVisitor&) const = 0;
/** Return -1 if lhs element is less than rhs element, 0 if equal,
* 1 if lhs element is greater than rhs element. */
virtual int compare(unsigned int lhs,unsigned int rhs) const = 0;
Type getType() const { return _arrayType; }
GLint getDataSize() const { return _dataSize; }
GLenum getDataType() const { return _dataType; }
virtual const GLvoid* getDataPointer() const = 0;
virtual unsigned int getTotalDataSize() const = 0;
virtual unsigned int getNumElements() const = 0;
/** Frees unused space on this vector - i.e. the difference between size() and max_size() of the underlying vector.*/
virtual void trim() {}
/** Set the VertexBufferObject.*/
inline void setVertexBufferObject(osg::VertexBufferObject* vbo) { setBufferObject(vbo); }
/** Get the VertexBufferObject. If no VBO is assigned returns NULL*/
inline osg::VertexBufferObject* getVertexBufferObject() { return dynamic_cast<osg::VertexBufferObject*>(_bufferObject.get()); }
/** Get the const VertexBufferObject. If no VBO is assigned returns NULL*/
inline const osg::VertexBufferObject* getVertexBufferObject() const { return dynamic_cast<const osg::VertexBufferObject*>(_bufferObject.get()); }
protected:
virtual ~Array() {}
Type _arrayType;
GLint _dataSize;
GLenum _dataType;
};
template<typename T, Array::Type ARRAYTYPE, int DataSize, int DataType>
class TemplateArray : public Array, public MixinVector<T>
{
public:
TemplateArray() : Array(ARRAYTYPE,DataSize,DataType) {}
TemplateArray(const TemplateArray& ta,const CopyOp& copyop=CopyOp::SHALLOW_COPY):
Array(ta,copyop),
MixinVector<T>(ta) {}
TemplateArray(unsigned int no) :
Array(ARRAYTYPE,DataSize,DataType),
MixinVector<T>(no) {}
TemplateArray(unsigned int no,const T* ptr) :
Array(ARRAYTYPE,DataSize,DataType),
MixinVector<T>(ptr,ptr+no) {}
template <class InputIterator>
TemplateArray(InputIterator first,InputIterator last) :
Array(ARRAYTYPE,DataSize,DataType),
MixinVector<T>(first,last) {}
TemplateArray& operator = (const TemplateArray& array)
{
if (this==&array) return *this;
assign(array.begin(),array.end());
return *this;
}
virtual Object* cloneType() const { return new TemplateArray(); }
virtual Object* clone(const CopyOp& copyop) const { return new TemplateArray(*this,copyop); }
inline virtual void accept(ArrayVisitor& av);
inline virtual void accept(ConstArrayVisitor& av) const;
inline virtual void accept(unsigned int index,ValueVisitor& vv);
inline virtual void accept(unsigned int index,ConstValueVisitor& vv) const;
virtual int compare(unsigned int lhs,unsigned int rhs) const
{
const T& elem_lhs = (*this)[lhs];
const T& elem_rhs = (*this)[rhs];
if (elem_lhs<elem_rhs) return -1;
if (elem_rhs<elem_lhs) return 1;
return 0;
}
/** Frees unused space on this vector - i.e. the difference between size() and max_size() of the underlying vector.*/
virtual void trim()
{
MixinVector<T>( *this ).swap( *this );
}
virtual const GLvoid* getDataPointer() const { if (!this->empty()) return &this->front(); else return 0; }
virtual unsigned int getTotalDataSize() const { return static_cast<unsigned int>(this->size()*sizeof(T)); }
virtual unsigned int getNumElements() const { return static_cast<unsigned int>(this->size()); }
typedef T ElementDataType; // expose T
protected:
virtual ~TemplateArray() {}
};
class OSG_EXPORT IndexArray : public Array
{
public:
IndexArray(Type arrayType=ArrayType,GLint dataSize=0,GLenum dataType=0):
Array(arrayType,dataSize,dataType) {}
IndexArray(const Array& array,const CopyOp& copyop=CopyOp::SHALLOW_COPY):
Array(array,copyop) {}
virtual bool isSameKindAs(const Object* obj) const { return dynamic_cast<const IndexArray*>(obj)!=NULL; }
virtual unsigned int index(unsigned int pos) const = 0;
protected:
virtual ~IndexArray() {}
};
template<typename T, Array::Type ARRAYTYPE, int DataSize, int DataType>
class TemplateIndexArray : public IndexArray, public MixinVector<T>
{
public:
TemplateIndexArray() : IndexArray(ARRAYTYPE,DataSize,DataType) {}
TemplateIndexArray(const TemplateIndexArray& ta,const CopyOp& copyop=CopyOp::SHALLOW_COPY):
IndexArray(ta,copyop),
MixinVector<T>(ta) {}
TemplateIndexArray(unsigned int no) :
IndexArray(ARRAYTYPE,DataSize,DataType),
MixinVector<T>(no) {}
TemplateIndexArray(unsigned int no,T* ptr) :
IndexArray(ARRAYTYPE,DataSize,DataType),
MixinVector<T>(ptr,ptr+no) {}
template <class InputIterator>
TemplateIndexArray(InputIterator first,InputIterator last) :
IndexArray(ARRAYTYPE,DataSize,DataType),
MixinVector<T>(first,last) {}
TemplateIndexArray& operator = (const TemplateIndexArray& array)
{
if (this==&array) return *this;
assign(array.begin(),array.end());
return *this;
}
virtual Object* cloneType() const { return new TemplateIndexArray(); }
virtual Object* clone(const CopyOp& copyop) const { return new TemplateIndexArray(*this,copyop); }
inline virtual void accept(ArrayVisitor& av);
inline virtual void accept(ConstArrayVisitor& av) const;
inline virtual void accept(unsigned int index,ValueVisitor& vv);
inline virtual void accept(unsigned int index,ConstValueVisitor& vv) const;
virtual int compare(unsigned int lhs,unsigned int rhs) const
{
const T& elem_lhs = (*this)[lhs];
const T& elem_rhs = (*this)[rhs];
if (elem_lhs<elem_rhs) return -1;
if (elem_rhs<elem_lhs) return 1;
return 0;
}
/** Frees unused space on this vector - i.e. the difference between size() and max_size() of the underlying vector.*/
virtual void trim()
{
MixinVector<T>( *this ).swap( *this );
}
virtual const GLvoid* getDataPointer() const { if (!this->empty()) return &this->front(); else return 0; }
virtual unsigned int getTotalDataSize() const { return static_cast<unsigned int>(this->size()*sizeof(T)); }
virtual unsigned int getNumElements() const { return static_cast<unsigned int>(this->size()); }
virtual unsigned int index(unsigned int pos) const { return (*this)[pos]; }
typedef T ElementDataType; // expose T
protected:
virtual ~TemplateIndexArray() {}
};
typedef TemplateIndexArray<GLbyte,Array::ByteArrayType,1,GL_BYTE> ByteArray;
typedef TemplateIndexArray<GLshort,Array::ShortArrayType,1,GL_SHORT> ShortArray;
typedef TemplateIndexArray<GLint,Array::IntArrayType,1,GL_INT> IntArray;
typedef TemplateIndexArray<GLubyte,Array::UByteArrayType,1,GL_UNSIGNED_BYTE> UByteArray;
typedef TemplateIndexArray<GLushort,Array::UShortArrayType,1,GL_UNSIGNED_SHORT> UShortArray;
typedef TemplateIndexArray<GLuint,Array::UIntArrayType,1,GL_UNSIGNED_INT> UIntArray;
typedef TemplateArray<GLfloat,Array::FloatArrayType,1,GL_FLOAT> FloatArray;
typedef TemplateArray<Vec2,Array::Vec2ArrayType,2,GL_FLOAT> Vec2Array;
typedef TemplateArray<Vec3,Array::Vec3ArrayType,3,GL_FLOAT> Vec3Array;
typedef TemplateArray<Vec4,Array::Vec4ArrayType,4,GL_FLOAT> Vec4Array;
typedef TemplateArray<Vec4ub,Array::Vec4ubArrayType,4,GL_UNSIGNED_BYTE> Vec4ubArray;
typedef TemplateArray<Vec2s,Array::Vec2sArrayType,2,GL_SHORT> Vec2sArray;
typedef TemplateArray<Vec3s,Array::Vec3sArrayType,3,GL_SHORT> Vec3sArray;
typedef TemplateArray<Vec4s,Array::Vec4sArrayType,4,GL_SHORT> Vec4sArray;
typedef TemplateArray<Vec2b,Array::Vec2bArrayType,2,GL_BYTE> Vec2bArray;
typedef TemplateArray<Vec3b,Array::Vec3bArrayType,3,GL_BYTE> Vec3bArray;
typedef TemplateArray<Vec4b,Array::Vec4bArrayType,4,GL_BYTE> Vec4bArray;
typedef TemplateArray<GLdouble,Array::DoubleArrayType,1,GL_DOUBLE> DoubleArray;
typedef TemplateArray<Vec2d,Array::Vec2dArrayType,2,GL_DOUBLE> Vec2dArray;
typedef TemplateArray<Vec3d,Array::Vec3dArrayType,3,GL_DOUBLE> Vec3dArray;
typedef TemplateArray<Vec4d,Array::Vec4dArrayType,4,GL_DOUBLE> Vec4dArray;
typedef TemplateArray<Matrixf,Array::MatrixArrayType,16,GL_FLOAT> MatrixfArray;
class ArrayVisitor
{
public:
ArrayVisitor() {}
virtual ~ArrayVisitor() {}
virtual void apply(Array&) {}
virtual void apply(ByteArray&) {}
virtual void apply(ShortArray&) {}
virtual void apply(IntArray&) {}
virtual void apply(UByteArray&) {}
virtual void apply(UShortArray&) {}
virtual void apply(UIntArray&) {}
virtual void apply(FloatArray&) {}
virtual void apply(DoubleArray&) {}
virtual void apply(Vec2Array&) {}
virtual void apply(Vec3Array&) {}
virtual void apply(Vec4Array&) {}
virtual void apply(Vec4ubArray&) {}
virtual void apply(Vec2bArray&) {}
virtual void apply(Vec3bArray&) {}
virtual void apply(Vec4bArray&) {}
virtual void apply(Vec2sArray&) {}
virtual void apply(Vec3sArray&) {}
virtual void apply(Vec4sArray&) {}
virtual void apply(Vec2dArray&) {}
virtual void apply(Vec3dArray&) {}
virtual void apply(Vec4dArray&) {}
virtual void apply(MatrixfArray&) {}
};
class ConstArrayVisitor
{
public:
ConstArrayVisitor() {}
virtual ~ConstArrayVisitor() {}
virtual void apply(const Array&) {}
virtual void apply(const ByteArray&) {}
virtual void apply(const ShortArray&) {}
virtual void apply(const IntArray&) {}
virtual void apply(const UByteArray&) {}
virtual void apply(const UShortArray&) {}
virtual void apply(const UIntArray&) {}
virtual void apply(const FloatArray&) {}
virtual void apply(const DoubleArray&) {}
virtual void apply(const Vec2Array&) {}
virtual void apply(const Vec3Array&) {}
virtual void apply(const Vec4Array&) {}
virtual void apply(const Vec4ubArray&) {}
virtual void apply(const Vec2bArray&) {}
virtual void apply(const Vec3bArray&) {}
virtual void apply(const Vec4bArray&) {}
virtual void apply(const Vec2sArray&) {}
virtual void apply(const Vec3sArray&) {}
virtual void apply(const Vec4sArray&) {}
virtual void apply(const Vec2dArray&) {}
virtual void apply(const Vec3dArray&) {}
virtual void apply(const Vec4dArray&) {}
virtual void apply(const MatrixfArray&) {}
};
class ValueVisitor
{
public:
ValueVisitor() {}
virtual ~ValueVisitor() {}
virtual void apply(GLbyte&) {}
virtual void apply(GLshort&) {}
virtual void apply(GLint&) {}
virtual void apply(GLushort&) {}
virtual void apply(GLubyte&) {}
virtual void apply(GLuint&) {}
virtual void apply(GLfloat&) {}
virtual void apply(GLdouble&) {}
virtual void apply(Vec2&) {}
virtual void apply(Vec3&) {}
virtual void apply(Vec4&) {}
virtual void apply(Vec4ub&) {}
virtual void apply(Vec2b&) {}
virtual void apply(Vec3b&) {}
virtual void apply(Vec4b&) {}
virtual void apply(Vec2s&) {}
virtual void apply(Vec3s&) {}
virtual void apply(Vec4s&) {}
virtual void apply(Vec2d&) {}
virtual void apply(Vec3d&) {}
virtual void apply(Vec4d&) {}
virtual void apply(Matrixf&) {}
};
class ConstValueVisitor
{
public:
ConstValueVisitor() {}
virtual ~ConstValueVisitor() {}
virtual void apply(const GLbyte&) {}
virtual void apply(const GLshort&) {}
virtual void apply(const GLint&) {}
virtual void apply(const GLushort&) {}
virtual void apply(const GLubyte&) {}
virtual void apply(const GLuint&) {}
virtual void apply(const GLfloat&) {}
virtual void apply(const GLdouble&) {}
virtual void apply(const Vec4ub&) {}
virtual void apply(const Vec2&) {}
virtual void apply(const Vec3&) {}
virtual void apply(const Vec4&) {}
virtual void apply(const Vec2b&) {}
virtual void apply(const Vec3b&) {}
virtual void apply(const Vec4b&) {}
virtual void apply(const Vec2s&) {}
virtual void apply(const Vec3s&) {}
virtual void apply(const Vec4s&) {}
virtual void apply(const Vec2d&) {}
virtual void apply(const Vec3d&) {}
virtual void apply(const Vec4d&) {}
virtual void apply(const Matrixf&) {}
};
template<typename T, Array::Type ARRAYTYPE, int DataSize, int DataType>
inline void TemplateArray<T,ARRAYTYPE,DataSize,DataType>::accept(ArrayVisitor& av) { av.apply(*this); }
template<typename T, Array::Type ARRAYTYPE, int DataSize, int DataType>
inline void TemplateArray<T,ARRAYTYPE,DataSize,DataType>::accept(ConstArrayVisitor& av) const { av.apply(*this); }
template<typename T, Array::Type ARRAYTYPE, int DataSize, int DataType>
inline void TemplateArray<T,ARRAYTYPE,DataSize,DataType>::accept(unsigned int index,ValueVisitor& vv) { vv.apply( (*this)[index] ); }
template<typename T, Array::Type ARRAYTYPE, int DataSize, int DataType>
inline void TemplateArray<T,ARRAYTYPE,DataSize,DataType>::accept(unsigned int index,ConstValueVisitor& vv) const { vv.apply( (*this)[index] );}
template<typename T, Array::Type ARRAYTYPE, int DataSize, int DataType>
inline void TemplateIndexArray<T,ARRAYTYPE,DataSize,DataType>::accept(ArrayVisitor& av) { av.apply(*this); }
template<typename T, Array::Type ARRAYTYPE, int DataSize, int DataType>
inline void TemplateIndexArray<T,ARRAYTYPE,DataSize,DataType>::accept(ConstArrayVisitor& av) const { av.apply(*this); }
template<typename T, Array::Type ARRAYTYPE, int DataSize, int DataType>
inline void TemplateIndexArray<T,ARRAYTYPE,DataSize,DataType>::accept(unsigned int index,ValueVisitor& vv) { vv.apply( (*this)[index] ); }
template<typename T, Array::Type ARRAYTYPE, int DataSize, int DataType>
inline void TemplateIndexArray<T,ARRAYTYPE,DataSize,DataType>::accept(unsigned int index,ConstValueVisitor& vv) const { vv.apply( (*this)[index] );}
}
#endif
| [
"vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13"
]
| [
[
[
1,
491
]
]
]
|
|
02e81fa14f42f90778328d25dfcf90a3f5590159 | 59ce53af7ad5a1f9b12a69aadbfc7abc4c4bfc02 | /src/SkinResEditor/SkinResDocument.cpp | 63e14414dda341114ec71df455ded9fb110712a4 | []
| no_license | fingomajom/skinengine | 444a89955046a6f2c7be49012ff501dc465f019e | 6bb26a46a7edac88b613ea9a124abeb8a1694868 | refs/heads/master | 2021-01-10T11:30:51.541442 | 2008-07-30T07:13:11 | 2008-07-30T07:13:11 | 47,892,418 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,648 | cpp | #include "StdAfx.h"
#include "SkinResDocument.h"
#include "SkinItemIdMgt.h"
SkinResDocument::SkinResDocument(void) :
m_pskinconfig(NULL)
{
m_strFileName = IDS_EMPTY_FILENAME;
m_bModify = FALSE;
}
SkinResDocument::~SkinResDocument(void)
{
}
BOOL SkinResDocument::NewDocument()
{
BOOL bResult = FALSE;
SkinItemIdMgt::instance().Clear();
bResult = m_resStrDoc.NewResDoc();
if (!bResult)
return bResult;
bResult = m_resImageDoc.NewResDoc();
if (!bResult)
return bResult;
bResult = m_resMenuDoc.NewResDoc();
if (!bResult)
return bResult;
bResult = m_resDialogDoc.NewResDoc();
if (!bResult)
return bResult;
if (m_pskinconfig != NULL)
delete m_pskinconfig;
m_pskinconfig = new skinconfig;
m_pskinconfig->m_pathSkinResPath.RemoveFileSpec();
m_pskinconfig->m_pathSkinResPath.RemoveFileSpec();
m_pskinconfig->m_pathSkinImagePath = m_pskinconfig->m_pathSkinResPath;
m_pskinconfig->m_pathSkinImagePath.Append(_T("images"));
m_resImageDoc.m_pskinconfig = m_pskinconfig;
_Module.init_skin(NULL, m_pskinconfig);
m_strFileName = IDS_EMPTY_FILENAME;
m_bModify = FALSE;
return bResult;
}
BOOL SkinResDocument::OpenDocument(const KSGUI::CString& strFileName)
{
BOOL bResult = FALSE;
KSGUI::SkinXmlDocument doc;
bResult = doc.LoadFile(strFileName);
if (!bResult)
return bResult;
SkinItemIdMgt::instance().Clear();
OpenDocument(doc);
CPath path = strFileName;
path.RemoveFileSpec();
if (m_pskinconfig != NULL)
delete m_pskinconfig;
m_pskinconfig = new skinconfig;
m_pskinconfig->m_pathSkinResPath = path;
path.Append(_T("images"));
m_pskinconfig->m_pathSkinImagePath = path;
m_resImageDoc.m_pskinconfig = m_pskinconfig;
_Module.init_skin(strFileName.Mid(m_pskinconfig->m_pathSkinResPath.m_strPath.GetLength() ),
m_pskinconfig);
KSGUI::CString strOnlyFileName = path.FindFileName();
m_strFileName = strFileName;
m_bModify = FALSE;
return bResult;
}
BOOL SkinResDocument::OpenDocument(KSGUI::SkinXmlDocument& doc)
{
m_resStrDoc.OpenResDoc(doc);
m_resImageDoc.OpenResDoc(doc);
m_resMenuDoc.OpenResDoc(doc);
m_resDialogDoc.OpenResDoc(doc);
return TRUE;
}
BOOL SkinResDocument::SaveDocument(const KSGUI::CString& strFileName)
{
BOOL bResult = FALSE;
KSGUI::SkinXmlDocument doc;
bResult = SaveDocument(doc);
if (!bResult)
return bResult;
m_strFileName = strFileName;
m_bModify = FALSE;
doc.SaveFile(strFileName);
return bResult;
}
BOOL SkinResDocument::SaveDocument(KSGUI::SkinXmlDocument& doc)
{
BOOL bResult = FALSE;
LPCTSTR pszDefResXML = _T("<?xml version=\"1.0\" encoding=\"UTF-8\"?><KSGUI></KSGUI>");
bResult = doc.LoadXML(pszDefResXML);
if (!bResult)
return bResult;
m_resStrDoc.SaveResDoc(doc);
m_resImageDoc.SaveResDoc(doc);
m_resMenuDoc.SaveResDoc(doc);
m_resDialogDoc.SaveResDoc(doc);
return bResult;
}
const KSGUI::CString& SkinResDocument::GetFileName() const
{
return m_strFileName;
}
BOOL SkinResDocument::Modify() const
{
return m_bModify;
}
void SkinResDocument::Modify(BOOL bModify)
{
m_bModify = bModify;
}
BOOL SkinResDocument::CheckValid( BOOL bShowErrorMsg )
{
if (!m_resDialogDoc.CheckValid(bShowErrorMsg))
return FALSE;
return TRUE;
} | [
"[email protected]"
]
| [
[
[
1,
168
]
]
]
|
42f079290be8a9c817f75d12a5a827c354f724ac | 724cded0e31f5fd52296d516b4c3d496f930fd19 | /inc/jrtp/rtcpcompoundpacket.h | 4796d8bba12f37cd1272bfb4fa55d5ad70403a77 | []
| no_license | yubik9/p2pcenter | 0c85a38f2b3052adf90b113b2b8b5b312fefcb0a | fc4119f29625b1b1f4559ffbe81563e6fcd2b4ea | refs/heads/master | 2021-08-27T15:40:05.663872 | 2009-02-19T00:13:33 | 2009-02-19T00:13:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,652 | h | /*
This file is a part of JRTPLIB
Copyright (c) 1999-2006 Jori Liesenborgs
Contact: [email protected]
This library was developed at the "Expertisecentrum Digitale Media"
(http://www.edm.uhasselt.be), a research center of the Hasselt University
(http://www.uhasselt.be). The library is based upon work done for
my thesis at the School for Knowledge Technology (Belgium/The Netherlands).
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.
*/
#ifndef RTCPCOMPOUNDPACKET_H
#define RTCPCOMPOUNDPACKET_H
#include "rtpconfig.h"
#include "rtptypes.h"
#include <list>
class RTPRawPacket;
class RTCPPacket;
class RTCPCompoundPacket
{
public:
RTCPCompoundPacket(RTPRawPacket &rawpack);
protected:
RTCPCompoundPacket(); // this is for the compoundpacket builder
public:
virtual ~RTCPCompoundPacket();
int GetCreationError() { return error; }
uint8_t *GetCompoundPacketData() { return compoundpacket; }
size_t GetCompoundPacketLength() { return compoundpacketlength; }
void GotoFirstPacket() { rtcppackit = rtcppacklist.begin(); }
// Note: the individual RTCPPackets may NOT be deleted!
RTCPPacket *GetNextPacket() { if (rtcppackit == rtcppacklist.end()) return 0; RTCPPacket *p = *rtcppackit; rtcppackit++; return p; }
#ifdef RTPDEBUG
void Dump();
#endif // RTPDEBUG
protected:
void ClearPacketList();
int error;
uint8_t *compoundpacket;
size_t compoundpacketlength;
std::list<RTCPPacket *> rtcppacklist;
std::list<RTCPPacket *>::const_iterator rtcppackit;
};
#endif // RTCPCOMPOUNDPACKET_H
| [
"fuwenke@b5bb1052-fe17-11dd-bc25-5f29055a2a2d"
]
| [
[
[
1,
79
]
]
]
|
6c6ef39859a7f67d22b4832eef0fc152fd8a0086 | f18a69245fd5b30b430d998f718ac477838c85ad | /ELF_decoder/ELF_file_decode/hook.cpp | bea250ee5144fbafeac695877a14201775c11e1f | []
| no_license | Coderdu/linux-hook-api | 4a6a61337fea0fe614f27f74a2a27726affb31ae | 9033d8c3d4eb08c906bea158bf07528f6fe550c3 | refs/heads/master | 2020-04-04T06:34:27.395570 | 2010-08-23T10:54:47 | 2010-08-23T10:54:47 | 33,172,776 | 3 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 90 | cpp | #include "stdafx.h"
#include "hook.h"
int hook_api(char *func)
{
return 0;
}
| [
"fifywang@a6e85a67-8fff-a3b3-25c0-fd83a3513f0e"
]
| [
[
[
1,
9
]
]
]
|
eb33f3fc0657a7b70d4a1b5318871b921999d209 | b4f709ac9299fe7a1d3fa538eb0714ba4461c027 | /trunk/position.cpp | 49fabc679a2171f3d7bc98e7aab55c41dc84e67f | []
| no_license | BackupTheBerlios/ptparser-svn | d953f916eba2ae398cc124e6e83f42e5bc4558f0 | a18af9c39ed31ef5fd4c5e7b69c3768c5ebb7f0c | refs/heads/master | 2020-05-27T12:26:21.811820 | 2005-11-06T14:23:18 | 2005-11-06T14:23:18 | 40,801,514 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,141 | cpp | /////////////////////////////////////////////////////////////////////////////
// Name: position.cpp
// Purpose: Stores and renders a position (a group of notes, or a rest)
// Author: Brad Larsen
// Modified by:
// Created: Dec 17, 2004
// RCS-ID:
// Copyright: (c) Brad Larsen
// License: wxWindows license
/////////////////////////////////////////////////////////////////////////////
#include "stdwx.h"
#include "position.h"
#include "powertabfileheader.h" // Needed for file version constants
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// Constants
// Default Constants
const wxByte Position::DEFAULT_POSITION = 0;
const wxByte Position::DEFAULT_BEAMING = 0;
const wxUint32 Position::DEFAULT_DATA = (wxUint32)(DEFAULT_DURATION_TYPE << 24);
const wxByte Position::DEFAULT_DURATION_TYPE = 8;
// Position Constants
const wxUint32 Position::MIN_POSITION = 0;
const wxUint32 Position::MAX_POSITION = 255;
// Irregular Grouping Constants
const wxByte Position::MIN_IRREGULAR_GROUPING_NOTES_PLAYED = 2;
const wxByte Position::MAX_IRREGULAR_GROUPING_NOTES_PLAYED = 16;
const wxByte Position::MIN_IRREGULAR_GROUPING_NOTES_PLAYED_OVER = 2;
const wxByte Position::MAX_IRREGULAR_GROUPING_NOTES_PLAYED_OVER = 8;
const wxByte Position::MAX_VOLUME_SWELL_DURATION = 8;
const wxByte Position::MAX_TREMOLO_BAR_DURATION = 8;
const wxByte Position::MAX_TREMOLO_BAR_PITCH = 28;
// Multibar Rest Constants
const wxByte Position::MIN_MULTIBAR_REST_MEASURE_COUNT = 2;
const wxByte Position::MAX_MULTIBAR_REST_MEASURE_COUNT = 255;
/// Default Constructor
Position::Position() :
m_position(DEFAULT_POSITION), m_beaming(DEFAULT_BEAMING), m_data(DEFAULT_DATA)
{
//------Last Checked------//
// - Jan 18, 2005
ClearComplexSymbolArrayContents();
}
/// Primary Constructor
/// @param position Zero-based index within the system where the position is anchored
/// @param durationType Duration type to set (1 = whole, 2 = half, 4 = quarter, 8 = 8th, 16 = 16th, 32 = 32nd, 64 = 64th)
/// @param dotCount Number of duration dots to set
Position::Position(wxUint32 position, wxByte durationType, wxByte dotCount) :
m_position(position), m_beaming(DEFAULT_BEAMING), m_data(DEFAULT_DATA)
{
//------Last Checked------//
// - Jan 18, 2005
wxASSERT(IsValidPosition(position));
wxASSERT(IsValidDurationType(durationType));
SetDurationType(durationType);
if (dotCount == 1)
SetDotted();
else if (dotCount == 2)
SetDoubleDotted();
ClearComplexSymbolArrayContents();
}
/// Copy Constructor
Position::Position(const Position& position) :
m_position(DEFAULT_POSITION), m_beaming(DEFAULT_BEAMING), m_data(DEFAULT_DATA)
{
//------Last Checked------//
// - Dec 17, 2004
*this = position;
}
/// Destructor
Position::~Position()
{
//------Last Checked------//
// - Jan 18, 2005
ClearComplexSymbolArrayContents();
m_noteArray.DeleteContents();
}
/// Assignment Operator
const Position& Position::operator=(const Position& position)
{
//------Last Checked------//
// - Jan 18, 2005
// Check for assignment to self
if (this != &position)
{
m_position = position.m_position;
m_beaming = position.m_beaming;
m_data = position.m_data;
size_t i = 0;
for (; i < MAX_POSITION_COMPLEX_SYMBOLS; i++)
m_complexSymbolArray[i] = position.m_complexSymbolArray[i];
m_noteArray.Copy(position.m_noteArray);
}
return (*this);
}
/// Equality Operator
bool Position::operator==(const Position& position) const
{
//------Last Checked------//
// - Jan 19, 2005
wxArrayInt thisComplexSymbolArray;
wxArrayInt thatComplexSymbolArray;
wxUint32 i = 0;
for (; i < MAX_POSITION_COMPLEX_SYMBOLS; i++)
{
thisComplexSymbolArray.Add(m_complexSymbolArray[i]);
thatComplexSymbolArray.Add(position.m_complexSymbolArray[i]);
}
thisComplexSymbolArray.Sort(wxCompareIntegers);
thatComplexSymbolArray.Sort(wxCompareIntegers);
i = 0;
for (; i < MAX_POSITION_COMPLEX_SYMBOLS; i++)
{
if (thisComplexSymbolArray[i] != thatComplexSymbolArray[i])
return (false);
}
return (
(m_position == position.m_position) &&
(m_beaming == position.m_beaming) &&
(m_data == position.m_data) &&
(m_noteArray.Equals(position.m_noteArray))
);
}
/// Inequality Operator
bool Position::operator!=(const Position& position) const
{
//------Last Checked------//
// - Dec 17, 2004
return (!operator==(position));
}
// Serialization Functions
/// Performs serialization for the class
/// @param stream Power Tab output stream to serialize to
/// @return True if the object was serialized, false if not
bool Position::DoSerialize(PowerTabOutputStream& stream)
{
//------Last Checked------//
// - Jan 17, 2005
stream << m_position << m_beaming << m_data;
wxCHECK(stream.CheckState(), false);
wxByte complexCount = GetComplexSymbolCount();
stream << complexCount;
wxCHECK(stream.CheckState(), false);
size_t i = 0;
for (; i < complexCount; i++)
{
stream << m_complexSymbolArray[i];
wxCHECK(stream.CheckState(), false);
}
m_noteArray.Serialize(stream);
wxCHECK(stream.CheckState(), false);
return (stream.CheckState());
}
/// Performs deserialization for the class
/// @param stream Power Tab input stream to load from
/// @param version File version
/// @return True if the object was deserialized, false if not
bool Position::DoDeserialize(PowerTabInputStream& stream, wxWord version)
{
//------Last Checked------//
// - Jan 17, 2005
// Version 1.0/1.0.2 beaming updated
if (version == PowerTabFileHeader::FILEVERSION_1_0 || version == PowerTabFileHeader::FILEVERSION_1_0_2)
{
stream >> m_position >> m_beaming >> m_data;
wxCHECK(stream.CheckState(), false);
// All we have to do is move the irregular flags to the duration variable, the document will be rebeamed in the CDocument::Serialize()
if ((m_beaming & 0x2000) == 0x2000)
m_data |= irregularGroupingStart;
if ((m_beaming & 0x4000) == 0x4000)
m_data |= irregularGroupingMiddle;
if ((m_beaming & 0x8000) == 0x8000)
m_data |= irregularGroupingEnd;
wxByte complexCount;
stream >> complexCount;
wxCHECK(stream.CheckState(), false);
// Read the symbols
size_t i = 0;
for (; i < complexCount; i++)
{
stream >> m_complexSymbolArray[i];
wxCHECK(stream.CheckState(), false);
}
m_noteArray.Deserialize(stream, version);
wxCHECK(stream.CheckState(), false);
}
// Version 1.5 and up
else
{
stream >> m_position >> m_beaming >> m_data;
wxCHECK(stream.CheckState(), false);
wxByte complexCount;
stream >> complexCount;
wxCHECK(stream.CheckState(), false);
// Read the symbols
size_t i = 0;
for (; i < complexCount; i++)
{
stream >> m_complexSymbolArray[i];
wxCHECK(stream.CheckState(), false);
}
m_noteArray.Deserialize(stream, version);
wxCHECK(stream.CheckState(), false);
}
return (stream.CheckState());
}
// Duration Type Functions
/// Sets the duration type
/// @param durationType Duration type to set (1 = whole, 2 = half, 4 = quarter, 8 = 8th, 16 = 16th, 32 = 32nd, 64 = 64th)
/// @return True if the duration type was set, false if not
bool Position::SetDurationType(wxByte durationType)
{
//------Last Checked------//
// - Jan 18, 2005
wxCHECK(IsValidDurationType(durationType), false);
// Duration type is stored in power of two format
m_data &= ~durationTypeMask;
m_data |= (wxUint32)(durationType << 24);
return (true);
}
/// Gets the duration type (1 = whole, 2 = half, 4 = quarter, 8 = 8th, 16 = 16th)
/// @return The duration type
wxByte Position::GetDurationType() const
{
//------Last Checked------//
// - Jan 18, 2005
return ((wxByte)((m_data & durationTypeMask) >> 24));
}
// Irregular Grouping Functions
/// Sets the irregular grouping timing
/// @param notesPlayed Number of notes played
/// @param notesPlayedOver Number of notes played over
/// @return True if the irregular grouping timing was set, false if not
bool Position::SetIrregularGroupingTiming(wxByte notesPlayed, wxByte notesPlayedOver)
{
//------Last Checked------//
// - Jan 18, 2005
wxCHECK(IsValidIrregularGroupingTiming(notesPlayed, notesPlayedOver), false);
// Values are stored as 1-15 and 1-7
notesPlayed--;
notesPlayedOver--;
m_beaming &= ~irregularGroupingTimingMask;
m_beaming |= (wxWord)(notesPlayed << 3);
m_beaming |= (wxWord)notesPlayedOver;
return (true);
}
/// Gets the irregular grouping timing
/// @param notesPlayed Top value for the irregular grouping timing
/// @param notesPlayedOver Bottom value for the irregular grouping timing
/// @return True if the irregular grouping was set, false if not
void Position::GetIrregularGroupingTiming(wxByte& notesPlayed, wxByte& notesPlayedOver) const
{
//------Last Checked------//
// - Jan 18, 2005
// Values are stored as 1-15 and 1-7, but there is no 1 value
notesPlayed = (wxByte)(((m_beaming & irregularGroupingNotesPlayedMask) >> 3) + 1);
notesPlayedOver = (wxByte)((m_beaming & irregularGroupingNotesPlayedOverMask) + 1);
}
/// Determines if the position has an irregular grouping timing
/// @return True if the position has an irregular grouping timing, false if not
bool Position::HasIrregularGroupingTiming() const
{
//------Last Checked------//
// - Jan 20, 2005
wxByte notesPlayed = 0;
wxByte notesPlayedOver = 0;
GetIrregularGroupingTiming(notesPlayed, notesPlayedOver);
return (!((notesPlayed == 1) && (notesPlayedOver == 1)));
}
/// Clears the irregular grouping timing
/// @return True if the irregular grouping was cleared, false if not
bool Position::ClearIrregularGroupingTiming()
{
//------Last Checked------//
// - Jan 20, 2005
m_beaming &= ~irregularGroupingTimingMask;
return (true);
}
// Previous Beam Duration Functions
/// Sets the duration type of the previous rhythm slash in the beam group (cache only)
/// @param durationType Duration type to set (0 = not beamed, 8 = 8th, 16 = 16th, 32 = 32nd, 64 = 64th)
/// @return True if the duration type was set, false if not
bool Position::SetPreviousBeamDurationType(wxByte durationType)
{
//------Last Checked------//
// - Jan 18, 2005
wxCHECK(IsValidPreviousBeamDurationType(durationType), false);
// Clear the current duration type
m_beaming &= ~previousBeamDurationTypeMask;
wxWord flag = 0;
if (durationType == 8)
flag = previousBeamDuration8th;
else if (durationType == 16)
flag = previousBeamDuration16th;
else if (durationType == 32)
flag = previousBeamDuration32nd;
else if (durationType == 64)
flag = previousBeamDuration64th;
m_beaming |= (wxWord)(flag << 7);
return (true);
}
/// Gets the duration type of the previous rhythm slash in the beam group
/// @return The duration type of the previous rhythm slash in the beam group (0 = not beamed, 8 = 8th, 16 = 16th)
wxByte Position::GetPreviousBeamDurationType() const
{
//------Last Checked------//
// - Jan 18, 2005
wxByte flag = (wxByte)((m_beaming & previousBeamDurationTypeMask) >> 7);
if (flag == previousBeamDuration8th)
return (8);
else if (flag == previousBeamDuration16th)
return (16);
else if (flag == previousBeamDuration32nd)
return (32);
else if (flag == previousBeamDuration64th)
return (64);
return (0);
}
// Beaming Functions
/// Sets a beaming flag
/// @param flag Flag to set
/// @return True if teh beaming flag was set, false if not
bool Position::SetBeamingFlag(wxWord flag)
{
//------Last Checked------//
// - Jan 7, 2005
wxCHECK(IsValidBeamingFlag(flag), false);
// Mutually exclusive operations
if ((flag & beamStart) == beamStart)
{
ClearBeamingFlag(beamEnd);
flag &= ~beamEnd;
}
else if ((flag & beamEnd) == beamEnd)
ClearBeamingFlag(beamStart);
m_beaming |= flag;
return (true);
}
// Data Flag Functions
/// Sets a data flag
/// @param flag Flag to set
/// @return True if the flag was set, false if not
bool Position::SetDataFlag(wxUint32 flag)
{
//------Last Checked------//
// - Jan 7, 2005
wxCHECK(IsValidDataFlag(flag), false);
// Mutually exclusive operations
if ((flag & dottedMask) != 0)
ClearDataFlag(dottedMask);
if ((flag & vibratoMask) != 0)
ClearDataFlag(vibratoMask);
if ((flag & arpeggioMask) != 0)
ClearDataFlag(arpeggioMask);
if ((flag & pickStrokeMask) != 0)
ClearDataFlag(pickStrokeMask);
if ((flag & accentMask) != 0)
ClearDataFlag(accentMask);
if ((flag & tripletFeelMask) != 0)
ClearDataFlag(tripletFeelMask);
m_data |= flag;
return (true);
}
// Volume Swell Functions
/// Sets (adds or updates) a volume swell
/// @param startVolume Starting volume of the swell
/// @param endVolume Ending volume of the swell
/// @param duration Duration of the swell (0 = occurs over position, 1 and up = occurs over next n positions)
/// @return True if the volume swell was added or updated
bool Position::SetVolumeSwell(wxByte startVolume, wxByte endVolume, wxByte duration)
{
//------Last Checked------//
// - Jan 19, 2005
wxCHECK(IsValidVolumeSwell(startVolume, endVolume, duration), false);
// Construct the symbol data, then add it to the array
wxUint32 symbolData = MAKELONG(MAKEWORD(endVolume, startVolume), MAKEWORD(duration, volumeSwell));
return (AddComplexSymbol(symbolData));
}
/// Gets the volume swell data (if any)
/// @param startVolume Holds the start volume return value
/// @param endVolume Holds the end volume return value
/// @param duration Holds the duration return value
/// @return True if the data was returned, false if not
bool Position::GetVolumeSwell(wxByte& startVolume, wxByte& endVolume, wxByte& duration) const
{
//------Last Checked------//
// - Jan 19, 2005
startVolume = 0;
endVolume = 0;
duration = 0;
// Get the index of the volume swell
wxUint32 index = FindComplexSymbol(volumeSwell);
if (index == (wxUint32)-1)
return (false);
// Get the individual pieces that make up the volume swell
wxUint32 symbolData = m_complexSymbolArray[index];
startVolume = HIBYTE(LOWORD(symbolData));
endVolume = LOBYTE(LOWORD(symbolData));
duration = LOBYTE(HIWORD(symbolData));
return (true);
}
/// Determines if the position has a volume swell
/// @return True if the position has a volume swell, false if not
bool Position::HasVolumeSwell() const
{
//------Last Checked------//
// - Jan 19, 2005
return (FindComplexSymbol(volumeSwell) != (wxUint32)-1);
}
/// Removes a volume swell from the position
/// @return True if the volume swell was removed, false if not
bool Position::ClearVolumeSwell()
{
//------Last Checked------//
// - Jan 19, 2005
return (RemoveComplexSymbol(volumeSwell));
}
// Tremolo Bar Functions
/// Sets (adds or updates) a tremolo bar
/// @param type Type of tremolo bar (see tremoloBarTypes enum for values)
/// @param duration Duration of the tremolo bar (0 = occurs over position, 1 and up = occurs over next n positions)
/// @param pitch Pitch of the tremolo bar
/// @return True if the tremolo bar was added or updated
bool Position::SetTremoloBar(wxByte type, wxByte duration, wxByte pitch)
{
//------Last Checked------//
// - Jan 19, 2005
wxCHECK(IsValidTremoloBar(type, duration, pitch), false);
// Construct the symbol data, then add it to the array
wxUint32 symbolData = MAKELONG(MAKEWORD(pitch, duration), MAKEWORD(type, tremoloBar));
return (AddComplexSymbol(symbolData));
}
/// Gets the tremolo bar data (if any)
/// @param type Holds the type return value
/// @param duration Holds the duration return value
/// @param pitch Holds the pitch return value
/// @return True if the data was returned, false if not
bool Position::GetTremoloBar(wxByte& type, wxByte& duration, wxByte& pitch) const
{
//------Last Checked------//
// - Jan 19, 2005
type = 0;
duration = 0;
pitch = 0;
// Get the index of the tremolo bar
wxUint32 index = FindComplexSymbol(tremoloBar);
if (index == (wxUint32)-1)
return (false);
// Get the individual pieces that make up the tremolo bar
wxUint32 symbolData = m_complexSymbolArray[index];
type = LOBYTE(HIWORD(symbolData));
duration = HIBYTE(LOWORD(symbolData));
pitch = LOBYTE(LOWORD(symbolData));
return (true);
}
/// Determines if the position has a tremolo bar
/// @return True if the position has a tremolo bar, false if not
bool Position::HasTremoloBar() const
{
//------Last Checked------//
// - Jan 19, 2005
return (FindComplexSymbol(tremoloBar) != (wxUint32)-1);
}
/// Removes a tremolo bar from the position
/// @return True if the tremolo bar was removed, false if not
bool Position::ClearTremoloBar()
{
//------Last Checked------//
// - Jan 19, 2005
return (RemoveComplexSymbol(tremoloBar));
}
// Multibar Rest Functions
/// Sets (adds or updates) a multibar rest
/// @param measureCount Number of measures to rest for
/// @return True if the multibar rest was added or updated
bool Position::SetMultibarRest(wxByte measureCount)
{
//------Last Checked------//
// - Jan 19, 2005
wxCHECK(IsValidMultibarRest(measureCount), false);
// Construct the symbol data, then add it to the array
wxUint32 symbolData = MAKELONG(MAKEWORD(measureCount, 0), MAKEWORD(0, multibarRest));
return (AddComplexSymbol(symbolData));
}
/// Gets the multibar rest data (if any)
/// @param measureCount Holds the measure count return value
/// @return True if the data was returned, false if not
bool Position::GetMultibarRest(wxByte& measureCount) const
{
//------Last Checked------//
// - Jan 19, 2005
measureCount = 0;
// Get the index of the multibar rest
wxUint32 index = FindComplexSymbol(multibarRest);
if (index == (wxUint32)-1)
return (false);
// Get the individual pieces that make up the multibar rest
wxUint32 symbolData = m_complexSymbolArray[index];
measureCount = LOBYTE(LOWORD(symbolData));
return (true);
}
/// Determines if the position has a multibar rest
/// @return True if the position has a multibar rest, false if not
bool Position::HasMultibarRest() const
{
//------Last Checked------//
// - Jan 19, 2005
return (FindComplexSymbol(multibarRest) != (wxUint32)-1);
}
/// Removes a multibar rest from the position
/// @return True if the multibar rest was removed, false if not
bool Position::ClearMultibarRest()
{
//------Last Checked------//
// - Jan 19, 2005
return (RemoveComplexSymbol(multibarRest));
}
// Complex Symbol Array Functions
/// Adds a complex symbol to the complex symbol array
/// @param symbolData Data that makes up the symbol
/// @return True if the symbol was added or updated, false if not
bool Position::AddComplexSymbol(wxUint32 symbolData)
{
//------Last Checked------//
// - Jan 19, 2005
// Get and validate the symbol type
wxByte type = HIBYTE(HIWORD(symbolData));
wxCHECK(IsValidComplexSymbolType(type), false);
bool returnValue = false;
// Get the index in the complex array where the symbol is stored
wxUint32 index = FindComplexSymbol(type);
// Found symbol in the array, update the symbol data
if (index != (wxUint32)-1)
{
m_complexSymbolArray[index] = symbolData;
returnValue = true;
}
// Symbol was not found in the array, find the first free array slot and insert there
else
{
wxUint32 i = 0;
for (; i < MAX_POSITION_COMPLEX_SYMBOLS; i++)
{
if (m_complexSymbolArray[i] == notUsed)
{
m_complexSymbolArray[i] = symbolData;
returnValue = true;
break;
}
}
}
return (returnValue);
}
/// Gets the number of complex symbols used by the position
/// @return The number of complex symbols used by the position
size_t Position::GetComplexSymbolCount() const
{
//------Last Checked------//
// - Jan 19, 2005
size_t returnValue = 0;
size_t i = 0;
for (; i < MAX_POSITION_COMPLEX_SYMBOLS; i++)
{
// Slot is not used; break out
if (m_complexSymbolArray[i] == notUsed)
break;
returnValue++;
}
return (returnValue);
}
/// Gets the index of a given complex symbol type in the complex symbol array
/// @param type Type of symbol to find
/// @return Index within the array where the symbol was found, or -1 if not found
wxUint32 Position::FindComplexSymbol(wxByte type) const
{
//------Last Checked------//
// - Jan 19, 2005
wxUint32 returnValue = (wxUint32)-1;
wxUint32 i = 0;
for (; i < MAX_POSITION_COMPLEX_SYMBOLS; i++)
{
// Found the symbol type; break out
if (HIBYTE(HIWORD(m_complexSymbolArray[i])) == type)
{
returnValue = i;
break;
}
}
return (returnValue);
}
/// Removes a complex symbol from the complex symbol array
/// @param type Type of symbol to remove
/// @return True if the symbol was removed, false if not
bool Position::RemoveComplexSymbol(wxByte type)
{
//------Last Checked------//
// - Jan 19, 2005
bool returnValue = false;
wxUint32 i = 0;
for (; i < MAX_POSITION_COMPLEX_SYMBOLS; i++)
{
if (HIBYTE(HIWORD(m_complexSymbolArray[i])) == type)
{
m_complexSymbolArray[i] = notUsed;
returnValue = true;
break;
}
}
return (returnValue);
}
/// Clears the contents of the symbol array (sets all elements to "not used")
void Position::ClearComplexSymbolArrayContents()
{
//------Last Checked------//
// - Jan 19, 2005
wxUint32 i = 0;
for (; i < MAX_POSITION_COMPLEX_SYMBOLS; i++)
m_complexSymbolArray[i] = notUsed;
}
| [
"blarsen@8c24db97-d402-0410-b267-f151a046c31a"
]
| [
[
[
1,
737
]
]
]
|
cc684b425c07566c018e25f7cd91f8e522ed7c18 | 5ff30d64df43c7438bbbcfda528b09bb8fec9e6b | /kserver/db/TransactionRunner.cpp | 6efb30fe7204dce1ead9e3d4cdc517a77ac04ab9 | []
| no_license | lvtx/gamekernel | c80cdb4655f6d4930a7d035a5448b469ac9ae924 | a84d9c268590a294a298a4c825d2dfe35e6eca21 | refs/heads/master | 2016-09-06T18:11:42.702216 | 2011-09-27T07:22:08 | 2011-09-27T07:22:08 | 38,255,025 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,385 | cpp | #include "stdafx.h"
#include <kserver/serverbase.h>
#include <kserver/db/TransactionRunner.h>
#include <kserver/Node.h>
namespace gk {
TransactionRunner::TransactionRunner()
: m_node( 0 )
, m_pool( 0 )
{
}
TransactionRunner::~TransactionRunner()
{
Fini();
}
bool
TransactionRunner::Init( Node* node, DbPool* pool )
{
K_ASSERT( node != 0 );
K_ASSERT( pool != 0 );
m_node = node;
m_pool = pool;
m_transCount = 0;
Start();
return IsRunning();
}
void
TransactionRunner::Request( Transaction* tx )
{
m_transCount.Inc();
m_transQ.Put( tx );
}
int
TransactionRunner::Run()
{
while ( IsRunning() )
{
processTransQ();
::Sleep( 10 );
}
return 0;
}
void
TransactionRunner::Fini()
{
Stop();
processTransQ();
}
uint
TransactionRunner::GetTransactionCount() const
{
return m_transCount;
}
void
TransactionRunner::processTransQ()
{
Transaction* tx = 0;
while ( m_transQ.Get( tx ) )
{
processTrans( tx );
}
}
void
TransactionRunner::processTrans( Transaction* tx )
{
K_ASSERT( tx != 0 );
LOG( FT_DEBUG, _T("TransactionRunner::processTrans> %d"), tx->GetTxNo() );
tx->Execute( m_pool );
CellId dst = tx->GetCellId();
if ( !dst.IsValid() )
{
delete tx;
return;
}
m_node->Completed( tx );
m_transCount.Dec();
}
} // gk
| [
"darkface@localhost"
]
| [
[
[
1,
106
]
]
]
|
748f42f36b6c14ba63138efb1e28eacc369d7f3d | 33f59b1ba6b12c2dd3080b24830331c37bba9fe2 | /Depend/Foundation/Distance/Wm4DistVector3Rectangle3.h | ec35c13b077f9333506c85e98514b6395eff24f4 | []
| no_license | daleaddink/flagship3d | 4835c223fe1b6429c12e325770c14679c42ae3c6 | 6cce5b1ff7e7a2d5d0df7aa0594a70d795c7979a | refs/heads/master | 2021-01-15T16:29:12.196094 | 2009-11-01T10:18:11 | 2009-11-01T10:18:11 | 37,734,654 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,977 | h | // Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// The Wild Magic Version 4 Foundation Library source code is supplied
// under the terms of the license agreement
// http://www.geometrictools.com/License/Wm4FoundationLicense.pdf
// and may not be copied or disclosed except in accordance with the terms
// of that agreement.
#ifndef WM4DISTVECTOR3RECTANGLE3_H
#define WM4DISTVECTOR3RECTANGLE3_H
#include "Wm4FoundationLIB.h"
#include "Wm4Distance.h"
#include "Wm4Rectangle3.h"
namespace Wm4
{
template <class Real>
class WM4_FOUNDATION_ITEM DistVector3Rectangle3
: public Distance<Real,Vector3<Real> >
{
public:
DistVector3Rectangle3 (const Vector3<Real>& rkVector,
const Rectangle3<Real>& rkRectangle);
// object access
const Vector3<Real>& GetVector () const;
const Rectangle3<Real>& GetRectangle () const;
// static distance queries
virtual Real Get ();
virtual Real GetSquared ();
// function calculations for dynamic distance queries
virtual Real Get (Real fT, const Vector3<Real>& rkVelocity0,
const Vector3<Real>& rkVelocity1);
virtual Real GetSquared (Real fT, const Vector3<Real>& rkVelocity0,
const Vector3<Real>& rkVelocity1);
// Information about the closest rectangle point.
Real GetRectangleCoordinate (int i) const;
private:
using Distance<Real,Vector3<Real> >::m_kClosestPoint0;
using Distance<Real,Vector3<Real> >::m_kClosestPoint1;
const Vector3<Real>& m_rkVector;
const Rectangle3<Real>& m_rkRectangle;
// Information about the closest rectangle point.
Real m_afRectCoord[2]; // closest1 = rect.center+param0*rect.dir0+
// param1*rect.dir1
};
typedef DistVector3Rectangle3<float> DistVector3Rectangle3f;
typedef DistVector3Rectangle3<double> DistVector3Rectangle3d;
}
#endif
| [
"yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa"
]
| [
[
[
1,
63
]
]
]
|
3a7213b4867568d9029580fae96e3c09698d16c1 | 65f587a75567b51375bde5793b4ec44e4b79bc7d | /stepEditController.cpp | e2ca5a16e2486accab7e195af120917faa750940 | []
| no_license | discordance/sklepseq | ce4082074afbdb7e4f7185f042ce9e34d42087ef | 8d4fa5a2710ba947e51f5572238eececba4fef74 | refs/heads/master | 2021-01-13T00:15:23.218795 | 2008-07-20T20:48:44 | 2008-07-20T20:48:44 | 49,079,555 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,092 | cpp | /*
==============================================================================
This is an automatically generated file created by the Jucer!
Creation date: 2 Jul 2008 9:33:57 pm
Be careful when adding custom code to these files, as only the code within
the "//[xyz]" and "//[/xyz]" sections will be retained when the file is loaded
and re-saved.
Jucer version: 1.11
------------------------------------------------------------------------------
The Jucer is part of the JUCE library - "Jules' Utility Class Extensions"
Copyright 2004-6 by Raw Material Software ltd.
==============================================================================
*/
//[Headers] You can add your own extra header files here...
//[/Headers]
#include "stepEditController.h"
//[MiscUserDefs] You can add your own user definitions and misc code here...
//[/MiscUserDefs]
//==============================================================================
stepEditController::stepEditController (myMidiMessage *msg)
: controllerValue (0),
controllerNumber (0),
label (0),
label2 (0),
typeCombo (0)
{
addAndMakeVisible (controllerValue = new Slider (T("Value")));
controllerValue->setTooltip (T("Value"));
controllerValue->setRange (0, 127, 1);
controllerValue->setSliderStyle (Slider::RotaryVerticalDrag);
controllerValue->setTextBoxStyle (Slider::TextBoxBelow, false, 80, 20);
controllerValue->addListener (this);
addAndMakeVisible (controllerNumber = new Slider (T("Number")));
controllerNumber->setTooltip (T("Number"));
controllerNumber->setRange (0, 127, 1);
controllerNumber->setSliderStyle (Slider::IncDecButtons);
controllerNumber->setTextBoxStyle (Slider::TextBoxLeft, false, 35, 20);
controllerNumber->addListener (this);
addAndMakeVisible (label = new Label (T("new label"),
T("Controller Value")));
label->setFont (Font (15.0000f, Font::plain));
label->setJustificationType (Justification::centredLeft);
label->setEditable (false, false, false);
label->setColour (TextEditor::textColourId, Colours::black);
label->setColour (TextEditor::backgroundColourId, Colour (0x0));
addAndMakeVisible (label2 = new Label (T("new label"),
T("Controller Number")));
label2->setFont (Font (15.0000f, Font::plain));
label2->setJustificationType (Justification::centredLeft);
label2->setEditable (false, false, false);
label2->setColour (TextEditor::textColourId, Colours::black);
label2->setColour (TextEditor::backgroundColourId, Colour (0x0));
addAndMakeVisible (typeCombo = new ComboBox (T("Controller Type")));
typeCombo->setTooltip (T("Type"));
typeCombo->setEditableText (false);
typeCombo->setJustificationType (Justification::centredLeft);
typeCombo->setTextWhenNothingSelected (String::empty);
typeCombo->setTextWhenNoChoicesAvailable (T("(no choices)"));
typeCombo->addItem (T("CC"), 1);
typeCombo->addItem (T("RPN"), 2);
typeCombo->addItem (T("NRPN"), 3);
typeCombo->addListener (this);
//[UserPreSize]
midiMessage = msg;
if (midiMessage)
{
if (midiMessage->isMulti())
{
MidiBuffer *b = midiMessage->getMidiBuffer();
MidiMessage msg(0xf0,0.0);
MidiBuffer::Iterator i(*b);
int len;
int controllerNumberLsb=0, controllerNumberMsb=0, controllerValueLsb=0, controllerValueMsb=0;
BitArray ctrlrValueArray;
BitArray ctrlrNumberArray;
while (i.getNextEvent (msg, len))
{
uint8 *d = msg.getRawData();
int len = msg.getRawDataSize();
String t;
for (int x=0; x<len; x++)
{
if (x==0)
t << String::formatted (T("%x"), *(d+x));
else
t << String::formatted (T(":%x"), *(d+x));
}
Logger::writeToLog (T("message: ") + t);
if (msg.getControllerNumber() == 98)
{
controllerNumberMsb = msg.getControllerValue();
}
if (msg.getControllerNumber() == 99)
{
typeCombo->setSelectedId (2, true);
controllerNumberLsb = msg.getControllerValue();
}
if (msg.getControllerNumber() == 100)
{
controllerNumberMsb = msg.getControllerValue();
}
if (msg.getControllerNumber() == 101)
{
typeCombo->setSelectedId (3, true);
controllerNumberLsb = msg.getControllerValue();
}
if (msg.getControllerNumber() == 6)
{
controllerValueLsb = msg.getControllerValue();
}
if (msg.getControllerNumber() == 38)
{
controllerValueMsb = msg.getControllerValue();
}
}
ctrlrNumberArray.setBitRangeAsInt (0, 7, controllerNumberLsb);
ctrlrNumberArray.setBitRangeAsInt (7, 7, controllerNumberMsb);
ctrlrValueArray.setBitRangeAsInt (0, 7, controllerValueLsb);
ctrlrValueArray.setBitRangeAsInt (7, 7, controllerValueMsb);
controllerNumber->setRange (0, 16383, 1);
controllerValue->setRange (0, 16383, 1);
controllerValue->setValue (ctrlrValueArray.getBitRangeAsInt(0,14));
controllerNumber->setValue (ctrlrNumberArray.getBitRangeAsInt(0,14));
}
else
{
controllerNumber->setRange (0, 127, 1);
controllerValue->setRange (0, 127, 1);
typeCombo->setSelectedId (1, true);
controllerNumber->setValue (midiMessage->getMidiMessage()->getControllerNumber());
controllerValue->setValue (midiMessage->getMidiMessage()->getControllerValue());
}
}
//[/UserPreSize]
setSize (112, 224);
//[Constructor] You can add your own custom stuff here..
//[/Constructor]
}
stepEditController::~stepEditController()
{
//[Destructor_pre]. You can add your own custom destruction code here..
//[/Destructor_pre]
deleteAndZero (controllerValue);
deleteAndZero (controllerNumber);
deleteAndZero (label);
deleteAndZero (label2);
deleteAndZero (typeCombo);
//[Destructor]. You can add your own custom destruction code here..
//[/Destructor]
}
//==============================================================================
void stepEditController::paint (Graphics& g)
{
//[UserPrePaint] Add your own custom painting code here..
//[/UserPrePaint]
g.fillAll (Colours::white);
//[UserPaint] Add your own custom painting code here..
//[/UserPaint]
}
void stepEditController::resized()
{
controllerValue->setBounds (0, 24, 112, 112);
controllerNumber->setBounds (4, 168, 108, 24);
label->setBounds (4, 0, 104, 24);
label2->setBounds (4, 144, 104, 24);
typeCombo->setBounds (16, 200, 80, 16);
//[UserResized] Add your own custom resize handling here..
//[/UserResized]
}
void stepEditController::sliderValueChanged (Slider* sliderThatWasMoved)
{
//[UsersliderValueChanged_Pre]
//[/UsersliderValueChanged_Pre]
if (sliderThatWasMoved == controllerValue)
{
//[UserSliderCode_controllerValue] -- add your slider handling code here..
setMidiData();
//[/UserSliderCode_controllerValue]
}
else if (sliderThatWasMoved == controllerNumber)
{
//[UserSliderCode_controllerNumber] -- add your slider handling code here..
setMidiData();
//[/UserSliderCode_controllerNumber]
}
//[UsersliderValueChanged_Post]
//[/UsersliderValueChanged_Post]
}
void stepEditController::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
{
//[UsercomboBoxChanged_Pre]
//[/UsercomboBoxChanged_Pre]
if (comboBoxThatHasChanged == typeCombo)
{
//[UserComboBoxCode_typeCombo] -- add your combo box handling code here..
switch (typeCombo->getSelectedId()-1)
{
case CC:
controllerNumber->setRange (0, 127, 1);
controllerValue->setRange (0, 127, 1);
break;
case RPN:
controllerNumber->setRange (0, 16383, 1);
controllerValue->setRange (0, 16383, 1);
break;
case NRPN:
controllerNumber->setRange (0, 16383, 1);
controllerValue->setRange (0, 16383, 1);
break;
default:
break;
}
setMidiData();
//[/UserComboBoxCode_typeCombo]
}
//[UsercomboBoxChanged_Post]
//[/UsercomboBoxChanged_Post]
}
//[MiscUserCode] You can add your own definitions of your custom methods or any other code here...
void stepEditController::setMidiData()
{
if (typeCombo->getSelectedId()-1 == NRPN)
{
/* (MSB x 128) + LSB == controller number*/
/* (MSB x 128) + LSB == value */
midiBuf.clear();
BitArray ctrlrNumber ((int)controllerNumber->getValue());
BitArray ctrlrValue ((int)controllerValue->getValue());
int ctrlrNumberLsb = ctrlrNumber.getBitRangeAsInt (0,6);
int ctrlrNumberMsb = ctrlrNumber.getBitRangeAsInt (7,13);
int ctrlrValueLsb = ctrlrValue.getBitRangeAsInt (0,6);
int ctrlrValueMsb = ctrlrValue.getBitRangeAsInt (7,13);
int firstByte = 0xb0;
MidiMessage msg (firstByte, 101, ctrlrNumberLsb);
midiBuf.addEvent (msg,0);
msg = MidiMessage(firstByte, 100, ctrlrNumberMsb);
midiBuf.addEvent (msg,1);
msg = MidiMessage(firstByte, 6, ctrlrValueLsb);
midiBuf.addEvent (msg,2);
msg = MidiMessage(firstByte, 38, ctrlrValueMsb);
midiBuf.addEvent (msg,3);
midiMessage->setMidiMessageMulti (midiBuf);
return;
}
if (typeCombo->getSelectedId()-1 == RPN)
{
/* (MSB x 128) + LSB == controller number*/
/* (MSB x 128) + LSB == value */
midiBuf.clear();
BitArray ctrlrNumber ((int)controllerNumber->getValue());
BitArray ctrlrValue ((int)controllerValue->getValue());
int ctrlrNumberLsb = ctrlrNumber.getBitRangeAsInt (0,6);
int ctrlrNumberMsb = ctrlrNumber.getBitRangeAsInt (7,13);
int ctrlrValueLsb = ctrlrValue.getBitRangeAsInt (0,6);
int ctrlrValueMsb = ctrlrValue.getBitRangeAsInt (7,13);
int firstByte = 0xb0;
MidiMessage msg (firstByte, 99, ctrlrNumberLsb);
midiBuf.addEvent (msg,0);
msg = MidiMessage(firstByte, 98, ctrlrNumberMsb);
midiBuf.addEvent (msg,1);
msg = MidiMessage(firstByte, 6, ctrlrValueLsb);
midiBuf.addEvent (msg,2);
msg = MidiMessage(firstByte, 38, ctrlrValueMsb);
midiBuf.addEvent (msg,3);
midiMessage->setMidiMessageMulti (midiBuf);
return;
}
if (typeCombo->getSelectedId()-1 == CC)
{
midiMessage->setMidiMessage (MidiMessage::controllerEvent (1, (int)controllerNumber->getValue(), (int)controllerValue->getValue()));
return;
}
}
//[/MiscUserCode]
//==============================================================================
#if 0
/* -- Jucer information section --
This is where the Jucer puts all of its metadata, so don't change anything in here!
BEGIN_JUCER_METADATA
<JUCER_COMPONENT documentType="Component" className="stepEditController" componentName=""
parentClasses="public Component" constructorParams="myMidiMessage *msg"
variableInitialisers="" snapPixels="8" snapActive="1" snapShown="1"
overlayOpacity="0.330000013" fixedSize="1" initialWidth="112"
initialHeight="224">
<BACKGROUND backgroundColour="ffffffff"/>
<SLIDER name="Value" id="594ba86bfe4c9ed5" memberName="controllerValue"
virtualName="" explicitFocusOrder="0" pos="0 24 112 112" tooltip="Value"
min="0" max="127" int="1" style="RotaryVerticalDrag" textBoxPos="TextBoxBelow"
textBoxEditable="1" textBoxWidth="80" textBoxHeight="20" skewFactor="1"/>
<SLIDER name="Number" id="6ce30323c5dbf062" memberName="controllerNumber"
virtualName="" explicitFocusOrder="0" pos="4 168 108 24" tooltip="Number"
min="0" max="127" int="1" style="IncDecButtons" textBoxPos="TextBoxLeft"
textBoxEditable="1" textBoxWidth="35" textBoxHeight="20" skewFactor="1"/>
<LABEL name="new label" id="6682b679404c2a6e" memberName="label" virtualName=""
explicitFocusOrder="0" pos="4 0 104 24" edTextCol="ff000000"
edBkgCol="0" labelText="Controller Value" editableSingleClick="0"
editableDoubleClick="0" focusDiscardsChanges="0" fontname="Default font"
fontsize="15" bold="0" italic="0" justification="33"/>
<LABEL name="new label" id="a92dafe37c5039b7" memberName="label2" virtualName=""
explicitFocusOrder="0" pos="4 144 104 24" edTextCol="ff000000"
edBkgCol="0" labelText="Controller Number" editableSingleClick="0"
editableDoubleClick="0" focusDiscardsChanges="0" fontname="Default font"
fontsize="15" bold="0" italic="0" justification="33"/>
<COMBOBOX name="Controller Type" id="5d0d63924ddad6e8" memberName="typeCombo"
virtualName="" explicitFocusOrder="0" pos="16 200 80 16" tooltip="Type"
editable="0" layout="33" items="CC RPN NRPN" textWhenNonSelected=""
textWhenNoItems="(no choices)"/>
</JUCER_COMPONENT>
END_JUCER_METADATA
*/
#endif
| [
"kubiak.roman@0c9c7eae-764f-0410-aff0-6774c5161e44"
]
| [
[
[
1,
392
]
]
]
|
9a237aa09bdcd12e447bbf7a226f293644bca8a2 | 7ab17e21347288deb29d1274f59576cd50387d46 | /EuroConvDlg.h | 7f8dbea2ae57c0ea306a6fa5175556e88cdc3866 | []
| no_license | feranick/EuroConv | 12a1d1376f1faf525148d981a72779523c3e7604 | 35a87e1c5bc022c07c83a0dc8711c7b9cb8d7245 | refs/heads/master | 2021-01-16T18:19:13.054910 | 2011-10-16T18:27:52 | 2011-10-16T18:27:52 | 2,587,423 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,594 | h | // EuroConvDlg.h : header file
//
#if !defined(AFX_EUROCONVDLG_H__FBCD0A2A_BC30_4A4D_9A24_C58B12270F1D__INCLUDED_)
#define AFX_EUROCONVDLG_H__FBCD0A2A_BC30_4A4D_9A24_C58B12270F1D__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
/////////////////////////////////////////////////////////////////////////////
// CEuroConvDlg dialog
class CEuroConvDlg : public CDialog
{
// Construction
public:
CEuroConvDlg(CWnd* pParent = NULL); // standard constructor
// Dialog Data
//{{AFX_DATA(CEuroConvDlg)
enum { IDD = IDD_EUROCONV_DIALOG };
CComboBox m_currency;
float m_input;
CString m_dispconv;
CString m_country;
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CEuroConvDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
HICON m_hIcon;
// float lira=1936.27;
float lira,a,b,c;
// Generated message map functions
//{{AFX_MSG(CEuroConvDlg)
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
afx_msg void OnEuroOld();
afx_msg void OnOldEuro();
afx_msg void OnEditchangeCurrency();
afx_msg void OnSelchangeCurrency();
afx_msg void OnRates();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_EUROCONVDLG_H__FBCD0A2A_BC30_4A4D_9A24_C58B12270F1D__INCLUDED_)
| [
"[email protected]"
]
| [
[
[
1,
58
]
]
]
|
bc34e2cf516c5c9fa2a1f00ebc0e6badef10ef25 | 2ea2445257dd404cdbefa57a95095b37c6e17d23 | /GPU_Warp/trunk/GPU_Warp/ImageIO.cpp | fad00ec94324226a34aca59939cbabbcdf5ffe75 | []
| no_license | loongfee/gpu-image-warp | 7143e32d30506b3c67e6fee60b3e312191398937 | 56143fbf6337576a0f8a11691ae8c463e5c8ee14 | refs/heads/master | 2020-05-17T19:07:39.813752 | 2009-03-29T08:27:16 | 2009-03-29T08:27:16 | 42,363,349 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,708 | cpp | #include <iostream>
#include <string>
#include <GL/glut.h>
#include "FreeImage.h"
#include "ImageIO.h"
using namespace std;
using namespace GpuImageProcess;
/***************************************************/
ImageIO::ImageIO()
{
root.width = 0;
root.height = 0;
root.type = TYPE_UNKNOW;
root.begin = NULL;
}
namespace
{
/* find the minimum color range and the maximum color range in float image */
void minMax(const GpuImageProcess::Image& floatimage,float& min,float& max)
{
if (floatimage.type != TYPE_FLOAT_32BPP)
{
cerr << "only float ...";
exit(1);
}
const float * ptr = (float *)floatimage.begin;
// find min and max
min = *ptr;
max = *ptr;
for(int y = 0; y < (floatimage.height*floatimage.width); y++,ptr++)
{
if (*ptr < min)
min = *ptr;
if (*ptr > max)
max = *ptr;
}
}
}
//#############################################################################
/* Convert float image to unsigned char
* only for testing purposes. We suppose the image in range[0..255]
* OpenGL makes it to be [0..1]
*/
//#############################################################################
bool ImageIO::floatToUc(const GpuImageProcess::Image& floatimage, GpuImageProcess::Image& ucimage)
{
float min,max;
minMax(floatimage,min,max);
const float * ptr = (float *)floatimage.begin;
unsigned char * ptr2 = (unsigned char *)malloc(floatimage.height*floatimage.width*sizeof(unsigned char));
ucimage.width = floatimage.width;
ucimage.height = floatimage.height;
ucimage.begin = ptr2;
ucimage.type = TYPE_UC_8BPP;
float clamp = 256.0 / (max-min);
for(int y = 0; y < (floatimage.height*floatimage.width); y++,ptr++,ptr2++)
{
*ptr2 = (unsigned char)((*ptr - min)*clamp);
}
return true;
}
//#############################################################################
// convert the image into range [0..1]
//#############################################################################
bool ImageIO::clamp( GpuImageProcess::Image& floatimage)
{
float min,max;
minMax(floatimage,min,max);
float * ptr = (float *)floatimage.begin;
float clamp = 1.0 / (max-min);
for(int y = 0; y < (floatimage.height*floatimage.width); y++,ptr++)
{
*ptr = (*ptr - min)*clamp;
}
return true;
}
//#############################################################################
/* Loads an image from file name into Image structure */
//#############################################################################
bool ImageIO::load(const char *fname,GpuImageProcess::Image& image)
{
FIBITMAP *img; // FreeImage type
FREE_IMAGE_FORMAT fif = FIF_UNKNOWN; // by default image format is unknown
unsigned int pixelSize; // size of each pixel
FREE_IMAGE_TYPE imageType; // type of image
FREE_IMAGE_COLOR_TYPE colorType; // color type
RGBQUAD aPixel;
// try to define image format
fif = FreeImage_GetFileType(fname,0); // second parameter unused !
if ( fif == FIF_UNKNOWN )
{
// try to guess image format from it's file name
fif = FreeImage_GetFIFFromFilename(fname);
if (fif == FIF_UNKNOWN)
{
cerr <<"Image format unknown\n";
return false;
}
}
// load image
if ((img = FreeImage_Load(fif, fname, 0)) == NULL)
{
cerr << "Error on image loading from file\n";
return false;
}
// get image INFORMATION
image.width = FreeImage_GetWidth(img);
image.height = FreeImage_GetHeight(img);
pixelSize = FreeImage_GetBPP(img); // bytes per pixel
imageType = FreeImage_GetImageType(img); // image type
colorType = FreeImage_GetColorType(img); //page 26
if ( image.width <=0 || image.height <=0 )
{
cerr << "Image dimensions are negetive or zero\n";
return false;
}
//################################## 8 BIT for pixel ###########################################
if ( imageType == FIT_BITMAP && pixelSize == 8 )
{
image.type = TYPE_UC_8BPP;
unsigned char *data = (unsigned char*) malloc(image.width * image.height * ( sizeof(unsigned char)));
unsigned int place=0;
unsigned char *line;
for(int y = 0; y < (image.height); y++)
{
line = (BYTE *)FreeImage_GetScanLine(img, y);
for(int x = 0; x < image.width; x++)
{
data[place] = line[x];
place++;
}
}
image.begin = (void*)data;
return true;
}
//################################## 24 BIT for pixel RGB #######################################
else if ( imageType == FIT_BITMAP && (pixelSize == 24 || pixelSize == 32) )
{
image.type = TYPE_RGB_8BPP;
unsigned char *data = (unsigned char*) malloc(image.width * image.height * ( sizeof(unsigned char) * 3));
unsigned int place=0;
for (int i=0; i<(image.height); i++)
{
for (int j=0; j<(image.width); j++)
{
FreeImage_GetPixelColor(img,j,i, &aPixel);
data[place++] = (GLubyte) aPixel.rgbRed;
data[place++] = (GLubyte) aPixel.rgbGreen;
data[place++] = (GLubyte) aPixel.rgbBlue;
}
}
image.begin = (void*)data;
return true;
}
//################################## 32 BIT for pixel FLOAT #######################################
else if ( imageType == FIT_FLOAT && pixelSize == 32)
{
image.type = TYPE_FLOAT_32BPP;
float *data = (float*) malloc(image.width * image.height * (sizeof(float)));
int place=0;
float *line;
for (int i=0; i<(image.height); i++)
{
line = (float *)FreeImage_GetScanLine(img,i);
for (int j=0; j<(image.width); j++)
{
data[place] = line[j];
place++;
}
}
image.begin = (void*)data;
return true;
}
cerr << "This image type can't be handled\n";
return false;
}
//#############################################################################
/* Save an image with given file name and data from Image structure */
//#############################################################################
bool ImageIO::save(char *fname, GpuImageProcess::Image& image)
{
FIBITMAP *img;
RGBQUAD aPixel;
FREE_IMAGE_FORMAT fif = FIF_UNKNOWN; // by default image format is unknown
int i,j;
fif = FreeImage_GetFIFFromFilename(fname);
if (fif == FIF_UNKNOWN)
{
cerr <<"Wrong image format or unsupported\n";
return false;
}
if (image.begin== NULL)
{
cerr << "Error on allocating memory for image\n";
return false;
}
if ( image.width < 0 || image.height < 0 )
{
cerr << "Image dimensions incorrect\n";
return false;
}
unsigned int place=0;
//################################## 8 BIT for pixel ###########################################
if ( image.type == TYPE_UC_8BPP)
{
unsigned char *data = (unsigned char*)image.begin;
img = FreeImage_AllocateT(FIT_BITMAP,image.width, image.height,8);
FIBITMAP* temp ;
temp = FreeImage_ConvertToGreyscale(img);
//img = FreeImage_ConvertTo8Bits(img);
FreeImage_Unload(img);
img = temp;
BYTE *line;
for (i=0; i<image.height; i++)
{
line = FreeImage_GetScanLine(img, i);
for (j=0; j<image.width; j++)
{
line[j] = data[place];
place++;
}
}
}
//################################## 24 BIT for pixel RGB #######################################
else if ( image.type == TYPE_RGB_8BPP)
{
unsigned char *data = (unsigned char*)image.begin;
img = FreeImage_Allocate(image.width, image.height,24);
for( i=0; i < image.height; i++)
{
for (j=0; j< image.width; j++)
{
aPixel.rgbRed = data[place++]; // red
aPixel.rgbGreen = data[place++]; // green
aPixel.rgbBlue = data[place++]; // blue
FreeImage_SetPixelColor(img,j,i, &aPixel);
}
}
}
//################################## 24 BIT for pixel RGB #######################################
else if ( image.type == TYPE_FLOAT_32BPP)
{
float *data = (float*)image.begin;
img = FreeImage_AllocateT(FIT_BITMAP,image.width, image.height,32);
float *line;
for( i=0; i < image.height; i++)
{
line = (float*)FreeImage_GetScanLine(img, i);
for (j=0; j<image.width; j++)
{
line[j] = data[place];
place++;
}
}
}
else
{
cerr << "image of unknown type\n";
return false;
}
// save the image
if (!FreeImage_Save(fif,img,fname,0))
{
cerr << "Error on saving image\n";
return false;
}
FreeImage_Unload(img);
return true;
}
//#############################################################################
/* Destructor */
//#############################################################################
ImageIO::~ImageIO()
{
if ( root.begin != NULL)
{
delete(root.begin);
}
} | [
"ralexay@ae3fb228-0cf0-11de-98bb-07cc9828235c"
]
| [
[
[
1,
301
]
]
]
|
f0c0bae1036c9af378f04d19f4ab682c0741aaa3 | bfcc0f6ef5b3ec68365971fd2e7d32f4abd054ed | /kguiinput.cpp | 1cc2ac85fe9fe66d67959dfff72a32473fd12a57 | []
| 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 | 34,239 | cpp | /*********************************************************************************/
/* kGUI - kguiinput.cpp */
/* */
/* Initially Designed and Programmed by Kevin Pickell */
/* */
/* http://code.google.com/p/kgui/ */
/* */
/* kGUI is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU Lesser General Public License as published by*/
/* the Free Software Foundation; version 2. */
/* */
/* kGUI 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. */
/* */
/* http://www.gnu.org/licenses/lgpl.txt */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with kGUI; if not, write to the Free Software */
/* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
/* */
/*********************************************************************************/
/*********************************************************************************/
/* */
/* This is the standard inputbox object. It can be in the default mode where */
/* all of the text shares a common font and point size, or it can be in */
/* rich mode where each character can have it's own settings. */
/* if password mode is enabled then '*'s are rendered for each character */
/* */
/* todo: (m_numviewlines & m_numfullviewlines) remove these since it screws */
/* up in "rich" mode where each line can have a different height */
/* */
/*********************************************************************************/
#include "kgui.h"
//used for Find/Replace requestor
#include "kguireq.h"
#define ILGAP 2
#define IEDGE 4
kGUIInputBoxObj::kGUIInputBoxObj()
{
m_ow=0;
m_oh=0;
m_xoff=0;
m_hcursor=0;
m_topoff=0; /* lines */
m_leftoff=0; /* pixels */
m_hstart=0;
m_hrange=false;
m_maxlen=-1; /* default is no limit on size */
m_locked=false;
m_wrap=true; /* default wrap mode to true */
m_allowenter=false;
m_allowtab=false;
m_allowcursorexit=false;
m_allowfind=true;
m_leaveselection=false;
m_leavescroll=false;
m_recalclines=true;
m_usevs=false;
m_usehs=false;
m_allowundo=false; /* default to off so as to not take to much memory */
m_password=false;
m_forceshowselection=false;
m_hint=0;
m_maxw=0; /* longest line in pixels */
m_valuetype=GUIINPUTTYPE_STRING; /* default type is string */
m_inputtype=GUIINPUTTYPE_STRING; /* default type is string */
SetUseBGColor(true); /* default to white background for input boxes */
m_valuetext=0;
m_undotext=0;
m_vscrollbar=0;
m_hscrollbar=0;
m_scroll=0;
m_showcommas=false;
}
void kGUIInputBoxObj::Control(unsigned int command,KGCONTROL_DEF *data)
{
switch(command)
{
case KGCONTROL_GETSKIPTAB:
data->m_bool=m_locked;
break;
default:
kGUIObj::Control(command,data);
break;
}
}
kGUIInputBoxObj::~kGUIInputBoxObj()
{
if(m_hint)
delete m_hint;
if(m_valuetext)
delete m_valuetext;
if(m_undotext)
delete m_undotext;
if(m_scroll)
delete m_scroll;
if(m_vscrollbar)
delete m_vscrollbar;
if(m_hscrollbar)
delete m_hscrollbar;
}
void kGUIInputBoxObj::DeleteSelection(void)
{
m_hrange=false;
if(m_hcursor==m_hstart)
return;
if(m_hcursor>m_hstart)
{
if(m_allowundo)
{
/*! @todo Handle mulitple Undo/Redo buffer */
}
if(GetUseRichInfo()==true)
DeleteRichInfo(m_hstart,m_hcursor-m_hstart,false);
Delete(m_hstart,m_hcursor-m_hstart);
m_hcursor=m_hstart;
PutCursorOnScreen();
}
else
{
if(m_allowundo)
{
/* todo: save in undo/redo buffer */
}
if(GetUseRichInfo()==true)
DeleteRichInfo(m_hcursor,m_hstart-m_hcursor,false);
Delete(m_hcursor,m_hstart-m_hcursor);
}
CalcLines(false);
Dirty();
m_hstart=m_hcursor;
}
/* calculate the line break table */
void kGUIInputBoxObj::CalcLines(bool full)
{
int w;
kGUICorners c;
// int lineheight=GetHeight()+ILGAP;
int boxheight;
m_recalclines=false;
m_ow=GetZoneW();
m_oh=GetZoneH();
GetCorners(&c);
c.lx+=2;
c.lx+=m_xoff;
c.rx-=2;
if(m_wrap==false)
{
if(!m_hscrollbar)
{
m_hscrollbar=new kGUIScrollBarObj;
m_hscrollbar->SetHorz();
m_hscrollbar->SetEventHandler(this,& CALLBACKNAME(ScrollMoveCol));
}
m_usehs=true;
}
else
m_usehs=false;
boxheight=c.by-c.ty;
if(m_usehs)
boxheight-=kGUI::GetSkin()->GetScrollbarHeight();
CalcViewLines();
/* if it fits on less than 3 lines then don't bother to show a scroll bar */
CalcLineList(c.rx-c.lx);
/* only show vert scroll if a large enough box */
if(boxheight>50 && GetNumLines()>3)
{
if(!m_vscrollbar)
{
m_vscrollbar=new kGUIScrollBarObj;
m_vscrollbar->SetVert();
m_vscrollbar->SetEventHandler(this,& CALLBACKNAME(ScrollMoveRow));
}
m_usevs=true;
c.rx-=kGUI::GetSkin()->GetScrollbarWidth();
}
else
m_usevs=false;
if((m_wrap==false) || (m_numviewlines==1))
w=100000;
else
w=c.rx-c.lx;
m_maxw=CalcLineList(w);
}
void kGUIInputBoxObj::CalcViewLines(void)
{
int boxheight;
boxheight=GetZoneH();
if(m_usehs)
boxheight-=kGUI::GetSkin()->GetScrollbarHeight();
if(GetUseRichInfo()==false || !GetNumLines())
{
int lineheight=(GetLineHeight()+ILGAP);
m_numviewlines=boxheight/lineheight;
m_numfullviewlines=m_numviewlines;
if((m_numviewlines*lineheight)>boxheight)
--m_numfullviewlines;
}
else
{
unsigned int line;
int y;
m_numviewlines=m_numfullviewlines=GetLineNumPix(GetLineInfo(m_topoff)->ty+boxheight)-m_topoff;
line=m_topoff+m_numviewlines;
y=GetLineInfo(m_topoff+m_numviewlines)->by-GetLineInfo(m_topoff)->ty;
if(y>boxheight)
--m_numfullviewlines;
else if((int)line==GetNumLines()-1 && m_topoff)
{
/* count number of lines back we can go since we have gone off the end */
line=m_topoff-1;
do
{
y+=(GetLineInfo(line)->by-GetLineInfo(line)->ty);
if(y>boxheight)
break;
++m_numviewlines;
if(!line)
break;
--line;
}while(1);
}
}
if(!m_numviewlines)
m_numviewlines=1;
if(m_numfullviewlines<1)
m_numfullviewlines=1;
}
void kGUIInputBoxObj::PutCursorOnScreen(void)
{
int cursorline;
kGUIInputLineInfo *lbptr;
int pixelx;
int width;
CallEvent(EVENT_MOVED);
/* this event can change the string, so we need to check for recalclines here! */
if(m_recalclines==true)
{
if(m_hcursor>GetLen())
m_hcursor=GetLen();
CalcLines(true);
}
cursorline=GetLineNum(m_hcursor);
if(cursorline<0)
return;
lbptr=GetLineInfo(cursorline);
if(cursorline<m_topoff)
{
m_topoff=cursorline;
Dirty();
}
else
{
int boxheight=GetZoneH();
if(m_usehs)
boxheight-=kGUI::GetSkin()->GetScrollbarHeight();
while((lbptr->by-GetLineInfo(m_topoff)->ty)>boxheight && m_topoff!=cursorline)
++m_topoff;
}
CalcViewLines();
/* check left / right now */
width=GetZoneW();
if(m_usevs)
width-=kGUI::GetSkin()->GetScrollbarWidth();
pixelx=GetWidthSub(lbptr->startindex,m_hcursor-lbptr->startindex);
/* scroll left */
if(pixelx<m_leftoff)
{
m_leftoff=pixelx;
Dirty();
}
else if(((pixelx+24)-m_leftoff)>width)
{
/* scroll right */
m_leftoff=(pixelx+24)-width;
Dirty();
}
}
bool kGUIInputBoxObj::MoveCursorRow(int delta)
{
int line;
int newline;
int pixelx,nc;
kGUIInputLineInfo *lbptr;
if(m_recalclines==true)
CalcLines(true);
line=GetLineNum(m_hcursor);
newline=line+delta;
if(newline<0)
newline=0;
else if(newline>=GetNumLines())
newline=MAX(0,GetNumLines()-1);
/* already at top or bottom? */
if(newline==line)
return(false); /* can't move anymore */
lbptr=GetLineInfo(line);
pixelx=GetWidthSub(lbptr->startindex,m_hcursor-lbptr->startindex);
lbptr=GetLineInfo(newline);
nc=CalcFitWidth(lbptr->startindex,lbptr->endindex-lbptr->startindex,pixelx);
m_hcursor=lbptr->startindex+nc;
PutCursorOnScreen();
Dirty();
return(true);
}
void kGUIInputBoxObj::MoveRow(int delta)
{
m_topoff+=delta;
CalcViewLines();
if(m_topoff<0)
{
m_topoff=0;
CalcViewLines();
}
else
{
while(m_topoff && (m_topoff+m_numviewlines)>GetNumLines())
{
--m_topoff;
CalcViewLines();
}
}
Dirty();
}
void kGUIInputBoxObj::MoveCol(int delta)
{
unsigned int width=GetZoneW()-kGUI::GetSkin()->GetScrollbarWidth();
m_leftoff+=delta;
if(m_leftoff+width>m_maxw)
m_leftoff=m_maxw-width;
if(m_leftoff<0)
m_leftoff=0;
Dirty();
}
void kGUIInputBoxObj::CallAfterUpdate(void)
{
/* only if different than undotext */
Dirty();
m_recalclines=true;
if(strcmp(m_undotext->GetString(),GetString()))
{
/* only reset the numeric value string if the field has changed */
if(m_valuetype==GUIINPUTTYPE_INT || m_valuetype==GUIINPUTTYPE_DOUBLE)
m_valuetext->SetString(GetString());
m_undotext->SetString(GetString());
/* call AA parents first as the object callback could delete the object */
kGUI::CallAAParents(this);
CallEvent(EVENT_AFTERUPDATE);
}
else
CallEvent(EVENT_NOCHANGE);
}
void kGUIInputBoxObj::Changed(void)
{
m_valuetype=GUIINPUTTYPE_STRING;
Dirty();
m_recalclines=true;
}
void kGUIInputBoxObj::SetInt(int v)
{
Sprintf("%d",v);
}
/* save the original value but only show it using the format */
/* supplied, so for example */
/* f="%.2f",v="123.45678" */
/* shown on the screen is "123.45" */
/* if you call the function GetValueString and the user didn't change */
/* the number then you will get back "123.45678", if the user did change */
/* it then you will get back the value shown on the screen. */
void kGUIInputBoxObj::SetDouble(const char *f,const char *v)
{
Sprintf(f,atof(v));
if(!m_valuetext)
m_valuetext=new kGUIString;
m_valuetext->SetString(v);
m_valuetext->TTZ();
m_valuetype=GUIINPUTTYPE_DOUBLE; /* must be done after sprintf as it set it to string type */
}
void kGUIInputBoxObj::SetDouble(const char *format,double v)
{
Sprintf(format,v);
if(!m_valuetext)
m_valuetext=new kGUIString;
m_valuetext->SetString(GetString());
m_valuetext->TTZ();
m_valuetype=GUIINPUTTYPE_DOUBLE; /* must be done after Sprintf as it set it to string type */
}
void kGUIInputBoxObj::SetInt(const char *v)
{
SetString(v);
if(!m_valuetext)
m_valuetext=new kGUIString;
m_valuetext->SetString(v);
m_valuetype=GUIINPUTTYPE_INT;
}
const char *kGUIInputBoxObj::GetValueString(void)
{
if(m_valuetype==GUIINPUTTYPE_INT || m_valuetype==GUIINPUTTYPE_DOUBLE)
return m_valuetext->GetString();
else
return kGUIText::GetString();
}
#define INPUTSCROLLDELAY (TICKSPERSEC/30)
void kGUIInputBoxObj::Activate(void)
{
if(this!=kGUI::GetActiveObj())
{
kGUI::PushActiveObj(this);
SetCurrent();
/* save copy into undo buffer */
if(!m_undotext)
m_undotext=new kGUIString;
m_undotext->SetString(GetString());
if(!m_scroll)
{
m_scroll=new kGUIScroll();
m_scroll->SetEventHandler(this,CALLBACKNAME(ScrollEvent));
}
if(GetNumLines())
m_scroll->Init(m_leftoff,GetLineInfo(m_topoff)->ty);
else
m_scroll->Init(m_leftoff,0);
}
}
void kGUIInputBoxObj::DeActivate(void)
{
if(this==kGUI::GetActiveObj())
{
Dirty();
kGUI::PopActiveObj();
CallAfterUpdate();
delete m_undotext;
m_undotext=0;
if(m_scroll)
{
delete m_scroll;
m_scroll=0;
}
}
}
bool kGUIInputBoxObj::UpdateInput(void)
{
int key;
int l;
int lx,rx;
kGUICorners c;
kGUICorners cs;
kGUIText text;
int line;
bool over;
kGUIInputLineInfo *lbptr;
bool used=false;
bool callenter=false;
/* have I been disabled by program code ( not the user )? */
if(this==kGUI::GetActiveObj())
{
if(ImCurrent()==false)
goto abort;
}
GetCorners(&c);
if(kGUI::WantHint()==true && m_hint)
kGUI::SetHintString(c.lx+10,c.ty-15,m_hint->GetString());
if(m_recalclines==true)
CalcLines(true);
over=kGUI::MouseOver(&c);
if(over==false && kGUI::GetMouseClick()==true)
{
abort:;
if(this==kGUI::GetActiveObj())
DeActivate();
PutCursorOnScreen();
if(m_leaveselection==false)
m_hrange=false;
return(false);
}
if(kGUI::GetMouseDoubleClickLeft()==true)
{
SetCurrent();
CallDoubleClick();
return(true);
}
if(kGUI::GetMouseClickRight()==true)
{
SetCurrent();
CallRightClick();
return(true);
}
if(this!=kGUI::GetActiveObj())
{
if(kGUI::GetMouseClickLeft()==true || kGUI::GetKey())
{
SetCurrent();
Activate();
callenter=true;
}
}
if(this==kGUI::GetActiveObj())
{
c.lx+=m_xoff;
if(m_usevs==true)
{
int below=GetNumLines()-m_topoff-m_numviewlines;
if(below<0)
below=0;
m_vscrollbar->SetValues(m_topoff,m_numviewlines,below);
}
if(m_usehs==true)
{
int width=c.rx-c.lx-kGUI::GetSkin()->GetScrollbarWidth();
int right=m_maxw-width-m_leftoff;
if(right<0)
right=0;
m_hscrollbar->SetValues(m_leftoff,width,right);
}
/* should we flash the cursor? */
if(kGUI::GetDrawCursorChanged())
Dirty();
/* is the horizontal scroll bar on? */
if(m_usehs==true)
{
if(m_hscrollbar->IsActive()==true)
return(m_hscrollbar->UpdateInput());
m_hscrollbar->GetCorners(&cs);
if(kGUI::MouseOver(&cs))
{
if(callenter)
CallEvent(EVENT_ENTER);
return(m_hscrollbar->UpdateInput());
}
}
/* is the vertical scroll bar on? */
if(m_usevs==true)
{
if(m_vscrollbar->IsActive()==true)
return(m_vscrollbar->UpdateInput());
m_vscrollbar->GetCorners(&cs);
if(kGUI::MouseOver(&cs))
{
if(callenter)
CallEvent(EVENT_ENTER);
return(m_vscrollbar->UpdateInput());
}
}
/* is the mouse button down? */
if(kGUI::GetMouseLeft()==true)
{
used=true;
/* scroll left? */
lx=c.lx+12;
rx=c.rx;
if(m_usehs)
rx-=kGUI::GetSkin()->GetScrollbarWidth();
if(kGUI::GetMouseX()<lx)
{
kGUIInputLineInfo *lbptr;
line=GetLineNum(m_hcursor);
lbptr=GetLineInfo(line);
if(m_hcursor>lbptr->startindex)
{
if(m_hdelay.Update(INPUTSCROLLDELAY))
{
/* go back 1 character, handle multi byte character sets */
m_hcursor-=GoBack(m_hcursor);
Dirty();
PutCursorOnScreen();
}
}
}
else if(kGUI::GetMouseX()>rx)
{
kGUIInputLineInfo *lbptr;
line=GetLineNum(m_hcursor);
lbptr=GetLineInfo(line);
if(m_hcursor<lbptr->endindex)
{
if(m_hdelay.Update(INPUTSCROLLDELAY))
{
unsigned int x;
/* go forward 1 character, handle multi byte character sets */
GetChar(m_hcursor,&x);
m_hcursor+=x;
Dirty();
PutCursorOnScreen();
}
}
}
else
{
int nc;
if(kGUI::GetMouseY()<c.ty)
{
if(m_topoff)
{
if(m_hdelay.Update(INPUTSCROLLDELAY))
{
--m_topoff;
m_hcursor=GetLineInfo(m_topoff)->startindex;
PutCursorOnScreen();
Dirty();
}
}
return(true);
}
else if(kGUI::GetMouseY()>c.by)
{
if((m_topoff+m_numviewlines)<GetNumLines())
{
if(m_hdelay.Update(INPUTSCROLLDELAY))
{
++m_topoff;
m_hcursor=GetLineInfo(m_topoff+m_numviewlines-1)->endindex;
PutCursorOnScreen();
Dirty();
}
}
return(true);
}
else
{
/* this needs to handle varying height lines */
line=GetLineNumPix(GetLineInfo(m_topoff)->ty+(kGUI::GetMouseY()-c.ty));
// line=(kGUI::GetMouseY()-c.ty)/(GetHeight()+ILGAP)+m_topoff;
// if(line>=GetNumLines())
// line=GetNumLines()-1;
lbptr=GetLineInfo(line);
nc=CalcFitWidth(lbptr->startindex,lbptr->endindex-lbptr->startindex,(kGUI::GetMouseX()-c.lx)+m_leftoff);
m_hcursor=lbptr->startindex+nc;
PutCursorOnScreen();
}
}
if(kGUI::GetKeyShift()==true || kGUI::GetMouseClickLeft()==true)
{
m_hstart=m_hcursor;
m_hrange=false;
}
if(m_hstart!=m_hcursor)
m_hrange=true;
Dirty();
}
if(callenter)
CallEvent(EVENT_ENTER);
{
int scroll=kGUI::GetMouseWheelDelta();
kGUI::ClearMouseWheelDelta();
if(scroll)
{
if(MoveCursorRow(-scroll)==false)
{
/* tried to cursor off of the field, if no changes then Deactivate */
if(!strcmp(m_undotext->GetString(),GetString()))
{
DeActivate();
return(false); /* return false so table knows to use this key */
}
}
}
}
key=kGUI::GetKey();
if(key)
{
used=true;
switch(key)
{
case GUIKEY_PGDOWN:
/* todo: move down the number of lines currently displayed */
MoveCursorRow(m_numfullviewlines);
break;
case GUIKEY_DOWN:
if(MoveCursorRow(1)==false)
{
if(m_allowcursorexit==true)
goto exitcell;
}
break;
case GUIKEY_PGUP:
/* todo: move up the number of lines currently displayed */
MoveCursorRow(-m_numfullviewlines);
break;
case GUIKEY_UP:
if(MoveCursorRow(-1)==false)
{
if(m_allowcursorexit==true)
goto exitcell;
}
break;
case GUIKEY_LEFT:
if(m_hcursor>0)
{
/*handle multi byte strings like UTF-8 etc. */
m_hcursor-=GoBack(m_hcursor);
Dirty();
}
break;
case GUIKEY_RIGHT:
if(m_hcursor<(GetLen()))
{
/*handle multi byte strings like UTF-8 etc. */
unsigned int x;
GetChar(m_hcursor,&x);
m_hcursor+=x;
Dirty();
}
break;
case GUIKEY_HOME:
if(kGUI::GetKeyControl()==true)
{
if(m_hcursor>0)
{
m_hcursor=0;
Dirty();
}
}
else
{
/* beginning of current line */
kGUIInputLineInfo *lbptr;
lbptr=GetLineInfo(GetLineNum(m_hcursor));
if(m_hcursor!=lbptr->startindex)
{
m_hcursor=lbptr->startindex;
Dirty();
}
}
break;
case GUIKEY_F2:
case GUIKEY_END:
if(kGUI::GetKeyControl()==true)
{
unsigned int el=GetLen();
if(m_hcursor!=el)
{
m_hcursor=el;
Dirty();
}
}
else
{
/* end of current line */
kGUIInputLineInfo *lbptr;
lbptr=GetLineInfo(GetLineNum(m_hcursor));
if(m_hcursor!=lbptr->endindex)
{
m_hcursor=lbptr->endindex;
Dirty();
}
}
break;
case GUIKEY_TAB:
if(m_allowtab==true)
{
key='\t';
goto keypressed;
}
/* fall through */
case GUIKEY_SHIFTTAB:
exitcell: m_leftoff=0;
m_hcursor=0;
m_hstart=0;
m_hrange=false;
PutCursorOnScreen();
DeActivate();
return(false); /* return false so table knows to use this key */
break;
case GUIKEY_ESC: /* undo */
m_leftoff=0;
m_hcursor=0;
m_hstart=0;
m_hrange=false;
m_recalclines=true;
SetString(m_undotext->GetString());
PutCursorOnScreen();
kGUI::ClearKey();
DeActivate();
return(true);
break;
case GUIKEY_SELECTALL:
SelectAll();
return(true);
break;
case GUIKEY_RETURN:
if(m_allowenter==true)
goto keypressed;
m_leftoff=0;
m_hcursor=0;
m_hstart=0;
m_hrange=false;
PutCursorOnScreen();
kGUI::ClearKey();
DeActivate();
CallEvent(EVENT_PRESSRETURN);
return(true);
break;
case GUIKEY_DELETE:
if(m_locked==false)
{
if(m_hrange==true)
DeleteSelection();
else if(m_hcursor<GetLen())
{
unsigned int nb;
GetChar(m_hcursor,&nb);
if(m_allowundo)
{
/* todo: save in undo/redo buffer */
}
/* handle multi-byte character sets */
if(GetUseRichInfo()==true)
DeleteRichInfo(m_hcursor,nb,false);
Delete(m_hcursor,nb);
CalcLines(false);
Dirty();
}
}
break;
case GUIKEY_BACKSPACE:
if(m_locked==false)
{
if(m_hrange==true)
DeleteSelection();
else if(m_hcursor>0)
{
unsigned int nb;
/* handle multi byte character sets */
nb=GoBack(m_hcursor);
if(m_allowundo)
{
/* todo: save in undo/redo buffer */
}
if(GetUseRichInfo()==true)
DeleteRichInfo(m_hcursor-nb,nb,false);
Delete(m_hcursor-nb,nb);
Dirty();
CalcLines(false);
m_hcursor-=nb;
}
m_hstart=m_hcursor;
}
break;
case GUIKEY_COPY:
/* should we disable this if this is a password box? */
if(m_hrange==true)
{
kGUIString paste;
int start,end;
start=MIN(m_hstart,m_hcursor);
end=MAX(m_hstart,m_hcursor);
if(end>start)
{
paste.SetString(GetString()+start,end-start);
paste.SetEncoding(GetEncoding());
kGUI::Copy(&paste);
}
}
break;
case GUIKEY_CUT:
/* should we disable this if this is a password box? */
if(m_hrange==true)
{
kGUIString paste;
int start,end;
start=MIN(m_hstart,m_hcursor);
end=MAX(m_hstart,m_hcursor);
if(end>start)
{
paste.SetString(GetString()+start,end-start);
paste.SetEncoding(GetEncoding());
kGUI::Copy(&paste);
DeleteSelection();
}
}
break;
case GUIKEY_UNDO:
//todo
break;
case GUIKEY_PASTE:
{
if(m_locked==false)
{
unsigned int ci;
unsigned int nb;
kGUIString paste;
kGUI::Paste(&paste);
if(m_hrange==true)
DeleteSelection();
paste.Replace("\r",""); /* remove c/r, only accept linefeeds */
if(m_allowenter==false)
paste.Replace("\n",""); /* remove c/r */
if(m_allowtab==false)
paste.Replace("\t",""); /* remove tabs */
/* handle different string types */
if(GetEncoding()!=paste.GetEncoding())
{
int charindex;
/* convert both strings to UTF-8, then merge */
/* convert character offset to a cursor position, and then back after change encoding */
charindex=CursorToIndex(m_hcursor);
ChangeEncoding(ENCODING_UTF8);
m_hcursor=IndexToCursor(charindex);
paste.ChangeEncoding(ENCODING_UTF8);
}
/* check all characters in the paste string and remove any */
/* invalid characters */
ci=0;
while(ci<paste.GetLen())
{
key=paste.GetChar(ci,&nb);
if(CheckInput(key)==false)
paste.Delete(ci,nb);
else
ci+=nb;
}
if(paste.GetLen())
{
if(m_allowundo==true)
{
/* save in undo buffer */
}
Insert(m_hcursor,paste.GetString());
if(GetUseRichInfo()==true)
InsertRichInfo(m_hcursor,paste.GetLen());
m_hcursor+=paste.GetLen();
/* is new size too long? */
if(m_maxlen>0)
{
if(GetLen()>(unsigned int)m_maxlen)
{
if(m_allowundo==true)
{
/* save in undo buffer */
}
if(GetUseRichInfo()==true)
DeleteRichInfo(m_maxlen,GetLen()-m_maxlen,false);
Clip((unsigned int)m_maxlen);
}
}
if(m_hcursor>GetLen())
m_hcursor=GetLen();
CalcLines(false);
PutCursorOnScreen();
Dirty();
m_hrange=false;
m_hstart=m_hcursor;
}
}
}
break;
case GUIKEY_FIND:
case GUIKEY_REPLACE:
if(m_allowfind)
{
kGUISearchReq::Open(this,this);
m_forceshowselection=true;
}
break;
default:
/* insert a letter into the string */
keypressed: if(m_locked==false)
{
if((key==10) || (key==13) || (key==GUIKEY_RETURN)) /* control return inside a string */
key=10; /* "\n" */
if(CheckInput(key)==true)
{
/* any selected area to delete? */
if(m_hrange==true)
DeleteSelection();
l=GetLen();
if(l<m_maxlen || (m_maxlen<0)) /* -1 == no limit */
{
/* handle multi byte character sets */
kGUIString kk;
unsigned int nb;
kk.Append((char)key);
/* make encoding for typed character match the strings encoding */
kk.ChangeEncoding(GetEncoding());
Insert(m_hcursor,kk.GetString());
GetChar(m_hcursor,&nb);
if(GetUseRichInfo()==true)
InsertRichInfo(m_hcursor,nb);
m_hcursor+=nb;
CalcLines(false);
Dirty();
}
m_hrange=false;
m_hstart=m_hcursor;
PutCursorOnScreen();
}
}
break;
}
kGUI::ClearKey();
if(kGUI::GetKeyShift()==true)
m_hrange=true;
else
{
m_hrange=false;
m_hstart=m_hcursor;
}
/* make sure cursor is onscreen, scroll if it is not */
PutCursorOnScreen();
}
}
else if(ImCurrent())
{
/* should we flash the cursor? */
if(kGUI::GetDrawCursorChanged())
Dirty();
}
return(used);
}
bool kGUIInputBoxObj::CheckInput(int key)
{
switch(m_inputtype)
{
case GUIINPUTTYPE_STRING:
if((key==10) || (key=='\t') || (key>=' ' && key<=255) || (key>='a' && key<='z') || (key>='A' && key<='Z') )
return(true);
break;
case GUIINPUTTYPE_INT:
if((key>='0' && key<='9') || (key=='-') )
return(true);
break;
case GUIINPUTTYPE_DOUBLE:
if((key>='0' && key<='9') || (key=='.') || (key=='$') || (key=='-') || (key=='e'))
return(true);
break;
}
return(false);
}
void kGUIInputBoxObj::Draw(void)
{
int i,x;
int hs,he,w;
unsigned int schar;
unsigned int echar;
int llen;
kGUICorners cc;
kGUICorners c;
bool imactive;
kGUIInputLineInfo *lbptr;
int h,y;
kGUIZone sz;
bool drawcursor;
int topoff,leftoff;
kGUIString save;
kGUIInputLineInfo saveli;
unsigned int hc=m_hcursor;
if((m_recalclines==true) || (m_ow!=GetZoneW()) || (m_oh!=GetZoneH()) )
CalcLines(true);
// m_forceshowselection
drawcursor=false;
imactive=(this==kGUI::GetActiveObj());
if(!imactive && m_leaveselection==false && m_forceshowselection==false)
{
if(ImCurrent())
{
if(GetLen())
{
m_hrange=true;
m_hstart=GetLen();
m_hcursor=0;
}
else
{
/* since there is no text to hilight, draw the cursor instead */
drawcursor=kGUI::GetDrawCursor()==true;
m_hrange=false;
m_hstart=0;
m_hcursor=0;
}
}
else
{
m_hrange=false;
m_hstart=m_hcursor;
}
}
else
{
if(kGUI::GetDrawCursor()==true && (m_hrange==false))
drawcursor=true;
}
GetCorners(&cc); /* get topcorner */
kGUI::PushClip();
GetCorners(&c);
kGUI::ShrinkClip(&c);
/* is there anywhere to draw? */
if(kGUI::ValidClip())
{
if(m_hrange==false)
{
hs=-1;
he=-1;
}
else if(m_hstart<m_hcursor)
{
hs=m_hstart;
he=m_hcursor;
}
else
{
hs=m_hcursor;
he=m_hstart;
}
if(m_password==true)
{
unsigned int cpos;
/* save string and put back after drawing */
save.SetString(this);
lbptr=GetLineInfo(0);
saveli=*(lbptr);
/* replace all chars with asterisks */
for(cpos=0;cpos<GetLen();++cpos)
SetChar(cpos,'*');
CalcLineList(GetZoneW());
}
else if(m_showcommas)
{
int cpos;
int slen;
/* I am assuming that the string is numbers only and on a single line */
/* at this point I am also assuming 8 bit characters since they should all be */
/* 0-9 digits only */
/* todo: make handle negative numbers */
/* save string and put back after drawing */
save.SetString(this);
lbptr=GetLineInfo(0);
saveli=*(lbptr);
if(GetChar(0)=='-')
slen=1;
else
slen=0;
cpos=GetLen()-3;
while(cpos>slen)
{
Insert(cpos,",");
if(hc>=(unsigned int)cpos)
hc+=1;
if(hs>=cpos)
hs+=1;
if(he>=cpos)
he+=1;
cpos-=3;
}
CalcLineList(GetZoneW());
}
if(GetUseBGColor())
kGUI::DrawRectBevelIn(c.lx,c.ty,c.rx,c.by,GetBGColor());
if(imactive==true || m_leavescroll)
{
if(m_usevs==true)
{
sz.SetZone(c.rx-kGUI::GetSkin()->GetScrollbarWidth(),c.ty,kGUI::GetSkin()->GetScrollbarWidth(),c.by-c.ty);
m_vscrollbar->MoveZone(&sz);
m_vscrollbar->Draw();
}
if(m_usehs==true)
{
sz.SetZone(c.lx,c.by-kGUI::GetSkin()->GetScrollbarHeight(),(c.rx-c.lx)-kGUI::GetSkin()->GetScrollbarWidth(),kGUI::GetSkin()->GetScrollbarHeight());
m_hscrollbar->MoveZone(&sz);
m_hscrollbar->Draw();
}
if(m_usehs==true || m_usevs==true)
{
if(m_usevs)
c.rx-=kGUI::GetSkin()->GetScrollbarWidth();
if(m_usehs)
c.by-=kGUI::GetSkin()->GetScrollbarHeight();
}
}
c.ty+=IEDGE;
c.lx+=IEDGE;
c.lx+=m_xoff;
kGUI::ShrinkClip(&c);
h=GetLineHeight()+ILGAP;
y=c.ty;
if(m_scroll)
{
int pixely;
m_scroll->SetDest(m_leftoff,GetLineInfo(m_topoff)->ty);
/* since scrolling is still happening get the actual topoff */
leftoff=m_scroll->GetCurrentX();
pixely=m_scroll->GetCurrentY();
/* get the line num at pixel down position y */
topoff=GetLineNumPix(pixely);
y-=pixely-GetLineInfo(topoff)->ty;
}
else
{
topoff=m_topoff;
leftoff=m_leftoff;
}
SetRevRange(hs,he);
x=c.lx-leftoff;
for(i=topoff;i<GetNumLines();++i)
{
lbptr=GetLineInfo(i);
schar=lbptr->startindex;
echar=lbptr->endindex;
llen=echar-schar;
if(lbptr->hardbreak==false)
--echar;
DrawSection(schar,llen,x,x,y,lbptr->pixheight);
/* is the cursor on this line? */
if((hc>=schar) && (hc<=echar))
{
if(drawcursor==true)
{
w=GetWidthSub(schar,hc-schar);
if(drawcursor==true)
kGUI::DrawRect(x+w,y,x+w+3,y+lbptr->pixheight-4,GetColor());
}
}
y+=lbptr->pixheight+2;
if(y>c.by)
break;
}
if(m_showcommas || m_password)
{
/* since string was changed, put it back now */
SetString(&save);
*(GetLineInfo(0))=saveli;
}
}
kGUI::PopClip();
}
void kGUIInputBoxObj::GetCursorRange(unsigned int *si,unsigned int *ei)
{
if(m_hrange==false)
{
*(si)=m_hcursor;
*(ei)=m_hcursor+1;
}
else if(m_hstart<m_hcursor)
{
*(si)=m_hstart;
*(ei)=m_hcursor;
}
else
{
*(si)=m_hcursor;
*(ei)=m_hstart;
}
}
void kGUIInputBoxObj::StringSearch(kGUIString *from,bool matchcase,bool matchword)
{
unsigned int c=m_hcursor+1;
bool wrap=false;
int newc;
if(c>=GetLen())
{
c=0;
wrap=true;
}
while(1)
{
newc=Str(from->GetString(),matchcase,matchword,c);
if(newc>=0)
{
m_hcursor=newc;
m_hstart=newc+from->GetLen();
m_hrange=true;
PutCursorOnScreen();
Dirty();
return;
}
if(wrap)
return;
c=0;
wrap=true;
}
}
void kGUIInputBoxObj::StringReplace(kGUIString *from,bool matchcase,bool matchword,kGUIString *to)
{
unsigned int c=m_hcursor;
bool wrap=false;
int newc;
if(c>=GetLen())
{
c=0;
wrap=true;
}
while(1)
{
newc=Str(from->GetString(),matchcase,matchword,c);
if(newc>=0)
{
Replace(from->GetString(),to->GetString(),newc,matchcase,1);
m_hcursor=newc;
m_hstart=newc+to->GetLen();
m_hrange=true;
PutCursorOnScreen();
Dirty();
return;
}
if(wrap)
return;
c=0;
wrap=true;
}
}
/***********************************************************/
kGUIScrollInputBoxObj::kGUIScrollInputBoxObj()
{
SetHAlign(FT_CENTER);
SetVAlign(FT_MIDDLE);
}
bool kGUIScrollInputBoxObj::UpdateInput(void)
{
bool used;
int x,w;
x=GetZoneX();w=GetZoneW();
MoveZoneX(x+16);MoveZoneW(w-32);
used=kGUIInputBoxObj::UpdateInput();
MoveZoneX(x);MoveZoneW(w);
if(used==false)
{
if(kGUI::GetMouseClickLeft()==true)
{
kGUICorners c;
kGUIEvent e;
int w=kGUI::GetSkin()->GetScrollHorizButtonWidths();
GetCorners(&c);
if(kGUI::GetMouseX()<(c.lx+w))
{
e.m_value[0].i=-1;
CallEvent(EVENT_PRESSED,&e); /* left arrow button was pressed */
kGUI::CallAAParents(this);
used=true;
}
else if(kGUI::GetMouseX()>(c.rx-w))
{
e.m_value[0].i=1;
CallEvent(EVENT_PRESSED,&e); /* right arrow button was pressed */
kGUI::CallAAParents(this);
used=true;
}
}
}
return(used);
}
void kGUIScrollInputBoxObj::Draw(void)
{
kGUICorners c;
int x,w;
kGUI::PushClip();
GetCorners(&c);
kGUI::ShrinkClip(&c);
/* is there anywhere to draw? */
if(kGUI::ValidClip())
{
kGUI::GetSkin()->DrawScrollHoriz(&c);
x=GetZoneX();w=GetZoneW();
MoveZoneX(x+16);MoveZoneW(w-32);
kGUIInputBoxObj::Draw();
MoveZoneX(x);MoveZoneW(w);
}
kGUI::PopClip();
}
| [
"[email protected]@4b35e2fd-144d-0410-91a6-811dcd9ab31d"
]
| [
[
[
1,
1521
]
]
]
|
ce0615803132ea99f467cd9196a1b4039c3b995f | 81e051c660949ac0e89d1e9cf286e1ade3eed16a | /quake3ce/code/game/g_active.cpp | 8d4f84bc9376293d04c4d75086a0cc205d46a230 | []
| no_license | crioux/q3ce | e89c3b60279ea187a2ebcf78dbe1e9f747a31d73 | 5e724f55940ac43cb25440a65f9e9e12220c9ada | refs/heads/master | 2020-06-04T10:29:48.281238 | 2008-11-16T15:00:38 | 2008-11-16T15:00:38 | 32,103,416 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 33,116 | cpp | /*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code 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.
Quake III Arena source code 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 Foobar; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
//
#include"game_pch.h"
/*
===============
G_DamageFeedback
Called just before a snapshot is sent to the given player.
Totals up all damage and generates both the player_state_t
damage values to that client for pain blends and kicks, and
global pain sound events for all clients.
===============
*/
void P_DamageFeedback( gentity_t *player ) {
gclient_t *client;
gfixed count;
avec3_t angles;
client = player->client;
if ( client->ps.pm_type == PM_DEAD ) {
return;
}
// total points of damage shot at the player this frame
count = MAKE_GFIXED(client->damage_blood + client->damage_armor);
if ( count == GFIXED_0 ) {
return; // didn't take any damage
}
if ( count > GFIXED(255 ,0)) {
count = GFIXED(255,0);
}
// send the information to the client
// world damage (falling, slime, etc) uses a special code
// to make the blend blob centered instead of positional
if ( client->damage_fromWorld ) {
client->ps.damagePitch = 255;
client->ps.damageYaw = 255;
client->damage_fromWorld = qfalse;
} else {
vectoangles( client->damage_from, angles );
client->ps.damagePitch = FIXED_TO_INT(angles[PITCH]/AFIXED(360,0) * AFIXED(256,0));
client->ps.damageYaw = FIXED_TO_INT(angles[YAW]/AFIXED(360,0) * AFIXED(256,0));
}
// play an apropriate pain sound
if ( (level.time > player->pain_debounce_time) && !(player->flags & FL_GODMODE) ) {
player->pain_debounce_time = level.time + 700;
G_AddEvent( player, EV_PAIN, player->health );
client->ps.damageEvent++;
}
client->ps.damageCount = FIXED_TO_INT(count);
//
// clear totals
//
client->damage_blood = 0;
client->damage_armor = 0;
client->damage_knockback = 0;
}
/*
=============
P_WorldEffects
Check for lava / slime contents and drowning
=============
*/
void P_WorldEffects( gentity_t *ent ) {
qboolean envirosuit;
int waterlevel;
if ( ent->client->noclip ) {
ent->client->airOutTime = level.time + 12000; // don't need air
return;
}
waterlevel = ent->waterlevel;
envirosuit = ent->client->ps.powerups[PW_BATTLESUIT] > level.time;
//
// check for drowning
//
if ( waterlevel == 3 ) {
// envirosuit give air
if ( envirosuit ) {
ent->client->airOutTime = level.time + 10000;
}
// if out of air, start drowning
if ( ent->client->airOutTime < level.time) {
// drown!
ent->client->airOutTime += 1000;
if ( ent->health > 0 ) {
// take more damage the longer underwater
ent->damage += 2;
if (ent->damage > 15)
ent->damage = 15;
// play a gurp sound instead of a normal pain sound
if (ent->health <= ent->damage) {
G_Sound(ent, CHAN_VOICE, G_SoundIndex("*drown.wav"));
} else if (rand()&1) {
G_Sound(ent, CHAN_VOICE, G_SoundIndex("sound/player/gurp1.wav"));
} else {
G_Sound(ent, CHAN_VOICE, G_SoundIndex("sound/player/gurp2.wav"));
}
// don't play a normal pain sound
ent->pain_debounce_time = level.time + 200;
G_Damage (ent, NULL, NULL, NULL, NULL,
ent->damage, DAMAGE_NO_ARMOR, MOD_WATER);
}
}
} else {
ent->client->airOutTime = level.time + 12000;
ent->damage = 2;
}
//
// check for sizzle damage (move to pmove?)
//
if (waterlevel &&
(ent->watertype&(CONTENTS_LAVA|CONTENTS_SLIME)) ) {
if (ent->health > 0
&& ent->pain_debounce_time <= level.time ) {
if ( envirosuit ) {
G_AddEvent( ent, EV_POWERUP_BATTLESUIT, 0 );
} else {
if (ent->watertype & CONTENTS_LAVA) {
G_Damage (ent, NULL, NULL, NULL, NULL,
30*waterlevel, 0, MOD_LAVA);
}
if (ent->watertype & CONTENTS_SLIME) {
G_Damage (ent, NULL, NULL, NULL, NULL,
10*waterlevel, 0, MOD_SLIME);
}
}
}
}
}
/*
===============
G_SetClientSound
===============
*/
void G_SetClientSound( gentity_t *ent ) {
#ifdef MISSIONPACK
if( ent->s.eFlags & EF_TICKING ) {
ent->client->ps.loopSound = G_SoundIndex( "sound/weapons/proxmine/wstbtick.wav");
}
else
#endif
if (ent->waterlevel && (ent->watertype&(CONTENTS_LAVA|CONTENTS_SLIME)) ) {
ent->client->ps.loopSound = level.snd_fry;
} else {
ent->client->ps.loopSound = 0;
}
}
//==============================================================
/*
==============
ClientImpacts
==============
*/
void ClientImpacts( gentity_t *ent, pmove_t *pm ) {
int i, j;
trace_t trace;
gentity_t *other;
memset( &trace, 0, sizeof( trace ) );
for (i=0 ; i<pm->numtouch ; i++) {
for (j=0 ; j<i ; j++) {
if (pm->touchents[j] == pm->touchents[i] ) {
break;
}
}
if (j != i) {
continue; // duplicated
}
other = &g_entities[ pm->touchents[i] ];
if ( ( ent->r.svFlags & SVF_BOT ) && ( ent->touch ) ) {
ent->touch( ent, other, &trace );
}
if ( !other->touch ) {
continue;
}
other->touch( other, ent, &trace );
}
}
/*
============
G_TouchTriggers
Find all trigger entities that ent's current position touches.
Spectators will only interact with teleporters.
============
*/
void G_TouchTriggers( gentity_t *ent ) {
int i, num;
int touch[MAX_GENTITIES];
gentity_t *hit;
trace_t trace;
bvec3_t mins, maxs;
static bvec3_t range = { BFIXED(40,0), BFIXED(40,0), BFIXED(52 ,0)};
if ( !ent->client ) {
return;
}
// dead clients don't activate triggers!
if ( ent->client->ps.stats[STAT_HEALTH] <= 0 ) {
return;
}
VectorSubtract( ent->client->ps.origin, range, mins );
VectorAdd( ent->client->ps.origin, range, maxs );
num = _G_trap_EntitiesInBox( mins, maxs, touch, MAX_GENTITIES );
// can't use ent->absmin, because that has a one unit pad
VectorAdd( ent->client->ps.origin, ent->r.mins, mins );
VectorAdd( ent->client->ps.origin, ent->r.maxs, maxs );
for ( i=0 ; i<num ; i++ ) {
hit = &g_entities[touch[i]];
if ( !hit->touch && !ent->touch ) {
continue;
}
if ( !( hit->r.contents & CONTENTS_TRIGGER ) ) {
continue;
}
// ignore most entities if a spectator
if ( ent->client->sess.sessionTeam == TEAM_SPECTATOR ) {
if ( hit->s.eType != ET_TELEPORT_TRIGGER &&
// this is ugly but adding a new ET_? type will
// most likely cause network incompatibilities
hit->touch != Touch_DoorTrigger) {
continue;
}
}
// use seperate code for determining if an item is picked up
// so you don't have to actually contact its bounding box
if ( hit->s.eType == ET_ITEM ) {
if ( !BG_PlayerTouchesItem( &ent->client->ps, &hit->s, level.time ) ) {
continue;
}
} else {
if ( !_G_trap_EntityContact( mins, maxs, hit ) ) {
continue;
}
}
memset( &trace, 0, sizeof(trace) );
if ( hit->touch ) {
hit->touch (hit, ent, &trace);
}
if ( ( ent->r.svFlags & SVF_BOT ) && ( ent->touch ) ) {
ent->touch( ent, hit, &trace );
}
}
// if we didn't touch a jump pad this pmove frame
if ( ent->client->ps.jumppad_frame != ent->client->ps.pmove_framecount ) {
ent->client->ps.jumppad_frame = 0;
ent->client->ps.jumppad_ent = 0;
}
}
/*
=================
SpectatorThink
=================
*/
void SpectatorThink( gentity_t *ent, usercmd_t *ucmd ) {
pmove_t pm;
gclient_t *client;
client = ent->client;
if ( client->sess.spectatorState != SPECTATOR_FOLLOW ) {
client->ps.pm_type = PM_SPECTATOR;
client->ps.speed = 400; // faster than normal
// set up for pmove
memset (&pm, 0, sizeof(pm));
pm.ps = &client->ps;
pm.cmd = *ucmd;
pm.tracemask = MASK_PLAYERSOLID & ~CONTENTS_BODY; // spectators can fly through bodies
pm.trace = _G_trap_Trace;
pm.pointcontents = _G_trap_PointContents;
// perform a pmove
Pmove (&pm);
// save results of pmove
VectorCopy( client->ps.origin, ent->s.origin );
G_TouchTriggers( ent );
_G_trap_UnlinkEntity( ent );
}
client->oldbuttons = client->buttons;
client->buttons = ucmd->buttons;
// attack button cycles through spectators
if ( ( client->buttons & BUTTON_ATTACK ) && ! ( client->oldbuttons & BUTTON_ATTACK ) ) {
Cmd_FollowCycle_f( ent, 1 );
}
}
/*
=================
ClientInactivityTimer
Returns qfalse if the client is dropped
=================
*/
qboolean ClientInactivityTimer( gclient_t *client ) {
if ( ! g_inactivity.integer ) {
// give everyone some time, so if the operator sets g_inactivity during
// gameplay, everyone isn't kicked
client->inactivityTime = level.time + 60 * 1000;
client->inactivityWarning = qfalse;
} else if ( client->pers.cmd.forwardmove ||
client->pers.cmd.rightmove ||
client->pers.cmd.upmove ||
(client->pers.cmd.buttons & BUTTON_ATTACK) ) {
client->inactivityTime = level.time + g_inactivity.integer * 1000;
client->inactivityWarning = qfalse;
} else if ( !client->pers.localClient ) {
if ( level.time > client->inactivityTime ) {
_G_trap_DropClient( client - level.clients, "Dropped due to inactivity" );
return qfalse;
}
if ( level.time > client->inactivityTime - 10000 && !client->inactivityWarning ) {
client->inactivityWarning = qtrue;
_G_trap_SendServerCommand( client - level.clients, "cp \"Ten seconds until inactivity drop!\n\"" );
}
}
return qtrue;
}
/*
==================
ClientTimerActions
Actions that happen once a second
==================
*/
void ClientTimerActions( gentity_t *ent, int msec ) {
gclient_t *client;
#ifdef MISSIONPACK
int maxHealth;
#endif
client = ent->client;
client->timeResidual += msec;
while ( client->timeResidual >= 1000 ) {
client->timeResidual -= 1000;
// regenerate
#ifdef MISSIONPACK
if( bg_itemlist[client->ps.stats[STAT_PERSISTANT_POWERUP]].giTag == PW_GUARD ) {
maxHealth = client->ps.stats[STAT_MAX_HEALTH] / 2;
}
else if ( client->ps.powerups[PW_REGEN] ) {
maxHealth = client->ps.stats[STAT_MAX_HEALTH];
}
else {
maxHealth = 0;
}
if( maxHealth ) {
if ( ent->health < maxHealth ) {
ent->health += 15;
if ( ent->health > maxHealth * GFIXED(1,1) ) {
ent->health = maxHealth * GFIXED(1,1);
}
G_AddEvent( ent, EV_POWERUP_REGEN, 0 );
} else if ( ent->health < maxHealth * 2) {
ent->health += 5;
if ( ent->health > maxHealth * 2 ) {
ent->health = maxHealth * 2;
}
G_AddEvent( ent, EV_POWERUP_REGEN, 0 );
}
#else
if ( client->ps.powerups[PW_REGEN] ) {
if ( ent->health < client->ps.stats[STAT_MAX_HEALTH]) {
ent->health += 15;
if ( ent->health > FIXED_TO_INT(MAKE_GFIXED(client->ps.stats[STAT_MAX_HEALTH]) * GFIXED(1,1)) ) {
ent->health = FIXED_TO_INT(MAKE_GFIXED(client->ps.stats[STAT_MAX_HEALTH]) * GFIXED(1,1));
}
G_AddEvent( ent, EV_POWERUP_REGEN, 0 );
} else if ( ent->health < client->ps.stats[STAT_MAX_HEALTH] * 2) {
ent->health += 5;
if ( ent->health > client->ps.stats[STAT_MAX_HEALTH] * 2 ) {
ent->health = client->ps.stats[STAT_MAX_HEALTH] * 2;
}
G_AddEvent( ent, EV_POWERUP_REGEN, 0 );
}
#endif
} else {
// count down health when over max
if ( ent->health > client->ps.stats[STAT_MAX_HEALTH] ) {
ent->health--;
}
}
// count down armor when over max
if ( client->ps.stats[STAT_ARMOR] > client->ps.stats[STAT_MAX_HEALTH] ) {
client->ps.stats[STAT_ARMOR]--;
}
}
#ifdef MISSIONPACK
if( bg_itemlist[client->ps.stats[STAT_PERSISTANT_POWERUP]].giTag == PW_AMMOREGEN ) {
int w, max, inc, t, i;
int weapList[]={WP_MACHINEGUN,WP_SHOTGUN,WP_GRENADE_LAUNCHER,WP_ROCKET_LAUNCHER,WP_LIGHTNING,WP_RAILGUN,WP_PLASMAGUN,WP_BFG,WP_NAILGUN,WP_PROX_LAUNCHER,WP_CHAINGUN};
int weapCount = sizeof(weapList) / sizeof(int);
//
for (i = 0; i < weapCount; i++) {
w = weapList[i];
switch(w) {
case WP_MACHINEGUN: max = 50; inc = 4; t = 1000; break;
case WP_SHOTGUN: max = 10; inc = 1; t = 1500; break;
case WP_GRENADE_LAUNCHER: max = 10; inc = 1; t = 2000; break;
case WP_ROCKET_LAUNCHER: max = 10; inc = 1; t = 1750; break;
case WP_LIGHTNING: max = 50; inc = 5; t = 1500; break;
case WP_RAILGUN: max = 10; inc = 1; t = 1750; break;
case WP_PLASMAGUN: max = 50; inc = 5; t = 1500; break;
case WP_BFG: max = 10; inc = 1; t = 4000; break;
case WP_NAILGUN: max = 10; inc = 1; t = 1250; break;
case WP_PROX_LAUNCHER: max = 5; inc = 1; t = 2000; break;
case WP_CHAINGUN: max = 100; inc = 5; t = 1000; break;
default: max = 0; inc = 0; t = 1000; break;
}
client->ammoTimes[w] += msec;
if ( client->ps.ammo[w] >= max ) {
client->ammoTimes[w] = 0;
}
if ( client->ammoTimes[w] >= t ) {
while ( client->ammoTimes[w] >= t )
client->ammoTimes[w] -= t;
client->ps.ammo[w] += inc;
if ( client->ps.ammo[w] > max ) {
client->ps.ammo[w] = max;
}
}
}
}
#endif
}
/*
====================
ClientIntermissionThink
====================
*/
void ClientIntermissionThink( gclient_t *client ) {
client->ps.eFlags &= ~EF_TALK;
client->ps.eFlags &= ~EF_FIRING;
// the level will exit when everyone wants to or after timeouts
// swap and latch button actions
client->oldbuttons = client->buttons;
client->buttons = client->pers.cmd.buttons;
if ( client->buttons & ( BUTTON_ATTACK | BUTTON_USE_HOLDABLE ) & ( client->oldbuttons ^ client->buttons ) ) {
// this used to be an ^1 but once a player says ready, it should stick
client->readyToExit = 1;
}
}
/*
================
ClientEvents
Events will be passed on to the clients for presentation,
but any server game effects are handled here
================
*/
void ClientEvents( gentity_t *ent, int oldEventSequence ) {
int i, j;
int event;
gclient_t *client;
int damage;
avec3_t dir;
bvec3_t origin;
avec3_t angles;
// qboolean fired;
gitem_t *item;
gentity_t *drop;
client = ent->client;
if ( oldEventSequence < client->ps.eventSequence - MAX_PS_EVENTS ) {
oldEventSequence = client->ps.eventSequence - MAX_PS_EVENTS;
}
for ( i = oldEventSequence ; i < client->ps.eventSequence ; i++ ) {
event = client->ps.events[ i & (MAX_PS_EVENTS-1) ];
switch ( event ) {
case EV_FALL_MEDIUM:
case EV_FALL_FAR:
if ( ent->s.eType != ET_PLAYER ) {
break; // not in the player model
}
if ( g_dmflags.integer & DF_NO_FALLING ) {
break;
}
if ( event == EV_FALL_FAR ) {
damage = 10;
} else {
damage = 5;
}
VectorSet (dir, AFIXED_0, AFIXED_0, AFIXED_1);
ent->pain_debounce_time = level.time + 200; // no normal pain sound
G_Damage (ent, NULL, NULL, NULL, NULL, damage, 0, MOD_FALLING);
break;
case EV_FIRE_WEAPON:
FireWeapon( ent );
break;
case EV_USE_ITEM1: // teleporter
// drop flags in CTF
item = NULL;
j = 0;
if ( ent->client->ps.powerups[ PW_REDFLAG ] ) {
item = BG_FindItemForPowerup( PW_REDFLAG );
j = PW_REDFLAG;
} else if ( ent->client->ps.powerups[ PW_BLUEFLAG ] ) {
item = BG_FindItemForPowerup( PW_BLUEFLAG );
j = PW_BLUEFLAG;
} else if ( ent->client->ps.powerups[ PW_NEUTRALFLAG ] ) {
item = BG_FindItemForPowerup( PW_NEUTRALFLAG );
j = PW_NEUTRALFLAG;
}
if ( item ) {
drop = Drop_Item( ent, item, AFIXED_0 );
// decide how many seconds it has left
drop->count = FIXED_TO_INT(MSECTIME_G( ent->client->ps.powerups[ j ] - level.time ));
if ( drop->count < 1 ) {
drop->count = 1;
}
ent->client->ps.powerups[ j ] = 0;
}
#ifdef MISSIONPACK
if ( g_gametype.integer == GT_HARVESTER ) {
if ( ent->client->ps.generic1 > 0 ) {
if ( ent->client->sess.sessionTeam == TEAM_RED ) {
item = BG_FindItem( "Blue Cube" );
} else {
item = BG_FindItem( "Red Cube" );
}
if ( item ) {
for ( j = 0; j < ent->client->ps.generic1; j++ ) {
drop = Drop_Item( ent, item, 0 );
if ( ent->client->sess.sessionTeam == TEAM_RED ) {
drop->spawnflags = TEAM_BLUE;
} else {
drop->spawnflags = TEAM_RED;
}
}
}
ent->client->ps.generic1 = 0;
}
}
#endif
SelectSpawnPoint( ent->client->ps.origin, origin, angles );
TeleportPlayer( ent, origin, angles );
break;
case EV_USE_ITEM2: // medkit
ent->health = ent->client->ps.stats[STAT_MAX_HEALTH] + 25;
break;
#ifdef MISSIONPACK
case EV_USE_ITEM3: // kamikaze
// make sure the invulnerability is off
ent->client->invulnerabilityTime = 0;
// start the kamikze
G_StartKamikaze( ent );
break;
case EV_USE_ITEM4: // portal
if( ent->client->portalID ) {
DropPortalSource( ent );
}
else {
DropPortalDestination( ent );
}
break;
case EV_USE_ITEM5: // invulnerability
ent->client->invulnerabilityTime = level.time + 10000;
break;
#endif
default:
break;
}
}
}
#ifdef MISSIONPACK
/*
==============
StuckInOtherClient
==============
*/
static int StuckInOtherClient(gentity_t *ent) {
int i;
gentity_t *ent2;
ent2 = &g_entities[0];
for ( i = 0; i < MAX_CLIENTS; i++, ent2++ ) {
if ( ent2 == ent ) {
continue;
}
if ( !ent2->inuse ) {
continue;
}
if ( !ent2->client ) {
continue;
}
if ( ent2->health <= 0 ) {
continue;
}
//
if (ent2->r.absmin[0] > ent->r.absmax[0])
continue;
if (ent2->r.absmin[1] > ent->r.absmax[1])
continue;
if (ent2->r.absmin[2] > ent->r.absmax[2])
continue;
if (ent2->r.absmax[0] < ent->r.absmin[0])
continue;
if (ent2->r.absmax[1] < ent->r.absmin[1])
continue;
if (ent2->r.absmax[2] < ent->r.absmin[2])
continue;
return qtrue;
}
return qfalse;
}
#endif
void BotTestSolid(bvec3_t origin);
/*
==============
SendPendingPredictableEvents
==============
*/
void SendPendingPredictableEvents( playerState_t *ps ) {
gentity_t *t;
int event, seq;
int extEvent, number;
// if there are still events pending
if ( ps->entityEventSequence < ps->eventSequence ) {
// create a temporary entity for this event which is sent to everyone
// except the client who generated the event
seq = ps->entityEventSequence & (MAX_PS_EVENTS-1);
event = ps->events[ seq ] | ( ( ps->entityEventSequence & 3 ) << 8 );
// set external event to zero before calling BG_PlayerStateToEntityState
extEvent = ps->externalEvent;
ps->externalEvent = 0;
// create temporary entity for event
t = G_TempEntity( ps->origin, event );
number = t->s.number;
BG_PlayerStateToEntityState( ps, &t->s, qtrue );
t->s.number = number;
t->s.eType = ET_EVENTS + event;
t->s.eFlags |= EF_PLAYER_EVENT;
t->s.otherEntityNum = ps->clientNum;
// send to everyone except the client who generated the event
t->r.svFlags |= SVF_NOTSINGLECLIENT;
t->r.singleClient = ps->clientNum;
// set back external event
ps->externalEvent = extEvent;
}
}
/*
==============
ClientThink
This will be called once for each client frame, which will
usually be a couple times for each server frame on fast clients.
If "g_synchronousClients 1" is set, this will be called exactly
once for each server frame, which makes for smooth demo recording.
==============
*/
void ClientThink_real( gentity_t *ent ) {
gclient_t *client;
pmove_t pm;
int oldEventSequence;
int msec;
usercmd_t *ucmd;
client = ent->client;
// don't think if the client is not yet connected (and thus not yet spawned in)
if (client->pers.connected != CON_CONNECTED) {
return;
}
// mark the time, so the connection sprite can be removed
ucmd = &ent->client->pers.cmd;
// sanity check the command time to prevent speedup cheating
if ( ucmd->serverTime > level.time + 200 ) {
ucmd->serverTime = level.time + 200;
// G_Printf("serverTime <<<<<\n" );
}
if ( ucmd->serverTime < level.time - 1000 ) {
ucmd->serverTime = level.time - 1000;
// G_Printf("serverTime >>>>>\n" );
}
msec = ucmd->serverTime - client->ps.commandTime;
// following others may result in bad times, but we still want
// to check for follow toggles
if ( msec < 1 && client->sess.spectatorState != SPECTATOR_FOLLOW ) {
return;
}
if ( msec > 200 ) {
msec = 200;
}
if ( pmove_msec.integer < 8 ) {
_G_trap_Cvar_Set("pmove_msec", "8");
}
else if (pmove_msec.integer > 33) {
_G_trap_Cvar_Set("pmove_msec", "33");
}
if ( pmove_fixed.integer || client->pers.pmoveFixed ) {
ucmd->serverTime = ((ucmd->serverTime + pmove_msec.integer-1) / pmove_msec.integer) * pmove_msec.integer;
//if (ucmd->serverTime - client->ps.commandTime <= 0)
// return;
}
//
// check for exiting intermission
//
if ( level.intermissiontime ) {
ClientIntermissionThink( client );
return;
}
// spectators don't do much
if ( client->sess.sessionTeam == TEAM_SPECTATOR ) {
if ( client->sess.spectatorState == SPECTATOR_SCOREBOARD ) {
return;
}
SpectatorThink( ent, ucmd );
return;
}
// check for inactivity timer, but never drop the local client of a non-dedicated server
if ( !ClientInactivityTimer( client ) ) {
return;
}
// clear the rewards if time
if ( level.time > client->rewardTime ) {
client->ps.eFlags &= ~(EF_AWARD_IMPRESSIVE | EF_AWARD_EXCELLENT | EF_AWARD_GAUNTLET | EF_AWARD_ASSIST | EF_AWARD_DEFEND | EF_AWARD_CAP );
}
if ( client->noclip ) {
client->ps.pm_type = PM_NOCLIP;
} else if ( client->ps.stats[STAT_HEALTH] <= 0 ) {
client->ps.pm_type = PM_DEAD;
} else {
client->ps.pm_type = PM_NORMAL;
}
client->ps.gravity = FIXED_TO_INT(g_gravity.value);
// set speed
client->ps.speed = FIXED_TO_INT(g_speed.value);
#ifdef MISSIONPACK
if( bg_itemlist[client->ps.stats[STAT_PERSISTANT_POWERUP]].giTag == PW_SCOUT ) {
client->ps.speed *= GFIXED(1,5);
}
else
#endif
if ( client->ps.powerups[PW_HASTE] ) {
client->ps.speed = FIXED_TO_INT(MAKE_GFIXED(client->ps.speed) * GFIXED(1,3));
}
// Let go of the hook if we aren't firing
if ( client->ps.weapon == WP_GRAPPLING_HOOK &&
client->hook && !( ucmd->buttons & BUTTON_ATTACK ) ) {
Weapon_HookFree(client->hook);
}
// set up for pmove
oldEventSequence = client->ps.eventSequence;
memset (&pm, 0, sizeof(pm));
// check for the hit-scan gauntlet, don't let the action
// go through as an attack unless it actually hits something
if ( client->ps.weapon == WP_GAUNTLET && !( ucmd->buttons & BUTTON_TALK ) &&
( ucmd->buttons & BUTTON_ATTACK ) && client->ps.weaponTime <= 0 ) {
pm.gauntletHit = CheckGauntletAttack( ent );
}
if ( ent->flags & FL_FORCE_GESTURE ) {
ent->flags &= ~FL_FORCE_GESTURE;
ent->client->pers.cmd.buttons |= BUTTON_GESTURE;
}
#ifdef MISSIONPACK
// check for invulnerability expansion before doing the Pmove
if (client->ps.powerups[PW_INVULNERABILITY] ) {
if ( !(client->ps.pm_flags & PMF_INVULEXPAND) ) {
bvec3_t mins = { -42, -42, -42 };
bvec3_t maxs = { 42, 42, 42 };
bvec3_t oldmins, oldmaxs;
VectorCopy (ent->r.mins, oldmins);
VectorCopy (ent->r.maxs, oldmaxs);
// expand
VectorCopy (mins, ent->r.mins);
VectorCopy (maxs, ent->r.maxs);
_G_trap_LinkEntity(ent);
// check if this would get anyone stuck in this player
if ( !StuckInOtherClient(ent) ) {
// set flag so the expanded size will be set in PM_CheckDuck
client->ps.pm_flags |= PMF_INVULEXPAND;
}
// set back
VectorCopy (oldmins, ent->r.mins);
VectorCopy (oldmaxs, ent->r.maxs);
_G_trap_LinkEntity(ent);
}
}
#endif
pm.ps = &client->ps;
pm.cmd = *ucmd;
if ( pm.ps->pm_type == PM_DEAD ) {
pm.tracemask = MASK_PLAYERSOLID & ~CONTENTS_BODY;
}
else if ( ent->r.svFlags & SVF_BOT ) {
pm.tracemask = MASK_PLAYERSOLID | CONTENTS_BOTCLIP;
}
else {
pm.tracemask = MASK_PLAYERSOLID;
}
pm.trace = _G_trap_Trace;
pm.pointcontents = _G_trap_PointContents;
pm.debugLevel = g_debugMove.integer;
pm.noFootsteps = ( g_dmflags.integer & DF_NO_FOOTSTEPS ) > 0;
pm.pmove_fixed = pmove_fixed.integer | client->pers.pmoveFixed;
pm.pmove_msec = pmove_msec.integer;
VectorCopy( client->ps.origin, client->oldOrigin );
#ifdef MISSIONPACK
if (level.intermissionQueued != 0 && g_singlePlayer.integer) {
if ( level.time - level.intermissionQueued >= 1000 ) {
pm.cmd.buttons = 0;
pm.cmd.forwardmove = 0;
pm.cmd.rightmove = 0;
pm.cmd.upmove = 0;
if ( level.time - level.intermissionQueued >= 2000 && level.time - level.intermissionQueued <= 2500 ) {
_G_trap_SendConsoleCommand( EXEC_APPEND, "centerview\n");
}
ent->client->ps.pm_type = PM_SPINTERMISSION;
}
}
Pmove (&pm);
#else
Pmove (&pm);
#endif
// save results of pmove
if ( ent->client->ps.eventSequence != oldEventSequence ) {
ent->eventTime = level.time;
}
if (g_smoothClients.integer) {
BG_PlayerStateToEntityStateExtraPolate( &ent->client->ps, &ent->s, ent->client->ps.commandTime, qtrue );
}
else {
BG_PlayerStateToEntityState( &ent->client->ps, &ent->s, qtrue );
}
SendPendingPredictableEvents( &ent->client->ps );
if ( !( ent->client->ps.eFlags & EF_FIRING ) ) {
client->fireHeld = qfalse; // for grapple
}
// use the snapped origin for linking so it matches client predicted versions
VectorCopy( ent->s.pos.trBase, ent->r.currentOrigin );
VectorCopy (pm.mins, ent->r.mins);
VectorCopy (pm.maxs, ent->r.maxs);
ent->waterlevel = pm.waterlevel;
ent->watertype = pm.watertype;
// execute client events
ClientEvents( ent, oldEventSequence );
// link entity now, after any personal teleporters have been used
_G_trap_LinkEntity (ent);
if ( !ent->client->noclip ) {
G_TouchTriggers( ent );
}
// NOTE: now copy the exact origin over otherwise clients can be snapped into solid
VectorCopy( ent->client->ps.origin, ent->r.currentOrigin );
//test for solid areas in the AAS file
BotTestAAS(ent->r.currentOrigin);
// touch other objects
ClientImpacts( ent, &pm );
// save results of triggers and client events
if (ent->client->ps.eventSequence != oldEventSequence) {
ent->eventTime = level.time;
}
// swap and latch button actions
client->oldbuttons = client->buttons;
client->buttons = ucmd->buttons;
client->latched_buttons |= client->buttons & ~client->oldbuttons;
// check for respawning
if ( client->ps.stats[STAT_HEALTH] <= 0 ) {
// wait for the attack button to be pressed
if ( level.time > client->respawnTime ) {
// forcerespawn is to prevent users from waiting out powerups
if ( g_forcerespawn.integer > 0 &&
( level.time - client->respawnTime ) > g_forcerespawn.integer * 1000 ) {
respawn( ent );
return;
}
// pressing attack or use is the normal respawn method
if ( ucmd->buttons & ( BUTTON_ATTACK | BUTTON_USE_HOLDABLE ) ) {
respawn( ent );
}
}
return;
}
// perform once-a-second actions
ClientTimerActions( ent, msec );
}
/*
==================
ClientThink
A new command has arrived from the client
==================
*/
void ClientThink( int clientNum ) {
gentity_t *ent;
ent = g_entities + clientNum;
_G_trap_GetUsercmd( clientNum, &ent->client->pers.cmd );
// mark the time we got info, so we can display the
// phone jack if they don't get any for a while
ent->client->lastCmdTime = level.time;
if ( !(ent->r.svFlags & SVF_BOT) && !g_synchronousClients.integer ) {
ClientThink_real( ent );
}
}
void G_RunClient( gentity_t *ent ) {
if ( !(ent->r.svFlags & SVF_BOT) && !g_synchronousClients.integer ) {
return;
}
ent->client->pers.cmd.serverTime = level.time;
ClientThink_real( ent );
}
/*
==================
SpectatorClientEndFrame
==================
*/
void SpectatorClientEndFrame( gentity_t *ent ) {
gclient_t *cl;
// if we are doing a chase cam or a remote view, grab the latest info
if ( ent->client->sess.spectatorState == SPECTATOR_FOLLOW ) {
int clientNum, flags;
clientNum = ent->client->sess.spectatorClient;
// team follow1 and team follow2 go to whatever clients are playing
if ( clientNum == -1 ) {
clientNum = level.follow1;
} else if ( clientNum == -2 ) {
clientNum = level.follow2;
}
if ( clientNum >= 0 ) {
cl = &level.clients[ clientNum ];
if ( cl->pers.connected == CON_CONNECTED && cl->sess.sessionTeam != TEAM_SPECTATOR ) {
flags = (cl->ps.eFlags & ~(EF_VOTED | EF_TEAMVOTED)) | (ent->client->ps.eFlags & (EF_VOTED | EF_TEAMVOTED));
ent->client->ps = cl->ps;
ent->client->ps.pm_flags |= PMF_FOLLOW;
ent->client->ps.eFlags = flags;
return;
} else {
// drop them to free spectators unless they are dedicated camera followers
if ( ent->client->sess.spectatorClient >= 0 ) {
ent->client->sess.spectatorState = SPECTATOR_FREE;
ClientBegin( ent->client - level.clients );
}
}
}
}
if ( ent->client->sess.spectatorState == SPECTATOR_SCOREBOARD ) {
ent->client->ps.pm_flags |= PMF_SCOREBOARD;
} else {
ent->client->ps.pm_flags &= ~PMF_SCOREBOARD;
}
}
/*
==============
ClientEndFrame
Called at the end of each server frame for each connected client
A fast client will have multiple ClientThink for each ClientEdFrame,
while a slow client may have multiple ClientEndFrame between ClientThink.
==============
*/
void ClientEndFrame( gentity_t *ent ) {
int i;
clientPersistant_t *pers;
if ( ent->client->sess.sessionTeam == TEAM_SPECTATOR ) {
SpectatorClientEndFrame( ent );
return;
}
pers = &ent->client->pers;
// turn off any expired powerups
for ( i = 0 ; i < MAX_POWERUPS ; i++ ) {
if ( ent->client->ps.powerups[ i ] < level.time ) {
ent->client->ps.powerups[ i ] = 0;
}
}
#ifdef MISSIONPACK
// set powerup for player animation
if( bg_itemlist[ent->client->ps.stats[STAT_PERSISTANT_POWERUP]].giTag == PW_GUARD ) {
ent->client->ps.powerups[PW_GUARD] = level.time;
}
if( bg_itemlist[ent->client->ps.stats[STAT_PERSISTANT_POWERUP]].giTag == PW_SCOUT ) {
ent->client->ps.powerups[PW_SCOUT] = level.time;
}
if( bg_itemlist[ent->client->ps.stats[STAT_PERSISTANT_POWERUP]].giTag == PW_DOUBLER ) {
ent->client->ps.powerups[PW_DOUBLER] = level.time;
}
if( bg_itemlist[ent->client->ps.stats[STAT_PERSISTANT_POWERUP]].giTag == PW_AMMOREGEN ) {
ent->client->ps.powerups[PW_AMMOREGEN] = level.time;
}
if ( ent->client->invulnerabilityTime > level.time ) {
ent->client->ps.powerups[PW_INVULNERABILITY] = level.time;
}
#endif
// save network bandwidth
#if 0
if ( !g_synchronousClients->integer && ent->client->ps.pm_type == PM_NORMAL ) {
// FIXME: this must change eventually for non-sync demo recording
VectorClear( ent->client->ps.viewangles );
}
#endif
//
// If the end of unit layout is displayed, don't give
// the player any normal movement attributes
//
if ( level.intermissiontime ) {
return;
}
// burn from lava, etc
P_WorldEffects (ent);
// apply all the damage taken this frame
P_DamageFeedback (ent);
// add the EF_CONNECTION flag if we haven't gotten commands recently
if ( level.time - ent->client->lastCmdTime > 1000 ) {
ent->s.eFlags |= EF_CONNECTION;
} else {
ent->s.eFlags &= ~EF_CONNECTION;
}
ent->client->ps.stats[STAT_HEALTH] = ent->health; // FIXME: get rid of ent->health...
G_SetClientSound (ent);
// set the latest infor
if (g_smoothClients.integer) {
BG_PlayerStateToEntityStateExtraPolate( &ent->client->ps, &ent->s, ent->client->ps.commandTime, qtrue );
}
else {
BG_PlayerStateToEntityState( &ent->client->ps, &ent->s, qtrue );
}
SendPendingPredictableEvents( &ent->client->ps );
// set the bit for the reachability area the client is currently in
// i = _G_trap_AAS_PointReachabilityAreaIndex( ent->client->ps.origin );
// ent->client->areabits[i >> 3] |= 1 << (i & 7);
}
| [
"jack.palevich@684fc592-8442-0410-8ea1-df6b371289ac"
]
| [
[
[
1,
1191
]
]
]
|
a8f73f263800def8eb7cfae68876496b375b0bbd | 016774685beb74919bb4245d4d626708228e745e | /iOS/Pulmon/ozcollide/intr_spherebox.h | 36f730efe2829439d1142db36501515ad152c980 | []
| no_license | sutuglon/Motor | 10ec08954d45565675c9b53f642f52f404cb5d4d | 16f667b181b1516dc83adc0710f8f5a63b00cc75 | refs/heads/master | 2020-12-24T16:59:23.348677 | 2011-12-20T20:44:19 | 2011-12-20T20:44:19 | 1,925,770 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,283 | h | /*
OZCollide - Collision Detection Library
Copyright (C) 2006 Igor Kravtchenko
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Contact the author: [email protected]
*/
#ifndef OZCOLLIDE_INTERSECTION_SPHEREBOX_H
#define OZCOLLIDE_INTERSECTION_SPHEREBOX_H
#ifndef OZCOLLIDE_PCH
#include <ozcollide/ozcollide.h>
#endif
ENTER_NAMESPACE_OZCOLLIDE
class Sphere;
class Ellipsoid;
class Box;
class Vec3f;
OZCOLLIDE_API bool testIntersectionSphereBox(const Sphere &, const Box &);
OZCOLLIDE_API bool testIntersectionEllipsoidBox(const Ellipsoid &, const Box &);
LEAVE_NAMESPACE
#endif
| [
"[email protected]"
]
| [
[
[
1,
42
]
]
]
|
1af37343a13696249544aa410c84245ca56186a0 | 8902879a2619a8278c4dd064f62d8e0e8ffb4e3b | /util/WinUtf8.cpp | 2d66b6cd82b00e285403307a749baff1d03a9fd8 | [
"BSD-2-Clause"
]
| permissive | ArnCarveris/directui | 4d9911143db125dfb114ca97a70f426dbd89dd79 | da531f8bc7737f932c960906cc5f4481a0e162b8 | refs/heads/master | 2023-03-17T00:59:28.853973 | 2011-05-19T02:38:42 | 2011-05-19T02:38:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,672 | cpp |
#define DONT_HIDE_WIN32
#include "WinUtf8.h"
#include "StrUtil.h"
bool DeleteFileUtf8(const char* path)
{
ScopedMem<WCHAR> pathW(str::Utf8ToUni(path));
return DeleteFileW(pathW) != 0;
}
char *GetFullPathNameUtf8(const char* lpFileNameUtf8)
{
WCHAR tmp[1024];
WCHAR *buf = tmp;
DWORD cchBuf = dimof(tmp);
ScopedMem<WCHAR> fileName(str::Utf8ToUni(lpFileNameUtf8));
OnceMore:
DWORD ret = GetFullPathNameW(fileName, cchBuf, buf, NULL);
if (0 == ret)
goto Error;
if (ret >= cchBuf) {
if (buf != tmp)
goto Error;
cchBuf = ret + 8;
buf = SAZA(WCHAR, cchBuf);
goto OnceMore;
}
char *p = str::UniToUtf8(tmp);
if (buf != tmp)
free(buf);
return p;
Error:
if (buf != tmp)
free(buf);
return NULL;
}
char *GetLongPathNameUtf8(const char* lpszShortPathUtf8)
{
WCHAR tmp[1024];
WCHAR *buf = tmp;
DWORD cchBuf = dimof(tmp);
ScopedMem<WCHAR> shortPath(str::Utf8ToUni(lpszShortPathUtf8));
OnceMore:
DWORD ret = GetLongPathNameW(shortPath, buf, cchBuf);
if (0 == ret)
goto Error;
if (ret >= cchBuf) {
if (buf != tmp)
goto Error;
cchBuf = ret + 8;
buf = SAZA(WCHAR, cchBuf);
goto OnceMore;
}
char *p = str::UniToUtf8(buf);
if (buf != tmp)
free(buf);
return p;
Error:
if (buf != tmp)
free(buf);
return NULL;
}
char *SHGetSpecialFolderPathUtf8(HWND hwndOwner, int csidl, BOOL fCreate)
{
WCHAR dir[MAX_PATH] = {0};
BOOL ok = SHGetSpecialFolderPathW(hwndOwner, dir, csidl, fCreate);
if (!ok)
return NULL;
return str::UniToUtf8(dir);
}
HANDLE CreateFileUtf8(const char *fileNameUtf8, DWORD dwDesiredAccess, DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes, HANDLE hTemplateFile)
{
ScopedMem<WCHAR> fileName(str::Utf8ToUni(fileNameUtf8));
HANDLE h = CreateFileW(fileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition,
dwFlagsAndAttributes, hTemplateFile);
return h;
}
bool CreateDirectoryUtf8(const char* lpPathNameUtf8, LPSECURITY_ATTRIBUTES lpSecurityAttributes)
{
ScopedMem<WCHAR> dir(str::Utf8ToUni(lpPathNameUtf8));
return !!CreateDirectoryW(dir, lpSecurityAttributes);
}
bool GetFileAttributesExUtf8(const char* lpFileNameUtf8, GET_FILEEX_INFO_LEVELS fInfoLevelId, void* lpFileInformation)
{
ScopedMem<WCHAR> fileName(str::Utf8ToUni(lpFileNameUtf8));
return !!GetFileAttributesExW(fileName, fInfoLevelId, lpFileInformation);
}
HWND CreateWindowExUtf8(DWORD dwExStyle, const char * lpClassName, const char *lpWindowName,
DWORD dwStyle, int X, int Y, int nWidth, int nHeight,
HWND hWndParent, HMENU hMenu, HINSTANCE hInstance, LPVOID lpParam)
{
ScopedMem<WCHAR> className(str::Utf8ToUni(lpClassName));
ScopedMem<WCHAR> windowName(str::Utf8ToUni(lpWindowName));
return CreateWindowExW(dwExStyle, className, windowName, dwStyle, X, Y, nWidth, nHeight,
hWndParent, hMenu, hInstance, lpParam);
}
void SetWindowTextUtf8(HWND hwnd, const char *s)
{
ScopedMem<WCHAR> tmp(str::Utf8ToUni(s));
SetWindowTextW(hwnd, tmp);
}
void Edit_SetTextUtf8(HWND hwnd, const char *s)
{
SetWindowTextUtf8(hwnd, s);
}
char *GetWindowTextUtf8(HWND hwnd)
{
WCHAR buf[1024];
WCHAR *tmp = buf;
int cch = GetWindowTextLength(hwnd);
if (cch + 1 > dimof(buf)) {
cch += 1;
tmp = (WCHAR*)malloc(cch * sizeof(WCHAR));
} else {
cch = dimof(buf);
}
BOOL ok = ::GetWindowTextW(hwnd, tmp, cch);
if (ok == 0)
return NULL;
return str::UniToUtf8(buf);
}
int DrawTextUtf8(HDC hdc, const char* lpchText, int cchText, LPRECT lprc, UINT format)
{
// TODO: not sure how cchText translates from utf8 to WCHAR
ScopedMem<WCHAR> s(str::Utf8ToUni(lpchText));
return DrawTextW(hdc, s, cchText, lprc, format);
}
BOOL TextOutUtf8(HDC hdc, int nXStart, int nYStart, const char* lpString, int cchString)
{
// TODO: not sure how cchText translates from utf8 to WCHAR
ScopedMem<WCHAR> s(str::Utf8ToUni(lpString));
return TextOutW(hdc, nXStart, nYStart, s, cchString);
}
BOOL GetTextExtentPoint32Utf8(HDC hdc, const char *lpString, int cch, LPSIZE lpSize)
{
// TODO: not sure how cchText translates from utf8 to WCHAR
ScopedMem<WCHAR> s(str::Utf8ToUni(lpString));
return GetTextExtentPoint32W(hdc, s, cch, lpSize);
}
| [
"[email protected]"
]
| [
[
[
1,
159
]
]
]
|
4c61bf54d489db5eef89ee7f2ed6b3c36f3850b4 | a92598d0a8a2e92b424915d2944212f2f13e7506 | /PtRPG/libs/cocos2dx/CCScheduler.cpp | 0ae2cf07ea9752f695c3f85bb1e6b2bbfe750799 | [
"MIT"
]
| permissive | peteo/RPG_Learn | 0cc4facd639bd01d837ac56cf37a07fe22c59211 | 325fd1802b14e055732278f3d2d33a9577608c39 | refs/heads/master | 2021-01-23T11:07:05.050645 | 2011-12-12T08:47:27 | 2011-12-12T08:47:27 | 2,299,148 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,638 | cpp | /****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011 Zynga Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCScheduler.h"
#include "ccMacros.h"
#include "support/data_support/utlist.h"
#include "support/data_support/ccCArray.h"
#include "CCMutableArray.h"
#include "CCScriptSupport.h"
#include <assert.h>
using namespace std;
namespace cocos2d {
// data structures
// A list double-linked list used for "updates with priority"
typedef struct _listEntry
{
struct _listEntry *prev, *next;
SelectorProtocol *target; // not retained (retained by hashUpdateEntry)
int priority;
bool paused;
bool markedForDeletion; // selector will no longer be called and entry will be removed at end of the next tick
} tListEntry;
typedef struct _hashUpdateEntry
{
tListEntry **list; // Which list does it belong to ?
tListEntry *entry; // entry in the list
SelectorProtocol *target; // hash key (retained)
UT_hash_handle hh;
} tHashUpdateEntry;
// Hash Element used for "selectors with interval"
typedef struct _hashSelectorEntry
{
ccArray *timers;
SelectorProtocol *target; // hash key (retained)
unsigned int timerIndex;
CCTimer *currentTimer;
bool currentTimerSalvaged;
bool paused;
UT_hash_handle hh;
} tHashSelectorEntry;
// Hash Element used for "script functions with interval"
typedef struct _hashScriptFuncEntry
{
CCTimer *timer;
bool paused;
const char *funcName;
UT_hash_handle hh;
} tHashScriptFuncEntry;
// implementation CCTimer
CCTimer::CCTimer()
: m_pTarget(NULL)
, m_scriptFunc("")
, m_fInterval(0.0f)
, m_fElapsed(0.0f)
, m_pfnSelector(NULL)
{
}
CCTimer* CCTimer::timerWithTarget(SelectorProtocol *pTarget, SEL_SCHEDULE pfnSelector)
{
CCTimer *pTimer = new CCTimer();
pTimer->initWithTarget(pTarget, pfnSelector);
pTimer->autorelease();
return pTimer;
}
CCTimer* CCTimer::timerWithScriptFuncName(const char* pszFuncName, ccTime fSeconds)
{
CCTimer *pTimer = new CCTimer();
pTimer->initWithScriptFuncName(pszFuncName, fSeconds);
pTimer->autorelease();
return pTimer;
}
CCTimer* CCTimer::timerWithTarget(SelectorProtocol *pTarget, SEL_SCHEDULE pfnSelector, ccTime fSeconds)
{
CCTimer *pTimer = new CCTimer();
pTimer->initWithTarget(pTarget, pfnSelector, fSeconds);
pTimer->autorelease();
return pTimer;
}
bool CCTimer::initWithScriptFuncName(const char *pszFuncName, cocos2d::ccTime fSeconds)
{
m_scriptFunc = string(pszFuncName);
m_fInterval = fSeconds;
m_fElapsed = -1;
return true;
}
bool CCTimer::initWithTarget(SelectorProtocol *pTarget, SEL_SCHEDULE pfnSelector)
{
return initWithTarget(pTarget, pfnSelector, 0);
}
bool CCTimer::initWithTarget(SelectorProtocol *pTarget, SEL_SCHEDULE pfnSelector, ccTime fSeconds)
{
m_pTarget = pTarget;
m_pfnSelector = pfnSelector;
m_fElapsed = -1;
m_fInterval = fSeconds;
return true;
}
void CCTimer::update(ccTime dt)
{
if (m_fElapsed == -1)
{
m_fElapsed = 0;
}
else
{
m_fElapsed += dt;
}
if (m_fElapsed >= m_fInterval)
{
if (0 != m_pfnSelector)
{
(m_pTarget->*m_pfnSelector)(m_fElapsed);
m_fElapsed = 0;
}
else if (m_scriptFunc.size() && CCScriptEngineManager::sharedScriptEngineManager()->getScriptEngine())
{
// call script function
CCScriptEngineManager::sharedScriptEngineManager()->getScriptEngine()->executeSchedule(m_scriptFunc.c_str(), m_fElapsed);
m_fElapsed = 0;
}
}
}
// implementation of CCScheduler
static CCScheduler *pSharedScheduler;
CCScheduler::CCScheduler(void)
: m_fTimeScale(0.0)
, m_pUpdatesNegList(NULL)
, m_pUpdates0List(NULL)
, m_pUpdatesPosList(NULL)
, m_pHashForUpdates(NULL)
, m_pHashForSelectors(NULL)
, m_pCurrentTarget(NULL)
, m_bCurrentTargetSalvaged(false)
, m_pHashForScriptFunctions(NULL)
{
assert(pSharedScheduler == NULL);
}
CCScheduler::~CCScheduler(void)
{
unscheduleAllSelectors();
pSharedScheduler = NULL;
}
CCScheduler* CCScheduler::sharedScheduler(void)
{
if (! pSharedScheduler)
{
pSharedScheduler = new CCScheduler();
pSharedScheduler->init();
}
return pSharedScheduler;
}
bool CCScheduler::init(void)
{
m_fTimeScale = 1.0f;
// used to trigger CCTimer#update
// m_pfnUpdateSelector = &CCScheduler::update;
// impMethod = (TICK_IMP) [CCTimer instanceMethodForSelector:updateSelector];
// updates with priority
m_pUpdates0List = NULL;
m_pUpdatesNegList = NULL;
m_pUpdatesPosList = NULL;
m_pHashForUpdates = NULL;
m_pHashForScriptFunctions = NULL;
// selectors with interval
m_pCurrentTarget = NULL;
m_bCurrentTargetSalvaged = false;
m_pHashForSelectors = NULL;
m_bUpdateHashLocked = false;
return true;
}
void CCScheduler::removeHashElement(_hashSelectorEntry *pElement)
{
ccArrayFree(pElement->timers);
pElement->target->selectorProtocolRelease();
pElement->target = NULL;
HASH_DEL(m_pHashForSelectors, pElement);
free(pElement);
}
void CCScheduler::scheduleSelector(SEL_SCHEDULE pfnSelector, SelectorProtocol *pTarget, float fInterval, bool bPaused)
{
assert(pfnSelector);
assert(pTarget);
tHashSelectorEntry *pElement = NULL;
HASH_FIND_INT(m_pHashForSelectors, &pTarget, pElement);
if (! pElement)
{
pElement = (tHashSelectorEntry *)calloc(sizeof(*pElement), 1);
pElement->target = pTarget;
if (pTarget)
{
pTarget->selectorProtocolRetain();
}
HASH_ADD_INT(m_pHashForSelectors, target, pElement);
// Is this the 1st element ? Then set the pause level to all the selectors of this target
pElement->paused = bPaused;
}
else
{
assert(pElement->paused == bPaused);
}
if (pElement->timers == NULL)
{
pElement->timers = ccArrayNew(10);
}
else
{
for (unsigned int i = 0; i < pElement->timers->num; ++i)
{
CCTimer *timer = (CCTimer*)pElement->timers->arr[i];
if (pfnSelector == timer->m_pfnSelector)
{
CCLOG("CCSheduler#scheduleSelector. Selector already scheduled.");
timer->m_fInterval = fInterval;
return;
}
}
ccArrayEnsureExtraCapacity(pElement->timers, 1);
}
CCTimer *pTimer = new CCTimer();
pTimer->initWithTarget(pTarget, pfnSelector, fInterval);
ccArrayAppendObject(pElement->timers, pTimer);
pTimer->release();
}
void CCScheduler::scheduleScriptFunc(const char *pszFuncName, ccTime fInterval, bool bPaused)
{
//assert(pfnSelector);
assert(pszFuncName);
tHashScriptFuncEntry *pElement = NULL;
HASH_FIND_INT(m_pHashForScriptFunctions, &pszFuncName, pElement);
if (! pElement)
{
pElement = (tHashScriptFuncEntry *)calloc(sizeof(*pElement), 1);
pElement->funcName = pszFuncName;
pElement->timer = new CCTimer();
pElement->timer->initWithScriptFuncName(pszFuncName, fInterval);
pElement->paused = bPaused;
HASH_ADD_INT(m_pHashForScriptFunctions, funcName, pElement);
}
else
{
assert(pElement->paused == bPaused);
}
}
void CCScheduler::unscheduleSelector(SEL_SCHEDULE pfnSelector, SelectorProtocol *pTarget)
{
// explicity handle nil arguments when removing an object
if (pTarget == 0 || pfnSelector == 0)
{
return;
}
//assert(pTarget);
//assert(pfnSelector);
tHashSelectorEntry *pElement = NULL;
HASH_FIND_INT(m_pHashForSelectors, &pTarget, pElement);
if (pElement)
{
for (unsigned int i = 0; i < pElement->timers->num; ++i)
{
CCTimer *pTimer = (CCTimer*)(pElement->timers->arr[i]);
if (pfnSelector == pTimer->m_pfnSelector)
{
if (pTimer == pElement->currentTimer && (! pElement->currentTimerSalvaged))
{
pElement->currentTimer->retain();
pElement->currentTimerSalvaged = true;
}
ccArrayRemoveObjectAtIndex(pElement->timers, i );
// update timerIndex in case we are in tick:, looping over the actions
if (pElement->timerIndex >= i)
{
pElement->timerIndex--;
}
if (pElement->timers->num == 0)
{
if (m_pCurrentTarget == pElement)
{
m_bCurrentTargetSalvaged = true;
}
else
{
removeHashElement(pElement);
}
}
return;
}
}
}
}
void CCScheduler::unscheduleScriptFunc(const char *pszFuncName)
{
// explicity handle nil arguments when removing an object
if (pszFuncName == 0)
{
return;
}
tHashScriptFuncEntry *pElement = NULL;
HASH_FIND_INT(m_pHashForScriptFunctions, &pszFuncName, pElement);
if (pElement)
{
pElement->timer->release();
HASH_DEL(m_pHashForScriptFunctions, pElement);
free(pElement);
}
}
void CCScheduler::priorityIn(tListEntry **ppList, SelectorProtocol *pTarget, int nPriority, bool bPaused)
{
tListEntry *pListElement = (tListEntry *)malloc(sizeof(*pListElement));
pListElement->target = pTarget;
pListElement->priority = nPriority;
pListElement->paused = bPaused;
pListElement->next = pListElement->prev = NULL;
pListElement->markedForDeletion = false;
// empey list ?
if (! *ppList)
{
DL_APPEND(*ppList, pListElement);
}
else
{
bool bAdded = false;
for (tListEntry *pElement = *ppList; pElement; pElement = pElement->next)
{
if (nPriority < pElement->priority)
{
if (pElement == *ppList)
{
DL_PREPEND(*ppList, pListElement);
}
else
{
pListElement->next = pElement;
pListElement->prev = pElement->prev;
pElement->prev->next = pListElement;
pElement->prev = pListElement;
}
bAdded = true;
break;
}
}
// Not added? priority has the higher value. Append it.
if (! bAdded)
{
DL_APPEND(*ppList, pListElement);
}
}
// update hash entry for quick access
tHashUpdateEntry *pHashElement = (tHashUpdateEntry *)calloc(sizeof(*pHashElement), 1);
pHashElement->target = pTarget;
pTarget->selectorProtocolRetain();
pHashElement->list = ppList;
pHashElement->entry = pListElement;
HASH_ADD_INT(m_pHashForUpdates, target, pHashElement);
}
void CCScheduler::appendIn(_listEntry **ppList, SelectorProtocol *pTarget, bool bPaused)
{
tListEntry *pListElement = (tListEntry *)malloc(sizeof(*pListElement));
pListElement->target = pTarget;
pListElement->paused = bPaused;
pListElement->markedForDeletion = false;
DL_APPEND(*ppList, pListElement);
// update hash entry for quicker access
tHashUpdateEntry *pHashElement = (tHashUpdateEntry *)calloc(sizeof(*pHashElement), 1);
pHashElement->target = pTarget;
pTarget->selectorProtocolRetain();
pHashElement->list = ppList;
pHashElement->entry = pListElement;
HASH_ADD_INT(m_pHashForUpdates, target, pHashElement);
}
void CCScheduler::scheduleUpdateForTarget(SelectorProtocol *pTarget, int nPriority, bool bPaused)
{
tHashUpdateEntry *pHashElement = NULL;
HASH_FIND_INT(m_pHashForUpdates, &pTarget, pHashElement);
if (pHashElement)
{
#if COCOS2D_DEBUG >= 1
assert(pHashElement->entry->markedForDeletion);
#endif
// TODO: check if priority has changed!
pHashElement->entry->markedForDeletion = false;
return;
}
// most of the updates are going to be 0, that's way there
// is an special list for updates with priority 0
if (nPriority == 0)
{
appendIn(&m_pUpdates0List, pTarget, bPaused);
} else
if (nPriority < 0)
{
priorityIn(&m_pUpdatesNegList, pTarget, nPriority, bPaused);
}
else
{
// priority > 0
priorityIn(&m_pUpdatesPosList, pTarget, nPriority, bPaused);
}
}
void CCScheduler::removeUpdateFromHash(struct _listEntry *entry)
{
tHashUpdateEntry *element = NULL;
HASH_FIND_INT(m_pHashForUpdates, &entry->target, element);
if (element)
{
// list entry
DL_DELETE(*element->list, element->entry);
free(element->entry);
// hash entry
element->target->selectorProtocolRelease();
HASH_DEL(m_pHashForUpdates, element);
free(element);
}
}
void CCScheduler::unscheduleUpdateForTarget(const SelectorProtocol *pTarget)
{
if (pTarget == NULL)
{
return;
}
tHashUpdateEntry *pElement = NULL;
HASH_FIND_INT(m_pHashForUpdates, &pTarget, pElement);
if (pElement)
{
if (m_bUpdateHashLocked)
{
pElement->entry->markedForDeletion = true;
}
else
{
this->removeUpdateFromHash(pElement->entry);
}
}
}
void CCScheduler::unscheduleAllSelectors(void)
{
// Custom Selectors
tHashSelectorEntry *pElement = NULL;
tHashSelectorEntry *pNextElement = NULL;
for (pElement = m_pHashForSelectors; pElement != NULL;)
{
// pElement may be removed in unscheduleAllSelectorsForTarget
pNextElement = (tHashSelectorEntry *)pElement->hh.next;
unscheduleAllSelectorsForTarget(pElement->target);
pElement = pNextElement;
}
// Updates selectors
tListEntry *pEntry, *pTmp;
DL_FOREACH_SAFE(m_pUpdates0List, pEntry, pTmp)
{
unscheduleUpdateForTarget(pEntry->target);
}
DL_FOREACH_SAFE(m_pUpdatesNegList, pEntry, pTmp)
{
unscheduleUpdateForTarget(pEntry->target);
}
DL_FOREACH_SAFE(m_pUpdatesPosList, pEntry, pTmp)
{
unscheduleUpdateForTarget(pEntry->target);
}
}
void CCScheduler::unscheduleAllSelectorsForTarget(SelectorProtocol *pTarget)
{
// explicit NULL handling
if (pTarget == NULL)
{
return;
}
// Custom Selectors
tHashSelectorEntry *pElement = NULL;
HASH_FIND_INT(m_pHashForSelectors, &pTarget, pElement);
if (pElement)
{
if (ccArrayContainsObject(pElement->timers, pElement->currentTimer)
&& (! pElement->currentTimerSalvaged))
{
pElement->currentTimer->retain();
pElement->currentTimerSalvaged = true;
}
ccArrayRemoveAllObjects(pElement->timers);
if (m_pCurrentTarget == pElement)
{
m_bCurrentTargetSalvaged = true;
}
else
{
removeHashElement(pElement);
}
}
// update selector
unscheduleUpdateForTarget(pTarget);
}
void CCScheduler::resumeTarget(SelectorProtocol *pTarget)
{
assert(pTarget != NULL);
// custom selectors
tHashSelectorEntry *pElement = NULL;
HASH_FIND_INT(m_pHashForSelectors, &pTarget, pElement);
if (pElement)
{
pElement->paused = false;
}
// update selector
tHashUpdateEntry *pElementUpdate = NULL;
HASH_FIND_INT(m_pHashForUpdates, &pTarget, pElementUpdate);
if (pElementUpdate)
{
assert(pElementUpdate->entry != NULL);
pElementUpdate->entry->paused = false;
}
}
void CCScheduler::pauseTarget(SelectorProtocol *pTarget)
{
assert(pTarget != NULL);
// custom selectors
tHashSelectorEntry *pElement = NULL;
HASH_FIND_INT(m_pHashForSelectors, &pTarget, pElement);
if (pElement)
{
pElement->paused = true;
}
// update selector
tHashUpdateEntry *pElementUpdate = NULL;
HASH_FIND_INT(m_pHashForUpdates, &pTarget, pElementUpdate);
if (pElementUpdate)
{
assert(pElementUpdate->entry != NULL);
pElementUpdate->entry->paused = true;
}
}
bool CCScheduler::isTargetPaused(SelectorProtocol *pTarget)
{
CCAssert( pTarget != NULL, "target must be non nil" );
// Custom selectors
tHashSelectorEntry *pElement = NULL;
HASH_FIND_INT(m_pHashForSelectors, &pTarget, pElement);
if( pElement )
{
return pElement->paused;
}
return false; // should never get here
}
// main loop
void CCScheduler::tick(ccTime dt)
{
m_bUpdateHashLocked = true;
if (m_fTimeScale != 1.0f)
{
dt *= m_fTimeScale;
}
// Iterate all over the Updates selectors
tListEntry *pEntry, *pTmp;
// updates with priority < 0
DL_FOREACH_SAFE(m_pUpdatesNegList, pEntry, pTmp)
{
if ((! pEntry->paused) && (! pEntry->markedForDeletion))
{
pEntry->target->update(dt);
}
}
// updates with priority == 0
DL_FOREACH_SAFE(m_pUpdates0List, pEntry, pTmp)
{
if ((! pEntry->paused) && (! pEntry->markedForDeletion))
{
pEntry->target->update(dt);
}
}
// updates with priority > 0
DL_FOREACH_SAFE(m_pUpdatesPosList, pEntry, pTmp)
{
if ((! pEntry->paused) && (! pEntry->markedForDeletion))
{
pEntry->target->update(dt);
}
}
// Interate all over the custom selectors
for (tHashSelectorEntry *elt = m_pHashForSelectors; elt != NULL; )
{
m_pCurrentTarget = elt;
m_bCurrentTargetSalvaged = false;
if (! m_pCurrentTarget->paused)
{
// The 'timers' array may change while inside this loop
for (elt->timerIndex = 0; elt->timerIndex < elt->timers->num; ++(elt->timerIndex))
{
elt->currentTimer = (CCTimer*)(elt->timers->arr[elt->timerIndex]);
elt->currentTimerSalvaged = false;
elt->currentTimer->update(dt);
if (elt->currentTimerSalvaged)
{
// The currentTimer told the remove itself. To prevent the timer from
// accidentally deallocating itself before finishing its step, we retained
// it. Now that step is done, it's safe to release it.
elt->currentTimer->release();
}
elt->currentTimer = NULL;
}
}
// elt, at this moment, is still valid
// so it is safe to ask this here (issue #490)
elt = (tHashSelectorEntry *)elt->hh.next;
// only delete currentTarget if no actions were scheduled during the cycle (issue #481)
if (m_bCurrentTargetSalvaged && m_pCurrentTarget->timers->num == 0)
{
removeHashElement(m_pCurrentTarget);
}
}
// delete all updates that are morked for deletion
// updates with priority < 0
DL_FOREACH_SAFE(m_pUpdatesNegList, pEntry, pTmp)
{
if (pEntry->markedForDeletion)
{
this->removeUpdateFromHash(pEntry);
}
}
// updates with priority == 0
DL_FOREACH_SAFE(m_pUpdates0List, pEntry, pTmp)
{
if (pEntry->markedForDeletion)
{
this->removeUpdateFromHash(pEntry);
}
}
// updates with priority > 0
DL_FOREACH_SAFE(m_pUpdatesPosList, pEntry, pTmp)
{
if (pEntry->markedForDeletion)
{
this->removeUpdateFromHash(pEntry);
}
}
m_bUpdateHashLocked = false;
m_pCurrentTarget = NULL;
// Interate all script functions
for (tHashScriptFuncEntry *elt = m_pHashForScriptFunctions; elt != NULL; )
{
if (! elt->paused)
{
elt->timer->update(dt);
}
elt = (tHashScriptFuncEntry *)elt->hh.next;
}
}
void CCScheduler::purgeSharedScheduler(void)
{
pSharedScheduler->release();
pSharedScheduler = NULL;
}
}//namespace cocos2d
| [
"[email protected]"
]
| [
[
[
1,
798
]
]
]
|
9adc5f707e3a0ef31195d6f9d86053a37c27dade | e6a648a68391135788fceda1d1218eb8c699f53d | /desktop.cpp | 3b65841144a6c321ecc677a02cbe64f414e11439 | []
| no_license | fei1700/apptest | 84a95bc9d35d8340b86278592ec63f0e924953eb | 83c297d24e6e9c361eaaf0fcea785040effdb34b | refs/heads/master | 2021-01-01T16:00:22.615179 | 2009-03-20T03:40:39 | 2009-03-20T03:40:39 | 154,770 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,377 | cpp | /*desktop.cpp*/
#include <QtGui>
#include "desktop.h"
#include "musicplayer.h"
#include "videoplayer.h"
#include "setting.h"
#include "photoviewer.h"
PhotoViewer *g_photoview;
ImageWidget *g_fullimage;
MusicPlayer *g_musicplay;
VideoPlayer *g_videoplay;
Setting *g_setting;
QVBoxLayout * g_mainlayout;
Desktop::Desktop()
{
this->setObjectName("desktop");
createAction();
createItem();
createLayout();
}
void Desktop::createAction()
{
char *desktop_style;
if( (desktop_style = getenv("DESKTOP_STYLE")) == NULL) {
printf("desktop style = NULL\n");
}
QFile file(desktop_style);
file.open(QFile::ReadOnly);
QString stylesheet = QLatin1String(file.readAll());
m_photoAction=new QToolButton;
m_photoAction->setObjectName("photoAction");
connect(m_photoAction, SIGNAL(clicked()), this, SLOT(gotoPhoto()));
m_musicAction=new QToolButton;
m_musicAction->setObjectName("musicAction");
connect(m_musicAction, SIGNAL(clicked()), this, SLOT(gotoMusic()));
m_videoAction=new QToolButton;
m_videoAction->setObjectName("videoAction");
connect(m_videoAction, SIGNAL(clicked()), this, SLOT(gotoVideo()));
m_settingAction=new QToolButton;
m_settingAction->setObjectName("settingAction");
connect(m_settingAction, SIGNAL(clicked()), this, SLOT(gotoSetting()));
//m_settingAction->setStyleSheet();
qApp->setStyleSheet(stylesheet);
}
void Desktop::createItem()
{
//g_musicplay=new MusicPlayer;
g_videoplay=new VideoPlayer;
g_setting=new Setting;
g_photoview=new PhotoViewer;
g_fullimage=new ImageWidget;
m_launchitemtimer=new QTimer;
connect(m_launchitemtimer,SIGNAL(timeout()), this, SLOT(createMusic()));
m_launchitemtimer->start(1000);
}
void Desktop::createMusic()
{
m_launchitemtimer->stop();
g_musicplay=new MusicPlayer;
}
void Desktop::createLayout()
{
m_topLayout = new QHBoxLayout;
m_topLayout->addWidget(m_photoAction);
m_topLayout->addWidget(m_musicAction);
m_topLayout->addWidget(m_videoAction);
m_topLayout->addWidget(m_settingAction);
m_mainLayout = new QVBoxLayout;
m_mainLayout->addLayout(m_topLayout);
QWidget* dummy =new QWidget;
m_mainLayout->addWidget(dummy);
//m_mainLayout->addWidget(g_musicplay);
m_lastWidget=dummy;
g_mainlayout=m_mainLayout;
setLayout(m_mainLayout);
//setCentralWidget(g_photoview);
}
void Desktop::gotoPhoto()
{
m_mainLayout->removeWidget(m_lastWidget);
m_mainLayout->addWidget(g_photoview);
m_lastWidget->hide();
m_lastWidget=g_photoview;
g_photoview->show();
qDebug()<<"goto photo\n";
}
void Desktop::gotoMusic()
{
m_mainLayout->removeWidget(m_lastWidget);
m_mainLayout->addWidget(g_musicplay);
m_lastWidget->hide();
m_lastWidget=g_musicplay;
g_musicplay->show();
qDebug()<<"goto music\n";
}
void Desktop::gotoVideo()
{
m_mainLayout->removeWidget(m_lastWidget);
m_mainLayout->addWidget(g_videoplay);
m_lastWidget->hide();
m_lastWidget=g_videoplay;
g_videoplay->show();
qDebug()<<"goto video\n";
}
void Desktop::gotoSetting()
{
m_mainLayout->removeWidget(m_lastWidget);
m_mainLayout->addWidget(g_setting);
m_lastWidget->hide();
m_lastWidget=g_setting;
g_setting->show();
qDebug()<<"goto setting\n";
}
/*end of desktop.cpp*/
| [
"[email protected]"
]
| [
[
[
1,
138
]
]
]
|
714e4fccf98c62e0948d48b92d391c1d1de0327c | e08de6b78df1f328ff5297de2c7cb0bb3dab7e39 | /9 - Курсовой проект/users/Rezvyakov/src/Manager.h | 0c3ac590506673462decab6d7f5013e187b04952 | []
| no_license | kereokerekeke/mai-13-x01 | 265aede9d81de8ac1869457581872e7fec5f6285 | a6a34b032dd4686603ae7193792195fb5cecad06 | refs/heads/master | 2021-01-10T08:20:17.027622 | 2011-11-14T19:31:49 | 2011-11-14T19:31:49 | 45,355,227 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 1,493 | h | #pragma once
// Класс эмулирует менеджер управления процессами
class Manager {
private:
int m_Step; // Номер шага обработки всех процессов
int m_TotalTick; // Текущее виртуальное время эмулятора
int m_Idle; // Время простоя эмулируемого процессора
int m_StepTicks; // Время работы на текущем шаге
int m_StepIdle; // Время простоя на текущем шаге
int m_ProcessCount; // Кол-во эмулируемых процессов
Process** m_Processes; // Ссылка на массив эмулируемых процессов
// Форматирует текст о времени работы по числовым значениям
void FormatTicks(char* Buffer, int Ticks, int Idle);
// Выводит текст в центре области указанной длины
void PrintIntAtCenter(int Value, int Length);
public:
Manager(Process** Processes, int Count); // Конструктор класса
bool RunStep(); // Запустить обработку очередного шага
void PrintHeader(); // Вывод заголовка статистики
void PrintStep(); // Вывод статистики по текущему шагу
void PrintFooter(); // Вывод итогов статистики
}; | [
"ncdinya@c9ba52fc-c71b-11de-8672-e51b9359e43c"
]
| [
[
[
1,
25
]
]
]
|
e632f9d70a34a44d56bf8360cf5fe9f3238c0d5b | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/nebula2/src/particle/nparticle_main.cc | c87db82da21622f32f18a1206677bf332c55ce89 | []
| no_license | ugozapad/TheZombieEngine | 832492930df28c28cd349673f79f3609b1fe7190 | 8e8c3e6225c2ed93e07287356def9fbdeacf3d6a | refs/heads/master | 2020-04-30T11:35:36.258363 | 2011-02-24T14:18:43 | 2011-02-24T14:18:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,706 | cc | //------------------------------------------------------------------------------
// nparticle_main.cc
// (C) 2003 RadonLabs GmbH
//------------------------------------------------------------------------------
#include "precompiled/pchnnebula.h"
#include "particle/nparticle.h"
#include "particle/nparticleemitter.h"
//------------------------------------------------------------------------------
/**
*/
nParticle::nParticle() :
state(Unborn),
birthTime(0.0),
lifeTime(0.0),
rotation(0.0f)
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
nParticle::~nParticle()
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
void nParticle::Initialize(const vector3& position, const vector3& velocity, float birthTime, float lifeTime, float rotation)
{
this->position = position;
this->velocity = velocity;
this->rotation = rotation;
this->birthTime = birthTime;
this->lifeTime = lifeTime;
this->state = Unborn;
}
//------------------------------------------------------------------------------
/**
*/
void
nParticle::Trigger(nParticleEmitter* emitter, float curTime, float frameTime, const vector3& absAccel)
{
static vector3 windVelocity;
static vector3 finalVelocity;
static const vector3 zVector(0.0, 0.0, 1.0);
nTime curAge = curTime - this->birthTime;
float relAge = (float) (curAge / lifeTime);
switch (this->state)
{
case Unborn:
if (curAge >= 0.0)
{
this->state = Living;
}
break;
case Living:
if (relAge >= 1.0)
{
this->state = Dead;
}
else
{
this->rotation += emitter->GetParticleRotationVelocity(relAge) * frameTime;
// update velocity
this->velocity += absAccel * emitter->GetParticleWeight(relAge) * frameTime;
// absolute acceleration
float airResistance = emitter->GetParticleAirResistance(relAge);
const nFloat4& wind = emitter->GetWind();
float windFactor = airResistance * wind.w;
windVelocity.set(wind.x * windFactor, wind.y * windFactor, wind.z * windFactor);
finalVelocity = (this->velocity * emitter->GetParticleVelocityFactor(relAge)) + windVelocity;
this->position += finalVelocity * (float) frameTime;
}
break;
default:
break;
}
}
| [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
]
| [
[
[
1,
88
]
]
]
|
4a2a2f742bc72ba7a4e21d00df90586f5eb21562 | 2c3cf8b4143b823fa25e3f0a8c26e42255cb890c | /MotorController.h | c38870995b15397c29c94f0d30124e69f047dc27 | []
| no_license | MankowitzProjects/Partula | ce069452b2bed7b6266cd7c441da7000fc18da06 | 4936d18d3699dede61e384e593e1a16e218cf0c6 | refs/heads/master | 2021-01-10T20:16:31.200846 | 2011-12-16T00:41:17 | 2011-12-16T00:41:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,847 | h | #ifndef MOTORCONTROLLER_H_INCLUDED
#define MOTORCONTROLLER_H_INCLUDED
#include "conf.h"
#include "Motor.h"
using namespace std;
class MotorController
{
public:
MotorController(void);
void init(void);
void fin(void);
inline void setVelLeft(float velLeft);
inline void setAccLeft(float accLeft);
inline void setVelRight(float velRight);
inline void setAccRight(float accRight);
inline void setAcc(float acc);
inline void setVel(float vel);
inline void setAcc(float accLeft, float accRight);
inline void setVel(float velLeft, float velRight);
inline void stop(void);
Motor motorLeft; /**< The left side motor */
Motor motorRight; /**< The right side motor */
private:
CPhidgetMotorControlHandle motorCtrlHandle; /**< Motor control handle */
int regHanlders(void);
void clrHandlers(void);
};
inline void MotorController::setVelLeft(float velLeft)
{
motorLeft.setVel(velLeft);
}
inline void MotorController::setAccLeft(float accLeft)
{
motorLeft.setAcc(accLeft);
}
inline void MotorController::setVelRight(float velRight)
{
motorRight.setVel(velRight);
}
inline void MotorController::setAccRight(float accRight)
{
motorRight.setAcc(accRight);
}
inline void MotorController::setAcc(float accLeft, float accRight)
{
setAccLeft(accLeft);
setAccRight(accRight);
}
inline void MotorController::setVel(float velLeft, float velRight)
{
setVelLeft(velLeft);
setVelRight(velRight);
}
inline void MotorController::setAcc(float acc)
{
setAcc(acc, acc);
}
inline void MotorController::setVel(float vel)
{
setVel(vel, vel);
}
inline void MotorController::stop(void)
{
setAcc(0.0);
setVel(0.0);
}
#endif // MOTORCONTROLLER_H_INCLUDED
| [
"daniel.mankowitz@gmail",
"Daniel@DanielLaptop.(none)",
"Madwyn@.(none)"
]
| [
[
[
1,
6
],
[
9,
11
],
[
13,
16
],
[
21,
21
],
[
24,
24
],
[
27,
27
],
[
29,
29
],
[
31,
31
],
[
33,
34
],
[
36,
40
],
[
42,
42
],
[
44,
45
],
[
47,
47
],
[
49,
50
],
[
52,
52
],
[
54,
55
],
[
57,
57
],
[
59,
60
],
[
62,
62
],
[
65,
65
],
[
67,
67
],
[
70,
71
],
[
73,
73
],
[
75,
76
],
[
78,
78
],
[
80,
81
],
[
83,
83
],
[
86,
88
]
],
[
[
7,
8
],
[
12,
12
],
[
17,
20
],
[
22,
23
],
[
25,
26
],
[
28,
28
],
[
30,
30
],
[
35,
35
],
[
41,
41
],
[
43,
43
],
[
46,
46
],
[
48,
48
],
[
51,
51
],
[
53,
53
],
[
56,
56
],
[
58,
58
],
[
61,
61
],
[
63,
64
],
[
66,
66
],
[
68,
69
],
[
72,
72
],
[
74,
74
],
[
77,
77
],
[
79,
79
],
[
82,
82
],
[
84,
85
]
],
[
[
32,
32
]
]
]
|
49117a59be38fde089b268ffb53c30311d0ea2dc | fac8de123987842827a68da1b580f1361926ab67 | /inc/physics/Common/Compat/hkHavokAllClassUpdates.h | 7c21ebfdca1acd4a944c25241146777680a5240b | []
| 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 | 1,617 | 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_COMPAT_HAVOK_ALL_CLASS_UPDATES_H
#define HK_COMPAT_HAVOK_ALL_CLASS_UPDATES_H
#include <Common/Serialize/Version/hkVersionRegistry.h>
#define HK_CLASS_UPDATE_INFO(FROM,TO) \
namespace hkCompat_hk##FROM##_hk##TO \
{ \
extern hkVersionRegistry::UpdateDescription hkVersionUpdateDescription; \
}
#include <Common/Compat/hkCompatVersions.h>
#undef HK_CLASS_UPDATE_INFO
#endif // HK_COMPAT_HAVOK_ALL_CLASS_UPDATES_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,
39
]
]
]
|
e8d7e61aa1f8b62912a4bc2f3fcdadbee22227af | 4de296187bc58b0a7c99deb66095884719245ec3 | /src/OpenCVDotNet/CVCapture.h | 0ca51f6412d492c4fb51ec976bd196f69ea8dca6 | []
| no_license | ashersyed/opencvdotnet | 8251e2dc22a0742cc3297c3de2380804dcd6e78f | 1afec3aeb9bd4b5a2f917892dc162146df6f09ab | refs/heads/master | 2020-06-05T19:41:20.494695 | 2008-02-10T12:43:26 | 2008-02-10T12:43:26 | 38,257,364 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,571 | h | /**
* (C) 2007 Elad Ben-Israel
* This code is licenced under the GPL.
*/
#pragma once
namespace OpenCVDotNet
{
public ref class CVCapture
{
private:
CvCapture* capture;
String^ filename;
CVImage^ asImage;
public:
CVCapture(String^ filename)
{
capture = NULL;
asImage = nullptr;
Open(filename);
}
CVCapture()
{
asImage = nullptr;
capture = cvCreateCameraCapture(CV_CAP_ANY);
}
CVCapture(int cameraId)
{
asImage = nullptr;
capture = cvCreateCameraCapture(cameraId);
}
~CVCapture()
{
Release();
}
void Release()
{
if (asImage != nullptr)
{
asImage->Release();
asImage = nullptr;
}
if (capture != NULL)
{
pin_ptr<CvCapture*> cap = &capture;
cvReleaseCapture(cap);
}
}
property int Width
{
int get()
{
if (asImage != nullptr) return asImage->Width;
return (int) cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
}
}
property int Height
{
int get()
{
if (asImage != nullptr) return asImage->Height;
return (int) cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);
}
}
CVImage^ QueryFrame()
{
if (asImage != nullptr) return asImage->Clone();
IplImage* frame = cvQueryFrame(capture);
if (frame == NULL) return nullptr;
CVImage^ newImage = gcnew CVImage(gcnew CVImage(frame));
return newImage;
}
void Open(String^ filename)
{
Release();
capture = NULL;
asImage = nullptr;
String^ ext = System::IO::Path::GetExtension(filename);
// if the extension of the filename is not AVI, try opening as an image.
if (ext->ToUpper()->CompareTo(".AVI") != 0)
{
asImage = gcnew CVImage(filename);
}
else
{
char fn[1024 + 1];
CVUtils::StringToCharPointer(filename, fn, 1024);
capture = cvCreateFileCapture(fn);
if (capture == NULL)
{
throw gcnew CVException(
String::Format("Unable to open file '{0}' for capture", filename));
}
}
this->filename = filename;
}
property int FramesPerSecond
{
int get()
{
// if this is an image, return 30 as default FPS.
if (asImage != nullptr) return 30;
return (int) cvGetCaptureProperty(capture, CV_CAP_PROP_FPS);
}
}
void Restart()
{
Open(filename);
}
CVImage^ CreateCompatibleImage()
{
CVImage^ img = gcnew CVImage(this->Width, this->Height, CVDepth::Depth8U, 3);
return img;
}
};
}; | [
"elad.benisrael@05b48626-c427-0410-92d5-518f3ac39d56"
]
| [
[
[
1,
138
]
]
]
|
a471457c8118f2dd6e6a6e5b465e3f7df0cc0b44 | cb87858032792e50607a06dceb10196d6a5de2fa | /FileGDB_DotNet/FileGDB_API_VS2008_1_0Final/include/GeodatabaseManagement.h | a5198b1601e2db1dfb1278acc04c8494ee384ed4 | []
| no_license | nakijun/filegdb-dotnet-wrapper | 16722077839b77b4940106dc5ac293325776c792 | 92f156a57527d802a6ace734f842528b359b11b4 | refs/heads/master | 2021-01-10T06:56:04.987321 | 2011-06-07T13:54:45 | 2011-06-07T13:54:45 | 51,569,516 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 3,084 | h | //
// GeodatabaseManagement.h
//
/*
COPYRIGHT © 2011 ESRI
TRADE SECRETS: ESRI PROPRIETARY AND CONFIDENTIAL
Unpublished material - all rights reserved under the
Copyright Laws of the United States and applicable international
laws, treaties, and conventions.
For additional information, contact:
Environmental Systems Research Institute, Inc.
Attn: Contracts and Legal Services Department
380 New York Street
Redlands, California, 92373
USA
email: [email protected]
*/
/// A set of functions for accessing, creating and deleting file geodatabases.
/// @file GeodatabaseManagement.h
#pragma once
#include <string>
#ifndef EXPORT_FILEGDB_API
# ifdef linux
# define EXT_FILEGDB_API
# else
# define EXT_FILEGDB_API _declspec(dllimport)
# endif
#else
# ifdef linux
# define EXT_FILEGDB_API __attribute__((visibility("default")))
# else
# define EXT_FILEGDB_API _declspec(dllexport)
# endif
#endif
#include "FileGDBCore.h"
namespace FileGDBAPI
{
class Geodatabase;
/// Creates a new 10.x file geodatabase in the specified location.
/// If the file geodatabase already exists a -2147220653 (The table already exists) error will be returned.
/// If the path is seriously in error, say pointing to the wrong drive, a -2147467259 (E_FAIL) error is returned.
/// @param[in] path The location where the geodatabase should be created.
/// @param[out] geodatabase A reference to the newly-created geodatabase.
/// @return Error code indicating whether the method finished successfully.
EXT_FILEGDB_API fgdbError CreateGeodatabase(const std::wstring& path, Geodatabase& geodatabase);
/// Opens an existing 10.x file geodatabase.
/// If the path is incorrect a -2147024894 (The system cannot find the file specified) error will be returned. If the
/// release is pre-10.x a -2147220965 (This release of the GeoDatabase is either invalid or out of date) error will be returned.
/// @param[in] path The path of the geodatabase.
/// @param[out] geodatabase A reference to the opened geodatabase.
/// @return Error code indicating whether the method finished successfully.
EXT_FILEGDB_API fgdbError OpenGeodatabase(const std::wstring& path, Geodatabase& geodatabase);
/// Closes an open file geodatabase.
/// @param[in] geodatabase A reference to the geodatabase.
/// @return Error code indicating whether the method finished successfully.
EXT_FILEGDB_API fgdbError CloseGeodatabase(Geodatabase& geodatabase);
/// Deletes a file geodatabase.
/// If the path is incorrect a -2147024894 (The system cannot find the file specified) error will be returned.
/// If another process has a lock on the geodatabase, a -2147220947 (Cannot acquire a lock) error will be returned.
/// If access is denied an E_FAIL is returned.
/// @param[in] path The path of the geodatabase.
/// @return Error code indicating whether the method finished successfully.
EXT_FILEGDB_API fgdbError DeleteGeodatabase(const std::wstring& path);
}; // namespace FileGDBAPI
| [
"sivetic@595f332e-62bf-ab4c-4ca1-b707e713c6df"
]
| [
[
[
1,
79
]
]
]
|
374cb91e300307defa27b3571d92a742a013f7d2 | 84f06293f8d797a6be92a5cbdf81e6992717cc9d | /touch_tracker/tbeta/app/nuigroup/OSC/src/Communication/TUIOOSC.cpp | 95b7e4ad0e4318e56138b2e6e4ced5db92ce66b8 | []
| no_license | emailtoan/touchapi | bd7b8fa140741051670137d1b93cae61e1c7234a | 54e41d3f1a05593e943129ef5b2c63968ff448b9 | refs/heads/master | 2016-09-07T18:43:51.754299 | 2008-10-17T06:18:43 | 2008-10-17T06:18:43 | 40,374,104 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,365 | cpp | #include "TUIOOSC.h"
TUIOOSC::TUIOOSC() {
printf("TUIO created: \n");
}
TUIOOSC::~TUIOOSC() {
// this could be useful for whenever we get rid of an object
printf("tuio killed: \n");
}
void TUIOOSC::setup(const char* host, int port) {
printf("TUIO setup: \n");
localHost = host;
TUIOPort = port;
TUIOSocket.setup(localHost, TUIOPort);
frameseq = 0;
}
void TUIOOSC::update() {
frameseq += 1;
}
void TUIOOSC::sendOSC()
{
ofxOscBundle b;
if(blobs.size() == 0)
{
//Sends alive message - saying 'Hey, there's no alive blobs'
ofxOscMessage m;
m.setAddress("/tuio/2Dcur");
m.addStringArg("alive");
b.addMessage( m ); //add message to bundle
//Send fseq message
//Commented out Since We're not using fseq right now
m.clear();
m.setAddress( "/tuio/2Dcur" );
m.addStringArg( "fseq" );
m.addIntArg(frameseq);
b.addMessage( m ); //add message to bundle
TUIOSocket.sendBundle( b ); //send bundle
}
else //actually send the blobs
{
map<int, ofxCvBlob>::iterator this_blob;
for(this_blob = blobs.begin(); this_blob != blobs.end(); this_blob++)
{
//Set Message
ofxOscMessage m;
m.setAddress("/tuio/2Dcur");
m.addStringArg("set");
m.addIntArg(this_blob->second.id); //id
m.addFloatArg(this_blob->second.centroid.x); // x
m.addFloatArg(this_blob->second.centroid.y); // y
m.addFloatArg(0); //X
m.addFloatArg(0); //Y
m.addFloatArg(this_blob->second.area); //m
m.addFloatArg(this_blob->second.boundingRect.width); // wd
m.addFloatArg(this_blob->second.boundingRect.height);// ht
b.addMessage( m ); //add message to bundle
//Send alive message of all alive IDs
m.clear();
m.setAddress("/tuio/2Dcur");
m.addStringArg("alive");
std::map<int, ofxCvBlob>::iterator this_blobID;
for(this_blobID = blobs.begin(); this_blobID != blobs.end(); this_blobID++)
{
m.addIntArg(this_blobID->second.id); //Get list of ALL active IDs
}
b.addMessage( m ); //add message to bundle
//Send fseq message
//Commented out Since We're not using fseq right now
m.clear();
m.setAddress( "/tuio/2Dcur" );
m.addStringArg( "fseq" );
m.addIntArg(frameseq);
b.addMessage( m ); //add message to bundle
TUIOSocket.sendBundle( b ); //send bundle
}
}
} | [
"cerupcat@5e10ba55-a837-0410-a92f-dfacd3436b42"
]
| [
[
[
1,
91
]
]
]
|
067e80f90b9c91e15d2e6409c5c2fe155c28f502 | 5927f0908f05d3f58fe0adf4d5d20c27a4756fbe | /examples/chrome/tab_controller.h | a368b7459997bedb6068b568ff09e2c30306b687 | []
| no_license | seasky013/x-framework | b5585505a184a7d00d229da8ab0f556ca0b4b883 | 575e29de5840ede157e0348987fa188b7205f54d | refs/heads/master | 2016-09-16T09:41:26.994686 | 2011-09-16T06:16:22 | 2011-09-16T06:16:22 | 41,719,436 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,306 | h |
#ifndef __tab_controller_h__
#define __tab_controller_h__
#pragma once
class BaseTab;
namespace gfx
{
class Point;
}
namespace view
{
class MouseEvent;
}
// Controller for tabs.
class TabController
{
public:
// Selects the tab.
virtual void SelectTab(BaseTab* tab) = 0;
// Extends the selection from the anchor to |tab|.
virtual void ExtendSelectionTo(BaseTab* tab) = 0;
// Toggles whether |tab| is selected.
virtual void ToggleSelected(BaseTab* tab) = 0;
// Adds the selection from the anchor to |tab|.
virtual void AddSelectionFromAnchorTo(BaseTab* tab) = 0;
// Closes the tab.
virtual void CloseTab(BaseTab* tab) = 0;
// Shows a context menu for the tab at the specified point in screen coords.
virtual void ShowContextMenuForTab(BaseTab* tab, const gfx::Point& p) = 0;
// Returns true if |tab| is the active tab. The active tab is the one whose
// content is shown in the browser.
virtual bool IsActiveTab(const BaseTab* tab) const = 0;
// Returns true if the specified Tab is selected.
virtual bool IsTabSelected(const BaseTab* tab) const = 0;
// Returns true if the specified Tab is closeable.
virtual bool IsTabCloseable(const BaseTab* tab) const = 0;
// Potentially starts a drag for the specified Tab.
virtual void MaybeStartDrag(BaseTab* tab, const view::MouseEvent& event) = 0;
// Continues dragging a Tab.
virtual void ContinueDrag(const view::MouseEvent& event) = 0;
// Ends dragging a Tab. |canceled| is true if the drag was aborted in a way
// other than the user releasing the mouse. Returns whether the tab has been
// destroyed.
virtual bool EndDrag(bool canceled) = 0;
// Returns the tab that contains the specified coordinates, in terms of |tab|,
// or NULL if there is no tab that contains the specified point.
virtual BaseTab* GetTabAt(BaseTab* tab,
const gfx::Point& tab_in_tab_coordinates) = 0;
// Informs that an active tab is selected when already active (ie - clicked
// when already active/foreground).
virtual void ClickActiveTab(const BaseTab* tab) const = 0;
protected:
virtual ~TabController() {}
};
#endif //__tab_controller_h__ | [
"[email protected]"
]
| [
[
[
1,
74
]
]
]
|
ac9d39396c411920d8aa2761d3243701f0a57212 | c85fd542bd7c23aed09e044b947c4a8e6074bc25 | /src/core/risse/src/risseBuiltinPackages.inc | 7391452247ec28de6f7dbca4d2876a485d89bba5 | []
| no_license | w-dee/kirikiri3-legacy | 35742a56cb1e5b5f0252a48c41d1c594ee3a79a6 | 9a918425c41fc3f64468ded61cdce6c464d2247a | refs/heads/master | 2020-06-23T22:18:34.794911 | 2010-01-04T06:33:50 | 2010-01-04T06:33:50 | 198,763,501 | 19 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,185 | inc | // このファイルは risseScriptEngine.h / risseScriptEngine.cpp
// から複数回呼ばれる。
// どのようにしてこのファイルが呼ばれているかは 上記ファイルを
// 参照のこと。
#ifdef RISSE_BUILTINPACKAGES_INCLUDE
// ここの部分は risseScriptEngine.cpp から呼ばれ、各パッケージイニシャライザを
// new するのに必要なインクルードファイルをインクルードするために使われる。
#include "builtin/date/risseDateClass.h"
#include "builtin/thread/risseThreadClass.h"
#include "builtin/coroutine/risseCoroutineClass.h"
#include "builtin/stream/risseStreamClass.h"
#else
// ここの部分は RISSE_BUILTINPACKAGES_PACKAGE( ) 内にクラス名を
// 列挙する方法で、組み込みクラスを定義する。
// ここに書いた順番でクラスの初期化が行われることに注意。
RISSE_BUILTINPACKAGES_PACKAGE(Date )
RISSE_BUILTINPACKAGES_PACKAGE(Thread )
RISSE_BUILTINPACKAGES_PACKAGE(Coroutine )
RISSE_BUILTINPACKAGES_PACKAGE(Stream )
#endif
| [
"w.dee@9e463c26-7fdd-0310-8662-bb9cb7c2284e"
]
| [
[
[
1,
28
]
]
]
|
8305fd990bfa57c871dd5c614387704d1860b18d | e4bad8b090b8f2fd1ea44b681e3ac41981f50220 | /trunk/Abeetles/Abeetles/Beetle.cpp | b9d61e3727af3d60e248038453614a01b9ed91c4 | []
| no_license | BackupTheBerlios/abeetles-svn | 92d1ce228b8627116ae3104b4698fc5873466aff | 803f916bab7148290f55542c20af29367ef2d125 | refs/heads/master | 2021-01-22T12:02:24.457339 | 2007-08-15T11:18:14 | 2007-08-15T11:18:14 | 40,670,857 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,212 | cpp | #include "StdAfx.h"
#include "Beetle.h"
#include "defines.h"
#include <assert.h>
int CBeetle::EnergyMax_C = MAX_ENERGY; //static variable must be inicialized like this out of the class!
int CBeetle::LastId=0;
int CBeetle::EFF_Age [EFF_BMP_X]={10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10};
extern int RandInBound(int);
CBeetle::CBeetle(void)
{
}
CBeetle::CBeetle(int id, int age,char brain[BRAIN_D1][BRAIN_D2][BRAIN_D3][BRAIN_D4],int direction,int energy,int expectOnPartner[EXPECT_ON_PARTNER_D], int hungryThreshold, int invInChild, int learnAbility, int numChildren=0)
{
int I,J,K,L;
Age=age;
for (I=0;I<2;I++)for (J=0;J<4;J++)for (K=0;K<4;K++)for (L=0;L<4;L++)
Brain[I][J][K][L]=brain[I][J][K][L];
if ((direction>=0) &&(direction<=3))Direction=direction;
else Direction=0;
if ((energy>0)&&(energy<=MAX_ENERGY)) Energy=energy;
else Energy=MAX_ENERGY;
for (I=0;I<EXPECT_ON_PARTNER_D;I++)
ExpectOnPartner[I]=expectOnPartner[I];
if ((hungryThreshold>0)&&(hungryThreshold<=EnergyMax_C))HungryThreshold = hungryThreshold;
else HungryThreshold=EnergyMax_C;
InvInChild=invInChild;
LearnAbility = learnAbility;
NumChildren=numChildren;
Id=id;
assert(Energy>0);
}
CBeetle::~CBeetle(void)
{
}
//returns amount really added to the beetle
int CBeetle::AddEnergy(int HowMuch)
{
if (Energy+HowMuch<=EnergyMax_C)
{
Energy+=HowMuch;
return HowMuch;
}
else
{
Energy=EnergyMax_C;
return EnergyMax_C-Energy;
}
}
//Left,Right, Front: 0-nic, 1-stena, 2-kytka, 3-brouk
int CBeetle::GetAction(bool bHunger, char Left, char Front, char Right)
{
return Brain[bHunger][Left][Front][Right];
}
bool CBeetle::IsHungry(void)
{
if (Energy>=HungryThreshold)return false;
else return true;
}
int CBeetle::GetEnergy(void)
{
return Energy;
}
char CBeetle::GetDirection(void)
{
return Direction;
}
int CBeetle::Decide(int Left, int Front, int Right)
{
//Left, Front, Right: NOTHING=1/WALL/FLOWER/BEETLE=4
if (Front==WALL) return A_ROTATERIGHT;
return Brain [IsHungry()][Left-1][Front-1][Right-1];
}
int CBeetle::EnergyFromFlower(void)
{
if (Age<EFF_BMP_X) return EFF_Age[Age];
else return EFF_Age[EFF_BMP_X-1];
//(int)((((double)1/(Age+1)) * 10)+1);
}
int CBeetle::ConsumeEnergy(int HowMuch)
{
Energy-=HowMuch;
if (IsDead())return DEAD;
else if (IsHungry()) return HUNGRY;
else return NOT_HUNGRY;
}
bool CBeetle::IsDead(void)
{
if (Energy<=0) return true;
else return false;
}
void CBeetle::Die(void)
{
//actions connected with beetles death.
}
void CBeetle::SetBrain(int Num, int Value)
{
int I1=0,I2=0,I3=0,I4=0;
I4=Num%4;Num=Num/4;
I3=Num%4;Num=Num/4;
I2=Num%4;Num=Num/4;
I1=Num%2;
Brain[I1][I2][I3][I4]=Value;
}
int CBeetle::GetExpectOnPartnerMax(int which)
{
// ExpectOnPartner - Age [2] = 2B how much older / younger can be the partner
// ExpectOnPartner - Energy = 1B how much more must at least have than ExpectOnPartner - InvInChild
// ExpectOnPartner - InvInChild = 1B how much more than InvInChild
// ExpectOnPartner - LearningAbility [2]= how much less/more can have the parter
switch (which)
{
case 0: return 100;
case 1: return 100;
case 2: return MAX_ENERGY - MAX_INV_IN_CHILD;
case 3: return MAX_INV_IN_CHILD;
case 4: return 100;
case 5: return 100;
default:
printf ("Wrong input for CBeetle::GetExpectOnPartnerMax(beetle)\n");
return 0;
}
}
bool CBeetle::IsExpectOnPartnerSatisfied(CBeetle * beetle2)
{
// ExpectOnPartner - Age [2] = 2B how much older / younger can be the partner
// ExpectOnPartner - Energy = 1B how much more than ExpectOnPartner - InvInChild
// ExpectOnPartner - InvInChild = 1B how much more than InvInChild
// ExpectOnPartner - LearningAbility [2]= how much less/more can have the parter
if (beetle2->Age < Age - ExpectOnPartner[0]) return false;
if (beetle2->Age > Age + ExpectOnPartner[1]) return false;
if (beetle2->Energy < ExpectOnPartner[3]+ExpectOnPartner[2])return false;
if (beetle2->InvInChild< ExpectOnPartner[3])return false;
if (beetle2->LearnAbility < LearnAbility - ExpectOnPartner[4]) return false;
if (beetle2->LearnAbility > LearnAbility + ExpectOnPartner[5]) return false;
if (beetle2->Energy <=beetle2->InvInChild) return false; //beetle2 would not survive creation of the child
//if the beetle who checks the other beetle is not hungry -- I am not sure whether this check should not be somewhere else
if (IsHungry() == true) return false;
return true;
}
CBeetle * CBeetle::CreateChild(CBeetle * beetle2)
{
CBeetle * beetle_child = Crossover1Point(this, beetle2);
Mutation(beetle_child);
return beetle_child;
}
CBeetle * CBeetle::Crossover1Point(CBeetle * beetle1, CBeetle * beetle2)
{
CBeetle * beetle_child1=new CBeetle();
CBeetle * beetle_child2=new CBeetle();
CBeetle * pom_ref_beetle;
int N,J,pom,rand;
//indexes of
int I [4];
int indxInI [4]={0,1,2,3};
for (N=3;N>=0;N--)
{
pom=indxInI[N];
indxInI[N] = indxInI[rand=RandInBound(N+1)];
indxInI[rand]=pom;
}
int PossibleCrossPoints = CBeetle::GetBrainDimension(indxInI[0]) +//size of first dimension of Brain
EXPECT_ON_PARTNER_D + //size of ExpectOnPartner array
1; // There are 3 variables left - we start CP_count from 0, thus 2 more CP and after the last variable is no CP, thus 1.
int CrossPoint = RandInBound(PossibleCrossPoints+1);
int CP_count=0;
bool isCrossed=false;
//Brain
for (I[indxInI[0]]=0;I[indxInI[0]]<CBeetle::GetBrainDimension(indxInI[0]);I[indxInI[0]]++)
{
for(I[indxInI[1]]=0;I[indxInI[1]]<CBeetle::GetBrainDimension(indxInI[1]);I[indxInI[1]]++)
for(I[indxInI[2]]=0;I[indxInI[2]]<CBeetle::GetBrainDimension(indxInI[2]);I[indxInI[2]]++)
for(I[indxInI[3]]=0;I[indxInI[3]]<CBeetle::GetBrainDimension(indxInI[3]);I[indxInI[3]]++)
{
beetle_child1->Brain[I[0]][I[1]][I[2]][I[3]] = beetle1->Brain[I[0]][I[1]][I[2]][I[3]];
beetle_child2->Brain[I[0]][I[1]][I[2]][I[3]] = beetle2->Brain[I[0]][I[1]][I[2]][I[3]];
}
if (!isCrossed &&(CP_count==CrossPoint))
{
isCrossed=true;
// switch of references of child 1 and 2
pom_ref_beetle = beetle_child1;beetle_child1=beetle_child2;beetle_child2=pom_ref_beetle;
}
CP_count++;
}
//ExpectOnPartner
for (J=0;J<EXPECT_ON_PARTNER_D;J++)
{
beetle_child1->ExpectOnPartner[J] = beetle1->ExpectOnPartner[J];
beetle_child2->ExpectOnPartner[J] = beetle2->ExpectOnPartner[J];
if (!isCrossed &&(CP_count==CrossPoint))
{
isCrossed=true;
// switch of references of child 1 and 2
pom_ref_beetle = beetle_child1;beetle_child1=beetle_child2;beetle_child2=pom_ref_beetle;
}
CP_count++;
}
//Hungry Threshold
beetle_child1->HungryThreshold = beetle1->HungryThreshold;
beetle_child2->HungryThreshold = beetle2->HungryThreshold;
if (!isCrossed &&(CP_count==CrossPoint))
{
isCrossed=true;
// switch of references of child 1 and 2
pom_ref_beetle = beetle_child1;beetle_child1=beetle_child2;beetle_child2=pom_ref_beetle;
}
CP_count++;
//InvInChild
beetle_child1->InvInChild = beetle1->InvInChild;
beetle_child2->InvInChild = beetle2->InvInChild;
if (!isCrossed &&(CP_count==CrossPoint))
{
isCrossed=true;
// switch of references of child 1 and 2
pom_ref_beetle = beetle_child1;beetle_child1=beetle_child2;beetle_child2=pom_ref_beetle;
}
CP_count++;
//LearnAbility
beetle_child1->LearnAbility = beetle1->LearnAbility;
beetle_child2->LearnAbility = beetle2->LearnAbility;
assert (isCrossed==true);
//choice of one of two beetle_childs, produced by crossover}
CBeetle * beetle_child=NULL;
if (RandInBound(2)==0) {beetle_child=beetle_child1;delete(beetle_child2);beetle_child2=NULL;}
else {beetle_child=beetle_child2;delete(beetle_child1);beetle_child1=NULL;};
beetle_child->Age=0;
beetle_child->Energy= beetle1->InvInChild + beetle2->InvInChild;
if (beetle_child->Energy > MAX_ENERGY)beetle_child->Energy= MAX_ENERGY;
assert (beetle_child->Energy>0);
beetle_child->Direction = RandInBound(4);
beetle_child->NumChildren=0;
beetle_child->Id=CBeetle::CreateNewId();
return beetle_child;
}
/**
* Static method: GetBrainDimension
* Desc: Returns certain dimension range of the Brain attribute
* System dependence: no
* Usage comments:
* @return (Return values - meaning) : no return value
* @param name [ descrip](Parameters - meaning): which - zero based index of the dimension, in which the range will be returned
* @throws name [descrip](Exceptions - meaning)
*/
int CBeetle::GetBrainDimension(int which)
{
switch (which)
{
case 0: return BRAIN_D1;
case 1: return BRAIN_D2;
case 2: return BRAIN_D3;
case 3: return BRAIN_D4;
default: return 0;
}
}
/**
* Static method: Mutation
* Desc: Mutates Genom a beetle with probability MUTATION_PROB
* System dependence: no
* Usage comments:
* @return (Return values - meaning) : no return value
* @param name [ descrip](Parameters - meaning):beetle - reference to the beetle, whose genome is to be mutated
* @throws name [descrip](Exceptions - meaning)
*/
void CBeetle::Mutation(CBeetle * beetle)
{
int M,N,K,L;
bool isChange = false;
for (M=0;M<BRAIN_D1;M++)
for(N=0;N<BRAIN_D2;N++)
for(K=0;K<BRAIN_D3;K++)
for(L=0;L<BRAIN_D4;L++)
if (RandInBound(100)<MUTATION_PROB)
{beetle->Brain [M][N][K][L]= RandInBound(NUM_ACTIONS); isChange=true;}
for (M=1;M<EXPECT_ON_PARTNER_D;M++)
if (RandInBound(100)<MUTATION_PROB){beetle->ExpectOnPartner[M]= RandInBound(GetExpectOnPartnerMax(M));isChange=true;}
if (RandInBound(100)<MUTATION_PROB){beetle->HungryThreshold= RandInBound(MAX_ENERGY);isChange=true;}
if (RandInBound(100)<MUTATION_PROB){beetle->InvInChild= RandInBound(MAX_INV_IN_CHILD);isChange=true;}
if (RandInBound(100)<MUTATION_PROB){beetle->LearnAbility= RandInBound(MAX_LEARN_ABILITY); isChange=true;}
}
void CBeetle::LearnFrom(CBeetle* beetle2)
{
int M,N,K,L;
bool isChange = false;
for (M=0;M<BRAIN_D1;M++)
for(N=0;N<BRAIN_D2;N++)
for(K=0;K<BRAIN_D3;K++)
for(L=0;L<BRAIN_D4;L++)
if (RandInBound(100)<LEARN_PROB)
{Brain [M][N][K][L]= beetle2->Brain [M][N][K][L]; isChange=true;}
for (M=1;M<EXPECT_ON_PARTNER_D;M++)
if (RandInBound(100)<LEARN_PROB){ExpectOnPartner[M]= beetle2->ExpectOnPartner[M];isChange=true;}
if (RandInBound(100)<LEARN_PROB){HungryThreshold= beetle2->HungryThreshold;isChange=true;}
if (RandInBound(100)<LEARN_PROB){InvInChild= beetle2->InvInChild;isChange=true;}
if (RandInBound(100)<LEARN_PROB){LearnAbility= beetle2->LearnAbility; isChange=true;}
}
int CBeetle::CreateNewId(void)
{
if (LastId<MAX_INT) return ++LastId;
else return LastId=1;
}
| [
"ibart@60a5a0de-1a2f-0410-942a-f28f22aea592"
]
| [
[
[
1,
350
]
]
]
|
50145ad5faa65ce1d64ef0dd7141de3f67b2fb8e | b73f27ba54ad98fa4314a79f2afbaee638cf13f0 | /projects/PacketsGrasper/httpcontentcheck.cpp | ab80d71bbf7d8989ef5c9b17f824f069059208d7 | []
| no_license | weimingtom/httpcontentparser | 4d5ed678f2b38812e05328b01bc6b0c161690991 | 54554f163b16a7c56e8350a148b1bd29461300a0 | refs/heads/master | 2021-01-09T21:58:30.326476 | 2009-09-23T08:05:31 | 2009-09-23T08:05:31 | 48,733,304 | 3 | 0 | null | null | null | null | GB18030 | C++ | false | false | 8,700 | cpp | #include "stdafx.h"
#include "httpcontentcheck.h"
#include ".\webrecordconfig.h"
#include <webcontenttype.h>
#include <utility/httppacket.h>
#include <utility/ZipUtility.h>
#include <utility/BufferOnStackHeap.h>
#include <assert.h>
#include <stdlib.h>
#include <io.h>
#include <memory>
#include <comdef.h>
#include <fstream>
#include <time.h>
#define IMAGE_LOW_LIMIT (1024 * 10) //图像的下届是5K
#define TEXT_LOW_LIMIT (1024 * 2) // 网页的下限是1K
/////////////////////////////////////////////
// class HTTPContentHander
HTTPContentHander::HTTPContentHander() {
memset(imageDir, 0, sizeof(imageDir));
memset(pagesDir, 0, sizeof(pagesDir));
}
HTTPContentHander::~HTTPContentHander() {
}
//===================================================================
// 是否是
int HTTPContentHander::handleContent(HTTPPacket *packet) {
if (false == needHandle(packet)) {
return CONTENT_CHECK_UNKNOWN;
}
char * data = NULL;
try {
// 分配缓冲区
int sizeRead;
data = new char[packet->getDataSize()];
// 读入数据
packet->read(data, packet->getDataSize(), sizeRead);
const int check_result = checkContent(packet);
saveContent(packet, check_result);
delete data;
data = NULL;
return check_result;
} catch (...) {
if (NULL == data) {
delete data;
data = NULL;
}
// 如果出现异常
return CONTENT_CHECK_UNKNOWN;
}
}
// 是否需要处理
bool HTTPContentHander::needHandle(HTTPPacket *packet) {
if (packet->getDataSize() == 0) {
return false;
}
if (isImage(packet->getContentType()) ||
isText(packet->getContentType()) ) {
return true;
} else {
return false;
}
}
int HTTPContentHander::saveContent(HTTPPacket *packet, const int check_result) {
record_caller_.Call(recorder_);
check_caller_.Call(checker_);
if (isImage(packet->getContentType()) && recorder_.shouldRecord(check_result, packet->getContentType())) {
return saveImage(packet, check_result);
} else if (isText(packet->getContentType()) && recorder_.shouldRecord(check_result, packet->getContentType())) {
return saveText(packet, check_result);
}
return check_result;
}
int HTTPContentHander::checkContent(HTTPPacket *packet) {
if (isImage(packet->getContentType()) == true) {
return checkImage(packet);;
} else if (isText(packet->getContentType()) == true) {
return checkText(packet);
}
return CONTENT_CHECK_UNKNOWN;
}
//=====================================================================
// member functions
// 检测内容是不是Porned的,如果是返回true, 否则返回false
// 首先他会检查是否在白名单当中,如果不在则继续,否则返回false
// 检测是否应该检查图片内容,如果不应该,则直接返回
// 检查图片内容,并获取黄色图片的松紧度
int HTTPContentHander::checkImage(HTTPPacket *packet) {
if (false == checker_.shouldCheck(packet)) {
return CONTENT_CHECK_UNKNOWN;
}
// 随机生成一个文件名
GUID m_guid;
TCHAR filename[1024];
if(SUCCEEDED(CoCreateGuid(&m_guid))) {
_sntprintf(filename, 1024, ".\\%08X-%04X-%04x", m_guid.Data1, m_guid.Data2, m_guid.Data3);
} else {
return CONTENT_CHECK_UNKNOWN;
}
// 保存文件先
packet->achieve_data(filename);
// check Data
//PornDetectorBase* pPornDetector = NULL;
//if (!CreateObject(&pPornDetector)) {
// return CONTENT_CHECK_UNKNOWN;
//}
//double score;
//bool flag = pPornDetector->Detection(filename, &score);
//DeleteObject();
//if (score > 0.0f) {
// OutputDebugString("block---------------");
// return CONTENT_CHECK_PORN;
//} else {
// return CONTENT_CHECK_NORMAL;
//}
//if (score < checker_.getImageVScore()) {
// return CONTENT_CHECK_PORN;
//} else {
// return CONTENT_CHECK_NORMAL;
//}
// 删除文件
return CONTENT_CHECK_UNKNOWN;
}
int HTTPContentHander::checkText(HTTPPacket *packet) {
return CONTENT_CHECK_UNKNOWN;
}
//=======================================================================
// 负责保存内容
int HTTPContentHander::saveImage(HTTPPacket *packet, const int check_result) {
assert (isImage(packet->getContentType()) == true);
if (packet->getDataSize() > IMAGE_LOW_LIMIT) {
// 生成文件名
TCHAR content_file_path[MAX_PATH];
if (NULL != generateImageName(content_file_path, MAX_PATH, packet->getContentType())) {
packet->achieve_data(content_file_path);
// 增加到配置文件当中
addToRepostory(content_file_path, packet, check_result);
}
}
return -1;
}
// 可能需要解压缩保存
int HTTPContentHander::saveText(HTTPPacket * packet, const int check_result) {
assert (isText(packet->getContentType()) == true);
if (packet->getDataSize() > TEXT_LOW_LIMIT) {
// 生成文件名
TCHAR content_file_path[MAX_PATH];
if (NULL != generatePageName(content_file_path, MAX_PATH, packet->getContentType())) {
// 如果未压缩则直接保存
if (HTTP_RESPONSE_HEADER::CONTENCODING_GZIP != packet->getHeader()->getContentEncoding()) {
packet->achieve_data(content_file_path);
} else {
// 否则需要解压缩保存
savezip(packet, content_file_path);
}
}
// 增加到配置文件当中
addToRepostory(content_file_path, packet, check_result);
}
return -1;
}
int HTTPContentHander::savezip(HTTPPacket *packet, const char *filename) {
const int buf_size = 1024 * 16;
char buffer[buf_size];
// 首先将文件保存到一个临时文件当中
char tmp_file[MAX_PATH];
sprintf(tmp_file, "%s.tmp", filename);
packet->achieve_data(tmp_file);
// 打开文件
gzFile gzfile = gzopen (tmp_file, "rb" );
if (Z_NULL == gzfile) {
return -1;
}
// 保存在文件当中
std::fstream f;
f.open(filename, std::ios::out | std::ios::app | std::ios::binary);
int length = 0;
while (0 < (length = gzread (gzfile, buffer, buf_size))) {
f.write(buffer, length);
}
f.close();
// 释放缓冲区
gzclose(gzfile);
// 删除临时文件
DeleteFile(tmp_file);
return 0;
}
// 添加到配置文件当中
void HTTPContentHander::addToRepostory(const TCHAR *fullpath, HTTPPacket * packet, const int check_result) {
}
// 生成文件名的规则
const TCHAR * HTTPContentHander::genRandomName(TCHAR * filename, const int bufsize, const int content_type) {
DWORD count = GetTickCount();
srand((unsigned int)time(0));
unsigned rd = rand();
_sntprintf(filename, bufsize, "%u-%u.%s", count, rd, getExt(content_type));
return filename;
}
// 生成名字
const TCHAR * HTTPContentHander::generateImageName(TCHAR *fullpath, const int bufsize, const int content_type) {
TCHAR filename[MAX_PATH];
const TCHAR * dir = GetImageDirectory();
if (dir != NULL) {
while (1) {
genRandomName(filename, MAX_PATH, content_type);
_sntprintf(fullpath, bufsize, "%s%s", dir, filename);
if (_taccess(fullpath, 0) == -1)
break;
}
return fullpath;
} else {
return NULL;
}
}
// 产生一个网页的名称
const TCHAR * HTTPContentHander::generatePageName(TCHAR *fullpath, const int bufsize, const int content_type) {
TCHAR filename[MAX_PATH];
const TCHAR * dir = GetPageDirectory();
if (NULL != dir) {
while (1) {
genRandomName(filename, MAX_PATH, content_type);
_sntprintf(fullpath, bufsize, "%s%s", dir, filename);
if (_taccess(fullpath, 0) == -1)
break;
}
return fullpath;
} else {
return NULL;
}
}
TCHAR * HTTPContentHander::GetImageDirectory() {
try {
if (imageDir[0] == '\0') {
AutoInitInScale _auto_com_init;
ISnowmanSetting *appSetting = NULL;
HRESULT hr = CoCreateInstance(CLSID_SnowmanSetting, NULL, CLSCTX_LOCAL_SERVER, IID_ISnowmanSetting, (LPVOID*)&appSetting);
if (FAILED(hr)) {
return NULL;
}
BSTR out;
appSetting->getImageFolder(&out);
_tcsncpy(imageDir, (TCHAR*)_bstr_t(out), MAX_PATH);
appSetting->Release();
appSetting = NULL;
}
return imageDir;
} catch (...) {
return NULL;
}
}
TCHAR * HTTPContentHander::GetPageDirectory() {
try {
if (pagesDir[0] == '\0') {
AutoInitInScale _auto_com_init;
ISnowmanSetting *appSetting = NULL;
HRESULT hr = CoCreateInstance(CLSID_SnowmanSetting, NULL, CLSCTX_LOCAL_SERVER, IID_ISnowmanSetting, (LPVOID*)&appSetting);
if (FAILED(hr)) {
return NULL;
}
BSTR out;
appSetting->getPagesFolder(&out);
_tcsncpy(pagesDir, (TCHAR*)_bstr_t(out), MAX_PATH);
appSetting->Release();
appSetting = NULL;
}
return pagesDir;
} catch (...) {
return NULL;
}
}
| [
"[email protected]"
]
| [
[
[
1,
323
]
]
]
|
89212ac8553dc737b53b449adb02375e0db8aba1 | b8fbe9079ce8996e739b476d226e73d4ec8e255c | /src/tools/rmax/filehistorydlg.h | c0f7a7fa606456465e6f5adf75e7e96269d8f2c0 | []
| 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 | 2,004 | h | /***********************************************************************************/
// File: FileHistoryDlg.h
// Desc: Exporter core class declaration
// Date: 13.08.2006
// Author: Ruslan Shestopalyuk
/***********************************************************************************/
#ifndef __FILEHISTORYDLG_H__
#define __FILEHISTORYDLG_H__
#include <vector>
#include <string>
/***********************************************************************************/
// Class: FileHistoryDlg
// Desc:
/***********************************************************************************/
class FileHistoryDlg
{
public:
FileHistoryDlg ( HWND hWnd = NULL, HINSTANCE hInstance= NULL );
~FileHistoryDlg ();
bool Show ( bool bSaveDlg = false );
void AddHistoryItem ( const char* item ) { m_History.push_back( item ); }
int GetNumHistoryItems () const { return m_History.size(); }
const char* GetHistoryItem ( int idx ) const { return m_History[idx].c_str(); }
void AddFilter ( const char* descr, const char* ext );
const char* GetFileName () const { return m_FileName.GetFullPath(); }
void SetFileName ( const char* path ) { m_FileName = path; }
void EnableHistory ( bool bEnable = true ) { m_bEnableHistory = bEnable; }
UINT_PTR CALLBACK HookProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam );
static UINT_PTR CALLBACK HookProcCB( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam );
private:
typedef std::vector<std::string> StringList;
HWND m_hWnd;
HINSTANCE m_hInstance;
StringList m_History;
Path m_FileName;
char m_Filter[_MAX_PATH];
HWND m_hHistory;
bool m_bEnableHistory;
}; // class FileHistoryDlger
#endif // __FileHistoryDlg_H__
| [
"[email protected]"
]
| [
[
[
1,
50
]
]
]
|
5db5b56cd1578a6d0c7ae68854347f9ddb85f92b | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/test/test/minimal_test.cpp | fc35eff20147866d8c344c11f5a8a925b6a28b6f | [
"LicenseRef-scancode-unknown-license-reference",
"BSL-1.0"
]
| 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 | 2,457 | cpp | // (C) Copyright Gennadiy Rozental 2001-2006.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
// File : $RCSfile: minimal_test.cpp,v $
//
// Version : $Revision: 1.11 $
//
// Description : minimal testing unit test
// ***************************************************************************
// Boost.Test
#include <boost/test/minimal.hpp>
//____________________________________________________________________________//
struct bool_convertible1 {
bool_convertible1( bool v ) : v_( v ) {}
operator bool() { return v_; }
bool v_;
};
//____________________________________________________________________________//
struct bool_convertible2 {
bool_convertible2( int v ) : v_( v ) {}
operator int() { return v_; }
int v_;
};
//____________________________________________________________________________//
struct bool_convertible3 {
bool_convertible3( void* v ) : v_( v ) {}
struct Tester {};
operator Tester*() { return (Tester*)v_; }
void* v_;
};
//____________________________________________________________________________//
int
test_main( int /*argc*/, char* /*argv*/[] )
{
int i = 1;
BOOST_CHECK( i == 1 );
BOOST_CHECK( i == 2 );
BOOST_CHECK( bool_convertible1( true ) );
BOOST_CHECK( bool_convertible1( false ) );
BOOST_CHECK( bool_convertible2( 1 ) );
BOOST_CHECK( bool_convertible2( 0 ) );
BOOST_CHECK( bool_convertible3( (void*)1 ) );
BOOST_CHECK( bool_convertible3( NULL ) );
BOOST_ERROR( "Some error" );
BOOST_REQUIRE( i == 4 );
return 0;
}
//____________________________________________________________________________//
// ***************************************************************************
// Revision History :
//
// $Log: minimal_test.cpp,v $
// Revision 1.11 2006/03/19 11:49:04 rogeeff
// *** empty log message ***
//
// Revision 1.10 2005/05/11 05:07:57 rogeeff
// licence update
//
// Revision 1.9 2005/05/21 06:26:10 rogeeff
// licence update
//
// Revision 1.8 2003/12/01 00:42:37 rogeeff
// prerelease cleaning
//
// ***************************************************************************
// EOF
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
]
| [
[
[
1,
94
]
]
]
|
9af5f0fc40edb54eb2ed897290396e716cfa0ee3 | 1fa55e54f26ce008717b3216d525dcb2cfa83f76 | /rce/detail/hook_base.h | 81799aa5980c3b5fdbe8533b05a755dcbfbd908c | [
"MIT"
]
| permissive | ascheglov/cpp-rce-lib | cf3b5255e9768ca4ad3e6f659154acea00b1ef40 | 7b3a27546e40e3f87fc0473f3dd5b27f18abc4b7 | refs/heads/master | 2016-08-12T03:39:08.756726 | 2011-03-28T12:01:31 | 2011-03-28T12:01:31 | 52,878,383 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 891 | h | /* C++ RCE Library
* http://code.google.com/p/cpp-rce-lib/
* (c) 2010-2011 Abyx. MIT License.
*
* Base class for all hook classes
*/
#pragma once
#pragma managed(push, off)
namespace hook {
namespace detail {
template<typename Derived>
struct HookBase
{
typedef Derived derived_t;
typedef unsigned long /* unspecified-type */ call_addr_t;
static call_addr_t callAddr;
template<typename T>
static T get_original(T)
{
return (T)callAddr;
}
static void set_installed(bool state)
{
state ? derived_t::install() : derived_t::uninstall();
}
static void* hook_fn()
{
return (void*)derived_t::hook;
}
};
template<typename Derived>
typename HookBase<Derived>::call_addr_t HookBase<Derived>::callAddr;
} // namespace detail
} // namespace hook
#pragma managed(pop)
| [
"Abyx@localhost"
]
| [
[
[
1,
45
]
]
]
|
7561e17c33236ac63b4c22b26be238d121e4a718 | d54d8b1bbc9575f3c96853e0c67f17c1ad7ab546 | /hlsdk-2.3-p3/singleplayer/dmc/dlls/func_break.cpp | 0f650054262ae9395ef4c6fc994784d4a134581f | []
| no_license | joropito/amxxgroup | 637ee71e250ffd6a7e628f77893caef4c4b1af0a | f948042ee63ebac6ad0332f8a77393322157fa8f | refs/heads/master | 2021-01-10T09:21:31.449489 | 2010-04-11T21:34:27 | 2010-04-11T21:34:27 | 47,087,485 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,018 | cpp | /***
*
* Copyright (c) 1996-2002, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
/*
===== bmodels.cpp ========================================================
spawn, think, and use functions for entities that use brush models
*/
#include "extdll.h"
#include "util.h"
#include "cbase.h"
#include "saverestore.h"
#include "func_break.h"
#include "decals.h"
#include "explode.h"
extern DLL_GLOBAL Vector g_vecAttackDir;
// =================== FUNC_Breakable ==============================================
// Just add more items to the bottom of this array and they will automagically be supported
// This is done instead of just a classname in the FGD so we can control which entities can
// be spawned, and still remain fairly flexible
const char *CBreakable::pSpawnObjects[] =
{
NULL, // 0
"item_battery", // 1
"item_healthkit", // 2
"weapon_9mmhandgun",// 3
"ammo_9mmclip", // 4
"weapon_9mmAR", // 5
"ammo_9mmAR", // 6
"ammo_ARgrenades", // 7
"weapon_shotgun", // 8
"ammo_buckshot", // 9
"weapon_crossbow", // 10
"ammo_crossbow", // 11
"weapon_357", // 12
"ammo_357", // 13
"weapon_rpg", // 14
"ammo_rpgclip", // 15
"ammo_gaussclip", // 16
"weapon_handgrenade",// 17
"weapon_tripmine", // 18
"weapon_satchel", // 19
"weapon_snark", // 20
"weapon_hornetgun", // 21
};
void CBreakable::KeyValue( KeyValueData* pkvd )
{
// UNDONE_WC: explicitly ignoring these fields, but they shouldn't be in the map file!
if (FStrEq(pkvd->szKeyName, "explosion"))
{
if (!stricmp(pkvd->szValue, "directed"))
m_Explosion = expDirected;
else if (!stricmp(pkvd->szValue, "random"))
m_Explosion = expRandom;
else
m_Explosion = expRandom;
pkvd->fHandled = TRUE;
}
else if (FStrEq(pkvd->szKeyName, "material"))
{
int i = atoi( pkvd->szValue);
// 0:glass, 1:metal, 2:flesh, 3:wood
if ((i < 0) || (i >= matLastMaterial))
m_Material = matWood;
else
m_Material = (Materials)i;
pkvd->fHandled = TRUE;
}
else if (FStrEq(pkvd->szKeyName, "deadmodel"))
{
pkvd->fHandled = TRUE;
}
else if (FStrEq(pkvd->szKeyName, "shards"))
{
// m_iShards = atof(pkvd->szValue);
pkvd->fHandled = TRUE;
}
else if (FStrEq(pkvd->szKeyName, "gibmodel") )
{
m_iszGibModel = ALLOC_STRING(pkvd->szValue);
pkvd->fHandled = TRUE;
}
else if (FStrEq(pkvd->szKeyName, "spawnobject") )
{
int object = atoi( pkvd->szValue );
if ( object > 0 && object < ARRAYSIZE(pSpawnObjects) )
m_iszSpawnObject = MAKE_STRING( pSpawnObjects[object] );
pkvd->fHandled = TRUE;
}
else if (FStrEq(pkvd->szKeyName, "explodemagnitude") )
{
ExplosionSetMagnitude( atoi( pkvd->szValue ) );
pkvd->fHandled = TRUE;
}
else if (FStrEq(pkvd->szKeyName, "lip") )
pkvd->fHandled = TRUE;
else
CBaseDelay::KeyValue( pkvd );
}
//
// func_breakable - bmodel that breaks into pieces after taking damage
//
LINK_ENTITY_TO_CLASS( func_breakable, CBreakable );
TYPEDESCRIPTION CBreakable::m_SaveData[] =
{
DEFINE_FIELD( CBreakable, m_Material, FIELD_INTEGER ),
DEFINE_FIELD( CBreakable, m_Explosion, FIELD_INTEGER ),
// Don't need to save/restore these because we precache after restore
// DEFINE_FIELD( CBreakable, m_idShard, FIELD_INTEGER ),
DEFINE_FIELD( CBreakable, m_angle, FIELD_FLOAT ),
DEFINE_FIELD( CBreakable, m_iszGibModel, FIELD_STRING ),
DEFINE_FIELD( CBreakable, m_iszSpawnObject, FIELD_STRING ),
// Explosion magnitude is stored in pev->impulse
};
IMPLEMENT_SAVERESTORE( CBreakable, CBaseEntity );
void CBreakable::Spawn( void )
{
Precache( );
if ( FBitSet( pev->spawnflags, SF_BREAK_TRIGGER_ONLY ) )
pev->takedamage = DAMAGE_NO;
else
pev->takedamage = DAMAGE_YES;
pev->solid = SOLID_BSP;
pev->movetype = MOVETYPE_PUSH;
m_angle = pev->angles.y;
pev->angles.y = 0;
SET_MODEL(ENT(pev), STRING(pev->model) );//set size and link into world.
SetTouch( BreakTouch );
if ( FBitSet( pev->spawnflags, SF_BREAK_TRIGGER_ONLY ) ) // Only break on trigger
SetTouch( NULL );
// Flag unbreakable glass as "worldbrush" so it will block ALL tracelines
if ( !IsBreakable() && pev->rendermode != kRenderNormal )
pev->flags |= FL_WORLDBRUSH;
}
const char *CBreakable::pSoundsWood[] =
{
"debris/wood1.wav",
"debris/wood2.wav",
"debris/wood3.wav",
};
const char *CBreakable::pSoundsFlesh[] =
{
"debris/flesh1.wav",
"debris/flesh2.wav",
"debris/flesh3.wav",
"debris/flesh5.wav",
"debris/flesh6.wav",
"debris/flesh7.wav",
};
const char *CBreakable::pSoundsMetal[] =
{
"debris/metal1.wav",
"debris/metal2.wav",
"debris/metal3.wav",
};
const char *CBreakable::pSoundsConcrete[] =
{
"debris/concrete1.wav",
"debris/concrete2.wav",
"debris/concrete3.wav",
};
const char *CBreakable::pSoundsGlass[] =
{
"debris/glass1.wav",
"debris/glass2.wav",
"debris/glass3.wav",
};
const char **CBreakable::MaterialSoundList( Materials precacheMaterial, int &soundCount )
{
const char **pSoundList = NULL;
switch ( precacheMaterial )
{
case matWood:
pSoundList = pSoundsWood;
soundCount = ARRAYSIZE(pSoundsWood);
break;
case matFlesh:
pSoundList = pSoundsFlesh;
soundCount = ARRAYSIZE(pSoundsFlesh);
break;
case matComputer:
case matUnbreakableGlass:
case matGlass:
pSoundList = pSoundsGlass;
soundCount = ARRAYSIZE(pSoundsGlass);
break;
case matMetal:
pSoundList = pSoundsMetal;
soundCount = ARRAYSIZE(pSoundsMetal);
break;
case matCinderBlock:
case matRocks:
pSoundList = pSoundsConcrete;
soundCount = ARRAYSIZE(pSoundsConcrete);
break;
case matCeilingTile:
case matNone:
default:
soundCount = 0;
break;
}
return pSoundList;
}
void CBreakable::MaterialSoundPrecache( Materials precacheMaterial )
{
const char **pSoundList;
int i, soundCount = 0;
pSoundList = MaterialSoundList( precacheMaterial, soundCount );
for ( i = 0; i < soundCount; i++ )
{
PRECACHE_SOUND( (char *)pSoundList[i] );
}
}
void CBreakable::MaterialSoundRandom( edict_t *pEdict, Materials soundMaterial, float volume )
{
const char **pSoundList;
int soundCount = 0;
pSoundList = MaterialSoundList( soundMaterial, soundCount );
if ( soundCount )
EMIT_SOUND( pEdict, CHAN_BODY, pSoundList[ RANDOM_LONG(0,soundCount-1) ], volume, 1.0 );
}
void CBreakable::Precache( void )
{
const char *pGibName;
switch (m_Material)
{
case matWood:
pGibName = "models/woodgibs.mdl";
PRECACHE_SOUND("debris/bustcrate1.wav");
PRECACHE_SOUND("debris/bustcrate2.wav");
break;
case matFlesh:
pGibName = "models/fleshgibs.mdl";
PRECACHE_SOUND("debris/bustflesh1.wav");
PRECACHE_SOUND("debris/bustflesh2.wav");
break;
case matComputer:
PRECACHE_SOUND("buttons/spark5.wav");
PRECACHE_SOUND("buttons/spark6.wav");
pGibName = "models/computergibs.mdl";
PRECACHE_SOUND("debris/bustmetal1.wav");
PRECACHE_SOUND("debris/bustmetal2.wav");
break;
case matUnbreakableGlass:
case matGlass:
pGibName = "models/glassgibs.mdl";
PRECACHE_SOUND("debris/bustglass1.wav");
PRECACHE_SOUND("debris/bustglass2.wav");
break;
case matMetal:
pGibName = "models/metalplategibs.mdl";
PRECACHE_SOUND("debris/bustmetal1.wav");
PRECACHE_SOUND("debris/bustmetal2.wav");
break;
case matCinderBlock:
pGibName = "models/cindergibs.mdl";
PRECACHE_SOUND("debris/bustconcrete1.wav");
PRECACHE_SOUND("debris/bustconcrete2.wav");
break;
case matRocks:
pGibName = "models/rockgibs.mdl";
PRECACHE_SOUND("debris/bustconcrete1.wav");
PRECACHE_SOUND("debris/bustconcrete2.wav");
break;
case matCeilingTile:
pGibName = "models/ceilinggibs.mdl";
PRECACHE_SOUND ("debris/bustceiling.wav");
break;
}
MaterialSoundPrecache( m_Material );
if ( m_iszGibModel )
pGibName = STRING(m_iszGibModel);
m_idShard = PRECACHE_MODEL( (char *)pGibName );
// Precache the spawn item's data
if ( m_iszSpawnObject )
UTIL_PrecacheOther( (char *)STRING( m_iszSpawnObject ) );
}
// play shard sound when func_breakable takes damage.
// the more damage, the louder the shard sound.
void CBreakable::DamageSound( void )
{
int pitch;
float fvol;
char *rgpsz[6];
int i;
int material = m_Material;
// if (RANDOM_LONG(0,1))
// return;
if (RANDOM_LONG(0,2))
pitch = PITCH_NORM;
else
pitch = 95 + RANDOM_LONG(0,34);
fvol = RANDOM_FLOAT(0.75, 1.0);
if (material == matComputer && RANDOM_LONG(0,1))
material = matMetal;
switch (material)
{
case matComputer:
case matGlass:
case matUnbreakableGlass:
rgpsz[0] = "debris/glass1.wav";
rgpsz[1] = "debris/glass2.wav";
rgpsz[2] = "debris/glass3.wav";
i = 3;
break;
case matWood:
rgpsz[0] = "debris/wood1.wav";
rgpsz[1] = "debris/wood2.wav";
rgpsz[2] = "debris/wood3.wav";
i = 3;
break;
case matMetal:
rgpsz[0] = "debris/metal1.wav";
rgpsz[1] = "debris/metal3.wav";
rgpsz[2] = "debris/metal2.wav";
i = 2;
break;
case matFlesh:
rgpsz[0] = "debris/flesh1.wav";
rgpsz[1] = "debris/flesh2.wav";
rgpsz[2] = "debris/flesh3.wav";
rgpsz[3] = "debris/flesh5.wav";
rgpsz[4] = "debris/flesh6.wav";
rgpsz[5] = "debris/flesh7.wav";
i = 6;
break;
case matRocks:
case matCinderBlock:
rgpsz[0] = "debris/concrete1.wav";
rgpsz[1] = "debris/concrete2.wav";
rgpsz[2] = "debris/concrete3.wav";
i = 3;
break;
case matCeilingTile:
// UNDONE: no ceiling tile shard sound yet
i = 0;
break;
}
if (i)
EMIT_SOUND_DYN(ENT(pev), CHAN_VOICE, rgpsz[RANDOM_LONG(0,i-1)], fvol, ATTN_NORM, 0, pitch);
}
void CBreakable::BreakTouch( CBaseEntity *pOther )
{
float flDamage;
entvars_t* pevToucher = pOther->pev;
// only players can break these right now
if ( !pOther->IsPlayer() || !IsBreakable() )
{
return;
}
if ( FBitSet ( pev->spawnflags, SF_BREAK_TOUCH ) )
{// can be broken when run into
flDamage = pevToucher->velocity.Length() * 0.01;
if (flDamage >= pev->health)
{
SetTouch( NULL );
TakeDamage(pevToucher, pevToucher, flDamage, DMG_CRUSH);
// do a little damage to player if we broke glass or computer
pOther->TakeDamage( pev, pev, flDamage/4, DMG_SLASH );
}
}
if ( FBitSet ( pev->spawnflags, SF_BREAK_PRESSURE ) && pevToucher->absmin.z >= pev->maxs.z - 2 )
{// can be broken when stood upon
// play creaking sound here.
DamageSound();
SetThink ( Die );
SetTouch( NULL );
if ( m_flDelay == 0 )
{// !!!BUGBUG - why doesn't zero delay work?
m_flDelay = 0.1;
}
pev->nextthink = pev->ltime + m_flDelay;
}
}
//
// Smash the our breakable object
//
// Break when triggered
void CBreakable::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value )
{
if ( IsBreakable() )
{
pev->angles.y = m_angle;
UTIL_MakeVectors(pev->angles);
g_vecAttackDir = gpGlobals->v_forward;
Die();
}
}
void CBreakable::TraceAttack( entvars_t *pevAttacker, float flDamage, Vector vecDir, TraceResult *ptr, int bitsDamageType )
{
// random spark if this is a 'computer' object
if (RANDOM_LONG(0,1) )
{
switch( m_Material )
{
case matComputer:
{
UTIL_Sparks( ptr->vecEndPos );
float flVolume = RANDOM_FLOAT ( 0.7 , 1.0 );//random volume range
switch ( RANDOM_LONG(0,1) )
{
case 0: EMIT_SOUND(ENT(pev), CHAN_VOICE, "buttons/spark5.wav", flVolume, ATTN_NORM); break;
case 1: EMIT_SOUND(ENT(pev), CHAN_VOICE, "buttons/spark6.wav", flVolume, ATTN_NORM); break;
}
}
break;
case matUnbreakableGlass:
UTIL_Ricochet( ptr->vecEndPos, RANDOM_FLOAT(0.5,1.5) );
break;
}
}
CBaseDelay::TraceAttack( pevAttacker, flDamage, vecDir, ptr, bitsDamageType );
}
//=========================================================
// Special takedamage for func_breakable. Allows us to make
// exceptions that are breakable-specific
// bitsDamageType indicates the type of damage sustained ie: DMG_CRUSH
//=========================================================
int CBreakable :: TakeDamage( entvars_t* pevInflictor, entvars_t* pevAttacker, float flDamage, int bitsDamageType )
{
Vector vecTemp;
// if Attacker == Inflictor, the attack was a melee or other instant-hit attack.
// (that is, no actual entity projectile was involved in the attack so use the shooter's origin).
if ( pevAttacker == pevInflictor )
{
vecTemp = pevInflictor->origin - ( pev->absmin + ( pev->size * 0.5 ) );
// if a client hit the breakable with a crowbar, and breakable is crowbar-sensitive, break it now.
if ( FBitSet ( pevAttacker->flags, FL_CLIENT ) &&
FBitSet ( pev->spawnflags, SF_BREAK_CROWBAR ) && (bitsDamageType & DMG_CLUB))
flDamage = pev->health;
}
else
// an actual missile was involved.
{
vecTemp = pevInflictor->origin - ( pev->absmin + ( pev->size * 0.5 ) );
}
if (!IsBreakable())
return 0;
// Breakables take double damage from the crowbar
if ( bitsDamageType & DMG_CLUB )
flDamage *= 2;
// Boxes / glass / etc. don't take much poison damage, just the impact of the dart - consider that 10%
if ( bitsDamageType & DMG_POISON )
flDamage *= 0.1;
// this global is still used for glass and other non-monster killables, along with decals.
g_vecAttackDir = vecTemp.Normalize();
// do the damage
pev->health -= flDamage;
if (pev->health <= 0)
{
Killed( pevAttacker, GIB_NORMAL );
Die();
return 0;
}
// Make a shard noise each time func breakable is hit.
// Don't play shard noise if cbreakable actually died.
DamageSound();
return 1;
}
void CBreakable::Die( void )
{
Vector vecSpot;// shard origin
Vector vecVelocity;// shard velocity
CBaseEntity *pEntity = NULL;
char cFlag = 0;
int pitch;
float fvol;
pitch = 95 + RANDOM_LONG(0,29);
if (pitch > 97 && pitch < 103)
pitch = 100;
// The more negative pev->health, the louder
// the sound should be.
fvol = RANDOM_FLOAT(0.85, 1.0) + (abs(pev->health) / 100.0);
if (fvol > 1.0)
fvol = 1.0;
switch (m_Material)
{
case matGlass:
switch ( RANDOM_LONG(0,1) )
{
case 0: EMIT_SOUND_DYN(ENT(pev), CHAN_VOICE, "debris/bustglass1.wav", fvol, ATTN_NORM, 0, pitch);
break;
case 1: EMIT_SOUND_DYN(ENT(pev), CHAN_VOICE, "debris/bustglass2.wav", fvol, ATTN_NORM, 0, pitch);
break;
}
cFlag = BREAK_GLASS;
break;
case matWood:
switch ( RANDOM_LONG(0,1) )
{
case 0: EMIT_SOUND_DYN(ENT(pev), CHAN_VOICE, "debris/bustcrate1.wav", fvol, ATTN_NORM, 0, pitch);
break;
case 1: EMIT_SOUND_DYN(ENT(pev), CHAN_VOICE, "debris/bustcrate2.wav", fvol, ATTN_NORM, 0, pitch);
break;
}
cFlag = BREAK_WOOD;
break;
case matComputer:
case matMetal:
switch ( RANDOM_LONG(0,1) )
{
case 0: EMIT_SOUND_DYN(ENT(pev), CHAN_VOICE, "debris/bustmetal1.wav", fvol, ATTN_NORM, 0, pitch);
break;
case 1: EMIT_SOUND_DYN(ENT(pev), CHAN_VOICE, "debris/bustmetal2.wav", fvol, ATTN_NORM, 0, pitch);
break;
}
cFlag = BREAK_METAL;
break;
case matFlesh:
switch ( RANDOM_LONG(0,1) )
{
case 0: EMIT_SOUND_DYN(ENT(pev), CHAN_VOICE, "debris/bustflesh1.wav", fvol, ATTN_NORM, 0, pitch);
break;
case 1: EMIT_SOUND_DYN(ENT(pev), CHAN_VOICE, "debris/bustflesh2.wav", fvol, ATTN_NORM, 0, pitch);
break;
}
cFlag = BREAK_FLESH;
break;
case matRocks:
case matCinderBlock:
switch ( RANDOM_LONG(0,1) )
{
case 0: EMIT_SOUND_DYN(ENT(pev), CHAN_VOICE, "debris/bustconcrete1.wav", fvol, ATTN_NORM, 0, pitch);
break;
case 1: EMIT_SOUND_DYN(ENT(pev), CHAN_VOICE, "debris/bustconcrete2.wav", fvol, ATTN_NORM, 0, pitch);
break;
}
cFlag = BREAK_CONCRETE;
break;
case matCeilingTile:
EMIT_SOUND_DYN(ENT(pev), CHAN_VOICE, "debris/bustceiling.wav", fvol, ATTN_NORM, 0, pitch);
break;
}
if (m_Explosion == expDirected)
vecVelocity = g_vecAttackDir * 200;
else
{
vecVelocity.x = 0;
vecVelocity.y = 0;
vecVelocity.z = 0;
}
vecSpot = pev->origin + (pev->mins + pev->maxs) * 0.5;
MESSAGE_BEGIN( MSG_PVS, SVC_TEMPENTITY, vecSpot );
WRITE_BYTE( TE_BREAKMODEL);
// position
WRITE_COORD( vecSpot.x );
WRITE_COORD( vecSpot.y );
WRITE_COORD( vecSpot.z );
// size
WRITE_COORD( pev->size.x);
WRITE_COORD( pev->size.y);
WRITE_COORD( pev->size.z);
// velocity
WRITE_COORD( vecVelocity.x );
WRITE_COORD( vecVelocity.y );
WRITE_COORD( vecVelocity.z );
// randomization
WRITE_BYTE( 10 );
// Model
WRITE_SHORT( m_idShard ); //model id#
// # of shards
WRITE_BYTE( 0 ); // let client decide
// duration
WRITE_BYTE( 25 );// 2.5 seconds
// flags
WRITE_BYTE( cFlag );
MESSAGE_END();
float size = pev->size.x;
if ( size < pev->size.y )
size = pev->size.y;
if ( size < pev->size.z )
size = pev->size.z;
// !!! HACK This should work!
// Build a box above the entity that looks like an 8 pixel high sheet
Vector mins = pev->absmin;
Vector maxs = pev->absmax;
mins.z = pev->absmax.z;
maxs.z += 8;
// BUGBUG -- can only find 256 entities on a breakable -- should be enough
CBaseEntity *pList[256];
int count = UTIL_EntitiesInBox( pList, 256, mins, maxs, FL_ONGROUND );
if ( count )
{
for ( int i = 0; i < count; i++ )
{
ClearBits( pList[i]->pev->flags, FL_ONGROUND );
pList[i]->pev->groundentity = NULL;
}
}
// Don't fire something that could fire myself
pev->targetname = 0;
pev->solid = SOLID_NOT;
// Fire targets on break
SUB_UseTargets( NULL, USE_TOGGLE, 0 );
SetThink( SUB_Remove );
pev->nextthink = pev->ltime + 0.1;
if ( m_iszSpawnObject )
CBaseEntity::Create( (char *)STRING(m_iszSpawnObject), VecBModelOrigin(pev), pev->angles, edict() );
if ( Explodable() )
{
ExplosionCreate( Center(), pev->angles, edict(), ExplosionMagnitude(), TRUE );
}
}
BOOL CBreakable :: IsBreakable( void )
{
return m_Material != matUnbreakableGlass;
}
int CBreakable :: DamageDecal( int bitsDamageType )
{
if ( m_Material == matGlass )
return DECAL_GLASSBREAK1 + RANDOM_LONG(0,2);
if ( m_Material == matUnbreakableGlass )
return DECAL_BPROOF1;
return CBaseEntity::DamageDecal( bitsDamageType );
}
class CPushable : public CBreakable
{
public:
void Spawn ( void );
void Precache( void );
void Touch ( CBaseEntity *pOther );
void Move( CBaseEntity *pMover, int push );
void KeyValue( KeyValueData *pkvd );
void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value );
void EXPORT StopSound( void );
// virtual void SetActivator( CBaseEntity *pActivator ) { m_pPusher = pActivator; }
virtual int ObjectCaps( void ) { return (CBaseEntity :: ObjectCaps() & ~FCAP_ACROSS_TRANSITION) | FCAP_CONTINUOUS_USE; }
virtual int Save( CSave &save );
virtual int Restore( CRestore &restore );
inline float MaxSpeed( void ) { return m_maxSpeed; }
// breakables use an overridden takedamage
virtual int TakeDamage( entvars_t* pevInflictor, entvars_t* pevAttacker, float flDamage, int bitsDamageType );
static TYPEDESCRIPTION m_SaveData[];
static char *m_soundNames[3];
int m_lastSound; // no need to save/restore, just keeps the same sound from playing twice in a row
float m_maxSpeed;
float m_soundTime;
};
TYPEDESCRIPTION CPushable::m_SaveData[] =
{
DEFINE_FIELD( CPushable, m_maxSpeed, FIELD_FLOAT ),
DEFINE_FIELD( CPushable, m_soundTime, FIELD_TIME ),
};
IMPLEMENT_SAVERESTORE( CPushable, CBreakable );
LINK_ENTITY_TO_CLASS( func_pushable, CPushable );
char *CPushable :: m_soundNames[3] = { "debris/pushbox1.wav", "debris/pushbox2.wav", "debris/pushbox3.wav" };
void CPushable :: Spawn( void )
{
if ( pev->spawnflags & SF_PUSH_BREAKABLE )
CBreakable::Spawn();
else
Precache( );
pev->movetype = MOVETYPE_PUSHSTEP;
pev->solid = SOLID_BBOX;
SET_MODEL( ENT(pev), STRING(pev->model) );
if ( pev->friction > 399 )
pev->friction = 399;
m_maxSpeed = 400 - pev->friction;
SetBits( pev->flags, FL_FLOAT );
pev->friction = 0;
pev->origin.z += 1; // Pick up off of the floor
UTIL_SetOrigin( pev, pev->origin );
// Multiply by area of the box's cross-section (assume 1000 units^3 standard volume)
pev->skin = ( pev->skin * (pev->maxs.x - pev->mins.x) * (pev->maxs.y - pev->mins.y) ) * 0.0005;
m_soundTime = 0;
}
void CPushable :: Precache( void )
{
for ( int i = 0; i < 3; i++ )
PRECACHE_SOUND( m_soundNames[i] );
if ( pev->spawnflags & SF_PUSH_BREAKABLE )
CBreakable::Precache( );
}
void CPushable :: KeyValue( KeyValueData *pkvd )
{
if ( FStrEq(pkvd->szKeyName, "size") )
{
int bbox = atoi(pkvd->szValue);
pkvd->fHandled = TRUE;
switch( bbox )
{
case 0: // Point
UTIL_SetSize(pev, Vector(-8, -8, -8), Vector(8, 8, 8));
break;
case 2: // Big Hull!?!? !!!BUGBUG Figure out what this hull really is
UTIL_SetSize(pev, VEC_DUCK_HULL_MIN*2, VEC_DUCK_HULL_MAX*2);
break;
case 3: // Player duck
UTIL_SetSize(pev, VEC_DUCK_HULL_MIN, VEC_DUCK_HULL_MAX);
break;
default:
case 1: // Player
UTIL_SetSize(pev, VEC_HULL_MIN, VEC_HULL_MAX);
break;
}
}
else if ( FStrEq(pkvd->szKeyName, "buoyancy") )
{
pev->skin = atof(pkvd->szValue);
pkvd->fHandled = TRUE;
}
else
CBreakable::KeyValue( pkvd );
}
// Pull the func_pushable
void CPushable :: Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value )
{
if ( !pActivator || !pActivator->IsPlayer() )
{
if ( pev->spawnflags & SF_PUSH_BREAKABLE )
this->CBreakable::Use( pActivator, pCaller, useType, value );
return;
}
if ( pActivator->pev->velocity != g_vecZero )
Move( pActivator, 0 );
}
void CPushable :: Touch( CBaseEntity *pOther )
{
if ( FClassnameIs( pOther->pev, "worldspawn" ) )
return;
Move( pOther, 1 );
}
void CPushable :: Move( CBaseEntity *pOther, int push )
{
entvars_t* pevToucher = pOther->pev;
int playerTouch = 0;
// Is entity standing on this pushable ?
if ( FBitSet(pevToucher->flags,FL_ONGROUND) && pevToucher->groundentity && VARS(pevToucher->groundentity) == pev )
{
// Only push if floating
if ( pev->waterlevel > 0 )
pev->velocity.z += pevToucher->velocity.z * 0.1;
return;
}
if ( pOther->IsPlayer() )
{
if ( push && !(pevToucher->button & (IN_FORWARD|IN_USE)) ) // Don't push unless the player is pushing forward and NOT use (pull)
return;
playerTouch = 1;
}
float factor;
if ( playerTouch )
{
if ( !(pevToucher->flags & FL_ONGROUND) ) // Don't push away from jumping/falling players unless in water
{
if ( pev->waterlevel < 1 )
return;
else
factor = 0.1;
}
else
factor = 1;
}
else
factor = 0.25;
pev->velocity.x += pevToucher->velocity.x * factor;
pev->velocity.y += pevToucher->velocity.y * factor;
float length = sqrt( pev->velocity.x * pev->velocity.x + pev->velocity.y * pev->velocity.y );
if ( push && (length > MaxSpeed()) )
{
pev->velocity.x = (pev->velocity.x * MaxSpeed() / length );
pev->velocity.y = (pev->velocity.y * MaxSpeed() / length );
}
if ( playerTouch )
{
pevToucher->velocity.x = pev->velocity.x;
pevToucher->velocity.y = pev->velocity.y;
if ( (gpGlobals->time - m_soundTime) > 0.7 )
{
m_soundTime = gpGlobals->time;
if ( length > 0 && FBitSet(pev->flags,FL_ONGROUND) )
{
m_lastSound = RANDOM_LONG(0,2);
EMIT_SOUND(ENT(pev), CHAN_WEAPON, m_soundNames[m_lastSound], 0.5, ATTN_NORM);
// SetThink( StopSound );
// pev->nextthink = pev->ltime + 0.1;
}
else
STOP_SOUND( ENT(pev), CHAN_WEAPON, m_soundNames[m_lastSound] );
}
}
}
#if 0
void CPushable::StopSound( void )
{
Vector dist = pev->oldorigin - pev->origin;
if ( dist.Length() <= 0 )
STOP_SOUND( ENT(pev), CHAN_WEAPON, m_soundNames[m_lastSound] );
}
#endif
int CPushable::TakeDamage( entvars_t* pevInflictor, entvars_t* pevAttacker, float flDamage, int bitsDamageType )
{
if ( pev->spawnflags & SF_PUSH_BREAKABLE )
return CBreakable::TakeDamage( pevInflictor, pevAttacker, flDamage, bitsDamageType );
return 1;
}
| [
"joropito@23c7d628-c96c-11de-a380-73d83ba7c083"
]
| [
[
[
1,
998
]
]
]
|
ecec3c066eddc0bd46ef28414680ca2b5c7b84b4 | 080941f107281f93618c30a7aa8bec9e8e2d8587 | /include/commandlineoptions.h | 8ce2cb77413eb2142479fcf9d3a36d9e0e961531 | [
"MIT"
]
| permissive | scoopr/COLLADA_Refinery | 6d40ee1497b9f33818ec1e71677c3d0a0bf8ced4 | 3a5ad1a81e0359f9025953e38e425bc10b5bf6c5 | refs/heads/master | 2021-01-22T01:55:14.642769 | 2009-03-10T21:31:04 | 2009-03-10T21:31:04 | 194,828 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,716 | h | /*
The MIT License
Copyright 2006 Sony Computer Entertainment Inc.
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.
*/
#ifndef _COMMAND_LINE_OPTIONS_H_
#define _COMMAND_LINE_OPTIONS_H_
//---------------------------------------------------------------------------
// CommandLineOptions
//
// Author: John Bates
// Date: 04/22/02
//
// Description: Creates a structure of command line parameters that can
// be accessed by their string name. Prints out a formatted "usage" screen
// based on the registered command line parameters if the input is not
// acceptable.
//
//---------------------------------------------------------------------------
#include <map>
#include <set>
#include <vector>
#include <string>
class CommandLineOptions
{
class PrintOut{
public:
virtual ~PrintOut(){}
virtual void print(const CommandLineOptions* const clo) const=0;
};
class Heading : public PrintOut {
public:
virtual ~Heading();
Heading();
Heading(const Heading& rhs);
Heading& operator=(const Heading& rhs);
std::string name;
virtual void print(const CommandLineOptions* const clo) const;
};
class Setting : public PrintOut {
public:
virtual ~Setting();
Setting();
Setting(const Setting& rhs);
Setting& operator=(const Setting& rhs);
std::string name, input, description;
virtual void print(const CommandLineOptions* const clo) const;
};
class Option : public PrintOut {
public:
virtual ~Option();
Option();
Option(const Option& rhs);
Option& operator=(const Option& rhs);
std::string name, description;
virtual void print(const CommandLineOptions* const clo) const;
};
class Global : public PrintOut {
public:
virtual ~Global();
Global();
Global(const Global& rhs);
Global& operator=(const Global& rhs);
std::string input, description;
virtual void print(const CommandLineOptions* const clo) const;
};
class Example : public PrintOut {
public:
virtual ~Example();
Example();
Example(const Example& rhs);
Example& operator=(const Example& rhs);
std::string input, description;
virtual void print(const CommandLineOptions* const clo) const;
};
private:
std::set<std::string> names;
std::map<std::string, std::string> aliases;
std::vector<Setting*> settings;
std::vector<Option*> options;
std::vector<Global*> globals;
std::vector<Example> examples;
std::vector<PrintOut*> printouts;
std::string binary_name;
std::string title;
std::map<std::string, std::string> isettings;
std::set<std::string> ioptions;
std::vector<std::string> iglobals;
std::vector<std::string>::iterator global_it;
// These private checks check for *support* of a setting or option
bool _CheckForSetting(std::string& name) const;
bool _CheckForOption(std::string& name) const;
const std::string& _BaseName(const std::string& name) const;
void _NewName(const std::string& name);
void _AddAlias(const std::string& name, const std::string& alias);
void _ExitUsage() const;
public:
CommandLineOptions();
CommandLineOptions(const CommandLineOptions *const clo); // For partial copies only
~CommandLineOptions();
void Load(int argc, char *argv[]);
void Unload();
void PartiallyUnload();
void SetTitle(const std::string& name);
void AddHeading(const std::string& name);
void AddExample(const std::string& example, const std::string& description);
void AddSetting(const std::string& name, const std::string& input, const std::string& description);
void AddSetting(const std::string& name, const std::string& input, const std::string& description, const std::string& alias);
void AddOption(const std::string& name, const std::string& description);
void AddOption(const std::string& name, const std::string& description, const std::string& alias);
void AddGlobal(const std::string& input, const std::string& description);
size_t NumSettings() const { return isettings.size(); }
size_t NumOptions() const { return ioptions.size(); }
size_t NumGlobals() const { return iglobals.size(); }
// These public checks check for presence of the setting or option on the command line
bool CheckForSetting(const std::string& name) const;
bool CheckForOption(const std::string& name) const;
bool CheckForGlobal() const { return !iglobals.empty(); }
// Get methods for settings. Make sure you call CheckForSetting() first.
std::string GetString(const std::string& name) const;
long GetInt(const std::string& name) const;
double GetFloat(const std::string& name) const;
// Returns the next global, or false if there is none
bool GetNextGlobal(std::string& s);
void PrintUsage() const;
};
#endif
| [
"alorino@7d79dae2-2c22-0410-a73c-a02ad39e49d4",
"sceahklaw@7d79dae2-2c22-0410-a73c-a02ad39e49d4"
]
| [
[
[
1,
1
],
[
23,
163
]
],
[
[
2,
22
]
]
]
|
0cb7adf3b934ae08ea94ea2a355e911af024d05b | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libc/testpipe/src/testpipe.cpp | 5a670dbc77036e3f7498a7dffe2a11a1531ed8dd | []
| 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 | 9,272 | cpp | /*
* Copyright (c) 2009 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:
*
*/
/*
* ==============================================================================
* Name : testpipe.cpp
* Part of : testpipe
*
* Description : ?Description
* Version: 0.5
*
*/
#include "testpipe.h"
CTestPipe::~CTestPipe()
{
}
CTestPipe::CTestPipe(const TDesC& aStepName)
{
// MANDATORY Call to base class method to set up the human readable name for logging.
SetTestStepName(aStepName);
}
TVerdict CTestPipe::doTestStepPreambleL()
{
__UHEAP_MARK;
SetTestStepResult(EFail);
return TestStepResult();
}
TVerdict CTestPipe::doTestStepPostambleL()
{
__UHEAP_MARKEND;
return TestStepResult();
}
TVerdict CTestPipe::doTestStepL()
{
int err;
if(TestStepName() == KTestPipe)
{
INFO_PRINTF1(_L("TestPipe():"));
err = TestPipe();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KPipeCheckWriteOnReadfd)
{
INFO_PRINTF1(_L("PipeCheckWriteOnReadfd():"));
err = PipeCheckWriteOnReadfd();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KPipeCheckReadOnWritefd)
{
INFO_PRINTF1(_L("PipeCheckReadOnWritefd():"));
err = PipeCheckReadOnWritefd();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KPipeWriteRead)
{
INFO_PRINTF1(_L("PipeWriteRead():"));
err = PipeWriteRead();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KPipeCheckWriteFd)
{
INFO_PRINTF1(_L("PipeCheckWriteFd():"));
err = PipeCheckWriteFd();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KPipeCheckReadFd)
{
INFO_PRINTF1(_L("PipeCheckReadFd():"));
err = PipeCheckReadFd();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KPopenPipeCommandRead)
{
INFO_PRINTF1(_L("Testing PopenPipeCommandRead()..."));
err = PopenPipeCommandRead();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KMultiplePopenPipeCommandRead)
{
INFO_PRINTF1(_L("Testing MultiplePopenPipeCommandRead()..."));
err = MultiplePopenPipeCommandRead();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KPopenPipeOEExeRead)
{
INFO_PRINTF1(_L("Testing PopenPipeOEExeRead()..."));
err = PopenPipeOEExeRead();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KPopenPipeInvalidPathRead)
{
INFO_PRINTF1(_L("Testing PopenPipeInvalidPathRead()..."));
err = PopenPipeInvalidPathRead();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KPopenPipeInvalidCommand)
{
INFO_PRINTF1(_L("Testing PopenPipeInvalidCommand()..."));
err = PopenPipeInvalidCommand();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KPopenPipeInvalidMode)
{
INFO_PRINTF1(_L("Testing PopenPipeInvalidMode()..."));
err = PopenPipeInvalidMode();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KPopenPipeWrite)
{
INFO_PRINTF1(_L("Testing PopenPipeWrite()..."));
err = PopenPipeWrite();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KPopenBlockingRead)
{
INFO_PRINTF1(_L("Testing PopenBlockingRead()..."));
err = PopenBlockingRead();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KPopen3PipeCommandRead)
{
INFO_PRINTF1(_L("Testing Popen3PipeCommandRead()..."));
err = Popen3PipeCommandRead();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KMultiplePopen3PipeCommandRead)
{
INFO_PRINTF1(_L("Testing MultiplePopen3PipeCommandRead()..."));
err = MultiplePopen3PipeCommandRead();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KPopen3PipeOEExeRead)
{
INFO_PRINTF1(_L("Testing Popen3PipeOEExeRead()..."));
err = Popen3PipeOEExeRead();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KPopen3PipeInvalidPathRead)
{
INFO_PRINTF1(_L("Testing Popen3PipeInvalidPathRead()..."));
err = Popen3PipeInvalidPathRead();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KPopen3PipeInvalidCommand)
{
INFO_PRINTF1(_L("Testing PopenPipeInvalidCommand()..."));
err = Popen3PipeInvalidCommand();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KTestProcessPopen3ChitChat)
{
INFO_PRINTF1(_L("Testing TestProcessPopen3ChitChat()..."));
err = TestProcessPopen3ChitChat();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KPopen3ReadWriteTest)
{
INFO_PRINTF1(_L("Testing Popen3ReadWriteTest()..."));
err = Popen3ReadWriteTest();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KTestSystem)
{
INFO_PRINTF1(_L("Testing System()..."));
err = TestSystem();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KLseekpipetest)
{
INFO_PRINTF1(_L("Lseekpipetest()..."));
err = Lseekpipetest();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KOpenMaxfdPipetest)
{
INFO_PRINTF1(_L("LOpenMaxfdPipetest()..."));
err = OpenMaxfdPipetest();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KSimultaneousOpenfdPipetest)
{
INFO_PRINTF1(_L("SimultaneousOpenfdPipetest()..."));
err = SimultaneousOpenfdPipetest();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KFopenMaxPopenTest)
{
INFO_PRINTF1(_L("FopenMaxPopenTest()..."));
err = FopenMaxPopenTest();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KFopenMaxPopen3Test)
{
INFO_PRINTF1(_L("FopenMaxPopen3Test()..."));
err = FopenMaxPopen3Test();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KTestEnvPopen3)
{
INFO_PRINTF1(_L("TestEnvPopen3()..."));
err = TestEnvPopen3();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KTestsystem_LongName)
{
INFO_PRINTF1(_L("Testsystem_LongName()..."));
err = Testsystem_LongName();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KTestwsystem_LongName)
{
INFO_PRINTF1(_L("Testwsystem_LongName()..."));
err = Testwsystem_LongName();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KTestpopen_LongName)
{
INFO_PRINTF1(_L("Testpopen_LongName()..."));
err = Testpopen_LongName();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KTestwpopen_LongName)
{
INFO_PRINTF1(_L("Testwpopen_LongName()..."));
err = Testwpopen_LongName();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KTestpopen3_LongName)
{
INFO_PRINTF1(_L("Testpopen3_LongName()..."));
err = Testpopen3_LongName();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KTestwpopen3_LongName)
{
INFO_PRINTF1(_L("Testwpopen3_LongName()..."));
err = Testwpopen3_LongName();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KTestPipeWaitForData)
{
INFO_PRINTF1(_L("TestPipeWaitForData()..."));
err = TestPipeWaitForData();
SetTestStepResult(err ? static_cast<TVerdict> (err): EPass);
}
return TestStepResult();
}
| [
"none@none"
]
| [
[
[
1,
271
]
]
]
|
449e3f48f78bae1e29984432c5d257436fd791c7 | d4a7bdadb66cb90ff25c033c50485bf1d5c7dfa3 | /src/ObjMesh.cpp | 6e29550b37455de6a8682ae3fd988e422918b029 | []
| no_license | atrzaska/rwgltest | 5c1be4105a11f5d66524eb95023f6ce743ab31f8 | a857773db90cc7028b6197036cd3604c39cedb36 | refs/heads/master | 2021-05-28T16:48:06.128199 | 2011-12-22T22:22:21 | 2011-12-22T22:22:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,592 | cpp | /* Copyright (C) 2011 Andrzej Trzaska
*
* 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 "ObjMesh.h"
#include <SOIL.h>
ObjMesh::ObjMesh(string filename) {
parse_mtl(filename);
parse_obj(filename);
}
void ObjMesh::parse_obj(string filename) {
string line;
GLuint materialid = 1;
ifstrm.open(filename);
if(!ifstrm.is_open()) {
return;
}
while(getline(ifstrm, line)) {
if(!line.find("# ")) {
} else if (line.empty()) {
} else if(!line.find("usemtl ")) {
line.replace(0, 7, "");
for(GLuint i = 0; i < Materials.size(); i++) {
if(Materials[i].name == line) {
materialid = Materials[i].matId;
break;
}
}
} else if(!line.find("v ")) {
Vertex o;// = {0, 0 ,0};
sscanf_s(line.c_str(), "v %f %f %f", &o.x, &o.y, &o.z);
VertexArray.push_back(o);
} else if(!line.find("vn ")) {
Normal o = {0, 0 ,0};
sscanf_s(line.c_str(), "vn %f %f %f", &o.x, &o.y, &o.z);
NormalArray.push_back(o);
} else if(!line.find("vt ")) {
TexCoord o = {0, 0};
sscanf_s(line.c_str(), "vt %f %f", &o.u, &o.v);
TexCoordArray.push_back(o);
} else if(!line.find("f ")) {
Face o;
sscanf_s(line.c_str(), "f %d/%d/%d %d/%d/%d %d/%d/%d",
&o.Vertex[0], &o.TexCoord[0], &o.Normal[0],
&o.Vertex[1], &o.TexCoord[1], &o.Normal[1],
&o.Vertex[2], &o.TexCoord[2], &o.Normal[2]);
o.TextureNo = materialid;
FaceArray.push_back(o);
}
}
ifstrm.close();
}
void ObjMesh::parse_mtl(string filename) {
string fname = filename;
GLuint fn = fname.find(".obj");
fname.replace(fn, 4, ".mtl");
ifstrm.open(fname);
if(!ifstrm.is_open()) {
return;
}
string line;
while(getline(ifstrm, line)) {
if(!line.find("# ")) {
} else if(line.empty()) {
} else if(!line.find("newmtl ")) {
Material o;
line.replace(0, 7, "");
o.name = line;
getline(ifstrm, line);
sscanf_s(line.c_str(), "Ka %f %f %f", &o.ambient[0], &o.ambient[1], &o.ambient[2]);
getline(ifstrm, line);
sscanf_s(line.c_str(), "Kd %f %f %f", &o.diffuse[0], &o.diffuse[1], &o.diffuse[2]);
getline(ifstrm, line);
sscanf_s(line.c_str(), "Ks %f %f %f", &o.specular[0], &o.specular[1], &o.specular[2]);
getline(ifstrm, line);
sscanf_s(line.c_str(), "illum %d", &o.illum);
getline(ifstrm, line);
line.replace(0, 7, "");
string mtlfile = "./Data/";
mtlfile += line;
o.matId = SOIL_load_OGL_texture(mtlfile.c_str(), SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_INVERT_Y);
Materials.push_back(o);
}
}
ifstrm.close();
}
void ObjMesh::DrawMe(void) {
GLuint currtexture = 0;
glPushMatrix();
glEnable(GL_TEXTURE_2D);
for(GLuint i = 0; i < FaceArray.size(); i++) {
if(currtexture != FaceArray[i].TextureNo) {
glEnd();
currtexture = FaceArray[i].TextureNo;
glBindTexture(GL_TEXTURE_2D, currtexture);
glBegin(GL_TRIANGLES);
}
for(int j = 0; j < 3; j++) {
glTexCoord2f(TexCoordArray[FaceArray[i].TexCoord[j] - 1].u,
TexCoordArray[FaceArray[i].TexCoord[j] - 1].v);
glNormal3f(NormalArray[FaceArray[i].Normal[j] - 1].x,
NormalArray[FaceArray[i].Normal[j] - 1].y,
NormalArray[FaceArray[i].Normal[j] - 1].z);
glVertex3f(VertexArray[FaceArray[i].Vertex[j] - 1].x,
VertexArray[FaceArray[i].Vertex[j] - 1].y,
VertexArray[FaceArray[i].Vertex[j] - 1].z);
}
}
glEnd();
glPopMatrix();
glDisable(GL_TEXTURE_2D);
}
ObjMesh::~ObjMesh(void) {
delete this;
}
| [
"[email protected]@6fd63c64-eb38-cfd0-a5bf-51302b3bf559"
]
| [
[
[
1,
149
]
]
]
|
c7132040fe2736c487f3d7fec4fc67c3badabe43 | 18f8abb90efece37949f5b5758c7752b1602fb12 | /projects/BejeweledAI/autoblitz-export/import/regplat/all/all/include/regplat/win32/rp_render_dd4.h | e10dfc4814f21f040793392aedeb39ae561efca8 | []
| no_license | marceltoben/evandrix.github.com | caa7d4c2ef84ba8c5a9a6ace2126e8fd6db1a516 | abc3fbfb34f791f84e9a9d4dc522966421778ab2 | refs/heads/master | 2021-08-02T06:18:12.953567 | 2011-08-23T16:49:33 | 2011-08-23T16:49:33 | 2,267,457 | 3 | 5 | null | 2021-07-28T11:39:25 | 2011-08-25T11:18:56 | C | UTF-8 | C++ | false | false | 2,708 | h | /******************************************************************************
*
* Regular Platform Project
*
* Copyright (c) 2007, Aaron "Caustik" Robinson
* All rights reserved.
*
* File := rp_render_dd4.h
* Desc := Render class for DirectDraw4
*
* 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 Aaron "Caustik" Robinson 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.
*
*****************************************************************************/
#ifndef RP_RENDER_DD4_H
#define RP_RENDER_DD4_H
#include "regplat/rp_render.h"
/*! @brief Render class for DirectDraw4 */
class rp_render_dd4 : public rp_render
{
public:
rp_render_dd4() { }
virtual ~rp_render_dd4() { }
/*! \name rp_render interface */
/*! \{ */
/*! create renderer */
virtual bool create(uint32 width, uint32 height);
/*! destroy renderer */
virtual bool destroy();
/*! message pump - should be called periodically for responsiveness */
virtual bool pump();
/*! render 8-bit pixels (pitch is in bytes) */
virtual bool draw_pixels(uint08 *p_pix, uint32 x, uint32 y, uint32 w, uint32 h, uint32 p);
/*! \} */
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
71
]
]
]
|
64409ca437a222793b531f637985bf9c0cf38ab0 | 1092bd6dc9b728f3789ba96e37e51cdfb9e19301 | /loci/platform/tstring.cpp | c72ecbadd9ea7c4017c52f3c834a8971ae1a3bc3 | []
| no_license | dtbinh/loci-extended | 772239e63b4e3e94746db82d0e23a56d860b6f0d | f4b5ad6c4412e75324d19b71559a66dd20f4f23f | refs/heads/master | 2021-01-10T12:23:52.467480 | 2011-03-15T22:03:06 | 2011-03-15T22:03:06 | 36,032,427 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,152 | cpp | /**
* Implementation of unicode narrow and widen functions.
* Implements the narrow and widen functions for std::string and std::wstring
* using the std::ctype facet.
*
* @file tstring.cpp
* @author David Gill
* @date 22/08/2009
*/
#include <string>
#include <locale>
#include <vector>
#include "loci/platform/tstring.h"
#include "loci/platform/win32/windows_common.h"
namespace loci {
namespace platform
{
std::string narrow(const std::wstring & s)
{
// get c-string-style information to work with
const wchar_t * wstr = s.c_str();
const std::wstring::size_type length = s.length();
// contiguous buffer to hold transformed characters
std::vector<char> buffer(length);
// transform using the ctype facet and default locale
typedef std::ctype<wchar_t> facet_type;
std::use_facet<facet_type>(std::locale()).narrow(
wstr,
wstr + length,
'?',
&buffer.front());
// return a string from the buffer
return std::string(buffer.begin(), buffer.end());
}
std::wstring widen(const std::string & s)
{
// get c-string-style information to work with
const char * str = s.c_str();
const std::string::size_type length = s.length();
// contiguous buffer to hold transformed characters
std::vector<wchar_t> buffer(length);
// transform using the ctype facet and default locale
typedef std::ctype<wchar_t> facet_type;
std::use_facet<facet_type>(std::locale()).widen(
str,
str + length,
&buffer.front());
// return a string from the buffer
return std::wstring(buffer.begin(), buffer.end());
}
tstring to_tstr(const std::string & s)
{
#ifdef LOCI_UNICODE
return widen(s);
#else
return s;
#endif
}
tstring to_tstr(const std::wstring & s)
{
#ifdef LOCI_UNICODE
return s;
#else
return narrow(s);
#endif
}
} // namespace platform
} // namespace loci | [
"[email protected]@0e8bac56-0901-9d1a-f0c4-3841fc69e132"
]
| [
[
[
1,
80
]
]
]
|
3f6bd6aa42b0fe0e71e2b98a164e01870cc041df | e5ded38277ec6db30ef7721a9f6f5757924e130e | /Cpp/SoSe10/Blatt07.Aufgabe02/Blatt07.Aufgabe02.cpp | 318f0189b3df843fd2123a8d10eb94195a7fcf61 | []
| no_license | TetsuoCologne/sose10 | 67986c8a014c4bdef19dc52e0e71e91602600aa0 | 67505537b0eec497d474bd2d28621e36e8858307 | refs/heads/master | 2020-05-27T04:36:02.620546 | 2010-06-22T20:47:08 | 2010-06-22T20:47:08 | 32,480,813 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 2,895 | cpp | // Blatt07.Aufgabe02.cpp : Definiert den Einstiegspunkt für die Konsolenanwendung.
//
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <cmath>
#include "MyVector.h"
void TestResult(const char* pc, int& nTest, bool b)
{
std::cout << "Test " << std::right << std::setw(2) << nTest << " : "
<< std::left << std::setw(50) << pc
<< ( b ? "OK " : "NOK") << std::endl;
++nTest;
}
int _tmain(int argc, _TCHAR* argv[])
{
using std::cout;
using std::endl;
bool b;
int nTest;
if (true) {
nTest = 1;
std::cout << "Test MyVector Begin" << std::endl
<< "-------------------" << std::endl;
{
MyVector v1;
b = (v1.dim()==1 && v1[0]==0.0);
TestResult("MyVector: dim=1, v=0, default cstr",nTest,b);
b = (MyVector::memory==1);
TestResult("MyVector: memory=1 at start",nTest,b);
MyVector v2(2),v3(3,1.0);
b = (v2.dim()==2 && v2[0]==0.0 && v2[1]==0.0)
&& (v3.dim()==3 && v3[0]==1.0 && v3[1]==1.0 && v3[2]==1.0);
TestResult("MyVector: dim in [2,3], v in [0,1], default cstr",nTest,b);
b = (MyVector::memory==6);
TestResult("MyVector: memory=6 after mult. defs.",nTest,b);
MyVector v4(v3),v5=v4;
b = (v4.dim()==v3.dim() && v4[0]==1.0 && v4[1]==1.0)
&& (v5.dim()==v4.dim() && v5[0]==1.0 && v5[1]==1.0 && v5[2]==1.0);
TestResult("MyVector: dim in [2,3], v in [0,1], copy cstr",nTest,b);
b = (MyVector::memory==12);
TestResult("MyVector: memory=12 after mult. defs.",nTest,b);
v2[0]=2.0; v2[1]=3.0;
b = (v2[0]==2.0 && v2[1]==3.0);
TestResult("MyVector: v in [2,3], op[] R/W",nTest,b);
v3[0]=4.0; v3[1]=5.0; v3[2]=6.0;
b = (v3[0]==4.0 && v3[1]==5.0 && v3[2]==6.0);
TestResult("MyVector: v in [4,5,6], op[] R/W",nTest,b);
v3 = v2;
b = (v3.dim()==v2.dim() && v3[0]==v2[0] && v3[1]==v2[1]);
TestResult("MyVector: op=(vector)",nTest,b);
b = (MyVector::memory==11);
TestResult("MyVector: memory=11 after mult. defs.",nTest,b);
b = (v3==v2);
TestResult("MyVector: op==(vector)",nTest,b);
b = !(v3!=v2);
TestResult("MyVector: op!=(vector)",nTest,b);
v2 = 12.5;
b = (v2[0]==12.5 && v2[1]==12.5);
TestResult("MyVector: op=(value)",nTest,b);
b = (v3!=v2);
TestResult("MyVector: op==(vector)",nTest,b);
b = !(v3==v2);
TestResult("MyVector: op!=(vector)",nTest,b);
v2[0]=3.0; v2[1]=4.0;
b = (std::fabs(v2.Norm()-5.0)<1e-15);
TestResult("MyVector: Norm()",nTest,b);
MyVector w1(2), w2(2), w3;
w1[0]=1.0; w1[1]=2.0;
w2[0]=3.0; w2[1]=4.0;
w1 += w2;
b = (w1[0]==4.0 && w1[1]==6.0);
TestResult("MyVector: op+=(vector)",nTest,b);
w3 = w1+w2;
b = (w3[0]==7.0 && w3[1]==10.0);
TestResult("MyVector: op+(vector)",nTest,b);
std::cout << "-----------------" << std::endl
<< "Test MyVector End" << std::endl << std::endl;
}
}
return 0;
}
| [
"[email protected]@f2f8bf26-27bb-74d3-be08-1e18597623ec"
]
| [
[
[
1,
110
]
]
]
|
c58ee4c4ecf64f20c781c4b6c2dfb50eb9d27182 | 885fc5f6e056abe95996b4fc6eebef06a94d50ce | /include/RealFFMpegBitmapConverter.h | 31fbeee8df1130587d4ff0422a9eea7d65c72a2c | []
| no_license | jdzyzh/ffmpeg-wrapper | bdf0a6f15db2625b2707cbac57d5bfaca6396e3d | 5185bb3695df9adda59f7f849095314f16b2bd48 | refs/heads/master | 2021-01-10T08:58:06.519741 | 2011-11-30T06:32:50 | 2011-11-30T06:32:50 | 54,611,386 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 731 | h | #pragma once
extern "C"
{
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include <libswscale/swscale.h>
#include <libavutil/pixdesc.h>
}
#include "FPSCounter.h"
class RealFFMpegBitmapConverter
{
public:
RealFFMpegBitmapConverter(int w1,int h1,PixelFormat f1,
int w2,int h2,PixelFormat f2,unsigned char* dstBuf=NULL,int dstBufSize=0);
~RealFFMpegBitmapConverter(void);
int initContext(int w1,int h1,PixelFormat f1,
int w2,int h2,PixelFormat f2);
AVPicture* convertVideo(AVPicture *picSrc);
SwsContext *img_convert_ctx;
int scaleBufSize;
unsigned char *scaleBuf;
AVPicture *pPicScaled;
bool m_bAllocBuf;
int w1,w2,h1,h2;
PixelFormat f1,f2;
};
| [
"[email protected]"
]
| [
[
[
1,
33
]
]
]
|
866385d43f41e9eff48ef170e30f88dda0a095ad | d9bf74086d94169f0e0c9e976965662f6639a9ae | /src/r3.cpp | ba1caf6cdf1aaa3cfa014a0b0782eabdd88fc1b5 | []
| no_license | th0m/projet-genie-logiciel-gstl | 75e77387b95c328f7e34428ca4f4b74198774d10 | c2d283897d36ba2e5bf4ec0bf3dbea6ab65884a8 | refs/heads/master | 2021-01-25T09:00:30.529804 | 2011-04-19T21:22:12 | 2011-04-19T21:22:12 | 32,145,361 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 2,169 | cpp | #include "r3.hpp"
#include "shape.hpp"
R3::R3(SDL_Surface *window)
: Race(window)
{
/* # On forge notre race, de façon très géométrique pour pouvoir boucler facilement */
/* # On place les limites hautes & basses de la piste */
for(unsigned int i = 1; i < m_nbRows - 1; ++i)
m_map[1][i] = m_map[m_nbLines - 1][i] = Shape::LIMIT;
/* # On place les limites gauches & droites de la piste */
for(unsigned int i = 2; i < m_nbLines - 1; ++i)
m_map[i][0] = m_map[i][m_nbRows - 1] = Shape::LIMIT;
/* # Les quatres bords blanc */
m_map[1][0] = m_map[1][m_nbRows - 1] = Shape::WHITE;
m_map[m_nbLines - 1][0] = m_map[m_nbLines - 1][m_nbRows - 1] = Shape::WHITE;
/* # Et maintenant les limites internes ! ; petit changement pour differencier la course 3 */
for(unsigned int i = (m_nbRows / 2) - 3 + 1; i < m_nbRows - 10; ++i)
m_map[m_nbLines / 2][i] = Shape::LIMIT;
/* # La ligne d'arrivée/de départ */
for(unsigned int i = m_nbLines / 2 + 1; i < m_nbLines - 1; ++i)
m_map[i][(m_nbRows / 2) - 1] = Shape::STARTINGFINISHLINE;
/* # Premiere flaque */
for(unsigned int i = m_nbLines / 2 + 2; i < m_nbLines / 2 + 4 ; ++i)
{
m_map[i][(m_nbRows / 2) + 3] = Shape::FLAQUE;
m_map[i][(m_nbRows / 2) + 4] = Shape::FLAQUE;
}
/* # Le bolide du joueur */
m_map[m_nbLines / 2 + 1][(m_nbRows / 2)] = Shape::PLAYERCAR;
m_map[m_nbLines / 2 + 1][(m_nbRows / 2) + 1] = Shape::IACAR;
m_map[m_nbLines / 2 + 1][(m_nbRows / 2) + 2] = Shape::IACAR;
m_map[m_nbLines / 2 + 1][(m_nbRows / 2) + 3] = Shape::IACAR;
/* # Réutilisation des checkpoints de la course numéro 1 étant donne que les courses ne changent que *tres* peu */
m_c1 = new Checkpoint(0, 210, 300, 210);
m_c2 = new Checkpoint(320, 0, 320, 210);
m_c3 = new Checkpoint(340, 210, 600, 210);
m_csfl = new Checkpoint(320, 210, 320, 400);
}
R3::~R3()
{
}
void R3::load()
{
Race::load();
m_pts.push_back(80);
m_pts.push_back(60);
m_pts.push_back(520);
m_pts.push_back(340);
initIAs();
}
| [
"axelscht@468702e1-5092-14fc-779a-dee4b53e0e13",
"[email protected]@468702e1-5092-14fc-779a-dee4b53e0e13",
"goussen.maxime@468702e1-5092-14fc-779a-dee4b53e0e13"
]
| [
[
[
1,
10
],
[
12,
14
],
[
16,
23
],
[
25,
29
],
[
36,
42
],
[
46,
46
],
[
48,
64
]
],
[
[
11,
11
],
[
15,
15
],
[
24,
24
],
[
30,
35
]
],
[
[
43,
45
],
[
47,
47
]
]
]
|
12a02612486bfbe7bcefa0cb233fbff09e0bb14f | 619941b532c6d2987c0f4e92b73549c6c945c7e5 | /Include/Zipex/ZStream.h | 43d2675e5495ef8a21f86c78f4e06a9cafdaefe6 | []
| no_license | dzw/stellarengine | 2b70ddefc2827be4f44ec6082201c955788a8a16 | 2a0a7db2e43c7c3519e79afa56db247f9708bc26 | refs/heads/master | 2016-09-01T21:12:36.888921 | 2008-12-12T12:40:37 | 2008-12-12T12:40:37 | 36,939,169 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,487 | h | // //
// ##### #### # # -= Zipex Library =- //
// ## # # ## ## zstream.h - Zipped iostream //
// ## #### ### //
// ## # ### iostream implementation for zipped files //
// ## # ## ## //
// ##### # # # R1 (C)2003-2004 Markus Ewald -> License.txt //
// //
#ifndef ZIPEX_ZSTREAM_H
#define ZIPEX_ZSTREAM_H
#include "zipex/zippedfile.h"
#include "zipex/ziparchive.h"
#include <streambuf>
namespace Zipex {
// //
// Zipex::basic_zstreambuf //
// //
/// Zipped stream buffer
/** A buffer for zipped streams
@param Character Data type of a character
@param Traits How to handle characters
*/
template<class Character, class Traits = std::char_traits<Character> >
class basic_zstreambuf : public std::basic_streambuf<Character, Traits> {
public:
typedef typename std::basic_streambuf<Character, Traits>::int_type int_type;
typedef typename std::basic_streambuf<Character, Traits>::char_type char_type;
enum {
BUFFER_SIZE = 64,
PUT_BACK_SIZE = 16
};
/// Constructor
basic_zstreambuf(ZippedFile &File, std::ios_base::openmode mode) :
m_File(File),
m_bBinary((mode & std::ios_base::binary) != 0) {
setg(0, 0, 0);
}
/// Destructor
virtual ~basic_zstreambuf() {}
protected:
int_type pbackfail(int_type character) {
if(eback() != gptr()) {
gbump(-1);
if(!traits_type::eq_int_type(traits_type::eof(), character))
*(gptr()) = traits_type::to_char_type(character);
return traits_type::not_eof(character);
} else {
return traits_type::eof();
}
}
int_type underflow() {
if(fillReadBuffer() > 0)
return sgetc();
else
return traits_type::eof();
}
private:
/// Private copy constructor
basic_zstreambuf(const basic_zstreambuf &);
/// Private assignment operator
basic_zstreambuf &operator =(const basic_zstreambuf &);
/// Translates newline characters from windows text files
static inline unsigned int toTextMode(char* buffer, unsigned int size) {
unsigned int newSize(size);
// Win32-only: Convert newline characters
#ifdef ZIPEX_WIN32
char *source = buffer;
char *destination = buffer;
char *end = buffer+size;
while(source < end) {
if(*source == '\r' && *(source+1) == '\n') {
++source;
--newSize;
}
if(destination != source)
*destination = *source;
++destination;
++source;
}
#endif // _WIN32
return newSize;
}
/// Loads new data into the read buffer
int fillReadBuffer() {
unsigned int putBackSize = 0;
if(eback() != 0) {
putBackSize = std::min(unsigned int(PUT_BACK_SIZE), unsigned int(gptr()-eback()));
memmove(m_pReadBuffer, gptr() - putBackSize, putBackSize);
}
char_type *begin = m_pReadBuffer + putBackSize;
std::size_t readBytes = m_File.readData(begin, (BUFFER_SIZE - putBackSize) * sizeof(char_type));
if(readBytes > 0) {
if(!m_bBinary)
readBytes = toTextMode(begin, readBytes);
setg(begin, begin, begin + readBytes);
}
return readBytes;
}
ZippedFile &m_File;
char_type m_pReadBuffer[BUFFER_SIZE];
bool m_bBinary;
};
typedef basic_zstreambuf<char> zstreambuf;
typedef basic_zstreambuf<wchar_t> wzstreambuf;
// //
// Zipex::basic_izstream //
// //
/// Zipped stream
/** Implementation of a zipped istream
@param Character Data type of a character
@param Traits How to handle characters
*/
template<class Character, class Traits = std::char_traits<Character> >
class basic_izstream :
public std::basic_istream<Character, Traits> {
public:
/// Constructor
/** Initializes an izstream reading from a zipped file
@param File File from which to read
@param mode Mode in which to open the file
*/
basic_izstream(ZippedFile &File,
std::ios_base::openmode mode = std::ios_base::in) :
std::basic_istream<Character, Traits>(0),
m_spBuffer(new basic_zstreambuf<Character, Traits>(File, mode)) {
init(m_spBuffer.get());
}
/// Constructor
/** Initializes an izstream, opening a zip archive and then
accessing a zipped file in the archive
@param pszFilename Filename of the zip archive
@param pszZippedFile Zipped file to read from
@param mode Mode in which to open the file
*/
basic_izstream(const char *pszFilename, const char *pszZippedFile,
std::ios_base::openmode mode = std::ios_base::in) :
std::basic_istream<Character, Traits>(0),
m_spArchive(new ZipArchive(pszFilename)) {
m_spBuffer.reset(new basic_zstreambuf<Character, Traits>(
m_spArchive->getFile(pszZippedFile), mode
));
init(m_spBuffer.get());
}
private:
std::auto_ptr<ZipArchive> m_spArchive;
std::auto_ptr<basic_zstreambuf<Character, Traits> > m_spBuffer;
};
typedef basic_izstream<char> izstream;
typedef basic_izstream<wchar_t> wizstream;
} // namespace Zipex
#endif // ZIPEX_ZSTREAM_H
| [
"ctuoMail@5f320639-c338-0410-82ad-c55551ec1e38"
]
| [
[
[
1,
184
]
]
]
|
9ff28782918dbca09754c05616a72ba810528b96 | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /Common/Com/ScdSlv/ScdSolver.cpp | 8510c3680431134652e10689f6c99e3a8997ad53 | []
| no_license | abcweizhuo/Test3 | 0f3379e528a543c0d43aad09489b2444a2e0f86d | 128a4edcf9a93d36a45e5585b70dee75e4502db4 | refs/heads/master | 2021-01-17T01:59:39.357645 | 2008-08-20T00:00:29 | 2008-08-20T00:00:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,371 | cpp | // ScdSolver.cpp : Implementation of CScdSolver
#include "stdafx.h"
#include "ScdSlv.h"
#include "ScdSolver.h"
#include "ScdNodes.h"
#include "sfe_srvr.h"
#include ".\scdsolver.h"
#include "licbase.h"
#include "scdslvwrap.h"
//#include "sfe_clnt.h"
/////////////////////////////////////////////////////////////////////////////
// CScdSolver
HRESULT CScdSolver::FinalConstruct()
{
FC_TESTLICENSE(gs_License.AllowCOMSlv());
//FC_ROF(CoCreateFreeThreadedMarshaler(GetControllingUnknown(), &m_pUnkMarshaler.p));
//FC_ROF(m_pMsgs.CoCreateInstance(CLSID_ScdMessages));
FC_ROF(m_pSpecieDefns.CoCreateInstance(CLSID_ScdSpecieDefns));
FC_ROF(m_pDebug.CoCreateInstance(CLSID_ScdDebug));
FC_ROF(m_pTest.CoCreateInstance(CLSID_ScdTest));
FC_ROF(m_pMTags.CoCreateInstance(CLSID_ScdSlvTags));
//FC_ROF(m_pNodes.CoCreateInstance(CLSID_ScdNodes));
//FC_ROF(m_pUnits.CoCreateInstance(CLSID_ScdUnits));
//FC_ROF(m_pLinks.CoCreateInstance(CLSID_ScdLinks));
FC_ROF(m_pProbal.CoCreateInstance(CLSID_ScdProbal));
FC_ROF(m_pDynamic.CoCreateInstance(CLSID_ScdDynamic));
//AddChildEvents(m_pNodes.p);
//AddChildEvents(m_pUnits.p);
//AddChildEvents(m_pLinks.p);
AddChildEvents(m_pProbal.p);
AddChildEvents(m_pDynamic.p);
return m_SlvWrap.FinalConstruct();
}
void CScdSolver::FinalRelease()
{
m_pTest.Release();
m_pDebug.Release();
//m_pSolver.Release();
m_pSpecieDefns.Release();
//m_pMsgs.Release();
m_SlvWrap.FinalRelease();
//m_pUnkMarshaler.Release();
m_pMTags.Release();
//m_pNodes.Release();
//m_pUnits.Release();
//m_pLinks.Release();
m_pProbal.Release();
m_pDynamic.Release();
}
STDMETHODIMP CScdSolver::InterfaceSupportsErrorInfo(REFIID riid)
{
static const IID* arr[] =
{
&IID_IScdSolver,
&IID_IScdTest,
};
for (int i=0; i < sizeof(arr) / sizeof(arr[0]); i++)
{
if (InlineIsEqualGUID(*arr[i],riid))
return S_OK;
}
return S_FALSE;
}
void CScdSolver::FireTheEvent(long Evt, long Data)
{
switch (Evt)
{
case ComCmd_NULL : /*Fire_On...*/ ; break;
};
};
STDMETHODIMP CScdSolver::InitialiseCfg(BSTR CfgFileName)
{
dllSCD_COMENTRY(long)
{
if (!m_SlvWrap.InitialiseCfg(CfgFileName))
return E_FAIL;
}
SCD_COMEXIT
}
STDMETHODIMP CScdSolver::InitialiseDB(BSTR DBFileName, SAFEARRAY *parrSpecies)
{
dllSCD_COMENTRY(long)
{
}
SCD_COMEXIT
}
STDMETHODIMP CScdSolver::get_Messages(/*[out, retval]*/ IScdMessages**pVal)
{
dllSCD_COMENTRYGET(long, pVal)
{
//Scd.ReturnH(m_pMsgs.CopyTo(pVal));
IScdMessages * p;
::CoCreateInstance(CLSID_ScdMessages, NULL, CLSCTX_ALL, IID_IScdMessages, (void**)&p);
//p->SetObjectInfo(eWhatNodes_All, (DWORD)NULL, eScdNodeType_All, eScdDirection_All);
*pVal=p;
}
SCD_COMEXIT
};
STDMETHODIMP CScdSolver::get_SpecieDefns(/*[out, retval]*/ IScdSpecieDefns**pVal)
{
dllSCD_COMENTRYGET(long, pVal)
{
Scd.ReturnH(m_pSpecieDefns.CopyTo(pVal));
}
SCD_COMEXIT
};
STDMETHODIMP CScdSolver::get_Conversions(IScdConversion ** pVal)
{
dllSCD_COMENTRYGET(long, pVal)
{
IScdConversion * p;
::CoCreateInstance(CLSID_ScdConversions, NULL, CLSCTX_ALL, IID_IScdConversions, (void**)&p);
//p->SetObjectInfo(eWhatNodes_All, (DWORD)NULL, eScdNodeType_All, eScdDirection_All);
*pVal=p;
}
SCD_COMEXIT
};
STDMETHODIMP CScdSolver::get_Tags(/*[out, retval]*/ IScdSlvTags**pVal)
{
dllSCD_COMENTRYGET(long, pVal)
{
Scd.ReturnH(m_pMTags.CopyTo(pVal));
}
SCD_COMEXIT
};
STDMETHODIMP CScdSolver::get_Debug(/*[out, retval]*/ IScdDebug**pVal)
{
dllSCD_COMENTRYGET(long, pVal)
{
Scd.ReturnH(m_pDebug.CopyTo(pVal));
}
SCD_COMEXIT
};
STDMETHODIMP CScdSolver::get_Test(/*[out, retval]*/ IScdTest**pVal)
{
dllSCD_COMENTRYGET(long, pVal)
{
Scd.ReturnH(m_pTest.CopyTo(pVal));
}
SCD_COMEXIT
};
//STDMETHODIMP CScdSolver::get_Units(IScdUnits **pUnits)
// {
// dllSCD_COMENTRYGET(long, pUnits)
// {
// Scd.ReturnH(m_pUnits.CopyTo(pUnits));
// }
// SCD_COMEXIT
// };
//
//STDMETHODIMP CScdSolver::get_Links(IScdLinks **pLinks)
// {
// dllSCD_COMENTRYGET(long, pLinks)
// {
// Scd.ReturnH(m_pLinks.CopyTo(pLinks));
// }
// SCD_COMEXIT
// };
STDMETHODIMP CScdSolver::get_Nodes(eScdNodeTypes eType, IScdNodes **pNodes)
{
dllSCD_COMENTRYGET(long, pNodes)
{
//Scd.ReturnH(m_pNodes.CopyTo(pNodes));
IScdNodes * p;
::CoCreateInstance(CLSID_ScdNodes, NULL, CLSCTX_ALL, IID_IScdNodes, (void**)&p);
p->SetObjectInfo(eWhatNodes_All, (DWORD)NULL, eType, eScdDirection_All);
*pNodes=p;
}
SCD_COMEXIT
};
STDMETHODIMP CScdSolver::get_Probal(IScdProbal **pVal)
{
dllSCD_COMENTRYGET(long, pVal)
{
Scd.ReturnH(m_pProbal.CopyTo(pVal));
}
SCD_COMEXIT
};
STDMETHODIMP CScdSolver::get_Dynamic(IScdDynamic **pVal)
{
dllSCD_COMENTRYGET(long, pVal)
{
Scd.ReturnH(m_pDynamic.CopyTo(pVal));
}
SCD_COMEXIT
};
STDMETHODIMP CScdSolver::CreateSpModel(BSTR ProgID, IScdTaggedObject **pModel)
{
dllSCD_COMENTRYGET(long, pModel)
{
CLSID clsid;
if (SUCCEEDED(CLSIDFromProgID(ProgID, &clsid)))
{
return Scd.ReturnH(::CoCreateInstance(clsid, NULL, CLSCTX_ALL, IID_IScdTaggedObject, (void**)pModel));
};
return Scd.ReturnH(E_FAIL);
}
SCD_COMEXIT
};
STDMETHODIMP CScdSolver::CollectEvalSequenceInfo(eScdEvalSeq_Options eReqdSeq, long * ItemCount)
{
dllSCD_COMENTRY(long)
{
if (!gs_pSfeSrvr)
return Scd.ReturnH(E_FAIL);
m_SeqOptions=eReqdSeq;
*ItemCount=gs_pSfeSrvr->FE_GetEvalOrder( (eReqdSeq&eScdEvalSeq_Control)!=0,
(eReqdSeq&eScdEvalSeq_FullDesc)!=0,
(eReqdSeq&eScdEvalSeq_FullDesc)!=0,
TV_None, m_SeqInfo);
}
SCD_COMEXIT
};
STDMETHODIMP CScdSolver::GetEvalSequenceItem(long Index, BSTR *Tag, BSTR *Class, long *IOCOunt)
{
dllSCD_COMENTRY(long)
{
if (Index<1 || Index>m_SeqInfo.GetSize())
return Scd.ReturnH(E_INVALIDARG);
CEvalOrderItem & Itm=m_SeqInfo[Index-1];
_bstr_t s(Itm.m_sTag());
*Tag=s.copy();
Strng ClassId;
flag b = gs_pSfeSrvr->RequestModelClassId(Itm.m_sTag(), ClassId);
_bstr_t s1(ClassId());
*Class=s1.copy();
*IOCOunt=Itm.m_FIOs.GetSize()+Itm.m_CIOs.GetSize()+Itm.m_XIOs.GetSize();
}
SCD_COMEXIT
};
STDMETHODIMP CScdSolver::GetEvalSequenceIOItem(long Index, long IOItem, eScdEvalSeqIO_Class *eClass, eScdEvalSeqIO_Flags *eFlags, long * RemoteIndex, BSTR * RemoteDesc)
{
dllSCD_COMENTRY(long)
{
if (Index<1 || Index>m_SeqInfo.GetSize())
return Scd.ReturnH(E_INVALIDARG);
CEvalOrderItem & Itm=m_SeqInfo[Index-1];
IOItem--;
if (IOItem<0)
Scd.ReturnH(E_INVALIDARG);
CEvalOrderIOItem *pIOItm=NULL;
if (IOItem<Itm.m_FIOs.GetSize())
{
pIOItm=&Itm.m_FIOs[IOItem];
}
else
{
IOItem-=Itm.m_FIOs.GetSize();
if (IOItem<Itm.m_CIOs.GetSize())
{
pIOItm=&Itm.m_CIOs[IOItem];
}
else
{
IOItem-=Itm.m_CIOs.GetSize();
if (IOItem<Itm.m_XIOs.GetSize())
{
pIOItm=&Itm.m_XIOs[IOItem];
}
else
return Scd.ReturnH(E_INVALIDARG);
}
}
dword Flgs=0;
if (pIOItm->m_bIn) Flgs|= eScdEvalSeqIOFlags_In;
if (pIOItm->m_bOut) Flgs|= eScdEvalSeqIOFlags_Out;
if (pIOItm->m_bTear) Flgs|= eScdEvalSeqIOFlags_Tear;
if (pIOItm->m_bOwner) Flgs|= eScdEvalSeqIOFlags_Owner;
*eFlags = (eScdEvalSeqIO_Flags)Flgs;
*eClass = (eScdEvalSeqIO_Class)pIOItm->m_dwType;
//eScdEvalSeqIO_Flags eFlags;
*RemoteIndex=m_SeqOptions&eScdEvalSeq_Control ? pIOItm->m_lRmtCtrlOrd : pIOItm->m_lRmtProcOrd;
_bstr_t s(pIOItm->m_sRmtTag());
*RemoteDesc=s.copy();
}
SCD_COMEXIT
};
STDMETHODIMP CScdSolver::get_RunMode(eScdMode *pVal)
{
dllSCD_COMENTRYGET(long, pVal)
{
*pVal=(eScdMode)( DefNetMode() | DefNodeSolveMode() | DefHeatMode() | DefFlowMode() );
}
SCD_COMEXIT
};
STDMETHODIMP CScdSolver::put_RunMode(eScdMode newVal)
{
dllSCD_COMENTRY(long)
{
if (newVal&NM_All) SetDefNetMode(newVal);
if (newVal&SM_All) SetDefNodeMode(newVal);
if (newVal&HM_All) SetDefHeatMode(newVal);
if (newVal&LFM_All) SetDefFlowMode(newVal);
}
SCD_COMEXIT
};
STDMETHODIMP CScdSolver::get_Time(eScdTimeFormat Fmt, VARIANT * pVal)
{
dllSCD_COMENTRYGET(long, pVal)
{
switch (Fmt)
{
case eScdTimeFmt_Seconds:
case eScdTimeFmt_Secs1970:
pVal->vt=VT_R8;
pVal->dblVal=gs_Exec.TheTime.Seconds;
break;
case eScdTimeFmt_Date1900:
SecsToDate1900Var(gs_Exec.TheTime/*.Seconds*/, pVal);
break;
default:
DoBreak();
break;
}
}
SCD_COMEXIT
}
STDMETHODIMP CScdSolver::put_Time(eScdTimeFormat Fmt, VARIANT newVal)
{
dllSCD_COMENTRY(long)
{
VARIANT T;
VariantInit(&T);
switch (Fmt)
{
case eScdTimeFmt_Seconds:
case eScdTimeFmt_Secs1970:
{
HRESULT hr=VariantChangeType(&T, &newVal, 0, VT_R8);
if (SUCCEEDED(hr))
gs_Exec.SetTheTime(T.dblVal, "ScdSolver", true);
else
Scd.ReturnH(hr);
break;
}
case eScdTimeFmt_Date1900:
{
HRESULT hr=VariantChangeType(&T, &newVal, 0, VT_DATE);
if (SUCCEEDED(hr))
{
CTimeValue RqdTime;
if (Date1900VarToSecs(T, &RqdTime))
{
gs_Exec.SetTheTime(RqdTime, "ScdSolver", true);
}
//else
// Scd.ReturnH(?hr);
}
else
Scd.ReturnH(hr);
break;
}
default:
DoBreak();
break;
}
VariantClear(&T);
}
SCD_COMEXIT
}
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
316
],
[
318,
325
],
[
330,
342
],
[
344,
345
],
[
347,
368
],
[
370,
378
],
[
380,
381
],
[
383,
399
]
],
[
[
317,
317
],
[
326,
329
],
[
343,
343
],
[
346,
346
],
[
369,
369
],
[
379,
379
],
[
382,
382
]
]
]
|
8d2b4aa2c82976fef769b0d8324c84470c354349 | 580738f96494d426d6e5973c5b3493026caf8b6a | /Include/Vcl/system.hpp | c5f07da8775cf0940bbfab4b18f605ccc701b9cc | []
| no_license | bravesoftdz/cbuilder-vcl | 6b460b4d535d17c309560352479b437d99383d4b | 7b91ef1602681e094a6a7769ebb65ffd6f291c59 | refs/heads/master | 2021-01-10T14:21:03.726693 | 2010-01-11T11:23:45 | 2010-01-11T11:23:45 | 48,485,606 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 13,006 | hpp | // Borland C++ Builder
// Copyright (c) 1995, 2002 by Borland Software Corporation
// All rights reserved
// (DO NOT EDIT: machine generated header) 'System.pas' rev: 6.00
#ifndef SystemHPP
#define SystemHPP
#pragma delphiheader begin
#pragma option push -w-
#pragma option push -Vx
#include <sysmac.H> // system macros
//-- user supplied -----------------------------------------------------------
namespace System
{
//-- type declarations -------------------------------------------------------
//-- var, const, procedure ---------------------------------------------------
static const bool False = false;
static const bool True = true;
static const int MaxInt = 0x7fffffff;
static const int MaxLongint = 0x7fffffff;
#define RTLVersion (1.420000E+01)
static const Shortint varEmpty = 0x0;
static const Shortint varNull = 0x1;
static const Shortint varSmallint = 0x2;
static const Shortint varInteger = 0x3;
static const Shortint varSingle = 0x4;
static const Shortint varDouble = 0x5;
static const Shortint varCurrency = 0x6;
static const Shortint varDate = 0x7;
static const Shortint varOleStr = 0x8;
static const Shortint varDispatch = 0x9;
static const Shortint varError = 0xa;
static const Shortint varBoolean = 0xb;
static const Shortint varVariant = 0xc;
static const Shortint varUnknown = 0xd;
static const Shortint varShortInt = 0x10;
static const Shortint varByte = 0x11;
static const Shortint varWord = 0x12;
static const Shortint varLongWord = 0x13;
static const Shortint varInt64 = 0x14;
static const Shortint varStrArg = 0x48;
static const Word varString = 0x100;
static const Word varAny = 0x101;
static const Word varTypeMask = 0xfff;
static const Word varArray = 0x2000;
static const Word varByRef = 0x4000;
static const Shortint vtInteger = 0x0;
static const Shortint vtBoolean = 0x1;
static const Shortint vtChar = 0x2;
static const Shortint vtExtended = 0x3;
static const Shortint vtString = 0x4;
static const Shortint vtPointer = 0x5;
static const Shortint vtPChar = 0x6;
static const Shortint vtObject = 0x7;
static const Shortint vtClass = 0x8;
static const Shortint vtWideChar = 0x9;
static const Shortint vtPWideChar = 0xa;
static const Shortint vtAnsiString = 0xb;
static const Shortint vtCurrency = 0xc;
static const Shortint vtVariant = 0xd;
static const Shortint vtInterface = 0xe;
static const Shortint vtWideString = 0xf;
static const Shortint vtInt64 = 0x10;
static const Shortint vmtSelfPtr = 0xffffffb4;
static const Shortint vmtIntfTable = 0xffffffb8;
static const Shortint vmtAutoTable = 0xffffffbc;
static const Shortint vmtInitTable = 0xffffffc0;
static const Shortint vmtTypeInfo = 0xffffffc4;
static const Shortint vmtFieldTable = 0xffffffc8;
static const Shortint vmtMethodTable = 0xffffffcc;
static const Shortint vmtDynamicTable = 0xffffffd0;
static const Shortint vmtClassName = 0xffffffd4;
static const Shortint vmtInstanceSize = 0xffffffd8;
static const Shortint vmtParent = 0xffffffdc;
static const Shortint vmtSafeCallException = 0xffffffe0;
static const Shortint vmtAfterConstruction = 0xffffffe4;
static const Shortint vmtBeforeDestruction = 0xffffffe8;
static const Shortint vmtDispatch = 0xffffffec;
static const Shortint vmtDefaultHandler = 0xfffffff0;
static const Shortint vmtNewInstance = 0xfffffff4;
static const Shortint vmtFreeInstance = 0xfffffff8;
static const Shortint vmtDestroy = 0xfffffffc;
static const Shortint vmtQueryInterface = 0x0;
static const Shortint vmtAddRef = 0x4;
static const Shortint vmtRelease = 0x8;
static const Shortint vmtCreateObject = 0xc;
static const Shortint opAdd = 0x0;
static const Shortint opSubtract = 0x1;
static const Shortint opMultiply = 0x2;
static const Shortint opDivide = 0x3;
static const Shortint opIntDivide = 0x4;
static const Shortint opModulus = 0x5;
static const Shortint opShiftLeft = 0x6;
static const Shortint opShiftRight = 0x7;
static const Shortint opAnd = 0x8;
static const Shortint opOr = 0x9;
static const Shortint opXor = 0xa;
static const Shortint opCompare = 0xb;
static const Shortint opNegate = 0xc;
static const Shortint opNot = 0xd;
static const Shortint opCmpEQ = 0xe;
static const Shortint opCmpNE = 0xf;
static const Shortint opCmpLT = 0x10;
static const Shortint opCmpLE = 0x11;
static const Shortint opCmpGT = 0x12;
static const Shortint opCmpGE = 0x13;
extern PACKAGE void *DispCallByIDProc;
extern PACKAGE void *ExceptProc;
extern PACKAGE void __fastcall (*ErrorProc)(Byte ErrorCode, void * ErrorAddr);
extern PACKAGE void *ExceptClsProc;
extern PACKAGE void *ExceptObjProc;
extern PACKAGE void *RaiseExceptionProc;
extern PACKAGE void *RTLUnwindProc;
extern PACKAGE TMetaClass*ExceptionClass;
extern PACKAGE TSafeCallErrorProc SafeCallErrorProc;
extern PACKAGE TAssertErrorProc AssertErrorProc;
extern PACKAGE void __fastcall (*ExitProcessProc)(void);
extern PACKAGE void __fastcall (*AbstractErrorProc)(void);
extern PACKAGE unsigned HPrevInst;
extern PACKAGE HINSTANCE MainInstance;
extern PACKAGE unsigned MainThreadID;
extern PACKAGE bool IsLibrary;
extern PACKAGE int CmdShow;
extern PACKAGE char *CmdLine;
extern PACKAGE void *InitProc;
extern PACKAGE int ExitCode;
extern PACKAGE void *ExitProc;
extern PACKAGE void *ErrorAddr;
extern PACKAGE int RandSeed;
extern PACKAGE bool IsConsole;
extern PACKAGE bool IsMultiThread;
extern PACKAGE Byte FileMode;
extern PACKAGE Byte Test8086;
extern PACKAGE Byte Test8087;
extern PACKAGE Shortint TestFDIV;
extern PACKAGE TextFile Input;
extern PACKAGE TextFile Output;
extern PACKAGE TextFile ErrOutput;
extern PACKAGE char * *envp;
static const Shortint CPUi386 = 0x2;
static const Shortint CPUi486 = 0x3;
static const Shortint CPUPentium = 0x4;
extern PACKAGE Word Default8087CW;
extern PACKAGE Word HeapAllocFlags;
extern PACKAGE Byte DebugHook;
extern PACKAGE Byte JITEnable;
extern PACKAGE bool NoErrMsg;
extern PACKAGE TTextLineBreakStyle DefaultTextLineBreakStyle;
#define sLineBreak "\r\n"
extern PACKAGE int AllocMemCount;
extern PACKAGE int AllocMemSize;
static const Word fmClosed = 0xd7b0;
static const Word fmInput = 0xd7b1;
static const Word fmOutput = 0xd7b2;
static const Word fmInOut = 0xd7b3;
static const Shortint tfCRLF = 0x1;
extern PACKAGE TLibModule *LibModuleList;
extern PACKAGE TModuleUnloadRec *ModuleUnloadList;
extern PACKAGE void __fastcall TextStart(void);
extern "C" void __stdcall SetLastError(int ErrorCode);
extern PACKAGE void * __fastcall SysGetMem(int Size);
extern PACKAGE int __fastcall SysFreeMem(void * P);
extern PACKAGE void * __fastcall SysReallocMem(void * P, int Size);
extern PACKAGE THeapStatus __fastcall GetHeapStatus();
extern PACKAGE void __fastcall GetMemoryManager(TMemoryManager &MemMgr);
extern PACKAGE void __fastcall SetMemoryManager(const TMemoryManager &MemMgr);
extern PACKAGE bool __fastcall IsMemoryManagerSet(void);
extern PACKAGE TObject* __fastcall ExceptObject(void);
extern PACKAGE void * __fastcall ExceptAddr(void);
extern PACKAGE void * __fastcall AcquireExceptionObject(void);
extern PACKAGE void __fastcall ReleaseExceptionObject(void);
extern PACKAGE void * __fastcall RaiseList(void);
extern PACKAGE void * __fastcall SetRaiseList(void * NewPtr);
extern PACKAGE void __fastcall SetInOutRes(int NewValue);
extern PACKAGE void __fastcall ChDir(const AnsiString S)/* overload */;
extern PACKAGE void __fastcall ChDir(char * P)/* overload */;
extern PACKAGE int __fastcall IOResult(void);
extern PACKAGE void __fastcall MkDir(const AnsiString S)/* overload */;
extern PACKAGE void __fastcall MkDir(char * P)/* overload */;
extern PACKAGE void __fastcall Move(const void *Source, void *Dest, int Count);
extern PACKAGE int __fastcall ParamCount(void);
extern PACKAGE AnsiString __fastcall ParamStr(int Index);
extern PACKAGE void __fastcall Randomize(void);
extern PACKAGE void __fastcall RmDir(const AnsiString S)/* overload */;
extern PACKAGE void __fastcall RmDir(char * P)/* overload */;
extern PACKAGE char __fastcall UpCase(char Ch);
extern PACKAGE void __fastcall Set8087CW(Word NewCW);
extern PACKAGE Word __fastcall Get8087CW(void);
extern PACKAGE int __fastcall Flush(TextFile &t);
extern PACKAGE void __fastcall Mark(void);
extern PACKAGE void __fastcall Release(void);
extern PACKAGE void __fastcall FPower10(void);
extern PACKAGE int __fastcall BeginThread(void * SecurityAttributes, unsigned StackSize, TThreadFunc ThreadFunc, void * Parameter, unsigned CreationFlags, unsigned &ThreadId);
extern PACKAGE void __fastcall EndThread(int ExitCode);
extern PACKAGE void __fastcall UniqueString(AnsiString &str)/* overload */;
extern PACKAGE void __fastcall UniqueString(WideString &str)/* overload */;
extern PACKAGE AnsiString __fastcall WideCharToString(wchar_t * Source);
extern PACKAGE AnsiString __fastcall WideCharLenToString(wchar_t * Source, int SourceLen);
extern PACKAGE void __fastcall WideCharToStrVar(wchar_t * Source, AnsiString &Dest);
extern PACKAGE void __fastcall WideCharLenToStrVar(wchar_t * Source, int SourceLen, AnsiString &Dest);
extern PACKAGE wchar_t * __fastcall StringToWideChar(const AnsiString Source, wchar_t * Dest, int DestSize);
extern PACKAGE AnsiString __fastcall OleStrToString(wchar_t * Source);
extern PACKAGE void __fastcall OleStrToStrVar(wchar_t * Source, AnsiString &Dest);
extern PACKAGE wchar_t * __fastcall StringToOleStr(const AnsiString Source);
extern PACKAGE void __fastcall GetVariantManager(TVariantManager &VarMgr);
extern PACKAGE void __fastcall SetVariantManager(const TVariantManager &VarMgr);
extern PACKAGE bool __fastcall IsVariantManagerSet(void);
extern PACKAGE void __fastcall DynArrayClear(void * &a, void * typeInfo);
extern PACKAGE void __fastcall DynArraySetLength(void * &a, void * typeInfo, int dimCnt, PLongint lengthVec);
extern PACKAGE unsigned __fastcall FindHInstance(void * Address);
extern PACKAGE unsigned __fastcall FindClassHInstance(TMetaClass* ClassType);
extern PACKAGE unsigned __fastcall FindResourceHInstance(unsigned Instance);
extern PACKAGE unsigned __fastcall LoadResourceModule(char * ModuleName, bool CheckOwner = true);
extern PACKAGE void __fastcall EnumModules(TEnumModuleFunc Func, void * Data)/* overload */;
extern PACKAGE void __fastcall EnumResourceModules(TEnumModuleFunc Func, void * Data)/* overload */;
extern PACKAGE void __fastcall EnumModules(TEnumModuleFuncLW Func, void * Data)/* overload */;
extern PACKAGE void __fastcall EnumResourceModules(TEnumModuleFuncLW Func, void * Data)/* overload */;
extern PACKAGE void __fastcall AddModuleUnloadProc(TModuleUnloadProc Proc)/* overload */;
extern PACKAGE void __fastcall RemoveModuleUnloadProc(TModuleUnloadProc Proc)/* overload */;
extern PACKAGE void __fastcall AddModuleUnloadProc(TModuleUnloadProcLW Proc)/* overload */;
extern PACKAGE void __fastcall RemoveModuleUnloadProc(TModuleUnloadProcLW Proc)/* overload */;
extern PACKAGE void __fastcall RegisterModule(PLibModule LibModule);
extern PACKAGE void __fastcall UnregisterModule(PLibModule LibModule);
extern PACKAGE double __cdecl CompToDouble(Comp Value);
extern PACKAGE void __cdecl DoubleToComp(double Value, Comp &Result);
extern PACKAGE Currency __cdecl CompToCurrency(Comp Value);
extern PACKAGE void __cdecl CurrencyToComp(Currency Value, Comp &Result);
extern PACKAGE void * __cdecl GetMemory(int Size);
extern PACKAGE int __cdecl FreeMemory(void * P);
extern PACKAGE void * __cdecl ReallocMemory(void * P, int Size);
extern PACKAGE void __fastcall SetLineBreakStyle(TextFile &T, TTextLineBreakStyle Style);
extern PACKAGE int __fastcall UnicodeToUtf8(char * Dest, wchar_t * Source, int MaxBytes)/* overload */;
extern PACKAGE unsigned __fastcall UnicodeToUtf8(char * Dest, unsigned MaxDestBytes, wchar_t * Source, unsigned SourceChars)/* overload */;
extern PACKAGE int __fastcall Utf8ToUnicode(wchar_t * Dest, char * Source, int MaxChars)/* overload */;
extern PACKAGE unsigned __fastcall Utf8ToUnicode(wchar_t * Dest, unsigned MaxDestChars, char * Source, unsigned SourceBytes)/* overload */;
extern PACKAGE AnsiString __fastcall UTF8Encode(const WideString WS);
extern PACKAGE WideString __fastcall UTF8Decode(const AnsiString S);
extern PACKAGE AnsiString __fastcall AnsiToUtf8(const AnsiString S);
extern PACKAGE AnsiString __fastcall Utf8ToAnsi(const AnsiString S);
extern PACKAGE AnsiString __fastcall LoadResString(PResStringRec ResStringRec);
extern PACKAGE PUCS4Char __fastcall PUCS4Chars(const UCS4String S);
extern PACKAGE UCS4String __fastcall WideStringToUCS4String(const WideString S);
extern PACKAGE WideString __fastcall UCS4StringToWideString(const UCS4String S);
} /* namespace System */
using namespace System;
#include <sysclass.H> // system class definitions
#pragma option pop // -w-
#pragma option pop // -Vx
#pragma delphiheader end.
//-- end unit ----------------------------------------------------------------
#endif // System
| [
"bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b"
]
| [
[
[
1,
257
]
]
]
|
da6c82e7584aaa57deb004306ba6d556afd4f88e | 36d0ddb69764f39c440089ecebd10d7df14f75f3 | /プログラム/Ngllib/include/Ngl/Line3.h | 04dda3cef923833ef7b3e687406e74d652eb0f27 | []
| 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 | 4,226 | h | /*******************************************************************************/
/**
* @file Line3.h.
*
* @brief 3次元線分構造体ヘッダファイル.
*
* @date 2008/07/12.
*
* @version 2.00.
*
* @author Kentarou Nishimura.
*/
/******************************************************************************/
#ifndef _NGL_LINE_H_
#define _NGL_LINE_H_
#include "Vector3.h"
#ifdef __cplusplus
#include "CollisionReport.h"
namespace Ngl{
#endif
/**
* @struct Line3.
* @brief 3次元線分構造体.
*/
typedef struct Line3
{
/** 始点座標 */
Vector3 begin;
/** 終点座標 */
Vector3 end;
#ifdef __cplusplus
/*=========================================================================*/
/**
* @brief コンストラクタ
*
* @param[in] なし.
*/
Line3();
/*=========================================================================*/
/**
* @brief コンストラクタ
*
* @param[in] Begin 開始位置3D座標.
* @param[in] End 終了位置3D座標.
*/
Line3( const Vector3& Begin, const Vector3& End );
/*=========================================================================*/
/**
* @brief コンストラクタ
*
* @param[in] Begin 開始位置座標配列.
* @param[in] End 終了位置座標配列.
*/
Line3( const float* Begin, const float* End );
/*=========================================================================*/
/**
* @brief 初期化する
*
* @param[in] x 始点x座標.
* @param[in] y 始点y座標.
* @param[in] z 始点z座標.
* @param[in] eX 終点x座標.
* @param[in] eY 終点y座標.
* @param[in] eZ 終点z座標.
* @return なし.
*/
void initialize( float x, float y, float z, float eX, float eY, float eZ );
/*=========================================================================*/
/**
* @brief 初期化する
*
* @param[in] Begin 開始位置3D座標.
* @param[in] End 終了位置3D座標.
* @return なし.
*/
void initialize( const Vector3& Begin, const Vector3& End );
/*=========================================================================*/
/**
* @brief 線分のベクトルを求める
*
* @param[in] なし.
* @return 線分のベクトル.
*/
Vector3 getVector();
/*=========================================================================*/
/**
* @brief 3D線分との衝突判定
*
* @param[in] otherBegin 判定する3D線分の始点座標.
* @param[in] otherEnd 判定する3D線分の終点座標.
* @param[in] epsilon 判定の閾値.
* @return 衝突判定結果構造体.
*/
const LineCollisionReport& collision( const Vector3& otherBegin, const Vector3& otherEnd, float epsilon );
/*=========================================================================*/
/**
* @brief 3D線分との衝突判定
*
* @param[in] other 判定する3D線分.
* @param[in] epsilon 判定の閾値.
* @return 衝突判定結果構造体.
*/
const LineCollisionReport& collision( const Line3& other, float epsilon );
/*=========================================================================*/
/**
* @brief 線分と、指定座標の最も隣接する線分上の座標パラメータを求める
*
* @param[in] x, 求める座標のx座標.
* @param[in] y, 求める座標のy座標.
* @param[in] z, 求める座標のz座標.
* @return 座標パラメータ.
*/
float getNearestPointParameter( float x, float y, float z );
/*=========================================================================*/
/**
* @brief 線分と、指定座標に最も隣接する線分上の座標を求める
*
* @param[in] x, 求める座標のx座標.
* @param[in] y, 求める座標のy座標.
* @param[in] z, 求める座標のz座標.
* @return 最も隣接する座標.
*/
Vector3 findNearestPoint( float x, float y, float z );
#endif
} NGLline3;
#ifdef __cplusplus
} // namespace Ngl
#endif
#endif
/*===== EOF ==================================================================*/ | [
"rs.drip@aa49b5b2-a402-11dd-98aa-2b35b7097d33"
]
| [
[
[
1,
165
]
]
]
|
7f229d13fa246eaa034e7da532e7a993e41b1dce | 57855d23617d6a65298c2ae3485ba611c51809eb | /Zen/Core/Utility/src/EnvironmentHandler.cpp | 2d3d58623707c06ee2a2a174aca25f7f19630ed3 | []
| no_license | Azaezel/quillus-daemos | 7ff4261320c29e0125843b7da39b7b53db685cd5 | 8ee6eac886d831eec3acfc02f03c3ecf78cc841f | refs/heads/master | 2021-01-01T20:35:04.863253 | 2011-04-08T13:46:40 | 2011-04-08T13:46:40 | 32,132,616 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,101 | cpp | //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
// Zen Core Framework
//
// Copyright (C) 2001 - 2009 Tony Richards
// Copyright (C) 2008 Steen Rasmussen
//
// 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.
//
// Steen Rasmussen [email protected]
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
#include "EnvironmentHandler.hpp"
#include <string>
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
namespace Zen {
namespace Utility {
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
EnvironmentHandler::EnvironmentHandler()
{
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
EnvironmentHandler::~EnvironmentHandler()
{
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
void
EnvironmentHandler::appendEnvironment(const Environment_type& _environment)
{
for(Environment_type::const_iterator iter = _environment.begin(); iter != _environment.end(); iter++)
{
m_environment[iter->first] = iter->second;
}
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
void
EnvironmentHandler::setCommandLine(int argc, const char *argv[])
{
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
const std::string&
EnvironmentHandler::getEnvironment(const std::string &_name) const
{
Environment_type::const_iterator iter = m_environment.find(_name);
if(iter == m_environment.end())
{
return m_empty;
}
return iter->second;
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
void
EnvironmentHandler::setEnvironment(const std::string& _name, const std::string& _value)
{
m_environment[_name] = _value;
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
void
EnvironmentHandler::appendHandler(I_EnvironmentHandler& _handler, bool _before)
{
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
} // namespace Utility
} // namespace Zen
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
| [
"sgtflame@Sullivan"
]
| [
[
[
1,
90
]
]
]
|
43872b2ad0a353d86bc1e77f5d7fba01158434b1 | 8aa65aef3daa1a52966b287ffa33a3155e48cc84 | /Source/3rdparty/Bullet/src/BulletDynamics/ConstraintSolver/btSliderConstraint.h | 9357b8fa3f763dd123f2a06b7d7f7613d6b7dfb1 | [
"Zlib",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | jitrc/p3d | da2e63ef4c52ccb70023d64316cbd473f3bd77d9 | b9943c5ee533ddc3a5afa6b92bad15a864e40e1e | refs/heads/master | 2020-04-15T09:09:16.192788 | 2009-06-29T04:45:02 | 2009-06-29T04:45:02 | 37,063,569 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,443 | h | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
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.
*/
/*
Added by Roman Ponomarev ([email protected])
April 04, 2008
TODO:
- add clamping od accumulated impulse to improve stability
- add conversion for ODE constraint solver
*/
#ifndef SLIDER_CONSTRAINT_H
#define SLIDER_CONSTRAINT_H
//-----------------------------------------------------------------------------
#include "LinearMath/btVector3.h"
#include "btJacobianEntry.h"
#include "btTypedConstraint.h"
//-----------------------------------------------------------------------------
class btRigidBody;
//-----------------------------------------------------------------------------
#define SLIDER_CONSTRAINT_DEF_SOFTNESS (btScalar(1.0))
#define SLIDER_CONSTRAINT_DEF_DAMPING (btScalar(1.0))
#define SLIDER_CONSTRAINT_DEF_RESTITUTION (btScalar(0.7))
//-----------------------------------------------------------------------------
class btSliderConstraint : public btTypedConstraint
{
protected:
///for backwards compatibility during the transition to 'getInfo/getInfo2'
bool m_useSolveConstraintObsolete;
btTransform m_frameInA;
btTransform m_frameInB;
// use frameA fo define limits, if true
bool m_useLinearReferenceFrameA;
// linear limits
btScalar m_lowerLinLimit;
btScalar m_upperLinLimit;
// angular limits
btScalar m_lowerAngLimit;
btScalar m_upperAngLimit;
// softness, restitution and damping for different cases
// DirLin - moving inside linear limits
// LimLin - hitting linear limit
// DirAng - moving inside angular limits
// LimAng - hitting angular limit
// OrthoLin, OrthoAng - against constraint axis
btScalar m_softnessDirLin;
btScalar m_restitutionDirLin;
btScalar m_dampingDirLin;
btScalar m_softnessDirAng;
btScalar m_restitutionDirAng;
btScalar m_dampingDirAng;
btScalar m_softnessLimLin;
btScalar m_restitutionLimLin;
btScalar m_dampingLimLin;
btScalar m_softnessLimAng;
btScalar m_restitutionLimAng;
btScalar m_dampingLimAng;
btScalar m_softnessOrthoLin;
btScalar m_restitutionOrthoLin;
btScalar m_dampingOrthoLin;
btScalar m_softnessOrthoAng;
btScalar m_restitutionOrthoAng;
btScalar m_dampingOrthoAng;
// for interlal use
bool m_solveLinLim;
bool m_solveAngLim;
btJacobianEntry m_jacLin[3];
btScalar m_jacLinDiagABInv[3];
btJacobianEntry m_jacAng[3];
btScalar m_timeStep;
btTransform m_calculatedTransformA;
btTransform m_calculatedTransformB;
btVector3 m_sliderAxis;
btVector3 m_realPivotAInW;
btVector3 m_realPivotBInW;
btVector3 m_projPivotInW;
btVector3 m_delta;
btVector3 m_depth;
btVector3 m_relPosA;
btVector3 m_relPosB;
btScalar m_linPos;
btScalar m_angPos;
btScalar m_angDepth;
btScalar m_kAngle;
bool m_poweredLinMotor;
btScalar m_targetLinMotorVelocity;
btScalar m_maxLinMotorForce;
btScalar m_accumulatedLinMotorImpulse;
bool m_poweredAngMotor;
btScalar m_targetAngMotorVelocity;
btScalar m_maxAngMotorForce;
btScalar m_accumulatedAngMotorImpulse;
//------------------------
void initParams();
public:
// constructors
btSliderConstraint(btRigidBody& rbA, btRigidBody& rbB, const btTransform& frameInA, const btTransform& frameInB ,bool useLinearReferenceFrameA);
btSliderConstraint();
// overrides
virtual void buildJacobian();
virtual void getInfo1 (btConstraintInfo1* info);
virtual void getInfo2 (btConstraintInfo2* info);
virtual void solveConstraintObsolete(btSolverBody& bodyA,btSolverBody& bodyB,btScalar timeStep);
// access
const btRigidBody& getRigidBodyA() const { return m_rbA; }
const btRigidBody& getRigidBodyB() const { return m_rbB; }
const btTransform & getCalculatedTransformA() const { return m_calculatedTransformA; }
const btTransform & getCalculatedTransformB() const { return m_calculatedTransformB; }
const btTransform & getFrameOffsetA() const { return m_frameInA; }
const btTransform & getFrameOffsetB() const { return m_frameInB; }
btTransform & getFrameOffsetA() { return m_frameInA; }
btTransform & getFrameOffsetB() { return m_frameInB; }
btScalar getLowerLinLimit() { return m_lowerLinLimit; }
void setLowerLinLimit(btScalar lowerLimit) { m_lowerLinLimit = lowerLimit; }
btScalar getUpperLinLimit() { return m_upperLinLimit; }
void setUpperLinLimit(btScalar upperLimit) { m_upperLinLimit = upperLimit; }
btScalar getLowerAngLimit() { return m_lowerAngLimit; }
void setLowerAngLimit(btScalar lowerLimit) { m_lowerAngLimit = lowerLimit; }
btScalar getUpperAngLimit() { return m_upperAngLimit; }
void setUpperAngLimit(btScalar upperLimit) { m_upperAngLimit = upperLimit; }
bool getUseLinearReferenceFrameA() { return m_useLinearReferenceFrameA; }
btScalar getSoftnessDirLin() { return m_softnessDirLin; }
btScalar getRestitutionDirLin() { return m_restitutionDirLin; }
btScalar getDampingDirLin() { return m_dampingDirLin ; }
btScalar getSoftnessDirAng() { return m_softnessDirAng; }
btScalar getRestitutionDirAng() { return m_restitutionDirAng; }
btScalar getDampingDirAng() { return m_dampingDirAng; }
btScalar getSoftnessLimLin() { return m_softnessLimLin; }
btScalar getRestitutionLimLin() { return m_restitutionLimLin; }
btScalar getDampingLimLin() { return m_dampingLimLin; }
btScalar getSoftnessLimAng() { return m_softnessLimAng; }
btScalar getRestitutionLimAng() { return m_restitutionLimAng; }
btScalar getDampingLimAng() { return m_dampingLimAng; }
btScalar getSoftnessOrthoLin() { return m_softnessOrthoLin; }
btScalar getRestitutionOrthoLin() { return m_restitutionOrthoLin; }
btScalar getDampingOrthoLin() { return m_dampingOrthoLin; }
btScalar getSoftnessOrthoAng() { return m_softnessOrthoAng; }
btScalar getRestitutionOrthoAng() { return m_restitutionOrthoAng; }
btScalar getDampingOrthoAng() { return m_dampingOrthoAng; }
void setSoftnessDirLin(btScalar softnessDirLin) { m_softnessDirLin = softnessDirLin; }
void setRestitutionDirLin(btScalar restitutionDirLin) { m_restitutionDirLin = restitutionDirLin; }
void setDampingDirLin(btScalar dampingDirLin) { m_dampingDirLin = dampingDirLin; }
void setSoftnessDirAng(btScalar softnessDirAng) { m_softnessDirAng = softnessDirAng; }
void setRestitutionDirAng(btScalar restitutionDirAng) { m_restitutionDirAng = restitutionDirAng; }
void setDampingDirAng(btScalar dampingDirAng) { m_dampingDirAng = dampingDirAng; }
void setSoftnessLimLin(btScalar softnessLimLin) { m_softnessLimLin = softnessLimLin; }
void setRestitutionLimLin(btScalar restitutionLimLin) { m_restitutionLimLin = restitutionLimLin; }
void setDampingLimLin(btScalar dampingLimLin) { m_dampingLimLin = dampingLimLin; }
void setSoftnessLimAng(btScalar softnessLimAng) { m_softnessLimAng = softnessLimAng; }
void setRestitutionLimAng(btScalar restitutionLimAng) { m_restitutionLimAng = restitutionLimAng; }
void setDampingLimAng(btScalar dampingLimAng) { m_dampingLimAng = dampingLimAng; }
void setSoftnessOrthoLin(btScalar softnessOrthoLin) { m_softnessOrthoLin = softnessOrthoLin; }
void setRestitutionOrthoLin(btScalar restitutionOrthoLin) { m_restitutionOrthoLin = restitutionOrthoLin; }
void setDampingOrthoLin(btScalar dampingOrthoLin) { m_dampingOrthoLin = dampingOrthoLin; }
void setSoftnessOrthoAng(btScalar softnessOrthoAng) { m_softnessOrthoAng = softnessOrthoAng; }
void setRestitutionOrthoAng(btScalar restitutionOrthoAng) { m_restitutionOrthoAng = restitutionOrthoAng; }
void setDampingOrthoAng(btScalar dampingOrthoAng) { m_dampingOrthoAng = dampingOrthoAng; }
void setPoweredLinMotor(bool onOff) { m_poweredLinMotor = onOff; }
bool getPoweredLinMotor() { return m_poweredLinMotor; }
void setTargetLinMotorVelocity(btScalar targetLinMotorVelocity) { m_targetLinMotorVelocity = targetLinMotorVelocity; }
btScalar getTargetLinMotorVelocity() { return m_targetLinMotorVelocity; }
void setMaxLinMotorForce(btScalar maxLinMotorForce) { m_maxLinMotorForce = maxLinMotorForce; }
btScalar getMaxLinMotorForce() { return m_maxLinMotorForce; }
void setPoweredAngMotor(bool onOff) { m_poweredAngMotor = onOff; }
bool getPoweredAngMotor() { return m_poweredAngMotor; }
void setTargetAngMotorVelocity(btScalar targetAngMotorVelocity) { m_targetAngMotorVelocity = targetAngMotorVelocity; }
btScalar getTargetAngMotorVelocity() { return m_targetAngMotorVelocity; }
void setMaxAngMotorForce(btScalar maxAngMotorForce) { m_maxAngMotorForce = maxAngMotorForce; }
btScalar getMaxAngMotorForce() { return m_maxAngMotorForce; }
btScalar getLinearPos() { return m_linPos; }
// access for ODE solver
bool getSolveLinLimit() { return m_solveLinLim; }
btScalar getLinDepth() { return m_depth[0]; }
bool getSolveAngLimit() { return m_solveAngLim; }
btScalar getAngDepth() { return m_angDepth; }
// internal
void buildJacobianInt(btRigidBody& rbA, btRigidBody& rbB, const btTransform& frameInA, const btTransform& frameInB);
void solveConstraintInt(btRigidBody& rbA, btSolverBody& bodyA,btRigidBody& rbB, btSolverBody& bodyB);
// shared code used by ODE solver
void calculateTransforms(void);
void testLinLimits(void);
void testLinLimits2(btConstraintInfo2* info);
void testAngLimits(void);
// access for PE Solver
btVector3 getAncorInA(void);
btVector3 getAncorInB(void);
};
//-----------------------------------------------------------------------------
#endif //SLIDER_CONSTRAINT_H
| [
"vadun87@6320d0be-1f75-11de-b650-e715bd6d7cf1"
]
| [
[
[
1,
229
]
]
]
|
a8a5d6c58f38e03bb7b94940ede04a0528b1709f | dd007771e947dbed60fe6a80d4f325c4ed006f8c | /stateMachine.h | 0a17390c0ab93c3fae8baf859e412ef7d5d73637 | []
| no_license | chenzhi/CameraGame | fccea24426ea5dacbe140b11adc949e043e84ef7 | 914e1a2b8bb45b729e8d55b4baebc9ba18989b55 | refs/heads/master | 2016-09-05T20:06:11.694787 | 2011-09-09T09:09:39 | 2011-09-09T09:09:39 | 2,005,632 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,905 | h | ///**********************
///状态机类
///************************
#ifndef stateMachine_h_h_h
#define stateMachine_h_h_h
#include "State.h"
#include <vector>
class StateMachine
{
public:
///构造函数
StateMachine();
///析构函数
virtual ~StateMachine();
/**初始化函数,一般在这个函数里注册所有的状态
*在这个函数里需要手动指定当前活动状态。同时调用活动状态的begin函数
*/
virtual void initState()=0;
/**每帧更新函数
*@param time 上一帧到当前帧的时间
*/
virtual void update(float time);
/**消除所有状态
*@remark 会删除所有状态的内存
*/
void destroyAllState();
/**查找指定类型状态
*@return 如果没找到返回空
*/
State* findState(StateType type);
/**注册一个新的状态
*@return 如果已经注册了返回false
*/
bool registerState(State* pState);
/**注销一个状态
*@return 成功返回真。失败返回假
*@remark 不会清空状态内存。注销的状态需要用户手工删除
*/
bool unregisterState(StateType type);
/**获取状态的数量*/
size_t getStateCount()const {return m_stateCollect.size();}
/**获取指定索引的状态指针
*无返回空
*/
State* getState(unsigned int index) const ;
/**返回当前活动状态*/
State* getCurrentActive()const {return m_pcurrentState;}
///设置游戏开始的状态
void setBeginState(StateType GS);
protected:
typedef std::vector<State*> StateCollect;
///所有类型状态机容器
StateCollect m_stateCollect;
//保存当前的状态类型
State* m_pcurrentState;
};
#endif | [
"chenzhi@aee8fb6d-90e1-2f42-9ce8-abdac5710353"
]
| [
[
[
1,
94
]
]
]
|
4aeaf2d411aa8541784b22eb35d90fd2e0806cc1 | ce1b0d027c41f70bc4cfa13cb05f09bd4edaf6a2 | / edge2d --username [email protected]/include/EdgeImageData.h | 33ec89f15190f28cd085998e18d3c7c3dfc62057 | []
| no_license | ratalaika/edge2d | 11189c41b166960d5d7d5dbcf9bfaf833a41c079 | 79470a0fa6e8f5ea255df1696da655145bbf83ff | refs/heads/master | 2021-01-10T04:59:22.495428 | 2010-02-19T13:45:03 | 2010-02-19T13:45:03 | 36,088,756 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,787 | h | /*
-----------------------------------------------------------------------------
This source file is part of EDGE
(A very object-oriented and plugin-based 2d game engine)
For the latest info, see http://edge2d.googlecode.com
Copyright (c) 2007-2008 The EDGE Team
Also see acknowledgements in Readme.html
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser 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, or go to
http://www.gnu.org/copyleft/lesser.txt.
-----------------------------------------------------------------------------
*/
#ifndef EDGE_IMAGEDATA_H
#define EDGE_IMAGEDATA_H
#include "EdgeCompile.h"
#include "EdgeSharedPtr.h"
namespace Edge
{
/**
* maintain the data for an image, the data includes the pixel information,
* and image information( width, height ). The pixel data is 32-bit, and it's
* ARGB format.
*
* BYET *data = imageData->getData();
* so : data[0] = b, data[1] = g, data[2] = r, data[3] = a
* Also you can do this :
* DWORD *data = (DWORD*)imageData->getData();
* so : data[pixel] = 0xaarrggbb.
*/
class EDGE_EXPORT ImageData
{
public:
/**
* Constructor
*
*/
ImageData();
/**
* Copy constructor, copy the data but not the pointer
*
*/
ImageData( const ImageData &id );
/**
* operator =
*
*/
ImageData &operator = ( const ImageData &id );
/**
* Destructor
*
*/
~ImageData();
/**
* create, it will allocate memory to store the data.
*
*/
bool create( unsigned width, unsigned height ) ;
/**
* release, frees the memory, automatically called by destructor
*
*/
void release();
/**
* getData, returns the pointer points to the memory
*
*/
unsigned char *getData();
/**
* get the image's width
*
*/
unsigned getWidth() { return mWidth; }
/**
* get the image's height.
*
*/
unsigned getHeight() { return mHeight; }
protected:
/// pixel data
unsigned char *mData;
/// width
unsigned mWidth;
/// height
unsigned mHeight;
};
typedef shared_ptr<ImageData> ImageDataPtr;
}
#endif
| [
"[email protected]@539dfdeb-0f3d-0410-9ace-d34ff1985647"
]
| [
[
[
1,
113
]
]
]
|
6e0e305f3e187947866691a1815fe53b56766994 | bbdc5e4560fc6bffc244b0cb4e2619818e67d949 | /GLWidget/camera.h | 94dcf7ad3865698382ef23398afba47717e75809 | []
| no_license | jhays200/OpenGL-Maze-with-Qt | 36490765a91e4df6e322f8f772e83caa2dbe20bd | cd007c41274408cb0923111189802819915237cb | refs/heads/master | 2020-06-01T04:52:16.522720 | 2011-05-17T13:27:42 | 2011-05-17T13:27:42 | 1,760,810 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,433 | h | #ifndef CAMERA_H
#define CAMERA_H
// OpenGL
#include <GL/gl.h>
#define PI 3.1415265359
#define PIdiv180 3.1415265359/180.0
/////////////////////////////////
//Note: All angles in degrees //
/////////////////////////////////
struct SF3dVector //Float 3d-vect, normally used
{
GLfloat x,y,z;
};
struct SF2dVector
{
GLfloat x,y;
};
class CCamera
{
private:
SF3dVector ViewDir; /*Not used for rendering the camera, but for "moveforwards"
So it is not necessary to "actualize" it always. It is only
actualized when ViewDirChanged is true and moveforwards is called*/
bool ViewDirChanged;
GLfloat RotatedX, RotatedY, RotatedZ;
void GetViewDir ( void );
public:
CCamera(); //inits the values (Position: (0|0|0) Target: (0|0|-1) )
void Render ( void ); //executes some glRotates and a glTranslate command
//Note: You should call glLoadIdentity before using Render
void Move ( SF3dVector Direction );
void RotateX ( GLfloat Angle );
void RotateY ( GLfloat Angle );
void RotateZ ( GLfloat Angle );
void RotateXYZ ( SF3dVector Angles );
void MoveForwards ( GLfloat Distance );
void StrafeRight ( GLfloat Distance );
SF3dVector Position;
};
SF3dVector F3dVector ( GLfloat x, GLfloat y, GLfloat z );
SF3dVector AddF3dVectors ( SF3dVector * u, SF3dVector * v);
void AddF3dVectorToVector ( SF3dVector * Dst, SF3dVector * V2);
#endif // CAMERA_H | [
"[email protected]"
]
| [
[
[
1,
52
]
]
]
|
e95e8472003c8637a152baffb4679dbaf881baeb | 4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61 | /CleanProject/Include/CPosition.h | 9ad919c0a4f7db950ba3e47fff05b0cf69eb0e77 | []
| no_license | bahao247/apeengine2 | 56560dbf6d262364fbc0f9f96ba4231e5e4ed301 | f2617b2a42bdf2907c6d56e334c0d027fb62062d | refs/heads/master | 2021-01-10T14:04:02.319337 | 2009-08-26T08:23:33 | 2009-08-26T08:23:33 | 45,979,392 | 0 | 1 | null | null | null | null | ISO-8859-10 | C++ | false | false | 1,707 | h | /*!
@file
@author Pablo Nuņez
@date 13/2009
@module
*//*
This file is part of the Nebula Engine.
Nebula Engine 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 3 of the License, or
(at your option) any later version.
Nebula Engine is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Nebula Engine. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _CPOSITION_H_
#define _CPOSITION_H_
#include "EnginePrerequisites.h"
namespace Nebula {
using namespace Ogre;
class IGameComponent;
struct NebulaDllPrivate CPositionDesc
{
CPositionDesc()
{
}
};
class NebulaDllPrivate CPosition : public IGameComponent,
public Ogre::Vector3
{
public:
CPosition();
CPosition(const CPositionDesc&);
~CPosition();
void update();
void setup();
CPositionDesc& getDescription() {
return mDesc;
}
void callLuaFunction(const std::string func );
virtual const std::string& componentID() const {
return mComponentID;
}
private:
//static const std::string mFamilyID;
std::string mComponentID;
CPositionDesc mDesc;
};
//const std::string CPosition::mFamilyID = "CPosition";
//const std::string CPosition::mComponentID = "CPosition";
} //end namespace
#endif
| [
"pablosn@06488772-1f9a-11de-8b5c-13accb87f508"
]
| [
[
[
1,
75
]
]
]
|
7a6caf82b19ab33a76238160f9cfe14e9d8f3c87 | d54d8b1bbc9575f3c96853e0c67f17c1ad7ab546 | /hlsdk-2.3-p3/singleplayer/utils/vgui/include/VGUI_ButtonController.h | b7349146eb8f859bfa5000ad899d1a3027b72df2 | []
| no_license | joropito/amxxgroup | 637ee71e250ffd6a7e628f77893caef4c4b1af0a | f948042ee63ebac6ad0332f8a77393322157fa8f | refs/heads/master | 2021-01-10T09:21:31.449489 | 2010-04-11T21:34:27 | 2010-04-11T21:34:27 | 47,087,485 | 1 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 516 | h | //========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================
#ifndef VGUI_BUTTONCONTROLLER_H
#define VGUI_BUTTONCONTROLLER_H
#include<VGUI.h>
namespace vgui
{
class Button;
class VGUIAPI ButtonController
{
public:
virtual void addSignals(Button* button)=0;
virtual void removeSignals(Button* button)=0;
};
}
#endif
| [
"joropito@23c7d628-c96c-11de-a380-73d83ba7c083"
]
| [
[
[
1,
27
]
]
]
|
2e8b33a7f8c017ebd7e3764f5b9abc5f759fe918 | b14d5833a79518a40d302e5eb40ed5da193cf1b2 | /cpp/extern/xercesc++/2.6.0/src/xercesc/internal/VecAttributesImpl.cpp | c019d79004359f7da6968ef3f77dcd71935cef9a | [
"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 | 7,650 | cpp | /*
* Copyright 1999-2001,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.
*/
/*
* $Log: VecAttributesImpl.cpp,v $
* Revision 1.6 2004/09/08 13:56:13 peiyongz
* Apache License Version 2.0
*
* Revision 1.5 2003/12/17 00:18:34 cargilld
* Update to memory management so that the static memory manager (one used to call Initialize) is only for static data.
*
* Revision 1.4 2003/05/16 21:36:57 knoaman
* Memory manager implementation: Modify constructors to pass in the memory manager.
*
* Revision 1.3 2002/11/04 14:58:18 tng
* C++ Namespace Support.
*
* Revision 1.2 2002/09/24 20:02:20 tng
* Performance: use XMLString::equals instead of XMLString::compareString
*
* Revision 1.1.1.1 2002/02/01 22:21:58 peiyongz
* sane_include
*
* Revision 1.7 2001/10/05 17:57:39 peiyongz
* [BUG# 3831]: -1 returned from getIndex() needs to be checked
*
* Revision 1.6 2001/05/11 13:26:16 tng
* Copyright update.
*
* Revision 1.5 2001/03/21 21:56:04 tng
* Schema: Add Schema Grammar, Schema Validator, and split the DTDValidator into DTDValidator, DTDScanner, and DTDGrammar.
*
* Revision 1.4 2001/02/26 19:44:14 tng
* Schema: add utility class QName, by Pei Yong Zhang.
*
* Revision 1.3 2000/11/02 01:14:07 andyh
* SAX bug fix: Attribute lists were throwing exceptions rather than returning
* null when an attribute could not be found by name. Fixed by Tinny Ng.
*
* Revision 1.2 2000/08/09 22:11:16 jpolast
* changes to allow const instances of the sax2
* Attributes class.
*
* Revision 1.1 2000/08/02 18:09:14 jpolast
* initial checkin: attributes vector needed for
* Attributes class as defined by sax2 spec
*
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/Janitor.hpp>
#include <xercesc/internal/VecAttributesImpl.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// Constructors and Destructor
// ---------------------------------------------------------------------------
VecAttributesImpl::VecAttributesImpl() :
fAdopt(false)
, fCount(0)
, fVector(0)
, fScanner(0)
{
}
VecAttributesImpl::~VecAttributesImpl()
{
//
// Note that some compilers can't deal with the fact that the pointer
// is to a const object, so we have to cast off the const'ness here!
//
if (fAdopt)
delete (RefVectorOf<XMLAttr>*)fVector;
}
// ---------------------------------------------------------------------------
// Implementation of the attribute list interface
// ---------------------------------------------------------------------------
unsigned int VecAttributesImpl::getLength() const
{
return fCount;
}
const XMLCh* VecAttributesImpl::getURI(const unsigned int index) const
{
// since this func really needs to be const, like the rest, not sure how we
// make it const and re-use the fURIBuffer member variable. we're currently
// creating a buffer each time you need a URI. there has to be a better
// way to do this...
//XMLBuffer tempBuf;
if (index >= fCount) {
return 0;
}
//fValidator->getURIText(fVector->elementAt(index)->getURIId(), tempBuf) ;
//return tempBuf.getRawBuffer() ;
return fScanner->getURIText(fVector->elementAt(index)->getURIId());
}
const XMLCh* VecAttributesImpl::getLocalName(const unsigned int index) const
{
if (index >= fCount) {
return 0;
}
return fVector->elementAt(index)->getName();
}
const XMLCh* VecAttributesImpl::getQName(const unsigned int index) const
{
if (index >= fCount) {
return 0;
}
return fVector->elementAt(index)->getQName();
}
const XMLCh* VecAttributesImpl::getType(const unsigned int index) const
{
if (index >= fCount) {
return 0;
}
return XMLAttDef::getAttTypeString(fVector->elementAt(index)->getType(), fVector->getMemoryManager());
}
const XMLCh* VecAttributesImpl::getValue(const unsigned int index) const
{
if (index >= fCount) {
return 0;
}
return fVector->elementAt(index)->getValue();
}
int VecAttributesImpl::getIndex(const XMLCh* const uri, const XMLCh* const localPart ) const
{
//
// Search the vector for the attribute with the given name and return
// its type.
//
XMLBuffer uriBuffer(1023, fVector->getMemoryManager()) ;
for (unsigned int index = 0; index < fCount; index++)
{
const XMLAttr* curElem = fVector->elementAt(index);
fScanner->getURIText(curElem->getURIId(), uriBuffer) ;
if ( (XMLString::equals(curElem->getName(), localPart)) &&
(XMLString::equals(uriBuffer.getRawBuffer(), uri)) )
return index ;
}
return -1;
}
int VecAttributesImpl::getIndex(const XMLCh* const qName ) const
{
//
// Search the vector for the attribute with the given name and return
// its type.
//
for (unsigned int index = 0; index < fCount; index++)
{
const XMLAttr* curElem = fVector->elementAt(index);
if (XMLString::equals(curElem->getQName(), qName))
return index ;
}
return -1;
}
const XMLCh* VecAttributesImpl::getType(const XMLCh* const uri, const XMLCh* const localPart ) const
{
int retVal = getIndex(uri, localPart);
return ((retVal < 0) ? 0 : getType(retVal));
}
const XMLCh* VecAttributesImpl::getType(const XMLCh* const qName) const
{
int retVal = getIndex(qName);
return ((retVal < 0) ? 0 : getType(retVal));
}
const XMLCh* VecAttributesImpl::getValue(const XMLCh* const uri, const XMLCh* const localPart ) const
{
int retVal = getIndex(uri, localPart);
return ((retVal < 0) ? 0 : getValue(retVal));
}
const XMLCh* VecAttributesImpl::getValue(const XMLCh* const qName) const
{
int retVal = getIndex(qName);
return ((retVal < 0) ? 0 : getValue(retVal));
}
// ---------------------------------------------------------------------------
// Setter methods
// ---------------------------------------------------------------------------
void VecAttributesImpl::setVector(const RefVectorOf<XMLAttr>* const srcVec
, const unsigned int count
, const XMLScanner * const scanner
, const bool adopt)
{
//
// Delete the previous vector (if any) if we are adopting. Note that some
// compilers can't deal with the fact that the pointer is to a const
// object, so we have to cast off the const'ness here!
//
if (fAdopt)
delete (RefVectorOf<XMLAttr>*)fVector;
fAdopt = adopt;
fCount = count;
fVector = srcVec;
fScanner = scanner ;
}
XERCES_CPP_NAMESPACE_END
| [
"[email protected]"
]
| [
[
[
1,
236
]
]
]
|
e15fceeb3a231a23986b86ad5f7226b290770b8c | 27b8c57bef3eb26b5e7b4b85803a8115e5453dcb | /branches/flatRL/lib/include/Learning/plain_direct_learning.hpp | 993e5d413fb9f24a30134cc4a5e36d20c7b256ba | []
| no_license | BackupTheBerlios/walker-svn | 2576609a17eab7a08bb2437119ef162487444f19 | 66ae38b2c1210ac2f036e43b5f0a96013a8e3383 | refs/heads/master | 2020-05-30T11:30:48.193275 | 2011-03-24T17:10:17 | 2011-03-24T17:10:17 | 40,819,670 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,484 | hpp | #ifndef __WALKER_YARD_PLAIN_DIRECT_LEARNING_HPP___
#define __WALKER_YARD_PLAIN_DIRECT_LEARNING_HPP___
#include <boost/random.hpp>
#include <boost/numeric/ublas/matrix.hpp>
namespace learn {
namespace ublas = boost::numeric::ublas;
template < typename ValueType,
typename Environment,
typename ActionFunction >
class plain_direct_learning
{
public:
typedef ValueType value_type;
typedef Environment environment_type;
typedef ActionFunction action_function_type;
private:
static boost::mt19937 rng;
private:
typedef boost::variate_generator< boost::mt19937,
boost::normal_distribution<value_type> > normal_variate_generator;
typedef boost::variate_generator< boost::mt19937,
boost::uniform_real<value_type> > uniform_variate_generator;
typedef ublas::matrix<value_type> matrix_type;
typedef ublas::vector<value_type> vector_type;
public:
plain_direct_learning( environment_type _environment,
action_function_type _bestAction);
void new_episode();
bool update();
size_t get_num_episodes() const { return 0; }
size_t get_num_actions() const { return 0; }
const value_type* get_last_state() const { return &lastState[0]; }
const value_type* get_last_action() const { return &lastAction[0]; }
value_type get_last_reward() const { return lastReward; }
environment_type get_environment() const { return environment; }
action_function_type get_best_action_function() const { return bestAction; }
private:
matrix_type mult(const matrix_type& mat, const vector_type& vec)
{
assert( vec.size() == mat.size1() );
matrix_type res(mat);
for (size_t i = 0; i < mat.size1(); ++i)
{
for (size_t j = 0; j < mat.size2(); ++j)
{
res(i, j) *= vec(i);
}
}
return res;
}
public:
value_type sigma;
value_type beta;
value_type gamma;
private:
// RL primitives
environment_type environment;
action_function_type bestAction;
// internal
size_t stateSize, actionSize;
value_type lastReward;
vector_type lastState;
vector_type lastAction;
vector_type lastBestAction;
vector_type currentState;
matrix_type Z;
matrix_type theta;
normal_variate_generator normal_sampler;
uniform_variate_generator uniform_sampler;
bool debug;
};
template < typename ValueType,
typename Environment,
typename ActionFunction >
plain_direct_learning<ValueType, Environment, ActionFunction>::plain_direct_learning( Environment _environment,
ActionFunction _bestAction)
: environment(_environment)
, bestAction(_bestAction)
, stateSize( environment.state_size() )
, actionSize( environment.action_size() )
, lastState(stateSize)
, lastAction(actionSize)
, lastBestAction(actionSize)
, currentState(stateSize)
, Z(_bestAction.num_components(), _bestAction.num_params()/_bestAction.num_components())
, theta(_bestAction.num_components(), _bestAction.num_params()/_bestAction.num_components())
, normal_sampler( rng, boost::normal_distribution<value_type>( 0, value_type(0.1) ) )
, uniform_sampler( rng, boost::uniform_real<value_type>(-1.0, 1.0) )
, sigma(0.05f)
, beta(0.9f)
, gamma(0.002f)
{
debug = false;
std::fill(theta.data().begin(), theta.data().end(), value_type(0));
}
template < typename ValueType,
typename Environment,
typename ActionFunction >
void plain_direct_learning<ValueType, Environment, ActionFunction>::new_episode()
{
Z = matrix_type( bestAction.num_components(),
bestAction.num_params() / bestAction.num_components() );
std::fill(Z.data().begin(), Z.data().end(), value_type(0));
environment.query_state( lastState.begin() );
// select first action
bestAction.compute( lastState.begin(),
lastState.end(),
lastBestAction.begin() );
for (size_t i = 0; i < actionSize; ++i)
{
//lastAction[i] += (*normal_sampler[i])();
lastAction[i] = lastBestAction[i] + normal_sampler();
}
lastReward = environment.perform_action( lastAction.begin(),
lastAction.end() );
debug = true;
}
template < typename ValueType,
typename Environment,
typename ActionFunction >
bool plain_direct_learning<ValueType, Environment, ActionFunction>::update()
{
bool terminal = environment.query_state( currentState.begin() );
matrix_type delta;
// ... compute delta
matrix_type gradient(bestAction.num_components(), bestAction.num_params()/bestAction.num_components());
bestAction.get_gradient(lastState.begin(), lastState.end(), gradient.data().begin()); // lastState?
delta = (1/(sigma*sigma))*mult(gradient, lastAction - lastBestAction);
Z = beta*Z + delta;
bestAction.get_params(theta.data().begin());
theta += gamma*lastReward*Z;
bestAction.set_params(theta.data().begin(), theta.data().end());
debug = false;
if (terminal)
{
return true;
}
// select new action
bestAction.compute( currentState.begin(),
currentState.end(),
lastBestAction.begin() );
// sum with variation
for (size_t i = 0; i < actionSize; ++i)
{
//lastBestAction[i] = std::max(std::min(lastBestAction[i], value_type(1.0)), value_type(-1.0));
//lastAction[i] += (*normal_sampler[i])();
lastAction[i] = lastBestAction[i] + normal_sampler();
//lastAction[i] = std::max(std::min(lastAction[i], 1.0f), -1.0f);
}
/*
value_type distance = value_type();
for (size_t i = 0; i<currentState.size(); ++i) {
distance += sqrt( (currentState[i] - lastState[i]) * (currentState[i] - lastState[i]) );
}
if (distance < 0.01)
{
std::cerr << "random action" << std::endl;
for (size_t i = 0; i < actionSize; ++i)
{
//lastAction[i] += (*normal_sampler[i])();
lastAction[i] = uniform_sampler();
}
}
*/
lastState.swap(currentState);
lastReward = environment.perform_action( lastAction.begin(),
lastAction.end() );
gamma *= 0.99f;
if (gamma < 0.0005f) gamma = 0.0005f;
return false;
}
template < typename ValueType,
typename Environment,
typename ActionFunction >
boost::mt19937 plain_direct_learning<ValueType, Environment, ActionFunction>::rng;
} // namespace learn
#endif // __WALKER_YARD_PLAIN_DIRECT_LEARNING_HPP___ | [
"red-haired@9454499b-da03-4d27-8628-e94e5ff957f9"
]
| [
[
[
1,
208
]
]
]
|
f690ca3f9f843b9a7332a4ff464a20515971ebac | 17e1b436ba01206d97861ec9153943592002ecbe | /uppsrc/Web/srcdoc.tpp/ConnectionOriented$en-us.tpp | edb2e86e064dea1fd4d5a8eb651c6da00a9fd377 | [
"BSD-2-Clause"
]
| permissive | ancosma/upp-mac | 4c874e858315a5e68ea74fbb1009ea52e662eca7 | 5e40e8e31a3247e940e1de13dd215222a7a5195a | refs/heads/master | 2022-12-22T17:04:27.008533 | 2010-12-30T16:38:08 | 2010-12-30T16:38:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,288 | tpp | TITLE("Connection-Oriented Socket Tutorial")
COMPRESSED
120,156,133,87,139,110,219,54,20,253,21,54,238,58,103,149,21,81,15,91,142,59,96,157,151,162,197,134,165,88,82,20,67,102,68,138,68,215,92,101,81,35,165,164,65,31,223,190,67,74,178,41,183,203,10,36,177,168,123,207,61,247,220,7,221,43,242,248,177,231,120,35,239,127,254,157,254,194,214,105,83,212,171,171,130,206,22,18,63,55,225,34,13,23,53,157,206,22,95,190,124,9,130,133,15,40,234,208,81,52,143,104,16,132,148,206,163,96,22,120,113,16,7,1,13,125,223,243,66,63,154,198,222,233,101,83,11,201,211,34,153,252,44,242,123,186,135,252,245,220,91,0,196,119,252,209,52,164,177,15,183,96,74,225,230,7,243,185,31,197,211,112,30,7,0,10,230,3,144,166,40,88,173,232,144,90,108,83,251,1,168,129,19,140,34,127,22,198,225,220,11,99,47,68,82,33,224,61,0,135,65,140,7,111,230,91,168,47,89,154,243,242,221,131,168,33,96,67,39,28,133,96,24,129,233,44,136,168,231,69,97,228,121,52,154,199,81,224,205,34,207,167,145,5,123,41,
42,158,117,216,128,142,131,54,113,11,117,249,211,216,143,221,208,119,33,216,49,69,132,200,137,70,62,13,189,216,143,181,180,51,127,174,229,157,83,63,242,195,56,70,224,192,155,90,17,150,34,103,15,145,62,209,117,154,58,211,17,188,163,8,117,138,226,8,138,206,230,243,32,166,1,141,244,239,208,163,97,248,149,24,254,67,132,169,63,115,91,190,51,103,54,138,41,13,192,47,8,162,200,155,70,83,26,1,215,15,241,19,64,145,104,234,31,240,93,138,237,150,149,104,174,143,215,159,191,59,251,125,242,230,130,92,169,112,65,150,162,44,89,86,115,81,38,147,115,201,97,194,114,114,33,178,247,172,38,61,194,147,213,149,10,22,164,251,243,130,75,85,19,85,179,74,233,19,218,159,220,139,134,108,27,124,200,36,75,107,70,210,30,70,220,252,141,8,46,121,187,97,165,177,234,12,234,13,87,221,75,7,15,140,168,214,30,167,188,36,105,73,154,50,107,217,129,146,170,225,178,32,220,188,46,69,77,82,5,115,158,234,119,119,188,222,192,254,158,108,132,66,156,87,37,17,
50,103,146,172,133,180,113,107,65,20,43,115,88,230,68,178,140,241,91,134,64,48,218,166,58,127,71,131,155,4,110,24,185,17,13,172,224,145,26,80,0,146,156,169,154,151,198,212,64,84,66,34,88,39,65,167,205,178,208,10,146,11,158,179,238,197,165,216,233,1,90,77,221,2,103,59,213,29,210,40,102,88,182,190,157,102,107,228,110,34,129,194,13,135,7,116,147,86,34,29,173,61,143,46,114,103,33,89,221,200,82,193,236,70,136,130,33,244,109,90,52,12,41,150,57,207,144,67,249,142,240,181,9,187,167,66,238,82,69,84,147,101,76,169,117,83,232,156,33,180,171,19,153,46,200,217,135,116,91,21,236,84,63,70,139,190,182,219,251,228,90,199,92,116,199,28,28,52,161,228,71,204,150,215,159,94,212,82,71,52,148,147,31,73,114,68,231,190,75,167,104,105,215,79,142,118,190,235,241,64,132,113,15,238,24,72,199,248,31,147,227,222,62,249,216,125,152,124,234,45,221,183,146,215,108,156,28,109,88,81,8,114,39,100,145,63,74,142,118,46,150,229,178,16,138,141,
247,96,159,135,93,126,193,228,45,90,200,170,100,119,162,112,66,210,170,42,140,142,2,34,23,28,195,80,154,110,227,232,216,173,78,181,171,195,94,92,229,146,231,253,169,106,145,90,63,101,138,184,193,47,12,195,122,109,187,232,66,11,212,72,154,178,221,242,188,73,139,14,67,145,113,163,240,88,220,3,173,74,101,59,79,104,180,92,29,239,154,18,189,39,42,48,75,141,126,26,237,91,84,173,128,142,25,207,190,33,223,36,79,147,167,228,106,217,101,222,22,101,181,107,77,247,240,213,248,120,133,198,251,167,225,146,33,41,61,196,85,131,22,237,179,110,39,221,100,171,209,15,40,1,239,193,70,75,209,150,85,221,214,142,161,23,242,180,78,251,167,195,230,211,61,182,107,191,217,130,156,156,144,223,246,137,219,2,55,74,43,144,92,15,209,237,134,124,52,200,240,144,133,142,134,142,180,58,17,69,16,119,200,33,67,19,46,69,83,228,101,242,125,221,142,112,175,67,105,242,47,68,134,106,154,225,181,26,180,109,195,150,243,159,122,85,98,116,115,209,174,74,189,20,225,38,
42,179,0,12,19,178,213,107,207,202,232,212,162,62,36,235,190,82,231,104,134,241,144,110,142,17,201,9,175,32,65,158,203,94,176,201,39,132,127,169,43,165,59,210,90,9,214,178,0,135,228,218,174,194,14,211,200,246,85,240,51,41,133,68,244,228,73,242,228,144,218,115,243,56,182,209,28,24,246,180,64,121,7,110,113,159,124,130,192,232,58,242,236,25,209,98,239,168,173,165,216,226,68,159,191,48,219,253,213,235,241,54,185,230,85,11,102,204,147,191,202,110,243,204,90,44,100,252,7,198,167,117,182,110,141,166,172,121,209,221,59,153,222,25,57,22,81,170,167,150,48,157,146,163,247,164,30,27,197,204,142,199,13,147,76,196,58,153,172,121,193,80,31,249,158,201,97,152,241,217,249,11,12,166,166,138,14,208,42,91,235,36,153,168,138,101,124,205,179,99,43,209,187,13,192,6,250,236,203,105,4,125,116,240,238,76,172,255,243,85,91,8,27,126,32,170,45,235,192,85,203,51,182,86,41,252,62,239,235,178,255,104,87,101,47,243,174,185,187,219,114,183,81,187,1,79,
142,244,144,40,148,109,120,101,247,187,194,221,205,67,173,191,71,244,75,106,240,29,67,219,235,29,120,114,167,175,1,195,222,61,8,41,218,111,32,128,209,245,210,8,216,98,135,11,128,172,222,233,21,123,112,61,238,247,52,186,65,15,6,162,25,103,91,37,178,50,223,70,58,224,174,177,177,24,183,172,222,136,220,37,151,154,252,87,94,43,211,82,195,120,238,64,37,213,101,140,46,108,161,218,111,61,201,209,165,217,250,228,53,238,121,45,158,88,127,227,238,49,11,3,23,226,157,89,128,41,201,152,172,83,172,147,178,217,222,224,118,217,249,24,67,246,1,187,114,127,189,80,82,49,217,221,45,199,134,19,254,7,177,250,23,96,139,48,170,
| [
"[email protected]"
]
| [
[
[
1,
9
]
]
]
|
d9161014460c297f5b06b1185cbebb9c363748f9 | d2e6d2d8f8bdf4e5eae823e1f1aef71164954df5 | /src/misc.h | eed3f7c50d47be4ab251c144689c4c850fd40bc2 | []
| no_license | beru/hew-io-file | 0c6bbb43a980eeb8a5fe1888c2ce5ecc20855d63 | ee4d5fd46de4a86294a19f16c178194f5addf28a | refs/heads/master | 2016-08-04T02:06:40.622339 | 2011-10-02T15:16:00 | 2011-10-02T15:16:00 | 33,050,465 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,405 | h | #pragma once
#include <cmath>
#include <vector>
inline
uint8_t hexCharToInt(char c)
{
if (c >= '0' && c <= '9') {
return c - '0';
}else if (c >= 'A' && c <= 'F') {
return c - 'A' + 10;
}else if (c >= 'a' && c <= 'f') {
return c - 'a' + 10;
}else {
assert(false);
}
return 0;
}
inline
bool isHex(char c)
{
return (0
|| (c >= '0' && c <= '9')
|| (c >= 'A' && c <= 'F')
|| (c >= 'a' && c <= 'f')
);
}
inline
uint8_t readHexByte(char c0, char c1)
{
if (isHex(c0) && isHex(c1)) {
return hexCharToInt(c0) * 16 + hexCharToInt(c1);
}else {
return 0;
}
}
inline
void readHexBytes(const char* str, uint8_t* data, size_t nBytes)
{
for (size_t i=0; i<nBytes; ++i) {
data[i] = readHexByte(str[0], str[1]);
str += 2;
}
}
// Round up to next higher power of 2 (return x if it's already a power of 2).
inline
uint8_t pow2roundup(uint8_t x)
{
--x;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
return x+1;
}
// Round up to next higher power of 2 (return x if it's already a power of 2).
inline
uint16_t pow2roundup16(uint16_t x)
{
--x;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
return x+1;
}
// Round up to next higher power of 2 (return x if it's already a power of 2).
inline
uint32_t pow2roundup32(uint32_t x)
{
--x;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x+1;
}
inline
uint8_t countBits32(uint32_t n)
{
n = ((n & 0xAAAAAAAA) >> 1) + (n & 0x55555555);
n = ((n & 0xCCCCCCCC) >> 2) + (n & 0x33333333);
n = ((n & 0xF0F0F0F0) >> 4) + (n & 0x0F0F0F0F);
n = ((n & 0xFF00FF00) >> 8) + (n & 0x00FF00FF);
n = ((n & 0xFFFF0000) >> 16) + (n & 0x0000FFFF);
return n;
}
inline
uint8_t countBits16(uint16_t n)
{
n = (unsigned short)( ((n & 0xAAAA) >> 1) + (n & 0x5555) );
n = (unsigned short)( ((n & 0xCCCC) >> 2) + (n & 0x3333) );
n = (unsigned short)( ((n & 0xF0F0) >> 4) + (n & 0x0F0F) );
n = (unsigned short)( ((n & 0xFF00) >> 8) + (n & 0x00FF) );
return (uint8_t) n;
}
inline
uint8_t countBits8(uint8_t n)
{
n = (uint8_t)( ((n & 0xAA) >> 1) + (n & 0x55) );
n = (uint8_t)( ((n & 0xCC) >> 2) + (n & 0x33) );
n = (uint8_t)( ((n & 0xF0) >> 4) + (n & 0x0F) );
return n;
}
/*
inline
uint8_t ntz(uint8_t n)
{
int x = n;
return countBits8((x&(-x))-1);
}
*/
inline
uint8_t ntz(uint16_t n)
{
int x = n;
return countBits16((x&(-x))-1);
}
inline
uint8_t ntz(uint32_t n)
{
int x = n;
return countBits32((x&(-x))-1);
}
// http://www.hackersdelight.org/HDcode/flp2.c.txt
/* Round down to a power of 2. */
inline
unsigned flp2_16(uint16_t x) {
x = x | (x >> 1);
x = x | (x >> 2);
x = x | (x >> 4);
x = x | (x >> 8);
return x - (x >> 1);
}
inline
uint8_t log2(uint32_t v)
{
int r; // result goes here
static const int MultiplyDeBruijnBitPosition[32] =
{
0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30,
8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31
};
v |= v >> 1; // first round down to one less than a power of 2
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
r = MultiplyDeBruijnBitPosition[(uint32_t)(v * 0x07C4ACDDU) >> 27];
return r;
}
std::vector<uint32_t> GetLinePositions(const char* buff, size_t len);
| [
"[email protected]"
]
| [
[
[
1,
173
]
]
]
|
90aaedff081864b304646655b98777626292eb50 | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/nGENE Proj/ScreenOverlay.cpp | 95c8c24f6ed57eddd3715cefb8b9d443c3c1b2da | []
| 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 | 8,571 | cpp | /*
---------------------------------------------------------------------------
This source file is part of nGENE Tech.
Copyright (c) 2006- Wojciech Toman
This program is free software.
File: ScreenOverlay.cpp
Version: 0.16
---------------------------------------------------------------------------
*/
#include "PrecompiledHeaders.h"
#include "ScreenOverlay.h"
#include "Material.h"
#include "Renderer.h"
#include "RenderPass.h"
#include "RenderTechnique.h"
#include "StateManager.h"
#include "VertexBufferManager.h"
#include "VertexDeclaration.h"
namespace nGENE
{
// Initialize static members
TypeInfo ScreenOverlay::Type(L"ScreenOverlay", NULL);
ScreenOverlay::ScreenOverlay(const RECT_FLOAT& _rect):
m_vecPosition(_rect.left, _rect.top),
m_fWidth(_rect.right - _rect.left),
m_fHeight(_rect.bottom - _rect.top),
m_nGSMask(0),
m_pVB(NULL),
m_pMaterial(NULL)
{
init();
}
//----------------------------------------------------------------------
ScreenOverlay::ScreenOverlay(float _x, float _y, float _width, float _height):
m_vecPosition(_x, _y),
m_fWidth(_width),
m_fHeight(_height),
m_nGSMask(0),
m_pVB(NULL),
m_pMaterial(NULL)
{
init();
}
//----------------------------------------------------------------------
ScreenOverlay::~ScreenOverlay()
{
cleanup();
}
//----------------------------------------------------------------------
void ScreenOverlay::cleanup()
{
m_pMaterial = NULL;
m_pVB = NULL;
}
//----------------------------------------------------------------------
void ScreenOverlay::init()
{
Real fWidthEps = 0.5f / m_fWidth;
Real fHeightEps = 0.5f / m_fHeight;
SVertex2D quad[] =
{
{
Vector3(m_vecPosition.x, m_vecPosition.y, 0.5f),
0xffffffff,
Vector2(0.0f + fWidthEps, 0.0f + fHeightEps)
},
{
Vector3(m_vecPosition.x + 1.0f, m_vecPosition.y, 0.5f),
0xffffffff,
Vector2(1.0f + fWidthEps, 0.0f + fHeightEps)
},
{
Vector3(m_vecPosition.x + 1.0f, m_vecPosition.y + 1.0f, 0.5f),
0xffffffff,
Vector2(1.0f + fWidthEps, 1.0f + fHeightEps)
},
{
Vector3(m_vecPosition.x, m_vecPosition.y + 1.0f, 0.5f),
0xffffffff,
Vector2(0.0f + fWidthEps, 1.0f + fHeightEps)
}
};
VertexBufferManager& manager = VertexBufferManager::getSingleton();
VERTEXBUFFER_DESC vbDesc;
vbDesc.vertices = quad;
vbDesc.verticesNum = 4;
vbDesc.primitivesNum = 2;
vbDesc.primitivesType = PT_TRIANGLEFAN;
vbDesc.vertexSize = sizeof(SVertex2D);
vbDesc.vertexDeclaration = manager.getVertexDeclaration(L"Declaration2D");
m_pVB = manager.createVertexBuffer(vbDesc);
}
//----------------------------------------------------------------------
void ScreenOverlay::begin()
{
Renderer& renderer = Renderer::getSingleton();
// Save current render state
RENDER_STATE renderState = renderer.getRenderState();
StateManager::getSingleton().push(renderState);
m_OldFillMode = renderer.getFillMode();
m_OldCullMode = renderer.getCullingMode();
m_nGSMask = renderer.getGlobalStatesMask();
if(m_OldCullMode != CULL_NONE)
{
if(renderer.isGlobalState(GS_CULLING))
renderer.setGlobalState(GS_CULLING, false);
renderer.setCullingMode(CULL_NONE);
}
if(m_OldFillMode != FILL_SOLID)
{
if(renderer.isGlobalState(GS_FILLMODE))
renderer.setGlobalState(GS_FILLMODE, false);
}
renderer.set2DMode();
}
//----------------------------------------------------------------------
void ScreenOverlay::end()
{
Renderer& renderer = Renderer::getSingleton();
// Restore previous render states
RENDER_STATE renderState = StateManager::getSingleton().pop();
renderer.setCullingMode(m_OldCullMode);
renderer.setFillMode(m_OldFillMode);
renderer.setGlobalStatesMask(m_nGSMask);
renderer.restore3DMode();
}
//----------------------------------------------------------------------
void ScreenOverlay::render()
{
if(!m_pMaterial)
{
Log::log(LET_ERROR, L"nGENE", __WFILE__, __WFUNCTION__, __LINE__,
L"Screen overlay does not have material assigned!");
return;
}
m_pMaterial->bind();
Renderer& renderer = Renderer::getSingleton();
RENDER_STATE& renderState = StateManager::getSingleton().top();
FILL_MODE oldFillMode = renderer.getFillMode();
uint globalStates = renderer.getGlobalStatesMask();
if(renderState.culling != CULL_NONE)
{
if(renderer.isGlobalState(GS_CULLING))
renderer.setGlobalState(GS_CULLING, false);
renderer.setCullingMode(CULL_NONE);
}
if(oldFillMode != FILL_SOLID)
{
if(renderer.isGlobalState(GS_FILLMODE))
renderer.setGlobalState(GS_FILLMODE, false);
}
Matrix4x4 newWorld;
Vector3 temp(m_fWidth, m_fHeight, 1.0f);
newWorld.scale(temp);
Matrix4x4 matTrans;
matTrans.translate(m_vecPosition.x, m_vecPosition.y, 0.0f);
newWorld.multiply(matTrans);
renderer.setWorldMatrix(newWorld);
m_pVB->prepare();
RenderTechnique* pTechnique = m_pMaterial->getActiveRenderTechnique();
for(uint i = 0; i < pTechnique->getPassesNum(); ++i)
{
RenderPass& pass = pTechnique->getRenderPass(i);
// Scene pass, so skip it
if(pass.getRenderingOrder() == DO_SCENE || !pass.isEnabled())
continue;
pass.bind();
pass.update();
m_pVB->render();
pass.unbind();
}
m_pMaterial->unbind();
// Restore previous states
renderer.setFillMode(oldFillMode);
renderer.setGlobalStatesMask(globalStates);
}
//----------------------------------------------------------------------
void ScreenOverlay::render(const Vector2& _position, Real _width, Real _height,
const SRect<Real>& _src, const Colour& _colour)
{
if(!m_pMaterial)
{
Log::log(LET_ERROR, L"nGENE", __WFILE__, __WFUNCTION__, __LINE__,
L"Screen overlay does not have material assigned!");
return;
}
dword col = _colour.getDwordARGB();
SVertex2D quad[] =
{
{Vector3(0, 0, 0.5f), col, Vector2(_src.left, _src.top)},
{Vector3(0 + 1.0f, 0, 0.5f), col, Vector2(_src.right, _src.top)},
{Vector3(0 + 1.0f, 0 + 1.0f, 0.5f), col, Vector2(_src.right, _src.bottom)},
{Vector3(0, 0 + 1.0f, 0.5f), col, Vector2(_src.left, _src.bottom)}
};
VertexBufferManager& manager = VertexBufferManager::getSingleton();
VERTEXBUFFER_DESC vbDesc;
vbDesc.vertices = quad;
vbDesc.verticesNum = 4;
vbDesc.primitivesNum = 2;
vbDesc.primitivesType = PT_TRIANGLEFAN;
vbDesc.vertexSize = sizeof(SVertex2D);
vbDesc.vertexDeclaration = manager.getVertexDeclaration(L"Declaration2D");
m_pMaterial->bind();
Renderer& renderer = Renderer::getSingleton();
RENDER_STATE& renderState = StateManager::getSingleton().top();
FILL_MODE oldFillMode = renderer.getFillMode();
uint globalStates = renderer.getGlobalStatesMask();
if(renderState.culling != CULL_NONE)
{
if(renderer.isGlobalState(GS_CULLING))
renderer.setGlobalState(GS_CULLING, false);
renderer.setCullingMode(CULL_NONE);
}
if(oldFillMode != FILL_SOLID)
{
if(renderer.isGlobalState(GS_FILLMODE))
renderer.setGlobalState(GS_FILLMODE, false);
}
Matrix4x4 newWorld;
Vector3 temp(_width, _height, 1.0f);
newWorld.scale(temp);
Matrix4x4 matTrans;
matTrans.translate(_position.x, _position.y, 0.0f);
newWorld.multiply(matTrans);
renderer.setWorldMatrix(newWorld);
VertexBufferManager::getSingleton().bindVertexDeclaration(vbDesc.vertexDeclaration);
RenderTechnique* pTechnique = m_pMaterial->getActiveRenderTechnique();
for(uint i = 0; i < pTechnique->getPassesNum(); ++i)
{
RenderPass& pass = pTechnique->getRenderPass(i);
// Scene pass, so skip it
if(pass.getRenderingOrder() == DO_SCENE || !pass.isEnabled())
continue;
pass.bind();
pass.update();
m_pVB->render(vbDesc);
VertexBufferManager::getSingleton().bindVertexBuffer(NULL);
pass.unbind();
}
m_pMaterial->unbind();
// Restore previous states
renderer.setFillMode(oldFillMode);
renderer.setGlobalStatesMask(globalStates);
}
//----------------------------------------------------------------------
void ScreenOverlay::setMaterial(Material* _material)
{
m_pMaterial = _material;
}
//----------------------------------------------------------------------
Material* ScreenOverlay::getMaterial() const
{
return m_pMaterial;
}
//----------------------------------------------------------------------
}
| [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
]
| [
[
[
1,
300
]
]
]
|
53d39108c443ad14fe7b4d8559216b73d61e4090 | 4275e8a25c389833c304317bdee5355ed85c7500 | /Netlib/cNetClock.h | 7f9165362ffdd0738a7add9d6f62ed0ba5e104c1 | []
| no_license | kumorikarasu/KylTek | 482692298ef8ff501fd0846b5f41e9e411afe686 | be6a09d20159d0a320abc4d947d4329f82d379b9 | refs/heads/master | 2021-01-10T07:57:40.134888 | 2010-07-26T12:10:09 | 2010-07-26T12:10:09 | 55,943,006 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,709 | h | /*******************************************************************
* Advanced 3D Game Programming with DirectX 10.0
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* See license.txt for modification and distribution information
* copyright (c) 2007 by Peter Walsh, Wordware
******************************************************************/
// cNetClock.h: interface for the cNetClock class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_CNETCLOCK_H__1E011A05_D341_11D3_AE4F_00E029031C67__INCLUDED_)
#define AFX_CNETCLOCK_H__1E011A05_D341_11D3_AE4F_00E029031C67__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "cMonitor.h"
struct cTimePair
{
public:
DWORD d_actual, // The actual time as reported by GetTickCount()
d_clock; // The clock time as determined by the server.
};
class cNetClock : public cMonitor
{
cTimePair d_start, // The first time set by the server.
d_lastUpdate; // the last updated time set by the server.
bool d_bInitialized; // first time has been received.
double d_ratio;
// The difference as measured by
// d_lastUpdated.d_clock - d_start.d_clock
// -----------------------------------------
// d_lastUpdated.d_actual - d_start.d_actual
public:
cNetClock();
virtual ~cNetClock();
void Init();
void Synchronize( DWORD serverTime, DWORD packetSendTime, DWORD packetACKTime, float ping );
DWORD GetTime() const;
DWORD TranslateTime( DWORD time ) const;
};
#endif // !defined(AFX_CNETCLOCK_H__1E011A05_D341_11D3_AE4F_00E029031C67__INCLUDED_)
| [
"Sean Stacey@localhost"
]
| [
[
[
1,
54
]
]
]
|
05fa1b30feacb21a7da059616b9ad74c1d546b9a | 631e5d0780b8dd333fb2c5471cbc853cc94aa355 | /slcd.h | b8b8d8a90cdcb23e3d40368912d3ba3f14670e04 | []
| no_license | derdos/DRO-C | c4b4b18806511355766da94b03c4f7559d70f815 | 8a384a79dfd698bf95ea29d55fda9557020a7df7 | refs/heads/master | 2021-01-19T18:52:06.892428 | 2010-10-07T23:49:21 | 2010-10-07T23:49:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,516 | h | /*
* LCD Driver for the Reach SLCD34 touch screen module
*
* Created on: Sep 2, 2010
* Author: David Erdos
*/
#ifndef SLCD_H_
#define SLCD_H_
#include <WProgram.h>
#include "dro.h"
#define HOME_SCREEN 1
#define SETUP_SCREEN 2
#define XAXIS_CONFIG 3
#define YAXIS_CONFIG 4
#define ZAXIS_CONFIG 5
#define RAXIS_CONFIG 6
class SLCD{
public:
SLCD();
static void initializeHome();
static void initializeConfig(const int axis);
static void updateHomeValues(int axis = 0);
static void forceUpdateHomeValues();
static void updateConfigValues(const double dist, int axis);
static void displayAxisConfig(int axis);
static void displaySetup();
static void updateSetup();
static void displayJog();
static void updateJog();
static void clearScreen();
static void setVolume(int newVolume);
static void sendVolume(int newVolume);
static void setUnits(int newUnits);
static int sendLCD(char *command, int final = 1);
static void dispXNeg(bool sign);
static void dispYNeg(bool sign);
static void dispZNeg(bool sign);
static void dispRNeg(bool sign);
private:
static double dXVal;
static double dYVal;
static double dZVal;
static double dRVal;
static char cValue[7];
static char cBuffer[7];
static void fmtDouble(double val, byte precision, char *buf, unsigned frontPad, unsigned bufLen = 0xffff);
static unsigned fmtUnsigned(unsigned long val, char *buf, unsigned bufLen = 0xffff, unsigned width = 0);
};
#endif /* SLCD_H_ */
| [
"David@.(none)",
"[email protected]"
]
| [
[
[
1,
31
],
[
34,
35
],
[
37,
58
]
],
[
[
32,
33
],
[
36,
36
]
]
]
|
eed6657b249fe612f838dba6484ddea53c8b22c3 | b05775cd4bc8b31c4180fe2ad53e72b36c622c84 | /trunk/aproxim/src/functions.h | 78e8049f14d4782ef70f7388eb76806752dbe8a4 | []
| no_license | BackupTheBerlios/aproxim-svn | 9049098bfc63134d914e7c4fef448637f07d6f9c | eb94c9f028e1f8eb04f4556ec1fa99ebec02ff10 | refs/heads/master | 2021-01-21T02:27:41.388224 | 2007-06-04T18:16:04 | 2007-06-04T18:16:04 | 40,672,123 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,900 | h | /*
* Copyright (c) 2006, Anatoly Sova 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 author 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.
*/
//---------------------------------------------------------------------------
#ifndef FunctionsH
#define FunctionsH
//---------------------------------------------------------------------------
#include <vector>
#include <cmath>
using namespace std;
//---------------------------------------------------------------------------
typedef double (*function)(double a, double b, double x);
double Func1(double a, double b, double x);
double Func2(double a, double b, double x);
double Func3(double a, double b, double x);
double Func4(double a, double b, double x);
double Func5(double a, double b, double x);
double Func6(double a, double b, double x);
double Func7(double a, double b, double x);
double Func8(double a, double b, double x);
double Func9(double a, double b, double x);
double Func10(double a, double b, double x);
double Func11(double a, double b, double x);
double Func12(double a, double b, double x);
double Func13(double a, double b, double x);
double Func14(double a, double b, double x);
double Func15(double a, double b, double x);
double Func16(double a, double b, double x);
double Func17(double a, double b, double x);
double Func18(double a, double b, double x, signed char n0);
double Func19(vector<double> &mbx, double x, signed char n0);
double Func20(double a, double b1, double b2, double x);
#endif
| [
"dark_elf@6f459bc1-eb31-0410-9770-a4c51203e036"
]
| [
[
[
1,
50
]
]
]
|
9e1bea4f5c102e9b3070cb85ac3ea67eeb6e3108 | 2fc8903fabbf9889c14a109b9210a8b51ed6df0a | /bench/fannkuch/fannkuch.gpp | fa1ddcc10b479ae199fd2a0435e5de1ee01b3dd2 | [
"BSD-3-Clause"
]
| permissive | kragen/shootout | 6620f5756d3a2f6d9dce32e86851835cfdf5d5bc | 71aa4ec4cd15940c59f1a1bb71ac1ff1572a55c2 | refs/heads/master | 2021-01-01T06:50:07.668336 | 2011-05-17T22:22:19 | 2011-05-17T22:22:19 | 1,693,719 | 18 | 8 | null | null | null | null | UTF-8 | C++ | false | false | 3,289 | gpp | /*
* The Computer Language Benchmarks Game
* http://shootout.alioth.debian.org/
*
* Contributed by Andrew Moon
* Based on the C++ code by The Anh Tran
* Based on the C code by Eckehard Berns
*/
#include <stdlib.h>
#include <stdio.h>
#include <memory.h>
#include <algorithm>
#include <pthread.h>
struct worker {
worker( int ndigits, int pos, worker *head = NULL ) :
digits(ndigits), pos_right(pos), next(head) {}
inline int countflips() {
if ( !p[0] )
return 0;
if ( !p[p[0]] )
return 1;
int tmp[16], flips = 0, last = p[0];
memcpy( tmp, p, digits * sizeof( int ) );
do {
if ( !tmp[last] )
return flips + 1;
for ( int lo = 1, hi = last - 1; lo < hi; lo++, hi-- )
std::swap( tmp[lo], tmp[hi] );
std::swap( tmp[last], last );
flips++;
} while ( last );
return flips;
}
inline void permute() {
int tmp = p[0];
for ( int i = 0; i < pos_left; i++ )
p[i] = p[i + 1];
p[pos_left] = tmp;
}
bool print( int &left ) {
if ( left-- > 0 ) {
for ( int i = 0; i < digits; i++ )
printf( "%d", p[i] + 1 );
printf( "\n" );
}
return ( left > 0 );
}
int fannkuch( int toprint = -1 ) {
bool printing = ( toprint >= 0 );
int left_limit = printing ? digits : digits - 1;
pos_left = printing ? 1 : digits - 2;
for ( int i = 0; i < digits; i++ ) {
p[i] = i;
count[i] = i + 1;
}
if ( printing )
print( toprint );
p[pos_right] = digits - 1;
p[digits - 1] = pos_right;
int maxflips = ( digits > 1 ) ? 1 : 0;
while ( pos_left < left_limit ) {
permute();
if ( --count[pos_left] > 0 ) {
if ( printing && !print( toprint ) )
return maxflips;
for ( ; pos_left != 1; pos_left-- )
count[pos_left - 1] = pos_left;
maxflips = std::max( maxflips, countflips() );
} else {
pos_left++;
}
}
return maxflips;
}
void launch() { pthread_create( &id, NULL, threadrun, this ); }
int finish() { int t; pthread_join( id, (void **)&t ); return t; }
static void *threadrun( void *args ) { return (void *)((worker *)args)->fannkuch(); }
protected:
int p[16], count[16];
int digits, pos_right, pos_left;
pthread_t id;
public:
worker *next;
};
int fannkuch( int n ) {
// create the workers
int count = n - 1;
worker *head = NULL;
if ( n > 0 ) {
for ( int i = 0; i < count; i++ ) {
head = new worker( n, i, head );
head->launch();
}
// print the first 30
worker(n,n-1).fannkuch( 30 );
}
// gather the results
int maxflips = 0;
while ( head ) {
maxflips = std::max( head->finish(), maxflips );
worker *tmp = head->next;
delete head;
head = tmp;
}
return maxflips;
}
int main( int argc, const char *argv[] ) {
int n = ( argc > 1 ) ? atoi( argv[1] ) : 0;
printf( "Pfannkuchen(%d) = %d\n", n, fannkuch( n ) );
return 0;
}
| [
"igouy-guest"
]
| [
[
[
1,
129
]
]
]
|
da43c35d859c8cbc6bfcd7bd802bc33ae080f4dc | 9b7fdcba49d9875d12641864b2ee1386b9cae280 | /src/Tools/SparkLanguagePackage/Colorizer.h | 8facbbb070ed31c2eef19bf965c1bef8439fbaf5 | [
"Apache-2.0"
]
| permissive | Ziaw/spark | 1c4e76a381380d3171d15c363377c48b7ef7ba6d | 53421d85887646035dd8eaef9d45916cc037db56 | refs/heads/master | 2021-01-17T22:08:01.801653 | 2010-06-29T11:48:30 | 2010-06-29T11:48:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,870 | h |
#pragma once
#include "atlutil.h"
#include "SparkLanguagePackage_i.h"
#include "Source.h"
class ColorizerInit
{
public:
CComPtr<ISparkLanguage> _language;
CComPtr<IVsTextLines> _buffer;
int _containedLanguageColorCount;
};
class ATL_NO_VTABLE Colorizer:
public CComCreatableObject<Colorizer, ColorizerInit>,
public IVsColorizer,
public IVsColorizer2
{
CComPtr<ISparkSource> _source;
CComPtr<IVsContainedLanguageColorizer> _containedColorizer;
CComPtr<IVsColorizer> _colorizer;
long _paintLength;
SourcePainting* _paintArray;
BOOL IsNemerle()
{
BOOL test = 0;
_source->IsNemerle(&test);
return test;
}
public:
Colorizer()
{
_paintLength = 0;
_paintArray = NULL;
}
BEGIN_COM_MAP(Colorizer)
COM_INTERFACE_ENTRY(IVsColorizer)
COM_INTERFACE_ENTRY(IVsColorizer2)
END_COM_MAP()
HRESULT FinalConstruct();
/**** IVsColorizer2 ****/
STDMETHODIMP GetStateMaintenanceFlag(
/* [out] */ __RPC__out BOOL *pfFlag)
{
*pfFlag = FALSE;
return S_OK;
}
STDMETHODIMP GetStartState(
/* [out] */ __RPC__out long *piStartState)
{
*piStartState = 0;
return S_OK;
}
STDMETHODIMP_(long) ColorizeLine(
/* [in] */ long iLine,
/* [in] */ long iLength,
/* [in] */ __RPC__in const WCHAR *pszText,
/* [in] */ long iState,
/* [out] */ __RPC__out ULONG *pAttributes);
STDMETHODIMP_(long) GetStateAtEndOfLine(
/* [in] */ long iLine,
/* [in] */ long iLength,
/* [in] */ __RPC__in const WCHAR *pText,
/* [in] */ long iState)
{
return 0;
}
STDMETHODIMP_(void) CloseColorizer( void)
{
}
/**** IVsColorizer2 ****/
STDMETHODIMP BeginColorization();
STDMETHODIMP EndColorization()
{
return S_OK;
}
};
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
5
],
[
7,
22
],
[
24,
26
],
[
34,
96
]
],
[
[
6,
6
],
[
23,
23
],
[
27,
33
]
]
]
|
f239e732c0ddf3c1eb6580dc30ae623ac1ae6558 | ff5c060273aeafed9f0e5aa7018f371b8b11cdfd | /Codigo/C/UForm_Melodia.cpp | e7c01b949723723169a12810a84ec1353a11fc14 | []
| no_license | BackupTheBerlios/genaro | bb14efcdb54394e12e56159313151930d8f26d6b | 03e618a4f259cfb991929ee48004b601486d610f | refs/heads/master | 2020-04-20T19:37:21.138816 | 2008-03-25T16:15:16 | 2008-03-25T16:15:16 | 40,075,683 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 8,276 | cpp | //---------------------------------------------------------------------------
#include <vcl.h>
#include <stdio.h>
#include <stdlib.h>
#include <fstream.h>
#pragma hdrstop
#include "UForm_Melodia.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm_Melodia *Form_Melodia;
//---------------------------------------------------------------------------
__fastcall TForm_Melodia::TForm_Melodia(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void TForm_Melodia::Dibuja_Curva()
{
X_Inicial=Panel_Curva_Melodia->Left;
Y_Inicial=Panel_Curva_Melodia->Top;
Ancho=Panel_Curva_Melodia->Width;
Alto=Panel_Curva_Melodia->Height;
X_Final=X_Inicial+Ancho;
Y_Final=Y_Inicial+Alto;
this->Canvas->FillRect(Rect(X_Inicial,Y_Inicial,X_Final,Y_Final));
this->Canvas->Pen->Width=2;
this->Canvas->MoveTo(X_Inicial,Y_Inicial);
this->Canvas->LineTo(X_Inicial,Y_Final);
this->Canvas->LineTo(X_Final,Y_Final);
this->Canvas->LineTo(X_Final,Y_Inicial);
this->Canvas->LineTo(X_Inicial,Y_Inicial);
this->Canvas->Pen->Width=1;
//Dibuja_Esqueleto();
int P_X=0,P_Y=Puntos[0];
for (int i=1;i<100;i++)
{
if (Puntos[i]!=-1)
{//dibujamos puntos
//dibujamos linea
this->Canvas->MoveTo(X_Inicial+P_X*4,Y_Inicial+P_Y*Resolucion);
this->Canvas->LineTo(X_Inicial+i*4,Y_Inicial+Puntos[i]*Resolucion);
//actualizamos último punto
P_X=i;P_Y=Puntos[i];
}
}
}
//---------------------------------------------------------------------------
void __fastcall TForm_Melodia::Boton_Aceptar_MelodiaClick(TObject *Sender)
{
Dibuja_Curva();
}
//---------------------------------------------------------------------------
void TForm_Melodia::Lee_Puntos(Cancion* Music,int Fila,int Columna)
{
Musica_G=Music;
Fila_P=Fila;
Columna_P=Columna;
Bloque Bloque_A_Manipular=Musica_G->Dame_Pista(Fila_P)->Dame_Bloque(Columna_P);
if (Bloque_A_Manipular.Curva_Melodica==NULL)
{
Puntos[0]=Panel_Curva_Melodia->Height/(Resolucion*2);
Puntos[99]=Panel_Curva_Melodia->Height/(Resolucion*2);
for (int i=1;i<99;i++)
{
Puntos[i]=-1;
}
}
else
{
for (int u=0;u<100;u++)
{
Puntos[u]=-1;
}
ifstream Lectura_Puntos;
String fichero=Bloque_A_Manipular.Curva_Melodica;
// Lectura_Puntos.open(fichero.c_str());*/
char comer;
int temporal;
/* Lectura_Puntos>>comer;
if (comer!='['){ShowMessage("Error fichero de curva melódica");}
while (comer!=']')
{
Lectura_Puntos>>temporal;
Lectura_Puntos>>comer;
} */
Puntos[0]=0+(Panel_Curva_Melodia->Height/(Resolucion*2));
Puntos[99]=0+(Panel_Curva_Melodia->Height/(Resolucion*2));
Lectura_Puntos.close();
Lectura_Puntos.open(fichero.c_str());
Lectura_Puntos>>comer;
if (comer!='['){ShowMessage("Error fichero de curva melódica");}
int puntos_totales=1;
int total_puntos;
int puntos_ya_recorridos;
int Puntos_Aux[100];
int ultimo_punto_metido=Puntos[0];
float distancia;
while (comer!=']')
{
Lectura_Puntos>>temporal;
if (comer=='[')//saltamos el punto 0
{Lectura_Puntos>>comer;Lectura_Puntos>>temporal;}
Lectura_Puntos>>comer;
if (comer!=']')//insertamos el punto en puntos totales, aumentamos puntos totales y separamos
{
Puntos[puntos_totales]=Puntos[puntos_totales-1]-temporal;
ultimo_punto_metido=Puntos[puntos_totales];
puntos_totales++;
total_puntos=1;
for (int i=1;i<99;i++)
{
if (Puntos[i]!=-1){total_puntos++;}
}
//ahora calculamos cual es la distancia entre los puntos
distancia=((float)98/(float)total_puntos);
Puntos_Aux[100];
for (int p=0;p<100;p++){Puntos_Aux[p]=-1;}
Puntos_Aux[0]=Puntos[0];
Puntos_Aux[99]=Puntos[99];
puntos_ya_recorridos=1;
for (int j=1;j<99;j++)
{
if (Puntos[j]!=-1)
{
Puntos_Aux[(int)(puntos_ya_recorridos*distancia)]=Puntos[j];
puntos_ya_recorridos++;
}
}
for (int k=0;k<100;k++)
{Puntos[k]=Puntos_Aux[k];}
}
else
{
Puntos[99]=ultimo_punto_metido-temporal;
}
}
}
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
void __fastcall TForm_Melodia::FormClick(TObject *Sender)
{
TMouse* Raton;//cogemos el ratón para preguntar por su posición
int X,Y;
TPoint Posicion=Raton->CursorPos;
X=Posicion.x-(this->Left)-((this->Width-this->ClientWidth)/2);//pasamos las coordenadas del ratón (globales) a nuestra ventana
Y=Posicion.y-(this->Top)-((this->Height-this->ClientHeight)-((this->Width-this->ClientWidth)/2));
if ((X<X_Final)&&(X>X_Inicial)&&(Y<Y_Final)&&(Y>Y_Inicial))
{
if (Radio_Aniade_Puntos->Checked)
{
Puntos[(X-X_Inicial)/4]=(Y-Y_Inicial)/Resolucion;
}
if (Radio_Mover_Puntos->Checked)
{
//recorrer y buscar el púnto más cercano
int P_X,P_Y,R;
R=0;
bool punto_vacio=true;
P_Y=(Y-Y_Inicial)/Resolucion;
P_X=(X-X_Inicial)/4;
while (punto_vacio)
{
if (P_X-R>=0)
{
if (Puntos[P_X-R]!=-1){punto_vacio=false;P_X=P_X-R;}
}
if (P_X+R<=99)
{
if (Puntos[P_X+R]!=-1){punto_vacio=false;P_X=P_X+R;}
}
R++;
}
Puntos[P_X]=P_Y;
}
if (Radio_Eliminar_Puntos->Checked)
{
//recorrer y buscar el púnto más cercano
int P_X,P_Y,R;
R=0;
bool punto_vacio=true;
P_Y=(Y-Y_Inicial)/Resolucion;
P_X=(X-X_Inicial)/4;
while (punto_vacio)
{
if (P_X-R>=0)
{
if (Puntos[P_X-R]!=-1){punto_vacio=false;P_X=P_X-R;}
}
if (P_X+R<=99)
{
if (Puntos[P_X+R]!=-1){punto_vacio=false;P_X=P_X+R;}
}
R++;
}
if ((P_X!=0)&&(P_X!=99))
{Puntos[P_X]=-1;}
}
}
//buscamos cuantos puntos existen en la curva
int total_puntos=1;
for (int i=1;i<99;i++)
{
if (Puntos[i]!=-1){total_puntos++;}
}
//ahora calculamos cual es la distancia entre los puntos
float distancia=((float)98/(float)total_puntos);
int Puntos_Aux[100];
for (int p=0;p<100;p++){Puntos_Aux[p]=-1;}
Puntos_Aux[0]=Puntos[0];
Puntos_Aux[99]=Puntos[99];
int puntos_ya_recorridos=1;
for (int j=1;j<99;j++)
{
if (Puntos[j]!=-1)
{
Puntos_Aux[(int)(puntos_ya_recorridos*distancia)]=Puntos[j];
puntos_ya_recorridos++;
}
}
for (int k=0;k<100;k++)
{Puntos[k]=Puntos_Aux[k];}
Dibuja_Curva();
}
//---------------------------------------------------------------------------
void __fastcall TForm_Melodia::FormPaint(TObject *Sender)
{
Dibuja_Curva();
}
//---------------------------------------------------------------------------
void __fastcall TForm_Melodia::Button1Click(TObject *Sender)
{
Guardar_Melodia();
}
//---------------------------------------------------------------------------
void TForm_Melodia::Guardar_Melodia()
{
Bloque Bloque_A_Manipular=Musica_G->Dame_Pista(Fila_P)->Dame_Bloque(Columna_P);
//creamos fichero
ofstream fichero_salida;
//ofstream fichero_salida2;
String fichero1;
//String fichero2;
fichero1="CurvaMelodica_"+IntToStr(Fila_P)+"_"+IntToStr(Columna_P)+".cm";
//fichero2=fichero1+'b';
fichero_salida.open(fichero1.c_str());//este nos lo tendrían que dar
//fichero_salida2.open(fichero2.c_str());
int P_X;//,P_Y;
//int P_X2,P_Y2;
P_X=0;//P_Y=Puntos[P_X];
int Salto=0;
/*for (int j=0;j<100;j++)
{
fichero_salida2<<Puntos[j]<<" ";
}*/
fichero_salida<<"[0";//escribimos punto 0
for (int i=1;i<100;i++)
{
if (Puntos[i]!=-1)
{
Salto=Puntos[P_X]-Puntos[i];
fichero_salida<<","<<Salto;
P_X=i;
}
}
fichero_salida<<"]";
fichero_salida.close();
//fichero_salida2.close();
Bloque_A_Manipular.Curva_Melodica=fichero1;
Musica_G->Dame_Pista(Fila_P)->Cambia_Bloque(Bloque_A_Manipular,Columna_P);
}
//---------------------------------------------------------------------------
void __fastcall TForm_Melodia::FormCreate(TObject *Sender)
{
Resolucion=10;
}
//---------------------------------------------------------------------------
| [
"gatchan"
]
| [
[
[
1,
291
]
]
]
|
d37857a319700a6b0a389df4f20dbe207796c5ca | 4d5ee0b6f7be0c3841c050ed1dda88ec128ae7b4 | /src/nvmesh/import/UnrealFile.h | 4117eb7cb791390f583401a4b87dc107d36c7236 | []
| no_license | saggita/nvidia-mesh-tools | 9df27d41b65b9742a9d45dc67af5f6835709f0c2 | a9b7fdd808e6719be88520e14bc60d58ea57e0bd | refs/heads/master | 2020-12-24T21:37:11.053752 | 2010-09-03T01:39:02 | 2010-09-03T01:39:02 | 56,893,300 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,766 | h | // This code is in the public domain -- [email protected]
#ifndef NV_MESH_IMPORT_UNREALFILE_H
#define NV_MESH_IMPORT_UNREALFILE_H
// References:
//
// - Binary format specifications for skeletal and vertex animation source files
// http://udn.epicgames.com/Two/BinaryFormatSpecifications.html
//
// - C++ data structures
// http://udn.epicgames.com/Two/rsrc/Two/BinaryFormatSpecifications/UnrealAnimDataStructs.h
#include <nvmath/Vector.h>
#include <nvmath/Quaternion.h>
namespace nv
{
class Stream;
namespace unreal
{
// A bone: an orientation, and a position, all relative to their parent.
struct JointPos
{
Quaternion orientation;
Vector3 position; //
float length; // For collision testing / debugging drawing. (unused)
float xSize;
float ySize;
float zSize;
};
// Binary animation info format - used to organize raw animation keys into FAnimSeqs on rebuild
// Similar to MotionChunkDigestInfo..
struct AnimInfoBinary
{
char name[64]; // Animation's name
char group[64]; // Animation's group name
int totalBones; // TotalBones * NumRawFrames is number of animation keys to digest.
int rootInclude; // 0 none 1 included (unused)
int keyCompressionStyle; // Reserved: variants in tradeoffs for compression.
int keyQuotum; // Max key quotum for compression
float keyReduction; // desired
float trackTime; // explicit - can be overridden by the animation rate
float animRate; // frames per second.
int startBone; // - Reserved: for partial animations (unused)
int firstRawFrame; //
int numRawFrames; // NumRawFrames and AnimRate dictate tracktime...
};
// File header structure.
struct ChunkHeader
{
char chunkID[20]; // String ID of up to 19 chars (usually zero-terminated)
int typeFlag; // Flags/reserved
int dataSize; // Size per struct following;
int dataCount; // Number of structs/
};
// Raw data material.
struct Material
{
char materialName[64];
int textureIndex; // Texture index ('multiskin index')
uint polyFlags; // ALL poly's with THIS material will have this flag.
int auxMaterial; // Reserved: index into another material, eg. detailtexture/shininess/whatever.
uint auxFlags; // Reserved: auxiliary flags
int lodBias; // Material-specific lod bias (unused)
int lodStyle; // Material-specific lod style (unused)
};
// Raw data bone.
struct Bone
{
char name[64]; //
uint flags; // Reserved.
int numChildren; // Children (not used.)
int parentIndex; // 0/NULL if this is the root bone.
JointPos bonePos; // Reference position.
};
// Raw data bone influence.
struct RawBoneInfluence // Just weight, vertex, and Bone, sorted later.
{
float weight;
int pointIndex;
int boneIndex;
};
// An animation key.
struct QuatAnimKey
{
Vector3 position; // Relative to parent.
Quaternion orientation; // Relative to parent.
float time; // The duration until the next key (end key wraps to first...)
};
// Vertex with texturing info, akin to Hoppe's 'Wedge' concept - import only.
struct Vertex
{
uint16 pointIndex; // Index into the 3d point table.
float u, v; // Texture U, V coordinates.
uint8 matIndex; // At runtime, this one will be implied by the face that's pointing to us.
uint8 reserved; // Top secret.
};
// Points: regular FVectors
struct Point
{
Vector3 point;
};
// Textured triangle.
struct Triangle
{
uint16 wedgeIndex[3]; // Point to three vertices in the vertex list.
uint8 matIndex; // Materials can be anything.
uint8 auxMatIndex; // Second material (unused).
uint32 smoothingGroups; // 32-bit flag for smoothing groups.
};
Stream & operator << (Stream &, JointPos & );
Stream & operator << (Stream &, AnimInfoBinary & );
Stream & operator << (Stream &, ChunkHeader & );
Stream & operator << (Stream &, Material & );
Stream & operator << (Stream &, Bone & );
Stream & operator << (Stream &, RawBoneInfluence & );
Stream & operator << (Stream &, QuatAnimKey & );
Stream & operator << (Stream &, Vertex & );
Stream & operator << (Stream &, Point & );
Stream & operator << (Stream &, Triangle & );
} // unreal namespace
} // nv namespace
#endif // NV_MESH_IMPORT_UNREALFILE_H
| [
"castano@0f2971b0-9fc2-11dd-b4aa-53559073bf4c"
]
| [
[
[
1,
148
]
]
]
|
df508cce0ae7fed717b5111a2032e1686d1122b2 | e618b452106f251f3ac7cf929da9c79256c3aace | /src/lib/cpp/API/Win32/regkey.h | 5734099f37d5656e31262773797e9a3be0131a42 | []
| no_license | dlinsin/yfrog | 714957669da86deff3a093a7714e7d800c9260d8 | 513e0d64a0ff749e902e797524ad4a521ead37f8 | refs/heads/master | 2020-12-25T15:40:54.751312 | 2010-04-13T16:31:15 | 2010-04-13T16:31:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,502 | h | // RegKey.h: Registry API.
//////////////////////////////////////////////////////////////////////
#pragma once
#include "Handle.h"
namespace API {
namespace Win32 {
//////////////////////////////////////////////////////////////////////
// RegKey
//////////////////////////////////////////////////////////////////////
class RegKey : public THandle<HKEY>
{
public:
RegKey(void)
{
}
RegKey(HKEY hKey, LPCTSTR lpSubKey = NULL)
{
Create(hKey, lpSubKey);
}
virtual ~RegKey(void)
{
Close();
}
public:
// Implements Closable
virtual void Close()
{
if (IsValid()) ::RegCloseKey(handle), handle = NULL;
}
public:
BOOL Create(HKEY hKey, LPCTSTR lpSubKey = NULL)
{
HKEY hResultKey = NULL;
if (ERROR_SUCCESS != ::RegCreateKey(hKey, lpSubKey, &hResultKey))
Close();
else
Attach(hResultKey);
return IsValid();
}
BOOL CreateEx(HKEY hKey, LPCTSTR lpSubKey, LPTSTR lpClass = NULL, DWORD dwOptions = REG_OPTION_NON_VOLATILE, REGSAM samDesired = KEY_ALL_ACCESS, LPSECURITY_ATTRIBUTES lpSecurityAttributes = NULL, LPDWORD lpdwDisposition = NULL)
{
HKEY hResultKey = NULL;
if (ERROR_SUCCESS != ::RegCreateKeyEx(hKey, lpSubKey, 0, lpClass, dwOptions, samDesired, lpSecurityAttributes, &hResultKey, lpdwDisposition))
Close();
else
Attach(hResultKey);
return IsValid();
}
BOOL OpenEx(HKEY hKey, LPCTSTR lpSubKey, REGSAM samDesired = KEY_ALL_ACCESS)
{
HKEY hResultKey = NULL;
if (ERROR_SUCCESS != ::RegOpenKeyEx(hKey, lpSubKey, 0, samDesired, &hResultKey))
Close();
else
Attach(hResultKey);
return IsValid();
}
LONG QueryValueEx(LPCTSTR lpValueName, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData) const
{
ATLASSERT(IsValid());
return ::RegQueryValueEx(handle, lpValueName, NULL, lpType, lpData, lpcbData);
}
LONG SetValueEx(LPCTSTR lpValueName, DWORD dwType, const BYTE* lpData, DWORD cbData)
{
ATLASSERT(IsValid());
return ::RegSetValueEx(handle, lpValueName, 0, dwType, lpData, cbData);
}
LONG QueryValueSize(LPCTSTR lpValueName, LPDWORD lpcbData, LPDWORD lpType = NULL) const
{
ATLASSERT(IsValid());
return ::RegQueryValueEx(handle, lpValueName, NULL, lpType, NULL, lpcbData);
}
BOOL QueryValue(LPCTSTR lpValueName, DWORD &dwValue) const
{
ATLASSERT(IsValid());
dwValue = 0;
DWORD dwSize = 0, dwType = 0;
if (ERROR_SUCCESS != QueryValueSize(lpValueName, &dwSize, &dwType))
return FALSE;
if (!dwSize || dwType != REG_DWORD)
return FALSE;
return ERROR_SUCCESS == QueryValueEx(lpValueName, &dwType, reinterpret_cast<BYTE*>(&dwValue), &dwSize);
}
BOOL QueryValue(LPCTSTR lpValueName, bool &bValue) const
{
DWORD dwValue = 0;
if (!QueryValue(lpValueName, dwValue))
return FALSE;
bValue = (TRUE == dwValue);
return TRUE;
}
BOOL QueryValue(LPCTSTR lpValueName, LONGLONG &llValue) const
{
ATLASSERT(IsValid());
llValue = 0;
DWORD dwSize = 0, dwType = 0;
if (ERROR_SUCCESS != QueryValueSize(lpValueName, &dwSize, &dwType))
return FALSE;
if (!dwSize || dwType != REG_QWORD)
return FALSE;
return ERROR_SUCCESS == QueryValueEx(lpValueName, &dwType, reinterpret_cast<BYTE*>(&llValue), &dwSize);
}
BOOL QueryValue(LPCSTR lpValueName, CStringA &sValue) const
{
ATLASSERT(IsValid());
sValue.Empty();
DWORD dwSize = 0, dwType = REG_SZ;
if (ERROR_SUCCESS != ::RegQueryValueExA(handle, lpValueName, NULL, &dwType, NULL, &dwSize))
return FALSE;
// TODO: check dwType and convert to string
if (!dwSize)
return TRUE;
// Reading...
char* buf = new char[dwSize];
ZeroMemory(buf, dwSize);
LONG lResult = ::RegQueryValueExA(handle, lpValueName, NULL, &dwType, reinterpret_cast<BYTE*>(buf), &dwSize);
if (ERROR_SUCCESS == lResult)
sValue = buf;
delete [] buf, buf = NULL;
return ERROR_SUCCESS == lResult;
}
BOOL QueryValue(LPCWSTR lpValueName, CStringW &sValue) const
{
ATLASSERT(IsValid());
sValue.Empty();
DWORD dwSize = 0, dwType = REG_SZ;
if (ERROR_SUCCESS != ::RegQueryValueExW(handle, lpValueName, NULL, &dwType, NULL, &dwSize))
return FALSE;
// TODO: check dwType and convert to string
if (!dwSize)
return TRUE;
// Reading...
char* buf = new char[dwSize];
ZeroMemory(buf, dwSize);
LONG lResult = ::RegQueryValueExW(handle, lpValueName, NULL, &dwType, reinterpret_cast<BYTE*>(buf), &dwSize);
if (ERROR_SUCCESS == lResult)
sValue = (LPCWSTR)buf;
delete [] buf, buf = NULL;
return ERROR_SUCCESS == lResult;
}
BOOL QueryValue(LPCOLESTR lpValueName, CComBSTR &bsValue) const
{
ATLASSERT(IsValid());
bsValue.Empty();
DWORD dwSize = 0, dwType = REG_SZ;
if (ERROR_SUCCESS != ::RegQueryValueExW(handle, lpValueName, NULL, &dwType, NULL, &dwSize))
return FALSE;
// TODO: check dwType and convert to string
if (!dwSize)
return TRUE;
// Reading...
CComBSTR buf(dwSize/sizeof(OLECHAR) - 1);
ZeroMemory(buf, dwSize);
LONG lResult = ::RegQueryValueExW(handle, lpValueName, NULL, &dwType, (BYTE*)(BSTR)buf, &dwSize);
if (ERROR_SUCCESS == lResult)
bsValue.Attach(buf.Detach());
return ERROR_SUCCESS == lResult;
}
LONG SetValue(LPCTSTR lpValueName, const CStringA &sValue)
{
return SetValueEx(lpValueName, REG_SZ, (BYTE*)(LPCSTR)sValue, ((DWORD)sValue.GetLength())+1);
}
LONG SetValue(LPCOLESTR lpValueName, const CStringW &wsValue)
{
ATLASSERT(IsValid());
return ::RegSetValueExW(handle, lpValueName, 0, REG_SZ, (BYTE*)(LPCOLESTR)wsValue, ((DWORD)wsValue.GetLength()+1)*sizeof(WCHAR));
}
LONG SetValue(LPCOLESTR lpValueName, BSTR bsValue)
{
ATLASSERT(IsValid());
return ::RegSetValueExW(handle, lpValueName, 0, REG_SZ, (BYTE*)bsValue, ((DWORD)::SysStringLen(bsValue) + 1)*sizeof(OLECHAR));
}
LONG SetValue(LPCTSTR lpValueName, DWORD dwValue)
{
return SetValueEx(lpValueName, REG_DWORD, (BYTE*)&dwValue, sizeof(dwValue));
}
LONG SetValue(LPCTSTR lpValueName, bool bValue)
{
return SetValue(lpValueName, (DWORD)(bValue ? TRUE : FALSE));
}
LONG SetValue(LPCTSTR lpValueName, LONGLONG llValue)
{
return SetValueEx(lpValueName, REG_QWORD, (BYTE*)&llValue, sizeof(llValue));
}
LONG DeleteValue(LPCSTR lpValueName)
{
ATLASSERT(IsValid());
return ::RegDeleteValueA(handle, lpValueName);
}
LONG DeleteValue(LPCOLESTR lpValueName)
{
ATLASSERT(IsValid());
return ::RegDeleteValueW(handle, lpValueName);
}
DWORD DeleteKey(LPCTSTR lpSubKey)
{
ATLASSERT(IsValid());
return ::SHDeleteKey(handle, lpSubKey);
}
LONG EnumValue(DWORD dwIndex, LPTSTR lpValueName, LPDWORD lpcValueName, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData)
{
ATLASSERT(IsValid());
return RegEnumValue(handle, dwIndex, lpValueName, lpcValueName, NULL, lpType, lpData, lpcbData);
}
BOOL IsKeyEmpty() const
{
ATLASSERT(IsValid());
TCHAR szBuf[255];
DWORD dwBufSize = sizeof(szBuf)/sizeof(TCHAR);
FILETIME ftTemp;
return ERROR_NO_MORE_ITEMS == RegEnumKeyEx(handle, 0, szBuf, &dwBufSize, NULL, NULL, NULL, &ftTemp);
}
BOOL IsValueSet(LPCTSTR lpValueName) const
{
DWORD cbData = 0;
return ERROR_SUCCESS == QueryValueSize(lpValueName, &cbData) && cbData > 0;
}
};
//////////////////////////////////////////////////////////////////////
}; //namespace Win32
}; //namespace API
| [
"[email protected]"
]
| [
[
[
1,
305
]
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.