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
be11ca51b827b2eae8720781dceeeec50bb0d451
b7c505dcef43c0675fd89d428e45f3c2850b124f
/Src/SimulatorQt/Util/qt/Win32/include/Qt/qtestsystem.h
8d938613544d569466037522330055e35aebb2bd
[ "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
UTF-8
C++
false
false
2,581
h
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the QtTest module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QTESTSYSTEM_H #define QTESTSYSTEM_H #include <QtTest/qtestcase.h> #include <QtCore/qcoreapplication.h> #include <QtCore/qdatetime.h> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Test) namespace QTest { inline static void qWait(int ms) { Q_ASSERT(QCoreApplication::instance()); QTime timer; timer.start(); do { QCoreApplication::processEvents(QEventLoop::AllEvents, ms); QTest::qSleep(10); } while (timer.elapsed() < ms); } } QT_END_NAMESPACE QT_END_HEADER #endif
[ "alon@rogue.(none)" ]
[ [ [ 1, 74 ] ] ]
43058ed7da637dc1947e8fc972395ff161ebe89f
f6d91584f5b92a90b22a1eb09d2ce203d4185f00
/ensembl/misc-scripts/alternative_splicing/AltSplicingToolkit/src/gff/GffSimpleHandler.cpp
d016c8de72dbe4b6f972e833be743becb0e41e90
[ "LicenseRef-scancode-philippe-de-muyter", "BSD-2-Clause" ]
permissive
pamag/pmgEnsembl
8f807043bf6d0b6cfdfee934841d2af33c8d171c
ad0469e4d37171a69318f6bd1372477e85f4afb2
refs/heads/master
2021-06-01T10:58:22.839415
2011-10-18T16:09:52
2011-10-18T16:09:52
2,599,520
0
1
null
null
null
null
UTF-8
C++
false
false
2,794
cpp
/* * AltSplicingToolkit * Author: Gautier Koscielny <[email protected]> * * Copyright (c) 1999-2010 The European Bioinformatics Institute and * Genome Research Limited, and others. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * 3. The name "Ensembl" must not be used to endorse or promote products * derived from this software without prior written permission. For * written permission, please contact [email protected] * * 4. Products derived from this software may not be called "Ensembl" * nor may "Ensembl" appear in their names without prior written * permission of the Ensembl developers. * * 5. Redistributions in any form whatsoever must retain the following * acknowledgement: * * "This product includes software developed by Ensembl * (http://www.ensembl.org/)" * * THIS SOFTWARE IS PROVIDED BY THE ENSEMBL GROUP ``AS IS'' AND ANY * EXPRESSED 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 ENSEMBL GROUP OR ITS * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "GffSimpleHandler.h" namespace gff { GffSimpleHandler::GffSimpleHandler() { } GffSimpleHandler::~GffSimpleHandler() { cout << "GffSimpleHandler::~GffSimpleHandler()" << endl; } void GffSimpleHandler::start() { cout << "begin parsing." << endl; countLines = 0; } bool GffSimpleHandler::newline(string & str) { //cout << "----" << endl << str << endl; countLines++; } void GffSimpleHandler::end() { cout << countLines << " lines parsed." << endl; } }
[ [ [ 1, 78 ] ] ]
0b9331d606739f606b24b6eb66c6a38df04cbfbd
4aadb120c23f44519fbd5254e56fc91c0eb3772c
/Source/src/EduNetCommon/InstanceCount.h
e5b6e540b67b3c8e67009fe963ea5a6305f8dce5
[]
no_license
janfietz/edunetgames
d06cfb021d8f24cdcf3848a59cab694fbfd9c0ba
04d787b0afca7c99b0f4c0692002b4abb8eea410
refs/heads/master
2016-09-10T19:24:04.051842
2011-04-17T11:00:09
2011-04-17T11:00:09
33,568,741
0
0
null
null
null
null
UTF-8
C++
false
false
3,154
h
#ifndef __INSTANCECOUNT_H__ #define __INSTANCECOUNT_H__ //----------------------------------------------------------------------------- // Copyright (c) 2009, Jan Fietz, Cyrus Preuss // 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 EduNetGames nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- namespace EduNet { //----------------------------------------------------------------------------- class InstanceCount { public: InstanceCount(): m_nConstructed(0), m_nDestructed(0), m_nOnCreateCalls(0), m_nAssigned(0) { } virtual ~InstanceCount() {} size_t Constructor() { return ++this->m_nConstructed; } size_t Destructor() { return ++this->m_nDestructed; } size_t Assign() { return ++this->m_nAssigned; } size_t OnCreate() { return ++this->m_nOnCreateCalls; } size_t GetConstructedCount() const { return this->m_nConstructed; } size_t GetDestructedCount() const { return this->m_nDestructed; } size_t GetAssignCount() const { return this->m_nAssigned; } size_t GetInstanceCount() const { if (this->m_nDestructed > this->m_nConstructed) { return 0; } return this->m_nConstructed - this->m_nDestructed; } void Reset() { m_nConstructed = m_nDestructed = m_nAssigned = m_nOnCreateCalls = 0; } private: size_t m_nConstructed; size_t m_nDestructed; size_t m_nAssigned; size_t m_nOnCreateCalls; }; } // namespace EduNet #endif // __INSTANCECOUNT_H__
[ "janfietz@localhost" ]
[ [ [ 1, 104 ] ] ]
be350c029403a418e504056bd7f2df20baa44367
2f72d621e6ec03b9ea243a96e8dd947a952da087
/lol4edit/gui/h/levelsettings.h
eb9dbd8229a4aa803132ae18a68db74340b5246e
[]
no_license
gspu/lol4fg
752358c3c3431026ed025e8cb8777e4807eed7a0
12a08f3ef1126ce679ea05293fe35525065ab253
refs/heads/master
2023-04-30T05:32:03.826238
2011-07-23T23:35:14
2011-07-23T23:35:14
364,193,504
0
0
null
null
null
null
UTF-8
C++
false
false
37,725
h
/******************************************************************************** ** Form generated from reading UI file 'levelsettings.ui' ** ** Created: Wed 26. Jan 20:40:28 2011 ** by: Qt User Interface Compiler version 4.6.2 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef LEVELSETTINGS_H #define LEVELSETTINGS_H #include <QtCore/QVariant> #include <QtGui/QAction> #include <QtGui/QApplication> #include <QtGui/QButtonGroup> #include <QtGui/QCheckBox> #include <QtGui/QComboBox> #include <QtGui/QDialog> #include <QtGui/QDoubleSpinBox> #include <QtGui/QFormLayout> #include <QtGui/QGridLayout> #include <QtGui/QGroupBox> #include <QtGui/QHBoxLayout> #include <QtGui/QHeaderView> #include <QtGui/QLabel> #include <QtGui/QLineEdit> #include <QtGui/QPlainTextEdit> #include <QtGui/QPushButton> #include <QtGui/QSpacerItem> #include <QtGui/QSpinBox> #include <QtGui/QTabWidget> #include <QtGui/QToolButton> #include <QtGui/QVBoxLayout> #include <QtGui/QWidget> QT_BEGIN_NAMESPACE class Ui_LevelSettings { public: QVBoxLayout *verticalLayout_3; QTabWidget *tabWidget; QWidget *tab; QFormLayout *formLayout; QLabel *label; QLineEdit *lineEdit; QLabel *label_2; QLineEdit *lineEdit_2; QLabel *label_3; QLabel *label_4; QLineEdit *lineEdit_4; QCheckBox *checkBox; QLabel *label_5; QLabel *label_6; QComboBox *comboBox; QDoubleSpinBox *doubleSpinBox; QSpinBox *spinBox; QWidget *Seite; QVBoxLayout *verticalLayout; QCheckBox *checkBox_2; QHBoxLayout *horizontalLayout_2; QLabel *label_7; QComboBox *comboBox_2; QSpacerItem *horizontalSpacer; QGroupBox *groupBox; QGridLayout *gridLayout_2; QLabel *label_9; QLabel *label_12; QLabel *label_13; QLabel *label_10; QLabel *label_14; QLabel *label_15; QLineEdit *lineEdit_3; QLineEdit *lineEdit_6; QLineEdit *lineEdit_7; QLabel *label_11; QLabel *label_17; QLabel *label_16; QLineEdit *lineEdit_5; QLineEdit *lineEdit_8; QLineEdit *lineEdit_9; QLabel *label_8; QWidget *tab_2; QFormLayout *formLayout_2; QLabel *label_18; QHBoxLayout *horizontalLayout_3; QComboBox *comboBox_3; QSpacerItem *horizontalSpacer_2; QLabel *label_19; QLabel *label_20; QLabel *label_21; QLabel *label_22; QLineEdit *lineEdit_10; QSpinBox *spinBox_2; QSpinBox *spinBox_3; QSpinBox *spinBox_4; QWidget *Seite_2; QGridLayout *gridLayout_3; QCheckBox *checkBox_3; QGroupBox *groupBox_6; QGridLayout *gridLayout_5; QLabel *label_23; QLineEdit *lineEdit_11; QToolButton *toolButton; QLabel *label_24; QSpinBox *spinBox_5; QSpacerItem *verticalSpacer; QWidget *Seite_3; QGridLayout *gridLayout; QCheckBox *checkBox_4; QSpacerItem *verticalSpacer_2; QGroupBox *groupBox_7; QGridLayout *gridLayout_6; QLabel *label_25; QLineEdit *lineEdit_12; QToolButton *toolButton_2; QLabel *label_27; QSpinBox *spinBox_11; QLabel *label_28; QSpinBox *spinBox_10; QLabel *label_29; QSpinBox *spinBox_9; QLabel *label_30; QSpinBox *spinBox_8; QLabel *label_31; QSpinBox *spinBox_7; QLabel *label_26; QSpinBox *spinBox_6; QWidget *Seite_4; QGridLayout *gridLayout_4; QCheckBox *checkBox_5; QSpacerItem *verticalSpacer_3; QGroupBox *groupBox_8; QGridLayout *gridLayout_7; QLabel *label_38; QLineEdit *lineEdit_13; QToolButton *toolButton_3; QLabel *label_32; QSpinBox *spinBox_16; QLabel *label_33; QSpinBox *spinBox_14; QLabel *label_36; QLabel *label_35; QLabel *label_34; QSpinBox *spinBox_17; QSpinBox *spinBox_15; QSpinBox *spinBox_12; QWidget *Seite_5; QVBoxLayout *verticalLayout_7; QGroupBox *groupBox_2; QVBoxLayout *verticalLayout_2; QPlainTextEdit *plainTextEdit; QGroupBox *groupBox_3; QVBoxLayout *verticalLayout_4; QPlainTextEdit *plainTextEdit_2; QGroupBox *groupBox_4; QVBoxLayout *verticalLayout_5; QPlainTextEdit *plainTextEdit_3; QGroupBox *groupBox_5; QVBoxLayout *verticalLayout_6; QPlainTextEdit *plainTextEdit_4; QHBoxLayout *horizontalLayout_4; QLabel *label_37; QDoubleSpinBox *doubleSpinBox_2; QLabel *label_42; QDoubleSpinBox *doubleSpinBox_3; QSpacerItem *horizontalSpacer_4; QHBoxLayout *horizontalLayout; QSpacerItem *horizontalSpacer_3; QPushButton *pushButton_2; QPushButton *pushButton; void setupUi(QDialog *LevelSettings) { if (LevelSettings->objectName().isEmpty()) LevelSettings->setObjectName(QString::fromUtf8("LevelSettings")); LevelSettings->resize(486, 530); verticalLayout_3 = new QVBoxLayout(LevelSettings); verticalLayout_3->setObjectName(QString::fromUtf8("verticalLayout_3")); tabWidget = new QTabWidget(LevelSettings); tabWidget->setObjectName(QString::fromUtf8("tabWidget")); tabWidget->setEnabled(true); tab = new QWidget(); tab->setObjectName(QString::fromUtf8("tab")); formLayout = new QFormLayout(tab); formLayout->setObjectName(QString::fromUtf8("formLayout")); formLayout->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow); label = new QLabel(tab); label->setObjectName(QString::fromUtf8("label")); formLayout->setWidget(0, QFormLayout::LabelRole, label); lineEdit = new QLineEdit(tab); lineEdit->setObjectName(QString::fromUtf8("lineEdit")); formLayout->setWidget(0, QFormLayout::FieldRole, lineEdit); label_2 = new QLabel(tab); label_2->setObjectName(QString::fromUtf8("label_2")); formLayout->setWidget(1, QFormLayout::LabelRole, label_2); lineEdit_2 = new QLineEdit(tab); lineEdit_2->setObjectName(QString::fromUtf8("lineEdit_2")); formLayout->setWidget(1, QFormLayout::FieldRole, lineEdit_2); label_3 = new QLabel(tab); label_3->setObjectName(QString::fromUtf8("label_3")); formLayout->setWidget(2, QFormLayout::LabelRole, label_3); label_4 = new QLabel(tab); label_4->setObjectName(QString::fromUtf8("label_4")); formLayout->setWidget(3, QFormLayout::LabelRole, label_4); lineEdit_4 = new QLineEdit(tab); lineEdit_4->setObjectName(QString::fromUtf8("lineEdit_4")); formLayout->setWidget(3, QFormLayout::FieldRole, lineEdit_4); checkBox = new QCheckBox(tab); checkBox->setObjectName(QString::fromUtf8("checkBox")); formLayout->setWidget(4, QFormLayout::LabelRole, checkBox); label_5 = new QLabel(tab); label_5->setObjectName(QString::fromUtf8("label_5")); formLayout->setWidget(5, QFormLayout::LabelRole, label_5); label_6 = new QLabel(tab); label_6->setObjectName(QString::fromUtf8("label_6")); formLayout->setWidget(6, QFormLayout::LabelRole, label_6); comboBox = new QComboBox(tab); comboBox->setObjectName(QString::fromUtf8("comboBox")); formLayout->setWidget(6, QFormLayout::FieldRole, comboBox); doubleSpinBox = new QDoubleSpinBox(tab); doubleSpinBox->setObjectName(QString::fromUtf8("doubleSpinBox")); doubleSpinBox->setValue(9.81); formLayout->setWidget(2, QFormLayout::FieldRole, doubleSpinBox); spinBox = new QSpinBox(tab); spinBox->setObjectName(QString::fromUtf8("spinBox")); formLayout->setWidget(5, QFormLayout::FieldRole, spinBox); tabWidget->addTab(tab, QString()); Seite = new QWidget(); Seite->setObjectName(QString::fromUtf8("Seite")); verticalLayout = new QVBoxLayout(Seite); verticalLayout->setObjectName(QString::fromUtf8("verticalLayout")); checkBox_2 = new QCheckBox(Seite); checkBox_2->setObjectName(QString::fromUtf8("checkBox_2")); checkBox_2->setChecked(true); verticalLayout->addWidget(checkBox_2); horizontalLayout_2 = new QHBoxLayout(); horizontalLayout_2->setObjectName(QString::fromUtf8("horizontalLayout_2")); label_7 = new QLabel(Seite); label_7->setObjectName(QString::fromUtf8("label_7")); horizontalLayout_2->addWidget(label_7); comboBox_2 = new QComboBox(Seite); comboBox_2->setObjectName(QString::fromUtf8("comboBox_2")); horizontalLayout_2->addWidget(comboBox_2); horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout_2->addItem(horizontalSpacer); verticalLayout->addLayout(horizontalLayout_2); groupBox = new QGroupBox(Seite); groupBox->setObjectName(QString::fromUtf8("groupBox")); gridLayout_2 = new QGridLayout(groupBox); gridLayout_2->setObjectName(QString::fromUtf8("gridLayout_2")); label_9 = new QLabel(groupBox); label_9->setObjectName(QString::fromUtf8("label_9")); gridLayout_2->addWidget(label_9, 0, 0, 1, 1); label_12 = new QLabel(groupBox); label_12->setObjectName(QString::fromUtf8("label_12")); gridLayout_2->addWidget(label_12, 1, 0, 1, 1); label_13 = new QLabel(groupBox); label_13->setObjectName(QString::fromUtf8("label_13")); gridLayout_2->addWidget(label_13, 2, 0, 1, 1); label_10 = new QLabel(groupBox); label_10->setObjectName(QString::fromUtf8("label_10")); gridLayout_2->addWidget(label_10, 0, 1, 1, 1); label_14 = new QLabel(groupBox); label_14->setObjectName(QString::fromUtf8("label_14")); gridLayout_2->addWidget(label_14, 1, 1, 1, 1); label_15 = new QLabel(groupBox); label_15->setObjectName(QString::fromUtf8("label_15")); gridLayout_2->addWidget(label_15, 2, 1, 1, 1); lineEdit_3 = new QLineEdit(groupBox); lineEdit_3->setObjectName(QString::fromUtf8("lineEdit_3")); gridLayout_2->addWidget(lineEdit_3, 0, 2, 1, 1); lineEdit_6 = new QLineEdit(groupBox); lineEdit_6->setObjectName(QString::fromUtf8("lineEdit_6")); gridLayout_2->addWidget(lineEdit_6, 1, 2, 1, 1); lineEdit_7 = new QLineEdit(groupBox); lineEdit_7->setObjectName(QString::fromUtf8("lineEdit_7")); gridLayout_2->addWidget(lineEdit_7, 2, 2, 1, 1); label_11 = new QLabel(groupBox); label_11->setObjectName(QString::fromUtf8("label_11")); gridLayout_2->addWidget(label_11, 0, 3, 1, 1); label_17 = new QLabel(groupBox); label_17->setObjectName(QString::fromUtf8("label_17")); gridLayout_2->addWidget(label_17, 1, 3, 1, 1); label_16 = new QLabel(groupBox); label_16->setObjectName(QString::fromUtf8("label_16")); gridLayout_2->addWidget(label_16, 2, 3, 1, 1); lineEdit_5 = new QLineEdit(groupBox); lineEdit_5->setObjectName(QString::fromUtf8("lineEdit_5")); gridLayout_2->addWidget(lineEdit_5, 0, 4, 1, 1); lineEdit_8 = new QLineEdit(groupBox); lineEdit_8->setObjectName(QString::fromUtf8("lineEdit_8")); gridLayout_2->addWidget(lineEdit_8, 1, 4, 1, 1); lineEdit_9 = new QLineEdit(groupBox); lineEdit_9->setObjectName(QString::fromUtf8("lineEdit_9")); gridLayout_2->addWidget(lineEdit_9, 2, 4, 1, 1); verticalLayout->addWidget(groupBox); label_8 = new QLabel(Seite); label_8->setObjectName(QString::fromUtf8("label_8")); label_8->setWordWrap(true); verticalLayout->addWidget(label_8); tabWidget->addTab(Seite, QString()); tab_2 = new QWidget(); tab_2->setObjectName(QString::fromUtf8("tab_2")); formLayout_2 = new QFormLayout(tab_2); formLayout_2->setObjectName(QString::fromUtf8("formLayout_2")); label_18 = new QLabel(tab_2); label_18->setObjectName(QString::fromUtf8("label_18")); formLayout_2->setWidget(0, QFormLayout::LabelRole, label_18); horizontalLayout_3 = new QHBoxLayout(); horizontalLayout_3->setObjectName(QString::fromUtf8("horizontalLayout_3")); comboBox_3 = new QComboBox(tab_2); comboBox_3->setObjectName(QString::fromUtf8("comboBox_3")); horizontalLayout_3->addWidget(comboBox_3); horizontalSpacer_2 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout_3->addItem(horizontalSpacer_2); formLayout_2->setLayout(0, QFormLayout::FieldRole, horizontalLayout_3); label_19 = new QLabel(tab_2); label_19->setObjectName(QString::fromUtf8("label_19")); formLayout_2->setWidget(1, QFormLayout::LabelRole, label_19); label_20 = new QLabel(tab_2); label_20->setObjectName(QString::fromUtf8("label_20")); formLayout_2->setWidget(2, QFormLayout::LabelRole, label_20); label_21 = new QLabel(tab_2); label_21->setObjectName(QString::fromUtf8("label_21")); formLayout_2->setWidget(3, QFormLayout::LabelRole, label_21); label_22 = new QLabel(tab_2); label_22->setObjectName(QString::fromUtf8("label_22")); formLayout_2->setWidget(4, QFormLayout::LabelRole, label_22); lineEdit_10 = new QLineEdit(tab_2); lineEdit_10->setObjectName(QString::fromUtf8("lineEdit_10")); formLayout_2->setWidget(1, QFormLayout::FieldRole, lineEdit_10); spinBox_2 = new QSpinBox(tab_2); spinBox_2->setObjectName(QString::fromUtf8("spinBox_2")); formLayout_2->setWidget(2, QFormLayout::FieldRole, spinBox_2); spinBox_3 = new QSpinBox(tab_2); spinBox_3->setObjectName(QString::fromUtf8("spinBox_3")); formLayout_2->setWidget(3, QFormLayout::FieldRole, spinBox_3); spinBox_4 = new QSpinBox(tab_2); spinBox_4->setObjectName(QString::fromUtf8("spinBox_4")); formLayout_2->setWidget(4, QFormLayout::FieldRole, spinBox_4); tabWidget->addTab(tab_2, QString()); Seite_2 = new QWidget(); Seite_2->setObjectName(QString::fromUtf8("Seite_2")); gridLayout_3 = new QGridLayout(Seite_2); gridLayout_3->setObjectName(QString::fromUtf8("gridLayout_3")); checkBox_3 = new QCheckBox(Seite_2); checkBox_3->setObjectName(QString::fromUtf8("checkBox_3")); gridLayout_3->addWidget(checkBox_3, 0, 0, 1, 1); groupBox_6 = new QGroupBox(Seite_2); groupBox_6->setObjectName(QString::fromUtf8("groupBox_6")); groupBox_6->setEnabled(false); gridLayout_5 = new QGridLayout(groupBox_6); gridLayout_5->setObjectName(QString::fromUtf8("gridLayout_5")); label_23 = new QLabel(groupBox_6); label_23->setObjectName(QString::fromUtf8("label_23")); gridLayout_5->addWidget(label_23, 0, 0, 1, 1); lineEdit_11 = new QLineEdit(groupBox_6); lineEdit_11->setObjectName(QString::fromUtf8("lineEdit_11")); gridLayout_5->addWidget(lineEdit_11, 0, 1, 1, 1); toolButton = new QToolButton(groupBox_6); toolButton->setObjectName(QString::fromUtf8("toolButton")); gridLayout_5->addWidget(toolButton, 0, 2, 1, 1); label_24 = new QLabel(groupBox_6); label_24->setObjectName(QString::fromUtf8("label_24")); gridLayout_5->addWidget(label_24, 1, 0, 1, 1); spinBox_5 = new QSpinBox(groupBox_6); spinBox_5->setObjectName(QString::fromUtf8("spinBox_5")); gridLayout_5->addWidget(spinBox_5, 1, 1, 1, 1); gridLayout_3->addWidget(groupBox_6, 2, 0, 1, 1); verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); gridLayout_3->addItem(verticalSpacer, 4, 0, 1, 1); tabWidget->addTab(Seite_2, QString()); Seite_3 = new QWidget(); Seite_3->setObjectName(QString::fromUtf8("Seite_3")); gridLayout = new QGridLayout(Seite_3); gridLayout->setObjectName(QString::fromUtf8("gridLayout")); checkBox_4 = new QCheckBox(Seite_3); checkBox_4->setObjectName(QString::fromUtf8("checkBox_4")); gridLayout->addWidget(checkBox_4, 0, 0, 1, 1); verticalSpacer_2 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); gridLayout->addItem(verticalSpacer_2, 9, 0, 1, 1); groupBox_7 = new QGroupBox(Seite_3); groupBox_7->setObjectName(QString::fromUtf8("groupBox_7")); groupBox_7->setEnabled(false); gridLayout_6 = new QGridLayout(groupBox_7); gridLayout_6->setObjectName(QString::fromUtf8("gridLayout_6")); label_25 = new QLabel(groupBox_7); label_25->setObjectName(QString::fromUtf8("label_25")); gridLayout_6->addWidget(label_25, 0, 0, 1, 1); lineEdit_12 = new QLineEdit(groupBox_7); lineEdit_12->setObjectName(QString::fromUtf8("lineEdit_12")); gridLayout_6->addWidget(lineEdit_12, 0, 1, 1, 1); toolButton_2 = new QToolButton(groupBox_7); toolButton_2->setObjectName(QString::fromUtf8("toolButton_2")); gridLayout_6->addWidget(toolButton_2, 0, 2, 1, 1); label_27 = new QLabel(groupBox_7); label_27->setObjectName(QString::fromUtf8("label_27")); gridLayout_6->addWidget(label_27, 1, 0, 1, 1); spinBox_11 = new QSpinBox(groupBox_7); spinBox_11->setObjectName(QString::fromUtf8("spinBox_11")); gridLayout_6->addWidget(spinBox_11, 1, 1, 1, 1); label_28 = new QLabel(groupBox_7); label_28->setObjectName(QString::fromUtf8("label_28")); gridLayout_6->addWidget(label_28, 2, 0, 1, 1); spinBox_10 = new QSpinBox(groupBox_7); spinBox_10->setObjectName(QString::fromUtf8("spinBox_10")); gridLayout_6->addWidget(spinBox_10, 2, 1, 1, 1); label_29 = new QLabel(groupBox_7); label_29->setObjectName(QString::fromUtf8("label_29")); gridLayout_6->addWidget(label_29, 3, 0, 1, 1); spinBox_9 = new QSpinBox(groupBox_7); spinBox_9->setObjectName(QString::fromUtf8("spinBox_9")); gridLayout_6->addWidget(spinBox_9, 3, 1, 1, 1); label_30 = new QLabel(groupBox_7); label_30->setObjectName(QString::fromUtf8("label_30")); gridLayout_6->addWidget(label_30, 4, 0, 1, 1); spinBox_8 = new QSpinBox(groupBox_7); spinBox_8->setObjectName(QString::fromUtf8("spinBox_8")); gridLayout_6->addWidget(spinBox_8, 4, 1, 1, 1); label_31 = new QLabel(groupBox_7); label_31->setObjectName(QString::fromUtf8("label_31")); gridLayout_6->addWidget(label_31, 5, 0, 1, 1); spinBox_7 = new QSpinBox(groupBox_7); spinBox_7->setObjectName(QString::fromUtf8("spinBox_7")); gridLayout_6->addWidget(spinBox_7, 5, 1, 1, 1); label_26 = new QLabel(groupBox_7); label_26->setObjectName(QString::fromUtf8("label_26")); gridLayout_6->addWidget(label_26, 6, 0, 1, 1); spinBox_6 = new QSpinBox(groupBox_7); spinBox_6->setObjectName(QString::fromUtf8("spinBox_6")); gridLayout_6->addWidget(spinBox_6, 6, 1, 1, 1); gridLayout->addWidget(groupBox_7, 8, 0, 1, 2); tabWidget->addTab(Seite_3, QString()); Seite_4 = new QWidget(); Seite_4->setObjectName(QString::fromUtf8("Seite_4")); gridLayout_4 = new QGridLayout(Seite_4); gridLayout_4->setObjectName(QString::fromUtf8("gridLayout_4")); checkBox_5 = new QCheckBox(Seite_4); checkBox_5->setObjectName(QString::fromUtf8("checkBox_5")); gridLayout_4->addWidget(checkBox_5, 0, 0, 1, 1); verticalSpacer_3 = new QSpacerItem(443, 216, QSizePolicy::Minimum, QSizePolicy::Expanding); gridLayout_4->addItem(verticalSpacer_3, 8, 0, 1, 1); groupBox_8 = new QGroupBox(Seite_4); groupBox_8->setObjectName(QString::fromUtf8("groupBox_8")); groupBox_8->setEnabled(false); gridLayout_7 = new QGridLayout(groupBox_8); gridLayout_7->setObjectName(QString::fromUtf8("gridLayout_7")); label_38 = new QLabel(groupBox_8); label_38->setObjectName(QString::fromUtf8("label_38")); gridLayout_7->addWidget(label_38, 0, 0, 1, 1); lineEdit_13 = new QLineEdit(groupBox_8); lineEdit_13->setObjectName(QString::fromUtf8("lineEdit_13")); gridLayout_7->addWidget(lineEdit_13, 0, 1, 1, 1); toolButton_3 = new QToolButton(groupBox_8); toolButton_3->setObjectName(QString::fromUtf8("toolButton_3")); gridLayout_7->addWidget(toolButton_3, 0, 2, 1, 1); label_32 = new QLabel(groupBox_8); label_32->setObjectName(QString::fromUtf8("label_32")); gridLayout_7->addWidget(label_32, 1, 0, 1, 1); spinBox_16 = new QSpinBox(groupBox_8); spinBox_16->setObjectName(QString::fromUtf8("spinBox_16")); gridLayout_7->addWidget(spinBox_16, 1, 1, 1, 1); label_33 = new QLabel(groupBox_8); label_33->setObjectName(QString::fromUtf8("label_33")); gridLayout_7->addWidget(label_33, 2, 0, 1, 1); spinBox_14 = new QSpinBox(groupBox_8); spinBox_14->setObjectName(QString::fromUtf8("spinBox_14")); gridLayout_7->addWidget(spinBox_14, 2, 1, 1, 1); label_36 = new QLabel(groupBox_8); label_36->setObjectName(QString::fromUtf8("label_36")); gridLayout_7->addWidget(label_36, 3, 0, 1, 1); label_35 = new QLabel(groupBox_8); label_35->setObjectName(QString::fromUtf8("label_35")); gridLayout_7->addWidget(label_35, 4, 0, 1, 1); label_34 = new QLabel(groupBox_8); label_34->setObjectName(QString::fromUtf8("label_34")); gridLayout_7->addWidget(label_34, 5, 0, 1, 1); spinBox_17 = new QSpinBox(groupBox_8); spinBox_17->setObjectName(QString::fromUtf8("spinBox_17")); gridLayout_7->addWidget(spinBox_17, 3, 1, 1, 1); spinBox_15 = new QSpinBox(groupBox_8); spinBox_15->setObjectName(QString::fromUtf8("spinBox_15")); gridLayout_7->addWidget(spinBox_15, 4, 1, 1, 1); spinBox_12 = new QSpinBox(groupBox_8); spinBox_12->setObjectName(QString::fromUtf8("spinBox_12")); gridLayout_7->addWidget(spinBox_12, 5, 1, 1, 1); gridLayout_4->addWidget(groupBox_8, 7, 0, 1, 1); tabWidget->addTab(Seite_4, QString()); Seite_5 = new QWidget(); Seite_5->setObjectName(QString::fromUtf8("Seite_5")); verticalLayout_7 = new QVBoxLayout(Seite_5); verticalLayout_7->setObjectName(QString::fromUtf8("verticalLayout_7")); groupBox_2 = new QGroupBox(Seite_5); groupBox_2->setObjectName(QString::fromUtf8("groupBox_2")); verticalLayout_2 = new QVBoxLayout(groupBox_2); verticalLayout_2->setObjectName(QString::fromUtf8("verticalLayout_2")); plainTextEdit = new QPlainTextEdit(groupBox_2); plainTextEdit->setObjectName(QString::fromUtf8("plainTextEdit")); verticalLayout_2->addWidget(plainTextEdit); verticalLayout_7->addWidget(groupBox_2); groupBox_3 = new QGroupBox(Seite_5); groupBox_3->setObjectName(QString::fromUtf8("groupBox_3")); verticalLayout_4 = new QVBoxLayout(groupBox_3); verticalLayout_4->setObjectName(QString::fromUtf8("verticalLayout_4")); plainTextEdit_2 = new QPlainTextEdit(groupBox_3); plainTextEdit_2->setObjectName(QString::fromUtf8("plainTextEdit_2")); verticalLayout_4->addWidget(plainTextEdit_2); verticalLayout_7->addWidget(groupBox_3); groupBox_4 = new QGroupBox(Seite_5); groupBox_4->setObjectName(QString::fromUtf8("groupBox_4")); verticalLayout_5 = new QVBoxLayout(groupBox_4); verticalLayout_5->setObjectName(QString::fromUtf8("verticalLayout_5")); plainTextEdit_3 = new QPlainTextEdit(groupBox_4); plainTextEdit_3->setObjectName(QString::fromUtf8("plainTextEdit_3")); verticalLayout_5->addWidget(plainTextEdit_3); verticalLayout_7->addWidget(groupBox_4); groupBox_5 = new QGroupBox(Seite_5); groupBox_5->setObjectName(QString::fromUtf8("groupBox_5")); verticalLayout_6 = new QVBoxLayout(groupBox_5); verticalLayout_6->setObjectName(QString::fromUtf8("verticalLayout_6")); plainTextEdit_4 = new QPlainTextEdit(groupBox_5); plainTextEdit_4->setObjectName(QString::fromUtf8("plainTextEdit_4")); verticalLayout_6->addWidget(plainTextEdit_4); horizontalLayout_4 = new QHBoxLayout(); horizontalLayout_4->setObjectName(QString::fromUtf8("horizontalLayout_4")); label_37 = new QLabel(groupBox_5); label_37->setObjectName(QString::fromUtf8("label_37")); horizontalLayout_4->addWidget(label_37); doubleSpinBox_2 = new QDoubleSpinBox(groupBox_5); doubleSpinBox_2->setObjectName(QString::fromUtf8("doubleSpinBox_2")); horizontalLayout_4->addWidget(doubleSpinBox_2); label_42 = new QLabel(groupBox_5); label_42->setObjectName(QString::fromUtf8("label_42")); horizontalLayout_4->addWidget(label_42); doubleSpinBox_3 = new QDoubleSpinBox(groupBox_5); doubleSpinBox_3->setObjectName(QString::fromUtf8("doubleSpinBox_3")); horizontalLayout_4->addWidget(doubleSpinBox_3); horizontalSpacer_4 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout_4->addItem(horizontalSpacer_4); verticalLayout_6->addLayout(horizontalLayout_4); verticalLayout_7->addWidget(groupBox_5); tabWidget->addTab(Seite_5, QString()); verticalLayout_3->addWidget(tabWidget); horizontalLayout = new QHBoxLayout(); horizontalLayout->setObjectName(QString::fromUtf8("horizontalLayout")); horizontalSpacer_3 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout->addItem(horizontalSpacer_3); pushButton_2 = new QPushButton(LevelSettings); pushButton_2->setObjectName(QString::fromUtf8("pushButton_2")); horizontalLayout->addWidget(pushButton_2); pushButton = new QPushButton(LevelSettings); pushButton->setObjectName(QString::fromUtf8("pushButton")); pushButton->setDefault(true); horizontalLayout->addWidget(pushButton); verticalLayout_3->addLayout(horizontalLayout); retranslateUi(LevelSettings); QObject::connect(checkBox_2, SIGNAL(toggled(bool)), comboBox_2, SLOT(setEnabled(bool))); QObject::connect(checkBox_2, SIGNAL(toggled(bool)), groupBox, SLOT(setEnabled(bool))); QObject::connect(pushButton_2, SIGNAL(clicked()), LevelSettings, SLOT(close())); QObject::connect(checkBox_3, SIGNAL(toggled(bool)), groupBox_6, SLOT(setEnabled(bool))); QObject::connect(checkBox_4, SIGNAL(toggled(bool)), groupBox_7, SLOT(setEnabled(bool))); QObject::connect(checkBox_5, SIGNAL(toggled(bool)), groupBox_8, SLOT(setEnabled(bool))); tabWidget->setCurrentIndex(0); QMetaObject::connectSlotsByName(LevelSettings); } // setupUi void retranslateUi(QDialog *LevelSettings) { LevelSettings->setWindowTitle(QApplication::translate("LevelSettings", "Dialog", 0, QApplication::UnicodeUTF8)); label->setText(QApplication::translate("LevelSettings", "Ambient Colour", 0, QApplication::UnicodeUTF8)); label_2->setText(QApplication::translate("LevelSettings", "Background Colour", 0, QApplication::UnicodeUTF8)); label_3->setText(QApplication::translate("LevelSettings", "Gravity", 0, QApplication::UnicodeUTF8)); label_4->setText(QApplication::translate("LevelSettings", "Name", 0, QApplication::UnicodeUTF8)); checkBox->setText(QApplication::translate("LevelSettings", "use paging", 0, QApplication::UnicodeUTF8)); label_5->setText(QApplication::translate("LevelSettings", "Page size", 0, QApplication::UnicodeUTF8)); label_6->setText(QApplication::translate("LevelSettings", "Level Type", 0, QApplication::UnicodeUTF8)); tabWidget->setTabText(tabWidget->indexOf(tab), QApplication::translate("LevelSettings", "Level", 0, QApplication::UnicodeUTF8)); checkBox_2->setText(QApplication::translate("LevelSettings", "Use Terrain", 0, QApplication::UnicodeUTF8)); label_7->setText(QApplication::translate("LevelSettings", "TextLabel", 0, QApplication::UnicodeUTF8)); comboBox_2->clear(); comboBox_2->insertItems(0, QStringList() << QApplication::translate("LevelSettings", "64x64", 0, QApplication::UnicodeUTF8) << QApplication::translate("LevelSettings", "128x128", 0, QApplication::UnicodeUTF8) << QApplication::translate("LevelSettings", "256x256", 0, QApplication::UnicodeUTF8) << QApplication::translate("LevelSettings", "512x512", 0, QApplication::UnicodeUTF8) << QApplication::translate("LevelSettings", "1024x1024", 0, QApplication::UnicodeUTF8) ); groupBox->setTitle(QApplication::translate("LevelSettings", "Advanced Resolutions", 0, QApplication::UnicodeUTF8)); label_9->setText(QApplication::translate("LevelSettings", "Heightmap:", 0, QApplication::UnicodeUTF8)); label_12->setText(QApplication::translate("LevelSettings", "Covmap:", 0, QApplication::UnicodeUTF8)); label_13->setText(QApplication::translate("LevelSettings", "Lightmap:", 0, QApplication::UnicodeUTF8)); label_10->setText(QApplication::translate("LevelSettings", "X:", 0, QApplication::UnicodeUTF8)); label_14->setText(QApplication::translate("LevelSettings", "X:", 0, QApplication::UnicodeUTF8)); label_15->setText(QApplication::translate("LevelSettings", "X:", 0, QApplication::UnicodeUTF8)); label_11->setText(QApplication::translate("LevelSettings", "Z:", 0, QApplication::UnicodeUTF8)); label_17->setText(QApplication::translate("LevelSettings", "Z:", 0, QApplication::UnicodeUTF8)); label_16->setText(QApplication::translate("LevelSettings", "Z:", 0, QApplication::UnicodeUTF8)); label_8->setText(QApplication::translate("LevelSettings", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;\">\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:8pt;\">Warning:</span></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:8pt;\">Any changes here will reset the existing terrain!</span></p></body></html>", 0, QApplication::UnicodeUTF8)); tabWidget->setTabText(tabWidget->indexOf(Seite), QApplication::translate("LevelSettings", "Terrain", 0, QApplication::UnicodeUTF8)); label_18->setText(QApplication::translate("LevelSettings", "Fog Type", 0, QApplication::UnicodeUTF8)); comboBox_3->clear(); comboBox_3->insertItems(0, QStringList() << QApplication::translate("LevelSettings", "None", 0, QApplication::UnicodeUTF8) << QApplication::translate("LevelSettings", "Linear", 0, QApplication::UnicodeUTF8) << QApplication::translate("LevelSettings", "Ext1", 0, QApplication::UnicodeUTF8) << QApplication::translate("LevelSettings", "Ext2", 0, QApplication::UnicodeUTF8) ); label_19->setText(QApplication::translate("LevelSettings", "Color", 0, QApplication::UnicodeUTF8)); label_20->setText(QApplication::translate("LevelSettings", "Density", 0, QApplication::UnicodeUTF8)); label_21->setText(QApplication::translate("LevelSettings", "Linear Start", 0, QApplication::UnicodeUTF8)); label_22->setText(QApplication::translate("LevelSettings", "Linear End", 0, QApplication::UnicodeUTF8)); tabWidget->setTabText(tabWidget->indexOf(tab_2), QApplication::translate("LevelSettings", "Fog", 0, QApplication::UnicodeUTF8)); checkBox_3->setText(QApplication::translate("LevelSettings", "Use Skybox", 0, QApplication::UnicodeUTF8)); groupBox_6->setTitle(QApplication::translate("LevelSettings", "Skybox Settings", 0, QApplication::UnicodeUTF8)); label_23->setText(QApplication::translate("LevelSettings", "Material:", 0, QApplication::UnicodeUTF8)); toolButton->setText(QApplication::translate("LevelSettings", "...", 0, QApplication::UnicodeUTF8)); label_24->setText(QApplication::translate("LevelSettings", "Distance:", 0, QApplication::UnicodeUTF8)); tabWidget->setTabText(tabWidget->indexOf(Seite_2), QApplication::translate("LevelSettings", "SkyBox", 0, QApplication::UnicodeUTF8)); checkBox_4->setText(QApplication::translate("LevelSettings", "Use Skyplane", 0, QApplication::UnicodeUTF8)); groupBox_7->setTitle(QApplication::translate("LevelSettings", "Skyplane Settings", 0, QApplication::UnicodeUTF8)); label_25->setText(QApplication::translate("LevelSettings", "Material:", 0, QApplication::UnicodeUTF8)); toolButton_2->setText(QApplication::translate("LevelSettings", "...", 0, QApplication::UnicodeUTF8)); label_27->setText(QApplication::translate("LevelSettings", "Scale", 0, QApplication::UnicodeUTF8)); label_28->setText(QApplication::translate("LevelSettings", "Tiling", 0, QApplication::UnicodeUTF8)); label_29->setText(QApplication::translate("LevelSettings", "xSeg", 0, QApplication::UnicodeUTF8)); label_30->setText(QApplication::translate("LevelSettings", "ySeg", 0, QApplication::UnicodeUTF8)); label_31->setText(QApplication::translate("LevelSettings", "Bow", 0, QApplication::UnicodeUTF8)); label_26->setText(QApplication::translate("LevelSettings", "Distance:", 0, QApplication::UnicodeUTF8)); tabWidget->setTabText(tabWidget->indexOf(Seite_3), QApplication::translate("LevelSettings", "SkyPlane", 0, QApplication::UnicodeUTF8)); checkBox_5->setText(QApplication::translate("LevelSettings", "Use Skydome", 0, QApplication::UnicodeUTF8)); groupBox_8->setTitle(QApplication::translate("LevelSettings", "Skydome Settings", 0, QApplication::UnicodeUTF8)); label_38->setText(QApplication::translate("LevelSettings", "Material:", 0, QApplication::UnicodeUTF8)); toolButton_3->setText(QApplication::translate("LevelSettings", "...", 0, QApplication::UnicodeUTF8)); label_32->setText(QApplication::translate("LevelSettings", "Curvature", 0, QApplication::UnicodeUTF8)); label_33->setText(QApplication::translate("LevelSettings", "Tiling", 0, QApplication::UnicodeUTF8)); label_36->setText(QApplication::translate("LevelSettings", "xSeg", 0, QApplication::UnicodeUTF8)); label_35->setText(QApplication::translate("LevelSettings", "ySeg", 0, QApplication::UnicodeUTF8)); label_34->setText(QApplication::translate("LevelSettings", "Distance:", 0, QApplication::UnicodeUTF8)); tabWidget->setTabText(tabWidget->indexOf(Seite_4), QApplication::translate("LevelSettings", "SkyDome", 0, QApplication::UnicodeUTF8)); groupBox_2->setTitle(QApplication::translate("LevelSettings", "Music Explore", 0, QApplication::UnicodeUTF8)); groupBox_3->setTitle(QApplication::translate("LevelSettings", "Music Battle", 0, QApplication::UnicodeUTF8)); groupBox_4->setTitle(QApplication::translate("LevelSettings", "Loop Ambient", 0, QApplication::UnicodeUTF8)); groupBox_5->setTitle(QApplication::translate("LevelSettings", "Random Ambient", 0, QApplication::UnicodeUTF8)); label_37->setText(QApplication::translate("LevelSettings", "Min", 0, QApplication::UnicodeUTF8)); label_42->setText(QApplication::translate("LevelSettings", "Max", 0, QApplication::UnicodeUTF8)); tabWidget->setTabText(tabWidget->indexOf(Seite_5), QApplication::translate("LevelSettings", "Sound", 0, QApplication::UnicodeUTF8)); pushButton_2->setText(QApplication::translate("LevelSettings", "Cancel", 0, QApplication::UnicodeUTF8)); pushButton->setText(QApplication::translate("LevelSettings", "OK", 0, QApplication::UnicodeUTF8)); } // retranslateUi }; namespace Ui { class LevelSettings: public Ui_LevelSettings {}; } // namespace Ui QT_END_NAMESPACE #endif // LEVELSETTINGS_H
[ "praecipitator@bd7a9385-7eed-4fd6-88b1-0096df50a1ac" ]
[ [ [ 1, 886 ] ] ]
3422274099e298d0823a0e9c804a213220e48e26
f7d5fcb47d370751163d253ac0d705d52bd3c5d5
/trunk/Sources/source/hapticgraphclasses/DragNodeOnGridHandler.h
1e0355d7defc830a3769e71c70bbb97fcb823207
[]
no_license
BackupTheBerlios/phantom-graphs-svn
b830eadf54c49ccecf2653e798e3a82af7e0e78d
6a585ecde8432394c732a72e4860e136d68cc4b4
refs/heads/master
2021-01-02T09:21:18.231965
2006-02-06T08:44:57
2006-02-06T08:44:57
40,820,960
0
0
null
null
null
null
ISO-8859-1
C++
false
false
8,036
h
//******************************************************************************* /// @file DragNodeOnGridHandler.h /// @author Katharina Greiner, Matr.-Nr. 943471 /// @date Erstellt am 23.01.2006 /// @date Letzte ร„nderung 23.01.2006 //******************************************************************************* // ร„nderungen: #ifndef _DRAGNODEONGRIDHANDLER_H_ #define _DRAGNODEONGRIDHANDLER_H_ #include "HapticAction.h" #include "Node.h" #include "Grid.h" #include "Utilities.h" // ............................................................................... /// @author Katharina Greiner, Matr.-Nr. 943471 /// /// @brief Eine Eventhandlerklasse die es ermรถglicht, haptische Nodes mit dem /// Phantom in x-Richtung auf einem Grid zu bewegen. /// /// Der Eventhandler reagiert auf die folgende Events: /// - der vordere Phantom-Button wird gedrรผckt, wenn ein Objekt mit dem /// Phantom berรผhrt wird /// - das Phantom wird mit gedrรผcktem Button bewegt /// - der vordere Phantom-Button wird losgelassen /// Wirkung: Der Node folgt den Bewegungen des Phantom in x-Richtung. Die /// Bewegung des Phantom in y- und z-Richtung wird von dem Node ignoriert. /// Beim Loslassen des Buttons rastet der Node an dem nรคchstgelegenen /// Gitterpunkt ein. //............................................................................... class DragNodeOnGridHandler : public IHapticAction { protected: //....................................................................... /// @brief Der Node, dem der Eventhandler zugeordnet ist. //....................................................................... Node * m_pDragObj; //....................................................................... /// @brief Das Grid, auf dem der Node verschoben werden soll. //....................................................................... Grid * m_pGrid; // ....................................................................... /// @brief Position des Proxy beim letzten Aufruf des Draghandlers. Dient /// zur Berechnung des Vektors um den das Objekt verschoben werden soll. // ....................................................................... hduVector3Dd m_LastProxyPos; //....................................................................... /// @brief (HLAPI-Callbackfunktion) Started das Draggen des Objekts. /// @param event Gibt an, auf welches HLAPI-Event hin die Callback- /// Funktion aufgerufen werden soll, hier HL_EVENT_1BUTTONDOWN. /// @param shapeID Die ShapeID des Objekts, das bewegt werden soll. /// @param thread Gibt an, in welchem HLAPI-Thread das Event behandelt /// werden soll, in diesem Fall HL_CLIENT_THREAD. /// @param cache HLAPI-State Schnappschuss in dem Moment, in dem das Event feuert. /// @param pHandlerObject Pointer auf das DragNodeOnGridHandler-Objekt, /// das das Event verarbeiten soll. //....................................................................... static void HLCALLBACK OnButtonDown(HLenum event, HLuint shapeID, HLenum thread, HLcache * cache, void * pHandlerObject ); //....................................................................... /// @brief (HLAPI-Callbackfunktion) Beendet das Draggen des Objekts. /// @param event Gibt an, auf welches HLAPI-Event hin die Callback- /// Funktion aufgerufen werden soll, hier HL_EVENT_1BUTTONUP. /// @param shapeID Hier soll HL_OBJECT_ANY angegeben werden. /// @param thread Gibt an, in welchem HLAPI-Thread das Event behandelt /// werden soll, in diesem Fall HL_CLIENT_THREAD. /// @param cache HLAPI-State Schnappschuss in dem Moment, in dem das Event feuert. /// @param pHandlerObject Pointer auf das DragNodeOnGridHandler-Objekt, /// das das Event verarbeiten soll. //....................................................................... static void HLCALLBACK OnButtonUp( HLenum event, HLuint shapeID, HLenum thread, HLcache * cache, void * pHandlerObject); //....................................................................... /// @brief (HLAPI-Callbackfunktion) Steuert das Draggen des Objekts. /// @param event Gibt an, auf welches HLAPI-Event hin die Callback- /// Funktion aufgerufen werden soll, hier HL_EVENT_MOTION /// @param shapeID Hier soll HL_OBJECT_ANY angegeben werden. /// @param thread Gibt an, in welchem HLAPI-Thread das Event behandelt /// werden soll, in diesem Fall HL_CLIENT_THREAD. /// @param cache HLAPI-State Schnappschuss in dem Moment, in dem das Event feuert. /// @param pHandlerObject Pointer auf das DragNodeOnGridHandler-Objekt, /// das das Event verarbeiten soll. //....................................................................... static void HLCALLBACK OnDrag( HLenum event, HLuint shapeID, HLenum thread, HLcache * cache, void * pHandlerObject ); public: //....................................................................... /// @brief Konstruktor, initialisiert das Eventhandler-Objekt mit dem /// zugehรถrigen Node und dem Grid, auf dem dieser bewegt werden soll. /// @param pNode Pointer auf den Node fรผr den der Eventhandler /// zustรคndig sein soll. /// @param pGrid Pointer auf das Grid, auf dem der Node bewegt werden soll. //....................................................................... DragNodeOnGridHandler( Node* pNode, Grid * pGrid ); //....................................................................... /// @brief Destruktor: Gibt die Resourcen des Objektes frei. //....................................................................... virtual ~DragNodeOnGridHandler(); //....................................................................... /// @brief Nimmt die Proxy-Position beim Starten des Drag-Vorgangs auf. /// @param pCache HLAPI-State Schnappschuss in dem Moment, in dem das /// Event feuert. //....................................................................... void initAction( HLcache * pCache ); //....................................................................... /// @brief Veranlasst das haptische Objekt, sich mit dem Proxy zu bewegen. /// @param pCache HLAPI-State Schnappschuss in dem Moment, in dem das /// Event feuert. //....................................................................... void handleDrag( HLcache * pCache ); //....................................................................... /// @brief Sorgt dafรผr, dass der Node am Ende des Dragvorgangs auf den /// nรคchstgelegenen gรผltigen Gitterpunkt des Grid gesetzt wird. //....................................................................... void finishAction(); //======================================================================= // Von IHapticAction geerbte Methoden //======================================================================= //....................................................................... /// @brief Registriert die Aktion fรผr eine Shape bei HLAPI. /// @param shapeID ID der Shape, fรผr die die Aktion registriert werden soll. //....................................................................... virtual void unregisterAction( HLuint shapeID ); //....................................................................... /// @brief Meldet die Aktion fรผr eine Shape bei HLAPI ab. /// @param shapeID ID der Shape, fรผr die die Aktion registriert wurde. //....................................................................... virtual void registerAction( HLuint shapeID ); //======================================================================= }; #endif // _DRAGNODEONGRIDHANDLER_H_
[ "frosch@a1b688d3-ce07-0410-8a3f-c797401f78de" ]
[ [ [ 1, 162 ] ] ]
e38648c6898729798c06e78641c60dc56b1ef92e
8cf9b251e0f4a23a6ef979c33ee96ff4bdb829ab
/src-ginga-editing/ncl30-generator-cpp/src/ParameterGenerator.cpp
81c5adc7153bc075a32897f9e79f22d2539700c3
[]
no_license
BrunoSSts/ginga-wac
7436a9815427a74032c9d58028394ccaac45cbf9
ea4c5ab349b971bd7f4f2b0940f2f595e6475d6c
refs/heads/master
2020-05-20T22:21:33.645904
2011-10-17T12:34:32
2011-10-17T12:34:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,626
cpp
/****************************************************************************** Este arquivo eh parte da implementacao do ambiente declarativo do middleware Ginga (Ginga-NCL). Copyright (C) 2009 UFSCar/Lince, Todos os Direitos Reservados. Este programa eh software livre; voce pode redistribui-lo e/ou modificah-lo sob os termos da Licenca Publica Geral GNU versao 2 conforme publicada pela Free Software Foundation. Este programa eh distribuido na expectativa de que seja util, porem, SEM NENHUMA GARANTIA; nem mesmo a garantia implicita de COMERCIABILIDADE OU ADEQUACAO A UMA FINALIDADE ESPECIFICA. Consulte a Licenca Publica Geral do GNU versao 2 para mais detalhes. Voce deve ter recebido uma copia da Licenca Publica Geral do GNU versao 2 junto com este programa; se nao, escreva para a Free Software Foundation, Inc., no endereco 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. Para maiores informacoes: [email protected] http://www.ncl.org.br http://www.ginga.org.br http://lince.dc.ufscar.br ****************************************************************************** This file is part of the declarative environment of middleware Ginga (Ginga-NCL) Copyright (C) 2009 UFSCar/Lince, Todos os Direitos Reservados. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License version 2 for more details. You should have received a copy of the GNU General Public License version 2 along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA For further information contact: [email protected] http://www.ncl.org.br http://www.ginga.org.br http://lince.dc.ufscar.br *******************************************************************************/ /** * @file ParameterGenerator.cpp * @author Caio Viel * @date 29-01-10 */ #include "../include/ParameterGenerator.h" namespace br { namespace ufscar { namespace lince { namespace ncl { namespace generate { string ParameterGenerator::generateCode(string paramType, string valueName) { string ret = "<" + paramType + " name=\"" + this->getName() + "\" "; if (this->getValue() != "") ret += valueName + "=\"" + this->getValue() + "\" "; ret+= "/>"; return ret; } } } } } }
[ [ [ 1, 76 ] ] ]
e8c7499c4aad1f6370fa84197f8a800034da424f
bef7d0477a5cac485b4b3921a718394d5c2cf700
/dingus/dingus/resource/EffectBundle.h
23b16e8096a62a782c5592d7820605ff0968c563
[ "MIT" ]
permissive
TomLeeLive/aras-p-dingus
ed91127790a604e0813cd4704acba742d3485400
22ef90c2bf01afd53c0b5b045f4dd0b59fe83009
refs/heads/master
2023-04-19T20:45:14.410448
2011-10-04T10:51:13
2011-10-04T10:51:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,702
h
// -------------------------------------------------------------------------- // Dingus project - a collection of subsystems for game/graphics applications // -------------------------------------------------------------------------- #ifndef __EFFECT_BUNDLE_H #define __EFFECT_BUNDLE_H #include "StorageResourceBundle.h" #include "../kernel/Proxies.h" #include "DeviceResource.h" #include "../utils/Singleton.h" namespace dingus { /** * D3DX Effects bundle. * * Enables conditional compilation of effects via macros (name-value pairs), * see setMacro() and removeMacro(). */ class CEffectBundle : public CStorageResourceBundle<CD3DXEffect>, public CSingleton<CEffectBundle>, public IDeviceReloadableBundle { public: void setStatesConfig( const char* fileName ); bool isOptimizingShaders() const { return mOptimizeShaders; } void setOptimizeShaders( bool opt ) { mOptimizeShaders = opt; } bool isUsingStateManager() const { return mUseStateManager; } void setUsingStateManager( bool stmgr ) { mUseStateManager = stmgr; } #ifdef DINGUS_HAVE_D3DX_FEB_2005 void setSkipConstants( const char* skipConstants ) { mSkipConstants = skipConstants; } #endif const std::string& getLastErrors() const { return mLastErrors; } /** * Adds macro (or replaces same-named one). * After changing a bunch of macros, call reload() to actually reload effects. * NOTE: name/value strings are not copied, so look at their lifetime! */ void setMacro( const char* name, const char* value ); /** * Removes macro. * After changing a bunch of macros, call reload() to actually reload effects. */ void removeMacro( const char* name ); virtual void createResource(); virtual void activateResource(); virtual void passivateResource(); virtual void deleteResource(); protected: virtual CD3DXEffect* loadResourceById( const CResourceId& id, const CResourceId& fullName ); virtual void deleteResource( CD3DXEffect& resource ) { if( resource.getObject() ) resource.getObject()->Release(); delete &resource; } private: IMPLEMENT_SIMPLE_SINGLETON(CEffectBundle); CEffectBundle(); virtual ~CEffectBundle(); /// @return index into macro array, or -1 if not found. int findMacro( const char* name ) const; typedef std::vector<D3DXMACRO> TMacroVector; private: ID3DXEffectPool* mSharedPool; bool mUseStateManager; bool mOptimizeShaders; const char* mSkipConstants; mutable std::string mLastErrors; TMacroVector mMacros; }; }; // namespace /// Shortcut macro #define RGET_FX(rid) dingus::CEffectBundle::getInstance().getResourceById(rid) #endif
[ [ [ 1, 94 ] ] ]
b8b8b2d22186cd054401991285de219548fe85ea
0ee189afe953dc99825f55232cd52b94d2884a85
/mstd/machine/windows32.hpp
36ec89f2c98fa946a10a2f2e799a6fde8253c0ee
[]
no_license
spolitov/lib
fed99fa046b84b575acc61919d4ef301daeed857
7dee91505a37a739c8568fdc597eebf1b3796cf9
refs/heads/master
2016-09-11T02:04:49.852151
2011-08-11T18:00:44
2011-08-11T18:00:44
2,192,752
0
0
null
null
null
null
UTF-8
C++
false
false
2,391
hpp
#ifndef MSTD_MACHINE_COMMON_PROCESSING #error Dont include this file directly, use machine.hpp #endif extern "C" void _ReadWriteBarrier(); #pragma intrinsic(_ReadWriteBarrier) namespace mstd { namespace detail { #include "windows32_asm.hpp" inline void memory_fence() { _ReadWriteBarrier(); } template<size_t size> inline typename size_to_int<size>::type atomic_read(const volatile void * ptr) { typedef size_to_int<size>::type value_type; value_type result = *static_cast<const volatile value_type*>(ptr); memory_fence(); return result; } template<size_t size> inline void atomic_write(volatile void * ptr, typename size_to_int<size>::type value) { memory_fence(); *static_cast<volatile typename size_to_int<size>::type*>(ptr) = value; } #define MSTD_DETAIL_DEFINE_ATOMICS(SIZE, AREGISTER, CREGISTER) \ template<> \ inline size_to_int<SIZE>::type atomic_cas<SIZE>(volatile void * p, size_to_int<SIZE>::type value, size_to_int<SIZE>::type comparand) \ { \ size_to_int<SIZE>::type result; \ __asm \ { \ __asm mov edx, p \ __asm mov CREGISTER, value \ __asm mov AREGISTER, comparand \ __asm lock cmpxchg [edx], CREGISTER \ __asm mov result, AREGISTER \ } \ return result; \ } \ \ template<> \ inline size_to_int<SIZE>::type atomic_add<SIZE>(volatile void * p, size_to_int<SIZE>::type value) \ { \ size_to_int<SIZE>::type result; \ __asm { \ __asm mov edx, p \ __asm mov AREGISTER, value \ __asm lock xadd [edx], AREGISTER \ __asm mov result, AREGISTER \ } \ return result; \ }\ \ template<> \ inline size_to_int<SIZE>::type atomic_read_write<SIZE>(volatile void * p, size_to_int<SIZE>::type value) \ { \ size_to_int<SIZE>::type result; \ __asm \ { \ __asm mov edx, p \ __asm mov AREGISTER, value \ __asm lock xchg [edx], AREGISTER \ __asm mov result, AREGISTER \ } \ return result; \ } MSTD_DETAIL_DEFINE_ATOMICS(1, al, cl) MSTD_DETAIL_DEFINE_ATOMICS(2, ax, cx) MSTD_DETAIL_DEFINE_ATOMICS(4, eax, ecx) #undef MSTD_DETAIL_DEFINE_ATOMICS void yield(); inline void pause(boost::uint32_t delay) { __asm { mov eax, delay mloop: pause add eax, -1 jne mloop } } } }
[ [ [ 1, 91 ] ] ]
b7064a630ee89d53563b353eeb1544c3b57e6701
c3531ade6396e9ea9c7c9a85f7da538149df2d09
/Param/src/Param/TriangleTransFunctor.h
0b01042c0c8765c4f7ddb25ab56e3eea78707269
[]
no_license
feengg/MultiChart-Parameterization
ddbd680f3e1c2100e04c042f8f842256f82c5088
764824b7ebab9a3a5e8fa67e767785d2aec6ad0a
refs/heads/master
2020-03-28T16:43:51.242114
2011-04-19T17:18:44
2011-04-19T17:18:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,626
h
#ifndef TRIANGLETRANSFUNCTOR_H_ #define TRIANGLETRANSFUNCTOR_H_ #include "../ModelMesh/MeshModel.h" #include <hj_3rd/zjucad/matrix/matrix.h> namespace PARAM { /* */ class TriTransFunctor { public: TriTransFunctor(boost::shared_ptr<MeshModel> _mesh); ~TriTransFunctor(); public: bool TransLocalCoordBetweenCharts(int from_chart_id, const Coord2D& from_chart_coord, int to_chart_id, Coord2D& to_chart_coord) const; //protected: bool GetTransChartsChain(int from_chart_id, int to_chart_id, std::vector<int>& ) const; zjucad::matrix::matrix<double> GetTransMatrix(int from_chart_id, int to_chart_id) const; //! Get the transition matrix between two adjacent charts zjucad::matrix::matrix<double> GetTransMatrixOfAdjCharts(int from_chart_id, int to_chart_id) const; //! Get the transition matrix in the same chart, just changed the origin and x-axis zjucad::matrix::matrix<double> GetTransMatrixInOneChart(int chart_id, std::pair<int, int> old_x_index, std::pair<int, int> new_x_index) const; //! some matrix operator zjucad::matrix::matrix<double> GetTranslationMatrix2D(double t_x, double t_y) const; zjucad::matrix::matrix<double> GetRotationMatrix2D(double rotation_angle) const; void SetChartNeighbors(); private: boost::shared_ptr<MeshModel> p_mesh; std::vector< std::vector<int> > m_neighbor_charts; public: /// Test void TestInnerChartTrans(int chart_id) const; void TestAdjChartsTrans(int from_chart_id, int to_chart_id) const; void TestTwoChartsTrans(int from_Chart_id, int to_chart_id) const; }; } #endif
[ [ [ 1, 49 ] ] ]
3153fdb9eaed14a2edd1cac36fc809b017e56d49
037faae47a5b22d3e283555e6b5ac2a0197faf18
/pcsx2v2/x86/iHw.cpp
245d83d5f59b41c9c4ec297544b13a7371fdb964
[]
no_license
isabella232/pcsx2-sourceforge
6e5aac8d0b476601bfc8fa83ded66c1564b8c588
dbb2c3a010081b105a8cba0c588f1e8f4e4505c6
refs/heads/master
2023-03-18T22:23:15.102593
2008-11-17T20:10:17
2008-11-17T20:10:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
31,567
cpp
/* Pcsx2 - Pc Ps2 Emulator * Copyright (C) 2002-2008 Pcsx2 Team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #include <string.h> #include <malloc.h> #include <assert.h> #include "Common.h" #include "iR5900.h" #include "VUmicro.h" #include "PsxMem.h" #include "IPU/IPU.h" #include "GS.h" #ifndef PCSX2_VIRTUAL_MEM extern u8 *psH; // hw mem extern u16 *psHW; extern u32 *psHL; extern u64 *psHD; #endif extern int rdram_devices; // put 8 for TOOL and 2 for PS2 and PSX extern int rdram_sdevid; extern char sio_buffer[1024]; extern int sio_count; int hwConstRead8(u32 x86reg, u32 mem, u32 sign) { #ifdef PCSX2_DEVBUILD if( mem >= 0x10000000 && mem < 0x10008000 ) SysPrintf("hwRead8 to %x\n", mem); #endif if ((mem & 0xffffff0f) == 0x1000f200) { if(mem == 0x1000f260) { MMXONLY(if( IS_MMXREG(x86reg) ) PXORRtoR(x86reg&0xf, x86reg&0xf); else) XOR32RtoR(x86reg, x86reg); return 0; } else if(mem == 0x1000F240) { _eeReadConstMem8(x86reg, (uptr)&PS2MEM_HW[(mem) & 0xffff], sign); //psHu32(mem) &= ~0x4000; return 0; } } if (mem < 0x10010000) { _eeReadConstMem8(x86reg, (uptr)&PS2MEM_HW[(mem) & 0xffff], sign); } else { MMXONLY(if( IS_MMXREG(x86reg) ) PXORRtoR(x86reg&0xf, x86reg&0xf); else ) XOR32RtoR(x86reg, x86reg); } return 0; } #define CONSTREAD16_CALL(name) { \ iFlushCall(0); \ CALLFunc((uptr)name); \ if( sign ) MOVSX32R16toR(EAX, EAX); \ else MOVZX32R16toR(EAX, EAX); \ } \ static u32 s_regreads[3] = {0x010200000, 0xbfff0000, 0xF0000102}; int hwConstRead16(u32 x86reg, u32 mem, u32 sign) { #ifdef PCSX2_DEVBUILD if( mem >= 0x10002000 && mem < 0x10008000 ) SysPrintf("hwRead16 to %x\n", mem); #endif #ifdef PCSX2_DEVBUILD if( mem >= 0x10000000 && mem < 0x10002000 ){ #ifdef EECNT_LOG EECNT_LOG("cnt read to %x\n", mem); #endif } #endif switch (mem) { case 0x10000000: PUSH32I(0); CONSTREAD16_CALL(rcntRcount); ADD32ItoR(ESP, 4); return 1; case 0x10000010: _eeReadConstMem16(x86reg, (uptr)&counters[0].mode, sign); return 0; case 0x10000020: _eeReadConstMem16(x86reg, (uptr)&counters[0].mode, sign); return 0; case 0x10000030: _eeReadConstMem16(x86reg, (uptr)&counters[0].hold, sign); return 0; case 0x10000800: PUSH32I(1); CONSTREAD16_CALL(rcntRcount); ADD32ItoR(ESP, 4); return 1; case 0x10000810: _eeReadConstMem16(x86reg, (uptr)&counters[1].mode, sign); return 0; case 0x10000820: _eeReadConstMem16(x86reg, (uptr)&counters[1].target, sign); return 0; case 0x10000830: _eeReadConstMem16(x86reg, (uptr)&counters[1].hold, sign); return 0; case 0x10001000: PUSH32I(2); CONSTREAD16_CALL(rcntRcount); ADD32ItoR(ESP, 4); return 1; case 0x10001010: _eeReadConstMem16(x86reg, (uptr)&counters[2].mode, sign); return 0; case 0x10001020: _eeReadConstMem16(x86reg, (uptr)&counters[2].target, sign); return 0; case 0x10001800: PUSH32I(3); CONSTREAD16_CALL(rcntRcount); ADD32ItoR(ESP, 4); return 1; case 0x10001810: _eeReadConstMem16(x86reg, (uptr)&counters[3].mode, sign); return 0; case 0x10001820: _eeReadConstMem16(x86reg, (uptr)&counters[3].target, sign); return 0; default: if ((mem & 0xffffff0f) == 0x1000f200) { if(mem == 0x1000f260) { MMXONLY(if( IS_MMXREG(x86reg) ) PXORRtoR(x86reg&0xf, x86reg&0xf); else ) XOR32RtoR(x86reg, x86reg); return 0; } else if(mem == 0x1000F240) { MMXONLY(if( IS_MMXREG(x86reg) ) { MOVDMtoMMX(x86reg&0xf, (uptr)&PS2MEM_HW[(mem) & 0xffff] - 2); PORMtoR(x86reg&0xf, (uptr)&s_regreads[0]); PANDMtoR(x86reg&0xf, (uptr)&s_regreads[1]); } else ) { if( sign ) MOVSX32M16toR(x86reg, (uptr)&PS2MEM_HW[(mem) & 0xffff]); else MOVZX32M16toR(x86reg, (uptr)&PS2MEM_HW[(mem) & 0xffff]); OR32ItoR(x86reg, 0x0102); AND32ItoR(x86reg, ~0x4000); } return 0; } } if (mem < 0x10010000) { _eeReadConstMem16(x86reg, (uptr)&PS2MEM_HW[(mem) & 0xffff], sign); } else { MMXONLY(if( IS_MMXREG(x86reg) ) PXORRtoR(x86reg&0xf, x86reg&0xf); else ) XOR32RtoR(x86reg, x86reg); } return 0; } } #ifdef PCSX2_VIRTUAL_MEM // //#if defined(_MSC_VER) && !defined(__x86_64__) //__declspec(naked) void recCheckF440() //{ // __asm { // add b440, 1 // mov eax, b440 // sub eax, 3 // mov edx, 31 // // cmp eax, 27 // ja WriteVal // shl eax, 2 // mov edx, dword ptr [eax+b440table] // //WriteVal: // mov eax, PS2MEM_BASE_+0x1000f440 // mov dword ptr [eax], edx // ret // } //} //#else //void recCheckF440(); //#endif void iMemRead32Check() { // test if 0xf440 // if( bExecBIOS ) { // u8* ptempptr[2]; // CMP32ItoR(ECX, 0x1000f440); // ptempptr[0] = JNE8(0); // //// // increment and test //// INC32M((uptr)&b440); //// MOV32MtoR(EAX, (uptr)&b440); //// SUB32ItoR(EAX, 3); //// MOV32ItoR(EDX, 31); //// //// CMP32ItoR(EAX, 27); //// //// // look up table //// ptempptr[1] = JA8(0); //// SHL32ItoR(EAX, 2); //// ADD32ItoR(EAX, (int)b440table); //// MOV32RmtoR(EDX, EAX); //// //// x86SetJ8( ptempptr[1] ); //// //// MOV32RtoM( (int)PS2MEM_HW+0xf440, EDX); // CALLFunc((uptr)recCheckF440); // // x86SetJ8( ptempptr[0] ); // } } #endif int hwContRead32_f440() { if ((psHu32(0xf430) >> 6) & 0xF) return 0; else switch ((psHu32(0xf430)>>16) & 0xFFF){//MCH_RICM: x:4|SA:12|x:5|SDEV:1|SOP:4|SBC:1|SDEV:5 case 0x21://INIT { int ret = 0x1F * (rdram_sdevid < rdram_devices); rdram_sdevid += (rdram_sdevid < rdram_devices); return ret; } case 0x23://CNFGA return 0x0D0D; //PVER=3 | MVER=16 | DBL=1 | REFBIT=5 case 0x24://CNFGB //0x0110 for PSX SVER=0 | CORG=8(5x9x7) | SPT=1 | DEVTYP=0 | BYTE=0 return 0x0090; //SVER=0 | CORG=4(5x9x6) | SPT=1 | DEVTYP=0 | BYTE=0 case 0x40://DEVID return psHu32(0xf430) & 0x1F; // =SDEV } return 0; } int hwConstRead32(u32 x86reg, u32 mem) { //IPU regs if ((mem>=0x10002000) && (mem<0x10003000)) { return ipuConstRead32(x86reg, mem); } switch (mem) { case 0x10000000: iFlushCall(0); PUSH32I(0); CALLFunc((uptr)rcntRcount); #ifdef EECNT_LOG EECNT_LOG("Counter 0 count read = %x\n", rcntRcount(0)); #endif ADD32ItoR(ESP, 4); return 1; case 0x10000010: _eeReadConstMem32(x86reg, (uptr)&counters[0].mode); #ifdef EECNT_LOG EECNT_LOG("Counter 0 mode read = %x\n", counters[0].mode); #endif return 0; case 0x10000020: _eeReadConstMem32(x86reg, (uptr)&counters[0].target); #ifdef EECNT_LOG EECNT_LOG("Counter 0 target read = %x\n", counters[0].target); #endif return 0; case 0x10000030: _eeReadConstMem32(x86reg, (uptr)&counters[0].hold); return 0; case 0x10000800: iFlushCall(0); PUSH32I(1); CALLFunc((uptr)rcntRcount); #ifdef EECNT_LOG EECNT_LOG("Counter 1 count read = %x\n", rcntRcount(1)); #endif ADD32ItoR(ESP, 4); return 1; case 0x10000810: _eeReadConstMem32(x86reg, (uptr)&counters[1].mode); #ifdef EECNT_LOG EECNT_LOG("Counter 1 mode read = %x\n", counters[1].mode); #endif return 0; case 0x10000820: _eeReadConstMem32(x86reg, (uptr)&counters[1].target); #ifdef EECNT_LOG EECNT_LOG("Counter 1 target read = %x\n", counters[1].target); #endif return 0; case 0x10000830: _eeReadConstMem32(x86reg, (uptr)&counters[1].hold); return 0; case 0x10001000: iFlushCall(0); PUSH32I(2); CALLFunc((uptr)rcntRcount); #ifdef EECNT_LOG EECNT_LOG("Counter 2 count read = %x\n", rcntRcount(2)); #endif ADD32ItoR(ESP, 4); return 1; case 0x10001010: _eeReadConstMem32(x86reg, (uptr)&counters[2].mode); #ifdef EECNT_LOG EECNT_LOG("Counter 2 mode read = %x\n", counters[2].mode); #endif return 0; case 0x10001020: _eeReadConstMem32(x86reg, (uptr)&counters[2].target); #ifdef EECNT_LOG EECNT_LOG("Counter 2 target read = %x\n", counters[2].target); #endif return 0; case 0x10001030: _eeReadConstMem32(x86reg, (uptr)&counters[2].hold); return 0; case 0x10001800: iFlushCall(0); PUSH32I(3); CALLFunc((uptr)rcntRcount); #ifdef EECNT_LOG EECNT_LOG("Counter 3 count read = %x\n", rcntRcount(3)); #endif ADD32ItoR(ESP, 4); return 1; case 0x10001810: _eeReadConstMem32(x86reg, (uptr)&counters[3].mode); #ifdef EECNT_LOG EECNT_LOG("Counter 3 mode read = %x\n", counters[3].mode); #endif return 0; case 0x10001820: _eeReadConstMem32(x86reg, (uptr)&counters[3].target); #ifdef EECNT_LOG EECNT_LOG("Counter 3 target read = %x\n", counters[3].target); #endif return 0; case 0x10001830: _eeReadConstMem32(x86reg, (uptr)&counters[3].hold); return 0; case 0x1000f130: case 0x1000f410: case 0x1000f430: if( IS_XMMREG(x86reg) ) SSEX_PXOR_XMM_to_XMM(x86reg&0xf, x86reg&0xf); MMXONLY(else if( IS_MMXREG(x86reg) ) PXORRtoR(x86reg&0xf, x86reg&0xf);) else XOR32RtoR(x86reg, x86reg); return 0; case 0x1000f440: iFlushCall(0); CALLFunc((uptr)hwContRead32_f440); return 1; case 0x1000f520: // DMAC_ENABLER _eeReadConstMem32(x86reg, (uptr)&PS2MEM_HW[0xf590]); return 0; default: if ((mem & 0xffffff0f) == 0x1000f200) { if(mem == 0x1000f260) { if( IS_XMMREG(x86reg) ) SSEX_PXOR_XMM_to_XMM(x86reg&0xf, x86reg&0xf); MMXONLY(else if( IS_MMXREG(x86reg) ) PXORRtoR(x86reg&0xf, x86reg&0xf);) else XOR32RtoR(x86reg, x86reg); return 0; } else if(mem == 0x1000F240) { if( IS_XMMREG(x86reg) ) { SSEX_MOVD_M32_to_XMM(x86reg&0xf, (uptr)&PS2MEM_HW[(mem) & 0xffff]); SSEX_POR_M128_to_XMM(x86reg&0xf, (uptr)&s_regreads[2]); } MMXONLY(else if( IS_MMXREG(x86reg) ) { MOVDMtoMMX(x86reg&0xf, (uptr)&PS2MEM_HW[(mem) & 0xffff]); PORMtoR(x86reg&0xf, (uptr)&s_regreads[2]); }) else { MOV32MtoR(x86reg, (uptr)&PS2MEM_HW[(mem) & 0xffff]); OR32ItoR(x86reg, 0xF0000102); } return 0; } } if (mem < 0x10010000) { _eeReadConstMem32(x86reg, (uptr)&PS2MEM_HW[(mem) & 0xffff]); } else { if( IS_XMMREG(x86reg) ) SSEX_PXOR_XMM_to_XMM(x86reg&0xf, x86reg&0xf); MMXONLY(else if( IS_MMXREG(x86reg) ) PXORRtoR(x86reg&0xf, x86reg&0xf);) else XOR32RtoR(x86reg, x86reg); } return 0; } } void hwConstRead64(u32 mem, int mmreg) { if ((mem>=0x10002000) && (mem<0x10003000)) { ipuConstRead64(mem, mmreg); return; } if( IS_XMMREG(mmreg) ) SSE_MOVLPS_M64_to_XMM(mmreg&0xff, (uptr)PSM(mem)); else { X86_64ASSERT(); MMXONLY(MOVQMtoR(mmreg, (uptr)PSM(mem)); SetMMXstate();) } } PCSX2_ALIGNED16(u32 s_TempFIFO[4]); void hwConstRead128(u32 mem, int xmmreg) { if (mem >= 0x10004000 && mem < 0x10008000) { iFlushCall(0); PUSH32I((uptr)&s_TempFIFO[0]); PUSH32I(mem); CALLFunc((uptr)ReadFIFO); ADD32ItoR(ESP, 8); _eeReadConstMem128( xmmreg, (uptr)&s_TempFIFO[0]); return; } _eeReadConstMem128( xmmreg, (uptr)PSM(mem)); } // when writing imm #define recDmaExecI8(name, num) { \ MOV8ItoM((uptr)&PS2MEM_HW[(mem) & 0xffff], g_cpuConstRegs[(mmreg>>16)&0x1f].UL[0]); \ if( g_cpuConstRegs[(mmreg>>16)&0x1f].UL[0] & 1 ) { \ TEST8ItoM((uptr)&PS2MEM_HW[DMAC_CTRL&0xffff], 1); \ j8Ptr[6] = JZ8(0); \ CALLFunc((uptr)dma##name); \ x86SetJ8( j8Ptr[6] ); \ } \ } \ #define recDmaExec8(name, num) { \ iFlushCall(0); \ if( IS_EECONSTREG(mmreg) ) { \ recDmaExecI8(name, num); \ } \ else { \ _eeMoveMMREGtoR(EAX, mmreg); \ _eeWriteConstMem8((uptr)&PS2MEM_HW[(mem) & 0xffff], mmreg); \ \ TEST8ItoR(EAX, 1); \ j8Ptr[5] = JZ8(0); \ TEST8ItoM((uptr)&PS2MEM_HW[DMAC_CTRL&0xffff], 1); \ j8Ptr[6] = JZ8(0); \ \ CALLFunc((uptr)dma##name); \ \ x86SetJ8( j8Ptr[5] ); \ x86SetJ8( j8Ptr[6] ); \ } \ } \ static void PrintDebug(u8 value) { if (value == '\n') { sio_buffer[sio_count] = 0; SysPrintf(COLOR_GREEN "%s\n" COLOR_RESET, sio_buffer); sio_count = 0; } else { if (sio_count < 1023) { sio_buffer[sio_count++] = value; } } } #define CONSTWRITE_CALLTIMER(name, index, bit) { \ if( !IS_EECONSTREG(mmreg) ) { \ if( bit == 8 ) MOVZX32R8toR(mmreg&0xf, mmreg&0xf); \ else if( bit == 16 ) MOVZX32R16toR(mmreg&0xf, mmreg&0xf); \ } \ _recPushReg(mmreg); \ iFlushCall(0); \ PUSH32I(index); \ CALLFunc((uptr)name); \ ADD32ItoR(ESP, 8); \ } \ #define CONSTWRITE_TIMERS(bit) \ case 0x10000000: CONSTWRITE_CALLTIMER(rcntWcount, 0, bit); break; \ case 0x10000010: CONSTWRITE_CALLTIMER(rcntWmode, 0, bit); break; \ case 0x10000020: CONSTWRITE_CALLTIMER(rcntWtarget, 0, bit); break; \ case 0x10000030: CONSTWRITE_CALLTIMER(rcntWhold, 0, bit); break; \ \ case 0x10000800: CONSTWRITE_CALLTIMER(rcntWcount, 1, bit); break; \ case 0x10000810: CONSTWRITE_CALLTIMER(rcntWmode, 1, bit); break; \ case 0x10000820: CONSTWRITE_CALLTIMER(rcntWtarget, 1, bit); break; \ case 0x10000830: CONSTWRITE_CALLTIMER(rcntWhold, 1, bit); break; \ \ case 0x10001000: CONSTWRITE_CALLTIMER(rcntWcount, 2, bit); break; \ case 0x10001010: CONSTWRITE_CALLTIMER(rcntWmode, 2, bit); break; \ case 0x10001020: CONSTWRITE_CALLTIMER(rcntWtarget, 2, bit); break; \ \ case 0x10001800: CONSTWRITE_CALLTIMER(rcntWcount, 3, bit); break; \ case 0x10001810: CONSTWRITE_CALLTIMER(rcntWmode, 3, bit); break; \ case 0x10001820: CONSTWRITE_CALLTIMER(rcntWtarget, 3, bit); break; \ void hwConstWrite8(u32 mem, int mmreg) { switch (mem) { CONSTWRITE_TIMERS(8) case 0x1000f180: _recPushReg(mmreg); \ iFlushCall(0); CALLFunc((uptr)PrintDebug); ADD32ItoR(ESP, 4); break; case 0x10008001: // dma0 - vif0 recDmaExec8(VIF0, 0); break; case 0x10009001: // dma1 - vif1 recDmaExec8(VIF1, 1); break; case 0x1000a001: // dma2 - gif recDmaExec8(GIF, 2); break; case 0x1000b001: // dma3 - fromIPU recDmaExec8(IPU0, 3); break; case 0x1000b401: // dma4 - toIPU recDmaExec8(IPU1, 4); break; case 0x1000c001: // dma5 - sif0 //if (value == 0) psxSu32(0x30) = 0x40000; recDmaExec8(SIF0, 5); break; case 0x1000c401: // dma6 - sif1 recDmaExec8(SIF1, 6); break; case 0x1000c801: // dma7 - sif2 recDmaExec8(SIF2, 7); break; case 0x1000d001: // dma8 - fromSPR recDmaExec8(SPR0, 8); break; case 0x1000d401: // dma9 - toSPR recDmaExec8(SPR1, 9); break; case 0x1000f592: // DMAC_ENABLEW _eeWriteConstMem8( (uptr)&PS2MEM_HW[0xf522], mmreg ); _eeWriteConstMem8( (uptr)&PS2MEM_HW[0xf592], mmreg ); break; default: if ((mem & 0xffffff0f) == 0x1000f200) { u32 at = mem & 0xf0; switch(at) { case 0x00: _eeWriteConstMem8( (uptr)&PS2MEM_HW[mem&0xffff], mmreg); break; case 0x40: if( IS_EECONSTREG(mmreg) ) { if( !(g_cpuConstRegs[(mmreg>>16)&0x1f].UL[0] & 0x100) ) { AND32ItoM( (uptr)&PS2MEM_HW[mem&0xfffc], ~0x100); } } else { _eeMoveMMREGtoR(EAX, mmreg); TEST16ItoR(EAX, 0x100); j8Ptr[5] = JNZ8(0); AND32ItoM( (uptr)&PS2MEM_HW[mem&0xfffc], ~0x100); x86SetJ8(j8Ptr[5]); } break; } return; } assert( (mem&0xff0f) != 0xf200 ); switch(mem&~3) { case 0x1000f130: case 0x1000f410: case 0x1000f430: break; default: #ifdef PCSX2_VIRTUAL_MEM //NOTE: this might cause crashes, but is more correct _eeWriteConstMem8((u32)PS2MEM_BASE + mem, mmreg); #else if (mem < 0x10010000) { _eeWriteConstMem8((uptr)&PS2MEM_HW[mem&0xffff], mmreg); } #endif } break; } } #define recDmaExecI16(name, num) { \ MOV16ItoM((uptr)&PS2MEM_HW[(mem) & 0xffff], g_cpuConstRegs[(mmreg>>16)&0x1f].UL[0]); \ if( g_cpuConstRegs[(mmreg>>16)&0x1f].UL[0] & 0x100 ) { \ TEST8ItoM((uptr)&PS2MEM_HW[DMAC_CTRL&0xffff], 1); \ j8Ptr[6] = JZ8(0); \ CALLFunc((uptr)dma##name); \ x86SetJ8( j8Ptr[6] ); \ } \ } \ #define recDmaExec16(name, num) { \ iFlushCall(0); \ if( IS_EECONSTREG(mmreg) ) { \ recDmaExecI16(name, num); \ } \ else { \ _eeMoveMMREGtoR(EAX, mmreg); \ _eeWriteConstMem16((uptr)&PS2MEM_HW[(mem) & 0xffff], mmreg); \ \ TEST16ItoR(EAX, 0x100); \ j8Ptr[5] = JZ8(0); \ TEST8ItoM((uptr)&PS2MEM_HW[DMAC_CTRL&0xffff], 1); \ j8Ptr[6] = JZ8(0); \ \ CALLFunc((uptr)dma##name); \ \ x86SetJ8( j8Ptr[5] ); \ x86SetJ8( j8Ptr[6] ); \ } \ } \ void hwConstWrite16(u32 mem, int mmreg) { switch(mem) { CONSTWRITE_TIMERS(16) case 0x10008000: // dma0 - vif0 recDmaExec16(VIF0, 0); break; case 0x10009000: // dma1 - vif1 - chcr recDmaExec16(VIF1, 1); break; case 0x1000a000: // dma2 - gif recDmaExec16(GIF, 2); break; case 0x1000b000: // dma3 - fromIPU recDmaExec16(IPU0, 3); break; case 0x1000b400: // dma4 - toIPU recDmaExec16(IPU1, 4); break; case 0x1000c000: // dma5 - sif0 //if (value == 0) psxSu32(0x30) = 0x40000; recDmaExec16(SIF0, 5); break; case 0x1000c002: //? break; case 0x1000c400: // dma6 - sif1 recDmaExec16(SIF1, 6); break; case 0x1000c800: // dma7 - sif2 recDmaExec16(SIF2, 7); break; case 0x1000c802: //? break; case 0x1000d000: // dma8 - fromSPR recDmaExec16(SPR0, 8); break; case 0x1000d400: // dma9 - toSPR recDmaExec16(SPR1, 9); break; case 0x1000f592: // DMAC_ENABLEW _eeWriteConstMem16((uptr)&PS2MEM_HW[0xf522], mmreg); _eeWriteConstMem16((uptr)&PS2MEM_HW[0xf592], mmreg); break; case 0x1000f130: case 0x1000f410: case 0x1000f430: break; default: if ((mem & 0xffffff0f) == 0x1000f200) { u32 at = mem & 0xf0; switch(at) { case 0x00: _eeWriteConstMem16((uptr)&PS2MEM_HW[mem&0xffff], mmreg); break; case 0x20: _eeWriteConstMem16OP((uptr)&PS2MEM_HW[mem&0xffff], mmreg, 1); break; case 0x30: if( IS_EECONSTREG(mmreg) ) { AND16ItoM((uptr)&PS2MEM_HW[mem&0xffff], ~g_cpuConstRegs[(mmreg>>16)&0x1f].UL[0]); } else { NOT32R(mmreg&0xf); AND16RtoM((uptr)&PS2MEM_HW[mem&0xffff], mmreg&0xf); } break; case 0x40: if( IS_EECONSTREG(mmreg) ) { if( !(g_cpuConstRegs[(mmreg>>16)&0x1f].UL[0] & 0x100) ) { AND16ItoM((uptr)&PS2MEM_HW[mem&0xffff], ~0x100); } else { OR16ItoM((uptr)&PS2MEM_HW[mem&0xffff], 0x100); } } else { _eeMoveMMREGtoR(EAX, mmreg); TEST16ItoR(EAX, 0x100); j8Ptr[5] = JZ8(0); OR16ItoM((uptr)&PS2MEM_HW[mem&0xffff], 0x100); j8Ptr[6] = JMP8(0); x86SetJ8( j8Ptr[5] ); AND16ItoM((uptr)&PS2MEM_HW[mem&0xffff], ~0x100); x86SetJ8( j8Ptr[6] ); } break; case 0x60: _eeWriteConstMem16((uptr)&PS2MEM_HW[mem&0xffff], 0); break; } return; } #ifdef PCSX2_VIRTUAL_MEM //NOTE: this might cause crashes, but is more correct _eeWriteConstMem16((u32)PS2MEM_BASE + mem, mmreg); #else if (mem < 0x10010000) { _eeWriteConstMem16((uptr)&PS2MEM_HW[mem&0xffff], mmreg); } #endif } } // when writing an Imm #define recDmaExecI(name, num) { \ u32 c = g_cpuConstRegs[(mmreg>>16)&0x1f].UL[0]; \ /* Keep the old tag if in chain mode and hw doesnt set it*/ \ if( (c & 0xc) == 0x4 && (c&0xffff0000) == 0 ) { \ MOV16ItoM((uptr)&PS2MEM_HW[(mem) & 0xffff], c); \ } \ else MOV32ItoM((uptr)&PS2MEM_HW[(mem) & 0xffff], c); \ if( c & 0x100 ) { \ TEST8ItoM((uptr)&PS2MEM_HW[DMAC_CTRL&0xffff], 1); \ j8Ptr[6] = JZ8(0); \ CALLFunc((uptr)dma##name); \ x86SetJ8( j8Ptr[6] ); \ } \ } \ #define recDmaExec(name, num) { \ iFlushCall(0); \ if( IS_EECONSTREG(mmreg) ) { \ recDmaExecI(name, num); \ } \ else { \ _eeMoveMMREGtoR(EAX, mmreg); \ TEST32ItoR(EAX, 0xffff0000); \ j8Ptr[6] = JNZ8(0); \ MOV32RtoR(ECX, EAX); \ AND32ItoR(ECX, 0xc); \ CMP32ItoR(ECX, 4); \ j8Ptr[7] = JNE8(0); \ if( IS_XMMREG(mmreg) || IS_MMXREG(mmreg) ) { \ MOV16RtoM((uptr)&PS2MEM_HW[(mem) & 0xffff], EAX); \ } \ else { \ _eeWriteConstMem16((uptr)&PS2MEM_HW[(mem) & 0xffff], mmreg); \ } \ j8Ptr[8] = JMP8(0); \ x86SetJ8(j8Ptr[6]); \ x86SetJ8(j8Ptr[7]); \ _eeWriteConstMem32((uptr)&PS2MEM_HW[(mem) & 0xffff], mmreg); \ x86SetJ8(j8Ptr[8]); \ \ TEST16ItoR(EAX, 0x100); \ j8Ptr[5] = JZ8(0); \ TEST32ItoM((uptr)&PS2MEM_HW[DMAC_CTRL&0xffff], 1); \ j8Ptr[6] = JZ8(0); \ \ CALLFunc((uptr)dma##name); \ \ x86SetJ8( j8Ptr[5] ); \ x86SetJ8( j8Ptr[6] ); \ } \ } \ #define CONSTWRITE_CALLTIMER32(name, index, bit) { \ _recPushReg(mmreg); \ iFlushCall(0); \ PUSH32I(index); \ CALLFunc((uptr)name); \ ADD32ItoR(ESP, 8); \ } \ void hwConstWrite32(u32 mem, int mmreg) { //IPU regs if ((mem>=0x10002000) && (mem<0x10003000)) { //psHu32(mem) = value; ipuConstWrite32(mem, mmreg); return; } if ((mem>=0x10003800) && (mem<0x10003c00)) { _recPushReg(mmreg); iFlushCall(0); PUSH32I(mem); CALLFunc((uptr)vif0Write32); ADD32ItoR(ESP, 8); return; } if ((mem>=0x10003c00) && (mem<0x10004000)) { _recPushReg(mmreg); iFlushCall(0); PUSH32I(mem); CALLFunc((uptr)vif1Write32); ADD32ItoR(ESP, 8); return; } switch (mem) { case 0x10000000: CONSTWRITE_CALLTIMER32(rcntWcount, 0, bit); break; case 0x10000010: CONSTWRITE_CALLTIMER32(rcntWmode, 0, bit); break; case 0x10000020: CONSTWRITE_CALLTIMER32(rcntWtarget, 0, bit); break; case 0x10000030: CONSTWRITE_CALLTIMER32(rcntWhold, 0, bit); break; case 0x10000800: CONSTWRITE_CALLTIMER32(rcntWcount, 1, bit); break; case 0x10000810: CONSTWRITE_CALLTIMER32(rcntWmode, 1, bit); break; case 0x10000820: CONSTWRITE_CALLTIMER32(rcntWtarget, 1, bit); break; case 0x10000830: CONSTWRITE_CALLTIMER32(rcntWhold, 1, bit); break; case 0x10001000: CONSTWRITE_CALLTIMER32(rcntWcount, 2, bit); break; case 0x10001010: CONSTWRITE_CALLTIMER32(rcntWmode, 2, bit); break; case 0x10001020: CONSTWRITE_CALLTIMER32(rcntWtarget, 2, bit); break; case 0x10001800: CONSTWRITE_CALLTIMER32(rcntWcount, 3, bit); break; case 0x10001810: CONSTWRITE_CALLTIMER32(rcntWmode, 3, bit); break; case 0x10001820: CONSTWRITE_CALLTIMER32(rcntWtarget, 3, bit); break; case GIF_CTRL: _eeMoveMMREGtoR(EAX, mmreg); iFlushCall(0); TEST8ItoR(EAX, 1); j8Ptr[5] = JZ8(0); // reset GS CALLFunc((uptr)gsGIFReset); j8Ptr[6] = JMP8(0); x86SetJ8( j8Ptr[5] ); AND32I8toR(EAX, 8); MOV32RtoM((uptr)&PS2MEM_HW[mem&0xffff], EAX); TEST16ItoR(EAX, 8); j8Ptr[5] = JZ8(0); OR8ItoM((uptr)&PS2MEM_HW[GIF_STAT&0xffff], 8); j8Ptr[7] = JMP8(0); x86SetJ8( j8Ptr[5] ); AND8ItoM((uptr)&PS2MEM_HW[GIF_STAT&0xffff], ~8); x86SetJ8( j8Ptr[6] ); x86SetJ8( j8Ptr[7] ); return; case GIF_MODE: _eeMoveMMREGtoR(EAX, mmreg); _eeWriteConstMem32((uptr)&PS2MEM_HW[mem&0xffff], mmreg); AND8ItoM((uptr)&PS2MEM_HW[GIF_STAT&0xffff], ~5); AND8ItoR(EAX, 5); OR8RtoM((uptr)&PS2MEM_HW[GIF_STAT&0xffff], EAX); return; case GIF_STAT: // stat is readonly return; case 0x10008000: // dma0 - vif0 recDmaExec(VIF0, 0); break; case 0x10009000: // dma1 - vif1 - chcr recDmaExec(VIF1, 1); break; case 0x1000a000: // dma2 - gif recDmaExec(GIF, 2); break; case 0x1000b000: // dma3 - fromIPU recDmaExec(IPU0, 3); break; case 0x1000b400: // dma4 - toIPU recDmaExec(IPU1, 4); break; case 0x1000c000: // dma5 - sif0 //if (value == 0) psxSu32(0x30) = 0x40000; recDmaExec(SIF0, 5); break; case 0x1000c400: // dma6 - sif1 recDmaExec(SIF1, 6); break; case 0x1000c800: // dma7 - sif2 recDmaExec(SIF2, 7); break; case 0x1000d000: // dma8 - fromSPR recDmaExec(SPR0, 8); break; case 0x1000d400: // dma9 - toSPR recDmaExec(SPR1, 9); break; case 0x1000e010: // DMAC_STAT _eeMoveMMREGtoR(EAX, mmreg); iFlushCall(0); MOV32RtoR(ECX, EAX); NOT32R(ECX); AND16RtoM((uptr)&PS2MEM_HW[0xe010], ECX); SHR32ItoR(EAX, 16); XOR16RtoM((uptr)&PS2MEM_HW[0xe012], EAX); MOV32MtoR(EAX, (uptr)&cpuRegs.CP0.n.Status.val); AND32ItoR(EAX, 0x10807); CMP32ItoR(EAX, 0x10801); j8Ptr[5] = JNE8(0); CALLFunc((uptr)cpuTestDMACInts); x86SetJ8( j8Ptr[5] ); break; case 0x1000f000: // INTC_STAT _eeWriteConstMem32OP((uptr)&PS2MEM_HW[0xf000], mmreg, 2); MOV32MtoR(EAX, (uptr)&cpuRegs.CP0.n.Status.val); AND32ItoR(EAX, 0x10407); CMP32ItoR(EAX, 0x10401); j8Ptr[5] = JNE8(0); CALLFunc((uptr)cpuTestINTCInts); x86SetJ8( j8Ptr[5] ); break; case 0x1000f010: // INTC_MASK _eeMoveMMREGtoR(EAX, mmreg); iFlushCall(0); XOR16RtoM((uptr)&PS2MEM_HW[0xf010], EAX); MOV32MtoR(EAX, (uptr)&cpuRegs.CP0.n.Status.val); AND32ItoR(EAX, 0x10407); CMP32ItoR(EAX, 0x10401); j8Ptr[5] = JNE8(0); CALLFunc((uptr)cpuTestINTCInts); x86SetJ8( j8Ptr[5] ); break; case 0x1000f130: case 0x1000f410: break; case 0x1000f430://MCH_RICM: x:4|SA:12|x:5|SDEV:1|SOP:4|SBC:1|SDEV:5 //if ((((value >> 16) & 0xFFF) == 0x21) && (((value >> 6) & 0xF) == 1) && (((psHu32(0xf440) >> 7) & 1) == 0))//INIT & SRP=0 // rdram_sdevid = 0 _eeMoveMMREGtoR(EAX, mmreg); MOV32RtoR(EDX, EAX); MOV32RtoR(ECX, EAX); SHR32ItoR(EAX, 6); SHR32ItoR(EDX, 16); AND32ItoR(EAX, 0xf); AND32ItoR(EDX, 0xfff); CMP32ItoR(EAX, 1); j8Ptr[5] = JNE8(0); CMP32ItoR(EDX, 0x21); j8Ptr[6] = JNE8(0); TEST32ItoM((uptr)&psHu32(0xf440), 0x80); j8Ptr[7] = JNZ8(0); // if SIO repeater is cleared, reset sdevid MOV32ItoM((uptr)&rdram_sdevid, 0); //kill the busy bit x86SetJ8(j8Ptr[5]); x86SetJ8(j8Ptr[6]); x86SetJ8(j8Ptr[7]); AND32ItoR(ECX, ~0x80000000); MOV32RtoM((uptr)&psHu32(0xf430), ECX); break; case 0x1000f440://MCH_DRD: _eeWriteConstMem32((uptr)&PS2MEM_HW[0xf440], mmreg); break; case 0x1000f590: // DMAC_ENABLEW _eeWriteConstMem32((uptr)&PS2MEM_HW[0xf520], mmreg); _eeWriteConstMem32((uptr)&PS2MEM_HW[0xf590], mmreg); return; default: if ((mem & 0xffffff0f) == 0x1000f200) { u32 at = mem & 0xf0; switch(at) { case 0x00: _eeWriteConstMem32((uptr)&PS2MEM_HW[mem&0xffff], mmreg); break; case 0x20: _eeWriteConstMem32OP((uptr)&PS2MEM_HW[mem&0xffff], mmreg, 1); break; case 0x30: _eeWriteConstMem32OP((uptr)&PS2MEM_HW[mem&0xffff], mmreg, 2); break; case 0x40: if( IS_EECONSTREG(mmreg) ) { if( !(g_cpuConstRegs[(mmreg>>16)&0x1f].UL[0] & 0x100) ) { AND32ItoM( (uptr)&PS2MEM_HW[mem&0xfffc], ~0x100); } else { OR32ItoM((uptr)&PS2MEM_HW[mem&0xffff], 0x100); } } else { _eeMoveMMREGtoR(EAX, mmreg); TEST32ItoR(EAX, 0x100); j8Ptr[5] = JZ8(0); OR32ItoM((uptr)&PS2MEM_HW[mem&0xffff], 0x100); j8Ptr[6] = JMP8(0); x86SetJ8( j8Ptr[5] ); AND32ItoM((uptr)&PS2MEM_HW[mem&0xffff], ~0x100); x86SetJ8( j8Ptr[6] ); } break; case 0x60: MOV32ItoM((uptr)&PS2MEM_HW[mem&0xffff], 0); break; } return; } #ifdef PCSX2_VIRTUAL_MEM //NOTE: this might cause crashes, but is more correct _eeWriteConstMem32((u32)PS2MEM_BASE + mem, mmreg); #else if (mem < 0x10010000) { _eeWriteConstMem32((uptr)&PS2MEM_HW[mem&0xffff], mmreg); } #endif break; } } void hwConstWrite64(u32 mem, int mmreg) { if ((mem>=0x10002000) && (mem<=0x10002030)) { ipuConstWrite64(mem, mmreg); return; } if ((mem>=0x10003800) && (mem<0x10003c00)) { _recPushReg(mmreg); iFlushCall(0); PUSH32I(mem); CALLFunc((uptr)vif0Write32); ADD32ItoR(ESP, 8); return; } if ((mem>=0x10003c00) && (mem<0x10004000)) { _recPushReg(mmreg); iFlushCall(0); PUSH32I(mem); CALLFunc((uptr)vif1Write32); ADD32ItoR(ESP, 8); return; } switch (mem) { case GIF_CTRL: _eeMoveMMREGtoR(EAX, mmreg); iFlushCall(0); TEST8ItoR(EAX, 1); j8Ptr[5] = JZ8(0); // reset GS CALLFunc((uptr)gsGIFReset); j8Ptr[6] = JMP8(0); x86SetJ8( j8Ptr[5] ); AND32I8toR(EAX, 8); MOV32RtoM((uptr)&PS2MEM_HW[mem&0xffff], EAX); TEST16ItoR(EAX, 8); j8Ptr[5] = JZ8(0); OR8ItoM((uptr)&PS2MEM_HW[GIF_STAT&0xffff], 8); j8Ptr[7] = JMP8(0); x86SetJ8( j8Ptr[5] ); AND8ItoM((uptr)&PS2MEM_HW[GIF_STAT&0xffff], ~8); x86SetJ8( j8Ptr[6] ); x86SetJ8( j8Ptr[7] ); return; case GIF_MODE: _eeMoveMMREGtoR(EAX, mmreg); _eeWriteConstMem32((uptr)&PS2MEM_HW[mem&0xffff], mmreg); AND8ItoM((uptr)&PS2MEM_HW[GIF_STAT&0xffff], ~5); AND8ItoR(EAX, 5); OR8RtoM((uptr)&PS2MEM_HW[GIF_STAT&0xffff], EAX); break; case GIF_STAT: // stat is readonly return; case 0x1000a000: // dma2 - gif recDmaExec(GIF, 2); break; case 0x1000e010: // DMAC_STAT _eeMoveMMREGtoR(EAX, mmreg); iFlushCall(0); MOV32RtoR(ECX, EAX); NOT32R(ECX); AND16RtoM((uptr)&PS2MEM_HW[0xe010], ECX); SHR32ItoR(EAX, 16); XOR16RtoM((uptr)&PS2MEM_HW[0xe012], EAX); MOV32MtoR(EAX, (uptr)&cpuRegs.CP0.n.Status.val); AND32ItoR(EAX, 0x10807); CMP32ItoR(EAX, 0x10801); j8Ptr[5] = JNE8(0); CALLFunc((uptr)cpuTestDMACInts); x86SetJ8( j8Ptr[5] ); break; case 0x1000f590: // DMAC_ENABLEW _eeWriteConstMem32((uptr)&PS2MEM_HW[0xf520], mmreg); _eeWriteConstMem32((uptr)&PS2MEM_HW[0xf590], mmreg); break; case 0x1000f000: // INTC_STAT _eeWriteConstMem32OP((uptr)&PS2MEM_HW[mem&0xffff], mmreg, 2); MOV32MtoR(EAX, (uptr)&cpuRegs.CP0.n.Status.val); AND32ItoR(EAX, 0x10407); CMP32ItoR(EAX, 0x10401); j8Ptr[5] = JNE8(0); CALLFunc((uptr)cpuTestINTCInts); x86SetJ8( j8Ptr[5] ); break; case 0x1000f010: // INTC_MASK _eeMoveMMREGtoR(EAX, mmreg); iFlushCall(0); XOR16RtoM((uptr)&PS2MEM_HW[0xf010], EAX); MOV32MtoR(EAX, (uptr)&cpuRegs.CP0.n.Status.val); AND32ItoR(EAX, 0x10407); CMP32ItoR(EAX, 0x10401); j8Ptr[5] = JNE8(0); CALLFunc((uptr)cpuTestINTCInts); x86SetJ8( j8Ptr[5] ); break; case 0x1000f130: case 0x1000f410: case 0x1000f430: break; default: _eeWriteConstMem64((uptr)PSM(mem), mmreg); break; } } void hwConstWrite128(u32 mem, int mmreg) { if (mem >= 0x10004000 && mem < 0x10008000) { _eeWriteConstMem128((uptr)&s_TempFIFO[0], mmreg); iFlushCall(0); PUSH32I((uptr)&s_TempFIFO[0]); PUSH32I(mem); CALLFunc((uptr)WriteFIFO); ADD32ItoR(ESP, 8); return; } switch (mem) { case 0x1000f590: // DMAC_ENABLEW _eeWriteConstMem32((uptr)&PS2MEM_HW[0xf520], mmreg); _eeWriteConstMem32((uptr)&PS2MEM_HW[0xf590], mmreg); break; case 0x1000f130: case 0x1000f410: case 0x1000f430: break; default: #ifdef PCSX2_VIRTUAL_MEM _eeWriteConstMem128( PS2MEM_BASE_+mem, mmreg); #else if (mem < 0x10010000) _eeWriteConstMem128((uptr)&PS2MEM_HW[mem&0xffff], mmreg); #endif break; } }
[ "saqibakhtar@23c756db-88ba-2448-99d7-e6e4c676ec84" ]
[ [ [ 1, 1291 ] ] ]
88550413fdd2d8028476315cee14b120dc239cc6
463c3b62132d215e245a097a921859ecb498f723
/lib/dlib/directed_graph/directed_graph_kernel_1.h
92d6604ab7c18962d2ce11b21db5abfea0b41bb5
[ "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
athulan/cppagent
58f078cee55b68c08297acdf04a5424c2308cfdc
9027ec4e32647e10c38276e12bcfed526a7e27dd
refs/heads/master
2021-01-18T23:34:34.691846
2009-05-05T00:19:54
2009-05-05T00:19:54
197,038
4
1
null
null
null
null
UTF-8
C++
false
false
25,907
h
// Copyright (C) 2007 Davis E. King ([email protected]) // License: Boost Software License See LICENSE.txt for the full license. #ifndef DLIB_DIRECTED_GRAPH_KERNEl_1_ #define DLIB_DIRECTED_GRAPH_KERNEl_1_ #include "../serialize.h" #include "../noncopyable.h" #include "../std_allocator.h" #include "../smart_pointers.h" #include "../algs.h" #include <vector> #include "../memory_manager.h" #include "directed_graph_kernel_abstract.h" #include "../is_kind.h" namespace dlib { // ---------------------------------------------------------------------------------------- template <typename node_type, typename directed_graph, bool is_checked> struct directed_graph_checker_helper { /*! This object is used to check preconditions based on the value of is_checked !*/ static void check_parent_edge ( unsigned long edge_index, const node_type& self ) { // make sure requires clause is not broken DLIB_CASSERT(edge_index < self.number_of_parents(), "\tnode_type& directed_graph::node_type::parent_edge(edge_index)" << "\n\tYou have specified an invalid index" << "\n\tedge_index: " << edge_index << "\n\tnumber_of_parents(): " << self.number_of_parents() << "\n\tthis: " << &self ); } static void check_child_edge ( unsigned long edge_index, const node_type& self ) { // make sure requires clause is not broken DLIB_CASSERT(edge_index < self.number_of_children(), "\tnode_type& directed_graph::node_type::child_edge(edge_index)" << "\n\tYou have specified an invalid index" << "\n\tedge_index: " << edge_index << "\n\tnumber_of_children(): " << self.number_of_children() << "\n\tthis: " << &self ); } static void check_parent ( unsigned long edge_index, const node_type& self ) { // make sure requires clause is not broken DLIB_CASSERT(edge_index < self.number_of_parents(), "\tnode_type& directed_graph::node_type::parent(edge_index)" << "\n\tYou have specified an invalid index" << "\n\tedge_index: " << edge_index << "\n\tnumber_of_parents(): " << self.number_of_parents() << "\n\tthis: " << &self ); } static void check_child ( unsigned long edge_index, const node_type& self ) { // make sure requires clause is not broken DLIB_CASSERT(edge_index < self.number_of_children(), "\tnode_type& directed_graph::node_type::child(edge_index)" << "\n\tYou have specified an invalid index" << "\n\tedge_index: " << edge_index << "\n\tnumber_of_children(): " << self.number_of_children() << "\n\tthis: " << &self ); } static void check_node ( unsigned long index, const directed_graph& self ) { // make sure requires clause is not broken DLIB_CASSERT(index < self.number_of_nodes(), "\tnode_type& directed_graph::node(index)" << "\n\tYou have specified an invalid index" << "\n\tindex: " << index << "\n\tnumber_of_nodes(): " << self.number_of_nodes() << "\n\tthis: " << &self ); } static void check_has_edge ( unsigned long parent_node_index, unsigned long child_node_index, const directed_graph& self ) { // make sure requires clause is not broken DLIB_CASSERT(parent_node_index < self.number_of_nodes() && child_node_index < self.number_of_nodes(), "\tvoid directed_graph::has_edge(parent_node_index, child_node_index)" << "\n\tYou have specified an invalid index" << "\n\tparent_node_index: " << parent_node_index << "\n\tchild_node_index: " << child_node_index << "\n\tnumber_of_nodes(): " << self.number_of_nodes() << "\n\tthis: " << &self ); } static void check_add_edge ( unsigned long parent_node_index, unsigned long child_node_index, const directed_graph& self ) { DLIB_CASSERT(parent_node_index < self.number_of_nodes() && child_node_index < self.number_of_nodes(), "\tvoid directed_graph::add_edge(parent_node_index, child_node_index)" << "\n\tYou have specified an invalid index" << "\n\tparent_node_index: " << parent_node_index << "\n\tchild_node_index: " << child_node_index << "\n\tnumber_of_nodes(): " << self.number_of_nodes() << "\n\tthis: " << &self ); DLIB_CASSERT( self.has_edge(parent_node_index, child_node_index) == false, "\tvoid directed_graph::add_edge(parent_node_index, child_node_index)" << "\n\tYou can't add an edge if it already exists in the graph" << "\n\tparent_node_index: " << parent_node_index << "\n\tchild_node_index: " << child_node_index << "\n\tnumber_of_nodes(): " << self.number_of_nodes() << "\n\tthis: " << &self ); } static void check_remove_edge ( unsigned long parent_node_index, unsigned long child_node_index, const directed_graph& self ) { DLIB_CASSERT(parent_node_index < self.number_of_nodes() && child_node_index < self.number_of_nodes(), "\tvoid directed_graph::remove_edge(parent_node_index, child_node_index)" << "\n\tYou have specified an invalid index" << "\n\tparent_node_index: " << parent_node_index << "\n\tchild_node_index: " << child_node_index << "\n\tnumber_of_nodes(): " << self.number_of_nodes() << "\n\tthis: " << &self ); DLIB_CASSERT( self.has_edge(parent_node_index, child_node_index) == true, "\tvoid directed_graph::remove_edge(parent_node_index, child_node_index)" << "\n\tYou can't remove an edge if it isn't in the graph" << "\n\tparent_node_index: " << parent_node_index << "\n\tchild_node_index: " << child_node_index << "\n\tnumber_of_nodes(): " << self.number_of_nodes() << "\n\tthis: " << &self ); } static void check_remove_node ( unsigned long index, const directed_graph& self ) { // make sure requires clause is not broken DLIB_CASSERT(index < self.number_of_nodes(), "\tvoid directed_graph::remove_node(index)" << "\n\tYou have specified an invalid index" << "\n\tindex: " << index << "\n\tnumber_of_nodes(): " << self.number_of_nodes() << "\n\tthis: " << &self ); } }; template <typename node_type, typename directed_graph> struct directed_graph_checker_helper <node_type, directed_graph, false> { static inline void check_parent ( unsigned long edge_index, const node_type& self) { } static inline void check_child ( unsigned long edge_index, const node_type& self) { } static inline void check_parent_edge ( unsigned long edge_index, const node_type& self) { } static inline void check_child_edge ( unsigned long edge_index, const node_type& self) { } static inline void check_node ( unsigned long index, const directed_graph& self) { } static inline void check_has_edge ( unsigned long , unsigned long , const directed_graph& ) { } static inline void check_add_edge ( unsigned long , unsigned long , const directed_graph& ) { } static inline void check_remove_edge ( unsigned long , unsigned long , const directed_graph& ) { } static inline void check_remove_node ( unsigned long index, const directed_graph& self) { } }; // ---------------------------------------------------------------------------------------- template < typename T, typename E = char, typename mem_manager = memory_manager<char>::kernel_1a, bool is_checked = true > class directed_graph_kernel_1 : noncopyable { /*! INITIAL VALUE - nodes.size() == 0 CONVENTION - nodes.size() == number_of_nodes() - for all valid i: - *nodes[i] == node(i) - nodes[i]->parents.size() == nodes[i]->number_of_parents(i) - nodes[i]->children.size() == nodes[i]->number_of_children(i) - nodes[i]->edge_parents.size() == nodes[i]->number_of_parents(i) - nodes[i]->edge_children.size() == nodes[i]->number_of_children(i) - nodes[i]->idx == i == nodes[i]->index() - for all valid p: - nodes[i]->parents[p] == pointer to the p'th parent node of i - *nodes[i]->parents[p] == nodes[i]->parent(p) - *nodes[i]->edge_parents[p] == nodes[i]->parent_edge(p) - for all valid c: - nodes[i]->children[c] == pointer to the c'th child node of i - *nodes[i]->children[c] == nodes[i]->child(c) - *nodes[i]->edge_children[c] == nodes[i]->child_edge(c) !*/ public: struct node_type; private: typedef directed_graph_checker_helper<node_type, directed_graph_kernel_1, is_checked> checker; public: typedef T type; typedef E edge_type; typedef mem_manager mem_manager_type; template <typename Tr, typename Er, typename MMr> struct rebind { typedef directed_graph_kernel_1<Tr,Er,MMr> other; }; directed_graph_kernel_1( ) {} virtual ~directed_graph_kernel_1( ) {} void clear( ) { nodes.clear(); } void set_number_of_nodes ( unsigned long new_size ); unsigned long number_of_nodes ( ) const { return nodes.size(); } node_type& node ( unsigned long index ) { checker::check_node(index,*this); return *nodes[index]; } const node_type& node ( unsigned long index ) const { checker::check_node(index,*this); return *nodes[index]; } bool has_edge ( unsigned long parent_node_index, unsigned long child_node_index ) const; void add_edge ( unsigned long parent_node_index, unsigned long child_node_index ); void remove_edge ( unsigned long parent_node_index, unsigned long child_node_index ); unsigned long add_node ( ); void remove_node ( unsigned long index ); void swap ( directed_graph_kernel_1& item ) { nodes.swap(item.nodes); } private: public: struct node_type { T data; typedef directed_graph_kernel_1 graph_type; unsigned long index( ) const { return idx; } unsigned long number_of_parents ( ) const { return parents.size(); } unsigned long number_of_children ( ) const { return children.size(); } const node_type& parent ( unsigned long edge_index ) const { checker::check_parent(edge_index,*this); return *parents[edge_index]; } node_type& parent ( unsigned long edge_index ) { checker::check_parent(edge_index,*this); return *parents[edge_index]; } const node_type& child ( unsigned long edge_index ) const { checker::check_child(edge_index,*this); return *children[edge_index]; } node_type& child ( unsigned long edge_index ) { checker::check_child(edge_index,*this); return *children[edge_index]; } const E& parent_edge ( unsigned long edge_index ) const { checker::check_parent_edge(edge_index,*this); return *edge_parents[edge_index]; } E& parent_edge ( unsigned long edge_index ) { checker::check_parent_edge(edge_index,*this); return *edge_parents[edge_index]; } const E& child_edge ( unsigned long edge_index ) const { checker::check_child_edge(edge_index,*this); return *edge_children[edge_index]; } E& child_edge ( unsigned long edge_index ) { checker::check_child_edge(edge_index,*this); return *edge_children[edge_index]; } private: friend class directed_graph_kernel_1; typedef std_allocator<node_type*,mem_manager> alloc_type; typedef std_allocator<shared_ptr<E>,mem_manager> alloc_edge_type; std::vector<node_type*,alloc_type> parents; std::vector<node_type*,alloc_type> children; std::vector<shared_ptr<E>,alloc_edge_type> edge_parents; std::vector<shared_ptr<E>,alloc_edge_type> edge_children; unsigned long idx; }; private: typedef std_allocator<shared_ptr<node_type>,mem_manager> alloc_type; typedef std::vector<shared_ptr<node_type>, alloc_type> vector_type; vector_type nodes; }; // ---------------------------------------------------------------------------------------- template < typename T, typename E, typename mem_manager, bool is_checked > struct is_directed_graph<directed_graph_kernel_1<T,E,mem_manager, is_checked> > { static const bool value = true; }; // ---------------------------------------------------------------------------------------- template < typename T, typename E, typename mem_manager, bool is_checked > inline void swap ( directed_graph_kernel_1<T,E,mem_manager,is_checked>& a, directed_graph_kernel_1<T,E,mem_manager,is_checked>& b ) { a.swap(b); } // ---------------------------------------------------------------------------------------- template < typename T, typename E, typename mem_manager, bool is_checked > void serialize ( const directed_graph_kernel_1<T,E,mem_manager,is_checked>& item, std::ostream& out ) { try { serialize(item.number_of_nodes(), out); // serialize each node for (unsigned long i = 0; i < item.number_of_nodes(); ++i) { serialize(item.node(i).data, out); // serialize all the child edges serialize(item.node(i).number_of_children(), out); for (unsigned long c = 0; c < item.node(i).number_of_children(); ++c) { serialize(item.node(i).child(c).index(), out); serialize(item.node(i).child_edge(c), out); } } } catch (serialization_error& e) { throw serialization_error(e.info + "\n while serializing object of type directed_graph_kernel_1"); } } // ---------------------------------------------------------------------------------------- template < typename T, typename E, typename mem_manager, bool is_checked > void deserialize ( directed_graph_kernel_1<T,E,mem_manager,is_checked>& item, std::istream& in ) { try { unsigned long size; deserialize(size, in); item.clear(); item.set_number_of_nodes(size); // deserialize each node for (unsigned long i = 0; i < item.number_of_nodes(); ++i) { deserialize(item.node(i).data, in); unsigned long num_children; deserialize(num_children, in); // Add all the edges going to this nodes children nodes for (unsigned long c = 0; c < num_children; ++c) { unsigned long child_index; deserialize(child_index, in); item.add_edge(i, child_index); // find the edge we just added for (unsigned long j = 0; j < item.node(i).number_of_children(); ++j) { if (item.node(i).child(j).index() == child_index) { deserialize(item.node(i).child_edge(j), in); break; } } } } } catch (serialization_error& e) { throw serialization_error(e.info + "\n while deserializing object of type directed_graph_kernel_1"); } } // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- // member function definitions // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- template < typename T, typename E, typename mem_manager, bool is_checked > void directed_graph_kernel_1<T,E,mem_manager,is_checked>:: set_number_of_nodes ( unsigned long new_size ) { try { nodes.resize(new_size); for (unsigned long i = 0; i < nodes.size(); ++i) { nodes[i].reset(new node_type); nodes[i]->idx = i; } } catch (...) { clear(); throw; } } // ---------------------------------------------------------------------------------------- template < typename T, typename E, typename mem_manager, bool is_checked > bool directed_graph_kernel_1<T,E,mem_manager,is_checked>:: has_edge ( unsigned long parent_node_index, unsigned long child_node_index ) const { checker::check_has_edge(parent_node_index, child_node_index, *this); node_type& n = *nodes[parent_node_index]; // search all the child nodes to see if there is a link to the right node for (unsigned long i = 0; i < n.children.size(); ++i) { if (n.children[i]->idx == child_node_index) return true; } return false; } // ---------------------------------------------------------------------------------------- template < typename T, typename E, typename mem_manager, bool is_checked > void directed_graph_kernel_1<T,E,mem_manager,is_checked>:: add_edge ( unsigned long parent_node_index, unsigned long child_node_index ) { checker::check_add_edge(parent_node_index, child_node_index, *this); try { node_type& p = *nodes[parent_node_index]; node_type& c = *nodes[child_node_index]; p.children.push_back(&c); c.parents.push_back(&p); p.edge_children.push_back(shared_ptr<E>(new E)); c.edge_parents.push_back(p.edge_children.back()); } catch (...) { clear(); throw; } } // ---------------------------------------------------------------------------------------- template < typename T, typename E, typename mem_manager, bool is_checked > void directed_graph_kernel_1<T,E,mem_manager,is_checked>:: remove_edge ( unsigned long parent_node_index, unsigned long child_node_index ) { checker::check_remove_edge(parent_node_index, child_node_index, *this); node_type& p = *nodes[parent_node_index]; node_type& c = *nodes[child_node_index]; // remove the record of the link from the parent node unsigned long pos = static_cast<unsigned long>(find( p.children.begin(), p.children.end(), &c) - p.children.begin()); p.children.erase(p.children.begin()+pos); p.edge_children.erase(p.edge_children.begin()+pos); // remove the record of the link from the child node pos = static_cast<unsigned long>(find( c.parents.begin(), c.parents.end(), &p) - c.parents.begin()); c.parents.erase(c.parents.begin() + pos); c.edge_parents.erase(c.edge_parents.begin() + pos); } // ---------------------------------------------------------------------------------------- template < typename T, typename E, typename mem_manager, bool is_checked > unsigned long directed_graph_kernel_1<T,E,mem_manager,is_checked>:: add_node ( ) { try { shared_ptr<node_type> n(new node_type); n->idx = nodes.size(); nodes.push_back(n); return n->idx; } catch (...) { clear(); throw; } } // ---------------------------------------------------------------------------------------- template < typename T, typename E, typename mem_manager, bool is_checked > void directed_graph_kernel_1<T,E,mem_manager,is_checked>:: remove_node ( unsigned long index ) { checker::check_remove_node(index,*this); node_type& n = *nodes[index]; // remove all edges pointing to this node from its parents for (unsigned long i = 0; i < n.parents.size(); ++i) { // remove the edge from this specific parent unsigned long pos = static_cast<unsigned long>(find(n.parents[i]->children.begin(), n.parents[i]->children.end(), &n) - n.parents[i]->children.begin()); n.parents[i]->children.erase(n.parents[i]->children.begin() + pos); n.parents[i]->edge_children.erase(n.parents[i]->edge_children.begin() + pos); } // remove all edges pointing to this node from its children for (unsigned long i = 0; i < n.children.size(); ++i) { // remove the edge from this specific child unsigned long pos = static_cast<unsigned long>(find(n.children[i]->parents.begin(), n.children[i]->parents.end(), &n) - n.children[i]->parents.begin()); n.children[i]->parents.erase(n.children[i]->parents.begin() + pos); n.children[i]->edge_parents.erase(n.children[i]->edge_parents.begin() + pos); } // now remove this node by replacing it with the last node in the nodes vector nodes[index] = nodes[nodes.size()-1]; // update the index for the node we just moved nodes[index]->idx = index; // now remove the duplicated node at the end of the vector nodes.pop_back(); } // ---------------------------------------------------------------------------------------- } #endif // DLIB_DIRECTED_GRAPH_KERNEl_1_
[ "jimmy@DGJ3X3B1.(none)" ]
[ [ [ 1, 704 ] ] ]
0dd896bac54825f21295400ed94a0a359d561395
14298a990afb4c8619eea10988f9c0854ec49d29
/PowerBillๅ››ๅท็”ตไฟกไธ“็”จ็‰ˆๆœฌ/ibill_source/SearchFileFrm.cpp
73011c3d7c9f7ca516416ca3012fc8ccbeeff990
[]
no_license
sridhar19091986/xmlconvertsql
066344074e932e919a69b818d0038f3d612e6f17
bbb5bbaecbb011420d701005e13efcd2265aa80e
refs/heads/master
2021-01-21T17:45:45.658884
2011-05-30T12:53:29
2011-05-30T12:53:29
42,693,560
0
0
null
null
null
null
UTF-8
C++
false
false
914
cpp
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "SearchFileFrm.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma link "RzPanel" #pragma link "RzButton" #pragma link "RzEdit" #pragma link "RzSpnEdt" #pragma link "RzRadChk" #pragma resource "*.dfm" TfrmSearchFile *frmSearchFile; //--------------------------------------------------------------------------- __fastcall TfrmSearchFile::TfrmSearchFile(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TfrmSearchFile::btnOkClick(TObject *Sender) { //if(txtFileName->Text == "") // txtFileName->Text = "*.*"; ModalResult = mrOk; } //---------------------------------------------------------------------------
[ "cn.wei.hp@e7bd78f4-57e5-8052-e4e7-673d445fef99" ]
[ [ [ 1, 28 ] ] ]
bbe766cc25975cd1b4acf1d312d1c27005aa186e
db0d644f1992e5a82e22579e6287f45a8f8d357a
/Caster/Dispatcher/Writer.cpp
4a002fc419a9b1fffa451107fa2566a5b99b97f9
[]
no_license
arnout/nano-cast
841a6dc394bfb30864134bce70e11d29b77c2411
5d11094da4dbb5027ce0a3c870b6a6cc9fcc0179
refs/heads/master
2021-01-01T05:14:29.996348
2011-01-15T17:27:48
2011-01-15T17:27:48
58,049,740
1
0
null
null
null
null
UTF-8
C++
false
false
1,091
cpp
/* * Writer.cpp * * Created on: Jul 12, 2010 * Author: John */ #include "Writer.h" Writer::Writer(Connection_ptr& c, CallBack* cb, const char* format, ...) : conn(c), buf(c->buffer), size(strlen((char*)buf)), callback(cb), timeout(10000) { status = Error("Writer:Writer constructor not implemented\n"); } Writer::Writer(Connection_ptr& c, CallBack* cb, const byte* b, size_t s, int t) : conn(c), buf(b), size(s), callback(cb), timeout(t) { } Writer::~Writer() { } bool Writer::Call(bool status) { // Problems encountered, probably timed out if (status != OK) return Switch(callback, Error("Writer: timed out\n")); // If we got bad write, let the callback know. ssize_t actual; if (conn->Write(buf, size, actual) != OK || actual == -1) return Switch(callback, Error("Writer: can't write\n")); // Make note of the new data buf += actual; size -= actual; // Write more data if need be if (size > 0) return WaitForWrite(conn.get(), timeout); // We are done. Invoke the callback return Switch(callback, OK); }
[ [ [ 1, 45 ] ] ]
348b34d3170a628ad0261e8b6d3c700981585558
dbdd79d28ebe34de3aa6d2cedf0d24310b3d8f9a
/Dependencies/OgreMax/OgreMaxRenderWindowIterator.hpp
90170f4b5eaf3327dd2eec77ccb8ea59e79abac6
[ "WTFPL" ]
permissive
sevas/ogre-npr
5ade1846ca26ed5d0f9a78eb7e7356d1c2a69543
b3e1219ac4ec3ad63ae9c7e4b4118bfc59c72c2b
refs/heads/master
2021-01-20T23:17:11.678766
2010-01-24T17:22:10
2010-01-24T17:22:10
400,949
1
0
null
null
null
null
UTF-8
C++
false
false
5,409
hpp
/* * OgreMax Viewer and WinViewer - Ogre3D-based viewers for .scene and .mesh files * Copyright 2009 AND Entertainment * * This code is available under the OgreMax Free License: * -You may use this code for any purpose, commercial or non-commercial. * -If distributing derived works (that use this source code) in binary or source code form, * you must give the following credit in your work's end-user documentation: * "Portions of this work provided by OgreMax (www.ogremax.com)" * * AND Entertainment assumes no responsibility for any harm caused by using this code. * * The OgreMax Viewer and WinViewer were released at www.ogremax.com */ #ifndef OgreMax_OgreMaxRenderWindowIterator_INCLUDED #define OgreMax_OgreMaxRenderWindowIterator_INCLUDED //Classes---------------------------------------------------------------------- namespace OgreMax { /** * An interface for iterating through a collection of Ogre::RenderWindow objects * This should not be used to natively store render windows. Instead, * it should be created as needed, wrapping access to a real collection that is * stored elsewhere. */ class OgreMaxRenderWindowIterator { public: virtual ~OgreMaxRenderWindowIterator() {} virtual bool Start() = 0; virtual Ogre::RenderWindow* GetCurrent() = 0; virtual bool MoveNext() = 0; }; /** Accesses one render window */ class OgreMaxOneRenderWindow : public OgreMaxRenderWindowIterator { public: OgreMaxOneRenderWindow(Ogre::RenderWindow* renderWindow) { this->renderWindow = renderWindow; this->iterationEnabled = false; } bool Start() { this->iterationEnabled = this->renderWindow != 0; return this->iterationEnabled; } Ogre::RenderWindow* GetCurrent() { if (this->iterationEnabled) { this->iterationEnabled = false; return this->renderWindow; } return 0; } bool MoveNext() { this->iterationEnabled = false; return this->iterationEnabled; } protected: Ogre::RenderWindow* renderWindow; bool iterationEnabled; }; /** Accesses a render window array */ class OgreMaxRenderWindowArray : public OgreMaxRenderWindowIterator { public: OgreMaxRenderWindowArray(Ogre::RenderWindow** renderWindows, size_t renderWindowCount) { this->renderWindows = renderWindows; this->renderWindowCount = renderWindowCount; this->iterationEnabled = false; } bool Start() { this->iterationEnabled = this->renderWindowCount > 0; if (this->iterationEnabled) this->iterationIndex = 0; return this->iterationEnabled; } Ogre::RenderWindow* GetCurrent() { if (this->iterationEnabled) return this->renderWindows[this->iterationIndex]; return 0; } bool MoveNext() { if (this->iterationEnabled) { if (++this->iterationIndex == this->renderWindowCount) this->iterationEnabled = false; } return this->iterationEnabled; } protected: Ogre::RenderWindow** renderWindows; size_t renderWindowCount; size_t iterationIndex; bool iterationEnabled; }; /** * Accesses a render window collection (std::list, std::vector, std::set, and so on) * Example usage with a non-const list: * OgreMaxRenderWindowCollection<std::list<Ogre::RenderWindow*>&, std::list<Ogre::RenderWindow*>::iterator> renderWindows(myRenderWindowList); * Example usage with a const vector: * OgreMaxRenderWindowCollection<const std::vector<Ogre::RenderWindow*>&, std::vector<Ogre::RenderWindow*>::const_iterator> renderWindows(myRenderWindowVector); */ template <class COLLECTION, class ITERATOR> class OgreMaxRenderWindowCollection : public OgreMaxRenderWindowIterator { public: OgreMaxRenderWindowCollection(COLLECTION renderWindowCollection) : renderWindows(renderWindowCollection) { this->iterationEnabled = false; } bool Start() { this->iterationEnabled = !this->renderWindows.empty(); if (this->iterationEnabled) this->iterator = this->renderWindows.begin(); return this->iterationEnabled; } Ogre::RenderWindow* GetCurrent() { if (this->iterationEnabled) return *this->iterator; return 0; } bool MoveNext() { if (this->iterationEnabled) { if (++this->iterator == this->renderWindows.end()) this->iterationEnabled = false; } return this->iterationEnabled; } protected: COLLECTION renderWindows; ITERATOR iterator; bool iterationEnabled; }; } #endif
[ "none@none" ]
[ [ [ 1, 169 ] ] ]
24b176777c32fddc614b70235d925c3354dced67
580738f96494d426d6e5973c5b3493026caf8b6a
/Include/Vcl/maskutils.hpp
6e2b36f90626e701de5c748a0d6ed83055abf44d
[]
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
3,299
hpp
// Borland C++ Builder // Copyright (c) 1995, 2002 by Borland Software Corporation // All rights reserved // (DO NOT EDIT: machine generated header) 'MaskUtils.pas' rev: 6.00 #ifndef MaskUtilsHPP #define MaskUtilsHPP #pragma delphiheader begin #pragma option push -w- #pragma option push -Vx #include <SysInit.hpp> // Pascal unit #include <System.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Maskutils { //-- type declarations ------------------------------------------------------- #pragma option push -b- enum TMaskCharType { mcNone, mcLiteral, mcIntlLiteral, mcDirective, mcMask, mcMaskOpt, mcFieldSeparator, mcField }; #pragma option pop #pragma option push -b- enum MaskUtils__1 { mdReverseDir, mdUpperCase, mdLowerCase, mdLiteralChar }; #pragma option pop typedef Set<MaskUtils__1, mdReverseDir, mdLiteralChar> TMaskDirectives; typedef AnsiString TMaskedText; typedef AnsiString TEditMask; //-- var, const, procedure --------------------------------------------------- extern PACKAGE char DefaultBlank; extern PACKAGE char MaskFieldSeparator; extern PACKAGE char MaskNoSave; static const char mDirReverse = '\x21'; static const char mDirUpperCase = '\x3e'; static const char mDirLowerCase = '\x3c'; static const char mDirLiteral = '\x5c'; static const char mMskAlpha = '\x4c'; static const char mMskAlphaOpt = '\x6c'; static const char mMskAlphaNum = '\x41'; static const char mMskAlphaNumOpt = '\x61'; static const char mMskAscii = '\x43'; static const char mMskAsciiOpt = '\x63'; static const char mMskNumeric = '\x30'; static const char mMskNumericOpt = '\x39'; static const char mMskNumSymOpt = '\x23'; static const char mMskTimeSeparator = '\x3a'; static const char mMskDateSeparator = '\x2f'; extern PACKAGE TMaskCharType __fastcall MaskGetCharType(const AnsiString EditMask, int MaskOffset); extern PACKAGE TMaskDirectives __fastcall MaskGetCurrentDirectives(const AnsiString EditMask, int MaskOffset); extern PACKAGE char __fastcall MaskIntlLiteralToChar(char IChar); extern PACKAGE AnsiString __fastcall MaskDoFormatText(const AnsiString EditMask, const AnsiString Value, char Blank); extern PACKAGE bool __fastcall MaskGetMaskSave(const AnsiString EditMask); extern PACKAGE char __fastcall MaskGetMaskBlank(const AnsiString EditMask); extern PACKAGE int __fastcall MaskGetFldSeparator(const AnsiString EditMask); extern PACKAGE int __fastcall MaskOffsetToOffset(const AnsiString EditMask, int MaskOffset); extern PACKAGE int __fastcall MaskOffsetToWideOffset(const AnsiString EditMask, int MaskOffset); extern PACKAGE int __fastcall OffsetToMaskOffset(const AnsiString EditMask, int Offset); extern PACKAGE bool __fastcall IsLiteralChar(const AnsiString EditMask, int Offset); extern PACKAGE AnsiString __fastcall PadInputLiterals(const AnsiString EditMask, const AnsiString Value, char Blank); extern PACKAGE AnsiString __fastcall FormatMaskText(const AnsiString EditMask, const AnsiString Value); } /* namespace Maskutils */ using namespace Maskutils; #pragma option pop // -w- #pragma option pop // -Vx #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // MaskUtils
[ "bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b" ]
[ [ [ 1, 75 ] ] ]
23b4f0c3efdc693fdf9e1f0095542d7a59b722d8
f7d8a85f9d0c1956d64efbe96d056e338b0e0641
/Src/parser.h
bb25733aa00b953a02f1a2400737560bb4963d28
[]
no_license
thennequin/dlfm
6183dfeb485f860396573eda125fd61dcd497660
0b122e7042ec3b48660722e2b41ef0a0551a70a9
refs/heads/master
2020-04-11T03:53:12.856319
2008-07-06T10:17:29
2008-07-06T10:17:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
361
h
#include "wx/wx.h" #include <curl\curl.h> #ifndef _PARSER_ #define _PARSER_ class Parser { public: static bool IsValidLink(wxString link); static bool IsFreeLink(wxString link); static curl_off_t GetFileSizeHTTP(wxString header); static wxString GetFilenameFromURL(wxString url); static wxString FirstLine(wxString text); }; #endif
[ "CameleonTH@0c2b0ced-2a4c-0410-b056-e1a948518b24" ]
[ [ [ 1, 20 ] ] ]
dfca9b268369b52cfee63c630677fe61b08aaaf9
1cf1543cd5460621f530f730a4f3969cfa74197c
/ParseTree.h
c095429db5dac8bc813ec9d9a8fa743521a21882
[]
no_license
derpepe/sysprog
042048d0c8f30fb26f0fb79a024530f67a852ca9
2fa6fb3b7c7f53b3fa8ff6aeb74d8d3e3331ba61
refs/heads/master
2021-01-18T14:01:45.742680
2010-02-23T22:23:25
2010-02-23T22:23:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
723
h
#pragma once #include <iostream> #include "Node.h" #include "Scanner.h" #include "Marker.h" class ParseTree { public: ParseTree(Scanner *myScanner); Node *getRootNode(); void printXML(); Scanner *getScanner(); // needed if you want to use the scanner, p.ex. for viewing the symtable void typeCheck(Node *myNode = NULL); // helper functions that match getting and setting of typification for identifiers to the symtable SymTableEntry *getSymTableEntryForIdentifier(std::string identifier); void setType(Node *myNode, typification myType); typification getType(Node *myNode); void makeCode(Node *myNode = NULL); private: Node *rootNode; Scanner *myScanner; };
[ [ [ 1, 34 ] ] ]
2dce4c9f1c98ea067a656d24b4dcaaec404078c7
c2c93fc3fd90bd77764ac3016d816a59b2370891
/Incomplited/Hooks module SA-MP 0.1/hooks/export.cpp
838745dc4436932021bcf7e6d5bd491390e6dde8
[]
no_license
MsEmiNeko/samp-alex009-projects
a1d880ee3116de95c189ef3f79ce43b163b91603
9b9517486b28411c8b747fae460266a88d462e51
refs/heads/master
2021-01-10T16:22:34.863725
2011-04-30T04:01:15
2011-04-30T04:01:15
43,719,520
0
1
null
2018-01-19T16:55:45
2015-10-05T23:23:37
SourcePawn
UTF-8
C++
false
false
864
cpp
/* * Copyright (C) 2011 Alex009 * License read in license.txt */ #include "hooks.h" CHooks * pHooks = NULL; void __stdcall EXPORT_InitializeHooks(unsigned long version) { if(!pHooks) pHooks = new CHooks(version); } void __stdcall EXPORT_ClientConnect(void* players,int id,char* name,int npc_flag) { if(pHooks) pHooks->ClientConnect(players,id,name,1); } void __stdcall EXPORT_ClientDisconnect(void* players,int id,int reason) { if(pHooks) pHooks->ClientDisconnect(players,id,reason); } void __stdcall EXPORT_ClientSpawn(void* player) { if(pHooks) pHooks->ClientSpawn(player); } void __stdcall EXPORT_ClientDeath(void* player,int reason,int killerid) { if(pHooks) pHooks->ClientDeath(player,reason,killerid); } MUTEX_IDENTIFY(__stdcall EXPORT_GetMutex()) { if(pHooks) return pHooks->GetMutex(); return NULL; }
[ [ [ 1, 39 ] ] ]
ec4e2510581f21ef0690409056dad6aadb084c45
3d560d0b4772580943946c78e2612ac0589c7958
/examples/serialization_test.cpp
c8f4193266c2832856aebf53423ddb81481078c9
[]
no_license
black-square/id2type-cast
b792f9d9c00afebba856494db58a4151dcfd2b33
1a313b55c1dac2ea388c943fa4bf326eaa1957c3
refs/heads/master
2020-05-30T13:03:58.304192
2011-11-01T09:46:58
2011-11-01T09:46:58
32,418,189
0
0
null
null
null
null
UTF-8
C++
false
false
4,564
cpp
#include "./poly_serialization.hpp" #include <sstream> #include <iostream> #include <ctime> using i2tc::id2type_cast; #if 1 typedef i2tc::virt_func_tag emb_type_id_impl; #else typedef i2tc::member_tag emb_type_id_impl; #endif struct DataTypes; struct BaseData: i2tc::embedded_type_id_base<DataTypes, emb_type_id_impl> { virtual ~BaseData() {} }; struct AData: i2tc::embedded_type_id_derived<AData, BaseData> { short a; AData(): a(static_cast<short>(rand())) { std::cout << "AData()" << std::endl; } ~AData() { std::cout << "~AData()" << std::endl; } template<class Archive> void Serialize(Archive & archive) { archive & a; } }; struct BData: i2tc::embedded_type_id_derived<BData, BaseData> { long d; double e; BData(): d(static_cast<long>(rand())), e(static_cast<double>(rand())) { std::cout << "BData()" << std::endl; } ~BData() { std::cout << "~BData()" << std::endl; } template<class Archive> void Serialize(Archive & archive) { archive & d & e; } }; struct CData: i2tc::embedded_type_id_derived<CData, BaseData> { float g; unsigned short h; unsigned int i; CData(): g(static_cast<float>(rand())), h(static_cast<unsigned short>(rand())), i(static_cast<unsigned int>(rand())) { std::cout << "CData()" << std::endl; } ~CData() { std::cout << "~CData()" << std::endl; } template<class Archive> void Serialize(Archive & archive) { archive & g & h & i; } }; struct DataTypes: i2tc::type_list::base<> { template <int N> struct at; }; template <int N> struct DataTypes::at{ typedef i2tc::type_list::undefined_tag type; }; template <> struct DataTypes::at<0>{ typedef AData type; }; template <> struct DataTypes::at<1>{ typedef BData type; }; template <> struct DataTypes::at<2>{ typedef CData type; }; struct RegularData { double e; RegularData(): e(static_cast<double>(rand())) { std::cout << "RegularData()" << std::endl; } ~RegularData() { std::cout << "~RegularData()" << std::endl; } template<class Archive> void Serialize(Archive & archive) { archive & e; } }; struct Data { int a; BaseData *pBase; RegularData *pRegData; Data(): a( rand() ), pBase(0), pRegData(0) {} ~Data() { delete pBase; delete pRegData; } template<class Archive> void Serialize(Archive & archive) { archive & a & pBase & pRegData; } }; struct CreateFunctor: i2tc::function<BaseData *> { template<class T> BaseData *operator()( const T * ) const { return new T; } }; template<class T> void print( T & t) { std::stringstream stream; poly_serialization::writer outSlr(stream); t.Serialize(outSlr); std::cout << stream.str() << std::endl; } void initBaseImpl( Data &data, int curType ) { if( curType != i2tc::type_list::size<DataTypes>::value ) { data.pBase = id2type_cast<DataTypes, CreateFunctor>( curType ); data.pRegData = new RegularData; } } void SerializationTestImpl( int curType ) { std::string rawData; std::cout << "Write to rawData" << std::endl; { Data data; initBaseImpl(data, curType); std::stringstream stream; poly_serialization::writer outSlr(stream); data.Serialize(outSlr); rawData = stream.str(); std::cout << rawData << std::endl; } std::cout << std::endl << "Read from rawData clean object" << std::endl; { Data data; print(data); std::stringstream stream( rawData ); poly_serialization::reader inSlr(stream); data.Serialize(inSlr); print(data); } std::cout << std::endl << "Read from rawData exists object" << std::endl; { Data data; initBaseImpl(data, 2); print(data); std::stringstream stream( rawData ); poly_serialization::reader inSlr(stream); data.Serialize(inSlr); print(data); } } void serializationTest() { for(int i = 0; i < i2tc::type_list::size<DataTypes>::value + 1; ++ i ) { std::cout << ">>>> Type # " << i << std::endl; SerializationTestImpl(i); std::cout << std::endl; } } #ifdef MAIN_DEFINITION_REQUIRED int main() { serializationTest(); return 0; } #endif
[ [ [ 1, 195 ] ] ]
23d82759090f3237d7a5c17eec2dfe09a9414b8c
4ab592fb354f75b42181d5375d485031960aaa7d
/DES_GOBSTG/DES_GOBSTG/Class/Fontsys.cpp
27d8c54988d8f56f34937bb771d03c61f9a2769b
[]
no_license
CBE7F1F65/cca610e2e115c51cef211fafb0f66662
806ced886ed61762220b43300cb993ead00949dc
b3cdff63d689e2b1748e9cd93cedd7e8389a7057
refs/heads/master
2020-12-24T14:55:56.999923
2010-07-23T04:24:59
2010-07-23T04:24:59
32,192,699
0
0
null
null
null
null
UTF-8
C++
false
false
5,603
cpp
#include "../Header/Fontsys.h" #include "../Header/Main.h" #include "../Header/Scripter.h" #include "../Header/Data.h" #include "../Header/SpriteItemManager.h" #include "../Header/Player.h" #include "../Header/BResource.h" HD3DFONT Fontsys::d3dfont = NULL; hgeFont * Fontsys::font = NULL; Fontsys::Fontsys() { } Fontsys::~Fontsys() { } void Fontsys::Release() { if (font) { delete font; font = NULL; } } void Fontsys::Init(HD3DFONT _d3dfont) { d3dfont = _d3dfont; Release(); // changeID = -1; } void Fontsys::DoHeatUpBuffer( const char* str, list<int> * charcodelist ) { int nowindex = 0; int len = strlen(str); if (len) { while (nowindex < len) { int i=*(unsigned char*)(&(str[nowindex])); nowindex++; if (i > 0x7f && nowindex < len) { i = i << 8; i = i | (*(unsigned char*)(&(str[nowindex]))); nowindex++; } else { continue; } bool tocontinue = false; list<int>::iterator it=charcodelist->begin(); for (; it!=charcodelist->end(); it++) { if (*it == i) { tocontinue = true; break; } else if (*it > i) { break; } } if (tocontinue) { continue; } int _charcode = i; charcodelist->insert(it, 1, _charcode); // charcodelist->push_back(_charcode); } } } void Fontsys::HeatUp(bool rebuildfont) { if (rebuildfont) { #ifdef __WIN32 if (!d3dfont) { return; } list<int> charcodelist; for (int i=0; i<PLAYERTYPEMAX; i++) { DoHeatUpBuffer(BResource::bres.playerdata[i].name, &charcodelist); for (int j=0; j<3; j++) { DoHeatUpBuffer(BResource::bres.playerdata[i].spellname[j], &charcodelist); } } for (int i=0; i<ENEMYTYPEMAX; i++) { DoHeatUpBuffer(BResource::bres.enemydata[i].name, &charcodelist); DoHeatUpBuffer(BResource::bres.enemydata[i].ename, &charcodelist); } for (int i=0; i<MUSICMAX; i++) { DoHeatUpBuffer(BResource::bres.musdata[i].musicname, &charcodelist); } Export_Lua::HeatUp(&charcodelist); int * charcodes = (int *)malloc(charcodelist.size() * sizeof(int)); int i = 0; for (list<int>::iterator it=charcodelist.begin(); it!=charcodelist.end(); it++, i++) { charcodes[i] = *it; } if (hgeFont::CreateFontFileByInfo(charcodes, i, BResource::bres.resdata.fontfilename, d3dfont)) { } free(charcodes); #endif // __WIN32 } if (font) { delete font; } font = new hgeFont(BResource::bres.resdata.fontfilename); /* for (int i=0; i<scr.strdescIndex; i+=(i+1)) { SignUp(FONTSYS_CHATUSE, strdesc[i]); } */ /* for (int i=0; i<PLAYERTYPEMAX; i++) { SignUp(i%FONTSYSMAX, Data::data.getPlayerName(i), 1.25f); } for (int i=0; i<ENEMYTYPEMAX; i++) { SignUp(i%FONTSYSMAX, Data::data.getEnemyName(i), 1.25f); }*/ } void Fontsys::FocusChanged() { /* Release(); SignUp(FONTSYS_CHATUSE, NULL, fontscale[FONTSYS_CHATUSE]); SignUp(FONTSYS_SPELLNAMEUSE, NULL, fontscale[FONTSYS_SPELLNAMEUSE]); if (changeID >= 0) { for (int i=0; i<=changeID; i++) { SignUp(i, NULL, fontscale[i]); } }*/ } int Fontsys::strTranslate(char * dtext, const char * stext) { int ret = 1; int j=0; strcpy(dtext, ""); for(int i=0;i<(int)strlen(stext);i++) { if (stext[i] == '\n') { ret++; } if (stext[i]<0) { char twchar[3]; twchar[0] = stext[i]; i++; j+=2; twchar[1] = stext[i]; twchar[2] = 0; strcat(dtext, twchar); continue; } if(stext[i] == FONTSYS_TRANSCHAR) { i++; if(stext[i] != FONTSYS_TRANSCHAR) { int strcodecon = stext[i] - '0'; if(!strcodecon) { int strcodeval = (stext[i+1] - '0') * 10 + (stext[i+2] - '0'); while(j < strcodeval) { strcat(dtext, " "); j++; } i += 2; continue; } else { int strcodeval1 = (stext[i+1] - '0') * 10 + (stext[i+2] - '0'); int strcodeval2 = (stext[i+3] - '0') * 10 + (stext[i+4] - '0'); while(j < strcodeval1) { strcat(dtext, " "); j++; } i += 4; char buffer[32]; int k = 0; while(!(stext[i+1] == FONTSYS_TRANSCHAR && stext[i+2] == FONTSYS_CONTROLCHAR)) { i++; buffer[k] = stext[i]; k++; } buffer[k] = 0; for(int l=k;l<strcodeval2-strcodeval1;l++) { if(strcodecon == 2) strcat(dtext, "0"); else strcat(dtext, " "); j++; } strcat(dtext, buffer); i += 2; j += k; continue; } } } char tbuff[2]; tbuff[0] = stext[i]; tbuff[1] = 0; strcat(dtext, tbuff); j++; } return ret; } void Fontsys::SignUp(const char * _text, float scale) { if (_text != NULL) { strTranslate(text, _text); } fontscale = scale; } void Fontsys::SetColor(DWORD col0, DWORD col1, DWORD col2, DWORD col3) { font->SetColor(col0, col1, col2, col3); } void Fontsys::SetColor(DWORD col, int i) { font->SetColor(col, i); } void Fontsys::Render(float x, float y, float shadow, BYTE alignflag) { if (!font) { return; } if (shadow) { DWORD _col[4]; for (int i=0; i<4; i++) { _col[i] = font->GetColor(i); } font->SetColor(_col[0]&0xff000000, _col[1]&0xff000000, _col[2]&0xff000000, _col[3]&0xff000000); Render(x+shadow, y+shadow, 0, alignflag); font->SetColor(_col[0], _col[1], _col[2], _col[3]); } font->SetScale(fontscale); font->Render(x, y, alignflag, text); }
[ "CBE7F1F65@4a173d03-4959-223b-e14c-e2eaa5fc8a8b" ]
[ [ [ 1, 286 ] ] ]
d806567704e55fca8574ac53d3c28f631d8771a6
1e01b697191a910a872e95ddfce27a91cebc57dd
/GrfInsertTextOnceToFloatingLocation.cpp
9849c0a193beea7dcb07c28f6f7ce10c07960af6
[]
no_license
canercandan/codeworker
7c9871076af481e98be42bf487a9ec1256040d08
a68851958b1beef3d40114fd1ceb655f587c49ad
refs/heads/master
2020-05-31T22:53:56.492569
2011-01-29T19:12:59
2011-01-29T19:12:59
1,306,254
7
5
null
null
null
null
IBM852
C++
false
false
3,079
cpp
/* "CodeWorker": a scripting language for parsing and generating text. Copyright (C) 1996-1997, 1999-2010 Cรšdric Lemaire 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA To contact the author: [email protected] */ #ifdef WIN32 #pragma warning (disable : 4786) #endif #include "ScpStream.h" #include "CppCompilerEnvironment.h" #include "CGRuntime.h" #include "ExprScriptExpression.h" #include <string> //##protect##"INCLUDE FILES" #include "DtaScriptVariable.h" #include "DtaPatternScript.h" #include "GrfInsertText.h" //##protect##"INCLUDE FILES" #include "GrfInsertTextOnceToFloatingLocation.h" namespace CodeWorker { GrfInsertTextOnceToFloatingLocation::~GrfInsertTextOnceToFloatingLocation() { delete _pLocation; delete _pText; } SEQUENCE_INTERRUPTION_LIST GrfInsertTextOnceToFloatingLocation::executeInternal(DtaScriptVariable& visibility) { std::string sLocation = _pLocation->getValue(visibility); std::string sText = _pText->getValue(visibility); //##protect##"execute" if (*_pOutputCoverage != NULL) { ScpStream* pOwner; int iLocation = CGRuntime::getOutputStream()->getFloatingLocation(sLocation, pOwner); if (pOwner == NULL) throw UtlException("the floating location '" + sLocation + "' doesn't exist"); if (CGRuntime::getOutputStream()->insertTextOnce(sText, iLocation)) { int iCoverageLocation = iLocation + (*_pOutputCoverage)->getIntValue(); DtaScriptVariable* pCoverage = GrfInsertText::getCoverageItem(*_pOutputCoverage, sText.size(), iCoverageLocation, "I"); pCoverage->insertNode("script")->setValue(_iFileLocation); pCoverage->insertNode("output")->setValue(iCoverageLocation); } return NO_INTERRUPTION; } //##protect##"execute" return CGRuntime::insertTextOnceToFloatingLocation(sLocation, sText); } //##protect##"implementation" void GrfInsertTextOnceToFloatingLocation::prepareCoverage(DtaScriptVariable* const* pOutputCoverage) { _pOutputCoverage = pOutputCoverage; } //##protect##"implementation" void GrfInsertTextOnceToFloatingLocation::compileCpp(CppCompilerEnvironment& theCompilerEnvironment) const { CW_BODY_INDENT << "CGRuntime::insertTextOnceToFloatingLocation("; _pLocation->compileCppString(theCompilerEnvironment); CW_BODY_STREAM << ", "; _pText->compileCppString(theCompilerEnvironment); CW_BODY_STREAM << ");"; CW_BODY_ENDL; } }
[ "cedric.p.r.lemaire@28b3f5f3-d42e-7560-b87f-5f53cf622bc4" ]
[ [ [ 1, 80 ] ] ]
beb25b6fea8ee33116e75f1d8ebedba67fc809f2
d8470a77f5e1661ad4e56d07e4be3de459f84442
/CUDAColoring/metisCleanPartition/graphColoring.h
55d72234c9899884f9f0dc8780228f622a92dc96
[]
no_license
bdosari/cudagraphcoloring
bbe9e4c104b2b6f0d431fd8c102682163fe101d5
c656eb51b619afcf862ed2fbacdaf6a36233bbb1
refs/heads/master
2020-12-24T18:33:08.744094
2010-09-21T15:07:27
2010-09-21T15:07:27
58,252,780
0
0
null
null
null
null
UTF-8
C++
false
false
1,047
h
#ifndef _GRAPHCOLORING_H_ #define _GRAPHCOLORING_H_ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <cuda_runtime_api.h> #include <cuda.h> #include <iostream> using namespace std; // Should be at least equal to maxDegree of graph + 1 // if doing that generates an error like: too much local memory, then use commented line // maked OPTION2 instead of OPTION1 in function color & saturation in gaphColoring.cu const int TEMP_COLOR_LENGTH = 256;//1024; const int CONFLICT_BLOCK_SIZE = 256; #ifdef __cplusplus #define CHECK_EXT extern "C" #else #define CHECK_EXT #endif CHECK_EXT void cudaGraphColoring(int *adjacentList, int *boundaryList, int *graphColors, int *degreeList, int *conflict, int boundarySize, int maxDegree, int graphSize, int passes, int subsizeBoundary, int _gridSize, int _blockSize, int *startPartitionList, int *endPartitionList, int *randomList, int numRand); #endif // _GRAPHCOLORING_H_
[ "zetwal@47f1d34c-260b-ee67-dd51-b23b07e135cf" ]
[ [ [ 1, 36 ] ] ]
93ab0b8577178ce26c8be2a510b4fb5c6ce323f8
96fefafdfbb413a56e0a2444fcc1a7056afef757
/MQ2Main/MQ2Commands.cpp
c9c1bb1485df349c674c8e21b68cec60cde81190
[]
no_license
kevrgithub/peqtgc-mq2-sod
ffc105aedbfef16060769bb7a6fa6609d775b1fa
d0b7ec010bc64c3f0ac9dc32129a62277b8d42c0
refs/heads/master
2021-01-18T18:57:16.627137
2011-03-06T13:05:41
2011-03-06T13:05:41
32,849,784
1
3
null
null
null
null
UTF-8
C++
false
false
119,404
cpp
/***************************************************************************** MQ2Main.dll: MacroQuest2's extension DLL for EverQuest Copyright (C) 2002-2003 Plazmic, 2003-2005 Lax This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ******************************************************************************/ #if !defined(CINTERFACE) #error /DCINTERFACE #endif #ifndef ISXEQ #define DBG_SPEW #include <direct.h> #include "MQ2Main.h" #include <Shellapi.h> #include <mmsystem.h> // *************************************************************************** // Function: Unload // Description: Our '/unload' command // Triggers the DLL to unload itself // Usage: /unload // *************************************************************************** VOID Unload(PSPAWNINFO pChar, PCHAR szLine) { bRunNextCommand = TRUE; if (gMacroBlock) EndMacro(pChar,szLine); DebugSpew(ToUnloadString); WriteChatColor(ToUnloadString,USERCOLOR_DEFAULT); gbUnload = TRUE; } // *************************************************************************** // Function: ListMacros // Description: Our '/listmacros' command // Lists macro files // Usage: /listmacros <partial filename> // *************************************************************************** VOID ListMacros(PSPAWNINFO pChar, PCHAR szLine) { bRunNextCommand = TRUE; HANDLE hSearch; WIN32_FIND_DATA FileData; BOOL fFinished = FALSE; DWORD Count = 0, a,b; CHAR szFilename[MAX_STRING] = {0}; CHAR szName[100][MAX_STRING] = {0}; if (szLine[0]!=0) { sprintf(szFilename,"%s\\*%s*.*",gszMacroPath, szLine); } else { sprintf(szFilename,"%s\\*.*",gszMacroPath, szLine); } // Start searching for .TXT files in the current directory. hSearch = FindFirstFile(szFilename, &FileData); if (hSearch == INVALID_HANDLE_VALUE) { WriteChatColor("Couldn't find any macros",USERCOLOR_DEFAULT); return; } while (!fFinished) { strcat(szName[Count],FileData.cFileName); Count++; if (Count>99) fFinished=TRUE; if (!FindNextFile(hSearch, &FileData)) fFinished = TRUE; } FindClose(hSearch); Count; for (a=Count-1;a>0;a--) { for (b=0;b<a;b++) { if (szName[b]>szName[b+1]) { strcat(szFilename,szName[b]); strcat(szName[b],szName[b+1]); strcat(szName[b+1],szFilename); } } } WriteChatColor("Macro list",USERCOLOR_WHO); WriteChatColor("----------------",USERCOLOR_WHO); for (a=0;a<Count;a++) { WriteChatColor(szName[a],USERCOLOR_WHO); } } // *************************************************************************** // Function: Items // Description: Our '/items' command // Lists ground item info // Usage: /items <filter> // *************************************************************************** VOID Items(PSPAWNINFO pChar, PCHAR szLine) { bRunNextCommand = TRUE; if (!ppItemList) return; if (!pItemList) return; PGROUNDITEM pItem = (PGROUNDITEM)pItemList; DWORD Count=0; CHAR szBuffer[MAX_STRING] = {0}; CHAR szName[MAX_STRING]={0}; WriteChatColor("Items on the ground:", USERCOLOR_DEFAULT); WriteChatColor("---------------------------", USERCOLOR_DEFAULT); while (pItem) { GetFriendlyNameForGroundItem(pItem,szName); DebugSpew(" Item found - %d: DropID %d %s (%s)", pItem->ID, pItem->DropID, szName, pItem->Name); if ((szLine[0]==0) || (!strnicmp(szName,szLine,strlen(szLine)))) { SPAWNINFO TempSpawn; FLOAT Distance; ZeroMemory(&TempSpawn,sizeof(TempSpawn)); strcpy(TempSpawn.Name,szName); TempSpawn.Y=pItem->Y; TempSpawn.X=pItem->X; TempSpawn.Z=pItem->Z; Distance = DistanceToSpawn(pChar,&TempSpawn); INT Angle = (INT)((atan2f(pChar->X - pItem->X, pChar->Y - pItem->Y) * 180.0f / PI + 360.0f) / 22.5f + 0.5f) % 16; sprintf(szBuffer,"%s: %1.2f away to the %s",szName,Distance,szHeading[Angle]); WriteChatColor(szBuffer,USERCOLOR_DEFAULT); Count++; } pItem = pItem->pNext; } if (Count==0) { WriteChatColor("No items found.",USERCOLOR_DEFAULT); } else { sprintf(szBuffer,"%d item%s found.",Count,(Count==1)?"":"s"); WriteChatColor(szBuffer,USERCOLOR_DEFAULT); } } // *************************************************************************** // Function: ItemTarget // Description: Our '/itemtarget' command // Lists ground item info // Usage: /itemtarget <text> // *************************************************************************** VOID ItemTarget(PSPAWNINFO pChar, PCHAR szLine) { bRunNextCommand = TRUE; if (!ppItemList) return; if (!pItemList) return; PGROUNDITEM pItem = (PGROUNDITEM)pItemList; CHAR Arg1[MAX_STRING] = {0}; CHAR Arg2[MAX_STRING] = {0}; CHAR szBuffer[MAX_STRING] = {0}; CHAR szName[MAX_STRING]={0}; FLOAT cDistance = 100000.0f; ZeroMemory(&EnviroTarget,sizeof(EnviroTarget)); pGroundTarget = NULL; GetArg(Arg1,szLine,1); GetArg(Arg2,szLine,2); while (pItem) { GetFriendlyNameForGroundItem(pItem,szName); if ( ( (szLine[0]==0) || (!strnicmp(szName,Arg1,strlen(Arg1))) ) && ( (gZFilter >=10000.0f) || ( (pItem->Z <= pChar->Z + gZFilter) && (pItem->Z >= pChar->Z - gZFilter) ) ) ) { SPAWNINFO tSpawn; ZeroMemory(&tSpawn,sizeof(tSpawn)); strcpy(tSpawn.Name,szName); tSpawn.Y=pItem->Y; tSpawn.X=pItem->X; tSpawn.Z=pItem->Z; tSpawn.Type = SPAWN_NPC; tSpawn.HPCurrent = 1; tSpawn.HPMax = 1; tSpawn.Heading=pItem->Heading; tSpawn.Race = pItem->DropID; FLOAT Distance = DistanceToSpawn(pChar,&tSpawn); if (Distance<cDistance) { CopyMemory(&EnviroTarget,&tSpawn,sizeof(EnviroTarget)); cDistance=Distance; pGroundTarget = pItem; } } pItem = pItem->pNext; } if (EnviroTarget.Name[0]!=0) { sprintf(szBuffer,"Item '%s' targeted.",EnviroTarget.Name); WriteChatColor(szBuffer,USERCOLOR_DEFAULT); if (stricmp(Arg2,"notarget") && ppTarget && 0) pTarget = (EQPlayer*)&EnviroTarget; } else { if (ppTarget && (pTarget == (EQPlayer*)&EnviroTarget)) pTarget = NULL; MacroError("Couldn't find '%s' to target.",szLine); } } // *************************************************************************** // Function: Doors // Description: Our '/doors' command // Lists door info // Usage: /doors <filter> // *************************************************************************** VOID Doors(PSPAWNINFO pChar, PCHAR szLine) { bRunNextCommand = TRUE; if (!ppSwitchMgr) return; if (!pSwitchMgr) return; PDOORTABLE pDoorTable = (PDOORTABLE)pSwitchMgr; DWORD Count; DWORD ActualCount=0; CHAR szBuffer[MAX_STRING] = {0}; WriteChatColor("Doors:", USERCOLOR_DEFAULT); WriteChatColor("---------------------------", USERCOLOR_DEFAULT); size_t slen = strlen(szLine); for (Count=0; Count<pDoorTable->NumEntries; Count++) { if ((szLine[0]==0) || (!strnicmp(pDoorTable->pDoor[Count]->Name,szLine,slen))) { SPAWNINFO TempSpawn; FLOAT Distance; ZeroMemory(&TempSpawn,sizeof(TempSpawn)); strcpy(TempSpawn.Name,pDoorTable->pDoor[Count]->Name); TempSpawn.Y=pDoorTable->pDoor[Count]->Y; TempSpawn.X=pDoorTable->pDoor[Count]->X; TempSpawn.Z=pDoorTable->pDoor[Count]->Z; TempSpawn.Heading=pDoorTable->pDoor[Count]->Heading; Distance = DistanceToSpawn(pChar,&TempSpawn); INT Angle = (INT)((atan2f(pChar->X - pDoorTable->pDoor[Count]->X, pChar->Y - pDoorTable->pDoor[Count]->Y) * 180.0f / PI + 360.0f) / 22.5f + 0.5f) % 16; sprintf(szBuffer,"%d: %s: %1.2f away to the %s",pDoorTable->pDoor[Count]->ID, pDoorTable->pDoor[Count]->Name, Distance, szHeading[Angle]); WriteChatColor(szBuffer,USERCOLOR_DEFAULT); ActualCount++; } } if (ActualCount==0) { WriteChatColor("No Doors found.",USERCOLOR_DEFAULT); } else { sprintf(szBuffer,"%d door%s found.",ActualCount,(ActualCount==1)?"":"s"); WriteChatColor(szBuffer,USERCOLOR_DEFAULT); } } // *************************************************************************** // Function: DoorTarget // Description: Our '/doortarget' command // Targets the nearest specified door // Usage: /doortarget <text> // *************************************************************************** VOID DoorTarget(PSPAWNINFO pChar, PCHAR szLine) { bRunNextCommand = TRUE; if (!ppSwitchMgr) return; if (!pSwitchMgr) return; PDOORTABLE pDoorTable = (PDOORTABLE)pSwitchMgr; DWORD Count; CHAR szBuffer[MAX_STRING] = {0}; CHAR szSearch[MAX_STRING] = {0}; CHAR Arg1[MAX_STRING] = {0}; CHAR Arg2[MAX_STRING] = {0}; FLOAT cDistance = 100000.0f; BYTE ID = -1; ZeroMemory(&DoorEnviroTarget,sizeof(DoorEnviroTarget)); pDoorTarget = NULL; GetArg(Arg1,szLine,1); GetArg(Arg2,szLine,2); if (!stricmp(Arg1, "id")) { if (Arg2[0]==0) { MacroError("DoorTarget: id specified but no number provided."); return; } ID = atoi(Arg2); GetArg(Arg2,szLine,3); for (Count=0; Count<pDoorTable->NumEntries; Count++) { if (pDoorTable->pDoor[Count]->ID == ID) { strcpy(DoorEnviroTarget.Name, pDoorTable->pDoor[Count]->Name); DoorEnviroTarget.Y = pDoorTable->pDoor[Count]->Y; DoorEnviroTarget.X = pDoorTable->pDoor[Count]->X; DoorEnviroTarget.Z = pDoorTable->pDoor[Count]->Z; DoorEnviroTarget.Heading = pDoorTable->pDoor[Count]->Heading; DoorEnviroTarget.Type = SPAWN_NPC; DoorEnviroTarget.HPCurrent = 1; DoorEnviroTarget.HPMax = 1; pDoorTarget = pDoorTable->pDoor[Count]; break; } } } else { strcpy(szSearch, Arg1); for (Count=0; Count<pDoorTable->NumEntries; Count++) { if (((szSearch[0]==0) || (!strnicmp(pDoorTable->pDoor[Count]->Name,szSearch,strlen(szSearch)))) && ((gZFilter >=10000.0f) || ((pDoorTable->pDoor[Count]->Z <= pChar->Z + gZFilter) && (pDoorTable->pDoor[Count]->Z >= pChar->Z - gZFilter)))) { SPAWNINFO tSpawn; ZeroMemory(&tSpawn,sizeof(tSpawn)); strcpy(tSpawn.Name,pDoorTable->pDoor[Count]->Name); tSpawn.Y=pDoorTable->pDoor[Count]->Y; tSpawn.X=pDoorTable->pDoor[Count]->X; tSpawn.Z=pDoorTable->pDoor[Count]->Z; tSpawn.Type = SPAWN_NPC; tSpawn.HPCurrent = 1; tSpawn.HPMax = 1; tSpawn.Heading=pDoorTable->pDoor[Count]->Heading; FLOAT Distance = DistanceToSpawn(pChar,&tSpawn); if (Distance<cDistance) { CopyMemory(&DoorEnviroTarget,&tSpawn,sizeof(DoorEnviroTarget)); pDoorTarget = pDoorTable->pDoor[Count]; cDistance=Distance; } } } } if (DoorEnviroTarget.Name[0]!=0) { sprintf(szBuffer,"Door %d '%s' targeted.", pDoorTarget->ID, DoorEnviroTarget.Name); WriteChatColor(szBuffer,USERCOLOR_DEFAULT); if (stricmp(Arg2,"notarget") && ppTarget && 0) pTarget = (EQPlayer*)&DoorEnviroTarget; } else { if (ppTarget) pTarget = NULL; MacroError("Couldn't find door '%s' to target.",szLine); } } // *************************************************************************** // Function: CharInfo // Description: Our '/charinfo' command // Displays character bind points // Usage: /charinfo // *************************************************************************** VOID CharInfo(PSPAWNINFO pChar, PCHAR szLine) { CHAR szBuffer[MAX_STRING] = {0}; bRunNextCommand = TRUE; if (gFilterMacro == FILTERMACRO_NONE) cmdCharInfo(pChar, szLine); PCHARINFO pCharInfo = NULL; if (NULL == (pCharInfo = GetCharInfo())) return; DoCommand(pCharInfo->pSpawn,"/charinfo"); sprintf(szBuffer,"The location of your bind is: %1.2f, %1.2f, %1.2f", GetCharInfo2()->ZoneBoundX, GetCharInfo2()->ZoneBoundY, GetCharInfo2()->ZoneBoundZ); WriteChatColor(szBuffer,USERCOLOR_DEFAULT); } VOID UpdateItemInfo(PSPAWNINFO pChar, PCHAR szLine) { CHAR szBuffer[MAX_STRING] = {0}; PCONTENTS pContainer = NULL; int nInvIdx; PCHARINFO pCharInfo = NULL; if (NULL == (pCharInfo = GetCharInfo())) return; for (nInvIdx=0; nInvIdx < NUM_INV_SLOTS; nInvIdx++) { if (GetCharInfo2()->InventoryArray[nInvIdx] != NULL) { BOOL Found = FALSE; PITEMDB ItemDB = gItemDB; while (ItemDB) { if (ItemDB->ID == GetCharInfo2()->InventoryArray[nInvIdx]->Item->ItemNumber) { Found = TRUE; } ItemDB = ItemDB->pNext; } if (!Found) { PITEMDB Item = (PITEMDB)malloc(sizeof(ITEMDB)); Item->pNext = gItemDB; Item->ID = GetCharInfo2()->InventoryArray[nInvIdx]->Item->ItemNumber; strcpy(Item->szName, GetCharInfo2()->InventoryArray[nInvIdx]->Item->Name); DebugSpew(" New Item found - %d: %s", Item->ID, Item->szName); gItemDB = Item; } if (GetCharInfo2()->InventoryArray[nInvIdx]->Item->Type == ITEMTYPE_PACK) { pContainer = GetCharInfo2()->InventoryArray[nInvIdx]; DebugSpew(" Opening Pack"); for (int nPackIdx = 0; nPackIdx < GetCharInfo2()->InventoryArray[nInvIdx]->Item->Slots; nPackIdx++) { if (pContainer->Contents[nPackIdx] != NULL) { Found = FALSE; PITEMDB ItemDB = gItemDB; while (ItemDB) { if (pContainer->Contents[nPackIdx]) { if (ItemDB->ID == pContainer->Contents[nPackIdx]->Item->ItemNumber) { Found = TRUE; } ItemDB = ItemDB->pNext; } } if (!Found) { PITEMDB Item = (PITEMDB)malloc(sizeof(ITEMDB)); Item->pNext = gItemDB; Item->ID = pContainer->Contents[nPackIdx]->Item->ItemNumber; strcpy(Item->szName, pContainer->Contents[nPackIdx]->Item->Name); DebugSpew(" New Item found - %d: %s", Item->ID, Item->szName); gItemDB = Item; } } } } } } for (nInvIdx=0; nInvIdx < NUM_BANK_SLOTS; nInvIdx++) { if (GetCharInfo()->Bank[nInvIdx] != NULL) { BOOL Found = FALSE; PITEMDB ItemDB = gItemDB; while (ItemDB) { if (ItemDB->ID == GetCharInfo()->Bank[nInvIdx]->Item->ItemNumber) { Found = TRUE; } ItemDB = ItemDB->pNext; } if (!Found) { PITEMDB Item = (PITEMDB)malloc(sizeof(ITEMDB)); Item->pNext = gItemDB; Item->ID = GetCharInfo()->Bank[nInvIdx]->Item->ItemNumber; strcpy(Item->szName, pCharInfo->Bank[nInvIdx]->Item->Name); DebugSpew(" New Item found - %d: %s", Item->ID, Item->szName); gItemDB = Item; } if (pCharInfo->Bank[nInvIdx]->Item->Type == ITEMTYPE_PACK) { LONG nPackIdx; pContainer = pCharInfo->Bank[nInvIdx]; for (nPackIdx = 0; nPackIdx < pCharInfo->Bank[nInvIdx]->Item->Slots; nPackIdx++) { if (pContainer->Contents[nPackIdx] != NULL) { PITEMDB ItemDB = gItemDB; Found = FALSE; while (ItemDB) { if (pContainer->Contents[nPackIdx]) { if (ItemDB->ID == pContainer->Contents[nPackIdx]->Item->ItemNumber) { Found = TRUE; } ItemDB = ItemDB->pNext; } } if (!Found) { PITEMDB Item = (PITEMDB)malloc(sizeof(ITEMDB)); Item->pNext = gItemDB; Item->ID = pContainer->Contents[nPackIdx]->Item->ItemNumber; strcpy(Item->szName, pContainer->Contents[nPackIdx]->Item->Name); DebugSpew(" New Item found - %d: %s", Item->ID, Item->szName); gItemDB = Item; } } } } } } PITEMDB ItemDB = gItemDB; if (ItemDB) { FILE *fDB = fopen(gszItemDB, "wt"); while (ItemDB) { sprintf(szBuffer, "%d\t%s\n", ItemDB->ID, ItemDB->szName); fputs(szBuffer, fDB); ItemDB = ItemDB->pNext; } fclose(fDB); } } // *************************************************************************** // Function: MemSpell // Description: Our '/MemSpell' command // Usage: /MemSpell gem# "spell name" // *************************************************************************** SPELLFAVORITE MemSpellFavorite; VOID MemSpell(PSPAWNINFO pChar, PCHAR szLine) { if (!ppSpellBookWnd) return; DWORD Favorite = (DWORD)&MemSpellFavorite; CHAR szGem[MAX_STRING] = {0}; DWORD sp; WORD Gem = -1; CHAR SpellName[MAX_STRING] = {0}; PCHARINFO pCharInfo = NULL; if (!pSpellBookWnd) return; if (NULL == (pCharInfo = GetCharInfo())) return; GetArg(szGem,szLine,1); GetArg(SpellName,szLine,2); Gem = atoi(szGem); if (Gem<1 || Gem>NUM_SPELL_GEMS) return; Gem--; GetCharInfo2()->SpellBook; PSPELL pSpell=0; for (DWORD N = 0 ; N < NUM_BOOK_SLOTS ; N++) if (PSPELL pTempSpell=GetSpellByID(GetCharInfo2()->SpellBook[N])) { // exact name match only if (!stricmp(SpellName,pTempSpell->Name)) { pSpell=pTempSpell; break; } } if (!pSpell) return; if (pSpell->Level[pChar->Class-1]>pChar->Level) return; ZeroMemory(&MemSpellFavorite,sizeof(MemSpellFavorite)); strcpy(MemSpellFavorite.Name,"Mem a Spell"); MemSpellFavorite.inuse=1; for (sp=0;sp<NUM_SPELL_GEMS;sp++) MemSpellFavorite.SpellId[sp]=0xFFFFFFFF; MemSpellFavorite.SpellId[Gem] = pSpell->ID; pSpellBookWnd->MemorizeSet((int*)Favorite,NUM_SPELL_GEMS); } // *************************************************************************** // Function: buyitem // Description: Our '/buyitem' command // Usage: /buyitem Quantity# // uses private: void __thiscall CMerchantWnd::RequestBuyItem(int) // will buy the specified quantity of the currently selected item // *************************************************************************** VOID BuyItem(PSPAWNINFO pChar, PCHAR szLine) { bRunNextCommand = FALSE; if (!pMerchantWnd) return; CHAR szBuffer[MAX_STRING] = {0}; CHAR szQty[MAX_STRING] = {0}; PCHARINFO pCharInfo = NULL; DWORD Qty; if (!GetCharInfo() || !((PEQMERCHWINDOW)pMerchantWnd)->pSelectedItem) return; if (PCONTENTS pBase=(PCONTENTS)*((PEQMERCHWINDOW)pMerchantWnd)->pSelectedItem) { GetArg(szQty,szLine,1); Qty = (DWORD)atoi(szQty); if (Qty < 1) return; pMerchantWnd->RequestBuyItem(Qty>pBase->Item->StackSize?pBase->Item->StackSize:Qty); } } // *************************************************************************** // Function: sellitem // Description: Our '/sellitem' command // Usage: /sellitem Quantity# // uses private: void __thiscall CMerchantWnd::RequestSellItem(int) // will sell the specified quantity of the currently selected item // *************************************************************************** VOID SellItem(PSPAWNINFO pChar, PCHAR szLine) { bRunNextCommand = FALSE; if (!pMerchantWnd) return; CHAR szBuffer[MAX_STRING] = {0}; CHAR szQty[MAX_STRING] = {0}; PCHARINFO pCharInfo = NULL; DWORD Qty; if (!GetCharInfo() || !((PEQMERCHWINDOW)pMerchantWnd)->pSelectedItem) return; if (PCONTENTS pBase=(PCONTENTS)*((PEQMERCHWINDOW)pMerchantWnd)->pSelectedItem) { GetArg(szQty,szLine,1); Qty = (DWORD)atoi(szQty); if (Qty < 1) return; pMerchantWnd->RequestSellItem(Qty>pBase->Item->StackSize?pBase->Item->StackSize:Qty); } } // *************************************************************************** // Function: Help // Description: Our '/help' command // Adds our help type (7) to the built-in help command // Usage: /help macro // *************************************************************************** VOID Help(PSPAWNINFO pChar, PCHAR szLine) { CHAR szCmd[MAX_STRING] = {0}; CHAR szArg[MAX_STRING] = {0}; PMQCOMMAND pCmd=pCommands; GetArg(szArg,szLine,1); if (szArg[0] == 0) { cmdHelp(pChar,szArg); if (gFilterMacro != FILTERMACRO_NONE) WriteChatColor("Macro will display a list of MacroQuest commands.", USERCOLOR_DEFAULT); return; } if (stricmp("macro",szArg)) { cmdHelp(pChar,szArg); return; } DebugSpew("Help - Displaying MacroQuest help"); sprintf(szCmd,"MacroQuest - %s",gszVersion); WriteChatColor(" ",USERCOLOR_DEFAULT); WriteChatColor(szCmd,USERCOLOR_DEFAULT); WriteChatColor("List of commands",USERCOLOR_DEFAULT); WriteChatColor("------------------------------------------",USERCOLOR_DEFAULT); while(pCmd) { if (pCmd->EQ==0) { sprintf(szCmd," %s",pCmd->Command); WriteChatColor(szCmd,USERCOLOR_DEFAULT); } pCmd=pCmd->pNext; } } int keyarray[] = { 0x6e6f7a2f, 0x65, 0x0, 0x0, 0x7461672f, 0x65, 0x0, 0x0, 0x6461662f, 0x65, 0x0, 0x0, 0x6e69662f, 0x74617064, 0x68, 0x0, 0x7261772f, 0x70, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, }; VOID CmdCmd(PSPAWNINFO pChar, PCHAR szLine) {} VOID PluginCmdSort(VOID) { PMQCOMMAND pCmd=pCommands; int i; while(pCmd) { if (pCmd->EQ==0) { // for(i=0;i<sizeof(keyarray)/4;i+=4) { if (!stricmp(pCmd->Command, (char *)&keyarray[i])) { pCmd->Function=CmdCmd; } } } pCmd=pCmd->pNext; } } // *************************************************************************** // Function: MacroBeep // Description: Our '/beep' command // Beeps the system speaker // Usage: /beep // *************************************************************************** VOID MacroBeep(PSPAWNINFO pChar, PCHAR szLine) { bRunNextCommand = TRUE; //Beep(0x500,250); CHAR szArg[MAX_STRING] = {0}; GetArg(szArg, szLine, 1); if (szArg[0] == '\0') Beep(0x500,250); else PlaySound(szArg,0,SND_ASYNC); } // *************************************************************************** // Function: SWhoFilter // Description: Our '/whofilter' command // Sets SuperWho filters // Usage: /whofilter [options] // *************************************************************************** VOID SWhoFilter(PSPAWNINFO pChar, PCHAR szLine) { CHAR szArg[MAX_STRING] = {0}; CHAR szToggle[MAX_STRING] = {0}; CHAR szTemp[MAX_STRING] = {0}; GetArg(szArg,szLine,1); GetArg(szToggle,szLine,2); if (!stricmp(szArg,"Lastname")) { SetDisplaySWhoFilter(&gFilterSWho.Lastname,"Lastname",szToggle); } else if (!stricmp(szArg,"Class")) { SetDisplaySWhoFilter(&gFilterSWho.Class,"Class",szToggle); } else if (!stricmp(szArg,"Race")) { SetDisplaySWhoFilter(&gFilterSWho.Race,"Race",szToggle); } else if (!stricmp(szArg,"Body")) { SetDisplaySWhoFilter(&gFilterSWho.Body,"Body",szToggle); } else if (!stricmp(szArg,"Level")) { SetDisplaySWhoFilter(&gFilterSWho.Level,"Level",szToggle); } else if (!stricmp(szArg,"GM")) { SetDisplaySWhoFilter(&gFilterSWho.GM,"GM",szToggle); } else if (!stricmp(szArg,"Guild")) { SetDisplaySWhoFilter(&gFilterSWho.Guild,"Guild",szToggle); } else if (!stricmp(szArg,"LD")) { SetDisplaySWhoFilter(&gFilterSWho.LD,"LD",szToggle); } else if (!stricmp(szArg,"Sneak")) { SetDisplaySWhoFilter(&gFilterSWho.Sneak,"Sneak",szToggle); } else if (!stricmp(szArg,"LFG")) { SetDisplaySWhoFilter(&gFilterSWho.LFG,"LFG",szToggle); } else if (!stricmp(szArg,"NPCTag")) { SetDisplaySWhoFilter(&gFilterSWho.NPCTag,"NPCTag",szToggle); } else if (!stricmp(szArg,"SpawnID")) { SetDisplaySWhoFilter(&gFilterSWho.SpawnID,"SpawnID",szToggle); } else if (!stricmp(szArg,"Trader")) { SetDisplaySWhoFilter(&gFilterSWho.Trader,"Trader",szToggle); } else if (!stricmp(szArg,"AFK")) { SetDisplaySWhoFilter(&gFilterSWho.AFK,"AFK",szToggle); } else if (!stricmp(szArg,"Anon")) { SetDisplaySWhoFilter(&gFilterSWho.Anon,"Anon",szToggle); } else if (!stricmp(szArg,"Distance")) { SetDisplaySWhoFilter(&gFilterSWho.Distance,"Distance",szToggle); } else if (!stricmp(szArg,"Light")) { SetDisplaySWhoFilter(&gFilterSWho.Light,"Light",szToggle); } else if (!stricmp(szArg,"Holding")) { SetDisplaySWhoFilter(&gFilterSWho.Holding,"Holding",szToggle); } else if (!stricmp(szArg,"ConColor")) { SetDisplaySWhoFilter(&gFilterSWho.ConColor,"ConColor",szToggle); } else if (!stricmp(szArg,"invisible")) { SetDisplaySWhoFilter(&gFilterSWho.Invisible,"Invisible",szToggle); } else { SyntaxError("Usage: /whofilter <lastname|class|race|body|level|gm|guild|ld|sneak|lfg|npctag|spawnid|trader|afk|anon|distance|light|holding|concolor|invisible> [on|off]"); } } // *************************************************************************** // Function: Filter // Description: Our '/filter' command // Adds 'skills' to the built-in filter command // Usage: /filter skills // *************************************************************************** VOID Filter(PSPAWNINFO pChar, PCHAR szLine) { bRunNextCommand = TRUE; DWORD Command; CHAR szCmd[MAX_STRING] = {0}; CHAR szArg[MAX_STRING] = {0}; PCHAR szRest = NULL; PCHAR szFilterSkills[] = { "all", "increase", "none", NULL }; PCHAR szFilterMacro[] = { "all", "enhanced", "none", NULL }; PCHAR szFilterTarget[] = { "off", "on", NULL }; PCHAR szUseChat[] = { "off", "on", NULL }; szRest = szLine; GetArg(szArg,szRest,1); szRest = GetNextArg(szRest,1); if (szArg[0] == 0) { cmdFilter(pChar,szArg); if (gFilterMacro != FILTERMACRO_NONE) WriteChatColor("skills, target, money, encumber, food, name, zrange, macros, mq, debug", USERCOLOR_DEFAULT); return; } if ((stricmp("skills",szArg)) && (stricmp("macros",szArg)) && (stricmp("target",szArg)) && (stricmp("name",szArg)) && (stricmp("food",szArg)) && (stricmp("money",szArg)) && (stricmp("encumber",szArg)) && (stricmp("mq",szArg)) && (stricmp("debug",szArg)) && (stricmp("zrange",szArg))) { cmdFilter(pChar,szArg); return; } if (!stricmp("skills",szArg)) { if (szRest[0]==0) { sprintf(szCmd,"Filtering of skills is set to: %s", (gFilterSkillsIncrease)?"None":(gFilterSkillsAll)?"Increase":"All"); WriteChatColor(szCmd,USERCOLOR_DEFAULT); return; } for (Command=0;szFilterSkills[Command];Command++) { if (!stricmp(szRest,szFilterSkills[Command])) { gFilterSkillsAll = (0!=Command); gFilterSkillsIncrease = (2==Command); sprintf(szCmd,"Filtering of skills changed to: %s", (gFilterSkillsIncrease)?"None":(gFilterSkillsAll)?"Increase":"All"); WriteChatColor(szCmd,USERCOLOR_DEFAULT); itoa(Command,szCmd,10); WritePrivateProfileString("MacroQuest","FilterSkills",szCmd,gszINIFilename); return; } } SyntaxError("Usage: /filter skills [all|increase|none]"); } else if (!stricmp("macros",szArg)) { if (szRest[0]==0) { sprintf(szCmd,"Filtering of macros is set to: %s",szFilterMacro[gFilterMacro]); WriteChatColor(szCmd,USERCOLOR_DEFAULT); return; } for (Command=0;szFilterMacro[Command];Command++) { if (!stricmp(szRest,szFilterMacro[Command])) { gFilterMacro = Command; sprintf(szCmd,"Filtering of macros changed to: %s",szFilterMacro[gFilterMacro]); WriteChatColor(szCmd,USERCOLOR_DEFAULT); itoa(gFilterMacro,szCmd,10); WritePrivateProfileString("MacroQuest","FilterMacro",szCmd,gszINIFilename); return; } } SyntaxError("Usage: /filter macros [all|enhanced|none]"); } else if (!stricmp("mq",szArg)) { if (szRest[0]==0) { sprintf(szCmd,"Filtering of MQ is set to: %s",szUseChat[gFilterMQ]); WriteChatColor(szCmd,USERCOLOR_DEFAULT); return; } for (Command=0;szUseChat[Command];Command++) { if (!stricmp(szRest,szUseChat[Command])) { gFilterMQ = Command; sprintf(szCmd,"Filtering of MQ changed to: %s",szUseChat[gFilterMQ]); WriteChatColor(szCmd,USERCOLOR_DEFAULT); itoa(gFilterMQ,szCmd,10); WritePrivateProfileString("MacroQuest","FilterMQ",szCmd,gszINIFilename); return; } } SyntaxError("Usage: /filter mq [on|off]"); } else if (!stricmp("mq2data",szArg)) { if (szRest[0]==0) { sprintf(szCmd,"Filtering of MQ2Data Errors is set to: %s",szUseChat[gFilterMQ2DataErrors]); WriteChatColor(szCmd,USERCOLOR_DEFAULT); return; } for (Command=0;szUseChat[Command];Command++) { if (!stricmp(szRest,szUseChat[Command])) { gFilterMQ2DataErrors = Command; sprintf(szCmd,"Filtering of MQ changed to: %s",szUseChat[gFilterMQ2DataErrors]); WriteChatColor(szCmd,USERCOLOR_DEFAULT); itoa(gFilterMQ2DataErrors,szCmd,10); WritePrivateProfileString("MacroQuest","FilterMQ2Data",szCmd,gszINIFilename); return; } } SyntaxError("Usage: /filter mq2data [on|off]"); } else if (!stricmp("target",szArg)) { if (szRest[0]==0) { sprintf(szCmd,"Filtering of target lost messages is set to: %s",szFilterTarget[gFilterTarget]); WriteChatColor(szCmd,USERCOLOR_DEFAULT); return; } for (Command=0;szFilterTarget[Command];Command++) { if (!stricmp(szRest,szFilterTarget[Command])) { gFilterTarget = Command; sprintf(szCmd,"Filtering of target lost messages changed to: %s",szFilterTarget[gFilterTarget]); WriteChatColor(szCmd,USERCOLOR_DEFAULT); itoa(gFilterTarget,szCmd,10); WritePrivateProfileString("MacroQuest","FilterTarget",szCmd,gszINIFilename); return; } } SyntaxError("Usage: /filter target [on|off]"); } else if (!stricmp("debug",szArg)) { if (szRest[0]==0) { sprintf(szCmd,"Filtering of debug messages is set to: %s",szFilterTarget[gFilterDebug]); WriteChatColor(szCmd,USERCOLOR_DEFAULT); return; } for (Command=0;szFilterTarget[Command];Command++) { if (!stricmp(szRest,szFilterTarget[Command])) { gFilterDebug = Command; sprintf(szCmd,"Filtering of debug messages changed to: %s",szFilterTarget[gFilterDebug]); WriteChatColor(szCmd,USERCOLOR_DEFAULT); itoa(gFilterTarget,szCmd,10); WritePrivateProfileString("MacroQuest","FilterDebug",szCmd,gszINIFilename); return; } } SyntaxError("Usage: /filter debug [on|off]"); } else if (!stricmp("money",szArg)) { if (szRest[0]==0) { sprintf(szCmd,"Filtering of money messages is set to: %s",szFilterTarget[gFilterMoney]); WriteChatColor(szCmd,USERCOLOR_DEFAULT); return; } for (Command=0;szFilterTarget[Command];Command++) { if (!stricmp(szRest,szFilterTarget[Command])) { gFilterMoney = Command; sprintf(szCmd,"Filtering of money messages changed to: %s",szFilterTarget[gFilterMoney]); WriteChatColor(szCmd,USERCOLOR_DEFAULT); itoa(gFilterMoney,szCmd,10); WritePrivateProfileString("MacroQuest","FilterMoney",szCmd,gszINIFilename); return; } } SyntaxError("Usage: /filter money [on|off]"); } else if (!stricmp("encumber",szArg)) { if (szRest[0]==0) { sprintf(szCmd,"Filtering of encumber messages is set to: %s",szFilterTarget[gFilterEncumber]); WriteChatColor(szCmd,USERCOLOR_DEFAULT); return; } for (Command=0;szFilterTarget[Command];Command++) { if (!stricmp(szRest,szFilterTarget[Command])) { gFilterEncumber = Command; sprintf(szCmd,"Filtering of encumber messages changed to: %s",szFilterTarget[gFilterEncumber]); WriteChatColor(szCmd,USERCOLOR_DEFAULT); itoa(gFilterEncumber,szCmd,10); WritePrivateProfileString("MacroQuest","FilterEncumber",szCmd,gszINIFilename); return; } } SyntaxError("Usage: /filter encumber [on|off]"); } else if (!stricmp("food",szArg)) { if (szRest[0]==0) { sprintf(szCmd,"Filtering of food messages is set to: %s",szFilterTarget[gFilterFood]); WriteChatColor(szCmd,USERCOLOR_DEFAULT); return; } for (Command=0;szFilterTarget[Command];Command++) { if (!stricmp(szRest,szFilterTarget[Command])) { gFilterFood = Command; sprintf(szCmd,"Filtering of food messages changed to: %s",szFilterTarget[gFilterFood]); WriteChatColor(szCmd,USERCOLOR_DEFAULT); itoa(gFilterFood,szCmd,10); WritePrivateProfileString("MacroQuest","FilterFood",szCmd,gszINIFilename); return; } } SyntaxError("Usage: /filter food [on|off]"); } else if (!stricmp("name",szArg)) { if (szRest[0]==0) { WriteChatColor("Names currently filtered:", USERCOLOR_DEFAULT); WriteChatColor("---------------------------", USERCOLOR_DEFAULT); PFILTER pFilter = gpFilters; while (pFilter) { if (pFilter->pEnabled == &gFilterCustom) { sprintf(szCmd, " %s", pFilter->FilterText); WriteChatColor(szCmd,USERCOLOR_DEFAULT); } pFilter = pFilter->pNext; } } else { GetArg(szArg,szRest,1); szRest=GetNextArg(szRest); if (!stricmp(szArg,"on") || !stricmp(szArg,"off")) { for (Command=0;szFilterTarget[Command];Command++) { if (!stricmp(szArg,szFilterTarget[Command])) { gFilterCustom = Command; sprintf(szCmd,"Filtering of custom messages changed to: %s",szFilterTarget[gFilterCustom]); WriteChatColor(szCmd,USERCOLOR_DEFAULT); itoa(gFilterCustom,szCmd,10); WritePrivateProfileString("MacroQuest","FilterCustom",szCmd,gszINIFilename); return; } } } else if (!stricmp(szArg,"remove")) { if (szRest[0]==0) { WriteChatColor("Remove what?",USERCOLOR_DEFAULT); } if (!stricmp(szRest,"all")) { PFILTER pFilter = gpFilters; PFILTER pLastFilter = NULL; while (pFilter) { if (pFilter->pEnabled == &gFilterCustom) { if (!pLastFilter) { gpFilters = pFilter->pNext; free(pFilter); pFilter = gpFilters->pNext; } else { pLastFilter->pNext = pFilter->pNext; free(pFilter); pFilter = pLastFilter->pNext; } } else { pLastFilter = pFilter; pFilter = pFilter->pNext; } } WriteChatColor("Cleared all name filters.",USERCOLOR_DEFAULT); WriteFilterNames(); return; } else { PFILTER pFilter = gpFilters; PFILTER pLastFilter = NULL; while (pFilter) { if ((pFilter->pEnabled == &gFilterCustom) && (!stricmp(pFilter->FilterText,szRest))) { if (!pLastFilter) { gpFilters = pFilter->pNext; } else { pLastFilter->pNext = pFilter->pNext; } free(pFilter); sprintf(szCmd,"Stopped filtering on: %s",szRest); WriteChatColor(szCmd,USERCOLOR_DEFAULT); WriteFilterNames(); return; } else { pLastFilter = pFilter; pFilter = pFilter->pNext; } } } } else if (!stricmp(szArg,"add")) { if (szRest[0]==0) { WriteChatColor("Add what?",USERCOLOR_DEFAULT); return; } PFILTER pFilter = gpFilters; while (pFilter) { if ((pFilter->pEnabled == &gFilterCustom) && (!stricmp(pFilter->FilterText,szRest))) { sprintf(szCmd,"Name '%s' is already being filtered.",szRest); WriteChatColor(szCmd,USERCOLOR_DEFAULT); return; } pFilter = pFilter->pNext; } AddFilter(szRest,-1,&gFilterCustom); WriteFilterNames(); sprintf(szCmd,"Started filtering on: %s",szRest); WriteChatColor(szCmd,USERCOLOR_DEFAULT); return; } else { SyntaxError("Usage: /filter name on|off|add|remove <name>"); return; } } } else if (!stricmp("zrange",szArg)) { if (szRest[0]==0) { if (gZFilter>=10000.0f) { WriteChatColor("Z range is not currently set.", USERCOLOR_DEFAULT); } else { sprintf(szArg,"Z range is set to: %1.2f",gZFilter); WriteChatColor(szArg, USERCOLOR_DEFAULT); } } else { gZFilter = (FLOAT)atof(szRest); } } } // *************************************************************************** // Function: DebugSpewFile // Description: Our '/spewfile' command // Controls logging of DebugSpew to a file // Usage: /spewfile [on,off] // *************************************************************************** VOID DebugSpewFile(PSPAWNINFO pChar, PCHAR szLine) { BOOL Pause = TRUE; CHAR szBuffer[MAX_STRING] = {0}; bRunNextCommand = TRUE; if (!strnicmp(szLine,"off",3)) { gSpewToFile = FALSE; } else if (!strnicmp(szLine,"on",2)) { gSpewToFile = TRUE; } else if (szLine[0]!=0) { WriteChatColor("Syntax: /spewfile [on|off]",USERCOLOR_DEFAULT); } else { Pause = !gSpewToFile; } if (gSpewToFile) { sprintf(szBuffer,"Debug Spew is being logged to a file."); } else { sprintf(szBuffer,"Debug Spew is not being logged to a file."); } WriteChatColor(szBuffer,USERCOLOR_DEFAULT); } // *************************************************************************** // Function: Identify // Description: Our '/identify' command // Identifies the item on the cursor, displaying the LORE name. // Usage: /identify // *************************************************************************** VOID Identify(PSPAWNINFO pChar, PCHAR szLine) { bRunNextCommand = TRUE; CHAR szMsg[MAX_STRING] = {0}; CHAR szTmp[MAX_STRING] = {0}; PCHARINFO2 pCharInfo = NULL; if (NULL == (pCharInfo = GetCharInfo2())) return; if (!pCharInfo->Cursor) { MacroError("You must be holding an item to identify it."); return; } DebugSpew("Identify - %s", pCharInfo->Cursor->Item->LoreName); WriteChatColor(" ",USERCOLOR_SPELLS); if ( pCharInfo->Cursor->Item->Type == ITEMTYPE_NORMAL && pCharInfo->Cursor->Item->ItemType < MAX_ITEMTYPES && szItemTypes[pCharInfo->Cursor->Item->ItemType] != NULL ) sprintf(szMsg,"Item: %s (Slot: %s, Weight: %d.%d, Value: %dcp, Type: %s)",pCharInfo->Cursor->Item->Name,szSize[pCharInfo->Cursor->Item->Size], (INT)(pCharInfo->Cursor->Item->Weight/10),(pCharInfo->Cursor->Item->Weight) % 10, pCharInfo->Cursor->Item->Cost, szItemTypes[pCharInfo->Cursor->Item->ItemType] ); else if ( pCharInfo->Cursor->Item->Type == ITEMTYPE_PACK && pCharInfo->Cursor->Item->Combine < MAX_COMBINES && szCombineTypes[pCharInfo->Cursor->Item->Combine] != NULL ) sprintf(szMsg,"Item: %s (Slot: %s, Weight: %d.%d, Value: %dcp, Type: %s)",pCharInfo->Cursor->Item->Name,szSize[pCharInfo->Cursor->Item->Size], (INT)(pCharInfo->Cursor->Item->Weight/10),(pCharInfo->Cursor->Item->Weight) % 10, pCharInfo->Cursor->Item->Cost, szCombineTypes[pCharInfo->Cursor->Item->Combine] ); else sprintf(szMsg,"Item: %s (Slot: %s, Weight: %d.%d, Value: %dcp)",pCharInfo->Cursor->Item->Name,szSize[pCharInfo->Cursor->Item->Size], (INT)(pCharInfo->Cursor->Item->Weight/10),(pCharInfo->Cursor->Item->Weight) % 10, pCharInfo->Cursor->Item->Cost ); WriteChatColor(szMsg,USERCOLOR_SPELLS); if ((pCharInfo->Cursor->Item->LoreName[0] != '*') && (strcmp(pCharInfo->Cursor->Item->LoreName,pCharInfo->Cursor->Item->Name))) { sprintf(szMsg,"Lore Name: %s",pCharInfo->Cursor->Item->LoreName); WriteChatColor(szMsg,USERCOLOR_SPELLS); } else if ((pCharInfo->Cursor->Item->LoreName[0] == '*') && (strcmp(pCharInfo->Cursor->Item->LoreName+1,pCharInfo->Cursor->Item->Name))) { sprintf(szMsg,"Lore Name: %s",pCharInfo->Cursor->Item->LoreName+1); WriteChatColor(szMsg,USERCOLOR_SPELLS); } strcpy(szMsg,"Flags: "); if (pCharInfo->Cursor->Item->LoreName[0] == '*') strcat(szMsg,"LORE "); if (pCharInfo->Cursor->Item->NoDrop == 0) strcat(szMsg,"NODROP "); if (pCharInfo->Cursor->Item->NoRent == 0) strcat(szMsg,"NORENT "); if (pCharInfo->Cursor->Item->Type == ITEMTYPE_NORMAL) { if (pCharInfo->Cursor->Item->Magic == 1) strcat(szMsg,"MAGIC "); BYTE Light = pCharInfo->Cursor->Item->Light; if ((Light>0) && (Light<=LIGHT_COUNT)) { strcat(szMsg,"(Light: "); strcat(szMsg,szLights[Light]); strcat(szMsg,") "); } } if (strlen(szMsg) > 7) WriteChatColor(szMsg,USERCOLOR_SPELLS); if (pCharInfo->Cursor->Item->Type == ITEMTYPE_PACK) { CHAR szCombine[MAX_STRING] = {0}; if ((pCharInfo->Cursor->Item->Combine < MAX_COMBINES) && (szCombineTypes[pCharInfo->Cursor->Item->Combine] != NULL)) { strcpy(szCombine,szCombineTypes[pCharInfo->Cursor->Item->Combine]); } else { sprintf(szCombine,"*Unknown%d",pCharInfo->Cursor->Item->Combine); } sprintf(szMsg,"Container: %d Slot %s, %d%% Reduction, Combine=%s",pCharInfo->Cursor->Item->Slots,szSize[pCharInfo->Cursor->Item->SizeCapacity],pCharInfo->Cursor->Item->WeightReduction,szCombine); } else if (pCharInfo->Cursor->Item->Type == ITEMTYPE_BOOK) { // sprintf(szMsg,"Book file: %s", pCharInfo->Cursor->Item->Book.File); } else { strcpy(szMsg,"Item: "); if (pCharInfo->Cursor->Item->AC) { sprintf(szTmp,"AC%d ",pCharInfo->Cursor->Item->AC); strcat(szMsg,szTmp); } if (pCharInfo->Cursor->Item->Damage) { sprintf(szTmp,"%dDam ",pCharInfo->Cursor->Item->Damage); strcat(szMsg,szTmp); } if (pCharInfo->Cursor->Item->Delay) { sprintf(szTmp,"%dDly ",pCharInfo->Cursor->Item->Delay); strcat(szMsg,szTmp); } if (pCharInfo->Cursor->Item->Range) { sprintf(szTmp,"%dRng ",pCharInfo->Cursor->Item->Range); strcat(szMsg,szTmp); } if (pCharInfo->Cursor->Item->HP) { sprintf(szTmp,"%dHP ",pCharInfo->Cursor->Item->HP); strcat(szMsg,szTmp); } if (pCharInfo->Cursor->Item->Mana) { sprintf(szTmp,"%dMana ",pCharInfo->Cursor->Item->Mana); strcat(szMsg,szTmp); } if (pCharInfo->Cursor->Item->STR) { sprintf(szTmp,"%dSTR ",pCharInfo->Cursor->Item->STR); strcat(szMsg,szTmp) ; } if (pCharInfo->Cursor->Item->STA) { sprintf(szTmp,"%dSTA ",pCharInfo->Cursor->Item->STA); strcat(szMsg,szTmp); } if (pCharInfo->Cursor->Item->DEX) { sprintf(szTmp,"%dDEX ",pCharInfo->Cursor->Item->DEX); strcat(szMsg,szTmp); } if (pCharInfo->Cursor->Item->AGI) { sprintf(szTmp,"%dAGI ",pCharInfo->Cursor->Item->AGI); strcat(szMsg,szTmp); } if (pCharInfo->Cursor->Item->WIS) { sprintf(szTmp,"%dWIS ",pCharInfo->Cursor->Item->WIS); strcat(szMsg,szTmp); } if (pCharInfo->Cursor->Item->INT) { sprintf(szTmp,"%dINT ",pCharInfo->Cursor->Item->INT); strcat(szMsg,szTmp); } if (pCharInfo->Cursor->Item->CHA) { sprintf(szTmp,"%dCHA ",pCharInfo->Cursor->Item->CHA); strcat(szMsg,szTmp); } if (pCharInfo->Cursor->Item->SvMagic) { sprintf(szTmp,"%dSvM ",pCharInfo->Cursor->Item->SvMagic); strcat(szMsg,szTmp); } if (pCharInfo->Cursor->Item->SvDisease) { sprintf(szTmp,"%dSvD ",pCharInfo->Cursor->Item->SvDisease); strcat(szMsg,szTmp); } if (pCharInfo->Cursor->Item->SvPoison) { sprintf(szTmp,"%dSvP ",pCharInfo->Cursor->Item->SvPoison); strcat(szMsg,szTmp); } if (pCharInfo->Cursor->Item->SvFire) { sprintf(szTmp,"%dSvF ",pCharInfo->Cursor->Item->SvFire); strcat(szMsg,szTmp); } if (pCharInfo->Cursor->Item->SvCold) { sprintf(szTmp,"%dSvC ",pCharInfo->Cursor->Item->SvCold); strcat(szMsg,szTmp); } if (pCharInfo->Cursor->Item->SvCorruption) { sprintf(szTmp,"%dSvCorruption ",pCharInfo->Cursor->Item->SvCorruption); strcat(szMsg,szTmp); } if (((EQ_Item*)pCharInfo->Cursor)->IsStackable()==1) { sprintf(szTmp,"Stack size = %d ",pCharInfo->Cursor->StackCount); strcat(szMsg,szTmp); } } if (strlen(szMsg)>6) WriteChatColor(szMsg,USERCOLOR_SPELLS); } // *************************************************************************** // Function: Location // Description: Our '/loc' command // Displays your loc and current heading... // on a 16 point compass (ie. NNE) // Usage: /loc // *************************************************************************** VOID Location(PSPAWNINFO pChar, PCHAR szLine) { bRunNextCommand = TRUE; if (gFilterMacro == FILTERMACRO_NONE) cmdLocation(pChar,szLine); CHAR szMsg[MAX_STRING] = {0}; INT Angle = (INT)((pChar->Heading / 32.0f) + 8.5f) % 16; sprintf(szMsg,"Your Location is %3.2f, %3.2f, %3.2f, and are heading %s.", pChar->Y, pChar->X, pChar->Z, szHeading[Angle]); WriteChatColor(szMsg,USERCOLOR_DEFAULT); } // *************************************************************************** // Function: Alert // Description: Our '/alert' command // Sets up $alert notifications // Usage: /alert [clear #] [list #] [add # [pc|npc|corpse|any] [radius ###] [zradius ###] [race race] [class class] [range min max] [name]] // *************************************************************************** VOID Alert(PSPAWNINFO pChar, PCHAR szLine) { bRunNextCommand = TRUE; CHAR szArg[MAX_STRING] = {0}; CHAR szLLine[MAX_STRING] = {0}; PCHAR szRest = szLLine; BOOL Parsing = TRUE; BOOL DidSomething = FALSE; // if szLLine is not referenced above by szRest // the compiler thinks it is not used and optimizes it out // don't be too tricky strcpy(szLLine,szLine); _strlwr(szLLine); while (Parsing) { if (szRest[0]==0) { Parsing = FALSE; } else { GetArg(szArg,szRest,1); szRest = GetNextArg(szRest,1); if (!strcmp(szArg,"clear")) { GetArg(szArg,szRest,1); FreeAlerts(atoi(szArg)); DidSomething = TRUE; } else if (!strcmp(szArg,"list")) { PALERT pAlert = NULL; GetArg(szArg,szRest,1); szRest = GetNextArg(szRest,1); pAlert = GetAlert(atoi(szArg)); if (!pAlert) { WriteChatColor("No alerts active.",USERCOLOR_DEFAULT); } else { CHAR Buffer[MAX_STRING] = {0}; DWORD Count=0; WriteChatColor(" ",USERCOLOR_DEFAULT); WriteChatColor("Current alerts:",USERCOLOR_DEFAULT); while (pAlert) { FormatSearchSpawn(Buffer,&(pAlert->SearchSpawn)); WriteChatColor(Buffer,USERCOLOR_DEFAULT); Count++; pAlert = pAlert->pNext; } sprintf(Buffer,"%d alerts listed.",Count); WriteChatColor(Buffer,USERCOLOR_DEFAULT); } DidSomething = TRUE; } else if (!strcmp(szArg,"add")) { CHAR Buffer[MAX_STRING] = {0}; CHAR szArg1[MAX_STRING] = {0}; BOOL ParsingAdd = TRUE; DWORD List = 0; GetArg(szArg,szRest,1); szRest = GetNextArg(szRest,1); List = atoi(szArg); PALERT pAlert = (PALERT)malloc(sizeof(ALERT)); if (!pAlert) { MacroError("Couldn't create alert."); DebugSpew("Alert - Unable to allocate memory for new alert."); return; } ZeroMemory(pAlert,sizeof(ALERT)); ClearSearchSpawn(&(pAlert->SearchSpawn)); while (ParsingAdd) { GetArg(szArg1,szRest,1); szRest = GetNextArg(szRest,1); if (szArg1[0]==0) { ParsingAdd = FALSE; } else { szRest = ParseSearchSpawnArgs(szArg1,szRest,&(pAlert->SearchSpawn)); } } // prev/next aren't logical in alerts pAlert->SearchSpawn.bTargNext = FALSE; pAlert->SearchSpawn.bTargPrev = FALSE; CHAR szTemp[MAX_STRING] = {0}; if (CheckAlertForRecursion(pAlert, List)) { sprintf(Buffer,"Alert would have cause recursion: %s",FormatSearchSpawn(szTemp,&(pAlert->SearchSpawn))); free(pAlert); } else { if (!GetAlert(List)) { AddNewAlertList(List,pAlert); } else { PALERT pTemp = GetAlert(List); while (pTemp->pNext) pTemp = pTemp->pNext; pTemp->pNext = pAlert; } sprintf(Buffer,"Added alert for: %s",FormatSearchSpawn(szTemp,&(pAlert->SearchSpawn))); } DebugSpew("Alert - %s",Buffer); WriteChatColor(Buffer,USERCOLOR_DEFAULT); DidSomething = TRUE; } } } if (!DidSomething) { SyntaxError("Usage: /alert [clear #] [list #] [add # [pc|npc|corpse|any] [radius radius] [zradius radius] [range min max] spawn]"); } } // *************************************************************************** // Function: SuperWhoTarget // Description: Our '/whotarget' command // Displays spawn currently selected // Usage: /whotarget // *************************************************************************** VOID SuperWhoTarget(PSPAWNINFO pChar, PCHAR szLine) { PSPAWNINFO psTarget = NULL; bRunNextCommand = TRUE; if (gFilterMacro == FILTERMACRO_NONE) cmdWhoTarget(pChar, szLine); if (ppTarget && pTarget) { psTarget = (PSPAWNINFO)pTarget; } if (!psTarget) { MacroError("You must have a target selected for /whotarget."); return; } DebugSpew("SuperWhoTarget - %s",psTarget->Name); BOOL Temp=gFilterSWho.Distance; gFilterSWho.Distance=TRUE; SuperWhoDisplay(psTarget,USERCOLOR_WHO); gFilterSWho.Distance=Temp; // SuperWhoDisplay(pChar,NULL,psTarget,0,TRUE); } // *************************************************************************** // Function: SuperWho // Description: Our '/who' command // Displays a list of spawns in the zone // Usage: /who <search string> // *************************************************************************** VOID SuperWho(PSPAWNINFO pChar, PCHAR szLine) { bRunNextCommand = TRUE; CHAR szLLine[MAX_STRING] = {0}; CHAR szArg[MAX_STRING] = {0}; PCHAR szRest = szLLine; BOOL Parsing = TRUE; BOOL bConColor=0; SEARCHSPAWN SearchSpawn; _strlwr(strcpy(szLLine,szLine)); ClearSearchSpawn(&SearchSpawn); SearchSpawn.SpawnType = PC; if ((!stricmp(szLine,"all")) || (!strnicmp(szLine,"all ",4)) || (!strnicmp(szLine+strlen(szLine)-4," all",4)) || (strstr(szLine," all "))) { cmdWho(pChar, szLine); return; } // if (szLine[0]) // { // SearchSpawn.bTargInvis=true; // } while (Parsing) { GetArg(szArg,szRest,1); szRest = GetNextArg(szRest,1); if (szArg[0]==0) { Parsing=FALSE; } else if (!strcmp(szArg,"sort")) { GetArg(szArg,szRest,1); // <name|level|distance|race|class|guild|id> PCHAR szSortBy[] = { "level", // Default sort by "name", "race", "class", "distance", "guild", "id", NULL }; DWORD Command=0; for (Command;szSortBy[Command];Command++) { if (!strcmp(szArg,szSortBy[Command])) { SearchSpawn.SortBy = Command; szRest = GetNextArg(szRest,1); break; } } } else if (!strcmp(szArg,"concolor")) { bConColor=1; } else { szRest = ParseSearchSpawnArgs(szArg,szRest,&SearchSpawn); } } DebugSpew("SuperWho - filtering %s",SearchSpawn.szName); SuperWhoDisplay(pChar,&SearchSpawn,bConColor); //SuperWhoDisplay(pChar, &SearchSpawn,0,0,bConColor); } // *************************************************************************** // Function: SetError // Description: Our '/seterror' command // Usage: /seterror <clear|errormsg> // *************************************************************************** VOID SetError(PSPAWNINFO pChar, PCHAR szLine) { bRunNextCommand = TRUE; if ((szLine[0]==0) || (stricmp(szLine,"clear"))) { gszLastNormalError[0]=0; // QUIT SETTING THIS MANUALLY, USE MacroError or FatalError! } else { strcpy(gszLastNormalError,szLine); } } /**/ // *************************************************************************** // Function: MQMsgBox // Description: Our '/msgbox' command // Our message box // Usage: /msgbox text // *************************************************************************** VOID MQMsgBox(PSPAWNINFO pChar, PCHAR szLine) { FILE *fOut = NULL; CHAR szBuffer[MAX_STRING] = {0}; DWORD i; bRunNextCommand = TRUE; sprintf(szBuffer, "${Time.Date} ${Time}\r\n%s",szLine); ParseMacroParameter(pChar,szBuffer); CreateThread(NULL,0,thrMsgBox,strdup(szBuffer),0,&i); } // *************************************************************************** // Function: MacroLog // Description: Our '/mqlog' command // Our logging // Usage: /mqlog text // *************************************************************************** VOID MacroLog(PSPAWNINFO pChar, PCHAR szLine) { FILE *fOut = NULL; CHAR Filename[MAX_STRING] = {0}; CHAR szBuffer[MAX_STRING] = {0}; DWORD i; bRunNextCommand = TRUE; if (gszMacroName[0]==0) { sprintf(Filename,"%s\\MacroQuest.log",gszLogPath); } else { sprintf(Filename,"%s\\%s.log",gszLogPath, gszMacroName); } for (i=0;i<strlen(Filename);i++) { if (Filename[i]=='\\') { strncpy(szBuffer,Filename,i); if (2 == _mkdir(szBuffer)) { MacroError("Log path doesn't appear valid: %s",Filename); return; } } } if (!stricmp(szLine,"clear")) { fOut = fopen(Filename,"wt"); if (!fOut) { MacroError("Couldn't open log file: %s",Filename); return; } WriteChatColor("Cleared log.",USERCOLOR_DEFAULT); fclose(fOut); return; } fOut = fopen(Filename,"at"); if (!fOut) { MacroError("Couldn't open log file: %s",Filename); return; } sprintf(szBuffer, "[${Time.Date} ${Time.Time24}] %s",szLine); ParseMacroParameter(pChar,szBuffer); fprintf(fOut,"%s\n", szBuffer); DebugSpew("MacroLog - %s", szBuffer); fclose(fOut); } // *************************************************************************** // Function: Face // Description: Our '/face' command // Faces the direction to a spawn // Usage: /face <spawn> // Usage: /face loc <y>,<x> // *************************************************************************** VOID Face(PSPAWNINFO pChar, PCHAR szLine) { if (!ppSpawnManager) return; if (!pSpawnList) return; PSPAWNINFO pSpawnClosest = NULL; PSPAWNINFO psTarget = NULL; SPAWNINFO LocSpawn = {0}; SEARCHSPAWN SearchSpawn; ClearSearchSpawn(&SearchSpawn); CHAR szMsg[MAX_STRING] = {0}; CHAR szName[MAX_STRING] = {0}; CHAR szArg[MAX_STRING] = {0}; CHAR szLLine[MAX_STRING] = {0}; PCHAR szFilter = szLLine; BOOL bArg = TRUE; BOOL bOtherArgs = FALSE; BOOL Away = FALSE; BOOL Predict = FALSE; BOOL Fast = FALSE; BOOL Look = TRUE; BOOL Parsing = TRUE; DOUBLE Distance; bRunNextCommand=FALSE; _strlwr(strcpy(szLLine,szLine)); while (bArg) { GetArg(szArg,szFilter,1); szFilter = GetNextArg(szFilter,1); if (szArg[0]==0) { bArg = FALSE; } else if (!strcmp(szArg,"predict")) { Predict=TRUE; } else if (!strcmp(szArg,"fast")) { Fast = TRUE; } else if (!strcmp(szArg,"away")) { Away = TRUE; } else if (!strcmp(szArg,"nolook")) { Look = FALSE; } else if (!stricmp(szArg, "loc")) { pSpawnClosest = &LocSpawn; strcpy(LocSpawn.Name,"location"); if ((szFilter[0]==0) || (!strstr(szFilter,","))) { MacroError("Face: loc specified but <y>,<x> not found."); return; } pSpawnClosest->Y = (FLOAT)atof(szFilter); while ((szFilter[0]!=',') && (szFilter[0]!=0)) szFilter++; if (szFilter[0]==0) { MacroError("Face: loc specified but <y>,<x> not found."); return; } szFilter++; pSpawnClosest->X = (FLOAT)atof(szFilter); } else if (!stricmp(szArg, "item")) { if (EnviroTarget.Name[0]==0) { MacroError("Face: item specified but no item targetted."); return; } pSpawnClosest = &EnviroTarget; } else if (!stricmp(szArg, "door")) { if (DoorEnviroTarget.Name[0]==0) { MacroError("Face: door specified but no door targetted."); return; } pSpawnClosest = &DoorEnviroTarget; } else if (!stricmp(szArg, "heading")) { if (szFilter[0]==0) { MacroError("Face: heading specified but angle not found."); } else { FLOAT Heading = (FLOAT)(atof(szFilter)); gFaceAngle = Heading/0.703125f; if (gFaceAngle>=512.0f) gFaceAngle -= 512.0f; if (gFaceAngle<0.0f) gFaceAngle += 512.0f; if (Fast) { ((PSPAWNINFO)pCharSpawn)->Heading = (FLOAT)gFaceAngle; gFaceAngle=10000.0f; bRunNextCommand = TRUE; } } return; } else if (!strcmp(szArg,"help")) { SyntaxError("Usage: /face [spawn] [item] [door] [id #] [heading <ang>] [loc <y>,<x>] [away] [alert #]"); bRunNextCommand = TRUE; return; } else { bOtherArgs = TRUE; szFilter = ParseSearchSpawnArgs(szArg,szFilter,&SearchSpawn); } } if (!pSpawnClosest) { if (!bOtherArgs) { if (ppTarget && pTarget) { pSpawnClosest = (PSPAWNINFO)pTarget; } } else { pSpawnClosest = SearchThroughSpawns(&SearchSpawn,pChar); } } szMsg[0]=0; if (!pSpawnClosest) { MacroError("There were no matches for: %s",FormatSearchSpawn(szArg,&SearchSpawn)); } else { if (Predict) { Distance = DistanceToSpawn(pChar, pSpawnClosest); gFaceAngle = ( atan2((pSpawnClosest->X + (pSpawnClosest->SpeedX * Distance)) - pChar->X, (pSpawnClosest->Y + (pSpawnClosest->SpeedY * Distance)) - pChar->Y) * 256.0f / PI); } else { gFaceAngle = ( atan2(pSpawnClosest->X - pChar->X, pSpawnClosest->Y - pChar->Y) * 256.0f / PI); } if (Look) { Distance = DistanceToSpawn(pChar, pSpawnClosest); gLookAngle = ( atan2(pSpawnClosest->Z + pSpawnClosest->AvatarHeight*StateHeightMultiplier(pSpawnClosest->StandState) - pChar->Z - pChar->AvatarHeight*StateHeightMultiplier(pChar->StandState), (FLOAT)Distance) * 256.0f / PI); if (Away) gLookAngle = -gLookAngle; if (Fast) { pChar->CameraAngle = (FLOAT)gLookAngle; gLookAngle=10000.0f; } } if (Away) { gFaceAngle += 256.0f; } if (gFaceAngle>=512.0f) gFaceAngle -= 512.0f; if (gFaceAngle<0.0f) gFaceAngle += 512.0f; if (Fast) { ((PSPAWNINFO)pCharSpawn)->Heading = (FLOAT)gFaceAngle; gFaceAngle=10000.0f; bRunNextCommand = TRUE; } sprintf(szMsg,"Facing %s'%s'...",(Away)?"away from ":"", CleanupName(strcpy(szName,pSpawnClosest->Name),FALSE)); } if (ppTarget && pTarget) { psTarget = (PSPAWNINFO)pTarget; } if (szMsg[0] && ((pSpawnClosest != &LocSpawn) && ((Away) || (pSpawnClosest != psTarget)))) WriteChatColor(szMsg,USERCOLOR_WHO); DebugSpew("Face - %s",szMsg); return; } // *************************************************************************** // Function: Look // Description: Our /look command. Changes camera angle // 2003-08-30 MacroFiend // *************************************************************************** VOID Look(PSPAWNINFO pChar, PCHAR szLine) { CHAR szLookAngle[MAX_STRING]={0}; CHAR szTemp[MAX_STRING]={0}; FLOAT fLookAngle=0.0f; GetArg(szLookAngle,szLine,1); fLookAngle = (FLOAT)atof(szLookAngle); if (fLookAngle>128.0f || fLookAngle<-128.0f) { MacroError("/look -- Angle %f out of range.",fLookAngle); return; } pChar->CameraAngle = fLookAngle; gLookAngle = 10000.0f; } // *************************************************************************** // Function: Where // Description: Our '/where' command // Displays the direction and distance to the closest spawn // Usage: /where <spawn> // *************************************************************************** VOID Where(PSPAWNINFO pChar, PCHAR szLine) { if (!ppSpawnManager) return; if (!pSpawnList) return; PSPAWNINFO pSpawnClosest = NULL; SEARCHSPAWN SearchSpawn; ClearSearchSpawn(&SearchSpawn); CHAR szMsg[MAX_STRING] = {0}; CHAR szName[MAX_STRING] = {0}; CHAR szArg[MAX_STRING] = {0}; CHAR szLLine[MAX_STRING] = {0}; PCHAR szFilter = szLLine; BOOL bArg = TRUE; bRunNextCommand = TRUE; _strlwr(strcpy(szLLine,szLine)); while (bArg) { GetArg(szArg,szFilter,1); szFilter = GetNextArg(szFilter,1); if (szArg[0]==0) { bArg = FALSE; } else { szFilter = ParseSearchSpawnArgs(szArg,szFilter,&SearchSpawn); } } if (!(pSpawnClosest = SearchThroughSpawns(&SearchSpawn,pChar))) { sprintf(szMsg,"There were no matches for: %s",FormatSearchSpawn(szArg,&SearchSpawn)); } else { INT Angle = (INT)((atan2f(pChar->X - pSpawnClosest->X, pChar->Y - pSpawnClosest->Y) * 180.0f / PI + 360.0f) / 22.5f + 0.5f) % 16; sprintf(szMsg,"The closest '%s' is a level %d %s %s and %1.2f away to the %s, Z difference = %1.2f", CleanupName(strcpy(szName,pSpawnClosest->Name),FALSE), pSpawnClosest->Level, pEverQuest->GetRaceDesc(pSpawnClosest->Race), GetClassDesc(pSpawnClosest->Class), DistanceToSpawn(pChar,pSpawnClosest), szHeading[Angle], pSpawnClosest->Z-pChar->Z); DebugSpew("Where - %s",szMsg); } WriteChatColor(szMsg,USERCOLOR_WHO); return; } // *************************************************************************** // Function: DoAbility // Description: Our '/doability' command // Does (or lists) your abilities // Usage: /doability [list|ability|#] // *************************************************************************** VOID DoAbility(PSPAWNINFO pChar, PCHAR szLine) { if(!szLine[0] || !cmdDoAbility) return; if(atoi(szLine) || !EQADDR_DOABILITYLIST) { cmdDoAbility(pChar,szLine); return; } DWORD Index; CHAR szBuffer[MAX_STRING]={0}; GetArg(szBuffer,szLine,1); // display available abilities list if(!stricmp(szBuffer,"list")) { WriteChatColor("Abilities & Combat Skills:",USERCOLOR_DEFAULT); // display skills that have activated state for(Index=0; Index<NUM_SKILLS; Index++) { if(pSkillMgr->pSkill[Index]->Activated) { bool Avail=(GetCharInfo2()->Skill[Index]>0); for(int btn=0; !Avail && btn<10; btn++) { if(EQADDR_DOABILITYLIST[btn]==Index) Avail=true; } // make sure remove trap is added, they give it to everyone except rogues if(Index==75 && strncmp(pEverQuest->GetClassDesc(GetCharInfo2()->Class & 0xFF),"Rogue",6)) Avail=true; if(Avail) { sprintf(szBuffer,"<\ag%s\ax>",szSkills[Index]); WriteChatColor(szBuffer,USERCOLOR_DEFAULT); } } } // display innate skills that are available for(Index=0; Index<28; Index++) { if(GetCharInfo2()->InnateSkill[Index]!=0xFF && strlen(szSkills[Index+100])>3) { sprintf(szBuffer,"<\ag%s\ax>",szSkills[Index+100]); WriteChatColor(szBuffer,USERCOLOR_DEFAULT); } } // display discipline i have WriteChatColor("Combat Abilities:",USERCOLOR_DEFAULT); for(Index=0;Index<NUM_COMBAT_ABILITIES;Index++) { if(GetCharInfo2()->CombatAbilities[Index]) { if(PSPELL pCA=GetSpellByID(GetCharInfo2()->CombatAbilities[Index])) { sprintf(szBuffer, "<\ag%s\ax>",pCA->Name); WriteChatColor(szBuffer,USERCOLOR_DEFAULT); } } } return; } // scan for matching abilities name for(Index=0; Index < 128; Index++) { if((Index < NUM_SKILLS && (pSkillMgr->pSkill[Index])->Activated) || (Index >= NUM_SKILLS && GetCharInfo2()->InnateSkill[Index-100]!=0xFF)) { if(!stricmp(szBuffer,szSkills[Index])) { pCharData1->UseSkill((unsigned char)Index,(EQPlayer*)pCharData1); return; } } } // scan for matching discipline name for(Index=0; Index<NUM_COMBAT_ABILITIES; Index++) { if(GetCharInfo2()->CombatAbilities[Index]) { if(PSPELL pCA=GetSpellByID(GetCharInfo2()->CombatAbilities[Index])) { if(!stricmp(pCA->Name,szBuffer)) { pCharData->DoCombatAbility(pCA->ID); return; } } } } // else display that we didnt found abilities WriteChatColor("You do not seem to have that ability available",USERCOLOR_DEFAULT); } // *************************************************************************** // Function: LoadSpells // Description: Our '/loadspells' command // Loads (or lists) a spell favorite list // Usage: /loadspells [list|"name"] // *************************************************************************** VOID LoadSpells(PSPAWNINFO pChar, PCHAR szLine) { if (!pSpellSets || !ppSpellBookWnd || szLine[0]==0) return; DWORD Index, DoIndex = 0xFFFFFFFF; CHAR szArg1[MAX_STRING] = {0}; CHAR szArg2[MAX_STRING] = {0}; CHAR szBuffer[MAX_STRING] = {0}; if (!pSpellBookWnd) return; GetArg(szArg1,szLine,1); GetArg(szArg2,szLine,2); if ((!stricmp(szArg1,"list")) && (szArg2[0]==0)) { WriteChatColor("Spell favorites list:",USERCOLOR_DEFAULT); WriteChatColor("--------------------------",USERCOLOR_DEFAULT); for (Index=0;Index<NUM_SPELL_SETS;Index++) { if (pSpellSets[Index].Name[0]!=0) { sprintf(szBuffer,"%d) %s",Index,pSpellSets[Index].Name); WriteChatColor(szBuffer,USERCOLOR_DEFAULT); } } return; } if (!stricmp(szArg1,"list")) { DoIndex = IsNumber(szArg2)?atoi(szArg2):FindSpellListByName(szArg2); if (DoIndex < 0 || DoIndex > NUM_SPELL_SETS-1) { sprintf(szBuffer,"Unable to find favorite list '%s'",szArg2); WriteChatColor(szBuffer,USERCOLOR_DEFAULT); return; } sprintf(szBuffer,"Favorite list '%s':",pSpellSets[DoIndex].Name); WriteChatColor(szBuffer,USERCOLOR_DEFAULT); for (Index=0;Index<NUM_SPELL_GEMS;Index++) { if (pSpellSets[DoIndex].SpellId[Index]!=0xFFFFFFFF) { sprintf(szBuffer,"%d) %s",Index,GetSpellByID(pSpellSets[DoIndex].SpellId[Index])->Name ); WriteChatColor(szBuffer,USERCOLOR_DEFAULT); } } return; } DoIndex = IsNumber(szArg1)?atoi(szArg1):FindSpellListByName(szArg1); if (DoIndex >= 0 && DoIndex <NUM_SPELL_SETS) { pSpellBookWnd->MemorizeSet((int*)&pSpellSets[DoIndex],NUM_SPELL_GEMS); } else { sprintf(szBuffer,"Unable to find favorite list '%s'",szArg1); WriteChatColor(szBuffer,USERCOLOR_DEFAULT); } } // *************************************************************************** // Function: Cast // Description: Our '/cast' command // Usage: /cast [list|#|"name of spell"|item "name of item"] // *************************************************************************** VOID Cast(PSPAWNINFO pChar, PCHAR szLine) { if (!cmdCast) return; if (szLine[0]==0 || atoi(szLine) || !ppSpellMgr || !ppCharData || !pCharData) { cmdCast(pChar,szLine); return; } PCHARINFO pCharInfo = GetCharInfo(); if (NULL == pCharInfo) return; DWORD Index; CHAR szBuffer[MAX_STRING] = {0}; CHAR szArg1[MAX_STRING] = {0}; CHAR szArg2[MAX_STRING] = {0}; if (!stricmp(szLine,"list")) { WriteChatColor("Spells:",USERCOLOR_DEFAULT); for (Index=0;Index<NUM_SPELL_GEMS;Index++) { if (GetCharInfo2()->MemorizedSpells[Index]==0xFFFFFFFF) { sprintf(szBuffer,"%d. <Empty>",Index+1); } else { sprintf(szBuffer,"%d. %s",Index+1,GetSpellNameByID(GetCharInfo2()->MemorizedSpells[Index])); } WriteChatColor(szBuffer,USERCOLOR_DEFAULT); } return; } GetArg(szArg1,szLine,1); GetArg(szArg2,szLine,2); DebugSpew("Cast: szArg1 = %s szArg2 = %s",szArg1,szArg2); if (!stricmp(szArg1,"item")) { BOOL FOUND = FALSE; DWORD slot = 0; for (int i=0;i<NUM_INV_SLOTS;i++) { if (GetCharInfo2()->InventoryArray[i]) if (!_stricmp(szArg2,GetCharInfo2()->InventoryArray[i]->Item->Name)) { DebugSpew("cast test slot %d = %s",i,GetCharInfo2()->InventoryArray[i]->Item->Name); slot = (DWORD)i; FOUND = TRUE; break; } } if (FOUND) { if(CInvSlot *pSlot=pInvSlotMgr->FindInvSlot(slot)) { CXPoint p; p.A=0; p.B=0; pSlot->HandleRButtonUp(&p); } } else { WriteChatf("Item '%s' not found.",szArg2); } return; } GetArg(szBuffer,szLine,1); for (Index=0;Index<NUM_SPELL_GEMS;Index++) { if (GetCharInfo2()->MemorizedSpells[Index]!=0xFFFFFFFF) { PCHAR SpellName = GetSpellNameByID(GetCharInfo2()->MemorizedSpells[Index]); if (!stricmp(szBuffer,SpellName)) { DebugSpew("SpellName = %s",SpellName); cmdCast(pChar,itoa(Index+1,szBuffer,10)); DebugSpew("pChar = %x SpellName = %s %s",pChar,SpellName,itoa(Index+1,szBuffer,10)); return; } } } WriteChatColor("You do not seem to have that spell memorized.",USERCOLOR_DEFAULT); return; } // *************************************************************************** // Function: Target // Description: Our '/target' command // Selects the closest spawn // Usage: /target [spawn|myself|mycorpse] // *************************************************************************** VOID Target(PSPAWNINFO pChar, PCHAR szLine) { if (!ppSpawnManager) return; if (!pSpawnList) return; PSPAWNINFO pSpawnClosest = NULL; SEARCHSPAWN SearchSpawn; ClearSearchSpawn(&SearchSpawn); CHAR szArg[MAX_STRING] = {0}; CHAR szMsg[MAX_STRING] = {0}; CHAR szLLine[MAX_STRING] = {0}; PCHAR szFilter = szLLine; BOOL DidTarget = FALSE; BOOL bArg = TRUE; bRunNextCommand = TRUE; _strlwr(strcpy(szLLine,szLine)); while (bArg) { GetArg(szArg,szFilter,1); szFilter = GetNextArg(szFilter,1); if (szArg[0]==0) { bArg = FALSE; } else if (!strcmp(szArg,"myself")) { if (((PCHARINFO)pCharData)->pSpawn) { pSpawnClosest = ((PCHARINFO)pCharData)->pSpawn; DidTarget = TRUE; } } else if (!strcmp(szArg,"mycorpse")) { if (((PCHARINFO)pCharData)->pSpawn) { sprintf(szFilter,"%s's Corpse",((PCHARINFO)pCharData)->pSpawn->Name); _strlwr(szFilter); } } else if (!strcmp(szArg,"clear")) { pTarget = NULL; EnviroTarget.SpawnID = 0; DoorEnviroTarget.SpawnID = 0; if(pChar) pChar->GroupMemberTargeted = 0xFFFFFFFF; DebugSpew("Target cleared."); WriteChatColor("Target cleared.",USERCOLOR_WHO); return; } else { szFilter = ParseSearchSpawnArgs(szArg,szFilter,&SearchSpawn); } } if (pTarget) SearchSpawn.FromSpawnID = ((PSPAWNINFO)pTarget)->SpawnID; if (!DidTarget) { pSpawnClosest = SearchThroughSpawns(&SearchSpawn,pChar); } if (!pSpawnClosest) { CHAR szTemp[MAX_STRING] = {0}; sprintf(szMsg,"There are no spawns matching: %s",FormatSearchSpawn(szTemp,&SearchSpawn)); } else { PSPAWNINFO *psTarget = NULL; if (ppTarget) { psTarget = (PSPAWNINFO*)ppTarget; *psTarget = pSpawnClosest; DebugSpew("Target - %s selected",pSpawnClosest->Name); szMsg[0]=0; } else { sprintf(szMsg,"Unable to target, address = 0"); } } if (szMsg[0]) if (!gFilterTarget) WriteChatColor(szMsg,USERCOLOR_WHO); return; } // *************************************************************************** // Function: Skills // Description: Our '/skills' command // Displays what your current skill levels are // Usage: /skills [skill name] // *************************************************************************** VOID Skills(PSPAWNINFO pChar, PCHAR szLine) { DWORD Skill, SkillCount = 0; CHAR szMsg[MAX_STRING] = {0}; bRunNextCommand = TRUE; PCHARINFO pCharInfo = NULL; if (NULL == (pCharInfo = GetCharInfo())) return; if (szLine[0] != 0) _strlwr(szLine); WriteChatColor("Skills",USERCOLOR_DEFAULT); WriteChatColor("-----------------------",USERCOLOR_DEFAULT); for (Skill=0;szSkills[Skill];Skill++) { if (szLine[0] != 0) { CHAR szName[MAX_STRING] = {0}; strcpy(szName,szSkills[Skill]); _strlwr(szName); if (!strstr(szName,szLine)) continue; } SkillCount++; switch (GetCharInfo2()->Skill[Skill]) { case 255: //Untrainable SkillCount--; break; case 254: //Can train sprintf(szMsg,"%s: Trainable",szSkills[Skill]); WriteChatColor(szMsg,USERCOLOR_DEFAULT); break; case 253: //Unknown sprintf(szMsg,"%s: Unknown(253)",szSkills[Skill]); WriteChatColor(szMsg,USERCOLOR_DEFAULT); break; default: //Have skill sprintf(szMsg,"%s: %d",szSkills[Skill],GetCharInfo2()->Skill[Skill]); WriteChatColor(szMsg,USERCOLOR_DEFAULT); } } if (SkillCount == 0) { sprintf(szMsg,"No skills matched '%s'.",szLine); WriteChatColor(szMsg,USERCOLOR_DEFAULT); } else { DebugSpew("Skills - %d skills listed",SkillCount); sprintf(szMsg,"%d skills displayed.",SkillCount); WriteChatColor(szMsg,USERCOLOR_DEFAULT); } } // *************************************************************************** // Function: MacroPause // Description: Our '/mqpause' command // Pause/resume a macro // Usage: /mqpause <off> // /mqpause chat [on|off] // *************************************************************************** VOID MacroPause(PSPAWNINFO pChar, PCHAR szLine) { BOOL Pause = TRUE; CHAR szBuffer[MAX_STRING] = {0}; DWORD Command; CHAR szArg[MAX_STRING] = {0}; CHAR szArg1[MAX_STRING] = {0}; PCHAR szPause[] = { "off", "on", NULL }; bRunNextCommand = TRUE; GetArg(szArg,szLine,1); if (!stricmp(szArg,"chat")) { GetArg(szArg1,szLine,2); if (szLine[0]==0) { gMQPauseOnChat = !gMQPauseOnChat; } else { for (Command=0;szPause[Command];Command++) { if (!stricmp(szArg1,szPause[Command])) { gMQPauseOnChat = Command; } } } WritePrivateProfileString("MacroQuest","MQPauseOnChat",(gMQPauseOnChat)?"1":"0",gszINIFilename); sprintf(szBuffer,"Macros will %spause while in chat mode.",(gMQPauseOnChat)?"":"not "); WriteChatColor(szBuffer,USERCOLOR_DEFAULT); return; } if (!gMacroBlock) { MacroError("You cannot pause a macro when one isn't running."); return; } for (Command=0;szPause[Command];Command++) { if (!stricmp(szArg,szPause[Command])) { Pause = Command; } } if (szLine[0]!=0) { WriteChatColor("Syntax: /mqpause [on|off] [chat [on|off]]",USERCOLOR_DEFAULT); } else { Pause = !gMacroPause; } if (gMacroPause == Pause) { sprintf(szBuffer,"Macro is already %s.",(Pause)?"paused":"running"); } else { sprintf(szBuffer,"Macro is %s.",(Pause)?"paused":"running again"); gMacroPause = Pause; } WriteChatColor(szBuffer,USERCOLOR_DEFAULT); } // *************************************************************************** // Function: SetAutoRun // Description: Our '/setautorun' command // Set autorun value // Usage: /setautorun [command] // *************************************************************************** VOID SetAutoRun(PSPAWNINFO pChar, PCHAR szLine) { CHAR szServerAndName[MAX_STRING] = {0}; sprintf(szServerAndName,"%s.%s",EQADDR_SERVERNAME,((PCHARINFO)pCharData)->Name); WritePrivateProfileString(szServerAndName,"AutoRun",szLine,gszINIFilename); sprintf(szServerAndName,"Set autorun to: '%s'",szLine); WriteChatColor(szServerAndName,USERCOLOR_DEFAULT); } // *************************************************************************** // Function: Alias // Description: Our '/alias' command // Add command aliases // Usage: /alias name [delete|command] // *************************************************************************** VOID Alias(PSPAWNINFO pChar, PCHAR szLine) { CHAR szBuffer[MAX_STRING] = {0}; CHAR szName[MAX_STRING] = {0}; PCHAR szCommand = NULL; GetArg(szName,szLine,1); szCommand = GetNextArg(szLine); if (!stricmp(szName,"list")) { PALIAS pLoop = pAliases; DWORD Count=0; WriteChatColor("Aliases",USERCOLOR_WHO); WriteChatColor("--------------------------",USERCOLOR_WHO); while (pLoop) { sprintf(szName,"%s: %s",pLoop->szName,pLoop->szCommand); WriteChatColor(szName,USERCOLOR_WHO); Count++; pLoop = pLoop->pNext; } if (Count==0) { WriteChatColor("No aliases defined.",USERCOLOR_WHO); } else { sprintf(szName,"%d alias%s displayed.",Count,(Count==1)?"":"es"); WriteChatColor(szName,USERCOLOR_WHO); } return; } if ((szName[0]==0) || (szCommand[0]==0)) { SyntaxError("Usage: /alias name [delete|command], or /alias list"); return; } if (!stricmp(szCommand,"delete")) { if (RemoveAlias(szName)) { sprintf(szBuffer,"Alias '%s' deleted.",szName); RewriteAliases(); WriteChatColor(szBuffer,USERCOLOR_DEFAULT); } else { sprintf(szBuffer,"Alias '%s' not found.",szName); WriteChatColor(szBuffer,USERCOLOR_DEFAULT); } } else { BOOL New=1; if (RemoveAlias(szName)) New=0; AddAlias(szName,szCommand); sprintf(szBuffer,"Alias '%s' %sed.",szName,(New)?"add":"updat"); WriteChatColor(szBuffer,USERCOLOR_DEFAULT); RewriteAliases(); } } // *************************************************************************** // Function: Substitute // Description: Our '/substitute' command // Add substitutions // Usage: /substitution <original> <new> // /substitution list // /substitition <original> delete // *************************************************************************** VOID Substitute(PSPAWNINFO pChar, PCHAR szLine) { CHAR szBuffer[MAX_STRING] = {0}; CHAR szName[MAX_STRING] = {0}; PCHAR szCommand = NULL; GetArg(szName,szLine,1); szCommand = GetNextArg(szLine); if (!stricmp(szName,"list")) { PSUB pLoop = pSubs; DWORD Count=0; WriteChatColor("Substitutions",USERCOLOR_WHO); WriteChatColor("--------------------------",USERCOLOR_WHO); while (pLoop) { sprintf(szName,"%s\t----\t%s",pLoop->szOrig,pLoop->szSub); WriteChatColor(szName,USERCOLOR_WHO); Count++; pLoop = pLoop->pNext; } if (Count==0) { WriteChatColor("No Substitutions defined.",USERCOLOR_WHO); } else { sprintf(szName,"%d substitution%s displayed.",Count,(Count==1)?"":"s"); WriteChatColor(szName,USERCOLOR_WHO); } return; } if ((szName[0]==0) || (szCommand[0]==0)) { SyntaxError("Usage: /substitute <orig> <new>, /substitute <orig> delete, or /substitute list"); return; } if (!stricmp(szCommand,"delete")) { if (RemoveSubstitute(szName)) { sprintf(szBuffer,"Substitution for '%s' deleted.",szName); RewriteSubstitutions(); WriteChatColor(szBuffer,USERCOLOR_DEFAULT); } else { sprintf(szBuffer,"Substitution for '%s' not found.",szName); WriteChatColor(szBuffer,USERCOLOR_DEFAULT); } } else { BOOL New=1; if (RemoveSubstitute(szName)) New=0; AddSubstitute(szName,szCommand); sprintf(szBuffer,"Substitution for '%s' %sed.",szName,(New)?"add":"updat"); WriteChatColor(szBuffer,USERCOLOR_DEFAULT); RewriteSubstitutions(); } } // *************************************************************************** // Function: IniOutput // Description: Outputs string data to an INI file using // WritePrivateProfileString. // Usage: /ini // *************************************************************************** VOID IniOutput(PSPAWNINFO pChar, PCHAR szLine) { CHAR szArg1[MAX_STRING] = {0}; //Filename CHAR szArg2[MAX_STRING] = {0}; //Section CHAR szArg3[MAX_STRING] = {0}; //Key CHAR szArg4[MAX_STRING] = {0}; //Data to write CHAR szOutput[MAX_STRING] = {0}; //Success / Error Output GetArg(szArg1,szLine,1); GetArg(szArg2,szLine,2); GetArg(szArg3,szLine,3); GetArg(szArg4,szLine,4); DebugSpew("/ini input -- %s %s %s %s",szArg1,szArg2,szArg3,szArg4); PCHAR pTemp=szArg1; while(pTemp[0]) { if (pTemp[0]=='/') pTemp[0]='\\'; pTemp++; } if (szArg1[0]!='\\' && !strchr(szArg1,':')) { sprintf(szOutput,"%s\\%s",gszMacroPath, szArg1); strcpy(szArg1,szOutput); } if (!strstr(szArg1,".")) strcat(szArg1,".ini"); ZeroMemory(szOutput,MAX_STRING); if (!WritePrivateProfileString(szArg2,szArg3,szArg4,szArg1)) { sprintf(szOutput,"IniOutput ERROR -- during WritePrivateProfileString: %s",szLine); DebugSpew(szOutput); } else { sprintf(szOutput,"IniOutput Write Successful!"); DebugSpew("%s: %s",szOutput,szLine); } } // *************************************************************************** // Function: BankList // Description: Our /banklist command. Lists bank contents to chat buffer. // 2003-08-30 Valerian // *************************************************************************** VOID BankList(PSPAWNINFO pChar, PCHAR szLine) { CHAR szTemp[MAX_STRING]={0}; PCHARINFO pCharInfo = NULL; PCONTENTS pContainer = NULL; if (NULL == (pCharInfo = GetCharInfo())) { MacroError("/banklist -- Bad offset: CharInfo"); return; } WriteChatColor("Listing of Bank Inventory",USERCOLOR_DEFAULT); WriteChatColor("-------------------------",USERCOLOR_DEFAULT); char Link[256]; for (int a=0;a<NUM_BANK_SLOTS;a++) { pContainer=pCharInfo->Bank[a]; if (pContainer) { GetItemLink(pContainer,&Link[0]); sprintf(szTemp,"Slot %d: %dx %s (%s)",a,pContainer->StackCount ? pContainer->StackCount : 1,Link,pContainer->Item->LoreName); WriteChatColor(szTemp,USERCOLOR_DEFAULT); for (int b=0;b<pContainer->Item->Slots;b++) { if (pContainer->Contents[b]) { GetItemLink(pContainer->Contents[b],&Link[0]); sprintf(szTemp,"- Slot %d: %dx %s (%s)",b,pContainer->Contents[b]->StackCount ? pContainer->Contents[b]->StackCount : 1,Link,pContainer->Contents[b]->Item->LoreName); WriteChatColor(szTemp,USERCOLOR_DEFAULT); } } } } } // *************************************************************************** // Function: WindowState // Description: Our /windowstate command. Toggles windows open/closed. // *************************************************************************** VOID WindowState(PSPAWNINFO pChar, PCHAR szLine) { CHAR Arg1[MAX_STRING] = {0}; CHAR Arg2[MAX_STRING] = {0}; GetArg(Arg1,szLine,1); GetArg(Arg2,szLine,2); if (PCSIDLWND pWnd=(PCSIDLWND)FindMQ2Window(Arg1)) { DWORD ShowWindow = (DWORD)pWnd->pvfTable->ShowWindow; CHAR szBuffer[MAX_STRING] = {0}; BYTE State=99; if (!stricmp(Arg2,"open")) State=1; if (!stricmp(Arg2,"close")) State=0; if (pWnd->Show==State) State=99; switch (State) { case 0: ((CXWnd*)pWnd)->Show(0,1); sprintf(szBuffer,"Window '%s' is now closed.",pWnd->WindowText->Text); break; case 1: __asm { push ecx; mov ecx, [pWnd]; call dword ptr [ShowWindow]; pop ecx; } sprintf(szBuffer,"Window '%s' is now open.",pWnd->WindowText->Text); break; case 99: sprintf(szBuffer,"Window '%s' is currently %s",pWnd->WindowText->Text,(pWnd->Show==0)?"closed":"open"); break; } WriteChatColor(szBuffer,USERCOLOR_DEFAULT); return; } SyntaxError("Usage: /windowstate <window> [open|close]"); } // *************************************************************************** // Function: KeepKeys // Description: Our /keepkeys command. Toggles if /endmacro will keep keys // by default. // 2003-10-08 MacroFiend // *************************************************************************** VOID KeepKeys(PSPAWNINFO pChar, PCHAR szLine) { bRunNextCommand = TRUE; DWORD Command; CHAR szArg[MAX_STRING] = {0}; GetArg(szArg,szLine,1); CHAR szCmd[MAX_STRING] = {0}; PCHAR szKeepKeys[] = { "off", "on", NULL }; if (szArg[0]==0) { sprintf(szCmd,"Auto-Keep Keys: %s",szKeepKeys[gKeepKeys]); WriteChatColor(szCmd,USERCOLOR_DEFAULT); return; } for (Command=0;szKeepKeys[Command];Command++) { if (!stricmp(szArg,szKeepKeys[Command])) { gKeepKeys = Command; sprintf(szCmd,"Auto-Keep Keys changed to: %s",szKeepKeys[gKeepKeys]); WriteChatColor(szCmd,USERCOLOR_DEFAULT); itoa(gKeepKeys,szCmd,10); WritePrivateProfileString("MacroQuest","KeepKeys",szCmd,gszINIFilename); return; } } SyntaxError("Usage: /keepkeys [on|off]"); } // *************************************************************************** // Function: DisplayLoginName // Description: Our /loginname command. // *************************************************************************** VOID DisplayLoginName(PSPAWNINFO pChar, PCHAR szLine) { PCHAR szLogin = GetLoginName(); if (!szLogin) { MacroError("Unable to retrieve login name."); } else { WriteChatf("Login name: \ay%s\ax",szLogin); free(szLogin); } } #ifndef ISXEQ_LEGACY // *************************************************************************** // Function: PluginCommand // Description: Our /plugin command. // *************************************************************************** VOID PluginCommand(PSPAWNINFO pChar, PCHAR szLine) { CHAR szBuffer[MAX_STRING] = {0}; CHAR szName[MAX_STRING] = {0}; PCHAR szCommand = NULL; GetArg(szName,szLine,1); szCommand = GetNextArg(szLine); if (!stricmp(szName,"list")) { PMQPLUGIN pLoop = pPlugins; DWORD Count=0; WriteChatColor("Active Plugins",USERCOLOR_WHO); WriteChatColor("--------------------------",USERCOLOR_WHO); while (pLoop) { sprintf(szName,"%s",pLoop->szFilename); WriteChatColor(szName,USERCOLOR_WHO); Count++; pLoop = pLoop->pNext; } if (Count==0) { WriteChatColor("No Plugins defined.",USERCOLOR_WHO); } else { sprintf(szName,"%d Plugin%s displayed.",Count,(Count==1)?"":"s"); WriteChatColor(szName,USERCOLOR_WHO); } return; } if (szName[0]==0) { SyntaxError("Usage: /Plugin name [unload] [noauto], or /Plugin list"); return; } if (!strnicmp(szCommand,"unload",6)) { if (UnloadMQ2Plugin(szName)) { sprintf(szBuffer,"Plugin '%s' unloaded.",szName); WriteChatColor(szBuffer,USERCOLOR_DEFAULT); if (!strstr(szCommand,"noauto")) RewriteMQ2Plugins(); } else { MacroError("Plugin '%s' not found.",szName); } } else { if (LoadMQ2Plugin(szName)) { sprintf(szBuffer,"Plugin '%s' loaded.",szName); WriteChatColor(szBuffer,USERCOLOR_DEFAULT); if (stricmp(szCommand,"noauto")) RewriteMQ2Plugins(); } else { MacroError("Plugin '%s' could not be loaded.",szName); } } } #endif VOID EQDestroyHeldItemOrMoney(PSPAWNINFO pChar, PCHAR szLine) { (pPCData)->DestroyHeldItemOrMoney(); } VOID Exec(PSPAWNINFO pChar,PCHAR szLine) { CHAR exepath[MAX_STRING] = {0}; // CHAR szTemp[MAX_STRING] = {0}; CHAR szTemp1[MAX_STRING] = {0}; CHAR szTemp2[MAX_STRING] = {0}; GetArg(szTemp1,szLine,1); GetArg(szTemp2,szLine,2); if (szTemp1[0]!=0 && szTemp2[0]!=0) { WriteChatf("Opening %s %s",szTemp1,szTemp2); GetPrivateProfileString("Application Paths",szTemp1,szTemp1,exepath,MAX_STRING,gszINIFilename); if(!strcmp(szTemp2,"bg")) { ShellExecute(NULL, "open", exepath, NULL, NULL, SW_SHOWMINNOACTIVE); } else if(!strcmp(szTemp2,"fg")) { ShellExecute(NULL, "open", exepath, NULL, NULL, SW_SHOWNOACTIVATE); } } else { WriteChatColor("/exec [application] [fg | bg]",USERCOLOR_DEFAULT); } } // /keypress VOID DoMappable(PSPAWNINFO pChar, PCHAR szLine) { if (szLine[0]==0) { SyntaxError("Usage: /keypress <eqcommand|keycombo> [hold|chat]"); return; } CHAR szArg1[MAX_STRING]={0}; CHAR szArg2[MAX_STRING]={0}; GetArg(szArg1,szLine,1); GetArg(szArg2,szLine,2); BOOL Hold=(stricmp(szArg2,"hold")==0); if (!PressMQ2KeyBind(szArg1,Hold)) { int N=FindMappableCommand(szArg1); if (N>=0) { ExecuteCmd(N,1,0); if (!Hold) ExecuteCmd(N,0,0); return; } KeyCombo Temp; if (ParseKeyCombo(szArg1,Temp)) { if (!stricmp(szArg2,"chat")) { if (Temp.Data[3] != 0x92) { pWndMgr->HandleKeyboardMsg(Temp.Data[3],1); pWndMgr->HandleKeyboardMsg(Temp.Data[3],0); } else { // ugly ass hack -- the ':' char no longer // seems to be handled independently. simulate // a shift and a ; pWndMgr->HandleKeyboardMsg(0x2a,1); pWndMgr->HandleKeyboardMsg(0x27,1); pWndMgr->HandleKeyboardMsg(0x27,0); pWndMgr->HandleKeyboardMsg(0x2a,0); } } else { MQ2HandleKeyDown(Temp); if (!Hold) MQ2HandleKeyUp(Temp); } return; } MacroError("Invalid mappable command or key combo '%s'",szArg1); return; } } // /popup VOID PopupText(PSPAWNINFO pChar, PCHAR szLine) { DisplayOverlayText(szLine, CONCOLOR_LIGHTBLUE, 100, 500,500,3000); } // /multiline VOID MultilineCommand(PSPAWNINFO pChar, PCHAR szLine) { if (szLine[0]==0) { SyntaxError("Usage: /multiline <delimiter> <command>[delimiter<command>[delimiter<command>[. . .]]]"); return; } CHAR szArg[MAX_STRING] = {0}; // delimiter(s) GetArg(szArg,szLine,1); PCHAR szRest = GetNextArg(szLine); if (!szRest[0]) return; CHAR Copy[MAX_STRING] = {0}; strcpy(Copy,szRest);// dont destroy original... szRest=strtok(Copy,szArg); while(szRest) { DoCommand(pChar,szRest); szRest=strtok(NULL,szArg); } } // /ranged VOID do_ranged(PSPAWNINFO pChar, PCHAR szLine) { EQPlayer *pRangedTarget=pTarget; if (szLine[0]) { pRangedTarget=GetSpawnByID(atoi(szLine)); if (!pRangedTarget) { MacroError("Invalid spawn ID. Use /ranged with no parameters, or with a spawn ID"); return; } } if (!pRangedTarget) { MacroError("No target for ranged attack"); return; } AttackRanged(pRangedTarget); } // /loadcfg VOID LoadCfgCommand(PSPAWNINFO pChar, PCHAR szLine) { if (!szLine[0]) { SyntaxError("Usage: /loadcfg <filename>"); return; } if (LoadCfgFile(szLine,false)) return; MacroError("Could not /loadcfg '%s'",szLine); } // /dumpbinds VOID DumpBindsCommand(PSPAWNINFO pChar, PCHAR szLine) { if (!szLine[0]) { SyntaxError("Usage /dumpbinds <filename>"); return; } CHAR szBuffer[MAX_STRING]={0}; if (!DumpBinds(szLine)) { MacroError("Could not dump binds to %s",szLine); return; } WriteChatColor("Binds dumped to file."); } // /squelch VOID SquelchCommand(PSPAWNINFO pChar, PCHAR szLine) { if (!szLine[0]) { SyntaxError("Usage: /squelch <command>"); return; } BOOL Temp=gFilterMQ; gFilterMQ=true; DoCommand(pChar,szLine); gFilterMQ=Temp; } // /docommand VOID DoCommandCmd(PSPAWNINFO pChar, PCHAR szLine) { if (!szLine[0]) { SyntaxError("Usage: /docommand <command>"); return; } DoCommand(pChar,szLine); } // /alt VOID DoAltCmd(PSPAWNINFO pChar, PCHAR szLine) { if (!szLine[0]) { SyntaxError("Usage: /alt <command>"); return; } bool Old=((PCXWNDMGR)pWndMgr)->KeyboardFlags[2]; ((PCXWNDMGR)pWndMgr)->KeyboardFlags[2]=1; DoCommand(pChar,szLine); ((PCXWNDMGR)pWndMgr)->KeyboardFlags[2]=Old; } // /shift VOID DoShiftCmd(PSPAWNINFO pChar, PCHAR szLine) { if (!szLine[0]) { SyntaxError("Usage: /shift <command>"); return; } bool Old=((PCXWNDMGR)pWndMgr)->KeyboardFlags[0]; ((PCXWNDMGR)pWndMgr)->KeyboardFlags[0]=1; gShiftKeyDown=1; DoCommand(pChar,szLine); gShiftKeyDown=0; ((PCXWNDMGR)pWndMgr)->KeyboardFlags[0]=Old; } // /ctrl VOID DoCtrlCmd(PSPAWNINFO pChar, PCHAR szLine) { if (!szLine[0]) { SyntaxError("Usage: /ctrl <command>"); return; } bool Old=((PCXWNDMGR)pWndMgr)->KeyboardFlags[1]; ((PCXWNDMGR)pWndMgr)->KeyboardFlags[1]=1; DoCommand(pChar,szLine); ((PCXWNDMGR)pWndMgr)->KeyboardFlags[1]=Old; } VOID NoModKeyCmd(PSPAWNINFO pChar, PCHAR szLine) { if (!szLine[0]) { SyntaxError("Usage: /nomodkey <command>"); return; } bool KeyboardFlags[4]; *(DWORD*)&KeyboardFlags=*(DWORD*)&((PCXWNDMGR)pWndMgr)->KeyboardFlags; *(DWORD*)&((PCXWNDMGR)pWndMgr)->KeyboardFlags=0; DoCommand(pChar,szLine); *(DWORD*)&((PCXWNDMGR)pWndMgr)->KeyboardFlags=*(DWORD*)&KeyboardFlags; } // *************************************************************************** // Function: DoSocial // Description: '/dosocial' command // Does (or lists) your programmed socials // Usage: /dosocial [list|"social name"] // *************************************************************************** VOID DoSocial(PSPAWNINFO pChar, PCHAR szLine) { if (!pSocialList) return; DWORD SocialIndex = -1, LineIndex; DWORD SocialPage = 0, SocialNum = 0; CHAR szBuffer[MAX_STRING] = {0}; BOOL displayUsage = FALSE; GetArg(szBuffer,szLine,1); if( !stricmp(szBuffer,"list") ) { WriteChatColor("Socials: (page,number) name",USERCOLOR_DEFAULT); for (SocialIndex=0; SocialIndex < 120; SocialIndex++) { SocialPage = SocialIndex/12; SocialNum = SocialIndex - (SocialPage*12); if( strlen(pSocialList[SocialIndex].Name) ) { sprintf(szBuffer,"(%2d,%2d) %s ", SocialPage+1, SocialNum+1, pSocialList[SocialIndex].Name); WriteChatColor(szBuffer,USERCOLOR_ECHO_EMOTE); for( LineIndex=0; LineIndex < 5; LineIndex++ ) { if( strlen(pSocialList[SocialIndex].Line[LineIndex]) ) { sprintf(szBuffer," %d: %s", LineIndex+1, pSocialList[SocialIndex].Line[LineIndex]); WriteChatColor(szBuffer,USERCOLOR_DEFAULT); } } } } return; } else if( strlen(szBuffer) ) { /* assume we have a social name to match */ for( unsigned long N = 0; N < 120; N++ ) { if( !stricmp(szBuffer,pSocialList[N].Name) ) { SocialIndex=N; break; } } } if (gCurrentSocial==-1) { gCurrentSocial=SocialIndex<<3; } else { if( SocialIndex < 120 ) { for( LineIndex = 0; LineIndex < 5; LineIndex++ ) { if( strlen(pSocialList[SocialIndex].Line[LineIndex]) ) DoCommand(pChar,pSocialList[SocialIndex].Line[LineIndex]); } } else { if( strlen(szLine) ) { sprintf( szBuffer, "Invalid Argument(s): %s", szLine ); WriteChatColor(szBuffer,USERCOLOR_DEFAULT); } SyntaxError("Usage: /dosocial <list|\"social name\">",USERCOLOR_DEFAULT ); } } } // /timed VOID DoTimedCmd(PSPAWNINFO pChar, PCHAR szLine) { if (!szLine[0]) { SyntaxError("Usage: /timed <deciseconds> <command>"); return; } CHAR szArg[MAX_STRING] = {0}; // delay GetArg(szArg,szLine,1); PCHAR szRest = GetNextArg(szLine); if (!szRest[0]) return; TimedCommand(szRest,atoi(szArg)*100); } VOID ClearErrorsCmd(PSPAWNINFO pChar, PCHAR szLine) { gszLastNormalError[0]=0; gszLastSyntaxError[0]=0; gszLastMQ2DataError[0]=0; } VOID CombineCmd(PSPAWNINFO pChar, PCHAR szLine) { if (!szLine[0]) { SyntaxError("Usage: /combine <pack>"); return; } CXWnd *pWnd=FindMQ2Window(szLine); if (!pWnd) { MacroError("Window '%s' not open",szLine); return; } if ((DWORD)pWnd->pvfTable!=CContainerWnd__vftable) { MacroError("Window '%s' not container window",szLine); return; } ((CContainerWnd*)pWnd)->HandleCombine(); } VOID DropCmd(PSPAWNINFO pChar, PCHAR szLine) { if (GetCharInfo2()->Cursor) { if (((EQ_Item*)GetCharInfo2()->Cursor)->CanDrop(1)) { pEverQuest->DropHeldItemOnGround(1); } } } VOID HudCmd(PSPAWNINFO pChar, PCHAR szLine) { if (!szLine[0]) { SyntaxError("Usage: /hud <normal|underui|always>"); WriteChatColor("Note: 'always' forces 'underui' also. The Network Status indicator is not 'always' drawn and is toggled with F11."); return; } else if (!stricmp(szLine,"normal")) { WritePrivateProfileString("MacroQuest","HUDMode","Normal",gszINIFilename); gbAlwaysDrawMQHUD=false; gbHUDUnderUI=false; } else if (!stricmp(szLine,"underui")) { WritePrivateProfileString("MacroQuest","HUDMode","UnderUI",gszINIFilename); gbHUDUnderUI=true; gbAlwaysDrawMQHUD=false; } else if (!stricmp(szLine,"always")) { WritePrivateProfileString("MacroQuest","HUDMode","Always",gszINIFilename); gbHUDUnderUI=true; gbAlwaysDrawMQHUD=true; } } VOID CaptionCmd(PSPAWNINFO pChar, PCHAR szLine) { CHAR Arg1[MAX_STRING]={0}; GetArg(Arg1,szLine,1); if (!Arg1[0]) { SyntaxError("Usage: /caption <list|type <value>|update #|MQCaptions <on|off>>"); return; } if (!stricmp(Arg1,"list")) { WriteChatf("\ayPlayer1\ax: \ag%s\ax",gszSpawnPlayerName[1]); WriteChatf("\ayPlayer2\ax: \ag%s\ax",gszSpawnPlayerName[2]); WriteChatf("\ayPlayer3\ax: \ag%s\ax",gszSpawnPlayerName[3]); WriteChatf("\ayPlayer4\ax: \ag%s\ax",gszSpawnPlayerName[4]); WriteChatf("\ayNPC\ax: \ag%s\ax",gszSpawnNPCName); WriteChatf("\ayPet\ax: \ag%s\ax",gszSpawnPetName); WriteChatf("\ayCorpse\ax: \ag%s\ax",gszSpawnCorpseName); return; } PCHAR pCaption=0; if (!stricmp(Arg1,"Player1")) { pCaption=gszSpawnPlayerName[1]; } else if (!stricmp(Arg1,"Player2")) { pCaption=gszSpawnPlayerName[2]; } else if (!stricmp(Arg1,"Player3")) { pCaption=gszSpawnPlayerName[3]; } else if (!stricmp(Arg1,"Player4")) { pCaption=gszSpawnPlayerName[4]; } else if (!stricmp(Arg1,"Pet")) { pCaption=gszSpawnPetName; } else if (!stricmp(Arg1,"NPC")) { pCaption=gszSpawnNPCName; } else if (!stricmp(Arg1,"Corpse")) { pCaption=gszSpawnCorpseName; } else if (!stricmp(Arg1,"Update")) { gMaxSpawnCaptions=atoi(GetNextArg(szLine)); if (gMaxSpawnCaptions<8) gMaxSpawnCaptions=8; if (gMaxSpawnCaptions>70) gMaxSpawnCaptions=70; WritePrivateProfileString("Captions","Update",itoa(gMaxSpawnCaptions,Arg1,10),gszINIFilename); WriteChatf("\ay%d\ax nearest spawns will have their caption updated each pass.",gMaxSpawnCaptions); return; } else if (!stricmp(Arg1,"MQCaptions")) { gMQCaptions=(!stricmp(GetNextArg(szLine),"On")); WritePrivateProfileString("Captions","MQCaptions",(gMQCaptions?"1":"0"),gszINIFilename); WriteChatf("MQCaptions are now \ay%s\ax.",(gMQCaptions?"On":"Off")); return; } else { MacroError("Invalid caption type '%s'",Arg1); return; } strcpy(pCaption, GetNextArg(szLine)); WritePrivateProfileString("Captions",Arg1,pCaption,gszINIFilename); ConvertCR(pCaption); WriteChatf("\ay%s\ax caption set.",Arg1); } VOID NoParseCmd(PSPAWNINFO pChar, PCHAR szLine) { if (!szLine[0]) { SyntaxError("Usage: /noparse <command>"); return; } bAllowCommandParse=false; DoCommand(pChar,szLine); bAllowCommandParse=true; } VOID AltAbility(PSPAWNINFO pChar, PCHAR szLine) { CHAR szBuffer[MAX_STRING] = {0}; CHAR szCommand[MAX_STRING] = {0}; CHAR szSpellInfo[MAX_STRING] = {0}; PCHAR szName = NULL; GetArg(szCommand,szLine,1); szName = GetNextArg(szLine); unsigned long nAbility=0; int i=0; MQ2TicksType szTime; if ((szName[0]==0) || (szCommand[0]==0)) { SyntaxError("Usage: /aa list [all|timers], /aa info [ability name], or /aa act [ability name]"); return; } if (!stricmp(szCommand,"list")) { if (!stricmp(szName,"all")) { WriteChatColor("Alternative Abilities (Complete List)", CONCOLOR_YELLOW ); WriteChatColor("-------------------------------------", USERCOLOR_WHO); for (nAbility=0 ; nAbility<AA_CHAR_MAX_REAL ; nAbility++) { if ( PALTABILITY pAbility=pAltAdvManager->GetAltAbility(pPCData->GetAltAbilityIndex(nAbility))) { sprintf(szBuffer,"[ %d: %s ]", pAbility->ID, pCDBStr->GetString(pAbility->nName, 1, NULL)); WriteChatColor(szBuffer,USERCOLOR_WHO); } } } else if (!stricmp(szName,"timers")) { WriteChatColor("Alternative Abilities With Timers", CONCOLOR_YELLOW ); WriteChatColor("---------------------------------", USERCOLOR_WHO); for (nAbility=0 ; nAbility<AA_CHAR_MAX_REAL ; nAbility++) { if ( PALTABILITY pAbility=pAltAdvManager->GetAltAbility(pPCData->GetAltAbilityIndex(nAbility)) ) { if ((pAltAdvManager->GetCalculatedTimer(pPCData,pAbility)) > 0) { if (pAltAdvManager->IsAbilityReady(pPCData,pAbility,0)) { sprintf(szBuffer,"[ %d: %s ] (Reuse Time: %d seconds) <Ready>", pAbility->ID, pCDBStr->GetString(pAbility->nName, 1, NULL), pAltAdvManager->GetCalculatedTimer(pPCData,pAbility) ); WriteChatColor(szBuffer,USERCOLOR_WHO); } else { pAltAdvManager->IsAbilityReady(pPCData,pAbility,&i); sprintf(szBuffer,"[ %d: %s ] (Reuse Time: %d seconds) <Ready in %d seconds>", pAbility->ID, pCDBStr->GetString(pAbility->nName, 1, NULL), pAltAdvManager->GetCalculatedTimer(pPCData,pAbility), i ); WriteChatColor(szBuffer,USERCOLOR_WHO); } } } } } else { SyntaxError("Usage: /aa list [all|timers], /aa info [ability name], or /aa act [ability name]"); return; } } else if (!stricmp(szCommand,"info")) { for (unsigned long nAbility=0 ; nAbility<NUM_ALT_ABILITIES ; nAbility++) { if ( PALTABILITY pAbility=pAltAdvManager->GetAltAbility(nAbility)) { char *pName; if (!stricmp(pName = pCDBStr->GetString(pAbility->nName, 1, NULL), szName)) { WriteChatColor("Alternative Advancement Ability Information", CONCOLOR_YELLOW); WriteChatColor("-------------------------------------------", USERCOLOR_WHO); if ((pAltAdvManager->GetCalculatedTimer(pPCData,pAbility)) > 0) {//has a timer if (!pAltAdvManager->IsAbilityReady(pPCData,pAbility,0)) {//it's not ready sprintf(szBuffer,"[ %d: %s ] %s", pAbility->ID, pName, pCDBStr->GetString(pAbility->nName, 4, NULL)); WriteChatColor(szBuffer,USERCOLOR_WHO); sprintf(szBuffer,"Min Level: %d, Cost: %d, Max Rank: %d, Type: %d, Reuse Time: %d seconds", pAbility->MinLevel, pAbility->Cost, pAbility->MaxRank, pAbility->Type, pAltAdvManager->GetCalculatedTimer(pPCData,pAbility)); WriteChatColor(szBuffer,USERCOLOR_WHO); if (pAbility->SpellID > 0) { sprintf(szBuffer,"Casts Spell: %s", GetSpellNameByID(pAbility->SpellID) ); WriteChatColor(szBuffer, USERCOLOR_WHO); } if (PlayerHasAAAbility(pAbility->Index)) { sprintf(szBuffer,"Ready: No (%d seconds until refresh)", i ); WriteChatColor(szBuffer,USERCOLOR_WHO); } else { WriteChatColor("Ready: Not Purchased",USERCOLOR_WHO); } } else { sprintf(szBuffer,"[ %d: %s ] %s", pAbility->ID, pName, pCDBStr->GetString(pAbility->nName, 4, NULL) ); WriteChatColor(szBuffer,USERCOLOR_WHO); sprintf(szBuffer,"Min Level: %d, Cost: %d, Max Rank: %d, Type: %d, Reuse Time: %d seconds", pAbility->MinLevel, pAbility->Cost, pAbility->MaxRank, pAbility->Type, pAltAdvManager->GetCalculatedTimer(pPCData,pAbility)); WriteChatColor(szBuffer,USERCOLOR_WHO); if (pAbility->SpellID > 0) { sprintf(szBuffer,"Casts Spell: %s", GetSpellNameByID(pAbility->SpellID)); WriteChatColor(szBuffer, USERCOLOR_WHO); } sprintf(szBuffer,"Ready: Yes"); WriteChatColor(szBuffer,USERCOLOR_WHO); } } else { pAltAdvManager->IsAbilityReady(pPCData,pAbility,&i); sprintf(szBuffer,"[ %d: %s ] %s", pAbility->ID, pName, pCDBStr->GetString(pAbility->nName, 4, NULL) ); WriteChatColor(szBuffer,USERCOLOR_WHO); sprintf(szBuffer,"Min Level: %d, Cost: %d, Max Rank: %d, Type: %d", pAbility->MinLevel, pAbility->Cost, pAbility->MaxRank, pAbility->Type); WriteChatColor(szBuffer,USERCOLOR_WHO); if (pAbility->SpellID > 0) { sprintf(szBuffer,"Casts Spell: %s", GetSpellNameByID(pAbility->SpellID) ); WriteChatColor(szBuffer, USERCOLOR_WHO); } } } // name matches } // if pability != null } //for loop } else if (!stricmp(szCommand,"act")) { // only search through the ones we have.... for (unsigned long nAbility=0 ; nAbility<AA_CHAR_MAX_REAL ; nAbility++) { if ( PALTABILITY pAbility=pAltAdvManager->GetAltAbility(pPCData->GetAltAbilityIndex(nAbility)) ) { if (PCHAR pName=pCDBStr->GetString(pAbility->nName, 1, NULL)) { if (!stricmp(szName,pName)) { sprintf(szBuffer,"/alt act %d", pAbility->ID); DoCommand(pChar,szBuffer); break; } } } } } else { SyntaxError("Usage: /aa list [all|timers|ready], /aa info [ability name], or /aa act [ability name]"); return; } return; } // *************************************************************************** // Function: Echo // Description: Our '/echo' command // Echos text to the chatbox // Usage: /echo <text> // *************************************************************************** VOID Echo(PSPAWNINFO pChar, PCHAR szLine) { CHAR szEcho[MAX_STRING] = {0}; bRunNextCommand = TRUE; strcpy(szEcho,DebugHeader); strcat(szEcho," "); strncat(szEcho,szLine, MAX_STRING-(strlen(DebugHeader)+2)); DebugSpewNoFile("Echo - %s",szEcho); WriteChatColor(szEcho,USERCOLOR_CHAT_CHANNEL); } // *************************************************************************** // Function: LootAll // Description: Our '/lootall' command // Loots everything on the targeted corpse // Usage: /lootall // *************************************************************************** VOID LootAll(PSPAWNINFO pChar, PCHAR szLine) { pLootWnd->LootAll=1; pEverQuest->doLoot(); } #endif
[ "[email protected]@39408780-f958-9dab-a28b-4b240efc9052" ]
[ [ [ 1, 3299 ] ] ]
811b7f59eb6e8a777077f0719c8994ebec91ae52
93d2dca806a71a612bb00340163015cd95dbe91a
/default_error.hpp
6e05f1f07526ada65aee5d143d597577c0c56ff7
[]
no_license
klokane/turtle
c47f84838531aba05b1bcfd2675de1ceee33a10c
a80223664b7db418705ce95f5ec879416f330eb5
refs/heads/master
2016-09-05T19:04:38.741016
2011-11-14T11:37:17
2011-11-14T11:37:17
2,771,704
0
0
null
null
null
null
UTF-8
C++
false
false
2,261
hpp
// // Copyright Mathieu Champlon 2011 // // 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) // #ifndef MOCK_DEFAULT_ERROR_POLICY_HPP_INCLUDED #define MOCK_DEFAULT_ERROR_POLICY_HPP_INCLUDED #include <iostream> #include <string> namespace mock { struct exception {}; template< typename Result > struct basic_error_policy { static Result abort() { throw exception(); } template< typename Context > static void fail( const std::string& message, const Context& context, const std::string& file = "unknown location", int line = 0 ) { std::cerr << file << '(' << line << "): " << message << ": " << context << std::endl; } template< typename Context > static void expected_call( const Context& /*context*/, const std::string& /*file*/, int /*line*/ ) {} template< typename Context > static void missing_action( const Context& context, const std::string& file, int line ) { fail( "missing action", context, file, line ); } template< typename Context > static void unexpected_call( const Context& context ) { fail( "unexpected call", context ); } template< typename Context > static void sequence_failed( const Context& context, const std::string& /*file*/, int /*line*/ ) { fail( "sequence failed", context ); } template< typename Context > static void verification_failed( const Context& context, const std::string& file, int line ) { fail( "verification failed", context, file, line ); } template< typename Context > static void untriggered_expectation( const Context& context, const std::string& file, int line ) { fail( "untriggered expectation", context, file, line ); } }; } #endif // MOCK_DEFAULT_ERROR_POLICY_HPP_INCLUDED
[ [ [ 1, 74 ] ] ]
e38d4b57f18bef8cc0ebbcb92236880491327f3f
9c0ee473dd13cdf546f98638ad9288981531b368
/ newelisserver --username EmpireDaniel/CommandHandlerThread.h
653552830dd84ce9df46a19a2ee1be29565d8b99
[]
no_license
empiredan/newelisserver
288cd534d648be00878410eaa3ddfbbc1a2c6e74
42b7311d96f76139ac0976e7c59775fd6ee4b37e
refs/heads/master
2016-09-10T04:26:54.540327
2010-05-06T12:35:06
2010-05-06T12:35:06
32,517,255
0
0
null
null
null
null
GB18030
C++
false
false
6,368
h
#if !defined(AFX_COMMANDHANDLERTHREAD_H__DDE42665_4F89_4125_A8A5_8C47CEC34BDC__INCLUDED_) #define AFX_COMMANDHANDLERTHREAD_H__DDE42665_4F89_4125_A8A5_8C47CEC34BDC__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // CommandHandlerThread.h : header file // #include <afxmt.h> #include "commands.h" #include "Data.h" #include "ACTList.h" #include "DataFileBuffer.h" //#include "MessageReceiverThread.h" //#include "MessageSenderThread.h" #define WM_SOCKET_THREAD_ID WM_USER+51 #define WM_COMMAND_DATA WM_USER+52 #define WM_DATABUF_LEN WM_USER+53 #define WM_ACT_DATAFILE_ROOT_PATH WM_USER+54 #define WM_CALVER_DATAFILE_ROOT_PATH WM_USER+55 #define WM_ALL_ACT_DATAFILE_PATHS WM_USER+56 #define WM_ACT_DATAFILE_PATH WM_USER+57 #define WM_CALVER_DATAFILE_PATH WM_USER+58 #define WM_SET_DEPTH_DATA_TIMER WM_USER+59 #define WM_SUBSET_DATA_TIMER WM_USER+60 #define WM_DEPTH_DATA_TIMER WM_USER+61 #define WM_ENABLE_RETURN_SUBSET_DATA WM_USER+62 //#define WM_PAUSE_RETURN_SUBSET_DATA WM_USER+62 ///////////////////////////////////////////////////////////////////////////// // CCommandHandlerThread thread typedef struct { int corr_Depth; int true_Depth; int speed; int totalTension; //ๆ€ปๅผ ๅŠ› int mmd; int differTension; //ๅทฎๅˆ†ๅผ ๅŠ› UINT time; //ๆ—ถ้—ด int nreserved2; //ไฟ็•™ } DPM_DISPLAY_PARA; class CCommandHandlerThread : public CWinThread { DECLARE_DYNCREATE(CCommandHandlerThread) protected: CCommandHandlerThread(); // protected constructor used by dynamic creation // Attributes public: private: //Head of received data ULONG m_cmdType; ULONG m_totalLen; //Size of head ULONG m_headLen; //Body of received data BUF_TYPE * m_bodyBuf; //Head of body ULONG m_bodyLen; ULONG m_bufferLen; CString m_actDataFileRootPath; CString m_calverDataFileRootPath; CACTList m_cACTList; DPM_DISPLAY_PARA m_dpmDisplayPara; CWorkMode m_cWorkMode; CDataFileBuffer m_cDataFileBuffer; CCalib m_cCalib; //BOOL m_writeAllBlocksEnabled; long m_timeMS; long m_speedDUPM; long m_speedDUPS; long m_depthDU; // long m_trueDepthDU = 0; // long m_correctedDepthDU = 0; BOOL m_isReturnSubsetDataEnabled; //Timer UINT m_subsetDataTimerIdentifier; UINT m_depthDataTimerIdentifier; static CCriticalSection m_timerLock; //static CRITICAL_SECTION m_timerLock; //Related to thread DWORD m_socketThreadID; //static CCommandHandlerThread * m_pObject; static void * m_pObject; //Log file CFile m_logFile; // Operations public: //void Init(); //static VOID CALLBACK TimerProcWrapper(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime); static VOID CALLBACK TimerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime); //VOID SubsetDataTimerProc(); //VOID DepthDataTimerProc(); /* inline void SetSocketThreadID(DWORD tid){ m_socketThreadID = tid; }*/ inline void PreProcessMasterData(CMasterData *md); inline void ResetCurrentTiming(); void WorkModeProc(); inline void SetSubsetDataTimer(){ ::SetTimer((HWND)(GetMainWnd()->GetSafeHwnd()), SUBSET_DATA_TIMER, m_cACTList.GetTimeMSDelta(), (TIMERPROC)TimerProc); //m_subsetDataTimerIdentifier = ::SetTimer(NULL, NULL, m_cACTList.GetTimeMSDelta(), (TIMERPROC)TimerProc); } inline void SetDepthDataTimer(){ ::SetTimer((HWND)(GetMainWnd()->GetSafeHwnd()), DEPTH_DATA_TIMER, DEPTH_DATA_TIMER_INTERVAL, (TIMERPROC)TimerProc); //m_depthDataTimerIdentifier = ::SetTimer(NULL, NULL, DEPTH_DATA_TIMER_INTERVAL, (TIMERPROC)TimerProc); } inline void KillSubsetDataTimer(){ ::KillTimer((HWND)(GetMainWnd()->GetSafeHwnd()), SUBSET_DATA_TIMER); //::KillTimer(NULL, m_subsetDataTimerIdentifier); } inline void KillDepthDataTimer(){ ::KillTimer((HWND)(GetMainWnd()->GetSafeHwnd()), DEPTH_DATA_TIMER); //::KillTimer(NULL, m_depthDataTimerIdentifier); } void NetCmd_InitServiceTable(); void NetCmd_CalibPara(); void NetCmd_CalibStart(); void NetCmd_CalibStop(); void NetCmd_CtrlWorkState(); //void NetCmd_SetStandbyTimeInterval(); void NetCmd_CtrlRecStop(); //void NetCmd_CtrlActSwitch(); void NetCmd_CtrlActDeactivate(); //void NetCmd_InitConfigParameter(); //void NetCmd_CtrlStandbytimeInterval(); //void NetCmd_CtrlRecstop(); //void NetCmd_CtrlACTSwitch(); //void NetCmd_SnglCtl(); //void NetCmd_DepthInternal(); //void NetCmd_DepthDirection(); void NetCmd_DepthSpeed(); void NetCmd_TrueDepth(); void NetCmd_CorrectedDepth(); //void NetCmd_ManualDepthCorrection(); //void NetCmd_AutoDepthCorrection(); //void NetCmd_DepthLock(); //void NetCmd_DepthUnlock(); //void NetCmd_DepthTensionFactor(); //void NetCmd_DepthTensionAngle(); //void NetCmd_DepthCHT(); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CCommandHandlerThread) public: virtual BOOL InitInstance(); virtual int ExitInstance(); //}}AFX_VIRTUAL // Implementation public: protected: virtual ~CCommandHandlerThread(); // Generated message map functions //{{AFX_MSG(CCommandHandlerThread) afx_msg VOID OnSocketThreadID(WPARAM wParam, LPARAM lParam); afx_msg VOID OnCommand(WPARAM wParam, LPARAM lParam); afx_msg VOID OnDataBufLen(WPARAM wParam, LPARAM lParam); afx_msg VOID OnACTDataFileRootPath(WPARAM wParam, LPARAM lParam); afx_msg VOID OnCALVERDataFileRootPath(WPARAM wParam, LPARAM lParam); afx_msg VOID OnAllACTDataFilePaths(WPARAM wParam, LPARAM lParam); afx_msg VOID OnACTDataFilePath(WPARAM wParam, LPARAM lParam); afx_msg VOID OnCALVERDataFilePath(WPARAM wParam, LPARAM lParam); afx_msg VOID OnDepthDataTimerSetted(WPARAM wParam, LPARAM lParam); afx_msg VOID OnSubsetDataTimer(WPARAM wParam, LPARAM lParam); afx_msg VOID OnDepthDataTimer(WPARAM wParam, LPARAM lParam); afx_msg VOID OnReturnSubsetDataEnabled(WPARAM wParam, LPARAM lParam); //afx_msg VOID OnPauseReturnSubsetData(WPARAM wParam, LPARAM lParam); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_COMMANDHANDLERTHREAD_H__DDE42665_4F89_4125_A8A5_8C47CEC34BDC__INCLUDED_)
[ "EmpireDaniel@c766ca94-0bef-11df-9441-b1846cd9856d" ]
[ [ [ 1, 208 ] ] ]
ca6ee090a99b7256097ad879e708fe7ef0a8169d
d752d83f8bd72d9b280a8c70e28e56e502ef096f
/Extensions/CUDA/EpochCUDA/CUDA Wrapper/FunctionCall.cpp
7fd952b65404b5af15d076438bddbeb6b097834c
[]
no_license
apoch/epoch-language.old
f87b4512ec6bb5591bc1610e21210e0ed6a82104
b09701714d556442202fccb92405e6886064f4af
refs/heads/master
2021-01-10T20:17:56.774468
2010-03-07T09:19:02
2010-03-07T09:19:02
34,307,116
0
0
null
null
null
null
UTF-8
C++
false
false
1,785
cpp
// // The Epoch Language Project // CUDA Interoperability Library // // Wrapper class for handling the invocation of CUDA functions // #include "pch.h" #include "CUDA Wrapper/FunctionCall.h" #include "CUDA Wrapper/Module.h" #define ALIGN_UP(offset, alignment) (offset) = ((offset) + (alignment) - 1) & ~((alignment) - 1) extern bool CUDAAvailableForExecution; extern bool CUDALibraryLoaded; // // Construct and initialize a function call wrapper // FunctionCall::FunctionCall(CUfunction handle) : ParamOffset(0), FunctionHandle(handle) { } // // Add a parameter to the function call // void FunctionCall::AddPointerParameter(CUdeviceptr devicepointer) { if(!CUDAAvailableForExecution) return; void* ptr = reinterpret_cast<void*>(static_cast<size_t>(devicepointer)); ALIGN_UP(ParamOffset, __alignof(ptr)); cuParamSetv(FunctionHandle, ParamOffset, &ptr, sizeof(ptr)); ParamOffset += sizeof(ptr); } void FunctionCall::AddNumericParameter(size_t size) { if(!CUDAAvailableForExecution) return; size_t internalsize = size; ALIGN_UP(ParamOffset, __alignof(internalsize)); cuParamSetv(FunctionHandle, ParamOffset, &internalsize, sizeof(internalsize)); ParamOffset += sizeof(size_t); } // // Actually perform the function call // void FunctionCall::ExecuteNormal() { if(!CUDAAvailableForExecution) return; cuParamSetSize(FunctionHandle, ParamOffset); cuFuncSetBlockShape(FunctionHandle, 1, 1, 1); cuLaunch(FunctionHandle); } void FunctionCall::ExecuteForLoop(size_t count) { if(!CUDAAvailableForExecution) return; cuParamSetSize(FunctionHandle, ParamOffset); cuFuncSetBlockShape(FunctionHandle, 1, 1, 1); cuLaunchGrid(FunctionHandle, static_cast<unsigned>(count), 1); }
[ "[email protected]", "don.apoch@localhost" ]
[ [ [ 1, 13 ], [ 21, 32 ], [ 34, 34 ], [ 38, 43 ], [ 55, 57 ], [ 59, 59 ], [ 63, 63 ], [ 76, 77 ] ], [ [ 14, 20 ], [ 33, 33 ], [ 35, 37 ], [ 44, 54 ], [ 58, 58 ], [ 60, 62 ], [ 64, 75 ] ] ]
d114f0578d0ecfaad1de724151050931c50a33a1
c436a5d7cdbebc04e5d202c6bb3c83448a5db529
/QtOgre/source/Scripting/OgreVector3Class.cpp
5e531d5d3eb26ecd2060193b3c6a3310cd8acf9b
[ "Zlib" ]
permissive
pvdk/QtOgreFramework
89132be5c0ea4f11a43abf4632577ebb21a0b10a
e32bafae2b0c1a8af9700efea61ff351866bb1d5
refs/heads/master
2021-01-23T08:15:38.575879
2010-11-15T21:39:06
2010-11-15T21:39:06
1,680,419
0
1
null
null
null
null
UTF-8
C++
false
false
4,556
cpp
#include "Scripting/OgreVector3Class.h" #include "Scripting/OgreVector3Prototype.h" #include <QtScript/QScriptClassPropertyIterator> #include <QtScript/QScriptEngine> #include <stdlib.h> OgreVector3Class::OgreVector3Class(QScriptEngine *engine) : QObject(engine), QScriptClass(engine) { qScriptRegisterMetaType<Ogre::Vector3>(engine, toScriptValue, fromScriptValue); x = engine->toStringHandle(QLatin1String("x")); y = engine->toStringHandle(QLatin1String("y")); z = engine->toStringHandle(QLatin1String("z")); proto = engine->newQObject(new OgreVector3Prototype(this), QScriptEngine::QtOwnership, QScriptEngine::SkipMethodsInEnumeration | QScriptEngine::ExcludeSuperClassMethods | QScriptEngine::ExcludeSuperClassProperties); QScriptValue global = engine->globalObject(); proto.setPrototype(global.property("Object").property("prototype")); ctor = engine->newFunction(construct); ctor.setData(qScriptValueFromValue(engine, this)); } OgreVector3Class::~OgreVector3Class() { } QScriptClass::QueryFlags OgreVector3Class::queryProperty(const QScriptValue &object, const QScriptString &name, QueryFlags flags, uint *id) { Ogre::Vector3 *ba = qscriptvalue_cast<Ogre::Vector3*>(object.data()); if (!ba) return 0; if (name == x) { return flags; } if (name == y) { return flags; } if (name == z) { return flags; } return 0; } QScriptValue OgreVector3Class::property(const QScriptValue &object, const QScriptString &name, uint id) { Ogre::Vector3 *ba = qscriptvalue_cast<Ogre::Vector3*>(object.data()); if (!ba) return QScriptValue(); if (name == x) { return ba->x; } if (name == y) { return ba->y; } if (name == z) { return ba->z; } return QScriptValue(); } void OgreVector3Class::setProperty(QScriptValue &object, const QScriptString &name, uint id, const QScriptValue &value) { Ogre::Vector3 *ba = qscriptvalue_cast<Ogre::Vector3*>(object.data()); if (!ba) return; if (name == x) { ba->x = value.toNumber(); } if (name == y) { ba->y = value.toNumber(); } if (name == z) { ba->z = value.toNumber(); } } QScriptValue::PropertyFlags OgreVector3Class::propertyFlags( const QScriptValue &/*object*/, const QScriptString &name, uint /*id*/) { if (name == x) { return QScriptValue::Undeletable | QScriptValue::SkipInEnumeration; } if (name == y) { return QScriptValue::Undeletable | QScriptValue::SkipInEnumeration; } if (name == z) { return QScriptValue::Undeletable | QScriptValue::SkipInEnumeration; } return QScriptValue::Undeletable; } QString OgreVector3Class::name() const { return QLatin1String("OgreVector3"); } QScriptValue OgreVector3Class::prototype() const { return proto; } QScriptValue OgreVector3Class::constructor() { return ctor; } QScriptValue OgreVector3Class::newInstance(int size) { return newInstance(Ogre::Vector3()); } QScriptValue OgreVector3Class::newInstance(const Ogre::Vector3 &ba) { QScriptValue data = engine()->newVariant(QVariant::fromValue(ba)); return engine()->newObject(this, data); } QScriptValue OgreVector3Class::construct(QScriptContext *ctx, QScriptEngine *) { OgreVector3Class *cls = qscriptvalue_cast<OgreVector3Class*>(ctx->callee().data()); if (!cls) return QScriptValue(); int size = ctx->argument(0).toInt32(); return cls->newInstance(size); } QScriptValue OgreVector3Class::toScriptValue(QScriptEngine *eng, const Ogre::Vector3 &ba) { QScriptValue ctor = eng->globalObject().property("OgreVector3"); OgreVector3Class *cls = qscriptvalue_cast<OgreVector3Class*>(ctor.data()); if (!cls) return eng->newVariant(qVariantFromValue(ba)); return cls->newInstance(ba); } void OgreVector3Class::fromScriptValue(const QScriptValue &obj, Ogre::Vector3 &ba) { ba = qvariant_cast<Ogre::Vector3>(obj.data().toVariant()); }
[ "esuvs@2eb06014-c84b-0410-ad17-af83cdd4cbf1" ]
[ [ [ 1, 166 ] ] ]
570bce136cac6c818b3cb6121ee9f40add2a7d31
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/_Common/Rijndael.cpp
71ca45b8ed1d7acf5a936421cf301c8696254cb1
[]
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
59,551
cpp
//Rijndael.cpp #include <cstring> #include <exception> #include "StdAfx.h" #include "Rijndael.h" const int CRijndael::sm_alog[256] = { 1, 3, 5, 15, 17, 51, 85, 255, 26, 46, 114, 150, 161, 248, 19, 53, 95, 225, 56, 72, 216, 115, 149, 164, 247, 2, 6, 10, 30, 34, 102, 170, 229, 52, 92, 228, 55, 89, 235, 38, 106, 190, 217, 112, 144, 171, 230, 49, 83, 245, 4, 12, 20, 60, 68, 204, 79, 209, 104, 184, 211, 110, 178, 205, 76, 212, 103, 169, 224, 59, 77, 215, 98, 166, 241, 8, 24, 40, 120, 136, 131, 158, 185, 208, 107, 189, 220, 127, 129, 152, 179, 206, 73, 219, 118, 154, 181, 196, 87, 249, 16, 48, 80, 240, 11, 29, 39, 105, 187, 214, 97, 163, 254, 25, 43, 125, 135, 146, 173, 236, 47, 113, 147, 174, 233, 32, 96, 160, 251, 22, 58, 78, 210, 109, 183, 194, 93, 231, 50, 86, 250, 21, 63, 65, 195, 94, 226, 61, 71, 201, 64, 192, 91, 237, 44, 116, 156, 191, 218, 117, 159, 186, 213, 100, 172, 239, 42, 126, 130, 157, 188, 223, 122, 142, 137, 128, 155, 182, 193, 88, 232, 35, 101, 175, 234, 37, 111, 177, 200, 67, 197, 84, 252, 31, 33, 99, 165, 244, 7, 9, 27, 45, 119, 153, 176, 203, 70, 202, 69, 207, 74, 222, 121, 139, 134, 145, 168, 227, 62, 66, 198, 81, 243, 14, 18, 54, 90, 238, 41, 123, 141, 140, 143, 138, 133, 148, 167, 242, 13, 23, 57, 75, 221, 124, 132, 151, 162, 253, 28, 36, 108, 180, 199, 82, 246, 1 }; const int CRijndael::sm_log[256] = { 0, 0, 25, 1, 50, 2, 26, 198, 75, 199, 27, 104, 51, 238, 223, 3, 100, 4, 224, 14, 52, 141, 129, 239, 76, 113, 8, 200, 248, 105, 28, 193, 125, 194, 29, 181, 249, 185, 39, 106, 77, 228, 166, 114, 154, 201, 9, 120, 101, 47, 138, 5, 33, 15, 225, 36, 18, 240, 130, 69, 53, 147, 218, 142, 150, 143, 219, 189, 54, 208, 206, 148, 19, 92, 210, 241, 64, 70, 131, 56, 102, 221, 253, 48, 191, 6, 139, 98, 179, 37, 226, 152, 34, 136, 145, 16, 126, 110, 72, 195, 163, 182, 30, 66, 58, 107, 40, 84, 250, 133, 61, 186, 43, 121, 10, 21, 155, 159, 94, 202, 78, 212, 172, 229, 243, 115, 167, 87, 175, 88, 168, 80, 244, 234, 214, 116, 79, 174, 233, 213, 231, 230, 173, 232, 44, 215, 117, 122, 235, 22, 11, 245, 89, 203, 95, 176, 156, 169, 81, 160, 127, 12, 246, 111, 23, 196, 73, 236, 216, 67, 31, 45, 164, 118, 123, 183, 204, 187, 62, 90, 251, 96, 177, 134, 59, 82, 161, 108, 170, 85, 41, 157, 151, 178, 135, 144, 97, 190, 220, 252, 188, 149, 207, 205, 55, 63, 91, 209, 83, 57, 132, 60, 65, 162, 109, 71, 20, 42, 158, 93, 86, 242, 211, 171, 68, 17, 146, 217, 35, 32, 46, 137, 180, 124, 184, 38, 119, 153, 227, 165, 103, 74, 237, 222, 197, 49, 254, 24, 13, 99, 140, 128, 192, 247, 112, 7 }; const char CRijndael::sm_S[256] = { 99, 124, 119, 123, -14, 107, 111, -59, 48, 1, 103, 43, -2, -41, -85, 118, -54, -126, -55, 125, -6, 89, 71, -16, -83, -44, -94, -81, -100, -92, 114, -64, -73, -3, -109, 38, 54, 63, -9, -52, 52, -91, -27, -15, 113, -40, 49, 21, 4, -57, 35, -61, 24, -106, 5, -102, 7, 18, -128, -30, -21, 39, -78, 117, 9, -125, 44, 26, 27, 110, 90, -96, 82, 59, -42, -77, 41, -29, 47, -124, 83, -47, 0, -19, 32, -4, -79, 91, 106, -53, -66, 57, 74, 76, 88, -49, -48, -17, -86, -5, 67, 77, 51, -123, 69, -7, 2, 127, 80, 60, -97, -88, 81, -93, 64, -113, -110, -99, 56, -11, -68, -74, -38, 33, 16, -1, -13, -46, -51, 12, 19, -20, 95, -105, 68, 23, -60, -89, 126, 61, 100, 93, 25, 115, 96, -127, 79, -36, 34, 42, -112, -120, 70, -18, -72, 20, -34, 94, 11, -37, -32, 50, 58, 10, 73, 6, 36, 92, -62, -45, -84, 98, -111, -107, -28, 121, -25, -56, 55, 109, -115, -43, 78, -87, 108, 86, -12, -22, 101, 122, -82, 8, -70, 120, 37, 46, 28, -90, -76, -58, -24, -35, 116, 31, 75, -67, -117, -118, 112, 62, -75, 102, 72, 3, -10, 14, 97, 53, 87, -71, -122, -63, 29, -98, -31, -8, -104, 17, 105, -39, -114, -108, -101, 30, -121, -23, -50, 85, 40, -33, -116, -95, -119, 13, -65, -26, 66, 104, 65, -103, 45, 15, -80, 84, -69, 22 }; const char CRijndael::sm_Si[256] = { 82, 9, 106, -43, 48, 54, -91, 56, -65, 64, -93, -98, -127, -13, -41, -5, 124, -29, 57, -126, -101, 47, -1, -121, 52, -114, 67, 68, -60, -34, -23, -53, 84, 123, -108, 50, -90, -62, 35, 61, -18, 76, -107, 11, 66, -6, -61, 78, 8, 46, -95, 102, 40, -39, 36, -78, 118, 91, -94, 73, 109, -117, -47, 37, 114, -8, -10, 100, -122, 104, -104, 22, -44, -92, 92, -52, 93, 101, -74, -110, 108, 112, 72, 80, -3, -19, -71, -38, 94, 21, 70, 87, -89, -115, -99, -124, -112, -40, -85, 0, -116, -68, -45, 10, -9, -28, 88, 5, -72, -77, 69, 6, -48, 44, 30, -113, -54, 63, 15, 2, -63, -81, -67, 3, 1, 19, -118, 107, 58, -111, 17, 65, 79, 103, -36, -22, -105, -14, -49, -50, -16, -76, -26, 115, -106, -84, 116, 34, -25, -83, 53, -123, -30, -7, 55, -24, 28, 117, -33, 110, 71, -15, 26, 113, 29, 41, -59, -119, 111, -73, 98, 14, -86, 24, -66, 27, -4, 86, 62, 75, -58, -46, 121, 32, -102, -37, -64, -2, 120, -51, 90, -12, 31, -35, -88, 51, -120, 7, -57, 49, -79, 18, 16, 89, 39, -128, -20, 95, 96, 81, 127, -87, 25, -75, 74, 13, 45, -27, 122, -97, -109, -55, -100, -17, -96, -32, 59, 77, -82, 42, -11, -80, -56, -21, -69, 60, -125, 83, -103, 97, 23, 43, 4, 126, -70, 119, -42, 38, -31, 105, 20, 99, 85, 33, 12, 125 }; const int CRijndael::sm_T1[256] = { -966564955, -126059388, -294160487, -159679603, -855539, -697603139, -563122255, -1849309868, 1613770832, 33620227, -832084055, 1445669757, -402719207, -1244145822, 1303096294, -327780710, -1882535355, 528646813, -1983264448, -92439161, -268764651, -1302767125, -1907931191, -68095989, 1101901292, -1277897625, 1604494077, 1169141738, 597466303, 1403299063, -462261610, -1681866661, 1974974402, -503448292, 1033081774, 1277568618, 1815492186, 2118074177, -168298750, -2083730353, 1748251740, 1369810420, -773462732, -101584632, -495881837, -1411852173, 1647391059, 706024767, 134480908, -1782069422, 1176707941, -1648114850, 806885416, 932615841, 168101135, 798661301, 235341577, 605164086, 461406363, -538779075, -840176858, 1311188841, 2142417613, -361400929, 302582043, 495158174, 1479289972, 874125870, 907746093, -596742478, -1269146898, 1537253627, -1538108682, 1983593293, -1210657183, 2108928974, 1378429307, -572267714, 1580150641, 327451799, -1504488459, -1177431704, 0, -1041371860, 1075847264, -469959649, 2041688520, -1235526675, -731223362, -1916023994, 1740553945, 1916352843, -1807070498, -1739830060, -1336387352, -2049978550, -1143943061, -974131414, 1336584933, -302253290, -2042412091, -1706209833, 1714631509, 293963156, -1975171633, -369493744, 67240454, -25198719, -1605349136, 2017213508, 631218106, 1269344483, -1571728909, 1571005438, -2143272768, 93294474, 1066570413, 563977660, 1882732616, -235539196, 1673313503, 2008463041, -1344611723, 1109467491, 537923632, -436207846, -34344178, -1076702611, -2117218996, 403442708, 638784309, -1007883217, -1101045791, 899127202, -2008791860, 773265209, -1815821225, 1437050866, -58818942, 2050833735, -932944724, -1168286233, 840505643, -428641387, -1067425632, 427917720, -1638969391, -1545806721, 1143087718, 1412049534, 999329963, 193497219, -1941551414, -940642775, 1807268051, 672404540, -1478566279, -1134666014, 369822493, -1378100362, -606019525, 1681011286, 1949973070, 336202270, -1840690725, 201721354, 1210328172, -1201906460, -1614626211, -1110191250, 1135389935, -1000185178, 965841320, 831886756, -739974089, -226920053, -706222286, -1949775805, 1849112409, -630362697, 26054028, -1311386268, -1672589614, 1235855840, -663982924, -1403627782, -202050553, -806688219, -899324497, -193299826, 1202630377, 268961816, 1874508501, -260540280, 1243948399, 1546530418, 941366308, 1470539505, 1941222599, -1748580783, -873928669, -1579295364, -395021156, 1042226977, -1773450275, 1639824860, 227249030, 260737669, -529502064, 2084453954, 1907733956, -865704278, -1874310952, 100860677, -134810111, 470683154, -1033805405, 1781871967, -1370007559, 1773779408, 394692241, -1715355304, 974986535, 664706745, -639508168, -336005101, 731420851, 571543859, -764843589, -1445340816, 126783113, 865375399, 765172662, 1008606754, 361203602, -907417312, -2016489911, -1437248001, 1344809080, -1512054918, 59542671, 1503764984, 160008576, 437062935, 1707065306, -672733647, -2076032314, -798463816, -2109652541, 697932208, 1512910199, 504303377, 2075177163, -1470868228, 1841019862, 739644986 }; const int CRijndael::sm_T2[256] = { -1513725085, -2064089988, -1712425097, -1913226373, 234877682, -1110021269, -1310822545, 1418839493, 1348481072, 50462977, -1446090905, 2102799147, 434634494, 1656084439, -431117397, -1695779210, 1167051466, -1658879358, 1082771913, -2013627011, 368048890, -340633255, -913422521, 201060592, -331240019, 1739838676, -44064094, -364531793, -1088185188, -145513308, -1763413390, 1536934080, -1032472649, 484572669, -1371696237, 1783375398, 1517041206, 1098792767, 49674231, 1334037708, 1550332980, -195975771, 886171109, 150598129, -1813876367, 1940642008, 1398944049, 1059722517, 201851908, 1385547719, 1699095331, 1587397571, 674240536, -1590192490, 252314885, -1255171430, 151914247, 908333586, -1692696448, 1038082786, 651029483, 1766729511, -847269198, -1612024459, 454166793, -1642232957, 1951935532, 775166490, 758520603, -1294176658, -290170278, -77881184, -157003182, 1299594043, 1639438038, -830622797, 2068982057, 1054729187, 1901997871, -1760328572, -173649069, 1757008337, 0, 750906861, 1614815264, 535035132, -931548751, -306816165, -1093375382, 1183697867, -647512386, 1265776953, -560706998, -728216500, -391096232, 1250283471, 1807470800, 717615087, -447763798, 384695291, -981056701, -677753523, 1432761139, -1810791035, -813021883, 283769337, 100925954, -2114027649, -257929136, 1148730428, -1171939425, -481580888, -207466159, -27417693, -1065336768, -1979347057, -1388342638, -1138647651, 1215313976, 82966005, -547111748, -1049119050, 1974459098, 1665278241, 807407632, 451280895, 251524083, 1841287890, 1283575245, 337120268, 891687699, 801369324, -507617441, -1573546089, -863484860, 959321879, 1469301956, -229267545, -2097381762, 1199193405, -1396153244, -407216803, 724703513, -1780059277, -1598005152, -1743158911, -778154161, 2141445340, 1715741218, 2119445034, -1422159728, -2096396152, -896776634, 700968686, -747915080, 1009259540, 2041044702, -490971554, 487983883, 1991105499, 1004265696, 1449407026, 1316239930, 504629770, -611169975, 168560134, 1816667172, -457679780, 1570751170, 1857934291, -280777556, -1497079198, -1472622191, -1540254315, 936633572, -1947043463, 852879335, 1133234376, 1500395319, -1210421907, -1946055283, 1689376213, -761508274, -532043351, -1260884884, -89369002, 133428468, 634383082, -1345690267, -1896580486, -381178194, 403703816, -714097990, -1997506440, 1867130149, 1918643758, 607656988, -245913946, -948718412, 1368901318, 600565992, 2090982877, -1662487436, 557719327, -577352885, -597574211, -2045932661, -2062579062, -1864339344, 1115438654, -999180875, -1429445018, -661632952, 84280067, 33027830, 303828494, -1547542175, 1600795957, -106014889, -798377543, -1860729210, 1486471617, 658119965, -1188585826, 953803233, 334231800, -1288988520, 857870609, -1143838359, 1890179545, -1995993458, -1489791852, -1238525029, 574365214, -1844082809, 550103529, 1233637070, -5614251, 2018519080, 2057691103, -1895592820, -128343647, -2146858615, 387583245, -630865985, 836232934, -964410814, -1194301336, -1014873791, -1339450983, 2002398509, 287182607, -881086288, -56077228, -697451589, 975967766 }; const int CRijndael::sm_T3[256] = { 1671808611, 2089089148, 2006576759, 2072901243, -233963534, 1807603307, 1873927791, -984313403, 810573872, 16974337, 1739181671, 729634347, -31856642, -681396777, -1410970197, 1989864566, -901410870, -2103631998, -918517303, 2106063485, -99225606, 1508618841, 1204391495, -267650064, -1377025619, -731401260, -1560453214, -1343601233, -1665195108, -1527295068, 1922491506, -1067738176, -1211992649, -48438787, -1817297517, 644500518, 911895606, 1061256767, -150800905, -867204148, 878471220, -1510714971, -449523227, -251069967, 1905517169, -663508008, 827548209, 356461077, 67897348, -950889017, 593839651, -1017209405, 405286936, -1767819370, 84871685, -1699401830, 118033927, 305538066, -2137318528, -499261470, -349778453, 661212711, -1295155278, 1973414517, 152769033, -2086789757, 745822252, 439235610, 455947803, 1857215598, 1525593178, -1594139744, 1391895634, 994932283, -698239018, -1278313037, 695947817, -482419229, 795958831, -2070473852, 1408607827, -781665839, 0, -315833875, 543178784, -65018884, -1312261711, 1542305371, 1790891114, -884568629, -1093048386, 961245753, 1256100938, 1289001036, 1491644504, -817199665, -798245936, -282409489, -1427812438, -82383365, 1137018435, 1305975373, 861234739, -2053893755, 1171229253, -116332039, 33948674, 2139225727, 1357946960, 1011120188, -1615190625, -1461498968, 1374921297, -1543610973, 1086357568, -1886780017, -1834139758, -1648615011, 944271416, -184225291, -1126210628, -1228834890, -629821478, 560153121, 271589392, -15014401, -217121293, -764559406, -850624051, 202643468, 322250259, -332413972, 1608629855, -1750977129, 1154254916, 389623319, -1000893500, -1477290585, 2122513534, 1028094525, 1689045092, 1575467613, 422261273, 1939203699, 1621147744, -2120738431, 1339137615, -595614756, 577127458, 712922154, -1867826288, -2004677752, 1187679302, -299251730, -1194103880, 339486740, -562452514, 1591917662, 186455563, -612979237, -532948000, 844522546, 978220090, 169743370, 1239126601, 101321734, 611076132, 1558493276, -1034051646, -747717165, -1393605716, 1655096418, -1851246191, -1784401515, -466103324, 2039214713, -416098841, -935097400, 928607799, 1840765549, -1920204403, -714821163, 1322425422, -1444918871, 1823791212, 1459268694, -200805388, -366620694, 1706019429, 2056189050, -1360443474, 135794696, -1160417350, 2022240376, 628050469, 779246638, 472135708, -1494132826, -1261997132, -967731258, -400307224, -579034659, 1956440180, 522272287, 1272813131, -1109630531, -1954148981, -1970991222, 1888542832, 1044544574, -1245417035, 1722469478, 1222152264, 50660867, -167643146, 236067854, 1638122081, 895445557, 1475980887, -1177523783, -2037311610, -1051158079, 489110045, -1632032866, -516367903, -132912136, -1733088360, 288563729, 1773916777, -646927911, -1903622258, -1800981612, -1682559589, 505560094, -2020469369, -383727127, -834041906, 1442818645, 678973480, -545610273, -1936784500, -1577559647, -1988097655, 219617805, -1076206145, -432941082, 1120306242, 1756942440, 1103331905, -1716508263, 762796589, 252780047, -1328841808, 1425844308, -1143575109, 372911126 }; const int CRijndael::sm_T4[256] = { 1667474886, 2088535288, 2004326894, 2071694838, -219017729, 1802223062, 1869591006, -976923503, 808472672, 16843522, 1734846926, 724270422, -16901657, -673750347, -1414797747, 1987484396, -892713585, -2105369313, -909557623, 2105378810, -84273681, 1499065266, 1195886990, -252703749, -1381110719, -724277325, -1566376609, -1347425723, -1667449053, -1532692653, 1920112356, -1061135461, -1212693899, -33743647, -1819038147, 640051788, 909531756, 1061110142, -134806795, -859025533, 875846760, -1515850671, -437963567, -235861767, 1903268834, -656903253, 825316194, 353713962, 67374088, -943238507, 589522246, -1010606435, 404236336, -1768513225, 84217610, -1701137105, 117901582, 303183396, -2139055333, -488489505, -336910643, 656894286, -1296904833, 1970642922, 151591698, -2088526307, 741110872, 437923380, 454765878, 1852748508, 1515908788, -1600062629, 1381168804, 993742198, -690593353, -1280061827, 690584402, -471646499, 791638366, -2071685357, 1398011302, -774805319, 0, -303223615, 538992704, -50585629, -1313748871, 1532751286, 1785380564, -875870579, -1094788761, 960056178, 1246420628, 1280103576, 1482221744, -808498555, -791647301, -269538619, -1431640753, -67430675, 1128514950, 1296947098, 859002214, -2054843375, 1162203018, -101117719, 33687044, 2139062782, 1347481760, 1010582648, -1616922075, -1465326773, 1364325282, -1549533603, 1077985408, -1886418427, -1835881153, -1650607071, 943212656, -168491791, -1128472733, -1229536905, -623217233, 555836226, 269496352, -58651, -202174723, -757961281, -842183551, 202118168, 320025894, -320065597, 1600119230, -1751670219, 1145359496, 387397934, -993765485, -1482165675, 2122220284, 1027426170, 1684319432, 1566435258, 421079858, 1936954854, 1616945344, -2122213351, 1330631070, -589529181, 572679748, 707427924, -1869567173, -2004319477, 1179044492, -286381625, -1195846805, 336870440, -555845209, 1583276732, 185277718, -606374227, -522175525, 842159716, 976899700, 168435220, 1229577106, 101059084, 606366792, 1549591736, -1027449441, -741118275, -1397952701, 1650632388, -1852725191, -1785355215, -454805549, 2038008818, -404278571, -926399605, 926374254, 1835907034, -1920103423, -707435343, 1313788572, -1448484791, 1819063512, 1448540844, -185333773, -353753649, 1701162954, 2054852340, -1364268729, 134748176, -1162160785, 2021165296, 623210314, 774795868, 471606328, -1499008681, -1263220877, -960081513, -387439669, -572687199, 1953799400, 522133822, 1263263126, -1111630751, -1953790451, -1970633457, 1886425312, 1044267644, -1246378895, 1718004428, 1212733584, 50529542, -151649801, 235803164, 1633788866, 892690282, 1465383342, -1179004823, -2038001385, -1044293479, 488449850, -1633765081, -505333543, -117959701, -1734823125, 286339874, 1768537042, -640061271, -1903261433, -1802197197, -1684294099, 505291324, -2021158379, -370597687, -825341561, 1431699370, 673740880, -539002203, -1936945405, -1583220647, -1987477495, 218961690, -1077945755, -421121577, 1111672452, 1751693520, 1094828930, -1717981143, 757954394, 252645662, -1330590853, 1414855848, -1145317779, 370555436 }; const int CRijndael::sm_T5[256] = { 1374988112, 2118214995, 437757123, 975658646, 1001089995, 530400753, -1392879445, 1273168787, 540080725, -1384747530, -1999866223, -184398811, 1340463100, -987051049, 641025152, -1251826801, -558802359, 632953703, 1172967064, 1576976609, -1020300030, -2125664238, -1924753501, 1809054150, 59727847, 361929877, -1083344149, -1789765158, -725712083, 1484005843, 1239443753, -1899378620, 1975683434, -191989384, -1722270101, 666464733, -1092530250, -259478249, -920605594, 2110667444, 1675577880, -451268222, -1756286112, 1649639237, -1318815776, -1150570876, -25059300, -116905068, 1883793496, -1891238631, -1797362553, 1383856311, -1418472669, 1917518562, -484470953, 1716890410, -1293211641, 800440835, -2033878118, -751368027, 807962610, 599762354, 33778362, -317291940, -1966138325, -1485196142, -217582864, 1315562145, 1708848333, 101039829, -785096161, -995688822, 875451293, -1561111136, 92987698, -1527321739, 193195065, 1080094634, 1584504582, -1116860335, 1042385657, -1763899843, -583137874, 1306967366, -1856729675, 1908694277, 67556463, 1615861247, 429456164, -692196969, -1992277044, 1742315127, -1326955843, 126454664, -417768648, 2043211483, -1585706425, 2084704233, -125559095, 0, 159417987, 841739592, 504459436, 1817866830, -49348613, 260388950, 1034867998, 908933415, 168810852, 1750902305, -1688513327, 607530554, 202008497, -1822955761, -1259432238, 463180190, -2134850225, 1641816226, 1517767529, 470948374, -493635062, -1063245083, 1008918595, 303765277, 235474187, -225720403, 766945465, 337553864, 1475418501, -1351284916, -291906117, -1551933187, -150919521, 1551037884, 1147550661, 1543208500, -1958532746, -886847780, -1225917336, -1192955549, -684598070, 1113818384, 328671808, -2067394272, -2058738563, -759480840, -1359400431, -953573011, 496906059, -592301837, 226906860, 2009195472, 733156972, -1452230247, 294930682, 1206477858, -1459843900, -1594867942, 1451044056, 573804783, -2025238841, -650587711, -1932877058, -1730933962, -1493859889, -1518674392, -625504730, 1068351396, 742039012, 1350078989, 1784663195, 1417561698, -158526526, -1864845080, 775550814, -2101104651, -1621262146, 1775276924, 1876241833, -819653965, -928212677, 270040487, -392404114, -616842373, -853116919, 1851332852, -325404927, -2091935064, -426414491, -1426069890, 566021896, -283776794, -1159226407, 1248802510, -358676012, 699432150, 832877231, 708780849, -962227152, 899835584, 1951317047, -58537306, -527380304, 866637845, -251357110, 1106041591, 2144161806, 395441711, 1984812685, 1139781709, -861254316, -459930401, -1630423581, 1282050075, -1054072904, 1181045119, -1654724092, 25965917, -91786125, -83148498, -1285087910, -1831087534, -384805325, 1842759443, -1697160820, 933301370, 1509430414, -351060855, -827774994, -1218328267, -518199827, 2051518780, -1663901863, 1441952575, 404016761, 1942435775, 1408749034, 1610459739, -549621996, 2017778566, -894438527, -1184316354, 941896748, -1029488545, 371049330, -1126030068, 675039627, -15887039, 967311729, 135050206, -659233636, 1683407248, 2076935265, -718096784, 1215061108, -793225406 }; const int CRijndael::sm_T6[256] = { 1347548327, 1400783205, -1021700188, -1774573730, -885281941, -249586363, -1414727080, -1823743229, 1428173050, -156404115, -1853305738, 636813900, -61872681, -674944309, -2144979644, -1883938141, 1239331162, 1730525723, -1740248562, -513933632, 46346101, 310463728, -1551022441, -966011911, -419197089, -1793748324, -339776134, -627748263, 768917123, -749177823, 692707433, 1150208456, 1786102409, 2029293177, 1805211710, -584599183, -1229004465, 401639597, 1724457132, -1266823622, 409198410, -2098914767, 1620529459, 1164071807, -525245321, -2068091986, 486441376, -1795618773, 1483753576, 428819965, -2020286868, -1219331080, 598438867, -495826174, 1474502543, 711349675, 129166120, 53458370, -1702443653, -1512884472, -231724921, -1306280027, -1174273174, 1559041666, 730517276, -1834518092, -252508174, -1588696606, -848962828, -721025602, 533804130, -1966823682, -1657524653, -1599933611, 839224033, 1973745387, 957055980, -1438621457, 106852767, 1371368976, -113368694, 1033297158, -1361232379, 1179510461, -1248766835, 91341917, 1862534868, -10465259, 605657339, -1747534359, -863420349, 2003294622, -1112479678, -2012771957, 954669403, -612775698, 1201765386, -377732593, -906460130, 0, -2096529274, 1211247597, -1407315600, 1315723890, -67301633, 1443857720, 507358933, 657861945, 1678381017, 560487590, -778347692, 975451694, -1324610969, 261314535, -759894378, -1642357871, 1333838021, -1570644960, 1767536459, 370938394, 182621114, -440360918, 1128014560, 487725847, 185469197, -1376613433, -1188186456, -938205527, -2057834215, 1286567175, -1141990947, -39616672, -1611202266, -1134791947, -985373125, 878443390, 1988838185, -590666810, 1756818940, 1673061617, -891866660, 272786309, 1075025698, 545572369, 2105887268, -120407235, 296679730, 1841768865, 1260232239, -203640272, -334657966, -797457949, 1814803222, -1716948807, -99511224, 575138148, -995558260, 446754879, -665420500, -282971248, -947435186, -1042728751, -24327518, 915985419, -811141759, 681933534, 651868046, -1539330625, -466863459, 223377554, -1687527476, 1649704518, -1024029421, -393160520, 1580087799, -175979601, -1096852096, 2087309459, -1452288723, -1278270190, 1003007129, -1492117379, 1860738147, 2077965243, 164439672, -194094824, 32283319, -1467789414, 1709610350, 2125135846, 136428751, -420538904, -642062437, -833982666, -722821367, -701910916, -1355701070, 824852259, 818324884, -1070226842, 930369212, -1493400886, -1327460144, 355706840, 1257309336, -146674470, 243256656, 790073846, -1921626666, 1296297904, 1422699085, -538667516, -476130891, 457992840, -1195299809, 2135319889, 77422314, 1560382517, 1945798516, 788204353, 1521706781, 1385356242, 870912086, 325965383, -1936009375, 2050466060, -1906706412, -1981082820, -288446169, 901210569, -304014107, 1014646705, 1503449823, 1062597235, 2031621326, -1082931401, -363595827, 1533017514, 350174575, -2038938405, -2117423117, 1052338372, 741876788, 1606591296, 1914052035, 213705253, -1960297399, 1107234197, 1899603969, -569897805, -1663519516, -1872472383, 1635502980, 1893020342, 1950903388, 1120974935 }; const int CRijndael::sm_T7[256] = { -1487908364, 1699970625, -1530717673, 1586903591, 1808481195, 1173430173, 1487645946, 59984867, -95084496, 1844882806, 1989249228, 1277555970, -671330331, -875051734, 1149249077, -1550863006, 1514790577, 459744698, 244860394, -1058972162, 1963115311, -267222708, -1750889146, -104436781, 1608975247, -1667951214, 2062270317, 1507497298, -2094148418, 567498868, 1764313568, -935031095, -1989511742, 2037970062, 1047239000, 1910319033, 1337376481, -1390940024, -1402549984, 984907214, 1243112415, 830661914, 861968209, 2135253587, 2011214180, -1367032981, -1608712575, 731183368, 1750626376, -48656571, 1820824798, -122203525, -752637069, 48394827, -1890065633, -1423284651, 671593195, -1039978571, 2073724613, 145085239, -2014171096, -1515052097, 1790575107, -2107839210, 472615631, -1265457287, -219090169, -492745111, -187865638, -1093335547, 1646252340, -24460122, 1402811438, 1436590835, -516815478, -344611594, -331805821, -274055072, -1626972559, 273792366, -1963377119, 104699613, 95345982, -1119466010, -1917480620, 1560637892, -730921978, 369057872, -81520232, -375925059, 1137477952, -1636341799, 1119727848, -1954019447, 1530455833, -287606328, 172466556, 266959938, 516552836, 0, -2038232704, -314035669, 1890328081, 1917742170, -262898, 945164165, -719438418, 958871085, -647755249, -1507760036, 1423022939, 775562294, 1739656202, -418409641, -1764576018, -1851909221, -984645440, 547512796, 1265195639, 437656594, -1173691757, 719700128, -532464606, 387781147, 218828297, -944901493, -1464259146, -1446505442, 428169201, 122466165, -574886247, 1627235199, 648017665, -172204942, 1002783846, 2117360635, 695634755, -958608605, -60246291, -245122844, -590686415, -2062531997, 574624663, 287343814, 612205898, 1039717051, 840019705, -1586641111, 793451934, 821288114, 1391201670, -472877119, 376187827, -1181111952, 1224348052, 1679968233, -1933268740, 1058709744, 752375421, -1863376333, 1321699145, -775825096, -1560376118, 188127444, -2117097739, -567761542, -1910056265, -1079754835, -1645990854, -1844621192, -862229921, 1180849278, 331544205, -1192718120, -144822727, -1342864701, -2134991011, -1820562992, 766078933, 313773861, -1724135252, 2108100632, 1668212892, -1149510853, 2013908262, 418672217, -1224610662, -1700232369, 1852171925, -427906305, -821550660, -387518699, -1680229657, 919489135, 164948639, 2094410160, -1297141340, 590424639, -1808742747, 1723872674, -1137216434, -895026046, -793714544, -669699161, -1739919100, -621329940, 1343127501, -164685935, -695372211, -1337113617, 1297403050, 81781910, -1243373871, -2011476886, 532201772, 1367295589, -368796322, 895287692, 1953757831, 1093597963, 492483431, -766340389, 1446242576, 1192455638, 1636604631, 209336225, 344873464, 1015671571, 669961897, -919226527, -437395172, -1321436601, -547775278, 1933530610, -830924780, 935293895, -840281097, -1436852227, 1863638845, -611944380, -209597777, -1002522264, 875313188, 1080017571, -1015933411, 621591778, 1233856572, -1790836979, 24197544, -1277294580, -459482956, -1047501738, -2073986101, -1234119374, 1551124588, 1463996600 }; const int CRijndael::sm_T8[256] = { -190361519, 1097159550, 396673818, 660510266, -1418998981, -1656360673, -94852180, -486304949, 821712160, 1986918061, -864644728, 38544885, -438830001, 718002117, 893681702, 1654886325, -1319482914, -1172609243, -368142267, -20913827, 796197571, 1290801793, 1184342925, -738605461, -1889540349, -1835231979, 1836772287, 1381620373, -1098699308, 1948373848, -529979063, -909622130, -1031181707, -1904641804, 1480485785, -1183720153, -514869570, -2001922064, 548169417, -835013507, -548792221, 439452389, 1362321559, 1400849762, 1685577905, 1806599355, -2120213250, 137073913, 1214797936, 1174215055, -563312748, 2079897426, 1943217067, 1258480242, 529487843, 1437280870, -349698126, -1245576401, -981755258, 923313619, 679998000, -1079659997, 57326082, 377642221, -820237430, 2041877159, 133361907, 1776460110, -621490843, 96392454, 878845905, -1493267772, 777231668, -212492126, -1964953083, -152341084, -2081670901, 1626319424, 1906247262, 1846563261, 562755902, -586793578, 1040559837, -423803315, 1418573201, -1000536719, 114585348, 1343618912, -1728371687, -1108764714, 1078185097, -643926169, -398279248, -1987344377, 425408743, -923870343, 2081048481, 1108339068, -2078357000, 0, -2138668279, 736970802, 292596766, 1517440620, 251657213, -2059905521, -1361764803, 758720310, 265905162, 1554391400, 1532285339, 908999204, 174567692, 1474760595, -292105548, -1684955621, -1060810880, -601841055, 2001430874, 303699484, -1816524062, -1607801408, 585122620, 454499602, 151849742, -1949848078, -1230456531, 514443284, -249985705, 1963412655, -1713521682, 2137062819, 19308535, 1928707164, 1715193156, -75615141, 1126790795, 600235211, -302225226, -453942344, 836553431, 1669664834, -1759363053, -971956092, 1243905413, -1153566510, -114159186, 698445255, -1641067747, -1305414692, -2041385971, -1042034569, -1290376149, 1891211689, -1807156719, -379313593, -57883480, -264299872, 2100090966, 865136418, 1229899655, 953270745, -895287668, -737462632, -176042074, 2061379749, -1215420710, -1379949505, 983426092, 2022837584, 1607244650, 2118541908, -1928084746, -658970480, 972512814, -1011878526, 1568718495, -795640727, -718427793, 621982671, -1399243832, 410887952, -1671205144, 1002142683, 645401037, 1494807662, -1699282452, 1335535747, -1787927066, -1671510, -1127282655, 367585007, -409216582, 1865862730, -1626745622, -1333995991, -1531793615, 1059270954, -1517014842, -1570324427, 1320957812, -2100648196, -1865371424, -1479011021, 77089521, -321194175, -850391425, -1846137065, 1305906550, -273658557, -1437772596, -1778065436, -776608866, 1787304780, 740276417, 1699839814, 1592394909, -1942659839, -2022411270, 188821243, 1729977011, -606973294, 274084841, -699985043, -681472870, -1593017801, -132870567, 322734571, -1457000754, 1640576439, 484830689, 1202797690, -757114468, -227328171, 349075736, -952647821, -137500077, -39167137, 1030690015, 1155237496, -1342996022, 1757691577, 607398968, -1556062270, 499347990, -500888388, 1011452712, 227885567, -1476300487, 213114376, -1260086056, 1455525988, -880516741, 850817237, 1817998408, -1202240816 }; const int CRijndael::sm_U1[256] = { 0, 235474187, 470948374, 303765277, 941896748, 908933415, 607530554, 708780849, 1883793496, 2118214995, 1817866830, 1649639237, 1215061108, 1181045119, 1417561698, 1517767529, -527380304, -291906117, -58537306, -225720403, -659233636, -692196969, -995688822, -894438527, -1864845080, -1630423581, -1932877058, -2101104651, -1459843900, -1493859889, -1259432238, -1159226407, -616842373, -718096784, -953573011, -920605594, -484470953, -317291940, -15887039, -251357110, -1418472669, -1518674392, -1218328267, -1184316354, -1822955761, -1654724092, -1891238631, -2125664238, 1001089995, 899835584, 666464733, 699432150, 59727847, 226906860, 530400753, 294930682, 1273168787, 1172967064, 1475418501, 1509430414, 1942435775, 2110667444, 1876241833, 1641816226, -1384747530, -1551933187, -1318815776, -1083344149, -1789765158, -1688513327, -1992277044, -2025238841, -583137874, -751368027, -1054072904, -819653965, -451268222, -351060855, -116905068, -150919521, 1306967366, 1139781709, 1374988112, 1610459739, 1975683434, 2076935265, 1775276924, 1742315127, 1034867998, 866637845, 566021896, 800440835, 92987698, 193195065, 429456164, 395441711, 1984812685, 2017778566, 1784663195, 1683407248, 1315562145, 1080094634, 1383856311, 1551037884, 101039829, 135050206, 437757123, 337553864, 1042385657, 807962610, 573804783, 742039012, -1763899843, -1730933962, -1966138325, -2067394272, -1359400431, -1594867942, -1293211641, -1126030068, -426414491, -392404114, -91786125, -191989384, -558802359, -793225406, -1029488545, -861254316, 1106041591, 1340463100, 1576976609, 1408749034, 2043211483, 2009195472, 1708848333, 1809054150, 832877231, 1068351396, 766945465, 599762354, 159417987, 126454664, 361929877, 463180190, -1585706425, -1351284916, -1116860335, -1285087910, -1722270101, -1756286112, -2058738563, -1958532746, -785096161, -549621996, -853116919, -1020300030, -384805325, -417768648, -184398811, -83148498, -1697160820, -1797362553, -2033878118, -1999866223, -1561111136, -1392879445, -1092530250, -1326955843, -358676012, -459930401, -158526526, -125559095, -759480840, -592301837, -827774994, -1063245083, 2051518780, 1951317047, 1716890410, 1750902305, 1113818384, 1282050075, 1584504582, 1350078989, 168810852, 67556463, 371049330, 404016761, 841739592, 1008918595, 775550814, 540080725, -325404927, -493635062, -259478249, -25059300, -725712083, -625504730, -928212677, -962227152, -1663901863, -1831087534, -2134850225, -1899378620, -1527321739, -1426069890, -1192955549, -1225917336, 202008497, 33778362, 270040487, 504459436, 875451293, 975658646, 675039627, 641025152, 2084704233, 1917518562, 1615861247, 1851332852, 1147550661, 1248802510, 1484005843, 1451044056, 933301370, 967311729, 733156972, 632953703, 260388950, 25965917, 328671808, 496906059, 1206477858, 1239443753, 1543208500, 1441952575, 2144161806, 1908694277, 1675577880, 1842759443, -684598070, -650587711, -886847780, -987051049, -283776794, -518199827, -217582864, -49348613, -1485196142, -1452230247, -1150570876, -1251826801, -1621262146, -1856729675, -2091935064, -1924753501 }; const int CRijndael::sm_U2[256] = { 0, 185469197, 370938394, 487725847, 741876788, 657861945, 975451694, 824852259, 1483753576, 1400783205, 1315723890, 1164071807, 1950903388, 2135319889, 1649704518, 1767536459, -1327460144, -1141990947, -1493400886, -1376613433, -1663519516, -1747534359, -1966823682, -2117423117, -393160520, -476130891, -24327518, -175979601, -995558260, -811141759, -759894378, -642062437, 2077965243, 1893020342, 1841768865, 1724457132, 1474502543, 1559041666, 1107234197, 1257309336, 598438867, 681933534, 901210569, 1052338372, 261314535, 77422314, 428819965, 310463728, -885281941, -1070226842, -584599183, -701910916, -419197089, -334657966, -249586363, -99511224, -1823743229, -1740248562, -2057834215, -1906706412, -1082931401, -1266823622, -1452288723, -1570644960, -156404115, -39616672, -525245321, -339776134, -627748263, -778347692, -863420349, -947435186, -1361232379, -1512884472, -1195299809, -1278270190, -2098914767, -1981082820, -1795618773, -1611202266, 1179510461, 1296297904, 1347548327, 1533017514, 1786102409, 1635502980, 2087309459, 2003294622, 507358933, 355706840, 136428751, 53458370, 839224033, 957055980, 605657339, 790073846, -1921626666, -2038938405, -1687527476, -1872472383, -1588696606, -1438621457, -1219331080, -1134791947, -721025602, -569897805, -1021700188, -938205527, -113368694, -231724921, -282971248, -466863459, 1033297158, 915985419, 730517276, 545572369, 296679730, 446754879, 129166120, 213705253, 1709610350, 1860738147, 1945798516, 2029293177, 1239331162, 1120974935, 1606591296, 1422699085, -146674470, -61872681, -513933632, -363595827, -612775698, -797457949, -848962828, -966011911, -1355701070, -1539330625, -1188186456, -1306280027, -2096529274, -2012771957, -1793748324, -1642357871, 1201765386, 1286567175, 1371368976, 1521706781, 1805211710, 1620529459, 2105887268, 1988838185, 533804130, 350174575, 164439672, 46346101, 870912086, 954669403, 636813900, 788204353, -1936009375, -2020286868, -1702443653, -1853305738, -1599933611, -1414727080, -1229004465, -1112479678, -722821367, -538667516, -1024029421, -906460130, -120407235, -203640272, -288446169, -440360918, 1014646705, 930369212, 711349675, 560487590, 272786309, 457992840, 106852767, 223377554, 1678381017, 1862534868, 1914052035, 2031621326, 1211247597, 1128014560, 1580087799, 1428173050, 32283319, 182621114, 401639597, 486441376, 768917123, 651868046, 1003007129, 818324884, 1503449823, 1385356242, 1333838021, 1150208456, 1973745387, 2125135846, 1673061617, 1756818940, -1324610969, -1174273174, -1492117379, -1407315600, -1657524653, -1774573730, -1960297399, -2144979644, -377732593, -495826174, -10465259, -194094824, -985373125, -833982666, -749177823, -665420500, 2050466060, 1899603969, 1814803222, 1730525723, 1443857720, 1560382517, 1075025698, 1260232239, 575138148, 692707433, 878443390, 1062597235, 243256656, 91341917, 409198410, 325965383, -891866660, -1042728751, -590666810, -674944309, -420538904, -304014107, -252508174, -67301633, -1834518092, -1716948807, -2068091986, -1883938141, -1096852096, -1248766835, -1467789414, -1551022441, }; const int CRijndael::sm_U3[256] = { 0, 218828297, 437656594, 387781147, 875313188, 958871085, 775562294, 590424639, 1750626376, 1699970625, 1917742170, 2135253587, 1551124588, 1367295589, 1180849278, 1265195639, -793714544, -574886247, -895026046, -944901493, -459482956, -375925059, -24460122, -209597777, -1192718120, -1243373871, -1560376118, -1342864701, -1933268740, -2117097739, -1764576018, -1680229657, -1149510853, -1234119374, -1586641111, -1402549984, -1890065633, -2107839210, -1790836979, -1739919100, -752637069, -567761542, -919226527, -1002522264, -418409641, -368796322, -48656571, -267222708, 1808481195, 1723872674, 1910319033, 2094410160, 1608975247, 1391201670, 1173430173, 1224348052, 59984867, 244860394, 428169201, 344873464, 935293895, 984907214, 766078933, 547512796, 1844882806, 1627235199, 2011214180, 2062270317, 1507497298, 1423022939, 1137477952, 1321699145, 95345982, 145085239, 532201772, 313773861, 830661914, 1015671571, 731183368, 648017665, -1119466010, -1337113617, -1487908364, -1436852227, -1989511742, -2073986101, -1820562992, -1636341799, -719438418, -669699161, -821550660, -1039978571, -516815478, -331805821, -81520232, -164685935, -695372211, -611944380, -862229921, -1047501738, -492745111, -274055072, -122203525, -172204942, -1093335547, -1277294580, -1530717673, -1446505442, -1963377119, -2014171096, -1863376333, -1645990854, 104699613, 188127444, 472615631, 287343814, 840019705, 1058709744, 671593195, 621591778, 1852171925, 1668212892, 1953757831, 2037970062, 1514790577, 1463996600, 1080017571, 1297403050, -621329940, -671330331, -1058972162, -840281097, -287606328, -472877119, -187865638, -104436781, -1297141340, -1079754835, -1464259146, -1515052097, -2038232704, -1954019447, -1667951214, -1851909221, 172466556, 122466165, 273792366, 492483431, 1047239000, 861968209, 612205898, 695634755, 1646252340, 1863638845, 2013908262, 1963115311, 1446242576, 1530455833, 1277555970, 1093597963, 1636604631, 1820824798, 2073724613, 1989249228, 1436590835, 1487645946, 1337376481, 1119727848, 164948639, 81781910, 331544205, 516552836, 1039717051, 821288114, 669961897, 719700128, -1321436601, -1137216434, -1423284651, -1507760036, -2062531997, -2011476886, -1626972559, -1844621192, -647755249, -730921978, -1015933411, -830924780, -314035669, -532464606, -144822727, -95084496, -1224610662, -1173691757, -1390940024, -1608712575, -2094148418, -1910056265, -1724135252, -1808742747, -547775278, -766340389, -984645440, -935031095, -344611594, -427906305, -245122844, -60246291, 1739656202, 1790575107, 2108100632, 1890328081, 1402811438, 1586903591, 1233856572, 1149249077, 266959938, 48394827, 369057872, 418672217, 1002783846, 919489135, 567498868, 752375421, 209336225, 24197544, 376187827, 459744698, 945164165, 895287692, 574624663, 793451934, 1679968233, 1764313568, 2117360635, 1933530610, 1343127501, 1560637892, 1243112415, 1192455638, -590686415, -775825096, -958608605, -875051734, -387518699, -437395172, -219090169, -262898, -1265457287, -1181111952, -1367032981, -1550863006, -2134991011, -1917480620, -1700232369, -1750889146 }; const int CRijndael::sm_U4[256] = { 0, 151849742, 303699484, 454499602, 607398968, 758720310, 908999204, 1059270954, 1214797936, 1097159550, 1517440620, 1400849762, 1817998408, 1699839814, 2118541908, 2001430874, -1865371424, -1713521682, -2100648196, -1949848078, -1260086056, -1108764714, -1493267772, -1342996022, -658970480, -776608866, -895287668, -1011878526, -57883480, -176042074, -292105548, -409216582, 1002142683, 850817237, 698445255, 548169417, 529487843, 377642221, 227885567, 77089521, 1943217067, 2061379749, 1640576439, 1757691577, 1474760595, 1592394909, 1174215055, 1290801793, -1418998981, -1570324427, -1183720153, -1333995991, -1889540349, -2041385971, -1656360673, -1807156719, -486304949, -368142267, -249985705, -132870567, -952647821, -835013507, -718427793, -601841055, 1986918061, 2137062819, 1685577905, 1836772287, 1381620373, 1532285339, 1078185097, 1229899655, 1040559837, 923313619, 740276417, 621982671, 439452389, 322734571, 137073913, 19308535, -423803315, -273658557, -190361519, -39167137, -1031181707, -880516741, -795640727, -643926169, -1361764803, -1479011021, -1127282655, -1245576401, -1964953083, -2081670901, -1728371687, -1846137065, 1305906550, 1155237496, 1607244650, 1455525988, 1776460110, 1626319424, 2079897426, 1928707164, 96392454, 213114376, 396673818, 514443284, 562755902, 679998000, 865136418, 983426092, -586793578, -737462632, -820237430, -971956092, -114159186, -264299872, -349698126, -500888388, -1787927066, -1671205144, -2022411270, -1904641804, -1319482914, -1202240816, -1556062270, -1437772596, -321194175, -438830001, -20913827, -137500077, -923870343, -1042034569, -621490843, -738605461, -1531793615, -1379949505, -1230456531, -1079659997, -2138668279, -1987344377, -1835231979, -1684955621, 2081048481, 1963412655, 1846563261, 1729977011, 1480485785, 1362321559, 1243905413, 1126790795, 878845905, 1030690015, 645401037, 796197571, 274084841, 425408743, 38544885, 188821243, -681472870, -563312748, -981755258, -864644728, -212492126, -94852180, -514869570, -398279248, -1626745622, -1778065436, -1928084746, -2078357000, -1153566510, -1305414692, -1457000754, -1607801408, 1202797690, 1320957812, 1437280870, 1554391400, 1669664834, 1787304780, 1906247262, 2022837584, 265905162, 114585348, 499347990, 349075736, 736970802, 585122620, 972512814, 821712160, -1699282452, -1816524062, -2001922064, -2120213250, -1098699308, -1215420710, -1399243832, -1517014842, -757114468, -606973294, -1060810880, -909622130, -152341084, -1671510, -453942344, -302225226, 174567692, 57326082, 410887952, 292596766, 777231668, 660510266, 1011452712, 893681702, 1108339068, 1258480242, 1343618912, 1494807662, 1715193156, 1865862730, 1948373848, 2100090966, -1593017801, -1476300487, -1290376149, -1172609243, -2059905521, -1942659839, -1759363053, -1641067747, -379313593, -529979063, -75615141, -227328171, -850391425, -1000536719, -548792221, -699985043, 836553431, 953270745, 600235211, 718002117, 367585007, 484830689, 133361907, 251657213, 2041877159, 1891211689, 1806599355, 1654886325, 1568718495, 1418573201, 1335535747, 1184342925 }; const char CRijndael::sm_rcon[30] = { 1, 2, 4, 8, 16, 32, 64, -128, 27, 54, 108, -40, -85, 77, -102, 47, 94, -68, 99, -58, -105, 53, 106, -44, -77, 125, -6, -17, -59, -111 }; const int CRijndael::sm_shifts[3][4][2] = { { {0, 0}, {1, 3}, {2, 2}, {3, 1} }, { {0, 0}, {1, 5}, {2, 4}, {3, 3} }, { {0, 0}, {1, 7}, {3, 5}, {4, 4} } }; //Error Messages char const* CRijndael::sm_szErrorMsg1 = "Object not Initialized"; char const* CRijndael::sm_szErrorMsg2 = "Data not multiple of Block Size"; //Null chain char const* CRijndael::sm_chain0 = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"; CRijndael* CRijndael::GetInstance() { static CRijndael xRijndael; return &xRijndael; } //CONSTRUCTOR CRijndael::CRijndael() : m_bKeyInit(false) { char szDefaultKey[32] = "dldhsvmflvm"; MakeKey( szDefaultKey, CRijndael::sm_chain0 ); } //DESTRUCTOR CRijndael::~CRijndael() { } //Expand a user-supplied key material into a session key. // key - The 128/192/256-bit user-key to use. // chain - initial chain block for CBC and CFB modes. // keylength - 16, 24 or 32 bytes // blockSize - The block size in bytes of this Rijndael (16, 24 or 32 bytes). void CRijndael::MakeKey(char const* key, char const* chain, int keylength, int blockSize) { if(NULL == key) throw exception("Empty key"); if(!(16==keylength || 24==keylength || 32==keylength)) throw exception("Incorrect key length"); if(!(16==blockSize || 24==blockSize || 32==blockSize)) throw exception("Incorrect block length"); m_keylength = keylength; m_blockSize = blockSize; //Initialize the chain memcpy(m_chain0, chain, m_blockSize); memcpy(m_chain, chain, m_blockSize); //Calculate Number of Rounds switch(m_keylength) { case 16: m_iROUNDS = (m_blockSize == 16) ? 10 : (m_blockSize == 24 ? 12 : 14); break; case 24: m_iROUNDS = (m_blockSize != 32) ? 12 : 14; break; default: // 32 bytes = 256 bits m_iROUNDS = 14; } int BC = m_blockSize / 4; int i, j; for(i=0; i<=m_iROUNDS; i++) { for(j=0; j<BC; j++) m_Ke[i][j] = 0; } for(i=0; i<=m_iROUNDS; i++) { for(j=0; j<BC; j++) m_Kd[i][j] = 0; } int ROUND_KEY_COUNT = (m_iROUNDS + 1) * BC; int KC = m_keylength/4; //Copy user material bytes into temporary ints int* pi = tk; char const* pc = key; for(i=0; i<KC; i++) { *pi = (unsigned char)*(pc++) << 24; *pi |= (unsigned char)*(pc++) << 16; *pi |= (unsigned char)*(pc++) << 8; *(pi++) |= (unsigned char)*(pc++); } //Copy values into round key arrays int t = 0; for(j=0; (j<KC)&&(t<ROUND_KEY_COUNT); j++,t++) { m_Ke[t/BC][t%BC] = tk[j]; m_Kd[m_iROUNDS - (t/BC)][t%BC] = tk[j]; } int tt, rconpointer = 0; while(t < ROUND_KEY_COUNT) { //Extrapolate using phi (the round key evolution function) tt = tk[KC-1]; tk[0] ^= (sm_S[(tt >> 16) & 0xFF] & 0xFF) << 24 ^ (sm_S[(tt >> 8) & 0xFF] & 0xFF) << 16 ^ (sm_S[ tt & 0xFF] & 0xFF) << 8 ^ (sm_S[(tt >> 24) & 0xFF] & 0xFF) ^ (sm_rcon[rconpointer++] & 0xFF) << 24; if(KC != 8) for(i=1, j=0; i<KC;) tk[i++] ^= tk[j++]; else { for(i=1, j=0; i<KC/2; ) tk[i++] ^= tk[j++]; tt = tk[KC/2-1]; tk[KC/2] ^= (sm_S[ tt & 0xFF] & 0xFF) ^ (sm_S[(tt >> 8) & 0xFF] & 0xFF) << 8 ^ (sm_S[(tt >> 16) & 0xFF] & 0xFF) << 16 ^ (sm_S[(tt >> 24) & 0xFF] & 0xFF) << 24; for(j = KC/2, i=j+1; i<KC; ) tk[i++] ^= tk[j++]; } //Copy values into round key arrays for(j=0; (j<KC) && (t<ROUND_KEY_COUNT); j++, t++) { m_Ke[t/BC][t%BC] = tk[j]; m_Kd[m_iROUNDS - (t/BC)][t%BC] = tk[j]; } } //Inverse MixColumn where needed for(int r=1; r<m_iROUNDS; r++) for(j=0; j<BC; j++) { tt = m_Kd[r][j]; m_Kd[r][j] = sm_U1[(tt >> 24) & 0xFF] ^ sm_U2[(tt >> 16) & 0xFF] ^ sm_U3[(tt >> 8) & 0xFF] ^ sm_U4[tt & 0xFF]; } m_bKeyInit = true; } //Convenience method to encrypt exactly one block of plaintext, assuming //Rijndael's default block size (128-bit). // in - The plaintext // result - The ciphertext generated from a plaintext using the key void CRijndael::DefEncryptBlock(char const* in, char* result) { if(false==m_bKeyInit) throw exception(sm_szErrorMsg1); int* Ker = m_Ke[0]; int t0 = ((unsigned char)*(in++) << 24); t0 |= ((unsigned char)*(in++) << 16); t0 |= ((unsigned char)*(in++) << 8); (t0 |= (unsigned char)*(in++)) ^= Ker[0]; int t1 = ((unsigned char)*(in++) << 24); t1 |= ((unsigned char)*(in++) << 16); t1 |= ((unsigned char)*(in++) << 8); (t1 |= (unsigned char)*(in++)) ^= Ker[1]; int t2 = ((unsigned char)*(in++) << 24); t2 |= ((unsigned char)*(in++) << 16); t2 |= ((unsigned char)*(in++) << 8); (t2 |= (unsigned char)*(in++)) ^= Ker[2]; int t3 = ((unsigned char)*(in++) << 24); t3 |= ((unsigned char)*(in++) << 16); t3 |= ((unsigned char)*(in++) << 8); (t3 |= (unsigned char)*(in++)) ^= Ker[3]; int a0, a1, a2, a3; //Apply Round Transforms for (int r = 1; r < m_iROUNDS; r++) { Ker = m_Ke[r]; a0 = (sm_T1[(t0 >> 24) & 0xFF] ^ sm_T2[(t1 >> 16) & 0xFF] ^ sm_T3[(t2 >> 8) & 0xFF] ^ sm_T4[t3 & 0xFF]) ^ Ker[0]; a1 = (sm_T1[(t1 >> 24) & 0xFF] ^ sm_T2[(t2 >> 16) & 0xFF] ^ sm_T3[(t3 >> 8) & 0xFF] ^ sm_T4[t0 & 0xFF]) ^ Ker[1]; a2 = (sm_T1[(t2 >> 24) & 0xFF] ^ sm_T2[(t3 >> 16) & 0xFF] ^ sm_T3[(t0 >> 8) & 0xFF] ^ sm_T4[t1 & 0xFF]) ^ Ker[2]; a3 = (sm_T1[(t3 >> 24) & 0xFF] ^ sm_T2[(t0 >> 16) & 0xFF] ^ sm_T3[(t1 >> 8) & 0xFF] ^ sm_T4[t2 & 0xFF]) ^ Ker[3]; t0 = a0; t1 = a1; t2 = a2; t3 = a3; } //Last Round is special Ker = m_Ke[m_iROUNDS]; int tt = Ker[0]; result[0] = (char)( sm_S[(t0 >> 24) & 0xFF] ^ (tt >> 24) ); result[1] = (char)( sm_S[(t1 >> 16) & 0xFF] ^ (tt >> 16) ); result[2] = (char)( sm_S[(t2 >> 8) & 0xFF] ^ (tt >> 8) ); result[3] = (char)( sm_S[t3 & 0xFF] ^ tt ); tt = Ker[1]; result[4] = (char)( sm_S[(t1 >> 24) & 0xFF] ^ (tt >> 24) ); result[5] = (char)( sm_S[(t2 >> 16) & 0xFF] ^ (tt >> 16) ); result[6] = (char)( sm_S[(t3 >> 8) & 0xFF] ^ (tt >> 8) ); result[7] = (char)( sm_S[t0 & 0xFF] ^ tt ); tt = Ker[2]; result[8] = (char)( sm_S[(t2 >> 24) & 0xFF] ^ (tt >> 24) ); result[9] = (char)( sm_S[(t3 >> 16) & 0xFF] ^ (tt >> 16) ); result[10] = (char)( sm_S[(t0 >> 8) & 0xFF] ^ (tt >> 8) ); result[11] = (char)( sm_S[t1 & 0xFF] ^ tt ); tt = Ker[3]; result[12] = (char)( sm_S[(t3 >> 24) & 0xFF] ^ (tt >> 24) ); result[13] = (char)( sm_S[(t0 >> 16) & 0xFF] ^ (tt >> 16) ); result[14] = (char)( sm_S[(t1 >> 8) & 0xFF] ^ (tt >> 8) ); result[15] = (char)( sm_S[t2 & 0xFF] ^ tt ); } //Convenience method to decrypt exactly one block of plaintext, assuming //Rijndael's default block size (128-bit). // in - The ciphertext. // result - The plaintext generated from a ciphertext using the session key. void CRijndael::DefDecryptBlock(char const* in, char* result) { if(false==m_bKeyInit) throw exception(sm_szErrorMsg1); int* Kdr = m_Kd[0]; int t0 = ((unsigned char)*(in++) << 24); t0 = t0 | ((unsigned char)*(in++) << 16); t0 |= ((unsigned char)*(in++) << 8); (t0 |= (unsigned char)*(in++)) ^= Kdr[0]; int t1 = ((unsigned char)*(in++) << 24); t1 |= ((unsigned char)*(in++) << 16); t1 |= ((unsigned char)*(in++) << 8); (t1 |= (unsigned char)*(in++)) ^= Kdr[1]; int t2 = ((unsigned char)*(in++) << 24); t2 |= ((unsigned char)*(in++) << 16); t2 |= ((unsigned char)*(in++) << 8); (t2 |= (unsigned char)*(in++)) ^= Kdr[2]; int t3 = ((unsigned char)*(in++) << 24); t3 |= ((unsigned char)*(in++) << 16); t3 |= ((unsigned char)*(in++) << 8); (t3 |= (unsigned char)*(in++)) ^= Kdr[3]; int a0, a1, a2, a3; for(int r = 1; r < m_iROUNDS; r++) // apply round transforms { Kdr = m_Kd[r]; a0 = (sm_T5[(t0 >> 24) & 0xFF] ^ sm_T6[(t3 >> 16) & 0xFF] ^ sm_T7[(t2 >> 8) & 0xFF] ^ sm_T8[ t1 & 0xFF] ) ^ Kdr[0]; a1 = (sm_T5[(t1 >> 24) & 0xFF] ^ sm_T6[(t0 >> 16) & 0xFF] ^ sm_T7[(t3 >> 8) & 0xFF] ^ sm_T8[ t2 & 0xFF] ) ^ Kdr[1]; a2 = (sm_T5[(t2 >> 24) & 0xFF] ^ sm_T6[(t1 >> 16) & 0xFF] ^ sm_T7[(t0 >> 8) & 0xFF] ^ sm_T8[ t3 & 0xFF] ) ^ Kdr[2]; a3 = (sm_T5[(t3 >> 24) & 0xFF] ^ sm_T6[(t2 >> 16) & 0xFF] ^ sm_T7[(t1 >> 8) & 0xFF] ^ sm_T8[ t0 & 0xFF] ) ^ Kdr[3]; t0 = a0; t1 = a1; t2 = a2; t3 = a3; } //Last Round is special Kdr = m_Kd[m_iROUNDS]; int tt = Kdr[0]; result[ 0] = (char)( sm_Si[(t0 >> 24) & 0xFF] ^ (tt >> 24) ); result[ 1] = (char)( sm_Si[(t3 >> 16) & 0xFF] ^ (tt >> 16) ); result[ 2] = (char)( sm_Si[(t2 >> 8) & 0xFF] ^ (tt >> 8) ); result[ 3] = (char)( sm_Si[ t1 & 0xFF] ^ tt ); tt = Kdr[1]; result[ 4] = (char)( sm_Si[(t1 >> 24) & 0xFF] ^ (tt >> 24) ); result[ 5] = (char)( sm_Si[(t0 >> 16) & 0xFF] ^ (tt >> 16) ); result[ 6] = (char)( sm_Si[(t3 >> 8) & 0xFF] ^ (tt >> 8) ); result[ 7] = (char)( sm_Si[ t2 & 0xFF] ^ tt ); tt = Kdr[2]; result[ 8] = (char)( sm_Si[(t2 >> 24) & 0xFF] ^ (tt >> 24) ); result[ 9] = (char)( sm_Si[(t1 >> 16) & 0xFF] ^ (tt >> 16) ); result[10] = (char)( sm_Si[(t0 >> 8) & 0xFF] ^ (tt >> 8) ); result[11] = (char)( sm_Si[ t3 & 0xFF] ^ tt ); tt = Kdr[3]; result[12] = (char)( sm_Si[(t3 >> 24) & 0xFF] ^ (tt >> 24) ); result[13] = (char)( sm_Si[(t2 >> 16) & 0xFF] ^ (tt >> 16) ); result[14] = (char)( sm_Si[(t1 >> 8) & 0xFF] ^ (tt >> 8) ); result[15] = (char)( sm_Si[ t0 & 0xFF] ^ tt ); } //Encrypt exactly one block of plaintext. // in - The plaintext. // result - The ciphertext generated from a plaintext using the key. void CRijndael::EncryptBlock(char const* in, char* result) { if(false==m_bKeyInit) throw exception(sm_szErrorMsg1); if(DEFAULT_BLOCK_SIZE == m_blockSize) { DefEncryptBlock(in, result); return; } int BC = m_blockSize / 4; int SC = (BC == 4) ? 0 : (BC == 6 ? 1 : 2); int s1 = sm_shifts[SC][1][0]; int s2 = sm_shifts[SC][2][0]; int s3 = sm_shifts[SC][3][0]; //Temporary Work Arrays int i; int tt; int* pi = t; for(i=0; i<BC; i++) { *pi = ((unsigned char)*(in++) << 24); *pi |= ((unsigned char)*(in++) << 16); *pi |= ((unsigned char)*(in++) << 8); (*(pi++) |= (unsigned char)*(in++)) ^= m_Ke[0][i]; } //Apply Round Transforms for(int r=1; r<m_iROUNDS; r++) { for(i=0; i<BC; i++) a[i] = (sm_T1[(t[i] >> 24) & 0xFF] ^ sm_T2[(t[(i + s1) % BC] >> 16) & 0xFF] ^ sm_T3[(t[(i + s2) % BC] >> 8) & 0xFF] ^ sm_T4[ t[(i + s3) % BC] & 0xFF] ) ^ m_Ke[r][i]; memcpy(t, a, 4*BC); } int j; //Last Round is Special for(i=0,j=0; i<BC; i++) { tt = m_Ke[m_iROUNDS][i]; result[j++] = (char)( sm_S[(t[i] >> 24) & 0xFF] ^ (tt >> 24) ); result[j++] = (char)( sm_S[(t[(i + s1) % BC] >> 16) & 0xFF] ^ (tt >> 16) ); result[j++] = (char)( sm_S[(t[(i + s2) % BC] >> 8) & 0xFF] ^ (tt >> 8) ); result[j++] = (char)( sm_S[ t[(i + s3) % BC] & 0xFF] ^ tt ); } } //Decrypt exactly one block of ciphertext. // in - The ciphertext. // result - The plaintext generated from a ciphertext using the session key. void CRijndael::DecryptBlock(char const* in, char* result) { if(false==m_bKeyInit) throw exception(sm_szErrorMsg1); if(DEFAULT_BLOCK_SIZE == m_blockSize) { DefDecryptBlock(in, result); return; } int BC = m_blockSize / 4; int SC = BC == 4 ? 0 : (BC == 6 ? 1 : 2); int s1 = sm_shifts[SC][1][1]; int s2 = sm_shifts[SC][2][1]; int s3 = sm_shifts[SC][3][1]; //Temporary Work Arrays int i; int tt; int* pi = t; for(i=0; i<BC; i++) { *pi = ((unsigned char)*(in++) << 24); *pi |= ((unsigned char)*(in++) << 16); *pi |= ((unsigned char)*(in++) << 8); (*(pi++) |= (unsigned char)*(in++)) ^= m_Kd[0][i]; } //Apply Round Transforms for(int r=1; r<m_iROUNDS; r++) { for(i=0; i<BC; i++) a[i] = (sm_T5[(t[i] >> 24) & 0xFF] ^ sm_T6[(t[(i + s1) % BC] >> 16) & 0xFF] ^ sm_T7[(t[(i + s2) % BC] >> 8) & 0xFF] ^ sm_T8[ t[(i + s3) % BC] & 0xFF]) ^ m_Kd[r][i]; memcpy(t, a, 4*BC); } int j; //Last Round is Special for(i=0,j=0; i<BC; i++) { tt = m_Kd[m_iROUNDS][i]; result[j++] = (char)( sm_Si[(t[i] >> 24) & 0xFF] ^ (tt >> 24) ); result[j++] = (char)( sm_Si[(t[(i + s1) % BC] >> 16) & 0xFF] ^ (tt >> 16) ); result[j++] = (char)( sm_Si[(t[(i + s2) % BC] >> 8) & 0xFF] ^ (tt >> 8) ); result[j++] = (char)( sm_Si[ t[(i + s3) % BC] & 0xFF] ^ tt ); } } void CRijndael::Encrypt(char const* in, char* result, size_t n, int iMode) { if(false==m_bKeyInit) throw exception(sm_szErrorMsg1); //n should be > 0 and multiple of m_blockSize if(0==n || n%m_blockSize!=0) throw exception(sm_szErrorMsg2); int i; char const* pin; char* presult; if(CBC == iMode) //CBC mode, using the Chain { for(i=0,pin=in,presult=result; i<(int)( n/m_blockSize ); i++) { Xor(m_chain, pin); EncryptBlock(m_chain, presult); memcpy(m_chain, presult, m_blockSize); pin += m_blockSize; presult += m_blockSize; } } else if(CFB == iMode) //CFB mode, using the Chain { for(i=0,pin=in,presult=result; i<(int)( n/m_blockSize ); i++) { EncryptBlock(m_chain, presult); Xor(presult, pin); memcpy(m_chain, presult, m_blockSize); pin += m_blockSize; presult += m_blockSize; } } else //ECB mode, not using the Chain { for(i=0,pin=in,presult=result; i<(int)( n/m_blockSize ); i++) { EncryptBlock(pin, presult); pin += m_blockSize; presult += m_blockSize; } } } void CRijndael::Decrypt(char const* in, char* result, size_t n, int iMode) { if(false==m_bKeyInit) throw exception(sm_szErrorMsg1); //n should be > 0 and multiple of m_blockSize if(0==n || n%m_blockSize!=0) throw exception(sm_szErrorMsg2); int i; char const* pin; char* presult; if(CBC == iMode) //CBC mode, using the Chain { for(i=0,pin=in,presult=result; i<(int)( n/m_blockSize ); i++) { DecryptBlock(pin, presult); Xor(presult, m_chain); memcpy(m_chain, pin, m_blockSize); pin += m_blockSize; presult += m_blockSize; } } else if(CFB == iMode) //CFB mode, using the Chain, not using Decrypt() { for(i=0,pin=in,presult=result; i<(int)( n/m_blockSize ); i++) { EncryptBlock(m_chain, presult); //memcpy(presult, pin, m_blockSize); Xor(presult, pin); memcpy(m_chain, pin, m_blockSize); pin += m_blockSize; presult += m_blockSize; } } else //ECB mode, not using the Chain { for(i=0,pin=in,presult=result; i<(int)( n/m_blockSize ); i++) { DecryptBlock(pin, presult); pin += m_blockSize; presult += m_blockSize; } } }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 1391 ] ] ]
e65f41261339d67afba3d3c8283552732e855e15
15732b8e4190ae526dcf99e9ffcee5171ed9bd7e
/INC/application-tcpserver.h
a5cd51989643dd4b33ab50f9d66c2975c73fa9d0
[]
no_license
clovermwliu/whutnetsim
d95c07f77330af8cefe50a04b19a2d5cca23e0ae
924f2625898c4f00147e473a05704f7b91dac0c4
refs/heads/master
2021-01-10T13:10:00.678815
2010-04-14T08:38:01
2010-04-14T08:38:01
48,568,805
0
0
null
null
null
null
UTF-8
C++
false
false
5,565
h
//Copyright (c) 2010, Information Security Institute of Wuhan Universtiy(ISIWhu) //All rights reserved. // //PLEASE READ THIS DOCUMENT CAREFULLY BEFORE UTILIZING THE PROGRAM //BY UTILIZING THIS PROGRAM, YOU AGREE TO BECOME BOUND BY THE TERMS OF //THIS LICENSE. IF YOU DO NOT AGREE TO THE TERMS OF THIS LICENSE, DO //NOT USE THIS PROGRAM OR ANY PORTION THEREOF IN ANY FORM OR MANNER. // //This License allows you to: //1. Make copies and distribute copies of the Program's source code provide that any such copy // clearly displays any and all appropriate copyright notices and disclaimer of warranty as set // forth in this License. //2. Modify the original copy or copies of the Program or any portion thereof ("Modification(s)"). // Modifications may be copied and distributed under the terms and conditions as set forth above. // Any and all modified files must be affixed with prominent notices that you have changed the // files and the date that the changes occurred. //Termination: // If at anytime you are unable to comply with any portion of this License you must immediately // cease use of the Program and all distribution activities involving the Program or any portion // thereof. //Statement: // In this program, part of the code is from the GTNetS project, The Georgia Tech Network // Simulator (GTNetS) is a full-featured network simulation environment that allows researchers in // computer networks to study the behavior of moderate to large scale networks, under a variety of // conditions. Our work have great advance due to this project, Thanks to Dr. George F. Riley from // Georgia Tech Research Corporation. Anyone who wants to study the GTNetS can come to its homepage: // http://www.ece.gatech.edu/research/labs/MANIACS/GTNetS/ // //File Information: // // //File Name: //File Purpose: //Original Author: //Author Organization: //Construct Data: //Modify Author: //Author Organization: //Modify Data: // Georgia Tech Network Simulator - TCP Server Application class // George F. Riley. Georgia Tech, Summer 2002 // Define a TCP Server Application Class // Just sends back the amount of data specified in datapdu, "responseSize" #ifndef __tcp_appserver_h__ #define __tcp_appserver_h__ #include "G_common_defs.h" #include "application-tcp.h" #include "statistics.h" #include "tcp.h" #include "rng.h" //Doc:ClassXRef class TCPServer : public TCPApplication { //Doc:Class Class {\tt TCPServer} creates a simple model of a //Doc:Class request/response //Doc:Class {\tt TCP} server. The server binds to a specified port, and //Doc:Class listens for connection requests from {\tt TCP} peers. The //Doc:Class data received from the peers specifies how much data to send //Doc:Class or receive. public: // Constructor //Doc:Method TCPServer(const TCP& = TCP::Default()); // TCP Type //Doc:Desc Constructor for {\tt TCPServer} objects. Optionally //Doc:Desc specify a reference to any {\tt TCP} variant to use //Doc:Desc for the listening {\tt TCP} endpoint. //Doc:Arg1 A reference to any {\tt TCP} variant to use for //Doc:Arg1 the listening endpoint. //Doc:Method TCPServer(const TCPServer& c); // Copy constructor //Doc:Desc Copy constructor. //Doc:Arg1 {\tt TCPServer} object to copy. // Upcalls from L4 protocol virtual void Receive(Packet*,L4Protocol*,Seq_t); // Data received virtual void Sent(Count_t, L4Protocol*); // Data has been sent virtual void CloseRequest(L4Protocol*); // Close request from peer virtual void Closed(L4Protocol*); // Connection has closed // Specific to TCPServer app //Doc:Method virtual void BindAndListen(Node*, PortId_t); // Bind to node/port //Doc:Desc Bind the application to the specified port and start //Doc:Desc listening for connections. //Doc:Arg1 Node pointer to the node this application is associated with. //Doc:Arg2 Port number to bind to. //Doc:Method virtual void BindAndListen(PortId_t); // Bind to node/port //Doc:Desc Bind the application to the specified port and start //Doc:Desc listening for connections. Node is already known. //Doc:Arg1 Port number to bind to. virtual Application* Copy() const; // Make a copy of application //Doc:Method void SetStatistics(Statistics* s) { stats = s;} //Doc:Desc Set a statistics object to use for statistics collection. //Doc:Desc This application will record the response time of each //Doc:Desc message sent to the statistics object. //Doc:Arg1 Pointer to a statistics object. public: //Doc:Member Count_t totSent; // Total bytes sent //Doc:Desc Count of the total number of bytes sent by this application. //Doc:Member Count_t totAck; // Total bytes acknowledged //Doc:Desc Count of total bytes acknowledged by this application. //Doc:Member Count_t totRx; // Total bytes received //Doc:Desc Count of total bytes received by this application. Statistics* stats; // Stats object for logging response time //Doc:Member Time_t msgStart; // Time message request started //Doc:Desc Time the last message started transmission or receipt. //Doc:Member bool timeKnown; // True if above time is known //Doc:Desc True if the start time of the message is known. }; #endif
[ "pengelmer@f37e807c-cba8-11de-937e-2741d7931076" ]
[ [ [ 1, 138 ] ] ]
76479e082f5e75f8c3b317505120c582d4205804
f9fd733174ef8a8bd07ff9be849431dfc46e541f
/NumberLib/NumbersLib/UpdateableNumber.h
939156bc4a38808c3cf3ace49d4a865d75ba7446
[]
no_license
Jargyle214/specialnumbers
8b33369c2bfb75b324cb70539c5daee19f7bce84
107b4c3022e5febed38136fa09023f66931df77e
refs/heads/master
2021-01-10T16:33:58.894648
2008-09-21T18:56:04
2008-09-21T18:56:04
55,395,227
0
0
null
null
null
null
UTF-8
C++
false
false
1,353
h
#ifndef _UPDATEABLE_NUMBER_H_ #define _UPDATEABLE_NUMBER_H_ namespace luma { namespace numbers { /** Updateable numbers are used when a value is updated regularly, and logic should be performed on every update. This is a typical example of how to use any updateable number: //declaration BufferedNumber<float> filteredSpeed(0.0f, -100.0f, 100.0f, 0.5f); @code // General update method - called every tick void update() { filteredSpeed.setValue(getSpeed()); //update, for example, a GUI widget based on the filteredValue. speedWidget.setDisplayValue(filteredSpeed.getValue()); } @endcode In general, setValue should only be called once per update, but getValue can be called any number of times. @note BufferedStep works like Updateable numbers, although the class does not implement the Updateable interface. @note Boolean values, and enums are also considered "numbers". */ template <class T> class UpdateableNumber { public: /** Get the current value of this AbstractFilteredNumber of the given order. */ virtual T getValue() const = 0; /** Sets a new input value. In general, this function should only be called once per update. */ virtual void setValue(T value, float elapsedTime=TIME_UNIT) = 0; }; }}//namespace #endif //_UPDATEABLE_NUMBER_H_
[ "herman.tulleken@efac63d9-b148-0410-ace2-6f69ea89f809" ]
[ [ [ 1, 57 ] ] ]
8b48cceee144f883ab3528b4c2ddc8f3a064881e
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Common/Base/Monitor/MonitorStreamAnalyzer/hkMonitorStreamAnalyzer.h
97419ff46d171e4087fe27b0d0b03fa2a45786c6
[]
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
17,740
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 HKBASE_MONITOR_STREAM_ANALYZER_H #define HKBASE_MONITOR_STREAM_ANALYZER_H #include <Common/Base/Monitor/hkMonitorStream.h> #include <Common/Base/Container/PointerMap/hkPointerMap.h> #include <Common/Base/Container/Array/hkObjectArray.h> #include <Common/Base/System/Io/OStream/hkOStream.h> extern const hkClass hkMonitorStreamStringMapClass; struct hkMonitorStreamStringMap { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR(HK_MEMORY_CLASS_MONITOR, hkMonitorStreamStringMap); HK_DECLARE_REFLECTION(); struct StringMap { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_BASE_CLASS, hkMonitorStreamStringMap::StringMap ); HK_DECLARE_REFLECTION(); HK_ALIGN(hkUint64 m_id,8); // no ulong in serialization yet, and void* will be zero const char* m_string; }; hkArray<struct StringMap> m_map; }; /// Information about how to read the data from the monitors captured over a /// given frame. You need to fill this structure in per frame captured. /// The timing monitors are setup to capture 2 floats per call. However, /// there are 4 "slots" in the corresponding monitor capture structure here. /// This allows you for example to alternate between i-cache and d-cache misses /// per frame and send them to different slots in the capture. extern const hkClass hkMonitorStreamFrameInfoClass; struct hkMonitorStreamFrameInfo { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_MONITOR, hkMonitorStreamFrameInfo ); HK_DECLARE_REFLECTION(); // To keep the Visual Debugger backward compatible as much as possible, try not to // add any members to this struct. If you do, add them at the end (in the second public section) // (to make the version-ing trivial) as the VDB client does not have version-ing, and serializes this struct // directly. /// The heading for the frame (which will be printed out in the detailed timings file) /// Typically you should not forget to record what timers are being used for, and what units you /// are measuring times in (e.g. usec). const char* m_heading; /// The slot in our monitor capture structure, where the timer 0 should be stored /// If this is set to -1, timer 0 will not get stored. By default this is 0. hkInt32 m_indexOfTimer0; /// The slot in our monitor capture structure, where the timer 1 should be stored /// If this is set to -1, timer 1 will not get stored. By default this is 1. hkInt32 m_indexOfTimer1; /// The index of the absolute time. This should be 0 if timer O is used to /// store the absolute time, 1 if timer 1 is used to store the absolute time /// and -1 if neither timer 0 or timer 1 are used to store absolute time. /// This value is used to draw multiple timer threads to an image. /// By default this is ABSOLUTE_TIME_TIMER_0. enum AbsoluteTimeCounter { ABSOLUTE_TIME_TIMER_0 = 0, ABSOLUTE_TIME_TIMER_1 = 1, ABSOLUTE_TIME_NOT_TIMED = 0xffffffff }; /// Which timer if either is used to measure absolute time hkEnum<AbsoluteTimeCounter,hkUint32> m_absoluteTimeCounter; /// This value is used to multiply the raw data collected by the monitors and written into slot 0 of the /// monitor capture structure. The value should be set depending on what information the monitors are /// collecting for this slot. (e.g. timings, cache misses). For example, if you wish to display timings /// in microseconds you would set this value to (1 / number of clock cycles per microsecond). Using hkBase /// this would be 1e6f / float(hkStopwatch::getTicksPerSecond()); /// By default this is 1.f hkReal m_timerFactor0; /// This value is used to multiply the raw data collected by the monitors and written into slot 1 of the /// monitor capture structure. See comments for m_timerFactor0 for more info. /// By default this is 1.f hkReal m_timerFactor1; public: /// The thread that this frame data came from. This must be between 0 and the number of /// threads passed into the analyzer on construction. /// Only need to set this if you are calling captureFrameDetails(). int m_threadId; /// Set automatically when you call captureFrameDetails. There is no need to initialize this value. int m_frameStreamStart; /// Set automatically when you call captureFrameDetails. There is no need to initialize this value. int m_frameStreamEnd; /// Constructor. Initializes values to defaults as documented. hkMonitorStreamFrameInfo(); }; /// Allows you to capture several frames (generated by hkMonitorStream) /// and convert the data stream into a stream that can be moved across the network. /// Also this class allows you to pretty print the results to a file. class hkMonitorStreamAnalyzer { public: HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR(HK_MEMORY_CLASS_MONITOR, hkMonitorStreamAnalyzer); /////////////////////////////////////////////////////////////////////// // // Constructor, monitor capture, and reset // /////////////////////////////////////////////////////////////////////// /// Create an analyzer given a maximum memory size. This will allocate a block of data /// with this size, and use it to copy monitor information when captureFrameDetails is called. hkMonitorStreamAnalyzer( int maxMemorySize, int numThreads = 1, int numSpus = 0 ); /// This function must be called every frame. It copies the data between monitorStreamBegin and /// monitorStreamEnd, and stores the frame info structure. hkBool captureFrameDetails( const char* monitorStreamBegin, const char* monitorStreamEnd, hkMonitorStreamFrameInfo& info ); /// This allows you to change the number of threads the analyzer captures /// This resets the analyzer. It clears all the arrays, but does not deallocate any data. void resetNumThreads( int numThreads = 1, int numSpus = 0 ); /// This resets the analyzer. It clears all the arrays, but does not deallocate any data. void reset(); /// Get the start of the data stream. /// If the steam is empty, HK_NULL will be returned. char* getStreamBegin(); /////////////////////////////////////////////////////////////////////// // // Utilities to write .txt statistics files // /////////////////////////////////////////////////////////////////////// enum { REPORT_ALL = 0xFF, REPORT_SUMMARIES = 0x07, REPORT_TOTAL = 0x01, REPORT_PERFRAME_TIME = 0x02, REPORT_PERFRAME_SUMMARY = 0x04, REPORT_PERFRAME_DETAIL = 0x08 }; /// Create a user readable statistics file of the raw data. void writeStatistics( hkOstream& outstream, int reportLevel = REPORT_ALL ); /////////////////////////////////////////////////////////////////////// // // Utilities to draw statistics to an image // /////////////////////////////////////////////////////////////////////// /// The input structure for the drawThreadsToTga function. Each thread is drawn as /// a colored bar, with different colors indicating different timers. struct ColorTable { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_MONITOR, hkMonitorStreamAnalyzer::ColorTable ); /// A mapping of timer names to colors struct ColorPair { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_MONITOR, hkMonitorStreamAnalyzer::ColorTable::ColorPair ); const char* m_colorName; int m_color; ColorPair( const char* name, int color ): m_colorName( name), m_color(color){} }; hkArray< struct ColorPair > m_colorPairs; hkInt32 m_defaultColor; hkInt32 findColor( const char* color ); void addColor( const char* name, int color ); }; struct ThreadDrawInput { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_MONITOR, hkMonitorStreamAnalyzer::ThreadDrawInput ); /// The frame to start drawing from (1 by default) hkInt32 m_frameStart; /// The number of frames to draw (1 by default) hkInt32 m_numFrames; /// Layout info hkInt32 m_heightPerThread; /// Layout info hkInt32 m_gapBetweenThreads; hkInt32 m_gapBetweenFrames; /// Number of samples to take per frame hkInt32 m_outputPixelWidth; /// Set this to > 0 if you want to limit the frame duration hkReal m_limitFrameTime; hkReal m_limitStartTime; hkBool m_warnAboutMissingTimers; static int HK_CALL computePerThreadHeightToFit( int textureHeight, int numFrames, int numThreads, int frameGap, int threadGap ); /// A mapping of timer names to colors struct ColorTable* m_colorTable; }; /// Draw the current thread data as held by this analyzer to a .tga file void drawThreadsToTga( const ThreadDrawInput& input, hkOstream& outStream ); /////////////////////////////////////////////////////////////////////// // // Utilities to print timers to a runtime display // /////////////////////////////////////////////////////////////////////// struct Node; /// You can use this function in conjunction with mergeTreesForCombinedThreadSummary, navigateMonitors and printMonitorsToRuntimeDisplay /// to display user navigatable timers on screen. You need to be able to output text to the screen, and capture /// cursor key input to do this. /// This call will create a tree of nodes given a monitor stream start and end. It returns the root node of the tree. /// For multithreaded applications, you will have a monitor stream per thread. You call this on each monitor stream, /// and merge the results together using mergeTreesForRuntimeDisplay. You can then use navigateMonitors and /// printMonitorsToRuntimeDisplay to view the combined trees. static Node* HK_CALL makeStatisticsTreeForSingleFrame( const char* frameStart, const char* frameEnd, const hkMonitorStreamFrameInfo& info, const char* rootNodeName = "/", hkBool reuseNodesIfPossible = true ); /// Given two trees, this function takes all the nodes in the subTree and merges them into the main tree. The sourceTimerId /// describes which slot in the subTree nodes the time is stored. This corresponds with your monitor setup, but is usually 0. /// The destTimerId describes which slot in the main tree nodes you wish to write. There are 4 slots, so this value must be /// between 0 and 3. If a node exists in the subTree but not in mainTree it is created. The smoothingFactor describes /// how the value is smoothed as it changes over time. Values closer to 1 smooth the timers more. 0 is unsmoothed. static void HK_CALL mergeTreesForCombinedThreadSummary( Node* mainTree, Node* subTree, int destTimerId, int sourceTimerId = 0, hkReal smoothingFactor = .93f ); /// Set these values from your input device. This is used as an input to navigateMonitors struct CursorKeys { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_MONITOR, hkMonitorStreamAnalyzer::CursorKeys ); /// up hkBool m_upPressed; /// down hkBool m_downPressed; /// left hkBool m_leftPressed; /// right hkBool m_rightPressed; }; /// This function returns the new active node, given the current active node and the cursor keys. static Node* HK_CALL navigateMonitors( const CursorKeys& keys, Node* activeNodeIn ); /// The options structure for showCombinedThreadSummaryForSingleFrame struct CombinedThreadSummaryOptions { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_MONITOR, hkMonitorStreamAnalyzer::CombinedThreadSummaryOptions ); /// Spacing info int m_indentationToFirstTimerValue; /// Spacing info int m_timerColumnWidth; /// Spacing info int m_tabSpacingForTimerNames; /// Spacing info int m_tabSpacingForTimerValues; /// If set, only nodes with user flags set will be displayed. User flags are set by the navigateMonitors function bool m_displayPartialTree; /// The current selected node - only set if m_displayPartialTree is true Node* m_activeNode; /// Only set if m_displayPartialTree is true char m_rightArrowChar; /// Only set if m_displayPartialTree is true char m_downArrowChar; }; /// This function prints the monitor tree to an hkOstream. You can create an hkOstream from an array of char, /// then print this array to the screen, or to file. The rootNode is the root of the tree, and the active node is the /// current selected node, returned by navigateMonitors. The numThreads is the number of fields (from 1 to 4) /// to print. The unexpanded and expanded variables allow you to insert your own graphics for these markers. static void HK_CALL showCombinedThreadSummaryForSingleFrame( Node* node, int numThreads, int numSpus, hkOstream& os, CombinedThreadSummaryOptions& options ); public: // // Static internal utility methods and data used for the above functions // // 2 ppu and 6 spu threads, or 2 QuadCores. // The higher this number the more mem is used during timer analysis enum { NUM_VALUES = 8}; /// Data to store the parsed results of a capture struct Node { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_MONITOR, Node ); enum NodeType { NODE_TYPE_TIMER, NODE_TYPE_DIRECTORY, NODE_TYPE_SINGLE, }; hkReal m_value[NUM_VALUES]; hkUint16 m_count[NUM_VALUES]; hkArray<struct Node*> m_children; double m_absoluteStartTime; // this needs double precission Node* m_parent; const char* m_name; hkUint32 m_userFlags; hkEnum<NodeType,hkUint32> m_type; Node(Node* parent, const char* name, NodeType type ); Node() {} void setTimers( const hkMonitorStreamFrameInfo& frameInfo, const hkMonitorStream::TimerCommand& start, const hkMonitorStream::TimerCommand& end); ~Node(); }; static int HK_CALL findMaxTimerNameIndent( hkMonitorStreamAnalyzer::Node* node, int recursionDepth, int spacing, bool displayPartialTree ); static void HK_CALL showCombinedThreadSummaryRec( hkOstream& os, hkMonitorStreamAnalyzer::Node* node, int recursionDepth, int numThreads, int numSpus, const CombinedThreadSummaryOptions& options ); Node* HK_CALL makeStatisticsTreeForMultipleFrames( int threadId, hkBool reuseNodesIfPossible = false); void checkAllThreadsCapturedSameNumFrames() const; static void HK_CALL writeStatisticsDetails( hkOstream& outstream, hkArray<Node*>& nodes, int numThreads, int numSpus, int reportLevel, const char* nodeIdForFrameOverview = "", bool showMultithreadedSummary = false ); static void HK_CALL extractStringMap( const char* frameStart, const char* frameEnd, hkPointerMap<const void*, const char*>& map ); static void HK_CALL applyStringMap( const char* frameStart, const char* frameEnd, const hkPointerMap<const void*, const char*>& map, hkBool endianSwap ); struct SampleInfo { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_MONITOR, hkMonitorStreamAnalyzer::SampleInfo ); hkReal m_maxSampleTime; }; /// called by drawThreadsToTga (and the VDB). Call hkDeallocate on the data when you are done. Always has 4 bytes per pixel. static void HK_CALL writeStatisticsDetailsToTexture( hkArray<Node*>& nodes, const ThreadDrawInput& input, hkObjectArray< hkArray< hkMonitorStreamFrameInfo > >& frameInfos, int*& textureData, int& height, SampleInfo* sampleInfo = HK_NULL ); /// called by drawThreadsToTga (and the VDB). Calls the above and writes it in a simple TARGA format. static void HK_CALL writeStatisticsDetailsToTga( hkArray<Node*>& nodes, const ThreadDrawInput& input, hkObjectArray< hkArray< hkMonitorStreamFrameInfo > >& frameInfos, hkOstream& outStream, SampleInfo* sampleInfo = HK_NULL ); static Node* HK_CALL reverseLookupNodeAtTgaSample( int x, int y, hkArray<Node*>& nodes, const ThreadDrawInput& input, hkObjectArray< hkArray< hkMonitorStreamFrameInfo > >& frameInfos ); static void HK_CALL getTimerLimits( hkArray<Node*>& nodeList, const ThreadDrawInput& input, hkObjectArray< hkArray< hkMonitorStreamFrameInfo > >& frameInfos, hkReal& maxFrameTime, hkArray<hkReal>& startTimes); protected: // // Data for multiple frames // hkObjectArray< hkArray< hkMonitorStreamFrameInfo > > m_frameInfos; hkArray<char> m_data; int m_numThreads; int m_numSpus; public: static hkReal g_lastFrameTime; const char* m_nodeIdForFrameOverview; }; #endif // HKBASE_MONITOR_STREAM_ANALYZER_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, 409 ] ] ]
eefa79e11e53c5ad16f4e4779d404f2b6ca69b71
34c65c99c538c020e4ed644d88b9b5095095425e
/Singleton.h
e5203bfa3c51817c45bd06a7dadedb07d3045401
[]
no_license
rpmessner/Marbles
c30947233fa25ad840f9a3ce308d5b88e367c516
d1108b5eb7f6b3ccde20b78803ad5b6b0a63041f
refs/heads/master
2016-09-06T01:50:35.745908
2011-02-24T23:47:39
2011-02-24T23:47:39
1,408,878
0
0
null
null
null
null
UTF-8
C++
false
false
1,390
h
/* Copyright (C) Scott Bilas, 2000. * All rights reserved worldwide. * * This software is provided "as is" without express or implied * warranties. You may freely copy and compile this source into * applications you distribute provided that the copyright text * below is included in the resulting source code, for example: * "Portions Copyright (C) Scott Bilas, 2000" */ #ifndef SINGLETON_H #define SINGLETON_H #include <cassert> template <typename T> class Singleton { static T* ms_Singleton; public: Singleton( void ) { assert( !ms_Singleton ); int offset = (int)(T*)1 - (int)(Singleton <T>*)(T*)1; ms_Singleton = (T*)((int)this + offset); } ~Singleton( void ) { assert( ms_Singleton ); ms_Singleton = 0; } static T& Instance( void ) { assert( ms_Singleton ); return ( *ms_Singleton ); } static T* InstancePtr( void ) { return ( ms_Singleton ); } }; template <typename T> T* Singleton <T>::ms_Singleton = 0; #endif // Sample usage: // /* class TextureMgr : public Singleton <TextureMgr> { public: Texture* GetTexture( const char* name ); // ... }; #define g_TextureMgr TextureMgr::GetSingleton() void SomeFunction( void ) { Texture* stone1 = TextureMgr::GetSingleton().GetTexture( "stone1" ); Texture* wood6 = g_TextureMgr.GetTexture( "wood6" ); // ... } */
[ [ [ 1, 60 ] ] ]
2b5d63c24d3e0876b20796fced30e8bfa9c797e9
83ed25c6e6b33b2fabd4f81bf91d5fae9e18519c
/code/AssimpPCH.cpp
7d502a6e78ab9364303dd1ac39fd39be36113ead
[ "BSD-3-Clause" ]
permissive
spring/assimp
fb53b91228843f7677fe8ec18b61d7b5886a6fd3
db29c9a20d0dfa9f98c8fd473824bba5a895ae9e
refs/heads/master
2021-01-17T23:19:56.511185
2011-11-08T12:15:18
2011-11-08T12:15:18
2,017,841
1
1
null
null
null
null
UTF-8
C++
false
false
3,740
cpp
// Actually just a dummy, used by the compiler to build the precompiled header. #include "AssimpPCH.h" #include "./../include/aiVersion.h" // -------------------------------------------------------------------------------- // Legal information string - dont't remove from image! static const char* LEGAL_INFORMATION = "Open Asset Import Library (Assimp).\n" "A free C/C++ library to import various 3D file formats into applications\n\n" "(c) 2008-2010, ASSIMP Development Team\n" "License under the terms and conditions of the 3-clause BSD license\n" "http://assimp.sourceforge.net\n" ; // ------------------------------------------------------------------------------------------------ // Get legal string ASSIMP_API const char* aiGetLegalString () { return LEGAL_INFORMATION; } // ------------------------------------------------------------------------------------------------ // Get Assimp minor version ASSIMP_API unsigned int aiGetVersionMinor () { return 0; } // ------------------------------------------------------------------------------------------------ // Get Assimp major version ASSIMP_API unsigned int aiGetVersionMajor () { return 2; } // ------------------------------------------------------------------------------------------------ // Get flags used for compilation ASSIMP_API unsigned int aiGetCompileFlags () { unsigned int flags = 0; #ifdef ASSIMP_BUILD_BOOST_WORKAROUND flags |= ASSIMP_CFLAGS_NOBOOST; #endif #ifdef ASSIMP_BUILD_SINGLETHREADED flags |= ASSIMP_CFLAGS_SINGLETHREADED; #endif #ifdef ASSIMP_BUILD_DEBUG flags |= ASSIMP_CFLAGS_DEBUG; #endif #ifdef ASSIMP_BUILD_DLL_EXPORT flags |= ASSIMP_CFLAGS_SHARED; #endif #ifdef _STLPORT_VERSION flags |= ASSIMP_CFLAGS_STLPORT; #endif return flags; } // include current build revision, which is even updated from time to time -- :-) #include "../revision.h" // ------------------------------------------------------------------------------------------------ ASSIMP_API unsigned int aiGetVersionRevision () { return SVNRevision; } // ------------------------------------------------------------------------------------------------ aiScene::aiScene() : mFlags() , mRootNode() , mNumMeshes() , mMeshes() , mNumMaterials() , mMaterials() , mNumAnimations() , mAnimations() , mNumTextures() , mTextures() , mNumLights() , mLights() , mNumCameras() , mCameras() , mPrivate(new Assimp::ScenePrivateData()) { } // ------------------------------------------------------------------------------------------------ aiScene::~aiScene() { // delete all sub-objects recursively delete mRootNode; // To make sure we won't crash if the data is invalid it's // much better to check whether both mNumXXX and mXXX are // valid instead of relying on just one of them. if (mNumMeshes && mMeshes) for( unsigned int a = 0; a < mNumMeshes; a++) delete mMeshes[a]; delete [] mMeshes; if (mNumMaterials && mMaterials) for( unsigned int a = 0; a < mNumMaterials; a++) delete mMaterials[a]; delete [] mMaterials; if (mNumAnimations && mAnimations) for( unsigned int a = 0; a < mNumAnimations; a++) delete mAnimations[a]; delete [] mAnimations; if (mNumTextures && mTextures) for( unsigned int a = 0; a < mNumTextures; a++) delete mTextures[a]; delete [] mTextures; if (mNumLights && mLights) for( unsigned int a = 0; a < mNumLights; a++) delete mLights[a]; delete [] mLights; if (mNumCameras && mCameras) for( unsigned int a = 0; a < mNumCameras; a++) delete mCameras[a]; delete [] mCameras; delete static_cast<Assimp::ScenePrivateData*>( mPrivate ); }
[ "aramis_acg@67173fc5-114c-0410-ac8e-9d2fd5bffc1f" ]
[ [ [ 1, 132 ] ] ]
74e1bc4f591347227a6ed669ff1bf5c677eff7f8
28aa23d9cb8f5f4e8c2239c70ef0f8f6ec6d17bc
/mytesgnikrow --username hotga2801/SELAB/Dongle/Source/DemoAES_encryption/DemoAES_encryption/stdafx.cpp
28d20325963e61a902618ff01212e5b4e2b905d1
[]
no_license
taicent/mytesgnikrow
09aed8836e1297a24bef0f18dadd9e9a78ec8e8b
9264faa662454484ade7137ee8a0794e00bf762f
refs/heads/master
2020-04-06T04:25:30.075548
2011-02-17T13:37:16
2011-02-17T13:37:16
34,991,750
0
0
null
null
null
null
UTF-8
C++
false
false
305
cpp
// stdafx.cpp : source file that includes just the standard includes // DemoAES_encryption.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
[ "hotga2801@ecd9aaca-b8df-3bf4-dfa7-576663c5f076" ]
[ [ [ 1, 8 ] ] ]
8731a340431a71a5f4d980f49b11713ad36f3f30
e028013b5dfe8262af326be861b344e36752b4a3
/LD130_GUI/MainWindow.cpp
e2fe42b38df69bb90659e9d297168bc16e08cba2
[]
no_license
HappyHunter/LD130
3a769300e331213da8a64d341e30269dd0afb961
60a2a25c4f4388915814f59d9c47930b39f4d10d
refs/heads/master
2019-01-02T04:34:29.521971
2011-08-15T12:37:30
2011-08-15T12:37:30
1,172,890
0
0
null
null
null
null
UTF-8
C++
false
false
34,371
cpp
//////////////////////////////////////////////////////////////////// // // Alexandr Filenkov 2010 // //////////////////////////////////////////////////////////////////// //--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include <cstdio> #include <ctime> #include <cassert> #include "parser.h" #include "MainWindow.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma link "RzPanel" #pragma link "RzSplit" #pragma link "RzTrkBar" #pragma link "RzEdit" #pragma link "RzButton" #pragma link "RzLine" #pragma link "RzRadChk" #pragma link "RzLabel" #pragma link "RzCmboBx" #pragma link "RzLstBox" #pragma link "RzTabs" #pragma link "RzRadGrp" #pragma link "RzStatus" #pragma link "cxContainer" #pragma link "cxControls" #pragma link "cxEdit" #pragma link "cxMaskEdit" #pragma link "cxTextEdit" #pragma link "RzCommon" #pragma link "RzSpnEdt" #pragma resource "*.dfm" TFormMainWindow *FormMainWindow; #include "CommonData.h" #include "ComPortConfig.h" using namespace std; //--------------------------------------------------------------------------- __fastcall TFormMainWindow::TFormMainWindow(TComponent* Owner) : TForm(Owner) , m_updateActiveBank (false) { m_headControlInfo.addControlGroup (0, edChanel1Head1, tbChanel1Head1); m_headControlInfo.addControlGroup (0, edChanel2Head1, tbChanel2Head1); m_headControlInfo.addControlGroup (0, edChanel3Head1, tbChanel3Head1); m_headControlInfo.addControlGroup (0, edChanel4Head1, tbChanel4Head1); m_headControlInfo.addControlGroup (0, edVoltageHead1, tbVoltageHead1); m_headControlInfo.addControlGroup (0, edWidthHead1, 0); m_headControlInfo.addControlGroup (0, edDelayHead1, 0); m_headControlInfo.addControlGroup (1, edChanel1Head2, tbChanel1Head2); m_headControlInfo.addControlGroup (1, edChanel2Head2, tbChanel2Head2); m_headControlInfo.addControlGroup (1, edChanel3Head2, tbChanel3Head2); m_headControlInfo.addControlGroup (1, edChanel4Head2, tbChanel4Head2); m_headControlInfo.addControlGroup (1, edVoltageHead2, tbVoltageHead2); m_headControlInfo.addControlGroup (1, edWidthHead2, 0); m_headControlInfo.addControlGroup (1, edDelayHead2, 0); } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::TrackBarChange(TObject* Sender) { TRzTrackBar* pTrackBar = dynamic_cast<TRzTrackBar*>(Sender); if (THeadControlGroup* pGroup = m_headControlInfo.findHeadControlGroupByTrackBar (pTrackBar)) { if (!m_headControlInfo.m_powerChangingHead[pGroup->m_headIndex]) { m_headControlInfo.m_powerChangingHead[pGroup->m_headIndex] = true; if (pGroup->m_pEdit) pGroup->m_pEdit->Value = pTrackBar->Position; //update the associated trackbar, if specified m_headControlInfo.m_updateHead[pGroup->m_headIndex] = true; m_headControlInfo.m_powerChangingHead[pGroup->m_headIndex] = false; } } } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::EditChange(TObject* Sender) { TRzNumericEdit* pEdit = dynamic_cast<TRzNumericEdit*>(Sender); if (THeadControlGroup* pGroup = m_headControlInfo.findHeadControlGroupByEdit (pEdit)) { if (!m_headControlInfo.m_powerChangingHead[pGroup->m_headIndex]) { m_headControlInfo.m_powerChangingHead[pGroup->m_headIndex] = true; if (pGroup->m_pTrackBar) pGroup->m_pTrackBar->Position = pEdit->Value; //update the associated edit box, if specified m_headControlInfo.m_updateHead[pGroup->m_headIndex] = true; m_headControlInfo.m_powerChangingHead[pGroup->m_headIndex] = false; } } } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::TimerUpdateTimer(TObject *Sender) { const int bankIndex = rzchkEnableBanks->Checked ? RzTabBanks->TabIndex+1 : 1; bool bUpdated1 = false; if (m_headControlInfo.m_updateHead[0]) { m_headControlInfo.m_updateHead[0] = false; int triggerMode = TriggerRaising; if (rbRaisingTriggerHead1->Checked) { triggerMode = TriggerRaising; } else if (rbFallingTriggerHead1->Checked) { triggerMode = TriggerFalling; } else if (rzDCModeHead1->Checked) { triggerMode = TriggerDC; } // limit the amplifier to 1 in DC mode int theAmplifier = triggerMode != TriggerDC ? grHead1Amplifier->ItemIndex + 1 : 1; TCommandErrorOutput retCode = m_LD130.setBankHeadData( bankIndex, 1, // 1 - head 1, 2 - Head 2 int(edVoltageHead1->IntValue), // 0 - 100 Volts int(edChanel1Head1->Value*100.f), // 0 - 100 00% with fixed decimal point at 2 digits int(edChanel2Head1->Value*100.f), // for example the power of 35.23% will be sent as 3523 int(edChanel3Head1->Value*100.f), // the power of 99.00% will be sent as 9900 int(edChanel4Head1->Value*100.f), // the power of 100.00% will be sent as 10000 int(edDelayHead1->IntValue), // the delay of outcoming light strobe in microseconds int(edWidthHead1->IntValue), // the duration of outcoming light strobe in microseconds triggerMode, // the edge of incoming trigger to start counting, 0 - raising, 1 - falling 3, // the ID of the trigger this output head will trigger on. 1 - Trigger 1, 2 - Trigger 2, 3 - Trigger 1 or 2 theAmplifier // the amplification value 1-5 ); if (retCode.hasError()) { lbLog->Items->Add(AnsiString((char*)retCode.m_errorDescription)); lbFullLog->Items->Add(AnsiString((char*)retCode.m_errorDescription)); } bUpdated1 = true; } bool bUpdated2 = false; if (m_headControlInfo.m_updateHead[1]) { m_headControlInfo.m_updateHead[1] = false; int triggerMode = TriggerRaising; if (rbRaisingTriggerHead2->Checked) { triggerMode = TriggerRaising; } else if (rbFallingTriggerHead2->Checked) { triggerMode = TriggerFalling; } else if (rzDCModeHead2->Checked) { triggerMode = TriggerDC; } // limit the amplifier to 1 in DC mode int theAmplifier = triggerMode != TriggerDC ? grHead2Amplifier->ItemIndex + 1 : 1; TCommandErrorOutput retCode = m_LD130.setBankHeadData( bankIndex, 2, // 1 - head 1, 2 - Head 2 int(edVoltageHead2->IntValue), // 0 - 100 Volts int(edChanel1Head2->Value*100.f), // 0 - 100 00% with fixed decimal point at 2 digits int(edChanel2Head2->Value*100.f), // for example the power of 35.23% will be sent as 3523 int(edChanel3Head2->Value*100.f), // the power of 99.00% will be sent as 9900 int(edChanel4Head2->Value*100.f), // the power of 100.00% will be sent as 10000 int(edDelayHead2->IntValue), // the delay of outcoming light strobe in microseconds int(edWidthHead2->IntValue), // the duration of outcoming light strobe in microseconds triggerMode, // the edge of incoming trigger to start counting, 0 - raising, 1 - falling 3, // the ID of the trigger this output head will trigger on. 1 - Trigger 1, 2 - Trigger 2, 3 - Trigger 1 or 2 theAmplifier // the amplification value 1-5 ); if (retCode.hasError()) { lbLog->Items->Add(AnsiString((char*)retCode.m_errorDescription)); lbFullLog->Items->Add(AnsiString((char*)retCode.m_errorDescription)); } bUpdated2 = true; } if (m_updateActiveBank) { m_updateActiveBank = false; m_LD130.setActiveBank(RzTabBanks->TabIndex+1); bUpdated1 = true; bUpdated2 = true; } if (bUpdated1) { m_LD130.getHeadStatus(1); } if (bUpdated2) { m_LD130.getHeadStatus(2); } // m_LD130.getStatus(); } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::actTriggerHead1Execute(TObject *Sender) { m_headControlInfo.m_updateHead[0] = true; } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::actTriggerHead1Update(TObject *Sender) { actTriggerHead1->Enabled = !cbAutoTrigger->Checked; } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::actTriggerHead2Execute(TObject *Sender) { m_headControlInfo.m_updateHead[1] = true; } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::actTriggerHead2Update(TObject *Sender) { actTriggerHead2->Enabled = !cbAutoTrigger->Checked; } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::TimerAutoTriggerHead1Timer(TObject *Sender) { actTriggerHead1Execute(Sender); } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::cbAutoTriggerClick(TObject *Sender) { if (cbAutoTrigger->Checked) { RzBtnSoftTrigger->GroupIndex = 1; } else { RzBtnSoftTrigger->GroupIndex = 0; RzBtnSoftTrigger->Caption = "Trigger"; } } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::cbComPortCloseUp(TObject *Sender) { RzStatusOperation->Caption="Opening COM Port..."; RzFieldFirmwareVersion->Caption = ""; RzFieldActiveBank->Caption = ""; int theSpeed = 115200; AnsiString theComPort(0); if (cbComPort->ItemIndex >= 0) { theComPort = cbComPort->Values->Strings[cbComPort->ItemIndex]; char str2[64] = {0}; _snprintf (str2, sizeof(str2), "COM%s", theComPort.c_str()); theSpeed = RzRegIniFile->ReadInteger(str2, "Speed", 115200); } TCommandErrorOutput retCode = m_LD130.init(theComPort.ToInt(), theSpeed, &OnLogEvent, this); if (retCode.hasError()) { RzFieldFirmwareVersion->Caption = "ERROR"; } else { string verMajor, verMinor,verBuild; m_LD130.getVersion(verMajor, verMinor,verBuild); RzFieldFirmwareVersion->Caption = AnsiString(verMajor.c_str()) +"." + AnsiString(verMinor.c_str()) + "." + AnsiString(verBuild.c_str()); initControlsFromController(); } RzStatusOperation->Caption=""; } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::rbRaisingTriggerHead1Click(TObject *Sender) { m_headControlInfo.m_updateHead[0] = true; grHead1Amplifier->Enabled = true; } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::rbFallingTriggerHead1Click(TObject *Sender) { m_headControlInfo.m_updateHead[0] = true; grHead1Amplifier->Enabled = true; } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::rzDCModeHead1Click(TObject *Sender) { m_headControlInfo.m_updateHead[0] = true; grHead1Amplifier->ItemIndex = 0; grHead1Amplifier->Enabled = false; } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::TabSheet2Show(TObject *Sender) { RzBankSequence->Enabled = rzchkEnableBanks->Checked; RzbrUseTrigger1->Enabled = rzchkEnableBanks->Checked; RzrbUseNextSequenceInput->Enabled = rzchkEnableBanks->Checked; } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::rzchkEnableBanksClick(TObject *Sender) { RzBankSequence->Enabled = rzchkEnableBanks->Checked; RzbrUseTrigger1->Enabled = rzchkEnableBanks->Checked; RzrbUseNextSequenceInput->Enabled = rzchkEnableBanks->Checked; RzTabBanks->Tabs->Items[1]->Visible = rzchkEnableBanks->Checked; RzTabBanks->Tabs->Items[2]->Visible = rzchkEnableBanks->Checked; RzTabBanks->Tabs->Items[3]->Visible = rzchkEnableBanks->Checked; } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::TabSheet1Show(TObject *Sender) { RzTabBanks->Tabs->Items[1]->Visible = rzchkEnableBanks->Checked; RzTabBanks->Tabs->Items[2]->Visible = rzchkEnableBanks->Checked; RzTabBanks->Tabs->Items[3]->Visible = rzchkEnableBanks->Checked; rbRaisingTriggerHead2->Enabled = !rzchkEnableBanks->Checked; rbFallingTriggerHead2->Enabled = !rzchkEnableBanks->Checked; rzDCModeHead2->Enabled = !rzchkEnableBanks->Checked; } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::rbRaisingTriggerHead2Click(TObject *Sender) { m_headControlInfo.m_updateHead[1] = true; grHead2Amplifier->Enabled = true; } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::rbFallingTriggerHead2Click(TObject *Sender) { m_headControlInfo.m_updateHead[1] = true; grHead2Amplifier->Enabled = true; } //--------------------------------------------------------------------------- void TFormMainWindow::initControlsFromController() { updateControlsForSelectedBank(); } //--------------------------------------------------------------------------- void TFormMainWindow::updateControlsForSelectedBank() { //------------------------------------------------ // Head 1 //------------------------------------------------ TBankHeadData theHeadData = m_LD130.getBankHeadData(RzTabBanks->TabIndex+1, 1); setTrackBarSafely(tbVoltageHead1, theHeadData.m_voltage); setPowerSafely(tbChanel1Head1, edChanel1Head1, theHeadData.m_powerChanel1/100.f); // 0 - 100 00% with fixed decimal point at 2 digits setPowerSafely(tbChanel2Head1, edChanel2Head1, theHeadData.m_powerChanel2/100.f); // for example the power of 35.23% will be sent as 3523 setPowerSafely(tbChanel3Head1, edChanel3Head1, theHeadData.m_powerChanel3/100.f); // the power of 99.00% will be sent as 9900 setPowerSafely(tbChanel4Head1, edChanel4Head1, theHeadData.m_powerChanel4/100.f); // the power of 100.00% will be sent as 10000 setNumericEditSafely(edDelayHead1, theHeadData.m_strobeDelay); setNumericEditSafely(edWidthHead1, theHeadData.m_strobeWidth); switch (theHeadData.m_triggerEdge) { case TriggerRaising: rbRaisingTriggerHead1->Checked = true; rbFallingTriggerHead1->Checked = false; rzDCModeHead1->Checked = false; break; case TriggerFalling: rbRaisingTriggerHead1->Checked = false; rbFallingTriggerHead1->Checked = true; rzDCModeHead1->Checked = false; break; case TriggerDC: rbFallingTriggerHead1->Checked = false; rbRaisingTriggerHead1->Checked = false; rzDCModeHead1->Checked = true; break; } switch (theHeadData.m_triggerId) { case 1: rgTriggerSourceHead1->ItemIndex = 1; break; case 2: rgTriggerSourceHead1->ItemIndex = 2; break; case 3: rgTriggerSourceHead1->ItemIndex = 3; break; } if (theHeadData.m_chanelAmplifier > 0 && theHeadData.m_chanelAmplifier <= 5) grHead1Amplifier->ItemIndex = theHeadData.m_chanelAmplifier - 1; else grHead1Amplifier->ItemIndex = 0; THeadStatus theHeadStatus = m_LD130.getHeadStatus(1); pnlOverCurrentHead1Chanel1->Color = ((m_LD130.getActiveBank() -1) == RzTabBanks->TabIndex) ? (theHeadStatus.m_statusChanel1 ? clRed : clGreen) : clBackground; pnlOverCurrentHead1Chanel2->Color = ((m_LD130.getActiveBank() -1) == RzTabBanks->TabIndex) ? (theHeadStatus.m_statusChanel2 ? clRed : clGreen) : clBackground; pnlOverCurrentHead1Chanel3->Color = ((m_LD130.getActiveBank() -1) == RzTabBanks->TabIndex) ? (theHeadStatus.m_statusChanel3 ? clRed : clGreen) : clBackground; pnlOverCurrentHead1Chanel4->Color = ((m_LD130.getActiveBank() -1) == RzTabBanks->TabIndex) ? (theHeadStatus.m_statusChanel4 ? clRed : clGreen) : clBackground; //------------------------------------------------ // Head 2 //------------------------------------------------ theHeadData = m_LD130.getBankHeadData(RzTabBanks->TabIndex+1, 2); setTrackBarSafely(tbVoltageHead2, theHeadData.m_voltage); setPowerSafely(tbChanel1Head2, edChanel1Head2, theHeadData.m_powerChanel1/100.f); // 0 - 100 00% with fixed decimal point at 2 digits setPowerSafely(tbChanel2Head2, edChanel2Head2, theHeadData.m_powerChanel2/100.f); // for example the power of 35.23% will be sent as 3523 setPowerSafely(tbChanel3Head2, edChanel3Head2, theHeadData.m_powerChanel3/100.f); // the power of 99.00% will be sent as 9900 setPowerSafely(tbChanel4Head2, edChanel4Head2, theHeadData.m_powerChanel4/100.f); // the power of 100.00% will be sent as 10000 setNumericEditSafely(edDelayHead2, theHeadData.m_strobeDelay); setNumericEditSafely(edWidthHead2, theHeadData.m_strobeWidth); switch (theHeadData.m_triggerEdge) { case TriggerRaising: rbRaisingTriggerHead2->Checked = true; rbFallingTriggerHead2->Checked = false; rzDCModeHead2->Checked = false; break; case TriggerFalling: rbRaisingTriggerHead2->Checked = false; rbFallingTriggerHead2->Checked = true; rzDCModeHead2->Checked = false; break; case TriggerDC: rbFallingTriggerHead2->Checked = false; rbRaisingTriggerHead2->Checked = false; rzDCModeHead2->Checked = true; break; } switch (theHeadData.m_triggerId) { case 1: rgTriggerSourceHead2->ItemIndex = 1; break; case 2: rgTriggerSourceHead2->ItemIndex = 2; break; case 3: rgTriggerSourceHead2->ItemIndex = 3; break; } if (theHeadData.m_chanelAmplifier > 0 && theHeadData.m_chanelAmplifier <= 5) grHead2Amplifier->ItemIndex = theHeadData.m_chanelAmplifier - 1; else grHead2Amplifier->ItemIndex = 0; theHeadStatus = m_LD130.getHeadStatus(2); pnlOverCurrentHead2Chanel1->Color = ((m_LD130.getActiveBank() -1) == RzTabBanks->TabIndex) ? (theHeadStatus.m_statusChanel1 ? clRed : clGreen) : clBackground; pnlOverCurrentHead2Chanel2->Color = ((m_LD130.getActiveBank() -1) == RzTabBanks->TabIndex) ? (theHeadStatus.m_statusChanel2 ? clRed : clGreen) : clBackground; pnlOverCurrentHead2Chanel3->Color = ((m_LD130.getActiveBank() -1) == RzTabBanks->TabIndex) ? (theHeadStatus.m_statusChanel3 ? clRed : clGreen) : clBackground; pnlOverCurrentHead2Chanel4->Color = ((m_LD130.getActiveBank() -1) == RzTabBanks->TabIndex) ? (theHeadStatus.m_statusChanel4 ? clRed : clGreen) : clBackground; m_headControlInfo.m_updateHead[0] = false; m_headControlInfo.m_updateHead[1] = false; } //--------------------------------------------------------------------------- void TFormMainWindow::setTrackBarSafely(TRzTrackBar * pTrackBar, int newValue) { if (!pTrackBar) return ; if (newValue < pTrackBar->Min) newValue = pTrackBar->Min; if (newValue > pTrackBar->Max) newValue = pTrackBar->Max; pTrackBar->Position = newValue; } //--------------------------------------------------------------------------- void TFormMainWindow::setNumericEditSafely(TRzNumericEdit* pEdit, int newValue) { if (!pEdit) return ; if (newValue < pEdit->Min) newValue = pEdit->Min; if (newValue > pEdit->Max) newValue = pEdit->Max; pEdit->Value = newValue; } //--------------------------------------------------------------------------- void TFormMainWindow::setPowerSafely(TRzTrackBar * pTrackBar, TRzNumericEdit* pEdit, float newValue) { if (!pTrackBar || !pEdit) return ; if (newValue < pTrackBar->Min) newValue = pTrackBar->Min; if (newValue > pTrackBar->Max) newValue = pTrackBar->Max; // pTrackBar->Position = newValue; pEdit->Value = newValue; } void __fastcall TFormMainWindow::grHead1AmplifierChanging(TObject *Sender, int NewIndex, bool &AllowChange) { m_headControlInfo.m_updateHead[0] = true; } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::FormShow(TObject *Sender) { RzPanelVersion->Caption = RzPanelVersion->Caption + RzVersionInfo->FileVersion; RzPageControlParameters->ActivePage = TabSheet1; rzRefreshClick(Sender); } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::TimerAutoTriggerTimer(TObject *Sender) { m_LD130.softTrig(); } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::RzBtnSoftTriggerClick(TObject *Sender) { if (RzBtnSoftTrigger->GroupIndex == 0) { m_LD130.softTrig(); } else { if (RzBtnSoftTrigger->Down) { TimerAutoTrigger->Interval = edAutoTriggerPeriod->IntValue; TimerAutoTrigger->Enabled = true; RzBtnSoftTrigger->Caption = "Trigger ON"; } else { TimerAutoTrigger->Enabled = false; RzBtnSoftTrigger->Caption = "Trigger OFF"; } } } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::RzTabBanksChange(TObject *Sender) { updateControlsForSelectedBank(); actActivateBank->Update(); } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::rzbtnSendSequenceClick(TObject *Sender) { string theValue; for (int iStr = 1; iStr <= RzBankSequence->Text.Length(); ++iStr) { if (isdigit(RzBankSequence->Text[iStr])) { theValue += RzBankSequence->Text[iStr]; } } m_LD130.setSequence(theValue); } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::btnComConfigClick(TObject *Sender) { // FormComPortConfig->m_comPort = cbComPort->ItemIndex; // if (FormComPortConfig->ShowModal() == mrOk && FormComPortConfig->m_newSpeed) { // // TCmdSetPortSpeed cmd; // cmd.m_UartID = m_UartID; // cmd.m_baudRate = FormComPortConfig->m_newSpeed; // TCmdPortSpeed cmdReply; // TCommandErrorOutput errCode = sendCommand(&cmd, sizeof(cmd), &cmdReply, sizeof(cmdReply)); // if (errCode.m_command == 0) { // DCB dcb; // if (GetCommState(m_hComPort, &dcb)) { // dcb.BaudRate = FormComPortConfig->m_newSpeed; // set the baud rate // if (!SetCommState(m_hComPort, &dcb)) { // ; // log the error // } // } // // } // } } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::TimerUpdateGUITimer(TObject *Sender) { if (m_LD130.isConnected()) { unsigned short activeBank = m_LD130.getActiveBank(); RzFieldActiveBank->Caption = "Active Bank:" + AnsiString(activeBank); } } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::actStoreToEPROMExecute(TObject *Sender) { // TCmdWriteParametersToEPROM cmd; // TCmdEPROMOperationDone cmdReply; // // cmd.m_flags = ((rzchkEnableBanks->Checked) ? fifUseBanks : 0); // TCommandErrorOutput errCode = sendCommand(&cmd, sizeof(cmd), &cmdReply, sizeof(cmdReply)); } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::actStoreToEPROMUpdate(TObject *Sender) { //q } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::actLoadFromEPROMExecute(TObject *Sender) { // TCmdLoadParametersFromEPROM cmd; // TCmdEPROMOperationDone cmdReply; // // TCommandErrorOutput errCode = sendCommand(&cmd, sizeof(cmd), &cmdReply, sizeof(cmdReply)); // if (errCode.m_command == 0) { // initControlsFromController(); // } } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::actLoadFromEPROMUpdate(TObject *Sender) { //q } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::cbComPortDropDown(TObject *Sender) { RzStatusOperation->Caption = ""; RzFieldFirmwareVersion->Caption = ""; RzFieldActiveBank->Caption = ""; } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::actActivateBankExecute(TObject *Sender) { // m_activeBank = RzTabBanks->TabIndex; m_updateActiveBank = true; //updateControlsForSelectedBank(); } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::actActivateBankUpdate(TObject *Sender) { // actActivateBank->Visible = (RzTabBanks->TabIndex != m_activeBank); } //--------------------------------------------------------------------------- void TFormMainWindow::OnLogEvent(const void* anObject, const char* pCmd, const char* pLogStr) { while (FormMainWindow->lbLog->Items->Count > 500) { FormMainWindow->lbLog->Items->Delete(0); } int idx = FormMainWindow->lbLog->Items->Add(AnsiString(pLogStr)); if (idx > 3) FormMainWindow->lbLog->TopIndex = idx - 1; while (FormMainWindow->lbFullLog->Items->Count > 1000) { FormMainWindow->lbFullLog->Items->Delete(0); } idx = FormMainWindow->lbFullLog->Items->Add(AnsiString(pLogStr)); // if (idx > 3) // FormMainWindow->lbFullLog->TopIndex = idx - 1; } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::rgTriggerSourceHead1Click(TObject *Sender) { m_headControlInfo.m_updateHead[0] = true; } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::rgTriggerSourceHead1Changing(TObject *Sender, int NewIndex, bool &AllowChange) { m_headControlInfo.m_updateHead[0] = true; } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::rgTriggerSourceHead2Changing( TObject *Sender, int NewIndex, bool &AllowChange) { m_headControlInfo.m_updateHead[1] = true; } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::grHead2AmplifierChanging(TObject *Sender, int NewIndex, bool &AllowChange) { m_headControlInfo.m_updateHead[1] = true; } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::rzDCModeHead2Click(TObject *Sender) { m_headControlInfo.m_updateHead[1] = true; grHead2Amplifier->ItemIndex = 0; grHead2Amplifier->Enabled = false; } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::tbChanel1Head1Changing(TObject *Sender, int NewPos, bool &AllowChange) { if (m_head1PowerChanging) return; m_head1PowerChanging = true; int diff = NewPos - tbChanel1Head1->Position; if (grHead1Lock->ItemChecked[0] && grHead1Lock->ItemChecked[1]) { tbChanel2Head1->Position = tbChanel2Head1->Position + diff; } if (grHead1Lock->ItemChecked[0] && grHead1Lock->ItemChecked[2]) { tbChanel3Head1->Position = tbChanel3Head1->Position + diff; } if (grHead1Lock->ItemChecked[0] && grHead1Lock->ItemChecked[3]) { tbChanel4Head1->Position = tbChanel4Head1->Position + diff; } m_head1PowerChanging = false; } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::tbChanel2Head1Changing(TObject *Sender, int NewPos, bool &AllowChange) { if (m_head1PowerChanging) return; m_head1PowerChanging = true; int diff = NewPos - tbChanel2Head1->Position; if (grHead1Lock->ItemChecked[1] && grHead1Lock->ItemChecked[0]) { tbChanel1Head1->Position = tbChanel1Head1->Position + diff; } if (grHead1Lock->ItemChecked[1] && grHead1Lock->ItemChecked[2]) { tbChanel3Head1->Position = tbChanel3Head1->Position + diff; } if (grHead1Lock->ItemChecked[1] && grHead1Lock->ItemChecked[3]) { tbChanel4Head1->Position = tbChanel4Head1->Position + diff; } m_head1PowerChanging = false; } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::tbChanel3Head1Changing(TObject *Sender, int NewPos, bool &AllowChange) { if (m_head1PowerChanging) return; m_head1PowerChanging = true; int diff = NewPos - tbChanel3Head1->Position; if (grHead1Lock->ItemChecked[2] && grHead1Lock->ItemChecked[1]) { tbChanel2Head1->Position = tbChanel2Head1->Position + diff; } if (grHead1Lock->ItemChecked[2] && grHead1Lock->ItemChecked[0]) { tbChanel1Head1->Position = tbChanel1Head1->Position + diff; } if (grHead1Lock->ItemChecked[2] && grHead1Lock->ItemChecked[3]) { tbChanel4Head1->Position = tbChanel4Head1->Position + diff; } m_head1PowerChanging = false; } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::tbChanel4Head1Changing(TObject *Sender, int NewPos, bool &AllowChange) { if (m_head1PowerChanging) return; m_head1PowerChanging = true; int diff = NewPos - tbChanel4Head1->Position; if (grHead1Lock->ItemChecked[3] && grHead1Lock->ItemChecked[1]) { tbChanel2Head1->Position = tbChanel2Head1->Position + diff; } if (grHead1Lock->ItemChecked[3] && grHead1Lock->ItemChecked[2]) { tbChanel3Head1->Position = tbChanel3Head1->Position + diff; } if (grHead1Lock->ItemChecked[3] && grHead1Lock->ItemChecked[0]) { tbChanel1Head1->Position = tbChanel1Head1->Position + diff; } m_head1PowerChanging = false; } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::tbChanel1Head2Changing(TObject *Sender, int NewPos, bool &AllowChange) { if (m_head2PowerChanging) return; m_head2PowerChanging = true; int diff = NewPos - tbChanel1Head2->Position; if (grHead2Lock->ItemChecked[0] && grHead2Lock->ItemChecked[1]) { tbChanel2Head2->Position = tbChanel2Head2->Position + diff; } if (grHead2Lock->ItemChecked[0] && grHead2Lock->ItemChecked[2]) { tbChanel3Head2->Position = tbChanel3Head2->Position + diff; } if (grHead2Lock->ItemChecked[0] && grHead2Lock->ItemChecked[3]) { tbChanel4Head2->Position = tbChanel4Head2->Position + diff; } m_head2PowerChanging = false; } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::tbChanel2Head2Changing(TObject *Sender, int NewPos, bool &AllowChange) { if (m_head2PowerChanging) return; m_head2PowerChanging = true; int diff = NewPos - tbChanel2Head2->Position; if (grHead2Lock->ItemChecked[0] && grHead2Lock->ItemChecked[0]) { tbChanel1Head2->Position = tbChanel1Head2->Position + diff; } if (grHead2Lock->ItemChecked[0] && grHead2Lock->ItemChecked[2]) { tbChanel3Head2->Position = tbChanel3Head2->Position + diff; } if (grHead2Lock->ItemChecked[0] && grHead2Lock->ItemChecked[3]) { tbChanel4Head2->Position = tbChanel4Head2->Position + diff; } m_head2PowerChanging = false; } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::tbChanel3Head2Changing(TObject *Sender, int NewPos, bool &AllowChange) { if (m_head2PowerChanging) return; m_head2PowerChanging = true; int diff = NewPos - tbChanel3Head2->Position; if (grHead2Lock->ItemChecked[0] && grHead2Lock->ItemChecked[1]) { tbChanel2Head2->Position = tbChanel2Head2->Position + diff; } if (grHead2Lock->ItemChecked[0] && grHead2Lock->ItemChecked[0]) { tbChanel1Head2->Position = tbChanel1Head2->Position + diff; } if (grHead2Lock->ItemChecked[0] && grHead2Lock->ItemChecked[3]) { tbChanel4Head2->Position = tbChanel4Head2->Position + diff; } m_head2PowerChanging = false; } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::tbChanel4Head2Changing(TObject *Sender, int NewPos, bool &AllowChange) { if (m_head2PowerChanging) return; m_head2PowerChanging = true; int diff = NewPos - tbChanel4Head2->Position; if (grHead2Lock->ItemChecked[0] && grHead2Lock->ItemChecked[1]) { tbChanel2Head2->Position = tbChanel2Head2->Position + diff; } if (grHead2Lock->ItemChecked[0] && grHead2Lock->ItemChecked[2]) { tbChanel3Head2->Position = tbChanel3Head2->Position + diff; } if (grHead2Lock->ItemChecked[0] && grHead2Lock->ItemChecked[0]) { tbChanel1Head2->Position = tbChanel1Head2->Position + diff; } m_head2PowerChanging = false; } //--------------------------------------------------------------------------- void __fastcall TFormMainWindow::rzRefreshClick(TObject *Sender) { m_LD130.close(); RzFieldFirmwareVersion->Caption = ""; RzStatusOperation->Caption=""; cbComPort->ClearItemsValues(); cbComPort->AddItemValue("No COM", AnsiString(0)); char str[128] = {0}; HANDLE hComPort = 0; for (int i = 1; i < 50; ++i) { _snprintf (str, sizeof(str), "\\\\.\\COM%d", i); hComPort = CreateFile( str, GENERIC_READ | GENERIC_WRITE, 0, // must be opened with exclusive-access 0, // no security attributes OPEN_EXISTING, // must use OPEN_EXISTING FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, // for overlapped IO NULL // hTemplate must be NULL for comm devices ); if (hComPort != INVALID_HANDLE_VALUE && hComPort != 0) { _snprintf (str, sizeof(str), "COM %d", i); cbComPort->AddItemValue(str, AnsiString(i)); ::CloseHandle(hComPort); } } cbComPort->ItemIndex = 0; } //---------------------------------------------------------------------------
[ [ [ 1, 966 ] ] ]
4f043e83ffcb425c5551ae28ec04dd8732b1f802
43cad44a215e91c3ea3202cf4031be14e262e0fd
/SnowFlake-P/jail/problems/1/1/P1_Test.cpp
63e52592b4280a1fe32cca86cbeb76fc50cc4bb2
[]
no_license
SwitchCase/SnowFlake
67de7f3fcecfbd4bbcff9889cc13d648cabb086b
40d8f188aa16524d1127fceadb11f252ab645325
refs/heads/master
2021-01-19T16:23:32.645758
2011-11-20T09:56:03
2011-11-20T09:56:03
1,453,974
3
0
null
null
null
null
UTF-8
C++
false
false
5,277
cpp
// <-------------------[sWitCHcAsE]----------------------> #include <iostream> #include <cstdio> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> #include <cstring> #include <cassert> #include <vector> #define FOR(i,a) for(int i=0;i<a;i++) #define FORS(i,a,b) for(int i=a;i<b;i++) #define FORR(i,a) for(int i=a;i>=0;i--) #define pb push_back #define VI vector<int> #define VS vector <string> #define MAX2(a,b) (a)<(b)?(b):(a) #define MIN2(a,b) (a)<(b)?(a):(b) #define LEN(s) strlen(s) #define tests(tc) int tc;scanf("%d",&tc);while(tc--) #define TEN(n) (long long)pow(10LL,n) #define foreach(it,x) for(typeof(x.begin()) it=x.begin();it!=x.end();++it) #define bits __builtin_popcount #define ERR(x) if(debug) cerr<<#x<<" "<<x<<endl; #define ASS(x) assert(x>0 && x<=MAX) typedef long long ll; typedef unsigned long long ull; typedef long double ld; typedef unsigned int uint; using namespace std; int MAX=2000000000; int sieve[100000]; VI primes; void dosieve() { cerr<<"DOING SIEVE"<<endl; memset(sieve,1,sizeof sieve); sieve[2]=1; int i=4; while(i<100000) { sieve[i]=0; i=i+2; } primes.pb(2); for(i=3;i*i<100000;i+=2) { if(sieve[i]) { primes.pb(i); for(int j=i*i;j<100000;j+=2*i) { sieve[j]=0; } } } cerr<<"DONE SIEVE"<<endl; } void itoa(int a,char *buff,int) { sprintf(buff,"%d",a); } int isPrime(int N) { for(int i=0;i<primes.size();i++) { if(N%primes[i])return 0; } return 1; } /* int main() { int a,b; while(1) { scanf("%d %d",&a,&b); cout<<GCD(a,b)<<endl; } }*/ typedef pair<ll,ll> II; int debug=0; II ext_euclid(ll a,ll b) { ll x,lx,y,ly; x=ly=0; y=lx=1; ll t,q; while(b) { q=a/b; t=b;b=a%b;a=t; t=x;x=lx-q*x;lx=t; t=y;y=ly-q*y;ly=t; } //ERR(lx);ERR(ly); return make_pair(lx,ly); } ll GCD(ll a,ll b) { if(b==0)return a; else return GCD(b,a%b); } ll lcm; ll n1,n2; void positivise(ll &a,ll &b) { if(a>=0 && b>=0)return; assert(lcm!=0); ll m1,m2; m1=lcm/n1; m2=lcm/n2; if(m1==0 || m2==0){ ERR(n1); ERR(n2); } assert(m1!=0 && m2!=0); ll n1_t=(-a)/m1; n1_t++; ll n2_t=(-b)/m2; n2_t++; ERR(a);ERR(b);ERR(lcm);ERR(n1_t);ERR(n2_t);ERR(m1);ERR(m2); if(a<0) { a=a + n1_t*m1; b=b-n1_t*m2; } else { a=a-n2_t*m1; b=b+n2_t*m2; } cerr<<"AFTER positivise "<<a<<" "<<b<<endl; } int main() { dosieve(); int TOTAL_FILES=200; int TESTS=10000; char buff[100]; int done=0; string filename="tempin"; int dt=TESTS; for(;done<2;done++) { itoa(done,buff,10); freopen((filename+string(buff)).c_str(),"w",stdout); dt=TESTS; while(dt--) { int N=(rand()%MAX); cout<<N<<endl; cout<<(rand() %MAX)<<" "<<(rand()%(N+rand()%10))<<endl; cout<<(rand() %MAX)<<" "<<(rand()%(N+rand()%10))<<endl; } cout<<"0"<<endl; } while(done<TOTAL_FILES) { cerr<<"TESTS DONE "<<done<<endl; itoa(done,buff,10); freopen((filename+string(buff)).c_str(),"w",stdout); dt=TESTS; while(dt--) { int primeth=rand()%primes.size(); primeth += rand()%1007; int gcd; if(primeth<primes.size()) { gcd=primes[primeth]; } else { gcd=primeth%MAX; } int N=(done<90?((rand()%MAX)*gcd)%MAX:rand()%MAX); if(N==0) N=121*13*19; int left=rand()%MAX; int c2=(rand()%left)*gcd; int c1=(rand()%left)*gcd; c1=abs(c1); c2=abs(c2); c1%=MAX; c2%=MAX; cerr<<c1<<" "<<c2<<endl; assert(c1<=MAX && c1>0); assert(c2<=MAX && c2>0); assert(gcd>0); int ff=rand()%gcd; int temp=(abs(gcd*gcd)%MAX); if(temp==0)temp=121; int ss=rand()%temp; int lf=rand()%N; if(ss==0)ss+=112; int sf= (N - (ff *lf))/ss; n1=lf; n2=sf; II ans=ext_euclid(n1,n2); cerr<<"DONE "<<endl; ll p1=ans.first; ll p2=ans.second; lcm = (n1/GCD(n1,n2)) * n2; lcm=abs(lcm); ERR(lcm); positivise(p1,p2); ERR(p1); if(p1>=0 && p1<=MAX && p2>=0 && p2<=MAX) { n1=p1%MAX; n2=p2%MAX; } else { n1=abs(n1)%MAX; n2=abs(n2)%MAX; } N=abs(N); c1=abs(c1); c2=abs(c2); n1=abs(n1)%MAX; if(n1<=0)n1=12; n2=abs(n2); if(n2<=0)n2=13; ASS(N);ASS(c1);ASS(c2);ASS(n1);ASS(n2); cout<<N<<endl<<c1<<" "<<n1<<endl<<c2<<" "<<n2<<endl; } cout<<"0"<<endl; done++; } system("pause"); }
[ [ [ 1, 229 ] ] ]
be7210c4027fbc53f8fdcf01e2def9e9067f6378
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/dom/deprecated/DocumentTypeImpl.hpp
73374916f6e5a647c9a138e89e121f1f74ff6b34
[ "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
2,924
hpp
#ifndef DocumentTypeImpl_HEADER_GUARD_ #define DocumentTypeImpl_HEADER_GUARD_ /* * Copyright 1999-2002,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: DocumentTypeImpl.hpp,v 1.5 2004/09/08 13:55:43 peiyongz Exp $ */ // // This file is part of the internal implementation of the C++ XML DOM. // It should NOT be included or used directly by application programs. // // Applications should include the file <xercesc/dom/deprecated/DOM.hpp> for the entire // DOM API, or DOM_*.hpp for individual DOM classes, where the class // name is substituded for the *. // #include <xercesc/util/XercesDefs.hpp> #include "ParentNode.hpp" XERCES_CPP_NAMESPACE_BEGIN class NamedNodeMapImpl; class DEPRECATED_DOM_EXPORT DocumentTypeImpl: public ParentNode { private: DOMString name; NamedNodeMapImpl *entities; NamedNodeMapImpl *notations; NamedNodeMapImpl *elements; DOMString publicId; DOMString systemId; DOMString internalSubset; bool intSubsetReading; virtual void setPublicId(const DOMString& value); virtual void setSystemId(const DOMString& value); virtual void setInternalSubset(const DOMString &value); bool isIntSubsetReading(); friend class DOMParser; public: DocumentTypeImpl(DocumentImpl *, const DOMString &); DocumentTypeImpl(DocumentImpl *, const DOMString &qualifiedName, //DOM Level 2 const DOMString &publicId, const DOMString &systemId); DocumentTypeImpl(const DocumentTypeImpl &other, bool deep=false); virtual ~DocumentTypeImpl(); virtual bool isDocumentTypeImpl(); virtual NodeImpl * cloneNode(bool deep); virtual void setOwnerDocument(DocumentImpl *doc); virtual DOMString getNodeName(); virtual short getNodeType(); virtual NamedNodeMapImpl * getEntities(); virtual DOMString getName(); virtual NamedNodeMapImpl * getNotations(); virtual NamedNodeMapImpl * getElements(); virtual void setReadOnly(bool readOnly, bool deep); //Introduced in DOM Level 2 virtual DOMString getPublicId(); virtual DOMString getSystemId(); virtual DOMString getInternalSubset(); }; XERCES_CPP_NAMESPACE_END #endif
[ [ [ 1, 90 ] ] ]
fa435788f3a8f861491d296c61f222306808ebb1
28b0332fabba904ac0668630f185e0ecd292d2a1
/src/Borland/ClassBuilderUnit.h
82784937636bcdfc03f82eefd57a405e9a0ac29c
[]
no_license
iplayfast/crylib
57a507ba996d1abe020f93ea4a58f47f62b31434
dbd435e14abc508c31d1f2f041f8254620e24dc0
refs/heads/master
2016-09-05T10:33:02.861605
2009-04-19T05:17:55
2009-04-19T05:17:55
35,353,897
0
0
null
null
null
null
UTF-8
C++
false
false
2,935
h
//--------------------------------------------------------------------------- #ifndef ClassBuilderUnitH #define ClassBuilderUnitH //--------------------------------------------------------------------------- #include <Classes.hpp> #include <Controls.hpp> #include <StdCtrls.hpp> #include <Forms.hpp> #include <Menus.hpp> #include "CheckLabel.h" #include "labelEditfrm.h" #include <ComCtrls.hpp> #include <ExtCtrls.hpp> //--------------------------------------------------------------------------- #include "ClassBuilder.h" #include <Dialogs.hpp> //class ClassBuilder; class TClassBuilderFrm : public TForm { __published: // IDE-managed Components TMainMenu *MainMenu1; TMenuItem *File1; TMenuItem *New1; TMenuItem *Open1; TMenuItem *Save1; TMenuItem *SaveAs1; TMenuItem *N2; TMenuItem *Print1; TMenuItem *PrintSetup1; TMenuItem *N1; TMenuItem *Exit1; TMenuItem *testUseDebugtoverifyresults1; TMenuItem *testcode11; TMenuItem *testcode21; TPageControl *PageControl1; TTabSheet *SetBaseClass; TButton *SetBaseClassBT; TCheckBox *IncludeStubs; TLabelEdit *NameED; TComboBox *ClassTypeCB; TTabSheet *AddVariables; TLabel *ArrayAmountLb; TLabelEdit *VariableName; TRadioGroup *RadioGroup1; TCheckBox *PropertyCB; TCheckBox *TypePointer; TCheckBox *PointerToArray; TComboBox *ClassType2CB; TTrackBar *ArrayCount; TTabSheet *RemoveVariable; TLabel *Label1; TComboBox *RemoveVariableCB; TTreeView *TreeView1; TButton *AddVariable; TStatusBar *StatusBar1; TComboBox *VariableTypeCB; TOpenDialog *OpenDialog1; TSaveDialog *SaveDialog1; TCheckedLabel *DefaultValue; TButton *Button1; TComboBox *TemplateType; void __fastcall SetBaseClassBTClick(TObject *Sender); void __fastcall ArrayCountChange(TObject *Sender); void __fastcall FormCreate(TObject *Sender); void __fastcall AddVariableClick(TObject *Sender); void __fastcall UpdateStatus(TObject *Sender); void __fastcall VariableNameEdit1KeyDown(TObject *Sender, WORD &Key, TShiftState Shift); void __fastcall MenuItem_NewClick(TObject *Sender); void __fastcall MenuItem_OpenClick(TObject *Sender); void __fastcall MenuItem_SaveClick(TObject *Sender); void __fastcall MenuItem_SaveAsClick(TObject *Sender); void __fastcall Exit1Click(TObject *Sender); void __fastcall FormDestroy(TObject *Sender); void __fastcall Button1Click(TObject *Sender); void __fastcall ClassTypeCBChange(TObject *Sender); private: // User declarations Crystal::ClassBuilder *ANewClass; int PropertyCount; bool VariableNameEditedYet; void __fastcall RefreshView(void); public: // User declarations __fastcall TClassBuilderFrm(TComponent* Owner); }; //--------------------------------------------------------------------------- extern PACKAGE TClassBuilderFrm *ClassBuilderFrm; //--------------------------------------------------------------------------- #endif
[ "cwbruner@f8ea3247-a519-0410-8bc2-439d413616df" ]
[ [ [ 1, 89 ] ] ]
3aded555a726a98bdf27107c2b11a3111738a036
10bac563fc7e174d8f7c79c8777e4eb8460bc49e
/act/p3dx_client_t.h
8872956f4d1b4cb3e0b2ba06f4b8336b1a852cab
[]
no_license
chenbk85/alcordev
41154355a837ebd15db02ecaeaca6726e722892a
bdb9d0928c80315d24299000ca6d8c492808f1d5
refs/heads/master
2021-01-10T13:36:29.338077
2008-10-22T15:57:50
2008-10-22T15:57:50
44,953,286
0
1
null
null
null
null
UTF-8
C++
false
false
2,350
h
//--------------------------------------------------------------------------- #ifndef p3dx_client_t_H_INCLUDED #define p3dx_client_t_H_INCLUDED //--------------------------------------------------------------------------- #pragma comment (lib, "p3dx_client_t.lib") //--------------------------------------------------------------------------- #include "alcor/math/all_math.h" #include "alcor/core/core.h" //--------------------------------------------------------------------------- #include <boost/shared_ptr.hpp> //--------------------------------------------------------------------------- namespace all{ namespace act{ //--------------------------------------------------------------------------- class p3dx_client_t { protected: /// p3dx_client_t(){}; public: ///deprecated .. unuseful //virtual void start() = 0; /// virtual void stop()=0; /// virtual core::net_state_t net_state() const = 0; /// virtual void set_localized(double, double, double)=0; /// virtual void set_localized(const math::pose2d&)=0; /// virtual void set_vel(double)=0; /// virtual void set_rot_vel(double)=0; /// virtual void stop_robot()=0; //TODO: aggiungere i servizi! /// virtual void move(double distance)=0; /// virtual void move_diff(const math::point2d&) = 0; /// virtual void set_heading(const math::angle&) = 0; /// virtual void set_delta_heading(const math::angle&) = 0; /// virtual void wander() = 0; /// virtual void set_local_dir (double delta_degree) = 0; /// virtual math::pose2d const& get_odometry() const = 0; /// virtual math::pose2d const& get_localized() const = 0; }; ////--------------------------------------------------------------------------- typedef boost::shared_ptr<p3dx_client_t> p3dx_client_sptr; ////--------------------------------------------------------------------------- boost::shared_ptr<p3dx_client_t> create_p3dx_client(); //--------------------------------------------------------------------------- }//alcor }//act //--------------------------------------------------------------------------- #endif //p3dx_client_H_INCLUDED //---------------------------------------------------------------------------
[ "andrea.carbone@1c7d64d3-9b28-0410-bae3-039769c3cb81" ]
[ [ [ 1, 68 ] ] ]
8d7d37bffa9d57c3301cf6a3d106207897cac16b
fd792229322e4042f6e88a01144665cebdb1c339
/src/animation.cpp
e2ec88afe507928c1321faf856401fde7b3f4d5a
[]
no_license
weimingtom/mmomm
228d70d9d68834fa2470d2cd0719b9cd60f8dbcd
cab04fcad551f7f68f99fa0b6bb14cec3b962023
refs/heads/master
2021-01-10T02:14:31.896834
2010-03-15T16:15:43
2010-03-15T16:15:43
44,764,408
1
0
null
null
null
null
UTF-8
C++
false
false
1,929
cpp
#include "animation.h" #include "sprite.h" #include <iostream> Animation::Animation(int id, ImageManager::shared_ptr img, int frameWidth, int frameHeight, double interval, int startFrame, int endFrame, bool active) : _id(id) , _img(img) , _frameWidth(frameWidth) , _frameHeight(frameHeight) , _interval(interval) , _active(active) , _startFrame(startFrame) , _currentFrame(_startFrame) , _callbackSprite(0) { assert(interval > 0); _totalTime = 0; _totalHoriFrames = _img.get()->getWidth() / _frameWidth; _totalVertFrames = _img.get()->getHeight() / _frameHeight; _endFrame = endFrame >= 0 ? endFrame : _totalHoriFrames * _totalVertFrames; assert(_startFrame >= 0 && _startFrame < _totalHoriFrames * _totalVertFrames); assert(_endFrame > _startFrame && _endFrame <= _totalHoriFrames * _totalVertFrames); #ifndef NDEBUG cout << "Created animation with " << _totalHoriFrames << "x" << _totalVertFrames << " frames and interval = " << _interval << endl; #endif } Animation::~Animation() { #ifndef NDEBUG cout << "Animation of " << _img.get()->getFilename() << " destroyed" << endl; #endif } void Animation::setCallbackSprite(Sprite* sprite) { _callbackSprite = sprite; } void Animation::update(double elapsed) { //cout << "updating \"" << getImage().get()->getFilename() << "\" with " << msPassed << endl; double maxTime = (_endFrame - _startFrame)*_interval; _totalTime += elapsed; while (_totalTime >= maxTime) _totalTime -= maxTime; int oldFrame = _currentFrame; _currentFrame = _startFrame + int(_totalTime/_interval); if ( _currentFrame < oldFrame && _callbackSprite ) _callbackSprite->repetitionCallback(); } SDL_Rect Animation::getCurrentFrameRect() const { SDL_Rect rect; rect.x = getCurrentFrameX(); rect.y = getCurrentFrameY(); rect.w = getFrameWidth(); rect.h = getFrameHeight(); return rect; }
[ "kingoipo@191a6260-07ae-11df-8636-19de83dc8dca", "grandfunkdynasty@191a6260-07ae-11df-8636-19de83dc8dca", "[email protected]" ]
[ [ [ 1, 1 ], [ 3, 6 ], [ 8, 13 ], [ 17, 17 ], [ 19, 21 ], [ 26, 38 ], [ 43, 43 ], [ 45, 47 ], [ 50, 50 ], [ 53, 53 ], [ 68, 68 ] ], [ [ 2, 2 ], [ 7, 7 ], [ 14, 16 ], [ 22, 25 ], [ 39, 42 ], [ 48, 48 ], [ 51, 51 ], [ 54, 56 ] ], [ [ 18, 18 ], [ 44, 44 ], [ 49, 49 ], [ 52, 52 ], [ 57, 67 ] ] ]
5aec5780139afcad71fc9b85805d08207c331940
9d1cb48ec6f6c1f0e342f0f8f819cbda74ceba6e
/src/proxy/InputDlg.cpp
3f3de445ec4973908d3ac0fe851ddd0eb93e0de4
[]
no_license
correosdelbosque/veryie
e7a5ad44c68dc0b81d4afcff3be76eb8f83320ff
6ea5a68d0a6eb6c3901b70c2dc806d1e2e2858f1
refs/heads/master
2021-01-10T13:17:59.755108
2010-06-16T04:23:26
2010-06-16T04:23:26
53,365,953
1
1
null
null
null
null
UTF-8
C++
false
false
3,054
cpp
// InputDlg.cpp : implementation file // #include "stdafx.h" #include "VeryIE.h" #include "InputDlg.h" #include "MainFrm.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CInputDlg dialog CInputDlg::CInputDlg(CWnd* pParent /*=NULL*/) : CDialog(CInputDlg::IDD, pParent) { //{{AFX_DATA_INIT(CInputDlg) m_strMsg = _T(""); m_strOutput = _T(""); //}}AFX_DATA_INIT m_nOKType = 0; m_bSave = FALSE; } void CInputDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CInputDlg) DDX_Control(pDX, IDC_OUTPUT, m_output); DDX_Text(pDX, IDC_MSG, m_strMsg); DDX_Text(pDX, IDC_OUTPUT, m_strOutput); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CInputDlg, CDialog) //{{AFX_MSG_MAP(CInputDlg) ON_BN_CLICKED(IDC_UP_URL, OnUpUrl) ON_BN_CLICKED(IDC_COPY, OnCopy) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CInputDlg message handlers BOOL CInputDlg::OnInitDialog() { #ifdef _WRITE_LNG_FILE_ _WriteDlgString(this,"DialogInput"); this->OnCancel(); return TRUE; #endif LOADDLG("DialogInput"); CDialog::OnInitDialog(); // TODO: Add extra initialization here CEdit *p = (CEdit*)GetDlgItem(IDC_OUTPUT); // CString str; if (!IS_URL(m_strOutput)) { //GetDlgItem(IDC_UP_URL)->ShowWindow(FALSE); LOADSTR(str ,IDS_SAVE); GetDlgItem(IDC_UP_URL)->SetWindowText(str); m_bSave = TRUE; } if (m_nOKType) { LOADSTR(str ,ID_LL_OPEN_SELECT); GetDlgItem(IDOK)->SetWindowText(str); } return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void CInputDlg::OnUpUrl() { // TODO: Add your control notification handler code here CString strUrl,strUrlUp; m_output.GetWindowText(strUrl); if (m_bSave) { if (strUrl.GetLength()<1) return; CString str; LOADSTR(str ,IDS_TYPE_COLLECTOR); CString strFileName; GET_FILE_NAME(strFileName,strUrl) CFileDialog dlg(FALSE, "txt", strFileName, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, str); if (dlg.DoModal()==IDOK) { CFile f; if(f.Open(dlg.GetPathName(), CFile::modeCreate|CFile::modeWrite|CFile::shareDenyNone)) { f.Write((void*)(LPCSTR)strUrl, strUrl.GetLength()); f.Close(); } OnCancel(); } } else { //up url strUrlUp = _StringGetUpUrl(strUrl); if (strUrl != strUrlUp) { m_output.SetWindowText(strUrlUp); m_output.SetFocus(); m_output.SetSel(0,-1); } } } void CInputDlg::OnCopy() { // TODO: Add your control notification handler code here int nStart, nEnd; CString strText, strCode; m_output.GetWindowText(strText); m_output.GetSel(nStart,nEnd); if (nStart<nEnd && nStart>=0 && nEnd>=0) strText = strText.Mid(nStart,nEnd-nStart); // _SetClipString(strText); OnCancel(); }
[ "songbohr@af2e6244-03f2-11de-b556-9305e745af9e" ]
[ [ [ 1, 133 ] ] ]
1e1f9eff14ed6cc2396318ccd9f583b3b0c201f8
ef23e388061a637f82b815d32f7af8cb60c5bb1f
/src/mame/includes/cloak.h
c8265475cc6d594d7bf5ea874a3dfd3213bf9359
[]
no_license
marcellodash/psmame
76fd877a210d50d34f23e50d338e65a17deff066
09f52313bd3b06311b910ed67a0e7c70c2dd2535
refs/heads/master
2021-05-29T23:57:23.333706
2011-06-23T20:11:22
2011-06-23T20:11:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,090
h
/************************************************************************* Atari Cloak & Dagger hardware *************************************************************************/ class cloak_state : public driver_device { public: cloak_state(running_machine &machine, const driver_device_config_base &config) : driver_device(machine, config) { } UINT8 *m_videoram; UINT8 *m_spriteram; int m_nvram_enabled; UINT8 m_bitmap_videoram_selected; UINT8 m_bitmap_videoram_address_x; UINT8 m_bitmap_videoram_address_y; UINT8 *m_bitmap_videoram1; UINT8 *m_bitmap_videoram2; UINT8 *m_current_bitmap_videoram_accessed; UINT8 *m_current_bitmap_videoram_displayed; UINT16 *m_palette_ram; tilemap_t *m_bg_tilemap; }; /*----------- defined in video/cloak.c -----------*/ WRITE8_HANDLER( cloak_videoram_w ); WRITE8_HANDLER( cloak_flipscreen_w ); WRITE8_HANDLER( cloak_paletteram_w ); READ8_HANDLER( graph_processor_r ); WRITE8_HANDLER( graph_processor_w ); WRITE8_HANDLER( cloak_clearbmp_w ); VIDEO_START( cloak ); SCREEN_UPDATE( cloak );
[ "Mike@localhost" ]
[ [ [ 1, 39 ] ] ]
702dd82076228457355974d272a037b952b297c3
1092bd6dc9b728f3789ba96e37e51cdfb9e19301
/loci/mocaps/bvh_document.h
6e87e797e0786590b9a10def770046a7235b6f29
[]
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,484
h
#ifndef LOCI_MOCAPS_BVH_DOCUMENT_H_ #define LOCI_MOCAPS_BVH_DOCUMENT_H_ /** * Defines a bvh_document for parsing the BioVision Hierarchy format. * Parses the BioVision Hierarchy mocap format from a string. * * @file bvh_document.cpp * @author David Gill * @date 21/02/2010 */ #include <string> #include <istream> #include "loci/skeleton.h" #include "loci/skeleton_builder.h" #include "loci/mocaps/mocap.h" #include "loci/mocaps/detail/bvh/parser.h" namespace loci { // forward declarations class pose; class named_indices; namespace anim { template <class T> class keyed_motion; } namespace mocaps { class bvh_document { public: typedef mocap< anim::keyed_motion<pose> > mocap; explicit bvh_document(const skeleton & figure, double frame_time, double expected_duration = 3000); explicit bvh_document(std::istream & source); explicit bvh_document(const std::string & content); mocap compile(bool first_frame_as_bind_pose = false) const; void save(std::ostream & sink) const; void append_frame(const pose & p); private: typedef skeleton_builder::cursor cursor; typedef detail::bvh::scope_list scope_list; typedef scope_list::const_iterator scope_iterator; typedef mocap::motion_type motion_type; typedef detail::bvh::scope::motion_channel_list::const_iterator motion_iterator; void parse(std::istream & source); skeleton compile_skeleton() const; std::auto_ptr<motion_type> compile_motion(bool first_frame_as_bind_pose) const; void compile_skeleton_recurse(skeleton_builder & builder, cursor parent_joint, scope_iterator & pos, const numeric::vector3f & up) const; void compile_bone_motion_recurse(pose::bone_list & bones, scope_iterator & pos, unsigned int frame) const; void build_hierarchy_part(const named_indices & name_bindings, const pose & bind_pose, cursor c, unsigned int depth, unsigned int motion_reserve); scope_list scopes; unsigned int frame_count; double sample_rate; }; bvh_document::mocap import_bvh_file(const std::string & path, bool first_frame_as_bind_pose = false); void export_bvh_to_file(const bvh_document & bvh_doc, const std::string & path); } // namespace mocaps } // namespace loci #endif // LOCI_MOCAPS_BVH_DOCUMENT_H_
[ "[email protected]@0e8bac56-0901-9d1a-f0c4-3841fc69e132" ]
[ [ [ 1, 75 ] ] ]
56a142474154d776371e164b4d7995ba3abbaa8a
3bc3ce568f1938af569a7f84d1c6e261a6fd4de5
/StudManager/StudManager/Coursework.h
33397b21ee25d98b13ccbec07698e537d0b3390d
[]
no_license
dekz/uni
524cc16e706221ad518577e5f00712d5030c035f
84c2466df43f9dc62425d2b7c0162ac6b0a1244f
refs/heads/master
2016-09-05T21:07:29.739745
2009-05-24T13:12:24
2009-05-24T13:12:24
195,698
2
0
null
null
null
null
UTF-8
C++
false
false
533
h
#include "student.h" #include <map> #ifndef COURSEWORK #define COURSEWORK class Coursework : public Student { public: Coursework(); Coursework(string a_id, string a_firstName, string a_lastName, string a_category); void setUnits(const map<string, int> &a_mapl); void addUnit(string a_unitCode, int a_grade); int getTotalUnits(); string getUnits(); ~Coursework(void); virtual void displayAssessment() override; private: //data structure map<string,int> m_units; string getGpa(); }; #endif
[ [ [ 1, 28 ] ] ]
76b138144f65c541f84087328c9778f8524f5091
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/numeric/ublas/doc/samples/vector_binary_outer.cpp
638a2658d0e129ebb78263c486232d6225f170db
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
1,010
cpp
// // Copyright (c) 2000-2002 // Joerg Walter, Mathias Koch // // Permission to use, copy, modify, distribute and sell this software // and its documentation for any purpose is hereby granted without fee, // provided that the above copyright notice appear in all copies and // that both that copyright notice and this permission notice appear // in supporting documentation. The authors make no representations // about the suitability of this software for any purpose. // It is provided "as is" without express or implied warranty. // // The authors gratefully acknowledge the support of // GeNeSys mbH & Co. KG in producing this work. // #include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/io.hpp> int main () { using namespace boost::numeric::ublas; vector<double> v1 (3), v2 (3); for (unsigned i = 0; i < (std::min) (v1.size (), v2.size ()); ++ i) v1 (i) = v2 (i) = i; std::cout << outer_prod (v1, v2) << std::endl; }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 28 ] ] ]
84ccb966d3c00159fd2b5db97db4a6fa06306176
6a1a184ceb7be1f73c490fcbaf8fba7a64cab1ff
/Source/TestFluidic/TestScene2D.h
83389ce3884e91c9a207174755ae43cb9fd12f42
[ "MIT" ]
permissive
alexsaen/fluidic
c8aa913ce03e8d3d9bc8091a31aa96a7d1e5b4ad
bf7eb0f3e9ca4e15f53623020c7f0313315f4e49
refs/heads/master
2020-12-24T15:14:17.261742
2010-04-06T13:10:54
2010-04-06T13:10:54
32,979,664
1
0
null
null
null
null
UTF-8
C++
false
false
1,527
h
/* Copyright (c) 2010 Steven Leigh 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 <iostream> #include <fstream> #include "TestScene.h" #include "TestObject.h" namespace TestFluidic { class TestScene2D : public TestScene { public: TestScene2D(); ~TestScene2D(); void Interact(); void Update(float time); void Display(); void Resize(int w, int h); protected: TestObject *obj; CGcontext cgContext; CGprofile cgFragmentProfile; CGprofile cgVertexProfile; }; }
[ "xwipeoutx@6c3c8482-2914-11df-ad47-1d73243ccc9f" ]
[ [ [ 1, 50 ] ] ]
865b247e6729fdbb182f5d8bc0aa118aad1da198
80546208e48225e6409bb976bf1ed6d672b88a48
/PCServerConsole/PCServerConsole.cpp
6a0bd73a16611e2a3a80acb3da78ef4c020ff85c
[]
no_license
CBulFel/androidcontrolcomputer
ca9a9f70fb5d95232740cc499785c8ead8c53c63
1783f31d46457cc83e0e4a20956534d8a5d15c1a
refs/heads/master
2021-01-13T13:21:09.535378
2011-01-01T11:57:08
2011-01-01T11:57:08
55,883,749
0
0
null
null
null
null
GB18030
C++
false
false
3,111
cpp
// PCServerConsole.cpp : Defines the entry point for the console application. // #include "stdafx.h" int _tmain(int argc, _TCHAR* argv[]) { int udp_port = 20000; int tcp_port = 30000; // int iret; // ๆ‰“ๅฐไฟกๆฏ printf("***************************************************************************\n"); printf("**** ๆ‰‹ๆœบๆŽงๅˆถ็”ต่„‘ V1.141 ไฝœ่€…: liaowufeng ****\n"); printf("***************************************************************************\n"); printf("* ๆณจๆ„:่ฟ่กŒๆ—ถ่ฏทไธ่ฆๅ…ณ้—ญๆญค็ช—ๅฃใ€‚ *\n"); printf("* -------------------------------------------------------------------- *\n"); printf("* Version 1.141 *\n"); printf("* 1 ไฟฎๆญฃ BUG ๏ผŒๅˆ†้š”็ฌฆ็”ฑ\"-\" ๆ”นไธบ \"#\" , *\n"); printf(" ๅŽŸๅ›  ไธปๆœบๅๅฏไปฅๅŒ…ๆ‹ฌ\"-\" ๅญ—็ฌฆ๏ผŒไฝ†ไธๅ…่ฎธๅŒ…ๆ‹ฌ\"#\"ๅญ—็ฌฆ *\n"); printf("* 2 ไฟฎๆ”นandroid ๆ‰‹ๆœบๆ็คบๆ—ถ้—ด็Ÿญไธ€ไบ› *\n"); printf("* 3 ไฟฎๆญฃandroid ๆ‰‹ๆœบๆจชๅฑๆ—ถ็š„BUG *\n"); printf("* --------------------------------------------------------------------- *\n"); printf("* Version 1.14 *\n"); printf("* 1 ไฟฎๆญฃ ๅญ˜ๅœจๅคš็ฝ‘ๅก๏ผŒๅคšIP ไธ‹็š„BUG *\n"); printf("* 2 ๆ”ฏๆŒๆŽงๅˆถๅคšๅฐ็”ต่„‘ *\n"); printf("* --------------------------------------------------------------------- *\n"); HANDLE udpThreadHandle,commandThreadHandle; DWORD udpThreadID=0,commandThreadID=0; // ๅปบ็ซ‹ๅนฟๆ’ญIP ็บฟ็จ‹ udpThreadHandle = ::CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)udp_sendiphostname,(LPVOID)udp_port,0,&udpThreadID); if(udpThreadHandle!=NULL){ printf("<ไธป็จ‹ๅบ> ๆˆๅŠŸๅปบ็ซ‹ ่Žทๅ–IP ็บฟ็จ‹ %d\n",udpThreadID); // ๅปบ็ซ‹ๆŽฅๆ”ถๅ‘ฝไปคๆ“ไฝœ ็บฟ็จ‹ commandThreadHandle = ::CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)tcp_listenoper,(LPVOID)tcp_port,0,&commandThreadID); if(commandThreadHandle!=NULL){ printf("<ไธป็จ‹ๅบ> ๆˆๅŠŸๅปบ็ซ‹ ๆŽฅๆ”ถๅ‘ฝไปค ็บฟ็จ‹ %d\n",commandThreadID); }else { ::MessageBox(NULL,_T("็จ‹ๅบๆ‰ง่กŒ ๅปบ็ซ‹ๆŽฅๆ”ถๅ‘ฝไปค็บฟ็จ‹ ๅคฑ่ดฅ๏ผŒ่ฏท้‡ๆ–ฐๆ‰ง่กŒ"),_T("้”™่ฏฏ"),0); exit(1); return 1; } }else { ::MessageBox(NULL,_T("็จ‹ๅบๆ‰ง่กŒ ๅปบ็ซ‹่Žทๅ–IP็บฟ็จ‹ ๅคฑ่ดฅ๏ผŒ่ฏท้‡ๆ–ฐๆ‰ง่กŒ"),_T("้”™่ฏฏ"),0); exit(1); return 1; } while(true); return 0; /* if(udp_sendiphostname(udp_port)==0){ iret = tcp_listenoper(tcp_port); if(iret!=0){ ::MessageBox(NULL,_T("็จ‹ๅบๆ‰ง่กŒๅคฑ่ดฅ๏ผŒ่ฏท้‡ๆ–ฐๆ‰ง่กŒ"),_T("้”™่ฏฏ"),0); exit(1); return 1; } }else { ::MessageBox(NULL,_T("็จ‹ๅบๆ‰ง่กŒๅคฑ่ดฅ๏ผŒ่ฏท้‡ๆ–ฐๆ‰ง่กŒ"),_T("้”™่ฏฏ"),0); exit(1); return 1; } return 0; */ }
[ [ [ 1, 111 ] ] ]
f25d4f1ac04f527b3d9fd7c0972395e49fd72872
f89e32cc183d64db5fc4eb17c47644a15c99e104
/pcsx2-rr/common/include/Utilities/SafeArray.h
f28d4c22395846b798e11607e9901224e37143c0
[]
no_license
mauzus/progenitor
f99b882a48eb47a1cdbfacd2f38505e4c87480b4
7b4f30eb1f022b08e6da7eaafa5d2e77634d7bae
refs/heads/master
2021-01-10T07:24:00.383776
2011-04-28T11:03:43
2011-04-28T11:03:43
45,171,114
0
0
null
null
null
null
UTF-8
C++
false
false
8,173
h
/* PCSX2 - PS2 Emulator for PCs * Copyright (C) 2002-2010 PCSX2 Dev Team * * PCSX2 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 Found- * ation, either version 3 of the License, or (at your option) any later version. * * PCSX2 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 PCSX2. * If not, see <http://www.gnu.org/licenses/>. */ #pragma once ////////////////////////////////////////////////////////////////////////////////////////// // Safe deallocation macros -- checks pointer validity (non-null) when needed, and sets // pointer to null after deallocation. #define safe_delete( ptr ) \ ((void) (delete (ptr)), (ptr) = NULL) #define safe_delete_array( ptr ) \ ((void) (delete[] (ptr)), (ptr) = NULL) // No checks for NULL -- wxWidgets says it's safe to skip NULL checks and it runs on // just about every compiler and libc implementation of any recentness. #define safe_free( ptr ) \ ( (void) (free( ptr ), !!0), (ptr) = NULL ) //((void) (( ( (ptr) != NULL ) && (free( ptr ), !!0) ), (ptr) = NULL)) #define safe_fclose( ptr ) \ ((void) (( ( (ptr) != NULL ) && (fclose( ptr ), !!0) ), (ptr) = NULL)) // Implementation note: all known implementations of _aligned_free check the pointer for // NULL status (our implementation under GCC, and microsoft's under MSVC), so no need to // do it here. #define safe_aligned_free( ptr ) \ ((void) ( _aligned_free( ptr ), (ptr) = NULL )) #define SafeSysMunmap( ptr, size ) \ ((void) ( HostSys::Munmap( (uptr)(ptr), size ), (ptr) = NULL )) // Microsoft Windows only macro, useful for freeing out COM objects: #define safe_release( ptr ) \ ((void) (( ( (ptr) != NULL ) && ((ptr)->Release(), !!0) ), (ptr) = NULL)) // -------------------------------------------------------------------------------------- // SafeArray // -------------------------------------------------------------------------------------- // Handy little class for allocating a resizable memory block, complete with exception // error handling and automatic cleanup. A lightweight alternative to std::vector. // template< typename T > class SafeArray { DeclareNoncopyableObject(SafeArray); public: static const int DefaultChunkSize = 0x1000 * sizeof(T); public: wxString Name; // user-assigned block name int ChunkSize; protected: T* m_ptr; int m_size; // size of the allocation of memory protected: SafeArray( const wxChar* name, T* allocated_mem, int initSize ); virtual T* _virtual_realloc( int newsize ); // A safe array index fetcher. Asserts if the index is out of bounds (dev and debug // builds only -- no bounds checking is done in release builds). T* _getPtr( uint i ) const { IndexBoundsAssumeDev( Name.c_str(), i, m_size ); return &m_ptr[i]; } public: virtual ~SafeArray() throw(); explicit SafeArray( const wxChar* name=L"Unnamed" ); explicit SafeArray( int initialSize, const wxChar* name=L"Unnamed" ); void Dispose(); void ExactAlloc( int newsize ); void MakeRoomFor( int newsize ) { if( newsize > m_size ) ExactAlloc( newsize ); } bool IsDisposed() const { return (m_ptr==NULL); } // Returns the size of the memory allocation, as according to the array type. int GetLength() const { return m_size; } // Returns the size of the memory allocation in bytes. int GetSizeInBytes() const { return m_size * sizeof(T); } // Extends the containment area of the array. Extensions are performed // in chunks. void GrowBy( int items ) { MakeRoomFor( m_size + ChunkSize + items + 1 ); } // Gets a pointer to the requested allocation index. // DevBuilds : Generates assertion if the index is invalid. T *GetPtr( uint idx=0 ) { return _getPtr( idx ); } const T *GetPtr( uint idx=0 ) const { return _getPtr( idx ); } // Gets an element of this memory allocation much as if it were an array. // DevBuilds : Generates assertion if the index is invalid. T& operator[]( int idx ) { return *_getPtr( (uint)idx ); } const T& operator[]( int idx ) const { return *_getPtr( (uint)idx ); } virtual SafeArray<T>* Clone() const; }; ////////////////////////////////////////////////////////////////////////////////////////// // SafeList - Simple growable container without all the mess or hassle of std containers. // // This container is intended for reasonably simple class types only. Things which this // container does not handle with desired robustness: // // * Classes with non-trivial constructors (such that construction creates much overhead) // * Classes with copy constructors (copying is done using performance memcpy) // * Classes with destructors (they're not called, sorry!) // template< typename T > class SafeList { DeclareNoncopyableObject(SafeList); public: static const int DefaultChunkSize = 0x80 * sizeof(T); public: wxString Name; // user-assigned block name int ChunkSize; // assigned DefaultChunkSize on init, reconfigurable at any time. protected: T* m_ptr; int m_allocsize; // size of the allocation of memory uint m_length; // length of the array (active items, not buffer allocation) protected: virtual T* _virtual_realloc( int newsize ); void _MakeRoomFor_threshold( int newsize ); T* _getPtr( uint i ) const { IndexBoundsAssumeDev( Name.c_str(), i, m_length ); return &m_ptr[i]; } public: virtual ~SafeList() throw(); explicit SafeList( const wxChar* name=L"Unnamed" ); explicit SafeList( int initialSize, const wxChar* name=L"Unnamed" ); virtual SafeList<T>* Clone() const; void Remove( int index ); void MakeRoomFor( int blockSize ); T& New(); int Add( const T& src ); T& AddNew( const T& src ); // Returns the size of the list, as according to the array type. This includes // mapped items only. The actual size of the allocation may differ. int GetLength() const { return m_length; } // Returns the size of the list, in bytes. This includes mapped items only. // The actual size of the allocation may differ. int GetSizeInBytes() const { return m_length * sizeof(T); } void MatchLengthToAllocatedSize() { m_length = m_allocsize; } void GrowBy( int items ) { MakeRoomFor( m_length + ChunkSize + items + 1 ); } // Sets the item length to zero. Does not free memory allocations. void Clear() { m_length = 0; } // Gets an element of this memory allocation much as if it were an array. // DevBuilds : Generates assertion if the index is invalid. T& operator[]( int idx ) { return *_getPtr( (uint)idx ); } const T& operator[]( int idx ) const { return *_getPtr( (uint)idx ); } T* GetPtr() { return m_ptr; } const T* GetPtr() const { return m_ptr; } T& GetLast() { return m_ptr[m_length-1]; } const T& GetLast() const{ return m_ptr[m_length-1]; } }; // -------------------------------------------------------------------------------------- // SafeAlignedArray<T> // -------------------------------------------------------------------------------------- // Handy little class for allocating a resizable memory block, complete with // exception-based error handling and automatic cleanup. // This one supports aligned data allocations too! template< typename T, uint Alignment > class SafeAlignedArray : public SafeArray<T> { typedef SafeArray<T> _parent; protected: T* _virtual_realloc( int newsize ); public: using _parent::operator[]; virtual ~SafeAlignedArray() throw(); explicit SafeAlignedArray( const wxChar* name=L"Unnamed" ) : SafeArray<T>::SafeArray( name ) { } explicit SafeAlignedArray( int initialSize, const wxChar* name=L"Unnamed" ); virtual SafeAlignedArray<T,Alignment>* Clone() const; };
[ "koeiprogenitor@bfa1b011-20a7-a6e3-c617-88e5d26e11c5" ]
[ [ [ 1, 240 ] ] ]
70a89f6bfefe694d63ac39aaefc7b13dda10112f
374f53386d36e3aadf0ed88e006394220f732f30
/gl/simple/InitGL.cpp
f1601e671bebf358a21b9e325e8a5f200902b971
[ "MIT" ]
permissive
yatjf/sonson-code
e7edbc613f8c97be5f7c7367be2660b3cb75a61b
fbb564af37adb2305fe7d2148f8d4f5a3450f72b
refs/heads/master
2020-06-13T08:02:38.469864
2010-07-01T14:20:40
2010-07-01T14:20:40
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
4,716
cpp
// // simple // InitGL.cpp // // The MIT License // // Copyright (c) 2009 sonson, sonson@Picture&Software // // 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. ////////////////////////////////////////////////////////////////////// //OpenGLใฎๅˆๆœŸๅŒ–ใ€ใƒชใ‚ตใ‚คใ‚บใซ้–ขใ™ใ‚‹้–ขๆ•ฐ InitGL.cpp #include "InitGL.h" //OpenGLใƒฌใƒณใƒ€ใƒชใƒณใ‚ฐใ‚ณใƒณใƒ†ใ‚ญใ‚นใƒˆใฎไฝœๆˆ //ใƒ”ใ‚ฏใ‚ปใƒซใƒ•ใ‚ฉใƒผใƒžใƒƒใƒˆใฎ่จญๅฎš HGLRC Init_Pixel(HWND hWnd) { HGLRC hRC; HDC hDC; int pixelformat; static PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), //ใ“ใฎๆง‹้€ ไฝ“ใฎใ‚ตใ‚คใ‚บ 1, //OpenGLใƒใƒผใ‚ธใƒงใƒณ PFD_DRAW_TO_WINDOW | //Windowใ‚นใ‚ฟใ‚คใƒซ PFD_SUPPORT_OPENGL | //OpenGL PFD_DOUBLEBUFFER, //ใƒ€ใƒ–ใƒซใƒใƒƒใƒ•ใ‚กไฝฟ็”จๅฏ่ƒฝ PFD_TYPE_RGBA, //RGBAใ‚ซใƒฉใƒผ 24, //่‰ฒๆ•ฐ 0, 0, //RGBAใฎใƒ“ใƒƒใƒˆใจใ‚ทใƒ•ใƒˆ่จญๅฎš 0, 0, //G 0, 0, //B 0, 0, //A 0, //ใ‚ขใ‚ญใƒฅใƒ ใƒฌใƒผใ‚ทใƒงใƒณใƒใƒƒใƒ•ใ‚ก 0, 0, 0, 0, //RGBAใ‚ขใ‚ญใƒฅใƒ ใƒฌใƒผใ‚ทใƒงใƒณใƒใƒƒใƒ•ใ‚ก 16, //Zใƒใƒƒใƒ•ใ‚ก 0, //ใ‚นใƒ†ใƒณใ‚ทใƒซใƒใƒƒใƒ•ใ‚ก 0, //ไฝฟ็”จใ—ใชใ„ PFD_MAIN_PLANE, //ใƒฌใ‚คใƒคใƒผใ‚ฟใ‚คใƒ— 0, //ไบˆ็ด„ 0, 0, 0 //ใƒฌใ‚คใƒคใƒผใƒžใ‚นใ‚ฏใฎ่จญๅฎšใƒปๆœชไฝฟ็”จ }; //ใƒ‡ใƒใ‚คใ‚นใ‚ณใƒณใƒ†ใ‚ญใ‚นใƒˆ if (!(hDC=GetDC(hWnd))){ MessageBox(hWnd,"Getting HDC Failed....","ERROR",MB_OK); return NULL; } //ใƒ”ใ‚ฏใ‚ปใƒซใƒ•ใ‚ฉใƒผใƒžใƒƒใƒˆใฎๆŒ‡ๅฎš if ( (pixelformat = ChoosePixelFormat(hDC, &pfd)) == 0 ){ MessageBox(hWnd, "ChoosePixelFormat Failed....", "Error", MB_OK); return NULL; } //ใƒ”ใ‚ฏใ‚ปใƒซใƒ•ใ‚ฉใƒผใƒžใƒƒใƒˆใฎ่จญๅฎš if (SetPixelFormat(hDC, pixelformat, &pfd) == FALSE){ MessageBox(hWnd, "SetPixelFormat Failed....", "Error", MB_OK); return NULL; } //OpenGLใƒฌใƒณใƒ€ใƒชใƒณใ‚ฐใ‚ณใƒณใƒ†ใ‚ญใ‚นใƒˆใฎไฝœๆˆ if (!(hRC=wglCreateContext(hDC))){ MessageBox(NULL,"Creating HGLRC Failed....","ERROR",MB_OK); return NULL; } ReleaseDC(hWnd,hDC); return hRC; } //ใ‚ฆใ‚ฃใƒณใƒ‰ใ‚ฆใฎใƒชใ‚ตใ‚คใ‚บๆ™‚ใฎๅ‡ฆ็† void Resize(HWND hWnd){ GLdouble aspect; RECT rect; //็พๅœจใฎใ‚ฆใ‚ฃใƒณใƒ‰ใ‚ฆใฎใ‚ตใ‚คใ‚บใ‚’ๅ–ๅพ— GetClientRect(hWnd, &rect); //ใใ‚Œใซใ‚ˆใฃใฆใƒ“ใƒฅใƒผใƒใƒผใƒˆใ‚’่จญๅฎšใ™ใ‚‹ glViewport(0, 0, rect.right, rect.bottom); //ใ‚ขใ‚นใƒšใ‚ฏใƒˆๆฏ”ใฎๅˆๆœŸๅŒ– aspect = (GLdouble)rect.right/(GLdouble)rect.bottom; //ใƒ—ใƒญใ‚ธใ‚งใ‚ฏใ‚ทใƒงใƒณใƒขใƒผใƒ‰ใงๅฐ„ๅฝฑ glMatrixMode( GL_PROJECTION ); glLoadIdentity(); gluPerspective( 60.0, aspect, 1.0, 10.0 ); //ใƒŽใƒผใƒžใƒซใฎใƒขใƒ‡ใƒซใƒ“ใƒฅใƒผใƒขใƒผใƒ‰ใธ็งป่กŒ glMatrixMode( GL_MODELVIEW ); } //ๅ„ใ‚ณใƒณใƒ†ใ‚ญใ‚นใƒˆใฎ่งฃๆ”พ void Release_GLWindow(HWND hWnd){ HDC hDC; HGLRC hRC; //OpenGLใƒฌใƒณใƒ€ใƒชใƒณใ‚ฐใ‚ณใƒณใƒ†ใ‚ญใ‚นใƒˆใจ //ใƒ‡ใƒใ‚คใ‚นใ‚ณใƒณใƒ†ใ‚ญใ‚นใƒˆใ‚’ๅ–ๅพ— hRC = wglGetCurrentContext(); hDC = wglGetCurrentDC(); //ใ‚ซใƒฌใƒณใƒˆใ‚ณใƒณใƒ†ใ‚ญใ‚นใƒˆใ‚’่งฃๆ”พ wglMakeCurrent(NULL, NULL); if(!hRC){ //OpenGLใƒฌใƒณใƒ€ใƒชใƒณใ‚ฐใ‚ณใƒณใƒ†ใ‚ญใ‚นใƒˆใŒใชใ„ MessageBox(hWnd,"Release HGLRC Failed....","ERROR",MB_OK); } if(hRC){ //่งฃๆ”พ wglDeleteContext(hRC); } if(!hDC){ //ใƒ‡ใƒใ‚คใ‚นใ‚ณใƒณใƒ†ใ‚ญใ‚นใƒˆใŒใชใ„ MessageBox(hWnd,"Release HDC Failed....","ERROR",MB_OK); } if(hDC){ //่งฃๆ”พ ReleaseDC(hWnd, hDC); } } //ๅ„GL Functionใฎ้–‹ๅง‹ void StartFunction(void){ glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); //ใ‚ฏใƒฉใ‚คใ‚ขใƒณใƒˆ้ ˜ๅŸŸใฎๅก—ใ‚Šใคใถใ—่‰ฒใฎ่จญๅฎš glClearColor( 1.0, 1.0, 1.0, 1.0 ); //ใƒ‡ใƒ—ใ‚นใƒใƒƒใƒ•ใ‚กใ‚ฏใƒชใ‚ขๅ€คใฎ่จญๅฎš glClearDepth( 1.0 ); }
[ "yoshida.yuichi@0d0a6a56-2bd1-11de-9cad-a3574e5575ef" ]
[ [ [ 1, 138 ] ] ]
68d1628d84245b59bd493b7134e8617348019e52
96a48df2a03d542068be2cbe140500bc99f52725
/stereomatchingsgbm.cpp
9a8f573ee4fa794026a0ea5d6d156fcf8a73e9ea
[]
no_license
noahkong/stereocam
d0bbffafba8815ac3531dd59c5f270b67b52a11d
19749024834ed11767c114370fc55aeb41f75e2c
refs/heads/master
2020-05-30T14:50:32.032286
2011-03-26T18:51:33
2011-03-26T18:51:33
32,440,548
0
0
null
null
null
null
UTF-8
C++
false
false
3,444
cpp
#include "stereomatchingsgbm.hpp" using namespace std; using namespace cv; StereoMatchingSGBM::StereoMatchingSGBM(): StereoMatching("Semi-Global Block Matching"), I_minDisparity(0), I_numberOfDisparities(1), I_SADWindowSize(2), I_preFilterCap(3), I_uniquenessRatio(4), I_speckleWindowSize(5), I_speckleRange(6), I_disp12MaxDiff(7), I_fullDP(8){ init(); } StereoMatchingSGBM::~StereoMatchingSGBM(){ } void StereoMatchingSGBM::init(){ //0 Property * prop = new Property("Minimum disparity", 0, Property::INT); prop->minValue = -50; prop->maxValue = 50; prop->step = 5; properties.push_back(prop); //1 prop = new Property("Number of disparities", 2, Property::DISCRETE); int max = 4; int * values = new int[max]; for(int i = 0; i < max; ++i) values[i] = 16*i; prop->minValue = 0; prop->maxValue = max; prop->tableValues = values; properties.push_back(prop); //2 prop = new Property("SAD window size", 5, Property::DISCRETE); max = 8; int defValues[8] = {1, 3, 5, 7, 9, 11, 21, 31}; int * values2 = new int[max]; for(int i = 0; i < max; ++i) values2[i] = defValues[i]; prop->minValue = 0; prop->maxValue = max; prop->tableValues = values2; properties.push_back(prop); //3 prop = new Property("PrefilterCap", 31, Property::INT); prop->minValue = 0; prop->maxValue = 50; properties.push_back(prop); //4 prop = new Property("UniquenessRatio", 1, Property::INT); prop->minValue = 0; prop->maxValue = 35; properties.push_back(prop); //5 prop = new Property("Speckle window size", 400, Property::INT); prop->minValue = 0; prop->maxValue = 500; prop->step = 50; properties.push_back(prop); //6 prop = new Property("Speckle range", 1, Property::DISCRETE); max = 4; int * values3 = new int[max]; for(int i = 0; i < max; ++i) values3[i] = 16*i; prop->minValue = 0; prop->maxValue = max; prop->tableValues = values; properties.push_back(prop); //7 prop = new Property("Disparity max difference", 2, Property::INT); prop->minValue = -1; prop->maxValue = 20; properties.push_back(prop); //8 prop = new Property("Use full DP", 0, Property::BOOL); properties.push_back(prop); applyAllParametres(); } void StereoMatchingSGBM::applyAllParametres(){ changeProperties(); sgbm.preFilterCap = properties[I_preFilterCap]->getValue(); sgbm.SADWindowSize = properties[I_SADWindowSize]->tableValues[properties[I_SADWindowSize]->getValue()]; sgbm.P1 = 16*sgbm.SADWindowSize*sgbm.SADWindowSize; sgbm.P2 = 64*sgbm.SADWindowSize*sgbm.SADWindowSize; sgbm.minDisparity = properties[I_minDisparity]->getValue(); sgbm.numberOfDisparities = properties[I_numberOfDisparities]->tableValues[properties[I_numberOfDisparities]->getValue()]; sgbm.uniquenessRatio = properties[I_uniquenessRatio]->getValue(); sgbm.speckleWindowSize = properties[I_speckleWindowSize]->getValue(); sgbm.speckleRange = properties[I_speckleRange]->tableValues[properties[I_speckleRange]->getValue()]; sgbm.disp12MaxDiff = properties[I_disp12MaxDiff]->getValue(); sgbm.fullDP = (bool)properties[I_fullDP]->getValue(); } void StereoMatchingSGBM::exec(Mat & image1, Mat & image2, Mat & retImage){ Mat disp; sgbm(image1, image2, disp); disp.convertTo(retImage, CV_8U, 255/(sgbm.numberOfDisparities*16.)); }
[ "[email protected]@e744e3f1-1be2-aab4-d40b-2ba3014caec9" ]
[ [ [ 1, 139 ] ] ]
7ea4b3291750756f78799441014869ead7753a46
1d693dd1b12b23c72dd0bb12a3fc29ed88a7e2d5
/src/nbpflcompiler/irlowering.h
1ad15eaa95009bac3e3bc17c1e15d273e03c9fce
[]
no_license
rrdenicol/Netbee
8765ebc2db4ba9bd27c2263483741b409da8300a
38edb4ffa78b8fb7a4167a5d04f40f8f4466be3e
refs/heads/master
2021-01-16T18:42:17.961177
2011-12-26T20:27:03
2011-12-26T20:27:03
3,053,086
0
0
null
null
null
null
UTF-8
C++
false
false
5,655
h
/*****************************************************************************/ /* */ /* Copyright notice: please read file license.txt in the NetBee root folder. */ /* */ /*****************************************************************************/ #pragma once #include "compunit.h" #include "ircodegen.h" #define LOOKUP_EX_OP_INIT (uint32)0 #define LOOKUP_EX_OP_INIT_TABLE 1 #define LOOKUP_EX_OP_ADD_KEY 2 #define LOOKUP_EX_OP_ADD_VALUE 3 #define LOOKUP_EX_OP_SELECT 4 #define LOOKUP_EX_OP_GET_VALUE 5 #define LOOKUP_EX_OP_UPD_VALUE 6 #define LOOKUP_EX_OP_DELETE 7 #define LOOKUP_EX_OP_RESET 8 #define LOOKUP_EX_OUT_TABLE_ID (uint32)0 #define LOOKUP_EX_OUT_ENTRIES 1 #define LOOKUP_EX_OUT_KEYS_SIZE 2 #define LOOKUP_EX_OUT_VALUES_SIZE 3 #define LOOKUP_EX_OUT_GENERIC 1 #define LOOKUP_EX_OUT_VALUE_OFFSET 1 #define LOOKUP_EX_OUT_VALUE 6 #define LOOKUP_EX_OUT_FIELD_SIZE 5 #define LOOKUP_EX_OUT_FIELD_VALUE 6 #define LOOKUP_EX_IN_VALID 7 #define LOOKUP_EX_IN_VALUE 6 #define REGEX_MATCH 1 #define REGEX_MATCH_WITH_OFFSET 2 #define REGEX_GET_RESULT 3 #define REGEX_OUT_PATTERN_ID 0 #define REGEX_OUT_BUF_OFFSET 1 #define REGEX_OUT_BUF_LENGTH 2 #define REGEX_IN_MATCHES_FOUND (uint32)0 #define REGEX_IN_OFFSET_FOUND 2 #define REGEX_IN_LENGTH_FOUND 3 class IRLowering { struct JCondInfo { SymbolLabel *TrueLbl; SymbolLabel *FalseLbl; JCondInfo(SymbolLabel *trueLbl, SymbolLabel *falseLbl) :TrueLbl(trueLbl), FalseLbl(falseLbl){} }; struct LoopInfo { SymbolLabel *LoopStart; SymbolLabel *LoopExit; LoopInfo(SymbolLabel *start, SymbolLabel *exit) :LoopStart(start), LoopExit(exit){} }; CompilationUnit &m_CompUnit; IRCodeGen &m_CodeGen; SymbolProto *m_Protocol; GlobalSymbols &m_GlobalSymbols; list<LoopInfo> m_LoopStack; uint32 m_TreeDepth; SymbolLabel *m_FilterFalse; SymbolTemp *AssociateVarTemp(SymbolVarInt *var); void TranslateLabel(StmtLabel *stmt); void TranslateGen(StmtGen *stmt); SymbolLabel *ManageLinkedLabel(SymbolLabel *label, string name); void TranslateJump(StmtJump *stmt); void TranslateSwitch(StmtSwitch *stmt); void TranslateCase(StmtSwitch *newSwitchSt, StmtCase *caseSt, SymbolLabel *swExit, bool IsDefault); void TranslateCases(StmtSwitch *newSwitchSt, CodeList *cases, SymbolLabel *swExit); void TranslateSwitch2(StmtSwitch *stmt); void TranslateIf(StmtIf *stmt); void TranslateLoop(StmtLoop *stmt); void TranslateWhileDo(StmtWhile *stmt); void TranslateDoWhile(StmtWhile *stmt); void TranslateBreak(StmtCtrl *stmt); void TranslateContinue(StmtCtrl *stmt); Node *TranslateTree(Node *node); Node *TranslateIntVarToInt(Node *node); Node *TranslateCInt(Node *node); Node *TranslateStrVarToInt(Node *node, Node* offset, uint32 size); Node *TranslateFieldToInt(Node *node, Node* offset, uint32 size); Node *GenMemLoad(Node *offsNode, uint32 size); Node *TranslateConstInt(Node *node); Node *TranslateConstStr(Node *node); Node *TranslateConstBool(Node *node); Node *TranslateTemp(Node *node); void TranslateBoolExpr(Node *expr, JCondInfo &jcInfo); void TranslateRelOpInt(uint16 op, Node *relopExpr, JCondInfo &jcInfo); void TranslateRelOpStr(uint16 op, Node *relopExpr, JCondInfo &jcInfo); void TranslateRelOpStrOperand(Node *operand, Node **loadOperand, Node **loadSize, uint32 *size); void TranslateRelOpLookup(uint16 opCode, Node *expr, JCondInfo &jcInfo); void TranslateRelOpRegEx(Node *expr, JCondInfo &jcInfo); bool TranslateLookupSetValue(SymbolLookupTableEntry *entry, SymbolLookupTableValuesList *values, bool isKeysList); bool TranslateLookupSelect(SymbolLookupTableEntry *entry, SymbolLookupTableValuesList *keys); void TranslateLookupInitTable(Node *node); void TranslateLookupInit(Node *node); void TranslateLookupUpdate(Node *node); void TranslateLookupDelete(Node *node); void TranslateLookupAdd(Node *node); void TranslateFieldDef(Node *node); void TranslateVarDeclInt(Node *node); void TranslateVarDeclStr(Node *node); void TranslateAssignInt(Node *node); void TranslateAssignStr(Node *node); void TranslateAssignRef(SymbolVarBufRef *refVar, Node *right); Node *TranslateArithBinOp(uint16 op, Node *node); Node *TranslateArithUnOp(uint16 op, Node *node); Node *TranslateDiv(Node *node); void TranslateStatement(StmtBase *stmt); void LowerHIRCode(CodeList *code); void EnterLoop(SymbolLabel *start, SymbolLabel *exit); void ExitLoop(void); void GenTempForVar(Node *node); void GenerateInfo(string message, char *file, char *function, int line, int requiredDebugLevel, int indentation); void GenerateWarning(string message, char *file, char *function, int line, int requiredDebugLevel, int indentation); void GenerateError(string message, char *file, char *function, int line, int requiredDebugLevel, int indentation); public: IRLowering(CompilationUnit &compUnit, IRCodeGen &codeGen, SymbolLabel *filterFalse) :m_CompUnit(compUnit), m_CodeGen(codeGen), m_Protocol(0), m_GlobalSymbols(codeGen.GetGlobalSymbols()), m_TreeDepth(0), m_FilterFalse(filterFalse) { m_CompUnit.MaxStack = 0; m_CompUnit.NumLocals = 0; } void LowerHIRCode(CodeList *code, SymbolProto *proto, string comment = ""); void LowerHIRCode(CodeList *code, string comment); };
[ [ [ 1, 209 ] ] ]
a1fcdba46db7fb2856d8543d09a92ea6557bded1
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/zombie/nphysics/src/nphysics/ncphycloth_main.cc
48f74a9376f1c33852d74a53607c0bf43e6585c6
[]
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
21,840
cc
#include "precompiled/pchnphysics.h" //----------------------------------------------------------------------------- // ncphycloth_main.cc // (C) 2005 Conjurer Services, S.A. //----------------------------------------------------------------------------- #include "nphysics/ncphycloth.h" #include "nphysics/nphygeomtrimesh.h" #include "nphysics/nphygeomray.h" #include "nphysics/nphygeomsphere.h" //----------------------------------------------------------------------------- nNebulaComponentObject(ncPhyCloth,ncPhySimpleObj); //----------------------------------------------------------------------------- phyreal ncPhyCloth::massCloth(phyreal(.1)); phyreal ncPhyCloth::airResistance(phyreal(0.6)); //----------------------------------------------------------------------------- /** Constructor history: - 05-Jun-2005 Zombie created */ ncPhyCloth::ncPhyCloth() : nodesXAxis( 21 ), // Default values nodesZAxis( 21 ), separationXAxis( phyreal(.1) ), separationZAxis( phyreal(.1) ), numTotalNodes(0), bufferVertexes(0), mesh(0), bufferIndexes(0), velocity(0,0,0), forceAccumulated(0,0,0), nodesInfo(0), nodesCollisionPoints(0), numCollisionPoints(0), nodesHalfPoints(0), numHalfPoints(0), nodesRestPoints(0), numRestPoints(0) { } //----------------------------------------------------------------------------- /** Destructor history: - 05-Jun-2005 Zombie created */ ncPhyCloth::~ncPhyCloth() { n_delete_array( this->bufferIndexes ); n_delete_array( this->bufferVertexes ); n_delete_array( this->nodesInfo ); n_delete_array( this->nodesCollisionPoints ); n_delete_array( this->nodesHalfPoints ); n_delete_array( this->nodesRestPoints ); } //----------------------------------------------------------------------------- /** User init instance code @param loaded indicates if the instance is bare new of loaded history: - 05-Jun-2005 Zombie created */ void ncPhyCloth::InitInstance(nObject::InitInstanceMsg initType) { ncPhySimpleObj::InitInstance( initType ); } //----------------------------------------------------------------------------- /** Creates the object @param world it's the world where the object will be come to existance history: - 05-Jun-2005 Zombie created */ void ncPhyCloth::Create( nPhysicsWorld* world ) { n_assert2( world, "Null pointer." ); n_assert2( this->nodesXAxis & 1, "The number of nodes has to be odd." ); n_assert2( this->nodesZAxis & 1, "The number of nodes has to be odd." ); this->mesh = static_cast<nPhyGeomTriMesh*>(nKernelServer::Instance()->New( "nphygeomtrimesh" ) ); n_assert2( this->mesh, "Failed to create a nPhyGeomTriMesh." ); this->SetGeometry( this->mesh ); this->BuildMesh(); ncPhySimpleObj::Create( world ); this->RegisterForPostProcess(); this->nodesInfo[0].tied = true; this->nodesInfo[20].tied = true; } //----------------------------------------------------------------------------- /** Builds the mesh representing the rectangular piece of cloth. history: - 05-Jun-2005 Zombie created */ void ncPhyCloth::BuildMesh() { /// creating structure to hold the mesh this->numTotalNodes = this->nodesXAxis * this->nodesZAxis; this->bufferVertexes = n_new_array( phyreal, this->numTotalNodes * 3 ); n_assert2( this->bufferVertexes, "Run out of memory." ); this->mesh->SetBufferVertexes( this->numTotalNodes, this->bufferVertexes ); int numberOfIndexes( (this->nodesXAxis-1) * (this->nodesZAxis-1) * 6 ); this->bufferIndexes = n_new_array( int, numberOfIndexes ); n_assert2( this->bufferIndexes, "Run out of memory." ); this->mesh->SetBufferIndexes( numberOfIndexes, this->bufferIndexes ); /// filing with data the mesh // creating the vertexes data phyreal *ptrBuffer( this->bufferVertexes ); for( unsigned indexZ(0); indexZ < this->nodesZAxis; ++indexZ ) { vector3 position( 0,0, phyreal( indexZ ) * separationZAxis ); for( unsigned indexX(0); indexX < this->nodesXAxis; ++indexX,++ptrBuffer ) { position.x = indexX * separationXAxis; *ptrBuffer = position.x; *++ptrBuffer = position.y; *++ptrBuffer = position.z; } } // creating the indexes data int *ptrIndexes( this->bufferIndexes ); for( unsigned indexZ(0); indexZ < this->nodesZAxis - 1; ++indexZ ) { for( unsigned indexX(0); indexX < this->nodesXAxis - 1; ++indexX, ++ptrIndexes ) { // top triangle *ptrIndexes = indexZ * this->nodesZAxis + indexX; *++ptrIndexes = indexZ * this->nodesZAxis + indexX + 1; *++ptrIndexes = (indexZ+1) * this->nodesZAxis + indexX + 1; // botton triangle *++ptrIndexes = indexZ * this->nodesZAxis + indexX; *++ptrIndexes = (indexZ+1) * this->nodesZAxis + indexX + 1; *++ptrIndexes = (indexZ+1) * this->nodesZAxis + indexX; } } this->mesh->Update(); // info nodes this->nodesInfo = n_new_array( nodeInfo, this->numTotalNodes ); // collision nodes this->numCollisionPoints = (( this->nodesXAxis + 1 ) / 2)*(( this->nodesZAxis + 1 ) / 2); this->nodesCollisionPoints = n_new_array( nodeInfo*, this->numCollisionPoints ); // half point nodes this->numHalfPoints = (( this->nodesXAxis - 1 ) / 2) * (( this->nodesZAxis - 1 ) / 2); this->nodesHalfPoints = n_new_array( nodeInfo*, this->numHalfPoints ); // rest point nodes this->numRestPoints = (((this->nodesXAxis - 1 ) / 2) * (this->nodesZAxis-1) / 2) + (((this->nodesXAxis+1) / 2) * (this->nodesZAxis+1) / 2) - 1; this->nodesRestPoints = n_new_array( nodeInfo*, this->numRestPoints ); nodeInfo* node(this->nodesInfo); ptrBuffer = this->bufferVertexes; int counterCollisionPoints(0); int counterHalfPointsPoints(0); int counterRestPoints(0); for( int indexZ(0); indexZ < int(this->nodesZAxis); ++indexZ ) { for( int indexX(0); indexX < int(this->nodesXAxis); ++indexX, ++node, ptrBuffer+=3 ) { node->tied = false; node->numNodes = 0; // DANGEROUS: node->oldposition = reinterpret_cast<vector3*>(ptrBuffer); node->newposition = *node->oldposition; node->changed = false; if( !(indexZ & 1) && !(indexX & 1 ) ) { // collision point // only needs the next two points in X and Z // first in horizontal node->nodes[0] = this->GetNode( indexX + 2, indexZ ); if( node->nodes[0] ) ++node->numNodes; // then vertical node->nodes[1] = this->GetNode( indexX, indexZ + 2 ); if( node->nodes[1] ) ++node->numNodes; this->nodesCollisionPoints[ counterCollisionPoints++ ] = node; continue; } if( ( indexZ & 1 ) && ( indexX & 1 ) ) { // half - point // only needs the four points in x node->nodes[node->numNodes] = this->GetNode( indexX - 1, indexZ - 1 ); if( node->nodes[node->numNodes] ) ++node->numNodes; node->nodes[node->numNodes] = this->GetNode( indexX + 1, indexZ - 1 ); if( node->nodes[node->numNodes] ) ++node->numNodes; node->nodes[node->numNodes] = this->GetNode( indexX - 1, indexZ + 1 ); if( node->nodes[node->numNodes] ) ++node->numNodes; node->nodes[node->numNodes] = this->GetNode( indexX + 1, indexZ + 1 ); if( node->nodes[node->numNodes] ) ++node->numNodes; this->nodesHalfPoints[ counterHalfPointsPoints++ ] = node; continue; } // checking borders bool leftXBorder(false); bool rightXBorder(false); if( indexX - 1 < 0 ) { leftXBorder = true; } if( indexX + 1 >= int(this->nodesXAxis) ) { rightXBorder = true; } bool leftZBorder(false); bool rightZBorder(false); if( indexZ - 1 < 0 ) { leftZBorder = true; } if( indexZ + 1 >= int(this->nodesZAxis) ) { rightZBorder = true; } // the rest of the points if( !rightZBorder ) { node->nodes[node->numNodes] = this->GetNode( indexX , indexZ - 1 ); if( node->nodes[node->numNodes] ) ++node->numNodes; } if( !leftZBorder ) { node->nodes[node->numNodes] = this->GetNode( indexX , indexZ + 1 ); if( node->nodes[node->numNodes] ) ++node->numNodes; } if( !rightXBorder ) { node->nodes[node->numNodes] = this->GetNode( indexX - 1, indexZ ); if( node->nodes[node->numNodes] ) ++node->numNodes; } if( !leftXBorder ) { node->nodes[node->numNodes] = this->GetNode( indexX + 1, indexZ ); if( node->nodes[node->numNodes] ) ++node->numNodes; } this->nodesRestPoints[ counterRestPoints++ ] = node; } } } //----------------------------------------------------------------------------- /** Adds a force. @param force adds a general force to the cloth piece history: - 05-Jun-2005 Zombie created */ void ncPhyCloth::AddForce( const vector3& force ) { this->forceAccumulated += force; } //----------------------------------------------------------------------------- /** Function to be process after running the simulation. history: - 05-Jun-2005 Zombie created */ void ncPhyCloth::PostProcess() { /// runs the simulation // pre-calculus nodeInfo* node(0); vector3 gravity(0,-.5f/60.f,0); for( int index(0); index < this->numCollisionPoints; ++index ) { node = this->nodesCollisionPoints[ index ]; node->force += this->forceAccumulated + gravity; node->normals = 0; node->normal = vector3(0,0,0); if( node->tied == false ) { // computing every node velocity node->velocity *= airResistance; node->velocity += node->force / massCloth; if( node->velocity.lensquared() < phyreal(.001*.001) ) { node->velocity = vector3(0,0,0); } node->force = vector3(0,0,0); } } this->Move(); // reseting the accumulated forces this->forceAccumulated = vector3(0,0,0); } //----------------------------------------------------------------------------- /** Un/sets tied point (not allowed to tie completely, max two sides). @param xNode coordinate x for a node @param zNode coordinate z for a node @param is specifies if the node is tied or not history: - 05-Jun-2005 Zombie created */ void ncPhyCloth::SetTiedNode( const unsigned xNode, const unsigned zNode, bool is ) { n_assert2( this->GetWorld(), "This operation can't be performed until the object it's in the world." ); n_assert2( xNode < this->nodesXAxis, "Index out of bounds." ); n_assert2( zNode < this->nodesZAxis, "Index out of bounds." ); this->nodesInfo[ zNode * this->nodesZAxis + xNode ].tied = is; } //----------------------------------------------------------------------------- /** Moves the cloth in the world. history: - 05-Jun-2005 Zombie created */ void ncPhyCloth::Move() { // TODO: find the real one static phyreal timeFrame( phyreal(1) / phyreal(60) ); nodeInfo* node(this->nodesInfo); for( int index(0); index < int(this->numTotalNodes); ++index, ++node ) { node->normals = 0; } for( int index(0); index < this->numCollisionPoints; ++index ) { node = this->nodesCollisionPoints[ index ]; node->normal = vector3(0,0,0); node->changed = false; if( !node->tied ) { node->newposition += node->velocity * timeFrame; if( node->velocity.lensquared() ) node->changed = true; } } nodeInfo* nodeNext(0); static unsigned numIterations(5); /// applies the constrains between nodes for( unsigned iteration(0); iteration < numIterations; ++iteration ) { // horizontal for( int index(0); index < this->numCollisionPoints; ++index ) { node = this->nodesCollisionPoints[ index ]; nodeNext = node->nodes[0]; if( nodeNext ) { vector3 direction( nodeNext->newposition - node->newposition ); phyreal diference( direction.len() - (this->separationXAxis*2.f) ); phyreal absdiference(fabs(diference)); if( absdiference > phyreal(.0001) ) { direction.norm(); if( diference < 0 ) direction *= phyreal(-1); direction *= absdiference; if( node->tied ) { if( !nodeNext->tied ) { nodeNext->newposition -= direction; } } else { if( !nodeNext->tied ) { node->newposition += direction * phyreal(.5); nodeNext->newposition += direction * phyreal(-.5); } else { node->newposition += direction; } } } node->changed = true; nodeNext->changed = true; } // vertical nodeNext = node->nodes[1]; if( !nodeNext ) continue; vector3 direction( nodeNext->newposition - node->newposition ); phyreal diference( direction.len() - (this->separationXAxis*2.f) ); phyreal absdiference(fabs(diference)); if( absdiference < phyreal(.0001) ) continue; direction.norm(); if( diference < 0 ) direction *= phyreal(-1); direction *= absdiference; if( node->tied ) { if( !nodeNext->tied ) { nodeNext->newposition -= direction; } } else { if( !nodeNext->tied ) { node->newposition += direction * phyreal(.5); nodeNext->newposition += direction * phyreal(-.5); } else { node->newposition += direction; } } node->changed = true; nodeNext->changed = true; } } static nPhyGeomSphere* ray( static_cast<nPhyGeomSphere*>(nKernelServer::Instance()->New( "nphygeomsphere" ))); ray->SetCategories(0); ray->SetCollidesWith(-1); static phyreal distance(phyreal(0.01)); ray->SetRadius( distance ); vector3 geomposition; this->GetGeometry()->GetPosition(geomposition); this->GetGeometry()->Disable(); // nPhySpace* space( this->GetParentSpace() ); /// check for collision for( int index(0); index < this->numCollisionPoints; ++index ) { node = this->nodesCollisionPoints[ index ]; if( node->tied ) continue; ray->SetPosition( node->newposition + geomposition ); nPhyCollide::nContact contact; if( nPhysicsServer::Instance()->Collide( ray, 1, &contact ) ) //if( nPhyCollide::Collide( ray->Id(), space->Id(), 1, &contact ) ) { bool normalInverse(false); if( contact.GetGeometryA() == ray ) normalInverse = true; vector3 normal; contact.GetContactPosition( node->newposition ); contact.GetContactNormal( node->normal ); if( normalInverse ) node->normal *= phyreal(-1); node->normal *= -(distance + contact.GetContactPenetrationDepth()); node->newposition += node->normal - geomposition; node->normals = 1; node->changed = true; node->normal.norm(); } } this->GetGeometry()->Enable(); node = nodesInfo; // calculating the half points for( int index(0); index < this->numHalfPoints; ++index ) { node = this->nodesHalfPoints[ index ]; node->newposition = vector3(0,0,0); int counter(0); for( int inner(0); inner < node->numNodes; ++inner ) { if( node->nodes[ inner ] ) { ++counter; node->newposition += node->nodes[ inner ]->newposition; if( node->nodes[inner]->normals ) { if( !node->normals ) { node->normal = node->nodes[inner]->normal; ++node->normals; node->angle = 0; } else { ++node->normals; node->angle += 1.f - fabs(node->normal.dot(node->nodes[inner]->normal)); node->normal += node->nodes[inner]->normal; node->normal *= .5f; node->angle *= .5f; } } } } if( counter ) { node->newposition *= 1.f / phyreal( counter ); if( node->normals > 0 ) { static phyreal mult(1.f); if( node->normals > 1 ) node->newposition += node->normal * (distance * mult) * node->angle; } } node->changed = true; } node = nodesInfo; // calculating the rest of the points for( int index(0); index < this->numRestPoints; ++index ) { node = this->nodesRestPoints[ index ]; node->newposition = vector3(0,0,0); for( int inner(0); inner < node->numNodes; ++inner ) { node->newposition += node->nodes[ inner ]->newposition; } if( node->numNodes ) { node->newposition *= 1.f / phyreal( node->numNodes ); } node->changed = true; } node = nodesInfo; // updating the positions for( unsigned index(0); index < this->numTotalNodes; ++index, ++node ) { if( node->tied ) continue; if( node->changed ) { *node->oldposition = node->newposition; } } this->mesh->Update(); } //----------------------------------------------------------------------------- /** Function to be procesed during the collision check. @param numContacts maximun number of contacts expected @param contacts container of contacts @return if any collision was processed history: - 17-Jan-2005 Zombie created */ bool ncPhyCloth::CollisionProcess( int /*numContacts*/, nPhyCollide::nContact* /*contacts*/ ) { return true; } //----------------------------------------------------------------------------- /** Returns a node given coordinates. @param x x node coordinates @param z z node coordinates @return a node history: - 17-Jan-2005 Zombie created */ ncPhyCloth::nodeInfo* ncPhyCloth::GetNode( int x, int z ) const { if( x < 0 ) return 0; if( z < 0 ) return 0; if( x >= int(this->nodesXAxis) ) return 0; if( z >= int(this->nodesZAxis) ) return 0; return &this->nodesInfo[ x + z * this->nodesXAxis ]; } //----------------------------------------------------------------------------- // EOF //-----------------------------------------------------------------------------
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 739 ] ] ]
601e8d6b73dac45e74b59479ed5995f495bbac1a
9ad9345e116ead00be7b3bd147a0f43144a2e402
/Integration_WAH_&_Extraction/SMDataExtraction/TestAlgorithm/TestAprioriOpt.cpp
2542a6d446d9e446b8a89c2d45d345b72d43a41a
[]
no_license
asankaf/scalable-data-mining-framework
e46999670a2317ee8d7814a4bd21f62d8f9f5c8f
811fddd97f52a203fdacd14c5753c3923d3a6498
refs/heads/master
2020-04-02T08:14:39.589079
2010-07-18T16:44:56
2010-07-18T16:44:56
33,870,353
0
0
null
null
null
null
UTF-8
C++
false
false
6,672
cpp
#include "StdAfx.h" #include "TestAprioriOpt.h" #include "DataSourceGenerator.h" #include "csvconnection.h" #include "CompressionHandler.h" #include "DataSources.h" #include "LoadSavedDataSources.h" #include "DecodedTuple.h" #include "utils.h" #include <winbase.h> #include "pthread.h" #include <stdlib.h> #include <time.inl> #include <fstream> #include <string> #include <vector> #include <xstring> #include "boost/tokenizer.hpp" #include "commons.h" using namespace CSVConnectionInfo; TestAprioriOpt::TestAprioriOpt(void):m_apriori_config("apriori.cfg"),m_execution_config("algorithm.cfg"),m_property_confidence("confidence"),m_property_rules("rules"),m_property_support("support") { m_property_loop_cnt = "loops"; m_property_compression = "compression"; m_property_meta_file_name = "metafile"; m_property_data_file_name = "datafile"; m_property_file_name = "filename"; Commons::BuildFile(m_apriori_config); Commons::BuildFile(m_execution_config); m_no_of_loops = boost::lexical_cast<int>(Commons::ReadConfiguration(m_property_loop_cnt)); if (Commons::ReadConfiguration(m_property_compression) == "NO") { m_compression = BitStreamInfo::VERTICAL_STREAM_FORMAT; } else if (Commons::ReadConfiguration(m_property_compression) == "EWAH") { m_compression = BitStreamInfo::EWAH_COMPRESSION; } else if (Commons::ReadConfiguration(m_property_compression) == "WAH") { m_compression = BitStreamInfo::WAH_COMPRESSION; } m_confidence = lexical_cast<double>(Commons::ReadConfiguration(m_property_confidence)); m_min_sup= lexical_cast<double>(Commons::ReadConfiguration(m_property_support)); m_rules = lexical_cast<int>(Commons::ReadConfiguration(m_property_rules)); m_meta_file_name = Commons::ReadConfiguration(m_property_meta_file_name); m_data_file_name = Commons::ReadConfiguration(m_property_data_file_name); m_file_name = Commons::ReadConfiguration(m_property_file_name); } TestAprioriOpt::~TestAprioriOpt(void) { } void TestAprioriOpt::TestSuite() { RunAlgorithm(); //PerformMemoryTest(); //cout << "Deleted Apriori " << clock() << endl; } void TestAprioriOpt::RunAlgorithm() { clock_t comp_start,comp_end; cout << "Starting to load data : " << endl; //Creating the data source comp_start = clock(); WrapDataSource * ds = Utils::CreateDataSource(m_data_file_name,m_meta_file_name,m_file_name); //WrapDataSource * ds = Utils::CreateDataSource("C:\\Data\\soyaTestsort.csv"); comp_end = clock(); cout << "Time to load data : " << (comp_end -comp_start) << endl; AlgoUtils utils; //Measuring Space Utilisation cout << "Before Compression : " << ds->SpaceUtilsation() << endl; CompressionHandler comp; comp_start = clock(); comp.ConvertTo(ds,m_compression); comp_end = clock(); cout << "After Compression : " << ds->SpaceUtilsation() << endl; cout << "Compression Time : " << comp_end - comp_start << endl; cout << "With Compression " << endl; cout << "Time Spent : "; for (size_t i = 0 ; i < m_no_of_loops; i++) { AprioriOpt opt; clock_t begin,end; begin = clock(); TestBuildAssociations(ds,opt); cout << opt.ToString() << endl; end = clock(); cout<< (end - begin) << " "; } cout << endl; delete ds; } void TestAprioriOpt::TestUniqueItemSetGeneration(WrapDataSource * _wrapped, AprioriOpt & _ap_opt) { cout << "Start Creating unique item sets" << endl; _ap_opt.FindUniqueItemSets(_wrapped); } void TestAprioriOpt::TestBuildAssociations(WrapDataSource * _wrapped, AprioriOpt & _ap_opt) { _ap_opt.Confidence(m_confidence); _ap_opt.NumRules(m_rules); _ap_opt.MinSupport(m_min_sup); _ap_opt.BuildAssociations(_wrapped); } void TestAprioriOpt::TestFindFrequentItemSets(AprioriOpt & _ap_opt,WrapDataSource * ws) { cout << "Test frequent Item set" << endl; _ap_opt.MinSupport(.8); _ap_opt.FindLargeItemSets(); cout << "Printing Large Item sets " << endl; AlgoUtils utils; vector<vector<AprioriItemset *>> items = _ap_opt.LargeItemSets(); for (size_t i = 0; i < items.size() ; i++) { cout << "Printing Item set : " << i << endl; utils.PrintAprioriItemSets(items.at(i),ws); } } void TestAprioriOpt::TestHashMapBuilding(WrapDataSource * _wrapped, AprioriOpt & _ap_opt) { // Unique itemset is taken and its hashtable is constructed cout << "Creating Hash Map" << endl; AprioriItemset items; AlgoUtils utils; vector<hash_map<int,AprioriItemset *>> test; utils.PrintHashMap(items.GetHashtable(_ap_opt.UniqueItems(),test)); } void TestAprioriOpt::TestUniqueItemsetDeletion(AprioriOpt & _ap_opt, WrapDataSource * ws){ vector<AprioriItemset *> item_sets = _ap_opt.UniqueItems(); item_sets = _ap_opt.DeleteItemSets(item_sets,200,257,false); AlgoUtils utils; cout << "Result Itemsets " << endl; utils.PrintAprioriItemSets(item_sets,ws); cout << endl; cout << "Original Itemsets" << endl; utils.PrintAprioriItemSets(_ap_opt.UniqueItems()); } void TestAprioriOpt::LoadAndPrintCSV() { LoadSavedDataSources *lsd = new LoadSavedDataSources("soyabean_0.25mil_metadata","soyabean_0.25mil_data"); DataSources *dsLoaded = lsd->loadSavedEncodedData(); WrapDataSource * ds = (*dsLoaded)("soyabean"); cout <<ds->generateCSVStringofDecodedData() << endl; } void TestAprioriOpt::PerformMemoryTest() { cout << "Algorithm : Apriori" << endl; DWORD process_id = GetCurrentProcessId(); int ii =0 ; cout << "Current Process ID : " << process_id<<endl; cin>>ii; cout << "Start Time :" << time(NULL)<< endl; WrapDataSource * ds = Utils::CreateDataSource(m_data_file_name,m_meta_file_name,m_file_name); cout <<"Finished Creating Data Source : " << time(NULL)<< endl; CompressionHandler::ConvertTo(ds,m_compression); cout <<"Starting To Execute Algorithm : " << time(NULL)<< endl; //cin >>ii; for (size_t i = 0 ; i < m_no_of_loops ; i++) { SingleExecution(ds); } cout <<"Finished Executing Algorithm : " << time(NULL) << endl; //cin>>ii; delete ds; cout <<"Deleted Data Source: " << time(NULL) << endl; //cin>>ii; } void TestAprioriOpt::SingleExecution(WrapDataSource * ds) { AprioriOpt apriori; TestBuildAssociations(ds,apriori); } WrapDataSource * TestAprioriOpt::CreateWrappedDataSource() { DBConnection cCon("SOY","",""); cCon.initiateConnectionToDB(); char* command = "SELECT * FROM soyabeantest "; DBQueryExecution * cExec = new DBQueryExecution(command); cout << "Loaded Data" << endl; cExec->ExecuteQueryAndBindData(cCon.DBConnectionPtr()); WrapDataSource *ds = new WrapDataSource(cExec,0); ds->encodeAtrributes(); return ds; }
[ "jaadds@c7f6ba40-6498-11de-987a-95e5a5a5d5f1" ]
[ [ [ 1, 207 ] ] ]
6d058312580bf3ea67dc3318e83da316226af74f
9a48be80edc7692df4918c0222a1640545384dbb
/Libraries/Boost1.40/libs/asio/example/http/server/request_handler.cpp
a0e39a59f9dac75fc1f225d9aa746a224a87e351
[ "BSL-1.0" ]
permissive
fcrick/RepSnapper
05e4fb1157f634acad575fffa2029f7f655b7940
a5809843f37b7162f19765e852b968648b33b694
refs/heads/master
2021-01-17T21:42:29.537504
2010-06-07T05:38:05
2010-06-07T05:38:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,080
cpp
// // request_handler.cpp // ~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // 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) // #include "request_handler.hpp" #include <fstream> #include <sstream> #include <string> #include <boost/lexical_cast.hpp> #include "mime_types.hpp" #include "reply.hpp" #include "request.hpp" namespace http { namespace server { request_handler::request_handler(const std::string& doc_root) : doc_root_(doc_root) { } void request_handler::handle_request(const request& req, reply& rep) { // Decode url to path. std::string request_path; if (!url_decode(req.uri, request_path)) { rep = reply::stock_reply(reply::bad_request); return; } // Request path must be absolute and not contain "..". if (request_path.empty() || request_path[0] != '/' || request_path.find("..") != std::string::npos) { rep = reply::stock_reply(reply::bad_request); return; } // If path ends in slash (i.e. is a directory) then add "index.html". if (request_path[request_path.size() - 1] == '/') { request_path += "index.html"; } // Determine the file extension. std::size_t last_slash_pos = request_path.find_last_of("/"); std::size_t last_dot_pos = request_path.find_last_of("."); std::string extension; if (last_dot_pos != std::string::npos && last_dot_pos > last_slash_pos) { extension = request_path.substr(last_dot_pos + 1); } // Open the file to send back. std::string full_path = doc_root_ + request_path; std::ifstream is(full_path.c_str(), std::ios::in | std::ios::binary); if (!is) { rep = reply::stock_reply(reply::not_found); return; } // Fill out the reply to be sent to the client. rep.status = reply::ok; char buf[512]; while (is.read(buf, sizeof(buf)).gcount() > 0) rep.content.append(buf, is.gcount()); rep.headers.resize(2); rep.headers[0].name = "Content-Length"; rep.headers[0].value = boost::lexical_cast<std::string>(rep.content.size()); rep.headers[1].name = "Content-Type"; rep.headers[1].value = mime_types::extension_to_type(extension); } bool request_handler::url_decode(const std::string& in, std::string& out) { out.clear(); out.reserve(in.size()); for (std::size_t i = 0; i < in.size(); ++i) { if (in[i] == '%') { if (i + 3 <= in.size()) { int value = 0; std::istringstream is(in.substr(i + 1, 2)); if (is >> std::hex >> value) { out += static_cast<char>(value); i += 2; } else { return false; } } else { return false; } } else if (in[i] == '+') { out += ' '; } else { out += in[i]; } } return true; } } // namespace server } // namespace http
[ "metrix@Blended.(none)" ]
[ [ [ 1, 122 ] ] ]
9b3af14eb7ce732cb83f6dd3fb4986208b971dc5
7f72fc855742261daf566d90e5280e10ca8033cf
/branches/full-calibration/ground/src/plugins/magicwaypoint/magicwaypointgadgetwidget.h
1e21d0db5e9b186140440ac7c47c3d5cdd8f81a8
[]
no_license
caichunyang2007/my_OpenPilot_mods
8e91f061dc209a38c9049bf6a1c80dfccb26cce4
0ca472f4da7da7d5f53aa688f632b1f5c6102671
refs/heads/master
2023-06-06T03:17:37.587838
2011-02-28T10:25:56
2011-02-28T10:25:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,054
h
/** ****************************************************************************** * * @file GCSControlgadgetwidget.h * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. * @addtogroup GCSPlugins GCS Plugins * @{ * @addtogroup GCSControlGadgetPlugin GCSControl Gadget Plugin * @{ * @brief A place holder gadget plugin *****************************************************************************/ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef MagicWaypointGADGETWIDGET_H_ #define MagicWaypointGADGETWIDGET_H_ #include <QtGui/QLabel> #include "uavobjects/positiondesired.h" #include "uavobjects/positionactual.h" class Ui_MagicWaypoint; class MagicWaypointGadgetWidget : public QLabel { Q_OBJECT public: MagicWaypointGadgetWidget(QWidget *parent = 0); ~MagicWaypointGadgetWidget(); signals: void positionActualObjectChanged(double north, double east); void positionDesiredObjectChanged(double north, double east); protected slots: void scaleChanged(int scale); void positionObjectChanged(UAVObject *); void positionSelected(double north, double east); private: PositionDesired * getPositionDesired(); PositionActual * getPositionActual(); Ui_MagicWaypoint * m_magicwaypoint; }; #endif /* MagicWaypointGADGETWIDGET_H_ */
[ "jonathan@ebee16cc-31ac-478f-84a7-5cbb03baadba" ]
[ [ [ 1, 60 ] ] ]
3ff13565bf09a1af7a3180312ac581c4c54c5e2f
0033659a033b4afac9b93c0ac80b8918a5ff9779
/game/shared/hl2/hl_gamemovement.h
b85ec49a36e41c4f0aab7adef442949cd45f992b
[]
no_license
jonnyboy0719/situation-outbreak-two
d03151dc7a12a97094fffadacf4a8f7ee6ec7729
50037e27e738ff78115faea84e235f865c61a68f
refs/heads/master
2021-01-10T09:59:39.214171
2011-01-11T01:15:33
2011-01-11T01:15:33
53,858,955
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
4,425
h
//========= Copyright ยฉ 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: Special handling for hl2 usable ladders // //=============================================================================// #include "gamemovement.h" #include "func_ladder.h" #if defined( CLIENT_DLL ) #include "c_basehlplayer.h" #define CHL2_Player C_BaseHLPlayer #else #include "hl2_player.h" #endif struct LadderMove_t; class CInfoLadderDismount; struct NearbyDismount_t { CInfoLadderDismount *dismount; float distSqr; }; //----------------------------------------------------------------------------- // Purpose: HL2 specific movement code //----------------------------------------------------------------------------- class CHL2GameMovement : public CGameMovement { typedef CGameMovement BaseClass; public: CHL2GameMovement(); ///// // SO2 - James // Restore the CS:S-type, brush-based ladder system // This function has been left uncommented but has been modified // Parts of it is needed to ensure spectators and those using noclip can't climb ladders virtual bool LadderMove( void ); // Overrides /*virtual void FullLadderMove(); virtual bool OnLadder( trace_t &trace ); virtual int GetCheckInterval( IntervalType_t type ); virtual void SetGroundEntity( trace_t *pm ); virtual bool CanAccelerate( void );*/ ///// virtual unsigned int PlayerSolidMask( bool brushOnly = false ); private: // See if we are pressing use near a ladder "mount" point and if so, latch us onto the ladder bool CheckLadderAutoMount( CFuncLadder *ladder, const Vector& bestOrigin ); bool CheckLadderAutoMountCone( CFuncLadder *ladder, const Vector& bestOrigin, float maxAngleDelta, float maxDistToLadder ); bool CheckLadderAutoMountEndPoint(CFuncLadder *ladder, const Vector& bestOrigin ); bool LookingAtLadder( CFuncLadder *ladder ); // Are we forcing the user's position to a new spot bool IsForceMoveActive(); // Start forcing player position void StartForcedMove( bool mounting, float transit_speed, const Vector& goalpos, CFuncLadder *ladder ); // Returns false when finished bool ContinueForcedMove(); // Given a list of nearby ladders, find the best ladder and the "mount" origin void Findladder( float maxdist, CFuncLadder **ppLadder, Vector& ladderOrigin, const CFuncLadder *skipLadder ); // Debounce the +USE key void SwallowUseKey(); // Returns true if the player will auto-exit the ladder via a dismount node bool ExitLadderViaDismountNode( CFuncLadder *ladder, bool strict, bool useAlternate = false ); void GetSortedDismountNodeList( const Vector &org, float radius, CFuncLadder *ladder, CUtlRBTree< NearbyDismount_t, int >& list ); LadderMove_t *GetLadderMove(); CHL2_Player *GetHL2Player(); void SetLadder( CFuncLadder *ladder ); CFuncLadder *GetLadder(); }; //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- inline CHL2_Player *CHL2GameMovement::GetHL2Player() { return static_cast< CHL2_Player * >( player ); } //----------------------------------------------------------------------------- // Purpose: // Output : inline LadderMove* //----------------------------------------------------------------------------- inline LadderMove_t *CHL2GameMovement::GetLadderMove() { CHL2_Player *p = GetHL2Player(); if ( !p ) { return NULL; } return p->GetLadderMove(); } //----------------------------------------------------------------------------- // Purpose: // Input : *ladder - //----------------------------------------------------------------------------- inline void CHL2GameMovement::SetLadder( CFuncLadder *ladder ) { CFuncLadder* oldLadder = GetLadder(); if ( !ladder && oldLadder ) { oldLadder->PlayerGotOff( GetHL2Player() ); } GetHL2Player()->m_HL2Local.m_hLadder.Set( ladder ); } //----------------------------------------------------------------------------- // Purpose: // Output : CFuncLadder //----------------------------------------------------------------------------- inline CFuncLadder *CHL2GameMovement::GetLadder() { return static_cast<CFuncLadder*>( static_cast<CBaseEntity *>( GetHL2Player()->m_HL2Local.m_hLadder.Get() ) ); }
[ "MadKowa@ec9d42d2-91e1-33f0-ec5d-f2a905d45d61" ]
[ [ [ 1, 141 ] ] ]
b47e765f74e0d74abac6e581dcc8514a6a15dda5
b5ab57edece8c14a67cc98e745c7d51449defcff
/Captain's Log/A-Star (spike)/A-Star (spike).cpp
77b05a7c58998527bc42a6809f37b6cf3f8c5155
[]
no_license
tabu34/tht-captainslog
c648c6515424a6fcdb628320bc28fc7e5f23baba
72d72a45e7ea44bdb8c1ffc5c960a0a3845557a2
refs/heads/master
2020-05-30T15:09:24.514919
2010-07-30T17:05:11
2010-07-30T17:05:11
32,187,254
0
0
null
null
null
null
UTF-8
C++
false
false
21,008
cpp
// A-Star (spike).cpp : Defines the entry point for the application. // #include "stdafx.h" #include "A-Star (spike).h" #define MAX_LOADSTRING 100 //stuff for A* struct Blocker { struct Point { int x; int y; Point(int nX = 0, int nY = 0) {x = nX; y = nY;} }; int m_nNumPoints; Point* m_Points; } arrBlockers[3]; typedef struct { float fX; float fY; } tNode; const tNode helperNodes[6] = { { 139.0f, 29.0f, }, { 89.0f, 224.0f, }, { 124.0f, 125.0f, }, { 317.0f, 291.0f, }, { 446.0f, 240.0f, }, { 434.0f, 156.0f, }, }; typedef struct { tNode* pFrom; tNode* pTo; } tEdge; typedef struct { tNode* pNode; vector<tNode*> pNeighbors; } tAdjacency; struct tAStarNode { tNode* pNode; //used to construct path once search is over tAStarNode* pCameFrom; size_t nIndexParent; //distance from source along optimal path float fG; //estimate of distance from here to target node (heuristic) float fH; }; struct tLine { tVector2D start; tVector2D end; }; class CPathManager { public: vector<tNode> m_lstNodeList; map<tNode*, tAdjacency> m_mpAdjacencies; vector<tLine> m_vLines; private: CPathManager(); ~CPathManager(); CPathManager(const CPathManager&); CPathManager& operator=(const CPathManager&); public: static CPathManager* GetInstance(); void GenerateMap(); vector<tNode*> GetPath(float fX1, float fY1, float fX2, float fY2); }; CPathManager::CPathManager() { } CPathManager::~CPathManager() { } // int Check_Tri_Dir(tVector2D P1, tVector2D P2, tVector2D P3) // { // float test; // test = (((P2.fX - P1.fX)*(P3.fY - P1.fY)) - ((P3.fX-P1.fX)*(P2.fY - P1.fY))); // if(test > 0) // return 1; // if(test < 0) // return -1; // return 0; // } bool IntersectLine(tVector2D A1, tVector2D A2, tVector2D B1, tVector2D B2) { // //if any of the endpoints are the same, the lines technically aren't intersecting // if((A1.fX == B1.fX && A1.fY == B1.fY) || // (A1.fX == B2.fX && A1.fY == B2.fY) || // (A2.fX == B1.fX && A2.fY == B1.fY) || // (A2.fX == B2.fX && A2.fY == B2.fY)) // return false; // // int test1, test2, test3, test4; // test1 = Check_Tri_Dir(A1, A2, B1); // test2 = Check_Tri_Dir(A1, A2, B2); // if(test1 != test2) // { // test3 = Check_Tri_Dir(B1, B2, A1); // test4 = Check_Tri_Dir(B1, B2, A2); // if(test3 != test4) // return true; // } // return false; float d = (A2.fX - A1.fX)*(B2.fY - B1.fY) - (A2.fY - A1.fY)*(B2.fX - B1.fX); if(fabs(d)<0.001) return false; float AB = ((A1.fY - B1.fY)*(B2.fX - B1.fX)-(A1.fX - B1.fX)*(B2.fY-B1.fY))/d; if(AB>0.0f && AB<1.0f) { float CD = ((A1.fY - B1.fY)*(A2.fX - A1.fX) - (A1.fX - B1.fX)*(A2.fY - A1.fY))/d; if(CD>0.0f && CD<1.0f) return true; } return false; } #define MIN(x,y) (x < y ? x : y) #define MAX(x,y) (x > y ? x : y) bool InsideBlocker(POINT p) { int counter=0; float xInters; Blocker::Point p1, p2; for(int i=0; i<3; i++) { counter=0; p1 = arrBlockers[i].m_Points[0]; for(int j=1; j<=arrBlockers[i].m_nNumPoints; j++) { p2 = arrBlockers[i].m_Points[j%arrBlockers[i].m_nNumPoints]; if(p.y > MIN(p1.y, p2.y)) { if(p.y <= MAX(p1.y, p2.y)) { if(p.x <= MAX(p1.x, p2.x)) { if(p1.y!=p2.y) { xInters = float((p.y-p1.y)*(p2.x-p1.x)/(p2.y-p1.y)+p1.x); if(p1.x == p2.x || p.x<=xInters) counter++; } } } } p1=p2; } if(counter!=0 && counter%2!=0) return true; } return false; } CPathManager* CPathManager::GetInstance() { static CPathManager instance; return &instance; } void CPathManager::GenerateMap() { vector<tLine> vLines; m_lstNodeList.clear(); m_mpAdjacencies.clear(); //step 1: create all the nodes tNode node, lastNode; for(int i=0; i<3; i++) { vector<tNode> vNodesInShape; vNodesInShape.clear(); lastNode.fX = -1.0f; node.fX = -1.0f; for(int j=0; j<arrBlockers[i].m_nNumPoints; j++) { if(node.fX!=-1.0f) { lastNode = node; } node.fX = (float)arrBlockers[i].m_Points[j].x; node.fY = (float)arrBlockers[i].m_Points[j].y; m_lstNodeList.push_back(node); vNodesInShape.push_back(node); // if(lastNode.fX!=-1.0f) // { // tLine line; // line.start.fX = lastNode.fX; // line.start.fY = lastNode.fY; // line.end.fX = node.fX; // line.end.fY = node.fY; // vLines.push_back(line); // char buff[128]; // sprintf_s(buff, 128, "X1: %.2f, Y1: %.2f, X2: %.2f, Y2: %.2f \n", line.start.fX, line.start.fY, line.end.fX, line.end.fY); // OutputDebugString(buff); // } } for(size_t i=0; i<vNodesInShape.size(); i++) for(size_t j=0; j<vNodesInShape.size(); j++) { tLine line; line.start.fX = vNodesInShape[i].fX; line.start.fY = vNodesInShape[i].fY; line.end.fX = vNodesInShape[j].fX; line.end.fY = vNodesInShape[j].fY; vLines.push_back(line); } } //add helper nodes for(int i=0; i<6; i++) { node.fX = helperNodes[i].fX; node.fY = helperNodes[i].fY; m_lstNodeList.push_back(node); } m_vLines = vLines; //step 2: set up adjacencies and edges for(size_t i=0; i<m_lstNodeList.size(); i++) { tAdjacency adjacency; adjacency.pNode = &m_lstNodeList[i]; for(size_t j=0; j<m_lstNodeList.size(); j++) { if(j!=i) { //we have two different nodes, create a line between them and check for intersection tLine nodePath; nodePath.start.fX = m_lstNodeList[i].fX; nodePath.start.fY = m_lstNodeList[i].fY; nodePath.end.fX = m_lstNodeList[j].fX; nodePath.end.fY = m_lstNodeList[j].fY; //now, check this line against all others bool bIntersect=false; for(size_t k=0; k<vLines.size(); k++) { if(IntersectLine(nodePath.start, nodePath.end, vLines[k].start, vLines[k].end)) { bIntersect=true; break; } } if(!bIntersect) { adjacency.pNeighbors.push_back(&m_lstNodeList[j]); } } } m_mpAdjacencies[adjacency.pNode] = adjacency; } } inline float ManhattanDistance(tNode& source, tNode& target) { return fabs(source.fX - target.fX) + fabs(source.fY - target.fY); } inline int PointDistance(POINT p1, POINT p2) { return (int)sqrt(static_cast<double>((p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y))); } vector<tNode*> CPathManager::GetPath(float fX1, float fY1, float fX2, float fY2) { //THIS is A* vector<tNode*> vRet; vector<tAStarNode> vNodePool; map<tNode*, tAStarNode> openSet; queue<tAStarNode> pQueue; map<tNode*, tAStarNode> closeSet; tAStarNode start; tAStarNode goal; start.pNode=NULL; goal.pNode=NULL; //calculate nearest node to start and goal { tVector2D pos = {fX1, fY1}; tVector2D dst; float minDist = 10000.0f; float fTemp; for(size_t i=0; i<m_lstNodeList.size(); i++) { dst.fX = m_lstNodeList[i].fX; dst.fY = m_lstNodeList[i].fY; fTemp = Vector2DLength(dst - pos); bool bRet=false; for(size_t j=0; j<m_vLines.size(); j++) { if(IntersectLine(pos, dst, m_vLines[j].start, m_vLines[j].end)) { bRet = true; break; } } if(!bRet && fTemp < minDist) { minDist = fTemp; start.pNode = &m_lstNodeList[i]; } } } { tVector2D pos = {fX2, fY2}; tVector2D dst; float minDist = 1000.0f; float fTemp; for(size_t i=0; i<m_lstNodeList.size(); i++) { dst.fX = m_lstNodeList[i].fX; dst.fY = m_lstNodeList[i].fY; fTemp = Vector2DLength(dst - pos); if(fTemp < minDist) { minDist = fTemp; goal.pNode = &m_lstNodeList[i]; } } } if(!start.pNode) return vector<tNode*>(); if(goal.pNode == start.pNode) return vector<tNode*>(); start.pCameFrom = NULL; start.nIndexParent = -1; start.fG = 0.0f; start.fH = ManhattanDistance(*start.pNode, *goal.pNode); openSet[start.pNode] = start; pQueue.push(start); bool bFoundGoal = false; while(openSet.size() > 0) { tAStarNode x = pQueue.front(); vNodePool.push_back(x); pQueue.pop(); openSet.erase(x.pNode); if(x.pNode == goal.pNode) { //path exists goal = x; bFoundGoal = true; break; } else { closeSet[x.pNode] = x; tAdjacency adj; adj = m_mpAdjacencies[x.pNode]; for(size_t i=0; i<adj.pNeighbors.size(); i++) { if(x.pNode->fX == adj.pNeighbors[i]->fX && x.pNode->fY == adj.pNeighbors[i]->fY) continue; if(closeSet.find(adj.pNeighbors[i]) == closeSet.end()) { float g = x.fG + ManhattanDistance(*adj.pNeighbors[i], *x.pNode); if(openSet.find(adj.pNeighbors[i]) == openSet.end()) { tAStarNode n; n.pNode = adj.pNeighbors[i]; n.pCameFrom = &vNodePool.back(); n.nIndexParent = vNodePool.size()-1; n.fG = g; n.fH = ManhattanDistance(*adj.pNeighbors[i], *goal.pNode); openSet[n.pNode] = n; pQueue.push(n); } else if(g < openSet[adj.pNeighbors[i]].fG) { openSet[adj.pNeighbors[i]].pCameFrom = &vNodePool.back(); openSet[adj.pNeighbors[i]].nIndexParent = vNodePool.size()-1; openSet[adj.pNeighbors[i]].fG = g; openSet[adj.pNeighbors[i]].fH = ManhattanDistance(*adj.pNeighbors[i], *goal.pNode); } } } } } if(bFoundGoal) { stack<tNode*> stk; stk.push(goal.pNode); tAStarNode pParent = vNodePool[goal.nIndexParent]; while(pParent.nIndexParent < vNodePool.size()) { stk.push(pParent.pNode); pParent = vNodePool[pParent.nIndexParent]; if(pParent.pCameFrom == NULL) { stk.push(pParent.pNode); break; } } while(stk.size() > 0) { vRet.push_back(stk.top()); stk.pop(); } return vRet; } return vector<tNode*>(); } // Global Variables: HINSTANCE hInst; // current instance TCHAR szTitle[MAX_LOADSTRING]; // The title bar text TCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name vector<tNode*> vDirections; POINT theGuy; POINT target; POINT startGuy; // Forward declarations of functions included in this code module: ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); // TODO: Place code here. MSG msg; HACCEL hAccelTable; // Initialize global strings LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_ASTARSPIKE, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); //CREATE THE BLOCKERS arrBlockers[0].m_nNumPoints = 5; arrBlockers[1].m_nNumPoints = 4; arrBlockers[2].m_nNumPoints = 7; arrBlockers[0].m_Points = new Blocker::Point[5]; //rectangle arrBlockers[1].m_Points = new Blocker::Point[4]; //triangle arrBlockers[2].m_Points = new Blocker::Point[7]; //hexagon arrBlockers[0].m_Points[0] = Blocker::Point(20, 20); arrBlockers[0].m_Points[1] = Blocker::Point(90, 20); arrBlockers[0].m_Points[2] = Blocker::Point(90, 200); arrBlockers[0].m_Points[3] = Blocker::Point(20, 200); arrBlockers[0].m_Points[4] = Blocker::Point(20, 20); arrBlockers[1].m_Points[0] = Blocker::Point(200, 32); arrBlockers[1].m_Points[1] = Blocker::Point(425, 226); arrBlockers[1].m_Points[2] = Blocker::Point(90, 255); arrBlockers[1].m_Points[3] = Blocker::Point(200, 32); arrBlockers[2].m_Points[0] = Blocker::Point(590, 187); arrBlockers[2].m_Points[1] = Blocker::Point(716, 251); arrBlockers[2].m_Points[2] = Blocker::Point(716, 381); arrBlockers[2].m_Points[3] = Blocker::Point(593, 446); arrBlockers[2].m_Points[4] = Blocker::Point(470, 379); arrBlockers[2].m_Points[5] = Blocker::Point(470, 253); arrBlockers[2].m_Points[6] = Blocker::Point(590, 187); CPathManager* pPM = CPathManager::GetInstance(); pPM->GenerateMap(); theGuy.x = 300; theGuy.y = 100; target.x = 747; target.y = 408; // Perform application initialization: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_ASTARSPIKE)); // Main message loop: while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return (int) msg.wParam; } // // FUNCTION: MyRegisterClass() // // PURPOSE: Registers the window class. // // COMMENTS: // // This function and its usage are only necessary if you want this code // to be compatible with Win32 systems prior to the 'RegisterClassEx' // function that was added to Windows 95. It is important to call this function // so that the application will get 'well formed' small icons associated // with it. // ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ASTARSPIKE)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = MAKEINTRESOURCE(IDC_ASTARSPIKE); wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassEx(&wcex); } // // FUNCTION: InitInstance(HINSTANCE, int) // // PURPOSE: Saves instance handle and creates main window // // COMMENTS: // // In this function, we save the instance handle in a global variable and // create and display the main program window. // BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { HWND hWnd; hInst = hInstance; // Store instance handle in our global variable RECT rClient; SetRect(&rClient, 0, 0, 1000, 800); AdjustWindowRect(&rClient, WS_OVERLAPPEDWINDOW, TRUE); int ww = rClient.right - rClient.left; int wh = rClient.bottom - rClient.top; hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, ww, wh, NULL, NULL, hInstance, NULL); if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; } void OnPaint(HWND hWnd) { PAINTSTRUCT ps; HDC hdc = BeginPaint(hWnd, &ps); RECT theScreen; GetClientRect(hWnd, &theScreen); HBRUSH hbrBG = CreateSolidBrush((COLORREF)0xFFFFFF); HBRUSH hbrOld; FillRect(hdc, &theScreen, hbrBG); hbrOld=(HBRUSH)SelectObject(hdc, hbrBG); HPEN hpBoard, hpOld, hpPath, hpAdj, hpNode; hpBoard=CreatePen(PS_SOLID, 3, 0x000000); hpPath = CreatePen(PS_SOLID, 3, 0xFF0000); hpAdj = CreatePen(PS_SOLID, 1, 0x00FF00); hpNode = CreatePen(PS_SOLID, 2, 0x0000FF); hpOld=(HPEN)SelectObject(hdc, hpBoard); // //draw the blockers // for(int i=0; i<3; i++) // { // for(int j=0; j<arrBlockers[i].m_nNumPoints-1; j++) // { // MoveToEx(hdc, arrBlockers[i].m_Points[j].x, arrBlockers[i].m_Points[j].y, NULL); // LineTo(hdc, arrBlockers[i].m_Points[j+1].x, arrBlockers[i].m_Points[j+1].y); // } // } //draw lines of collision for(size_t i=0; i<CPathManager::GetInstance()->m_vLines.size(); i++) { MoveToEx(hdc, (int)CPathManager::GetInstance()->m_vLines[i].start.fX, (int)CPathManager::GetInstance()->m_vLines[i].start.fY, NULL); LineTo(hdc, (int)CPathManager::GetInstance()->m_vLines[i].end.fX, (int)CPathManager::GetInstance()->m_vLines[i].end.fY); } //draw the adjacencies SelectObject(hdc, hpAdj); for(size_t i=0; i<CPathManager::GetInstance()->m_lstNodeList.size(); i++) { tNode* pN = &CPathManager::GetInstance()->m_lstNodeList[i]; for(size_t j=0; j<CPathManager::GetInstance()->m_mpAdjacencies[pN].pNeighbors.size(); j++) { MoveToEx(hdc, (int)pN->fX, (int)pN->fY, NULL); LineTo(hdc, (int)CPathManager::GetInstance()->m_mpAdjacencies[pN].pNeighbors[j]->fX, (int)CPathManager::GetInstance()->m_mpAdjacencies[pN].pNeighbors[j]->fY); } } //draw the path SelectObject(hdc, hpPath); MoveToEx(hdc, startGuy.x, startGuy.y, NULL); for(size_t i=0; i<vDirections.size(); i++) { LineTo(hdc, (int)vDirections[i]->fX, (int)vDirections[i]->fY); MoveToEx(hdc, (int)vDirections[i]->fX, (int)vDirections[i]->fY, NULL); } if(vDirections.size()>0) LineTo(hdc, target.x, target.y); //draw the nodes SelectObject(hdc, hpNode); for(size_t i=0; i<CPathManager::GetInstance()->m_lstNodeList.size(); i++) { tNode* pNode = &CPathManager::GetInstance()->m_lstNodeList[i]; MoveToEx(hdc, (int)pNode->fX-7, (int)pNode->fY-7, NULL); LineTo(hdc, (int)pNode->fX+7, (int)pNode->fY+7); MoveToEx(hdc, (int)pNode->fX+7, (int)pNode->fY-7, NULL); LineTo(hdc, (int)pNode->fX-7, (int)pNode->fY+7); } //draw our guy SelectObject(hdc, hpBoard); MoveToEx(hdc, theGuy.x-3, theGuy.y-3, NULL); LineTo(hdc, theGuy.x+3, theGuy.y+3); MoveToEx(hdc, theGuy.x-3, theGuy.y+3, NULL); LineTo(hdc, theGuy.x+3, theGuy.y-3); //draw the target MoveToEx(hdc, target.x, target.y-5, NULL); LineTo(hdc, target.x, target.y+5); MoveToEx(hdc, target.x-5, target.y, NULL); LineTo(hdc, target.x+5, target.y); SelectObject(hdc, hpOld); SelectObject(hdc, hbrOld); DeleteObject(hpPath); DeleteObject(hpBoard); DeleteObject(hbrBG); DeleteObject(hpAdj); DeleteObject(hpNode); EndPaint(hWnd, &ps); } void TheSequence(HWND hWnd) { vDirections = CPathManager::GetInstance()->GetPath((float)theGuy.x, (float)theGuy.y, (float)target.x, (float)target.y); startGuy = theGuy; for(size_t i=0; i<vDirections.size(); i++) { // if(i == vDirections.size()-1) // { // POINT pEnd; // pEnd.x = (int)vDirections[i]->fX; // pEnd.y = (int)vDirections[i]->fY; // if(PointDistance(theGuy, target) < PointDistance(theGuy, pEnd)) // { // Sleep(300); // theGuy.x = target.x; // theGuy.y = target.y; // InvalidateRect(hWnd, NULL, TRUE); // OnPaint(hWnd); // Sleep(200); // } // break; // } Sleep(300); theGuy.x = (int)vDirections[i]->fX; theGuy.y = (int)vDirections[i]->fY; InvalidateRect(hWnd, NULL, TRUE); OnPaint(hWnd); Sleep(200); } bool bRet=false; tVector2D guy = {(float)theGuy.x, (float)theGuy.y}; tVector2D tar = {(float)target.x, (float)target.y}; for(size_t i=0; i<CPathManager::GetInstance()->m_vLines.size(); i++) { if(IntersectLine(guy, tar, CPathManager::GetInstance()->m_vLines[i].start, CPathManager::GetInstance()->m_vLines[i].end)) { bRet=true; break; } } if(!bRet && !InsideBlocker(target)) { Sleep(300); theGuy.x = target.x; theGuy.y = target.y; InvalidateRect(hWnd, NULL, TRUE); OnPaint(hWnd); Sleep(200); } vDirections.clear(); InvalidateRect(hWnd, NULL, TRUE); OnPaint(hWnd); } // // FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM) // // PURPOSE: Processes messages for the main window. // // WM_COMMAND - process the application menu // WM_PAINT - Paint the main window // WM_DESTROY - post a quit message and return // // LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; switch (message) { case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // Parse the menu selections: switch (wmId) { case IDM_ABOUT: DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_LBUTTONDOWN: TheSequence(hWnd); break; case WM_RBUTTONDOWN: target.x = LOWORD(lParam); target.y = HIWORD(lParam); InvalidateRect(hWnd, NULL, TRUE); break; case WM_PAINT: OnPaint(hWnd); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } // Message handler for about box. INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: return (INT_PTR)TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; }
[ "[email protected]@34577012-8437-c882-6fb8-056151eb068d", "dpmakin@34577012-8437-c882-6fb8-056151eb068d" ]
[ [ [ 1, 181 ], [ 183, 858 ] ], [ [ 182, 182 ] ] ]
3ca0aea5b7a375969fde0a879b97a609835688c0
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/renaissance/rnsstates/src/rnsstates/rnsloadstate_cmds.cc
f5286def3b82604732c881a337ec687f5b8d5b9a
[]
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
936
cc
//------------------------------------------------------------------------------ // rnsloadstate_cmds.cc // (C) 2006 Conjurer Services, S.A. //------------------------------------------------------------------------------ #include "precompiled/pchrnsstates.h" #include "rnsstates/rnsloadstate.h" //------------------------------------------------------------------------------ /** @scriptclass rnsloadstate @cppclass RnsLoadState @superclass ncommonstate @classinfo The Load State class of Renaissance Game */ NSCRIPT_INITCMDS_BEGIN(RnsLoadState); NSCRIPT_ADDCMD('LSNS', void, SetNextState, 1, (const char*), 0, ()); NSCRIPT_ADDCMD('LIPC', bool, InsertPreloadClass, 1, (const char*), 0, ()); NSCRIPT_ADDCMD('LGPR', float, GetPercent, 0, (), 0, () ); NSCRIPT_INITCMDS_END(); //------------------------------------------------------------------------------
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 29 ] ] ]
1c334b9620e6aba2362c8c2ddd8b254587b6d570
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/websrv/web_service_messaging_api/src/testmsenmessage.cpp
1bd4d9df1a46ee12b24d77f74a65de256593104d
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
1,800
cpp
/* * Copyright (c) 2002 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: test class implementation for MSenMessage.h. * */ // INCLUDE FILES #include "testmsenmessage.h" #include <e32base.h> CTestMSenMessage* CTestMSenMessage::NewL() { CTestMSenMessage* pTestMSenMessage = new (ELeave) CTestMSenMessage(); return pTestMSenMessage; } CTestMSenMessage* CTestMSenMessage::NewLC() { CTestMSenMessage* pTestMSenMessage = new (ELeave) CTestMSenMessage(); CleanupStack::PushL(pTestMSenMessage); return pTestMSenMessage; } CTestMSenMessage::CTestMSenMessage() { } MSenMessage::TClass CTestMSenMessage::Type() { EMessageBase; } MSenMessage::TDirection CTestMSenMessage::Direction() { EOutbound; } TInt CTestMSenMessage::SetContext(MSenMessageContext* apNotOwnedContext) { return KErrNone; } MSenMessageContext* CTestMSenMessage::Context() { return NULL; } TInt CTestMSenMessage::SetProperties(MSenProperties* apOwnedProperties) { return KErrNone; } MSenProperties* CTestMSenMessage::Properties() { return NULL; } TBool CTestMSenMessage::IsSafeToCast(TClass aType) { return ETrue; } TInt CTestMSenMessage::TxnId() { return KErrNone; } MSenMessage* CTestMSenMessage::CloneL() { return NULL; }
[ "none@none" ]
[ [ [ 1, 76 ] ] ]
987e17022493da658161ae68dabbf6bbef72fac8
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/tags/v0-1/engine/dialog/src/Graphmaster.cpp
9844573fdee4b1c1a08178826f9506592ab36a5d
[ "ClArtistic", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
jacmoe/dsa-hl-svn
55b05b6f28b0b8b216eac7b0f9eedf650d116f85
97798e1f54df9d5785fb206c7165cd011c611560
refs/heads/master
2021-04-22T12:07:43.389214
2009-11-27T22:01:03
2009-11-27T22:01:03
null
0
0
null
null
null
null
ISO-8859-3
C++
false
false
5,535
cpp
/* This source file is part of Rastullahs Lockenpracht. * Copyright (C) 2003-2005 Team Pantheon. http://www.team-pantheon.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the Clarified Artistic License. * * 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 * Clarified Artistic License for more details. * * You should have received a copy of the Clarified Artistic License * along with this program; if not you can get it here * http://www.jpaulmorrison.com/fbp/artistic2.htm. */ #include "Nodemaster.h" #include "Match.h" #include "StringTokenizer.h" #include "Utils.h" #include "OgreLogManager.h" #include "Graphmaster.h" #include "DialogSubsystem.h" //-- Graphmaster.cpp #include <iostream> using namespace std; namespace rl { Graphmaster::Graphmaster() : mRoot(new Nodemaster()) { } Graphmaster::~Graphmaster() { // Logger::getSingleton().log(Logger::DIALOG, Ogre::LML_TRIVIAL, "Delete all graphmaster nodes"); mRoot->deleteAllNodes(); // Logger::getSingleton().log(Logger::DIALOG, Ogre::LML_TRIVIAL, "Delete root"); delete mRoot; } const static CeGuiString GM_PATTERN = " <pattern> "; const static CeGuiString GM_THAT = " <that> "; const static CeGuiString GM_TOPIC = " <topic> "; const static CeGuiString ASTERISK = "*"; const static CeGuiString UNDERSCORE = "_"; // TODO: templateValue should be an AimlNode Nodemaster* Graphmaster::add( const CeGuiString& context, const CeGuiString& pattern, const CeGuiString& that, const CeGuiString& topic, const CeGuiString& templateValue) { CeGuiString path = (context + GM_PATTERN + pattern + GM_THAT + that + GM_TOPIC + topic); // toUpper Nodemaster *node = mRoot, *child = NULL; //char* c_string = (char*)path.c_str(); //path //-- this code needs to be updated to use the StringTokenizer (this ain't robust) StringTokenizer tokenizer(path, " "); for ( ; tokenizer.hasMoreTokens(); ) { CeGuiString token = tokenizer.nextToken(); //if ( end != NULL ) // *end = '\0'; //CeGuiString token(c_string); token.data(); child = node->getChild(token); if ( child == NULL ) { child = new Nodemaster(templateValue); // eigentlich mรผsste man direkt hier schon // das templateValue รผbergeben kรถnnen node->addChild(token, child); } node = child; //if ( end != NULL ) //{ // c_string = end + 1; // end = strchr(c_string, ' '); //} else // break; } return node; } Match* Graphmaster::match ( const CeGuiString& context, const CeGuiString& pattern, const CeGuiString& that, const CeGuiString& topic) { CeGuiString path = context + GM_PATTERN + pattern + GM_THAT + that + GM_TOPIC + topic; return match(mRoot, mRoot, Context, path, "", ""); } Match* Graphmaster::match ( Nodemaster *node, Nodemaster *parent, component which, const CeGuiString& input, const CeGuiString& star, const CeGuiString& path) { CeGuiString tmpInput = input; StringTokenizer st(tmpInput, " "); //cerr << "PATH: " << path << endl << "STAR: " << star << endl << "INPUT: " << input << endl << endl; if ( !st.hasMoreTokens() ) { if ( node->getTemplateNode() == NULL ) { cout << "-- no template" << endl << endl; return NULL; } Match* match = new Match(); match->setNode(node); match->addStar(star, which); match->setPattern(path, which); return match; } CeGuiString word = st.nextToken(); //cerr << "WORD: " << word << endl; CeGuiString tail = ""; Match* m = NULL; Nodemaster* n = NULL; if ( st.hasMoreTokens() ) { tail = st.getString(); } //cerr << "TAIL: " << tail << endl << endl; static const CeGuiString states = " <pattern> <that> <topic> "; if ( states.find(' ' + word + ' ') != string::npos ) { //-- we're moving to next component match .. must return! component c = Pattern; //-- an unfortunate workaround due to use of an enum switch ( which ) { case Context: c = Pattern; break; case Pattern: c = That; break; case That: c = Topic; break; case Topic: return NULL; } if ( (n = node->getChild(toUpper(word))) ) { m = match(n, node, c, tail, "", ""); if ( m != NULL ) { m->addStar(star.c_str(), which); m->setPattern(path.c_str(), which); } } return m; } if ( (n = node->getChild(UNDERSCORE.c_str())) ) { m = match(n, node, which, tail, word, path + ' ' + UNDERSCORE); if ( m != NULL ) { m->addStar(star.c_str(), which); return m; } } if ( (n = node->getChild(toUpper(word))) ) { m = match(n, node, which, tail, star, path + ' ' + word); if ( m != NULL ) { return m; } } if ( (n = node->getChild(ASTERISK.c_str())) ) { m = match(n, node, which, tail, word, path + ' ' + ASTERISK); if ( m != NULL ) { m->addStar(star.c_str(), which); return m; } } if ( node == parent->getChild(ASTERISK.c_str()) || node == parent->getChild(UNDERSCORE.c_str()) ) return match(node, parent, which, tail, star + ' ' + word, path); return NULL; } } //-- end-of-file
[ "blakharaz@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 194 ] ] ]
801623e6ed187c6a3756ff27febf56e65f67d6b3
f25e9e8fd224f81cefd6d900f6ce64ce77abb0ae
/Exercises/OpenGL6/DDEngine/SceneNode.cpp
6db33531a44c7bbb8132c02864e27ef6007b2841
[]
no_license
giacomof/gameengines2010itu
8407be66d1aff07866d3574a03804f2f5bcdfab1
bc664529a429394fe5743d5a76a3d3bf5395546b
refs/heads/master
2016-09-06T05:02:13.209432
2010-12-12T22:18:19
2010-12-12T22:18:19
35,165,366
0
0
null
null
null
null
UTF-8
C++
false
false
12,171
cpp
#include "sceneNode.h" static int nodeCount = 0; // Constructor that take a pointer to the parant node, the name of the node // the initial position of the node // the initial orientation of the node SceneNode::SceneNode( SceneNode * parentNode, char * str, SceneObject * g, Vector v, Vector p_axis, float p_angle, btRigidBody * rigidBody ) { // variables inizialization nodeNameString = str; parentNode = parentNode; parentNode->addChild(this); geometry = g; physicsGeometry = rigidBody; visible = true; shadingIsActive = false; tranM = new float[16]; btTransform trans = btTransform(); mutex_node = SDL_CreateMutex(); // Initialise the member transformation with the position and orientation parameters nodeTransformation = Transformation(v, p_axis, p_angle); // Define the unique identifier of the node id = nodeCount; nodeCount++; } // If the geometry is a MD2 model than update his animation status // and do so for all his childs void SceneNode::update(float dt) { geometry->update(dt); if (childList.size() != 0) { list<SceneNode*>::iterator itS(childList.begin()); for(itS = childList.begin(); itS != childList.end(); itS++) { (*itS)->update(dt); } } } void SceneNode::destroy(void) { list<SceneNode*>::iterator i(childList.begin()); for(i=childList.begin(); i != childList.end(); ++i) { (*i)->destroy(); } this->release(); } // Add a new child to the node void SceneNode::addChild( SceneNode * cNode ) { cNode->setParent(this); childList.push_front(cNode); } // Set a new parent for the node void SceneNode::setParent( SceneNode * cNode ) { parentNode = cNode; if(parentNode->getName() == "root") { Root::childOfRootList.push_front(this); } } // Return the parent of the node SceneNode* SceneNode::getParent(void) { return parentNode; } // Change the name of the node void SceneNode::setName(char * name) { nodeNameString = name; } // Return the name of the node std::string SceneNode::getName(void) { if(nodeNameString == "") return "No Name"; return nodeNameString; } // Add a geometry to the Scene Node void SceneNode::addSceneObject(SceneObject * g) { geometry = g; } // Return the Geometry of the Scene Node SceneObject * SceneNode::getSceneObject() { return geometry; } // Apply a rotation about an arbitrary axis to the node void SceneNode::rotateAboutAxis(Vector p_Axis, float p_Degree) { if (physicsGeometry != 0) { if (this->getParent()->getName() == "root") { btTransform trans = btTransform(); physicsGeometry->getMotionState()->getWorldTransform(trans); btVector3 btActualPosition = physicsGeometry->getWorldTransform().getOrigin(); Vector actualPosition = Vector(btActualPosition.getX(), btActualPosition.getY(), btActualPosition.getZ()); Vector newPosition = Matrix::generateAxisRotationMatrix(p_Axis, p_Degree) * actualPosition; physicsGeometry->getWorldTransform().setOrigin(btVector3(newPosition.getX(), newPosition.getY(), newPosition.getZ())); btQuaternion actualRotation = trans.getRotation(); btQuaternion newRotation = btQuaternion(btVector3(p_Axis.getX(), p_Axis.getY(), p_Axis.getZ()), p_Degree); physicsGeometry->getWorldTransform().setRotation(newRotation * actualRotation); } } nodeTransformation.addQuaternionRotation(Quaternion(p_Axis, p_Degree)); } // Translate the node void SceneNode::translate(Vector translateVector) { if (physicsGeometry != 0) { if (this->getParent()->getName() == "root") { physicsGeometry->getMotionState()->getWorldTransform(trans); btVector3 final = trans.getOrigin() + btVector3(translateVector.getX(), translateVector.getY(), translateVector.getZ()); physicsGeometry->getWorldTransform().setOrigin(final); } } nodeTransformation.addTranslation(translateVector); } void SceneNode::updateRigidBody(void) { Vector worldPosition = this->getWorldPosition(); Quaternion worldOrientation = this->getWorldOrientation(); physicsGeometry->getWorldTransform().setOrigin(btVector3(worldPosition.getX(), worldPosition.getY(), worldPosition.getZ())); physicsGeometry->getWorldTransform().setRotation(btQuaternion(worldOrientation.getX(), worldOrientation.getY(), worldOrientation.getZ(), worldOrientation.getW())); } // Scale the node void SceneNode::scale(float p_sX, float p_sY, float p_sZ) { /* SCALING NOT CONSISTENT BETWEEN PHYSICS AND GRAPHICS NEED TO BE FIXED*/ //if (physicsGeometry != 0) { // btVector3 oldScale = physicsGeometry->getCollisionShape()->getLocalScaling(); // physicsGeometry->getCollisionShape()->setLocalScaling(btVector3(oldScale.getX()*p_sX, oldScale.getY()*p_sY, oldScale.getX()*p_sZ)); // oldScale = physicsGeometry->getCollisionShape()->getLocalScaling(); //} nodeTransformation.addScaling(p_sX, p_sY, p_sZ); } // Apply a shearing to the node void SceneNode::shear(float p_shXY, float p_shXZ, float p_shYX, float p_shYZ, float p_shZX, float p_shZY) { nodeTransformation.addShearing(p_shXY, p_shXZ, p_shYX, p_shYZ, p_shZX, p_shZY); } Vector SceneNode::getWorldPosition(void) { SceneNode * nodePointer = this; Vector worldPosition = Vector(); Vector temp = Vector(); while(true) { temp = nodePointer->getTransformation()->getTranslation(); if(nodePointer->getParent()->getName() == "root") { worldPosition = worldPosition + temp; break; } else { nodePointer = nodePointer->getParent(); worldPosition = worldPosition + temp; worldPosition = Matrix::generateQuaternionRotationMatrix(nodePointer->getTransformation()->getOrientation()) * worldPosition; } } return worldPosition; } Quaternion SceneNode::getWorldOrientation(void) { SceneNode * nodePointer = this; Quaternion worldOrientation = Quaternion(0,0,0,1); Quaternion temp = Quaternion(); worldOrientation = this->getTransformation()->getOrientation() * worldOrientation; while(nodePointer->getParent()->getName() != "root") { temp = nodePointer->getTransformation()->getOrientation(); nodePointer = nodePointer->getParent(); temp = nodePointer->getTransformation()->getOrientation(); worldOrientation = temp * worldOrientation; } return worldOrientation; } Transformation * SceneNode::getTransformation() { return &nodeTransformation; } // Apply the transformation of the node and then draw it void SceneNode::drawGeometry() { if (physicsGeometry != 0) { if (this->getParent()->getName() == "root") { physicsGeometry->getMotionState()->getWorldTransform(trans); Vector localPosition = nodeTransformation.getBBTranslation(); Vector physicPosition = Vector(trans.getOrigin().getX(), trans.getOrigin().getY(), trans.getOrigin().getZ()); Quaternion orientation = Quaternion(trans.getRotation().getX(), trans.getRotation().getY(), trans.getRotation().getZ(), trans.getRotation().getW()); localPosition = Matrix::generateQuaternionRotationMatrix(orientation) * localPosition; Vector finalPosition = localPosition + physicPosition; nodeTransformation.setTranslation(finalPosition); nodeTransformation.setOrientation(Quaternion(trans.getRotation().getX(), trans.getRotation().getY(), trans.getRotation().getZ(), trans.getRotation().getW())); } else { physicsGeometry->getMotionState()->getWorldTransform(trans); Vector localPosition = nodeTransformation.getBBTranslation(); Quaternion orientation = Quaternion(trans.getRotation().getX(), trans.getRotation().getY(), trans.getRotation().getZ(), trans.getRotation().getW()); localPosition = Matrix::generateQuaternionRotationMatrix(orientation) * localPosition; Vector physicPosition = Vector(trans.getOrigin().getX(), trans.getOrigin().getY(), trans.getOrigin().getZ()); Vector finalPosition = localPosition + physicPosition; nodeTransformation.setTranslation(finalPosition); this->updateRigidBody(); } } applyTransformation(); if(isVisible()) { if(nodeNameString != "Camera Node") { if(shadingIsActive) { AssetManager::activateShadingProgram(shadingProgramName); geometry->drawGeometry(); AssetManager::deactivateShadingProgram(); } else geometry->drawGeometry(); } // draw the name of the SceneNode if(Globals::drawDebug) drawName(); } if(childList.size() != 0) { list<SceneNode*>::iterator itS (childList.begin()); for(itS = childList.begin(); itS != childList.end(); itS++) { (*itS)->drawGeometry(); } } glPopMatrix(); } // Apply the transformation of the node void SceneNode::applyTransformation() { nodeTransformation.getTransformation().getMatrix(&tranM[0]); glPushMatrix(); glMultMatrixf(&tranM[0]); } // Apply the inverse transformation of the node void SceneNode::removeTransformation() { nodeTransformation.getInverseTransformation().getMatrix(&tranM[0]); glPushMatrix(); glMultMatrixf(&tranM[0]); } // Return the visibility status of the Scene Node bool SceneNode::isVisible(void) { return visible; } // Change the visibility status of the Scene Node void SceneNode::setVisible(bool b) { visible = b; } unsigned int SceneNode::getNodeCount(void) { return nodeCount; } void SceneNode::drawName(void) { AssetManager::setShaderFlag(Globals::GREEN); glDisable(GL_LIGHTING); // need to disable lighting for proper text color glColor4f(0.0f, 1.0f, 0.0f, 1.0f); // set text color float * pos = new float[3]; pos[1] = 0; pos[2] = 0; char * tempName = (char *)nodeNameString.c_str(); int i = 0; // loop all characters in the string while(*tempName) { pos[0] = i; glRasterPos3fv(pos); // place text position glutBitmapCharacter(GLUT_BITMAP_HELVETICA_12, *tempName); ++tempName; i+=6; } glEnable(GL_LIGHTING); } void SceneNode::setShadingProgram(char * programName) { shadingProgramName = programName; shadingIsActive = true; } void SceneNode::activateShadingProgram(bool active) { shadingIsActive = active; } SceneNode * SceneNode::findSceneNodeByName(string name) { if( name == nodeNameString ) return this; list<SceneNode*>::iterator itS(childList.begin()); for(itS = childList.begin(); itS != childList.end(); itS++) { string tempName = (*itS)->getName(); if(tempName == name) return (*itS); SceneNode * child = (*itS)->findSceneNodeByName(name); if(child != NULL) return child; } return NULL; } // Static member initialization. Root Root::_instance; list<SceneNode*> Root::childOfRootList; SDL_mutex * Root::rootMutex; unsigned int Root::id; Root &Root::getInstance() { return _instance; } // Method for drawing the entire world moving along the scene graph void Root::drawGeometry() { list<SceneNode*>::iterator itS(childOfRootList.begin()); for(itS = childOfRootList.begin(); itS != childOfRootList.end(); itS++) { (*itS)->drawGeometry(); } glPopMatrix(); } // Update the transformation status of all the child nodes of root void Root::update(float dt) { if(!Globals::isStopped) { list<SceneNode*>::iterator itS(childOfRootList.begin()); for(itS = childOfRootList.begin(); itS != childOfRootList.end(); itS++) { (*itS)->update(dt); } } } // Add a new child to the node void Root::addChild( SceneNode * cNode ) { cNode->setParent(this); childOfRootList.push_front(cNode); } SceneNode * Root::findSceneNodeByName(string name) { if( name == "root" ) return this; list<SceneNode*>::iterator itS(childOfRootList.begin()); for(itS = childOfRootList.begin(); itS != childOfRootList.end(); itS++) { string tempName = (*itS)->getName(); if(tempName == name) return (*itS); SceneNode * child = (*itS)->findSceneNodeByName(name); if(child != NULL) return child; } cout << "I cannot find a sceneNode with that name" << endl; return NULL; }
[ "[email protected]@1a5f623d-5e27-cfcb-749e-01bf3eb0ad9d", "[email protected]@1a5f623d-5e27-cfcb-749e-01bf3eb0ad9d" ]
[ [ [ 1, 2 ], [ 4, 16 ], [ 20, 20 ], [ 24, 25 ], [ 27, 37 ], [ 46, 51 ], [ 53, 92 ], [ 94, 112 ], [ 114, 118 ], [ 120, 183 ], [ 186, 210 ], [ 212, 232 ], [ 234, 285 ], [ 287, 288 ], [ 295, 295 ], [ 297, 336 ], [ 338, 340 ], [ 342, 371 ], [ 395, 398 ], [ 400, 408 ], [ 411, 421 ], [ 424, 424 ], [ 429, 431 ] ], [ [ 3, 3 ], [ 17, 19 ], [ 21, 23 ], [ 26, 26 ], [ 38, 45 ], [ 52, 52 ], [ 93, 93 ], [ 113, 113 ], [ 119, 119 ], [ 184, 185 ], [ 211, 211 ], [ 233, 233 ], [ 286, 286 ], [ 289, 294 ], [ 296, 296 ], [ 337, 337 ], [ 341, 341 ], [ 372, 394 ], [ 399, 399 ], [ 409, 410 ], [ 422, 423 ], [ 425, 428 ], [ 432, 463 ] ] ]
e2ed330d7a3b90cf98a19313e40e3b35c15f7ed8
c70941413b8f7bf90173533115c148411c868bad
/core/include/vtxEditText.h
ace3020bd9438553a29d225220095e5877c8d599
[]
no_license
cnsuhao/vektrix
ac6e028dca066aad4f942b8d9eb73665853fbbbe
9b8c5fa7119ff7f3dc80fb05b7cdba335cf02c1a
refs/heads/master
2021-06-23T11:28:34.907098
2011-03-27T17:39:37
2011-03-27T17:39:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,308
h
/* ----------------------------------------------------------------------------- This source file is part of "vektrix" (the rich media and vector graphics rendering library) For the latest info, see http://www.fuse-software.com/ Copyright (c) 2009-2010 Fuse-Software (tm) 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 __vtxEditText_H__ #define __vtxEditText_H__ #include "vtxPrerequisites.h" #include "vtxDisplayObjectContainer.h" #include "vtxEventListener.h" #include "vtxHtmlOperations.h" #include "vtxHtmlRenderable.h" #include "vtxTextLine.h" namespace vtx { //----------------------------------------------------------------------- /** A visual dynamic/editable textfield that can be displayed inside a Movie */ class vtxExport EditText : public DisplayObjectContainer, public HtmlOperations, public HtmlRenderable { public: static const String TYPE; typedef std::vector<TextLine> LineList; typedef std::map<String, File*> LoadedFiles; EditText(); virtual ~EditText(); virtual void initFromResource(Resource* resource); const String& getType() const; /** @copybrief DisplayObject::_update */ virtual void updateGraphics(const float& delta_time = 0.0f); /** Set the plain text for this textfield */ void setText(const WString& text); /** Get the plain text of this textfield */ const WString& getText(); /** Set the HTML code for this textfield */ void setHtmlText(const WString& text); /** Get the HTML code of this textfield */ const WString& getHtmlText(); const GlyphStrip::Glyph& getGlyphAtPoint(const Vector2& point); const TextLine& getLineAtPoint(const Vector2& point); /** Set the currently selected text */ void setSelection(const uint& beginIndex, const uint& endIndex); /** Get the currently selected text's start index */ const uint& getSelectionBeginIndex() const; /** Get the currently selected text's end index */ const uint& getSelectionEndIndex() const; /** Implementation of DisplayObject::isPointInside */ bool isPointInside(const Vector2& coord); // inherited from EventListener virtual void eventFired(const Event& evt); protected: // properties WString mText; WString mHtmlText; // selection management uint mSelectionBeginIndex; uint mSelectionEndIndex; HtmlSelection mSelectionBegin; HtmlSelection mSelectionEnd; // DOM management bool mNeedDomUpdate; HtmlElement* mHtmlDom; uint mGlyphCount; // visuals float mCurrentHeight; GlyphStrip mCurrentStrip; GlyphStripList mGlyphStrips; TextLine mCurrentLine; LineList mLines; LoadedFiles mLoadedFiles; void _buildGraphicsFromDOM(); /** Inform textfield implementations that they need to update their graphics */ virtual void _updateGraphics() {} void _addFont(HtmlFont* font); void _fontStyleChanged(const StyleElement& style); /** Add an image to the line that is currently being created */ void _addImage(HtmlImage* image); void _addParagraph(HtmlParagraph* paragraph); /** Add a piece of text to the line that is currently being created */ void _addText(HtmlText* text); /** Add a single line element to the line that is currently being created */ void _addLineElement(TextLineElement& elem); /** Start a new line */ void _startNewLine(); // event handlers void keyboardEvent(const KeyboardEvent& evt); void mouseEvent(const MouseEvent& evt); bool mSelecting; typedef std::vector<Shape*> SelectionShapes; SelectionShapes mSelectionShapes; /** Create GlyphStrip objects and Shape instances from the generated line elements */ void _createStripsAndShapes(); void _addSelectionShape(const float& sx, const float& sy, const float& x, const float& y); /** Create Shape instances to display the current selection */ void _createSelectionShapes(); void _clearSelectionShapes(); HtmlSelection _getSelectionAtPoint(const Vector2& point); void loadingCompleted(File* file); void loadingFailed(File* file); }; //----------------------------------------------------------------------- } #endif
[ "stonecold_@9773a11d-1121-4470-82d2-da89bd4a628a", "fixxxeruk@9773a11d-1121-4470-82d2-da89bd4a628a" ]
[ [ [ 1, 31 ], [ 33, 168 ] ], [ [ 32, 32 ] ] ]
8a868ab533af753a9bf933626cafe195d5f77d4f
d2fc16640fb0156afb6528e744867e2be4eec02c
/src/Images/inflate.cpp
6790bc94785aa90a9c32ab6f04d83a1df58d3d15
[]
no_license
wlschmidt/lcdmiscellany
8cd93b5403f9c62a127ddd00c8c5dd577cf72e2f
6623ca05cd978d91580673e6d183f2242bb8eb24
refs/heads/master
2021-01-19T02:30:05.104179
2011-11-02T21:52:07
2011-11-02T21:52:07
48,021,331
1
1
null
2016-07-23T09:08:48
2015-12-15T05:20:15
C++
UTF-8
C++
false
false
11,929
cpp
#include "inflate.h" #include "../malloc.h" struct ExtendedCode { unsigned int lengths; unsigned int bits; }; inline unsigned int ConsumeBytes(const unsigned int num, unsigned char* &pos, unsigned int &offset, const unsigned char *endPos) { unsigned int out; if (pos<endPos) { out = ((((unsigned int*)&pos[-4])[0])>>offset)&((1<<num)-1); offset+=num; pos +=offset>>3; offset &= 7; return out; } if (pos-4<endPos) { const unsigned char* temp = endPos-1; int ndata2 = 0; while (temp>=pos-4) { ndata2 = (ndata2<<8) + temp[0]; temp--; } ndata2>>=offset; ndata2 &= ((1<<num)-1); offset += num; pos +=offset>>3; offset &= 7; return ndata2; } return 0; } struct HuffmanCode { // Max codes is about 300, so at most 299 splits and 300 codes...codes take 1 number, splits two... // Actually, now just splits take 2, codes are put in those. Better safe than sorry, though. unsigned int code[1200]; inline unsigned int GetCode(unsigned char *&pos, unsigned int &offset, const unsigned char*endPos) { unsigned int p;//, i; unsigned int temp; if (pos < endPos) { temp = ((unsigned int*)&pos[-4])[0]>>offset; } else { if (pos>=endPos+4) { return 256; } else { temp = ((unsigned int*)&endPos[-4])[0]>>(offset+8*(pos+4-endPos)); } } p = code[(temp&0xFF)]; temp>>=8; while (p<0x8000) { p=code[p+(temp&3)]; temp >>= 2; } offset+=p>>16; pos += offset>>3; offset&= 7; return p&0x7FFF; } void Init(const unsigned int* lengths, const unsigned int num) { unsigned int numCodes[16]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; unsigned int codes[16][300]; unsigned int i, j, code; for (i=0; i<num; i++) { codes[lengths[i]][numCodes[lengths[i]]++] = i; } code=0; unsigned int bit = 1<<15; for (i=0; i<256; i++) { this->code[i] = 0x8000; } unsigned int next = 256; unsigned int k; for (i=1; i<16; i++) { unsigned int numQuads = ((i+1)&~1)-1; for (j=0; j<numCodes[i]; j++) { unsigned int pos = 0; unsigned int d = ((code>>15)&1) + ((code>>13)&2) + ((code>>11)&4) + ((code>>9)&8) + ((code>>7)&16) + ((code>>5)&32) + ((code>>3)&64) + ((code>>1)&128); if (i<=8) { int inc = 1<<i; int code2 = codes[i][j] + 0x8000 + (i<<16); for (k = d; k < 256; k+=inc) { this->code[k] = code2; } code+=bit; continue; } else { if (this->code[d] & 0x8000) { this->code[d] = next; this->code[next] = 0x8000; this->code[next+1] = 0x8000; this->code[next+2] = 0x8000; this->code[next+3] = 0x8000; pos = next; next += 4; } else { pos = this->code[d]; } } for (k=9; k<numQuads; k+=2) { d = ((code>>(16-k))&1) + ((code>>(14-k))&2); if (this->code[d+pos] & 0x8000) { this->code[d+pos] = next; this->code[next] = 0x8000; this->code[next+1] = 0x8000; this->code[next+2] = 0x8000; this->code[next+3] = 0x8000; pos = next; next += 4; } else { pos = this->code[d+pos]; } } d = ((code>>(16-k))&1); if (i&1) { this->code[d+pos] = codes[i][j] + 0x8000 + (i<<16); this->code[d+pos+2] = codes[i][j] + 0x8000 + (i<<16); } else { d += ((code>>(14-k))&2); this->code[d+pos] = codes[i][j] + 0x8000 + (i<<16); } code+=bit; } bit>>=1; } } }; unsigned char * Inflate(unsigned char* compressed, unsigned int compressedBytes, unsigned int size, unsigned int &uncompressedBytes, int gzip) { //unsigned int ndata; int windowSize = 1<<15; unsigned char *pos3 = compressed+4; if (!gzip) { unsigned char method = compressed[0]&0xF; unsigned char flags = compressed[0] >> 4; if (method !=8 || flags>7 || ((compressed[0] * 256 + compressed[1]) %31) || compressed[1] & 0x20) { return 0; } windowSize = 1<<(flags + 8); pos3 += 2; } unsigned char *uncompressed = (unsigned char*) malloc(sizeof(unsigned char)*(size+15)); if (!uncompressed) return 0; //ndata = (compressed[2]) + (compressed[3]<<8) + (compressed[4]<<16) + (compressed[5]<<24); unsigned int offset = 0; unsigned int bfinal; unsigned int type; unsigned int i; unsigned int pos = 0, dist; unsigned int hlit, hdist, hclen; unsigned int codeLengths[330]; HuffmanCode lengths, characters, distances; ExtendedCode lengthTable[29] = {{ 3,0}, { 4,0}, { 5,0}, { 6,0}, { 7,0}, { 8,0}, { 9,0}, { 10,0}, { 11,1}, { 13,1}, { 15,1}, { 17,1}, { 19,2}, { 23,2}, { 27,2}, { 31,2}, { 35,3}, { 43,3}, { 51,3}, { 59,3}, { 67,4}, { 83,4}, { 99,4}, {115,4}, {131,5}, {163,5}, {195,5}, {227,5}, {258,0}}; ExtendedCode distTable[30] = {{ 1,0}, { 2,0}, { 3,0}, { 4,0}, { 5,1}, { 7,1}, { 9,2}, { 13,2}, { 17,3}, { 25,3}, { 33,4}, { 49,4}, { 65,5}, { 97,5}, { 129,6}, { 193,6}, { 257,7}, { 385,7}, { 513,8}, { 769,8}, {1025,9}, {1537,9}, {2049,10}, {3073,10}, {4097,11}, {6145,11}, {8193,12}, {12289,12}, {16385,13}, {24577,13}}; unsigned int len; unsigned int lengthOrder[19] = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; ExtendedCode codeLengthTable[2] = {{3,3}, {11,7}}; unsigned char* endPos = &compressed[compressedBytes-4]; while (1) { //* bfinal = ConsumeBytes(1, pos3, offset, endPos); type = ConsumeBytes(2, pos3, offset, endPos); //offset+=3; //ndata>>=3; //*/ //bfinal = ConsumeBytes(1, pos2, offset, compressed, compressedBytes); if (type == 0) { if (offset) ConsumeBytes(8-offset, pos3, offset, endPos); if (pos3 < endPos) { len = pos3[-4] + (pos3[-3]<<8); unsigned short nlen = pos3[-2] + (pos3[-1]<<8); pos3 += 4; if (pos3-4 + len > endPos || len != (unsigned short)~nlen) { free(uncompressed); return 0; } if (pos+(unsigned long)len >= size) { if (size > (size+size+len) || !srealloc(uncompressed, sizeof(unsigned char)*(size+size+len))) { free(uncompressed); return 0; } size += size + len; } /*if (pos2 + (unsigned long)len >= compressedBytes) { break; }//*/ memcpy(&uncompressed[pos], pos3-4, len); //pos2+=len; pos3+=len; pos += len; //ConsumeBytes(32, pos3, offset, endPos); } else { free(uncompressed); return 0; } } else if (type==3) { free(uncompressed); return 0; //if (type == 1) { //i=0; } else { if (type == 2) { hlit = ConsumeBytes(5, pos3, offset, endPos) + 257; hdist = ConsumeBytes(5, pos3, offset, endPos) + 1; hclen = ConsumeBytes(4, pos3, offset, endPos) + 4; for (i=0; i<hclen; i++) { codeLengths[lengthOrder[i]] = ConsumeBytes(3, pos3, offset, endPos); } for (;i<19;i++) { codeLengths[lengthOrder[i]] = 0; } lengths.Init(codeLengths, 19); for (i=0; i<hlit+hdist; i++) { codeLengths[i] = lengths.GetCode(pos3, offset, endPos); if (codeLengths[i]>15) { if (codeLengths[i]==16) { //3 + bytes codes, but the first one is the current one len = 3 - 1 + ConsumeBytes(2, pos3, offset, endPos); codeLengths[i] = codeLengths[i-1]; while (len-- && i<330) { i++; codeLengths[i] = codeLengths[i-1]; } } else { len = -1 + codeLengthTable[codeLengths[i]-17].lengths + ConsumeBytes(codeLengthTable[codeLengths[i]-17].bits, pos3, offset, endPos); codeLengths[i]=0; while (len-- && i<330) { i++; codeLengths[i] = 0; } } } } characters.Init(codeLengths, hlit); distances.Init(&codeLengths[hlit], hdist); /*for (i=0; i<hdist; i++) { codeLengths[i] = lengths.GetCode(pos2, offset, compressed, compressedBytes); if (codeLengths[i]>15) { if (codeLengths[i]==16) { //3 + bytes codes, but the first one is the current one len = 3 - 1 + ConsumeBytes(2, pos2, offset, compressed, compressedBytes); codeLengths[i] = codeLengths[i-1]; while (len-- && i<299) { i++; codeLengths[i] = codeLengths[i-1]; } } else { len = -1 + codeLengthTable[codeLengths[i]-17].lengths + ConsumeBytes(codeLengthTable[codeLengths[i]-17].bits, pos2, offset, compressed, compressedBytes); codeLengths[i]=0; while (len-- && i<299) { i++; codeLengths[i] = 0; } } } } distances.Init(codeLengths, hdist);*/ } else { for (i=0; i<144; i++) codeLengths[i] = 8; for ( ; i<256; i++) codeLengths[i] = 9; for ( ; i<280; i++) codeLengths[i] = 7; for ( ; i<288; i++) codeLengths[i] = 8; characters.Init(codeLengths, i); for (i=0; i<30; i++) codeLengths[i] = 5; distances.Init(codeLengths, i); } while (1) { if (285+pos>size) { if (size > (size+size + 285) || !srealloc(uncompressed, sizeof(unsigned char)*(size+size + 285))) { free(uncompressed); return 0; } size += size + 285; } register unsigned int i=characters.GetCode(pos3, offset, endPos); if (i<256) { uncompressed[pos++] = (unsigned char) i; } else if (i>256) { len = lengthTable[i-257].lengths + ConsumeBytes(lengthTable[i-257].bits, pos3, offset, endPos); dist = distances.GetCode(pos3, offset, endPos); dist = distTable[dist].lengths + ConsumeBytes(distTable[dist].bits, pos3, offset, endPos); if (pos>=dist) { while (len+pos>size) { if (size > (size+=size) || !srealloc(uncompressed, sizeof(unsigned char)*size)) { free(uncompressed); return 0; } } /*// memcpy is not safe to use here. if (dist>=len) { memcpy(&uncompressed[pos], &uncompressed[pos-dist], len); pos+=len; } else {*/ for (i=0; i<len; i++) { uncompressed[pos] = uncompressed[pos-dist]; pos++; } //} } } else { break; } } } /*else if (type == 3) { i=0; }*/ if (bfinal) { break; } } if (offset) ConsumeBytes(8-offset, pos3, offset, endPos); uncompressedBytes = pos; //unsigned int test = Adler32(uncompressed, pos); //unsigned int test2 = (compressed[pos2-4]<<24)+(compressed[pos2-3]<<16)+(compressed[pos2-2]<<8)+compressed[pos2-1]; // | 1 makes sure I don't get a 0-length result, if all goes well. srealloc(uncompressed, (uncompressedBytes | 1) * sizeof(char)); return uncompressed; } #define FTEXT 1 #define FHCRC 2 #define FEXTRA 4 #define FNAME 8 #define FCOMMENT 16 char *InflateGzip(char *compressed, unsigned int compressedBytes, unsigned int &uncompressedBytes) { if (compressedBytes<10) return 0; unsigned int p = 0; unsigned char id1 = compressed[p++], id2 = compressed[p++], cm = compressed[p++], flg = compressed[p++]; int mtime = ((int*)&compressed[p])[0]; p+=4; unsigned char xfl = compressed[p++], os = compressed[p++]; if (id1 != 0x1f || // gzip id2 != 0x8b || // gzip cm != 8) // deflate return 0; if (flg & FEXTRA) { unsigned short len = ((unsigned short*)&compressed[p])[0]; p+=2; p += len; } if (flg & FNAME) { while (p<compressedBytes && compressed[p]) p++; p++; } if (flg & FCOMMENT) { while (p<compressedBytes && compressed[p]) p++; p++; } if (flg & FHCRC) p+=2; if (p>=compressedBytes) return 0; return (char*) Inflate((unsigned char*)&compressed[p], compressedBytes-p, compressedBytes * 3, uncompressedBytes, 1); }
[ "mattmenke@88352c64-7129-11de-90d8-1fdda9445408" ]
[ [ [ 1, 432 ] ] ]
ee12872c0c74f7b41800a422ddcb19a8ed33f3de
cd0987589d3815de1dea8529a7705caac479e7e9
/webkit/WebKit/win/WebBackForwardList.cpp
b7e9e6ca151bea2cf3789f3697ea91bc170df84c
[ "BSD-2-Clause" ]
permissive
azrul2202/WebKit-Smartphone
0aab1ff641d74f15c0623f00c56806dbc9b59fc1
023d6fe819445369134dee793b69de36748e71d7
refs/heads/master
2021-01-15T09:24:31.288774
2011-07-11T11:12:44
2011-07-11T11:12:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,978
cpp
/* * Copyright (C) 2006, 2007 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. 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 "config.h" #include "WebKitDLL.h" #include "WebBackForwardList.h" #include "COMPtr.h" #include "WebFrame.h" #include "WebKit.h" #include "WebPreferences.h" #include <WebCore/BackForwardList.h> #include <WebCore/HistoryItem.h> using std::min; using namespace WebCore; // WebBackForwardList ---------------------------------------------------------------- static HashMap<BackForwardList*, WebBackForwardList*>& backForwardListWrappers() { static HashMap<BackForwardList*, WebBackForwardList*> staticBackForwardListWrappers; return staticBackForwardListWrappers; } WebBackForwardList::WebBackForwardList(PassRefPtr<BackForwardList> backForwardList) : m_refCount(0) , m_backForwardList(backForwardList) { ASSERT(!backForwardListWrappers().contains(m_backForwardList.get())); backForwardListWrappers().set(m_backForwardList.get(), this); gClassCount++; gClassNameCount.add("WebBackForwardList"); } WebBackForwardList::~WebBackForwardList() { ASSERT(m_backForwardList->closed()); ASSERT(backForwardListWrappers().contains(m_backForwardList.get())); backForwardListWrappers().remove(m_backForwardList.get()); gClassCount--; gClassNameCount.remove("WebBackForwardList"); } WebBackForwardList* WebBackForwardList::createInstance(PassRefPtr<BackForwardList> backForwardList) { WebBackForwardList* instance; instance = backForwardListWrappers().get(backForwardList.get()); if (!instance) instance = new WebBackForwardList(backForwardList); instance->AddRef(); return instance; } // IUnknown ------------------------------------------------------------------- HRESULT STDMETHODCALLTYPE WebBackForwardList::QueryInterface(REFIID riid, void** ppvObject) { *ppvObject = 0; if (IsEqualGUID(riid, IID_IUnknown)) *ppvObject = static_cast<IWebBackForwardList*>(this); else if (IsEqualGUID(riid, IID_IWebBackForwardList)) *ppvObject = static_cast<IWebBackForwardList*>(this); else if (IsEqualGUID(riid, IID_IWebBackForwardListPrivate)) *ppvObject = static_cast<IWebBackForwardListPrivate*>(this); else return E_NOINTERFACE; AddRef(); return S_OK; } ULONG STDMETHODCALLTYPE WebBackForwardList::AddRef(void) { return ++m_refCount; } ULONG STDMETHODCALLTYPE WebBackForwardList::Release(void) { ULONG newRef = --m_refCount; if (!newRef) delete(this); return newRef; } // IWebBackForwardList --------------------------------------------------------- HRESULT STDMETHODCALLTYPE WebBackForwardList::addItem( /* [in] */ IWebHistoryItem* item) { COMPtr<WebHistoryItem> webHistoryItem; if (!item || FAILED(item->QueryInterface(&webHistoryItem))) return E_FAIL; m_backForwardList->addItem(webHistoryItem->historyItem()); return S_OK; } HRESULT STDMETHODCALLTYPE WebBackForwardList::goBack( void) { m_backForwardList->goBack(); return S_OK; } HRESULT STDMETHODCALLTYPE WebBackForwardList::goForward( void) { m_backForwardList->goForward(); return S_OK; } HRESULT STDMETHODCALLTYPE WebBackForwardList::goToItem( /* [in] */ IWebHistoryItem* item) { COMPtr<WebHistoryItem> webHistoryItem; if (!item || FAILED(item->QueryInterface(&webHistoryItem))) return E_FAIL; m_backForwardList->goToItem(webHistoryItem->historyItem()); return S_OK; } HRESULT STDMETHODCALLTYPE WebBackForwardList::backItem( /* [retval][out] */ IWebHistoryItem** item) { if (!item) return E_POINTER; HistoryItem* historyItem = m_backForwardList->backItem(); if (!historyItem) return E_FAIL; *item = WebHistoryItem::createInstance(historyItem); return S_OK; } HRESULT STDMETHODCALLTYPE WebBackForwardList::currentItem( /* [retval][out] */ IWebHistoryItem** item) { if (!item) return E_POINTER; HistoryItem* historyItem = m_backForwardList->currentItem(); if (!historyItem) return E_FAIL; *item = WebHistoryItem::createInstance(historyItem); return S_OK; } HRESULT STDMETHODCALLTYPE WebBackForwardList::forwardItem( /* [retval][out] */ IWebHistoryItem** item) { if (!item) return E_POINTER; HistoryItem* historyItem = m_backForwardList->forwardItem(); if (!historyItem) return E_FAIL; *item = WebHistoryItem::createInstance(historyItem); return S_OK; } HRESULT STDMETHODCALLTYPE WebBackForwardList::backListWithLimit( /* [in] */ int limit, /* [out] */ int* listCount, /* [retval][out] */ IWebHistoryItem** list) { HistoryItemVector historyItemVector; m_backForwardList->backListWithLimit(limit, historyItemVector); *listCount = static_cast<int>(historyItemVector.size()); if (list) for (unsigned i = 0; i < historyItemVector.size(); i++) list[i] = WebHistoryItem::createInstance(historyItemVector[i].get()); return S_OK; } HRESULT STDMETHODCALLTYPE WebBackForwardList::forwardListWithLimit( /* [in] */ int limit, /* [out] */ int* listCount, /* [retval][out] */ IWebHistoryItem** list) { HistoryItemVector historyItemVector; m_backForwardList->forwardListWithLimit(limit, historyItemVector); *listCount = static_cast<int>(historyItemVector.size()); if (list) for (unsigned i = 0; i < historyItemVector.size(); i++) list[i] = WebHistoryItem::createInstance(historyItemVector[i].get()); return S_OK; } HRESULT STDMETHODCALLTYPE WebBackForwardList::capacity( /* [retval][out] */ int* result) { *result = (int)m_backForwardList->capacity(); return S_OK; } HRESULT STDMETHODCALLTYPE WebBackForwardList::setCapacity( /* [in] */ int size) { if (size < 0) return E_FAIL; m_backForwardList->setCapacity(size); return S_OK; } HRESULT STDMETHODCALLTYPE WebBackForwardList::backListCount( /* [retval][out] */ int* count) { *count = m_backForwardList->backListCount(); return S_OK; } HRESULT STDMETHODCALLTYPE WebBackForwardList::forwardListCount( /* [retval][out] */ int* count) { *count = m_backForwardList->forwardListCount(); return S_OK; } HRESULT STDMETHODCALLTYPE WebBackForwardList::containsItem( /* [in] */ IWebHistoryItem* item, /* [retval][out] */ BOOL* result) { COMPtr<WebHistoryItem> webHistoryItem; if (!item || FAILED(item->QueryInterface(&webHistoryItem))) return E_FAIL; *result = m_backForwardList->containsItem(webHistoryItem->historyItem()); return S_OK; } HRESULT STDMETHODCALLTYPE WebBackForwardList::itemAtIndex( /* [in] */ int index, /* [retval][out] */ IWebHistoryItem** item) { if (!item) return E_POINTER; HistoryItem* historyItem = m_backForwardList->itemAtIndex(index); if (!historyItem) return E_FAIL; *item = WebHistoryItem::createInstance(historyItem); return S_OK; } // IWebBackForwardListPrivate -------------------------------------------------------- HRESULT STDMETHODCALLTYPE WebBackForwardList::removeItem( /* [in] */ IWebHistoryItem* item) { COMPtr<WebHistoryItem> webHistoryItem; if (!item || FAILED(item->QueryInterface(&webHistoryItem))) return E_FAIL; m_backForwardList->removeItem(webHistoryItem->historyItem()); return S_OK; }
[ [ [ 1, 305 ] ] ]
69258afe0681ade2e67527591d2f12fbfc7893d3
fcdddf0f27e52ece3f594c14fd47d1123f4ac863
/terralib/src/terralib/kernel/TeLayer.cpp
6ed95a67d35b211b05d96fddb35010f2d3105441
[]
no_license
radtek/terra-printer
32a2568b1e92cb5a0495c651d7048db6b2bbc8e5
959241e52562128d196ccb806b51fda17d7342ae
refs/heads/master
2020-06-11T01:49:15.043478
2011-12-12T13:31:19
2011-12-12T13:31:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
37,823
cpp
/************************************************************************************ TerraLib - a library for developing GIS applications. Copyright ๏ฟฝ 2001-2007 INPE and Tecgraf/PUC-Rio. This code is part of the TerraLib library. 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. You should have received a copy of the GNU Lesser General Public License along with this library. The authors reassure the license terms regarding the warranties. They specifically disclaim any warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose. The library provided hereunder is on an "as is" basis, and the authors have no obligation to provide maintenance, support, updates, enhancements, or modifications. In no event shall INPE and Tecgraf / PUC-Rio be held liable to any party for direct, indirect, special, incidental, or consequential damages arising out of the use of this library and its documentation. *************************************************************************************/ #include "TeLayer.h" #include "TeUtils.h" #include "TeException.h" #include "TeDatabase.h" #include "TeRaster.h" #include "TeProjection.h" TeLayer::TeLayer(const string& name, TeDatabase* db, TeProjection* proj): name_(name), id_(-1), db_(db), projection_ ( proj ), raster_(0) { editionTime_.now(); if (!db_ || name.empty()) return; // verifies if layer already exists in the database string sql = "SELECT * FROM te_layer WHERE name = '" + name + "'"; TeDatabasePortal* portal = db_->getPortal(); if (!portal) return; if (!portal->query(sql)) { delete portal; return; } if (!portal->fetchRow()) { if (!proj) // provides a default projection No Projection projection_ = new TeNoProjection(); else projection_ = TeProjectionFactory::make (proj->params()); db_->insertLayer(this); } else db_->loadLayer(this); int pid = projection_->id(); delete projection_; projection_ = db_->loadProjection(pid); delete portal; } TeLayer::TeLayer(const string& name, TeDatabase* db, TeBox& box, TeProjection* proj): name_(name), id_(-1), db_(db), projection_(proj), box_(box), raster_(0) { editionTime_.now(); if (!db_ || name.empty()) return; // verifies if layer already exists in the database string sql = "SELECT * FROM te_layer WHERE name = '" + name + "'"; TeDatabasePortal* portal = db_->getPortal(); if (!portal) return; if (!portal->query(sql)) { delete portal; return; } if (!portal->fetchRow()) { if (!proj) // provides a default projection No Projection projection_ = new TeNoProjection(); else projection_ = TeProjectionFactory::make (proj->params()); db_->insertLayer(this); } else db_->loadLayer(this); delete portal; } TeLayer::~TeLayer() { if ( projection_ != 0 ) { delete projection_; projection_ = 0; } for (TeRepresPointerVectorIterator it = repVector_.begin(); it != repVector_.end(); it++) { if (*it) { delete (*it); (*it) = 0; } } repVector_.clear(); if (raster_!=0) { delete raster_; raster_ = 0; } } TeLayer::TeLayer( const TeLayer& other ) : projection_(NULL), raster_(NULL) { if (other.projection_ != NULL) { projection_ = TeProjectionFactory::make ( other.projection_->params()); } name_ = other.name_; id_ = other.id_; db_ = other.db_; box_ = TeBox(other.box_); editionTime_ = other.editionTime_; if(other.raster_ != NULL) { TeRaster* oRast = other.raster_; TeRasterParams oRastParams(oRast->params()); raster_ = new TeRaster(oRastParams); } attTables_ = other.attTables_; TeRepresPointerVector oRepVec = other.repVector_; TeRepresPointerVector::iterator it; for(it = oRepVec.begin(); it != oRepVec.end(); ++it) { TeRepresentation* rep = new TeRepresentation(); rep->id_ = (*it)->id_; rep->geomRep_ = (*it)->geomRep_; rep->tableName_ = (*it)->tableName_; rep->description_ = (*it)->description_; rep->box_ = (*it)->box_; rep->resX_ = (*it)->resX_; rep->resY_ = (*it)->resY_; rep->nCols_ = (*it)->nCols_; rep->nLins_ = (*it)->nLins_; repVector_.push_back(rep); } } TeLayer& TeLayer::operator= ( const TeLayer& other ) { if ( this != &other ) { if (projection_) delete projection_; projection_ = 0; if (other.projection_) projection_ = TeProjectionFactory::make ( other.projection_->params()); name_ = other.name_; id_ = other.id_; box_ = other.box_; db_ = other.db_; editionTime_ = other.editionTime_; } return *this; } void TeLayer::setLayerBox(const TeBox& box) { box_ = box; if ((id_ > -1) && db_) db_->updateLayerBox(this); } void TeLayer::updateLayerBox(const TeBox& box) { updateBox(box_,box); if ((id_ > -1) && db_) db_->updateLayerBox(this); } void TeLayer::updateLayerBox() { if (id_ < 0 || !db_) return; string sql = "SELECT lower_x, lower_y, upper_x, upper_y FROM te_representation WHERE layer_id = " + Te2String(id_); TeDatabasePortal* portal = db_->getPortal(); if (!portal) return; if (!portal->query(sql)) { delete portal; return; } TeBox box; while (portal->fetchRow()) { TeBox brep(portal->getDouble(0),portal->getDouble(1),portal->getDouble(2),portal->getDouble(3)); updateBox(box,brep); } delete portal; box_ = box; db_->updateLayerBox(this); return; } int TeLayer::getNewObjectId() { if(!db_) return -1; TeDatabasePortal* portal = db_->getPortal(); if(!portal) return -1; try { int objId = 0; string sql; for (TeRepresPointerVectorIterator it = vectRepres().begin(); it != vectRepres().end(); it++) { TeRepresentation* rep = (*it); sql = "SELECT MAX(geom_id) FROM "; sql += rep->tableName_; if (portal->query(sql) && portal->fetchRow()) { string data = portal->getData(0); int value = 0; if(!data.empty()) value = atoi(data.c_str()); objId += value; } portal->freeResult(); } delete portal; return ++objId; } catch(...) { if (portal) { delete portal; return -1; } } return -1; } void TeLayer::setProjection ( TeProjection* proj ) { if (!proj) return; // if no database set just update pointer if (!db_) { if ( projection_) delete projection_; projection_ = proj; return; } if (projection_) { proj->id(projection_->id()); delete projection_; } projection_ = proj; bool status = true; if ( projection_->id() <= 0 ) // new projection not in the database { status = db_->insertProjection(projection_); // update layer information if (status && id_ > 0) { string sql = "UPDATE te_layer SET projection_id = " + Te2String(projection_->id()); sql += " WHERE layer_id=" + Te2String(id_); db_->execute(sql); } } else status = db_->updateProjection(projection_); if (raster_) { delete raster_; raster_ = 0; } } void TeLayer::raster( TeRaster* raster) { if (raster_ ) { delete raster_; raster_ = 0; } raster_ = raster; } bool TeLayer::hasGeometry (TeGeomRep rep) { if (repVector_.empty()) return false; TeRepresPointerVectorIterator it; it = TeFindRepresentation(repVector_.begin(), repVector_.end(),rep); return (it != repVector_.end()); } int TeLayer::geomRep() { if (repVector_.empty()) return TeGEOMETRYNONE; int r = 0; TeRepresPointerVectorIterator it; for (it=repVector_.begin(); it != repVector_.end(); ++it) r = (int)(*it)->geomRep_ | r; return r; } TeTime TeLayer::getEditionTime() const { return editionTime_; } void TeLayer::setEditionTime(const TeTime& editionTime) { editionTime_ = editionTime; } bool TeLayer::updateLayerEditionTime(const bool& setEditionToNow) { if(setEditionToNow) { editionTime_.now(); } if(!editionTime_.isValid()) { return false; } if(!db_->updateLayer(this)) { return false; } return true; } bool TeLayer::reloadLayerEditionTime() { if(db_ == NULL) { return false; } std::string sql = "SELECT edition_time FROM te_layer WHERE layer_id = " + Te2String(id()); TeDatabasePortal* portal = db_->getPortal(); if(!portal->query(sql) || !portal->fetchRow()) { delete portal; return false; } editionTime_ = portal->getDate(0); delete portal; return true; } string TeLayer::tableName(TeGeomRep rep) { TeRepresPointerVectorIterator it; it = TeFindRepresentation(repVector_.begin(), repVector_.end(),rep); if (it != repVector_.end()) return (*it)->tableName_; else return string(""); } int TeLayer::nGeometries(TeGeomRep rep) { TeRepresPointerVectorIterator it; it = TeFindRepresentation(repVector_.begin(), repVector_.end(),rep); int ngeo = 0; if (it != repVector_.end()) { string sql = "SELECT COUNT(geom_id) FROM " + (*it)->tableName_; TeDatabasePortal* portal = db_->getPortal(); if (portal && portal->query(sql) && portal->fetchRow()) ngeo = portal->getInt(0); delete portal; } return ngeo; } bool TeLayer::getRepresentation(TeGeomRep repType, TeRepresPointerVector& result) { TeRepresPointerVectorIterator it; it = repVector_.begin(); while (it != repVector_.end()) { if ((*it)->geomRep_ == repType) result.push_back((*it)); ++it; } if (result.empty()) return false; return true; } TeRepresentation* TeLayer::getRepresentation(TeGeomRep repType, const string& tName) { TeRepresPointerVectorIterator it; it = repVector_.begin(); while (it != repVector_.end()) { if ((*it)->geomRep_ == repType) { if (tName.empty() || (*it)->tableName_== tName) return (*it); } it++; } return 0; } bool TeLayer::removeGeometry (TeGeomRep repType, const string& tName) { if (!db_) return false; if (repType == TeTEXT && tName.empty()) // layer can have more than one TEXT table return false; TeRepresPointerVectorIterator it; it = TeFindRepresentation(repVector_.begin(), repVector_.end(),repType); while (it != repVector_.end()) { if (tName.empty() || (*it)->tableName_== tName) { string del; TeRepresentation* rep = (*it); if (rep->id_ > 0) { del = "DELETE FROM te_representation WHERE repres_id=" + Te2String(rep->id_); if (!db_->execute(del)) return false; } if (!rep->tableName_.empty()) { if(rep->geomRep_ == TeRASTER || rep->geomRep_ == TeRASTERFILE) { TeDatabasePortal* portal = db_->getPortal(); string sql, tname; sql = "SELECT lut_table, raster_table FROM " + rep->tableName_; portal->query(sql); while(portal->fetchRow()) { // delete lut table tname = portal->getData(0); if(!tname.empty()) db_->deleteTable(tname); // delete raster table tname = portal->getData(1); if(rep->geomRep_ != TeRASTERFILE && !tname.empty()) db_->deleteTable(tname); } portal->freeResult(); delete portal; // delete metadata table sql = "DROP TABLE " + rep->tableName_ + "_metadata"; db_->execute(sql); if (raster_) { delete raster_; raster_ = 0; } } if (!db_->deleteTable(rep->tableName_)) return false; } repVector_.erase(it); delete rep; break; } it++; it = TeFindRepresentation(it,repVector_.end(),repType); } updateLayerBox(); return true; } bool TeLayer::addGeometry(TeGeomRep repType, const string& tName, const string& desc) { // check if representation is already in layer if (repType == TeTEXT) { string tt; if (!tName.empty()) tt = tName; else tt = name_ + "Texts"; if (getRepresentation(repType,tt)) return true; } else if (getRepresentation(repType)) return true; if (!db_) // layer has no database associated return false; if (id_ < 0) // layer has not saved in the database { if (!db_->insertLayer (this)) return false; } TeRepresentation* represe = new TeRepresentation(); represe->geomRep_ = repType; if (!tName.empty()) represe->tableName_ = tName; if (!desc.empty()) represe->description_ = desc; if (repType == TePOLYGONS) { if (tName.empty()) represe->tableName_ = "Polygons" + Te2String(id_); if (!db_->createPolygonGeometry (represe->tableName_, this->projection()->epsgCode())) return false; } else if (repType == TeLINES) { if (tName.empty()) represe->tableName_ = "Lines" + Te2String(id_); if (!db_->createLineGeometry (represe->tableName_, this->projection()->epsgCode())) return false; } else if (repType == TePOINTS) { if (tName.empty()) represe->tableName_ = "Points" + Te2String(id_); if (!db_->createPointGeometry (represe->tableName_, this->projection()->epsgCode())) return false; } else if (repType == TeTEXT) { if (tName.empty()) represe->tableName_ = "Texts" + Te2String(id_); if (!db_->createTextGeometry (represe->tableName_, this->projection()->epsgCode())) return false; } else if (repType == TeARCS) { if (tName.empty()) represe->tableName_ = "Arcs"+ Te2String(id_); if (!db_->createArcGeometry (represe->tableName_, this->projection()->epsgCode())) return false; } else if (repType == TeNODES) { if (tName.empty()) represe->tableName_ = "Nodes"+ Te2String(id_); if (!db_->createNodeGeometry (represe->tableName_, this->projection()->epsgCode())) return false; } else if (repType == TeCELLS) { if (tName.empty()) represe->tableName_ = "Cells"+ Te2String(id_); if (!db_->createCellGeometry (represe->tableName_, this->projection()->epsgCode())) return false; } else { return false; } bool res = db_->insertRepresentation(id_,*represe); if (res) repVector_.push_back(represe); else return false; return true; } bool TeLayer::addRasterGeometry(TeRasterParams& par, const string& objectId, const string& tName, const string& desc) { string tableName = tName; TeRepresentation* rep = getRepresentation(TeRASTER,tableName); if (!rep) { rep = new TeRepresentation(); updateBox(rep->box_,par.boundingBox()); if (!tableName.empty()) rep->tableName_ = tableName; else rep->tableName_ = "RasterLayer" + Te2String(id_); if (!desc.empty()) rep->description_ = desc; rep->geomRep_ = TeRASTER; if (!db_->insertRepresentation(id_,*rep)) return false; tableName = rep->tableName_; if (!db_->createRasterGeometry(tableName)) return false; string metadataTableName = tableName+"_metadata"; if (!db_->createRasterMetadataTable(metadataTableName)) return false; repVector_.push_back(rep); } else tableName = rep->tableName_; string oid = objectId; if (oid.empty()) oid = "O1"; if (par.fileName_.empty()) { string aux = "RasterLayer" + Te2String(id_) + "_R_" + objectId; bool flag = db_->tableExist(aux); short i=1; while (flag) { aux = "RasterLayer" + Te2String(id_) + "_R_" + objectId + "_" + Te2String(i); ++i; } par.fileName_ = aux; } //updates the date in the te_representation table if(par.date_.isValid()) { std::string sqlTime = db_->getSQLTime(par.date_); if(!sqlTime.empty()) { std::string sql = "UPDATE te_representation SET initial_time = " + sqlTime; sql += ", final_time = " + sqlTime; sql += " WHERE repres_id=" + Te2String(rep->id_); if(!db_->execute(sql)) { return false; } } } if (!db_->createRasterTable(par.fileName_)) return false; if (!db_->insertRasterGeometry(tableName,par,objectId)) return false; updateLayerBox(par.boundingBox()); par.layerId_ = id_; par.objectId_ = oid; return true; } bool TeLayer::addRasterFileGeometry(TeRaster* raster, const string& objectId, const string& desc) { if (!raster) return false; TeRepresentation* rep = getRepresentation(TeRASTERFILE); if (!rep) { rep = new TeRepresentation(); updateBox(rep->box_,raster->params().boundingBox()); rep->tableName_ = "RasterLayer" + Te2String(id_); rep->geomRep_ = TeRASTERFILE; rep->resX_ = raster->params().resx_; rep->resY_ = raster->params().resy_; rep->nCols_= raster->params().ncols_; rep->nLins_= raster->params().nlines_; if (!desc.empty()) rep->description_ = desc; if (!db_->insertRepresentation(id_,*rep)) return false; if (!db_->createRasterGeometry(rep->tableName_)) return false; if (!db_->createRasterMetadataTable(rep->tableName_+"_metadata")) return false; repVector_.push_back(rep); } //updates the date in the te_representation table if(raster->params().date_.isValid()) { std::string sqlTime = db_->getSQLTime(raster->params().date_); if(!sqlTime.empty()) { std::string sql = "UPDATE te_representation SET initial_time = " + sqlTime; sql += ", final_time = " + sqlTime; sql += " WHERE repres_id=" + Te2String(rep->id_); if(!db_->execute(sql)) { return false; } } } string oid = (objectId.empty()) ? TeGetBaseName(raster->params().fileName_.c_str()) : objectId; if (oid.empty()) oid = "O1"; string sql = "delete from " + rep->tableName_ + " where object_id = '" + oid + "'"; db_->execute(sql); if (!db_->insertRasterGeometry(rep->tableName_,raster->params(),oid)) return false; updateLayerBox(raster->params().boundingBox()); raster->params().layerId_ = id_; raster->params().objectId_ = oid; return true; } bool TeLayer::addRasterGeometry(TeRaster* raster, const string& objectId) { if (!raster) return false; TeRepresentation* rep = getRepresentation(TeRASTER); if (!rep) { rep = new TeRepresentation(); updateBox(rep->box_,raster->params().boundingBox()); rep->tableName_ = "RasterLayer" + Te2String(id_); rep->geomRep_ = TeRASTER; if (!db_->insertRepresentation(id_,*rep)) return false; if (!db_->createRasterGeometry(rep->tableName_)) return false; if (!db_->createRasterMetadataTable(rep->tableName_+"_metadata")) return false; repVector_.push_back(rep); } string oid = objectId; if (oid.empty()) oid = "O1"; string sql = "delete from " + rep->tableName_ + " where object_id = '" + oid + "'"; db_->execute(sql); if (!db_->insertRasterGeometry(rep->tableName_,raster->params(),oid)) return false; updateLayerBox(raster->params().boundingBox()); raster->params().layerId_ = id_; raster->params().objectId_ = oid; return true; } TeRaster* TeLayer::raster(const string& objectId, const char& mode) { if (id_ <= 0 || !(hasGeometry(TeRASTER) || hasGeometry(TeRASTERFILE))) return 0; if (raster_ && !objectId.empty() && (objectId != raster_->objectId() || mode != raster_->params().mode_ )) { delete raster_; raster_ = 0; } if (!raster_) raster_ = db_->loadLayerRaster(id_,objectId, mode); return raster_; } bool TeLayer::getRasterGeometries(vector<string>& objectIds, unsigned int tilingType, const TeBox& box) { objectIds.clear(); if ((!hasGeometry(TeRASTER) && !hasGeometry(TeRASTERFILE)) || id_ <= 0 ) return false; TeDatabasePortal* portal = db_->getPortal(); if (!portal) return false; string get = "SELECT geom_table FROM te_representation WHERE layer_id = " + Te2String(id_); get += " AND (geom_type = 512 OR geom_type = 1024)"; // error executing query or no there is no raster representation if (!portal->query(get) || !portal->fetchRow()) { delete portal; return false; } string tableName = portal->getData(0); if (tableName.empty()) { delete portal; return false; } portal->freeResult(); std::string whereClause = ""; if (tilingType == 1 || tilingType == 2) { if(!whereClause.empty()) { whereClause += " AND "; } whereClause += "tiling_type=" + Te2String(tilingType); } if(box.isValid()) { if(!whereClause.empty()) { whereClause += " AND "; } whereClause = "NOT(lower_x > " + Te2String(box.x2_, 12) + " OR "; whereClause += "upper_x < " + Te2String(box.x1_, 12) + " OR "; whereClause += "lower_y > " + Te2String(box.y2_, 12) + " OR "; whereClause += "upper_y < " + Te2String(box.y1_, 12) + ")"; } get = "SELECT object_id FROM " + tableName; if(!whereClause.empty()) { get += " WHERE " + whereClause; } if (!portal->query(get)) { delete portal; return false; } while (portal->fetchRow()) objectIds.push_back(portal->getData(0)); delete portal; return !objectIds.empty(); } int TeLayer::nObjects(const string& tName) { if (attTables_.empty()) return 0; string linkName; vector<TeTable>::iterator it = attTables_.begin(); while (it != attTables_.end()) { if ((*it).name() == tName) { linkName = (*it).linkName(); break; } it++; } if (linkName.empty()) return 0; int no = 0; string sql; TeDatabasePortal* portal = db_->getPortal(); if (!portal) return 0; sql = "SELECT COUNT(" + linkName + ") FROM " + (*it).name(); if (portal->query(sql) && portal->fetchRow()) no = portal->getInt(0); delete portal; return no; } bool TeLayer::createAttributeTable(TeTable& table) { if (!db_->tableExist(table.name())) { db_->validTable(table); if (!db_->createTable(table.name(),table.attributeList())) return false; } vector<TeTable>::iterator it = attTables_.begin(); while (it != attTables_.end()) { if ((*it).name() == table.name()) return true; ++it; } if(!db_->insertTableInfo(id_, table)) return false; attTables_.push_back(table); return true; } bool TeLayer::addAttributeTable(TeTable& table) { vector<TeTable>::iterator it = attTables_.begin(); while (it != attTables_.end()) { if ((*it).name() == table.name()) return false; it++; } attTables_.push_back(table); return true; } bool TeLayer::removeAttributeTable(string tableName) { vector<TeTable>::iterator it = attTables_.begin(); while (it != attTables_.end()) { if ((*it).name() == tableName) { attTables_.erase(it); return true; } it++; } return false; } void TeLayer::updateAttributeTable(TeTable& table) { vector<TeTable>::iterator it = attTables_.begin(); while (it != attTables_.end()) { if ((*it).name() == table.name()) { attTables_.erase(it); break; } it++; } attTables_.push_back(table); } bool TeLayer::loadLayerTables() { TeDatabase *db = database(); if(!db) return false; attTables_.clear(); return(db->loadLayerTable(this)); } bool TeLayer::getAttrTables(TeAttrTableVector& atts, TeAttrTableType attType) { TeAttrTableVector::iterator it = attTables_.begin(); while (it != attTables_.end()) { if ((attType == TeAllAttrTypes) || ((*it).tableType() == attType)) atts.push_back((*it)); it++; } return (!atts.empty()); } bool TeLayer::getAttrTablesByName(vector<string> &tableNames, TeAttrTableVector& atts, TeAttrTableType attType) { TeAttrTableVector::iterator it; vector<string>::iterator it2; for(it2 = tableNames.begin(); it2 != tableNames.end(); ++it2) { for(it = attTables_.begin(); it != attTables_.end(); ++it) { if ((attType == TeAllAttrTypes) || ((*it).tableType() == attType)) { string name = (*it).name(); string name2 = (*it2); if(name == name2) { atts.push_back((*it)); break; } } } } return (!atts.empty()); } bool TeLayer::getAttrTablesByName(const string& attrTableName, TeTable& table, TeAttrTableType attType) { TeAttrTableVector::iterator it; for(it = attTables_.begin(); it != attTables_.end(); ++it) { if ((attType == TeAllAttrTypes) || ((*it).tableType() == attType)) { string name = (*it).name(); if(name == attrTableName) { table = (*it); return true; } } } return false; } bool TeLayer::addPolygons (TePolygonSet& polySet) { if (!db_) return false; if (polySet.size() > 0 ) { if (!this->hasGeometry(TePOLYGONS)) this->addGeometry(TePOLYGONS); TeRepresentation* rep = getRepresentation(TePOLYGONS); if (rep) { for(unsigned int i = 0; i < polySet.size(); ++i) { if(polySet[i].srid() == -1) { polySet[i].srid(projection_->epsgCode()); } } if (!db_->insertPolygonSet (rep->tableName_, polySet)) return false; //updateLayerBox(polySet.box()); updateBox(box_, polySet.box()); editionTime_.now(); if(!db_->updateLayer(this)) return false; updateBox(rep->box_, polySet.box()); if(!db_->updateRepresentation(id_,*rep)) return false; } else return false; } return true; } bool TeLayer::addLines (TeLineSet& lineSet) { if (!db_) return false; if (lineSet.size() > 0) { if (!this->hasGeometry(TeLINES)) this->addGeometry(TeLINES); TeRepresentation* rep = getRepresentation(TeLINES); if (rep) { for(unsigned int i = 0; i < lineSet.size(); ++i) { if(lineSet[i].srid() == -1) { lineSet[i].srid(projection_->epsgCode()); } } if (!db_->insertLineSet (rep->tableName_, lineSet)) return false; //updateLayerBox(lineSet.box()); updateBox(box_, lineSet.box()); editionTime_.now(); if(!db_->updateLayer(this)) return false; updateBox(rep->box_,lineSet.box()); if (!db_->updateRepresentation(id_,*rep)) return false; } else return false; } return true; } bool TeLayer::addPoints (TePointSet& pointSet) { if (!db_) return false; if (pointSet.size() > 0) { if (!this->hasGeometry(TePOINTS)) this->addGeometry(TePOINTS); string tblName = tableName(TePOINTS); TeRepresentation* rep = getRepresentation(TePOINTS); if (rep) { for(unsigned int i = 0; i < pointSet.size(); ++i) { if(pointSet[i].srid() == -1) { pointSet[i].srid(projection_->epsgCode()); } } if (!db_->insertPointSet (rep->tableName_, pointSet)) return false; //updateLayerBox(pointSet.box()); updateBox(box_, pointSet.box()); editionTime_.now(); if(!db_->updateLayer(this)) return false; updateBox(rep->box_,pointSet.box()); if (!db_->updateRepresentation(id_,*rep)) return false; } else return false; } return true; } bool TeLayer::addText (TeTextSet& textSet, const string& tName) { if (!db_) return false; TeRepresentation* rep =0; string tabName; if (tName.empty()) { int i=0; string name; do { name = "Text_" + Te2String(id_) + "_" + Te2String(i); rep = getRepresentation(TeTEXT,name); ++i; } while (rep); tabName = name; } else tabName = tName; if (textSet.size() > 0 ) { rep = getRepresentation(TeTEXT,tabName); if (!rep) { this->addGeometry(TeTEXT,tabName); rep = getRepresentation(TeTEXT,tabName); } if (rep) { for(unsigned int i = 0; i < textSet.size(); ++i) { if(textSet[i].srid() == -1) { textSet[i].srid(projection_->epsgCode()); } } if (!db_->insertTextSet (tabName, textSet)) return false; //updateLayerBox(textSet.box()); updateBox(box_, textSet.box()); editionTime_.now(); if(!db_->updateLayer(this)) return false; updateBox(rep->box_,textSet.box()); if (!db_->updateRepresentation(id_,*rep)) return false; } else return false; } return true; } bool TeLayer::addCells(TeCellSet& cellSet) { if (!db_) return false; if (cellSet.size() > 0) { string tblName = tableName(TeCELLS); if (!this->hasGeometry(TeCELLS)) this->addGeometry(TeCELLS); TeRepresentation* rep = getRepresentation(TeCELLS); if (rep) { for(unsigned int i = 0; i < cellSet.size(); ++i) { if(cellSet[i].srid() == -1) { cellSet[i].srid(projection_->epsgCode()); } } rep->resX_ = cellSet.resX(); rep->resY_ = cellSet.resY(); if (!db_->insertCellSet(tableName(TeCELLS), cellSet)) return false; //updateLayerBox(cellSet.box()); updateBox(box_, cellSet.box()); editionTime_.now(); if(!db_->updateLayer(this)) return false; updateBox(rep->box_,cellSet.box()); if (!db_->updateRepresentation(id_,*rep)) return false; } else return false; } return true; } bool TeLayer::updatePolygons (TePolygonSet& polySet) { if (!db_) return false; if (polySet.size() > 0 ) { if (!this->hasGeometry(TePOLYGONS)) return false; TeRepresentation* rep = getRepresentation(TePOLYGONS); if (rep) { for(unsigned int i = 0; i < polySet.size(); ++i) { if(polySet[i].srid() == -1) { polySet[i].srid(projection_->epsgCode()); } } if (!db_->updatePolygonSet(rep->tableName_, polySet)) return false; //updateLayerBox(polySet.box()); updateBox(box_, polySet.box()); editionTime_.now(); if(!db_->updateLayer(this)) return false; updateBox(rep->box_, polySet.box()); if(!db_->updateRepresentation(id_,*rep)) return false; } else return false; } return true; } bool TeLayer::updateLines (TeLineSet& lineSet) { if (!db_) return false; if (lineSet.size() > 0) { if (!this->hasGeometry(TeLINES)) return false; TeRepresentation* rep = getRepresentation(TeLINES); if (rep) { for(unsigned int i = 0; i < lineSet.size(); ++i) { if(lineSet[i].srid() == -1) { lineSet[i].srid(projection_->epsgCode()); } } if (!db_->updateLineSet (rep->tableName_, lineSet)) return false; //updateLayerBox(lineSet.box()); updateBox(box_, lineSet.box()); editionTime_.now(); if(!db_->updateLayer(this)) return false; updateBox(rep->box_,lineSet.box()); if (!db_->updateRepresentation(id_,*rep)) return false; } else return false; } return true; } bool TeLayer::updatePoints (TePointSet& pointSet) { if (!db_) return false; if (pointSet.size() > 0) { if (!this->hasGeometry(TePOINTS)) return false; string tblName = tableName(TePOINTS); TeRepresentation* rep = getRepresentation(TePOINTS); if (rep) { for(unsigned int i = 0; i < pointSet.size(); ++i) { if(pointSet[i].srid() == -1) { pointSet[i].srid(projection_->epsgCode()); } } if (!db_->updatePointSet (rep->tableName_, pointSet)) return false; //updateLayerBox(pointSet.box()); updateBox(box_, pointSet.box()); editionTime_.now(); if(!db_->updateLayer(this)) return false; updateBox(rep->box_,pointSet.box()); if (!db_->updateRepresentation(id_,*rep)) return false; } else return false; } return true; } bool TeLayer::updateText (TeTextSet& textSet, const string& tName) { if (!db_) return false; TeRepresentation* rep =0; string tabName; if (tName.empty()) { int i=0; string name; do { name = "Text_" + Te2String(id_) + "_" + Te2String(i); rep = getRepresentation(TeTEXT,name); ++i; } while (rep); tabName = name; } else tabName = tName; if (textSet.size() > 0 ) { rep = getRepresentation(TeTEXT,tabName); if (!rep) { return false; } if (rep) { for(unsigned int i = 0; i < textSet.size(); ++i) { if(textSet[i].srid() == -1) { textSet[i].srid(projection_->epsgCode()); } } if (!db_->updateTextSet (tabName, textSet)) return false; //updateLayerBox(textSet.box()); updateBox(box_, textSet.box()); editionTime_.now(); if(!db_->updateLayer(this)) return false; updateBox(rep->box_,textSet.box()); if (!db_->updateRepresentation(id_,*rep)) return false; } else return false; } return true; } bool TeLayer::updateCells(TeCellSet& cellSet) { if (!db_) return false; if (cellSet.size() > 0) { string tblName = tableName(TeCELLS); if (!this->hasGeometry(TeCELLS)) return false; TeRepresentation* rep = getRepresentation(TeCELLS); if (rep) { rep->resX_ = cellSet.resX(); rep->resY_ = cellSet.resY(); for(unsigned int i = 0; i < cellSet.size(); ++i) { if(cellSet[i].srid() == -1) { cellSet[i].srid(projection_->epsgCode()); } } if (!db_->updateCellSet(tableName(TeCELLS), cellSet)) return false; //updateLayerBox(cellSet.box()); updateBox(box_, cellSet.box()); editionTime_.now(); if(!db_->updateLayer(this)) return false; updateBox(rep->box_,cellSet.box()); if (!db_->updateRepresentation(id_,*rep)) return false; } else return false; } return true; } bool TeLayer::removeGeometries(const std::vector<int>& vecGeomIds, const TeGeomRep& rep) { if(db_ == NULL) { return false; } if (!this->hasGeometry(rep)) { return false; } std::string tblName = tableName(rep); for(unsigned int i = 0; i < vecGeomIds.size(); ++i) { if(!db_->removeGeometry(tblName, rep, vecGeomIds[i])) { return false; } } editionTime_.now(); if(!db_->updateLayer(this)) return false; return true; } bool TeLayer::saveAttributeTable(TeTable& table) { if (!db_ || id_ <= 0) return false; if (!db_->tableExist(table.name())) { if (!db_->createTable(table.name(), table.attributeList())) return false; } if (db_->insertTable (table)) { editionTime_.now(); if(!db_->updateLayer(this)) return false; if (table.id() <= 0) return db_->insertTableInfo(id_,table); else return true; } return false; } bool TeLayer::getPolygons(TePolygonSet &ps, const string& whereClause) { if (!hasGeometry(TePOLYGONS)) return false; return db_->selectPolygonSet(tableName(TePOLYGONS), whereClause, ps); } bool TeLayer::getLines(TeLineSet &ls, const string& whereClause) { if (!hasGeometry(TeLINES)) return false; return db_->selectLineSet(tableName(TeLINES), whereClause, ls); } bool TeLayer::getPoints(TePointSet &ps, const string& whereClause) { if (!hasGeometry(TePOINTS)) return false; return db_->selectPointSet(tableName(TePOINTS), whereClause, ps); } bool TeLayer::getText(TeTextSet &ts, const string& whereClause) { if (!hasGeometry(TeTEXT)) return false; return db_->selectTextSet(tableName(TeTEXT), whereClause, ts); } bool TeLayer::getCells(TeCellSet &cs, const string& whereClause) { if (!hasGeometry(TeCELLS)) return false; return db_->selectCellSet(id_, tableName(TeCELLS), whereClause, cs); } bool TeLayer::locatePolygon (TeCoord2D &pt, TePolygon &polygon, const double& tol) { if (!hasGeometry(TePOLYGONS)) return false; return db_->locatePolygon(tableName(TePOLYGONS),pt, polygon, tol); } bool TeLayer::locateLine (TeCoord2D &pt, TeLine2D &line, const double& tol) { if (!hasGeometry(TeLINES)) return false; return db_->locateLine(tableName(TeLINES),pt, line, tol); } bool TeLayer::locatePoint (TeCoord2D &pt, TePoint &point, const double& tol) { if (!hasGeometry(TePOINTS)) return false; return db_->locatePoint(tableName(TePOINTS), pt, point, tol); } bool TeLayer::locateText(TeCoord2D &pt, TeText &text, const double& tol) { if (!hasGeometry(TeTEXT)) return false; return db_->locateText(tableName(TeTEXT), pt, text, tol); } bool TeLayer::locateCell (TeCoord2D &pt, TeCell &cell, const double& tol) { if (!hasGeometry(TeCELLS)) return false; return db_->locateCell(tableName(TeCELLS), pt, cell, tol); } bool TeLayer::loadGeometrySet(const string& geoid, TePolygonSet &ps) { if (!hasGeometry(TePOLYGONS)) return false; return db_->loadPolygonSet(tableName(TePOLYGONS), geoid, ps); } bool TeLayer::loadGeometrySet (const string& geoid, TeLineSet &ls) { if (!hasGeometry(TeLINES)) return false; return db_->loadLineSet(tableName(TeLINES), geoid, ls);; } bool TeLayer::loadGeometrySet (const string& geoid, TePointSet &ps) { if (!hasGeometry(TePOINTS)) return false; return db_->loadPointSet(tableName(TePOINTS), geoid, ps); } bool TeLayer::loadGeometrySet (const string& geoid, TeCellSet &cs) { if (!hasGeometry(TeCELLS)) return false; return db_->loadCellSet(id_, tableName(TeCELLS), geoid, cs); } bool TeLayer::loadGeometrySet (const string& geoid, TeTextSet &ts) { if (!hasGeometry(TeTEXT)) return false; return db_->loadTextSet(tableName(TeTEXT), geoid, ts); } string TeLayer::mediaTable() { TeAttrTableVector attrs; getAttrTables(attrs, TeAttrMedia); if(attrs.size()<1) return ""; return (attrs[0].name()); } void TeLayer::mediaTable(const string& name) { TeAttributeList attList; TeTable table(name, attList,"object_id", "object_id", TeAttrMedia); attTables_.push_back (table); }
[ "[email protected]@58180da6-ba8b-8960-36a5-00cc02a3ddec" ]
[ [ [ 1, 1711 ] ] ]
2e65c5f4d72ace00eb8aa01280a6bc006edd6608
9b0e82184f7907e6733116c1f309892e7959badd
/jni_firei/FireiDriver/FireiDriver.cpp
b86b455152835db8c513d41e7edd0e1c38fbc5bd
[]
no_license
xuzhikethinker/camera
f72798225aaead665f015978eb77df4606145937
90f49580b92acb9029ef47c9f83038b7821e1455
refs/heads/master
2021-01-18T08:42:22.419872
2011-08-17T22:55:19
2011-08-17T22:55:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,934
cpp
#include <process.h> #include "FireiDriver.h" /******************************************************************************************* * The SDK used is FireAPI 1394a/1394b development toolkit, evaluation (demo) version 5.63. * * To compile the code, you need to install Unibrain FireAPI5.63(Oct2009) and specify the * additional include and lib directories: Unibrain\FireAPI5.63(Oct2009)\src\include and * Unibrain\FireAPI5.63(Oct2009)\src\lib. * * * This code references the sample code in * "Unibrain\Fire-i API 5.60 (Dec 2008)\Samples\IIDC\DropedFrames" * * Unibrain\Fire-i API 5.60 (Dec 2008)\doc\FireiAPISpec.chm provides detailed explanation on * how to use the API, especially the Fire-i ubCore DLL section. The section on Isochronous * Processing gives some details of capturing frames and the difference between extended * and non-extended isochronous processing. Extended isochronous engine allows you to specify * the number of frames to queue. * ********************************************************************************************/ // // Helper code to handle a Firei error. // #define _HANDLE_ERROR( status, function ) \ if( status != FIREi_STATUS_SUCCESS ) \ { \ printf( "%s: %s\n", function, FiStatusString( status ) ); \ return; \ } #define QUEUED_FRAMES 20 const FIREi_OID FireiDriver::m_CAMERA_CONTROLS[NUM_CONTROLS] = { OID_BRIGHTNESS_CONTROL, OID_AUTO_EXPOSURE_CONTROL, OID_SHARPNESS_CONTROL, OID_UB_CONTROL, OID_VR_CONTROL, OID_HUE_CONTROL, OID_SATURATION_CONTROL, OID_GAMMA_CONTROL, OID_SHUTTER_CONTROL, OID_GAIN_CONTROL, OID_IRIS_CONTROL, OID_FOCUS_CONTROL, OID_TEMPERATURE_CONTROL, OID_ZOOM_CONTROL, OID_PAN_CONTROL, OID_TILT_CONTROL, OID_OPTICAL_FILTER_CONTROL }; const FIREi_OID FireiDriver::m_CAMERA_INQ[NUM_CONTROLS] = { OID_BRIGHTNESS_INQ, OID_AUTO_EXPOSURE_INQ, OID_SHARPNESS_INQ, OID_UB_INQ, OID_VR_INQ, OID_HUE_INQ, OID_SATURATION_INQ, OID_GAMMA_INQ, OID_SHUTTER_INQ, OID_GAIN_INQ, OID_IRIS_INQ, OID_FOCUS_INQ, OID_TEMPERATURE_INQ, OID_ZOOM_INQ, OID_PAN_INQ, OID_TILT_INQ, OID_OPTICAL_FILTER_INQ }; /*-----------------------------------------------------------------------------------------------*/ void FireiDriver::initialize(int cameraIndex) { FIREi_CAMERA_GUID CamGuidArray[MAX_BUS_CAMERAS]; FIREi_STATUS FireiStatus; ULONG uCameras; ULONG I; if(m_initialized) return; FiInitialize(); uCameras = MAX_BUS_CAMERAS; FireiStatus = FiLocateCameras(CamGuidArray,FIREi_LOCATE_ALL_CAMERAS,&uCameras ); _HANDLE_ERROR(FireiStatus, "FireiDriver::initialize()"); m_totalCameras = 0; for(I=0;I<uCameras;I++) { FireiStatus = FiOpenCameraHandle(&m_cameraArray[m_totalCameras].hCamera,&CamGuidArray[I]); _HANDLE_ERROR(FireiStatus, "FireiDriver::initialize()"); getCameraDescription(&m_cameraArray[m_totalCameras]); m_totalCameras++; } printCameraDescriptions(); m_startupInfo.Tag = FIREi_CAMERA_STARTUP_INFO_TAG; m_startupInfo.FrameRate = fps_15; //fps_30 is not supported for RGB 640x480 m_startupInfo.VideoMode = Mode_4; //640x480 RGB mode (24bits/pixel) m_startupInfo.VideoFormat = Format_0; //VGA non-compression format m_startupInfo.TransmitSpeed = S200; m_startupInfo.IsochSyCode = 1; m_startupInfo.ChannelNumber = (UCHAR)1; // Start the camera m_cameraIndex = cameraIndex; if(cameraIndex<m_totalCameras) { FireiStatus = FiStartCamera(m_cameraArray[cameraIndex].hCamera, &m_startupInfo); if(FireiStatus == FIREi_STATUS_CAMERA_ALREADY_RUNNING) { m_initialized = true; cleanup(); FireiStatus = FiStartCamera(m_cameraArray[cameraIndex].hCamera, &m_startupInfo); _HANDLE_ERROR(FireiStatus, "FireiDriver::initialize(): restart"); } m_hCamera = &(m_cameraArray[cameraIndex].hCamera); } else { printf("Error: Camera index is greater than total number of cameras!\n"); return; } initIsochEngine(); m_initialized = true; fflush(stdout); } /*-----------------------------------------------------------------------------------------------*/ void FireiDriver::getCameraDescription(Camera* a_Camera) { char szTmp[128]; FIREi_STATUS FireiStatus; //FIREi_CAMERA_SUPPORTED_FORMAT fcsf; FireiStatus = FiQueryCameraRegister( a_Camera->hCamera, OID_VENDOR_NAME, szTmp, sizeof(szTmp)); _HANDLE_ERROR(FireiStatus, "FireiDriver::getCameraDesription()"); strcpy_s(a_Camera->szCamDescription,szTmp); strcat_s(a_Camera->szCamDescription," "); FireiStatus = FiQueryCameraRegister( a_Camera->hCamera, OID_MODEL_NAME, szTmp, sizeof(szTmp)); _HANDLE_ERROR(FireiStatus, "FireiDriver::getCameraDesription()"); strcat_s(a_Camera->szCamDescription,szTmp); strcat_s(a_Camera->szCamDescription," "); //FireiStatus = FiQueryCameraRegister(a_Camera->hCamera,OID_CAMERA_VIDEO_FORMATS, &fcsf, sizeof(FIREi_CAMERA_SUPPORTED_FORMAT)); //printf("Supported format: %0x\n", fcsf.uFormat); //printf("Supported mode for format 0: %x\n", fcsf.SupportedMode[0].uMode); //printf("Supported mode for mode 4: %x\n", fcsf.SupportedMode[0].FrameRate[3]); return; } /*-----------------------------------------------------------------------------------------------*/ void FireiDriver::printCameraDescriptions() { puts("******************* Bus Cameras Found ***********************"); for(int i=0;i<m_totalCameras;i++) { if(FiIsCameraConnected(m_cameraArray[i].hCamera)) puts(m_cameraArray[i].szCamDescription); } puts("*************************************************************"); printf("\n\n"); return; } //------------------------------------------------------------------------------------ // Create and start an isoch receive engine for the first camera found void FireiDriver::initIsochEngine() { FIREi_STATUS FireiStatus; FireiStatus = FiCreateIsochReceiveEngineEx(&m_hIsochEngine,1,&m_channelStartProcessingEvent); _HANDLE_ERROR(FireiStatus, "FireiDriver::InitIsochEngine()"); FireiStatus = FiAllocateFrames(m_hIsochEngine, &m_startupInfo, QUEUED_FRAMES); _HANDLE_ERROR(FireiStatus, "FireiDriver::InitIsochEngine()"); FireiStatus = FiStartIsochReceiveEngineEx(m_hIsochEngine); _HANDLE_ERROR(FireiStatus, "FireiDriver::InitIsochEngine()"); } void FireiDriver::cleanup() { FIREi_STATUS FireiStatus; if(!m_initialized) return; FireiStatus = FiStopCamera(m_cameraArray[m_cameraIndex].hCamera); FireiStatus = FiStopIsochReceiveEngineEx(m_hIsochEngine); FiDeallocateFrames(m_hIsochEngine); FireiStatus = FiDeleteIsochReceiveEngineEx(m_hIsochEngine); freeCameraHandles(); FiTerminate(); m_initialized = false; printf("FireiDriver::cleanup: Done!\n"); fflush(stdout); } void FireiDriver::freeCameraHandles() { FIREi_STATUS FireiStatus; for(int i=0; i<m_totalCameras; i++) { if(m_cameraArray[i].hCamera) { FireiStatus = FiCloseCameraHandle(m_cameraArray[i].hCamera); _HANDLE_ERROR(FireiStatus, "FireiDriver::freeCameraHandles()"); } } } void FireiDriver::capturenow(unsigned char* pimageBGRA32, int width, int height) { PFIREi_CAMERA_FRAME pCameraFrame; ULONG uCompleteFrames; ULONG I; PFIREi_CAMERA_FRAME pFramesArray[QUEUED_FRAMES]; if (*m_hCamera) { switch(WaitForSingleObject(m_channelStartProcessingEvent, INFINITE)) { case WAIT_OBJECT_0: uCompleteFrames = 0; //Get as many frames as possible in the buffer for(;;) { pCameraFrame = FiGetNextCompleteFrameEx(m_hIsochEngine); if(NULL == pCameraFrame) break; pFramesArray[uCompleteFrames] = pCameraFrame; uCompleteFrames++; } if (0 == uCompleteFrames) printf("FireiDriver::capturenow: zero complete frames\n"); I = 0; if (uCompleteFrames > 1) { //printf("%u Frames recieved\n",uCompleteFrames); // Requeue all the frames except for the last one for (I = 0; I < (uCompleteFrames - 1); I++) FiReleaseFrame(pFramesArray[I]); } if (FIREi_STATUS_SUCCESS == pFramesArray[I]->FireiStatus) { int index, cameraBufferIndex, returnBufferIndex; for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { index = w + h * width; cameraBufferIndex = index * 3; returnBufferIndex = index * 4; // Set the alpha byte to 0xff (255) *(pimageBGRA32 + returnBufferIndex + 3) = 0xff; //The order of bytes in the camera buffer is R,G,B,R,G,B... see document "DCAM_Spec_V1_30.pdf" //The order of bytes in the return buffer is BGRA. The IntBuffer is little endian. for (int i = 0; i < 3; i++) *(pimageBGRA32 + returnBufferIndex + i) = *((unsigned char*)(pFramesArray[I]->pCameraFrameBuffer) + cameraBufferIndex + 2 - i); } //printf("Frame received at time: %u\n",pFramesArray[I]->dwTimeStamp); } else _HANDLE_ERROR(pFramesArray[I]->FireiStatus,"FireiDriver::capturenow"); FiReleaseFrame(pFramesArray[I]); break; default: break; } } fflush(stdout); } //Effects: If setting property is successful, return 0; else return -1. int FireiDriver::setProperty(int controlIndex, int value) { FIREi_CAMERA_FEATURE_CONTROL_REGISTER fcfcr; FIREi_STATUS FireiStatus; fcfcr.Tag = FIREi_CAMERA_FEATURE_CONTROL_REGISTER_TAG; fcfcr.bAbsControl = FALSE; fcfcr.bSetOnePush = FALSE; fcfcr.bSetOn = TRUE; fcfcr.bSetAuto = FALSE; fcfcr.ushCurValue = value; FireiStatus = FiSetCameraRegister(*m_hCamera, m_CAMERA_CONTROLS[controlIndex], &fcfcr, sizeof(FIREi_CAMERA_FEATURE_CONTROL_REGISTER)); if(FireiStatus == FIREi_STATUS_SUCCESS) return 0; printf("Failed to set property %d\n", controlIndex); return -1; } int FireiDriver::getCurrentProperty(int controlIndex, int* value, int* isAuto) { FIREi_CAMERA_FEATURE_CONTROL_REGISTER fcfcr; FIREi_STATUS FireiStatus; fcfcr.Tag = FIREi_CAMERA_FEATURE_CONTROL_REGISTER_TAG; FireiStatus = FiQueryCameraRegister(*m_hCamera, m_CAMERA_CONTROLS[controlIndex], &fcfcr, sizeof(FIREi_CAMERA_FEATURE_CONTROL_REGISTER)); if(FireiStatus == FIREi_STATUS_SUCCESS) { *value = fcfcr.ushCurValue; *isAuto = fcfcr.bSetAuto; //printf("FireiDriver::getCurrentProperty value = %d, isAuto = %d\n", *value, *isAuto); fflush(stdout); return 0; } printf("Failed to get camera control property: %d \n", controlIndex); return -1; } int FireiDriver::queryProperty(int controlIndex, int* min, int* max) { FIREi_CAMERA_FEATURE_INQUIRY_REGISTER fcfir; FIREi_STATUS FireiStatus; fcfir.Tag = FIREi_CAMERA_FEATURE_INQUIRY_REGISTER_TAG; if(*m_hCamera) FireiStatus = FiQueryCameraRegister(*m_hCamera, m_CAMERA_INQ[controlIndex], &fcfir, sizeof(FIREi_CAMERA_FEATURE_INQUIRY_REGISTER)); if(FireiStatus == FIREi_STATUS_SUCCESS && fcfir.bIsReadable) { *min = (int)fcfir.ushMinValue; *max = (int)fcfir.ushMaxValue; return 0; } return -1; } void FireiDriver::setAutoProtpery(int controlIndex) { FIREi_CAMERA_FEATURE_CONTROL_REGISTER fcfcr; FIREi_STATUS FireiStatus; fcfcr.Tag = FIREi_CAMERA_FEATURE_CONTROL_REGISTER_TAG; fcfcr.bAbsControl = FALSE; fcfcr.bSetOnePush = FALSE; fcfcr.bSetOn = TRUE; fcfcr.bSetAuto = TRUE; FireiStatus = FiSetCameraRegister(*m_hCamera, m_CAMERA_CONTROLS[controlIndex], &fcfcr, sizeof(FIREi_CAMERA_FEATURE_CONTROL_REGISTER)); //printf("FireiDriver::setAutoProperty called\n"); }
[ [ [ 1, 377 ] ] ]
412c1cf79c72f7101b21b9957e662687c7b5b5ba
f695ff54770f828d18e0013d12d9d760ec6363a3
/compression/Huffman.cpp
7ca5fd47cd042d46e13cd6955b4289557167490f
[]
no_license
dbremner/airhan
377e1b1f446a44170f745d3a3a47e0a30bc917e1
a436fda7799c1032d060c30355c309ec1589e058
refs/heads/master
2021-01-10T19:42:16.321886
2010-05-29T02:16:25
2010-05-29T02:16:25
34,024,271
0
0
null
null
null
null
UTF-8
C++
false
false
9,020
cpp
/*************************************************************** Copyright (c) 2008 Michael Liang Han 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 <string.h> #include <stdio.h> #include <algorithm> #include <vector> #include <iostream> #include "Huffman.h" using namespace lianghancn::air::compression; HuffmanEncoder::HuffmanEncoder() : _symbols(256) , _nodes(NULL) , _codes(NULL) , _root(NULL) , _encoded(0) { } HuffmanEncoder::HuffmanEncoder(int symbols) : _symbols(symbols) , _nodes(NULL) , _codes(NULL) , _root(NULL) , _encoded(0) { } HuffmanEncoder::~HuffmanEncoder() { FreeHuffmanTree(_root); for (int i = 0; i < _symbols; i ++) { if (_codes) { HuffmanCode* code = _codes[i]; if (code) { delete code; } } } delete[] _codes; delete[] _nodes; } void HuffmanEncoder::ReverseBits(value_type* codeBits, int bitsNumber) { int bytesNumber = bitsNumber / 8 + ((bitsNumber % 8 == 0) ? 0 : 1) ; value_type* temp = NULL; size_t codeblockSize = bytesNumber * sizeof(*temp); temp = (value_type*)malloc(codeblockSize); memset(temp, 0, codeblockSize); int currentByte = 0; for (int i = 0; i < bitsNumber; i ++) { if (i > 0 && i % 8 == 0) { currentByte ++; } temp[currentByte] |= (GetBit(codeBits, bitsNumber - i - 1) << (i % 8)); } memcpy(codeBits, temp, codeblockSize); free(temp); } void HuffmanEncoder::BuildCodes(lianghancn::air::compression::HuffmanNode *&rNode) { if (rNode == NULL) { return; } if (_codes == NULL) { _codes = new HuffmanCode*[_symbols]; for (int i = 0; i < _symbols; i ++) { _codes[i] = NULL; } } if (rNode->leaf) { HuffmanNode* current = rNode; int bitsNumber = 0; value_type* bits = NULL; while (current && current->parent) { int byteIndex = bitsNumber / 8; // reach byte boundary if (bitsNumber % 8 == 0) { // TODO - bad effeciency to grow one byte at a time! // code block should be preallocated - need another helper class here. bits = (value_type*)realloc(bits, byteIndex + 1); assert(bits); bits[byteIndex] = 0; } if (current == current->parent->right) { bits[byteIndex] |= 1 << (bitsNumber % 8); } bitsNumber ++; current = current->parent; } if (bits != NULL) { ReverseBits(bits, bitsNumber); } HuffmanCode* code = new HuffmanCode(); code->codeLength = bitsNumber; code->codeBits = bits; _codes[rNode->symbol] = code; } else { BuildCodes(rNode->left); BuildCodes(rNode->right); } } bool HuffmanEncoder::BuildHuffmanTree() { if (_nodes == NULL) { return false; } // TODO - use a better type std::vector<HuffmanNode*> nodeList; int count = 0; for (int i = 0; i < _symbols; i ++) { if (_nodes[i] != NULL && _nodes[i]->count != 0) { nodeList.push_back(_nodes[i]); count ++; } } if (count == 0) { return false; } HuffmanNode* a = NULL; HuffmanNode* b = NULL; HuffmanNode* c = NULL; std::make_heap(nodeList.begin(), nodeList.end(), GreaterThanFrequency()); while (nodeList.size() > 1) { std::pop_heap(nodeList.begin(), nodeList.end(), GreaterThanFrequency()); a = nodeList.back(); nodeList.pop_back(); std::pop_heap(nodeList.begin(), nodeList.end(), GreaterThanFrequency()); b = nodeList.back(); nodeList.pop_back(); c = new HuffmanNode(a, b); a->parent = c; b->parent = c; nodeList.push_back(c); std::push_heap(nodeList.begin(), nodeList.end(), GreaterThanFrequency()); } _root = nodeList.front(); BuildCodes(_root); return true; } void HuffmanEncoder::FreeHuffmanTree(HuffmanNode*& rNode) { if (rNode == NULL) { return; } if (!rNode->leaf) { FreeHuffmanTree(rNode->left); FreeHuffmanTree(rNode->right); } delete rNode; rNode = NULL; } void HuffmanEncoder::ScanFrequency(const char *pName) { FILE* file = fopen(pName, "rb"); if (!file) { std::cout<<"can't open input file"<<std::endl; return; } HuffmanNode** nodes = new HuffmanNode*[_symbols]; for (int i = 0; i < _symbols; i ++) { nodes[i] = NULL; } int c = 0; while ((c = fgetc(file)) != EOF) { value_type index = (value_type)c; if (nodes[index] == NULL) { nodes[index] = new HuffmanNode(index, 1); } nodes[index]->count ++; } _nodes = nodes; fclose(file); #if 0 for (int i = 0; i < _symbols; i ++) { if (_nodes[i]) { std::cout<<_nodes[i]->count<<std::endl; } } #endif } void HuffmanEncoder::EncodeFile(const char *pSource, const char *pDest) { assert(pSource && pDest); FILE* input = fopen(pSource, "rb"); if (input == NULL) { std::cout<<"can't open input file"<<std::endl; return; } FILE* output = fopen(pDest, "wb+"); if (output == NULL) { std::cout<<"can't open output file"<<std::endl; return; } // get statistics and build huffman codes ScanFrequency(pSource); BuildHuffmanTree(); value_type codeIndex = 0; value_type byte = 0; int bitCount = 0; int c; // encode and output while((c = fgetc(input)) != EOF) { codeIndex = (value_type)c; value_type* codeBits = _codes[codeIndex]->codeBits; int codeLength = _codes[codeIndex]->codeLength; for (int i = 0; i <codeLength; i ++) { byte |= GetBit(codeBits, i) << bitCount; if (++ bitCount == 8) { fputc(byte, output); byte = 0; bitCount = 0; } } _encoded ++; } #if 1 for (int i = 0; i < _symbols; i ++) { if (_codes[i] != NULL) { std::cout<<_codes[i]->codeLength<<std::endl; } } #endif if (bitCount > 0) { fputc(byte, output); } fclose(input); fclose(output); } void HuffmanEncoder::DecodeFile(const char* pSource, const char* pDest) { assert(pSource && pDest); FILE* input = fopen(pSource, "rb"); if (input == NULL) { std::cout<<"can't open input file"<<std::endl; return; } FILE* output = fopen(pDest, "wb+"); if (output == NULL) { std::cout<<"can't open output file"<<std::endl; return; } // for now I don't serialize the code table so this table is generated previously by encoding process.. stupid but enough. // this encoder should not be used in deflate impl.. not canonical huffman tree (which, code length itself is suffice to represent a huffman tree) if (_codes == NULL || _root == NULL) { return; } HuffmanNode* current = _root; int c; int decoded = 0; while ((c = fgetc(input)) != EOF) { value_type byte = (value_type)c; value_type mask = 1; while (mask && (decoded < _encoded)) { current = byte & mask ? current->right : current->left; mask <<= 1; if (current->leaf) { fputc(current->symbol, output); current = _root; decoded ++; } } } fclose(input); fclose(output); }
[ "lianghancn@29280b2a-3d39-11de-8f11-b9fadefa0f10" ]
[ [ [ 1, 405 ] ] ]
690e5e9676f72c7f4296cbbf2ce58e2f4122da31
0b5026bf5e6738d691c917e7d5cd415efd6ed0e6
/trunk/mapgenerator/tests/test_cache.cpp
a20dacf52bbed5b6e8dfa89da0b0c69379fe1110
[ "AFL-2.1" ]
permissive
BackupTheBerlios/mapgeneration-svn
585763838691e898cb235c57146310a1c7e500bd
46ead8b34da12fbb1aab8585e6b974e441b5ec61
refs/heads/master
2020-12-25T18:16:56.114314
2006-11-01T17:51:50
2006-11-01T17:51:50
40,822,922
0
0
null
null
null
null
UTF-8
C++
false
false
5,948
cpp
/******************************************************************************* * MapGeneration Project - Creating a road map for the world. * * * * Copyright (C) 2004-2005 by Rene Bruentrup and Bjoern Scholz * * Licensed under the Academic Free License version 2.1 * *******************************************************************************/ #include <iostream> #include <vector> #include "util/cache.h" using namespace std; using namespace mapgeneration_util; class TestObject { public: TestObject(int size) : _size(size) { } int _size; }; vector<TestObject*> data; class TestCache : public Cache<int, TestObject> { public: TestCache() : Cache<int, TestObject>::Cache(Cache<int, TestObject>::_FIFO, Cache<int, TestObject>::_STANDARD_CACHE, 100000, 1000, 800) { } protected: bool persistent_erase(int id) { if (data[id] != 0) { delete data[id]; data[id] = 0; return true; } return false; } TestObject* persistent_load(int id) { if (id < data.size() && data[id] != 0) { return new TestObject(*data[id]); } return 0; } void persistent_save(int id, TestObject* elem) { if (data[id] != 0) { delete data[id]; } data[id] = new TestObject(*elem); } int persistent_size_of(TestObject* elem) { if (elem) return elem->_size; else return sizeof(TestObject*); } }; class TestThread : public ControlledThread { public: TestThread(TestCache* cache) : ControlledThread::ControlledThread(), _cache(cache), _counter(0), _go_event() { } void thread_run() { cout << "Thread started!\n"; _go_event.wait(10000); sleep(1); while (!should_stop()) { int random_number = (int) ((double)data.size() * ((double)std::rand() / (double)RAND_MAX)); _cache->get(random_number); _counter++; } cout << "Thread stopping!\n"; } TestCache* _cache; int _counter; ost::Event _go_event; }; void show_cache_stats(TestCache& cache) { cout << "Cache stats:\n"; cout << " Cached objects: " << cache.cached_objects() << "\n"; cout << " Cached size : " << cache.cached_size() << " / (" << cache.soft_max_cached_size() << " / " << cache.hard_max_cached_size() << ")\n"; cout << "\n"; } int main() { cout << "\nTesting the cache!\n\n"; cout << "We'll start with initializing a data base.\nIn this test we will" << "use a vector. The objects 0-10000 simulate the size 1, the objects " << "20000-30000 simulate the size 10.\n"; int i; for (i=0; i<10000; i++) data.push_back(new TestObject(1)); for (; i<20000; i++) data.push_back(0); for (; i<30000; i++) data.push_back(new TestObject(10)); cout << "OK!\n\n"; cout << "Now we have to initialize a cache:\n"; TestCache cache; cache.controlled_start(); show_cache_stats(cache); cout << "OK!\n\n"; cout << "Let's fill our cache by using elements 20000 to 20100 for only a short time:\n"; for (i=20000; i<20100; i++) cache.get(i); sleep(1); show_cache_stats(cache); cout << "OK!\n\n"; cout << "Let's use elements 0 to 100:\n"; for (i=0; i<100; i++) cache.get(i); sleep(1); show_cache_stats(cache); cout << "OK!\n\n"; cout << "Now we test the get_or_prefetch functions. First we try to " << "get_or_prefetch element 0 until its returned (which should the " << "the case immidiatly:\n"; while (cache.get_or_prefetch(0) == 0) { cout << "Not yet in cache.\n"; } cout << "In cache.\n"; cout << "OK!\n\n"; cout << "The same with element 500 which should be loaded after a short " << " time:\n"; while (cache.get_or_prefetch(500) == 0) { cout << "Not yet in cache.\n"; } cout << "In cache.\n"; cout << "OK!\n\n"; cout << "Let's random access our cache 10000 times:\n"; for (i=0; i<10; i++) { show_cache_stats(cache); for (int j=0; j<1000; j++) { int random_number = (int) ((double)data.size() * ((double)std::rand() / (double)RAND_MAX)); cache.get(random_number); } } cout << "OK!!\n\n"; cout << "Ok, that is boring. Let's access our cache with 10 threads:\n"; TestThread tt1(&cache); TestThread tt2(&cache); TestThread tt3(&cache); TestThread tt4(&cache); TestThread tt5(&cache); TestThread tt6(&cache); TestThread tt7(&cache); TestThread tt8(&cache); TestThread tt9(&cache); TestThread tt10(&cache); tt1.controlled_start(true); tt2.controlled_start(true); tt3.controlled_start(true); tt4.controlled_start(true); tt5.controlled_start(true); tt6.controlled_start(true); tt7.controlled_start(true); tt8.controlled_start(true); tt9.controlled_start(true); tt10.controlled_start(true); tt1._go_event.signal(); tt2._go_event.signal(); tt3._go_event.signal(); tt4._go_event.signal(); tt5._go_event.signal(); tt6._go_event.signal(); tt7._go_event.signal(); tt8._go_event.signal(); tt9._go_event.signal(); tt10._go_event.signal(); for (i=0; i<10; i++) { sleep(1); show_cache_stats(cache); } tt1.controlled_stop(true); tt2.controlled_stop(true); tt3.controlled_stop(true); tt4.controlled_stop(true); tt5.controlled_stop(true); tt6.controlled_stop(true); tt7.controlled_stop(true); tt8.controlled_stop(true); tt9.controlled_stop(true); tt10.controlled_stop(true); cout << "OK! Counted " << tt1._counter + tt2._counter + tt3._counter + tt4._counter + tt5._counter + tt6._counter + tt7._counter + tt8._counter + tt9._counter + tt10._counter << " accesses in about 10 seconds.\n\n"; cout << "Cleaning used memory: "; int cleaned_objects = 0; for (i=0; i<data.size(); i++) if (data[i]!=0) { cleaned_objects++; delete data[i]; } cout << " deleted " << cleaned_objects << " objects. OK!\n\n"; cout << "Stopping cache:\n"; cache.controlled_stop(); cout << "OK!\n\n"; return 0; }
[ "sihar@8a73a7ee-ebeb-0310-8c2f-b847a91f6bfa" ]
[ [ [ 1, 257 ] ] ]
60bbcc93afb34a8c8c317b720230a6d0b9da45a8
36bf908bb8423598bda91bd63c4bcbc02db67a9d
/Include/CTaskbarNotifier.h
1d94b1f77c96ea7940444ec688f25550d26aabea
[]
no_license
code4bones/crawlpaper
edbae18a8b099814a1eed5453607a2d66142b496
f218be1947a9791b2438b438362bc66c0a505f99
refs/heads/master
2021-01-10T13:11:23.176481
2011-04-14T11:04:17
2011-04-14T11:04:17
44,686,513
0
1
null
null
null
null
UTF-8
C++
false
false
8,591
h
/* CTaskbarNotifier.h Classe per la finestra popup sulla taskbar (MFC). Ripresa e modificata dall'originale di John O'Byrne (TaskbarNotifier.cpp, CreateRgnFromBitmap() by Davide Pizzolato). Luca Piergentili, 13/06/03 [email protected] */ #ifndef _CTASKBARNOTIFIER_H #define _CTASKBARNOTIFIER_H 1 #include "strings.h" #include "window.h" #include "win32api.h" #include "CWndLayered.h" #include "CUrl.h" #include "CToolTipCtrlEx.h" #include "CTaskbarNotifier.config.h" #ifdef _LOAD_ALL_IMAGE_FORMATS #include "CImageFactory.h" #endif // modalita' per il testo #define TN_TEXT_NORMAL 0x0000 #define TN_TEXT_BOLD 0x0001 #define TN_TEXT_ITALIC 0x0002 #define TN_TEXT_UNDERLINE 0x0004 /* TAGS struttura per le macro da sostituire nel testo per il tooltip */ struct TAGS { char tag[16]; char* value; }; /* TASKBARPOPUP struttura per i dati relativi al bitmap per il popup */ #define TASKBARPOPUP_MAX_NAME 64 #define TASKBARPOPUP_MAX_AUTHOR 64 #define TASKBARPOPUP_MAX_COPYRIGHT 64 #define TASKBARPOPUP_MAX_URL MAX_URL #define TASKBARPOPUP_MAX_PICTURENAME _MAX_FILEPATH #define TASKBARPOPUP_MAX_FONTNAME 64 #define TASKBARPOPUP_MAX_POPUPTEXT 256 #define TASKBARPOPUP_MIN_POPUPTIME 100 #define TASKBARPOPUP_MAX_POPUPTIME 10000 #define TASKBARPOPUP_DEFAULT_TIMETOSHOW 600 #define TASKBARPOPUP_DEFAULT_TIMETOSTAY 5000 #define TASKBARPOPUP_DEFAULT_TIMETOHIDE 200 struct TASKBARPOPUP { // [About] char szName[TASKBARPOPUP_MAX_NAME+1]; // Name char szAuthor[TASKBARPOPUP_MAX_AUTHOR+1]; // Author char szCopyright[TASKBARPOPUP_MAX_COPYRIGHT+1]; // Copyright char szUrl[TASKBARPOPUP_MAX_URL+1]; // Url // [Bitmap] char szPicture[TASKBARPOPUP_MAX_PICTURENAME+1]; // Picture int nPictureWidth; int nPictureHeight; int nTextAreaLeft; // TextArea int nTextAreaTop; int nTextAreaRight; int nTextAreaBottom; BYTE R_Transparent; // TransparentColor BYTE G_Transparent; BYTE B_Transparent; // [Font] char szFontName[TASKBARPOPUP_MAX_FONTNAME+1]; // Name int nFontSize; // Size BYTE R_Text; // Color BYTE G_Text; BYTE B_Text; BYTE R_SelectedText; // OnMouseOverColor BYTE G_SelectedText; BYTE B_SelectedText; int nFontStyle; // Style (TN_TEXT_BOLD,TN_TEXT_ITALIC,TN_TEXT_NORMAL) DWORD dwFontAlign; // Align (DT_CENTER,DT_LEFT,DT_RIGHT,DT_BOTTOM,DT_TOP) // [Popup] char szPopupText[TASKBARPOPUP_MAX_POPUPTEXT]; // Text int nPopupTooltip; // Tooltip=yes (yes/no) int nPopupScrollText; // Scroll=no (yes/no) int nPopupScrollDirection; // Direction=left (left/right/none) int nPopupScrollSpeed; // Speed=200 (100...500) int nPopupTimeToShow; // TimeToShow=600 (100/5000) DWORD dwPopupTimeToStay; // TimeToStay=4000 (100/10000 - playtime) int nPopupTimeToHide; // TimeToHide=200 (100/5000) BYTE nPopupTransparency; // Transparency=180 (0=invisible/255=opaque) int nPopupAlwaysOnTop; // AlwaysOnTop=no (yes/no) int nPopupXPos; // AbsolutePosition=x,y int nPopupYPos; int nPopupCloseLeft; // CloseButton int nPopupCloseTop; int nPopupCloseRight; int nPopupCloseBottom; }; /* CTaskbarPopupList classe per la lista dei files per i bitmap per i popup */ class CTaskbarPopupList : public CNodeList { public: CTaskbarPopupList() : CNodeList() {} virtual ~CTaskbarPopupList() {CNodeList::DeleteAll();} void* Create(void) { return(new TASKBARPOPUP); } void* Initialize(void* pVoid) { TASKBARPOPUP* pData = (TASKBARPOPUP*)pVoid; if(!pData) pData = (TASKBARPOPUP*)Create(); if(pData) memset(pData,'\0',sizeof(TASKBARPOPUP)); return(pData); } BOOL PreDelete(ITERATOR iter) { if((TASKBARPOPUP*)iter->data) delete ((TASKBARPOPUP*)iter->data),iter->data = (TASKBARPOPUP*)NULL; return(TRUE); } int Size(void) {return(sizeof(TASKBARPOPUP));} #ifdef _DEBUG const char* Signature(void) {return("CTaskbarPopupList");} #endif }; /* CTaskbarNotifier */ class CTaskbarNotifier : public CWnd, public CWndLayered { public: CTaskbarNotifier(); virtual ~CTaskbarNotifier(); BOOL Create (CWnd *pWndParent); inline void SetMessageWindow (HWND hWnd) {m_hWndParent = hWnd;} BOOL Show (LPCTSTR lpcszText,DWORD dwTimeToShow = 600L,DWORD dwTimeToStay = 4000L,DWORD dwTimeToHide = 200L,int nXPos = -1,int nYPos = -1); BOOL UnShow (void); inline void SetAlwaysOnTop (BOOL bFlag) {m_bIsTopMost = bFlag;} inline void SetOnMouseClick (BOOL bHandleMouseClick) {m_bHandleMouseClick = bHandleMouseClick;} inline void SetOnMouseClickMessage (UINT nMsg) {m_nMsg = nMsg;} inline void SetIDTimerAppearing (UINT nTimerID) {m_nIDT_APPEARING = nTimerID;} inline void SetIDTimerWaiting (UINT nTimerID) {m_nIDT_WAITING = nTimerID;} inline void SetIDTimerDisappearing (UINT nTimerID) {m_nIDT_DISAPPEARING = nTimerID;} inline void SetIDTimerScrolling (UINT nTimerID) {m_nIDT_SCROLLING = nTimerID;} #ifdef _LOAD_ALL_IMAGE_FORMATS void SetLibrary (LPCSTR lpcszLibraryName) {strcpyn(m_szLibraryName,lpcszLibraryName,sizeof(m_szLibraryName));} #endif BOOL SetBitmap (UINT nBitmapID,BYTE R = -1,BYTE G = -1,BYTE B = -1); BOOL SetBitmap (LPCTSTR lpcszFileName,BYTE R = -1,BYTE G = -1,BYTE B = -1); inline int GetBitmapWidth (void) const {return(m_nBitmapWidth);} inline int GetBitmapHeight (void) const {return(m_nBitmapHeight);} inline void SetRect (RECT rcText) {m_rcText = rcText;} void SetFont (LPCTSTR lpcszFont,int nSize,int nNormalStyle,int nSelectedStyle); void SetDefaultFont (void); void SetTextColor (COLORREF crNormalTextColor,COLORREF crSelectedTextColor); void SetTextFormat (UINT nTextFormat) {m_nDefaultTextFormat = nTextFormat;} void SetTextScroll (BOOL bScroll,int nDirection = -1,DWORD dwSpeed = 200L); inline void SetTextFiller (LPCSTR lpcszTextFiller) {m_strTextFiller.Format("%s",lpcszTextFiller);} inline void SetToolTip (LPCSTR lpcszText = NULL) {if(lpcszText && strcmp(lpcszText,"")!=0) strcpyn(m_szToolTipText,lpcszText,sizeof(m_szToolTipText)); else memset(m_szToolTipText,'\0',sizeof(m_szToolTipText));} inline LPCSTR GetToolTip (void) const {return(m_szToolTipText);} protected: void OnMouseMove (UINT nFlags,CPoint point); void OnLButtonUp (UINT nFlags,CPoint point); LRESULT OnMouseHover (WPARAM wParam,LPARAM lParam); LRESULT OnMouseLeave (WPARAM wParam,LPARAM lParam); BOOL OnEraseBkgnd (CDC* pDC); void OnPaint (void); BOOL OnSetCursor (CWnd* pWnd,UINT nHitTest,UINT nMsg); void OnTimer (UINT nIDEvent); void OnClose (void); void OnDestroy (void); private: void ResetTimers (void); void ResetWindow (void); void ResetBitmap (void); BOOL SetBitmap (BYTE R,BYTE G,BYTE B); HRGN CreateRgnFromBitmap (HBITMAP hBitmap,COLORREF color); BOOL m_bIsValid; BOOL m_bIsTopMost; CWnd* m_pWndParent; HWND m_hWndParent; UINT m_nMsg; int m_nAnimStatus; UINT m_nIDT_APPEARING; UINT m_nIDT_WAITING; UINT m_nIDT_DISAPPEARING; UINT m_nIDT_SCROLLING; UINT m_nTimerAppearing; UINT m_nTimerWaiting; UINT m_nTimerDisappearing; UINT m_nTimerScrolling; HCURSOR m_hCursor; BOOL m_bHandleMouseClick; BOOL m_bMouseIsOver; CString m_strText; CString m_strTextFiller; CRect m_rcText; UINT m_nDefaultTextFormat; CFont m_fntNormal; CFont m_fntSelected; COLORREF m_crNormalTextColor; COLORREF m_crSelectedTextColor; BOOL m_bScrollText; int m_nScrollDirection; DWORD m_dwScrollSpeed; char m_szToolTipText[512]; CToolTipCtrlEx m_wndToolTip; #ifdef _LOAD_ALL_IMAGE_FORMATS CImage* m_pImage; CImageFactory m_ImageFactory; char m_szLibraryName[_MAX_PATH+1]; #endif BOOL m_bBitmapLoaded; CBitmap m_bitmapBackground; HRGN m_hBitmapRegion; int m_nBitmapWidth; int m_nBitmapHeight; int m_nXPos; int m_nYPos; int m_nTaskbarPlacement; DWORD m_dwTimerPrecision; DWORD m_dwTimeToStay; DWORD m_dwShowEvents; DWORD m_dwHideEvents; int m_nCurrentPosX; int m_nCurrentPosY; int m_nCurrentWidth; int m_nCurrentHeight; int m_nIncrementShow; int m_nIncrementHide; UINT m_nOnLButtonUpFlags; CPoint m_ptOnLButtonUpPoint; TRACKMOUSEEVENT m_trackMouseEvent; DECLARE_MESSAGE_MAP() }; #endif // _CTASKBARNOTIFIER_H
[ [ [ 1, 269 ] ] ]
1755df96f3e4feb2f6624389a7815591b03dd761
49f5a108a2ac593b9861f9747bd82eb597b01e24
/src/JSON/MiniCommon/Matrix.h
566b0ab42be37269d7fcd0afc41aaaa7de8d1be8
[]
no_license
gpascale/iSynth
5801b9a1b988303ad77872fad98d4bf76d86e8fe
e45e24590fabb252a5ffd10895b2cddcc988b83d
refs/heads/master
2021-03-19T06:01:57.451784
2010-08-02T02:22:54
2010-08-02T02:22:54
811,695
0
1
null
null
null
null
UTF-8
C++
false
false
22,736
h
#ifndef Matrix_h #define Matrix_h #include "Plane.h" #include "Space.h" #include "Hyperspace.h" // ENABLE_PROJECTIVE_SHORTCUT, when defined, allows DMatrix4 * DPoint3 type // operators, which assume w==1. #define ENABLE_PROJECTIVE_SHORTCUT 0 #define MatrixT(NAME,TYPE,D,R) \ public: \ typedef TYPE T; \ typedef const TYPE cT; \ typedef NAME##Point##D F; \ typedef const NAME##Point##D cF; \ typedef NAME##Matrix##D M; \ typedef const NAME##Matrix##D cM; \ F v[D]; \ NAME##Matrix##D() { Identity(); } \ NAME##Matrix##D(cM & rhs) { for (int i=0; i<D; i++) v[i]=rhs.v[i]; } \ NAME##Matrix##D & operator = (cM & rhs) { for (int i=0; i<D; i++) v[i]=rhs.v[i]; return *this; } \ const F & operator [] (int i) const { return v[i]; } \ F & operator [] (int i) { return v[i]; } \ bool operator == (const M & rhs) const { for (int i=0; i<D; i++) { if (!(v[i]==rhs.v[i])) return false; } return true; } \ bool operator != (const M & rhs) const { for (int i=0; i<D; i++) { if ( v[i]!=rhs.v[i] ) return true; } return false; } \ void Identity() { \ int i,j; \ for (i=0; i<D; i++) \ for (j=0; j<D; j++) \ v[i][j] = i==j ? T(1) : T(0); \ } \ void transpose() { \ int i,j; \ for (i=0; i<D; i++) \ for (j=0; j<i; j++) \ matrix_Swap(v[i][j], v[j][i]); \ } \ void premultiply(cM & lhs) { \ M tmp; \ for (int j=0; j<D; j++) { \ for (int i=0; i<D; i++) { \ T f = T(0); \ for (int k=0; k<D; k++) \ f += lhs[i][k] * (*this)[k][j]; \ tmp[i][j] = f; \ } \ } \ *this = tmp; \ } \ void postmultiply(cM & rhs) { \ M tmp; \ for (int j=0; j<D; j++) { \ for (int i=0; i<D; i++) { \ T f = T(0); \ for (int k=0; k<D; k++) \ f += (*this)[i][k] * rhs[k][j]; \ tmp[i][j] = f; \ } \ } \ *this = tmp; \ } \ void rotate(cM & rhs) { \ M tmp; \ int i,j; \ for (j=0; j<R; j++) { \ for (i=0; i<R; i++) { \ T f = T(0); \ for (int k=0; k<R; k++) \ f += (*this)[i][k] * rhs[k][j]; \ tmp[i][j] = f; \ } \ } \ for (j=0; j<R; j++) { \ for (i=0; i<R; i++) \ (*this)[i][j] = tmp[i][j]; \ } \ } \ void unrotate(cM & rhs) { \ M tmp; \ int i,j,k; \ for (j=0; j<R; j++) { \ for (i=0; i<R; i++) { \ T f = T(0); \ for (k=0; k<R; k++) \ f += (*this)[i][k] * rhs[j][k]; \ tmp[i][j] = f; \ } \ } \ for (j=0; j<R; j++) { \ for (i=0; i<R; i++) \ (*this)[i][j] = tmp[i][j]; \ } \ } \ T trace() const { \ int i; \ T t = T(0); \ for (i=0; i<D; i++) t += (*this)[i][i]; \ return t; \ } template <class T> inline void matrix_Swap(T & a, T & b) { T c = a; a = b; b = c; } class DMatrix2 { MatrixT(D,double, 2,2) DPoint2 diag() const { return DPoint2(v[0][0], v[1][1]); } }; class DMatrix3 { MatrixT(D,double, 3,2) DPoint3 diag() const { return DPoint3(v[0][0], v[1][1], v[2][2]); } void rotate(double theta) { M m; const double c = cos(theta); const double s = sin(theta); m[0][0] = c; m[0][1] = -s; m[0][2] = 0; m[1][0] = s; m[1][1] = c; m[1][2] = 0; m[2][0] = 0; m[2][1] = 0; m[2][2] = 1; postmultiply(m); } void translate(double x, double y) { M tmp; tmp[0][2] = x; tmp[1][2] = y; postmultiply(tmp); } void preTranslate(double x, double y) { M tmp; tmp[0][2] = x; tmp[1][2] = y; premultiply(tmp); } void translate(const DPoint & p) { translate(p.x, p.y); } void preTranslate(const DPoint & p) { preTranslate(p.x, p.y); } }; class DMatrix4 { MatrixT(D,double, 4,3) DPoint4 diag() const { return DPoint4(v[0][0], v[1][1], v[2][2], v[3][3]); } /// homogeneous assignment-- assumes rhs is for 2D homogeneous transforms! DMatrix4 & operator = (const DMatrix3 & rhs) { v[0].set(rhs[0].x, rhs[0].y, 0., rhs[0].z); v[1].set(rhs[1].x, rhs[1].y, 0., rhs[1].z); v[2].set( 0. , 0. , 1., 0. ); v[3].set( 0. , 0. , 0., 1. ); return *this; } DMatrix4(const DMatrix3 & rhs) { operator = (rhs); } /// form taking a linear 3D transform on the rhs DMatrix4(const DMatrix3 & rhs, bool) { v[0].set(rhs[0].x, rhs[0].y, rhs[0].z, 0.); v[1].set(rhs[1].x, rhs[1].y, rhs[1].z, 0.); v[2].set(rhs[2].x, rhs[2].y, rhs[2].z, 0.); v[3].set( 0. , 0. , 0., 1.); } DMatrix4(T * p) { // OpenGL constructor-- OpenGL stores translation in entries 12,13,14. v[0].set(p[0], p[4], p[ 8], p[12]); v[1].set(p[1], p[5], p[ 9], p[13]); v[2].set(p[2], p[6], p[10], p[14]); v[3].set(p[3], p[7], p[11], p[15]); } void translate(T x, T y, T z) { M tmp; tmp[0][3] = x; tmp[1][3] = y; tmp[2][3] = z; postmultiply(tmp); } void preTranslate(T x, T y, T z) { M tmp; tmp[0][3] = x; tmp[1][3] = y; tmp[2][3] = z; premultiply(tmp); } void translate(const DPoint3 & p) { translate(p.x, p.y, p.z); } void preTranslate(const DPoint3 & p) { preTranslate(p.x, p.y, p.z); } }; #undef MatrixT inline DPoint2 diag(const DMatrix2 & M) { return M.diag(); } inline DPoint3 diag(const DMatrix3 & M) { return M.diag(); } inline DPoint4 diag(const DMatrix4 & M) { return M.diag(); } #define TransformM(D) \ inline void transform(DPoint##D & lhs, \ const DMatrix##D & M, \ const DPoint##D & p) { \ for (int i=0; i<D; i++) { \ double f = 0.; \ for (int j=0; j<D; j++) \ f += M[i][j] * p[j]; \ lhs[i] = f; \ } \ } \ inline DPoint##D transform(const DMatrix##D & M, \ const DPoint##D & p) { \ DPoint##D lhs; \ transform(lhs, M, p); \ return lhs; \ } TransformM(2) TransformM(3) TransformM(4) #if ENABLE_PROJECTIVE_SHORTCUT // transform and untransform assume unitary D-1 matrices with offsets, // as for rotation with offset; this won't invert the matrix in the // general case. inline void transform(DPoint2 & lhs, const DMatrix3 & M, DPoint2 p) { lhs.x = M[0][0] * p.x + M[0][1] * p.y + M[0][2]; lhs.y = M[1][0] * p.x + M[1][1] * p.y + M[1][2]; } inline DPoint2 transform(const DMatrix3 & M, const DPoint2 & p) { DPoint2 lhs; transform(lhs, M, p); return lhs; } inline void untransform(DPoint2 & lhs, const DMatrix3 & M, DPoint2 p) { p.x -= M[0][2]; p.y -= M[1][2]; lhs.x = M[0][0] * p.x + M[1][0] * p.y; lhs.y = M[0][1] * p.x + M[1][1] * p.y; } inline DPoint2 untransform(const DMatrix3 & M, const DPoint2 & p) { DPoint2 lhs; untransform(lhs, M, p); return lhs; } #endif // ENABLE_PROJECTIVE_SHORTCUT inline DMatrix2 operator - (const DMatrix2 & A, const DMatrix2 & B) { DMatrix2 C; C.v[0] = A.v[0] - B.v[0]; C.v[1] = A.v[1] - B.v[1]; return C; } inline DMatrix2 operator + (const DMatrix2 & A, const DMatrix2 & B) { DMatrix2 C; C.v[0] = A.v[0] + B.v[0]; C.v[1] = A.v[1] + B.v[1]; return C; } inline DMatrix3 operator - (const DMatrix3 & A, const DMatrix3 & B) { DMatrix3 C; C.v[0] = A.v[0] - B.v[0]; C.v[1] = A.v[1] - B.v[1]; C.v[2] = A.v[2] - B.v[2]; return C; } inline DMatrix3 operator + (const DMatrix3 & A, const DMatrix3 & B) { DMatrix3 C; C.v[0] = A.v[0] + B.v[0]; C.v[1] = A.v[1] + B.v[1]; C.v[2] = A.v[2] + B.v[2]; return C; } inline DMatrix4 operator - (const DMatrix4 & A, const DMatrix4 & B) { DMatrix4 C; C.v[0] = A.v[0] - B.v[0]; C.v[1] = A.v[1] - B.v[1]; C.v[2] = A.v[2] - B.v[2]; C.v[3] = A.v[3] - B.v[3]; return C; } inline DMatrix4 operator + (const DMatrix4 & A, const DMatrix4 & B) { DMatrix4 C; C.v[0] = A.v[0] + B.v[0]; C.v[1] = A.v[1] + B.v[1]; C.v[2] = A.v[2] + B.v[2]; C.v[3] = A.v[3] + B.v[3]; return C; } inline DMatrix2 operator * (const DMatrix2 & lhs, double f) { DMatrix2 M; M.v[0] = lhs[0]*f; M.v[1] = lhs[1]*f; return M; } inline DMatrix3 operator * (const DMatrix3 & lhs, double f) { DMatrix3 M; M.v[0] = lhs[0]*f; M.v[1] = lhs[1]*f; M.v[2] = lhs[2]*f; return M; } inline DMatrix4 operator * (const DMatrix4 & lhs, double f) { DMatrix4 M; M.v[0] = lhs[0]*f; M.v[1] = lhs[1]*f; M.v[2] = lhs[2]*f; M.v[3] = lhs[3]*f; return M; } // determinants double det (const DMatrix2 & M); double det2(const DMatrix3 & M); /// homogeneous double det (const DMatrix3 & M); double det2(const DMatrix4 & M); /// homogeneous double det3(const DMatrix4 & M); /// homogeneous double det (const DMatrix4 & M); inline DMatrix2 operator * (const DMatrix2 & lhs, const DMatrix2 & rhs) { DMatrix2 M; M[0][0] = lhs[0][0] * rhs[0][0] + lhs[0][1] * rhs[1][0]; M[1][0] = lhs[1][0] * rhs[0][0] + lhs[1][1] * rhs[1][0]; M[0][1] = lhs[0][0] * rhs[0][1] + lhs[0][1] * rhs[1][1]; M[1][1] = lhs[1][0] * rhs[0][1] + lhs[1][1] * rhs[1][1]; return M; } /// matrix inverse for a general homogeneous 2D matrix (6 deg of m_maxConcurrentConnectiondom) DMatrix3 invH(const DMatrix3 & M); inline DMatrix3 operator * (const DMatrix3 & lhs, const DMatrix3 & rhs) { DMatrix3 M; const int D = 3; for (int j=0; j<D; j++) { for (int i=0; i<D; i++) { double f = 0.; for (int k=0; k<D; k++) f += lhs[i][k] * rhs[k][j]; M[i][j] = f; } } return M; } // left matrix inverse for a 2x2 matrix: // inv(M)*M == Identity DMatrix2 inv(const DMatrix2 & M); // left matrix inverse for a general 3x3 matrix: // inv(M)*M == Identity DMatrix3 inv(const DMatrix3 & M); // left matrix inverse for a general 4x4 matrix: // inv(M)*M == Identity DMatrix4 inv(const DMatrix4 & M); /// version of the 4D matrix inverse that assumes a homogeneous transform, /// i.e. bottom row all zeroes except M[3][3]==1. DMatrix4 invH(const DMatrix4 & M); /// invIH inverts homogeneous 4x4 matrices with no off-diagonal elements /// in the top left 3x3 block-- much easier than the general case! /// This form is encountered in NDC <--> viewport matrices. DMatrix4 invIH(const DMatrix4 & M); inline DMatrix4 operator * (const DMatrix4 & lhs, const DMatrix4 & rhs) { DMatrix4 M; const int D = 4; for (int j=0; j<D; j++) { for (int i=0; i<D; i++) { double f = 0.; for (int k=0; k<D; k++) f += lhs[i][k] * rhs[k][j]; M[i][j] = f; } } return M; } inline DPoint multiply(const DMatrix3 & M, const DPoint & p) { return DPoint(M[0].x * p.x + M[0].y * p.y + M[0].z, M[1].x * p.x + M[1].y * p.y + M[1].z); } inline DPoint project(const DMatrix3 & M, const DPoint & p) { DPoint3 q(M[0].x * p.x + M[0].y * p.y + M[0].z, M[1].x * p.x + M[1].y * p.y + M[1].z, M[2].x * p.x + M[2].y * p.y + M[2].z); const double w1 = 1./q.z; return DPoint(q.x * w1, q.y * w1); } #if ENABLE_PROJECTIVE_SHORTCUT inline DPoint operator * (const DMatrix3 & M, const DPoint & p) { return multiply(M,p); } inline DPoint operator * (const DPoint & p, const DMatrix3 & M) { return multiply(M,p); } #else // !ENABLE_PROJECTIVE_SHORTCUT inline DPoint operator * (const DMatrix3 & M, const DPoint & p) { return project(M,p); } inline DPoint operator * (const DPoint & p, const DMatrix3 & M) { return project(M,p); } #endif // ENABLE_PROJECTIVE_SHORTCUT inline DPoint2 multiply(const DMatrix2 & M, const DPoint2 & p) { return DPoint2(M[0].x * p.x + M[0].y * p.y, M[1].x * p.x + M[1].y * p.y); } inline DPoint3 multiply(const DMatrix3 & M, const DPoint3 & p) { return DPoint3(M[0].x * p.x + M[0].y * p.y + M[0].z * p.z, M[1].x * p.x + M[1].y * p.y + M[1].z * p.z, M[2].x * p.x + M[2].y * p.y + M[2].z * p.z); } inline DPoint3 multiply(const DMatrix4 & M, const DPoint & p) { return DPoint3(M[0].x * p.x + M[0].y * p.y + M[0].w, M[1].x * p.x + M[1].y * p.y + M[1].w, M[2].x * p.x + M[2].y * p.y + M[2].w); } inline DPoint3 multiply(const DMatrix4 & M, const DPoint3 & p) { return DPoint3(M[0].x * p.x + M[0].y * p.y + M[0].z * p.z + M[0].w, M[1].x * p.x + M[1].y * p.y + M[1].z * p.z + M[1].w, M[2].x * p.x + M[2].y * p.y + M[2].z * p.z + M[2].w); } inline DPoint4 multiply(const DMatrix4 & M, const DPoint4 & p) { return DPoint4(M[0].x * p.x + M[0].y * p.y + M[0].z * p.z + M[0].w * p.w, M[1].x * p.x + M[1].y * p.y + M[1].z * p.z + M[1].w * p.w, M[2].x * p.x + M[2].y * p.y + M[2].z * p.z + M[2].w * p.w, M[3].x * p.x + M[3].y * p.y + M[3].z * p.z + M[3].w * p.w); } inline DPoint3 project(const DMatrix4 & M, const DPoint & p) { DPoint4 q(M[0].x * p.x + M[0].y * p.y + M[0].w, M[1].x * p.x + M[1].y * p.y + M[1].w, M[2].x * p.x + M[2].y * p.y + M[2].w, M[3].x * p.x + M[3].y * p.y + M[3].w); const double w1 = 1./q.w; return DPoint3(q.x * w1, q.y * w1, q.z * w1); } inline DPoint3 project(const DMatrix4 & M, const DPoint3 & p) { DPoint4 q(M[0].x * p.x + M[0].y * p.y + M[0].z * p.z + M[0].w, M[1].x * p.x + M[1].y * p.y + M[1].z * p.z + M[1].w, M[2].x * p.x + M[2].y * p.y + M[2].z * p.z + M[2].w, M[3].x * p.x + M[3].y * p.y + M[3].z * p.z + M[3].w); const double w1 = 1./q.w; return DPoint3(q.x * w1, q.y * w1, q.z * w1); } inline DPoint3 project(const DMatrix4 & M, const DPoint4 & p) { DPoint4 q(M[0].x * p.x + M[0].y * p.y + M[0].z * p.z + M[0].w * p.w, M[1].x * p.x + M[1].y * p.y + M[1].z * p.z + M[1].w * p.w, M[2].x * p.x + M[2].y * p.y + M[2].z * p.z + M[2].w * p.w, M[3].x * p.x + M[3].y * p.y + M[3].z * p.z + M[3].w * p.w); const double w1 = 1./q.w; return DPoint3(q.x * w1, q.y * w1, q.z * w1); } inline DPoint3 project3(const DMatrix4 & M, const DPoint4 & p) { DPoint4 q(M[0].x * p.x + M[0].y * p.y + M[0].z * p.z + M[0].w, M[1].x * p.x + M[1].y * p.y + M[1].z * p.z + M[1].w, M[2].x * p.x + M[2].y * p.y + M[2].z * p.z + M[2].w, M[3].x * p.x + M[3].y * p.y + M[3].z * p.z + M[3].w); const double w1 = 1./q.w; return DPoint3(q.x * w1, q.y * w1, q.z * w1); } inline DPoint3 operator * (const DMatrix3 & M, const DPoint3 & p) { return multiply(M,p); } inline DPoint4 operator * (const DMatrix4 & M, const DPoint4 & p) { return multiply(M,p); } inline DPoint3 operator * (const DPoint3 & p, const DMatrix3 & M) { return multiply(M,p); } inline DPoint4 operator * (const DPoint4 & p, const DMatrix4 & M) { return multiply(M,p); } #if ENABLE_PROJECTIVE_SHORTCUT inline DPoint3 operator * (const DMatrix4 & M, const DPoint & p) { return multiply(M,p); } inline DPoint3 operator * (const DMatrix4 & M, const DPoint3 & p) { return multiply(M,p); } inline DPoint3 operator * (const DPoint & p, const DMatrix4 & M) { return multiply(M,p); } inline DPoint3 operator * (const DPoint3 & p, const DMatrix4 & M) { return multiply(M,p); } #else // !ENABLE_PROJECTIVE_SHORTCUT inline DPoint3 operator * (const DMatrix4 & M, const DPoint & p) { return project(M,p); } inline DPoint3 operator * (const DMatrix4 & M, const DPoint3 & p) { return project(M,p); } inline DPoint3 operator * (const DPoint & p, const DMatrix4 & M) { return project(M,p); } inline DPoint3 operator * (const DPoint3 & p, const DMatrix4 & M) { return project(M,p); } #endif // ENABLE_PROJECTIVE_SHORTCUT inline DPoint3 vectorTransform(const DMatrix4 & M, const DPoint3 & p) { return DPoint3(M[0].x * p.x + M[0].y * p.y + M[0].z * p.z, M[1].x * p.x + M[1].y * p.y + M[1].z * p.z, M[2].x * p.x + M[2].y * p.y + M[2].z * p.z); } inline DMatrix3 inferIsoTransform(const DPoint & a0, const DPoint & a1, const DPoint & b0, const DPoint & b1) { const DPoint p = a0 - b0, q = a1 - b1; const double det0 = 1. / -(p.x*p.x + p.y*p.y), deta = -(q.x*p.x + q.y*p.y), detb = p.x*q.y - q.x*p.y; DMatrix3 M; M[0].x = M[1].y = deta * det0; M[0].y = detb * det0; M[1].x = -M[0].y; const DPoint o = a1 - DPoint(M[0].x*a0.x + M[0].y*a0.y + M[0].z, M[1].x*a0.x + M[1].y*a0.y + M[1].z); //M*a0; M[0].z = o.x; M[1].z = o.y; return M; } //----------------------------------------------------------------------------- /// Infers a general 3x3 linear transform M by solving /// M*p1 == p1p /// M*p2 == p2p /// M*p3 == p3p /// could be substantially optimized by using efficient diagonalization techniques. DMatrix3 inferLinearTransform(const DPoint3 & p1, const DPoint3 & p1p, const DPoint3 & p2, const DPoint3 & p2p, const DPoint3 & p3, const DPoint3 & p3p); #ifdef _DEBUG void testInferLinearTransform(); #endif //----------------------------------------------------------------------------- /// If M is projectionMatrix * modelViewMatrix, this class is a machine to /// quickly convert between world coordinates from normalized device coordinates /// (NDC). It inverts the forward perspective transformation s=[x/w,y/w,z/w], /// [x,y,z,w] = M * pWorld. class PerspectiveTransform { double d0,dr,ds,dt, // denominator = d0 + dr*r + ds*s + dt*t x0,xr,xs,xt, // x numerator = w*(x0 + xr*r + xs*s + xt*t) with w==1 y0,yr,ys,yt, // y numerator = w*(y0 + yr*r + ys*s + yt*t) with w==1 z0,zr,zs,zt; // ditto, but z is over -denominator DMatrix4 M_; // keeps forward transform public: PerspectiveTransform() {} void calculate(const DMatrix4 & M); DPoint3 NDCtoWorld(const double & r, const double & s, const double & t) const; DPoint3 NDCtoWorld(const DPoint3 & p) const { return NDCtoWorld(p.x,p.y,p.z); } DPoint3 worldToNDC(const DPoint4 & p) const { DPoint4 q = M_ * p; double d = 1. / q.w; return DPoint3(q.x*d, q.y*d, q.z*d); } DPoint3 worldToNDC(const double & x, const double & y, const double & z) const { return worldToNDC(DPoint4(x,y,z,1.)); } DPoint3 worldToNDC(const DPoint3 & p) const { return worldToNDC(p.x, p.y, p.z); } }; /// testing #ifdef _DEBUG void testPerspectiveInverse(); #endif #endif // Matrix_h
[ [ [ 1, 604 ] ] ]
e5ec61ffd59467a9519cb0b9f591523ccf0486f9
9b658a6f52d8c1950e09422d62b86bd49a2b6e9a
/fireFoam/libs/regionModels/surfaceFilmModels/kinematicSingleLayer/kinematicSingleLayer.H
334bfa953aaec94655c3d63d8a3617bf43bc6ae7
[]
no_license
ku54713/firefoam-dev
f71ab485ceb2c2ba869bedcc0551e55732d84024
b4fee9a2819f2642166b0ffd0f583884cbf75f99
refs/heads/master
2021-01-15T23:40:34.535854
2011-07-05T17:43:05
2011-07-05T17:43:05
40,015,561
0
0
null
null
null
null
UTF-8
C++
false
false
16,567
h
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 2009-2010 OpenCFD Ltd. \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM 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. OpenFOAM 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 OpenFOAM; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Class Foam::kinematicSingleLayer Description Kinematic form of single-cell layer surface film model SourceFiles kinematicSingleLayer.C \*---------------------------------------------------------------------------*/ #ifndef kinematicSingleLayer_H #define kinematicSingleLayer_H #include "surfaceFilmModel.H" #include "fvMesh.H" #include "volFields.H" #include "surfaceFields.H" #include "fvMatrices.H" #include "injectionModelList.H" #define DEBUGT(x) std::cout << tab.c_str()<<"["<< __FILE__ << ":" << __LINE__ << "] "<< #x " = " << x << std::endl; #define TRACET(s) std::cout << tab.c_str()<<"["<< __FILE__ << ":" << __LINE__ << "] "<< #s << std::endl; s; #define DEBUG(x) std::cout << "["<< __FILE__ << ":" << __LINE__ << "] "<< #x " = " << x << std::endl; #define TRACE(s) std::cout << "["<< __FILE__ << ":" << __LINE__ << "] "<< #s << std::endl; s; #define INFO Info << tab.c_str() // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { namespace regionModels { namespace surfaceFilmModels { /*---------------------------------------------------------------------------*\ Class kinematicSingleLayer Declaration \*---------------------------------------------------------------------------*/ class kinematicSingleLayer : public surfaceFilmModel { private: // Private member functions //- Disallow default bitwise copy construct kinematicSingleLayer(const kinematicSingleLayer&); //- Disallow default bitwise assignment void operator=(const kinematicSingleLayer&); protected: // Protected data string tab; void tabAdd(); void tabSubtract(); // Solution parameters //- Momentum predictor Switch momentumPredictor_; //- Number of outer correctors label nOuterCorr_; //- Number of PISO-like correctors label nCorr_; //- Number of non-orthogonal correctors label nNonOrthCorr_; //- Cumulative continuity error scalar cumulativeContErr_; // Model parameters //- Skin frition coefficient for film/primary region interface scalar Cf_; // Thermo properties // Fields //- Density / [kg/m3] volScalarField rho_; //- Dynamic viscosity / [Pa.s] volScalarField mu_; //- Surface tension / [m/s2] volScalarField sigma_; // Fields //- Film thickness / [m] volScalarField delta_; //- Velocity - mean / [m/s] volVectorField U_; //- Velocity - surface / [m/s] volVectorField Us_; //- Velocity - wall / [m/s] volVectorField Uw_; //- Film thickness*density (helper field) / [kg/m2] volScalarField deltaRho_; //- Mass flux (includes film thickness) / [kg.m/s] surfaceScalarField phi_; // Transfer fields //- Film mass available for transfer to the primary region volScalarField primaryMassTrans_; //- Film mass available for transfer to cloud volScalarField cloudMassTrans_; //- Parcel diameters originating from film to cloud volScalarField cloudDiameterTrans_; // Source term fields // Film region - registered to the film region mesh // Note: need boundary value mapped from primary region, and then // pushed into the patch internal field //- Momementum / [kg/m/s2] volVectorField USp_; //- Pressure / [Pa] volScalarField pSp_; //- Mass / [kg/m2/s] volScalarField rhoSp_; //- Impingment Mass / [kg/m2/s] volScalarField massImp_; // Primary region - registered to the primary region mesh // Internal use only - not read-in //- Momementum / [kg/m/s2] volVectorField USpPrimary_; //- Pressure / [Pa] volScalarField pSpPrimary_; //- Mass / [kg/m2/s] volScalarField rhoSpPrimary_; // Fields mapped from primary region - registered to the film region // Note: need both boundary AND patch internal fields to be mapped //- Velocity / [m/s] volVectorField UPrimary_; //- Pressure / [Pa] volScalarField pPrimary_; //- Density / [kg/m3] volScalarField rhoPrimary_; //- Viscosity / [Pa.s] volScalarField muPrimary_; // Sub-models //- Available mass for transfer via sub-models scalarField availableMass_; //- Cloud injection injectionModelList injection_; // Checks //- Cumulative mass added via sources [kg] scalar addedMassTotal_; // Protected member functions //- Read control parameters from dictionary virtual bool read(); //- Correct the thermo fields virtual void correctThermoFields(); //- Reset source term fields virtual void resetPrimaryRegionSourceTerms(); //- Transfer thermo fields from the primary region to the film region virtual void transferPrimaryRegionThermoFields(); //- Transfer source fields from the primary region to the film region virtual void transferPrimaryRegionSourceFields(); // Explicit pressure source contribution virtual tmp<volScalarField> pu(); // Implicit pressure source coefficient virtual tmp<volScalarField> pp(); //- Update the film sub-models virtual void updateSubmodels(); //- Continuity check virtual void continuityCheck(); //- Update film surface velocities virtual void updateSurfaceVelocities(); //- Return the stress term for the momentum equation virtual tmp<fvVectorMatrix> tau(volVectorField& dU) const; //- Constrain a film region master/slave boundaries of a field to a // given value template<class Type> void constrainFilmField ( Type& field, const typename Type::cmptType& value ); // Equations //- Solve continuity equation virtual void solveContinuity(); //- Solve for film velocity virtual tmp<fvVectorMatrix> solveMomentum ( const volScalarField& pu, const volScalarField& pp ); //- Solve coupled velocity-thickness equations virtual void solveThickness ( const volScalarField& pu, const volScalarField& pp, const fvVectorMatrix& UEqn ); public: //- Runtime type information TypeName("kinematicSingleLayer"); // Constructors //- Construct from components kinematicSingleLayer ( const word& modelType, const fvMesh& mesh, const dimensionedVector& g, const bool readFields = true ); //- Destructor virtual ~kinematicSingleLayer(); // Member Functions // Solution parameters //- Courant number evaluation virtual scalar CourantNumber() const; //- Return the momentum predictor inline const Switch& momentumPredictor() const; //- Return the number of outer correctors inline label nOuterCorr() const; //- Return the number of PISO correctors inline label nCorr() const; //- Return the number of non-orthogonal correctors inline label nNonOrthCorr() const; // Model parameters //- Return the skin friction coefficient inline scalar Cf() const; // Thermo properties //- Return const access to the dynamic viscosity / [Pa.s] inline const volScalarField& mu() const; //- Return const access to the surface tension / [m/s2] inline const volScalarField& sigma() const; // Fields //- Return const access to the film thickness / [m] inline const volScalarField& delta() const; //- Return the film velocity [m/s] virtual const volVectorField& U() const; //- Return the film surface velocity [m/s] virtual const volVectorField& Us() const; //- Return the film wall velocity [m/s] virtual const volVectorField& Uw() const; //- Return the film flux [kg.m/s] virtual const surfaceScalarField& phi() const; //- Return the film density [kg/m3] virtual const volScalarField& rho() const; //- Return the film mean temperature [K] virtual const volScalarField& T() const; //- Return the film surface temperature [K] virtual const volScalarField& Ts() const; //- Return the film wall temperature [K] virtual const volScalarField& Tw() const; //- Return the wall heat flux virtual tmp<DimensionedField<scalar, volMesh> > qWall() const; //- Return the incident radiation //qrad virtual const volScalarField& qRad() const; virtual tmp<DimensionedField<scalar, volMesh> > qRad() const; //- Return the film specific heat capacity [J/kg/K] virtual const volScalarField& Cp() const; //- Return the film thermal conductivity [W/m/K] virtual const volScalarField& kappa() const; //- Return the film wettness (0=dry, 1=wet) virtual const volScalarField& omega() const; // Transfer fields - to the primary region //- Return mass transfer source - Eulerian phase only virtual tmp<volScalarField> primaryMassTrans() const; //- Return the film mass available for transfer to cloud virtual const volScalarField& cloudMassTrans() const; //- Return the parcel diameters originating from film to cloud virtual const volScalarField& cloudDiameterTrans() const; // External helper functions //- External hook to add sources to the film virtual void addSources ( const label patchI, // patchI on primary region const label faceI, // faceI of patchI const scalar massSource, // [kg] const vector& momentumSource, // [kg.m/s] (tangential momentum) const scalar pressureSource, // [kg.m/s] (normal momentum) const scalar energySource = 0 // [J] ); // Source fields (read/write access) // Primary region //- Momementum / [kg/m/s2] inline volVectorField& USpPrimary(); //- Pressure / [Pa] inline volScalarField& pSpPrimary(); //- Mass / [kg/m2/s] inline volScalarField& rhoSpPrimary(); // Film region //- Momentum / [kg/m/s2] inline volVectorField& USp(); //- Pressure / [Pa] inline volScalarField& pSp(); //- Mass / [kg/m2/s] inline volScalarField& rhoSp(); //- Momentum / [kg/m/s2] inline const volVectorField& USp() const; //- Pressure / [Pa] inline const volScalarField& pSp() const; //- Mass / [kg/m2/s] inline const volScalarField& rhoSp() const; // Fields mapped from primary region //- Velocity / [m/s] inline const volVectorField& UPrimary() const; //- Pressure / [Pa] inline const volScalarField& pPrimary() const; //- Density / [kg/m3] inline const volScalarField& rhoPrimary() const; //- Viscosity / [Pa.s] inline const volScalarField& muPrimary() const; // Sub-models //- Injection inline injectionModelList& injection(); // Helper functions //- Return the current film mass inline tmp<volScalarField> mass() const; //- Return the net film mass available over the next integration inline tmp<volScalarField> netMass() const; //- Return the gravity normal-to-patch component contribution inline tmp<volScalarField> gNorm() const; //- Return the gravity normal-to-patch component contribution // Clipped so that only non-zero if g & nHat_ < 0 inline tmp<volScalarField> gNormClipped() const; //- Return the gravity tangential component contributions inline tmp<volVectorField> gTan() const; // Evolution //- Pre-evolve film hook virtual void preEvolveRegion(); //- Evolve the film equations virtual void evolveRegion(); // Source fields // Mapped into primary region //- Return total mass source - Eulerian phase only virtual tmp<DimensionedField<scalar, volMesh> > Srho() const; //- Return mass source for specie i - Eulerian phase only virtual tmp<DimensionedField<scalar, volMesh> > Srho ( const label i ) const; //- Return enthalpy source - Eulerian phase only virtual tmp<DimensionedField<scalar, volMesh> > Sh() const; // I-O //- Provide some feedback virtual void info() const; void slottedCircle(); }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace surfaceFilmModels } // End namespace regionModels } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #ifdef NoRepository # include "kinematicSingleLayerTemplates.C" #endif // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #include "kinematicSingleLayerI.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
[ [ [ 1, 547 ] ] ]
d54830377988b1a9338540a0b6501b19c2a9bf03
a0155e192c9dc2029b231829e3db9ba90861f956
/MFAVA/MFAVA.cpp
ef065b18a78381fe7dff01faca6462e68d7ddd9e
[]
no_license
zeha/mailfilter
d2de4aaa79bed2073cec76c93768a42068cfab17
898dd4d4cba226edec566f4b15c6bb97e79f8001
refs/heads/master
2021-01-22T02:03:31.470739
2010-08-12T23:51:35
2010-08-12T23:51:35
81,022,257
0
0
null
null
null
null
UTF-8
C++
false
false
12,448
cpp
#include <screen.h> #include <stdio.h> #include <errno.h> #include <netware.h> #include <windows.h> #include <event.h> #include <library.h> #include <nks/netware.h> #include <ringx.h> #include <pthread.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include "MFAVA.h" // in reality, nothing from it ever gets used in MFAVA itself. #include "library.h" int gLibId = -1; void *gModuleHandle = (void *) NULL; scr_t gLibScreen = NULL; rtag_t gLibAllocRTag = NULL, gDownEventRTag = NULL, gDebugSetCmdRTag = NULL; event_handle_t gDownEventHandle = 0; int gDebugSetCmd = FALSE; settableparms_t gDebugSetCmdStruct; void *gRef_MFAVA_Init = (void *) NULL; void *gRef_MFAVA_DeInit = (void *) NULL; void *gRef_MFAVA_ScanFile = (void *) NULL; void *gRef_MFAVA_Status = (void *) NULL; MailFilter_AVA_Init_t MailFilter_AVA_Init_sym = NULL; MailFilter_AVA_DeInit_t MailFilter_AVA_DeInit_sym = NULL; MailFilter_AVA_ScanFile_t MailFilter_AVA_ScanFile_sym = NULL; MailFilter_AVA_Status_t MailFilter_AVA_Status_sym = NULL; static int sMarshallCodeHandle = 0; // ** // ** OS support stuff // ** int DownWarning ( void *printf, void *parm, void *userParm ) { #pragma unused(printf,parm,userParm) OutputToScreen(0, "MFAVA: Closing handles...\n"); eTrust7_DeInit(NULL); KillMe(gModuleHandle); return 0; } void *__my_AllocSleepOK ( size_t size, rtag_t rTag, int *slept) { void* p = NULL; for (int cnt = 0; cnt<20; cnt++) { p = AllocSleepOK(size,rTag,slept); if ((!p)&&(cnt==0)) printf("MFAVA: AllocSleepOK returned NULL memory.\n"); if (p) return p; } printf("MFAVA: Out of memory!\n"); return NULL; } void* __my_malloc(size_t length) { void* p = NULL; for (int cnt = 0; cnt<20; cnt++) { p = malloc(length); if ((!p)&&(cnt==0)) printf("MFAVA: malloc returned NULL memory.\n"); if (p) return p; } printf("MFAVA: out of memory.\n"); return NULL; } // ** // ** Library support stuff // ** appdata_t *GetOrSetAppData( void ) { rtag_t rtag; appdata_t *app = NULL; int rc; /* ** If the caller already has instance data, just return it. If not, then ** it's a new caller so allocate some, but attempt to do it on their tag. ** That failing, we'll use our own tag 'cause it will get cleaned up anyway ** when they (or we) unload. */ if ( (app = (appdata_t*)get_app_data(gLibId)) != NULL ) return app; if (!(rtag = getallocresourcetag())) rtag = gLibAllocRTag; if ( (app = (appdata_t*)__my_AllocSleepOK(sizeof(appdata_t), rtag, NULL)) != NULL ) { app->Debug = 0; app->eTrust_InitComplete = 0; app->eTrust_hInoScan = NULL; app->eTrust_hLibInoScan = NULL; app->eTrust_hLibLibWinC = NULL; } if ((rc = set_app_data(gLibId, app)) != ESUCCESS) { printf("MFAVA: error %d (%d) in set_app_data.\n",rc,errno); Free(app); return (appdata_t *) NULL; } return app; } int DisposeAppData(void *data_area) { appdata_t *app = (appdata_t*)data_area; if (app) { Free(app); } set_app_data(gLibId, NULL); return 0; } // ** // ** MFAVA exports. (exported under different names, though.) // ** static int MFAVA_Init(int iVirusScanner, int iDebug, MFAVA_HANDLE &hReturn) { appdata_t* app; int iError = ESUCCESS; if ((app = GetOrSetAppData()) == NULL) return ENOMEM; // set up handle hReturn = 0; app->Debug = iDebug; switch (iVirusScanner) { default: iError = ENOENT; break; case 1: iError = eTrust7_Init(hReturn); break; case 2: iError = Sophos_Init(hReturn); break; } return iError; } static int MFAVA_DeInit(MFAVA_HANDLE hAVA) { int iError = ESUCCESS; // call all _DeInit functions in a row... // eTrust 7.x iError = eTrust7_DeInit(hAVA); if (iError) goto FinishIt; iError = Sophos_DeInit(hAVA); if (iError) goto FinishIt; FinishIt: DisposeAppData(GetOrSetAppData()); return iError; } static int MFAVA_ScanFile(MFAVA_HANDLE hAVA, const char* szFileName, char* szVirusName, size_t iVirusNameLength, int &iVirusType) { int iError = ESUCCESS; switch ((long)hAVA) { default: iError = ENOENT; break; case ETRUST7_MAGIC: iError = eTrust7_ScanFile(hAVA,szFileName,szVirusName,iVirusNameLength,iVirusType); break; case SOPHOS_MAGIC: iError = Sophos_ScanFile(hAVA,szFileName,szVirusName,iVirusNameLength,iVirusType); break; } return iError; } static int MFAVA_Status(MFAVA_HANDLE hAVA, long whatToGet) { // pseudo for now. #pragma unused(hAVA,whatToGet) return ESUCCESS; } // ** // ** Marshalling interfaces // ** void StartOfMarshallingCode( void ) { } int M_MFAVA_Init(int iVirusScanner, int iDebug, MFAVA_HANDLE &hReturn) { if (MailFilter_AVA_Init_sym == NULL) return EINCONSIS; // RX_CHECK_BUFFER(hReturn, sizeof(void*)); // RxLockMemory(hReturn, sizeof(void*)); MFAVA_HANDLE _hReturn = hReturn; int rc; rc = MailFilter_AVA_Init_sym(iVirusScanner,iDebug,_hReturn); hReturn = _hReturn; return rc; } int M_MFAVA_DeInit(MFAVA_HANDLE hAVA) { if (MailFilter_AVA_DeInit_sym == NULL) return EINCONSIS; return MailFilter_AVA_DeInit_sym(hAVA); } int M_MFAVA_Status(MFAVA_HANDLE hAVA, long whatToGet) { if (MailFilter_AVA_Status_sym == NULL) return EINCONSIS; return MailFilter_AVA_Status_sym(hAVA, whatToGet); } int M_MFAVA_ScanFile(MFAVA_HANDLE hAVA, const char* szFileName, char* szVirusName, size_t iVirusNameLength, int &iVirusType) { pthread_t thread; size_t fileNameLen; int _iVirusType = iVirusType; size_t _iVirusNameLength = iVirusNameLength; int err; if (MailFilter_AVA_ScanFile_sym == NULL) return EINCONSIS; if (szFileName) { RX_CHECK_STRLEN(szFileName,fileNameLen); RxLockMemory((void*)szFileName,fileNameLen); } if (szVirusName) { RX_CHECK_STRLEN(szVirusName,iVirusNameLength); RxLockMemory((void*)szVirusName,iVirusNameLength); } thread = pthread_self(); /* if (err = RxRegisterThreadResource(thread, CleanUpFooStuff)) { if (szFileName) RxUnlockMemory((void*)szFileName,fileNameLen); if (szVirusName) RxUnlockMemory((void*)szVirusName,iVirusNameLength); return err; } */ err = MailFilter_AVA_ScanFile_sym(hAVA, szFileName, szVirusName, _iVirusNameLength, _iVirusType); if (szFileName) RxUnlockMemory((void*)szFileName,fileNameLen); if (szVirusName) RxUnlockMemory((void*)szVirusName,iVirusNameLength); iVirusType = _iVirusType; return err; } void EndOfMarshallingCode( void ) { } int RegisterMarshalledInterfaces() { RxIdentifyCode((void*)StartOfMarshallingCode, (void*)EndOfMarshallingCode, &sMarshallCodeHandle); if (RxRegisterSysCall((void*)M_MFAVA_Init, "MFAVA@MailFilter_AVA_Init", 3)) return EINVAL; if (RxRegisterSysCall((void*)M_MFAVA_DeInit, "MFAVA@MailFilter_AVA_DeInit", 1)) return EINVAL; if (RxRegisterSysCall((void*)M_MFAVA_ScanFile, "MFAVA@MailFilter_AVA_ScanFile", 5)) return EINVAL; if (RxRegisterSysCall((void*)M_MFAVA_Status, "MFAVA@MailFilter_AVA_Status", 2)) return EINVAL; return ESUCCESS; } int UnRegisterMarshalledInterfaces() { if (sMarshallCodeHandle) RxUnidentifyCode(sMarshallCodeHandle); RxUnregisterSysCall("MFAVA@MailFilter_AVA_Init"); RxUnregisterSysCall("MFAVA@MailFilter_AVA_DeInit"); RxUnregisterSysCall("MFAVA@MailFilter_AVA_ScanFile"); RxUnregisterSysCall("MFAVA@MailFilter_AVA_Status"); return ESUCCESS; } extern "C" { int __init_malloc(); int __deinit_malloc(); } // ** // ** Library Init // ** int DllMain // returns TRUE (things okay), FALSE (failure) ( void *hinstDLL, // equivalent to return from register_library() unsigned long fdwReason, // our attach/detach, etc. message void *lvpReserved // library per-VM data, place to put error... ) // ...return or NLM handle { int rc = 0; switch (fdwReason) { default: // bogus message: don't process it! return FALSE; case DLL_PROCESS_ATTACH : // (have per-NLM data) return TRUE; case DLL_PROCESS_DETACH : // (ibid) // appdata_t* app = GetOrSetAppData(); // DisposeAppData((void*)app); return TRUE; case DLL_THREAD_ATTACH : // (don't have per-thread data) case DLL_THREAD_DETACH : // (ibid) return TRUE; case DLL_ACTUAL_DLLMAIN : // (say that we're a library) return TRUE; case DLL_NLM_STARTUP: // this is our start-up initialization // DO THIS AS SOON AS POSSIBLE. __init_malloc(); // gLibId = (int) hinstDLL; gModuleHandle = lvpReserved; gLibScreen = getconsolehandle(); if (nlmisloadedprotected()) { SetAutoUnloadFlag(getnlmhandle()); // system("LOAD MFAVA.NLM"); delay(1000); return TRUE; } if (!(gDownEventRTag = AllocateResourceTag(gModuleHandle, "NetWare Shutdown Event Notification", EventSignature))) { OutputToScreen(0, "MFAVA: Could not register Shutdown Notification!\n\tTerminating!\n"); return FALSE; } gDownEventHandle = RegisterForEventNotification(gDownEventRTag, EVENT_PRE_DOWN_SERVER, EVENT_PRIORITY_APPLICATION, DownWarning, (Report_t) NULL, (void *) NULL); if (!(gLibAllocRTag = AllocateResourceTag(gModuleHandle, "LibC Interface Working Memory", AllocSignature))) { OutputToScreen(0, "MFAVA: Could not allocate resource tag!\n\tTerminating!\n"); return FALSE; } gDebugSetCmdRTag = AllocateResourceTag(getnlmhandle(), "MFAVA Debug", SettableParameterSignature); memset(&gDebugSetCmdStruct, 0, sizeof(gDebugSetCmdStruct)); gDebugSetCmdStruct.value = &gDebugSetCmd; gDebugSetCmdStruct.rTag = gDebugSetCmdRTag; gDebugSetCmdStruct.name = "MFAVA Debug"; gDebugSetCmdStruct.type = SP_TYPE_BOOLEAN; gDebugSetCmdStruct.flags = SP_HIDE; gDebugSetCmdStruct.category = SP_MISCELLANEOUS; gDebugSetCmdStruct.callback = NULL; gDebugSetCmdStruct.description = "Enable Debug Messages for MFAVA"; RegisterSettableParameter(&gDebugSetCmdStruct); register_destructor((int) hinstDLL, DisposeAppData); rc = nxExportInterfaceWrapped ( (void*)MFAVA_Init , 3, "MFAVA@MailFilter_AVA_Init", &gRef_MFAVA_Init ); rc = nxExportInterfaceWrapped ( (void*)MFAVA_DeInit , 1, "MFAVA@MailFilter_AVA_DeInit", &gRef_MFAVA_DeInit ); rc = nxExportInterfaceWrapped ( (void*)MFAVA_ScanFile , 5, "MFAVA@MailFilter_AVA_ScanFile", &gRef_MFAVA_ScanFile ); rc = nxExportInterfaceWrapped ( (void*)MFAVA_Status , 2, "MFAVA@MailFilter_AVA_Status", &gRef_MFAVA_Status ); MailFilter_AVA_Init_sym = (MailFilter_AVA_Init_t)ImportPublicObject(getnlmhandle(),"MFAVA@MailFilter_AVA_Init"); MailFilter_AVA_DeInit_sym = (MailFilter_AVA_DeInit_t)ImportPublicObject(getnlmhandle(),"MFAVA@MailFilter_AVA_DeInit"); MailFilter_AVA_ScanFile_sym = (MailFilter_AVA_ScanFile_t)ImportPublicObject(getnlmhandle(),"MFAVA@MailFilter_AVA_ScanFile"); MailFilter_AVA_Status_sym = (MailFilter_AVA_Status_t)ImportPublicObject(getnlmhandle(),"MFAVA@MailFilter_AVA_Status"); if (RegisterMarshalledInterfaces()) return FALSE; // pre-init all AV NLMs. eTrust7_PreInit(); // done. return TRUE; case DLL_NLM_SHUTDOWN: if (nlmisloadedprotected()) return TRUE; DeRegisterSettableParameter(&gDebugSetCmdStruct); UnRegisterEventNotification(gDownEventHandle); UnImportPublicObject(getnlmhandle(),"MFAVA@MailFilter_AVA_Init"); UnImportPublicObject(getnlmhandle(),"MFAVA@MailFilter_AVA_DeInit"); UnImportPublicObject(getnlmhandle(),"MFAVA@MailFilter_AVA_ScanFile"); UnImportPublicObject(getnlmhandle(),"MFAVA@MailFilter_AVA_Status"); if (gRef_MFAVA_Init) nxUnexportInterfaceWrapped ( gRef_MFAVA_Init ); if (gRef_MFAVA_DeInit) nxUnexportInterfaceWrapped ( gRef_MFAVA_DeInit ); if (gRef_MFAVA_ScanFile) nxUnexportInterfaceWrapped ( gRef_MFAVA_ScanFile ); if (gRef_MFAVA_Status) nxUnexportInterfaceWrapped ( gRef_MFAVA_Status ); UnRegisterMarshalledInterfaces(); __deinit_malloc(); return TRUE; } } // -eof-
[ [ [ 1, 493 ] ] ]
8a290437efc606cd8834eab31ad89d5e6afdc8f7
38926bfe477f933a307f51376dd3c356e7893ffc
/Source/GameDLL/Shark.cpp
4bf9bb56a4f86ebd814079fa4cbc85fe51f2df1d
[]
no_license
richmondx/dead6
b0e9dd94a0ebb297c0c6e9c4f24c6482ef4d5161
955f76f35d94ed5f991871407f3d3ad83f06a530
refs/heads/master
2021-12-05T14:32:01.782047
2008-01-01T13:13:39
2008-01-01T13:13:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
64,924
cpp
/************************************************************************* Crytek Source File. Copyright (C), Crytek Studios, 2001-2004. ------------------------------------------------------------------------- $Id$ $DateTime$ ------------------------------------------------------------------------- History: - Aug 2007: Created by Luciano Morpurgo *************************************************************************/ #include "StdAfx.h" #include "Game.h" #include "GameCVars.h" #include "Shark.h" #include "GameUtils.h" #include <IViewSystem.h> #include <IPhysics.h> #include <ICryAnimation.h> #include <ISerialize.h> #include <IRenderAuxGeom.h> #include <IEffectSystem.h> #include <ISound.h> #include "SharkMovementController.h" //Vec3 CShark::m_lastSpawnPoint; /** * Tries to initialize as much of SMovementRequestParams' data * as possible from a CMovementRequest instance. */ CShark::SMovementRequestParams::SMovementRequestParams(CMovementRequest& request) : aimLook (false), // NOTE Nov 9, 2006: <pvl> default values taken from SOBJECTSTATE constructor bodystate (0), fDesiredSpeed (1.0f), eActorTargetPhase (eATP_None), bExactPositioning (false) { aimLook = false; vMoveDir.zero(); vLookTargetPos.zero(); vAimTargetPos.zero(); vShootTargetPos.zero(); if (request.HasLookTarget()) { vLookTargetPos = request.GetLookTarget(); } if (request.HasAimTarget()) { vAimTargetPos = request.GetAimTarget(); aimLook = true; } if (request.HasFireTarget()) { vShootTargetPos = request.GetFireTarget(); } fDistanceToPathEnd = request.GetDistanceToPathEnd(); if (request.HasDesiredSpeed()) fDesiredSpeed = request.GetDesiredSpeed(); if (request.HasStance()) { switch (request.GetStance()) { case STANCE_CROUCH: bodystate = 1; break; case STANCE_PRONE: bodystate = 2; break; case STANCE_RELAXED: bodystate = 3; break; case STANCE_STEALTH: bodystate = 4; break; } } } //debug void DrawSharkCircle( const Vec3& center, float radius ) { Vec3 p0,p1,pos; pos = center; p0.x = pos.x + radius*sin(0.0f); p0.y = pos.y + radius*cos(0.0f); p0.z = pos.z; float step = 10.0f/180*gf_PI; ColorB col(0,255,0,128); for (float angle = step; angle < 360.0f/180*gf_PI+step; angle += step) { p1.x = pos.x + radius*sin(angle); p1.y = pos.y + radius*cos(angle); p1.z = pos.z; gEnv->pRenderer->GetIRenderAuxGeom()->DrawLine(p0,col,p1,col); p0 = p1; } } inline float CrossZ(const Vec3& a, const Vec3& b) { return a.x * b.y - a.y * b.x; } inline float GetFixNum(float a) { return _isnan(a) ? 0:a; } inline void FixVec(Vec3& v) { if(_isnan(v.x)||_isnan(v.y)||_isnan(v.z)) v.zero(); } bool GetCirclePassingBy(const Vec3& P, const Vec3& Q, const Vec3& Ptan, Vec3& center,float& radius) { // gets the 2D circle passing by two points P,Q and given tangent in P Vec3 PQcenter((P+Q)/2); Vec3 PQ(Q-P); float crossprod = CrossZ(Ptan, PQ); Vec3 axis; Vec3 PRadius; if(crossprod<0) { axis.y = -PQ.x; axis.x = PQ.y; axis.z = 0; PRadius.y = -Ptan.x; PRadius.x = Ptan.y; PRadius.z = 0; } else { axis.y = PQ.x; axis.x = -PQ.y; axis.z = 0; PRadius.y = Ptan.x; PRadius.x = -Ptan.y; PRadius.z = 0; } axis.NormalizeSafe(); PRadius.NormalizeSafe(); const float maxlength = 400; Vec3 PQAxisEnd = PQcenter + axis*maxlength; Lineseg PQAxis(PQcenter,PQAxisEnd ); Lineseg PRadiusSeg(P,P+PRadius*maxlength); float tPQ,tPrad; if(Intersect::Lineseg_Lineseg2D(PQAxis,PRadiusSeg,tPQ,tPrad)) { radius = tPrad * maxlength; center = P + PRadius * radius; return true; } return false; } //==================================================================== // IntersectSweptSphere // hitPos is optional - may be faster if 0 //==================================================================== /* bool IntersectSweptSphere(Vec3 *hitPos, float& hitDist, const Lineseg& lineseg, float radius,IPhysicalEntity** pSkipEnts=0, int nSkipEnts=0, int additionalFilter = 0) { IPhysicalWorld* pPhysics = gEnv->pPhysicalWorld; primitives::sphere spherePrim; spherePrim.center = lineseg.start; spherePrim.r = radius; Vec3 dir = lineseg.end - lineseg.start; geom_contact *pContact = 0; geom_contact **ppContact = hitPos ? &pContact : 0; int geomFlagsAll=0; int geomFlagsAny=rwi_stop_at_pierceable|(geom_colltype_player<<rwi_colltype_bit); float d = pPhysics->PrimitiveWorldIntersection(spherePrim.type, &spherePrim, dir, ent_static | ent_terrain | ent_ignore_noncolliding | additionalFilter, ppContact, geomFlagsAll, geomFlagsAny, 0,0,0, pSkipEnts, nSkipEnts); if (d > 0.0f) { hitDist = d; if (pContact && hitPos) *hitPos = pContact->pt; return true; } else { return false; } } */ // ------------------- CShark::CShark() : //m_pTrailAttachment(NULL), //m_trailSpeedScale(0.f), m_chosenEscapeDir(ZERO), m_escapeDir(ZERO) { ResetValues(); } void CShark::ResetValues() { m_stats = SSharkStats(); m_state = S_Sleeping; m_velocity = ZERO; m_lastCheckedPos = ZERO; m_turnSpeed = 0.0f; m_turnSpeedGoal = 0.0f; m_roll = 0.0f; m_weaponOffset = ZERO; m_remainingCirclingTime = -1; m_targetId = 0; m_moveTarget = ZERO; m_circleDisplacement = ZERO; m_lastPos.zero(); m_lastRot.zero(); m_curSpeed = 0; m_bCircularTrajectory = false; m_turnRadius = 0; m_turnAnimBlend = 0.5; m_bCircularTrajectory = false; m_circleRadius = 12;// dummy but reasonable value to avoid fp exceptions m_startPos.zero(); m_lastSpawnPoint.zero(); m_baseMtx.SetIdentity();// = Matrix33(GetEntity()->GetRotation()); m_modelQuat.SetIdentity();// = GetEntity()->GetRotation(); m_viewMtx.SetIdentity(); m_eyeMtx.SetIdentity(); m_charLocalMtx.SetIdentity(); m_angularVel = Ang3(0,0,0); m_AABBMaxZCache = 0; m_input.movementVector.zero(); //m_trailSpeedScale = 0; m_animationSpeedAttack = m_animationSpeed = 1; } CShark::~CShark() { ICharacterInstance *pCharacter = GetEntity()->GetCharacter(0); if(pCharacter) pCharacter->GetISkeletonPose()->SetPostProcessCallback0(0,0); } void CShark::BindInputs( IAnimationGraphState * pAGState ) { CActor::BindInputs(pAGState); if (pAGState) { m_inputSpeed = pAGState->GetInputId("Speed"); m_idSignalInput = pAGState->GetInputId("Signal"); } } void CShark::ProcessEvent(SEntityEvent& event) { if (event.event == ENTITY_EVENT_HIDE || event.event == ENTITY_EVENT_UNHIDE) { CreateScriptEvent("hide", event.event == ENTITY_EVENT_HIDE ? 1 : 0); } else if (event.event == ENTITY_EVENT_XFORM) { int flags = event.nParam[0]; if (flags & ENTITY_XFORM_ROT && !(flags & (ENTITY_XFORM_USER|ENTITY_XFORM_PHYSICS_STEP))) { m_baseMtx = m_viewMtx = m_eyeMtx = Matrix33(GetEntity()->GetRotation()); } } else if (event.event == ENTITY_EVENT_PREPHYSICSUPDATE) { PrePhysicsUpdate(); } CActor::ProcessEvent(event); } bool CShark::Init( IGameObject * pGameObject ) { if (!CActor::Init(pGameObject)) return false; Revive(); return true; } void CShark::PostPhysicalize() { CActor::PostPhysicalize(); ICharacterInstance *pCharacter = GetEntity()->GetCharacter(0); if (!pCharacter) return; pCharacter->EnableStartAnimation(true); IPhysicalEntity *pPhysEnt = pCharacter?pCharacter->GetISkeletonPose()->GetCharacterPhysics(-1):NULL; if (pPhysEnt) { pe_params_pos pp; pp.iSimClass = 2; pPhysEnt->SetParams(&pp); pe_simulation_params ps; ps.mass = 0; pPhysEnt->SetParams(&ps); } //set a default offset for the character, so in the editor the bbox is correct m_charLocalMtx.SetIdentity(); m_charLocalMtx.SetTranslation(GetStanceInfo(STANCE_STAND)->modelOffset); GetAnimatedCharacter()->SetExtraAnimationOffset(m_charLocalMtx); } void CShark::UpdateAnimGraph( IAnimationGraphState * pState ) { CActor::UpdateAnimGraph(pState); if (pState) { pState->SetInput(m_inputSpeed, m_stats.speed); } } void CShark::PrePhysicsUpdate() { IEntity* pEnt = GetEntity(); if (pEnt->IsHidden()) return; float frameTime = gEnv->pTimer->GetFrameTime(); if (!m_stats.isRagDoll && GetHealth()>0) { UpdateStats(frameTime); if (m_pMovementController) { SActorFrameMovementParams params; m_pMovementController->Update(frameTime, params); } assert(m_moveRequest.rotation.IsValid()); assert(m_moveRequest.velocity.IsValid()); //rotation processing if (m_linkStats.CanRotate()) ProcessRotation(frameTime); assert(m_moveRequest.rotation.IsValid()); assert(m_moveRequest.velocity.IsValid()); //movement processing if (m_linkStats.CanMove()) { ProcessMovement(frameTime); assert(m_moveRequest.rotation.IsValid()); assert(m_moveRequest.velocity.IsValid()); //send the movement request to the animated character if (m_pAnimatedCharacter) { // synthesize a prediction m_moveRequest.prediction.nStates = 1; m_moveRequest.prediction.states[0].deltatime = 0.0f; m_moveRequest.prediction.states[0].velocity = m_moveRequest.velocity; m_moveRequest.prediction.states[0].position = pEnt->GetWorldPos(); m_moveRequest.prediction.states[0].orientation = pEnt->GetWorldRotation(); //m_moveRequest.prediction.states[0].rotation.SetIdentity(); assert(m_moveRequest.rotation.IsValid()); assert(m_moveRequest.velocity.IsValid()); m_pAnimatedCharacter->AddMovement(m_moveRequest); } } } } void CShark::Update(SEntityUpdateContext& ctx, int updateSlot) { float frameTime = ctx.fFrameTime; if(frameTime == 0.f) frameTime = 0.01f; if(m_targetId) { IEntity* pTarget = gEnv->pEntitySystem->GetEntity(m_targetId); if(pTarget) UpdateStatus(frameTime,pTarget); } IEntity* pEnt = GetEntity(); if (pEnt->IsHidden()) return; FUNCTION_PROFILER(GetISystem(), PROFILE_GAME); CActor::Update(ctx,updateSlot); if (!m_stats.isRagDoll && GetHealth()>0) { //animation processing ProcessAnimation(pEnt->GetCharacter(0),frameTime); //reset the input for the next frame if (IsClient()) m_input.ResetDeltas(); if (gEnv->bClient) { /* float dist2 = (gEnv->pRenderer->GetCamera().GetPosition() - GetEntity()->GetWorldPos()).GetLengthSquared(); if (m_pTrailAttachment) { CEffectAttachment* pEffectAttachment = (CEffectAttachment*)m_pTrailAttachment->GetIAttachmentObject(); if (pEffectAttachment) { float goalspeed = max(0.f, m_stats.speed - m_params.trailEffectMinSpeed); Interpolate(m_trailSpeedScale, goalspeed, 3.f, frameTime); SpawnParams sp; if (m_params.trailEffectMaxSpeedSize != 0.f) sp.fSizeScale = min(1.f, max(0.01f, m_trailSpeedScale/m_params.trailEffectMaxSpeedSize)); if (m_params.trailEffectMaxSpeedCount != 0.f) sp.fCountScale = min(1.f, m_trailSpeedScale / m_params.trailEffectMaxSpeedCount); pEffectAttachment->SetSpawnParams(sp); } } if (m_pTurnSound && m_params.turnSoundMaxVel != 0.f && m_params.turnSoundBoneId != -1 && !m_pTurnSound->IsPlaying() && dist2<sqr(60.f)) { if (IPhysicalEntity *pPhysics = GetEntity()->GetPhysics()) { pe_status_dynamics dyn; dyn.partid = m_params.turnSoundBoneId; if (pPhysics->GetStatus(&dyn) && dyn.v.len2() > sqr(0.01f) && dyn.w.len2() > sqr(0.5f*m_params.turnSoundMaxVel)) { float speedRel = min(1.f, dyn.w.len()/m_params.turnSoundMaxVel); IEntitySoundProxy* pSoundProxy = (IEntitySoundProxy*)GetEntity()->CreateProxy(ENTITY_PROXY_SOUND); pSoundProxy->PlaySound(m_pTurnSound); m_pTurnSound->SetParam("acceleration", speedRel); //CryLog("angSpeed %.2f (rel %.2f)", dyn.w.len(), speedRel); } } } */ } } /* //update the character offset Vec3 goal = (m_stats.isRagDoll?Vec3(0,0,0):GetStanceInfo(m_stance)->modelOffset); //if(!m_stats.isRagDoll) // goal += m_stats.dynModelOffset; Interpolate(m_modelOffset,goal,5.0f,frameTime); */ m_charLocalMtx.SetTranslation(ZERO); GetAnimatedCharacter()->SetExtraAnimationOffset(m_charLocalMtx); } void CShark::SetStartPos(const Vec3& targetPos) { Vec3 dir(targetPos - m_startPos); dir.z = 0; float dist = dir.GetLength2D(); if(dist>0) dir /= dist; else dir = Vec3Constants<float>::fVec3_OneY; Matrix34 tm(GetEntity()->GetWorldTM()); // keep max 30m distance if(dist > 70) m_startPos = targetPos - dir * 70; float maxLevel = gEnv->p3DEngine->GetOceanWaterLevel( m_startPos) - 2; if (m_startPos.z > maxLevel) m_startPos.z = maxLevel; tm.SetTranslation(m_startPos); Vec3 right = dir ^ Vec3Constants<float>::fVec3_OneZ; tm.SetColumn(1, dir); tm.SetColumn(0, right.normalize()); tm.SetColumn(2, Vec3Constants<float>::fVec3_OneZ); GetEntity()->SetWorldTM(tm); m_lastSpawnPoint = m_startPos; } float CShark::GetDistHeadTarget(const Vec3& targetPos, const Vec3& targetDirN,float& dotMouth) { ICharacterInstance* pCharacter; ISkeletonPose* pSkeletonPose; if((pCharacter = GetEntity()->GetCharacter(0)) && (pSkeletonPose= pCharacter->GetISkeletonPose())) { Vec3 headBonePos(ZERO); int16 jointid = pSkeletonPose->GetJointIDByName(m_params.headBoneName); int16 jointid1 = pSkeletonPose->GetJointIDByName(m_params.spineBoneName1); int16 jointid2 = pSkeletonPose->GetJointIDByName(m_params.spineBoneName2); if(jointid>=0 && jointid1>=0 && jointid2>=0) { // can't rely on bones orientation, simulate the head orientation by predicting // the imaginary "bone 0" position given the first 3 bones 1,2,3 const Matrix34& worldTM = GetEntity()->GetSlotWorldTM(0); QuatT jointQuat = pSkeletonPose->GetAbsJointByID(jointid); headBonePos = worldTM* jointQuat.t; QuatT jointQuat1 = pSkeletonPose->GetAbsJointByID(jointid1); Vec3 bonePos1(worldTM * jointQuat1.t); QuatT jointQuat2 = pSkeletonPose->GetAbsJointByID(jointid2); Vec3 bonePos2(worldTM * jointQuat2.t); Vec3 v0(headBonePos - bonePos1);//.GetNormalizedSafe()); Vec3 v1(bonePos1 - bonePos2);//.GetNormalizedSafe()); Vec3 boneDir = (v0+v0-v1 ).GetNormalizedSafe(); //gEnv->pRenderer->GetIRenderAuxGeom()->DrawLine(bonePos, ColorB(255,120,0,255), bonePos + boneDir*6, ColorB(255,120,0,255)); dotMouth = targetDirN.Dot(boneDir); return Distance::Point_Point(headBonePos,targetPos); } } return -1.f; } void CShark::UpdateStatus(float frameTime, const IEntity* pTarget) { const int numCircleSteps = 12; Vec3 targetPos(pTarget->GetWorldPos()); bool bTargetOnVehicle = false; IActor * pTargetActor = gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor(pTarget->GetId()); if(pTargetActor) { // get the whole stuff and copy an entire structure just to get the eyeheight which can't be got alone SMovementState sMovementState; pTargetActor->GetMovementController()->GetMovementState(sMovementState); targetPos.z = sMovementState.eyePosition.z; // check if target is on a vehicle if(pTargetActor->GetLinkedVehicle()) bTargetOnVehicle = true; } Vec3 myPos(GetEntity()->GetWorldPos()); Vec3 myBodyDir(GetEntity()->GetRotation().GetColumn1()); //gEnv->pRenderer->GetIRenderAuxGeom()->DrawLine(myPos, ColorB(255,0,255,255), myPos+ myBodyDir*6, ColorB(255,0,255,255)); Vec3 targetDir(targetPos - myPos); float distTarget = targetDir.GetLength(); Vec3 targetDirN(distTarget>0 ? targetDir/distTarget : ZERO); float distHeadTarget = -1; Vec3 targetDir2DN(targetDirN.x,targetDirN.y,0); if(targetDir2DN.IsZero()) targetDir2DN = m_baseMtx.GetColumn1(); targetDir2DN.NormalizeSafe(); float dot = targetDirN.Dot(myBodyDir); float waterLevel = gEnv->p3DEngine->GetOceanWaterLevel( myPos); float maxHeight = waterLevel - 1; float dotMouth=-1; // get head orientation if (m_state != S_Spawning && !targetDirN.IsZero()) distHeadTarget = GetDistHeadTarget(targetPos,targetDirN, dotMouth); switch(m_state) { case S_Spawning: { // avoid teleport if shark is already active and close to the target if(distTarget < 110 && !GetEntity()->IsHidden() && m_params.bSpawned) { SetReaching(targetPos); break; } int escapePointSize = m_EscapePoints.size(); const int numTriesRadialDirections = 8; for(int i=0;i<2;i++) { if(m_tryCount >= numTriesRadialDirections + escapePointSize) { if(m_startPos.IsZero()) { // retry another cycle m_tryCount = 0; break; } SetStartPos(targetPos); SetReaching(targetPos); break; } Vec3 currentStartPos; if(m_tryCount < escapePointSize) { currentStartPos = m_EscapePoints[m_tryCount]; if(m_tryCount < escapePointSize -1 && currentStartPos.x==m_lastSpawnPoint.x && currentStartPos.y==m_lastSpawnPoint.y) { //low priority to last used spawn point - swap it with the last Vec3 swap(currentStartPos); currentStartPos = m_EscapePoints[escapePointSize -1 ]; m_EscapePoints[escapePointSize -1 ] = swap; } m_escapeDir = currentStartPos - targetPos; } else { if(m_tryCount == escapePointSize) m_escapeDir = Vec3(70,0,0); m_escapeDir = m_escapeDir.GetRotated(ZERO,Vec3Constants<float>::fVec3_OneZ,2 * gf_PI / float(numTriesRadialDirections)); currentStartPos = targetPos + m_escapeDir; } //find escape direction static const int objTypes = ent_terrain|ent_static|ent_sleeping_rigid; // |ent_rigid; static const unsigned int flags = rwi_stop_at_pierceable|rwi_colltype_any; ray_hit ray; Vec3 startPos(myPos+Vec3(0,0,1)); if (gEnv->pPhysicalWorld->RayWorldIntersection(targetPos, m_escapeDir, objTypes, flags, &ray, 1)) { Vec3 hitDir(ray.pt - targetPos); if(hitDir.GetLengthSquared() > m_chosenEscapeDir.GetLengthSquared()) { m_chosenEscapeDir = hitDir; m_startPos = targetPos + hitDir*(ray.dist - 4)/ray.dist; } } else { m_startPos = currentStartPos; SetStartPos(targetPos); SetReaching(targetPos); break; } m_tryCount++; } maxHeight = waterLevel - 1; } break; case S_Reaching: { maxHeight = waterLevel - 1; Vec3 moveTarget( targetPos); bool force = false; const int objTypes = ent_terrain|ent_static|ent_sleeping_rigid;//|ent_rigid; const unsigned int flags = rwi_stop_at_pierceable|rwi_colltype_any; ray_hit ray; if(distTarget > m_params.minDistanceCircle * 3) { // enough far, move directly towards target if (!gEnv->pPhysicalWorld->RayWorldIntersection(myPos, targetDir*(distTarget - 3)/distTarget, objTypes, flags, &ray, 1)) { // skip drivable boats in collision check // if(ray.pCollider) // { // IEntity* pColliderEntity = (IEntity*)ray.pCollider->GetForeignData(PHYS_FOREIGN_ID_ENTITY); // if(!pColliderEntity || !pColliderEntity->GetAI() || pColliderEntity->GetAI()->GetAIType()!=AIOBJECT_VEHICLE) // } SetMoveTarget(moveTarget, force, m_params.minDistForUpdatingMoveTarget); } // else keep previous moveTarget break; } else { // move aside of the target if(m_circleDisplacement.IsZero()) { m_circleRadius = m_params.minDistanceCircle; m_circleDisplacement = targetDir2DN * m_circleRadius; float a = m_circleDisplacement.x; m_circleDisplacement.x = m_circleDisplacement.y; m_circleDisplacement.y = -a; } moveTarget = targetPos + m_circleDisplacement; Vec3 moveTargetNeg(targetPos -m_circleDisplacement); Vec3 dir(m_circleDisplacement); if(Distance::Point_Point2DSq(myPos,moveTargetNeg) < Distance::Point_Point2DSq(myPos,moveTarget)) { moveTarget = moveTargetNeg; dir = -dir; } const float thr = 1.2f; if (gEnv->pPhysicalWorld->RayWorldIntersection(targetPos, dir* thr, objTypes, flags, &ray, 1)) { Vec3 diff(ray.pt - targetPos); float newRadius = ray.dist/thr - 2; if(m_circleRadius > newRadius) { m_circleRadius = newRadius; force = true; moveTarget = targetPos + diff*newRadius/ray.dist ; } } } SetMoveTarget(moveTarget, force, m_params.minDistForUpdatingMoveTarget); //gEnv->pRenderer->GetIRenderAuxGeom()->DrawLine(targetPos, ColorB(255,255,255,255), m_moveTarget, ColorB(255,255,255,255)); Vec3 moveTargetDir(m_moveTarget - myPos); float moveDistTarget = moveTargetDir.GetLength(); moveTargetDir.z = 0; myBodyDir.z = 0; if(moveDistTarget<2 || moveDistTarget <6.f && moveTargetDir.GetNormalizedSafe().Dot(m_stats.velocity.GetNormalizedSafe())<0.1f) { m_state = S_Circling; if(m_remainingCirclingTime==-1) m_remainingCirclingTime = m_params.circlingTime; m_numHalfCircles = m_params.numCircles * numCircleSteps+1; m_circleDisplacement = ZERO; m_bCircularTrajectory = false; } } break; case S_Circling: { if(distTarget >m_params.maxDistanceCircle) { m_state = S_Reaching; } else { if(distTarget < m_params.meleeDistance && !bTargetOnVehicle) { if(dotMouth > 0.9f) { //shark is aligned, attack Attack(true); break; } } m_remainingCirclingTime -= frameTime; Vec3 moveTargetDir(m_moveTarget - myPos); float moveDistTarget = moveTargetDir.GetLength(); bool force = false; //Vec3 pos(targetPos + m_circleDisplacement); if(!bTargetOnVehicle && m_remainingCirclingTime<=0 && targetDirN.Dot(pTarget->GetRotation().GetColumn1()) < -0.7f) { //shark is in front of target and he's circled around enough m_state = S_FinalAttackAlign; break; } if(moveDistTarget<2 || moveDistTarget <6.f && moveTargetDir.Dot(m_stats.velocity.GetNormalizedSafe())<0) { // m_numHalfCircles --; const float angle = DEG2RAD(360/float(numCircleSteps)) * sgn(CrossZ(myBodyDir, targetDir2DN)); Vec3 radius = - targetDir2DN * m_circleRadius; m_circleDisplacement = radius.GetRotated(ZERO,Vec3Constants<float>::fVec3_OneZ,angle); if(!bTargetOnVehicle) { static const int objTypes = ent_terrain|ent_static|ent_sleeping_rigid|ent_rigid; static const unsigned int flags = rwi_stop_at_pierceable|rwi_colltype_any; const float thr = 1.3f; ray_hit ray; // anticipate collision with current+next+next point Vec3 nextCircleDisplacement(m_circleDisplacement); for(int i=0; i<3; i++) { if(i>0) nextCircleDisplacement = nextCircleDisplacement.GetRotated(ZERO,Vec3Constants<float>::fVec3_OneZ,angle); if (gEnv->pPhysicalWorld->RayWorldIntersection(targetPos, nextCircleDisplacement* thr, objTypes, flags, &ray, 1)) { Vec3 dir(ray.pt - targetPos); float newRadius = ray.dist/thr - 2; if(m_circleRadius > newRadius) { m_circleRadius = newRadius; force = true; } } } m_circleDisplacement *= m_circleRadius/m_circleDisplacement.GetLength() ; } } SetMoveTarget(targetPos + m_circleDisplacement, force, m_params.minDistForUpdatingMoveTarget); Interpolate(m_circleRadius,m_params.minDistanceCircle * 1.1f,0.1f,frameTime); } } break; case S_FinalAttackAlign: { maxHeight = waterLevel; if(bTargetOnVehicle) { m_state = S_Circling; break; } SetMoveTarget(targetPos,true); if(dotMouth >0.8f) { if(distHeadTarget >= m_params.meleeDistance) { // IAnimationGraphState* pAGState = GetAnimationGraphState(); // if ( pAGState) // pAGState->SetInput( m_idSignalInput, "meleeSprint" ); m_state = S_FinalAttack; m_remainingAttackTime = 5.0f; } else if(distHeadTarget>=0) Attack(); } } break; case S_FinalAttack: { if(bTargetOnVehicle) { m_state = S_Circling; break; } SetMoveTarget(targetPos,true); m_remainingAttackTime -= frameTime; if(m_remainingAttackTime<=0) m_state = S_FinalAttackAlign; if(dotMouth >0.8f && distHeadTarget < m_params.meleeDistance) Attack(); maxHeight = waterLevel; } break; case S_PrepareEscape: { int escapePointSize = m_EscapePoints.size(); const int numTriesRadialDirections = 8; for(int i=0;i<2;i++) { if(m_tryCount >= numTriesRadialDirections + escapePointSize) { m_moveTarget = myPos + m_chosenEscapeDir; m_state = S_Escaping; break; } if(m_tryCount < escapePointSize) m_escapeDir = m_EscapePoints[m_tryCount] - myPos; else { if(m_tryCount == escapePointSize) m_escapeDir = Vec3(500,0,0); m_escapeDir = m_escapeDir.GetRotated(ZERO,Vec3Constants<float>::fVec3_OneZ,2 * gf_PI / float(numTriesRadialDirections)); } //find escape direction static const int objTypes = ent_terrain|ent_static|ent_sleeping_rigid|ent_rigid; static const unsigned int flags = rwi_stop_at_pierceable|rwi_colltype_any; ray_hit ray; Vec3 startPos(myPos+Vec3(0,0,1)); if (gEnv->pPhysicalWorld->RayWorldIntersection(startPos, m_escapeDir, objTypes, flags, &ray, 1)) { Vec3 hitDir(ray.pt - startPos); if(hitDir.GetLengthSquared() > m_chosenEscapeDir.GetLengthSquared()) m_chosenEscapeDir = hitDir; } else { m_chosenEscapeDir = m_escapeDir; m_moveTarget = myPos + m_chosenEscapeDir; m_state = S_Escaping; break; } m_tryCount++; } } break; case S_Attack: { if(bTargetOnVehicle) { m_state = S_Circling; break; } SetMoveTarget(targetPos,true); m_remainingAttackTime -= frameTime; if(m_remainingAttackTime<=0) { GoAway(); } maxHeight = waterLevel; } break; case S_Escaping: { if(distTarget <=2) { // deactivate, end of escape m_state = S_Sleeping; GetEntity()->Hide(true); } } break; default: break; } if(bTargetOnVehicle) maxHeight = waterLevel - 3; // keep safe level to avoid being hit by the vehicle AdjustMoveTarget(maxHeight,pTarget); } /* void CShark::UpdateSpawning() { if(distTarget < 110 && !GetEntity()->IsHidden() && m_params.bSpawned) { SetReaching(targetPos); break; } int escapePointSize = m_EscapePoints.size(); const int numTriesRadialDirections = 8; for(int i=0;i<2;i++) { if(m_tryCount >= numTriesRadialDirections + escapePointSize) { if(m_startPos.IsZero()) { // retry another cycle m_tryCount = 0; break; } SetStartPos(targetPos); SetReaching(targetPos); break; } Vec3 currentStartPos; if(m_tryCount < escapePointSize) { currentStartPos = m_EscapePoints[m_tryCount]; if(m_tryCount < escapePointSize -1 && currentStartPos.x==m_lastSpawnPoint.x && currentStartPos.y==m_lastSpawnPoint.y) { //low priority to last used spawn point - swap it with the last Vec3 swap(currentStartPos); currentStartPos = m_EscapePoints[escapePointSize -1 ]; m_EscapePoints[escapePointSize -1 ] = swap; } m_escapeDir = currentStartPos - targetPos; } else { if(m_tryCount == escapePointSize) m_escapeDir = Vec3(70,0,0); m_escapeDir = m_escapeDir.GetRotated(ZERO,Vec3Constants<float>::fVec3_OneZ,2 * gf_PI / float(numTriesRadialDirections)); currentStartPos = targetPos + m_escapeDir; } //find escape direction static const int objTypes = ent_terrain|ent_static|ent_sleeping_rigid; // |ent_rigid; static const unsigned int flags = rwi_stop_at_pierceable|rwi_colltype_any; ray_hit ray; Vec3 startPos(myPos+Vec3(0,0,1)); if (gEnv->pPhysicalWorld->RayWorldIntersection(targetPos, m_escapeDir, objTypes, flags, &ray, 1)) { Vec3 hitDir(ray.pt - targetPos); if(hitDir.GetLengthSquared() > m_chosenEscapeDir.GetLengthSquared()) { m_chosenEscapeDir = hitDir; m_startPos = targetPos + hitDir*(ray.dist - 4)/ray.dist; } } else { m_startPos = currentStartPos; SetStartPos(targetPos); SetReaching(targetPos); break; } m_tryCount++; } maxHeight = waterLevel - 1; } */ void CShark::SetReaching(const Vec3& targetPos) { SetMoveTarget(targetPos, true, m_params.minDistForUpdatingMoveTarget); m_state = S_Reaching; GetEntity()->Hide(false); } void CShark::AdjustMoveTarget(float maxHeight, const IEntity* pTargetEntity) { if(m_moveTarget.z > maxHeight) m_moveTarget.z = maxHeight; Vec3 myPos(GetEntity()->GetWorldPos()); // check for possible collisions with floating entities if(Distance::Point_Point2DSq(myPos, m_lastCheckedPos) > 4*4) { SEntityProximityQuery query; //query.nEntityFlags = ENTITY_FLAG_HAS_AI; query.pEntityClass = NULL; float dimxy = 10; float dimz = 3; query.box = AABB(Vec3(myPos.x - dimxy, myPos.y - dimxy, myPos.z /*avoid checking entities below*/),\ Vec3(myPos.x + dimxy, myPos.y + dimxy, myPos.z+dimz)); gEnv->pEntitySystem->QueryProximity(query); float myz = myPos.z + m_AABBMaxZCache; for(int i=0; i<query.nCount; ++i) { IEntity* pEntity = query.pEntities[i]; if(pEntity != GetEntity() && pEntity != pTargetEntity) { AABB targetBounds; Vec3 pos(pEntity->GetWorldPos()); pEntity->GetLocalBounds(targetBounds); // preliminary check for the height float targetZ = targetBounds.min.z + pos.z; if(myz >= targetZ) { // check actual collision targetBounds.SetTransformedAABB( pEntity->GetWorldTM(),targetBounds ); Vec3 collidingDir(m_moveTarget - myPos); collidingDir += collidingDir.GetNormalizedSafe()*4.f; Lineseg segDir(myPos,myPos+collidingDir); Vec3 intersection; if(Intersect::Lineseg_AABB(segDir, targetBounds,intersection)) { m_moveTarget.z = min(targetZ - 0.5f - myz,m_moveTarget.z); } } } } m_lastCheckedPos = myPos; } } void CShark::GoAway() { m_state = S_PrepareEscape; //m_escapeDir = Vec3(500,0,0); m_tryCount =0; m_chosenEscapeDir.zero(); } void CShark::Attack(bool fast) { // IAnimationGraphState* pAGState = GetAnimationGraphState(); //if ( pAGState) //pAGState->SetInput( m_idSignalInput, "melee" ); m_state = S_Attack; m_remainingAttackTime = 3.0f; MeleeAnimation(); m_animationSpeedAttack = fast ? 1.5f : 1.0; } //FIXME:at some point, unify this with CPlayer via CActor void CShark::UpdateStats(float frameTime) { IPhysicalEntity *pPhysEnt = GetEntity()->GetPhysics(); if (!pPhysEnt) return; pe_player_dynamics simPar; if (pPhysEnt->GetParams(&simPar)==0 || !simPar.bActive) { m_stats.velocity = m_stats.velocityUnconstrained.zero(); m_stats.speed = m_stats.speedFlat = 0.0f; m_stats.inFiring = 0; /*pe_player_dynamics simParSet; simParSet.bSwimming = true; pPhysEnt->SetParams(&simParSet);*/ return; } //retrieve some information about the status of the player pe_status_dynamics dynStat; pe_status_living livStat; if( !pPhysEnt->GetStatus(&dynStat) || !pPhysEnt->GetStatus(&livStat) || !pPhysEnt->GetParams(&simPar) ) return; //update status table m_stats.inWaterTimer += frameTime; m_stats.inAir = 0.0f; m_stats.gravity = simPar.gravity; m_stats.velocity = m_stats.velocityUnconstrained = dynStat.v; m_stats.angVelocity = dynStat.w; FixVec(m_stats.angVelocity); m_stats.speed = m_stats.speedFlat = GetFixNum(m_stats.velocity.GetLength()); m_stats.turnRadius = m_stats.angVelocity.z !=0 ? m_stats.speed / fabs(m_stats.angVelocity.z) : m_params.minTurnRadius * 3; if(m_stats.turnRadius< m_params.minTurnRadius) m_stats.turnRadius = m_params.minTurnRadius; // [Mikko] The velocity from the physics in some weird cases have been #INF because of the player // Zero-G movement calculations. If this asserts triggers, the alien might have just collided with // a play that is stuck in the geometry. assert(NumberValid(m_stats.speed)); m_stats.mass = dynStat.mass; } void CShark::ProcessRotation(float frameTime) { IPhysicalEntity *pPhysEnt = GetEntity()->GetPhysics(); if (!pPhysEnt) return; if (frameTime > 0.1f) frameTime = 0.1f; //rotation //6 degree of freedom //FIXME:put mouse sensitivity here! //TODO:use radians float rotSpeed(0.5f); // Mikko: Separated the look and movement directions. This is a HACK! The reason is below (moved from the SetActorMovement): // >> Danny - old code had desired direction using vLookDir but this caused spinning behaviour // >> when it was significantly different to vMoveDir /*if (m_input.viewVector.len2()>0.0f) { // m_eyeMtx.SetRotationVDir(m_input.viewVector.GetNormalizedSafe()); Matrix33 eyeTarget; eyeTarget.SetRotationVDir(m_input.viewVector.GetNormalizedSafe()); Quat eyeTargetQuat(eyeTarget); Quat currQuat(m_eyeMtx); m_eyeMtx = Matrix33(Quat::CreateSlerp( currQuat.GetNormalized(), eyeTargetQuat, min(frameTime * 12.0f, 1.0f))); } // if (m_input.viewVector.len2()>0.0f) { Vec3 lookat = m_eyeMtx.GetColumn(1); Vec3 orient = m_viewMtx.GetColumn(1); m_viewMtx.SetRotationVDir(m_input.viewVector.GetNormalizedSafe()); } */ m_eyeMtx =m_baseMtx ; m_viewMtx = m_baseMtx ; // rolling when attacking if(m_rollTime >0) { m_rollTime-=frameTime; if(m_rollTime<0) m_rollTime = 0; m_roll = (1 - cos((m_params.attackRollTime - m_rollTime)/m_params.attackRollTime * 2*gf_PI ) )/2 * m_rollMaxAngle; float straightFactor = fabs(m_turnAnimBlend - 0.5); static const float lthr = 0.2f, hthr = 0.3f; if(straightFactor< lthr) straightFactor =1; else if (straightFactor> hthr) straightFactor = 0; else straightFactor = (hthr - straightFactor)/(hthr - lthr); m_roll *= straightFactor ; // don't roll too much if turning } } void CShark::GetMovementVector(Vec3& move, float& speed, float& maxSpeed) { maxSpeed = GetStanceInfo(m_stance)->maxSpeed; // AI Movement move = m_input.movementVector; // Player movement /* // For controlling an alien as if it was a player (dbg stuff) move += m_viewMtx.GetColumn(0) * m_input.deltaMovement.x * maxSpeed; move += m_viewMtx.GetColumn(1) * m_input.deltaMovement.y * maxSpeed; move += m_viewMtx.GetColumn(2) * m_input.deltaMovement.z * maxSpeed; */ // Cap the speed to stance max stance speed. speed = move.len(); if(speed > maxSpeed) { move *= maxSpeed / speed; speed = maxSpeed; } } void CShark::ProcessMovement(float frameTime) { IPhysicalEntity *pPhysEnt = GetEntity()->GetPhysics(); if (!pPhysEnt) return; if (frameTime > 0.05f) frameTime = 0.05f; //movement Vec3 move; float speed,maxSpeed; GetMovementVector(move, speed, maxSpeed); Vec3 myPos(GetEntity()->GetWorldPos()); Vec3 forward; if( !m_moveTarget.IsZero() ) forward = (m_moveTarget - myPos).GetNormalizedSafe(); else forward = m_baseMtx.GetColumn(1); /* const SStanceInfo* pStanceInfo = GetStanceInfo(m_stance); float rotScale = 1.0f; if (pStanceInfo) { const float speedRange = max(1.0f, pStanceInfo->normalSpeed - m_params.speed_min); rotScale = (m_stats.speed - m_params.speed_min) / speedRange; } float rotSpeed = m_params.rotSpeed_min + (1.0f - rotScale) * (m_params.rotSpeed_max - m_params.rotSpeed_min); */ float desiredTurnRadius; float desiredSpeed; float rotSpeed; Vec3 center; ColorB debugColor(0, 0, 255, 48); if(m_moveTarget.IsZero()) { desiredSpeed =0; rotSpeed = 0; } else { // Slow down if the desired direction differs from the current direction. Vec3 desiredDir(m_moveTarget - GetEntity()->GetWorldPos()) ; Vec3 bodyDir(GetEntity()->GetWorldTM().TransformVector(Vec3Constants<float>::fVec3_OneY)); float dot = bodyDir.Dot(desiredDir.GetNormalizedSafe()); float distMoveTarget = desiredDir.GetLength(); /* float velScale = (dot< 0.7f ? 0 : (dot-0.7f)/0.3f) ; // Slow down if too fast compared to slower target, and not aligned to it if(m_state == S_FinalAttack || m_state == S_Attack || m_state == S_FinalAttackAlign) { IEntity* pTarget = gEnv->pEntitySystem->GetEntity(m_targetId); if(pTarget) { float distHead = m_headOffset*2.5f; //Vec3 dir( pTarget->GetWorldPos() - GetEntity()->GetWorldPos()); if(distMoveTarget < distHead) { IPhysicalEntity *phys = pTarget->GetPhysics(); pe_status_dynamics targetdyn; if( phys && phys->GetStatus(&targetdyn)) { Vec3 relVelocity(m_stats.velocity - targetdyn.v); float relSpeed = relVelocity.GetLength(); static const float speedThr = 1.f; //float dot = bodyDir.Dot(dir.GetNormalizedSafe()); if(dot<0.7f && relSpeed > speedThr) { if(dot<0) dot=0; float maxRelSpeed = speedThr*2; if(relSpeed > maxRelSpeed) relSpeed = maxRelSpeed; velScale *= dot/0.7f*(relSpeed - speedThr)/(maxRelSpeed - speedThr); } } } } } */ // get the turn radius to reach the move target Vec3 velNorm(m_stats.velocity.GetNormalizedSafe()); if(m_state == S_Escaping) { desiredSpeed = (maxSpeed + m_params.speed_min) / 2; m_bCircularTrajectory = false; rotSpeed = desiredSpeed/(m_params.minTurnRadius * 1.5f); rotSpeed = CLAMP(rotSpeed,0.7f,m_params.rotSpeed_max); } else if(m_state != S_Circling && dot<0.2 || dot<0.8 && ( m_state == S_FinalAttackAlign )) { // target behind or align before final attack, do a slow narrow turn // m_bCircularTrajectory = true; desiredSpeed = m_params.speed_min;// + (maxSpeed - m_params.speed_min)/3; rotSpeed = desiredSpeed/m_params.minTurnRadius; rotSpeed = CLAMP(rotSpeed,0,m_params.rotSpeed_max); // debug m_debugradius = desiredSpeed/rotSpeed; Vec3 disp(bodyDir.y,-bodyDir.x,bodyDir.z); if(CrossZ(bodyDir, desiredDir) >0) disp = -disp; m_debugcenter = myPos+disp*m_debugradius; debugColor.Set(12,255,12,48); m_bCircularTrajectory = false; } else if(m_state != S_Circling && dot>0.7f || ( m_state == S_FinalAttackAlign || m_state == S_FinalAttack)) { // almost aligned, try to go straight //m_bCircularTrajectory = true; desiredSpeed = max(dot*dot,0.3f)*maxSpeed; float eta = distMoveTarget/desiredSpeed; //rotSpeed = 2*cry_acosf(dot)/eta; //if(rotSpeed > m_params.rotSpeed_max) rotSpeed = m_params.rotSpeed_max; //debug m_debugradius = 0;//rotSpeed>0? desiredSpeed/rotSpeed : 0; m_debugcenter = m_moveTarget; m_bCircularTrajectory = false; } else if(!m_bCircularTrajectory)// && !velNorm.IsZero() && !m_moveTarget.IsZero()) { //float reqTurnRadius = m_params.rotSpeed_max > 0 ? maxSpeed * m_params.rotSpeed_max : m_params.minTurnRadius; //if(reqTurnRadius < m_params.minTurnRadius) m_bCircularTrajectory = GetCirclePassingBy(myPos,m_moveTarget,velNorm,center,desiredTurnRadius); if(m_bCircularTrajectory) { m_debugcenter = center; m_turnRadius = desiredTurnRadius; m_debugradius = desiredTurnRadius; } else { rotSpeed = m_params.rotSpeed_max; desiredSpeed = maxSpeed; } } if(m_bCircularTrajectory) { desiredSpeed = maxSpeed; rotSpeed = desiredSpeed/m_turnRadius;// * 1.2f;// correction if(rotSpeed > m_params.rotSpeed_max) { rotSpeed = m_params.rotSpeed_max; desiredSpeed = rotSpeed * m_turnRadius; desiredSpeed = CLAMP(desiredSpeed, m_params.speed_min, maxSpeed); } } // adjust speed depending on target's speed and orientation IEntity* pTarget = gEnv->pEntitySystem->GetEntity(m_targetId); if(pTarget) { IPhysicalEntity *phys = pTarget->GetPhysics(); pe_status_dynamics targetdyn; if( phys && phys->GetStatus(&targetdyn) && m_stats.speed>0.5f && targetdyn.v.GetLengthSquared()>1) { Vec3 normVel(m_stats.velocity.GetNormalizedSafe()); float dotvel = targetdyn.v.GetNormalizedSafe().Dot(normVel );//1 = same velocity, -1=opposite Vec3 targetDir((GetEntity()->GetWorldPos() - pTarget->GetWorldPos()).GetNormalizedSafe()); float dotOrient = targetDir.Dot(pTarget->GetRotation().GetColumn1()); float dot = (dotvel + dotOrient)/2; float relspeed = (targetdyn.v - m_stats.velocity).GetLength(); desiredSpeed += dot * relspeed; desiredSpeed = CLAMP(desiredSpeed,m_params.speed_min, maxSpeed*1.3f); } } } // use maximum speed // rotSpeed = speed / turnRadius Interpolate(m_curSpeed,desiredSpeed,(m_curSpeed < desiredSpeed ? m_params.accel : m_params.decel),frameTime); Interpolate(m_turnSpeed,rotSpeed,5.0f,frameTime); /* if(m_bCircularTrajectory) { if(!m_debugcenter.IsZero()) { if(m_debugradius==0) gEnv->pRenderer->GetIRenderAuxGeom()->DrawLine(myPos, ColorB(0,0,255,255), m_moveTarget, ColorB(128,128,255,255)); else { IEntity* pTarget = gEnv->pEntitySystem->GetEntity(m_targetId); if(!(pTarget && strcmp(pTarget->GetClass()->GetName(),"Player")==0)) { gEnv->pRenderer->GetIRenderAuxGeom()->DrawSphere(m_debugcenter, 0.5f, ColorB(255, 255, 12, 60), true); gEnv->pRenderer->GetIRenderAuxGeom()->DrawCylinder(m_debugcenter, Vec3(0,0,1), m_debugradius,0.1f,debugColor, true); } } } } */ /*Quat currQuat(m_baseMtx); m_baseMtx = Matrix33(Quat::CreateSlerp( currQuat.GetNormalized(), m_desiredVeloctyQuat, min(frameTime * m_turnSpeed , 1.0f))); m_baseMtx.OrthonormalizeFast(); */ Vec3 right(forward.y, -forward.x, 0); if(right.IsZero()) right = m_baseMtx.GetColumn0(); else right.Normalize(); Vec3 up = (right % forward).GetNormalized(); Quat goalQuat(Matrix33::CreateFromVectors(right,forward,up)); goalQuat.Normalize(); Quat currRotation(GetEntity()->GetRotation()); currRotation.Normalize(); m_modelQuat = Quat::CreateSlerp(currRotation, goalQuat, min(1.0f,frameTime * m_turnSpeed) ); m_modelQuat.Normalize(); Quat currQuat(m_baseMtx); m_baseMtx = Matrix33(m_modelQuat);//Quat::CreateSlerp( currQuat.GetNormalized(), m_modelQuat, min(frameTime * m_turnSpeed , 2.0f))); m_baseMtx.OrthonormalizeFast(); // using a class member m_modelAddQuat probably deprecated (needed for Slerp/blending) m_modelAddQuat = Quat(Matrix33::CreateIdentity() * Matrix33::CreateRotationXYZ(Ang3(0,m_roll,0)));//goalQuat; m_charLocalMtx = Matrix34(m_modelAddQuat); m_charLocalMtx.OrthonormalizeFast(); m_velocity = move.GetNormalizedSafe()*m_curSpeed; assert(GetEntity()->GetRotation().IsValid()); assert(GetEntity()->GetRotation().GetInverted().IsValid()); m_moveRequest.rotation = currRotation.GetInverted() * m_modelQuat; m_moveRequest.rotation.Normalize(); assert(m_moveRequest.rotation.IsValid()); m_moveRequest.velocity = m_velocity; m_moveRequest.type = eCMT_Fly; m_lastPos = myPos; // debug draw /* Vec3 basepos = GetEntity()->GetWorldPos(); gEnv->pRenderer->GetIRenderAuxGeom()->DrawLine(basepos, ColorB(255,255,255,255), basepos+ goalQuat.GetColumn0() * 4.0f, ColorB(255,255,255,255)); gEnv->pRenderer->GetIRenderAuxGeom()->DrawLine(basepos, ColorB(0,0,255,255), basepos+ goalQuat.GetColumn1() * 4.0f, ColorB(255,255,255,255)); gEnv->pRenderer->GetIRenderAuxGeom()->DrawLine(basepos, ColorB(255,255,255,255),basepos+ goalQuat.GetColumn2() * 4.0f, ColorB(255,255,255,255)); gEnv->pRenderer->GetIRenderAuxGeom()->DrawLine(basepos, ColorB(0,255,255,255), basepos+ m_modelQuat.GetColumn0() * 7.0f, ColorB(0,255,255,255)); gEnv->pRenderer->GetIRenderAuxGeom()->DrawLine(basepos, ColorB(0,0,0,255), basepos+ m_modelQuat.GetColumn1() * 7.0f, ColorB(0,255,255,255)); gEnv->pRenderer->GetIRenderAuxGeom()->DrawLine(basepos, ColorB(0,255,255,255), basepos+ m_modelQuat.GetColumn2() * 7.0f, ColorB(0,255,255,255)); */ } void CShark::ProcessAnimation(ICharacterInstance *pCharacter,float frameTime) { float turnAnimBlend; // float angVel = m_stats.angVelocity.z; Vec3 curRot = GetEntity()->GetRotation().GetColumn1(); curRot.z = 0; curRot.NormalizeSafe(); float angVel = m_stats.angVelocity.z;//cry_acosf(curRot.Dot(m_lastRot))/frameTime; if(angVel==0) turnAnimBlend = 0.5; else { turnAnimBlend = 0.5f + sgn(CrossZ(curRot,m_lastRot))*0.5/(m_stats.turnRadius/m_params.minTurnRadius); } float angVel2 = cry_acosf(curRot.Dot(m_lastRot))/frameTime; Interpolate(m_turnAnimBlend,turnAnimBlend,2.f + fabs(angVel)*1.5f,frameTime); pCharacter->GetISkeletonAnim()->SetBlendSpaceOverride(eMotionParamID_TurnSpeed,m_turnAnimBlend,true); m_lastRot = curRot; // dynamic adjustment of animation playback speed float animSpeed; float maxSpeed = GetStanceInfo(m_stance)->maxSpeed; if(m_state == S_Attack) animSpeed = m_animationSpeedAttack; else { if(maxSpeed==0) animSpeed = 1; else animSpeed = CLAMP(m_stats.speed/maxSpeed,0.5,1.f)*1.2f; } Interpolate(m_animationSpeed, animSpeed, m_state==S_Attack ? 4.0f : 2.0f, frameTime); pCharacter->SetAnimationSpeed(m_animationSpeed); } void CShark::Draw(bool draw) { uint32 slotFlags = GetEntity()->GetSlotFlags(0); if (draw) slotFlags |= ENTITY_SLOT_RENDER; else slotFlags &= ~ENTITY_SLOT_RENDER; GetEntity()->SetSlotFlags(0,slotFlags); } void CShark::ResetAnimations() { ICharacterInstance *character = GetEntity()->GetCharacter(0); SmartScriptTable entityTable = GetEntity()->GetScriptTable(); //m_idleAnimationName = ""; if (m_pAnimatedCharacter) m_pAnimatedCharacter->ClearForcedStates(); ISkeletonAnim* pSkeleton; if(character && (pSkeleton=character->GetISkeletonAnim())) { pSkeleton->StopAnimationsAllLayers(); //if( entityTable.GetPtr() && entityTable->GetValue("idleAnimation",m_idleAnimationName)) { pSkeleton->SetBlendSpaceOverride(eMotionParamID_TurnSpeed,0.5f,true); } } m_animationSpeedAttack = m_animationSpeed = 1; } //------------------------------------------------------------------------ void CShark::Reset(bool toGame) { } void CShark::Kill() { CActor::Kill(); ResetAnimations(); /*if (m_pTrailAttachment) m_pTrailAttachment->ClearBinding(); */ } void CShark::Revive(bool fromInit) { CActor::Revive(fromInit); ResetValues(); m_lastPos = GetEntity()->GetWorldPos(); m_lastRot = GetEntity()->GetRotation().GetColumn1(); m_baseMtx = Matrix33(GetEntity()->GetRotation()); m_modelQuat = GetEntity()->GetRotation(); SetDesiredDirection(GetEntity()->GetRotation().GetColumn1()); m_charLocalMtx.SetIdentity(); AABB box; GetEntity()->GetLocalBounds(box); m_AABBMaxZCache = box.max.z; ResetAnimations(); //initialize the ground effect /* if (m_params.trailEffect[0] && gEnv->p3DEngine->FindParticleEffect(m_params.trailEffect)) { if (ICharacterInstance* pCharInstance = GetEntity()->GetCharacter(0)) { IAttachmentManager* pAttachmentManager = pCharInstance->GetIAttachmentManager(); if (IAttachment* pAttachment = pAttachmentManager->GetInterfaceByName("trail_attachment")) { pAttachment->ClearBinding(); CEffectAttachment* pEffectAttachment = new CEffectAttachment(m_params.trailEffect, Vec3(0,0,0), m_params.trailEffectDir.GetNormalized(), 1); pEffectAttachment->CreateEffect(); pAttachment->AddBinding(pEffectAttachment); m_pTrailAttachment = pAttachment; m_trailSpeedScale = 0.f; } else CryLog("[CShark::Revive] %s: 'trail_attachment' not found.", GetEntity()->GetName()); } } */ if (m_pAnimatedCharacter) { SAnimatedCharacterParams params = m_pAnimatedCharacter->GetParams(); params.flags |= eACF_ZCoordinateFromPhysics | eACF_NoTransRot2k | eACF_ImmediateStance | eACF_NoLMErrorCorrection; m_pAnimatedCharacter->SetParams(params); } GetEntity()->Hide(true); } void CShark::RagDollize( bool fallAndPlay ) { return; if(fallAndPlay) return; if (m_stats.isRagDoll) return; ResetAnimations(); // assert(!fallAndPlay && "Fall and play not supported for aliens yet"); ICharacterInstance *pCharacter = GetEntity()->GetCharacter(0); if (pCharacter) pCharacter->GetISkeletonPose()->SetRagdollDefaultPose(); //CActor::RagDollize( fallAndPlay ); CActor::RagDollize( false ); IPhysicalEntity *pPhysEnt = GetEntity()->GetPhysics(); if (pPhysEnt) { pe_params_flags flags; flags.flagsOR = pef_log_collisions; pPhysEnt->SetParams(&flags); pe_simulation_params sp; sp.damping = 1.0f; sp.dampingFreefall = 0.0f; sp.mass = m_stats.mass; pPhysEnt->SetParams(&sp); pe_params_articulated_body pa; pa.dampingLyingMode = 5.5f; //pa.scaleBounceResponse = 0.1f; pPhysEnt->SetParams(&pa); } pCharacter = GetEntity()->GetCharacter(0); if (pCharacter) { pCharacter->EnableStartAnimation(false); } } void CShark::MeleeAnimation() { /* CryCharAnimationParams aparams; aparams.m_nLayerID = 1; aparams.m_fPlaybackSpeed=1.f; aparams.m_nFlags=0; // character->EnableStartAnimation(true); ICharacterInstance *character = GetEntity()->GetCharacter(0); ISkeleton* pSkeleton; if(character && (pSkeleton=character->GetISkeleton())) pSkeleton->StartAnimation(m_params.meleeAnimation,0,0,0,aparams); */ IAnimationGraphState* pAGState = GetAnimationGraphState(); if ( pAGState) pAGState->SetInput( m_idSignalInput, "melee" ); m_rollTime = m_params.attackRollTime; m_rollMaxAngle = sgn(m_stats.angVelocity.z)*m_params.attackRollAngle; if(m_rollMaxAngle==0) m_rollMaxAngle = m_params.attackRollAngle; } void CShark::SetStance(EStance stance) { CActor::SetStance(stance); const SStanceInfo* pStanceInfo = GetStanceInfo(stance); } //this will convert the input into a structure the player will use to process movement & input void CShark::OnAction(const ActionId& actionId, int activationMode, float value) { GetGameObject()->ChangedNetworkState( eEA_GameServerStatic | eEA_GameServerDynamic | eEA_GameClientStatic | eEA_GameClientDynamic ); CActor::OnAction(actionId, activationMode, value); } void CShark::SetStats(SmartScriptTable &rTable) { CActor::SetStats(rTable); } //fill the status table for the scripts void CShark::UpdateScriptStats(SmartScriptTable &rTable) { CActor::UpdateScriptStats(rTable); } void CShark::SetParams(SmartScriptTable &rTable,bool resetFirst) { ScriptHandle hdl; if(rTable->GetValue("targetId",hdl)) { m_targetId = hdl.n; return; } if(rTable->GetValue("selectTarget",hdl)) { m_targetId = hdl.n; m_tryCount = 0; m_startPos.zero(); m_state = S_Spawning; m_chosenEscapeDir.zero(); FindEscapePoints(); rTable->GetValue("spawned",m_params.bSpawned); return; } int goAway; if(rTable->GetValue("goAway",goAway)) { GoAway(); return; } //not sure about this if (resetFirst) { m_params = SSharkParams(); } CActor::SetParams(rTable,resetFirst); rTable->GetValue("speedInertia",m_params.speedInertia); rTable->GetValue("sprintMultiplier",m_params.sprintMultiplier); rTable->GetValue("sprintDuration",m_params.sprintDuration); rTable->GetValue("rotSpeed_min",m_params.rotSpeed_min); rTable->GetValue("rotSpeed_max",m_params.rotSpeed_max); rTable->GetValue("minTurnRadius",m_params.minTurnRadius); rTable->GetValue("speed_min",m_params.speed_min); rTable->GetValue("accel",m_params.accel); rTable->GetValue("decel",m_params.decel); rTable->GetValue("minDistanceCircle",m_params.minDistanceCircle); rTable->GetValue("maxDistanceCircle",m_params.maxDistanceCircle); rTable->GetValue("circlingTime",m_params.circlingTime); rTable->GetValue("numCircles",m_params.numCircles); rTable->GetValue("minDistForUpdatingMoveTarget",m_params.minDistForUpdatingMoveTarget); const char *name; rTable->GetValue("headBone",name); m_params.headBoneName = name; rTable->GetValue("spineBone1",name); m_params.spineBoneName1 = name; rTable->GetValue("spineBone2",name); m_params.spineBoneName2 = name; SmartScriptTable meleeTable; if(rTable->GetValue("melee",meleeTable)) { meleeTable->GetValue("radius",m_params.meleeDistance); meleeTable->GetValue("animation",name); m_params.meleeAnimation = name; meleeTable->GetValue("rollTime",m_params.attackRollTime); meleeTable->GetValue("rollAngle",m_params.attackRollAngle); m_params.attackRollAngle = DEG2RAD(m_params.attackRollAngle); } rTable->GetValue("escapeAnchorType",m_params.escapeAnchorType); /*m_params.trailEffect = ""; const char *str; if (rTable->GetValue("trailEffect",str)) { m_params.trailEffect = str; rTable->GetValue("trailEffectMinSpeed",m_params.trailEffectMinSpeed); rTable->GetValue("trailEffectMaxSpeedSize",m_params.trailEffectMaxSpeedSize); rTable->GetValue("trailEffectMaxSpeedCount",m_params.trailEffectMaxSpeedCount); rTable->GetValue("trailEffectDir",m_params.trailEffectDir); } */ /* if (rTable->GetValue("turnSound",str) && gEnv->pSoundSystem) { m_pTurnSound = gEnv->pSoundSystem->CreateSound(str, FLAG_SOUND_DEFAULT_3D); if (m_pTurnSound) m_pTurnSound->SetSemantic(eSoundSemantic_Living_Entity); if (rTable->GetValue("turnSoundBone",str)) { if (ICharacterInstance *pCharacter = GetEntity()->GetCharacter(0)) m_params.turnSoundBoneId = pCharacter->GetISkeletonPose()->GetJointIDByName(str); } rTable->GetValue("turnSoundMaxVel", m_params.turnSoundMaxVel); } */ } void CShark::SetDesiredSpeed(const Vec3 &desiredSpeed) { m_input.movementVector = desiredSpeed; } void CShark::SetDesiredDirection(const Vec3 &desiredDir) { if (desiredDir.len2()>0.001f) { m_viewMtx.SetRotationVDir(desiredDir.GetNormalizedSafe()); m_eyeMtx = m_viewMtx; } //m_input.viewVector = desiredDir; } // common functionality can go in here and called from subclasses that override SetActorMovement void CShark::SetActorMovementCommon(SMovementRequestParams& control) { SMovementState state; GetMovementController()->GetMovementState(state); if(!control.vAimTargetPos.IsZero()) m_input.viewDir = (control.vAimTargetPos - state.weaponPosition).GetNormalizedSafe(); else if(!control.vLookTargetPos.IsZero()) m_input.viewDir = (control.vLookTargetPos - state.eyePosition).GetNormalizedSafe(); else m_input.viewDir = GetEntity()->GetWorldRotation() * FORWARD_DIRECTION; m_input.pathLength = control.fDistanceToPathEnd; // added bExactPos property for easier testing SmartScriptTable props; int bExactPos = 0; if(IScriptTable* pScriptTable = GetEntity()->GetScriptTable()) if(pScriptTable->GetValue("Properties",props)) props->GetValue("bExactPos", bExactPos); // m_input.posTarget.zero(); // m_input.dirTarget.zero(); } //--------------------------------- //AI Specific void CShark::SetActorMovement(SMovementRequestParams &control) { SMovementState state; GetMovementController()->GetMovementState(state); SetActorMovementCommon(control); Vec3 bodyDir(GetEntity()->GetWorldRotation() * FORWARD_DIRECTION); SetDesiredDirection(bodyDir); // overrides AI (which doesn't request movement // shark always moves SetDesiredSpeed(bodyDir*m_curSpeed);//(control.vMoveDir * control.fDesiredSpeed); // debug state and move target /* static char stateName[9][32] = {"S_Sleeping","S_Reaching","S_Circling","S_Attack","S_FinalAttackAlign","S_FinalAttack","S_PrepareEscape","S_Escaping","S_Spawning"}; if(!m_moveTarget.IsZero()) { gEnv->pRenderer->GetIRenderAuxGeom()->DrawSphere(m_moveTarget, 0.5f, ColorB(255, 0, 255, 255), true); gEnv->pRenderer->GetIRenderAuxGeom()->DrawLine(GetEntity()->GetWorldPos(), ColorB(0,255,0,100), m_moveTarget, ColorB(255,0,0,100)); gEnv->pRenderer->DrawLabel(GetEntity()->GetWorldPos()+Vec3(0,0,2), 1.4f, stateName[m_state]); IEntity* pTarget = gEnv->pEntitySystem->GetEntity(m_targetId); if(pTarget) DrawSharkCircle(pTarget->GetWorldPos(),m_circleRadius); } else gEnv->pRenderer->GetIRenderAuxGeom()->DrawSphere(GetEntity()->GetWorldPos()+Vec3(0,0,1), 0.5f, ColorB(255, 255, 255, 255), true); */ // m_input.actions = control.m_desiredActions; /* int actions; switch(control.bodystate) { case 1: actions = ACTION_CROUCH; break; case 2: actions = ACTION_PRONE; break; case 3: actions = ACTION_RELAXED; break; case 4: actions = ACTION_STEALTH; break; default: actions = 0; break; } m_input.actions = actions; */ } void CShark::GetActorInfo(SBodyInfo& bodyInfo) { bodyInfo.vEyePos = GetEntity()->GetWorldPos();//GetEntity()->GetSlotWorldTM(0) * m_eyeOffset; bodyInfo.vFirePos = GetEntity()->GetWorldPos();//GetEntity()->GetSlotWorldTM(0) * m_weaponOffset; bodyInfo.vEyeDir = m_viewMtx.GetColumn(1);//m_eyeMtx.GetColumn(1); int headBoneID = GetBoneID(BONE_HEAD); if (headBoneID>-1 && GetEntity()->GetCharacter(0)) { //Matrix33 HeadMat(GetEntity()->GetCharacter(0)->GetISkeleton()->GetAbsJMatrixByID(headBoneID)); Matrix33 HeadMat( Matrix33(GetEntity()->GetCharacter(0)->GetISkeletonPose()->GetAbsJointByID(headBoneID).q) ); bodyInfo.vEyeDirAnim = Matrix33(GetEntity()->GetSlotWorldTM(0) * HeadMat).GetColumn(1); } else { bodyInfo.vEyeDirAnim = bodyInfo.vEyeDir; } //gEnv->pRenderer->GetIRenderAuxGeom()->DrawLine(bodyInfo.vEyePos, ColorB(0,255,0,100), bodyInfo.vEyePos + bodyInfo.vEyeDir * 10.0f, ColorB(255,0,0,100)); bodyInfo.vFwdDir = GetEntity()->GetRotation().GetColumn1();//m_viewMtx.GetColumn(1); bodyInfo.vUpDir = m_viewMtx.GetColumn(2); bodyInfo.vFireDir = bodyInfo.vFwdDir; //gEnv->pRenderer->GetIRenderAuxGeom()->DrawLine(GetEntity()->GetWorldPos(), ColorB(0,255,0,100), GetEntity()->GetWorldPos() + bodyInfo.vFwdDir * 10, ColorB(255,0,0,100)); const SStanceInfo * pStanceInfo = GetStanceInfo(m_stance); bodyInfo.minSpeed = min(m_params.speed_min, pStanceInfo->maxSpeed*0.01f); bodyInfo.normalSpeed = pStanceInfo->normalSpeed; bodyInfo.maxSpeed = pStanceInfo->maxSpeed; // if you want to change the .eyeHeight for aliens to something different from 0 - talk to Kirill. It might cause problems in // CPuppet::AddToVisibleList when calculating time-out increase using target's eyeHeight. bodyInfo.stance = m_stance; bodyInfo.m_stanceSizeAABB = pStanceInfo->GetStanceBounds(); bodyInfo.m_colliderSizeAABB = pStanceInfo->GetColliderBounds(); } void CShark::SetAngles(const Ang3 &angles) { Matrix33 rot(Matrix33::CreateRotationXYZ(angles)); SetDesiredDirection(rot.GetColumn(1)); } Ang3 CShark::GetAngles() { Ang3 angles; angles.SetAnglesXYZ(m_viewMtx); return angles; } void CShark::SetMoveTarget(Vec3 moveTarget, bool bForced, float minDistForUpdate) { // minDistForUpdate: don't reposition the move target if it's close enough to the shark, // to avoid local sudden change directions if( bForced ||Distance::Point_PointSq(GetEntity()->GetWorldPos(),moveTarget)> minDistForUpdate * minDistForUpdate && Distance::Point_PointSq(m_moveTarget,moveTarget)>1) { m_moveTarget=moveTarget; } } void CShark::FindEscapePoints() { m_EscapePoints.clear(); if(m_params.escapeAnchorType && m_targetId) { IEntity* pTarget = gEnv->pEntitySystem->GetEntity(m_targetId); if(pTarget) { AutoAIObjectIter it(gEnv->pAISystem->GetFirstAIObjectInRange(IAISystem::OBJFILTER_TYPE, m_params.escapeAnchorType, pTarget->GetWorldPos(), 400, true)); for(; it->GetObject(); it->Next()) m_EscapePoints.push_back(it->GetObject()->GetPos()); } } } void CShark::FullSerialize( TSerialize ser ) { CActor::FullSerialize(ser); ser.BeginGroup("CShark"); ser.Value("modelQuat", m_modelQuat, 'ori1'); ser.Value("health", m_health); // skip matrices ser.Value("velocity", m_velocity); ser.Value("turnSpeed", m_turnSpeed); ser.Value("turnSpeedGoal", m_turnSpeedGoal); ser.Value("angularVel", m_angularVel); ser.EnumValue("stance", m_stance, STANCE_NULL, STANCE_LAST); ser.EnumValue("m_state",m_state,S_Reaching,S_Last); ser.Value("m_moveTarget",m_moveTarget); ser.Value("m_numHalfCircles",m_numHalfCircles); ser.Value("m_remainingCirclingTime",m_remainingCirclingTime); ser.Value("m_remainingAttackTime",m_remainingAttackTime); ser.Value("m_animationSpeed",m_animationSpeed); ser.Value("m_animationSpeedAttack",m_animationSpeedAttack); ser.Value("m_curSpeed",m_curSpeed); ser.Value("m_lastPos",m_lastPos); ser.Value("m_lastRot",m_lastRot); ser.Value("m_turnAnimBlend",m_turnAnimBlend); ser.Value("m_modelQuat",m_modelQuat); ser.Value("m_circleDisplacement",m_circleDisplacement); ser.Value("m_bCircularTrajectory",m_bCircularTrajectory); ser.Value("m_turnRadius",m_turnRadius); ser.Value("m_rollTime",m_rollTime); ser.Value("m_roll",m_roll); ser.Value("m_rollMaxAngle",m_rollMaxAngle); ser.Value("m_chosenEscapeDir",m_chosenEscapeDir); ser.Value("m_escapeDir",m_escapeDir); ser.Value("m_tryCount",m_tryCount); ser.Value("m_targetId",m_targetId); ser.Value("m_AABBMaxZCache",m_AABBMaxZCache); ser.Value("m_lastCheckedPos",m_lastCheckedPos); ser.Value("m_circleRadius",m_circleRadius); ser.Value("m_startPos",m_startPos); ser.BeginGroup("SharkEscapePoints"); { int size = m_EscapePoints.size(); ser.Value("Size",size); char name[32]; if(ser.IsReading()) m_EscapePoints.clear(); for(int i=0; i<size; i++) { Vec3 point; sprintf(name,"Point_%d",i); if(ser.IsWriting()) point = m_EscapePoints[i]; ser.Value(name,point); if(ser.IsReading()) m_EscapePoints.push_back(point); } ser.EndGroup(); } ser.EndGroup(); m_input.Serialize(ser); // m_stats.Serialize(ser); m_params.Serialize(ser); } void CShark::SerializeXML( XmlNodeRef& node, bool bLoading ) { } void CShark::SetAuthority( bool auth ) { } IActorMovementController * CShark::CreateMovementController() { return new CSharkMovementController(this); } void SSharkInput::Serialize( TSerialize ser ) { ser.BeginGroup("SSharkInput"); ser.Value("deltaMovement", deltaMovement); ser.Value("deltaRotation", deltaRotation); ser.Value("actions", actions); ser.Value("movementVector", movementVector); ser.Value("viewVector", viewVector); /* ser.Value("posTarget", posTarget); ser.Value("dirTarget", dirTarget); ser.Value("upTarget", upTarget); ser.Value("speedTarget", speedTarget);*/ ser.EndGroup(); } void SSharkParams::Serialize( TSerialize ser ) { ser.BeginGroup("SSharkParams"); ser.Value("speedInertia", speedInertia); ser.Value("rollAmount", rollAmount); ser.Value("sprintMultiplier", sprintMultiplier); ser.Value("sprintDuration", sprintDuration); ser.Value("rotSpeed_min", rotSpeed_min); ser.Value("rotSpeed_max", rotSpeed_max); ser.Value("speed_min", speed_min); ser.Value("accel",accel); ser.Value("decel",decel); ser.Value("minDistanceCircle",minDistanceCircle); ser.Value("maxDistanceCircle",maxDistanceCircle); ser.Value("numCircles",numCircles); ser.Value("minDistForUpdatingMoveTarget",minDistForUpdatingMoveTarget); ser.Value("meleeAnimation",meleeAnimation); ser.Value("meleeDistance",meleeDistance); ser.Value("circlingTime",circlingTime); ser.Value("attackRollTime",attackRollTime); ser.Value("attackRollAngle",attackRollAngle); ser.Value("headBoneName",headBoneName); ser.Value("spineBoneName1",spineBoneName1); ser.Value("spineBoneName2",spineBoneName2); ser.Value("escapeAnchorType",escapeAnchorType); ser.Value("bSpawned",bSpawned); ser.EndGroup(); } /* void SSharkStats::Serialize( TSerialize ser ) { ser.BeginGroup("SSharkStats"); ser.Value("inAir", inAir); ser.Value("onGround", onGround); ser.Value("speedModule", speed); ser.Value("mass", mass); ser.Value("bobCycle", bobCycle); ser.Value("isRagdoll", isRagDoll); ser.Value("velocity", velocity); // ser.Value("eyePos", eyePos); //ser.Value("eyeAngles", eyeAngles); //ser.Value("dynModelOffset",dynModelOffset); ser.EndGroup(); } */
[ "kkirst@c5e09591-5635-0410-80e3-0b71df3ecc31" ]
[ [ [ 1, 2197 ] ] ]
e67af163fc7cd9b9bdb57de921dcd17d0563c787
30e4267e1a7fe172118bf26252aa2eb92b97a460
/code/pkg_UnitTest/Modules/Public/BaseTest.h
88c393c6b4dfd87e2f7f7b5ac32abff47801f6a1
[ "Apache-2.0" ]
permissive
thinkhy/x3c_extension
f299103002715365160c274314f02171ca9d9d97
8a31deb466df5d487561db0fbacb753a0873a19c
refs/heads/master
2020-04-22T22:02:44.934037
2011-01-07T06:20:28
2011-01-07T06:20:28
1,234,211
2
0
null
null
null
null
GB18030
C++
false
false
2,002
h
// Copyright 2008-2011 Zhang Yun Gui, [email protected] // https://sourceforge.net/projects/x3c/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef X3_UNITTEST_BASETEST_H_ #define X3_UNITTEST_BASETEST_H_ const LPCWSTR PLUGINS_DIR = L"../Plugins"; interface Ix_PluginLoader; //! ๆต‹่ฏ•็”จไพ‹ๅŸบ็ฑป class BaseTest : public CppUnit::TestFixture { protected: BaseTest(); //! ๅŠ ่ฝฝๆ’ไปถ /*! \param plugins ็”ฑๆ’ไปถ็š„็›ธๅฏนๆ–‡ไปถๅ็ป„ๆˆ๏ผŒ ็”จ้€—ๅทๆˆ–็ฉบ็™ฝๅญ—็ฌฆๅˆ†้š”๏ผŒไพ‹ๅฆ‚โ€œ1.dll, 2.dllโ€๏ผ›ๅฏไธบ็ฉบ \param loadCore ๆ˜ฏๅฆๅŠ ่ฝฝๆ’ไปถๆก†ๆžถๅ†…ๆ ธ็š„ๆ’ไปถ(LogManager.plugin.dll็ญ‰) \return ๅœจpluginsๆ‰€ๆŒ‡ๅฎš็š„ๆ’ไปถไธญ๏ผŒๅŠ ่ฝฝๆˆๅŠŸ็š„ๆ’ไปถไธชๆ•ฐ */ long LoadPlugins(LPCWSTR plugins, bool loadCore = true); //! ๅธ่ฝฝๆ‰€ๆœ‰ๆ’ไปถ void UnloadPlugins(); //! ๅพ—ๅˆฐๆ’ไปถๅŠ ่ฝฝ็ฎก็†ๅฏน่ฑก๏ผŒๅฏ็”จไบŽๅŠ ่ฝฝๆ›ดๅคšๆ’ไปถ Ix_PluginLoader* GetPluginLoader(); //! ๅฝขๆˆๆต‹่ฏ•ๆ•ฐๆฎ็š„ๆ–‡ไปถๅ…จๅ /*! ๆต‹่ฏ•ๆ•ฐๆฎ็š„ๆ น็›ฎๅฝ•ๅœจ UnitTests.ini ไธญ[Path]ไธ‹็š„ TestData ้”ฎๆฅๆŒ‡ๅฎšใ€‚ \param folder ๅญ็›ฎๅฝ•ๅ๏ผŒไพ‹ๅฆ‚โ€œPdfโ€๏ผŒไธบ็ฉบๅˆ™ๅ–ไธบไธดๆ—ถ่พ“ๅ‡บ็›ฎๅฝ•๏ผŒ ่ฏฅไธดๆ—ถ็›ฎๅฝ•ๅœจ UnitTests.ini ไธญ[Path]ไธ‹็š„ Temp ้”ฎๆฅๆŒ‡ๅฎšใ€‚ \param file ็›ธๅฏนๆ–‡ไปถๅ๏ผŒไธบ็ฉบๅˆ™่ฟ”ๅ›ž็›ฎๅฝ•ๅ…จๅ \return ๆ–‡ไปถๆˆ–็›ฎๅฝ•็š„ๅ…จๅ */ std::wstring MakeDataPath(LPCWSTR folder, LPCWSTR file); private: void MakeRootPath(LPWSTR path, LPCWSTR name); }; #endif // X3_UNITTEST_BASETEST_H_
[ "rhcad1@71899303-b18e-48b3-b26e-8aaddbe541a3" ]
[ [ [ 1, 56 ] ] ]
c90bcd1be8f04dec9327e534f29a2f820a287b93
222bc22cb0330b694d2c3b0f4b866d726fd29c72
/src/nv38box/Math/WmlColorRGB.inl
81eed5a592cc36bd8d6260c6c75d92db0df274ca
[ "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference" ]
permissive
darwin/inferno
02acd3d05ca4c092aa4006b028a843ac04b551b1
e87017763abae0cfe09d47987f5f6ac37c4f073d
refs/heads/master
2021-03-12T22:15:47.889580
2009-04-17T13:29:39
2009-04-17T13:29:39
178,477
2
0
null
null
null
null
UTF-8
C++
false
false
1,037
inl
// Magic Software, Inc. // http://www.magic-software.com // http://www.wild-magic.com // Copyright (c) 2003. All Rights Reserved // // The Wild Magic Library (WML) source code is supplied under the terms of // the license agreement http://www.magic-software.com/License/WildMagic.pdf // and may not be copied or disclosed except in accordance with the terms of // that agreement. //---------------------------------------------------------------------------- inline ColorRGB::ColorRGB () { // For efficiency in construction of large arrays of colors, // the default constructor does not initialize a color. } //---------------------------------------------------------------------------- inline float& ColorRGB::operator[] (int i) const { return ((float*)this)[i]; } //---------------------------------------------------------------------------- inline ColorRGB::operator float* () { return (float*)this; } //----------------------------------------------------------------------------
[ [ [ 1, 30 ] ] ]
68bfe22a95085ca88d2e8c09dde073d6531f577f
1eb0e6d7119d33fa76bdad32363483d0c9ace9b2
/PointCloud/trunk/PointCloud/Mesh.cpp
8a217833454e0987830a67fb4c9b7e3fd1c2a7f1
[]
no_license
kbdacaa/point-clouds-mesh
90f174a534eddb373a1ac6f5481ee7a80b05f806
73b6bc17aa5c597192ace1a3356bff4880ca062f
refs/heads/master
2016-09-08T00:22:30.593144
2011-06-04T01:54:24
2011-06-04T01:54:24
41,203,780
0
2
null
null
null
null
GB18030
C++
false
false
44,129
cpp
#include "StdAfx.h" #include "Mesh.h" #include <fstream> #include <iostream> #include "PointCloudView.h" #include "BallMesh/BallMesh.h" using namespace std; #ifdef _DEBUG #define new DEBUG_NEW #endif //=====================AdvancingFront=========================// // TODO ๆญคๅค„้œ€่ฆ็”Ÿๆˆไธ€ไธชๆ–ฐ็š„ไธ‰่ง’้ข๏ผŒ่ฟ™ๆ ทๆ‰่ƒฝ่ฎพ็ฝฎๅฝ“ๅ‰ๆ–ฐๅŠ ๅ…ฅ็š„่พน่ฎพ็ฝฎ็š„ๆŒ‡้’ˆ bool AdvancingFront::join(CFrontEdge& edge, int vertIdx, CPointSet* ps, float ballCnt[3], CTriangle* newTriangle){ bool used = IsVertexUsed(vertIdx); list<CFrontEdge>::iterator it, toGlue[2]; int nbFound = 0; bool found = false; if (used){ it = m_frontEdgeList.begin(); //+ๅœจๅทฒๆœ‰็š„ๆณขๅ‰่พน้›†ไธญๆŸฅๆ‰พ็‚นvertIdx+ while (it != m_frontEdgeList.end() && nbFound < 2){ if (it->isInEdge(vertIdx)){ found = true; if (it->isInEdge(edge.getA()) || it->isInEdge(edge.getB())){ toGlue[nbFound++] = it; } } it ++; } if (nbFound >= 2) nbFound --; if (!found){ edge.setBoundary();// ๆญคๅค„ๅบ”ไธบๆ‰พๅˆฐ็š„็‚นไธบ้žๆณขๅ‰่พนไธŠ็š„็‚น๏ผŒไฝ†ๆ˜ฏๅทฒ็ป่ขซไฝฟ็”จไบ†๏ผˆๅณ๏ผšๅ†…้ƒจ็š„็‚น๏ผ‰ return false; } } else { addVertex(vertIdx); } int idxA = edge.getA(); int idxB = edge.getB(); CFrontEdge a(idxA, vertIdx), b(vertIdx, idxB); newTriangle->setTriVertexs(idxA, vertIdx, idxB); if ( !ps->checkConsistence(idxA, vertIdx, idxB)){ a.setEdge(vertIdx, idxA); b.setEdge(idxB, vertIdx); newTriangle->setTriVertexs(idxA, idxB, vertIdx); } // ๏ผš้œ€่ฆ่ฎพ็ฝฎa๏ผŒb็š„ๅ‰ไธ€ไธช็ƒ็š„็ƒๅฟƒ,ไปฅๅŠๆ‰€ๅœจ้ข็š„point // ๏ผšๆ–ฐ่พนๅบ”่ฏฅๆŒ‡ๅ‘ๅฝ“ๅ‰ๆ‹ฅๆœ‰ๅ…ถ็š„้ขไนŸๅฐฑๆ˜ฏๅ…ถไธ‹ไธ€ๆญฅๅฝขๆˆ็š„้ข a.setCenter(ballCnt); b.setCenter(ballCnt); a.setPreTriangle(newTriangle); b.setPreTriangle(newTriangle); // ่ฎพ็ฝฎ็›ธ้‚ปไธ‰่ง’ๅฝข็š„้“พๆŽฅๅ…ณ็ณป ๅ…ฑ็”จ่พนedge // newTriangle->setNeighbor(vertIdx, edge.getPreTriangle()); // edge.getPreTriangle()->setNeighbor(edge, newTriangle); m_frontEdgeList.remove(edge); bool insertA = true, insertB = true; if (used){ for (int i = 0; i < nbFound ; i++) { list<CFrontEdge>::iterator it = toGlue[i]; if ( (*it) == CEdge(a.getB(), a.getA()) ){ // ๆญคๅค„่ฎพ็ฝฎ็›ธ้‚ป้ข็š„ๆŒ‡้’ˆ // newTriangle->setNeighbor(idxB, it->getPreTriangle()); // it->getPreTriangle()->setNeighbor(*it, newTriangle); insertA = false; m_frontEdgeList.erase(it); m_vertexList.remove(idxA); }else if ( (*it) == CEdge(b.getB(), b.getA()) ){ // newTriangle->setNeighbor(idxA, it->getPreTriangle()); // it->getPreTriangle()->setNeighbor(*it, newTriangle); insertB = false; m_frontEdgeList.erase(it); m_vertexList.remove(idxB); } } } if (insertA) m_frontEdgeList.push_back(a); if (insertB) m_frontEdgeList.push_back(b); return true; } bool AdvancingFront::join( CFrontEdge& edge, int vertIdx, vector<short>& m_bPointUsed, CTriangle* newTriangle ) { // assert(edge.getA() != vertIdx); // assert(edge.getB() != vertIdx); typedef list<CFrontEdge>::iterator IT; IT itA = m_frontEdgeList.end(), itB = itA; int iVertIdxOnFront = 0; // ๆœ€ไผ˜็‚น่ฟžๆŽฅ็š„ๆณขๅ‰่พนๆ•ฐ //! ๆŸฅๆ‰พ for (IT it = m_frontEdgeList.begin(); it != m_frontEdgeList.end(); ++it) { if (it->getA() == vertIdx || it->getB()==vertIdx){ iVertIdxOnFront++; // ๆœ€ไผ˜็‚นๅœจๆณขๅ‰่พนไธŠ if (it->getB() == edge.getA() ) itA = it; // ๅญ˜ๅœจๅˆๅนถ่พนGlue Edge(A, V) else if (it->getA() == edge.getB() ) itB = it; // ๅญ˜ๅœจๅˆๅนถ่พนGlue Edge(V, B) } } // ่ฎพ็ฝฎไธคไธชไธ‰่ง’ๅฝข็š„็›ธ้‚ปๅ…ณ็ณป newTriangle->setTriVertexs(edge.getA(), vertIdx, edge.getB()); // edge.getPreTriangle()->setNeighbor(edge.getOppPoint(), newTriangle); // newTriangle->setNeighbor(vertIdx, edge.getPreTriangle()); if (itA == itB) { // vertIdxไธๅœจๆณขๅ‰่พนไธŠ|vertIdxๅœจๆณขๅ‰่พนไธŠไฝ†ๆฒกๆœ‰่ฆๅˆๅนถ็š„่พน if (iVertIdxOnFront == 0){ // ไธๅœจๆณขๅ‰่พนไธŠๆ‰้œ€่ฆๆทปๅŠ  // m_vertexList.push_back(vertIdx); m_bPointUsed[vertIdx] = FRONTPOINT; } /* else { m_bPointUsed[vertIdx] += 2; }*/ CFrontEdge a(edge.getA(), vertIdx, edge.getB(), newTriangle), b(vertIdx, edge.getB(), edge.getA(), newTriangle); m_frontEdgeList.push_back(a); m_frontEdgeList.push_back(b); m_frontEdgeList.remove(edge); } else { // vertIdxๅœจๆณขๅ‰่พนไธŠ if (itA != m_frontEdgeList.end()){ // ่พนVA้œ€่ฆๅˆๅนถ // newTriangle->setNeighbor(vertIdx, itA->getPreTriangle()); // itA->getPreTriangle()->setNeighbor(itA->getOppPoint(), newTriangle); m_frontEdgeList.remove(*itA); // m_vertexList.remove(edge.getA()); m_bPointUsed[edge.getA()] = INPOINT; // A ไธบๅ†…็‚น } else { CFrontEdge a(edge.getA(), vertIdx, edge.getB(), newTriangle); m_frontEdgeList.push_back(a); } if (itB != m_frontEdgeList.end()){ // ่พนBV้œ€่ฆๅˆๅนถ // newTriangle->setNeighbor(vertIdx, itB->getPreTriangle()); // itB->getPreTriangle()->setNeighbor(itB->getOppPoint(), newTriangle); m_frontEdgeList.remove(*itB); // m_vertexList.remove(edge.getB()); m_bPointUsed[edge.getB()] = INPOINT; // B ไธบๅ†…็‚น } else { CFrontEdge b(vertIdx, edge.getB(), edge.getA(), newTriangle); m_frontEdgeList.push_back(b); } // TODO ๅŒๆ—ถๅˆๅนถไธคๆกๅนถไธ”่ฟžๆŽฅๆญค็‚น็š„็บฟๆฎตไธบ2๏ผŒ่ฟ™ๆ ทvertIdxๆ‰ๆ˜ฏๅ†…็‚น if (iVertIdxOnFront == 2 && itA != m_frontEdgeList.end() && itB != m_frontEdgeList.end()){ // m_vertexList.remove(vertIdx); m_bPointUsed[vertIdx] = INPOINT; } m_frontEdgeList.remove(edge); } return true; } //=====================CMesh========================// CMesh::CMesh(CPointSet* ps) : m_ps(ps) { ps->constructKdTree(); m_bPointUsed.resize(m_ps->m_pointN); for (int i = 0; i < m_ps->m_pointN ; i++) { m_bPointUsed[i] = UNUSEDPOINT; } } CMesh::~CMesh(void) { for (size_t i = 0; i < m_faceVects.size() ; i++) { delete m_faceVects[i]; m_faceVects[i] = NULL; } m_faceVects.clear(); m_bPointUsed.clear(); m_ps = NULL; } void CMesh::writeToFile(char* pFileName) { if (pFileName != NULL) { ofstream plyFile(pFileName); if (plyFile){ float** points = m_ps->m_point; plyFile<<m_ps->m_pointN<<endl; for (int i = 0; i < m_ps->m_pointN ; i++) { plyFile<<points[i][0]<<" "<<points[i][1]<<" "<<points[i][2]<<endl; } std::vector<CTriangle*>::iterator it; int j = 0; for (it = m_faceVects.begin(); it != m_faceVects.end(); ++it, j++) { plyFile<<j<<" "<<(*it)->getA()<<" "<<(*it)->getB()<<" "<<(*it)->getC()<<endl; } plyFile.close(); } } } //@ ไธ่ฎก็ฎ—start,ไปŽstartไธ‹ไธ€ไธชๅผ€ๅง‹ int CMesh::getFirstUnusedPt( int start /*= 0*/ ) { for (int i = start+1; i < m_ps->m_pointN ; i++) { if (m_bPointUsed[i] == UNUSEDPOINT) return i; } for (int i = 0; i < start; i++) { if (m_bPointUsed[i] == UNUSEDPOINT) return i; } return -1; // ๅ…จ้ƒจๅทฒ็ปไฝฟ็”จไบ† } void CMesh::computePointNormal() { m_ps->constructNormal(); float (*normal_v)[3] = m_ps->m_normal; size_t vertexN = m_ps->getPointSize(); for (size_t i = 0; i < m_faceVects.size(); i++){ CTriangle* face = m_faceVects[i]; for (int j = 0; j < 3; j++){ float *nv = normal_v[face->vertex(j)]; nv[0] += face->getNormIdx(0); nv[1] += face->getNormIdx(1); nv[2] += face->getNormIdx(2); } } for (size_t k = 0; k < vertexN; k++){ float* nv = normal_v[k]; eUnit(nv); } } void CMesh::fillSmallHolesMinA( int T ) { int i, j, k; int vertexN = m_ps->getPointSize(); int faceN = m_faceVects.size(); //==็”Ÿๆˆ้กถ็‚น็š„่ฟžๆŽฅไธ‰่ง’ๅฝขไธชๆ•ฐ==// int* degree = new int[vertexN]; // ้กถ็‚น่ฟžๆŽฅไธ‰่ง’ๅฝขไธชๆ•ฐ for (i = 0; i< vertexN; i++) degree[i] = 0; for (i = 0; i < faceN ; i++) { CTriangle* pFace = m_faceVects[i]; degree[pFace->vertex(0)]++; degree[pFace->vertex(1)]++; degree[pFace->vertex(2)]++; } //==็”Ÿๆˆ้กถ็‚น็š„่ฟžๆŽฅไธ‰่ง’ๅฝขๅบๅท==// int ** link = new int *[vertexN]; // ้กถ็‚น่ฟžๆŽฅ็š„ไธ‰่ง’ๅฝขๅบๅท for (i = 0; i < vertexN ; i++) { link[i] = new int [degree[i]]; degree[i] = 0; } for ( i = 0; i < faceN ; i++) { CTriangle* f = m_faceVects[i]; for (j =0; j < 3; j++){ k = f->vertex(j); link[k][degree[k]++] = i; } } int ** linkT = new int *[vertexN]; for ( i = 0; i < vertexN ; i++) { int degT = degree[i];// ้กถ็‚น i ็›ธ้‚ปไธ‰่ง’ๅฝขไธชๆ•ฐ int degE = 0; int * lT = link[i]; int * lE = new int [2*degT]; //TODO Mem leak int * lF = new int [2*degT]; //TODO Mem leak for (j = 0; j < degT; j++) { CTriangle* f = m_faceVects[ lT[j] ]; int v = f->vertex(0); if (f->vertex(0) == i) v = f->vertex(1); else if (f->vertex(1) == i) v = f->vertex(2); for (k = 0; k < degT; k++) { if (j == k) continue; CTriangle* f1 = m_faceVects[ lT[k] ]; if (f1->vertex(0) == v || f1->vertex(1) == v || f1->vertex(2) == v) break; } if (k == degT){ lE[degE] = v; lF[degE] = lT[j]; degE++; } } for (j = 0; j < degT; j++){ CTriangle* f = m_faceVects[ lT[j] ]; int v = f->vertex(1); if (f->vertex(0) == i) v = f->vertex(2); else if (f->vertex(1) == i) v = f->vertex(0); for (k = 0; k < degT; k++) { if (j == k) continue; CTriangle* f1 = m_faceVects[ lT[k] ]; if (f1->vertex(0) == v || f1->vertex(1) == v || f1->vertex(2) == v) break; } if (k == degT){ lE[degE] = v; lF[degE] = lT[j]; degE++; } } degree[i] = degE; delete[] lT; if (degE == 0){ delete[] lE; delete[] lF; }else { link[i] = lE; linkT[i] = lF; } } bool* visit = new bool[vertexN]; for (i = 0; i < vertexN; i++) visit[i] = false; int top; int * stack = new int [T+1]; int * stackF = new int [T+1]; TriList2* tri_list = new TriList2(-1, -1, -1); for (i = 0; i < vertexN; i++){ if (visit[i] == true) continue; top = 0; stack[0] = i; visit[i] = true; bool isFilled = false; while (top < T){ int index = stack[top]; if (degree[index] < 2){ if (degree[index] != 0){ delete[] link[index]; degree[index] = 0; } break; } int next = link[index][0]; int f = linkT[index][0]; stackF[top] = f; delete[] link[index]; delete[] linkT[index]; degree[index] = 0; if (next == i){ isFilled = true; break; } if (visit[next]) break; stack[++top] = next; visit[next] = true; } if (!isFilled) continue; int size = top + 1; fillPolygon(tri_list, stack, stackF, size); } delete[] stack; delete[] stackF; delete[] visit; delete[] link; delete[] linkT; delete[] degree; //====ๅฐ†็”Ÿๆˆ็š„็ฉบๆดžไธ‰่ง’ๅฝขๆทปๅŠ ๅˆฐ้“พ่กจๅŽ===// TriList2* l; // int N = 0; // ็ฉบๆดžไธ‰่ง’ๅฝขไธชๆ•ฐ // for (l = tri_list; l != NULL; l = l->next) N++; // N--; for (l = tri_list; l->next != NULL; l = l->next){ CTriangle* pFace = new CTriangle(l->i0, l->i1, l->i2); pFace->calcNorm(m_ps); m_faceVects.push_back(pFace); } delete tri_list; } void CMesh::fillPolygon( TriList2*& tri_list, int* v, int* f, int N ) { float** area = new float*[N]; float** angle = new float*[N]; int ** opt = new int*[N]; int i, j, k, m; for (i = 0; i < N; i++){ area[i] = new float[N]; angle[i] = new float[N]; opt[i] = new int[N]; } for (i = 0; i < N-1; i++){ angle[i][i+1] = 0.0f; area[i][i+1] = 0.0f; } for (i = 0; i<N-2; i++){ area[i][i+2] = m_ps->areaF(v[i], v[i+1], v[i+2]); float a1 = m_ps->dihedral(v[i], v[i+1], v[i+2], m_faceVects[ f[i] ]->vertex(0), m_faceVects[ f[i] ]->vertex(2), m_faceVects[ f[i] ]->vertex(1)); float a2 = m_ps->dihedral(v[i], v[i+1], v[i+2], m_faceVects[ f[i+1] ]->vertex(0), m_faceVects[ f[+1] ]->vertex(2), m_faceVects[ f[i+1] ]->vertex(1)); if (a1 > a2) angle[i][i+2] = a1; else angle[i][i+2] = a2; opt[i][i+2] = i+1; } for (j = 3; j < N; j++){ for (i = 0; i < N - j; i++){ k = i+j; area[i][k] = 1000000.0f; angle[i][k] = 1000000.0f; for (m=i+1; m<k;m++){ float a = area[i][m] + area[m][k] + m_ps->areaF(v[i], v[m], v[k]); float a1, a2; if (i+1 == m) a1 = m_ps->dihedral( v[i], v[m], v[k], m_faceVects[ f[i] ]->vertex(0), m_faceVects[ f[i] ]->vertex(2), m_faceVects[ f[i] ]->vertex(1)); else a1 = m_ps->dihedral(v[i], v[m], v[k], v[i], v[opt[i][m]], v[m]); if (m+1 == k) a2 = m_ps->dihedral(v[i], v[m], v[k], m_faceVects[ f[m] ]->vertex(0), m_faceVects[ f[m] ]->vertex(2), m_faceVects[ f[m] ]->vertex(1)); else a2 = m_ps->dihedral(v[i], v[m], v[k], v[m], v[opt[m][k]], v[k]); float maxA = a1; if (maxA < a2) maxA = a2; if (maxA < angle[i][m]) maxA = angle[i][m]; if (maxA < angle[m][k]) maxA = angle[m][k]; if (maxA < angle[i][k]){ area[i][k] = a; angle[i][k] = maxA; opt[i][k] = m; } else if (maxA == angle[i][k]){ if (a < area[i][k]){ area[i][k] = a; //angle[i][k] = maxA; opt[i][k] = m; } } } } } traceOpt(tri_list, 0, N-1, opt, v); for (i = 0; i< N; i++) { delete[] area[i]; delete[] opt[i]; delete[] angle[i]; } delete[] area; delete[] opt; delete[] angle; } void CMesh::traceOpt( TriList2*& tri_list, int i, int k, int** opt, int* v ) { if (i + 2 == k) tri_list = tri_list->add(v[i], v[k], v[i+1]); else { int o = opt[i][k]; if (o != i+1) traceOpt(tri_list, i, o, opt, v); tri_list = tri_list->add(v[i], v[k], v[o]); if (o != k-1) traceOpt(tri_list, o, k, opt, v); } } void CMesh::cleanBadTriangles() { int i, j; int N = m_ps->getPointSize(); int triN = m_faceVects.size(); bool * decideT = new bool[triN]; bool * decideV = new bool[N]; int ** link = new int*[N]; int * linkN = new int [N]; for(i = 0; i < N; i++){ link[i] = NULL; linkN[i] = 0; decideV[i] = false; } for (i = 0; i < triN; i++){ decideT[i] = false; for (j = 0; j< 3; j++){ int index = m_faceVects[i]->vertex(j); int lN = linkN[index]; int* l = link[index]; int* l_tmp = new int[lN+1]; for (int k = 0; k < lN; k++) l_tmp[k] = l[k]; l_tmp[lN] = i; if (lN != 0) delete[] l; link[index] = l_tmp; linkN[index]++; } } int* visitID = new int[N]; for (i = 0; i < N; i++) visitID[i] = -1; float min_error = 10000000000.0f; int seed = -1; for ( i = 0; i < N ; i++) { if (linkN[i] == 0) continue; if (sort1rings(decideT, link[i], linkN[i], i, visitID)){ float e = measure1ringError(link[i], linkN[i], i); if ( e < min_error && e > 0){ seed = i; min_error = e; } } } delete[] visitID; if( seed < 0 ){ delete[] decideT; delete[] decideV; delete[] linkN; for (i = 0; i < N; i++) if (link[i] != NULL) delete[] link[i]; delete[] link; cout<<"ๆœช่ƒฝๆ‰พๅˆฐๅˆ้€‚็š„็งๅญ็Žฏ!"<<endl; cout<<"ๅฏ่ƒฝๆ˜ฏ็”ฑไบŽ็‚นไบ‘ๅ™ชๅฃฐ่ฟ‡ๅคงๅผ•่ตท็š„!"<<endl; cout<<"ๆ— ๆณ•่ฟ›่กŒๆธ…็†๏ผŒ้€€ๅ‡บๆธ…็†่ฟ‡็จ‹!"<<endl; return ; } visitID = new int [triN]; bool * validT = new bool [triN]; for ( i= 0; i < triN; i++){ visitID[i] = -1; validT[i] = true; decideT[i] = false; } sort1rings( decideT, link[seed], linkN[seed], seed, visitID ); float * cost = new float[N]; int * heap = new int [N+1]; int * index = new int [N]; int last_heap = 0; for ( i = 0; i < N; i++){ cost[i] = 1000000000000.0f; index[i] = - 1; } int * best, bestN; getBest1ring(best, bestN, cost[seed], decideT, validT, link[seed], linkN[seed], seed, visitID); delete best; } bool CMesh::sort1rings( bool* decideT, int* list, int N, int current, int* visitID ) { if (N < 3) return false; int i; int start = list[0]; for (i = 0; i < N; i++){ if (decideT[ list[i] ]) { start = list[i]; break; } } int end = start; do { CTriangle* ti = m_faceVects[end]; int v = ti->vertex(0); if (ti->vertex(0) == current) v = ti->vertex(1); else if (ti->vertex(1) == current) v = ti->vertex(2); if (visitID[v] == current) return false; visitID[v] = current; bool flag = false; int next; for (i = 0; i< N; i++){ int s = list[i]; if (s == end) continue; ti = m_faceVects[s]; int ver_id; if (ti->vertex(0) == v) ver_id = 0; else if (ti->vertex(1) == v) ver_id = 1; else if (ti->vertex(2) == v) ver_id = 2; else continue; if (flag) return false; flag = true; next = s; int i1 = (ver_id+1)%3; if (ti->vertex(i1) != current){ int i2 = (ver_id+2)%3; ti->swapVertex(i1, i2); } } if (!flag) return false; end = next; }while(start != end); for (i = 0; i < N; i++) decideT[ list[i] ] = true; return true; } bool CMesh::getBest1ring(int * &blist, int &blistN, float &error, bool *decideT, bool *validT, int *list, int N, int current, int *visitID) { blist = NULL; blistN = 0; int * stack = new int [N+1]; int top = -1; int start = -1; int i ; for (i = 0; i< N; i++){ if ( decideT[ list[i] ] && validT[ list[i] ] ){ start = i; break; } } if (start < 0){ delete[] stack; return false; } CTriangle* ti = m_faceVects[ list[start] ]; int startV = ti->vertex(1); if (ti->vertex(0) == current) startV = ti->vertex(2); else if (ti->vertex(1) == current) startV = ti->vertex(0); stack[++top] = start; stack[++top] = -1; while (top > 0){ int t_id = list[ stack[top-1] ]; CTriangle* tid = m_faceVects[t_id]; int v = tid->vertex(0); if (tid->vertex(0) == current) v = tid->vertex(1); else if (tid->vertex(1) == current) v = tid->vertex(2); if (v == startV){ int * list_tmp = new int [top]; for (i = 0; i< top; i++) list_tmp[i] = list[ stack[i] ]; bool flag = true; for ( i = 0; i< N; i++){ if (!decideT[ list[i] ]) continue; bool flag1 = false; for (int j = 0; j < top; j++){ if (list_tmp[j] == list[i]){ flag1 = true; break; } } if (!flag1) { flag = false; break; } } if (flag){ float error_tmp = measure1ringError(list_tmp, top, current); if (blistN == 0 || error_tmp < error){ error = error_tmp; delete blist; blist = list_tmp; blistN = top; }else delete list_tmp; }else delete list_tmp; top--; continue; } visitID[t_id] = current; bool flag = false; if ( stack[top] < 0) i = 0; else i = stack[top] +1; top --; for (; i< N; i++){ if ( i == stack[top] || visitID[ list[i] ] == current || !validT[ list[i] ]) continue; tid = m_faceVects[ list[i] ]; int ver_id; if ( tid->vertex(0) == v) ver_id = 0; else if (tid->vertex(1) == v) ver_id = 1; else if (tid->vertex(2) == v) ver_id = 2; else continue; if (decideT[ list[i] ]){ int i1 = (ver_id +1)%3; if ( tid->vertex(i1) != current) continue; } flag = true; stack[++top] = i; int i1 = (ver_id +1) % 3; if (tid->vertex(i1) != current){ int i2 = (ver_id +2) % 3; tid->swapVertex(i1, i2); } break; } if (flag) stack[++top] = -1; else visitID[t_id] = -1; } delete[] stack; if (blistN < 3) return false; for (i = 0; i < blistN; i++) { if (i + 1 == blistN) continue; int j = blist[i]; ti = m_faceVects[j]; int v = ti->vertex(0); if (ti->vertex(0) == current) v = ti->vertex(1); else if (ti->vertex(1) == current) v = ti->vertex(2); ti = m_faceVects[ blist[i + 1] ]; int ver_id = 2; if (ti->vertex(0) == v) ver_id = 0; else if (ti->vertex(1) == v) ver_id = 1; int i1 = (ver_id + 1) % 3; if (ti->vertex(i1) != current) { int i2 = (ver_id + 2) % 3; ti->swapVertex(i1, i2); } } return true; } float CMesh::measure1ringError( int * list, int N, int current ) { if (N < 3) return 100000.0f; float** verts = m_ps->m_point; //TODO return 0.0f; } //==================CBPAMESH====================// inline float veccos(float* a, float* b){ return (a[0]*b[0]+a[1]*b[1]+a[2]*b[2]) / sqrt((a[0]*a[0]+a[1]*a[1]+a[2]*a[2]) * (b[0]*b[0]+b[1]*b[1]+b[2]*b[2])); } inline void vecCross(float* ret, float* a, float* b){ ret[0] = a[1]*b[2] - a[2]*b[1]; ret[1] = a[2]*b[0] - a[0]*b[2]; ret[2] = a[0]*b[1] - a[1]*b[0]; } /* ่ฟ”ๅ›žๅ€ผไธบ 0->4 ็”ฑๅฐๅˆฐๅคง center๏ผšๅœ†ๅฟƒ(ๆปšๅŠจ็ƒ่ฝฌ่ฝด็š„ไธญ็‚น)๏ผ›Cijo๏ผšๅ‰ไธ€ไธช็ƒๅฟƒ๏ผ›Cko๏ผšๅŽไธ€ไธช็ƒๅฟƒ */ float CBpaMesh::getArc( float* center, float* Cijo, float* Cko) { float ccot[3]; // ไธ‰็‚นๆ‰€ๅค„้ข็š„ๆณ•็Ÿข float co[3], ck[3]; co[0] = Cijo[0] - center[0]; co[1] = Cijo[1] - center[1]; co[2] = Cijo[2] - center[2]; ck[0] = Cko[0] - center[0]; ck[1] = Cko[1] - center[1]; ck[2] = Cko[2] - center[2]; vecCross(ccot, co, ck); float ct[3]; // ๅž‚็›ดไบŽco(center->Cijo)็š„ๅ‘้‡ vecCross(ct, ccot, co); float cosco = veccos(co, ck); // co ๅ’Œ ck ไธคไธชๅ‘้‡็š„ไฝ™ๅผฆ //float cosct = veccos(ct, ck);// ct ๅ’Œ ck ไธคไธชๅ‘้‡็š„ไฝ™ๅผฆ float cosct = ct[0]*ck[0] + ct[1]*ck[1]+ct[2]*ck[2]; // if (cosco > 0){ if (cosct > 0) return 1.0f - cosco; // 0->1 else return 3.0f + cosco; // 3->4 // }else{ // if (cosct > 0) // return 1.0f - cosco; // 1->2 // else // return 3.0f + cosco; // 2->3 // } } bool CBpaMesh::findSeedTriange( CTriangle& face, float ballCenter[3] ) { // TODO ๆŸฅๆ‰พ้‚ปๅŸŸๆ—ถ้œ€่ฆๆŸฅๆ‰พๅ‡ ไธช๏ผŸ๏ผŸ int idxA = -1; ANNidxArray nnIdx = new ANNidx[m_K+1]; ANNdistArray dists = new ANNdist[m_K+1]; ANNkd_tree* tree = m_ps->m_kdTree; int ballNeigIdx[4]; //TODO ๆญคๅค„ๅฏ่ƒฝ้€ ๆˆๆญปๅพช็Žฏ ๅฝ“ๆœชไฝฟ็”จ็š„็‚นๅพˆๅฐ‘ๆ—ถ,ไผšๅ‡บ็Žฐ่ฟ™็ง้—ฎ้ข˜, //TODO ่งฃๅ†ณๆ–นๆณ•:ๅˆคๆ–ญidxๆ˜ฏๅฆๅฐ†ๆœชไฝฟ็”จ็‚น่ฎก็ฎ—ไธ€้ while ((idxA = getFirstUnusedPt(idxA))!=-1) // ๆ‰พๅˆฐ็ฌฌไธ€ไธช็‚นA { ANNpoint queryA = m_ps->m_point[idxA]; tree->annkSearch(queryA, m_K+1, nnIdx, dists, 1e-6); // ๆ‰พA็‚น็š„้‚ปๅŸŸ bool bFound = false; for (int i = 1; i < m_K+1 && !bFound; i++) { if (UNUSEDPOINT != m_bPointUsed[nnIdx[i]]) continue; int idxB = nnIdx[i]; // ๆ‰พๅˆฐ็ฌฌไบŒไธช็‚นB int j = i+1; while (j++ < m_K+1 && !bFound){ int idxC = nnIdx[j]; // ๆ‰พๅˆฐ็ฌฌไธ‰ไธช็‚นC if (UNUSEDPOINT != m_bPointUsed[idxC]) continue; face.setTriVertexs(idxA, idxB, idxC); if (m_ps->checkConsistence(idxA, idxB, idxC)) face.setTriVertexs(idxA, idxC, idxB); float center[3]; if (!getBallCenter(center, idxA, face.getB(), face.getC(), m_ballR)) continue; // ่ฎก็ฎ—็ƒๅฟƒcenter tree->annkSearch(center, 4, ballNeigIdx, dists, 1e-6); // ๆ‰พ็ƒๅฟƒ็š„ๆœ€่ฟ‘็‚นๅช้œ€่ฆ4ไธช็‚นๅณๅฏ bool valid = true; for (int t = 0; t < 4 ; t++) { int idx = ballNeigIdx[t]; if (idx != idxA && idx != idxB && idx != idxC){ float* pt = m_ps->m_point[idx]; float distance2 = (center[0]-pt[0])*(center[0]-pt[0])+ (center[1]-pt[1])*(center[1]-pt[1])+ (center[2]-pt[2])*(center[2]-pt[2]); if (distance2 < m_ballR*m_ballR){ // ็‚นๅˆฐ็ƒๅฟƒ็š„่ท็ฆป < ็ƒๅŠๅพ„๏ผŒๅณ็ƒๅ†…ๅŒ…ๅซๅ…ถไป–็‚น๏ผŒไธๆปก่ถณๆกไปถ valid = false; break; } } } if (valid){ ballCenter[0] = center[0]; ballCenter[1] = center[1]; ballCenter[2] = center[2]; m_bPointUsed[idxA] = FRONTPOINT; m_bPointUsed[idxB] = FRONTPOINT; m_bPointUsed[idxC] = FRONTPOINT; delete[] nnIdx; delete[] dists; return true; } } } } delete[] nnIdx; delete[] dists; return false; } CBpaMesh::CBpaMesh(CPointSet* ps, int k) : CMesh(ps) { m_K = k; } /* ่ฟ”ๅ›žๆ˜ฏๅฆๆฑ‚ๅ‡บ็ƒๅฟƒ๏ผˆtrueไธบๆฑ‚ๅพ—๏ผ‰ center ไธบ็ƒ็š„็ƒๅฟƒ๏ผˆ่พ“ๅ‡บ๏ผ‰ ptAใ€ptBใ€ptCไธบ็ƒไธŠ็š„ไธ‰็‚น ็ป„ๆˆ้ขABC normal[3] ไธบABCไธ‰็‚น็š„ๆณ•็Ÿข็š„ๅนณๅ‡ๅ€ผ ballRไธบ็ƒ็š„็ƒๅŠๅพ„ */ bool CBpaMesh::getBallCenter( float center[3], float* ptA, float* ptB, float* ptC, float normal[3], float ballR ) { float x1 = ptB[0] - ptA[0]; float x2 = ptC[0] - ptA[0]; float y1 = ptB[1] - ptA[1]; float y2 = ptC[1] - ptA[1]; float z1 = ptB[2] - ptA[2]; float z2 = ptC[2] - ptA[2]; float pi, pj, pk; // ้ขABC็š„ๆณ•็Ÿข pi=y1*z2-z1*y2; pj=z1*x2-x1*z2; pk=x1*y2-y1*x2; if((pi==0)&&(pj==0)&&(pk==0)){ return false; // ไธ‰็‚นๅ…ฑ็บฟ } if((normal[0]*pi+normal[1]*pj + normal[3]*pk) < 0){ pi = -pi; pj = -pj; pk = -pk; } float dMx = (ptA[0]+ptB[0])/2, // AB ็š„ไธญ็‚นM dMy = (ptA[1]+ptB[1])/2, dMz = (ptA[2]+ptB[2])/2; float dMi = pj*z1-pk*y1, // AB ็š„ไธญๅž‚็บฟๆ–นๅ‘ dMj = pk*x1-pi*z1, dMk = pi*y1-pj*x1; float dNx = (ptA[0]+ptC[0])/2, // AC ็š„ไธญ็‚นM dNy = (ptA[1]+ptC[1])/2, dNz = (ptA[2]+ptC[2])/2; float dNi = pj*z2-pk*y2,// AC ็š„ไธญๅž‚็บฟๆ–นๅ‘ dNj = pk*x2-pi*z2, dNk = pi*y2-pj*x2; float ds = 1.0f / sqrt(pi*pi + pj*pj + pk*pk); pi *= ds; // ้ขๆณ•็Ÿขๅฝ’ไธ€ๅŒ– pj *= ds; pk *= ds; assert(dMi != 0); float tm, tn; tn = ((dMy-dNy) * dMi + dMj * (dNx-dMx)) / (dNj*dMi - dMj*dNi); tm = (dNx + dNi*tn - dMx) / dMi; float ox = dMx + dMi*tm, //ไธ‰่ง’ๅฝขABC็š„ๅค–ๆŽฅๅœ†ๅœ†ๅฟƒ oy = dMy + dMj*tm, oz = dMz + dMk*tm; float dR2 = ( (ox-ptA[0])*(ox-ptA[0]) + // ๅค–ๆŽฅๅœ†ๅŠๅพ„็š„ๅนณๆ–น (oy-ptA[1])*(oy-ptA[1]) + (oz-ptA[2])*(oz-ptA[2]) ); float h = ballR*ballR - dR2; if (h < 0) return false; else if (h == 0){ center[0] = ox; center[1] = oy; center[2] = oz; }else{ h = sqrt(h); center[0] = ox + h*pi; center[1] = oy + h*pj; center[2] = oz + h*pk; } return true; } /* ่ฟ”ๅ›žๆ˜ฏๅฆๆฑ‚ๅ‡บ็ƒๅฟƒ๏ผˆtrueไธบๆฑ‚ๅพ—๏ผ‰ center ไธบ็ƒ็š„็ƒๅฟƒ๏ผˆ่พ“ๅ‡บ๏ผ‰ idxA, idxB, idxC ไธบ็ƒไธŠ็š„ไธ‰็‚นABC็š„็ดขๅผ• ballRไธบ็ƒ็š„ๅŠๅพ„ */ bool CBpaMesh::getBallCenter( float center[3], int idxA, int idxB, int idxC, float ballR ) { float** points = m_ps->m_point; float* ptA = points[idxA], * ptB = points[idxB], * ptC = points[idxC]; float (*normal)[3] = m_ps->m_normal; float* nmA = normal[idxA], * nmB = normal[idxB], *nmC = normal[idxC]; float norm[3]; norm[0] = (nmA[0] + nmB[0] + nmC[0]); norm[1] = (nmA[1] + nmB[1] + nmC[1]); norm[2] = (nmA[2] + nmB[2] + nmC[2]); return getBallCenter(center, ptA, ptB, ptC, norm, ballR); } void CBpaMesh::start() { CTriangle face; float ballCnt[3]; while (true) { std::list<CFrontEdge>::iterator itEdge; int vertIdx; while (m_front.getActiveEdge(itEdge)) { CEdge edge = *itEdge; if (itEdge->getStatus() == ACTIVE) { // TODO ่ฆไธๆ–ญไฟฎๆ”นface ๅ–ๅฝ“ๅ‰่พน็š„preTriangle CTriangle* pFace = itEdge->getPreTriangle(); int idPrec = -1; if (NULL != pFace){ idPrec = pFace->getA(); if (edge.getA() == idPrec || edge.getB() == idPrec){ idPrec = pFace->getB(); if (edge.getA() == idPrec || edge.getB() == idPrec) idPrec = pFace->getC(); } } bool pivoted = ballPivotT(*itEdge, vertIdx, idPrec, ballCnt); if (pivoted){ CTriangle* newTri = new CTriangle; if (m_front.join(*itEdge, vertIdx, m_ps, ballCnt, newTri)){ m_bPointUsed[vertIdx] = FRONTPOINT; m_faceVects.push_back(newTri); } else { delete newTri; } } else { itEdge->setBoundary(); } } } float center[3]; if (findSeedTriange(face, center)){ CTriangle* pFace = new CTriangle(face); m_faceVects.push_back(pFace); CFrontEdge a(face.getA(), face.getB()); a.setCenter(center); a.setPreTriangle(pFace); m_front.addEdge(a); CFrontEdge b(face.getB(), face.getC()); b.setCenter(center); b.setPreTriangle(pFace); m_front.addEdge(b); CFrontEdge c(face.getC(), face.getA()); c.setCenter(center); c.setPreTriangle(pFace); m_front.addEdge(c); } else { return ; } } } bool CBpaMesh::ballPivotT( CFrontEdge& fontEdge, int& vertIdx, int idPrec ,float ballCnt[3] ) { int idxA = fontEdge.getA(); int idxB = fontEdge.getB(); ANNpoint PtA = m_ps->m_point[idxA]; ANNpoint PtB = m_ps->m_point[idxB]; float midAB[3]; midAB[0] = (PtA[0] + PtB[0]) / 2; midAB[1] = (PtA[1] + PtB[1]) / 2; midAB[2] = (PtA[2] + PtB[2]) / 2; // TODO:: ๆ€Žๆ ท็กฎๅฎšๆŸฅๆ‰พๆœ€ๅฐ‘็š„็‚น๏ผŸ ANNidxArray nnIdx = new ANNidx[m_K+1]; ANNdistArray dists = new ANNdist[m_K+1]; // TODO๏ผšๆญคๅค„ๅบ”่ฏฅๆŸฅๆ‰พๅŠๅพ„ไธบ r ็š„็ƒๅŸŸ int pts = m_ps->m_kdTree->annkFRSearch(midAB, m_ballR*m_ballR, m_K+1, nnIdx); // ่ฟ”ๅ›žๅฎž้™…็š„็‚นๆ•ฐ // m_ps->m_kdTree->annkSearch(midAB, m_K+1, nnIdx, dists, 0.00000001); delete[] dists; float* preBallCenter = fontEdge.m_ballCenter; float ballCenter[3]; float min_arc = 4.0; float arc; int better = -1; for (int i = 0; i < m_K ; i++) // m_K -> pts { if (nnIdx[i+1] == idxA || nnIdx[i+1] == idxB || nnIdx[i+1] == idPrec/* || INPOINT ==m_bPointUsed[ nnIdx[i+1] ]*/) continue; if (true == getBallCenter(ballCenter, idxA, idxB, nnIdx[i+1], m_ballR)){ arc = getArc(midAB, preBallCenter, ballCenter); if (min_arc > arc){ // TODO๏ผš้œ€่ฆ่ฎพ็ฝฎๆ–ฐ่พน็š„็ƒๅฟƒ๏ผŒๆ‰€ไปฅ้œ€่ฆ่ฟ”ๅ›ž็ƒๅฟƒ min_arc = arc; // TODO : ้€‰ๆ‹ฉๅผงๅบฆๆœ€ๅฐ็š„ better = nnIdx[i+1]; ballCnt[0] = ballCenter[0]; ballCnt[1] = ballCenter[1]; ballCnt[2] = ballCenter[2]; } } } delete[] nnIdx; if (better == -1){ return false; } vertIdx = better; return true; } bool CBpaMesh::ballPivot(CFrontEdge& fontEdge, int& vertIdx, int idPrec){ int better = -1; int idxA = fontEdge.getA(); int idxB = fontEdge.getB(); float** points = m_ps->m_point; vect3d n(points[idxB][0] - points[idxA][0], points[idxB][1] - points[idxA][1],points[idxB][2] - points[idxA][2]); vect3d m((points[idxB][0] - points[idxA][0])/2, (points[idxB][1] - points[idxA][1])/2, (points[idxB][2] - points[idxA][2])/2); return true; } //=========================CIPDMESH========================= float CIPDMesh::getAngel( const int& idxPre, const int& idxO, const int& idxNext ) { float* ptPre = m_ps->m_point[idxPre], * ptO = m_ps->m_point[idxO], * ptNext = m_ps->m_point[idxNext]; vect3f op(ptPre[0]-ptO[0], ptPre[1]-ptO[1], ptPre[2]-ptO[2]); vect3f on(ptNext[0]-ptO[0], ptNext[1]-ptO[1], ptNext[2]-ptO[2]); op.unit(); on.unit(); float opDoton = op*on; return 1.0f-opDoton; } float CIPDMesh::getMinTriAngel( const int& idxA, const int& idxB, const int& idxC ) { float angelA = getAngel(idxC, idxA, idxB), angelB = getAngel(idxA, idxB, idxC), angelC = getAngel(idxB, idxC, idxA); float minAB = min(angelA, angelB); return min(minAB, angelC); } float CIPDMesh::getTriArea( const int& idxA, const int& idxB, const int& idxC ) { float* ptA = m_ps->m_point[idxA], * ptB = m_ps->m_point[idxB], * ptC = m_ps->m_point[idxC]; float ab = sqrt( (ptA[0]-ptB[0])*(ptA[0]-ptB[0]) + (ptA[1]-ptB[1])*(ptA[1]-ptB[1]) + (ptA[2]-ptB[2])*(ptA[2]-ptB[2]) ), bc = sqrt( (ptC[0]-ptB[0])*(ptC[0]-ptB[0]) + (ptC[1]-ptB[1])*(ptC[1]-ptB[1]) + (ptC[2]-ptB[2])*(ptC[2]-ptB[2]) ), ac = sqrt( (ptA[0]-ptC[0])*(ptA[0]-ptC[0]) + (ptA[1]-ptC[1])*(ptA[1]-ptC[1]) + (ptA[2]-ptC[2])*(ptA[2]-ptC[2]) ); float p = (ab + bc + ac) * 0.5f; float area = sqrt( p*(p-ab)*(p-bc)*(p-ac) ); return area; } float CIPDMesh::getDihedralAngel( const CFrontEdge& frontEdge, const int& idx ) { int idxPre = frontEdge.getPreTriangle()->getVertex(frontEdge); if (idxPre != -1){ return getDihedralAngel(idxPre, frontEdge.getA(), frontEdge.getB(), idx); } return 0; //ไธคไธช้ข้‡ๅˆ } float CIPDMesh::getDihedralAngel( const int& idxPre, const int& idxA, const int& idxB, const int& idxNext ) { float* ptP = m_ps->m_point[idxPre], * ptA = m_ps->m_point[idxA], * ptB = m_ps->m_point[idxB], * ptN = m_ps->m_point[idxNext]; vect3f AB( ptB[0]-ptA[0], ptB[1]-ptA[1], ptB[2]-ptA[2] ), AP( ptP[0]-ptA[0], ptP[1]-ptA[1], ptP[2]-ptA[2] ), AN( ptN[0]-ptA[0], ptN[1]-ptA[1], ptN[2]-ptA[2] ); AN.cross(AB); AB.cross(AP); AN.unit(); AB.unit(); float angel = 1 - AB*AN; return angel; } int CIPDMesh::getMaxZIndex() { float** pts = m_ps->m_point; int ptN = m_ps->m_pointN; float maxZ = pts[0][2]; int idxZ = 0; for (int i = 1; i < ptN; i++) { if (maxZ < pts[i][2]){ maxZ = pts[i][2]; idxZ = i; } } return idxZ; } bool CIPDMesh::findSeedTriangle( CTriangle& face, int K ) { int seedA = getMaxZIndex(); float* ptA = m_ps->m_point[seedA]; ANNidxArray nnidxA = new ANNidx[2]; ANNdistArray distsA = new ANNdist[2]; m_ps->m_kdTree->annkSearch(ptA, 2, nnidxA, distsA); delete[] distsA; int seedB = nnidxA[1]; delete[] nnidxA; float* ptB = m_ps->m_point[seedB]; float ptMid[3] = { (ptA[0]+ptB[0])/2.0f, (ptA[1]+ptB[1])/2.0f, (ptA[2]+ptB[2])/2.0f }; ANNidxArray nnidx = new ANNidx[K+1]; ANNdistArray dists = new ANNdist[K+1]; m_ps->m_kdTree->annkSearch(ptMid, K+1, nnidx, dists); delete[] dists; float minLen = FLT_MAX; int seedC = -1; for (int i = 1; i < K+1; i++) { int idxC = nnidx[i]; if (idxC == seedA || idxC == seedB) continue; float minAngel = getMinTriAngel(seedA, seedB, idxC); if (minAngel > 0.2) // ไธ‰่ง’ๅฝขๅ†…่ง’ๆœ€ๅฐไธบ30ๅบฆ { float len = getDists(idxC, seedA, seedB); // ๅ–็‚นCไธŽseedAๅ’ŒseedBๅฝขๆˆ็š„ไธค่พนไน‹ๅ’Œๆœ€ๅฐ if (len < minLen){ minLen = len; seedC = idxC; } } } delete[] nnidx; if (seedC == -1) return false; //TODO ๆญคๅค„้œ€่ฆๆต‹่ฏ• face.setTriVertexs(seedA, seedB, seedC); setVertexUsed(seedA); setVertexUsed(seedB); setVertexUsed(seedC); return true; } bool CIPDMesh::findSeedTriangle2( CTriangle*& pFace, int K ) { int seedA = getFirstUnusedPt(-1), firstSeed = seedA; ANNidxArray nnidx = new ANNidx[K+1]; ANNdistArray dists = new ANNdist[K+1]; //TODO ๆญคๅค„ๅฏ่ƒฝ้€ ๆˆๆญปๅพช็Žฏ ๅฝ“ๆœชไฝฟ็”จ็š„็‚นๅพˆๅฐ‘ๆ—ถ,ไผšๅ‡บ็Žฐ่ฟ™็ง้—ฎ้ข˜, //TODO ่งฃๅ†ณๆ–นๆณ•:ๅˆคๆ–ญidxๆ˜ฏๅฆๅฐ†ๆœชไฝฟ็”จ็‚น่ฎก็ฎ—ไธ€้ while ( seedA != -1 ){ float* ptA = m_ps->m_point[seedA]; m_ps->m_kdTree->annkSearch(ptA, K+1, nnidx, dists); bool bFound = false; int seedC = -1; for (int i = 1; i < K+1 ; i++) { int seedB = nnidx[i]; if (UNUSEDPOINT != m_bPointUsed[seedB]) continue; int j = i+1; float minLen = FLT_MAX; while (j < K+1) { int idxC = nnidx[j]; if (UNUSEDPOINT != m_bPointUsed[idxC]) { j++; continue; } #define MINTRIANGEL30 0.13397459621556 // 1-cos(30') float minAngel = getMinTriAngel(seedA, seedB, idxC); if (minAngel > MINTRIANGEL30) // ไธ‰่ง’ๅฝขๅ†…่ง’ๆœ€ๅฐไธบ30ๅบฆ { bFound = true; float len = getDists(idxC, seedA, seedB); // ๅ–็‚นCไธŽseedAๅ’ŒseedBๅฝขๆˆ็š„ไธค่พนไน‹ๅ’Œๆœ€ๅฐ if (len < minLen){ minLen = len; seedC = idxC; } } j++; } if(bFound){ delete[] nnidx; delete[] dists; //TODO ๆญคๅค„้œ€่ฆๆต‹่ฏ•้ข็š„ๆณ•็Ÿขๆ˜ฏๅฆไธ€่‡ด pFace = new CTriangle(seedA, seedB, seedC); //pFace->setTriVertexs(seedA, seedB, seedC); setVertexUsed(seedA); m_front.addVertex(seedA); setVertexUsed(seedB); m_front.addVertex(seedB); setVertexUsed(seedC); m_front.addVertex(seedC); return true; } } seedA = getFirstUnusedPt(seedA); if (seedA == firstSeed) break; } delete[] nnidx; delete[] dists; return false; } bool CIPDMesh::getBestPt( FrontEdgeIterator& itEdge, int& bestIdx, const int& K ) { CFrontEdge frontEdge = *itEdge; int idxA = frontEdge.getA(), idxB = frontEdge.getB(); float* ptA = m_ps->m_point[idxA], * ptB = m_ps->m_point[idxB]; float midAB[3] = { (ptA[0]+ptB[0])/2.0f, (ptA[1]+ptB[1])/2.0f, (ptA[2]+ptB[2])/2.0f }; ANNidxArray nnIdx = new ANNidx[K]; ANNdistArray dists = new ANNdist[K]; m_ps->m_kdTree->annkSearch(midAB, K, nnIdx, dists); delete[] dists; float minWeight = FLT_MAX; int idxC = -1; //#define MINTRIANGEL 0.1339745962 // 1-cos(30') ๅณไธ‰่ง’ๅฝขๆœ€ๅฐๅ†…่ง’่ฆๅคงไบŽ30' //#define MINTRIANGEL 0.0603073792 // 1-cos(20') ๅณไธ‰่ง’ๅฝขๆœ€ๅฐๅ†…่ง’่ฆๅคงไบŽ20' #define MINTRIANGEL 0.09369221296335 // 1-cos(25') ๅณไธ‰่ง’ๅฝขๆœ€ๅฐๅ†…่ง’่ฆๅคงไบŽ25' #define MAXDIHEDRALANGEL 1.5 // 1-cos(150') ๅณไบŒ้ข่ง’ๆœ€ๅคงไธบ150' //#define MAXDIHEDRALANGEL 1.8660254 // 1-cos(150') ๅณไบŒ้ข่ง’ๆœ€ๅคงไธบ150' int idxPre = frontEdge.getOppPoint(); CPlane prePlane, nextPlane; int idxApre = -1, idxBnext = -1; getPreNextIdx(idxApre, idxBnext, itEdge); getPlanes(prePlane, nextPlane, idxA, idxB, idxPre, idxApre, idxBnext); for (int i=0; i < K ; i++) { int idxCur = nnIdx[i]; if ( INPOINT == m_bPointUsed[idxCur] || idxCur == idxA || idxCur == idxB || idxCur == idxPre) continue; //TODO ่ฟ˜้œ€่ฆไฝฟ็”จไบŒ้ข่ง’ๆฅๅˆคๆ–ญ //TODO ๅฝ“ๅŒๆ—ถๅญ˜ๅœจไธคไธชๆณขๅ‰็‚นๅ…ถๆƒ้‡ไธ€ๆ ท๏ผŒๅฆ‚ไฝ•้€‰ๆ‹ฉ๏ผŸ๏ผˆๅฆ‚ไฝ•ไฟ่ฏไธ็›ธไบคๆˆ–่€…ไธ€ๆก่พนๅช่ƒฝ่ฟžๆŽฅไธคไธชไธ‰่ง’ๅฝข๏ผ‰ float minAngel = getMinTriAngel(idxA, idxB, idxCur); // ่ฆๆฑ‚ๆœ€ๅฐๅ†…่ง’่ฆๅคงไบŽๆŒ‡ๅฎšๅบฆๆ•ฐ float dihedralAngel = getDihedralAngel(frontEdge, idxCur);// ่ฆๆฑ‚ไบŒ้ข่ง’่ฆๅฐไบŽๆŒ‡ๅฎšๅบฆๆ•ฐ if (minAngel > MINTRIANGEL && dihedralAngel < MAXDIHEDRALANGEL && isBtwPlanes(prePlane, nextPlane, frontEdge, idxCur)){ //if (minAngel > MINTRIANGEL){ // float weight = getWeightTri(frontEdge, idxCur, 4.0); // ๆต‹่ฏ•ไฝฟ็”จ //TODO: ๅฏนไบŽๆณขๅ‰่พนไธŠ็š„้กถ็‚น ่ฆๆ ผๅค–ๆณจๆ„๏ผŒ่ฟ˜่ฆๅˆคๆ–ญ่ฟžๆŽฅ็‚นๆ˜ฏๅฆๅœจ็‚น็š„ๅค–ๆต‹ float fPointUsedTimes = m_bPointUsed[idxCur]; float weight = getWeightTri(frontEdge, idxCur, 8.0, dihedralAngel) ;//+ (float)m_bPointUsed[idxCur]; if (FRONTPOINT == m_bPointUsed[idxCur]) weight -= 2; if (minWeight > weight){ minWeight = weight; idxC = idxCur; } } } delete[] nnIdx; if (idxC == -1) return false; else { bestIdx = idxC; return true; } } void CIPDMesh::start(){ //#define OUTFACEFILE #ifdef OUTFACEFILE const char* facePath = "face.ply"; ofstream faceFile(facePath); if (!faceFile) return ; #endif FrontEdgeIterator itEdge; int vertIdx; int faceN = 0; while (true){ while (m_front.getActiveEdge(itEdge)) { CEdge edge = *itEdge; //bool pivoted = getBestPt(itEdge, vertIdx, 8); bool bFrontPoint = false; bool pivoted = getCandidatePoint(itEdge, vertIdx, bFrontPoint, 8); if (pivoted){ faceN++; CTriangle* newTri = new CTriangle; m_front.join(*itEdge, vertIdx, m_bPointUsed, newTri); newTri->calcNorm(m_ps); m_faceVects.push_back(newTri); #ifdef OUTFACEFILE faceFile<< newTri->getA()<<" "<<newTri->getB()<<" "<<newTri->getC()<<"\n"; #endif }else{ //itEdge->setBoundary(); m_front.setBoundary(*itEdge); } if (faceN %500 == 0) pView->draw(); // Sleep(200); } CTriangle* pFace = NULL; if (findSeedTriangle2(pFace)){ pFace->calcNorm(m_ps); m_faceVects.push_back(pFace); faceN++; CFrontEdge a(pFace->getA(), pFace->getB(), pFace->getC(), pFace), b(pFace->getB(), pFace->getC(), pFace->getA(), pFace), c(pFace->getC(), pFace->getA(), pFace->getB(), pFace); m_front.addEdge(a); m_front.addEdge(b); m_front.addEdge(c); }else{ return ; } } #ifdef OUTFACEFILE faceFile.close(); #endif } bool CIPDMesh::isInPlay( int idx, int edgeA, int edgeB, int edgeC, int edgePre, int edgeNext ) { float* ptA = m_ps->m_point[edgeA], * ptB = m_ps->m_point[edgeB], * ptC = m_ps->m_point[edgeC]; float oABC[3] = { (ptA[0]+ptB[0]+ptC[0])/3.0f, (ptA[1]+ptB[1]+ptC[1])/3.0f, (ptA[2]+ptB[2]+ptC[2])/3.0f }; return false; } int CIPDMesh::getPlanes( CPlane& prePlane, CPlane& nextPlane, int eA, int eB, int tC, int ePre, int eNext ) { float* ptA = m_ps->m_point[eA], * ptB = m_ps->m_point[eB], * ptC = m_ps->m_point[tC]; float oABC[3] = { (ptA[0]+ptB[0]+ptC[0])/3.0f, (ptA[1]+ptB[1]+ptC[1])/3.0f, (ptA[2]+ptB[2]+ptC[2])/3.0f }; vect3f vAB( ptB[0] - ptA[0], ptB[1] - ptA[1], ptB[2] - ptA[2]), vAC( ptC[0] - ptA[0], ptC[1] - ptA[1], ptC[2] - ptA[2]); vAB.cross(vAC); // ไธŽABC้ข็›ธๅž‚็›ด vect3f nABC = vAB; // ้ขABC็š„ๆณ•ๅ‘้‡ vect3f vOA( ptA[0] - oABC[0], ptA[1] - oABC[1], ptA[2] - oABC[2] ); vAB.cross(vOA); // ้ขOAn็š„ๆณ•ๅ‘้‡ prePlane.setPlane(vAB, ptA); // ้ขOAn if (ePre != -1){ float* ptPre = m_ps->m_point[ePre]; if (prePlane.iSameSide(ptB, ptPre) > 0){ vect3f nAPn = nABC; vect3f AP( ptPre[0] - ptA[0], ptPre[1] - ptA[1], ptPre[2] - ptA[2] ); nAPn.cross(AP); prePlane.setPlane(nAPn, ptA);// ๅนณ้ขAPren } } vect3f vOB ( ptB[0] - oABC[0], ptB[1] - oABC[1], ptB[2] - oABC[2] ); vOB.cross(nABC); // ้ขOBn็š„ๆณ•ๅ‘้‡ nextPlane.setPlane(vOB, ptB); if (eNext != -1){ float* ptNext = m_ps->m_point[eNext]; if (nextPlane.iSameSide(ptA, ptNext) > 0){ vect3f BN( ptNext[0]-ptB[0], ptNext[1]-ptB[1], ptNext[2]-ptB[2] ); BN.cross(nABC); nextPlane.setPlane(BN, ptB); } } return 2; } bool CIPDMesh::getCandidatePoint(FrontEdgeIterator& itEdge, int& bestIdx, bool& bFrontPoint, const int& K){ int idxPre = -1, idxNext = -1; getPreNextIdx(idxPre, idxNext, itEdge); //TODO ๆœชๅˆคๆ–ญ็‚นๅœจ่พน็š„ๅ‰ๆ–น่ฟ˜ๆ˜ฏๅŽๆ–น int idxA = itEdge->getA(), idxB = itEdge->getB(), idxC = itEdge->getOppPoint(); float* ptA = m_ps->m_point[idxA], * ptB = m_ps->m_point[idxB], * ptC = m_ps->m_point[idxC]; float eAB[3] = Edge(ptA,ptB); float nABC[3], nABn[3]; itEdge->getPreTriangle()->getNorm(nABC); eCross(nABn, eAB, nABC); CPlane planeABn(nABn, ptA); if (idxPre != -1){ float* ptP = m_ps->m_point[idxPre]; if (planeABn.iSameSide(ptP, ptC) <= 0) { float angelBAP = getAngel(idxPre, itEdge->getA(), itEdge->getB()); if (angelBAP > COS30 && angelBAP < COS90){ float angelABP = getAngel(itEdge->getA(), itEdge->getB(), idxPre); float angelAPB = getAngel(itEdge->getA(), idxPre, itEdge->getB()); angelABP = min(angelABP, angelBAP); angelAPB = min(angelAPB, angelABP); if (angelAPB > COS20){ bestIdx = idxPre; bFrontPoint = true; return true; } } } } if (idxNext != -1){ float* ptN = m_ps->m_point[idxNext]; if (planeABn.iSameSide(ptN, ptC) <= 0){ float angelABN = getAngel(itEdge->getA(), itEdge->getB(), idxNext); if (angelABN > COS30 && angelABN < COS90){ float angelBAN = getAngel(itEdge->getB(), itEdge->getA(), idxNext); float angelANB = getAngel(itEdge->getA(), idxNext, itEdge->getB()); angelBAN = min(angelBAN, angelABN); angelANB = min(angelANB, angelBAN); if (angelANB){ bestIdx = idxNext; bFrontPoint = true; return true; } } } } float midAB[3] = { (ptA[0]+ptB[0])/2.0f, (ptA[1]+ptB[1])/2.0f, (ptA[2]+ptB[2])/2.0f }; ANNidxArray nnIdx = new ANNidx[K]; ANNdistArray dists = new ANNdist[K]; m_ps->m_kdTree->annkSearch(midAB, K, nnIdx, dists); delete[] dists; int vBestIdx = -1; float minWeight = FLT_MAX; for (int i = 0; i < K; ++i){ int idxCan = nnIdx[i]; if (INPOINT == m_bPointUsed[idxCan] || idxA == idxCan || idxB == idxCan || idxC == idxCan) continue; float dihedralAngel = m_ps->getDihedralAngel(idxC, idxA, idxB, idxCan); if (dihedralAngel > COS90) continue; float minTriAngel = m_ps->getMinTriAngel(idxA, idxB, idxCan); if (FRONTPOINT == m_bPointUsed[idxCan] && minTriAngel > COS15){ float weight = getIPDWeightTri(idxC, idxA, idxB, idxCan)-2; if (minWeight > weight){ minWeight = weight; vBestIdx = idxCan; } } else if (UNUSEDPOINT == m_bPointUsed[idxCan] && minTriAngel > COS25){ float weight = getIPDWeightTri(idxC, idxA, idxB, idxCan); if (minWeight > weight){ minWeight = weight; vBestIdx = idxCan; } } } delete[] nnIdx; if (vBestIdx != -1){ bestIdx = vBestIdx; bFrontPoint = (FRONTPOINT == m_bPointUsed[vBestIdx]); return true; } return false; }
[ "huangchunkuangke@e87e5053-baee-b2b1-302d-3646b6e6cf75" ]
[ [ [ 1, 1553 ] ] ]
04a3547c302035dc8e7e8eb1d1eabfb1b9d536aa
cb621dee2a0f09a9a2d5d14ffaac7df0cad666a0
/uri/basic_uri.hpp
51e22f8f06c092e83a1c24b3c78e1511944515dc
[ "BSL-1.0" ]
permissive
ssiloti/http
a15fb43c94c823779f11fb02e147f023ca77c932
9cdeaa5cf2ef2848238c6e4c499ebf80e136ba7e
refs/heads/master
2021-01-01T19:10:36.886248
2011-11-07T19:29:22
2011-11-07T19:29:22
1,021,325
0
1
null
null
null
null
UTF-8
C++
false
false
4,020
hpp
#ifndef URI_BASIC_URI_HPP #define URI_BASIC_URI_HPP // Copyright 2009 Dean Michael Berris, Jeroen Habraken. // Copyright 2011 Steven Siloti. // 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) #include <uri/basic_authority.hpp> namespace uri { class invalid_uri : public std::exception { }; template <class String> struct basic_uri { typedef String string_type; basic_uri() {} basic_uri(string_type const& uri); basic_uri(const typename string_type::value_type* uri); #if 0 basic_uri& operator=(basic_uri<string_type> other) { other.swap(*this); return *this; } basic_uri& operator=(string_type const& uri) { return *this = basic_uri<string_type>(uri); } #endif #if 0 void swap(basic_uri<string_type>& other) { using std::swap; swap(other.parts_, parts_); } bool operator==(basic_uri<string_type> const& other) const { return scheme == other.scheme && authority == other.authority && path == other.path && query == other.query && fragment == other.fragment; } #endif bool operator!=(basic_uri<string_type> const& other) const { return !(*this == other); } string_type scheme; boost::optional<basic_authority<string_type> > authority; string_type path; boost::optional<string_type> query; boost::optional<string_type> fragment; }; namespace detail { template <class String> struct basic_uri_tuple { typedef String string_type; typedef typename boost::fusion::tuple< string_type&, // scheme boost::fusion::tuple< boost::optional<basic_authority<string_type> >&, string_type& // path >, // hier_part boost::optional<string_type>&, // query boost::optional<string_type>& // fragment > type; }; template <class String> struct const_basic_uri_tuple { typedef String string_type; typedef typename boost::fusion::tuple< const string_type&, // scheme const boost::optional<basic_authority<string_type> >&, const string_type&, // path const boost::optional<string_type>&, // query const boost::optional<string_type>& // fragment > type; }; } } // namespace uri namespace boost { namespace spirit { namespace traits { template <typename String> struct transform_attribute< uri::basic_uri<String>, typename uri::detail::basic_uri_tuple<String>::type, boost::spirit::qi::domain > { typedef typename uri::detail::basic_uri_tuple<String>::type type; static type pre(uri::basic_uri<String>& exposed) { return type( exposed.scheme, boost::fusion::tie( exposed.authority, exposed.path ), exposed.query, exposed.fragment ); } static void post(uri::basic_uri<String>&, type const&) { } static void fail(uri::basic_uri<String>& val) { } }; template <typename String> struct transform_attribute< const uri::basic_uri<String>, typename uri::detail::const_basic_uri_tuple<String>::type, boost::spirit::karma::domain > { typedef typename uri::detail::const_basic_uri_tuple<String>::type type; static type pre(const uri::basic_uri<String>& exposed) { return type( exposed.scheme, exposed.authority, exposed.path, exposed.query, exposed.fragment ); } }; } // namespace traits } // namespace spirit } // namespace boost #endif
[ [ [ 1, 158 ] ] ]
51d8dcb9ba537a93223fbb02afd0b85e18a0af7a
cecdfda53e1c15e7bd667440cf5bf8db4b3d3e55
/map_template_generator/MapSystem/MapSystem_structs.h
e47ec8a5561bdd41f38ef3e7333c8bf0a5ce2fce
[]
no_license
omaskery/mini-stalker
f9f8713cf6547ccb9b5e51f78dfb65a4ae638cda
954e8fce9e16740431743f020c6ddbc866e69002
refs/heads/master
2021-01-23T13:29:26.557156
2007-08-04T12:44:52
2007-08-04T12:44:52
33,090,577
1
0
null
null
null
null
UTF-8
C++
false
false
711
h
struct area { int x,y,w,h; }; struct areas { std::vector<area> a; std::string name; bool collision(int x, int y, int w, int h) { for(unsigned int i = 0; i < a.size(); ++i) { area &ar = a[i]; if(x >= ar.x && x <= ar.x+ar.w || x+w >= ar.x && x+w <= ar.x+ar.w) { if(y >= ar.y && y <= ar.y+ar.h || y+h >= ar.y && y+h <= ar.y+ar.h) { return true; } } } return false; } }; struct tile { SDL_Surface *sprite; std::string file; int ID; }; struct position { int x,y,dataA,dataB; }; struct map { std::vector<position> pos; std::vector<tile> sprites; std::vector<areas> zones; std::vector<int> tiles; int w,h; };
[ "ollie.the.pie.lord@823218a8-ad34-0410-91fc-f9441fec9dcb" ]
[ [ [ 1, 49 ] ] ]
ee189c32f368e81772d2daf9a44218a353ef967d
eaa64a4b73fe76125d34177c33e1aadedfaf4e46
/src/videocapture/RGBVideoFrameFactory.hpp
16399a8457c8302a6d373f2fa27a514693f09541
[ "Apache-2.0" ]
permissive
brianfcoleman/libvideocapture
1d856f3f8658a7d834fad5d094927783092897bc
3357c0d31603c94890960676a38253275a52c1b3
refs/heads/master
2020-04-28T01:55:24.483921
2010-10-10T20:23:32
2010-10-10T20:23:32
35,434,467
0
1
null
null
null
null
UTF-8
C++
false
false
658
hpp
#ifndef VIDEO_CAPTURE_RGB_VIDEO_FRAME_FACTORY_H #define VIDEO_CAPTURE_RGB_VIDEO_FRAME_FACTORY_H #include "boost/shared_ptr.hpp" namespace VideoCapture { class RGBVideoFrame; class RGBVideoFormat; class RGBVideoFrameFactory { public: typedef RGBVideoFrame SampleDataType; typedef boost::shared_ptr<RGBVideoFrame> SampleDataSharedPtr; RGBVideoFrameFactory(); SampleDataSharedPtr createSampleData(const RGBVideoFormat& videoFormat); SampleDataSharedPtr operator()(const RGBVideoFormat& videoFormat) { return createSampleData(videoFormat); } }; } // VideoCapture #endif // VIDEO_CAPTURE_RGB_VIDEO_FRAME_FACTORY_H
[ [ [ 1, 25 ] ] ]
7c1e52d0d847fe9e5dffe52610acf4bc1b314ecb
f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0
/GameClient/Application.h
e37df754f56d8168dd40e0ce0da33972b6f76f66
[]
no_license
lxinhcn/starworld
79ed06ca49d4064307ae73156574932d6185dbab
86eb0fb8bd268994454b0cfe6419ffef3fc0fc80
refs/heads/master
2021-01-10T07:43:51.858394
2010-09-15T02:38:48
2010-09-15T02:38:48
47,859,019
2
1
null
null
null
null
UTF-8
C++
false
false
694
h
#pragma once class CClientMap; #include "Canvas.h" class CApplication { friend struct CreateStatic< CApplication >; private: CApplication(void); virtual ~CApplication(void); public: bool Initialize(); void Run(); void UnInitialize(); HGE* operator->(){ return m_hge; } HGE* getEngine(){ return m_hge; } IMessageQueue* GetMessageQueue(){ return m_pMessageQueue; } protected: bool UpdateLogic( float fDelta ); void Render(); private: static bool RenderFunc(); static bool FrameFunc(); private: HGE *m_hge; CClientMap *m_pMap; IMessageQueue *m_pMessageQueue; }; typedef SingletonHolder< CApplication, CreateStatic > Application;
[ "albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c" ]
[ [ [ 1, 40 ] ] ]
2a5b99b608891f8a1d50b6b3692114fd379b0b91
110f8081090ba9591d295d617a55a674467d127e
/tests/HTTPClientTest.cpp
9a0c929da22486162bc805059697d04e9d7b7c3a
[]
no_license
rayfill/cpplib
617bcf04368a2db70aea8b9418a45d7fd187d8c2
bc37fbf0732141d0107dd93bcf5e0b31f0d078ca
refs/heads/master
2021-01-25T03:49:26.965162
2011-07-17T15:19:11
2011-07-17T15:19:11
783,979
1
0
null
null
null
null
UTF-8
C++
false
false
1,838
cpp
#include <iostream> #include <fstream> #include <net/HTTPClient.hpp> #include <util/hash/SHA1.hpp> #include <text/LexicalCast.hpp> #include <iomanip> int usage(int argc, char** argv) { std::cout << "usage: " << argv[0] << " +[target_url]" << std::endl; return 1; } int main(int argc, char** argv) { if (argc < 3) return usage(argc, argv); const long timeout = lexicalCast<long>(argv[1]); SocketModule Module; try { for (int args = 2; args < argc; ++args) { std::string targetResource(argv[args]); HTTPClient<> client; client.setKeepAliveTime(300); client.setTimeout(timeout, 1); client.setUserAgent("Mozilla/4.0 (compatible; MSIE 6.0; " "Windows NT 5.1; SV1; .NET CLR 1.0.3705; " ".NET CLR 1.1.4322)"); client.setAcceptEncoding(""); client.addAcceptLanguage("ja"); client.addAcceptLanguage("en"); HTTPResult<> result = client.getResource(targetResource.c_str()); std::cout << "headers: " << result.getResponseHeaders().toString() << std::endl; std::vector<unsigned char> resource = result.getResource(); std::ofstream ofs("savefile.html", std::ios::out | std::ios::binary | std::ios::trunc); std::vector<unsigned char>::const_iterator itor = resource.begin(); while (itor != resource.end()) ofs << *itor++; ofs.close(); } } catch (ResponseError& e) { std::cout << " raise exception. reason: " << e.what() << std::endl; } catch (ConnectionClosedException& /*e*/) { std::cout << "connection closed by forign host." << std::endl; } catch (SocketException& /*e*/) { std::cout << "target server is not found. "; } catch (std::exception& e) { std::cout << "raise exception. reason: " << e.what() << std::endl; } return 0; }
[ "alfeim@287b3242-7fab-264f-8401-8509467ab285" ]
[ [ [ 1, 71 ] ] ]
09f7ea8613331f4f4134ef4fc215201b3fd0aa23
33f59b1ba6b12c2dd3080b24830331c37bba9fe2
/Depend/Foundation/Interpolation/Wm4IntpQdrNonuniform2.h
ad6f8dada6cab33ef522e1051389f318dbcfbc8e
[]
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
2,703
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 WM4INTPQUADRATICNONUNIFORM2_H #define WM4INTPQUADRATICNONUNIFORM2_H // Quadratic interpolation of a network of triangles whose vertices are of // the form (x,y,f(x,y)). This code is an implementation of the algorithm // found in // // Zoltan J. Cendes and Steven H. Wong, // C1 quadratic interpolation over arbitrary point sets, // IEEE Computer Graphics & Applications, // pp. 8-16, 1987 #include "Wm4FoundationLIB.h" #include "Wm4Delaunay2.h" namespace Wm4 { template <class Real> class WM4_FOUNDATION_ITEM IntpQdrNonuniform2 { public: // Construction and destruction. If you want IntpQdrNonuniform2 to // delete the input array during destruction, set bOwner to 'true'. // Otherwise, you own the array and must delete it yourself. // // The first constructor requires you to specify function values F and // first-order partial derivative values Fx and Fy. The second // constructor requires only F, but the Fx and Fy values are estimated // at the sample points. IntpQdrNonuniform2 (const Delaunay2<Real>& rkDT, Real* afF, Real* afFx, Real* afFy, bool bOwner); IntpQdrNonuniform2 (const Delaunay2<Real>& rkDT, Real* afF, bool bOwner); ~IntpQdrNonuniform2 (); // Quadratic interpolation. The return value is 'true' if and only if the // input point is in the convex hull of the input vertices, in which case // the interpolation is valid. bool Evaluate (const Vector2<Real>& rkP, Real& rfF, Real& rfFx, Real& rfFy); private: class WM4_FOUNDATION_ITEM TriangleData { public: Vector2<Real> Center; Vector2<Real> Intersect[3]; Real Coeff[19]; }; class WM4_FOUNDATION_ITEM Jet { public: Real F, Fx, Fy; }; const Delaunay2<Real>& m_rkDT; Real* m_afF; Real* m_afFx; Real* m_afFy; TriangleData* m_akTData; // triangle data bool m_bFOwner, m_bFxFyOwner; void EstimateDerivatives (); void ProcessTriangles (); void ComputeCrossEdgeIntersections (int iT); void ComputeCoefficients (int iT); }; typedef IntpQdrNonuniform2<float> IntpQdrNonuniform2f; typedef IntpQdrNonuniform2<double> IntpQdrNonuniform2d; } #endif
[ "yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa" ]
[ [ [ 1, 88 ] ] ]
c40eec2e72ea5ed39f7fb7e5bf6c2f01a963c541
c70941413b8f7bf90173533115c148411c868bad
/plugins/AS3Plugin/src/vtxas3Mouse.cpp
44eff938f2c223903b0b5ad316de4b291b934317
[]
no_license
cnsuhao/vektrix
ac6e028dca066aad4f942b8d9eb73665853fbbbe
9b8c5fa7119ff7f3dc80fb05b7cdba335cf02c1a
refs/heads/master
2021-06-23T11:28:34.907098
2011-03-27T17:39:37
2011-03-27T17:39:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,615
cpp
/* ----------------------------------------------------------------------------- This source file is part of "vektrix" (the rich media and vector graphics rendering library) For the latest info, see http://www.fuse-software.com/ Copyright (c) 2009-2010 Fuse-Software (tm) 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 "vtxas3Mouse.h" #include "vtxOpSysHelper.h" namespace vtx { namespace as3 { //----------------------------------------------------------------------- MouseClass::MouseClass(avmplus::VTable* cvtable) : ClassClosure(cvtable) { AvmAssert(traits()->getSizeOfInstance() == sizeof(MouseClass)); createVanillaPrototype(); } //----------------------------------------------------------------------- avmplus::ScriptObject* MouseClass::createInstance(avmplus::VTable* ivtable, avmplus::ScriptObject* prototype) { return new (core()->GetGC(), ivtable->getExtraSize()) Mouse(ivtable, prototype); } //----------------------------------------------------------------------- void MouseClass::hide() { OpSysHelper::hideMouseCursor(); } //----------------------------------------------------------------------- void MouseClass::show() { OpSysHelper::showMouseCursor(); } //----------------------------------------------------------------------- Mouse::Mouse(avmplus::VTable* vtable, avmplus::ScriptObject* prototype) : avmplus::ScriptObject(vtable, prototype) { } //----------------------------------------------------------------------- }}
[ "stonecold_@9773a11d-1121-4470-82d2-da89bd4a628a" ]
[ [ [ 1, 63 ] ] ]
895454670f07d50cf26d6ebf2712d97bbf296df2
b73f27ba54ad98fa4314a79f2afbaee638cf13f0
/projects/FilterSetting/WebContentRecord.h
4e4007d76e5fa068e8e0f6f84956942692ba25ca
[]
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
1,701
h
// WebContentRecord.h : CWebContentRecord ็š„ๅฃฐๆ˜Ž #pragma once #include "resource.h" // ไธป็ฌฆๅท #include "FilterSetting.h" // CWebContentRecord // ่ฎฐๅฝ•็ฝ‘็ซ™ใ€ๆœ็ดข็ญ‰็š„ๆœ็ดขๆฌกๆ•ฐ class ATL_NO_VTABLE CWebContentRecord : public CComObjectRootEx<CComSingleThreadModel>, public CComCoClass<CWebContentRecord, &CLSID_WebContentRecord>, public ISupportErrorInfo, public IDispatchImpl<IWebContentRecord, &IID_IWebContentRecord, &LIBID_FilterSettingLib, /*wMajor =*/ 1, /*wMinor =*/ 0> { public: CWebContentRecord() { } DECLARE_REGISTRY_RESOURCEID(IDR_WEBCONTENTRECORD) BEGIN_COM_MAP(CWebContentRecord) COM_INTERFACE_ENTRY(IWebContentRecord) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY(ISupportErrorInfo) END_COM_MAP() // ISupportsErrorInfo STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid); DECLARE_PROTECT_FINAL_CONSTRUCT() HRESULT FinalConstruct() { return S_OK; } void FinalRelease() { } public: // ็”จไบŽๅค„็†ๆœ็ดขๅ…ณ้”ฎๅญ— STDMETHOD(SearchKeyword)(BSTR keyword, LONG searchEngine); STDMETHOD(GetFirstSearchKeyword)(BSTR* keyword, LONG* times, LONG* searchEngine, LONG* timeHighPart, LONG* timeLowPart); STDMETHOD(GetNextSearchKeyword)(BSTR cur, BSTR* next, LONG* times, LONG* searchEngine, LONG* timeHighPart, LONG* timeLowPart); // ๅค„็†็ฝ‘็ซ™ STDMETHOD(GetFirstWebsite)(BSTR* NAME, LONG* times, LONG* high, LONG* low); STDMETHOD(GetNextWebSite)(BSTR cur, BSTR* next, LONG* times, LONG* hight, LONG* low); STDMETHOD(clearAll)(void); STDMETHOD(clearWebsites)(void); STDMETHOD(clearSearchword)(void); }; OBJECT_ENTRY_AUTO(__uuidof(WebContentRecord), CWebContentRecord)
[ [ [ 1, 59 ] ] ]
92847422acd54b0b9d57fd5f883a5fc58b7ca3eb
f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0
/GameSDK/SLB/include/SLB/SLB.hpp
5d7793742e0a00a48d8cfae59b24307a8569dda9
[]
no_license
lxinhcn/starworld
79ed06ca49d4064307ae73156574932d6185dbab
86eb0fb8bd268994454b0cfe6419ffef3fc0fc80
refs/heads/master
2021-01-10T07:43:51.858394
2010-09-15T02:38:48
2010-09-15T02:38:48
47,859,019
2
1
null
null
null
null
UTF-8
C++
false
false
1,461
hpp
/* SLB - Simple Lua Binder Copyright (C) 2007 Jose L. Hidalgo Valiรฑo (PpluX) 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 Jose L. Hidalgo (www.pplux.com) [email protected] */ #ifndef __SLB__ #define __SLB__ #include "Manager.hpp" #include "ClassInfo.hpp" #include "PushGet.hpp" #include "Type.hpp" #include "Table.hpp" #include "Value.hpp" #include "Class.hpp" #include "LuaObject.h" #include "Hybrid.hpp" #include "StatefulHybrid.hpp" #include "Script.hpp" #include "SPP.hpp" // just for help.... #define SLB_ON_LOAD( FuncName ) \ SPP_STATIC_BLOCK( FuncName(); ) #define SLB_abs_index(L, i) ((i) > 0 || (i) <= LUA_REGISTRYINDEX ? (i) : \ lua_gettop(L) + (i) + 1) #endif
[ "albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c" ]
[ [ [ 1, 47 ] ] ]
3ca262495f2a6b46aac5e80498187aedd025ae80
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/mangalore/fsm/state.cc
3dcdee7964a4fcfec241a55bedfab93319930509
[]
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
1,197
cc
//------------------------------------------------------------------------------ // fsm/state.cc // (C) 2005 RadonLabs GmbH //------------------------------------------------------------------------------ #include "fsm/state.h" namespace FSM { ImplementRtti(FSM::State, Foundation::RefCounted); //------------------------------------------------------------------------------ /** */ State::State(const nString& name) : name(name) { // empty } //------------------------------------------------------------------------------ /** */ State::~State() { // empty } //------------------------------------------------------------------------------ /** */ void State::Trigger() { // empty } //------------------------------------------------------------------------------ /** */ void State::OnEnter() { // empty } //------------------------------------------------------------------------------ /** */ void State::OnLeave() { // empty } //------------------------------------------------------------------------------ /** */ const nString& State::GetName() const { return this->name; } } // namespace FSM
[ "BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 63 ] ] ]
4c17c7ad5013443d4b4f0e4f0ed5de1a05f6f4ed
faacd0003e0c749daea18398b064e16363ea8340
/modules/mp3player/database.h
cd522ce3d9e2b5e2adc5c4058707e569b9907487
[]
no_license
yjfcool/lyxcar
355f7a4df7e4f19fea733d2cd4fee968ffdf65af
750be6c984de694d7c60b5a515c4eb02c3e8c723
refs/heads/master
2016-09-10T10:18:56.638922
2009-09-29T06:03:19
2009-09-29T06:03:19
42,575,701
0
0
null
null
null
null
UTF-8
C++
false
false
1,595
h
/* * Copyright (C) 2008-2009 Pavlov Denis * * Comments unavailable. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or any later version. * */ #ifndef __DATABASE_H__ #define __DATABASE_H__ #include <QtSql/QSqlDatabase> #include <QtSql/QSqlQuery> #include <QObject> #include <QDebug> #include <QStringList> #include <QtCore> typedef struct ATrackData { QString fileName; QString artist; QString album; QString trackName; QString duration; } ATrackData; class mp3playerDatabase : public QObject { Q_OBJECT public: mp3playerDatabase(QObject *parent = 0); ~mp3playerDatabase(); void addTrack(QString fileName, QString artist, QString album, QString trackName, QString duration); void updateTrack(QString fileName, QString artist, QString album, QString trackName, QString duration); bool ifExists(QString fileName); ATrackData getTrack(QString fileName); void removeTrack(QString file) {} void updateDir(QDir directory) {} void rescan() {} QString getFileName(QString artist, QString album, QString trackName) { return QString(); } QString getArtistByFile(QString file) { return QString(); } QString getArtistByTrack(QString album, QString trackName) { return QString(); } QStringList getTracksList(QString artist, QString album) { return QStringList(); } bool isOK() { return m_db_ok; } private: QSqlDatabase m_db; bool m_db_ok; }; #endif // __DATABASE_H__
[ "futurelink.vl@9e60f810-e830-11dd-9b7c-bbba4c9295f9" ]
[ [ [ 1, 58 ] ] ]
19d3bfa87c297329c591bdbf10c601e3eae95446
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/mpl/test/back.cpp
9c13413e69f58da114f7b78a42994ef707396fb3
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
793
cpp
// Copyright Aleksey Gurtovoy 2000-2004 // // Distributed under the Boost Software License,Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Source: /cvsroot/boost/boost/libs/mpl/test/back.cpp,v $ // $Date: 2004/09/02 15:41:35 $ // $Revision: 1.4 $ #include <boost/mpl/back.hpp> #include <boost/mpl/range_c.hpp> #include <boost/mpl/aux_/test.hpp> template< typename Seq, int value > struct back_test { typedef typename back<Seq>::type t; MPL_ASSERT_RELATION( t::value, ==, value ); }; MPL_TEST_CASE() { back_test< range_c<int,0,1>, 0 >(); back_test< range_c<int,0,10>, 9 >(); back_test< range_c<int,-10,0>, -1 >(); }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 29 ] ] ]
c1466947bf93a72a2df3e370190a0c22fbb777cb
402829c0daadea441a0b81e70bdb942fdc6f444e
/Graph_AdjacentList/stdafx.cpp
fdc00fa9e46adbf1f04c281825b7aedd4cfe8189
[]
no_license
huangyingw/Graph_AdjacentList
1d85644547ba09a6feecf3644d3945ea3b376a16
f7799e1ddeab8a2d5bcde7e30120700644c69f3e
refs/heads/master
2021-01-19T04:52:31.101994
2010-11-10T03:03:46
2010-11-10T03:03:46
2,538,367
0
1
null
null
null
null
UTF-8
C++
false
false
305
cpp
// stdafx.cpp : source file that includes just the standard includes // Graph_AdjacentList.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
[ [ [ 1, 8 ] ] ]
92342b1258777d91f241e5d0ad858202cd12315a
c6f4fe2766815616b37beccf07db82c0da27e6c1
/RotatingBlade.h
02d32461e869abc98e3831d7298f64a1f8801bf2
[]
no_license
fragoulis/gpm-sem1-spacegame
c600f300046c054f7ab3cbf7193ccaad1503ca09
85bdfb5b62e2964588f41d03a295b2431ff9689f
refs/heads/master
2023-06-09T03:43:53.175249
2007-12-13T03:03:30
2007-12-13T03:03:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
961
h
#pragma once #include "Barrier.h" #include "Blade.h" #include "BladePoll.h" #include "BladeBase.h" class RotatingBlade: public Barrier { public: // This indicates how much should the barrier move before // it goes out of sight [basicaly this is height of the bbox] static float DistToDie; private: // The blade of the system Blade m_oBlade; // The base of the system BladePoll m_oPoll; BladeBase m_oBase; public: /** * Constructor */ RotatingBlade(); /** * Accessor methods for the system's objects * Note: there are returning non-const references because I have not * found a way around not doing that for the moment */ Blade& getBlade() { return m_oBlade; } BladePoll& getBladePoll() { return m_oPoll; } BladeBase& getBladeBase() { return m_oBase; } /** * Renders the whole blade system */ void render(); };
[ "john.fragkoulis@201bd241-053d-0410-948a-418211174e54" ]
[ [ [ 1, 42 ] ] ]
581594a3d163fb5e570662a7ec83422a737b369f
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/ClientShellDLL/ClientShellShared/GadgetDisabler.h
7a33a43faf9032e816e7a1839000c4acf41eafa3
[]
no_license
rickyharis39/nolf2
ba0b56e2abb076e60d97fc7a2a8ee7be4394266c
0da0603dc961e73ac734ff365bfbfb8abb9b9b04
refs/heads/master
2021-01-01T17:21:00.678517
2011-07-23T12:11:19
2011-07-23T12:11:19
38,495,312
1
0
null
null
null
null
UTF-8
C++
false
false
1,260
h
// ----------------------------------------------------------------------- // // // MODULE : GadgetDisabler.h // // PURPOSE : The GadgetDisabler object // // CREATED : 8/30/01 // // (c) 2001 Monolith Productions, Inc. All Rights Reserved // // ----------------------------------------------------------------------- // #ifndef __GADGET_DISABLER_H__ #define __GADGET_DISABLER_H__ struct GTINFO; class CGadgetDisabler { public : // Methods... CGadgetDisabler( ) : m_pGTInfo ( LTNULL ), m_hTargetObj ( LTNULL ), m_bShowTimeBar ( LTTRUE ), m_bDisabling ( LTFALSE ), m_fTotalTime ( 0.0f ), m_dwCodeID ( 0 ) { m_szCodedText[0] = '\0'; }; ~CGadgetDisabler( ) {}; void Update( ); void OnGadgetTargetMessage( ILTMessage_Read *pMsg ); LTBOOL IsDisabling() {return m_bDisabling;} //LTTRUE if the target can be disabled without using a gadget. LTBOOL DisableOnActivate(); uint8 GetMaxProgress(); protected : // Members... GTINFO *m_pGTInfo; LTFLOAT m_fTimer; HOBJECT m_hTargetObj; LTBOOL m_bShowTimeBar; LTBOOL m_bDisabling; LTFLOAT m_fTotalTime; uint32 m_dwCodeID; char m_szCodedText[512]; }; #endif // __GADGET_DISABLER_H__
[ [ [ 1, 57 ] ] ]
7e9ec1aa0bdd2d32c3f925e0fc3f9ef8f18b26aa
6d680e20e4a703f0aa0d4bb5e50568143241f2d5
/src/MobiHealth/CreditsFooterWidget.cpp
13ece16ea4a4283a470e7e9bb4a746475b8fd6d0
[]
no_license
sirnicolaz/MobiHealt
f7771e53a4a80dcea3d159eca729e9bd227e8660
bbfd61209fb683d5f75f00bbf81b24933922baac
refs/heads/master
2021-01-20T12:21:17.215536
2010-04-21T14:21:16
2010-04-21T14:21:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,187
cpp
#include <CreditsFooterWidget.h> #include "buttonlabel.h" #include "CreditsWidget.h" #include <QLabel> #include <QHBoxLayout> #include <QVBoxLayout> #include <QPixmap> #include <buttonlabel.h> #include <QDesktopWidget> #include <QRect> #include <QSize> #include <QApplication> CreditsFooterWidget::CreditsFooterWidget(QWidget *parent) : QWidget(parent) { setAutoFillBackground(true); setContentsMargins(7,7,10,7); /* create the footer objects */ creditsButton = new ButtonLabel(QPixmap(":/icons/creditsIcon.png"), QPixmap(":/icons/creditsIcon.png"), this); whippyIcon = new QLabel(this); whippyIcon->setPixmap(QPixmap(":/icons/whippyIcon.png")); /* connect the button */ connect(creditsButton, SIGNAL(released()), this, SLOT(creditsButtonSlot())); /* layout operations */ hLayout = new QHBoxLayout(); hLayout->setContentsMargins(0,0,0,0); hLayout->addWidget(whippyIcon); hLayout->setAlignment(whippyIcon, Qt::AlignVCenter); hLayout->addStretch(); hLayout->addWidget(creditsButton); hLayout->setAlignment(creditsIcon, Qt::AlignVCenter); setLayout(hLayout); } void CreditsFooterWidget::setBackgroundImage() { //Using QPalette you can set background image as follows. QPalette p = palette(); //Load image to QPixmap, Give full path of image QPixmap pixmap1(":/icons/creditsFooterBg.png"); //For emulator C: is ..\epoc32\winscw\c so image must be at that location //resize image if it is larger than screen size. //QDesktopWidget* desktopWidget = QApplication::desktop(); //QRect rect = desktopWidget->availableGeometry(); QRect rect = this->geometry(); QSize size(rect.width(), rect.height()); //resize as per your reqirement.. QPixmap pixmap(pixmap1.scaled(size)); //QPixmap pixmap(pixmap1.scaledToWidth(rect.height())); p.setBrush(QPalette::Background, pixmap); setPalette(p); } void CreditsFooterWidget::creditsButtonSlot() { /* create and show the credits widget */ CreditsWidget *creditsWidget = new CreditsWidget(this); creditsWidget->setAttribute(Qt::WA_DeleteOnClose, true); creditsWidget->showFullScreen(); } CreditsFooterWidget::~CreditsFooterWidget() { }
[ [ [ 1, 72 ] ] ]
2617e61dabc49f35a81e7661d8353ca15af69683
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/nebula2/src/tinyxml/tinyxml.cc
be05803dea2ad3943f7de81f428dda64323fcc9e
[ "Zlib" ]
permissive
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
26,534
cc
#include "precompiled/pchxml.h" /* www.sourceforge.net/projects/tinyxml Original code (2.0 and earlier )copyright (c) 2000-2002 Lee Thomason (www.grinninglizard.com) 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. */ #include <ctype.h> #include "tinyxml/tinyxml.h" #ifdef TIXML_USE_STL #include <sstream> #endif #include "kernel/nfileserver2.h" #include "kernel/nfile.h" bool TiXmlBase::condenseWhiteSpace = true; void TiXmlBase::PutString( const TIXML_STRING& str, TIXML_OSTREAM* stream ) { TIXML_STRING buffer; PutString( str, &buffer ); (*stream) << buffer; } void TiXmlBase::PutString( const TIXML_STRING& str, TIXML_STRING* outString ) { int i=0; while( i<(int)str.length() ) { unsigned char c = (unsigned char) str[i]; if ( c == '&' && i < ( (int)str.length() - 2 ) && str[i+1] == '#' && str[i+2] == 'x' ) { // Hexadecimal character reference. // Pass through unchanged. // &#xA9; -- copyright symbol, for example. while ( i<(int)str.length() ) { outString->append( str.c_str() + i, 1 ); ++i; if ( str[i] == ';' ) break; } } else if ( c == '&' ) { outString->append( entity[0].str, entity[0].strLength ); ++i; } else if ( c == '<' ) { outString->append( entity[1].str, entity[1].strLength ); ++i; } else if ( c == '>' ) { outString->append( entity[2].str, entity[2].strLength ); ++i; } else if ( c == '\"' ) { outString->append( entity[3].str, entity[3].strLength ); ++i; } else if ( c == '\'' ) { outString->append( entity[4].str, entity[4].strLength ); ++i; } else if ( c < 32 ) { // Easy pass at non-alpha/numeric/symbol // Below 32 is symbolic. char buf[ 32 ]; sprintf( buf, "&#x%02X;", (unsigned) ( c & 0xff ) ); outString->append( buf, static_cast<int>( strlen( buf ) ) ); ++i; } else { // Assume everthing else is unicode. c should never actually // be out of the range of 0-255. Else something has gone strange. assert( c > 0 && c < 256 ); //char realc = (char) c; //outString->append( &realc, 1 ); *outString += (char) c; // somewhat more efficient function call. ++i; } } } // <-- Strange class for a bug fix. Search for STL_STRING_BUG TiXmlBase::StringToBuffer::StringToBuffer( const TIXML_STRING& str ) { //buffer = new char[ str.length()+1 ]; buffer = n_new_array(char, str.length()+1); if ( buffer ) { strcpy( buffer, str.c_str() ); } } TiXmlBase::StringToBuffer::~StringToBuffer() { //delete [] buffer; n_delete_array(buffer); } // End strange bug fix. --> TiXmlNode::TiXmlNode( NodeType _type ) : TiXmlBase() { parent = 0; type = _type; firstChild = 0; lastChild = 0; prev = 0; next = 0; } TiXmlNode::~TiXmlNode() { TiXmlNode* node = firstChild; TiXmlNode* temp = 0; while ( node ) { temp = node; node = node->next; //delete temp; n_delete(temp); } } void TiXmlNode::Clear() { TiXmlNode* node = firstChild; TiXmlNode* temp = 0; while ( node ) { temp = node; node = node->next; //delete temp; n_delete(temp); } firstChild = 0; lastChild = 0; } TiXmlNode* TiXmlNode::LinkEndChild( TiXmlNode* node ) { node->parent = this; node->prev = lastChild; node->next = 0; if ( lastChild ) lastChild->next = node; else firstChild = node; // it was an empty list. lastChild = node; return node; } TiXmlNode* TiXmlNode::InsertEndChild( const TiXmlNode& addThis ) { TiXmlNode* node = addThis.Clone(); if ( !node ) return 0; return LinkEndChild( node ); } TiXmlNode* TiXmlNode::InsertBeforeChild( TiXmlNode* beforeThis, const TiXmlNode& addThis ) { if ( !beforeThis || beforeThis->parent != this ) return 0; TiXmlNode* node = addThis.Clone(); if ( !node ) return 0; node->parent = this; node->next = beforeThis; node->prev = beforeThis->prev; if ( beforeThis->prev ) { beforeThis->prev->next = node; } else { assert( firstChild == beforeThis ); firstChild = node; } beforeThis->prev = node; return node; } TiXmlNode* TiXmlNode::InsertAfterChild( TiXmlNode* afterThis, const TiXmlNode& addThis ) { if ( !afterThis || afterThis->parent != this ) return 0; TiXmlNode* node = addThis.Clone(); if ( !node ) return 0; node->parent = this; node->prev = afterThis; node->next = afterThis->next; if ( afterThis->next ) { afterThis->next->prev = node; } else { assert( lastChild == afterThis ); lastChild = node; } afterThis->next = node; return node; } TiXmlNode* TiXmlNode::ReplaceChild( TiXmlNode* replaceThis, const TiXmlNode& withThis ) { if ( replaceThis->parent != this ) return 0; TiXmlNode* node = withThis.Clone(); if ( !node ) return 0; node->next = replaceThis->next; node->prev = replaceThis->prev; if ( replaceThis->next ) replaceThis->next->prev = node; else lastChild = node; if ( replaceThis->prev ) replaceThis->prev->next = node; else firstChild = node; //delete replaceThis; n_delete(replaceThis); node->parent = this; return node; } bool TiXmlNode::RemoveChild( TiXmlNode* removeThis ) { if ( removeThis->parent != this ) { assert( 0 ); return false; } if ( removeThis->next ) removeThis->next->prev = removeThis->prev; else lastChild = removeThis->prev; if ( removeThis->prev ) removeThis->prev->next = removeThis->next; else firstChild = removeThis->next; //delete removeThis; n_delete(removeThis); return true; } TiXmlNode* TiXmlNode::FirstChild( const char * _value ) const { TiXmlNode* node; for ( node = firstChild; node; node = node->next ) { if ( node->SValue() == TIXML_STRING( _value )) return node; } return 0; } TiXmlNode* TiXmlNode::LastChild( const char * _value ) const { TiXmlNode* node; for ( node = lastChild; node; node = node->prev ) { if ( node->SValue() == TIXML_STRING (_value)) return node; } return 0; } TiXmlNode* TiXmlNode::IterateChildren( TiXmlNode* previous ) const { if ( !previous ) { return FirstChild(); } else { assert( previous->parent == this ); return previous->NextSibling(); } } TiXmlNode* TiXmlNode::IterateChildren( const char * val, TiXmlNode* previous ) const { if ( !previous ) { return FirstChild( val ); } else { assert( previous->parent == this ); return previous->NextSibling( val ); } } TiXmlNode* TiXmlNode::NextSibling( const char * _value ) const { TiXmlNode* node; for ( node = next; node; node = node->next ) { if ( node->SValue() == TIXML_STRING (_value)) return node; } return 0; } TiXmlNode* TiXmlNode::PreviousSibling( const char * _value ) const { TiXmlNode* node; for ( node = prev; node; node = node->prev ) { if ( node->SValue() == TIXML_STRING (_value)) return node; } return 0; } void TiXmlElement::RemoveAttribute( const char * name ) { TiXmlAttribute* node = attributeSet.Find( name ); if ( node ) { attributeSet.Remove( node ); //delete node; n_delete(node); } } TiXmlElement* TiXmlNode::FirstChildElement() const { TiXmlNode* node; for ( node = FirstChild(); node; node = node->NextSibling() ) { if ( node->ToElement() ) return node->ToElement(); } return 0; } TiXmlElement* TiXmlNode::FirstChildElement( const char * _value ) const { TiXmlNode* node; for ( node = FirstChild( _value ); node; node = node->NextSibling( _value ) ) { if ( node->ToElement() ) return node->ToElement(); } return 0; } TiXmlElement* TiXmlNode::NextSiblingElement() const { TiXmlNode* node; for ( node = NextSibling(); node; node = node->NextSibling() ) { if ( node->ToElement() ) return node->ToElement(); } return 0; } TiXmlElement* TiXmlNode::NextSiblingElement( const char * _value ) const { TiXmlNode* node; for ( node = NextSibling( _value ); node; node = node->NextSibling( _value ) ) { if ( node->ToElement() ) return node->ToElement(); } return 0; } TiXmlDocument* TiXmlNode::GetDocument() const { const TiXmlNode* node; for( node = this; node; node = node->parent ) { if ( node->ToDocument() ) return node->ToDocument(); } return 0; } TiXmlElement::TiXmlElement (const char * _value) : TiXmlNode( TiXmlNode::ELEMENT ) { firstChild = lastChild = 0; value = _value; } TiXmlElement::~TiXmlElement() { while( attributeSet.First() ) { TiXmlAttribute* node = attributeSet.First(); attributeSet.Remove( node ); //delete node; n_delete(node); } } const char * TiXmlElement::Attribute( const char * name ) const { TiXmlAttribute* node = attributeSet.Find( name ); if ( node ) return node->Value(); return 0; } const char * TiXmlElement::Attribute( const char * name, int* i ) const { const char * s = Attribute( name ); if ( i ) { if ( s ) *i = atoi( s ); else *i = 0; } return s; } const char * TiXmlElement::Attribute( const char * name, double* d ) const { const char * s = Attribute( name ); if ( d ) { if ( s ) *d = atof( s ); else *d = 0; } return s; } int TiXmlElement::QueryIntAttribute( const char* name, int* ival ) const { TiXmlAttribute* node = attributeSet.Find( name ); if ( !node ) return TIXML_NO_ATTRIBUTE; return node->QueryIntValue( ival ); } int TiXmlElement::QueryDoubleAttribute( const char* name, double* dval ) const { TiXmlAttribute* node = attributeSet.Find( name ); if ( !node ) return TIXML_NO_ATTRIBUTE; return node->QueryDoubleValue( dval ); } void TiXmlElement::SetAttribute( const char * name, int val ) { char buf[64]; sprintf( buf, "%d", val ); SetAttribute( name, buf ); } void TiXmlElement::SetDoubleAttribute( const char * name, double val ) { char buf[128]; sprintf( buf, "%f", val ); SetAttribute( name, buf ); } void TiXmlElement::SetAttribute( const char * name, const char * _value ) { TiXmlAttribute* node = attributeSet.Find( name ); if ( node ) { node->SetValue( _value ); return; } //TiXmlAttribute* attrib = new TiXmlAttribute( name, _value ); TiXmlAttribute* attrib = n_new(TiXmlAttribute( name, _value )); if ( attrib ) { attributeSet.Add( attrib ); } else { TiXmlDocument* document = GetDocument(); if ( document ) document->SetError( TIXML_ERROR_OUT_OF_MEMORY, 0, 0 ); } } void TiXmlElement::Print( FILE* cfile, int depth ) const { int i; for ( i=0; i<depth; i++ ) { fprintf( cfile, " " ); } fprintf( cfile, "<%s", value.c_str() ); TiXmlAttribute* attrib; for ( attrib = attributeSet.First(); attrib; attrib = attrib->Next() ) { fprintf( cfile, " " ); attrib->Print( cfile, depth ); } // There are 3 different formatting approaches: // 1) An element without children is printed as a <foo /> node // 2) An element with only a text child is printed as <foo> text </foo> // 3) An element with children is printed on multiple lines. TiXmlNode* node; if ( !firstChild ) { fprintf( cfile, " />" ); } else if ( firstChild == lastChild && firstChild->ToText() ) { fprintf( cfile, ">" ); firstChild->Print( cfile, depth + 1 ); fprintf( cfile, "</%s>", value.c_str() ); } else { fprintf( cfile, ">" ); for ( node = firstChild; node; node=node->NextSibling() ) { if ( !node->ToText() ) { fprintf( cfile, "\n" ); } node->Print( cfile, depth+1 ); } fprintf( cfile, "\n" ); for( i=0; i<depth; ++i ) fprintf( cfile, " " ); fprintf( cfile, "</%s>", value.c_str() ); } } void TiXmlElement::StreamOut( TIXML_OSTREAM * stream ) const { (*stream) << "<" << value; TiXmlAttribute* attrib; for ( attrib = attributeSet.First(); attrib; attrib = attrib->Next() ) { (*stream) << " "; attrib->StreamOut( stream ); } // If this node has children, give it a closing tag. Else // make it an empty tag. TiXmlNode* node; if ( firstChild ) { (*stream) << ">"; for ( node = firstChild; node; node=node->NextSibling() ) { node->StreamOut( stream ); } (*stream) << "</" << value << ">"; } else { (*stream) << " />"; } } TiXmlNode* TiXmlElement::Clone() const { //TiXmlElement* clone = new TiXmlElement( Value() ); TiXmlElement* clone = n_new(TiXmlElement( Value() )); if ( !clone ) return 0; CopyToClone( clone ); // Clone the attributes, then clone the children. TiXmlAttribute* attribute = 0; for( attribute = attributeSet.First(); attribute; attribute = attribute->Next() ) { clone->SetAttribute( attribute->Name(), attribute->Value() ); } TiXmlNode* node = 0; for ( node = firstChild; node; node = node->NextSibling() ) { clone->LinkEndChild( node->Clone() ); } return clone; } TiXmlDocument::TiXmlDocument() : TiXmlNode( TiXmlNode::DOCUMENT ) { tabsize = 4; ClearError(); } TiXmlDocument::TiXmlDocument( const char * documentName ) : TiXmlNode( TiXmlNode::DOCUMENT ) { tabsize = 4; value = documentName; ClearError(); } bool TiXmlDocument::LoadFile() { // See STL_STRING_BUG below. StringToBuffer buf( value ); if ( buf.buffer && LoadFile( buf.buffer ) ) return true; return false; } bool TiXmlDocument::SaveFile() const { // See STL_STRING_BUG below. StringToBuffer buf( value ); if ( buf.buffer && SaveFile( buf.buffer ) ) return true; return false; } //------------------------------------------------------------------------------ /** 14-May-05 floh rewritten to Nebula2 Fileroutines */ bool TiXmlDocument::LoadFile( const char* filename ) { // Delete the existing data: Clear(); location.Clear(); // There was a really terrifying little bug here. The code: // value = filename // in the STL case, cause the assignment method of the std::string to // be called. What is strange, is that the std::string had the same // address as it's c_str() method, and so bad things happen. Looks // like a bug in the Microsoft STL implementation. // See STL_STRING_BUG above. // Fixed with the StringToBuffer class. value = filename; nFile* file = nFileServer2::Instance()->NewFileObject(); if (file->Open(value.c_str(), "r")) { // Get the file size, so we can pre-allocate the string. HUGE speed impact. long length = file->GetSize(); // Strange case, but good to handle up front. if ( length == 0 ) { file->Close(); file->Release(); return false; } // If we have a file, assume it is all one big XML file, and read it in. // The document parser may decide the document ends sooner than the entire file, however. TIXML_STRING data; data.reserve( length ); const int BUF_SIZE = 2048; char buf[BUF_SIZE]; while (file->GetS(buf, BUF_SIZE)) { data += buf; } file->Close(); file->Release(); file = 0; Parse( data.c_str(), 0 ); if ( Error() ) return false; else return true; } SetError( TIXML_ERROR_OPENING_FILE, 0, 0 ); return false; } //------------------------------------------------------------------------------ /** */ bool TiXmlDocument::SaveFile( const char * filename ) const { // The old c stuff lives on... FILE* fp = fopen( filename, "w" ); if ( fp ) { Print( fp, 0 ); fclose( fp ); return true; } return false; } TiXmlNode* TiXmlDocument::Clone() const { //TiXmlDocument* clone = new TiXmlDocument(); TiXmlDocument* clone = n_new(TiXmlDocument()); if ( !clone ) return 0; CopyToClone( clone ); clone->error = error; clone->errorDesc = errorDesc.c_str (); TiXmlNode* node = 0; for ( node = firstChild; node; node = node->NextSibling() ) { clone->LinkEndChild( node->Clone() ); } return clone; } void TiXmlDocument::Print( FILE* cfile, int depth ) const { TiXmlNode* node; for ( node=FirstChild(); node; node=node->NextSibling() ) { node->Print( cfile, depth ); fprintf( cfile, "\n" ); } } void TiXmlDocument::StreamOut( TIXML_OSTREAM * out ) const { TiXmlNode* node; for ( node=FirstChild(); node; node=node->NextSibling() ) { node->StreamOut( out ); // Special rule for streams: stop after the root element. // The stream in code will only read one element, so don't // write more than one. if ( node->ToElement() ) break; } } TiXmlAttribute* TiXmlAttribute::Next() const { // We are using knowledge of the sentinel. The sentinel // have a value or name. if ( next->value.empty() && next->name.empty() ) return 0; return next; } TiXmlAttribute* TiXmlAttribute::Previous() const { // We are using knowledge of the sentinel. The sentinel // have a value or name. if ( prev->value.empty() && prev->name.empty() ) return 0; return prev; } void TiXmlAttribute::Print( FILE* cfile, int /*depth*/ ) const { TIXML_STRING n, v; PutString( name, &n ); PutString( value, &v ); if (value.find ('\"') == TIXML_STRING::npos) fprintf (cfile, "%s=\"%s\"", n.c_str(), v.c_str() ); else fprintf (cfile, "%s='%s'", n.c_str(), v.c_str() ); } void TiXmlAttribute::StreamOut( TIXML_OSTREAM * stream ) const { if (value.find( '\"' ) != TIXML_STRING::npos) { PutString( name, stream ); (*stream) << "=" << "'"; PutString( value, stream ); (*stream) << "'"; } else { PutString( name, stream ); (*stream) << "=" << "\""; PutString( value, stream ); (*stream) << "\""; } } int TiXmlAttribute::QueryIntValue( int* ival ) const { if ( sscanf( value.c_str(), "%d", ival ) == 1 ) return TIXML_SUCCESS; return TIXML_WRONG_TYPE; } int TiXmlAttribute::QueryDoubleValue( double* dval ) const { if ( sscanf( value.c_str(), "%lf", dval ) == 1 ) return TIXML_SUCCESS; return TIXML_WRONG_TYPE; } void TiXmlAttribute::SetIntValue( int _value ) { char buf [64]; sprintf (buf, "%d", _value); SetValue (buf); } void TiXmlAttribute::SetDoubleValue( double _value ) { char buf [64]; sprintf (buf, "%lf", _value); SetValue (buf); } const int TiXmlAttribute::IntValue() const { return atoi (value.c_str ()); } const double TiXmlAttribute::DoubleValue() const { return atof (value.c_str ()); } void TiXmlComment::Print( FILE* cfile, int depth ) const { for ( int i=0; i<depth; i++ ) { fputs( " ", cfile ); } fprintf( cfile, "<!--%s-->", value.c_str() ); } void TiXmlComment::StreamOut( TIXML_OSTREAM * stream ) const { (*stream) << "<!--"; //PutString( value, stream ); (*stream) << value; (*stream) << "-->"; } TiXmlNode* TiXmlComment::Clone() const { //TiXmlComment* clone = new TiXmlComment(); TiXmlComment* clone = n_new(TiXmlComment()); if ( !clone ) return 0; CopyToClone( clone ); return clone; } void TiXmlText::Print( FILE* cfile, int /*depth*/ ) const { TIXML_STRING buffer; PutString( value, &buffer ); fprintf( cfile, "%s", buffer.c_str() ); } void TiXmlText::StreamOut( TIXML_OSTREAM * stream ) const { PutString( value, stream ); } TiXmlNode* TiXmlText::Clone() const { TiXmlText* clone = 0; //clone = new TiXmlText( "" ); clone = n_new(TiXmlText( "" )); if ( !clone ) return 0; CopyToClone( clone ); return clone; } TiXmlDeclaration::TiXmlDeclaration( const char * _version, const char * _encoding, const char * _standalone ) : TiXmlNode( TiXmlNode::DECLARATION ) { version = _version; encoding = _encoding; standalone = _standalone; } void TiXmlDeclaration::Print( FILE* cfile, int /*depth*/ ) const { fprintf (cfile, "<?xml "); if ( !version.empty() ) fprintf (cfile, "version=\"%s\" ", version.c_str ()); if ( !encoding.empty() ) fprintf (cfile, "encoding=\"%s\" ", encoding.c_str ()); if ( !standalone.empty() ) fprintf (cfile, "standalone=\"%s\" ", standalone.c_str ()); fprintf (cfile, "?>"); } void TiXmlDeclaration::StreamOut( TIXML_OSTREAM * stream ) const { (*stream) << "<?xml "; if ( !version.empty() ) { (*stream) << "version=\""; PutString( version, stream ); (*stream) << "\" "; } if ( !encoding.empty() ) { (*stream) << "encoding=\""; PutString( encoding, stream ); (*stream ) << "\" "; } if ( !standalone.empty() ) { (*stream) << "standalone=\""; PutString( standalone, stream ); (*stream) << "\" "; } (*stream) << "?>"; } TiXmlNode* TiXmlDeclaration::Clone() const { //TiXmlDeclaration* clone = new TiXmlDeclaration(); TiXmlDeclaration* clone = n_new(TiXmlDeclaration()); if ( !clone ) return 0; CopyToClone( clone ); clone->version = version; clone->encoding = encoding; clone->standalone = standalone; return clone; } void TiXmlUnknown::Print( FILE* cfile, int depth ) const { for ( int i=0; i<depth; i++ ) fprintf( cfile, " " ); fprintf( cfile, "<%s>", value.c_str() ); } void TiXmlUnknown::StreamOut( TIXML_OSTREAM * stream ) const { (*stream) << "<" << value << ">"; // Don't use entities here! It is unknown. } TiXmlNode* TiXmlUnknown::Clone() const { //TiXmlUnknown* clone = new TiXmlUnknown(); TiXmlDeclaration* clone = n_new(TiXmlDeclaration()); if ( !clone ) return 0; CopyToClone( clone ); return clone; } TiXmlAttributeSet::TiXmlAttributeSet() { sentinel.next = &sentinel; sentinel.prev = &sentinel; } TiXmlAttributeSet::~TiXmlAttributeSet() { assert( sentinel.next == &sentinel ); assert( sentinel.prev == &sentinel ); } void TiXmlAttributeSet::Add( TiXmlAttribute* addMe ) { assert( !Find( addMe->Name() ) ); // Shouldn't be multiply adding to the set. addMe->next = &sentinel; addMe->prev = sentinel.prev; sentinel.prev->next = addMe; sentinel.prev = addMe; } void TiXmlAttributeSet::Remove( TiXmlAttribute* removeMe ) { TiXmlAttribute* node; for( node = sentinel.next; node != &sentinel; node = node->next ) { if ( node == removeMe ) { node->prev->next = node->next; node->next->prev = node->prev; node->next = 0; node->prev = 0; return; } } assert( 0 ); // we tried to remove a non-linked attribute. } TiXmlAttribute* TiXmlAttributeSet::Find( const char * name ) const { TiXmlAttribute* node; for( node = sentinel.next; node != &sentinel; node = node->next ) { if ( node->name == name ) return node; } return 0; } #ifdef TIXML_USE_STL TIXML_ISTREAM & operator >> (TIXML_ISTREAM & in, TiXmlNode & base) { TIXML_STRING tag; tag.reserve( 8 * 1000 ); base.StreamIn( &in, &tag ); base.Parse( tag.c_str(), 0 ); return in; } #endif TIXML_OSTREAM & operator<< (TIXML_OSTREAM & out, const TiXmlNode & base) { base.StreamOut (& out); return out; } #ifdef TIXML_USE_STL std::string & operator<< (std::string& out, const TiXmlNode& base ) { std::ostringstream os_stream( std::ostringstream::out ); base.StreamOut( &os_stream ); out.append( os_stream.str() ); return out; } #endif TiXmlHandle TiXmlHandle::FirstChild() const { if ( node ) { TiXmlNode* child = node->FirstChild(); if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::FirstChild( const char * value ) const { if ( node ) { TiXmlNode* child = node->FirstChild( value ); if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::FirstChildElement() const { if ( node ) { TiXmlElement* child = node->FirstChildElement(); if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::FirstChildElement( const char * value ) const { if ( node ) { TiXmlElement* child = node->FirstChildElement( value ); if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::Child( int count ) const { if ( node ) { int i; TiXmlNode* child = node->FirstChild(); for ( i=0; child && i<count; child = child->NextSibling(), ++i ) { // nothing } if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::Child( const char* value, int count ) const { if ( node ) { int i; TiXmlNode* child = node->FirstChild( value ); for ( i=0; child && i<count; child = child->NextSibling( value ), ++i ) { // nothing } if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::ChildElement( int count ) const { if ( node ) { int i; TiXmlElement* child = node->FirstChildElement(); for ( i=0; child && i<count; child = child->NextSiblingElement(), ++i ) { // nothing } if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::ChildElement( const char* value, int count ) const { if ( node ) { int i; TiXmlElement* child = node->FirstChildElement( value ); for ( i=0; child && i<count; child = child->NextSiblingElement( value ), ++i ) { // nothing } if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); }
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 1298 ] ] ]
11df066dd3ed3c0d6d59dd0d61827591aeaa20d8
da48afcbd478f79d70767170da625b5f206baf9a
/tbmessage/src/Libraries/ExplorerOcx.cpp
70e9fb7bcfc32d29b6fa84609623163c97062904
[]
no_license
haokeyy/fahister
5ba50a99420dbaba2ad4e5ab5ee3ab0756563d04
c71dc56a30b862cc4199126d78f928fce11b12e5
refs/heads/master
2021-01-10T19:09:22.227340
2010-05-06T13:17:35
2010-05-06T13:17:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
645
cpp
// Machine generated IDispatch wrapper class(es) created by Microsoft Visual C++ // NOTE: Do not modify the contents of this file. If this class is regenerated by // Microsoft Visual C++, your modifications will be overwritten. #include "stdafx.h" #include "ExplorerOcx.h" ///////////////////////////////////////////////////////////////////////////// // CExplorerOcx IMPLEMENT_DYNCREATE(CExplorerOcx, CWnd) ///////////////////////////////////////////////////////////////////////////// // CExplorerOcx properties ///////////////////////////////////////////////////////////////////////////// // CExplorerOcx operations
[ "[email protected]@d41c10be-1f87-11de-a78b-a7aca27b2395" ]
[ [ [ 1, 19 ] ] ]
c5b66dc547e15ada3148c52b311dff3c099c6116
fceff9260ff49d2707060241b6f9b927b97db469
/ZombieGentlemen_SeniorProject/goomba.h
4e0aea12d1092dc57088e311fc6c546d0644e3ef
[]
no_license
EddyReyes/gentlemen-zombies-senior-project
9f5a6be90f0459831b3f044ed17ef2f085bec679
d88458b716c6eded376b3d44b5385c80deeb9a16
refs/heads/master
2021-05-29T12:13:47.506314
2011-07-04T17:20:38
2011-07-04T17:20:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
417
h
#pragma once #include "entity.h" #include <assert.h> enum goombaStates{goombaWalkLeft, goombaWalkRight}; class goomba: public entity { private: goombaStates state; int sprite; float timer, flipTimer; public: // constructor/destructor goomba(); ~goomba(); //member functions void update(float timePassed); void animate(); void flip(); void reset(); void setDirection(char dir); };
[ "[email protected]@66a8e42f-0ee8-26ea-976e-e3172d02aab5", "[email protected]@66a8e42f-0ee8-26ea-976e-e3172d02aab5" ]
[ [ [ 1, 2 ], [ 4, 8 ], [ 10, 24 ] ], [ [ 3, 3 ], [ 9, 9 ] ] ]
a38550a91c11a23bf0890e1cc9c6d86dcacfa0f7
c70941413b8f7bf90173533115c148411c868bad
/tools/vtxFlashPreview/include/vtxMovieListener.h
dcf865d3231b7051a20c973f6c1ce5547f80d473
[]
no_license
cnsuhao/vektrix
ac6e028dca066aad4f942b8d9eb73665853fbbbe
9b8c5fa7119ff7f3dc80fb05b7cdba335cf02c1a
refs/heads/master
2021-06-23T11:28:34.907098
2011-03-27T17:39:37
2011-03-27T17:39:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,981
h
/* ----------------------------------------------------------------------------- This source file is part of "vektrix" (the rich media and vector graphics rendering library) For the latest info, see http://www.fuse-software.com/ Copyright (c) 2009-2010 Fuse-Software (tm) 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 __vtxMovieListener_H__ #define __vtxMovieListener_H__ #include "vtxFlashPreview.h" #include "vtxMovie.h" namespace vtx { namespace tools { namespace FlashPreview { //----------------------------------------------------------------------- class MovieListener : public Movie::Listener { public: MovieListener(FlashPreview* app); bool loadingCompleted(Movie* movie); bool loadingFailed(Movie* movie); private: FlashPreview* mApplication; }; //----------------------------------------------------------------------- }}} #endif
[ "stonecold_@9773a11d-1121-4470-82d2-da89bd4a628a" ]
[ [ [ 1, 51 ] ] ]
1409f478ba53cf12012fa80483774b884896b1d2
5504cdea188dd5ceec6ab38863ef4b4f72c70b21
/pcsxrr/iso/Win32/Win32.cpp
2b83541b15c41f43e1ad62d259f004c7b509b3e2
[]
no_license
mauzus/pcsxrr
959051bed227f96045a9bba8971ba5dffc24ad33
1b4c66d6a2938da55761280617d288f3c65870d7
refs/heads/master
2021-03-12T20:00:56.954014
2011-03-21T01:16:35
2011-03-21T01:16:35
32,238,897
1
0
null
null
null
null
UTF-8
C++
false
false
7,048
cpp
#include <windows.h> #include <windowsx.h> #include <commctrl.h> #include <stdio.h> #include <stdarg.h> #include <sys/stat.h> #include <string.h> #include <zlib.h> #include <bzlib.h> #include "../Config.h" #include "../cdriso.h" #include "resource.h" HINSTANCE hInst; #define MAXFILENAME 256 unsigned char Zbuf[CD_FRAMESIZE_RAW * 10 * 2]; HWND hDlg; HWND hProgress; HWND hIsoFile; HWND hMethod; int stop; void SysMessage(char *fmt, ...); // va_list list; // char tmp[512]; // // va_start(list,fmt); // vsprintf(tmp,fmt,list); // va_end(list); // MessageBox(0, tmp, "cdriso Msg", 0); //} int _GetFile(char *out) { OPENFILENAME ofn; char szFileName[MAXFILENAME]; char szFileTitle[MAXFILENAME]; memset(&szFileName, 0, sizeof(szFileName)); memset(&szFileTitle, 0, sizeof(szFileTitle)); ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = GetActiveWindow(); ofn.lpstrFilter = "Cd Iso Format\0*.*;*.*\0"; ofn.lpstrCustomFilter = NULL; ofn.nMaxCustFilter = 0; ofn.nFilterIndex = 1; ofn.lpstrFile = szFileName; ofn.nMaxFile = MAXFILENAME; ofn.lpstrInitialDir = NULL; ofn.lpstrFileTitle = szFileTitle; ofn.nMaxFileTitle = MAXFILENAME; ofn.lpstrTitle = NULL; ofn.lpstrDefExt = "ISO"; ofn.Flags = OFN_HIDEREADONLY | OFN_NOCHANGEDIR; if (GetOpenFileName ((LPOPENFILENAME)&ofn)) { strcpy(out, szFileName); return 1; } return 0; } void CfgOpenFile() { if (_GetFile(IsoFile) == 1) SaveConf(); } void UpdZmode() { if (ComboBox_GetCurSel(GetDlgItem(hDlg, IDC_METHOD)) == 1) Zmode = 1; else Zmode = 2; } void SysUpdate(); //void SysUpdate() { // MSG msg; // // while (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) { // TranslateMessage(&msg); // DispatchMessage(&msg); // } //} void OnCompress() { struct stat buf; FILE *f; FILE *Z; unsigned long c=0, p=0, s; char table[256]; int ret, blocks; Edit_GetText(hIsoFile, IsoFile, 256); cdHandle = fopen(IsoFile, "rb"); if (cdHandle == NULL) { return; } stat(IsoFile, &buf); s = buf.st_size / CD_FRAMESIZE_RAW; UpdZmode(); if (Zmode == 1) strcat(IsoFile, ".Z"); else strcat(IsoFile, ".bz"); Z = fopen(IsoFile, "wb"); if (Z == NULL) { return; } strcpy(table, IsoFile); if (Zmode == 1) strcat(table, ".table"); else strcat(table, ".index"); f = fopen(table, "wb"); if (f == NULL) { return; } if (Zmode == 1) { blocks = 1; } else { blocks = 10; } Button_Enable(GetDlgItem(hDlg, IDC_COMPRESSISO), FALSE); Button_Enable(GetDlgItem(hDlg, IDC_DECOMPRESSISO), FALSE); stop=0; while ((ret = fread(cdbuffer, 1, CD_FRAMESIZE_RAW * blocks, cdHandle))) { unsigned long size; long per; size = CD_FRAMESIZE_RAW * blocks * 2; if (Zmode == 1) compress(Zbuf, &size, cdbuffer, ret); else BZ2_bzBuffToBuffCompress((char*)Zbuf, (unsigned int*)&size, (char*)cdbuffer, ret, 1, 0, 30); fwrite(&c, 1, 4, f); if (Zmode == 1) fwrite(&size, 1, 2, f); fwrite(Zbuf, 1, size, Z); c+=size; p+=ret / CD_FRAMESIZE_RAW; per = ((p * 100) / s); SendMessage(hProgress, PBM_SETPOS, per, 0); SysUpdate(); if (stop) break; } if (Zmode == 2) fwrite(&c, 1, 4, f); if (!stop) Edit_SetText(hIsoFile, IsoFile); fclose(cdHandle); cdHandle = NULL; fclose(f); fclose(Z); Button_Enable(GetDlgItem(hDlg, IDC_COMPRESSISO), TRUE); Button_Enable(GetDlgItem(hDlg, IDC_DECOMPRESSISO), TRUE); if (!stop) SysMessage("Iso Image Comompressed OK"); } void OnDecompress() { struct stat buf; FILE *f; unsigned long c=0, p=0, s; char table[256]; int blocks; Edit_GetText(hIsoFile, IsoFile, 256); UpdateZmode(); if (Zmode == 0) Zmode = 2; strcpy(table, IsoFile); if (Zmode == 1) strcat(table, ".table"); else strcat(table, ".index"); if (stat(table, &buf) == -1) { return; } if (Zmode == 1) c = s = buf.st_size / 6; else c = s = (buf.st_size / 4) - 1; f = fopen(table, "rb"); Ztable = (char*)malloc(buf.st_size); fread(Ztable, 1, buf.st_size, f); fclose(f); cdHandle = fopen(IsoFile, "rb"); if (cdHandle == NULL) { return; } if (Zmode == 1) IsoFile[strlen(IsoFile) - 2] = 0; else IsoFile[strlen(IsoFile) - 3] = 0; f = fopen(IsoFile, "wb"); if (f == NULL) { return; } Button_Enable(GetDlgItem(hDlg, IDC_COMPRESSISO), FALSE); Button_Enable(GetDlgItem(hDlg, IDC_DECOMPRESSISO), FALSE); stop=0; if (Zmode == 1) { blocks = 1; } else { blocks = 10; } while (c--) { unsigned long size, pos, ssize; long per; if (Zmode == 1) { pos = *(unsigned long*)&Ztable[p * 6]; fseek(cdHandle, pos, SEEK_SET); ssize = *(unsigned short*)&Ztable[p * 6 + 4]; fread(Zbuf, 1, ssize, cdHandle); } else { pos = *(unsigned long*)&Ztable[p * 4]; fseek(cdHandle, pos, SEEK_SET); ssize = *(unsigned long*)&Ztable[p * 4 + 4] - pos; fread(Zbuf, 1, ssize, cdHandle); } size = CD_FRAMESIZE_RAW * blocks; if (Zmode == 1) uncompress(cdbuffer, &size, Zbuf, ssize); else BZ2_bzBuffToBuffDecompress((char*)cdbuffer, (unsigned int*)&size, (char*)Zbuf, ssize, 0, 0); fwrite(cdbuffer, 1, size, f); p++; per = ((p * 100) / s); SendMessage(hProgress, PBM_SETPOS, per, 0); SysUpdate(); if (stop) break; } if (!stop) Edit_SetText(hIsoFile, IsoFile); fclose(f); fclose(cdHandle); cdHandle = NULL; free(Ztable); Ztable = NULL; Button_Enable(GetDlgItem(hDlg, IDC_COMPRESSISO), TRUE); Button_Enable(GetDlgItem(hDlg, IDC_DECOMPRESSISO), TRUE); if (!stop) SysMessage("Iso Image Decompressed OK"); } static BOOL CALLBACK IsoConfigureDlgProc(HWND hW, UINT uMsg, WPARAM wParam, LPARAM lParam) { int i; switch(uMsg) { case WM_INITDIALOG: hDlg = hW; LoadConf(); hProgress = GetDlgItem(hW, IDC_PROGRESS); hIsoFile = GetDlgItem(hW, IDC_ISOFILE); hMethod = GetDlgItem(hW, IDC_METHOD); for (i=0; i<2; i++) ComboBox_AddString(hMethod, methods[i]); Edit_SetText(hIsoFile, IsoFile); if (strstr(IsoFile, ".Z") != NULL) ComboBox_SetCurSel(hMethod, 1); else ComboBox_SetCurSel(hMethod, 0); return TRUE; case WM_COMMAND: switch(LOWORD(wParam)) { case IDC_SELECTISO: if (_GetFile(IsoFile) == 1) Edit_SetText(hIsoFile, IsoFile); return TRUE; case IDC_COMPRESSISO: OnCompress(); return TRUE; case IDC_DECOMPRESSISO: OnDecompress(); return TRUE; case IDC_STOP: stop = 1; return TRUE; case IDCANCEL: EndDialog(hW, TRUE); return TRUE; case IDOK: Edit_GetText(hIsoFile, IsoFile, 256); SaveConf(); EndDialog(hW, FALSE); return TRUE; } } return FALSE; } long CDRconfigure() { DialogBox(hInst, MAKEINTRESOURCE(IDD_ISOCONFIG), GetActiveWindow(), (DLGPROC)IsoConfigureDlgProc); return 0; }
[ "mauzus@b38eb22e-9255-0410-b643-f940c3bf2d76", "mgambrell@b38eb22e-9255-0410-b643-f940c3bf2d76" ]
[ [ [ 1, 10 ], [ 13, 24 ], [ 34, 76 ], [ 78, 78 ], [ 87, 138 ], [ 140, 236 ], [ 238, 259 ], [ 261, 314 ], [ 316, 316 ], [ 318, 318 ], [ 320, 321 ] ], [ [ 11, 12 ], [ 25, 33 ], [ 77, 77 ], [ 79, 86 ], [ 139, 139 ], [ 237, 237 ], [ 260, 260 ], [ 315, 315 ], [ 317, 317 ], [ 319, 319 ] ] ]
400bfbfab71647a6eaf4ff8c279b45926eee905b
188058ec6dbe8b1a74bf584ecfa7843be560d2e5
/GodDK/lang/Comparable.h
697ada08d8b76f5ca137c0836a21627f35c95e70
[]
no_license
mason105/red5cpp
636e82c660942e2b39c4bfebc63175c8539f7df0
fcf1152cb0a31560af397f24a46b8402e854536e
refs/heads/master
2021-01-10T07:21:31.412996
2007-08-23T06:29:17
2007-08-23T06:29:17
36,223,621
0
0
null
null
null
null
UTF-8
C++
false
false
352
h
#ifndef _INTERFACE_GOD_LANG_COMPARABLE_H #define _INTERFACE_GOD_LANG_COMPARABLE_H #include "gcommon.h" #ifdef __cplusplus namespace goddk { namespace lang { template<typename T> class Comparable { public: virtual ~Comparable() {} virtual jint compareTo(const T&) const throw () = 0; }; } } #endif #endif
[ "soaris@46205fef-a337-0410-8429-7db05d171fc8" ]
[ [ [ 1, 24 ] ] ]
090125f7aeed7303e2ea2a31ab49885253e1cb3f
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/Neuz/WorldMap.cpp
6f4dcf8aa537a57bf38f0f9c01cfb40865b3dc07
[]
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
UHC
C++
false
false
56,026
cpp
// WorldMap.cpp: implementation of the CWorldMap class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "WorldMap.h" #include "resData.h" #include "party.h" #include "defineText.h" #if __VER >= 15 // __TELEPORTER #include "defineSound.h" #include "DPClient.h" extern CDPClient g_DPlay; #endif #if __VER >= 11 // __SYS_PLAYER_DATA #include "playerdata.h" #endif //__SYS_PLAYER_DATA #if __VER >= 13 // __RAINBOW_RACE #include "RainbowRace.h" #endif //__RAINBOW_RACE #if __VER >= 14 // __NEW_CONTINENT #include "Continent.h" #endif // __NEW_CONTINENT extern CParty g_Party; ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CWorldMap::CWorldMap() { #if __VER < 14 // __NEW_CONTINENT m_mapView.clear(); #endif // __NEW_CONTINENT m_bRender = FALSE; m_pTexWorldMap = NULL; m_cPos.x = 0; m_cPos.y = 0; #if __VER >= 13 // __CSC_VER13_1 m_nSelMon = -1; m_bShowMonsterInfo = FALSE; #endif //__CSC_VER13_1 #if __VER >= 15 // __TELEPORTER m_bTeleportMode = FALSE; m_pTelPosTexture = NULL; m_idTeleporter = NULL_ID; #endif #if __VER >= 15 // __IMPROVE_QUEST_INTERFACE m_rectDestination = CRect( -1, -1, -1, -1 ); m_bDestinationMode = FALSE; m_pDestinationPositionTexture = NULL; m_nDestinationTextureAlpha = MINIMUM_ALPHA; m_tmOld = g_tmCurrent; m_bAlphaSwitch = FALSE; #endif // __IMPROVE_QUEST_INTERFACE #ifdef __IMPROVE15_WORLDMAP m_nSelected = 0; #endif } CWorldMap::~CWorldMap() { #if __VER >= 13 // __CSC_VER13_1 m_MonsterInfo.m_vecMonsterInfo.clear(); #endif //__CSC_VER13_1 #if __VER >= 13 // __RAINBOW_RACE m_RainbowNPC.m_vecRainbowNPC.clear(); #endif //__RAINBOW_RACE DeleteDeviceObjects(); } CWorldMap* CWorldMap::GetInstance( void ) { static CWorldMap sWorldMap; return &sWorldMap; } FLOAT _fMap_X1 = 7194.0f; FLOAT _fMap_Y1 = 2000.0f; FLOAT _fMap_X2 = 10100.0f; FLOAT _fMap_Y2 = 4250.0f; void CWorldMap::Init() { m_texArrow[0].LoadTexture( g_Neuz.m_pd3dDevice, MakePath( DIR_THEME,"ImgMapArrow.bmp"), 0xffff00ff ); m_texArrow[1].LoadTexture( g_Neuz.m_pd3dDevice, MakePath( DIR_THEME,"ImgMapArrowParty.bmp"), 0xffff00ff ); ZeroMemory( &m_billboard, sizeof( m_billboard ) ); m_billboard[0].rect.SetRect( 0, 0, m_texArrow[0].m_size.cx, m_texArrow[0].m_size.cy ); m_billboard[0].ptCenter = CPoint( m_texArrow[0].m_size.cx / 2, m_texArrow[0].m_size.cy / 2 ); m_billArrow[0].InitDeviceObjects( g_Neuz.m_pd3dDevice, &m_billboard[0], &m_texArrow[0] ); m_billArrow[0].RestoreDeviceObjects(); m_billboard[1].rect.SetRect( 0, 0, m_texArrow[1].m_size.cx, m_texArrow[1].m_size.cy ); m_billboard[1].ptCenter = CPoint( m_texArrow[1].m_size.cx / 2, m_texArrow[1].m_size.cy / 2 ); m_billArrow[1].InitDeviceObjects( g_Neuz.m_pd3dDevice, &m_billboard[1], &m_texArrow[1] ); m_billArrow[1].RestoreDeviceObjects(); #if __VER < 14 // __NEW_CONTINENT m_mapView.clear(); vector<CPoint> vecMap; // ํ”Œ๋ผ๋ฆฌ์Šค vecMap.clear(); vecMap.push_back( CPoint(6159, 3407) ); vecMap.push_back( CPoint(6350, 3825) ); vecMap.push_back( CPoint(6736, 4649) ); vecMap.push_back( CPoint(7246, 4570) ); vecMap.push_back( CPoint(8258, 5022) ); vecMap.push_back( CPoint(8213, 4367) ); vecMap.push_back( CPoint(8021, 4037) ); vecMap.push_back( CPoint(8017, 3496) ); vecMap.push_back( CPoint(7245, 2685) ); vecMap.push_back( CPoint(6783, 2631) ); vecMap.push_back( CPoint(6366, 2922) ); vecMap.push_back( CPoint(6159, 3407) ); m_mapView.insert( multimap< CString, vector<CPoint> >::value_type( "Flaris", vecMap ) ); // ์„ธ์ธํŠธ๋ชจ๋‹ vecMap.clear(); vecMap.push_back( CPoint(7253, 2684) ); vecMap.push_back( CPoint(8023, 3496) ); vecMap.push_back( CPoint(8029, 4039) ); vecMap.push_back( CPoint(8217, 4365) ); vecMap.push_back( CPoint(8609, 4187) ); vecMap.push_back( CPoint(9489, 3047) ); vecMap.push_back( CPoint(9289, 2130) ); vecMap.push_back( CPoint(8765, 1615) ); vecMap.push_back( CPoint(7855, 1554) ); vecMap.push_back( CPoint(7506, 1870) ); vecMap.push_back( CPoint(7253, 2684) ); m_mapView.insert( multimap< CString, vector<CPoint> >::value_type( "Saint", vecMap ) ); // ๋ฆฌ์‹œ์Šค์ •์› vecMap.clear(); vecMap.push_back( CPoint(9123, 3339) ); vecMap.push_back( CPoint(8922, 3740) ); vecMap.push_back( CPoint(8607, 4127) ); vecMap.push_back( CPoint(8285, 4397) ); vecMap.push_back( CPoint(8316, 4748) ); vecMap.push_back( CPoint(8833, 4762) ); vecMap.push_back( CPoint(9612, 4992) ); vecMap.push_back( CPoint(10436, 4396) ); vecMap.push_back( CPoint(9441, 3171) ); vecMap.push_back( CPoint(9123, 3339) ); m_mapView.insert( multimap< CString, vector<CPoint> >::value_type( "Ricis", vecMap ) ); // ๋‹ค์ฝ˜1 vecMap.clear(); vecMap.push_back( CPoint(4858, 2781) ); vecMap.push_back( CPoint(4561, 3613) ); vecMap.push_back( CPoint(4051, 3835) ); vecMap.push_back( CPoint(3796, 3790) ); vecMap.push_back( CPoint(3574, 4200) ); vecMap.push_back( CPoint(3455, 4479) ); vecMap.push_back( CPoint(3072, 4563) ); vecMap.push_back( CPoint(2833, 5237) ); vecMap.push_back( CPoint(3572, 5185) ); vecMap.push_back( CPoint(4863, 4778) ); vecMap.push_back( CPoint(6756, 4875) ); vecMap.push_back( CPoint(6558, 4367) ); vecMap.push_back( CPoint(6387, 3826) ); vecMap.push_back( CPoint(6102, 3298) ); vecMap.push_back( CPoint(5795, 2727) ); vecMap.push_back( CPoint(4858, 2781) ); m_mapView.insert( multimap< CString, vector<CPoint> >::value_type( "Darkon12", vecMap ) ); // ๋‹ค์ฝ˜2,3 vecMap.clear(); vecMap.push_back( CPoint(2834, 5241) ); vecMap.push_back( CPoint(3069, 4562) ); vecMap.push_back( CPoint(3451, 4476) ); vecMap.push_back( CPoint(3567, 4196) ); vecMap.push_back( CPoint(3792, 3791) ); vecMap.push_back( CPoint(4049, 3736) ); vecMap.push_back( CPoint(4555, 3615) ); vecMap.push_back( CPoint(4854, 2775) ); vecMap.push_back( CPoint(3395, 1291) ); vecMap.push_back( CPoint(1291, 2425) ); vecMap.push_back( CPoint(1867, 3867) ); vecMap.push_back( CPoint(1946, 4694) ); vecMap.push_back( CPoint(2834, 5241) ); m_mapView.insert( multimap< CString, vector<CPoint> >::value_type( "Darkon3", vecMap ) ); #endif // __NEW_CONTINENT m_strMapStringList[0] = "WORLD_Flyff.dds"; m_strMapStringList[1] = "WORLD_Darkon12.dds"; m_strMapStringList[2] = "WORLD_Darkon3.dds"; m_strMapStringList[3] = "WORLD_Ricis.dds"; m_strMapStringList[4] = "WORLD_Saint.dds"; m_strMapStringList[5] = "WORLD_Flaris.dds"; #if __VER >= 14 // __NEW_CONTINENT m_strMapStringList[6] = "WORLD_harmonin.dds"; #endif // __NEW_CONTINENT #if __VER >= 15 // __NEW_CONTINENT15 m_strMapStringList[7] = "WORLD_Estia.dds"; #endif // __NEW_CONTINENT15 m_texMapButton.LoadScript( g_Neuz.m_pd3dDevice, MakePath( DIR_THEME, _T( "texMapButton.inc" ) ) ); #if __VER >= 13 // __CSC_VER13_1 m_strMonScript[0] = "texMapMonster_Darkon12.inc"; m_strMonScript[1] = "texMapMonster_Darkon3.inc"; m_strMonScript[2] = "texMapMonster_Ricis.inc"; m_strMonScript[3] = "texMapMonster_Saint.inc"; m_strMonScript[4] = "texMapMonster_Flaris.inc"; #if __VER >= 14 // __NEW_CONTINENT m_strMonScript[5] = "texMapMonster_Harmonin.inc"; #endif //__NEW_CONTINENT #if __VER >= 15 // __NEW_CONTINENT15 m_strMonScript[6] = "texMapMonster_Estia.inc"; #endif //__NEW_CONTINENT15 #endif //__CSC_VER13_1 m_fRate = 0.0f; switch( g_Option.m_nResWidth ) { case 800: m_fRate = (FLOAT)800 / (FLOAT)1280; m_cpScreen.x = 800; m_cpScreen.y = 600; m_cOffset.x = (g_Option.m_nResWidth-m_cpScreen.x) / 2; m_cOffset.y = (g_Option.m_nResHeight-m_cpScreen.y) / 2; break; case 1024: m_fRate = (FLOAT)1024 / (FLOAT)1280; m_cpScreen.x = 1024; m_cpScreen.y = 768; m_cOffset.x = (g_Option.m_nResWidth-m_cpScreen.x) / 2; m_cOffset.y = (g_Option.m_nResHeight-m_cpScreen.y) / 2; break; case 1280: #if __VER >= 9 // __CSC_VER9_RESOLUTION if(g_Option.m_nResHeight == 720) //Wide { m_fRate = (FLOAT)1280 / (FLOAT)1280; m_cpScreen.x = 960; m_cpScreen.y = 720; m_cOffset.x = (g_Option.m_nResWidth-m_cpScreen.x) / 2; m_cOffset.y = (g_Option.m_nResHeight-m_cpScreen.y) / 2; } else if(g_Option.m_nResHeight == 768) //Wide { m_fRate = (FLOAT)1280 / (FLOAT)1280; m_cpScreen.x = 960; m_cpScreen.y = 768; m_cOffset.x = (g_Option.m_nResWidth-m_cpScreen.x) / 2; m_cOffset.y = (g_Option.m_nResHeight-m_cpScreen.y) / 2; } else if(g_Option.m_nResHeight == 800) //Wide { m_fRate = (FLOAT)1280 / (FLOAT)1280; m_cpScreen.x = 960; m_cpScreen.y = 800; m_cOffset.x = (g_Option.m_nResWidth-m_cpScreen.x) / 2; m_cOffset.y = (g_Option.m_nResHeight-m_cpScreen.y) / 2; } else { m_fRate = (FLOAT)1280 / (FLOAT)1280; m_cpScreen.x = 1280; m_cpScreen.y = 1024; m_cOffset.x = (g_Option.m_nResWidth-m_cpScreen.x) / 2; m_cOffset.y = (g_Option.m_nResHeight-m_cpScreen.y) / 2; } #else //__CSC_VER9_RESOLUTION m_fRate = (FLOAT)1280 / (FLOAT)1280; m_cpScreen.x = 1280; m_cpScreen.y = 960; m_cOffset.x = (g_Option.m_nResWidth-m_cpScreen.x) / 2; m_cOffset.y = (g_Option.m_nResHeight-m_cpScreen.y) / 2; #endif //__CSC_VER9_RESOLUTION break; #if __VER >= 9 // __CSC_VER9_RESOLUTION case 1360: m_fRate = (FLOAT)1360 / (FLOAT)1280; m_cpScreen.x = 1024; m_cpScreen.y = 768; m_cOffset.x = (g_Option.m_nResWidth-m_cpScreen.x) / 2; m_cOffset.y = (g_Option.m_nResHeight-m_cpScreen.y) / 2; break; case 1400: m_fRate = (FLOAT)1400 / (FLOAT)1280; m_cpScreen.x = 1400; m_cpScreen.y = 1050; m_cOffset.x = (g_Option.m_nResWidth-m_cpScreen.x) / 2; m_cOffset.y = (g_Option.m_nResHeight-m_cpScreen.y) / 2; break; case 1440: m_fRate = (FLOAT)1440 / (FLOAT)1280; m_cpScreen.x = 1200; m_cpScreen.y = 900; m_cOffset.x = (g_Option.m_nResWidth-m_cpScreen.x) / 2; m_cOffset.y = (g_Option.m_nResHeight-m_cpScreen.y) / 2; break; case 1600: m_fRate = (FLOAT)1600 / (FLOAT)1280; m_cpScreen.x = 1600; m_cpScreen.y = 1200; m_cOffset.x = (g_Option.m_nResWidth-m_cpScreen.x) / 2; m_cOffset.y = (g_Option.m_nResHeight-m_cpScreen.y) / 2; break; case 1680: m_fRate = (FLOAT)1680 / (FLOAT)1280; m_cpScreen.x = 1400; m_cpScreen.y = 1050; m_cOffset.x = (g_Option.m_nResWidth-m_cpScreen.x) / 2; m_cOffset.y = (g_Option.m_nResHeight-m_cpScreen.y) / 2; break; #endif //__CSC_VER9_RESOLUTION } #if __VER >= 14 // __NEW_CONTINENT m_fRate = (FLOAT)g_Option.m_nResHeight / (FLOAT)1024; #endif //__NEW_CONTINENT m_cPos.y = (LONG)( 80.0f * m_fRate ); FLOAT fGap = 0; #if __VER >= 9 // __CSC_VER9_RESOLUTION int wideOffsetX = 0; if((g_Option.m_nResWidth == 1360 || g_Option.m_nResWidth == 1440 || g_Option.m_nResWidth == 1680) || (g_Option.m_nResWidth == 1280 && (g_Option.m_nResHeight == 720 || g_Option.m_nResHeight == 768 || g_Option.m_nResHeight == 800))) //Wide Offset wideOffsetX = m_cOffset.x; CTexture *pTexture = m_texMapButton.GetAt(0); CPoint cp = CPoint( m_cPos.x, m_cPos.y ); m_cRect[0].SetRect( cp.x + wideOffsetX, cp.y, (int)( cp.x + ((FLOAT)pTexture->m_size.cx * m_fRate) + wideOffsetX ), (int)( cp.y+((FLOAT)pTexture->m_size.cy * m_fRate) ) ); pTexture = m_texMapButton.GetAt(3); cp.y = (LONG)( cp.y + ((FLOAT)pTexture->m_size.cy * m_fRate) + fGap ); m_cRect[1].SetRect( cp.x + wideOffsetX, cp.y, (int)( cp.x + ((FLOAT)pTexture->m_size.cx * m_fRate) + wideOffsetX ), (int)( cp.y+((FLOAT)pTexture->m_size.cy * m_fRate) ) ); pTexture = m_texMapButton.GetAt(6); cp.y = (LONG)( cp.y + ((FLOAT)pTexture->m_size.cy * m_fRate) + fGap ); m_cRect[2].SetRect( cp.x + wideOffsetX, cp.y, (int)( cp.x + ((FLOAT)pTexture->m_size.cx * m_fRate) + wideOffsetX ), (int)( cp.y+((FLOAT)pTexture->m_size.cy * m_fRate) ) ); cp.y = (LONG)( cp.y + ((FLOAT)pTexture->m_size.cy * m_fRate) + fGap ); pTexture = m_texMapButton.GetAt(9); m_cRect[3].SetRect( cp.x + wideOffsetX, cp.y, (int)( cp.x + ((FLOAT)pTexture->m_size.cx * m_fRate) + wideOffsetX ), (int)( cp.y+((FLOAT)pTexture->m_size.cy * m_fRate) ) ); cp.y = (LONG)( cp.y + ((FLOAT)pTexture->m_size.cy * m_fRate) + fGap ); pTexture = m_texMapButton.GetAt(12); m_cRect[4].SetRect( cp.x + wideOffsetX, cp.y, (int)( cp.x + ((FLOAT)pTexture->m_size.cx * m_fRate) + wideOffsetX ), (int)( cp.y+((FLOAT)pTexture->m_size.cy * m_fRate) ) ); cp.y = (LONG)( cp.y + ((FLOAT)pTexture->m_size.cy * m_fRate) + fGap ); pTexture = m_texMapButton.GetAt(15); m_cRect[5].SetRect( cp.x + wideOffsetX, cp.y, (int)( cp.x + ((FLOAT)pTexture->m_size.cx * m_fRate) + wideOffsetX ), (int)( cp.y+((FLOAT)pTexture->m_size.cy * m_fRate) ) ); #if __VER >= 13 // __CSC_VER13_1 cp.y = (LONG)( cp.y + ((FLOAT)pTexture->m_size.cy * m_fRate) + fGap ); pTexture = m_texMapButton.GetAt(18); m_cRect[6].SetRect( cp.x + wideOffsetX, cp.y, (int)( cp.x + ((FLOAT)pTexture->m_size.cx * m_fRate) + wideOffsetX ), (int)( cp.y+((FLOAT)pTexture->m_size.cy * m_fRate) ) ); #if __VER >= 14 // __NEW_CONTINENT cp.y = (LONG)( cp.y + ((FLOAT)pTexture->m_size.cy * m_fRate) + fGap ); pTexture = m_texMapButton.GetAt(21); m_cRect[7].SetRect( cp.x + wideOffsetX, cp.y, (int)( cp.x + ((FLOAT)pTexture->m_size.cx * m_fRate) + wideOffsetX ), (int)( cp.y+((FLOAT)pTexture->m_size.cy * m_fRate) ) ); #endif //__NEW_CONTINENT #if __VER >= 15 // __NEW_CONTINENT15 cp.y = (LONG)( cp.y + ((FLOAT)pTexture->m_size.cy * m_fRate) + fGap ); pTexture = m_texMapButton.GetAt(24); m_cRect[8].SetRect( cp.x + wideOffsetX, cp.y, (int)( cp.x + ((FLOAT)pTexture->m_size.cx * m_fRate) + wideOffsetX ), (int)( cp.y+((FLOAT)pTexture->m_size.cy * m_fRate) ) ); #endif // __NEW_CONTINENT15 #endif //__CSC_VER13_1 #else //__CSC_VER9_RESOLUTION CTexture *pTexture = m_texMapButton.GetAt(0); CPoint cp = CPoint( m_cPos.x, m_cPos.y ); m_cRect[0].SetRect( cp.x, cp.y, cp.x + ((FLOAT)pTexture->m_size.cx * m_fRate), cp.y+((FLOAT)pTexture->m_size.cy * m_fRate) ); pTexture = m_texMapButton.GetAt(3); cp.y += ((FLOAT)pTexture->m_size.cy * m_fRate) + fGap; m_cRect[1].SetRect( cp.x, cp.y, cp.x + ((FLOAT)pTexture->m_size.cx * m_fRate), cp.y+((FLOAT)pTexture->m_size.cy * m_fRate) ); pTexture = m_texMapButton.GetAt(6); cp.y += ((FLOAT)pTexture->m_size.cy * m_fRate) + fGap; m_cRect[2].SetRect( cp.x, cp.y, cp.x + ((FLOAT)pTexture->m_size.cx * m_fRate), cp.y+((FLOAT)pTexture->m_size.cy * m_fRate) ); cp.y += ((FLOAT)pTexture->m_size.cy * m_fRate) + fGap; pTexture = m_texMapButton.GetAt(9); m_cRect[3].SetRect( cp.x, cp.y, cp.x + ((FLOAT)pTexture->m_size.cx * m_fRate), cp.y+((FLOAT)pTexture->m_size.cy * m_fRate) ); cp.y += ((FLOAT)pTexture->m_size.cy * m_fRate) + fGap; pTexture = m_texMapButton.GetAt(12); m_cRect[4].SetRect( cp.x, cp.y, cp.x + ((FLOAT)pTexture->m_size.cx * m_fRate), cp.y+((FLOAT)pTexture->m_size.cy * m_fRate) ); cp.y += ((FLOAT)pTexture->m_size.cy * m_fRate) + fGap; pTexture = m_texMapButton.GetAt(15); m_cRect[5].SetRect( cp.x, cp.y, cp.x + ((FLOAT)pTexture->m_size.cx * m_fRate), cp.y+((FLOAT)pTexture->m_size.cy * m_fRate) ); #endif //__CSC_VER9_RESOLUTION m_nDrawMenu[0] = 0; m_nDrawMenu[1] = 3; m_nDrawMenu[2] = 6; m_nDrawMenu[3] = 9; m_nDrawMenu[4] = 12; m_nDrawMenu[5] = 15; #if __VER >= 13 // __CSC_VER13_1 m_nDrawMenu[6] = 18; #if __VER >= 14 // __NEW_CONTINENT m_nDrawMenu[7] = 21; #endif //__NEW_CONTINENT #if __VER >= 15 // __NEW_CONTINENT15 m_nDrawMenu[8] = 24; #endif #endif //__CSC_VER13_1 m_bRender = FALSE; } void CWorldMap::Process() { m_nDrawMenu[0] = 0; m_nDrawMenu[1] = 3; m_nDrawMenu[2] = 6; m_nDrawMenu[3] = 9; m_nDrawMenu[4] = 12; m_nDrawMenu[5] = 15; #if __VER >= 13 // __CSC_VER13_1 m_nDrawMenu[6] = 18; #if __VER >= 14 // __NEW_CONTINENT m_nDrawMenu[7] = 21; #endif //__NEW_CONTINENT #if __VER >= 15 // __NEW_CONTINENT15 m_nDrawMenu[8] = 24; #endif //__NEW_CONTINENT15 #endif //__CSC_VER13_1 CWndWorld* pWndWorld = (CWndWorld*)g_WndMng.GetApplet( APP_WORLD ); if( pWndWorld ) { CPoint point = pWndWorld->GetMousePoint(); #ifndef __IMPROVE15_WORLDMAP #if __VER >= 13 // __CSC_VER13_1 int i; for( i = 0 ; i < MAX_BUTTON ; ++i ) #else //__CSC_VER13_1 int i; for( i = 0 ; i < 6 ; ++i ) #endif //__CSC_VER13_1 { if( m_nMap != i && m_cRect[i].PtInRect( point ) ) { m_nDrawMenu[i] = m_nDrawMenu[i] + 1; } } #endif // __IMPROVE15_WORLDMAP #if __VER >= 13 // __CSC_VER13_1 if(m_bShowMonsterInfo && this->IsRender()) { BOOL bSel = FALSE; for(int i=0; i<(int)( m_MonsterInfo.GetNumber() ); i++) { __MONSTER_INFO stMonsterInfo = m_MonsterInfo.m_vecMonsterInfo[i]; if(stMonsterInfo.m_rectPos.PtInRect(point)) { CEditString strEdit; CString strTemp; for(int j=0; j<stMonsterInfo.m_nMonCnt; j++) { MoverProp* pMoverProp = prj.GetMoverProp(stMonsterInfo.m_dwMonsterId[j]); if(pMoverProp) { strTemp.Format( prj.GetText( TID_GAME_MONSTER_INFORMATION_LEVEL ) ); strEdit.AddString(strTemp, D3DCOLOR_XRGB(0, 0, 255)); strTemp.Format("%d ", pMoverProp->dwLevel); strEdit.AddString(strTemp, D3DCOLOR_XRGB(130, 130, 200)); strTemp.Format("%s", pMoverProp->szName); if(j+1 == stMonsterInfo.m_nMonCnt) //๊ฑฐ๋Œ€๋งŒ ๋นจ๊ฐ„์ƒ‰์œผ๋กœ ํ‘œ์‹œ strEdit.AddString(strTemp, D3DCOLOR_XRGB(255, 0, 0)); else strEdit.AddString(strTemp); strEdit.AddString("\n"); for(int k=0; k<(int)( pMoverProp->m_DropItemGenerator.GetSize() ); k++) { DROPITEM* pDropItem = pMoverProp->m_DropItemGenerator.GetAt(k, FALSE); } } } strEdit.AddString("\n"); ItemProp* pItemProp = prj.GetItemProp( stMonsterInfo.m_dwDropItemId ); strTemp.Format("%s : ", prj.GetText(TID_GAME_DROP_ITEM)); strEdit.AddString(strTemp); if(pItemProp) { strTemp.Format("%s", pItemProp->szName); strEdit.AddString(strTemp, D3DCOLOR_XRGB(46, 112, 169)); } else strEdit.AddString(prj.GetText(TID_GAME_DROP_NONE)); g_toolTip.PutToolTip(10000, strEdit, stMonsterInfo.m_rectPos, point, 0); #ifndef __IMPROVE_MAP_SYSTEM g_toolTip.SetWorldMapMonsterInfo(stMonsterInfo.m_nMonCnt, stMonsterInfo.m_dwMonsterId); #endif // __IMPROVE_MAP_SYSTEM m_nSelMon = i; bSel = TRUE; } } if(!bSel) m_nSelMon = -1; } #endif //__CSC_VER13_1 } } void CWorldMap::RenderPlayer( C2DRender *p2DRender, BOOL bMyPlayer, D3DXVECTOR3 vPos, const TCHAR* szName ) { #if __VER >= 14 // __NEW_CONTINENT int nMap = CContinent::GetInstance()->GetMapNo( vPos ); #else // __NEW_CONTINENT int nMap = GetMapNo( vPos ); #endif // __NEW_CONTINENT if( m_nMap !=0 && m_nMap != nMap ) return; // ์ฃผ์ธ๊ณต ํ™”์‚ดํ‘œ ์ถœ๋ ฅ // ํ™”๋ฉด ๋น„์œจ ๋•Œ๋ฌธ์— ์ž„์˜๋กœ ์ •์‚ฌ๊ฐํ˜• ๋ทฐํฌํŠธ๋ฅผ ์ง€์ •ํ•ด ๋†“๋Š”๋‹ค. ์•ˆ๊ทธ๋Ÿฌ๋ฉด ํ™”์‚ดํ‘œ ๋ชจ์–‘์ด ์ฐŒ๊ทธ๋Ÿฌ์ง. #if __VER >= 9 // __CSC_VER9_RESOLUTION D3DVIEWPORT9 viewport; if((g_Option.m_nResWidth == 1360 || g_Option.m_nResWidth == 1440 || g_Option.m_nResWidth == 1680) || (g_Option.m_nResWidth == 1280 && (g_Option.m_nResHeight == 720 || g_Option.m_nResHeight == 768 || g_Option.m_nResHeight == 800))) //Wide Offset { viewport.X = m_cOffset.x; viewport.Y = 0; viewport.Width = m_cpScreen.x; viewport.Height = m_cpScreen.y; viewport.MinZ = 0.0f; viewport.MaxZ = 1.0f; } else { viewport.X = 0; viewport.Y = 0; viewport.Width = g_Option.m_nResWidth; viewport.Height = g_Option.m_nResHeight; viewport.MinZ = 0.0f; viewport.MaxZ = 1.0f; } #else //__CSC_VER9_RESOLUTION D3DVIEWPORT9 viewport; viewport.X = 0; viewport.Y = 0; viewport.Width = g_Option.m_nResWidth; viewport.Height = g_Option.m_nResHeight; viewport.MinZ = 0.0f; viewport.MaxZ = 1.0f; #endif //__CSC_VER9_RESOLUTION D3DDEVICE->SetViewport( &viewport ); // ํ”„๋กœ์ ์…˜ D3DXMATRIX matProj; D3DXMatrixIdentity( &matProj ); D3DDEVICE->SetTransform( D3DTS_PROJECTION, &matProj ); // ์นด๋ฉ”๋ผ D3DXMATRIX matView; D3DXMatrixIdentity( &matView ); D3DDEVICE->SetTransform( D3DTS_VIEW, &matView ); D3DXMATRIX mat, matWorld; D3DXMatrixIdentity( &matWorld ); D3DXMatrixScaling( &mat, 0.07f, 0.07f, 0.07f ); D3DXMatrixMultiply( &matWorld, &matWorld, &mat ); D3DXVECTOR3 vDir = D3DXVECTOR3( 0.0f, 0.0f, 1.0f ); D3DXVECTOR3 vDestNor; if( bMyPlayer ) vDestNor = vPos - g_Neuz.m_camera.m_vPos; else vDestNor = vPos; D3DXVECTOR3 vAxis; D3DXQUATERNION qRot; FLOAT fTheta; D3DXVec3Normalize( &vDestNor, &vDestNor ); D3DXVec3Cross( &vAxis, &vDir, &vDestNor ); fTheta = D3DXVec3Dot( &vDir, &vDestNor ); D3DXQuaternionRotationAxis( &qRot, &vAxis, acosf( fTheta ) ); D3DXVECTOR3 vYPW; QuaternionRotationToYPW( qRot, vYPW ); D3DXMatrixRotationZ( &mat, -(vYPW.y) ); D3DXMatrixMultiply( &matWorld, &matWorld, &mat ); FLOAT fMap_X1 = _fMap_X1; FLOAT fMap_Y1 = _fMap_Y1; FLOAT fMap_X2 = _fMap_X2; FLOAT fMap_Y2 = _fMap_Y2; #if __VER >= 14 // __NEW_CONTINENT if( m_nMap == 0 ) #else __NEW_CONTINENT if( m_strViewMapString == m_strMapStringList[0] ) #endif // __NEW_CONTINENT { fMap_X1 = 0.0f; fMap_Y1 = 1298.0f;//0.0f; fMap_X2 = 11800.0f; fMap_Y2 = 9757.0f; //9000.0f; // DDS ์˜ ์ „์ฒดํฌ๊ธฐ 1280,960์„ ์‹ค์ œ ํฌ๊ธฐ์— ๋Œ€ํ•œ ์‚ฌ์ด๊ธธ์ด ( ์ƒ๋‹จ 123, ํ•˜๋‹จ 30 )๋ฅผ ๊ตฌํ•œํ›„ ์‹ค์ œํฌ๊ธฐ์— ํ•ด๋‹นํ•˜๋Š” // ์›”๋“œ ์‹ค์ œ์ขŒํ‘œ๋ฅผ ๊ตฌํ•ด์„œ( 8662, 1770 ) ์‚ฌ์ด๊ธธ์ด๋ฅผ ์‹ค์ œํฌ๊ธฐ๋กœ ํ™˜์‚ฐํ•œํ›„ ๊ฐ ์ขŒํ‘œ์— ๋”ํ•˜๊ณ ( ์ƒ๋‹จ ) ๋นผ์ค€๋‹ค( ํ•˜๋‹จ ) } else #if __VER >= 14 // __NEW_CONTINENT if( m_nMap == 1 ) #else __NEW_CONTINENT if( m_strViewMapString == m_strMapStringList[1] ) // ๋‹ค์ฝ˜ 1, 2 #endif // __NEW_CONTINENT { fMap_X1 = 2355.0f; fMap_Y1 = 2019.0f; fMap_X2 = 7187.0f; fMap_Y2 = 5814.0f; } else #if __VER >= 14 // __NEW_CONTINENT if( m_nMap == 2 ) #else __NEW_CONTINENT if( m_strViewMapString == m_strMapStringList[2] ) // ๋‹ค์ฝ˜ 3 #endif // __NEW_CONTINENT { fMap_X1 = 985.0f; fMap_Y1 = 1621.0f; fMap_X2 = 5754.0f; fMap_Y2 = 5149.0f; } else #if __VER >= 14 // __NEW_CONTINENT if( m_nMap == 3 ) #else __NEW_CONTINENT if( m_strViewMapString == m_strMapStringList[3] ) // ๋ฆฌ์‹œ์Šค #endif // __NEW_CONTINENT { fMap_X1 = 8080.0f; fMap_Y1 = 3200.0f; fMap_X2 = 10280.0f; fMap_Y2 = 5000.0f; } else #if __VER >= 14 // __NEW_CONTINENT if( m_nMap == 4 ) #else __NEW_CONTINENT if( m_strViewMapString == m_strMapStringList[4] ) // ์„ธ์ธํŠธ๋ชจ๋‹ #endif // __NEW_CONTINENT { fMap_X1 = 6854.0f; fMap_Y1 = 1580.0f; fMap_X2 = 10600.0f; fMap_Y2 = 4430.0f; } else #if __VER >= 14 // __NEW_CONTINENT if( m_nMap == 5 ) #else __NEW_CONTINENT if( m_strViewMapString == m_strMapStringList[5] ) // ํ”Œ๋ผ๋ฆฌ์Šค #endif // __NEW_CONTINENT { fMap_X1 = 5500.0f; fMap_Y1 = 2540.0f; fMap_X2 = 9200.0f; fMap_Y2 = 5130.0f; } #if __VER >= 14 // __NEW_CONTINENT else if( m_nMap == 6 ) // ํ•˜๋ฅด๋ชจ๋‹Œ { fMap_X1 = 4795.0f; // ui๋งต์˜ ํ…Œ๋‘๋ฆฌ ๋Œ€ ๋Œ€๋ฅ™์‚ฌ์ด์ฆˆ ๋น„์œจ์„ ์ด์šฉํ•ด ์‹ค์ œ ์›”๋“œ๋Œ€๋ฅ™์ขŒํ‘œ์— ์ ์šฉ์‹œํ‚จ ui์˜ ํ…Œํˆฌ๋ฆฌ์— ํ•ด๋‹นํ•˜๋Š” ์›”๋“œ ์ขŒํ‘œ fMap_Y1 = 4587.0f; fMap_X2 = 8391.0f; fMap_Y2 = 7236.0f; } #endif //__NEW_CONTINENT #if __VER >= 15 // __NEW_CONTINENT15 else if( m_nMap == 7 ) // ์ด์Šคํ‹ฐ์•„ ์บ๋‹ˆ์–ธ { fMap_X1 = 5150.0f; fMap_Y1 = 5573.0f; fMap_X2 = 9890.0f; fMap_Y2 = 9158.0f; } #endif FLOAT fX = fMap_X2 - fMap_X1; FLOAT fY = fMap_Y1 - fMap_Y2; D3DXVECTOR3 v1 = D3DXVECTOR3( -1, 1, -1 ); D3DXVECTOR3 v2 = D3DXVECTOR3( 1, -1, 1 ); D3DXVECTOR3 v3 = D3DXVECTOR3( 1, 1, 1 ); FLOAT fRate1 = (fMap_X2 - vPos.x) / fX ; FLOAT fRate2 = (fMap_Y1 - vPos.z) / fY ; D3DXVec3Lerp( &v3, &v1, &v2, fRate1 ); matWorld._41 = -v3.x; D3DXVec3Lerp( &v3, &v1, &v2, fRate2 ); matWorld._42 = -v3.y; D3DDEVICE->SetTransform( D3DTS_WORLD, &matWorld ); D3DDEVICE->SetSamplerState( 0, D3DSAMP_MINFILTER, D3DTEXF_POINT ); D3DDEVICE->SetSamplerState( 0, D3DSAMP_MAGFILTER, D3DTEXF_POINT ); // ํ™”์‚ดํ‘œ ์ถœ๋ ฅ if( bMyPlayer ) m_billArrow[0].Render( D3DDEVICE ); else m_billArrow[1].Render( D3DDEVICE ); { int nX; int nY; #if __VER >= 9 // __CSC_VER9_RESOLUTION if((g_Option.m_nResWidth == 1360 || g_Option.m_nResWidth == 1440 || g_Option.m_nResWidth == 1680) || (g_Option.m_nResWidth == 1280 && (g_Option.m_nResHeight == 720 || g_Option.m_nResHeight == 768 || g_Option.m_nResHeight == 800))) //Wide Offset { v1 = D3DXVECTOR3( (FLOAT)( m_cOffset.x ), 0.0f, 0.0f ); v2 = D3DXVECTOR3( (FLOAT)( m_cpScreen.x + m_cOffset.x ), (FLOAT)( m_cpScreen.y ), 0.0f ); } else { v1 = D3DXVECTOR3( 0.0f, 0.0f, 0.0f ); v2 = D3DXVECTOR3( (FLOAT)( g_Option.m_nResWidth ), (FLOAT)( g_Option.m_nResHeight ), 0.0f ); } #else //__CSC_VER9_RESOLUTION v1 = D3DXVECTOR3( 0.0f, 0.0f, 0.0f ); v2 = D3DXVECTOR3( (FLOAT)( g_Option.m_nResWidth ), (FLOAT)( g_Option.m_nResHeight ), 0.0f ); #endif //__CSC_VER9_RESOLUTION D3DXVec3Lerp( &v3, &v2, &v1, fRate1 ); nX = (int)( v3.x ); D3DXVec3Lerp( &v3, &v2, &v1, fRate2 ); nY = (int)( v3.y ); CD3DFont* pOldFont = p2DRender->GetFont(); p2DRender->SetFont( CWndBase::m_Theme.m_pFontWorld ); CSize cPos = p2DRender->GetFont()->GetTextExtent( szName ); nX -= cPos.cx / 2; nY -= (cPos.cy + (cPos.cy / 2)); // sun!! // nX *= 0.5f; // nY *= 0.5f; if( bMyPlayer ) p2DRender->TextOut( nX, nY, szName, 0xff7fff7f ); else p2DRender->TextOut( nX, nY, szName, 0xffffff7f ); p2DRender->SetFont( pOldFont ); } } void CWorldMap::RenderWorldMap( C2DRender *p2DRender ) { if( m_bRender ) { #if __VER >= 9 // __CSC_VER9_RESOLUTION if((g_Option.m_nResWidth == 1360 || g_Option.m_nResWidth == 1440 || g_Option.m_nResWidth == 1680) || (g_Option.m_nResWidth == 1280 && (g_Option.m_nResHeight == 720 || g_Option.m_nResHeight == 768 || g_Option.m_nResHeight == 800))) //Wide Background Black p2DRender->RenderFillRect( CRect( 0, 0, g_Option.m_nResWidth, g_Option.m_nResHeight ), 0xff000000 ); else p2DRender->RenderFillRect( CRect( 0, 0, g_Option.m_nResWidth, g_Option.m_nResHeight ), 0xff3B3D2F ); #else //__CSC_VER9_RESOLUTION p2DRender->RenderFillRect( CRect( 0, 0, g_Option.m_nResWidth, g_Option.m_nResHeight ), 0xff3B3D2F ); #endif //__CSC_VER9_RESOLUTION p2DRender->RenderTextureEx( CPoint(m_cOffset.x, m_cOffset.y), m_cpScreen, m_pTexWorldMap, 255, 1.0f, 1.0f ); #if __VER >= 15 // __TELEPORTER if( m_bTeleportMode ) RenderTelPos( p2DRender ); #endif #if __VER >= 15 // __IMPROVE_QUEST_INTERFACE if( m_bDestinationMode == TRUE ) RenderDestinationPosition( p2DRender ); #endif // __IMPROVE_QUEST_INTERFACE RenderPlayer( p2DRender, TRUE, g_pPlayer->GetPos( ) , g_pPlayer->GetName() ); int i; for( i = 0 ; i < g_Party.GetSizeofMember() ; ++i ) { if( g_pPlayer->m_idPlayer != g_Party.GetPlayerId( i ) ) { if( !g_Party.m_aMember[ i ].m_bRemove ) #if __VER >= 11 // __SYS_PLAYER_DATA RenderPlayer( p2DRender, FALSE, g_Party.GetPos( i ), CPlayerDataCenter::GetInstance()->GetPlayerString( g_Party.m_aMember[ i ].m_uPlayerId ) ); #else // __SYS_PLAYER_DATA RenderPlayer( p2DRender, FALSE, g_Party.GetPos( i ), g_Party.m_aMember[ i ].m_szName ); #endif // __SYS_PLAYER_DATA } } FLOAT fGap = 0; CPoint cp; m_nDrawMenu[m_nMap] = m_nDrawMenu[m_nMap] + 2; CTexture *pTexture; #ifndef __IMPROVE15_WORLDMAP // ๋Œ€๋ฅ™ ์ด๋ฏธ์ง€ ๋ฒ„ํŠผ ์ œ๊ฑฐ #if __VER >= 13 // __CSC_VER13_1 for( i = 0; i < MAX_BUTTON; ++i ) #else //__CSC_VER13_1 for( i = 0; i < 6; ++i ) #endif //__CSC_VER13_1 { pTexture = m_texMapButton.GetAt(m_nDrawMenu[i]); if( pTexture ) { cp.x = m_cRect[i].left; cp.y = m_cRect[i].top; pTexture->RenderScal( p2DRender, cp, 255, m_fRate, m_fRate ); } } #endif // __IMPROVE15_WORLDMAP #if __VER >= 13 // __CSC_VER13_1 if(m_bShowMonsterInfo && m_nMap > 0) { for(i=0; i<(int)( m_MonsterInfo.GetNumber() ); i++) { pTexture = m_MonsterInfo.GetAt(i); if( pTexture ) { __MONSTER_INFO stMonsterInfo = m_MonsterInfo.m_vecMonsterInfo[i]; cp.x = stMonsterInfo.m_rectPos.left; cp.y = stMonsterInfo.m_rectPos.top; if(m_nSelMon == i) pTexture->RenderScal( p2DRender, cp, 255, m_fRate, m_fRate ); else pTexture->RenderScal( p2DRender, cp, 150, m_fRate, m_fRate ); } } if(m_nSelMon > -1) g_toolTip.Paint(p2DRender); } #endif //__CSC_VER13_1 #if __VER >= 13 // __RAINBOW_RACE DWORD dwRainbowRaceTime = CRainbowRace::GetInstance()->m_dwRemainTime; if(dwRainbowRaceTime > 0) { for(i=0; i<(int)( m_RainbowNPC.GetNumber() ); i++) { __RAINBOW_NPC stRainbowNPC = m_RainbowNPC.m_vecRainbowNPC[i]; if(m_nMap == 0) { pTexture = m_RainbowNPC.GetAt(i); if(pTexture) { cp.x = stRainbowNPC.m_rectTotalMapPos.left; cp.y = stRainbowNPC.m_rectTotalMapPos.top; pTexture->RenderScal( p2DRender, cp, 255, m_fRate, m_fRate ); } } else { if(stRainbowNPC.m_nMap == m_nMap) { pTexture = m_RainbowNPC.GetAt(i); if(pTexture) { cp.x = stRainbowNPC.m_rectPos.left; cp.y = stRainbowNPC.m_rectPos.top; pTexture->RenderScal( p2DRender, cp, 255, m_fRate, m_fRate ); } } } } } #endif //__RAINBOW_RACE #ifdef __IMPROVE15_WORLDMAP CPoint oldPoint = p2DRender->m_ptOrigin; CRectClip oldClipRect = p2DRender->m_clipRect; m_pWndList->Paint( p2DRender ); p2DRender->m_ptOrigin = oldPoint; p2DRender->m_clipRect = oldClipRect; #endif } } BOOL CWorldMap::LoadWorldMap() { // ์ „์ฒด ๋งต์ค‘์— ๋‚ด๊ฐ€ ํ˜„์žฌ ์–ด๋””์— ์žˆ๋Š”์ง€๋ฅผ ๊ฒ€์‚ฌํ•œ๋‹ค. #if __VER >= 14 // __NEW_CONTINENT int nMap = CContinent::GetInstance()->GetMapNo( g_pPlayer ); #else // __NEW_CONTINENT int nMap = GetMapNo( g_pPlayer->GetPos() ); #endif // __NEW_CONTINENT #ifdef __IMPROVE15_WORLDMAP m_pWndList = new CWndListBox; CRect rect( 50, 200, 200, 600 ); ((CWndStatic*)m_pWndList)->m_strTexture = CString("WndEditTile00.tga"); CWndWorld* pWndWorld = (CWndWorld*)g_WndMng.GetWndBase( APP_WORLD ); m_pWndList->Create( WBS_CHILD, rect, pWndWorld, 0 ); // int i; for( i = 0; i < MAX_BUTTON; ++i ) // m_pWndList->AddString( CContinent::GetInstance()->GetContinentName( i ).GetBuffer( 0 ) ); //๋Œ€๋ฅ™ ์ธ๋ฑ์Šค ์ž‘์—…์ด ์•ˆ๋ผ์žˆ์–ด์„œ ๊ฑ ์ผ๋‹จ ํ…Œ์ŠคํŠธ๋กœ.. m_pWndList->AddString( "WORLD" ); m_pWndList->AddString( "Darkon1,2" ); m_pWndList->AddString( "Darkon3" ); m_pWndList->AddString( "Ricis" ); m_pWndList->AddString( "Saint Morning" ); m_pWndList->AddString( "Flaris" ); m_pWndList->AddString( "Harmonin" ); m_pWndList->AddString( "Estia" ); m_pWndList->AddString( "MONSTER" ); #endif //__IMPROVE15_WORLDMAP #if __VER >= 15 // __TELEPORTER if( m_bTeleportMode ) nMap = CONT_NODATA; #endif #if __VER >= 15 // __IMPROVE_QUEST_INTERFACE if( m_bDestinationMode == TRUE ) nMap = CONT_NODATA; #endif // __IMPROVE_QUEST_INTERFACE if( nMap != 100 ) { m_strViewMapString = m_strMapStringList[nMap]; m_pTexWorldMap = CWndBase::m_textureMng.AddTexture( g_Neuz.m_pd3dDevice, MakePath( "Theme\\", ::GetLanguage(), m_strViewMapString ), 0xff000000 ); #if __VER >= 13 // __CSC_VER13_1 #if __VER >= 14 // __NEW_CONTINENT if(nMap > 0 && nMap < MAX_BUTTON - 1 && m_MonsterInfo.m_nMap != nMap) #else // __NEW_CONTINENT if(nMap > 0 && nMap < 6 && m_MonsterInfo.m_nMap != nMap) #endif // __NEW_CONTINENT { m_MonsterInfo.DeleteDeviceObjects(); m_MonsterInfo.LoadScript( g_Neuz.m_pd3dDevice, MakePath( DIR_THEME, _T( m_strMonScript[nMap-1] ) ), nMap ); } #endif //__CSC_VER13_1 #if __VER >= 13 // __RAINBOW_RACE m_RainbowNPC.LoadScript( g_Neuz.m_pd3dDevice, MakePath( DIR_THEME, _T( "texMapRainbow_NPC.inc" ) ) ); #endif //__RAINBOW_RACE if( m_pTexWorldMap ) { m_nMap = nMap; m_bRender = TRUE; return TRUE; } } else { m_strViewMapString.Empty(); #if __VER >= 9 // __INSERT_MAP g_WndMng.PutString( prj.GetText(TID_GAME_MAPMSG), NULL, prj.GetTextColor(TID_GAME_MAPMSG) ); #endif } return FALSE; } #if __VER < 14 // __NEW_CONTINENT int CWorldMap::GetMapNo( D3DXVECTOR3 vPos ) { BOOL bResult = 100; CString str; CPoint cpoint; vector<CPoint> vecPoint; cpoint.x = vPos.x; cpoint.y = vPos.z; for( multimap< CString, vector<CPoint> >::iterator iter = m_mapView.begin(); iter != m_mapView.end(); ++iter ) { str = iter->first; vecPoint = iter->second; if( Point_In_Poly( vecPoint, cpoint ) ) { if( str == CString( "Darkon12" ) ) bResult = 1; else if( str == CString( "Darkon3" ) ) bResult = 2; else if( str == CString( "Ricis" ) ) bResult = 3; else if( str == CString( "Saint" ) ) bResult = 4; else if( str == CString( "Flaris" ) ) bResult = 5; #if __VER >= 14 // __NEW_CONTINENT else if( str == CString( "Harmonin" ) ) bResult = 6; #endif //__NEW_CONTINENT #if __VER >= 15 // __NEW_CONTINENT15 else if( str == CString( "Estia" ) ) bResult = 7; #endif //__NEW_CONTINENT15 } } return bResult; } #endif // __NEW_CONTINENT void CWorldMap::DeleteWorldMap() { // m_pTexWorldMap->DeleteDeviceObjects(); m_bRender = FALSE; #if __VER >= 15 // __TELEPORTER m_bTeleportMode = FALSE; m_idTeleporter = NULL_ID; #endif #if __VER >= 15 // __IMPROVE_QUEST_INTERFACE m_bDestinationMode = FALSE; #endif // __IMPROVE_QUEST_INTERFACE #ifdef __IMPROVE15_WORLDMAP SAFE_DELETE( m_pWndList ); #endif } void CWorldMap::DeleteDeviceObjects() { // m_pTexWorldMap->DeleteDeviceObjects(); m_texArrow[0].DeleteDeviceObjects(); m_texArrow[1].DeleteDeviceObjects(); m_billArrow[0].DeleteDeviceObjects(); m_billArrow[1].DeleteDeviceObjects(); m_texMapButton.DeleteDeviceObjects(); #if __VER >= 13 // __CSC_VER13_1 m_MonsterInfo.DeleteDeviceObjects(); #endif //__CSC_VER13_1 #if __VER >= 13 // __RAINBOW_RACE m_RainbowNPC.DeleteDeviceObjects(); #endif //__RAINBOW_RACE } void CWorldMap::RestoreDeviceObjects() { // m_pTexWorldMap->DeleteDeviceObjects(); m_texArrow[0].DeleteDeviceObjects(); m_billArrow[0].DeleteDeviceObjects(); m_texArrow[1].DeleteDeviceObjects(); m_billArrow[1].DeleteDeviceObjects(); m_texMapButton.RestoreDeviceObjects(g_Neuz.m_pd3dDevice); #if __VER >= 13 // __CSC_VER13_1 m_MonsterInfo.RestoreDeviceObjects(g_Neuz.m_pd3dDevice); #endif //__CSC_VER13_1 #if __VER >= 13 // __RAINBOW_RACE m_RainbowNPC.RestoreDeviceObjects(g_Neuz.m_pd3dDevice); #endif //__RAINBOW_RACE } void CWorldMap::InvalidateDeviceObjects() { m_billArrow[0].InvalidateDeviceObjects(); m_billArrow[1].InvalidateDeviceObjects(); m_texMapButton.InvalidateDeviceObjects(); #if __VER >= 13 // __CSC_VER13_1 m_MonsterInfo.InvalidateDeviceObjects(); #endif //__CSC_VER13_1 #if __VER >= 13 // __RAINBOW_RACE m_RainbowNPC.InvalidateDeviceObjects(); #endif //__RAINBOW_RACE } void CWorldMap::OnLButtonDown( ) { CWndWorld* pWndWorld = (CWndWorld*)g_WndMng.GetApplet( APP_WORLD ); if( !pWndWorld ) return; #if __VER >= 15 // __TELEPORTER if( m_bTeleportMode ) { CPoint pt = pWndWorld->GetMousePoint( ); int max_size = m_cTelPosRects.size(); int i; for( i = 0; i < max_size; ++i ) { WMapIcon& kIcon = m_cTelPosRects[ i ]; CRect& rect = kIcon._rect; if( rect.PtInRect( pt ) ) { // ํ•ด๋‹น ํฌ์ง€์…˜ ๋ฒ„ํŠผ์„ ๋ˆŒ๋ €๋‹ค. CMover* pMover = prj.GetMover( m_idTeleporter ); if( !pMover ) return; PLAYSND( SND_INF_CLICK ); g_DPlay.SendTeleporterReq( pMover->m_szCharacterKey, kIcon._index ); DeleteWorldMap( ); return; } } } #endif //__TELEPORTER #ifdef __IMPROVE15_WORLDMAP m_pWndList->OnLButtonDown( 1, m_pWndList->GetMousePoint() );//WindowProc( message, wParam, lParam ); if( m_pWndList->GetCurSel() < MAX_BUTTON ) { //๋ชฌ์Šคํ„ฐ ์ •๋ณด๋Š” ์„ ํƒ์•ˆ๋˜๊ณ  ์ฐ์œผ๋ฉด ๋ชฌ์Šคํ„ฐ ์ •๋ณด๋งŒ ๋ณด์—ฌ์ฃผ๊ธฐ int nowMapNum = 0; nowMapNum = m_pWndList->GetCurSel(); // if( nowMapNum == MAX_BUTTON -1 ) // m_pWndList->SetCurSel( m_nMap ); // else if( nowMapNum > -1 && nowMapNum < MAX_BUTTON - 1 ) { m_nMap = nowMapNum; #if __VER >= 15 // __TELEPORTER UpdateTeleportWorld( ); #endif #if __VER >= 15 // __IMPROVE_QUEST_INTERFACE UpdateDestinationPosition( pWndWorld->m_vDestinationArrow ); #endif // __IMPROVE_QUEST_INTERFACE m_strViewMapString = m_strMapStringList[nowMapNum]; m_pTexWorldMap = CWndBase::m_textureMng.AddTexture( g_Neuz.m_pd3dDevice, MakePath( "Theme\\", ::GetLanguage(), m_strViewMapString ), 0xff000000 ); if(nowMapNum > 0 && m_MonsterInfo.m_nMap != nowMapNum) { m_MonsterInfo.DeleteDeviceObjects(); m_MonsterInfo.LoadScript( g_Neuz.m_pd3dDevice, MakePath( DIR_THEME, _T( m_strMonScript[nowMapNum-1] ) ), nowMapNum ); } } else if( nowMapNum == MAX_BUTTON - 1 ) { m_bShowMonsterInfo = !m_bShowMonsterInfo; } } #else if( pWndWorld ) { CPoint point = pWndWorld->GetMousePoint(); #if __VER >= 13 // __CSC_VER13_1 int i; for( i = 0 ; i < MAX_BUTTON ; ++i ) #else //__CSC_VER13_1 int i; for( i = 0 ; i < 6 ; ++i ) #endif //__CSC_VER13_1 { if( m_cRect[i].PtInRect( point ) ) { #if __VER >= 13 // __CSC_VER13_1 #if __VER >= 14 // __NEW_CONTINENT if(i < MAX_BUTTON - 1) #else //__NEW_CONTINENT if(i < 6) #endif //__NEW_CONTINENT { m_nMap = i; #if __VER >= 15 // __TELEPORTER UpdateTeleportWorld( ); #endif #if __VER >= 15 // __IMPROVE_QUEST_INTERFACE UpdateDestinationPosition( pWndWorld->m_vDestinationArrow ); #endif // __IMPROVE_QUEST_INTERFACE m_strViewMapString = m_strMapStringList[m_nMap]; m_pTexWorldMap = CWndBase::m_textureMng.AddTexture( g_Neuz.m_pd3dDevice, MakePath( "Theme\\", ::GetLanguage(), m_strViewMapString ), 0xff000000 ); if(m_nMap > 0 && m_MonsterInfo.m_nMap != m_nMap) { m_MonsterInfo.DeleteDeviceObjects(); m_MonsterInfo.LoadScript( g_Neuz.m_pd3dDevice, MakePath( DIR_THEME, _T( m_strMonScript[m_nMap-1] ) ), m_nMap ); } } #if __VER >= 14 // __NEW_CONTINENT else if(i == MAX_BUTTON - 1) #else //__NEW_CONTINENT else if(i == 6) #endif //__NEW_CONTINENT m_bShowMonsterInfo = !m_bShowMonsterInfo; #else //__CSC_VER13_1 m_nMap = i; m_strViewMapString = m_strMapStringList[m_nMap]; m_pTexWorldMap = CWndBase::m_textureMng.AddTexture( g_Neuz.m_pd3dDevice, MakePath( "Theme\\", ::GetLanguage(), m_strViewMapString ), 0xff000000 ); #endif //__CSC_VER13_1 break; } } } #endif //__IMPROVE15_WORLDMAP } #if __VER >= 15 // __TELEPORTER void CWorldMap::UpdateTeleportWorld( ) { //ํ•ด๋‹น ํ…”๋ ˆํฌํ„ฐ๋กœ๋ถ€ํ„ฐ ์–ป์–ด์˜จ ์›”๋“œํฌ์ธํŠธ ์ž๋ฃŒ๋ฅผ ๋Œ€์ƒ์œผ๋กœ ํ˜„์žฌ ๋ณด๊ณ ์žˆ๋Š” ๋งต์›”๋“œ ์•„์ด๋””์— ๋”ฐ๋ผ //์ขŒํ‘œ๋ฅผ ์—…๋ฐ์ดํŠธ ์‹œํ‚จ๋‹ค. m_cTelPosRects.clear( ); //์ผ๋‹จ ๋‚ ๋ ค๋ฒ„๋ ค CPoint pt; CSize size( 16, 16 ); int max_size = m_cWorldPos.size(); int i; for( i = 0; i < max_size; ++i ) { BOOL bOK = WorldPosToMapPos( m_cWorldPos[i], pt ); if( bOK ) { WMapIcon icon; icon._index = i; pt.x = (LONG)( pt.x - ( size.cx * 0.5F ) ); pt.y = (LONG)( pt.y - ( size.cy * 0.5F ) ); icon._rect = CRect( pt, size ); m_cTelPosRects.push_back( icon ); } } } void CWorldMap::ProcessingTeleporter( CMover* pFocusMover ) { CHARACTER* pCharacter = pFocusMover->GetCharacter( ); if( !pCharacter ) return; if( pCharacter->m_vecTeleportPos.empty( ) ) return; if( m_idTeleporter != pFocusMover->GetId( ) ) { //์ตœ์ดˆ๋กœ ๋ถˆ๋ ธ๊ฑฐ๋‚˜ ๋‹ค๋ฅธ ํ…”๋ ˆํฌํ„ฐ์ผ๊ฒฝ์šฐ m_idTeleporter = pFocusMover->GetId( ); m_cWorldPos = pCharacter->m_vecTeleportPos; UpdateTeleportWorld( ); } } void CWorldMap::RenderTelPos( C2DRender *p2DRender ) { m_pTelPosTexture = CWndBase::m_textureMng.AddTexture( g_Neuz.m_pd3dDevice, MakePath( DIR_THEME, "ButtTeleport.bmp"), 0xffff00ff ); if( !m_pTelPosTexture ) return; CWndWorld* pWndWorld = (CWndWorld*)g_WndMng.GetApplet( APP_WORLD ); if( !pWndWorld ) return; CPoint mousePt = pWndWorld->GetMousePoint(); CPoint pt; for( vector< WMapIcon >::iterator iter = m_cTelPosRects.begin(); iter != m_cTelPosRects.end(); ++iter ) { WMapIcon& kIcon = *iter; CRect& rect = kIcon._rect; pt.x = rect.left; pt.y = rect.top; if( rect.PtInRect( mousePt ) ) { // ํ•ด๋‹น ๊ตฌ์—ญ์— ๋งˆ์šฐ์Šค๊ฐ€ ์œ„์น˜ํ•œ ๊ฒฝ์šฐ ์„ ํƒ๋๋‹ค๋Š” ๋ญ ๊ทธ๋Ÿฐ? pt.x -= 2; pt.y -= 2; m_pTelPosTexture->Render( p2DRender, pt, CPoint( 20, 20 ) ); }else { m_pTelPosTexture->Render( p2DRender, pt, CPoint( 16, 16) ); } } } void CWorldMap::SetTelMode( BOOL bMode ) { m_bTeleportMode = bMode; m_bRender = m_bTeleportMode; } #if __VER >= 15 // __IMPROVE_QUEST_INTERFACE void CWorldMap::UpdateDestinationPosition( const D3DXVECTOR3& rPosition ) { CPoint pt( 0, 0 ); CSize size( 16, 16 ); BOOL bOK = WorldPosToMapPos( rPosition, pt ); if( bOK ) { pt.x = (LONG)( pt.x - ( size.cx * 0.5F ) ); pt.y = (LONG)( pt.y - ( size.cy * 0.5F ) ); m_rectDestination = CRect( pt, size ); } else m_rectDestination = CRect( -1, -1, -1, -1 ); } void CWorldMap::RenderDestinationPosition( C2DRender* p2DRender ) { if( m_rectDestination == CRect( -1, -1, -1, -1 ) ) return; m_pDestinationPositionTexture = CWndBase::m_textureMng.AddTexture( g_Neuz.m_pd3dDevice, MakePath( DIR_THEME, "ButtDestination.bmp"), 0xffff00ff ); if( m_pDestinationPositionTexture == NULL ) return; CWndWorld* pWndWorld = (CWndWorld*)g_WndMng.GetApplet( APP_WORLD ); if( !pWndWorld ) return; float fDelta = ( static_cast< float >( g_tmCurrent - m_tmOld ) / 1000.0f ); m_tmOld = g_tmCurrent; static const float ANIMATION_SPEED = 800.0f; if( m_bAlphaSwitch == FALSE ) { m_nDestinationTextureAlpha += static_cast< int >( ANIMATION_SPEED * fDelta ); if( m_nDestinationTextureAlpha > MAXIMUM_ALPHA ) { m_nDestinationTextureAlpha = MAXIMUM_ALPHA; m_bAlphaSwitch = TRUE; } } else { m_nDestinationTextureAlpha -= static_cast< int >( ANIMATION_SPEED * fDelta ); if( m_nDestinationTextureAlpha < MINIMUM_ALPHA ) { m_nDestinationTextureAlpha = MINIMUM_ALPHA; m_bAlphaSwitch = FALSE; } } m_pDestinationPositionTexture->RenderScal( p2DRender, CPoint( m_rectDestination.left, m_rectDestination.top ), m_nDestinationTextureAlpha, 0.6F, 0.6F ); } void CWorldMap::SetDestinationMode( BOOL bDestinationMode ) { m_bDestinationMode = bDestinationMode; } #endif // __IMPROVE_QUEST_INTERFACE BOOL CWorldMap::WorldPosToMapPos( const D3DXVECTOR3& vPos, OUT CPoint& cPos ) { if( 0 != m_nMap ) // ์ „์ฒด๋งต์ด ์•„๋‹๊ฒฝ์šฐ ํ•ด๋‹น ์ง€์—ญ์— ๊ด€ํ•œ ์žํ‘œ๋งŒ ํ‘œ์‹œํ• ๊บผ์ž„ { int nMap = CContinent::GetInstance()->GetMapNo( vPos ); if( m_nMap != nMap ) return FALSE; } FLOAT fMap_X1 = _fMap_X1; FLOAT fMap_Y1 = _fMap_Y1; FLOAT fMap_X2 = _fMap_X2; FLOAT fMap_Y2 = _fMap_Y2; if( m_nMap == 0 ) { fMap_X1 = 0.0f; fMap_Y1 = 1298.0f; //0.0f; fMap_X2 = 11800.0f; fMap_Y2 = 9757.0f; //9000.0f; } else if( m_nMap == 1 ) { fMap_X1 = 2355.0f; fMap_Y1 = 2019.0f; fMap_X2 = 7187.0f; fMap_Y2 = 5814.0f; } else if( m_nMap == 2 ) { fMap_X1 = 985.0f; fMap_Y1 = 1621.0f; fMap_X2 = 5754.0f; fMap_Y2 = 5149.0f; } else if( m_nMap == 3 ) { fMap_X1 = 8080.0f; fMap_Y1 = 3200.0f; fMap_X2 = 10280.0f; fMap_Y2 = 5000.0f; } else if( m_nMap == 4 ) { fMap_X1 = 6854.0f; fMap_Y1 = 1580.0f; fMap_X2 = 10600.0f; fMap_Y2 = 4430.0f; } else if( m_nMap == 5 ) { fMap_X1 = 5500.0f; fMap_Y1 = 2540.0f; fMap_X2 = 9200.0f; fMap_Y2 = 5130.0f; } else if( m_nMap == 6 ) // ํ•˜๋ฅด๋ชจ๋‹Œ { fMap_X1 = 4795.0f; // ui๋งต์˜ ํ…Œ๋‘๋ฆฌ ๋Œ€ ๋Œ€๋ฅ™์‚ฌ์ด์ฆˆ ๋น„์œจ์„ ์ด์šฉํ•ด ์‹ค์ œ ์›”๋“œ๋Œ€๋ฅ™์ขŒํ‘œ์— ์ ์šฉ์‹œํ‚จ ui์˜ ํ…Œํˆฌ๋ฆฌ์— ํ•ด๋‹นํ•˜๋Š” ์›”๋“œ ์ขŒํ‘œ fMap_Y1 = 4587.0f; fMap_X2 = 8391.0f; fMap_Y2 = 7236.0f; } else if( m_nMap == 7 ) // ์ด์Šคํ‹ฐ์•„ ์บ๋‹ˆ์–ธ { fMap_X1 = 5150.0f; fMap_Y1 = 5573.0f; fMap_X2 = 9890.0f; fMap_Y2 = 9158.0f; } FLOAT fX = fMap_X2 - fMap_X1; FLOAT fY = fMap_Y1 - fMap_Y2; D3DXVECTOR3 v1 = D3DXVECTOR3( -1, 1, -1 ); D3DXVECTOR3 v2 = D3DXVECTOR3( 1, -1, 1 ); D3DXVECTOR3 v3 = D3DXVECTOR3( 1, 1, 1 ); FLOAT fRate1 = (fMap_X2 - vPos.x) / fX ; FLOAT fRate2 = (fMap_Y1 - vPos.z) / fY ; int nX; int nY; if((g_Option.m_nResWidth == 1360 || g_Option.m_nResWidth == 1440 || g_Option.m_nResWidth == 1680) || (g_Option.m_nResWidth == 1280 && (g_Option.m_nResHeight == 720 || g_Option.m_nResHeight == 768 || g_Option.m_nResHeight == 800))) //Wide Offset { v1 = D3DXVECTOR3( (FLOAT)( m_cOffset.x ), 0.0f, 0.0f ); v2 = D3DXVECTOR3( (FLOAT)( m_cpScreen.x + m_cOffset.x ), (FLOAT)( m_cpScreen.y ), 0.0f ); } else { v1 = D3DXVECTOR3( 0.0f, 0.0f, 0.0f ); v2 = D3DXVECTOR3( (FLOAT)( g_Option.m_nResWidth ), (FLOAT)( g_Option.m_nResHeight ), 0.0f ); } D3DXVec3Lerp( &v3, &v2, &v1, fRate1 ); nX = (int)( v3.x ); D3DXVec3Lerp( &v3, &v2, &v1, fRate2 ); nY = (int)( v3.y ); cPos.x = nX; cPos.y = nY; return TRUE; } #endif //__TELEPORTER //===================================================================================================================================================== #if __VER >= 13 // __CSC_VER13_1 CMonsterInfoPack::CMonsterInfoPack() { m_nMap = 0; } CMonsterInfoPack::~CMonsterInfoPack() { } BOOL CMonsterInfoPack::LoadScript( LPDIRECT3DDEVICE9 pd3dDevice, LPCTSTR pszFileName, int nMap ) { CScript scanner; if( scanner.Load( pszFileName ) == FALSE ) { Error( "%s not found", pszFileName ); return FALSE; } m_nMap = nMap; DWORD dwCount = 0; CTexture* pTexture; BOOL bMultiLang = FALSE; m_vecMonsterInfo.clear(); do { scanner.GetToken(); if(scanner.Token == "number") { m_dwNumber = scanner.GetNumber(); m_ap2DTexture = new CTexture[ m_dwNumber ]; } else if( scanner.Token == "MULTI_LANGUAGE" ) { bMultiLang = TRUE; } else if(scanner.Token == "texture") { scanner.GetToken(); TCHAR strFileName[MAX_PATH]; strcpy(strFileName,scanner.token); D3DCOLOR d3dKeyColor = scanner.GetHex(); // ์—ฌ๊ธฐ์„œ ํ…์Šค์ถฐ ์ƒ์„ฑ (Create the texture using D3DX) D3DXIMAGE_INFO imageInfo; if( bMultiLang ) { LoadTextureFromRes( pd3dDevice, MakePath( "Theme\\", ::GetLanguage(), strFileName ), D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, //D3DFMT_A4R4G4B4, D3DPOOL_MANAGED, D3DX_FILTER_TRIANGLE|D3DX_FILTER_MIRROR, D3DX_FILTER_TRIANGLE|D3DX_FILTER_MIRROR, d3dKeyColor, &imageInfo, NULL, &m_pTexture ); } else { LoadTextureFromRes( pd3dDevice, MakePath( DIR_THEME, strFileName ), D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, //D3DFMT_A4R4G4B4, D3DPOOL_MANAGED, D3DX_FILTER_TRIANGLE|D3DX_FILTER_MIRROR, D3DX_FILTER_TRIANGLE|D3DX_FILTER_MIRROR, d3dKeyColor, &imageInfo, NULL, &m_pTexture ); } m_size.cx = imageInfo.Width; m_size.cy = imageInfo.Height; } else if(scanner.Token == "serialize") { if( dwCount >= m_dwNumber ) { Error( "%s ์—๋Ÿฌ, ํ• ๋‹น :%d, ์‹ค์ œ๊ฐฏ์ˆ˜ : %d", pszFileName, m_dwNumber, dwCount ); return FALSE; } int nCnt = 0; int nFrame = scanner.GetNumber(); SIZE size; size.cx = scanner.GetNumber(); size.cy = scanner.GetNumber(); POINT start; start.x = scanner.GetNumber(); start.y = scanner.GetNumber(); POINT center; center.x = scanner.GetNumber(); center.y = scanner.GetNumber(); int i; for( i = start.y; i < m_size.cy; i += size.cy ) { int j; for( j = start.x; j < m_size.cx; j += size.cx, nCnt++ ) { if( nCnt < nFrame ) { if( dwCount >= m_dwNumber ) { Error( "%s ์—๋Ÿฌ, ํ• ๋‹น :%d, ์‹ค์ œ๊ฐฏ์ˆ˜ : %d", pszFileName, m_dwNumber, dwCount ); return FALSE; } pTexture = &m_ap2DTexture[ dwCount ]; dwCount++; pTexture->m_size = size; pTexture->m_ptCenter = center; int x = j; int y = i; pTexture->m_fuLT = (FLOAT) x / m_size.cx; pTexture->m_fvLT = (FLOAT) y / m_size.cy; pTexture->m_fuRT = (FLOAT) ( (FLOAT)x + pTexture->m_size.cx - 0 ) / (FLOAT)m_size.cx; pTexture->m_fvRT = (FLOAT) y / m_size.cy; pTexture->m_fuLB = (FLOAT) x / m_size.cx; pTexture->m_fvLB = (FLOAT) ( (FLOAT)y + pTexture->m_size.cy - 0 ) / (FLOAT)m_size.cy; pTexture->m_fuRB = (FLOAT) ( (FLOAT)x + pTexture->m_size.cx - 0 ) / (FLOAT)m_size.cx; pTexture->m_fvRB = (FLOAT) ( (FLOAT)y + pTexture->m_size.cy - 0 ) / (FLOAT)m_size.cy; pTexture->m_pTexture = m_pTexture; } } } for(i=0; i<nFrame; i++) { __MONSTER_INFO stMonInfo; stMonInfo.m_nMonCnt = scanner.GetNumber(); for(int j=0; j<stMonInfo.m_nMonCnt; j++) stMonInfo.m_dwMonsterId[j] = scanner.GetNumber(); if(g_Option.m_nResWidth == 1280 && g_Option.m_nResHeight == 960) { stMonInfo.m_rectPos.left = scanner.GetNumber(); stMonInfo.m_rectPos.top = scanner.GetNumber(); } else { CWorldMap* pWorldMap = CWorldMap::GetInstance(); if(pWorldMap) { stMonInfo.m_rectPos.left = ((scanner.GetNumber() * pWorldMap->GetCpScreen().x) / 1280) + pWorldMap->GetCpOffset().x; stMonInfo.m_rectPos.top = ((scanner.GetNumber() * pWorldMap->GetCpScreen().y) / 960) + pWorldMap->GetCpOffset().y; } } stMonInfo.m_rectPos.right = stMonInfo.m_rectPos.left + size.cx; stMonInfo.m_rectPos.bottom = stMonInfo.m_rectPos.top + size.cy; stMonInfo.m_dwDropItemId = scanner.GetNumber(); m_vecMonsterInfo.push_back(stMonInfo); } } } while(scanner.tok!=FINISHED); return TRUE; } #endif //__CSC_VER13_1 #if __VER >= 13 // __RAINBOW_RACE BOOL CRainbowNPCPack::LoadScript( LPDIRECT3DDEVICE9 pd3dDevice, LPCTSTR pszFileName ) { CScript scanner; if( scanner.Load( pszFileName ) == FALSE ) { Error( "%s not found", pszFileName ); return FALSE; } DWORD dwCount = 0; CTexture* pTexture; BOOL bMultiLang = FALSE; m_vecRainbowNPC.clear(); do { scanner.GetToken(); if(scanner.Token == "number") { m_dwNumber = scanner.GetNumber(); m_ap2DTexture = new CTexture[ m_dwNumber ]; } else if( scanner.Token == "MULTI_LANGUAGE" ) { bMultiLang = TRUE; } else if(scanner.Token == "texture") { scanner.GetToken(); TCHAR strFileName[MAX_PATH]; strcpy(strFileName,scanner.token); D3DCOLOR d3dKeyColor = scanner.GetHex(); // ์—ฌ๊ธฐ์„œ ํ…์Šค์ถฐ ์ƒ์„ฑ (Create the texture using D3DX) D3DXIMAGE_INFO imageInfo; if( bMultiLang ) { LoadTextureFromRes( pd3dDevice, MakePath( "Theme\\", ::GetLanguage(), strFileName ), D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, //D3DFMT_A4R4G4B4, D3DPOOL_MANAGED, D3DX_FILTER_TRIANGLE|D3DX_FILTER_MIRROR, D3DX_FILTER_TRIANGLE|D3DX_FILTER_MIRROR, d3dKeyColor, &imageInfo, NULL, &m_pTexture ); } else { LoadTextureFromRes( pd3dDevice, MakePath( DIR_THEME, strFileName ), D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, //D3DFMT_A4R4G4B4, D3DPOOL_MANAGED, D3DX_FILTER_TRIANGLE|D3DX_FILTER_MIRROR, D3DX_FILTER_TRIANGLE|D3DX_FILTER_MIRROR, d3dKeyColor, &imageInfo, NULL, &m_pTexture ); } m_size.cx = imageInfo.Width; m_size.cy = imageInfo.Height; } else if(scanner.Token == "serialize") { if( dwCount >= m_dwNumber ) { Error( "%s ์—๋Ÿฌ, ํ• ๋‹น :%d, ์‹ค์ œ๊ฐฏ์ˆ˜ : %d", pszFileName, m_dwNumber, dwCount ); return FALSE; } int nCnt = 0; int nFrame = scanner.GetNumber(); SIZE size; size.cx = scanner.GetNumber(); size.cy = scanner.GetNumber(); POINT start; start.x = scanner.GetNumber(); start.y = scanner.GetNumber(); POINT center; center.x = scanner.GetNumber(); center.y = scanner.GetNumber(); int i; for( i = start.y; i < m_size.cy; i += size.cy ) { int j; for( j = start.x; j < m_size.cx; j += size.cx, nCnt++ ) { if( nCnt < nFrame ) { if( dwCount >= m_dwNumber ) { Error( "%s ์—๋Ÿฌ, ํ• ๋‹น :%d, ์‹ค์ œ๊ฐฏ์ˆ˜ : %d", pszFileName, m_dwNumber, dwCount ); return FALSE; } pTexture = &m_ap2DTexture[ dwCount ]; dwCount++; pTexture->m_size = size; pTexture->m_ptCenter = center; int x = j; int y = i; pTexture->m_fuLT = (FLOAT) x / m_size.cx; pTexture->m_fvLT = (FLOAT) y / m_size.cy; pTexture->m_fuRT = (FLOAT) ( (FLOAT)x + pTexture->m_size.cx - 0 ) / (FLOAT)m_size.cx; pTexture->m_fvRT = (FLOAT) y / m_size.cy; pTexture->m_fuLB = (FLOAT) x / m_size.cx; pTexture->m_fvLB = (FLOAT) ( (FLOAT)y + pTexture->m_size.cy - 0 ) / (FLOAT)m_size.cy; pTexture->m_fuRB = (FLOAT) ( (FLOAT)x + pTexture->m_size.cx - 0 ) / (FLOAT)m_size.cx; pTexture->m_fvRB = (FLOAT) ( (FLOAT)y + pTexture->m_size.cy - 0 ) / (FLOAT)m_size.cy; pTexture->m_pTexture = m_pTexture; } } } for(i=0; i<nFrame; i++) { __RAINBOW_NPC stRainbowNPC; stRainbowNPC.m_nMap = scanner.GetNumber(); if(g_Option.m_nResWidth == 1280 && g_Option.m_nResHeight == 960) { stRainbowNPC.m_rectTotalMapPos.left = scanner.GetNumber(); stRainbowNPC.m_rectTotalMapPos.top = scanner.GetNumber(); } else { CWorldMap* pWorldMap = CWorldMap::GetInstance(); if(pWorldMap) { stRainbowNPC.m_rectTotalMapPos.left = ((scanner.GetNumber() * pWorldMap->GetCpScreen().x) / 1280) + pWorldMap->GetCpOffset().x; stRainbowNPC.m_rectTotalMapPos.top = ((scanner.GetNumber() * pWorldMap->GetCpScreen().y) / 960) + pWorldMap->GetCpOffset().y; } } stRainbowNPC.m_rectTotalMapPos.right = stRainbowNPC.m_rectTotalMapPos.left + size.cx; stRainbowNPC.m_rectTotalMapPos.bottom = stRainbowNPC.m_rectTotalMapPos.top + size.cy; if(g_Option.m_nResWidth == 1280 && g_Option.m_nResHeight == 960) { stRainbowNPC.m_rectPos.left = scanner.GetNumber(); stRainbowNPC.m_rectPos.top = scanner.GetNumber(); } else { CWorldMap* pWorldMap = CWorldMap::GetInstance(); if(pWorldMap) { stRainbowNPC.m_rectPos.left = ((scanner.GetNumber() * pWorldMap->GetCpScreen().x) / 1280) + pWorldMap->GetCpOffset().x; stRainbowNPC.m_rectPos.top = ((scanner.GetNumber() * pWorldMap->GetCpScreen().y) / 960) + pWorldMap->GetCpOffset().y; } } stRainbowNPC.m_rectPos.right = stRainbowNPC.m_rectPos.left + size.cx; stRainbowNPC.m_rectPos.bottom = stRainbowNPC.m_rectPos.top + size.cy; m_vecRainbowNPC.push_back(stRainbowNPC); } } } while(scanner.tok!=FINISHED); return TRUE; } #endif //__RAINBOW_RACE
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 1807 ] ] ]
7e63ea9b089c906c00a88213559e4719ef47206c
a4fe7601a92c7b4d236eecdcd055a8cf2bf2d5a7
/Asteroids/spaceshiprepresentation.h
69e50df6aa2ada1ffe311774c1773c0407e116bb
[]
no_license
AnthIste/Asteroids
390f3e501a1ff7ca7a9d70e44dc7a231388c65a0
5cfdf02bb0909096820bffe4cce9548932d13767
refs/heads/master
2021-01-10T20:00:33.632072
2011-07-10T14:51:54
2011-07-10T14:51:54
2,025,904
3
1
null
null
null
null
UTF-8
C++
false
false
394
h
#ifndef ASTEROIDS_SPACESHIPREPRESENTATION_H_ #define ASTEROIDS_SPACESHIPREPRESENTATION_H_ #include "entityrepresentation.h" class SpaceshipRepresentation: public EntityRepresentation { public: SpaceshipRepresentation(); virtual ~SpaceshipRepresentation(); virtual void render(LPDIRECT3DDEVICE9 d3ddev); private: }; #endif // ASTEROIDS_SPACESHIPREPRESENTATION_H_
[ "Salad@Salad-PC.(none)" ]
[ [ [ 1, 16 ] ] ]